Skip to content

Commit

Permalink
Fix detection whether a query contains the GROUP BY clause
Browse files Browse the repository at this point in the history
There is a logic for translating WHERE ... HAVING without GROUP BY
to WHERE ... AND, and this bug was causing that every HAVING was
rewritten to AND, which resulted in GROUP BY ... HAVING queries
like the following one failing:

SELECT name, COUNT(*) as count FROM _tmp_table GROUP BY name HAVING COUNT(*) > 1;
  • Loading branch information
JanJakes committed Aug 12, 2024
1 parent dd6bd6b commit e910d7f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
29 changes: 29 additions & 0 deletions tests/WP_SQLite_Translator_Tests.php
Original file line number Diff line number Diff line change
Expand Up @@ -3048,6 +3048,35 @@ public function testCurrentTimestamp() {
$this->assertQuery( 'DELETE FROM _dates WHERE option_value = CURRENT_TIMESTAMP()' );
}

public function testGroupByHaving() {
$this->assertQuery(
'CREATE TABLE _tmp_table (
name varchar(20)
);'
);

$this->assertQuery(
"INSERT INTO _tmp_table VALUES ('a'), ('b'), ('b'), ('c'), ('c'), ('c')"
);

$result = $this->assertQuery(
'SELECT name, COUNT(*) as count FROM _tmp_table GROUP BY name HAVING COUNT(*) > 1'
);
$this->assertEquals(
array(
(object) array(
'name' => 'b',
'count' => '2',
),
(object) array(
'name' => 'c',
'count' => '3',
),
),
$result
);
}

/**
* @dataProvider mysqlVariablesToTest
*/
Expand Down
6 changes: 1 addition & 5 deletions wp-includes/sqlite/class-wp-sqlite-translator.php
Original file line number Diff line number Diff line change
Expand Up @@ -2607,15 +2607,11 @@ private function capture_group_by( $token ) {
! $token->matches(
WP_SQLite_Token::TYPE_KEYWORD,
WP_SQLite_Token::FLAG_KEYWORD_RESERVED,
array( 'GROUP' )
array( 'GROUP BY' )
)
) {
return false;
}
$next = $this->rewriter->peek_nth( 2 )->value;
if ( 'BY' !== strtoupper( $next ?? '' ) ) {
return false;
}

$this->has_group_by = true;

Expand Down

0 comments on commit e910d7f

Please sign in to comment.