Skip to content

Commit 5af40ea

Browse files
committed
Lex qualified names with MySQL's lexer states
MySQL reads "t.1", "t.1st", and "order.id" as qualified names, but both lexers failed on them: they scanned ".1" as a decimal number, and they emitted "order" as the ORDER keyword. Follow MySQL's lexer, where a token sets a state for the next one ("next_state" in sql/sql_lex.cc): - A name followed by "." and a name character sets STATE_IDENTIFIER_SEPARATOR. The "." then separates qualified name parts, even before digits ("t.1"), and a keyword before it is an identifier ("order.id"). - A "." token followed by a name character sets STATE_IDENTIFIER_START. The name after it is then always an identifier ("t.order", "t.1"), even when it looks like a literal prefix ("x" in "t.x'41'"). - "@@" sets STATE_IDENTIFIER_OR_KEYWORD, so system variable scopes like "@@session.sql_mode" stay keywords. A "." that ends a number sets no state, so "1.FROM dual" is a number and the FROM keyword, as in MySQL. A "." after a quoted name or a space still starts a number. The lexing speed stays the same. The fix applies to the mysql-parser lexer and to the mysql-on-sqlite lexer that the driver still uses. The MySQL server corpus query that covers this case now parses in both, and driver tests run such queries end to end. See: https://github.com/mysql/mysql-server/blob/mysql-8.4.10/sql/sql_lex.cc
1 parent c13b4d3 commit 5af40ea

9 files changed

Lines changed: 406 additions & 48 deletions

‎packages/mysql-on-sqlite/src/mysql/class-wp-mysql-lexer.php‎

Lines changed: 108 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -944,6 +944,22 @@ class WP_MySQL_Lexer {
944944
const WHITESPACE = 0;
945945
const EOF = -1;
946946

947+
/**
948+
* Lexer states that a token sets for the next one (see "next_state").
949+
*
950+
* They match MySQL's lexer states in sql/sql_lex.cc, with full words
951+
* instead of MySQL's abbreviations:
952+
*
953+
* - STATE_START: MY_LEX_START
954+
* - STATE_IDENTIFIER_SEPARATOR: MY_LEX_IDENT_SEP
955+
* - STATE_IDENTIFIER_START: MY_LEX_IDENT_START
956+
* - STATE_IDENTIFIER_OR_KEYWORD: MY_LEX_IDENT_OR_KEYWORD
957+
*/
958+
private const STATE_START = -2;
959+
private const STATE_IDENTIFIER_SEPARATOR = -3;
960+
private const STATE_IDENTIFIER_START = -4;
961+
private const STATE_IDENTIFIER_OR_KEYWORD = -5;
962+
947963
/**
948964
* A map of SQL keyword string values to their corresponding token types.
949965
*
@@ -2176,6 +2192,26 @@ class WP_MySQL_Lexer {
21762192
*/
21772193
private $token_type;
21782194

2195+
/**
2196+
* The lexer state that the previous token set for the next one.
2197+
*
2198+
* Like MySQL's "next_state", each token reads and resets it:
2199+
*
2200+
* - STATE_IDENTIFIER_SEPARATOR: Set by a name before "." and a name
2201+
* character. The "." is then a separator, even before digits ("t.1"),
2202+
* and the name is an identifier, even if it's a keyword ("order.id").
2203+
* - STATE_IDENTIFIER_START: Set by a "." before a name character. The
2204+
* name is then always an identifier ("t.order", "t.1", "t.x'41'").
2205+
* - STATE_IDENTIFIER_OR_KEYWORD: Set by "@@" before a name character.
2206+
* The name then stays a keyword, even before a "." ("@@session.x").
2207+
*
2208+
* A "." that ends a number sets no state, so "1.FROM" is a number and
2209+
* a keyword.
2210+
*
2211+
* @var int
2212+
*/
2213+
private $next_state = self::STATE_START;
2214+
21792215
/**
21802216
* Whether the tokenizer is inside an active MySQL-specific comment.
21812217
*
@@ -2420,6 +2456,10 @@ public static function get_token_name( int $token_id ): ?string {
24202456
}
24212457

24222458
private function read_next_token(): ?int {
2459+
// Read and reset the state that the previous token set.
2460+
$state = $this->next_state;
2461+
$this->next_state = self::STATE_START;
2462+
24232463
$byte = $this->sql[ $this->bytes_already_read ] ?? null;
24242464
$next_byte = $this->sql[ $this->bytes_already_read + 1 ] ?? null;
24252465

@@ -2455,19 +2495,25 @@ private function read_next_token(): ?int {
24552495
) {
24562496
$started_at = $this->bytes_already_read;
24572497
$type = $this->read_identifier();
2458-
if (
2459-
self::IDENTIFIER === $type
2460-
// When preceded by a dot, it is always an identifier.
2461-
&& ! ( $started_at > 0 && '.' === $this->sql[ $started_at - 1 ] )
2462-
) {
2498+
2499+
// After a "." separator, it is always an identifier. Invalid input
2500+
// needs no check: the type is then null, and no keyword is empty.
2501+
if ( self::STATE_IDENTIFIER_START !== $state ) {
24632502
// Inline the keyword lookup on the hot identifier path: most
24642503
// identifiers are not keywords, so this avoids two method calls
24652504
// (token-bytes extraction + keyword determination) per token.
24662505
$keyword = self::TOKENS[ strtoupper(
24672506
substr( $this->sql, $started_at, $this->bytes_already_read - $started_at )
24682507
) ] ?? self::IDENTIFIER;
24692508
if ( self::IDENTIFIER !== $keyword ) {
2470-
$type = $this->resolve_keyword_type( $keyword );
2509+
// Before "." and a name, a keyword is an identifier ("order.id"),
2510+
// except after "@@" ("session" in "@@session.x"). read_identifier()
2511+
// has just set STATE_IDENTIFIER_SEPARATOR if "." and a name follow.
2512+
if ( self::STATE_IDENTIFIER_SEPARATOR !== $this->next_state ) {
2513+
$type = $this->resolve_keyword_type( $keyword );
2514+
} elseif ( self::STATE_IDENTIFIER_OR_KEYWORD === $state ) {
2515+
$type = $this->resolve_keyword_type( $keyword );
2516+
}
24712517
}
24722518
}
24732519
} elseif ( null !== $byte && isset( $single_byte_ops[ $byte ] ) ) {
@@ -2477,13 +2523,28 @@ private function read_next_token(): ?int {
24772523
} elseif ( "'" === $byte || '"' === $byte || '`' === $byte ) {
24782524
$type = $this->read_quoted_text();
24792525
} elseif ( null !== $byte && strspn( $byte, self::DIGIT_MASK ) > 0 ) {
2480-
$type = $this->read_number();
2526+
// After a "." separator, it is a qualified name part ("1" in "t.1").
2527+
if ( self::STATE_IDENTIFIER_START === $state ) {
2528+
$type = $this->read_identifier();
2529+
} else {
2530+
$type = $this->read_number();
2531+
}
24812532
} elseif ( '.' === $byte ) {
2482-
if ( null !== $next_byte && strspn( $next_byte, self::DIGIT_MASK ) > 0 ) {
2533+
if (
2534+
null !== $next_byte
2535+
&& strspn( $next_byte, self::DIGIT_MASK ) > 0
2536+
// Right after a name, it is a qualified name separator.
2537+
&& self::STATE_IDENTIFIER_SEPARATOR !== $state
2538+
) {
24832539
$type = $this->read_number();
24842540
} else {
24852541
$this->bytes_already_read += 1;
24862542
$type = self::DOT_SYMBOL;
2543+
2544+
// A name character right after it starts a qualified name part.
2545+
if ( null !== $next_byte && ( strspn( $next_byte, self::IDENTIFIER_MASK ) > 0 || $next_byte > "\x7F" ) ) {
2546+
$this->next_state = self::STATE_IDENTIFIER_START;
2547+
}
24872548
}
24882549
} elseif ( ':' === $byte ) {
24892550
$this->bytes_already_read += 1; // Consume the ':'.
@@ -2604,6 +2665,14 @@ private function read_next_token(): ?int {
26042665
if ( '@' === $next_byte ) {
26052666
$this->bytes_already_read += 1; // Consume the second '@'.
26062667
$type = self::AT_AT_SIGN_SYMBOL;
2668+
2669+
// The name after it may be a keyword ("session" in "@@session.x").
2670+
if (
2671+
strspn( $this->sql, self::IDENTIFIER_MASK, $this->bytes_already_read, 1 ) > 0
2672+
|| ( $this->sql[ $this->bytes_already_read ] ?? '' ) > "\x7F"
2673+
) {
2674+
$this->next_state = self::STATE_IDENTIFIER_OR_KEYWORD;
2675+
}
26072676
} else {
26082677
/**
26092678
* Check whether the '@' marks an unquoted user-defined variable:
@@ -2634,9 +2703,18 @@ private function read_next_token(): ?int {
26342703
} elseif ( null !== $byte && strspn( $byte, self::WHITESPACE_MASK ) > 0 ) {
26352704
$this->bytes_already_read += strspn( $this->sql, self::WHITESPACE_MASK, $this->bytes_already_read );
26362705
$type = self::WHITESPACE;
2637-
} elseif ( ( 'x' === $byte || 'X' === $byte || 'b' === $byte || 'B' === $byte ) && "'" === $next_byte ) {
2706+
} elseif (
2707+
( 'x' === $byte || 'X' === $byte || 'b' === $byte || 'B' === $byte )
2708+
&& "'" === $next_byte
2709+
// Not after a "." separator, where the letter is a name ("x" in "t.x'41'").
2710+
&& self::STATE_IDENTIFIER_START !== $state
2711+
) {
26382712
$type = $this->read_number();
2639-
} elseif ( ( 'n' === $byte || 'N' === $byte ) && "'" === $next_byte ) {
2713+
} elseif (
2714+
( 'n' === $byte || 'N' === $byte )
2715+
&& "'" === $next_byte
2716+
&& self::STATE_IDENTIFIER_START !== $state
2717+
) {
26402718
$this->bytes_already_read += 1; // n/N
26412719
$type = $this->read_quoted_text( "'" );
26422720
if ( self::SINGLE_QUOTED_TEXT === $type ) {
@@ -2648,8 +2726,8 @@ private function read_next_token(): ?int {
26482726
$started_at = $this->bytes_already_read;
26492727
$type = $this->read_identifier();
26502728
if ( self::IDENTIFIER === $type ) {
2651-
// When preceded by a dot, it is always an identifier.
2652-
if ( $started_at > 0 && '.' === $this->sql[ $started_at - 1 ] ) {
2729+
// After a "." separator, it is always an identifier.
2730+
if ( self::STATE_IDENTIFIER_START === $state ) {
26532731
$type = self::IDENTIFIER;
26542732
} elseif ( '_' === $byte && isset( self::UNDERSCORE_CHARSETS[ strtolower( $this->get_current_token_bytes() ) ] ) ) {
26552733
$type = self::UNDERSCORE_CHARSET;
@@ -2673,13 +2751,13 @@ private function get_current_token_bytes(): string {
26732751
* Read an unquoted identifier.
26742752
*
26752753
* This function reads characters that are allowed in an unquoted identifier.
2676-
* An identifier cannot consist solely of digits, but this function doesn't
2677-
* ensure that explicitly, as numbers are processed before identifiers in
2678-
* the tokenization process, recognizing all digit-only sequences as numbers.
2754+
* It accepts digit-only sequences too; callers scan those as numbers, except
2755+
* for qualified name parts.
26792756
*
26802757
* Rules:
26812758
* 1. Allowed characters are ASCII a-z, A-Z, 0-9, _, $, and Unicode U+0080-U+FFFF.
26822759
* 2. Unquoted identifiers may begin with a digit but may not consist solely of digits.
2760+
* An exception is a part of a qualified name, such as "1" in "t.1".
26832761
*
26842762
* See:
26852763
* https://dev.mysql.com/doc/refman/8.4/en/identifiers.html
@@ -2738,17 +2816,25 @@ private function read_identifier(): ?int {
27382816
break;
27392817
}
27402818

2741-
// An identifier cannot consist solely of digits, but we don't need to
2742-
// ensure that explicitly, as numbers are processed before identifiers.
2819+
if ( $this->bytes_already_read === $started_at ) {
2820+
return null; // Invalid input.
2821+
}
27432822

2744-
return $this->bytes_already_read - $started_at > 0
2745-
? self::IDENTIFIER
2746-
: null; // Invalid input.
2823+
// When "." and a name character follow, the "." is a separator.
2824+
// "$byte_1" already holds the byte after the name. A nested "if" is
2825+
// faster than "&&" without opcache.
2826+
if ( 0x2E === $byte_1 ) {
2827+
if (
2828+
strspn( $this->sql, self::IDENTIFIER_MASK, $this->bytes_already_read + 1, 1 ) > 0
2829+
|| ( $this->sql[ $this->bytes_already_read + 1 ] ?? '' ) > "\x7F"
2830+
) {
2831+
$this->next_state = self::STATE_IDENTIFIER_SEPARATOR;
2832+
}
2833+
}
2834+
return self::IDENTIFIER;
27472835
}
27482836

27492837
private function read_number(): ?int {
2750-
// @TODO: Support numeric-only identifier parts after "." (e.g., 1ea10.1).
2751-
27522838
$byte = $this->sql[ $this->bytes_already_read ] ?? null;
27532839
$next_byte = $this->sql[ $this->bytes_already_read + 1 ] ?? null;
27542840
$third_byte = $this->sql[ $this->bytes_already_read + 2 ] ?? null;

‎packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14475,6 +14475,51 @@ public function testFullyQualifiedTableName(): void {
1447514475
$this->assertCount( 0, $result );
1447614476
}
1447714477

14478+
public function testQualifiedNamePartsStartingWithDigits(): void {
14479+
$this->assertQuery( 'CREATE TABLE 1t (`1` INT, `1st` INT, `1e5` INT)' );
14480+
$this->assertQuery( 'INSERT INTO 1t VALUES (1, 2, 3), (4, 5, 6)' );
14481+
14482+
$result = $this->assertQuery( 'SELECT 1t.1, 1t.1st, 1t.1e5 FROM 1t WHERE 1t.1 = 4' );
14483+
$this->assertEquals(
14484+
array(
14485+
(object) array(
14486+
'1' => '4',
14487+
'1st' => '5',
14488+
'1e5' => '6',
14489+
),
14490+
),
14491+
$result
14492+
);
14493+
14494+
$result = $this->assertQuery( 'SELECT wp.1t.1st FROM wp.1t ORDER BY wp.1t.1 DESC' );
14495+
$this->assertEquals(
14496+
array( (object) array( '1st' => '5' ), (object) array( '1st' => '2' ) ),
14497+
$result
14498+
);
14499+
}
14500+
14501+
public function testReservedWordsAsQualifiers(): void {
14502+
$this->assertQuery( 'CREATE TABLE `order` (id INT, `1` INT)' );
14503+
$this->assertQuery( 'INSERT INTO `order` VALUES (7, 8), (9, 10)' );
14504+
14505+
$result = $this->assertQuery( 'SELECT order.id, order.1 FROM `order` WHERE order.id = 7' );
14506+
$this->assertEquals(
14507+
array(
14508+
(object) array(
14509+
'id' => '7',
14510+
'1' => '8',
14511+
),
14512+
),
14513+
$result
14514+
);
14515+
14516+
$result = $this->assertQuery( 'SELECT wp.order.1 FROM wp.`order` ORDER BY order.id DESC' );
14517+
$this->assertEquals(
14518+
array( (object) array( '1' => '10' ), (object) array( '1' => '8' ) ),
14519+
$result
14520+
);
14521+
}
14522+
1447814523
public function testWriteWithUsageOfInformationSchemaTables(): void {
1447914524
// Ensure "information_schema.tables" is empty.
1448014525
$this->assertQuery( 'DROP TABLE _options, _dates' );

‎packages/mysql-on-sqlite/tests/mysql/WP_MySQL_Lexer_Tests.php‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,72 @@ public function data_underscore_charset_after_dot(): array {
422422
);
423423
}
424424

425+
/**
426+
* Qualified names are lexed as in MySQL. A "." right after a name is
427+
* a separator, even before digits, and a keyword before it is an
428+
* identifier, except after "@@". A name right after a "." separator is
429+
* always an identifier. Elsewhere, ".N" is a number. All cases are
430+
* verified against MySQL 8.4.
431+
*
432+
* @dataProvider data_qualified_name_tokens
433+
*/
434+
public function test_qualified_name_tokens( string $sql, array $expected ): void {
435+
$names = array();
436+
foreach ( ( new WP_MySQL_Lexer( $sql ) )->remaining_tokens() as $token ) {
437+
$names[] = $token->get_name();
438+
}
439+
$this->assertSame( array_merge( $expected, array( 'EOF' ) ), $names );
440+
}
441+
442+
/**
443+
* @return array<string,array{0:string,1:string[]}>
444+
*/
445+
public function data_qualified_name_tokens(): array {
446+
$qualified = array( 'IDENTIFIER', 'DOT_SYMBOL', 'IDENTIFIER' );
447+
return array(
448+
// Digits after a dot are a qualified name part.
449+
'digits only' => array( 't.1', $qualified ),
450+
'digit-led identifier' => array( 't.1st', $qualified ),
451+
'float-like identifier' => array( 't.1e5', $qualified ),
452+
'part ends before a sign' => array( 't.1e+5', array_merge( $qualified, array( 'PLUS_OPERATOR', 'INT_NUMBER' ) ) ),
453+
'after a digit-led qualifier' => array( '1ea10.1', $qualified ),
454+
'three parts' => array( 'd.1.2', array_merge( $qualified, array( 'DOT_SYMBOL', 'IDENTIFIER' ) ) ),
455+
456+
// Elsewhere, ".N" is a number.
457+
'after a quoted identifier' => array( '`t`.1', array( 'BACK_TICK_QUOTED_ID', 'DECIMAL_NUMBER' ) ),
458+
'after whitespace' => array( 't .1', array( 'IDENTIFIER', 'DECIMAL_NUMBER' ) ),
459+
'after a separator dot' => array( 't..1', array( 'IDENTIFIER', 'DOT_SYMBOL', 'DECIMAL_NUMBER' ) ),
460+
'after a decimal' => array( '1.5.6', array( 'DECIMAL_NUMBER', 'DECIMAL_NUMBER' ) ),
461+
'after a float' => array( '1e5.1', array( 'FLOAT_NUMBER', 'DECIMAL_NUMBER' ) ),
462+
'after a hex number' => array( '0x1F.1', array( 'HEX_NUMBER', 'DECIMAL_NUMBER' ) ),
463+
'after a binary number' => array( '0b1.1', array( 'BIN_NUMBER', 'DECIMAL_NUMBER' ) ),
464+
'after "\N"' => array( '\N.1', array( 'NULL2_SYMBOL', 'DECIMAL_NUMBER' ) ),
465+
'after a version comment' => array( '/*!50000.5*/', array( 'DECIMAL_NUMBER' ) ),
466+
467+
// A user variable name includes the dot.
468+
'in a user variable' => array( '@a.1', array( 'AT_TEXT_SUFFIX' ) ),
469+
470+
// A keyword before a dot and a name is an identifier.
471+
'keyword before a name' => array( 'order.id', $qualified ),
472+
'keyword before digits' => array( 'select.1', $qualified ),
473+
'keyword before non-ASCII' => array( 'order.ñ', $qualified ),
474+
'keyword before "$"' => array( 'order.$x', $qualified ),
475+
'keyword in three parts' => array( 'order.t.id', array_merge( $qualified, array( 'DOT_SYMBOL', 'IDENTIFIER' ) ) ),
476+
477+
// A name after a separator dot is an identifier.
478+
'keyword after a dot' => array( '`t`.order', array( 'BACK_TICK_QUOTED_ID', 'DOT_SYMBOL', 'IDENTIFIER' ) ),
479+
'literal prefix after a dot' => array( "t.x'41'", array_merge( $qualified, array( 'SINGLE_QUOTED_TEXT' ) ) ),
480+
481+
// Otherwise, it stays a keyword or a charset.
482+
'keyword after a decimal' => array( '1.FROM', array( 'DECIMAL_NUMBER', 'FROM_SYMBOL' ) ),
483+
'keyword before a backtick' => array( 'order.`id`', array( 'ORDER_SYMBOL', 'DOT_SYMBOL', 'BACK_TICK_QUOTED_ID' ) ),
484+
'keyword before an asterisk' => array( 'order.*', array( 'ORDER_SYMBOL', 'DOT_SYMBOL', 'MULT_OPERATOR' ) ),
485+
'keyword before whitespace' => array( 'order .id', array( 'ORDER_SYMBOL', 'DOT_SYMBOL', 'IDENTIFIER' ) ),
486+
'system variable scope' => array( '@@session.sql_mode', array( 'AT_AT_SIGN_SYMBOL', 'SESSION_SYMBOL', 'DOT_SYMBOL', 'IDENTIFIER' ) ),
487+
'charset introducer' => array( '_utf8mb4.x', array( 'UNDERSCORE_CHARSET', 'DOT_SYMBOL', 'IDENTIFIER' ) ),
488+
);
489+
}
490+
425491
public function test_ignore_space_preserves_function_name_ranges(): void {
426492
// Without "(", COUNT is an identifier whose range excludes trailing whitespace.
427493
$sql = 'SELECT COUNT FROM t';

‎packages/mysql-on-sqlite/tests/mysql/WP_MySQL_Server_Suite_Parser_Tests.php‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ class WP_MySQL_Server_Suite_Parser_Tests extends TestCase {
1515
*/
1616
const KNOWN_FAILURES = array(
1717
'SELECT 1 /*!99999 /* */ */' => true,
18-
'select 1ea10.1a20,1e+ 1e+10 from 1ea10' => true,
1918
"聠聡聢聣聤聬聭聮聯聰聲聽隆垄拢陇楼卤潞禄录陆戮 聶職聳聴\n0聲5\n1聲5\n2聲5\n3聲5\n4\n\nSET NAMES gb18030" => true,
2019
"alter user mysqltest_7@ identified by 'systpass'" => true,
2120
"SELECT 'a%' LIKE 'a!%' ESCAPE '!', 'a%' LIKE 'a!' || '%' ESCAPE '!'" => true,

0 commit comments

Comments
 (0)