Skip to content

Commit e82c914

Browse files
authored
Fix long bit literals and validate BIT widths and defaults (WordPress#636)
## Summary This PR fixes **bit literals and `BIT` column defaults of 64 or more bits**, and it makes the driver **reject invalid `BIT` widths and defaults** with the same errors as MySQL. The fixes: - **Bit literals of any length** translate to the correct bytes. A literal such as `b'101'` or `0b101` is converted byte by byte, instead of through a number. - **Hex defaults of `BIT` columns** are converted digit by digit, so `BIT(64) DEFAULT 0xFFFFFFFFFFFFFFFF` works. - **The `BIT` width** must be 1 to 64 bits. `BIT(65)` gives error 1439 and `BIT(0)` gives error 3013. - **A literal `BIT` default** must fit the column width. Otherwise, it gives error 1067. Expression defaults are not checked, as in MySQL. ## Why The driver converted these values with `base_convert()`, `bindec()`, and `hexdec()`. They lose precision above `PHP_INT_MAX`, so the results were wrong for 64 or more bits. **PHP 8.6 also raises a notice for these calls**, so this PR needs to land before the PHP 8.6 support in WordPress#635. The driver also accepted `BIT` columns and defaults that MySQL rejects. With the new checks, a stored `BIT` default always has at most 64 bits, which keeps its conversion for SQLite simple and exact. These results now match MySQL 8.4: | Query | Before | After | | --- | --- | --- | | `SELECT HEX(b'1…1')` with 64 bits | SQLite syntax error | `FFFFFFFFFFFFFFFF` | | `SELECT HEX(b'')` | SQLite syntax error | Empty string | | `SELECT HEX(0b…)` with 72 bits | Wrong last byte | The correct bytes | | `BIT(64) DEFAULT 0xFFFFFFFFFFFFFFFF` | `TypeError` | `b'1…1'` in `SHOW CREATE TABLE` | | `BIT(65)` | Accepted | Error 1439 | | `BIT(0)` | Accepted | Error 3013 | | `BIT(8) DEFAULT b'111111111'` | Accepted | Error 1067 | ## Notes Some `BIT` behavior still differs from MySQL. This PR doesn't change it: - **Values that use the 64th bit can't be stored**, because SQLite integers are signed. Inserting one fails with an SQLite error. - **Decimal defaults of 2^63 or more** are capped to 63 ones. - **Literals longer than 8 bytes** are accepted when the value fits. MySQL rejects them in strict mode. - **Quoted strings** are read as numbers, and fractions are truncated. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Improved handling of binary literals, including values that don’t contain a whole number of bytes and values up to 64 bits. * BIT column defaults are now validated against the column’s width and the 64-bit limit, with accepted values formatted consistently. * Invalid BIT widths and defaults now return MySQL-compatible errors with details about the affected column. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent 1b1a0be commit e82c914

5 files changed

Lines changed: 397 additions & 41 deletions

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

Lines changed: 36 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4584,16 +4584,15 @@ private function translate_token( WP_MySQL_Token $token ): ?string {
45844584
$value = substr( $value, 2, -1 );
45854585
}
45864586

4587-
// Convert the binary string to HEX.
4588-
$hex = base_convert( $value, 2, 16 );
4589-
45904587
/*
4591-
* The "base_convert()" function doesn't add or preserve padding.
4592-
* Let's compute how many bytes we expect and pad the HEX value
4593-
* to full bytes (SQLite requires HEX strings of even length).
4588+
* Pad the binary string to full bytes, as SQLite requires HEX strings
4589+
* of even length. Then convert each byte to two HEX digits.
45944590
*/
4595-
$byte_count = (int) ceil( strlen( $value ) / 8 );
4596-
$hex = str_pad( $hex, $byte_count * 2, '0', STR_PAD_LEFT );
4591+
$value = str_pad( $value, (int) ceil( strlen( $value ) / 8 ) * 8, '0', STR_PAD_LEFT );
4592+
$hex = '';
4593+
for ( $i = 0; $i < strlen( $value ); $i += 8 ) {
4594+
$hex .= sprintf( '%02x', bindec( substr( $value, $i, 8 ) ) );
4595+
}
45974596
return sprintf( "x'%s'", $hex );
45984597
case WP_MySQL_Lexer::HEX_NUMBER:
45994598
/*
@@ -7918,8 +7917,15 @@ private function get_internal_savepoint_name( string $name ): string {
79187917
*/
79197918
private function format_sqlite_column_default( array $column ): string {
79207919
if ( 'bit' === $column['DATA_TYPE'] ) {
7921-
// BIT defaults are stored as b'...' literals; reformat as an integer.
7922-
return (string) bindec( substr( $column['COLUMN_DEFAULT'], 2, -1 ) );
7920+
// BIT defaults are stored as b'...' literals of up to 64 bits.
7921+
$bits = substr( $column['COLUMN_DEFAULT'], 2, -1 );
7922+
if ( strlen( $bits ) > 64 ) {
7923+
throw WP_SQLite_Information_Schema_Exception::invalid_default_value( $column['COLUMN_NAME'] );
7924+
}
7925+
7926+
// Reformat as an integer. The "%u" format prints all 64 bits as unsigned.
7927+
// Requires 64-bit PHP. A 32-bit integer loses the bits shifted by 32.
7928+
return sprintf( '%u', bindec( substr( $bits, 0, -32 ) ) << 32 | bindec( substr( $bits, -32 ) ) );
79237929
}
79247930

79257931
// 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
83608366
null,
83618367
array( '42000', 1067, $driver_message )
83628368
);
8369+
case WP_SQLite_Information_Schema_Exception::TYPE_INVALID_COLUMN_SIZE:
8370+
$driver_message = sprintf( "Invalid size for column '%s'.", $e->get_data()['column_name'] );
8371+
return $this->new_driver_exception(
8372+
'SQLSTATE[HY000]: General error: 3013 ' . $driver_message,
8373+
'HY000',
8374+
null,
8375+
array( 'HY000', 3013, $driver_message )
8376+
);
8377+
case WP_SQLite_Information_Schema_Exception::TYPE_DISPLAY_WIDTH_OUT_OF_RANGE:
8378+
$driver_message = sprintf(
8379+
"Display width out of range for column '%s' (max = %d)",
8380+
$e->get_data()['column_name'],
8381+
$e->get_data()['max_width']
8382+
);
8383+
return $this->new_driver_exception(
8384+
'SQLSTATE[42000]: Syntax error or access violation: 1439 ' . $driver_message,
8385+
'42000',
8386+
null,
8387+
array( '42000', 1439, $driver_message )
8388+
);
83638389
case WP_SQLite_Information_Schema_Exception::TYPE_CONSTRAINT_DOES_NOT_EXIST:
83648390
$driver_message = sprintf( "Constraint '%s' does not exist.", $e->get_data()['name'] );
83658391
return $this->new_driver_exception(

‎packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-builder.php‎

Lines changed: 72 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1069,7 +1069,7 @@ private function record_alter_column_default(
10691069
): void {
10701070
$columns_table = $this->get_table_name( $table_is_temporary, 'columns' );
10711071
$column = $this->connection->query(
1072-
'SELECT DATA_TYPE, DATETIME_PRECISION, IS_NULLABLE, EXTRA FROM ' . $this->connection->quote_identifier( $columns_table ) . '
1072+
'SELECT DATA_TYPE, NUMERIC_PRECISION, DATETIME_PRECISION, IS_NULLABLE, EXTRA FROM ' . $this->connection->quote_identifier( $columns_table ) . '
10731073
WHERE table_schema = ? AND table_name = ? AND column_name = ?',
10741074
array( self::SAVED_DATABASE_NAME, $table_name, $column_name )
10751075
)->fetch( PDO::FETCH_ASSOC );
@@ -1094,9 +1094,10 @@ private function record_alter_column_default(
10941094
$expression = $node->get_first_child_node( 'exprWithParentheses' );
10951095
$literal = $expression ? $this->get_parenthesized_default_literal( $expression ) : null;
10961096
$datetime_precision = null === $column['DATETIME_PRECISION'] ? null : (int) $column['DATETIME_PRECISION'];
1097+
$numeric_precision = null === $column['NUMERIC_PRECISION'] ? null : (int) $column['NUMERIC_PRECISION'];
10971098
$default = $literal
1098-
? $this->get_literal_default( $literal, $column['DATA_TYPE'], $column_name, $datetime_precision )
1099-
: $this->get_default_value( $node, $column['DATA_TYPE'], $column_name, $datetime_precision );
1099+
? $this->get_literal_default( $literal, $column['DATA_TYPE'], $column_name, $datetime_precision, $numeric_precision )
1100+
: $this->get_default_value( $node, $column['DATA_TYPE'], $column_name, $datetime_precision, $numeric_precision );
11001101
if ( null === $default && 'NO' === $column['IS_NULLABLE'] ) {
11011102
throw WP_SQLite_Information_Schema_Exception::invalid_default_value( $column_name );
11021103
}
@@ -1669,16 +1670,21 @@ private function record_drop_check_constraint(
16691670
*/
16701671
private function extract_column_data( string $table_name, string $column_name, WP_Parser_Node $node, int $position ): array {
16711672
list ( $data_type, $column_type ) = $this->get_column_data_types( $node );
1673+
list ( $precision, $scale ) = $this->get_column_numeric_attributes( $node, $data_type );
16721674

1673-
$default = $this->get_column_default( $node, $data_type, $column_name );
1675+
// Like MySQL, check the width of a BIT column before its default value.
1676+
if ( 'bit' === $data_type ) {
1677+
$this->validate_bit_width( $column_name, $precision );
1678+
}
1679+
1680+
$default = $this->get_column_default( $node, $data_type, $column_name, $precision );
16741681
$nullable = $this->get_column_nullable( $node );
16751682
$key = $this->get_column_key( $node );
16761683
$extra = $this->get_column_extra( $node );
16771684
$comment = $this->get_column_comment( $node );
16781685

16791686
list ( $charset, $collation ) = $this->get_column_charset_and_collation( $node, $data_type );
16801687
list ( $char_length, $octet_length ) = $this->get_column_lengths( $node, $data_type, $charset );
1681-
list ( $precision, $scale ) = $this->get_column_numeric_attributes( $node, $data_type );
16821688
$datetime_precision = $this->get_column_datetime_precision( $node, $data_type );
16831689
$generation_expression = $this->get_column_generation_expression( $node );
16841690

@@ -2212,12 +2218,13 @@ private function get_table_comment( WP_Parser_Node $node ): string {
22122218
/**
22132219
* Extract column default value from the "columnDefinition" or "fieldDefinition" AST node.
22142220
*
2215-
* @param WP_Parser_Node $node The "columnDefinition" or "fieldDefinition" AST node.
2216-
* @param string $data_type The column data type as stored in information schema.
2217-
* @param string $column_name The column name.
2218-
* @return string|null The column default as stored in information schema.
2221+
* @param WP_Parser_Node $node The "columnDefinition" or "fieldDefinition" AST node.
2222+
* @param string $data_type The column data type as stored in information schema.
2223+
* @param string $column_name The column name.
2224+
* @param int|null $numeric_precision The column numeric precision. For BIT, the width in bits.
2225+
* @return string|null The column default as stored in information schema.
22192226
*/
2220-
private function get_column_default( WP_Parser_Node $node, string $data_type, string $column_name ): ?string {
2227+
private function get_column_default( WP_Parser_Node $node, string $data_type, string $column_name, ?int $numeric_precision ): ?string {
22212228
$default_attr = null;
22222229
foreach ( $node->get_descendant_nodes( 'columnAttribute' ) as $attr ) {
22232230
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
22292236
return null;
22302237
}
22312238
$datetime_precision = $this->get_column_datetime_precision( $node, $data_type );
2232-
return $this->get_default_value( $default_attr, $data_type, $column_name, $datetime_precision );
2239+
return $this->get_default_value( $default_attr, $data_type, $column_name, $datetime_precision, $numeric_precision );
22332240
}
22342241

22352242
/**
@@ -2239,9 +2246,10 @@ private function get_column_default( WP_Parser_Node $node, string $data_type, st
22392246
* @param string $data_type The column data type as stored in information schema.
22402247
* @param string $column_name The column name.
22412248
* @param int|null $datetime_precision The column fractional seconds precision.
2249+
* @param int|null $numeric_precision The column numeric precision. For BIT, the width in bits.
22422250
* @return string|null The default value as stored in information schema.
22432251
*/
2244-
private function get_default_value( WP_Parser_Node $node, string $data_type, string $column_name, ?int $datetime_precision ): ?string {
2252+
private function get_default_value( WP_Parser_Node $node, string $data_type, string $column_name, ?int $datetime_precision, ?int $numeric_precision ): ?string {
22452253
/*
22462254
* [GRAMMAR]
22472255
* columnAttribute:
@@ -2271,10 +2279,10 @@ private function get_default_value( WP_Parser_Node $node, string $data_type, str
22712279
// A signed number, such as "-5", has no "literal" child node.
22722280
// Like MySQL, drop the unary plus, e.g., "+5" becomes "5".
22732281
$number = ltrim( $this->get_value( $signed_literal ), '+' );
2274-
$default = $this->normalize_literal_default( $number, $data_type, $column_name );
2282+
$default = $this->normalize_literal_default( $number, $data_type, $column_name, $numeric_precision );
22752283
return $this->get_temporal_zero_value( $data_type, $default, $datetime_precision ) ?? $default;
22762284
}
2277-
return $this->get_literal_default( $literal, $data_type, $column_name, $datetime_precision );
2285+
return $this->get_literal_default( $literal, $data_type, $column_name, $datetime_precision, $numeric_precision );
22782286
}
22792287

22802288
// 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
22932301
* @param string $data_type The column data type as stored in information schema.
22942302
* @param string $column_name The column name.
22952303
* @param int|null $datetime_precision The column fractional seconds precision.
2304+
* @param int|null $numeric_precision The column numeric precision. For BIT, the width in bits.
22962305
* @return string|null The default value as stored in information schema.
22972306
*/
2298-
private function get_literal_default( WP_Parser_Node $literal, string $data_type, string $column_name, ?int $datetime_precision ): ?string {
2307+
private function get_literal_default( WP_Parser_Node $literal, string $data_type, string $column_name, ?int $datetime_precision, ?int $numeric_precision ): ?string {
22992308
// DEFAULT NULL
23002309
if ( $literal->has_child_node( 'nullLiteral' ) ) {
23012310
return null;
@@ -2311,7 +2320,7 @@ private function get_literal_default( WP_Parser_Node $literal, string $data_type
23112320
$bool_value = $bool_literal->has_child_token( WP_MySQL_Lexer::TRUE_SYMBOL ) ? '1' : '0';
23122321
$default = 'bit' === $data_type ? "b'{$bool_value}'" : $bool_value;
23132322
} else {
2314-
$default = $this->normalize_literal_default( $this->get_value( $literal ), $data_type, $column_name );
2323+
$default = $this->normalize_literal_default( $this->get_value( $literal ), $data_type, $column_name, $numeric_precision );
23152324
}
23162325

23172326
/*
@@ -2328,19 +2337,22 @@ private function get_literal_default( WP_Parser_Node $literal, string $data_type
23282337
/**
23292338
* Normalize a literal default value for the column data type.
23302339
*
2331-
* @param string $default_value The literal default value.
2332-
* @param string $data_type The column data type as stored in information schema.
2333-
* @param string $column_name The column name.
2334-
* @return string The default value as stored in information schema.
2340+
* @param string $default_value The literal default value.
2341+
* @param string $data_type The column data type as stored in information schema.
2342+
* @param string $column_name The column name.
2343+
* @param int|null $numeric_precision The column numeric precision. For BIT, the width in bits.
2344+
* @return string The default value as stored in information schema.
23352345
*/
2336-
private function normalize_literal_default( string $default_value, string $data_type, string $column_name ): string {
2346+
private function normalize_literal_default( string $default_value, string $data_type, string $column_name, ?int $numeric_precision ): string {
23372347
if ( 'bit' === $data_type ) {
23382348
/*
23392349
* @TODO: Validate and normalize defaults from their AST and the full
23402350
* column definition before storing them in the information schema.
23412351
*/
23422352
$bit_default = $this->get_bit_default( $default_value );
2343-
if ( null === $bit_default ) {
2353+
2354+
// The value must fit the column width. The "b''" wrapper takes 3 bytes.
2355+
if ( null === $bit_default || strlen( $bit_default ) - 3 > $numeric_precision ) {
23442356
throw WP_SQLite_Information_Schema_Exception::invalid_default_value( $column_name );
23452357
}
23462358
return $bit_default;
@@ -2439,6 +2451,19 @@ private function get_bit_default( string $default_value ): ?string {
24392451
return "b'0'";
24402452
}
24412453

2454+
// Hex literal, e.g. x'05' or 0x05. Convert it to a bit literal digit by
2455+
// digit, as a value of 64 bits doesn't fit into an integer.
2456+
if (
2457+
preg_match( "/\Ax'([0-9a-f]*)'\z/", $value, $matches )
2458+
|| preg_match( '/\A0x([0-9a-f]+)\z/', $value, $matches )
2459+
) {
2460+
$value = "b'";
2461+
foreach ( str_split( $matches[1] ) as $digit ) {
2462+
$value .= sprintf( '%04b', hexdec( $digit ) );
2463+
}
2464+
$value .= "'";
2465+
}
2466+
24422467
// Bit literal, e.g. b'101' or 0b101.
24432468
if (
24442469
preg_match( "/\Ab'([01]*)'\z/", $value, $matches )
@@ -2448,14 +2473,6 @@ private function get_bit_default( string $default_value ): ?string {
24482473
return "b'" . ( '' === $bits ? '0' : $bits ) . "'";
24492474
}
24502475

2451-
// Hex literal, e.g. x'05' or 0x05.
2452-
if (
2453-
preg_match( "/\Ax'([0-9a-f]*)'\z/", $value, $matches )
2454-
|| preg_match( '/\A0x([0-9a-f]+)\z/', $value, $matches )
2455-
) {
2456-
return "b'" . decbin( hexdec( $matches[1] ) ) . "'";
2457-
}
2458-
24592476
// Non-negative decimal, e.g. 5, or a numeric string literal such as '0'.
24602477
if ( is_numeric( $value ) && $value >= 0 ) {
24612478
return "b'" . decbin( (int) $value ) . "'";
@@ -2913,7 +2930,9 @@ private function get_column_numeric_attributes( WP_Parser_Node $node, string $da
29132930

29142931
// For bit columns, we need to check the precision.
29152932
if ( 'bit' === $data_type ) {
2916-
$field_length = $node->get_first_descendant_node( 'fieldLength' );
2933+
// Search only the data type. An expression in the column definition
2934+
// can contain a length as well, e.g. "CAST(... AS CHAR(10))".
2935+
$field_length = $node->get_first_descendant_node( 'dataType' )->get_first_descendant_node( 'fieldLength' );
29172936
if ( null === $field_length ) {
29182937
return array( 1, null );
29192938
}
@@ -2948,6 +2967,28 @@ private function get_column_numeric_attributes( WP_Parser_Node $node, string $da
29482967
return array( null, null );
29492968
}
29502969

2970+
/**
2971+
* Check that the width of a BIT column is 1 to 64 bits.
2972+
*
2973+
* @param string $column_name The column name.
2974+
* @param int $width The column width in bits.
2975+
* @throws WP_SQLite_Information_Schema_Exception When the width is not valid.
2976+
*/
2977+
private function validate_bit_width( string $column_name, int $width ): void {
2978+
if ( 0 === $width ) {
2979+
throw WP_SQLite_Information_Schema_Exception::invalid_column_size( $column_name );
2980+
}
2981+
2982+
if ( $width > 64 ) {
2983+
// MySQL reports a different limit when the width doesn't fit in 32 bits.
2984+
$max_width = 64;
2985+
if ( $width > 4294967295 ) {
2986+
$max_width = 4294967295;
2987+
}
2988+
throw WP_SQLite_Information_Schema_Exception::display_width_out_of_range( $column_name, $max_width );
2989+
}
2990+
}
2991+
29512992
/**
29522993
* Extract column date/time precision from the "columnDefinition" or "fieldDefinition" AST node.
29532994
*

‎packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-exception.php‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ class WP_SQLite_Information_Schema_Exception extends Exception {
1818
const TYPE_CONSTRAINT_DOES_NOT_EXIST = 'constraint-does-not-exist';
1919
const TYPE_MULTIPLE_CONSTRAINTS_WITH_NAME = 'multiple-constraints-with-name';
2020
const TYPE_INVALID_DEFAULT_VALUE = 'invalid-default-value';
21+
const TYPE_INVALID_COLUMN_SIZE = 'invalid-column-size';
22+
const TYPE_DISPLAY_WIDTH_OUT_OF_RANGE = 'display-width-out-of-range';
2123

2224
/**
2325
* The exception type.
@@ -185,4 +187,36 @@ public static function invalid_default_value( string $column_name ): WP_SQLite_I
185187
array( 'column_name' => $column_name )
186188
);
187189
}
190+
191+
/**
192+
* Create an invalid column size exception.
193+
*
194+
* @param string $column_name The name of the affected column.
195+
* @return self The exception instance.
196+
*/
197+
public static function invalid_column_size( string $column_name ): WP_SQLite_Information_Schema_Exception {
198+
return new self(
199+
self::TYPE_INVALID_COLUMN_SIZE,
200+
sprintf( "Invalid size for column '%s'.", $column_name ),
201+
array( 'column_name' => $column_name )
202+
);
203+
}
204+
205+
/**
206+
* Create a display width out of range exception.
207+
*
208+
* @param string $column_name The name of the affected column.
209+
* @param int $max_width The maximum display width.
210+
* @return self The exception instance.
211+
*/
212+
public static function display_width_out_of_range( string $column_name, int $max_width ): WP_SQLite_Information_Schema_Exception {
213+
return new self(
214+
self::TYPE_DISPLAY_WIDTH_OUT_OF_RANGE,
215+
sprintf( "Display width out of range for column '%s' (max = %d).", $column_name, $max_width ),
216+
array(
217+
'column_name' => $column_name,
218+
'max_width' => $max_width,
219+
)
220+
);
221+
}
188222
}

0 commit comments

Comments
 (0)