Skip to content

Commit 958f029

Browse files
chubes4JanJakes
andauthored
Normalize zero defaults of temporal columns (#542)
## Summary A numeric zero default on a temporal column was stored verbatim and emitted as a quoted string: ```sql CREATE TABLE t (created_at TIMESTAMP NOT NULL DEFAULT 0); SHOW CREATE TABLE t; -- `created_at` timestamp NOT NULL DEFAULT '0' (MySQL: '0000-00-00 00:00:00') ``` MySQL rejects `DEFAULT '0'` in strict SQL mode (`ERROR 1067: Invalid default value`), so dumps of these tables don't import. The H5P plugin creates its tables with this pattern, so exports of sites that use it fail. ## Changes Zero defaults of temporal columns now get MySQL's zero values, both in new tables and in existing databases: - **Normalize on write.** `CREATE TABLE` and `ALTER TABLE` store zero defaults of `DATE`, `TIME`, `DATETIME`, `TIMESTAMP`, and `YEAR` columns as MySQL zero values, including fractional seconds precision (`DATETIME(3)` → `'0000-00-00 00:00:00.000'`). This covers all numeric forms, such as `0`, `-0`, `0.0`, `0e0`, and `FALSE`, and it fixes `SHOW CREATE TABLE`, `INFORMATION_SCHEMA.COLUMNS`, and the default that new rows receive. - **Normalize `ALTER COLUMN ... SET DEFAULT`.** Defaults set with `SET DEFAULT`, added in #555, are normalized the same way. This includes a parenthesized literal, such as `SET DEFAULT (0)`, which MySQL also stores as a literal. - **Normalize quoted zeros, except for `YEAR`.** Quoted zeros, such as `DEFAULT '0'`, are normalized the same way, as older driver versions stored them the same as numbers. For `YEAR` columns, MySQL reads the strings `'0'` and `'00'` as the year 2000, so they stay as written. - **Fix `DATETIME_PRECISION`.** `INFORMATION_SCHEMA.COLUMNS` reported `0` for all `TIME(n)`, `DATETIME(n)`, and `TIMESTAMP(n)` columns. It now reports the precision of the column type. - **Repair existing databases.** For databases last configured by driver 3.1.1 or older, the configuration corrects the stored `DATETIME_PRECISION` values, and it changes zero defaults of temporal columns, such as `0`, to the zero values with `ALTER TABLE ... ALTER COLUMN ... SET DEFAULT`. This also recreates the tables, so that new rows get the zero value. This includes tables created by the legacy SQLite driver. The repair runs once, within the configuration transaction, so it either fully succeeds or changes nothing. - **Repair existing rows.** Rows that got such a zero default from older driver versions still store it, such as `'0'`. The repair replaces it with the zero value, so that dumps of these rows import into MySQL in strict SQL mode. The update doesn't run the table's triggers, such as the emulation of `ON UPDATE CURRENT_TIMESTAMP`. - **Report why a table rebuild fails.** `ANALYZE`, `CHECK`, `OPTIMIZE`, and `REPAIR TABLE` reported every general SQLite error as a missing table, so a failed table rebuild could say `Table '…' doesn't exist` for a table that exists. They now report only SQLite's "no such table" error that way, and other errors as SQLite returns them. Values match MySQL 8 output for the same default in `CREATE TABLE` or `ALTER COLUMN ... SET DEFAULT`, in `STRICT_TRANS_TABLES` mode: | Column | `COLUMN_DEFAULT` | | --- | --- | | `TIMESTAMP` / `DATETIME DEFAULT 0` | `0000-00-00 00:00:00` | | `DATE DEFAULT 0` | `0000-00-00` | | `TIME DEFAULT 0` | `00:00:00` | | `YEAR DEFAULT 0` | `0000` | | `DATETIME(3) DEFAULT 0` | `0000-00-00 00:00:00.000` | | `TIMESTAMP(6) DEFAULT 0` | `0000-00-00 00:00:00.000000` | | `TIME(2) DEFAULT 0` | `00:00:00.00` | ## Scope - **Non-zero temporal defaults**, such as `DEFAULT 20200102`, are still stored verbatim. The existing `@TODO` covers them. - **`YEAR` string zeros**, such as `'0'`, stay as written. MySQL reads them as the year 2000, but the driver also stores an inserted `'0'` as `0000`, so both need a separate fix, tracked in #545. Older driver versions stored `YEAR DEFAULT 0` and `YEAR DEFAULT '0'` the same way, so the repair can't tell them apart and leaves them unchanged. - **Recreated tables reset their `AUTO_INCREMENT` counter** to the highest existing ID. This is an existing problem of `ALTER TABLE` and `OPTIMIZE TABLE`, tracked in #544. - **Recreated legacy tables lose `ON UPDATE CURRENT_TIMESTAMP`.** The legacy SQLite driver implemented it with triggers, which a table rebuild drops without replacing them. This is an existing problem of `ALTER TABLE` and `OPTIMIZE TABLE`, tracked in #547. The repair also rebuilds legacy tables that have a temporal zero default, so they lose it as well. ## Testing End to end, the `SHOW CREATE TABLE` output for H5P's `wp_h5p_contents` and `wp_h5p_contents_user_data` imports into MySQL with `sql_mode='STRICT_TRANS_TABLES'`. Before the change, it fails with `ERROR 1067`. See the [verification on a WordPress Studio site](#542 (comment)). --- AI assistance: Claude (Anthropic) via the Pi coding agent, with an initial candidate from a Homeboy cook. Claude traced the failure, reworked and tested the implementation, verified it against MySQL, and drafted this PR at Chris Huber's direction. Fixes #541. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Temporal columns with numeric-zero defaults now use MySQL-compatible zero dates or times, including fractional seconds. * Temporal defaults are consistently represented in table definitions, metadata, and inserted or altered rows. * Existing databases are normalized when reopened, including temporal precision corrections for older driver versions. * Non-numeric defaults and string `YEAR` zero values remain unchanged. * Foreign-key relationships and active transactions remain intact during reconfiguration. * Failed table repairs now roll back cleanly and preserve the underlying error details. * Administrative errors distinguish missing tables from other database errors. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Jan Jakeš <jan@jakes.pro>
1 parent 503958e commit 958f029

5 files changed

Lines changed: 1134 additions & 33 deletions

File tree

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4155,7 +4155,11 @@ private function execute_administration_statement( WP_Parser_Node $node ): void
41554155
} catch ( PDOException $e ) {
41564156
if ( '42S02' === $e->getCode() && isset( $e->errorInfo[2] ) ) {
41574157
$errors = array( $e->errorInfo[2] );
4158-
} elseif ( 'HY000' === $e->getCode() ) {
4158+
} elseif (
4159+
// SQLite reports a missing table as a general error.
4160+
'HY000' === $e->getCode()
4161+
&& str_starts_with( $e->errorInfo[2] ?? '', 'no such table' )
4162+
) {
41594163
$errors = array( "Table '$table_name' doesn't exist" );
41604164
} else {
41614165
$errors = array( $e->getMessage() );

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

Lines changed: 207 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -75,20 +75,49 @@ public function ensure_database_configured(): void {
7575
* SQLite driver version and attempt to repair any configuration corruption.
7676
*/
7777
public function configure_database(): void {
78-
// Use an EXCLUSIVE transaction to prevent multiple connections
79-
// from attempting to configure the database at the same time.
80-
$this->driver->execute_sqlite_query( 'BEGIN EXCLUSIVE TRANSACTION' );
78+
/*
79+
* In SQLite, disabling foreign keys inside a transaction is a no-op.
80+
* We need to disable them here, because some configuration operations
81+
* may expect them disabled, e.g., to avoid triggering cascades.
82+
*
83+
* See:
84+
* https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes
85+
*/
86+
$foreign_keys = $this->driver->execute_sqlite_query( 'PRAGMA foreign_keys' )->fetchColumn();
87+
$this->driver->execute_sqlite_query( 'PRAGMA foreign_keys = OFF' );
88+
$transaction_started = false;
8189
try {
90+
// Use an EXCLUSIVE transaction to prevent multiple connections
91+
// from attempting to configure the database at the same time.
92+
$this->driver->execute_sqlite_query( 'BEGIN EXCLUSIVE TRANSACTION' );
93+
$transaction_started = true;
94+
$this->set_driver_in_transaction( true );
95+
96+
// Read the saved version within the transaction, before it's updated.
97+
$saved_version = $this->driver->get_saved_driver_version();
98+
8299
$this->ensure_global_variables_table();
83100
$this->schema_builder->ensure_information_schema_tables();
84101
$this->schema_reconstructor->ensure_correct_information_schema();
85-
$this->save_current_driver_version();
86102
$this->ensure_database_data();
103+
$this->run_migrations( $saved_version );
104+
$this->save_current_driver_version();
105+
$this->driver->execute_sqlite_query( 'COMMIT' );
87106
} catch ( Throwable $e ) {
88-
$this->driver->execute_sqlite_query( 'ROLLBACK' );
107+
// Roll back only the transaction started here, unless a failed
108+
// MySQL query already rolled it back in the driver.
109+
if ( $transaction_started && $this->driver->inTransaction() ) {
110+
$this->driver->execute_sqlite_query( 'ROLLBACK' );
111+
}
89112
throw $e;
113+
} finally {
114+
if ( $transaction_started ) {
115+
$this->set_driver_in_transaction( false );
116+
}
117+
if ( 1 === (int) $foreign_keys ) {
118+
$this->driver->execute_sqlite_query( 'PRAGMA foreign_keys = ON' );
119+
}
90120
}
91-
$this->driver->execute_sqlite_query( 'COMMIT' );
92121
}
93122

94123
/**
@@ -252,6 +281,29 @@ public function ensure_database_data(): void {
252281
}
253282
}
254283

284+
/**
285+
* Ensure that the driver knows that we started or ended an SQLite transaction.
286+
*
287+
* This is a workaround for PHP < 8.4, where PDO::inTransaction() doesn't
288+
* reflect transaction state started via a query, such as "BEGIN EXCLUSIVE".
289+
*
290+
* @see WP_MySQL_On_SQLite::inTransaction()
291+
*
292+
* @param bool $in_transaction Whether the driver is in a transaction.
293+
*/
294+
private function set_driver_in_transaction( bool $in_transaction ): void {
295+
if ( PHP_VERSION_ID >= 80400 ) {
296+
return;
297+
}
298+
299+
// Bind the closure to the driver class, so that it can access the private
300+
// property even when the driver is an instance of a subclass.
301+
$set_in_transaction = function () use ( $in_transaction ): void {
302+
$this->in_transaction = $in_transaction;
303+
};
304+
Closure::bind( $set_in_transaction, $this->driver, WP_MySQL_On_SQLite::class )();
305+
}
306+
255307
/**
256308
* Save the current SQLite driver version.
257309
*
@@ -272,4 +324,153 @@ private function save_current_driver_version(): void {
272324
)
273325
);
274326
}
327+
328+
/**
329+
* Migrate data stored by older driver versions.
330+
*
331+
* This is used when a new driver version needs to change some existing data.
332+
* Migrations can be version-gated so that they don't rerun on every update.
333+
*
334+
* @param string $saved_version The driver version that last configured the database.
335+
*/
336+
private function run_migrations( string $saved_version ): void {
337+
// Fix temporal precision and zero defaults stored by versions <= 3.1.1.
338+
if ( version_compare( $saved_version, '3.1.1', '<=' ) ) {
339+
$this->migrate_datetime_precision();
340+
$this->migrate_temporal_zero_defaults();
341+
}
342+
}
343+
344+
/**
345+
* Migrate DATETIME_PRECISION values stored by older driver versions.
346+
*
347+
* Older versions stored 0 regardless of fractional seconds precision.
348+
* The correct value is read from the column type, such as "datetime(3)".
349+
*/
350+
private function migrate_datetime_precision(): void {
351+
// CAST() reads the leading integer, e.g., "3)" as 3, or returns 0 when there is none.
352+
$this->driver->execute_sqlite_query(
353+
sprintf(
354+
"UPDATE %s
355+
SET DATETIME_PRECISION = CAST(SUBSTR(COLUMN_TYPE, INSTR(COLUMN_TYPE, '(') + 1) AS INTEGER)
356+
WHERE DATA_TYPE IN ('time', 'datetime', 'timestamp')",
357+
$this->driver->get_connection()->quote_identifier(
358+
$this->schema_builder->get_table_name( false, 'columns' )
359+
)
360+
)
361+
);
362+
}
363+
364+
/**
365+
* Migrate zero defaults of temporal columns stored by older driver versions.
366+
*
367+
* Older driver versions stored defaults such as "DEFAULT 0" of a TIMESTAMP
368+
* column verbatim, while MySQL stores them as a zero date/time value. Rows
369+
* that got such a default store it as well, so they get the zero value too.
370+
*/
371+
private function migrate_temporal_zero_defaults(): void {
372+
$connection = $this->driver->get_connection();
373+
$columns_table = $connection->quote_identifier(
374+
$this->schema_builder->get_table_name( false, 'columns' )
375+
);
376+
377+
// Read SQLite defaults; reconstructed metadata may already be normalized.
378+
$columns = $this->driver->execute_sqlite_query(
379+
sprintf(
380+
"SELECT c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE, c.DATETIME_PRECISION, p.dflt_value
381+
FROM %s AS c
382+
JOIN pragma_table_info(c.TABLE_NAME, 'main') AS p ON c.COLUMN_NAME = p.name
383+
WHERE c.TABLE_SCHEMA = ?
384+
AND c.DATA_TYPE IN ('date', 'time', 'datetime', 'timestamp', 'year')
385+
AND c.EXTRA NOT LIKE '%%DEFAULT_GENERATED%%'
386+
AND p.dflt_value IS NOT NULL",
387+
$columns_table
388+
),
389+
array( WP_SQLite_Information_Schema_Builder::SAVED_DATABASE_NAME )
390+
)->fetchAll( PDO::FETCH_ASSOC );
391+
392+
// Normalize zeros, such as 0, '0', -0.0, or 0e0.
393+
$table_columns = array();
394+
foreach ( $columns as $column ) {
395+
// SQLite returns the default as an SQL literal, e.g., 0, '0', or "0".
396+
$default = $column['dflt_value'];
397+
$is_string = in_array( $default[0], array( "'", '"', '`' ), true );
398+
if ( $is_string ) {
399+
$default = substr( $default, 1, -1 );
400+
}
401+
if ( ! is_numeric( $default ) || 0.0 !== (float) $default ) {
402+
continue;
403+
}
404+
405+
// A string zero of a YEAR column, such as '0', can be the year 2000.
406+
if ( $is_string && 'year' === $column['DATA_TYPE'] ) {
407+
continue;
408+
}
409+
410+
$zero_value = WP_SQLite_Information_Schema_Builder::TEMPORAL_ZERO_VALUE_MAP[ $column['DATA_TYPE'] ];
411+
$precision = (int) $column['DATETIME_PRECISION'];
412+
if ( $precision > 0 ) {
413+
$zero_value .= '.' . str_repeat( '0', $precision );
414+
}
415+
416+
$table_columns[ $column['TABLE_NAME'] ][] = array(
417+
'name' => $column['COLUMN_NAME'],
418+
'zero_value' => $zero_value,
419+
'old_default' => $default,
420+
'is_string' => $is_string,
421+
);
422+
}
423+
424+
foreach ( $table_columns as $table_name => $repaired_columns ) {
425+
// Disable driver triggers during row repair. The table rebuild restores them.
426+
$triggers = $this->driver->execute_sqlite_query(
427+
"SELECT name FROM sqlite_master WHERE type = 'trigger' AND tbl_name = ? COLLATE NOCASE",
428+
array( $table_name )
429+
)->fetchAll( PDO::FETCH_COLUMN );
430+
foreach ( $triggers as $trigger ) {
431+
$this->driver->execute_sqlite_query(
432+
sprintf( 'DROP TRIGGER %s', $connection->quote_identifier( $trigger ) )
433+
);
434+
}
435+
436+
$alter_list = array();
437+
foreach ( $repaired_columns as $column ) {
438+
// Preserve numeric and string types so comparisons apply the same
439+
// SQLite conversion as when the defaults were stored.
440+
$quoted_column = $connection->quote_identifier( $column['name'] );
441+
$this->driver->execute_sqlite_query(
442+
sprintf(
443+
'UPDATE %s SET %s = ? WHERE %s = %s',
444+
$connection->quote_identifier( $table_name ),
445+
$quoted_column,
446+
$quoted_column,
447+
$column['is_string'] ? '?' : $column['old_default']
448+
),
449+
$column['is_string']
450+
? array( $column['zero_value'], $column['old_default'] )
451+
: array( $column['zero_value'] )
452+
);
453+
454+
$alter_list[] = sprintf(
455+
'ALTER COLUMN `%s` SET DEFAULT %s',
456+
str_replace( '`', '``', $column['name'] ),
457+
$this->driver->quote( $column['zero_value'] )
458+
);
459+
}
460+
461+
// ALTER TABLE stores the new defaults, and it recreates the table to apply them.
462+
try {
463+
$this->driver->query(
464+
sprintf( 'ALTER TABLE `%s` %s', str_replace( '`', '``', $table_name ), implode( ', ', $alter_list ) )
465+
);
466+
} catch ( WP_MySQL_On_SQLite_Exception $e ) {
467+
throw new WP_MySQL_On_SQLite_Exception(
468+
$this->driver,
469+
sprintf( 'Failed to recreate table "%s": %s', $table_name, $e->getMessage() ),
470+
$e->getCode(),
471+
$e
472+
);
473+
}
474+
}
475+
}
275476
}

0 commit comments

Comments
 (0)