Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 116 additions & 0 deletions packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php
Original file line number Diff line number Diff line change
Expand Up @@ -4444,6 +4444,11 @@ private function translate( $node ): ?string {
return $this->translate_like( $node );
}
return $this->translate_sequence( $node->get_children() );
case 'sumExpr':
if ( $node->has_child_token( WP_MySQL_Lexer::GROUP_CONCAT_SYMBOL ) ) {
return $this->translate_group_concat( $node );
}
return $this->translate_sequence( $node->get_children() );
case 'runtimeFunctionCall':
return $this->translate_runtime_function_call( $node );
case 'functionCall':
Expand Down Expand Up @@ -5411,6 +5416,117 @@ private function translate_function_call( WP_Parser_Node $node ): string {
}
}

/**
* Translate MySQL GROUP_CONCAT() to SQLite.
*
* MySQL: GROUP_CONCAT([DISTINCT] expr [, expr ...] [ORDER BY ...] [SEPARATOR str])
* SQLite: GROUP_CONCAT([DISTINCT] expr [, separator] [ORDER BY ...])
*
* In MySQL, several expressions are concatenated per row; in SQLite, the
* second argument is the separator. Each expression is parenthesized, as
* "||" binds more tightly than most operators. As in MySQL, a row in which
* one of the expressions is NULL is skipped, because "||" returns NULL then.
*
* ORDER BY in an aggregate function requires SQLite 3.44.0 or newer. SQLite
* allows DISTINCT only with a single argument, so DISTINCT can't be combined
* with a separator other than the default ",". Nor with several expressions:
* MySQL compares their values separately, not their concatenation.
*
* A number in ORDER BY refers to an expression of GROUP_CONCAT() itself, as
* in MySQL ("ORDER BY 1" sorts by the first one). SQLite would take it as a
* constant, so it is replaced with that expression.
*
* @param WP_Parser_Node $node The "sumExpr" AST node.
* @return string The translated value.
* @throws WP_MySQL_On_SQLite_Exception When the translation fails.
*/
private function translate_group_concat( WP_Parser_Node $node ): string {
$expressions = array();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MySQL doesn't support GROUP_CONCAT() as a window function. SELECT GROUP_CONCAT(x) OVER () FROM t fails with error 1235 (SQLSTATE 42000). Let's return the same error, before any other check:

Suggested change
$expressions = array();
if ( $node->has_child_node( 'windowingClause' ) ) {
$driver_message = "This version of MySQL doesn't yet support 'group_concat as window function'";
throw $this->new_driver_exception(
'SQLSTATE[42000]: Syntax error or access violation: 1235 ' . $driver_message,
'42000',
null,
array( '42000', 1235, $driver_message )
);
}
$expressions = array();

Please also add a test for it that checks errorInfo. testRejectsInvalidBitDefaultValues shows the pattern.

foreach ( $node->get_first_child_node( 'exprList' )->get_child_nodes( 'expr' ) as $expr ) {
$expressions[] = $this->translate( $expr );
}

$is_distinct = $node->has_child_token( WP_MySQL_Lexer::DISTINCT_SYMBOL );
if ( 1 === count( $expressions ) ) {
$value = $expressions[0];
} elseif ( $is_distinct ) {
throw $this->new_not_supported_exception(
'GROUP_CONCAT() with DISTINCT and several expressions'
);
} else {
$value = '((' . implode( ') || (', $expressions ) . '))';
}
$args = $is_distinct ? 'DISTINCT ' . $value : $value;

$separator = $node->get_first_child_node( 'textString' );
if ( null !== $separator ) {
$separator_sql = $this->translate( $separator );
if ( $this->quote_sqlite_value( ',' ) !== $separator_sql ) {
if ( $is_distinct ) {
throw $this->new_not_supported_exception(
'GROUP_CONCAT() with DISTINCT and a SEPARATOR other than ","'
);
}
$args .= ', ' . $separator_sql;
}
}

$order = $node->get_first_child_node( 'orderClause' );
if ( null !== $order ) {
if ( version_compare( $this->get_sqlite_version(), '3.44.0', '<' ) ) {
throw $this->new_not_supported_exception(
'GROUP_CONCAT() with ORDER BY requires SQLite 3.44.0 or newer'
);
}
Comment on lines +5476 to +5480

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A note for later, no change needed here.

Aggregate ORDER BY requires SQLite 3.44, and the project supports SQLite 3.37.0+. For this PR, that's OK: on older versions, it replaces a syntax error with a clear explanation.

In a follow-up, a PHP aggregate function (PDO::sqliteCreateAggregate()) can do the ordering on all supported versions. It can also cover the two DISTINCT cases that throw above.

$terms = array();
foreach ( $order->get_first_child_node( 'orderList' )->get_child_nodes( 'orderExpression' ) as $term ) {
$expr = $term->get_first_child_node( 'expr' );
$direction = $term->get_first_child_node( 'direction' );
$position = $this->get_order_position( $expr );
if ( null === $position ) {
$sql = $this->translate( $expr );
} elseif ( $position >= 1 && $position <= count( $expressions ) ) {
$sql = '(' . $expressions[ $position - 1 ] . ')';
} else {
throw $this->new_driver_exception(
sprintf( "SQLSTATE[42S22]: Column not found: 1054 Unknown column '%s' in 'order clause'", $position ),
'42S22'
);
Comment on lines +5491 to +5494

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This exception reports native error code 1105 in $e->errorInfo[1]. MySQL reports 1054. Passing the error info fixes it:

Suggested change
throw $this->new_driver_exception(
sprintf( "SQLSTATE[42S22]: Column not found: 1054 Unknown column '%s' in 'order clause'", $position ),
'42S22'
);
$driver_message = sprintf( "Unknown column '%s' in 'order clause'", $position );
throw $this->new_driver_exception(
'SQLSTATE[42S22]: Column not found: 1054 ' . $driver_message,
'42S22',
null,
array( '42S22', 1054, $driver_message )
);

The exception message doesn't change, so please also check errorInfo in the test.

The two 'field list' errors in this file have the same gap. They can be fixed separately.

}
$terms[] = null === $direction ? $sql : $sql . ' ' . $this->translate( $direction );
}
$args .= ' ORDER BY ' . implode( ', ', $terms );
}

$sql = sprintf( 'GROUP_CONCAT(%s)', $args );
$window = $node->get_first_child_node( 'windowingClause' );
if ( null !== $window ) {
$sql .= ' ' . $this->translate( $window );
}
return $sql;
Comment on lines +5501 to +5506

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the check at the start of the method, this can be:

Suggested change
$sql = sprintf( 'GROUP_CONCAT(%s)', $args );
$window = $node->get_first_child_node( 'windowingClause' );
if ( null !== $window ) {
$sql .= ' ' . $this->translate( $window );
}
return $sql;
return sprintf( 'GROUP_CONCAT(%s)', $args );

}

/**
* Get the position an ORDER BY term refers to, if it is one.
*
* In MySQL, an ORDER BY term that is an integer, also in parentheses, is a
* position, not a constant. Other expressions, such as "-1" or "1 + 1", are not.
*
* @param WP_Parser_Node $expr The "expr" AST node of the ORDER BY term.
* @return int|null The position, or null when the term is not one.
*/
private function get_order_position( WP_Parser_Node $expr ): ?int {
$number = null;
foreach ( $expr->get_descendant_tokens() as $token ) {
if ( WP_MySQL_Lexer::INT_NUMBER === $token->id && null === $number ) {
$number = $token;
} elseif ( WP_MySQL_Lexer::OPEN_PAR_SYMBOL !== $token->id && WP_MySQL_Lexer::CLOSE_PAR_SYMBOL !== $token->id ) {
return null;
}
}
return null === $number ? null : (int) $number->get_value();
}

/**
* Get the configured MySQL version in dotted notation.
*
Expand Down
92 changes: 92 additions & 0 deletions packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php
Original file line number Diff line number Diff line change
Expand Up @@ -18132,4 +18132,96 @@ public function testReverseFunction(): void {
$result = $this->assertQuery( 'SELECT REVERSE(NULL) AS reversed' );
$this->assertNull( $result[0]->reversed );
}

public function testGroupConcatFunction(): void {
$this->assertQuery( 'CREATE TABLE t (g INT, x VARCHAR(10), y INT, z VARCHAR(10))' );
$this->assertQuery( "INSERT INTO t VALUES (1, 'b', 2, 'p'), (1, 'a', 1, NULL), (2, 'c', 1, 'r'), (2, 'a,b', 2, 's')" );

$tests = array(
// The default separator is ",".
'GROUP_CONCAT(x)' => array( 'b,a', 'c,a,b' ),
"GROUP_CONCAT(x SEPARATOR ',')" => array( 'b,a', 'c,a,b' ),
"GROUP_CONCAT(x SEPARATOR '; ')" => array( 'b; a', 'c; a,b' ),
"GROUP_CONCAT(x SEPARATOR '')" => array( 'ba', 'ca,b' ),
"GROUP_CONCAT(x SEPARATOR 'it''s')" => array( "bit'sa", "cit'sa,b" ),
// Several expressions are concatenated per row.
'GROUP_CONCAT(x, y)' => array( 'b2,a1', 'c1,a,b2' ),
"GROUP_CONCAT(x, '-', y SEPARATOR ' | ')" => array( 'b-2 | a-1', 'c-1 | a,b-2' ),
// Each expression keeps its own boundaries ("||" binds more tightly than "+").
'GROUP_CONCAT(y + 1, y * 10)' => array( '320,210', '210,320' ),
// Rows with a NULL value are skipped.
'GROUP_CONCAT(z)' => array( 'p', 'r,s' ),
'GROUP_CONCAT(x, z)' => array( 'bp', 'cr,a,bs' ),
"UPPER(GROUP_CONCAT(x SEPARATOR '/'))" => array( 'B/A', 'C/A,B' ),
);
foreach ( $tests as $expression => $expected ) {
$result = $this->assertQuery( "SELECT $expression AS result FROM t GROUP BY g ORDER BY g" );
$this->assertSame( $expected, array_column( $result, 'result' ), $expression );
}

// No rows.
$result = $this->assertQuery( "SELECT GROUP_CONCAT(x SEPARATOR '; ') AS result FROM t WHERE g = 3" );
$this->assertNull( $result[0]->result );
}

public function testGroupConcatFunctionWithOrderBy(): void {
$this->assertQuery( 'CREATE TABLE t (g INT, x VARCHAR(10), y INT)' );
$this->assertQuery( "INSERT INTO t VALUES (1, 'b', 2), (1, 'a', 1), (1, 'b', 3), (2, 'c', 1), (2, 'a,b', 2)" );

$tests = array(
'GROUP_CONCAT(x ORDER BY y DESC)' => array( 'b,b,a', 'a,b,c' ),
"GROUP_CONCAT(x ORDER BY y DESC SEPARATOR '; ')" => array( 'b; b; a', 'a,b; c' ),
"GROUP_CONCAT(x ORDER BY x, y DESC SEPARATOR '|')" => array( 'a|b|b', 'a,b|c' ),
'GROUP_CONCAT(DISTINCT x ORDER BY x DESC)' => array( 'b,a', 'c,a,b' ),
// A number refers to an expression of GROUP_CONCAT(), also in parentheses.
'GROUP_CONCAT(x ORDER BY 1)' => array( 'a,b,b', 'a,b,c' ),
'GROUP_CONCAT(x, y ORDER BY 2 DESC)' => array( 'b3,b2,a1', 'a,b2,c1' ),
"GROUP_CONCAT(x ORDER BY (1) DESC SEPARATOR '|')" => array( 'b|b|a', 'c|a,b' ),
);
foreach ( $tests as $expression => $expected ) {
$query = "SELECT $expression AS result FROM t GROUP BY g ORDER BY g";

// ORDER BY in an aggregate function requires SQLite 3.44.0.
if ( version_compare( $this->engine->get_sqlite_version(), '3.44.0', '<' ) ) {
$this->assertQueryError(
$query,
'MySQL query not supported. Cause: GROUP_CONCAT() with ORDER BY requires SQLite 3.44.0 or newer'
);
continue;
}

$result = $this->assertQuery( $query );
$this->assertSame( $expected, array_column( $result, 'result' ), $expression );
}

// A number that is not the position of an expression is an error, as in MySQL.
if ( version_compare( $this->engine->get_sqlite_version(), '3.44.0', '>=' ) ) {
$this->assertQueryError(
'SELECT GROUP_CONCAT(x ORDER BY 2) AS result FROM t',
"SQLSTATE[42S22]: Column not found: 1054 Unknown column '2' in 'order clause'"
);
}
}

public function testGroupConcatFunctionWithDistinctAndSeparator(): void {
$this->assertQuery( 'CREATE TABLE t (g INT, x VARCHAR(10))' );
$this->assertQuery( "INSERT INTO t VALUES (1, 'b'), (1, 'a'), (1, 'b')" );

// The default separator works with DISTINCT.
$result = $this->assertQuery( "SELECT GROUP_CONCAT(DISTINCT x SEPARATOR ',') AS result FROM t" );
$this->assertSame( 'b,a', $result[0]->result );

// SQLite allows DISTINCT only with a single argument.
$this->assertQueryError(
"SELECT GROUP_CONCAT(DISTINCT x SEPARATOR '; ') AS result FROM t",
'MySQL query not supported. Cause: GROUP_CONCAT() with DISTINCT and a SEPARATOR other than ","'
);

// MySQL compares the values of several expressions separately, not their
// concatenation: ('a', 'bc') and ('ab', 'c') are two different values.
$this->assertQueryError(
'SELECT GROUP_CONCAT(DISTINCT x, x) AS result FROM t',
'MySQL query not supported. Cause: GROUP_CONCAT() with DISTINCT and several expressions'
);
}
}
Loading