diff --git a/packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php b/packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php index a751d5fd8..1e9053e18 100644 --- a/packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php +++ b/packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php @@ -4584,16 +4584,15 @@ private function translate_token( WP_MySQL_Token $token ): ?string { $value = substr( $value, 2, -1 ); } - // Convert the binary string to HEX. - $hex = base_convert( $value, 2, 16 ); - /* - * The "base_convert()" function doesn't add or preserve padding. - * Let's compute how many bytes we expect and pad the HEX value - * to full bytes (SQLite requires HEX strings of even length). + * Pad the binary string to full bytes, as SQLite requires HEX strings + * of even length. Then convert each byte to two HEX digits. */ - $byte_count = (int) ceil( strlen( $value ) / 8 ); - $hex = str_pad( $hex, $byte_count * 2, '0', STR_PAD_LEFT ); + $value = str_pad( $value, (int) ceil( strlen( $value ) / 8 ) * 8, '0', STR_PAD_LEFT ); + $hex = ''; + for ( $i = 0; $i < strlen( $value ); $i += 8 ) { + $hex .= sprintf( '%02x', bindec( substr( $value, $i, 8 ) ) ); + } return sprintf( "x'%s'", $hex ); case WP_MySQL_Lexer::HEX_NUMBER: /* @@ -7918,8 +7917,15 @@ private function get_internal_savepoint_name( string $name ): string { */ private function format_sqlite_column_default( array $column ): string { if ( 'bit' === $column['DATA_TYPE'] ) { - // BIT defaults are stored as b'...' literals; reformat as an integer. - return (string) bindec( substr( $column['COLUMN_DEFAULT'], 2, -1 ) ); + // BIT defaults are stored as b'...' literals of up to 64 bits. + $bits = substr( $column['COLUMN_DEFAULT'], 2, -1 ); + if ( strlen( $bits ) > 64 ) { + throw WP_SQLite_Information_Schema_Exception::invalid_default_value( $column['COLUMN_NAME'] ); + } + + // Reformat as an integer. The "%u" format prints all 64 bits as unsigned. + // Requires 64-bit PHP. A 32-bit integer loses the bits shifted by 32. + return sprintf( '%u', bindec( substr( $bits, 0, -32 ) ) << 32 | bindec( substr( $bits, -32 ) ) ); } // A BLOB column in a STRICT table only accepts a BLOB default. @@ -8360,6 +8366,26 @@ private function convert_information_schema_exception( WP_SQLite_Information_Sch null, array( '42000', 1067, $driver_message ) ); + case WP_SQLite_Information_Schema_Exception::TYPE_INVALID_COLUMN_SIZE: + $driver_message = sprintf( "Invalid size for column '%s'.", $e->get_data()['column_name'] ); + return $this->new_driver_exception( + 'SQLSTATE[HY000]: General error: 3013 ' . $driver_message, + 'HY000', + null, + array( 'HY000', 3013, $driver_message ) + ); + case WP_SQLite_Information_Schema_Exception::TYPE_DISPLAY_WIDTH_OUT_OF_RANGE: + $driver_message = sprintf( + "Display width out of range for column '%s' (max = %d)", + $e->get_data()['column_name'], + $e->get_data()['max_width'] + ); + return $this->new_driver_exception( + 'SQLSTATE[42000]: Syntax error or access violation: 1439 ' . $driver_message, + '42000', + null, + array( '42000', 1439, $driver_message ) + ); case WP_SQLite_Information_Schema_Exception::TYPE_CONSTRAINT_DOES_NOT_EXIST: $driver_message = sprintf( "Constraint '%s' does not exist.", $e->get_data()['name'] ); return $this->new_driver_exception( 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 f7a49423f..fb3024d85 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 @@ -1069,7 +1069,7 @@ private function record_alter_column_default( ): void { $columns_table = $this->get_table_name( $table_is_temporary, 'columns' ); $column = $this->connection->query( - 'SELECT DATA_TYPE, DATETIME_PRECISION, IS_NULLABLE, EXTRA FROM ' . $this->connection->quote_identifier( $columns_table ) . ' + 'SELECT DATA_TYPE, NUMERIC_PRECISION, DATETIME_PRECISION, IS_NULLABLE, EXTRA FROM ' . $this->connection->quote_identifier( $columns_table ) . ' WHERE table_schema = ? AND table_name = ? AND column_name = ?', array( self::SAVED_DATABASE_NAME, $table_name, $column_name ) )->fetch( PDO::FETCH_ASSOC ); @@ -1094,9 +1094,10 @@ private function record_alter_column_default( $expression = $node->get_first_child_node( 'exprWithParentheses' ); $literal = $expression ? $this->get_parenthesized_default_literal( $expression ) : null; $datetime_precision = null === $column['DATETIME_PRECISION'] ? null : (int) $column['DATETIME_PRECISION']; + $numeric_precision = null === $column['NUMERIC_PRECISION'] ? null : (int) $column['NUMERIC_PRECISION']; $default = $literal - ? $this->get_literal_default( $literal, $column['DATA_TYPE'], $column_name, $datetime_precision ) - : $this->get_default_value( $node, $column['DATA_TYPE'], $column_name, $datetime_precision ); + ? $this->get_literal_default( $literal, $column['DATA_TYPE'], $column_name, $datetime_precision, $numeric_precision ) + : $this->get_default_value( $node, $column['DATA_TYPE'], $column_name, $datetime_precision, $numeric_precision ); if ( null === $default && 'NO' === $column['IS_NULLABLE'] ) { throw WP_SQLite_Information_Schema_Exception::invalid_default_value( $column_name ); } @@ -1669,8 +1670,14 @@ private function record_drop_check_constraint( */ private function extract_column_data( string $table_name, string $column_name, WP_Parser_Node $node, int $position ): array { list ( $data_type, $column_type ) = $this->get_column_data_types( $node ); + list ( $precision, $scale ) = $this->get_column_numeric_attributes( $node, $data_type ); - $default = $this->get_column_default( $node, $data_type, $column_name ); + // Like MySQL, check the width of a BIT column before its default value. + if ( 'bit' === $data_type ) { + $this->validate_bit_width( $column_name, $precision ); + } + + $default = $this->get_column_default( $node, $data_type, $column_name, $precision ); $nullable = $this->get_column_nullable( $node ); $key = $this->get_column_key( $node ); $extra = $this->get_column_extra( $node ); @@ -1678,7 +1685,6 @@ private function extract_column_data( string $table_name, string $column_name, W list ( $charset, $collation ) = $this->get_column_charset_and_collation( $node, $data_type ); list ( $char_length, $octet_length ) = $this->get_column_lengths( $node, $data_type, $charset ); - list ( $precision, $scale ) = $this->get_column_numeric_attributes( $node, $data_type ); $datetime_precision = $this->get_column_datetime_precision( $node, $data_type ); $generation_expression = $this->get_column_generation_expression( $node ); @@ -2212,12 +2218,13 @@ private function get_table_comment( WP_Parser_Node $node ): string { /** * Extract column default value from the "columnDefinition" or "fieldDefinition" AST node. * - * @param WP_Parser_Node $node The "columnDefinition" or "fieldDefinition" AST node. - * @param string $data_type The column data type as stored in information schema. - * @param string $column_name The column name. - * @return string|null The column default as stored in information schema. + * @param WP_Parser_Node $node The "columnDefinition" or "fieldDefinition" AST node. + * @param string $data_type The column data type as stored in information schema. + * @param string $column_name The column name. + * @param int|null $numeric_precision The column numeric precision. For BIT, the width in bits. + * @return string|null The column default as stored in information schema. */ - private function get_column_default( WP_Parser_Node $node, string $data_type, string $column_name ): ?string { + private function get_column_default( WP_Parser_Node $node, string $data_type, string $column_name, ?int $numeric_precision ): ?string { $default_attr = null; foreach ( $node->get_descendant_nodes( 'columnAttribute' ) as $attr ) { if ( $attr->has_child_token( WP_MySQL_Lexer::DEFAULT_SYMBOL ) ) { @@ -2229,7 +2236,7 @@ private function get_column_default( WP_Parser_Node $node, string $data_type, st return null; } $datetime_precision = $this->get_column_datetime_precision( $node, $data_type ); - return $this->get_default_value( $default_attr, $data_type, $column_name, $datetime_precision ); + return $this->get_default_value( $default_attr, $data_type, $column_name, $datetime_precision, $numeric_precision ); } /** @@ -2239,9 +2246,10 @@ private function get_column_default( WP_Parser_Node $node, string $data_type, st * @param string $data_type The column data type as stored in information schema. * @param string $column_name The column name. * @param int|null $datetime_precision The column fractional seconds precision. + * @param int|null $numeric_precision The column numeric precision. For BIT, the width in bits. * @return string|null The default value as stored in information schema. */ - private function get_default_value( WP_Parser_Node $node, string $data_type, string $column_name, ?int $datetime_precision ): ?string { + private function get_default_value( WP_Parser_Node $node, string $data_type, string $column_name, ?int $datetime_precision, ?int $numeric_precision ): ?string { /* * [GRAMMAR] * columnAttribute: @@ -2271,10 +2279,10 @@ private function get_default_value( WP_Parser_Node $node, string $data_type, str // A signed number, such as "-5", has no "literal" child node. // Like MySQL, drop the unary plus, e.g., "+5" becomes "5". $number = ltrim( $this->get_value( $signed_literal ), '+' ); - $default = $this->normalize_literal_default( $number, $data_type, $column_name ); + $default = $this->normalize_literal_default( $number, $data_type, $column_name, $numeric_precision ); return $this->get_temporal_zero_value( $data_type, $default, $datetime_precision ) ?? $default; } - return $this->get_literal_default( $literal, $data_type, $column_name, $datetime_precision ); + return $this->get_literal_default( $literal, $data_type, $column_name, $datetime_precision, $numeric_precision ); } // DEFAULT (expression) - MySQL 8.0.13+ supports exprWithParentheses @@ -2293,9 +2301,10 @@ private function get_default_value( WP_Parser_Node $node, string $data_type, str * @param string $data_type The column data type as stored in information schema. * @param string $column_name The column name. * @param int|null $datetime_precision The column fractional seconds precision. + * @param int|null $numeric_precision The column numeric precision. For BIT, the width in bits. * @return string|null The default value as stored in information schema. */ - private function get_literal_default( WP_Parser_Node $literal, string $data_type, string $column_name, ?int $datetime_precision ): ?string { + private function get_literal_default( WP_Parser_Node $literal, string $data_type, string $column_name, ?int $datetime_precision, ?int $numeric_precision ): ?string { // DEFAULT NULL if ( $literal->has_child_node( 'nullLiteral' ) ) { return null; @@ -2311,7 +2320,7 @@ private function get_literal_default( WP_Parser_Node $literal, string $data_type $bool_value = $bool_literal->has_child_token( WP_MySQL_Lexer::TRUE_SYMBOL ) ? '1' : '0'; $default = 'bit' === $data_type ? "b'{$bool_value}'" : $bool_value; } else { - $default = $this->normalize_literal_default( $this->get_value( $literal ), $data_type, $column_name ); + $default = $this->normalize_literal_default( $this->get_value( $literal ), $data_type, $column_name, $numeric_precision ); } /* @@ -2328,19 +2337,22 @@ private function get_literal_default( WP_Parser_Node $literal, string $data_type /** * Normalize a literal default value for the column data type. * - * @param string $default_value The literal default value. - * @param string $data_type The column data type as stored in information schema. - * @param string $column_name The column name. - * @return string The default value as stored in information schema. + * @param string $default_value The literal default value. + * @param string $data_type The column data type as stored in information schema. + * @param string $column_name The column name. + * @param int|null $numeric_precision The column numeric precision. For BIT, the width in bits. + * @return string The default value as stored in information schema. */ - private function normalize_literal_default( string $default_value, string $data_type, string $column_name ): string { + private function normalize_literal_default( string $default_value, string $data_type, string $column_name, ?int $numeric_precision ): string { if ( 'bit' === $data_type ) { /* * @TODO: Validate and normalize defaults from their AST and the full * column definition before storing them in the information schema. */ $bit_default = $this->get_bit_default( $default_value ); - if ( null === $bit_default ) { + + // The value must fit the column width. The "b''" wrapper takes 3 bytes. + if ( null === $bit_default || strlen( $bit_default ) - 3 > $numeric_precision ) { throw WP_SQLite_Information_Schema_Exception::invalid_default_value( $column_name ); } return $bit_default; @@ -2439,6 +2451,19 @@ private function get_bit_default( string $default_value ): ?string { return "b'0'"; } + // Hex literal, e.g. x'05' or 0x05. Convert it to a bit literal digit by + // digit, as a value of 64 bits doesn't fit into an integer. + if ( + preg_match( "/\Ax'([0-9a-f]*)'\z/", $value, $matches ) + || preg_match( '/\A0x([0-9a-f]+)\z/', $value, $matches ) + ) { + $value = "b'"; + foreach ( str_split( $matches[1] ) as $digit ) { + $value .= sprintf( '%04b', hexdec( $digit ) ); + } + $value .= "'"; + } + // Bit literal, e.g. b'101' or 0b101. if ( preg_match( "/\Ab'([01]*)'\z/", $value, $matches ) @@ -2448,14 +2473,6 @@ private function get_bit_default( string $default_value ): ?string { return "b'" . ( '' === $bits ? '0' : $bits ) . "'"; } - // Hex literal, e.g. x'05' or 0x05. - if ( - preg_match( "/\Ax'([0-9a-f]*)'\z/", $value, $matches ) - || preg_match( '/\A0x([0-9a-f]+)\z/', $value, $matches ) - ) { - return "b'" . decbin( hexdec( $matches[1] ) ) . "'"; - } - // Non-negative decimal, e.g. 5, or a numeric string literal such as '0'. if ( is_numeric( $value ) && $value >= 0 ) { return "b'" . decbin( (int) $value ) . "'"; @@ -2913,7 +2930,9 @@ private function get_column_numeric_attributes( WP_Parser_Node $node, string $da // For bit columns, we need to check the precision. if ( 'bit' === $data_type ) { - $field_length = $node->get_first_descendant_node( 'fieldLength' ); + // Search only the data type. An expression in the column definition + // can contain a length as well, e.g. "CAST(... AS CHAR(10))". + $field_length = $node->get_first_descendant_node( 'dataType' )->get_first_descendant_node( 'fieldLength' ); if ( null === $field_length ) { return array( 1, null ); } @@ -2948,6 +2967,28 @@ private function get_column_numeric_attributes( WP_Parser_Node $node, string $da return array( null, null ); } + /** + * Check that the width of a BIT column is 1 to 64 bits. + * + * @param string $column_name The column name. + * @param int $width The column width in bits. + * @throws WP_SQLite_Information_Schema_Exception When the width is not valid. + */ + private function validate_bit_width( string $column_name, int $width ): void { + if ( 0 === $width ) { + throw WP_SQLite_Information_Schema_Exception::invalid_column_size( $column_name ); + } + + if ( $width > 64 ) { + // MySQL reports a different limit when the width doesn't fit in 32 bits. + $max_width = 64; + if ( $width > 4294967295 ) { + $max_width = 4294967295; + } + throw WP_SQLite_Information_Schema_Exception::display_width_out_of_range( $column_name, $max_width ); + } + } + /** * Extract column date/time precision from the "columnDefinition" or "fieldDefinition" AST node. * diff --git a/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-exception.php b/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-exception.php index 9dbe567b3..0a50fec73 100644 --- a/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-exception.php +++ b/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-exception.php @@ -18,6 +18,8 @@ class WP_SQLite_Information_Schema_Exception extends Exception { const TYPE_CONSTRAINT_DOES_NOT_EXIST = 'constraint-does-not-exist'; const TYPE_MULTIPLE_CONSTRAINTS_WITH_NAME = 'multiple-constraints-with-name'; const TYPE_INVALID_DEFAULT_VALUE = 'invalid-default-value'; + const TYPE_INVALID_COLUMN_SIZE = 'invalid-column-size'; + const TYPE_DISPLAY_WIDTH_OUT_OF_RANGE = 'display-width-out-of-range'; /** * The exception type. @@ -185,4 +187,36 @@ public static function invalid_default_value( string $column_name ): WP_SQLite_I array( 'column_name' => $column_name ) ); } + + /** + * Create an invalid column size exception. + * + * @param string $column_name The name of the affected column. + * @return self The exception instance. + */ + public static function invalid_column_size( string $column_name ): WP_SQLite_Information_Schema_Exception { + return new self( + self::TYPE_INVALID_COLUMN_SIZE, + sprintf( "Invalid size for column '%s'.", $column_name ), + array( 'column_name' => $column_name ) + ); + } + + /** + * Create a display width out of range exception. + * + * @param string $column_name The name of the affected column. + * @param int $max_width The maximum display width. + * @return self The exception instance. + */ + public static function display_width_out_of_range( string $column_name, int $max_width ): WP_SQLite_Information_Schema_Exception { + return new self( + self::TYPE_DISPLAY_WIDTH_OUT_OF_RANGE, + sprintf( "Display width out of range for column '%s' (max = %d).", $column_name, $max_width ), + array( + 'column_name' => $column_name, + 'max_width' => $max_width, + ) + ); + } } 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 97bbc1704..f57393ef7 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 @@ -2397,6 +2397,51 @@ public function testShowCreateTableWithBitDefaultValues(): void { ); } + public function testShowCreateTableWithLargeBitDefaultValues(): void { + // Values of 64 bits don't fit into an integer. + $bits_63 = str_repeat( '1', 63 ); + $bits_64 = str_repeat( '1', 64 ); + $this->assertQuery( + "CREATE TABLE _tmp_bit_defaults ( + id INT DEFAULT 0, + bit_literal_63_bits BIT(64) DEFAULT b'$bits_63', + hex_number_63_bits BIT(64) DEFAULT 0x7FFFFFFFFFFFFFFF, + bit_literal_64_bits BIT(64) DEFAULT b'$bits_64', + binary_number_64_bits BIT(64) DEFAULT 0b$bits_64, + hex_literal_64_bits BIT(64) DEFAULT x'FFFFFFFFFFFFFFFF', + hex_number_64_bits BIT(64) DEFAULT 0xFFFFFFFFFFFFFFFF, + hex_number_odd_length BIT(16) DEFAULT 0xABC + )" + ); + + $this->assertQuery( 'SHOW CREATE TABLE _tmp_bit_defaults;' ); + $results = $this->last_result; + $create_table = $results[0]->{'Create Table'}; + $this->assertStringContainsString( "`bit_literal_63_bits` bit(64) DEFAULT b'$bits_63',", $create_table ); + $this->assertStringContainsString( "`hex_number_63_bits` bit(64) DEFAULT b'$bits_63',", $create_table ); + $this->assertStringContainsString( "`bit_literal_64_bits` bit(64) DEFAULT b'$bits_64',", $create_table ); + $this->assertStringContainsString( "`binary_number_64_bits` bit(64) DEFAULT b'$bits_64',", $create_table ); + $this->assertStringContainsString( "`hex_literal_64_bits` bit(64) DEFAULT b'$bits_64',", $create_table ); + $this->assertStringContainsString( "`hex_number_64_bits` bit(64) DEFAULT b'$bits_64',", $create_table ); + $this->assertStringContainsString( "`hex_number_odd_length` bit(16) DEFAULT b'101010111100'", $create_table ); + } + + public function testLongBitLiterals(): void { + $bits_64 = str_repeat( '1', 64 ); + $bits_72 = '10000001' . str_repeat( '0', 56 ) . '00000001'; + $this->assertQuery( "SELECT HEX(b'$bits_64') AS bits_64, HEX(0b$bits_72) AS bits_72, HEX(b'') AS no_bits" ); + $this->assertEquals( + array( + (object) array( + 'bits_64' => 'FFFFFFFFFFFFFFFF', + 'bits_72' => '810000000000000001', + 'no_bits' => '', + ), + ), + $this->last_result + ); + } + /** * @dataProvider invalidBitDefaultQueries */ @@ -2492,6 +2537,181 @@ public static function invalidBitDefaultQueries(): array { "ALTER TABLE _tmp_invalid_bit_default ALTER COLUMN injected SET DEFAULT '-0.1'", 'injected', ), + 'CREATE too wide' => array( + "CREATE TABLE _tmp_created_invalid_bit_default (injected BIT(8) DEFAULT b'111111111')", + 'injected', + ), + 'CREATE no width' => array( + "CREATE TABLE _tmp_created_invalid_bit_default (injected BIT DEFAULT b'10')", + 'injected', + ), + 'ADD too wide' => array( + "ALTER TABLE _tmp_invalid_bit_default ADD COLUMN injected_2 BIT(8) DEFAULT b'111111111'", + 'injected_2', + ), + 'MODIFY too wide' => array( + 'ALTER TABLE _tmp_invalid_bit_default MODIFY COLUMN injected BIT(8) DEFAULT 0x01FF', + 'injected', + ), + 'CHANGE too wide' => array( + 'ALTER TABLE _tmp_invalid_bit_default CHANGE COLUMN injected injected_2 BIT(8) DEFAULT 0b111111111', + 'injected_2', + ), + 'SET too wide' => array( + "ALTER TABLE _tmp_invalid_bit_default ALTER COLUMN injected SET DEFAULT b'10'", + 'injected', + ), + 'SET (too wide)' => array( + "ALTER TABLE _tmp_invalid_bit_default ALTER COLUMN injected SET DEFAULT (b'10')", + 'injected', + ), + 'too large number' => array( + 'ALTER TABLE _tmp_invalid_bit_default MODIFY COLUMN injected BIT(8) DEFAULT 256', + 'injected', + ), + '64 bits in BIT(63)' => array( + sprintf( "ALTER TABLE _tmp_invalid_bit_default MODIFY COLUMN injected BIT(63) DEFAULT b'%s'", str_repeat( '1', 64 ) ), + 'injected', + ), + '65 bits in BIT(64)' => array( + sprintf( "ALTER TABLE _tmp_invalid_bit_default MODIFY COLUMN injected BIT(64) DEFAULT b'1%s'", str_repeat( '0', 64 ) ), + 'injected', + ), + '9 bytes in BIT(64)' => array( + 'ALTER TABLE _tmp_invalid_bit_default MODIFY COLUMN injected BIT(64) DEFAULT 0x01FFFFFFFFFFFFFFFF', + 'injected', + ), + ); + } + + public function testBitDefaultValuesOfFullColumnWidth(): void { + $bits_64 = str_repeat( '1', 64 ); + $this->assertQuery( + "CREATE TABLE _tmp_bit_defaults ( + no_width BIT DEFAULT 1, + true_literal BIT(1) DEFAULT TRUE, + bit_literal BIT(8) DEFAULT b'11111111', + leading_zeros BIT(8) DEFAULT b'0000000011111111', + hex_number BIT(8) DEFAULT 0x00FF, + integer_number BIT(8) DEFAULT 255, + bits_64 BIT(64) DEFAULT b'$bits_64', + expression BIT(8) DEFAULT (b'111111111') + )" + ); + $this->assertQuery( "ALTER TABLE _tmp_bit_defaults ALTER COLUMN no_width SET DEFAULT b'01'" ); + $this->assertQuery( "ALTER TABLE _tmp_bit_defaults ALTER COLUMN true_literal SET DEFAULT (b'1')" ); + + $this->assertQuery( 'SHOW CREATE TABLE _tmp_bit_defaults' ); + $create_table = $this->last_result[0]->{'Create Table'}; + $this->assertStringContainsString( "`no_width` bit(1) DEFAULT b'1',", $create_table ); + $this->assertStringContainsString( "`true_literal` bit(1) DEFAULT b'1',", $create_table ); + $this->assertStringContainsString( "`bit_literal` bit(8) DEFAULT b'11111111',", $create_table ); + $this->assertStringContainsString( "`leading_zeros` bit(8) DEFAULT b'11111111',", $create_table ); + $this->assertStringContainsString( "`hex_number` bit(8) DEFAULT b'11111111',", $create_table ); + $this->assertStringContainsString( "`integer_number` bit(8) DEFAULT b'11111111',", $create_table ); + $this->assertStringContainsString( "`bits_64` bit(64) DEFAULT b'$bits_64',", $create_table ); + + // Like in MySQL, an expression default is not checked. + $this->assertStringContainsString( "`expression` bit(8) DEFAULT (b'111111111')", $create_table ); + } + + public function testRejectsStoredBitDefaultValueOfMoreThan64Bits(): void { + // Only a driver version without the width check could store such a default. + $this->assertQuery( 'CREATE TABLE _tmp_bit_defaults (id INT, b BIT(64))' ); + $this->sqlite->exec( + sprintf( + "UPDATE _wp_sqlite_mysql_information_schema_columns SET column_default = 'b''1%s''' WHERE table_name = '_tmp_bit_defaults' AND column_name = 'b'", + str_repeat( '0', 64 ) + ) + ); + + $exception = null; + try { + $this->query( 'ALTER TABLE _tmp_bit_defaults ADD COLUMN c INT' ); + } catch ( WP_MySQL_On_SQLite_Exception $e ) { + $exception = $e; + } + + $this->assertInstanceOf( WP_MySQL_On_SQLite_Exception::class, $exception ); + $this->assertSame( array( '42000', 1067, "Invalid default value for 'b'" ), $exception->errorInfo ); + + // The table is not changed. + $this->assertQuery( 'SHOW COLUMNS FROM _tmp_bit_defaults' ); + $this->assertSame( array( 'id', 'b' ), array_column( $this->last_result, 'Field' ) ); + } + + /** + * @dataProvider invalidBitWidthQueries + */ + public function testRejectsInvalidBitWidths( string $query, string $message, string $sqlstate, int $code ): void { + $this->assertQuery( 'CREATE TABLE _tmp_invalid_bit_width (id INT, b BIT(8))' ); + + $exception = null; + try { + $this->query( $query ); + } catch ( WP_MySQL_On_SQLite_Exception $e ) { + $exception = $e; + } + + $this->assertInstanceOf( WP_MySQL_On_SQLite_Exception::class, $exception ); + $this->assertStringEndsWith( ": $code $message", $exception->getMessage() ); + $this->assertSame( $sqlstate, $exception->getCode() ); + $this->assertSame( array( $sqlstate, $code, $message ), $exception->errorInfo ); + + // The table is not changed. + $this->assertQuery( 'SHOW CREATE TABLE _tmp_invalid_bit_width' ); + $this->assertStringContainsString( '`b` bit(8) DEFAULT NULL', $this->last_result[0]->{'Create Table'} ); + } + + public static function invalidBitWidthQueries(): array { + $too_wide = array( "Display width out of range for column 'b' (max = 64)", '42000', 1439 ); + $invalid_size = array( "Invalid size for column 'b'.", 'HY000', 3013 ); + + return array( + 'CREATE 65 bits' => array_merge( array( 'CREATE TABLE _tmp_created_invalid_bit_width (b BIT(65))' ), $too_wide ), + 'CREATE leading zero' => array_merge( array( 'CREATE TABLE _tmp_created_invalid_bit_width (b BIT(065))' ), $too_wide ), + 'CREATE 65 bits, default' => array_merge( array( 'CREATE TABLE _tmp_created_invalid_bit_width (b BIT(65) DEFAULT -1)' ), $too_wide ), + 'ADD 65 bits' => array( + 'ALTER TABLE _tmp_invalid_bit_width ADD COLUMN c BIT(65)', + "Display width out of range for column 'c' (max = 64)", + '42000', + 1439, + ), + 'MODIFY 65 bits' => array_merge( array( 'ALTER TABLE _tmp_invalid_bit_width MODIFY COLUMN b BIT(65)' ), $too_wide ), + 'CHANGE 65 bits' => array_merge( array( 'ALTER TABLE _tmp_invalid_bit_width CHANGE COLUMN b b BIT(65)' ), $too_wide ), + 'CREATE 4294967295 bits' => array_merge( array( 'CREATE TABLE _tmp_created_invalid_bit_width (b BIT(4294967295))' ), $too_wide ), + 'CREATE more than 32 bits' => array( + 'CREATE TABLE _tmp_created_invalid_bit_width (b BIT(4294967296))', + "Display width out of range for column 'b' (max = 4294967295)", + '42000', + 1439, + ), + 'CREATE more than 64 bits' => array( + 'CREATE TABLE _tmp_created_invalid_bit_width (b BIT(99999999999999999999))', + "Display width out of range for column 'b' (max = 4294967295)", + '42000', + 1439, + ), + 'CREATE zero bits' => array_merge( array( 'CREATE TABLE _tmp_created_invalid_bit_width (b BIT(0))' ), $invalid_size ), + 'CREATE zero bits, default' => array_merge( array( "CREATE TABLE _tmp_created_invalid_bit_width (b BIT(0) DEFAULT b'1')" ), $invalid_size ), + 'MODIFY zero bits' => array_merge( array( 'ALTER TABLE _tmp_invalid_bit_width MODIFY COLUMN b BIT(0)' ), $invalid_size ), + ); + } + + public function testBitWidthIgnoresLengthsInColumnExpressions(): void { + $this->assertQuery( "CREATE TABLE _tmp_bit_widths (b BIT CHECK (CAST(b AS CHAR(100)) <> ''))" ); + + $this->assertQuery( + "SELECT COLUMN_TYPE, NUMERIC_PRECISION FROM information_schema.columns WHERE table_name = '_tmp_bit_widths'" + ); + $this->assertEquals( + array( + (object) array( + 'COLUMN_TYPE' => 'bit(1)', + 'NUMERIC_PRECISION' => '1', + ), + ), + $this->last_result ); } diff --git a/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Translation_Tests.php b/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Translation_Tests.php index f6c253d2d..66853a627 100644 --- a/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Translation_Tests.php +++ b/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Translation_Tests.php @@ -1254,6 +1254,16 @@ public function testBitDataTypes(): void { ); } + public function testBitDefaultValues(): void { + // SQLite reads an integer that doesn't fit into 63 bits as a real number. + $bits_63 = str_repeat( '1', 63 ); + $bits_64 = str_repeat( '1', 64 ); + $this->assertQuery( + 'CREATE TABLE `t` ( `i1` INTEGER DEFAULT 5, `i2` INTEGER DEFAULT 9223372036854775807, `i3` INTEGER DEFAULT 18446744073709551615 )' . $this->strict_suffix, + "CREATE TABLE t (i1 BIT(4) DEFAULT b'101', i2 BIT(64) DEFAULT b'$bits_63', i3 BIT(64) DEFAULT b'$bits_64')" + ); + } + public function testBooleanDataTypes(): void { $this->assertQuery( 'CREATE TABLE `t` ( `i1` INTEGER, `i2` INTEGER )' . $this->strict_suffix, @@ -1724,6 +1734,31 @@ public function testBinaryLiterals(): void { "SELECT x'417a' AS `0b0100000101111010`", 'SELECT 0b0100000101111010' ); + + // Values that are not a whole number of bytes are padded with leading zeros. + $this->assertQuery( + "SELECT x'01e1' AS `b'111100001'`", + "SELECT b'111100001'" + ); + + // Values of 64 or more bits don't fit into an integer. + $bits = str_repeat( '1', 64 ); + $this->assertQuery( + "SELECT x'ffffffffffffffff' AS `b'$bits'`", + "SELECT b'$bits'" + ); + + $bits = '10000001' . str_repeat( '0', 56 ) . '00000001'; + $this->assertQuery( + "SELECT x'810000000000000001' AS `0b$bits`", + "SELECT 0b$bits" + ); + + // An empty value. + $this->assertQuery( + "SELECT x'' AS `b''`", + "SELECT b''" + ); } public function testHexadecimalLiterals(): void {