Skip to content

Commit e312a20

Browse files
authored
Fix ON UPDATE CURRENT_TIMESTAMP for explicit values and unchanged rows (#560)
The driver emulated `ON UPDATE CURRENT_TIMESTAMP` with a trigger that ran after every `UPDATE`. It **overwrote explicit timestamps and changed timestamps on unchanged rows**: ```sql CREATE TABLE t (id INT PRIMARY KEY, n INT, ts TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP); INSERT INTO t VALUES (1, 1, '2000-01-01 00:00:00'); UPDATE t SET ts = '2001-01-01 00:00:00'; -- MySQL: keeps the explicit value UPDATE t SET n = n; -- MySQL: keeps the timestamp UPDATE t SET n = 2, ts = ts; -- MySQL: keeps the timestamp -- Previously, all three set ts to the current time. ``` Automatic updates were also missing in these cases: - Columns with `DEFAULT CURRENT_TIMESTAMP` never got an `ON UPDATE` trigger. - `ALTER COLUMN ... SET DEFAULT (expr)` could remove the trigger. - Rebuilding a legacy table could drop its triggers and lose its `ON UPDATE` behavior. ## Changes This PR handles automatic timestamps in the translated `UPDATE` and `INSERT ... ON DUPLICATE KEY UPDATE` statements: - **Update timestamps only when the row changes.** Compare the new values with the stored ones after type conversion. - **Evaluate assignments once per row.** Reuse the new values for change detection, keeping `RAND()` results consistent and avoiding repeated subqueries. - **Keep explicitly assigned timestamps.** Assigning a value, the column itself (`ts = ts`), or `DEFAULT` prevents the automatic update, as [MySQL documents](https://dev.mysql.com/doc/refman/8.4/en/timestamp-initialization.html). - **Handle columns with defaults.** Automatic updates work with `DEFAULT CURRENT_TIMESTAMP`, expression defaults, and defaults changed by `ALTER COLUMN`. - **Migrate old triggers.** Restore missing `ON UPDATE` metadata before other migrations can rebuild tables, then remove the legacy and AST driver triggers. Match exact trigger names and their tables to preserve unrelated user triggers. As in MySQL, changing `'a'` to `'A'` counts as a change. Assigning `'1'` to an `INT` column already containing `1` does not. Expected results were checked against MySQL 8.4 and 8.0. Fixes #554. Fixes #547. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * `ON UPDATE CURRENT_TIMESTAMP` now updates automatically when another value in the row changes, while preserving the timestamp when assigned values remain unchanged. Explicit timestamp assignments continue to be respected. * Timestamp behavior is more consistent across updates involving aliases, joined tables, multiple timestamp columns, and duplicate-key updates. * **Compatibility** * Existing databases are migrated to preserve automatic timestamp behavior while removing legacy timestamp triggers. User-created triggers are retained. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent 958f029 commit e312a20

4 files changed

Lines changed: 888 additions & 99 deletions

File tree

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

Lines changed: 87 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -2724,7 +2724,7 @@ private function execute_update_statement( WP_Parser_Node $node ): void {
27242724
}
27252725

27262726
// Translate UPDATE list, applying relevant type casting and IMPLICIT DEFAULT values.
2727-
$update_list = $this->translate_update_list( $update_target_table, $node );
2727+
$update_list = $this->translate_update_list( $update_target_table, $node, $update_target );
27282728

27292729
// Translate WHERE, ORDER BY, and LIMIT clauses.
27302730
if ( $where_subquery ) {
@@ -6275,11 +6275,19 @@ function ( $column ) use ( $is_strict_mode, $insert_map ) {
62756275
* For more information about IMPLICIT DEFAULT values in MySQL, see:
62766276
* https://dev.mysql.com/doc/refman/8.4/en/data-type-defaults.html#data-type-defaults-implicit
62776277
*
6278+
* Additionally, this method emulates "ON UPDATE CURRENT_TIMESTAMP" columns.
6279+
* In MySQL, such a column is set to the current timestamp when any other
6280+
* column in the row changes, unless the statement assigns it explicitly.
6281+
*
6282+
* For more information about ON UPDATE CURRENT_TIMESTAMP in MySQL, see:
6283+
* https://dev.mysql.com/doc/refman/8.4/en/timestamp-initialization.html
6284+
*
62786285
* @param string $table_name The name of the target table.
62796286
* @param WP_Parser_Node $parent_node The "updateList" AST node parent node.
6287+
* @param string|null $table_alias Optional. The target table alias. Defaults to the table name.
62806288
* @return string The translated UPDATE list.
62816289
*/
6282-
private function translate_update_list( string $table_name, WP_Parser_Node $parent_node ): string {
6290+
private function translate_update_list( string $table_name, WP_Parser_Node $parent_node, ?string $table_alias = null ): string {
62836291
$node = $parent_node->get_first_child_node( 'updateList' );
62846292

62856293
// This method is always used with the main database.
@@ -6296,7 +6304,7 @@ private function translate_update_list( string $table_name, WP_Parser_Node $pare
62966304
$columns_table = $this->information_schema_builder->get_table_name( $is_temporary, 'columns' );
62976305
$columns = $this->execute_sqlite_query(
62986306
'
6299-
SELECT LOWER(column_name) AS COLUMN_NAME, is_nullable, data_type, column_default
6307+
SELECT LOWER(column_name) AS COLUMN_NAME, is_nullable, data_type, column_default, extra
63006308
FROM ' . $this->quote_sqlite_identifier( $columns_table ) . '
63016309
WHERE table_schema = ?
63026310
AND table_name = ?
@@ -6312,7 +6320,8 @@ private function translate_update_list( string $table_name, WP_Parser_Node $pare
63126320
$column_map = array_combine( array_column( $columns, 'COLUMN_NAME' ), $columns );
63136321

63146322
// Translate the UPDATE list, emulating IMPLICIT DEFAULTs for NULL values.
6315-
$fragment = '';
6323+
$fragment = '';
6324+
$assigned_values = array();
63166325
foreach ( $node->get_child_nodes() as $i => $update_element ) {
63176326
$column_ref = $update_element->get_first_child_node( 'columnRef' );
63186327
$column_ref_parts = $column_ref->get_descendant_nodes( 'identifier' );
@@ -6364,8 +6373,80 @@ private function translate_update_list( string $table_name, WP_Parser_Node $pare
63646373
$fragment .= $this->translate( end( $column_ref_parts ) );
63656374
$fragment .= ' = ';
63666375
$fragment .= $value;
6376+
6377+
$assigned_values[ strtolower( $column_name ) ] = $value;
63676378
}
6368-
return $fragment;
6379+
6380+
// Collect unassigned ON UPDATE CURRENT_TIMESTAMP columns for automatic updates.
6381+
$on_update_columns = array();
6382+
foreach ( $column_map as $column_name => $column_info ) {
6383+
if (
6384+
isset( $assigned_values[ $column_name ] )
6385+
|| ! str_contains( $column_info['EXTRA'], 'on update CURRENT_TIMESTAMP' )
6386+
) {
6387+
continue;
6388+
}
6389+
6390+
$on_update_columns[] = $this->quote_sqlite_identifier( $column_name );
6391+
}
6392+
if ( 0 === count( $on_update_columns ) ) {
6393+
return $fragment;
6394+
}
6395+
6396+
/*
6397+
* Emulate ON UPDATE CURRENT_TIMESTAMP for columns that are not assigned.
6398+
*
6399+
* Evaluate assigned expressions once per row and reuse their values to
6400+
* detect changes and determine whether to use the current timestamp.
6401+
*
6402+
* With "updated_at ... ON UPDATE CURRENT_TIMESTAMP", this MySQL query:
6403+
*
6404+
* UPDATE items SET score = FLOOR(RAND(1) * 10);
6405+
*
6406+
* Becomes the following SQLite query (simplified):
6407+
*
6408+
* UPDATE items SET (score, updated_at) = (
6409+
* SELECT
6410+
* score,
6411+
* CASE WHEN items.score IS NOT score THEN CURRENT_TIMESTAMP ELSE items.updated_at END
6412+
* FROM (SELECT FLOOR(RAND(1) * 10) AS score)
6413+
* );
6414+
*
6415+
* Here, items.score is the stored value and score is the new value.
6416+
* The inner SELECT has no FROM clause, so SQLite cannot flatten it
6417+
* and repeat the assigned expressions when checking for changes.
6418+
* See: https://www.sqlite.org/optoverview.html#flattening
6419+
*/
6420+
$quoted_table = $this->quote_sqlite_identifier( $table_alias ?? $table_name );
6421+
$assigned_columns = array();
6422+
$value_expressions = array();
6423+
$changes = array();
6424+
foreach ( $assigned_values as $column_name => $value ) {
6425+
$quoted_column = $this->quote_sqlite_identifier( $column_name );
6426+
$assigned_columns[] = $quoted_column;
6427+
$value_expressions[] = sprintf( '(%s) COLLATE BINARY AS %s', $value, $quoted_column );
6428+
6429+
// Compare row data using binary collation, qualifying the old values.
6430+
$changes[] = sprintf( '%s.%s IS NOT %s COLLATE BINARY', $quoted_table, $quoted_column, $quoted_column );
6431+
}
6432+
$is_row_changed = implode( ' OR ', $changes );
6433+
$row_values = $assigned_columns;
6434+
foreach ( $on_update_columns as $quoted_column ) {
6435+
$assigned_columns[] = $quoted_column;
6436+
$row_values[] = sprintf(
6437+
'CASE WHEN %s THEN CURRENT_TIMESTAMP ELSE %s.%s END',
6438+
$is_row_changed,
6439+
$quoted_table,
6440+
$quoted_column
6441+
);
6442+
}
6443+
6444+
return sprintf(
6445+
'(%s) = (SELECT %s FROM (SELECT %s))',
6446+
implode( ', ', $assigned_columns ),
6447+
implode( ', ', $row_values ),
6448+
implode( ', ', $value_expressions )
6449+
);
63696450
}
63706451

63716452
/**
@@ -7159,7 +7240,6 @@ private function get_sqlite_create_table_statement(
71597240

71607241
// 6. Generate CREATE TABLE statement columns.
71617242
$rows = array();
7162-
$on_update_queries = array();
71637243
$has_autoincrement = false;
71647244
foreach ( $column_info as $column ) {
71657245
$query = ' ';
@@ -7230,13 +7310,6 @@ private function get_sqlite_create_table_statement(
72307310
}
72317311
}
72327312
$rows[] = $query;
7233-
7234-
if ( 'on update CURRENT_TIMESTAMP' === $column['EXTRA'] ) {
7235-
$on_update_queries[] = $this->get_column_on_update_trigger_query(
7236-
$table_name,
7237-
$column['COLUMN_NAME']
7238-
);
7239-
}
72407313
}
72417314

72427315
// 6. Generate CREATE TABLE statement constraints, collect indexes.
@@ -7372,7 +7445,7 @@ function ( $column ) {
73727445
$create_table_query .= ' STRICT';
73737446
}
73747447

7375-
return array_merge( array( $create_table_query ), $create_index_queries, $on_update_queries );
7448+
return array_merge( array( $create_table_query ), $create_index_queries );
73767449
}
73777450

73787451
/**
@@ -7705,36 +7778,6 @@ private function get_internal_savepoint_name( string $name ): string {
77057778
return sprintf( '%ssavepoint_%s', self::RESERVED_PREFIX, $name );
77067779
}
77077780

7708-
/**
7709-
* Get an SQLite query to emulate MySQL "ON UPDATE CURRENT_TIMESTAMP".
7710-
*
7711-
* In SQLite, "ON UPDATE CURRENT_TIMESTAMP" is not supported. We need to
7712-
* create a trigger to emulate this behavior.
7713-
*
7714-
* @param string $table The table name.
7715-
* @param string $column The column name.
7716-
*/
7717-
private function get_column_on_update_trigger_query( string $table, string $column ): string {
7718-
// The trigger wouldn't work for virtual and "WITHOUT ROWID" tables,
7719-
// but currently that can't happen as we're not creating such tables.
7720-
// See: https://www.sqlite.org/rowidtable.html
7721-
$trigger_name = self::RESERVED_PREFIX . "{$table}_{$column}_on_update";
7722-
return sprintf(
7723-
'
7724-
CREATE TRIGGER %s
7725-
AFTER UPDATE ON %s
7726-
FOR EACH ROW
7727-
BEGIN
7728-
UPDATE %s SET %s = CURRENT_TIMESTAMP WHERE rowid = NEW.rowid;
7729-
END
7730-
',
7731-
$this->quote_sqlite_identifier( $trigger_name ),
7732-
$this->quote_sqlite_identifier( $table ),
7733-
$this->quote_sqlite_identifier( $table ),
7734-
$this->quote_sqlite_identifier( $column )
7735-
);
7736-
}
7737-
77387781
/**
77397782
* Format a column default value as a literal for an SQLite CREATE TABLE statement.
77407783
*

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

Lines changed: 52 additions & 1 deletion
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
*
@@ -422,7 +473,7 @@ private function migrate_temporal_zero_defaults(): void {
422473
}
423474

424475
foreach ( $table_columns as $table_name => $repaired_columns ) {
425-
// Disable driver triggers during row repair. The table rebuild restores them.
476+
// Drop triggers, so they don't run during row repair. The table rebuild drops them anyway.
426477
$triggers = $this->driver->execute_sqlite_query(
427478
"SELECT name FROM sqlite_master WHERE type = 'trigger' AND tbl_name = ? COLLATE NOCASE",
428479
array( $table_name )

0 commit comments

Comments
 (0)