Skip to content

Commit a2848be

Browse files
committed
Recreate tables when repairing temporal zero defaults
The repair of temporal zero defaults stored by older driver versions only updated the information schema, while the SQLite tables kept their "0" defaults. INSERT statements that omitted the column then stored "0", also in non-strict SQL mode, where the stored "0" default was previously replaced by an implicit zero value. Recreate the affected tables with OPTIMIZE TABLE, so that their SQLite defaults match the information schema. OPTIMIZE TABLE runs as a savepoint within the configuration transaction. On PHP < 8.4, the driver can't detect a transaction that it didn't start, so the configurator sets its private transaction state directly. A transaction that the configuration didn't start, such as one on a shared SQLite connection, is never rolled back. Foreign keys are disabled during the configuration, as recreating a table drops it, which would otherwise fail or trigger foreign key actions, such as ON DELETE CASCADE, in referencing tables. The driver itself has the same problem when recreating tables: #528 The repair moves from the information schema builder to the configurator, next to the other configuration steps, as nothing else uses it. It now also: - Runs after the database name migration, which table recreation needs. - Finds the columns by their SQLite defaults, so that it also repairs tables reconstructed from the legacy SQLite driver, whose information schema already has a zero value. - Reads the fractional seconds precision from COLUMN_TYPE, as older driver versions stored a DATETIME_PRECISION of 0. - Repairs YEAR columns only for an unquoted SQLite default, such as 0, as a string zero, such as '0', can be the year 2000. - Skips expression defaults, such as DEFAULT (0).
1 parent 0cdb9e5 commit a2848be

3 files changed

Lines changed: 470 additions & 59 deletions

File tree

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

Lines changed: 139 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -75,21 +75,45 @@ 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 );
8295
$this->ensure_global_variables_table();
8396
$this->schema_builder->ensure_information_schema_tables();
8497
$this->schema_reconstructor->ensure_correct_information_schema();
85-
$this->schema_builder->normalize_temporal_zero_defaults();
8698
$this->save_current_driver_version();
8799
$this->ensure_database_data();
100+
$this->ensure_temporal_zero_defaults();
101+
$this->driver->execute_sqlite_query( 'COMMIT' );
88102
} catch ( Throwable $e ) {
89-
$this->driver->execute_sqlite_query( 'ROLLBACK' );
103+
// Roll back only the transaction started here, unless a failed
104+
// MySQL query already rolled it back in the driver.
105+
if ( $transaction_started && $this->driver->inTransaction() ) {
106+
$this->driver->execute_sqlite_query( 'ROLLBACK' );
107+
}
90108
throw $e;
109+
} finally {
110+
if ( $transaction_started ) {
111+
$this->set_driver_in_transaction( false );
112+
}
113+
if ( 1 === (int) $foreign_keys ) {
114+
$this->driver->execute_sqlite_query( 'PRAGMA foreign_keys = ON' );
115+
}
91116
}
92-
$this->driver->execute_sqlite_query( 'COMMIT' );
93117
}
94118

95119
/**
@@ -253,6 +277,29 @@ public function ensure_database_data(): void {
253277
}
254278
}
255279

280+
/**
281+
* Ensure that the driver knows that we started or ended an SQLite transaction.
282+
*
283+
* This is a workaround for PHP < 8.4, where PDO::inTransaction() doesn't
284+
* reflect transaction state started via a query, such as "BEGIN EXCLUSIVE".
285+
*
286+
* @see WP_MySQL_On_SQLite::inTransaction()
287+
*
288+
* @param bool $in_transaction Whether the driver is in a transaction.
289+
*/
290+
private function set_driver_in_transaction( bool $in_transaction ): void {
291+
if ( PHP_VERSION_ID >= 80400 ) {
292+
return;
293+
}
294+
295+
// Bind the closure to the driver class, so that it can access the private
296+
// property even when the driver is an instance of a subclass.
297+
$set_in_transaction = function () use ( $in_transaction ): void {
298+
$this->in_transaction = $in_transaction;
299+
};
300+
Closure::bind( $set_in_transaction, $this->driver, WP_MySQL_On_SQLite::class )();
301+
}
302+
256303
/**
257304
* Save the current SQLite driver version.
258305
*
@@ -273,4 +320,90 @@ private function save_current_driver_version(): void {
273320
)
274321
);
275322
}
323+
324+
/**
325+
* Ensure that temporal columns store numeric zero defaults as zero values.
326+
*
327+
* Older driver versions stored defaults such as "DEFAULT 0" of a TIMESTAMP
328+
* column verbatim, while MySQL stores them as a zero date/time value.
329+
*
330+
* The columns are found by their SQLite defaults, as the information schema
331+
* of a table reconstructed from the legacy SQLite driver already has a zero
332+
* value, while the SQLite table still stores "0".
333+
*/
334+
private function ensure_temporal_zero_defaults(): void {
335+
$columns_table = $this->driver->get_connection()->quote_identifier(
336+
$this->schema_builder->get_table_name( false, 'columns' )
337+
);
338+
/*
339+
* Older driver versions stored a DATETIME_PRECISION of 0, so the precision
340+
* is read from the column type, such as "datetime(3)". CAST() reads the
341+
* leading integer, e.g., "3)" as 3, or returns 0 when there is none.
342+
*/
343+
$columns = $this->driver->execute_sqlite_query(
344+
sprintf(
345+
"SELECT
346+
c.rowid,
347+
c.TABLE_NAME,
348+
c.DATA_TYPE,
349+
CAST(SUBSTR(c.COLUMN_TYPE, INSTR(c.COLUMN_TYPE, '(') + 1) AS INTEGER) AS DATETIME_PRECISION,
350+
p.dflt_value
351+
FROM %s AS c
352+
JOIN pragma_table_info(c.TABLE_NAME, 'main') AS p ON c.COLUMN_NAME = p.name
353+
WHERE c.TABLE_SCHEMA = ?
354+
AND c.DATA_TYPE IN ('date', 'time', 'datetime', 'timestamp', 'year')
355+
AND c.EXTRA NOT LIKE '%%DEFAULT_GENERATED%%'
356+
AND p.dflt_value IS NOT NULL",
357+
$columns_table
358+
),
359+
array( WP_SQLite_Information_Schema_Builder::SAVED_DATABASE_NAME )
360+
)->fetchAll( PDO::FETCH_ASSOC );
361+
362+
// Normalize numeric zeros, such as 0, '0', '-0.0', or '0e0'.
363+
$table_names = array();
364+
foreach ( $columns as $column ) {
365+
// SQLite returns the default as an SQL literal, e.g., 0, '0', or "0".
366+
$default = $column['dflt_value'];
367+
$is_string = in_array( $default[0], array( "'", '"', '`' ), true );
368+
if ( $is_string ) {
369+
$default = substr( $default, 1, -1 );
370+
}
371+
if ( ! is_numeric( $default ) || 0.0 !== (float) $default ) {
372+
continue;
373+
}
374+
375+
// A string zero of a YEAR column, such as '0', can be the year 2000.
376+
if ( $is_string && 'year' === $column['DATA_TYPE'] ) {
377+
continue;
378+
}
379+
380+
$zero_value = WP_SQLite_Information_Schema_Builder::TEMPORAL_ZERO_VALUE_MAP[ $column['DATA_TYPE'] ];
381+
$precision = (int) $column['DATETIME_PRECISION'];
382+
if ( $precision > 0 ) {
383+
$zero_value .= '.' . str_repeat( '0', $precision );
384+
}
385+
386+
$this->driver->execute_sqlite_query(
387+
sprintf( 'UPDATE %s SET COLUMN_DEFAULT = ? WHERE rowid = ?', $columns_table ),
388+
array( $zero_value, $column['rowid'] )
389+
);
390+
$table_names[] = $column['TABLE_NAME'];
391+
}
392+
393+
// Recreate the affected tables to apply the new defaults.
394+
foreach ( array_unique( $table_names ) as $table_name ) {
395+
// OPTIMIZE TABLE recreates the table, and it reports errors as rows.
396+
$results = $this->driver->query(
397+
sprintf( 'OPTIMIZE TABLE `%s`', str_replace( '`', '``', $table_name ) )
398+
)->fetchAll( PDO::FETCH_ASSOC );
399+
foreach ( $results as $result ) {
400+
if ( 'Error' === $result['Msg_type'] ) {
401+
throw new WP_MySQL_On_SQLite_Exception(
402+
$this->driver,
403+
sprintf( 'Failed to recreate table "%s": %s', $table_name, $result['Msg_text'] )
404+
);
405+
}
406+
}
407+
}
408+
}
276409
}

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

Lines changed: 0 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -424,46 +424,6 @@ public function ensure_information_schema_tables(): void {
424424
}
425425
}
426426

427-
/**
428-
* Normalize numeric zero defaults of temporal columns in the information schema.
429-
*
430-
* Older driver versions stored defaults such as "DEFAULT 0" of a TIMESTAMP
431-
* column verbatim. MySQL stores them as a canonical zero value, such as
432-
* "0000-00-00 00:00:00", and "SHOW CREATE TABLE" must emit that value for
433-
* the output to be accepted by MySQL in strict SQL mode.
434-
*/
435-
public function normalize_temporal_zero_defaults(): void {
436-
$columns_table = $this->connection->quote_identifier( $this->get_table_name( false, 'columns' ) );
437-
$columns = $this->connection->query(
438-
sprintf(
439-
"SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, DATETIME_PRECISION, COLUMN_DEFAULT
440-
FROM %s
441-
WHERE DATA_TYPE IN ('date', 'time', 'datetime', 'timestamp', 'year')
442-
AND COLUMN_DEFAULT IS NOT NULL",
443-
$columns_table
444-
)
445-
)->fetchAll( PDO::FETCH_ASSOC ); // phpcs:ignore WordPress.DB.RestrictedClasses.mysql__PDO
446-
447-
foreach ( $columns as $column ) {
448-
$default = $this->get_temporal_zero_value(
449-
$column['DATA_TYPE'],
450-
$column['COLUMN_DEFAULT'],
451-
null === $column['DATETIME_PRECISION'] ? null : (int) $column['DATETIME_PRECISION']
452-
);
453-
if ( null === $default || $default === $column['COLUMN_DEFAULT'] ) {
454-
continue;
455-
}
456-
457-
$this->connection->query(
458-
sprintf(
459-
'UPDATE %s SET COLUMN_DEFAULT = ? WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ?',
460-
$columns_table
461-
),
462-
array( $default, $column['TABLE_SCHEMA'], $column['TABLE_NAME'], $column['COLUMN_NAME'] )
463-
);
464-
}
465-
}
466-
467427
/**
468428
* Get the definition and data of a computed information schema table.
469429
*

0 commit comments

Comments
 (0)