Skip to content
Open
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
31 changes: 29 additions & 2 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 @@ -6437,6 +6437,15 @@ private function translate_update_list( string $table_name, WP_Parser_Node $pare
if ( null === $expr ) {
// Emulate "column = DEFAULT".
$value = null === $default ? 'NULL' : $this->format_sqlite_column_default( $column_info );

/*
* A stored YEAR default is already a year, such as '2000' or '0000',
* so don't read it as a string, which would turn '0' into 2000.
* Older driver versions stored both DEFAULT 0 and DEFAULT '0' as '0'.
*/
if ( null !== $default && 'year' === strtolower( $data_type ) ) {
$value = sprintf( 'CAST(%s AS INTEGER)', $value );
}
} else {
$value = $this->translate( $expr );
}
Expand Down Expand Up @@ -7079,20 +7088,38 @@ private function cast_value_for_saving(
* The YEAR type in MySQL only uses 1 byte and therefore
* covers only 256 values from 1901 to 2155 included.
* Additionally:
* - Numbers from 0 to 69 correspond to years 2000 to 2069.
* - Numbers from 1 to 69 correspond to years 2001 to 2069.
* - Numbers from 70 to 99 correspond to years 1970 to 1999.
* - The number 0 is the year 0000.
* - A string whose number rounds to 0 is the year 2000, unless
* it is 4 bytes long. E.g., '0', '00', or '0.0' is 2000, but
* '0000' is 0000. Like MySQL, the conversion skips leading
* spaces and tabs, and it needs a number at the start.
*/
return sprintf(
"(
SELECT CASE
WHEN value IS NULL THEN NULL
WHEN typeof(raw) = 'text'
AND ROUND(CAST(raw AS REAL)) = 0
AND LENGTH(CAST(raw AS BLOB)) <> 4
AND (
trimmed GLOB '[0-9]*'
OR trimmed GLOB '.[0-9]*'
OR trimmed GLOB '[+-][0-9]*'
OR trimmed GLOB '[+-].[0-9]*'
)
THEN 2000
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
WHEN value = 0 THEN '0000'
WHEN value BETWEEN 1901 AND 2155 THEN value
WHEN value BETWEEN 1 AND 69 THEN 2000 + value
WHEN value BETWEEN 70 AND 99 THEN 1900 + value
ELSE %s
END
FROM (SELECT CAST(%s AS INTEGER) AS value)
FROM (
SELECT raw, CAST(raw AS INTEGER) AS value, LTRIM(raw, ' ' || CHAR(9)) AS trimmed
FROM (SELECT %s AS raw)
)
)",
$is_strict_mode
? sprintf( "THROW('Out of range value: ''' || %s || '''')", $translated_value )
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,16 @@ class WP_SQLite_Information_Schema_Builder {
*/
private $temporary_information_schema_exists = false;

/**
* Whether to keep the string zero defaults of YEAR columns as written.
*
* This is used when reconstructing the information schema of an existing
* SQLite table, as the table keeps such defaults as written as well.
*
* @var bool
*/
private $keep_year_string_zero_defaults = false;

/**
* An instance of the SQLite connection.
*
Expand Down Expand Up @@ -499,6 +509,24 @@ public function ensure_temporary_information_schema_tables(): void {
$this->temporary_information_schema_exists = true;
}

/**
* Record the information schema of an existing SQLite table.
*
* This works like record_create_table(), but it keeps the string zero
* defaults of YEAR columns, such as '0', as written. Older driver versions
* stored such defaults as written, so the SQLite table uses them as well.
*
* @param WP_Parser_Node $node The "createStatement" AST node with "createTable" child.
*/
public function record_reconstructed_table( WP_Parser_Node $node ): void {
$this->keep_year_string_zero_defaults = true;
try {
$this->record_create_table( $node );
} finally {
$this->keep_year_string_zero_defaults = false;
}
}

/**
* Analyze CREATE TABLE statement and record data in the information schema.
*
Expand Down Expand Up @@ -2286,10 +2314,13 @@ private function get_literal_default( WP_Parser_Node $literal, string $data_type
/*
* Normalize numeric zero defaults to MySQL's temporal zero values.
* Also normalize string zeros, even where strict MySQL rejects them.
* Preserve YEAR strings '0' and '00', which MySQL interprets as 2000.
* YEAR strings that are zero follow their own rule, e.g., '0' is 2000.
*/
if ( 'year' === $data_type && $literal->has_child_node( 'textLiteral' ) ) {
return $default;
if ( $this->keep_year_string_zero_defaults ) {
return $default;
}
return $this->get_year_string_zero_value( $default ) ?? $default;
}
return $this->get_temporal_zero_value( $data_type, $default, $datetime_precision ) ?? $default;
}
Expand Down Expand Up @@ -2328,6 +2359,25 @@ private function normalize_literal_default( string $default_value, string $data_
return $default_value;
}

/**
* Get the year of a YEAR string default when the string is zero.
*
* MySQL stores a string whose number rounds to 0 as the year 2000, unless
* the string is 4 bytes long. For example, '0', '00', and '0.4' are 2000,
* while '0000' is 0000. Spaces and tabs around the number are allowed, and
* they count toward the length. The number 0, which is not a string, is 0000.
*
* @param string $default_value The YEAR column default value of a string literal.
* @return string|null The year, or null when the string is not a number that rounds to 0.
*/
private function get_year_string_zero_value( string $default_value ): ?string {
$number = trim( $default_value, " \t" );
if ( trim( $number ) !== $number || ! is_numeric( $number ) || 0.0 !== round( (float) $number ) ) {
return null;
}
return 4 === strlen( $default_value ) ? '0000' : '2000';
}

/**
* Get the zero value of a temporal column when its default is zero.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public function ensure_correct_information_schema(): void {
*/
$this->record_drop_table( $table );

$this->schema_builder->record_create_table( $ast );
$this->schema_builder->record_reconstructed_table( $ast );
}

// Remove information schema records for tables that don't exist.
Expand Down
193 changes: 190 additions & 3 deletions packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php
Original file line number Diff line number Diff line change
Expand Up @@ -7154,8 +7154,8 @@ public function testShowCreateTableWithTemporalZeroDefaults(): void {
" `col_string_zero` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',",
" `col_time_string_zero` time NOT NULL DEFAULT '00:00:00',",
" `col_year_false` year NOT NULL DEFAULT '0000',",
" `col_year_string_zero` year NOT NULL DEFAULT '0',",
" `col_year_string_double_zero` year NOT NULL DEFAULT '00',",
" `col_year_string_zero` year NOT NULL DEFAULT '2000',",
" `col_year_string_double_zero` year NOT NULL DEFAULT '2000',",
' `col_expression` datetime NOT NULL DEFAULT (0),',
" `col_int` int NOT NULL DEFAULT '0',",
" `col_varchar` varchar(10) NOT NULL DEFAULT '0',",
Expand Down Expand Up @@ -7225,6 +7225,193 @@ public function testInsertUsesTemporalZeroDefaults(): void {
);
}

/**
* @dataProvider yearZeroValues
*/
public function testSavesYearZeroValues( string $value, string $expected_year ): void {
$this->assertQuery( 'CREATE TABLE _tmp_table (id INT NOT NULL, y YEAR, source VARCHAR(10))' );

// A number stored in the VARCHAR column becomes a string, so only strings are read from it.
$is_string = "'" === $value[0] || 0 === strpos( $value, 'CONCAT(' );

foreach ( array( 'STRICT_TRANS_TABLES', '' ) as $sql_mode ) {
$this->assertQuery( "SET sql_mode = '$sql_mode'" );
$this->assertQuery( 'DELETE FROM _tmp_table' );

// INSERT and UPDATE with the value.
$this->assertQuery( "INSERT INTO _tmp_table (id, y) VALUES (1, $value)" );
$this->assertQuery( 'INSERT INTO _tmp_table (id, y) VALUES (2, 1999)' );
$this->assertQuery( "UPDATE _tmp_table SET y = $value WHERE id = 2" );

// INSERT ... SELECT and UPDATE with the value read from a column.
if ( $is_string ) {
$this->assertQuery( "INSERT INTO _tmp_table (id, y, source) VALUES (3, 1999, $value)" );
$this->assertQuery( 'UPDATE _tmp_table SET y = source WHERE id = 3' );
$this->assertQuery( 'INSERT INTO _tmp_table (id, y) SELECT 4, source FROM _tmp_table WHERE id = 3' );
}

$this->assertQuery( 'SELECT y FROM _tmp_table ORDER BY id' );
$this->assertSame(
array_fill( 0, $is_string ? 4 : 2, $expected_year ),
array_column( $this->last_result, 'y' ),
"SQL mode: '$sql_mode'"
);
}
}

public static function yearZeroValues(): array {
/*
* MySQL stores a string whose number rounds to 0 as the year 2000, unless
* the string is 4 bytes long. The number 0 is the year 0000.
* The expected values are from MySQL 8.0.46.
*/
return array(
'number 0' => array( '0', '0000' ),
'number 0.4' => array( '0.4', '0000' ),
'number 0e0' => array( '0e0', '0000' ),
'FALSE' => array( 'FALSE', '0000' ),
"'0'" => array( "'0'", '2000' ),
"'00'" => array( "'00'", '2000' ),
"'000'" => array( "'000'", '2000' ),
"'00000'" => array( "'00000'", '2000' ),
"'0.0'" => array( "'0.0'", '2000' ),
"'.0'" => array( "'.0'", '2000' ),
"'0.4'" => array( "'0.4'", '2000' ),
"'0e0'" => array( "'0e0'", '2000' ),
"'-0'" => array( "'-0'", '2000' ),
"'+0'" => array( "'+0'", '2000' ),
"' 0'" => array( "' 0'", '2000' ),
"'0 '" => array( "'0 '", '2000' ),
'tab and 0' => array( "CONCAT(CHAR(9), '0')", '2000' ),
"CONCAT('0', '')" => array( "CONCAT('0', '')", '2000' ),
"'0000'" => array( "'0000'", '0000' ),
"'0.00'" => array( "'0.00'", '0000' ),
"'5'" => array( "'5'", '2005' ),
"'70'" => array( "'70'", '1970' ),
);
}

public function testSavesYearStringsWithoutNumberAsZero(): void {
$this->assertQuery( 'CREATE TABLE _tmp_table (id INT NOT NULL, y YEAR)' );

// MySQL reads these as 0000 in non-strict mode, as no number starts the string.
$this->assertQuery( "SET sql_mode = ''" );
$this->assertQuery(
"INSERT INTO _tmp_table (id, y) VALUES
(1, 'abc'),
(2, ''),
(3, '-'),
(4, CONCAT(CHAR(10), '0')),
(5, '0abc'),
(6, '00abc')"
);

$this->assertQuery( 'SELECT y FROM _tmp_table ORDER BY id' );
$this->assertSame(
array( '0000', '0000', '0000', '0000', '0000', '2000' ),
array_column( $this->last_result, 'y' )
);
}

public function testYearStringZeroDefaults(): void {
$this->assertQuery(
"CREATE TABLE _tmp_table (
id INT NOT NULL,
year_zero YEAR NOT NULL DEFAULT '0',
year_double_zero YEAR NOT NULL DEFAULT '00',
year_decimal_zero YEAR NOT NULL DEFAULT '0.0',
year_padded_zero YEAR NOT NULL DEFAULT ' 0',
year_four_zeros YEAR NOT NULL DEFAULT '0000',
year_four_char_zero YEAR NOT NULL DEFAULT '0.00',
year_number_zero YEAR NOT NULL DEFAULT 0,
year_altered YEAR NOT NULL DEFAULT '1999'
)"
);
$this->assertQuery( "ALTER TABLE _tmp_table ALTER COLUMN year_altered SET DEFAULT '0'" );

$this->assertQuery( 'SHOW CREATE TABLE _tmp_table' );
$this->assertSame(
implode(
"\n",
array(
'CREATE TABLE `_tmp_table` (',
' `id` int NOT NULL,',
" `year_zero` year NOT NULL DEFAULT '2000',",
" `year_double_zero` year NOT NULL DEFAULT '2000',",
" `year_decimal_zero` year NOT NULL DEFAULT '2000',",
" `year_padded_zero` year NOT NULL DEFAULT '2000',",
" `year_four_zeros` year NOT NULL DEFAULT '0000',",
" `year_four_char_zero` year NOT NULL DEFAULT '0000',",
" `year_number_zero` year NOT NULL DEFAULT '0000',",
" `year_altered` year NOT NULL DEFAULT '2000'",
') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci',
)
),
$this->last_result[0]->{'Create Table'}
);

$this->assertQuery(
"SELECT column_name, column_default FROM information_schema.columns
WHERE table_name = '_tmp_table' AND column_name IN ('year_zero', 'year_four_zeros')
ORDER BY ordinal_position"
);
$this->assertEquals(
array(
(object) array(
'COLUMN_NAME' => 'year_zero',
'COLUMN_DEFAULT' => '2000',
),
(object) array(
'COLUMN_NAME' => 'year_four_zeros',
'COLUMN_DEFAULT' => '0000',
),
),
$this->last_result
);

// New rows get the defaults, and so does "column = DEFAULT".
$this->assertQuery( 'INSERT INTO _tmp_table (id) VALUES (1)' );
$this->assertQuery( "INSERT INTO _tmp_table (id, year_zero) VALUES (2, '1999')" );
$this->assertQuery( 'UPDATE _tmp_table SET year_zero = DEFAULT WHERE id = 2' );
$this->assertQuery( 'SELECT * FROM _tmp_table ORDER BY id' );
$expected_row = array(
'year_zero' => '2000',
'year_double_zero' => '2000',
'year_decimal_zero' => '2000',
'year_padded_zero' => '2000',
'year_four_zeros' => '0000',
'year_four_char_zero' => '0000',
'year_number_zero' => '0000',
'year_altered' => '2000',
);
$this->assertEquals(
array(
(object) array_merge( array( 'id' => '1' ), $expected_row ),
(object) array_merge( array( 'id' => '2' ), $expected_row ),
),
$this->last_result
);
}

public function testUpdateToStoredYearZeroDefault(): void {
// Driver 3.1.x and older stored both DEFAULT 0 and DEFAULT '0' of a YEAR column as '0'.
$this->assertQuery( 'CREATE TABLE _tmp_table (id INT PRIMARY KEY, y YEAR NOT NULL DEFAULT 0)' );
$this->sqlite->exec(
"UPDATE _wp_sqlite_mysql_information_schema_columns
SET column_default = '0'
WHERE table_name = '_tmp_table' AND column_name = 'y'"
);
$this->assertQuery( 'OPTIMIZE TABLE _tmp_table' );

// Setting the column to its default still stores 0000, not 2000.
$this->assertQuery( 'INSERT INTO _tmp_table (id, y) VALUES (1, 1999), (2, 1999)' );
$this->assertQuery( 'UPDATE _tmp_table SET y = DEFAULT WHERE id = 1' );
$this->assertQuery( 'INSERT INTO _tmp_table (id, y) VALUES (2, 1999) ON DUPLICATE KEY UPDATE y = DEFAULT' );

$this->assertQuery( 'SELECT y FROM _tmp_table ORDER BY id' );
$this->assertSame( array( '0000', '0000' ), array_column( $this->last_result, 'y' ) );
}

public function testAlterTableWithTemporalZeroDefaults(): void {
$this->assertQuery(
'CREATE TABLE _tmp_table (
Expand Down Expand Up @@ -7266,7 +7453,7 @@ public function testAlterTableWithTemporalZeroDefaults(): void {
" `updated_on` date NOT NULL DEFAULT '0000-00-00',",
" `duration` time(2) NOT NULL DEFAULT '00:00:00.00',",
" `year_number` year NOT NULL DEFAULT '0000',",
" `year_string` year NOT NULL DEFAULT '0',",
" `year_string` year NOT NULL DEFAULT '2000',",
" `parenthesized_zero` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',",
" `false_value` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',",
" `string_zero` time NOT NULL DEFAULT '00:00:00',",
Expand Down
Loading