Skip to content

Commit d2262de

Browse files
chubes4JanJakes
authored andcommitted
Normalize zero defaults of temporal columns
MySQL stores a numeric zero default of a temporal column, such as DEFAULT 0 on a TIMESTAMP column, as its zero value, e.g. '0000-00-00 00:00:00'. The driver stored it verbatim, so SHOW CREATE TABLE emitted DEFAULT '0', which MySQL rejects in strict SQL mode. Normalize these defaults when recording column definitions, and repair defaults stored by older driver versions when the database is configured.
1 parent 503958e commit d2262de

3 files changed

Lines changed: 245 additions & 14 deletions

File tree

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ public function configure_database(): void {
8282
$this->ensure_global_variables_table();
8383
$this->schema_builder->ensure_information_schema_tables();
8484
$this->schema_reconstructor->ensure_correct_information_schema();
85+
$this->schema_builder->normalize_temporal_zero_defaults();
8586
$this->save_current_driver_version();
8687
$this->ensure_database_data();
8788
} catch ( Throwable $e ) {

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

Lines changed: 104 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,46 @@ public function ensure_information_schema_tables(): void {
413413
}
414414
}
415415

416+
/**
417+
* Normalize numeric zero defaults of temporal columns in the information schema.
418+
*
419+
* Older driver versions stored defaults such as "DEFAULT 0" of a TIMESTAMP
420+
* column verbatim. MySQL stores them as a canonical zero value, such as
421+
* "0000-00-00 00:00:00", and "SHOW CREATE TABLE" must emit that value for
422+
* the output to be accepted by MySQL in strict SQL mode.
423+
*/
424+
public function normalize_temporal_zero_defaults(): void {
425+
$columns_table = $this->connection->quote_identifier( $this->get_table_name( false, 'columns' ) );
426+
$columns = $this->connection->query(
427+
sprintf(
428+
"SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, COLUMN_TYPE, COLUMN_DEFAULT
429+
FROM %s
430+
WHERE DATA_TYPE IN ('date', 'time', 'datetime', 'timestamp', 'year')
431+
AND COLUMN_DEFAULT IS NOT NULL",
432+
$columns_table
433+
)
434+
)->fetchAll( PDO::FETCH_ASSOC ); // phpcs:ignore WordPress.DB.RestrictedClasses.mysql__PDO
435+
436+
foreach ( $columns as $column ) {
437+
$default = $this->get_temporal_zero_default(
438+
(string) $column['COLUMN_DEFAULT'],
439+
$column['DATA_TYPE'],
440+
$column['COLUMN_TYPE']
441+
);
442+
if ( null === $default || $default === $column['COLUMN_DEFAULT'] ) {
443+
continue;
444+
}
445+
446+
$this->connection->query(
447+
sprintf(
448+
'UPDATE %s SET COLUMN_DEFAULT = ? WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ?',
449+
$columns_table
450+
),
451+
array( $default, $column['TABLE_SCHEMA'], $column['TABLE_NAME'], $column['COLUMN_NAME'] )
452+
);
453+
}
454+
}
455+
416456
/**
417457
* Get the definition and data of a computed information schema table.
418458
*
@@ -1028,7 +1068,7 @@ private function record_alter_column_default(
10281068
): void {
10291069
$columns_table = $this->get_table_name( $table_is_temporary, 'columns' );
10301070
$column = $this->connection->query(
1031-
'SELECT DATA_TYPE, IS_NULLABLE, EXTRA FROM ' . $this->connection->quote_identifier( $columns_table ) . '
1071+
'SELECT DATA_TYPE, COLUMN_TYPE, IS_NULLABLE, EXTRA FROM ' . $this->connection->quote_identifier( $columns_table ) . '
10321072
WHERE table_schema = ? AND table_name = ? AND column_name = ?',
10331073
array( self::SAVED_DATABASE_NAME, $table_name, $column_name )
10341074
)->fetch( PDO::FETCH_ASSOC );
@@ -1053,8 +1093,8 @@ private function record_alter_column_default(
10531093
$expression = $node->get_first_child_node( 'exprWithParentheses' );
10541094
$literal = $expression ? $this->get_parenthesized_default_literal( $expression ) : null;
10551095
$default = $literal
1056-
? $this->get_literal_default( $literal, $column['DATA_TYPE'], $column_name )
1057-
: $this->get_default_value( $node, $column['DATA_TYPE'], $column_name );
1096+
? $this->get_literal_default( $literal, $column['DATA_TYPE'], $column_name, $column['COLUMN_TYPE'] )
1097+
: $this->get_default_value( $node, $column['DATA_TYPE'], $column_name, $column['COLUMN_TYPE'] );
10581098
if ( null === $default && 'NO' === $column['IS_NULLABLE'] ) {
10591099
throw WP_SQLite_Information_Schema_Exception::invalid_default_value( $column_name );
10601100
}
@@ -1628,7 +1668,7 @@ private function record_drop_check_constraint(
16281668
private function extract_column_data( string $table_name, string $column_name, WP_Parser_Node $node, int $position ): array {
16291669
list ( $data_type, $column_type ) = $this->get_column_data_types( $node );
16301670

1631-
$default = $this->get_column_default( $node, $data_type, $column_name );
1671+
$default = $this->get_column_default( $node, $data_type, $column_name, $column_type );
16321672
$nullable = $this->get_column_nullable( $node );
16331673
$key = $this->get_column_key( $node );
16341674
$extra = $this->get_column_extra( $node );
@@ -2173,9 +2213,10 @@ private function get_table_comment( WP_Parser_Node $node ): string {
21732213
* @param WP_Parser_Node $node The "columnDefinition" or "fieldDefinition" AST node.
21742214
* @param string $data_type The column data type as stored in information schema.
21752215
* @param string $column_name The column name.
2216+
* @param string $column_type The column type as stored in information schema.
21762217
* @return string|null The column default as stored in information schema.
21772218
*/
2178-
private function get_column_default( WP_Parser_Node $node, string $data_type, string $column_name ): ?string {
2219+
private function get_column_default( WP_Parser_Node $node, string $data_type, string $column_name, string $column_type ): ?string {
21792220
$default_attr = null;
21802221
foreach ( $node->get_descendant_nodes( 'columnAttribute' ) as $attr ) {
21812222
if ( $attr->has_child_token( WP_MySQL_Lexer::DEFAULT_SYMBOL ) ) {
@@ -2186,7 +2227,7 @@ private function get_column_default( WP_Parser_Node $node, string $data_type, st
21862227
if ( null === $default_attr ) {
21872228
return null;
21882229
}
2189-
return $this->get_default_value( $default_attr, $data_type, $column_name );
2230+
return $this->get_default_value( $default_attr, $data_type, $column_name, $column_type );
21902231
}
21912232

21922233
/**
@@ -2195,9 +2236,10 @@ private function get_column_default( WP_Parser_Node $node, string $data_type, st
21952236
* @param WP_Parser_Node $node The "columnAttribute" or "alterListItem" AST node.
21962237
* @param string $data_type The column data type as stored in information schema.
21972238
* @param string $column_name The column name.
2239+
* @param string $column_type The column type as stored in information schema.
21982240
* @return string|null The default value as stored in information schema.
21992241
*/
2200-
private function get_default_value( WP_Parser_Node $node, string $data_type, string $column_name ): ?string {
2242+
private function get_default_value( WP_Parser_Node $node, string $data_type, string $column_name, string $column_type ): ?string {
22012243
/*
22022244
* [GRAMMAR]
22032245
* columnAttribute:
@@ -2227,9 +2269,9 @@ private function get_default_value( WP_Parser_Node $node, string $data_type, str
22272269
// A signed number, such as "-5", has no "literal" child node.
22282270
// Like MySQL, drop the unary plus, e.g., "+5" becomes "5".
22292271
$number = ltrim( $this->get_value( $signed_literal ), '+' );
2230-
return $this->normalize_literal_default( $number, $data_type, $column_name );
2272+
return $this->normalize_literal_default( $number, $data_type, $column_name, $column_type );
22312273
}
2232-
return $this->get_literal_default( $literal, $data_type, $column_name );
2274+
return $this->get_literal_default( $literal, $data_type, $column_name, $column_type );
22332275
}
22342276

22352277
// DEFAULT (expression) - MySQL 8.0.13+ supports exprWithParentheses
@@ -2247,9 +2289,10 @@ private function get_default_value( WP_Parser_Node $node, string $data_type, str
22472289
* @param WP_Parser_Node $literal The "literal" AST node.
22482290
* @param string $data_type The column data type as stored in information schema.
22492291
* @param string $column_name The column name.
2292+
* @param string $column_type The column type as stored in information schema.
22502293
* @return string|null The default value as stored in information schema.
22512294
*/
2252-
private function get_literal_default( WP_Parser_Node $literal, string $data_type, string $column_name ): ?string {
2295+
private function get_literal_default( WP_Parser_Node $literal, string $data_type, string $column_name, string $column_type ): ?string {
22532296
// DEFAULT NULL
22542297
if ( $literal->has_child_node( 'nullLiteral' ) ) {
22552298
return null;
@@ -2262,7 +2305,7 @@ private function get_literal_default( WP_Parser_Node $literal, string $data_type
22622305
return 'bit' === $data_type ? "b'{$bool_value}'" : $bool_value;
22632306
}
22642307

2265-
return $this->normalize_literal_default( $this->get_value( $literal ), $data_type, $column_name );
2308+
return $this->normalize_literal_default( $this->get_value( $literal ), $data_type, $column_name, $column_type );
22662309
}
22672310

22682311
/**
@@ -2271,9 +2314,16 @@ private function get_literal_default( WP_Parser_Node $literal, string $data_type
22712314
* @param string $default_value The literal default value.
22722315
* @param string $data_type The column data type as stored in information schema.
22732316
* @param string $column_name The column name.
2317+
* @param string $column_type The column type as stored in information schema.
22742318
* @return string The default value as stored in information schema.
22752319
*/
2276-
private function normalize_literal_default( string $default_value, string $data_type, string $column_name ): string {
2320+
private function normalize_literal_default( string $default_value, string $data_type, string $column_name, string $column_type ): string {
2321+
// Numeric zero temporal defaults, such as "DEFAULT 0" of a DATETIME column.
2322+
$zero_default = $this->get_temporal_zero_default( $default_value, $data_type, $column_type );
2323+
if ( null !== $zero_default ) {
2324+
return $zero_default;
2325+
}
2326+
22772327
if ( 'bit' === $data_type ) {
22782328
/*
22792329
* @TODO: Validate and normalize defaults from their AST and the full
@@ -2287,8 +2337,9 @@ private function normalize_literal_default( string $default_value, string $data_
22872337
}
22882338

22892339
/*
2290-
* @TODO: Non-BIT literal defaults are currently stored verbatim. To
2291-
* match MySQL, they should be normalized. For example:
2340+
* @TODO: Other non-BIT literal defaults (apart from numeric zero temporal
2341+
* defaults handled above) are currently stored verbatim. To match MySQL,
2342+
* they should be normalized. For example:
22922343
* - BINARY/VARBINARY defaults stored as 0x hex literals.
22932344
* - Hex and bit literals coerced to raw bytes for text columns and to
22942345
* their decimal value for numeric columns.
@@ -2298,6 +2349,45 @@ private function normalize_literal_default( string $default_value, string $data_
22982349
return $default_value;
22992350
}
23002351

2352+
/**
2353+
* Normalize a numeric zero default of a temporal column to its MySQL zero value.
2354+
*
2355+
* MySQL stores "DEFAULT 0" of a DATETIME column as "0000-00-00 00:00:00",
2356+
* and it rejects the quoted form "DEFAULT '0'" in strict SQL mode. Other
2357+
* temporal defaults are not handled here.
2358+
*
2359+
* @param string $default_value The default value.
2360+
* @param string $data_type The column data type as stored in information schema.
2361+
* @param string $column_type The column type as stored in information schema.
2362+
* @return string|null The zero value, or null when the default is not a numeric zero
2363+
* or the column is not a temporal column.
2364+
*/
2365+
private function get_temporal_zero_default( string $default_value, string $data_type, string $column_type ): ?string {
2366+
if ( ! preg_match( '/\A[+-]?(?:0+(?:\.0*)?|\.0+)\z/', $default_value ) ) {
2367+
return null;
2368+
}
2369+
2370+
// Fractional seconds precision, e.g., "datetime(3)".
2371+
$fraction = '';
2372+
if ( preg_match( '/\((\d+)\)/', $column_type, $matches ) && (int) $matches[1] > 0 ) {
2373+
$fraction = '.' . str_repeat( '0', (int) $matches[1] );
2374+
}
2375+
2376+
switch ( $data_type ) {
2377+
case 'date':
2378+
return '0000-00-00';
2379+
case 'year':
2380+
return '0000';
2381+
case 'time':
2382+
return '00:00:00' . $fraction;
2383+
case 'datetime':
2384+
case 'timestamp':
2385+
return '0000-00-00 00:00:00' . $fraction;
2386+
default:
2387+
return null;
2388+
}
2389+
}
2390+
23012391
/**
23022392
* Normalize a BIT default value to a MySQL bit literal.
23032393
*

‎packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php‎

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6333,6 +6333,146 @@ public function testUnionAll(): void {
63336333
);
63346334
}
63356335

6336+
public function testShowCreateTableWithTemporalZeroDefaults(): void {
6337+
$this->assertQuery(
6338+
'CREATE TABLE _tmp_table (
6339+
col_timestamp TIMESTAMP NOT NULL DEFAULT 0,
6340+
col_datetime DATETIME NOT NULL DEFAULT 0,
6341+
col_date DATE NOT NULL DEFAULT 0,
6342+
col_time TIME NOT NULL DEFAULT 0,
6343+
col_year YEAR NOT NULL DEFAULT 0,
6344+
col_datetime_fsp DATETIME(3) NOT NULL DEFAULT 0,
6345+
col_timestamp_fsp TIMESTAMP(6) NOT NULL DEFAULT 0,
6346+
col_time_fsp TIME(2) NOT NULL DEFAULT 0,
6347+
col_decimal_zero DATETIME NOT NULL DEFAULT 0.0,
6348+
col_negative_zero DATETIME NOT NULL DEFAULT -0,
6349+
col_positive_zero DATETIME NOT NULL DEFAULT +0,
6350+
col_padded_zero DATETIME NOT NULL DEFAULT 00,
6351+
col_int INT NOT NULL DEFAULT 0
6352+
)'
6353+
);
6354+
6355+
$this->assertQuery( 'SHOW CREATE TABLE _tmp_table' );
6356+
$this->assertSame(
6357+
implode(
6358+
"\n",
6359+
array(
6360+
'CREATE TABLE `_tmp_table` (',
6361+
" `col_timestamp` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',",
6362+
" `col_datetime` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',",
6363+
" `col_date` date NOT NULL DEFAULT '0000-00-00',",
6364+
" `col_time` time NOT NULL DEFAULT '00:00:00',",
6365+
" `col_year` year NOT NULL DEFAULT '0000',",
6366+
" `col_datetime_fsp` datetime(3) NOT NULL DEFAULT '0000-00-00 00:00:00.000',",
6367+
" `col_timestamp_fsp` timestamp(6) NOT NULL DEFAULT '0000-00-00 00:00:00.000000',",
6368+
" `col_time_fsp` time(2) NOT NULL DEFAULT '00:00:00.00',",
6369+
" `col_decimal_zero` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',",
6370+
" `col_negative_zero` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',",
6371+
" `col_positive_zero` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',",
6372+
" `col_padded_zero` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',",
6373+
" `col_int` int NOT NULL DEFAULT '0'",
6374+
') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci',
6375+
)
6376+
),
6377+
$this->last_result[0]->{'Create Table'}
6378+
);
6379+
6380+
$this->assertQuery(
6381+
"SELECT column_name, column_default FROM information_schema.columns WHERE table_name = '_tmp_table' AND column_name IN ('col_timestamp', 'col_date', 'col_time_fsp') ORDER BY ordinal_position"
6382+
);
6383+
$this->assertEquals(
6384+
array(
6385+
(object) array(
6386+
'COLUMN_NAME' => 'col_timestamp',
6387+
'COLUMN_DEFAULT' => '0000-00-00 00:00:00',
6388+
),
6389+
(object) array(
6390+
'COLUMN_NAME' => 'col_date',
6391+
'COLUMN_DEFAULT' => '0000-00-00',
6392+
),
6393+
(object) array(
6394+
'COLUMN_NAME' => 'col_time_fsp',
6395+
'COLUMN_DEFAULT' => '00:00:00.00',
6396+
),
6397+
),
6398+
$this->last_result
6399+
);
6400+
}
6401+
6402+
public function testInsertUsesTemporalZeroDefaults(): void {
6403+
$this->assertQuery(
6404+
'CREATE TABLE _tmp_table (
6405+
id INT NOT NULL,
6406+
created_at TIMESTAMP NOT NULL DEFAULT 0,
6407+
updated_on DATE NOT NULL DEFAULT 0
6408+
)'
6409+
);
6410+
$this->assertQuery( 'INSERT INTO _tmp_table (id) VALUES (1)' );
6411+
$this->assertQuery( 'SELECT created_at, updated_on FROM _tmp_table' );
6412+
$this->assertEquals(
6413+
array(
6414+
(object) array(
6415+
'created_at' => '0000-00-00 00:00:00',
6416+
'updated_on' => '0000-00-00',
6417+
),
6418+
),
6419+
$this->last_result
6420+
);
6421+
}
6422+
6423+
public function testAlterTableWithTemporalZeroDefaults(): void {
6424+
$this->assertQuery( 'CREATE TABLE _tmp_table (id INT NOT NULL, modified_at DATETIME NOT NULL)' );
6425+
$this->assertQuery( 'ALTER TABLE _tmp_table ADD COLUMN created_at TIMESTAMP NOT NULL DEFAULT 0' );
6426+
$this->assertQuery( 'ALTER TABLE _tmp_table MODIFY COLUMN modified_at DATETIME NOT NULL DEFAULT 0' );
6427+
6428+
$this->assertQuery( 'SHOW CREATE TABLE _tmp_table' );
6429+
$this->assertSame(
6430+
implode(
6431+
"\n",
6432+
array(
6433+
'CREATE TABLE `_tmp_table` (',
6434+
' `id` int NOT NULL,',
6435+
" `modified_at` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',",
6436+
" `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'",
6437+
') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci',
6438+
)
6439+
),
6440+
$this->last_result[0]->{'Create Table'}
6441+
);
6442+
}
6443+
6444+
public function testConfigurationNormalizesStoredTemporalZeroDefaults(): void {
6445+
$this->assertQuery( 'CREATE TABLE _tmp_table (id INT NOT NULL DEFAULT 0, created_at TIMESTAMP NOT NULL DEFAULT 0, label VARCHAR(20) NOT NULL DEFAULT 0)' );
6446+
6447+
// Simulate a database configured by an older driver version that
6448+
// stored numeric zero temporal defaults verbatim.
6449+
$this->sqlite->exec( "UPDATE _wp_sqlite_mysql_information_schema_columns SET column_default = '0' WHERE table_name = '_tmp_table'" );
6450+
$this->sqlite->exec( "UPDATE _wp_sqlite_global_variables SET value = '0.0.0' WHERE name = '_wp_sqlite_driver_version'" );
6451+
6452+
$this->engine = new WP_MySQL_On_SQLite(
6453+
'mysql-on-sqlite:dbname=wp',
6454+
null,
6455+
null,
6456+
array( 'sqlite_pdo' => $this->sqlite )
6457+
);
6458+
$this->engine->setAttribute( PDO::ATTR_STRINGIFY_FETCHES, true );
6459+
6460+
$this->assertQuery( 'SHOW CREATE TABLE _tmp_table' );
6461+
$this->assertSame(
6462+
implode(
6463+
"\n",
6464+
array(
6465+
'CREATE TABLE `_tmp_table` (',
6466+
" `id` int NOT NULL DEFAULT '0',",
6467+
" `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',",
6468+
" `label` varchar(20) NOT NULL DEFAULT '0'",
6469+
') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci',
6470+
)
6471+
),
6472+
$this->last_result[0]->{'Create Table'}
6473+
);
6474+
}
6475+
63366476
public function testShowCreateTableWithEmptyDatetimeDefault() {
63376477
$this->assertQuery(
63386478
"CREATE TABLE _tmp_table (

0 commit comments

Comments
 (0)