Skip to content

Commit 02814c0

Browse files
committed
Drop old ON UPDATE CURRENT_TIMESTAMP triggers on upgrade
Remove the legacy and AST driver triggers before they can overwrite values set by the UPDATE translation. Recover missing ON UPDATE column metadata before other migrations rebuild tables and discard the legacy triggers. Match exact trigger names and their tables to preserve unrelated triggers. Cover legacy upgrades, table rebuilds, version gating, and rollback. See: #554 Fixes: #547
1 parent c4bdf15 commit 02814c0

2 files changed

Lines changed: 283 additions & 8 deletions

File tree

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

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,13 +334,64 @@ private function save_current_driver_version(): void {
334334
* @param string $saved_version The driver version that last configured the database.
335335
*/
336336
private function run_migrations( string $saved_version ): void {
337+
// Drop ON UPDATE CURRENT_TIMESTAMP triggers created by versions <= 3.1.1.
338+
// Run this before other migrations would drop them by table rebuilds.
339+
if ( version_compare( $saved_version, '3.1.1', '<=' ) ) {
340+
$this->migrate_on_update_triggers();
341+
}
342+
337343
// Fix temporal precision and zero defaults stored by versions <= 3.1.1.
338344
if ( version_compare( $saved_version, '3.1.1', '<=' ) ) {
339345
$this->migrate_datetime_precision();
340346
$this->migrate_temporal_zero_defaults();
341347
}
342348
}
343349

350+
/**
351+
* Migrate ON UPDATE CURRENT_TIMESTAMP triggers to column metadata.
352+
*
353+
* Handles old ON UPDATE triggers with the following name formats:
354+
*
355+
* 1. Versions 3.0.0 to 3.1.1: "_wp_sqlite_{table}_{column}_on_update"
356+
* 2. Versions before 3.0.0: "__{table}_{column}_on_update__"
357+
*/
358+
private function migrate_on_update_triggers(): void {
359+
$connection = $this->driver->get_connection();
360+
$columns_table = $connection->quote_identifier( $this->schema_builder->get_table_name( false, 'columns' ) );
361+
$columns = $this->driver->execute_sqlite_query(
362+
sprintf(
363+
"SELECT c.TABLE_NAME, c.COLUMN_NAME, c.EXTRA, t.name AS TRIGGER_NAME
364+
FROM %s AS c
365+
JOIN main.sqlite_master AS t ON t.type = 'trigger'
366+
AND t.tbl_name = c.TABLE_NAME COLLATE NOCASE
367+
AND (
368+
t.name = '__' || c.TABLE_NAME || '_' || c.COLUMN_NAME || '_on_update__' COLLATE NOCASE
369+
OR t.name = ? || c.TABLE_NAME || '_' || c.COLUMN_NAME || '_on_update' COLLATE NOCASE
370+
)
371+
WHERE c.TABLE_SCHEMA = ?",
372+
$columns_table
373+
),
374+
array( WP_MySQL_On_SQLite::RESERVED_PREFIX, WP_SQLite_Information_Schema_Builder::SAVED_DATABASE_NAME )
375+
)->fetchAll( PDO::FETCH_ASSOC );
376+
377+
foreach ( $columns as $column ) {
378+
if ( ! str_contains( $column['EXTRA'], 'on update CURRENT_TIMESTAMP' ) ) {
379+
$this->driver->execute_sqlite_query(
380+
sprintf( 'UPDATE %s SET EXTRA = ? WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ?', $columns_table ),
381+
array(
382+
trim( $column['EXTRA'] . ' on update CURRENT_TIMESTAMP' ),
383+
WP_SQLite_Information_Schema_Builder::SAVED_DATABASE_NAME,
384+
$column['TABLE_NAME'],
385+
$column['COLUMN_NAME'],
386+
)
387+
);
388+
}
389+
$this->driver->execute_sqlite_query(
390+
sprintf( 'DROP TRIGGER main.%s', $connection->quote_identifier( $column['TRIGGER_NAME'] ) )
391+
);
392+
}
393+
}
394+
344395
/**
345396
* Migrate DATETIME_PRECISION values stored by older driver versions.
346397
*

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

Lines changed: 232 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -141,18 +141,22 @@ function ( $row ) use ( $now ) {
141141
*
142142
* @param string $table The table name.
143143
* @param string $column The column name.
144+
* @param bool $legacy Whether to use the legacy driver's trigger name.
144145
*/
145-
private function createOnUpdateTrigger( string $table, string $column ): void {
146+
private function createOnUpdateTrigger( string $table, string $column, bool $legacy = false ): void {
147+
$connection = $this->engine->get_connection();
148+
$trigger_name = $legacy ? "__{$table}_{$column}_on_update__" : "_wp_sqlite_{$table}_{$column}_on_update";
146149
$this->sqlite->exec(
147150
sprintf(
148-
'CREATE TRIGGER `_wp_sqlite_%1$s_%2$s_on_update`
149-
AFTER UPDATE ON `%1$s`
151+
'CREATE TRIGGER %1$s
152+
AFTER UPDATE ON %2$s
150153
FOR EACH ROW
151154
BEGIN
152-
UPDATE `%1$s` SET `%2$s` = CURRENT_TIMESTAMP WHERE rowid = NEW.rowid;
155+
UPDATE %2$s SET %3$s = CURRENT_TIMESTAMP WHERE rowid = NEW.rowid;
153156
END',
154-
$table,
155-
$column
157+
$connection->quote_identifier( $trigger_name ),
158+
$connection->quote_identifier( $table ),
159+
$connection->quote_identifier( $column )
156160
)
157161
);
158162
}
@@ -7290,6 +7294,222 @@ public static function migrationDriverVersions(): array {
72907294
);
72917295
}
72927296

7297+
public function testConfigurationDropsOnUpdateCurrentTimestampTriggers(): void {
7298+
$this->assertQuery(
7299+
'CREATE TABLE _tmp_table (
7300+
id INT PRIMARY KEY,
7301+
n INT,
7302+
updated_at TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP
7303+
)'
7304+
);
7305+
$this->assertQuery(
7306+
"INSERT INTO _tmp_table VALUES
7307+
(1, 1, '2000-01-01 00:00:00'),
7308+
(2, 1, '2000-01-01 00:00:00')"
7309+
);
7310+
7311+
// Create the trigger, as older driver versions did, and a user trigger.
7312+
$this->createOnUpdateTrigger( '_tmp_table', 'updated_at' );
7313+
$this->sqlite->exec( 'CREATE TRIGGER `_tmp_table_updated_at_on_update` AFTER UPDATE ON `_tmp_table` BEGIN SELECT 1; END' );
7314+
7315+
// Only the driver trigger is dropped.
7316+
$this->reconnectAfterDriverUpgrade();
7317+
$this->assertSame(
7318+
array( '_tmp_table_updated_at_on_update' ),
7319+
$this->sqlite->query( "SELECT name FROM sqlite_master WHERE type = 'trigger'" )->fetchAll( PDO::FETCH_COLUMN )
7320+
);
7321+
7322+
// UPDATE emulates ON UPDATE CURRENT_TIMESTAMP as MySQL does.
7323+
$now = gmdate( 'Y-m-d H:i:s' );
7324+
$this->assertQuery( 'UPDATE _tmp_table SET n = 2 WHERE id = 1' );
7325+
$this->assertQuery( 'UPDATE _tmp_table SET n = 1 WHERE id = 2' );
7326+
$this->assertSame(
7327+
array( $now, '2000-01-01 00:00:00' ),
7328+
$this->getOnUpdateTimestamps( 'SELECT updated_at FROM _tmp_table ORDER BY id', $now )
7329+
);
7330+
}
7331+
7332+
/**
7333+
* @dataProvider onUpdateTriggerMigrationDriverVersions
7334+
*/
7335+
public function testConfigurationDropsOnUpdateCurrentTimestampTriggersOnlyForOlderDriverVersions(
7336+
string $saved_version,
7337+
array $expected_triggers,
7338+
bool $legacy = false
7339+
): void {
7340+
$this->assertQuery( 'CREATE TABLE _tmp_table (id INT, updated_at TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP)' );
7341+
$this->createOnUpdateTrigger( '_tmp_table', 'updated_at', $legacy );
7342+
7343+
// Configure the database as if it was last configured by the given driver version.
7344+
$this->sqlite->exec(
7345+
sprintf(
7346+
"UPDATE %s SET value = '%s' WHERE name = '%s'",
7347+
WP_MySQL_On_SQLite::GLOBAL_VARIABLES_TABLE_NAME,
7348+
$saved_version,
7349+
WP_MySQL_On_SQLite::DRIVER_VERSION_VARIABLE_NAME
7350+
)
7351+
);
7352+
$configurator = new WP_SQLite_Configurator(
7353+
$this->engine,
7354+
new WP_SQLite_Information_Schema_Builder( WP_MySQL_On_SQLite::RESERVED_PREFIX, $this->engine->get_connection() )
7355+
);
7356+
$configurator->configure_database();
7357+
7358+
$this->assertSame(
7359+
$expected_triggers,
7360+
$this->sqlite->query( "SELECT name FROM sqlite_master WHERE type = 'trigger'" )->fetchAll( PDO::FETCH_COLUMN )
7361+
);
7362+
}
7363+
7364+
public static function onUpdateTriggerMigrationDriverVersions(): array {
7365+
return array(
7366+
'migrated from 3.1.1' => array( '3.1.1', array() ),
7367+
'not migrated from 3.1.2' => array( '3.1.2', array( '_wp_sqlite__tmp_table_updated_at_on_update' ) ),
7368+
'legacy from 3.1.1' => array( '3.1.1', array(), true ),
7369+
'legacy from 3.1.2' => array( '3.1.2', array( '___tmp_table_updated_at_on_update__' ), true ),
7370+
);
7371+
}
7372+
7373+
/**
7374+
* @dataProvider legacyOnUpdateTriggerMigrations
7375+
*/
7376+
public function testConfigurationMigratesLegacyOnUpdateTriggers( bool $already_reconstructed, string $rebuild_query ): void {
7377+
// Reproduce the table, type cache, and triggers created by the legacy driver.
7378+
$this->sqlite->exec(
7379+
'CREATE TABLE _mysql_data_types_cache (
7380+
`table` TEXT NOT NULL,
7381+
`column_or_index` TEXT NOT NULL,
7382+
`mysql_type` TEXT NOT NULL,
7383+
PRIMARY KEY (`table`, `column_or_index`)
7384+
)'
7385+
);
7386+
$this->sqlite->exec(
7387+
"INSERT INTO _mysql_data_types_cache VALUES
7388+
('legacy_timestamps', 'id', 'int'),
7389+
('legacy_timestamps', 'n', 'int'),
7390+
('legacy_timestamps', 'zero_default', 'timestamp'),
7391+
('legacy_timestamps', 'generated_default', 'datetime'),
7392+
('legacy_timestamps', 'nullable', 'timestamp')"
7393+
);
7394+
$this->sqlite->exec(
7395+
'CREATE TABLE legacy_timestamps (
7396+
id INTEGER PRIMARY KEY,
7397+
n INTEGER,
7398+
zero_default TEXT NOT NULL DEFAULT 0,
7399+
generated_default TEXT DEFAULT CURRENT_TIMESTAMP,
7400+
nullable TEXT
7401+
)'
7402+
);
7403+
foreach ( range( 1, 5 ) as $id ) {
7404+
$this->sqlite->exec(
7405+
"INSERT INTO legacy_timestamps VALUES ($id, 1, '2000-01-01 00:00:00', '2000-01-01 00:00:00', '2000-01-01 00:00:00')"
7406+
);
7407+
}
7408+
$this->sqlite->exec( 'UPDATE legacy_timestamps SET zero_default = 0 WHERE id = 5' );
7409+
foreach ( array( 'zero_default', 'generated_default', 'nullable' ) as $column ) {
7410+
$this->createOnUpdateTrigger( 'legacy_timestamps', $column, true );
7411+
}
7412+
7413+
if ( $already_reconstructed ) {
7414+
// Earlier AST versions reconstructed the table but missed ON UPDATE metadata.
7415+
$reconstructor = new WP_SQLite_Information_Schema_Reconstructor(
7416+
$this->engine,
7417+
new WP_SQLite_Information_Schema_Builder( WP_MySQL_On_SQLite::RESERVED_PREFIX, $this->engine->get_connection() )
7418+
);
7419+
$reconstructor->ensure_correct_information_schema();
7420+
}
7421+
7422+
// Recover ON UPDATE before the zero-default migration rebuilds the table.
7423+
$this->reconnectAfterDriverUpgrade();
7424+
$this->assertQuery( 'SELECT zero_default, generated_default, nullable FROM legacy_timestamps WHERE id = 5' );
7425+
$this->assertEquals(
7426+
array(
7427+
(object) array(
7428+
'zero_default' => '0000-00-00 00:00:00',
7429+
'generated_default' => '2000-01-01 00:00:00',
7430+
'nullable' => '2000-01-01 00:00:00',
7431+
),
7432+
),
7433+
$this->last_result
7434+
);
7435+
$this->assertSame(
7436+
array(),
7437+
$this->sqlite->query( "SELECT name FROM sqlite_master WHERE type = 'trigger'" )->fetchAll( PDO::FETCH_COLUMN )
7438+
);
7439+
7440+
// Repeated configuration must preserve other EXTRA flags without duplicating ON UPDATE.
7441+
$this->reconnectAfterDriverUpgrade();
7442+
$this->assertQuery( "SELECT extra FROM information_schema.columns WHERE table_name = 'legacy_timestamps' AND column_name != 'id' AND column_name != 'n' ORDER BY ordinal_position" );
7443+
$this->assertSame(
7444+
array( 'on update CURRENT_TIMESTAMP', 'DEFAULT_GENERATED on update CURRENT_TIMESTAMP', 'on update CURRENT_TIMESTAMP' ),
7445+
array_column( $this->last_result, 'EXTRA' )
7446+
);
7447+
7448+
if ( '' !== $rebuild_query ) {
7449+
$this->assertQuery( $rebuild_query );
7450+
}
7451+
$this->assertQuery( 'SHOW CREATE TABLE legacy_timestamps' );
7452+
$this->assertSame( 3, substr_count( $this->last_result[0]->{'Create Table'}, 'ON UPDATE CURRENT_TIMESTAMP' ) );
7453+
7454+
$now = gmdate( 'Y-m-d H:i:s' );
7455+
$this->assertQuery( 'UPDATE legacy_timestamps SET n = 2 WHERE id IN (1, 5)' );
7456+
$this->assertQuery( 'UPDATE legacy_timestamps SET n = n WHERE id = 2' );
7457+
$this->assertQuery( 'UPDATE legacy_timestamps SET n = 2, zero_default = zero_default, generated_default = generated_default, nullable = nullable WHERE id = 3' );
7458+
$this->assertQuery( "UPDATE legacy_timestamps SET zero_default = '2001-01-01 00:00:00', generated_default = '2001-01-01 00:00:00', nullable = '2001-01-01 00:00:00' WHERE id = 4" );
7459+
foreach ( array( 'zero_default', 'generated_default', 'nullable' ) as $column ) {
7460+
$this->assertSame(
7461+
array( $now, '2000-01-01 00:00:00', '2000-01-01 00:00:00', '2001-01-01 00:00:00', $now ),
7462+
$this->getOnUpdateTimestamps( "SELECT $column FROM legacy_timestamps ORDER BY id", $now )
7463+
);
7464+
}
7465+
}
7466+
7467+
public static function legacyOnUpdateTriggerMigrations(): array {
7468+
$cases = array();
7469+
foreach ( array( false, true ) as $already_reconstructed ) {
7470+
foreach ( array( '', 'ALTER TABLE legacy_timestamps ADD COLUMN note TEXT', 'OPTIMIZE TABLE legacy_timestamps', 'REPAIR TABLE legacy_timestamps' ) as $query ) {
7471+
$name = ( $already_reconstructed ? 'existing metadata: ' : 'reconstructed metadata: ' ) . $query;
7472+
$cases[ $name ] = array( $already_reconstructed, $query );
7473+
}
7474+
}
7475+
return $cases;
7476+
}
7477+
7478+
public function testConfigurationMigratesLegacyOnUpdateTriggersWithQuotedNames(): void {
7479+
$table = 'Legacy_`"table';
7480+
$column = 'Updated_`"at';
7481+
$connection = $this->engine->get_connection();
7482+
$quoted_table = $connection->quote_identifier( $table );
7483+
$quoted_column = $connection->quote_identifier( $column );
7484+
$this->assertQuery( "CREATE TABLE $quoted_table (id INT, $quoted_column TIMESTAMP NULL)" );
7485+
$this->assertQuery( "INSERT INTO $quoted_table VALUES (1, '2000-01-01 00:00:00')" );
7486+
$this->createOnUpdateTrigger( strtoupper( $table ), strtoupper( $column ), true );
7487+
$this->createOnUpdateTrigger( $table, $column );
7488+
7489+
// Similar names and a matching name on a different table are user triggers.
7490+
$this->sqlite->exec( "CREATE TRIGGER `__legacy_user_on_update__suffix` AFTER UPDATE ON $quoted_table BEGIN SELECT 1; END" );
7491+
$this->assertQuery( 'CREATE TABLE other_table (updated_at TIMESTAMP NULL)' );
7492+
$this->sqlite->exec( "CREATE TRIGGER `__other_table_updated_at_on_update__` AFTER UPDATE ON $quoted_table BEGIN SELECT 1; END" );
7493+
7494+
// A temporary trigger with the same name must not hide the main trigger.
7495+
$temp_trigger = $connection->quote_identifier( '__' . strtoupper( $table ) . '_' . strtoupper( $column ) . '_on_update__' );
7496+
$this->sqlite->exec( "CREATE TEMP TRIGGER $temp_trigger AFTER UPDATE ON $quoted_table BEGIN SELECT 1; END" );
7497+
$this->reconnectAfterDriverUpgrade();
7498+
$this->assertSame(
7499+
array( '__legacy_user_on_update__suffix', '__other_table_updated_at_on_update__' ),
7500+
$this->sqlite->query( "SELECT name FROM sqlite_master WHERE type = 'trigger' ORDER BY name" )->fetchAll( PDO::FETCH_COLUMN )
7501+
);
7502+
$this->assertSame( '1', (string) $this->sqlite->query( "SELECT COUNT(*) FROM sqlite_temp_master WHERE type = 'trigger'" )->fetchColumn() );
7503+
$this->assertQuery( "SELECT extra FROM information_schema.columns WHERE table_name = 'other_table'" );
7504+
$this->assertSame( '', $this->last_result[0]->EXTRA );
7505+
7506+
$now = gmdate( 'Y-m-d H:i:s' );
7507+
$this->assertQuery( "UPDATE $quoted_table SET id = 2" );
7508+
$this->assertSame( array( $now ), $this->getOnUpdateTimestamps( "SELECT $quoted_column FROM $quoted_table", $now ) );
7509+
$this->assertQuery( "UPDATE $quoted_table SET $quoted_column = '2001-01-01 00:00:00'" );
7510+
$this->assertSame( array( '2001-01-01 00:00:00' ), $this->getOnUpdateTimestamps( "SELECT $quoted_column FROM $quoted_table", $now ) );
7511+
}
7512+
72937513
public function testConfigurationNormalizesStoredTemporalZeroDefaultsOfReferencedTable(): void {
72947514
$this->assertQuery( 'CREATE TABLE _tmp_parent (id INT PRIMARY KEY, created_at TIMESTAMP NOT NULL DEFAULT 0)' );
72957515
$this->assertQuery( 'CREATE TABLE _tmp_cascade (id INT PRIMARY KEY, parent_id INT, FOREIGN KEY (parent_id) REFERENCES _tmp_parent (id) ON DELETE CASCADE)' );
@@ -7478,7 +7698,9 @@ public function testConfigurationRollsBackWhenRecreatingTableFails(): void {
74787698
// Make recreating the second table fail, as its data doesn't match the information schema.
74797699
$this->sqlite->exec( "UPDATE _wp_sqlite_mysql_information_schema_columns SET is_nullable = 'NO' WHERE table_name = '_tmp_failing' AND column_name = 'id'" );
74807700

7481-
$sqlite_schema_query = "SELECT sql FROM sqlite_master WHERE name IN ('_tmp_recreated', '_tmp_failing') ORDER BY name";
7701+
// Trigger removal and recovered ON UPDATE metadata must also roll back.
7702+
$this->createOnUpdateTrigger( '_tmp_recreated', 'created_at', true );
7703+
$sqlite_schema_query = "SELECT sql FROM sqlite_master WHERE tbl_name IN ('_tmp_recreated', '_tmp_failing') ORDER BY name";
74827704
$sqlite_schema = $this->sqlite->query( $sqlite_schema_query )->fetchAll( PDO::FETCH_COLUMN );
74837705

74847706
$exception = null;
@@ -7494,16 +7716,18 @@ public function testConfigurationRollsBackWhenRecreatingTableFails(): void {
74947716
// All configuration changes are rolled back, including the recreated table.
74957717
$this->assertSame( '0.0.0', $this->engine->get_saved_driver_version() );
74967718
$this->assertSame( $sqlite_schema, $this->sqlite->query( $sqlite_schema_query )->fetchAll( PDO::FETCH_COLUMN ) );
7497-
$this->assertQuery( "SELECT table_name, column_default FROM information_schema.columns WHERE column_name = 'created_at' ORDER BY table_name" );
7719+
$this->assertQuery( "SELECT table_name, column_default, extra FROM information_schema.columns WHERE column_name = 'created_at' ORDER BY table_name" );
74987720
$this->assertEquals(
74997721
array(
75007722
(object) array(
75017723
'TABLE_NAME' => '_tmp_failing',
75027724
'COLUMN_DEFAULT' => '0',
7725+
'EXTRA' => '',
75037726
),
75047727
(object) array(
75057728
'TABLE_NAME' => '_tmp_recreated',
75067729
'COLUMN_DEFAULT' => '0',
7730+
'EXTRA' => '',
75077731
),
75087732
),
75097733
$this->last_result

0 commit comments

Comments
 (0)