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
150 changes: 135 additions & 15 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 @@ -4383,8 +4383,12 @@ private function translate( $node ): ?string {
}
}
return $value;
case 'literal':
return $this->translate_literal( $node );
case 'textLiteral':
return $this->translate_text_literal( $node );
case 'textStringLiteral':
return $this->translate_string_literal( $node->get_first_child_token() );
return $this->translate_string_literal( $node->get_first_child_token()->get_value() );
case 'dataType':
case 'nchar':
$child = $node->get_first_child();
Expand Down Expand Up @@ -4614,7 +4618,7 @@ private function translate_token( WP_MySQL_Token $token ): ?string {
return $value;
case WP_MySQL_Lexer::NCHAR_TEXT:
// A national string, such as N'abc', is a regular string in SQLite.
return $this->translate_string_literal( $token );
return $this->translate_string_literal( $token->get_value() );
case WP_MySQL_Lexer::AUTO_INCREMENT_SYMBOL:
return 'AUTOINCREMENT';
case WP_MySQL_Lexer::BINARY_SYMBOL:
Expand Down Expand Up @@ -4663,14 +4667,120 @@ private function translate_sequence( array $nodes, string $separator = ' ' ): ?s
}

/**
* Translate a MySQL string literal to SQLite.
* Translate a MySQL literal to SQLite.
*
* @param WP_MySQL_Token $token The string literal token.
* @return string The translated value.
* This handles hex and bit-value literals with a character set introducer,
* such as "_binary 0x41" or "_utf8mb4 b'01000001'". A text literal has its
* introducer in the "textLiteral" node, and other literals have none.
*
* @param WP_Parser_Node $node The "literal" AST node.
* @return string|null The translated value.
*/
private function translate_string_literal( WP_MySQL_Token $token ): string {
$value = $token->get_value();
private function translate_literal( WP_Parser_Node $node ): ?string {
$introducer = $node->get_first_child_token( WP_MySQL_Lexer::UNDERSCORE_CHARSET );
if ( null === $introducer ) {
return $this->translate_sequence( $node->get_children() );
}

/*
* Hex and bit-value literals translate to SQLite blobs. With "_binary",
* the literal is a binary string, and it stays a blob. With any other
* character set, the literal is a string with the same bytes.
*/
$value = $this->translate( $node->get_child_tokens()[1] );
$charset = strtolower( substr( $introducer->get_value(), 1 ) );
if ( 'binary' === $charset ) {
return $value;
}

// Like MySQL, reject bytes that aren't valid in a UTF-8 character set.
if ( 'utf8mb4' === $charset || 'utf8mb3' === $charset || 'utf8' === $charset ) {
$this->validate_utf8_literal( hex2bin( substr( $value, 2, -1 ) ), 'utf8mb4' === $charset );
}
return sprintf( 'CAST(%s AS TEXT)', $value );
Comment thread
youknowriad marked this conversation as resolved.
Resolved
}

/**
* Validate the bytes of a literal in a UTF-8 character set.
*
* @param string $bytes The literal bytes.
* @param bool $allow_4_bytes Whether 4-byte characters are valid (utf8mb4).
* @throws WP_MySQL_On_SQLite_Exception When the bytes are not valid.
*/
private function validate_utf8_literal( string $bytes, bool $allow_4_bytes ): void {
// PCRE validates UTF-8 without backtracking, so this works for any length.
if ( 1 === preg_match( $allow_4_bytes ? '//u' : '/\A[\x{0}-\x{FFFF}]*\z/u', $bytes ) ) {
return;
}

// Find the first invalid byte, in chunks that keep PCRE within its limits.
$characters = '[\x00-\x7F]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]'
. '|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]';
if ( $allow_4_bytes ) {
$characters .= '|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2}';
}
$valid_length = 0;
while ( 1 === preg_match( '/\G(?:' . $characters . '){1,64}+/', $bytes, $matches, 0, $valid_length ) ) {
$valid_length += strlen( $matches[0] );
}

// MySQL shows up to 3 bytes, starting at the first invalid byte.
$message = sprintf(
"Invalid %s character string: '%s'",
$allow_4_bytes ? 'utf8mb4' : 'utf8mb3',
strtoupper( bin2hex( substr( $bytes, $valid_length, 3 ) ) )
);
throw $this->new_driver_exception(
'SQLSTATE[HY000]: General error: 1300 ' . $message,
'HY000',
null,
array( 'HY000', 1300, $message )
);
}

/**
* Translate a MySQL text literal to SQLite.
*
* A text literal is one or more adjacent strings, which MySQL concatenates
* ('a' 'b' is 'ab'). The first string can be a national string (N'a'), or
* it can have a character set introducer (_binary 'a', _utf8mb4 'a').
*
* @param WP_Parser_Node $node The "textLiteral" AST node.
* @return string The translated value.
*/
private function translate_text_literal( WP_Parser_Node $node ): string {
$value = '';
$introducer = null;
foreach ( $node->get_children() as $child ) {
if ( $child instanceof WP_Parser_Node ) {
$value .= $child->get_first_child_token()->get_value();
} elseif ( WP_MySQL_Lexer::UNDERSCORE_CHARSET === $child->id ) {
$introducer = $child->get_value();
} else {
$value .= $child->get_value();
}
}

/*
* A "_binary" string is a binary string, which is a blob in SQLite.
* This keeps all the bytes, including NUL bytes.
*
* Other introducers set the character set of the string. The driver
* uses UTF-8 for all strings, so the introducer is omitted.
*/
if ( null !== $introducer && '_binary' === strtolower( $introducer ) ) {
return sprintf( "x'%s'", bin2hex( $value ) );
}
return $this->translate_string_literal( $value );
}

/**
* Translate a MySQL string literal value to SQLite.
*
* @param string $value The string literal value.
* @return string The translated value.
*/
private function translate_string_literal( string $value ): string {
/*
* Translate datetime literals.
*
Expand Down Expand Up @@ -5604,23 +5714,33 @@ private function translate_select_item( WP_Parser_Node $node ): string {
* For example, for "SELECT 'abc'", the resulting column name is "abc"
* in MySQL, but would be "'abc'" in SQLite if an alias was not used.
*
* Descend the AST until we reach a textStringLiteral. If at any level
* we don't have a single child node, bail out; it's not a bare literal.
* Descend the AST until we reach a textLiteral. If at any level we
* don't have a single child node, bail out; it's not a bare literal.
*
* MySQL names the column after the first string of the literal, without
* its introducer. For example, "SELECT _binary 'a' 'b'" is named "a".
* A national string, such as N'abc', is a single NCHAR_TEXT token.
*/
$current = $node;
while ( 'textStringLiteral' !== $current->rule_name ) {
while ( 'textLiteral' !== $current->rule_name ) {
$children = $current->get_children();
if ( 1 !== count( $children ) || ! $children[0] instanceof WP_Parser_Node ) {
break;
}
$current = $children[0];
}
if (
'textStringLiteral' === $current->rule_name
|| ( 1 === count( $current->get_children() ) && $current->has_child_token( WP_MySQL_Lexer::NCHAR_TEXT ) )
) {
$alias = $current->get_first_child_token()->get_value();
if ( 'textLiteral' === $current->rule_name ) {
$first_token = $current->get_first_child_token( WP_MySQL_Lexer::NCHAR_TEXT )
?? $current->get_first_child_node( 'textStringLiteral' )->get_first_child_token();
$alias = $first_token->get_value();
Comment thread
youknowriad marked this conversation as resolved.
Resolved

/*
* MySQL skips leading bytes that aren't printable characters: spaces
* and control bytes, and in a binary string, all non-ASCII bytes.
*/
$introducer = $current->get_first_child_token( WP_MySQL_Lexer::UNDERSCORE_CHARSET );
$is_binary = null !== $introducer && '_binary' === strtolower( $introducer->get_value() );
$alias = ltrim( $alias, $is_binary ? "\x00..\x20\x7F..\xFF" : "\x00..\x20\x7F" );

// When the literal value contains a NULL byte, MySQL truncates the
// resulting identifier at the position of the first one of them.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -955,6 +955,10 @@ public function test_quote_supports_parameter_types(): void {
$this->driver->quote( $value, PDO::PARAM_STR_NATL | PDO::PARAM_STR_CHAR )
);
$this->assertSame( '_binary' . $quoted, $this->driver->quote( $value, PDO::PARAM_LOB ) );
$this->assertSame(
$value,
$this->driver->query( 'SELECT ' . $this->driver->quote( $value, PDO::PARAM_LOB ) )->fetchColumn()
);
$this->assertSame(
'_binary' . $quoted,
$this->driver->quote( $value, PDO::PARAM_LOB | PDO::PARAM_STR_NATL )
Expand Down
121 changes: 121 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 @@ -1717,6 +1717,127 @@ public function testDeleteWithAliasAndLimit() {
$this->assertSame( 'b', $rows[0]->option_name );
}

public function testCharsetIntroducers(): void {
$result = $this->assertQuery(
"SELECT
_binary 'abc' AS binary_string,
HEX(_binary 'a\\0b') AS binary_nul,
_utf8mb4 'abc' AS utf8mb4_string,
_utf8mb4 'abc' = 'abc' AS utf8mb4_comparison,
_utf8mb4 0x616263 AS utf8mb4_hex,
HEX(_binary 0x00ff) AS binary_hex,
_latin1 b'01100001' AS latin1_bits"
);
$this->assertEquals(
array(
(object) array(
'binary_string' => 'abc',
'binary_nul' => '610062',
'utf8mb4_string' => 'abc',
'utf8mb4_comparison' => '1',
'utf8mb4_hex' => 'abc',
'binary_hex' => '00FF',
'latin1_bits' => 'a',
),
),
$result
);

// A "_binary" string keeps all its bytes when saved to a binary column.
$this->assertQuery( 'CREATE TABLE t (id INT, b BLOB, vb VARBINARY(10), s VARCHAR(10))' );
$this->assertQuery( "INSERT INTO t VALUES (1, _binary '\\0', _binary 'a\\0b', _utf8mb4 'abc')" );
$this->assertQuery( "INSERT INTO t VALUES (2, _binary '\x01', _binary '', _utf8mb4 '')" );
$result = $this->assertQuery( 'SELECT id, HEX(b) AS b, HEX(vb) AS vb, s FROM t ORDER BY id' );
$this->assertEquals(
array(
(object) array(
'id' => '1',
'b' => '00',
'vb' => '610062',
's' => 'abc',
),
(object) array(
'id' => '2',
'b' => '01',
'vb' => '',
's' => '',
),
),
$result
);
}

public function testRejectInvalidBytesInUtf8HexLiterals(): void {
$result = $this->assertQuery( 'SELECT _utf8mb4 0xC3A9 AS utf8mb4, HEX(_binary 0xE9) AS bin, HEX(_latin1 0xE9) AS latin1' );
$this->assertEquals(
array(
(object) array(
'utf8mb4' => 'é',
'bin' => 'E9',
'latin1' => 'E9',
),
),
$result
);

$this->assertQueryError(
'SELECT _utf8mb4 0xE9',
"SQLSTATE[HY000]: General error: 1300 Invalid utf8mb4 character string: 'E9'"
);
$this->assertQueryError(
"SELECT _utf8mb4 b'0100000111101001010000100100001101000100'",
"SQLSTATE[HY000]: General error: 1300 Invalid utf8mb4 character string: 'E94243'"
);
$this->assertQueryError(
'SELECT _utf8 0xF09F9982',
"SQLSTATE[HY000]: General error: 1300 Invalid utf8mb3 character string: 'F09F99'"
);

$exception = null;
try {
$this->query( 'SELECT _utf8mb4 0xE9' );
} catch ( WP_MySQL_On_SQLite_Exception $e ) {
$exception = $e;
}
$this->assertSame( array( 'HY000', 1300, "Invalid utf8mb4 character string: 'E9'" ), $exception->errorInfo );

// Large literals are checked within the PCRE limits.
$valid = str_repeat( "\xF0\x9F\x99\x82", 1000000 );
$this->assertSame( $valid, $this->assertQuery( 'SELECT _utf8mb4 0x' . bin2hex( $valid ) . ' AS v' )[0]->v );
$this->assertQueryError(
'SELECT _utf8mb4 0x' . bin2hex( $valid ) . 'E9',
"SQLSTATE[HY000]: General error: 1300 Invalid utf8mb4 character string: 'E9'"
);
}

public function testTextLiteralColumnNamesSkipLeadingNonPrintableBytes(): void {
$this->assertQuery( "SELECT ' a', '\\t\\nb c', '\\0 \\0d\\0e', ' ', _binary ' \x80f'" );
$this->assertSame( array( 'a', 'b c', 'd', '', 'f' ), array_column( $this->getLastColumnMeta(), 'name' ) );

$result = $this->assertQuery( "SELECT HEX(d.a) AS a FROM (SELECT _binary '\\0a' 'b') d" );
$this->assertSame( '006162', $result[0]->a );
}

public function testAdjacentStringLiterals(): void {
$result = $this->assertQuery( "SELECT 'a' 'b' 'c' AS plain, N'a' 'b' AS national, HEX(_binary 'a' '\\0') AS binary_string" );
$this->assertEquals(
array(
(object) array(
'plain' => 'abc',
'national' => 'ab',
'binary_string' => '6100',
),
),
$result
);

// MySQL names the column after the first string, without its introducer.
$this->assertQuery( "SELECT 'a' 'b', _utf8mb4 'c' 'd'" );
$this->assertSame( array( 'a', 'c' ), array_column( $this->getLastColumnMeta(), 'name' ) );
$result = $this->assertQuery( "SELECT a FROM (SELECT 'a' 'b') AS t" );
$this->assertSame( 'ab', $result[0]->a );
}

public function testCastAsBinary() {
// Use a confusing alias to make sure it replaces only the correct token
$this->assertQuery( "SELECT CAST('ABC' AS BINARY) as `binary`" );
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1804,6 +1804,57 @@ public function testNationalStringLiterals(): void {
);
}

public function testCharsetIntroducers(): void {
// A "_binary" string is a blob.
$this->assertQuery(
"SELECT x'616263' AS `abc`",
"SELECT _binary 'abc'"
);
$this->assertQuery(
"SELECT x'00' AS ``",
"SELECT _binary '\\0'"
);

// Other introducers are omitted.
$this->assertQuery(
"SELECT 'abc' AS `abc`",
"SELECT _utf8mb4'abc'"
);
$this->assertQuery(
"SELECT 'abc' AS `abc`",
"SELECT _LATIN1 'abc'"
);

// Hex and bit-value literals stay blobs with "_binary" and become strings otherwise.
$this->assertQuery(
"SELECT x'41' AS `_binary 0x41`",
'SELECT _binary 0x41'
);
$this->assertQuery(
"SELECT CAST(x'41' AS TEXT) AS `_utf8mb4 0x41`",
'SELECT _utf8mb4 0x41'
);
$this->assertQuery(
"SELECT CAST(x'41' AS TEXT) AS `_utf8mb4 b'01000001'`",
"SELECT _utf8mb4 b'01000001'"
);
}

public function testAdjacentStringLiterals(): void {
$this->assertQuery(
"SELECT 'abc' AS `a`",
"SELECT 'a' 'b' 'c'"
);
$this->assertQuery(
"SELECT 'ab' AS `a`",
"SELECT N'a' 'b'"
);
$this->assertQuery(
"SELECT x'6162' AS `a`",
"SELECT _binary 'a' 'b'"
);
}

public function testSystemVariables(): void {
$this->assertQuery(
"SELECT 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' AS `@@sql_mode`",
Expand Down
Loading