Skip to content

Commit dbcffbd

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 dbcffbd

9 files changed

Lines changed: 388 additions & 42 deletions

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

Lines changed: 99 additions & 19 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

@@ -2444,21 +2484,22 @@ private function read_next_token(): ?int {
24442484
// restricts the accepted identifier codepoints to U+0080-U+FFFF.
24452485
// `"'" !== $next_byte` defers x'..', n'..' and similar special
24462486
// literals to their dedicated branches below; only single quotes
2447-
// form those, regardless of SQL mode.
2487+
// form those, regardless of SQL mode. After a "." separator, the
2488+
// letter is a name instead ("x" in "t.x'41'").
24482489
if (
24492490
(
24502491
( $byte >= 'a' && $byte <= 'z' )
24512492
|| ( $byte >= 'A' && $byte <= 'Z' )
24522493
|| $byte > "\x7F"
24532494
)
2454-
&& "'" !== $next_byte
2495+
&& ( "'" !== $next_byte || self::STATE_IDENTIFIER_START === $state )
24552496
) {
24562497
$started_at = $this->bytes_already_read;
24572498
$type = $this->read_identifier();
24582499
if (
24592500
self::IDENTIFIER === $type
2460-
// When preceded by a dot, it is always an identifier.
2461-
&& ! ( $started_at > 0 && '.' === $this->sql[ $started_at - 1 ] )
2501+
// After a "." separator, it is always an identifier.
2502+
&& self::STATE_IDENTIFIER_START !== $state
24622503
) {
24632504
// Inline the keyword lookup on the hot identifier path: most
24642505
// identifiers are not keywords, so this avoids two method calls
@@ -2467,7 +2508,15 @@ private function read_next_token(): ?int {
24672508
substr( $this->sql, $started_at, $this->bytes_already_read - $started_at )
24682509
) ] ?? self::IDENTIFIER;
24692510
if ( self::IDENTIFIER !== $keyword ) {
2470-
$type = $this->resolve_keyword_type( $keyword );
2511+
// Before "." and a name, a keyword is an identifier ("order.id"),
2512+
// except for a system variable scope ("@@session.x"). The next
2513+
// state that read_identifier() has just set tells what follows.
2514+
if (
2515+
self::STATE_IDENTIFIER_SEPARATOR !== $this->next_state
2516+
|| self::STATE_IDENTIFIER_OR_KEYWORD === $state
2517+
) {
2518+
$type = $this->resolve_keyword_type( $keyword );
2519+
}
24712520
}
24722521
}
24732522
} elseif ( null !== $byte && isset( $single_byte_ops[ $byte ] ) ) {
@@ -2477,13 +2526,28 @@ private function read_next_token(): ?int {
24772526
} elseif ( "'" === $byte || '"' === $byte || '`' === $byte ) {
24782527
$type = $this->read_quoted_text();
24792528
} elseif ( null !== $byte && strspn( $byte, self::DIGIT_MASK ) > 0 ) {
2480-
$type = $this->read_number();
2529+
// After a "." separator, it is a qualified name part ("1" in "t.1").
2530+
if ( self::STATE_IDENTIFIER_START === $state ) {
2531+
$type = $this->read_identifier();
2532+
} else {
2533+
$type = $this->read_number();
2534+
}
24812535
} elseif ( '.' === $byte ) {
2482-
if ( null !== $next_byte && strspn( $next_byte, self::DIGIT_MASK ) > 0 ) {
2536+
if (
2537+
null !== $next_byte
2538+
&& strspn( $next_byte, self::DIGIT_MASK ) > 0
2539+
// Right after a name, it is a qualified name separator.
2540+
&& self::STATE_IDENTIFIER_SEPARATOR !== $state
2541+
) {
24832542
$type = $this->read_number();
24842543
} else {
24852544
$this->bytes_already_read += 1;
24862545
$type = self::DOT_SYMBOL;
2546+
2547+
// A name character right after it starts a qualified name part.
2548+
if ( null !== $next_byte && ( strspn( $next_byte, self::IDENTIFIER_MASK ) > 0 || $next_byte > "\x7F" ) ) {
2549+
$this->next_state = self::STATE_IDENTIFIER_START;
2550+
}
24872551
}
24882552
} elseif ( ':' === $byte ) {
24892553
$this->bytes_already_read += 1; // Consume the ':'.
@@ -2604,6 +2668,14 @@ private function read_next_token(): ?int {
26042668
if ( '@' === $next_byte ) {
26052669
$this->bytes_already_read += 1; // Consume the second '@'.
26062670
$type = self::AT_AT_SIGN_SYMBOL;
2671+
2672+
// The system variable name after it is read with keywords.
2673+
if (
2674+
strspn( $this->sql, self::IDENTIFIER_MASK, $this->bytes_already_read, 1 ) > 0
2675+
|| ( $this->sql[ $this->bytes_already_read ] ?? '' ) > "\x7F"
2676+
) {
2677+
$this->next_state = self::STATE_IDENTIFIER_OR_KEYWORD;
2678+
}
26072679
} else {
26082680
/**
26092681
* Check whether the '@' marks an unquoted user-defined variable:
@@ -2648,8 +2720,8 @@ private function read_next_token(): ?int {
26482720
$started_at = $this->bytes_already_read;
26492721
$type = $this->read_identifier();
26502722
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 ] ) {
2723+
// After a "." separator, it is always an identifier.
2724+
if ( self::STATE_IDENTIFIER_START === $state ) {
26532725
$type = self::IDENTIFIER;
26542726
} elseif ( '_' === $byte && isset( self::UNDERSCORE_CHARSETS[ strtolower( $this->get_current_token_bytes() ) ] ) ) {
26552727
$type = self::UNDERSCORE_CHARSET;
@@ -2673,13 +2745,13 @@ private function get_current_token_bytes(): string {
26732745
* Read an unquoted identifier.
26742746
*
26752747
* 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.
2748+
* It accepts digit-only sequences too; callers scan those as numbers, except
2749+
* for qualified name parts.
26792750
*
26802751
* Rules:
26812752
* 1. Allowed characters are ASCII a-z, A-Z, 0-9, _, $, and Unicode U+0080-U+FFFF.
26822753
* 2. Unquoted identifiers may begin with a digit but may not consist solely of digits.
2754+
* An exception is a part of a qualified name, such as "1" in "t.1".
26832755
*
26842756
* See:
26852757
* https://dev.mysql.com/doc/refman/8.4/en/identifiers.html
@@ -2738,17 +2810,25 @@ private function read_identifier(): ?int {
27382810
break;
27392811
}
27402812

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

2744-
return $this->bytes_already_read - $started_at > 0
2745-
? self::IDENTIFIER
2746-
: null; // Invalid input.
2817+
// When "." and a name character follow, the "." is a separator.
2818+
// "$byte_1" already holds the byte after the name.
2819+
if (
2820+
0x2E === $byte_1
2821+
&& (
2822+
strspn( $this->sql, self::IDENTIFIER_MASK, $this->bytes_already_read + 1, 1 ) > 0
2823+
|| ( $this->sql[ $this->bytes_already_read + 1 ] ?? '' ) > "\x7F"
2824+
)
2825+
) {
2826+
$this->next_state = self::STATE_IDENTIFIER_SEPARATOR;
2827+
}
2828+
return self::IDENTIFIER;
27472829
}
27482830

27492831
private function read_number(): ?int {
2750-
// @TODO: Support numeric-only identifier parts after "." (e.g., 1ea10.1).
2751-
27522832
$byte = $this->sql[ $this->bytes_already_read ] ?? null;
27532833
$next_byte = $this->sql[ $this->bytes_already_read + 1 ] ?? null;
27542834
$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)