Skip to content

Commit 6ca5528

Browse files
authored
Fix character set handling in the MySQL lexer and query corpus (#609)
This PR fixes character set handling in the `mysql-parser` package, in both the lexer and the query corpus. It was split out from the MySQL version support work, but it doesn't depend on it. ## Lexer **The lexer now accepts two kinds of names that MySQL accepts:** - **4-byte characters in unquoted names, like `🐬` or `𩸽`.** The lexer stopped at U+FFFF, the limit in the MySQL documentation, but MySQL accepts any multibyte character of the connection character set. This was checked in the MySQL 5.5 and 5.7 lexer sources and on MySQL 8.4. - **Non-ASCII characters in names after `@`.** The scan stopped at the first non-ASCII byte, so `SET @é = 1` failed to parse, and `SELECT @x🐬` would read `@x` with the alias `🐬`. MySQL reads these as one name. The same scan reads hosts like `u@é.example.com`. **Some things don't change:** - **Names that MySQL can't store:** MySQL converts names to `utf8mb3`, which can't store 4-byte characters. A quoted alias like `'🐬'` fails since MySQL 8.0.17, and unquoted and backticked names become `?`, so tables `🐬` and `😀` collide. The lexer follows the syntax and leaves this to the code that uses the parser. - **Invalid UTF-8:** MySQL accepts it in names, but the lexer keeps rejecting it. - **The driver:** Its own lexer in `mysql-on-sqlite` still rejects 4-byte names and still stops at non-ASCII bytes after `@`. ## Query corpus extractor The extractor decoded every MySQL test file as Latin-1, but most of them are UTF-8. Non-ASCII text came out double-encoded (`geprüft` became `geprüft`), `0x85` bytes inside UTF-8 characters split lines, and sections using `--character_set` were decoded twice. **It now reads test files as MySQL reads them:** - **Client character set:** Each line uses the character set that the test selects with `SET NAMES`, `SET CHARACTER SET`, or `character_set_client`. The default comes from the test suite's `default_client.cnf`, which is utf8mb4 on MySQL 8.4. - **String literals:** A literal with an introducer, like `_koi8r'...'`, is read in that character set. - **Invalid text:** Text that isn't valid in these character sets is read as MySQL's latin1, with the same result on all PHP versions. - **`--character_set`:** This mysqltest command is ignored. It only affects connections that a test opens later, and no query depends on that. - **Line endings:** Only LF and CRLF end a line, as in mysqltest. **Two edge cases are expected:** - **Queries that look double-encoded:** A test that sends UTF-8 bytes after `SET NAMES latin1` is read as latin1, because that's how MySQL reads it. Queries like `"óra"` look wrong for this reason. - **Introducers inside strings:** The extractor doesn't track strings here, so `"_latin1'é'"` would be read as an introducer. No query extracted from the MySQL 8.4.10 or 5.7.44 tests does this. **The extractor also has some cleanup:** - The decoding moved to its own file, with tests. - The cp1250 character set has its own table, because mbstring doesn't support it. - The deprecated `utf8_encode()` and `HTML-ENTITIES` conversion are gone, and `fputcsv()` gets the escape character that PHP 8.4 requires. ## Regenerated corpus The MySQL 8.4.10 corpus now gives these results: - **Queries:** 69,076 instead of 69,158. The total falls because statements that two test files have in different encodings now read the same and count once, such as 242 queries shared by the `ctype_gb18030_encoding_cn` and `ctype_gb18030_encoding_utf8` tests. Statements that a misread quote used to merge are now separate, and six `comments.test` queries that differ only in a line separator are back. - **Failures:** 166 instead of 167. The failing queries are the same, now with correct text, except for one former failure that was several statements merged into one. See: https://bugs.mysql.com/bug.php?id=93626 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * MySQL identifiers can include valid four-byte UTF-8 characters, including characters outside the Basic Multilingual Plane, and are preserved during parsing. * User-variable names can include dots and non-ASCII characters and are recognized as a single token. * **Bug Fixes** * Improved parsing of SQL containing Unicode identifiers and user-variable names, including SQL using different character sets. * **Tests** * Added coverage for Unicode parsing, variable names, character-set handling, and query-corpus contents. * Updated the MySQL query-corpus test totals. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent f05c1f9 commit 6ca5528

9 files changed

Lines changed: 2016 additions & 1551 deletions

‎packages/mysql-parser/data/mysql-server-query-corpus/mysql-latest.csv‎

Lines changed: 1257 additions & 1414 deletions
Large diffs are not rendered by default.

‎packages/mysql-parser/src/class-wp-mysql-lexer.php‎

Lines changed: 45 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -667,11 +667,11 @@ private function produce_with_or_rollup( array &$out, int $with_start, int $with
667667
*
668668
* MySQL treats "@" as its own terminal. A single "@" is followed by the
669669
* unquoted user-variable name (always an identifier, never a keyword; it may
670-
* contain "." and "$"), by an empty name (MySQL's empty LEX_HOSTNAME, which
671-
* makes "SELECT @" and "user1@" valid), or by a quoted name supplied by the
672-
* following token. A "@@" prefix is two "@" terminals, followed by the system
673-
* variable name. As in MySQL, that name can't be empty, and only backticks
674-
* can quote it.
670+
* contain ".", "$", and non-ASCII characters), by an empty name (MySQL's empty
671+
* LEX_HOSTNAME, which makes "SELECT @" and "user1@" valid), or by a quoted name
672+
* supplied by the following token. A "@@" prefix is two "@" terminals, followed
673+
* by the system variable name. As in MySQL, that name can't be empty, and only
674+
* backticks can quote it.
675675
*
676676
* @param int $at_start Byte offset of the "@" token.
677677
*/
@@ -697,14 +697,21 @@ private function produce_at_variable( array &$out, int $at_start ): void {
697697
return;
698698
}
699699

700-
$name_length = strspn(
701-
$this->sql,
702-
self::IDENTIFIER_MASK . '.',
703-
$position
704-
);
700+
// Read the identifier characters and any "." between them as one name.
701+
while ( true ) {
702+
$this->read_identifier();
703+
if ( '.' !== ( $this->sql[ $this->bytes_already_read ] ?? null ) ) {
704+
break;
705+
}
706+
$this->bytes_already_read += 1;
707+
}
708+
709+
// The "." read as a part of the name is not a qualified name separator.
710+
$this->next_state = self::STATE_START;
711+
712+
$name_length = $this->bytes_already_read - $position;
705713
if ( $name_length > 0 ) {
706-
$out[] = $this->make_token( self::IDENT, $position, $name_length );
707-
$this->bytes_already_read = $position + $name_length;
714+
$out[] = $this->make_token( self::IDENT, $position, $name_length );
708715
} elseif ( "'" !== $next && '"' !== $next && '`' !== $next ) {
709716
$out[] = $this->make_token( self::IDENT, $position, 0 );
710717
}
@@ -803,7 +810,7 @@ private function read_next_token(): ?int {
803810

804811
// Fast path for keywords and identifiers.
805812
// `$byte > "\x7F"` catches any non-ASCII byte (0x80-0xFF); read_identifier()
806-
// restricts the accepted identifier codepoints to U+0080-U+FFFF.
813+
// restricts the accepted identifier codepoints to U+0080-U+10FFFF.
807814
// `"'" !== $next_byte` defers x'..', n'..' and similar special
808815
// literals to their dedicated branches below; only single quotes
809816
// form those, regardless of SQL mode.
@@ -1026,10 +1033,13 @@ private function get_current_token_bytes(): string {
10261033
*
10271034
* This function reads characters that are allowed in an unquoted identifier.
10281035
* It accepts digit-only sequences too; callers scan those as numbers, except
1029-
* after "." or "@@".
1036+
* after ".", "@", or "@@".
10301037
*
10311038
* Rules:
1032-
* 1. Allowed characters are ASCII a-z, A-Z, 0-9, _, $, and Unicode U+0080-U+FFFF.
1039+
* 1. Allowed characters are ASCII a-z, A-Z, 0-9, _, $, and Unicode U+0080-U+10FFFF.
1040+
* The MySQL documentation lists only U+0080-U+FFFF, but the MySQL lexer accepts
1041+
* any utf8mb4 character, including U+10000-U+10FFFF. MySQL then stores
1042+
* these characters as "?", because it keeps names in utf8mb3.
10331043
* 2. Unquoted identifiers may begin with a digit but may not consist solely of digits.
10341044
* An exception is a part of a qualified name, such as "1" in "t.1".
10351045
*
@@ -1047,13 +1057,13 @@ private function read_identifier(): ?int {
10471057
);
10481058

10491059
// Check if the following byte can be part of a multibyte character
1050-
// in the range of U+0080 to U+FFFF before looking at further bytes.
1060+
// in the range of U+0080 to U+10FFFF before looking at further bytes.
10511061
// If it can't, bail out early to avoid unnecessary UTF-8 decoding.
10521062
// Identifiers are usually ASCII-only, so we can optimize for that.
10531063
$byte_1 = ord(
10541064
$this->sql[ $this->bytes_already_read ] ?? "\0"
10551065
);
1056-
if ( $byte_1 < 0xC2 || $byte_1 > 0xEF ) {
1066+
if ( $byte_1 < 0xC2 || $byte_1 > 0xF4 ) {
10571067
break;
10581068
}
10591069

@@ -1086,6 +1096,24 @@ private function read_identifier(): ?int {
10861096
continue;
10871097
}
10881098

1099+
// Look for a valid 4-byte UTF-8 symbol in range U+10000 - U+10FFFF.
1100+
$byte_4 = ord(
1101+
$this->sql[ $this->bytes_already_read + 3 ] ?? "\0"
1102+
);
1103+
if (
1104+
$byte_1 >= 0xF0
1105+
&& $byte_2 >= 0x80 && $byte_2 <= 0xBF
1106+
&& $byte_3 >= 0x80 && $byte_3 <= 0xBF
1107+
&& $byte_4 >= 0x80 && $byte_4 <= 0xBF
1108+
// Exclude overlong encodings:
1109+
&& ! ( 0xF0 === $byte_1 && $byte_2 < 0x90 )
1110+
// Exclude codepoints above U+10FFFF:
1111+
&& ! ( 0xF4 === $byte_1 && $byte_2 > 0x8F )
1112+
) {
1113+
$this->bytes_already_read += 4;
1114+
continue;
1115+
}
1116+
10891117
// Not a valid identifier character.
10901118
break;
10911119
}

‎packages/mysql-parser/tests/WP_MySQL_Lexer_Tests.php‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,53 @@ public function test_at_name_splits_into_at_and_ident(): void {
217217
$this->assertSame( 4, $tokens[2]->length );
218218
}
219219

220+
/**
221+
* In MySQL, the name after "@" is one token, also with non-ASCII characters.
222+
*
223+
* @dataProvider data_at_names
224+
*/
225+
public function test_at_name_is_one_token( string $sql, array $expected ): void {
226+
$tokens = ( new WP_MySQL_Lexer( $sql ) )->remaining_tokens();
227+
$this->assertSame(
228+
$expected,
229+
array_map(
230+
static function ( WP_MySQL_Token $token ): string {
231+
return $token->get_bytes();
232+
},
233+
$tokens
234+
)
235+
);
236+
}
237+
238+
/**
239+
* @return array<string,array{0:string,1:string[]}>
240+
*/
241+
public function data_at_names(): array {
242+
return array(
243+
'ASCII' => array( '@a1_$', array( '@', 'a1_$', '', '' ) ),
244+
'with a dot' => array( '@a.b', array( '@', 'a.b', '', '' ) ),
245+
'starting with a dot' => array( '@.a', array( '@', '.a', '', '' ) ),
246+
'ending with a dot' => array( '@a.', array( '@', 'a.', '', '' ) ),
247+
'only dots' => array( '@..', array( '@', '..', '', '' ) ),
248+
'2-byte character' => array( '@é', array( '@', 'é', '', '' ) ),
249+
'after an ASCII character' => array( '@xé', array( '@', 'xé', '', '' ) ),
250+
'3-byte character' => array( '@x€y', array( '@', 'x€y', '', '' ) ),
251+
'4-byte character' => array( '@🐬', array( '@', '🐬', '', '' ) ),
252+
'4-byte character after x' => array( '@x🐬', array( '@', 'x🐬', '', '' ) ),
253+
'non-ASCII after a dot' => array( '@a.🐬', array( '@', 'a.🐬', '', '' ) ),
254+
'non-ASCII before a dot' => array( '@🐬.a', array( '@', '🐬.a', '', '' ) ),
255+
'followed by an operator' => array( '@é+1', array( '@', 'é', '+', '1', '', '' ) ),
256+
'followed by a name' => array( '@é a', array( '@', 'é', 'a', '', '' ) ),
257+
'followed by a number' => array( '@a.b .5', array( '@', 'a.b', '.5', '', '' ) ),
258+
'host part of a user' => array( 'u@é.example.com', array( 'u', '@', 'é.example.com', '', '' ) ),
259+
260+
// Invalid UTF-8 ends the stream, as elsewhere in the lexer.
261+
'invalid byte' => array( "@x\xFF", array( '@', 'x' ) ),
262+
'truncated 4-byte sequence' => array( "@x\xF0\x9F\x90", array( '@', 'x' ) ),
263+
'invalid byte first' => array( "@\xFF", array( '@', '' ) ),
264+
);
265+
}
266+
220267
public function test_at_at_splits_into_two_at_signs(): void {
221268
$this->assertSame(
222269
array( 'SELECT', 'AT_SIGN', 'AT_SIGN', 'IDENT', 'END_OF_INPUT', 'YYEOF' ),
@@ -425,6 +472,61 @@ public function test_identifier_utf8_three_byte_sequences(): void {
425472
}
426473
}
427474

475+
/**
476+
* Test valid and invalid 4-byte UTF-8 sequences in an identifier.
477+
* The validity is checked against PCRE with the "u" (PCRE_UTF8) modifier set.
478+
*
479+
* Testing all 4-byte sequences would take too long, so the first two bytes
480+
* are tested with valid trailing bytes, and the last two bytes are tested
481+
* with valid leading bytes. The first byte starts from 0xF0 to mark the
482+
* beginning of a 4-byte sequence, and the other bytes go from 128 to 255.
483+
*/
484+
public function test_identifier_utf8_four_byte_sequences(): void {
485+
$values = array();
486+
for ( $byte_1 = 0xF0; $byte_1 <= 0xFF; $byte_1 += 1 ) {
487+
for ( $byte_2 = 128; $byte_2 <= 255; $byte_2 += 1 ) {
488+
$values[] = chr( $byte_1 ) . chr( $byte_2 ) . "\x80\x80";
489+
}
490+
}
491+
for ( $byte_3 = 128; $byte_3 <= 255; $byte_3 += 1 ) {
492+
for ( $byte_4 = 128; $byte_4 <= 255; $byte_4 += 1 ) {
493+
$values[] = "\xF0\x9F" . chr( $byte_3 ) . chr( $byte_4 );
494+
}
495+
}
496+
497+
foreach ( $values as $value ) {
498+
$lexer = new WP_MySQL_Lexer( $value );
499+
$result = $lexer->next_token();
500+
$token = $lexer->get_token();
501+
502+
$is_valid = preg_match( '/^[\x{10000}-\x{10ffff}]$/u', $value );
503+
if ( $is_valid ) {
504+
$this->assertTrue( $result );
505+
$this->assertSame( WP_MySQL_Lexer::IDENT, $token->id );
506+
$this->assertSame( $value, $token->get_bytes() );
507+
} else {
508+
$this->assertFalse( $result );
509+
$this->assertNull( $token );
510+
}
511+
}
512+
}
513+
514+
public function test_identifier_with_4_byte_characters(): void {
515+
// The MySQL lexer accepts 4-byte characters in unquoted identifiers on all versions.
516+
foreach ( array( 50744, 80410 ) as $mysql_version ) {
517+
$tokens = ( new WP_MySQL_Lexer( 'SELECT a🐬b, 𩸽 FROM 🐬', $mysql_version ) )->remaining_tokens();
518+
$this->assertSame(
519+
array( 'SELECT', 'a🐬b', ',', '𩸽', 'FROM', '🐬', '', '' ),
520+
array_map(
521+
static function ( WP_MySQL_Token $token ): string {
522+
return $token->get_bytes();
523+
},
524+
$tokens
525+
)
526+
);
527+
}
528+
}
529+
428530
/**
429531
* A charset-introducer-like name used as a qualified member (after a dot)
430532
* must lex as an identifier. A real charset introducer only appears before

‎packages/mysql-parser/tests/WP_MySQL_Parser_Tests.php‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,9 +102,15 @@ public function test_parses_representative_statements(): void {
102102
'UPDATE t SET a = a + 1 WHERE b IN (SELECT b FROM u)',
103103
'DELETE FROM t WHERE a IS NOT NULL',
104104
'CREATE TABLE t (id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))',
105+
'CREATE TABLE 🐬 (🐬 INT, a🐬b INT)',
106+
'SELECT 🐬.a🐬b FROM 🐬 AS 𩸽',
105107
'ALTER TABLE t ADD COLUMN c JSON',
106108
'DROP TABLE IF EXISTS t',
107109
'SET @v = 1',
110+
'SET @é = 1',
111+
'SELECT @xé + 1 AS plus_one',
112+
'SELECT @x🐬 + 1 AS plus_one, a FROM t',
113+
'CREATE USER u@é',
108114
'SET @@SESSION.sql_mode = \'\'',
109115
'SELECT @@`version`',
110116
'SHOW TABLES',

0 commit comments

Comments
 (0)