Skip to content

Commit 0116e18

Browse files
committed
Repair temporal zero defaults with ALTER TABLE
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. Apply the zero values with ALTER TABLE ... ALTER COLUMN ... SET DEFAULT, which stores them in the information schema and recreates the table, so that its SQLite defaults match. ALTER 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 failed ALTER TABLE rolls back the whole transaction in the driver, so the configuration doesn't roll it back again. 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 cf6be95 commit 0116e18

3 files changed

Lines changed: 477 additions & 59 deletions

File tree

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

Lines changed: 146 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,97 @@ 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+
private function ensure_temporal_zero_defaults(): void {
331+
$columns_table = $this->driver->get_connection()->quote_identifier(
332+
$this->schema_builder->get_table_name( false, 'columns' )
333+
);
334+
335+
/*
336+
* Older driver versions stored a DATETIME_PRECISION of 0, so the precision
337+
* is read from the column type, such as "datetime(3)". CAST() reads the
338+
* leading integer, e.g., "3)" as 3, or returns 0 when there is none.
339+
*/
340+
341+
// Read SQLite defaults; reconstructed metadata may already be normalized.
342+
$columns = $this->driver->execute_sqlite_query(
343+
sprintf(
344+
"SELECT
345+
c.TABLE_NAME,
346+
c.COLUMN_NAME,
347+
c.DATA_TYPE,
348+
CAST(SUBSTR(c.COLUMN_TYPE, INSTR(c.COLUMN_TYPE, '(') + 1) AS INTEGER) AS DATETIME_PRECISION,
349+
p.dflt_value
350+
FROM %s AS c
351+
JOIN pragma_table_info(c.TABLE_NAME, 'main') AS p ON c.COLUMN_NAME = p.name
352+
WHERE c.TABLE_SCHEMA = ?
353+
AND c.DATA_TYPE IN ('date', 'time', 'datetime', 'timestamp', 'year')
354+
AND c.EXTRA NOT LIKE '%%DEFAULT_GENERATED%%'
355+
AND p.dflt_value IS NOT NULL",
356+
$columns_table
357+
),
358+
array( WP_SQLite_Information_Schema_Builder::SAVED_DATABASE_NAME )
359+
)->fetchAll( PDO::FETCH_ASSOC );
360+
361+
// Normalize numeric zeros, such as 0, '0', '-0.0', or '0e0'.
362+
$table_columns = array();
363+
foreach ( $columns as $column ) {
364+
// SQLite returns the default as an SQL literal, e.g., 0, '0', or "0".
365+
$default = $column['dflt_value'];
366+
$is_string = in_array( $default[0], array( "'", '"', '`' ), true );
367+
if ( $is_string ) {
368+
$default = substr( $default, 1, -1 );
369+
}
370+
if ( ! is_numeric( $default ) || 0.0 !== (float) $default ) {
371+
continue;
372+
}
373+
374+
// A string zero of a YEAR column, such as '0', can be the year 2000.
375+
if ( $is_string && 'year' === $column['DATA_TYPE'] ) {
376+
continue;
377+
}
378+
379+
$zero_value = WP_SQLite_Information_Schema_Builder::TEMPORAL_ZERO_VALUE_MAP[ $column['DATA_TYPE'] ];
380+
$precision = (int) $column['DATETIME_PRECISION'];
381+
if ( $precision > 0 ) {
382+
$zero_value .= '.' . str_repeat( '0', $precision );
383+
}
384+
385+
$table_columns[ $column['TABLE_NAME'] ][] = array(
386+
'name' => $column['COLUMN_NAME'],
387+
'zero_value' => $zero_value,
388+
);
389+
}
390+
391+
foreach ( $table_columns as $table_name => $repaired_columns ) {
392+
$alter_list = array();
393+
foreach ( $repaired_columns as $column ) {
394+
$alter_list[] = sprintf(
395+
'ALTER COLUMN `%s` SET DEFAULT %s',
396+
str_replace( '`', '``', $column['name'] ),
397+
$this->driver->quote( $column['zero_value'] )
398+
);
399+
}
400+
401+
// ALTER TABLE stores the new defaults, and it recreates the table to apply them.
402+
try {
403+
$this->driver->query(
404+
sprintf( 'ALTER TABLE `%s` %s', str_replace( '`', '``', $table_name ), implode( ', ', $alter_list ) )
405+
);
406+
} catch ( WP_MySQL_On_SQLite_Exception $e ) {
407+
throw new WP_MySQL_On_SQLite_Exception(
408+
$this->driver,
409+
sprintf( 'Failed to recreate table "%s": %s', $table_name, $e->getMessage() ),
410+
$e->getCode(),
411+
$e
412+
);
413+
}
414+
}
415+
}
276416
}

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