Skip to content

Commit 359c484

Browse files
committed
Emulate ON UPDATE CURRENT_TIMESTAMP in UPDATE translation
The driver emulated ON UPDATE CURRENT_TIMESTAMP with an unconditional AFTER UPDATE trigger. Explicit values, self-assignments, and unchanged rows all got the current time. Columns with DEFAULT_GENERATED in EXTRA never got a trigger. Now, the SET list translation appends a CASE for each ON UPDATE column that the statement doesn't assign. The column gets the current time only when an assigned value differs from the stored one. This covers UPDATE and ON DUPLICATE KEY UPDATE, and tables no longer get triggers. See: #554
1 parent 958f029 commit 359c484

4 files changed

Lines changed: 611 additions & 97 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: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -422,7 +422,7 @@ private function migrate_temporal_zero_defaults(): void {
422422
}
423423

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

0 commit comments

Comments
 (0)