Skip to content

Commit

Permalink
DB/DirectDatabaseQuery: bug fix - ignore TRUNCATE queries
Browse files Browse the repository at this point in the history
Prevent unsolvable false positives for `TRUNCATE` queries. Those cannot be cached and need a direct DB query. (second opinion appreciated!)

Includes unit tests.

Fixes 1947
  • Loading branch information
jrfnl committed Jan 7, 2023
1 parent 307ff0b commit 0913f35
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
8 changes: 7 additions & 1 deletion WordPress/Sniffs/DB/DirectDatabaseQuerySniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use PHP_CodeSniffer\Util\Tokens;
use PHPCSUtils\Tokens\Collections;
use PHPCSUtils\Utils\Conditions;
use PHPCSUtils\Utils\TextStrings;
use WordPressCS\WordPress\Helpers\RulesetPropertyHelper;
use WordPressCS\WordPress\Sniff;

Expand Down Expand Up @@ -194,13 +195,18 @@ public function process_token( $stackPtr ) {

$endOfStatement = $this->phpcsFile->findNext( array( \T_SEMICOLON, \T_CLOSE_TAG ), ( $stackPtr + 1 ) );

// Check for Database Schema Changes.
// Check for Database Schema Changes/ table truncation.
for ( $_pos = ( $stackPtr + 1 ); $_pos < $endOfStatement; $_pos++ ) {
$_pos = $this->phpcsFile->findNext( Tokens::$textStringTokens, $_pos, $endOfStatement );
if ( false === $_pos ) {
break;
}

if ( strpos( TextStrings::stripQuotes( $this->tokens[ $_pos ]['content'] ), 'TRUNCATE ' ) === 0 ) {
// Ignore queries to truncate the database as caching those is irrelevant and they need a direct db query.
return;
}

if ( preg_match( '#\b(?:ALTER|CREATE|DROP)\b#i', $this->tokens[ $_pos ]['content'] ) > 0 ) {
$this->phpcsFile->addWarning( 'Attempting a database schema change is discouraged.', $_pos, 'SchemaChange' );
}
Expand Down
10 changes: 10 additions & 0 deletions WordPress/Tests/DB/DirectDatabaseQueryUnitTest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -307,3 +307,13 @@ function correctly_determine_end_of_statement() {
<?php
$next_query = 'ALTER TABLE TO ADD SOME FIELDS' ); // Should not be flagged as not in a call to $wpdb.
}

function stay_silent_for_truncate_query() {
global $wpdb;
$wpdb->query(
$wpdb->prepare(
'TRUNCATE TABLE `%1$s`',
plugin_get_table_name( 'Name' )
)
);
}

0 comments on commit 0913f35

Please sign in to comment.