Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 36 additions & 10 deletions packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php
Original file line number Diff line number Diff line change
Expand Up @@ -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:
/*
Expand Down Expand Up @@ -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 ) ) );
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

// A BLOB column in a STRICT table only accepts a BLOB default.
Expand Down Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
Expand All @@ -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 );
}
Expand Down Expand Up @@ -1669,16 +1670,21 @@ 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 );
$comment = $this->get_column_comment( $node );

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 );

Expand Down Expand Up @@ -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 ) ) {
Expand All @@ -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 );
}

/**
Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand All @@ -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;
Expand All @@ -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 );
}

/*
Expand All @@ -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;
Expand Down Expand Up @@ -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 )
Expand All @@ -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 ) . "'";
Expand Down Expand Up @@ -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 );
}
Expand Down Expand Up @@ -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.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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,
)
);
}
}
Loading
Loading