diff --git a/packages/mysql-on-sqlite/src/mysql/class-wp-mysql-lexer.php b/packages/mysql-on-sqlite/src/mysql/class-wp-mysql-lexer.php index c99e2cefd..fa4bb7c7b 100644 --- a/packages/mysql-on-sqlite/src/mysql/class-wp-mysql-lexer.php +++ b/packages/mysql-on-sqlite/src/mysql/class-wp-mysql-lexer.php @@ -45,6 +45,7 @@ class WP_MySQL_Lexer { const WHITESPACE_MASK = " \t\n\r\f\v"; const DIGIT_MASK = '0123456789'; const HEX_DIGIT_MASK = '0123456789abcdefABCDEF'; + const IDENTIFIER_MASK = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$'; /** * Tokens from the MySQL Workbench "predefined.tokens" list. @@ -943,6 +944,32 @@ class WP_MySQL_Lexer { const WHITESPACE = 0; const EOF = -1; + /** + * Lexer states that a token sets for the next one, like MySQL's + * "next_state". They use MySQL's names from sql/sql_lex.cc, with the + * abbreviations written out: + * + * - STATE_START (MY_LEX_START): The default state. + * - STATE_IDENTIFIER_SEPARATOR (MY_LEX_IDENT_SEP): Set by a name before + * "." and a name character. The "." is then a separator, even before + * digits ("t.1"), and the name is an identifier, even if it's + * a keyword ("order.id"). + * - STATE_IDENTIFIER_START (MY_LEX_IDENT_START): Set by a "." before + * a name character. The name is then always an identifier + * ("t.order", "t.1", "t.x'41'"). + * - STATE_IDENTIFIER_OR_KEYWORD (MY_LEX_IDENT_OR_KEYWORD): Set by "@@" + * before a name character. The name is then an identifier or + * a keyword, even before "." ("@@session.x"), but never a number + * or a literal ("@@123"). + * + * A "." that ends a number sets no state, so "1.FROM" is a number and + * a keyword. + */ + private const STATE_START = -2; + private const STATE_IDENTIFIER_SEPARATOR = -3; + private const STATE_IDENTIFIER_START = -4; + private const STATE_IDENTIFIER_OR_KEYWORD = -5; + /** * A map of SQL keyword string values to their corresponding token types. * @@ -2175,6 +2202,13 @@ class WP_MySQL_Lexer { */ private $token_type; + /** + * The lexer state that the previous token set for the next one. + * + * @var int + */ + private $next_state = self::STATE_START; + /** * Whether the tokenizer is inside an active MySQL-specific comment. * @@ -2419,6 +2453,23 @@ public static function get_token_name( int $token_id ): ?string { } private function read_next_token(): ?int { + // Read and reset the state that the previous token set. + $state = $this->next_state; + $this->next_state = self::STATE_START; + + // After "." or "@@", read a name, never a number or a literal. + if ( self::STATE_START !== $state ) { + if ( self::STATE_IDENTIFIER_START === $state ) { + return $this->read_identifier(); + } + if ( self::STATE_IDENTIFIER_OR_KEYWORD === $state ) { + $type = $this->read_identifier(); + return self::IDENTIFIER === $type + ? $this->determine_identifier_or_keyword_type( $this->get_current_token_bytes() ) + : $type; + } + } + $byte = $this->sql[ $this->bytes_already_read ] ?? null; $next_byte = $this->sql[ $this->bytes_already_read + 1 ] ?? null; @@ -2454,18 +2505,19 @@ private function read_next_token(): ?int { ) { $started_at = $this->bytes_already_read; $type = $this->read_identifier(); - if ( - self::IDENTIFIER === $type - // When preceded by a dot, it is always an identifier. - && ! ( $started_at > 0 && '.' === $this->sql[ $started_at - 1 ] ) - ) { + if ( self::IDENTIFIER === $type ) { // Inline the keyword lookup on the hot identifier path: most // identifiers are not keywords, so this avoids two method calls // (token-bytes extraction + keyword determination) per token. $keyword = self::TOKENS[ strtoupper( substr( $this->sql, $started_at, $this->bytes_already_read - $started_at ) ) ] ?? self::IDENTIFIER; - if ( self::IDENTIFIER !== $keyword ) { + // Before "." and a name, a keyword is an identifier ("order.id"). + // read_identifier() sets STATE_IDENTIFIER_SEPARATOR in that case. + if ( + self::IDENTIFIER !== $keyword + && self::STATE_IDENTIFIER_SEPARATOR !== $this->next_state + ) { $type = $this->resolve_keyword_type( $keyword ); } } @@ -2478,11 +2530,21 @@ private function read_next_token(): ?int { } elseif ( null !== $byte && strspn( $byte, self::DIGIT_MASK ) > 0 ) { $type = $this->read_number(); } elseif ( '.' === $byte ) { - if ( null !== $next_byte && strspn( $next_byte, self::DIGIT_MASK ) > 0 ) { + if ( + null !== $next_byte + && strspn( $next_byte, self::DIGIT_MASK ) > 0 + // Right after a name, it is a qualified name separator. + && self::STATE_IDENTIFIER_SEPARATOR !== $state + ) { $type = $this->read_number(); } else { $this->bytes_already_read += 1; $type = self::DOT_SYMBOL; + + // A name character right after it starts a qualified name part. + if ( null !== $next_byte && ( strspn( $next_byte, self::IDENTIFIER_MASK ) > 0 || $next_byte > "\x7F" ) ) { + $this->next_state = self::STATE_IDENTIFIER_START; + } } } elseif ( ':' === $byte ) { $this->bytes_already_read += 1; // Consume the ':'. @@ -2603,6 +2665,17 @@ private function read_next_token(): ?int { if ( '@' === $next_byte ) { $this->bytes_already_read += 1; // Consume the second '@'. $type = self::AT_AT_SIGN_SYMBOL; + + // The name after it may be a keyword ("session" in "@@session.x"). + // As in MySQL, it can't be empty, and only backticks can quote it. + if ( + strspn( $this->sql, self::IDENTIFIER_MASK, $this->bytes_already_read, 1 ) > 0 + || ( $this->sql[ $this->bytes_already_read ] ?? '' ) > "\x7F" + ) { + $this->next_state = self::STATE_IDENTIFIER_OR_KEYWORD; + } elseif ( '`' !== ( $this->sql[ $this->bytes_already_read ] ?? '' ) ) { + return null; // Invalid input. + } } else { /** * Check whether the '@' marks an unquoted user-defined variable: @@ -2612,7 +2685,7 @@ private function read_next_token(): ?int { * 1. Starts with a '@'. * 2. Allowed following characters are ASCII a-z, A-Z, 0-9, _, ., $. */ - $length = strspn( $this->sql, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.$', $this->bytes_already_read ); + $length = strspn( $this->sql, self::IDENTIFIER_MASK . '.', $this->bytes_already_read ); if ( $length > 0 ) { $this->bytes_already_read += $length; $type = self::AT_TEXT_SUFFIX; @@ -2644,13 +2717,9 @@ private function read_next_token(): ?int { } elseif ( null === $byte ) { $type = self::EOF; } else { - $started_at = $this->bytes_already_read; - $type = $this->read_identifier(); + $type = $this->read_identifier(); if ( self::IDENTIFIER === $type ) { - // When preceded by a dot, it is always an identifier. - if ( $started_at > 0 && '.' === $this->sql[ $started_at - 1 ] ) { - $type = self::IDENTIFIER; - } elseif ( '_' === $byte && isset( self::UNDERSCORE_CHARSETS[ strtolower( $this->get_current_token_bytes() ) ] ) ) { + if ( '_' === $byte && isset( self::UNDERSCORE_CHARSETS[ strtolower( $this->get_current_token_bytes() ) ] ) ) { $type = self::UNDERSCORE_CHARSET; } else { $type = $this->determine_identifier_or_keyword_type( $this->get_current_token_bytes() ); @@ -2672,13 +2741,13 @@ private function get_current_token_bytes(): string { * Read an unquoted identifier. * * This function reads characters that are allowed in an unquoted identifier. - * An identifier cannot consist solely of digits, but this function doesn't - * ensure that explicitly, as numbers are processed before identifiers in - * the tokenization process, recognizing all digit-only sequences as numbers. + * It accepts digit-only sequences too; callers scan those as numbers, except + * after "." or "@@". * * Rules: * 1. Allowed characters are ASCII a-z, A-Z, 0-9, _, $, and Unicode U+0080-U+FFFF. * 2. Unquoted identifiers may begin with a digit but may not consist solely of digits. + * An exception is a part of a qualified name, such as "1" in "t.1". * * See: * https://dev.mysql.com/doc/refman/8.4/en/identifiers.html @@ -2689,7 +2758,7 @@ private function read_identifier(): ?int { // First, let's try to parse an ASCII sequence. $this->bytes_already_read += strspn( $this->sql, - 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$', + self::IDENTIFIER_MASK, $this->bytes_already_read ); @@ -2737,17 +2806,25 @@ private function read_identifier(): ?int { break; } - // An identifier cannot consist solely of digits, but we don't need to - // ensure that explicitly, as numbers are processed before identifiers. + if ( $this->bytes_already_read === $started_at ) { + return null; // Invalid input. + } - return $this->bytes_already_read - $started_at > 0 - ? self::IDENTIFIER - : null; // Invalid input. + // When "." and a name character follow, the "." is a separator. + // "$byte_1" already holds the byte after the name. + if ( + 0x2E === $byte_1 + && ( + strspn( $this->sql, self::IDENTIFIER_MASK, $this->bytes_already_read + 1, 1 ) > 0 + || ( $this->sql[ $this->bytes_already_read + 1 ] ?? '' ) > "\x7F" + ) + ) { + $this->next_state = self::STATE_IDENTIFIER_SEPARATOR; + } + return self::IDENTIFIER; } private function read_number(): ?int { - // @TODO: Support numeric-only identifier parts after "." (e.g., 1ea10.1). - $byte = $this->sql[ $this->bytes_already_read ] ?? null; $next_byte = $this->sql[ $this->bytes_already_read + 1 ] ?? null; $third_byte = $this->sql[ $this->bytes_already_read + 2 ] ?? null; diff --git a/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-builder.php b/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-builder.php index dc9c78aa7..fd89329e9 100644 --- a/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-builder.php +++ b/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-builder.php @@ -3324,8 +3324,9 @@ private function get_value( WP_Parser_Node $node ): string { * This is used for storing DEFAULT and CHECK expressions in the database. * * The current implementation is using a naive approach based on directly - * joining the original expression token bytes. This is safe, beacuase the - * original tokens must comprise a valid expression. While functionally + * joining the original expression token bytes. This is safe, because the + * original tokens must comprise a valid expression, and they are joined so + * that they are lexed the same way when parsed again. While functionally * equivalent, it is not strictly identical to what MySQL stores, because * MySQL normalizes and prints the expression in a specific format. * @@ -3347,23 +3348,22 @@ private function serialize_mysql_expression( WP_Parser_Node $node ): string { } $value = ''; - $last_token_id = null; - foreach ( $node->get_descendant_tokens() as $i => $token ) { - // Do not insert whitespace around parentheses. This is primarily to - // avoid inserting whitespace before '(', which may break function - // calls, depending on the value of the "IGNORE_SPACE" SQL mode. - if ( - 0 === $i - || WP_MySQL_Lexer::OPEN_PAR_SYMBOL === $token->id + $last_no_space = true; + foreach ( $node->get_descendant_tokens() as $token ) { + // Do not insert whitespace around parentheses and dots, and after "@@". + // Before '(', whitespace may break function calls, depending on the + // value of the "IGNORE_SPACE" SQL mode. Around '.', it changes how + // qualified names are lexed: "t . 1" has a number, and "order . id" + // has a keyword. After "@@", it leaves the variable name empty. + $no_space = WP_MySQL_Lexer::OPEN_PAR_SYMBOL === $token->id || WP_MySQL_Lexer::CLOSE_PAR_SYMBOL === $token->id - || WP_MySQL_Lexer::OPEN_PAR_SYMBOL === $last_token_id - || WP_MySQL_Lexer::CLOSE_PAR_SYMBOL === $last_token_id - ) { - $value .= $token->get_bytes(); - } else { - $value .= ' ' . $token->get_bytes(); + || WP_MySQL_Lexer::DOT_SYMBOL === $token->id; + + if ( ! $no_space && ! $last_no_space ) { + $value .= ' '; } - $last_token_id = $token->id; + $value .= $token->get_bytes(); + $last_no_space = $no_space || WP_MySQL_Lexer::AT_AT_SIGN_SYMBOL === $token->id; } return $value; } diff --git a/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php b/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php index fff5bc6b5..5ad027e16 100644 --- a/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php +++ b/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php @@ -14475,6 +14475,101 @@ public function testFullyQualifiedTableName(): void { $this->assertCount( 0, $result ); } + public function testQualifiedNamePartsStartingWithDigits(): void { + $this->assertQuery( 'CREATE TABLE 1t (`1` INT, `1st` INT, `1e5` INT)' ); + $this->assertQuery( 'INSERT INTO 1t VALUES (1, 2, 3), (4, 5, 6)' ); + + $result = $this->assertQuery( 'SELECT 1t.1, 1t.1st, 1t.1e5 FROM 1t WHERE 1t.1 = 4' ); + $this->assertEquals( + array( + (object) array( + '1' => '4', + '1st' => '5', + '1e5' => '6', + ), + ), + $result + ); + + $result = $this->assertQuery( 'SELECT wp.1t.1st FROM wp.1t ORDER BY wp.1t.1 DESC' ); + $this->assertEquals( + array( (object) array( '1st' => '5' ), (object) array( '1st' => '2' ) ), + $result + ); + } + + public function testReservedWordsAsQualifiers(): void { + $this->assertQuery( 'CREATE TABLE `order` (id INT, `1` INT)' ); + $this->assertQuery( 'INSERT INTO `order` VALUES (7, 8), (9, 10)' ); + + $result = $this->assertQuery( 'SELECT order.id, order.1 FROM `order` WHERE order.id = 7' ); + $this->assertEquals( + array( + (object) array( + 'id' => '7', + '1' => '8', + ), + ), + $result + ); + + $result = $this->assertQuery( 'SELECT wp.order.1 FROM wp.`order` ORDER BY order.id DESC' ); + $this->assertEquals( + array( (object) array( '1' => '10' ), (object) array( '1' => '8' ) ), + $result + ); + } + + public function testCheckConstraintsWithQualifiedNames(): void { + // The stored check clauses are parsed again to create the SQLite table. + $this->assertQuery( 'CREATE TABLE `order` (id INT, `1` INT, CHECK (order.id > 0), CHECK (wp.order.1 < 10))' ); + + $result = $this->assertQuery( 'SHOW CREATE TABLE `order`' ); + $this->assertEquals( + implode( + "\n", + array( + 'CREATE TABLE `order` (', + ' `id` int DEFAULT NULL,', + ' `1` int DEFAULT NULL,', + ' CONSTRAINT `order_chk_1` CHECK (order.id > 0),', + ' CONSTRAINT `order_chk_2` CHECK (wp.order.1 < 10)', + ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci', + ) + ), + $result[0]->{'Create Table'} + ); + + $this->assertQuery( 'INSERT INTO `order` VALUES (1, 9)' ); + + $this->expectException( WP_MySQL_On_SQLite_Exception::class ); + $this->expectExceptionMessage( 'SQLSTATE[23000]: Integrity constraint violation: 19 CHECK constraint failed: order_chk_2' ); + $this->assertQuery( 'INSERT INTO `order` VALUES (1, 10)' ); + } + + public function testCheckConstraintsAndDefaultsWithSystemVariables(): void { + // MySQL rejects variables in CHECK and DEFAULT expressions, but the driver + // accepts them. ALTER TABLE parses the stored expressions again. + $this->assertQuery( 'CREATE TABLE t (a INT DEFAULT (@@auto_increment_increment), b INT, CHECK (b < @@max_connections))' ); + $this->assertQuery( 'ALTER TABLE t ADD COLUMN c INT' ); + + $result = $this->assertQuery( 'SHOW CREATE TABLE t' ); + $this->assertEquals( + implode( + "\n", + array( + 'CREATE TABLE `t` (', + ' `a` int DEFAULT (@@auto_increment_increment),', + ' `b` int DEFAULT NULL,', + ' `c` int DEFAULT NULL,', + ' CONSTRAINT `t_chk_1` CHECK (b < @@max_connections)', + ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci', + ) + ), + $result[0]->{'Create Table'} + ); + } + public function testWriteWithUsageOfInformationSchemaTables(): void { // Ensure "information_schema.tables" is empty. $this->assertQuery( 'DROP TABLE _options, _dates' ); diff --git a/packages/mysql-on-sqlite/tests/mysql/WP_MySQL_Lexer_Tests.php b/packages/mysql-on-sqlite/tests/mysql/WP_MySQL_Lexer_Tests.php index 0a736cc8d..817ac2d02 100644 --- a/packages/mysql-on-sqlite/tests/mysql/WP_MySQL_Lexer_Tests.php +++ b/packages/mysql-on-sqlite/tests/mysql/WP_MySQL_Lexer_Tests.php @@ -55,6 +55,29 @@ public function test_tokenize_invalid_input(): void { $this->assertNull( $lexer->get_token() ); } + public function test_system_variable_name_must_not_be_empty(): void { + // As in MySQL, the name after "@@" can't be empty, and only backticks + // can quote it. Otherwise, the tokens end before the "@@", with no EOF. + $invalid = array( + array( 'SELECT @@', array() ), + array( 'SELECT @@ version', array() ), + array( "SELECT @@'version'", array() ), + array( 'SELECT @@"version"', array() ), + array( 'SELECT @@"version"', array( 'ANSI_QUOTES' ) ), + ); + foreach ( $invalid as list( $sql, $sql_modes ) ) { + $tokens = ( new WP_MySQL_Lexer( $sql, 80038, $sql_modes ) )->remaining_tokens(); + $this->assertCount( 1, $tokens, $sql ); + $this->assertSame( WP_MySQL_Lexer::SELECT_SYMBOL, $tokens[0]->id, $sql ); + } + + $names = array(); + foreach ( ( new WP_MySQL_Lexer( 'SELECT @@`version`' ) )->remaining_tokens() as $token ) { + $names[] = $token->get_name(); + } + $this->assertSame( array( 'SELECT_SYMBOL', 'AT_AT_SIGN_SYMBOL', 'BACK_TICK_QUOTED_ID', 'EOF' ), $names ); + } + /** * Test that the whole U+0080 to U+FFFF UTF-8 range is valid in an identifier. * The validity is checked against PCRE with the "u" (PCRE_UTF8) modifier set. @@ -422,6 +445,75 @@ public function data_underscore_charset_after_dot(): array { ); } + /** + * Qualified names and system variable names are lexed as in MySQL. + * All cases are verified against MySQL 8.4. + * + * @dataProvider data_qualified_name_tokens + */ + public function test_qualified_name_tokens( string $sql, array $expected ): void { + $names = array(); + foreach ( ( new WP_MySQL_Lexer( $sql ) )->remaining_tokens() as $token ) { + $names[] = $token->get_name(); + } + $this->assertSame( array_merge( $expected, array( 'EOF' ) ), $names ); + } + + /** + * @return array + */ + public function data_qualified_name_tokens(): array { + $qualified = array( 'IDENTIFIER', 'DOT_SYMBOL', 'IDENTIFIER' ); + return array( + // A qualified name part can start with digits. + 'digits only' => array( 't.1', $qualified ), + 'digit-led identifier' => array( 't.1st', $qualified ), + 'float-like identifier' => array( 't.1e5', $qualified ), + 'part ends before a sign' => array( 't.1e+5', array_merge( $qualified, array( 'PLUS_OPERATOR', 'INT_NUMBER' ) ) ), + 'after a digit-led qualifier' => array( '1ea10.1', $qualified ), + 'three parts' => array( 'd.1.2', array_merge( $qualified, array( 'DOT_SYMBOL', 'IDENTIFIER' ) ) ), + + // Elsewhere, ".N" is a number. + 'after a quoted identifier' => array( '`t`.1', array( 'BACK_TICK_QUOTED_ID', 'DECIMAL_NUMBER' ) ), + 'after whitespace' => array( 't .1', array( 'IDENTIFIER', 'DECIMAL_NUMBER' ) ), + 'after a separator dot' => array( 't..1', array( 'IDENTIFIER', 'DOT_SYMBOL', 'DECIMAL_NUMBER' ) ), + 'after a decimal' => array( '1.5.6', array( 'DECIMAL_NUMBER', 'DECIMAL_NUMBER' ) ), + 'after a float' => array( '1e5.1', array( 'FLOAT_NUMBER', 'DECIMAL_NUMBER' ) ), + 'after a hex number' => array( '0x1F.1', array( 'HEX_NUMBER', 'DECIMAL_NUMBER' ) ), + 'after a binary number' => array( '0b1.1', array( 'BIN_NUMBER', 'DECIMAL_NUMBER' ) ), + 'after "\N"' => array( '\N.1', array( 'NULL2_SYMBOL', 'DECIMAL_NUMBER' ) ), + 'after a version comment' => array( '/*!50000.5*/', array( 'DECIMAL_NUMBER' ) ), + + // A user variable name includes the dot. + 'in a user variable' => array( '@a.1', array( 'AT_TEXT_SUFFIX' ) ), + + // A keyword before a dot and a name is an identifier. + 'keyword before a name' => array( 'order.id', $qualified ), + 'keyword before digits' => array( 'select.1', $qualified ), + 'keyword before non-ASCII' => array( 'order.ñ', $qualified ), + 'keyword before "$"' => array( 'order.$x', $qualified ), + 'keyword in three parts' => array( 'order.t.id', array_merge( $qualified, array( 'DOT_SYMBOL', 'IDENTIFIER' ) ) ), + + // A name right after a "." token is always an identifier. + 'keyword after a dot' => array( '`t`.order', array( 'BACK_TICK_QUOTED_ID', 'DOT_SYMBOL', 'IDENTIFIER' ) ), + 'literal prefix after a dot' => array( "t.x'41'", array_merge( $qualified, array( 'SINGLE_QUOTED_TEXT' ) ) ), + + // Otherwise, it stays a keyword or a charset. + 'keyword after a decimal' => array( '1.FROM', array( 'DECIMAL_NUMBER', 'FROM_SYMBOL' ) ), + 'keyword before a backtick' => array( 'order.`id`', array( 'ORDER_SYMBOL', 'DOT_SYMBOL', 'BACK_TICK_QUOTED_ID' ) ), + 'keyword before an asterisk' => array( 'order.*', array( 'ORDER_SYMBOL', 'DOT_SYMBOL', 'MULT_OPERATOR' ) ), + 'keyword before whitespace' => array( 'order .id', array( 'ORDER_SYMBOL', 'DOT_SYMBOL', 'IDENTIFIER' ) ), + 'system variable scope' => array( '@@session.sql_mode', array( 'AT_AT_SIGN_SYMBOL', 'SESSION_SYMBOL', 'DOT_SYMBOL', 'IDENTIFIER' ) ), + 'charset introducer' => array( '_utf8mb4.x', array( 'UNDERSCORE_CHARSET', 'DOT_SYMBOL', 'IDENTIFIER' ) ), + + // After "@@", the name is never a number, a literal, or a charset. + 'system variable digits' => array( '@@123', array( 'AT_AT_SIGN_SYMBOL', 'IDENTIFIER' ) ), + 'system variable float-like' => array( '@@1e5', array( 'AT_AT_SIGN_SYMBOL', 'IDENTIFIER' ) ), + 'system variable before text' => array( "@@b'01'", array( 'AT_AT_SIGN_SYMBOL', 'IDENTIFIER', 'SINGLE_QUOTED_TEXT' ) ), + 'system variable charset' => array( '@@_utf8mb4', array( 'AT_AT_SIGN_SYMBOL', 'IDENTIFIER' ) ), + ); + } + public function test_ignore_space_preserves_function_name_ranges(): void { // Without "(", COUNT is an identifier whose range excludes trailing whitespace. $sql = 'SELECT COUNT FROM t'; diff --git a/packages/mysql-on-sqlite/tests/mysql/WP_MySQL_Server_Suite_Parser_Tests.php b/packages/mysql-on-sqlite/tests/mysql/WP_MySQL_Server_Suite_Parser_Tests.php index 027698849..b20b51f27 100644 --- a/packages/mysql-on-sqlite/tests/mysql/WP_MySQL_Server_Suite_Parser_Tests.php +++ b/packages/mysql-on-sqlite/tests/mysql/WP_MySQL_Server_Suite_Parser_Tests.php @@ -15,7 +15,6 @@ class WP_MySQL_Server_Suite_Parser_Tests extends TestCase { */ const KNOWN_FAILURES = array( 'SELECT 1 /*!99999 /* */ */' => true, - 'select 1ea10.1a20,1e+ 1e+10 from 1ea10' => true, "聠聡聢聣聤聬聭聮聯聰聲聽隆垄拢陇楼卤潞禄录陆戮 聶職聳聴\n0聲5\n1聲5\n2聲5\n3聲5\n4\n\nSET NAMES gb18030" => true, "alter user mysqltest_7@ identified by 'systpass'" => true, "SELECT 'a%' LIKE 'a!%' ESCAPE '!', 'a%' LIKE 'a!' || '%' ESCAPE '!'" => true, diff --git a/packages/mysql-parser/src/class-wp-mysql-lexer.php b/packages/mysql-parser/src/class-wp-mysql-lexer.php index 87bc44d9c..cb13dcddc 100644 --- a/packages/mysql-parser/src/class-wp-mysql-lexer.php +++ b/packages/mysql-parser/src/class-wp-mysql-lexer.php @@ -125,6 +125,7 @@ class WP_MySQL_Lexer { private const WHITESPACE_MASK = " \t\n\r\f\v"; private const DIGIT_MASK = '0123456789'; private const HEX_DIGIT_MASK = '0123456789abcdefABCDEF'; + private const IDENTIFIER_MASK = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$'; /** * Internal scanner sentinels. @@ -142,6 +143,33 @@ class WP_MySQL_Lexer { private const MYSQL_COMMENT_START = -4; private const MYSQL_COMMENT_END = -5; + /** + * Lexer states that a token sets for the next one, like MySQL's + * "next_state". They use MySQL's names from sql/sql_lex.cc, with the + * abbreviations written out: + * + * - STATE_START (MY_LEX_START): The default state. + * - STATE_IDENTIFIER_SEPARATOR (MY_LEX_IDENT_SEP): Set by a name before + * "." and a name character. The "." is then a separator, even before + * digits ("t.1"), and the name is an identifier, even if it's + * a keyword ("order.id"). + * - STATE_IDENTIFIER_START (MY_LEX_IDENT_START): Set by a "." before + * a name character. The name is then always an identifier + * ("t.order", "t.1", "t.x'41'"). + * - STATE_IDENTIFIER_OR_KEYWORD (MY_LEX_IDENT_OR_KEYWORD): Set by "@@" + * before a name character. The name is then an identifier or + * a keyword, even before "." ("@@session.x"), but never a number + * or a literal ("@@123"). + * + * A "." that ends a number sets no state, so "1.FROM" is a number and + * a keyword. Like the scanner sentinels, the states are negative, so + * they never collide with a grammar token number. + */ + private const STATE_START = -6; + private const STATE_IDENTIFIER_SEPARATOR = -7; + private const STATE_IDENTIFIER_START = -8; + private const STATE_IDENTIFIER_OR_KEYWORD = -9; + /** * Identifier-like strings that may represent underscore-prefixed charset names. * @@ -266,6 +294,13 @@ class WP_MySQL_Lexer { */ private $token_type; + /** + * The lexer state that the previous token set for the next one. + * + * @var int + */ + private $next_state = self::STATE_START; + /** * Whether the tokenizer is inside an active MySQL-specific comment. * @@ -444,7 +479,7 @@ public function remaining_tokens(): array { list( $type, $start, $length ) = $this->lookahead; $this->lookahead = null; } else { - // Inlined scan_lexeme(): skip whitespace and comments, then scan. + // Inline scan_lexeme() for performance. $this->bytes_already_read += strspn( $sql, self::WHITESPACE_MASK, $this->bytes_already_read ); do { $this->token_starts_at = $this->bytes_already_read; @@ -653,8 +688,9 @@ private function produce_with_or_rollup( array &$out, int $with_start, int $with * unquoted user-variable name (always an identifier, never a keyword; it may * contain "." and "$"), by an empty name (MySQL's empty LEX_HOSTNAME, which * makes "SELECT @" and "user1@" valid), or by a quoted name supplied by the - * following token. A "@@" prefix is two "@" terminals, with the system - * variable name scanned normally afterwards. + * following token. A "@@" prefix is two "@" terminals, followed by the system + * variable name. As in MySQL, that name can't be empty, and only backticks + * can quote it. * * @param int $at_start Byte offset of the "@" token. */ @@ -667,12 +703,22 @@ private function produce_at_variable( array &$out, int $at_start ): void { if ( '@' === $next ) { $out[] = $this->make_token( self::AT_SIGN_SYMBOL, $position, 1 ); $this->bytes_already_read = $position + 1; + + // The name after it may be a keyword ("session" in "@@session.x"). + if ( + strspn( $this->sql, self::IDENTIFIER_MASK, $this->bytes_already_read, 1 ) > 0 + || ( $this->sql[ $this->bytes_already_read ] ?? '' ) > "\x7F" + ) { + $this->next_state = self::STATE_IDENTIFIER_OR_KEYWORD; + } elseif ( '`' !== ( $this->sql[ $this->bytes_already_read ] ?? '' ) ) { + $this->stream_ended = true; // Invalid input. + } return; } $name_length = strspn( $this->sql, - 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.$', + self::IDENTIFIER_MASK . '.', $position ); if ( $name_length > 0 ) { @@ -738,6 +784,23 @@ private function make_token( int $type, int $start, int $length ): WP_MySQL_Toke } private function read_next_token(): ?int { + // Read and reset the state that the previous token set. + $state = $this->next_state; + $this->next_state = self::STATE_START; + + // After "." or "@@", read a name, never a number or a literal. + if ( self::STATE_START !== $state ) { + if ( self::STATE_IDENTIFIER_START === $state ) { + return $this->read_identifier(); + } + if ( self::STATE_IDENTIFIER_OR_KEYWORD === $state ) { + $type = $this->read_identifier(); + return self::IDENTIFIER === $type + ? $this->determine_identifier_or_keyword_type( $this->get_current_token_bytes() ) + : $type; + } + } + $byte = $this->sql[ $this->bytes_already_read ] ?? null; $next_byte = $this->sql[ $this->bytes_already_read + 1 ] ?? null; @@ -773,11 +836,7 @@ private function read_next_token(): ?int { ) { $started_at = $this->bytes_already_read; $type = $this->read_identifier(); - if ( - self::IDENTIFIER === $type - // When preceded by a dot, it is always an identifier. - && ! ( $started_at > 0 && '.' === $this->sql[ $started_at - 1 ] ) - ) { + if ( self::IDENTIFIER === $type ) { // Inline the keyword lookup on the hot identifier path: most // identifiers are not keywords, so this avoids two method calls // (token-bytes extraction + keyword determination) per token. @@ -785,7 +844,12 @@ private function read_next_token(): ?int { substr( $this->sql, $started_at, $this->bytes_already_read - $started_at ) ); $keyword = self::KEYWORDS[ $word ] ?? self::IDENTIFIER; - if ( self::IDENTIFIER !== $keyword ) { + // Before "." and a name, a keyword is an identifier ("order.id"). + // read_identifier() sets STATE_IDENTIFIER_SEPARATOR in that case. + if ( + self::IDENTIFIER !== $keyword + && self::STATE_IDENTIFIER_SEPARATOR !== $this->next_state + ) { $type = $this->resolve_keyword_type( $keyword, $word ); } } @@ -798,54 +862,64 @@ private function read_next_token(): ?int { } elseif ( null !== $byte && strspn( $byte, self::DIGIT_MASK ) > 0 ) { $type = $this->read_number(); } elseif ( '.' === $byte ) { - if ( null !== $next_byte && strspn( $next_byte, self::DIGIT_MASK ) > 0 ) { + if ( + null !== $next_byte + && strspn( $next_byte, self::DIGIT_MASK ) > 0 + // Right after a name, it is a qualified name separator. + && self::STATE_IDENTIFIER_SEPARATOR !== $state + ) { $type = $this->read_number(); } else { $this->bytes_already_read += 1; $type = self::DOT_SYMBOL; + + // A name character right after it starts a qualified name part. + if ( null !== $next_byte && ( strspn( $next_byte, self::IDENTIFIER_MASK ) > 0 || $next_byte > "\x7F" ) ) { + $this->next_state = self::STATE_IDENTIFIER_START; + } } } elseif ( ':' === $byte ) { - $this->bytes_already_read += 1; // Consume the ':'. + $this->bytes_already_read += 1; if ( '=' === $next_byte ) { - $this->bytes_already_read += 1; // Consume the '='. + $this->bytes_already_read += 1; $type = self::ASSIGN_OPERATOR; } else { $type = self::COLON_SYMBOL; } } elseif ( '<' === $byte ) { - $this->bytes_already_read += 1; // Consume the '<'. + $this->bytes_already_read += 1; if ( '=' === $next_byte ) { - $this->bytes_already_read += 1; // Consume the '='. + $this->bytes_already_read += 1; if ( '>' === ( $this->sql[ $this->bytes_already_read ] ?? null ) ) { - $this->bytes_already_read += 1; // Consume the '>'. + $this->bytes_already_read += 1; $type = self::NULL_SAFE_EQUAL_OPERATOR; } else { $type = self::LESS_OR_EQUAL_OPERATOR; } } elseif ( '>' === $next_byte ) { - $this->bytes_already_read += 1; // Consume the '>'. + $this->bytes_already_read += 1; $type = self::NOT_EQUAL_OPERATOR; } elseif ( '<' === $next_byte ) { - $this->bytes_already_read += 1; // Consume the '<'. + $this->bytes_already_read += 1; $type = self::SHIFT_LEFT_OPERATOR; } else { $type = self::LESS_THAN_OPERATOR; } } elseif ( '>' === $byte ) { - $this->bytes_already_read += 1; // Consume the '>'. + $this->bytes_already_read += 1; if ( '=' === $next_byte ) { - $this->bytes_already_read += 1; // Consume the '='. + $this->bytes_already_read += 1; $type = self::GREATER_OR_EQUAL_OPERATOR; } elseif ( '>' === $next_byte ) { - $this->bytes_already_read += 1; // Consume the '>'. + $this->bytes_already_read += 1; $type = self::SHIFT_RIGHT_OPERATOR; } else { $type = self::GREATER_THAN_OPERATOR; } } elseif ( '!' === $byte ) { - $this->bytes_already_read += 1; // Consume the '!'. + $this->bytes_already_read += 1; if ( '=' === $next_byte ) { - $this->bytes_already_read += 1; // Consume the '='. + $this->bytes_already_read += 1; $type = self::NOT_EQUAL_OPERATOR; } else { $type = self::LOGICAL_NOT_OPERATOR; @@ -858,9 +932,9 @@ private function read_next_token(): ?int { ) { $type = $this->read_line_comment(); } elseif ( '>' === $next_byte ) { - $this->bytes_already_read += 2; // Consume the '->'. + $this->bytes_already_read += 2; if ( '>' === ( $this->sql[ $this->bytes_already_read ] ?? null ) ) { - $this->bytes_already_read += 1; // Consume the '>'. + $this->bytes_already_read += 1; if ( $this->mysql_version >= 50713 ) { $type = self::JSON_UNQUOTED_SEPARATOR_SYMBOL; } else { @@ -874,13 +948,13 @@ private function read_next_token(): ?int { } } } else { - $this->bytes_already_read += 1; // Consume the '-'. + $this->bytes_already_read += 1; $type = self::MINUS_OPERATOR; } } elseif ( '*' === $byte ) { $this->bytes_already_read += 1; if ( '/' === $next_byte && $this->in_mysql_comment ) { - $this->bytes_already_read += 1; // Consume the '/'. + $this->bytes_already_read += 1; $type = self::MYSQL_COMMENT_END; $this->in_mysql_comment = false; } else { @@ -891,7 +965,7 @@ private function read_next_token(): ?int { if ( '!' === ( $this->sql[ $this->bytes_already_read + 2 ] ?? null ) ) { $type = $this->read_mysql_comment(); } else { - $this->bytes_already_read += 2; // Consume the '/*'. + $this->bytes_already_read += 2; $this->read_comment_content(); $type = self::COMMENT; } @@ -900,17 +974,17 @@ private function read_next_token(): ?int { $type = self::DIV_OPERATOR; } } elseif ( '&' === $byte ) { - $this->bytes_already_read += 1; // Consume the '&'. + $this->bytes_already_read += 1; if ( '&' === $next_byte ) { - $this->bytes_already_read += 1; // Consume the '&'. + $this->bytes_already_read += 1; $type = self::LOGICAL_AND_OPERATOR; } else { $type = self::BITWISE_AND_OPERATOR; } } elseif ( '|' === $byte ) { - $this->bytes_already_read += 1; // Consume the '|'. + $this->bytes_already_read += 1; if ( '|' === $next_byte ) { - $this->bytes_already_read += 1; // Consume the '|'. + $this->bytes_already_read += 1; $type = $this->is_sql_mode_active( self::SQL_MODE_PIPES_AS_CONCAT ) ? self::CONCAT_PIPES_SYMBOL : self::LOGICAL_OR_OPERATOR; @@ -920,12 +994,12 @@ private function read_next_token(): ?int { } elseif ( '@' === $byte ) { // MySQL treats "@" as a standalone terminal; the variable name that // follows is emitted as its own token (see produce_at_variable()). - $this->bytes_already_read += 1; // Consume the '@'. + $this->bytes_already_read += 1; $type = self::AT_SIGN_SYMBOL; } elseif ( '\\' === $byte ) { - $this->bytes_already_read += 1; // Consume the '\'. + $this->bytes_already_read += 1; if ( 'N' === $next_byte ) { - $this->bytes_already_read += 1; // Consume the 'N'. + $this->bytes_already_read += 1; $type = self::NULL2_SYMBOL; } else { return null; // Invalid input. @@ -938,7 +1012,7 @@ private function read_next_token(): ?int { } elseif ( ( 'x' === $byte || 'X' === $byte || 'b' === $byte || 'B' === $byte ) && "'" === $next_byte ) { $type = $this->read_number(); } elseif ( ( 'n' === $byte || 'N' === $byte ) && "'" === $next_byte ) { - $this->bytes_already_read += 1; // n/N + $this->bytes_already_read += 1; $type = $this->read_quoted_text( "'" ); if ( self::SINGLE_QUOTED_TEXT === $type ) { $type = self::NCHAR_TEXT; @@ -946,13 +1020,9 @@ private function read_next_token(): ?int { } elseif ( null === $byte ) { $type = self::EOF; } else { - $started_at = $this->bytes_already_read; - $type = $this->read_identifier(); + $type = $this->read_identifier(); if ( self::IDENTIFIER === $type ) { - // When preceded by a dot, it is always an identifier. - if ( $started_at > 0 && '.' === $this->sql[ $started_at - 1 ] ) { - $type = self::IDENTIFIER; - } elseif ( '_' === $byte && isset( self::UNDERSCORE_CHARSETS[ strtolower( $this->get_current_token_bytes() ) ] ) ) { + if ( '_' === $byte && isset( self::UNDERSCORE_CHARSETS[ strtolower( $this->get_current_token_bytes() ) ] ) ) { $type = self::UNDERSCORE_CHARSET; } else { $type = $this->determine_identifier_or_keyword_type( $this->get_current_token_bytes() ); @@ -974,13 +1044,13 @@ private function get_current_token_bytes(): string { * Read an unquoted identifier. * * This function reads characters that are allowed in an unquoted identifier. - * An identifier cannot consist solely of digits, but this function doesn't - * ensure that explicitly, as numbers are processed before identifiers in - * the tokenization process, recognizing all digit-only sequences as numbers. + * It accepts digit-only sequences too; callers scan those as numbers, except + * after "." or "@@". * * Rules: * 1. Allowed characters are ASCII a-z, A-Z, 0-9, _, $, and Unicode U+0080-U+FFFF. * 2. Unquoted identifiers may begin with a digit but may not consist solely of digits. + * An exception is a part of a qualified name, such as "1" in "t.1". * * See: * https://dev.mysql.com/doc/refman/8.4/en/identifiers.html @@ -991,7 +1061,7 @@ private function read_identifier(): ?int { // First, let's try to parse an ASCII sequence. $this->bytes_already_read += strspn( $this->sql, - 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$', + self::IDENTIFIER_MASK, $this->bytes_already_read ); @@ -1039,17 +1109,25 @@ private function read_identifier(): ?int { break; } - // An identifier cannot consist solely of digits, but we don't need to - // ensure that explicitly, as numbers are processed before identifiers. + if ( $this->bytes_already_read === $started_at ) { + return null; // Invalid input. + } - return $this->bytes_already_read - $started_at > 0 - ? self::IDENTIFIER - : null; // Invalid input. + // When "." and a name character follow, the "." is a separator. + // "$byte_1" already holds the byte after the name. + if ( + 0x2E === $byte_1 + && ( + strspn( $this->sql, self::IDENTIFIER_MASK, $this->bytes_already_read + 1, 1 ) > 0 + || ( $this->sql[ $this->bytes_already_read + 1 ] ?? '' ) > "\x7F" + ) + ) { + $this->next_state = self::STATE_IDENTIFIER_SEPARATOR; + } + return self::IDENTIFIER; } private function read_number(): ?int { - // @TODO: Support numeric-only identifier parts after "." (e.g., 1ea10.1). - $byte = $this->sql[ $this->bytes_already_read ] ?? null; $next_byte = $this->sql[ $this->bytes_already_read + 1 ] ?? null; $third_byte = $this->sql[ $this->bytes_already_read + 2 ] ?? null; diff --git a/packages/mysql-parser/src/class-wp-mysql-token.php b/packages/mysql-parser/src/class-wp-mysql-token.php index bca56c9c8..123e74213 100644 --- a/packages/mysql-parser/src/class-wp-mysql-token.php +++ b/packages/mysql-parser/src/class-wp-mysql-token.php @@ -176,8 +176,7 @@ public function get_value(): string { * Legacy multi-byte charsets like big5 or gbk, where a trail byte can be * a backslash, are not supported. */ - $preg_quoted_backslash = preg_quote( $backslash ); - $value = preg_replace( "/$preg_quoted_backslash(.)/s", '$1', $value ); + $value = preg_replace( '/\\\\(.)/s', '$1', $value ); } return $value; } diff --git a/packages/mysql-parser/tests/WP_MySQL_Lexer_Tests.php b/packages/mysql-parser/tests/WP_MySQL_Lexer_Tests.php index 0738762a3..47589b72f 100644 --- a/packages/mysql-parser/tests/WP_MySQL_Lexer_Tests.php +++ b/packages/mysql-parser/tests/WP_MySQL_Lexer_Tests.php @@ -267,6 +267,21 @@ public function test_invalid_input_returns_partial_stream_without_end_markers(): $this->assertSame( array( 'SELECT', 'INT_NUMBER', 'WITH' ), $names ); } + public function test_system_variable_name_must_not_be_empty(): void { + // As in MySQL, the name after "@@" can't be empty, and only backticks + // can quote it. Otherwise, the stream ends after the "@@". + $at_at = array( 'AT_SIGN_SYMBOL', 'AT_SIGN_SYMBOL' ); + $this->assertSame( $at_at, self::token_names( '@@' ) ); + $this->assertSame( $at_at, self::token_names( '@@ version' ) ); + $this->assertSame( $at_at, self::token_names( "@@'version'" ) ); + $this->assertSame( $at_at, self::token_names( '@@"version"' ) ); + $this->assertSame( $at_at, self::token_names( '@@"version"', array( 'ANSI_QUOTES' ) ) ); + $this->assertSame( + array_merge( $at_at, array( 'BACK_TICK_QUOTED_ID', 'END_OF_INPUT', 'END_MARKER' ) ), + self::token_names( '@@`version`' ) + ); + } + public function test_high_not_precedence_emits_not2(): void { $names = self::token_names( 'SELECT NOT 1', array( 'HIGH_NOT_PRECEDENCE' ) ); $this->assertContains( 'NOT2_SYMBOL', $names ); @@ -425,6 +440,74 @@ public function data_underscore_charset_after_dot(): array { ); } + /** + * Qualified names and system variable names are lexed as in MySQL. + * All cases are verified against MySQL 8.4. + * + * @dataProvider data_qualified_name_tokens + */ + public function test_qualified_name_tokens( string $sql, array $expected ): void { + $this->assertSame( + array_merge( $expected, array( 'END_OF_INPUT', 'END_MARKER' ) ), + self::token_names( $sql ) + ); + } + + /** + * @return array + */ + public function data_qualified_name_tokens(): array { + $qualified = array( 'IDENTIFIER', 'DOT_SYMBOL', 'IDENTIFIER' ); + return array( + // A qualified name part can start with digits. + 'digits only' => array( 't.1', $qualified ), + 'digit-led identifier' => array( 't.1st', $qualified ), + 'float-like identifier' => array( 't.1e5', $qualified ), + 'part ends before a sign' => array( 't.1e+5', array_merge( $qualified, array( 'PLUS_OPERATOR', 'INT_NUMBER' ) ) ), + 'after a digit-led qualifier' => array( '1ea10.1', $qualified ), + 'three parts' => array( 'd.1.2', array_merge( $qualified, array( 'DOT_SYMBOL', 'IDENTIFIER' ) ) ), + + // Elsewhere, ".N" is a number. + 'after a quoted identifier' => array( '`t`.1', array( 'BACK_TICK_QUOTED_ID', 'DECIMAL_NUMBER' ) ), + 'after whitespace' => array( 't .1', array( 'IDENTIFIER', 'DECIMAL_NUMBER' ) ), + 'after a separator dot' => array( 't..1', array( 'IDENTIFIER', 'DOT_SYMBOL', 'DECIMAL_NUMBER' ) ), + 'after a decimal' => array( '1.5.6', array( 'DECIMAL_NUMBER', 'DECIMAL_NUMBER' ) ), + 'after a float' => array( '1e5.1', array( 'FLOAT_NUMBER', 'DECIMAL_NUMBER' ) ), + 'after a hex number' => array( '0x1F.1', array( 'HEX_NUMBER', 'DECIMAL_NUMBER' ) ), + 'after a binary number' => array( '0b1.1', array( 'BIN_NUMBER', 'DECIMAL_NUMBER' ) ), + 'after "\N"' => array( '\N.1', array( 'NULL', 'DECIMAL_NUMBER' ) ), + 'after a version comment' => array( '/*!50000.5*/', array( 'DECIMAL_NUMBER' ) ), + + // A user variable name includes the dot. + 'in a user variable' => array( '@a.1', array( 'AT_SIGN_SYMBOL', 'IDENTIFIER' ) ), + + // A keyword before a dot and a name is an identifier. + 'keyword before a name' => array( 'order.id', $qualified ), + 'keyword before digits' => array( 'select.1', $qualified ), + 'keyword before non-ASCII' => array( 'order.ñ', $qualified ), + 'keyword before "$"' => array( 'order.$x', $qualified ), + 'keyword in three parts' => array( 'order.t.id', array_merge( $qualified, array( 'DOT_SYMBOL', 'IDENTIFIER' ) ) ), + + // A name right after a "." token is always an identifier. + 'keyword after a dot' => array( '`t`.order', array( 'BACK_TICK_QUOTED_ID', 'DOT_SYMBOL', 'IDENTIFIER' ) ), + 'literal prefix after a dot' => array( "t.x'41'", array_merge( $qualified, array( 'SINGLE_QUOTED_TEXT' ) ) ), + + // Otherwise, it stays a keyword or a charset. + 'keyword after a decimal' => array( '1.FROM', array( 'DECIMAL_NUMBER', 'FROM' ) ), + 'keyword before a backtick' => array( 'order.`id`', array( 'ORDER', 'DOT_SYMBOL', 'BACK_TICK_QUOTED_ID' ) ), + 'keyword before an asterisk' => array( 'order.*', array( 'ORDER', 'DOT_SYMBOL', 'MULT_OPERATOR' ) ), + 'keyword before whitespace' => array( 'order .id', array( 'ORDER', 'DOT_SYMBOL', 'IDENTIFIER' ) ), + 'system variable scope' => array( '@@session.sql_mode', array( 'AT_SIGN_SYMBOL', 'AT_SIGN_SYMBOL', 'SESSION', 'DOT_SYMBOL', 'IDENTIFIER' ) ), + 'charset introducer' => array( '_utf8mb4.x', array( 'UNDERSCORE_CHARSET', 'DOT_SYMBOL', 'IDENTIFIER' ) ), + + // After "@@", the name is never a number, a literal, or a charset. + 'system variable digits' => array( '@@123', array( 'AT_SIGN_SYMBOL', 'AT_SIGN_SYMBOL', 'IDENTIFIER' ) ), + 'system variable float-like' => array( '@@1e5', array( 'AT_SIGN_SYMBOL', 'AT_SIGN_SYMBOL', 'IDENTIFIER' ) ), + 'system variable before text' => array( "@@b'01'", array( 'AT_SIGN_SYMBOL', 'AT_SIGN_SYMBOL', 'IDENTIFIER', 'SINGLE_QUOTED_TEXT' ) ), + 'system variable charset' => array( '@@_utf8mb4', array( 'AT_SIGN_SYMBOL', 'AT_SIGN_SYMBOL', 'IDENTIFIER' ) ), + ); + } + /** * @dataProvider data_integer_types */ diff --git a/packages/mysql-parser/tests/WP_MySQL_Parser_Tests.php b/packages/mysql-parser/tests/WP_MySQL_Parser_Tests.php index 3dc7c1017..5a7e8927d 100644 --- a/packages/mysql-parser/tests/WP_MySQL_Parser_Tests.php +++ b/packages/mysql-parser/tests/WP_MySQL_Parser_Tests.php @@ -90,6 +90,11 @@ public function test_parses_representative_statements(): void { $statements = array( 'SELECT 1', 'SELECT * FROM t1 JOIN t2 ON t1.id = t2.id', + 'SELECT t.1, t.1st, t.1e5 FROM t', + 'SELECT d.1.2 FROM d.1', + 'SELECT order.id, key.1, order.t.id FROM t AS `order`', + "SELECT t.x'41' FROM t", + 'SELECT 1.FROM dual', 'SELECT COUNT(*), MAX(a) FROM t GROUP BY b HAVING COUNT(*) > 1 ORDER BY 1 LIMIT 10', 'SELECT a FROM t GROUP BY a WITH ROLLUP', 'WITH c AS (SELECT 1 AS x) SELECT x FROM c', @@ -101,6 +106,7 @@ public function test_parses_representative_statements(): void { 'DROP TABLE IF EXISTS t', 'SET @v = 1', 'SET @@SESSION.sql_mode = \'\'', + 'SELECT @@`version`', 'SHOW TABLES', 'EXPLAIN SELECT 1', ); @@ -115,6 +121,12 @@ public function test_rejects_statements_invalid_in_mysql_84(): void { 'SHOW SLAVE STATUS', // Removed in MySQL 8.4. 'SELECT 1; SELECT 2', // Multi-statement input. 'CREATE TABLE current_date (a INT)', // Reserved word as a table name. + 'SELECT `t`.1 FROM t', // A quoted name followed by ".1". + 'SELECT.1', // "SELECT" before ".1" is a name. + 'SELECT order.* FROM t AS `order`', // A reserved word before ".*". + 'SELECT 0.select', // "SELECT" after "0." is a keyword. + 'SELECT @@ version', // An empty name after "@@". + "SELECT @@'version'", // A single-quoted name after "@@". ); foreach ( $statements as $sql ) { $this->assertNull( self::parse( $sql ), "Should not parse: $sql" ); diff --git a/packages/mysql-parser/tests/WP_MySQL_Server_Suite_Parser_Tests.php b/packages/mysql-parser/tests/WP_MySQL_Server_Suite_Parser_Tests.php index 4f99663a8..7e3dab250 100644 --- a/packages/mysql-parser/tests/WP_MySQL_Server_Suite_Parser_Tests.php +++ b/packages/mysql-parser/tests/WP_MySQL_Server_Suite_Parser_Tests.php @@ -20,7 +20,7 @@ class WP_MySQL_Server_Suite_Parser_Tests extends TestCase { * legitimately changes. */ const EXPECTED_QUERIES = 69158; - const EXPECTED_FAILURES = 171; + const EXPECTED_FAILURES = 170; public function test_corpus_acceptance_rate(): void { $parser = WP_MySQL_Parser_Factory::create_parser(); diff --git a/packages/mysql-parser/tests/data/corpus-failures.csv b/packages/mysql-parser/tests/data/corpus-failures.csv index bb4b62830..78e09b53d 100644 --- a/packages/mysql-parser/tests/data/corpus-failures.csv +++ b/packages/mysql-parser/tests/data/corpus-failures.csv @@ -935,7 +935,6 @@ end" "select ""stmt 1"";select ""stmt 2 terminated"";" "select ""stmt 1"";select ""stmt 2 terminated, comment""; /* comment */" "select ""stmt 1"";select ""stmt 2 terminated, space""; " -"select 1ea10.1a20,1e+ 1e+10 from 1ea10" "select 2; select 3; select 4"