diff --git a/packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php b/packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php index c3554be94..17acaa086 100644 --- a/packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php +++ b/packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php @@ -2768,7 +2768,7 @@ private function execute_update_statement( WP_Parser_Node $node ): void { } // Translate UPDATE list, applying relevant type casting and IMPLICIT DEFAULT values. - $update_list = $this->translate_update_list( $update_target_table, $node, $update_target ); + $update_list = $this->translate_update_list( $update_target_table, $node, $update_target, $table_alias_map ); // Translate WHERE, ORDER BY, and LIMIT clauses. if ( $where_subquery ) { @@ -6186,7 +6186,9 @@ function ( $column ) use ( $is_strict_mode, $insert_map ) { * * INSERT INTO ... SELECT FROM () */ - $select_list = array(); + $select_list = array(); + $select_column_metas = array(); + $select_alias_map = array(); if ( 'insertQueryExpression' === $node->rule_name ) { // When inserting from a SELECT query, we don't know the column names. // Let's wrap the query with a "SELECT (...) LIMIT 0" to obtain them. @@ -6214,8 +6216,13 @@ function ( $column ) use ( $is_strict_mode, $insert_map ) { return $this->translate( $node ); } } - $select_list[] = $stmt->getColumnMeta( $i )['name']; + $column_meta = $stmt->getColumnMeta( $i ); + $select_list[] = $column_meta['name']; + $select_column_metas[] = $column_meta; } + + // Map aliases of plain column references to the column names. + $select_alias_map = $this->create_select_alias_column_map( $expr ); } else { // When inserting from a VALUES list, SQLite uses a "columnN" naming. // This also applies to the SET syntax, which is converted to VALUES. @@ -6253,9 +6260,13 @@ function ( $column ) use ( $is_strict_mode, $insert_map ) { $fragment .= null === $default ? 'NULL' : $this->quote_sqlite_value( $default ); } else { // When a column value is included, we need to apply type casting. + // The YEAR conversion also depends on the source data type. $position = array_search( $column['COLUMN_NAME'], $insert_list, true ); $identifier = $this->quote_sqlite_identifier( $select_list[ $position ] ); - $value = $this->cast_value_for_saving( $column['DATA_TYPE'], $identifier ); + $is_string_source = 'year' === strtolower( $column['DATA_TYPE'] ) + ? $this->is_string_result_column( $select_column_metas[ $position ] ?? array(), $select_alias_map ) + : null; + $value = $this->cast_value_for_saving( $column['DATA_TYPE'], $identifier, $is_string_source ); $is_auto_increment = str_contains( $column['EXTRA'], 'auto_increment' ); /* @@ -6396,10 +6407,12 @@ function ( $column ) use ( $is_strict_mode, $insert_map ) { * * @param string $table_name The name of the target table. * @param WP_Parser_Node $parent_node The "updateList" AST node parent node. - * @param string|null $table_alias Optional. The target table alias. Defaults to the table name. - * @return string The translated UPDATE list. + * @param string|null $table_alias Optional. The target table alias. Defaults to the table name. + * @param array $table_alias_map Optional. The table reference map of a multi-table UPDATE. + * @see WP_MySQL_On_SQLite::create_table_reference_map() + * @return string The translated UPDATE list. */ - private function translate_update_list( string $table_name, WP_Parser_Node $parent_node, ?string $table_alias = null ): string { + private function translate_update_list( string $table_name, WP_Parser_Node $parent_node, ?string $table_alias = null, array $table_alias_map = array() ): string { $node = $parent_node->get_first_child_node( 'updateList' ); // This method is always used with the main database. @@ -6457,15 +6470,30 @@ private function translate_update_list( string $table_name, WP_Parser_Node $pare $default = $column_info['COLUMN_DEFAULT']; // Get the UPDATE value. It's either an expression or a DEFAULT keyword. + $is_string_source = null; if ( null === $expr ) { // Emulate "column = DEFAULT". $value = null === $default ? 'NULL' : $this->format_sqlite_column_default( $column_info ); + + /* + * A stored YEAR default is already a year, such as '2000' or '0000', + * so don't read it as a string, which would turn '0' into 2000. + * Older driver versions stored both DEFAULT 0 and DEFAULT '0' as '0'. + */ + if ( null !== $default && 'year' === strtolower( $data_type ) ) { + $value = sprintf( 'CAST(%s AS INTEGER)', $value ); + } } else { $value = $this->translate( $expr ); + + // The YEAR conversion depends on the source data type. + if ( 'year' === strtolower( $data_type ) ) { + $is_string_source = $this->is_string_column_ref( $expr, $column_map, $table_name, $table_alias, $table_alias_map ); + } } // Apply type casting. - $value = $this->cast_value_for_saving( $data_type, $value ); + $value = $this->cast_value_for_saving( $data_type, $value, $is_string_source ); /* * In MySQL non-STRICT mode, when a column is declared as NOT NULL, @@ -7042,17 +7070,289 @@ private function validate_foreign_key_references( WP_Parser_Node $node ): void { } } + /** + * Create a map of SELECT item aliases to column names for plain column references. + * + * The map includes the SELECT items of the query, its derived tables, and its + * common table expressions, as these provide the result columns. Subqueries in + * expressions, such as EXISTS (...), are skipped. Each alias maps to a list of + * column names with a flag that tells whether the column is a table column. + * That is the case when the SELECT reads no derived table or CTE. + * + * SELECT items without an alias get the name of their MySQL text, as in + * translate_select_item(). A name of an expression maps to a null column. + * + * For example, "SELECT q.x AS z FROM (SELECT t.a AS x FROM t) q" gives + * array( 'z' => array( array( 'x', false ) ), 'x' => array( array( 'a', true ) ) ). + * + * @param WP_Parser_Node $node The "queryExpressionOrParens" AST node. + * @return array The map of SELECT item aliases to lists of column names. + */ + private function create_select_alias_column_map( WP_Parser_Node $node ): array { + // Collect the names of common table expressions. + $cte_names = array(); + foreach ( $node->get_descendant_nodes( 'commonTableExpression' ) as $cte ) { + $cte_names[] = strtolower( $this->unquote_sqlite_identifier( $this->translate( $cte->get_first_child_node( 'identifier' ) ) ) ); + } + + // Collect the query specifications that provide result columns. + $query_specs = array(); + $nodes = array( $node ); + while ( count( $nodes ) > 0 ) { + $current = array_pop( $nodes ); + foreach ( $current->get_child_nodes() as $child ) { + if ( + 'subquery' === $child->rule_name + && 'derivedTable' !== $current->rule_name + && 'commonTableExpression' !== $current->rule_name + ) { + continue; + } + if ( 'querySpecification' === $child->rule_name ) { + $query_specs[] = $child; + } + $nodes[] = $child; + } + } + + $map = array(); + foreach ( $query_specs as $query_spec ) { + // Check whether the SELECT reads only tables, and no derived tables or CTEs. + $reads_tables = true; + $from = $query_spec->get_first_child_node( 'fromClause' ); + if ( null !== $from ) { + if ( null !== $from->get_first_descendant_node( 'derivedTable' ) ) { + $reads_tables = false; + } + foreach ( $from->get_descendant_nodes( 'tableRef' ) as $table_ref ) { + $table_ref_parts = $table_ref->get_descendant_nodes( 'identifier' ); + $table_ref_name = $this->unquote_sqlite_identifier( $this->translate( end( $table_ref_parts ) ) ); + if ( in_array( strtolower( $table_ref_name ), $cte_names, true ) ) { + $reads_tables = false; + } + } + } + + $select_item_list = $query_spec->get_first_child_node( 'selectItemList' ); + foreach ( $select_item_list ? $select_item_list->get_child_nodes( 'selectItem' ) : array() as $select_item ) { + $expr = $select_item->get_first_child_node( 'expr' ); + if ( null === $expr ) { + continue; + } + + // Check for simple and parenthesized column references. + $column_ref = $expr->get_first_descendant_node( 'columnRef' ); + $is_column_ref = null !== $column_ref + && $this->translate( $this->unnest_parenthesized_expression( $expr ) ) === $this->translate( $column_ref ); + $column_name = null; + if ( $is_column_ref ) { + $parts = $column_ref->get_descendant_nodes( 'identifier' ); + $column_name = $this->unquote_sqlite_identifier( $this->translate( end( $parts ) ) ); + } + + // The alias is an identifier or a string literal, such as 'x'. + $alias = $select_item->get_first_child_node( 'selectAlias' ); + if ( null !== $alias ) { + $name = $alias->get_first_child_node()->get_first_descendant_token()->get_value(); + } else { + $name = substr( $this->last_mysql_query, $select_item->get_start(), $select_item->get_length() ); + } + + // Skip a column without an alias, which keeps its name. + if ( null === $alias && $name === $column_name ) { + continue; + } + + $map[ $name ] = $map[ $name ] ?? array(); + $map[ $name ][] = array( $column_name, $reads_tables ); + } + } + return $map; + } + + /** + * Check whether a result column comes from a string column. + * + * SQLite reports the source table of a result column that is a plain column + * reference, also through derived tables. The result column name can be an + * alias, so the aliases are followed to the table column. + * + * @param array $column_meta The result column metadata from PDOStatement::getColumnMeta(). + * @param array $select_alias_map The map of SELECT item aliases to lists of column names. + * @return bool|null Whether the column is a CHAR, VARCHAR, or TEXT column. False when + * its data type is unknown. Null when the result isn't a column. + */ + private function is_string_result_column( array $column_meta, array $select_alias_map ): ?bool { + $table = $column_meta['table'] ?? null; + if ( null === $table || '' === $table ) { + return null; + } + + // Follow the aliases from the result column name to the table column names. + $names = array( $column_meta['name'] ); + $columns = array(); + $i = 0; + while ( $i < count( $names ) ) { + $name = $names[ $i ]; + ++$i; + if ( ! isset( $select_alias_map[ $name ] ) ) { + $columns[] = $name; + continue; + } + foreach ( $select_alias_map[ $name ] as list( $column_name, $is_table_column ) ) { + // An expression is not a column. + if ( null === $column_name ) { + return null; + } + + // A table column, or a column with the same name in a derived table or CTE. + if ( $is_table_column || $column_name === $name ) { + $columns[] = $column_name; + } elseif ( ! in_array( $column_name, $names, true ) ) { + $names[] = $column_name; + } + } + } + + $data_types = array(); + foreach ( $columns as $column ) { + $data_type = $this->get_table_column_data_type( $table, $column ); + if ( null !== $data_type ) { + $data_types[ $data_type ] = true; + } + } + return 1 === count( $data_types ) && $this->is_string_data_type( key( $data_types ) ); + } + + /** + * Get the MySQL data type of a table column from the information schema. + * + * @param string $table_name The table name. + * @param string $column_name The column name. + * @return string|null The MySQL data type, or null when the column doesn't exist. + */ + private function get_table_column_data_type( string $table_name, string $column_name ): ?string { + $is_temporary = $this->information_schema_builder->temporary_table_exists( $table_name ); + $columns_table = $this->information_schema_builder->get_table_name( $is_temporary, 'columns' ); + $data_type = $this->execute_sqlite_query( + sprintf( + 'SELECT DATA_TYPE FROM %s WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ?', + $this->quote_sqlite_identifier( $columns_table ) + ), + array( $this->get_saved_db_name( $this->main_db_name ), $table_name, $column_name ) + )->fetchColumn(); + return false === $data_type ? null : $data_type; + } + + /** + * Check whether a MySQL data type is a CHAR, VARCHAR, or TEXT type. + * + * @param string $data_type The MySQL data type. + * @return bool Whether the data type is a string type. + */ + private function is_string_data_type( string $data_type ): bool { + return str_contains( $data_type, 'char' ) || str_contains( $data_type, 'text' ); + } + + /** + * Check whether an UPDATE value is a plain column reference to a string column. + * + * Columns of the target table are resolved, such as "col", "(col)", "alias.col", + * or "db.table.col", and in a multi-table UPDATE, also columns of the other tables. + * + * @param WP_Parser_Node $expr The "expr" AST node. + * @param array $column_map The target table columns (lowercase column name => column info). + * @param string $table_name The name of the target table. + * @param string|null $table_alias The target table alias, if any. + * @param array $table_alias_map The table reference map of a multi-table UPDATE. + * @return bool|null Whether the column is a CHAR, VARCHAR, or TEXT column. False when + * its data type is unknown. Null when the value isn't a column. + */ + private function is_string_column_ref( WP_Parser_Node $expr, array $column_map, string $table_name, ?string $table_alias, array $table_alias_map ): ?bool { + $column_ref = $expr->get_first_descendant_node( 'columnRef' ); + if ( null === $column_ref ) { + return null; + } + + // Consider only simple and parenthesized column references. + $unnested_expr = $this->unnest_parenthesized_expression( $expr ); + if ( $this->translate( $unnested_expr ) !== $this->translate( $column_ref ) ) { + return null; + } + + $data_type = $this->get_column_ref_data_type( $column_ref, $column_map, $table_name, $table_alias, $table_alias_map ); + return null !== $data_type && $this->is_string_data_type( $data_type ); + } + + /** + * Get the MySQL data type of a column reference in an UPDATE value. + * + * @param WP_Parser_Node $column_ref The "columnRef" AST node. + * @param array $column_map The target table columns (lowercase column name => column info). + * @param string $table_name The name of the target table. + * @param string|null $table_alias The target table alias, if any. + * @param array $table_alias_map The table reference map of a multi-table UPDATE. + * @return string|null The MySQL data type, or null when it is unknown. + */ + private function get_column_ref_data_type( WP_Parser_Node $column_ref, array $column_map, string $table_name, ?string $table_alias, array $table_alias_map ): ?string { + // Skip the database name of a "db.table.column" reference to the main database. + $parts = $column_ref->get_descendant_nodes( 'identifier' ); + if ( 3 === count( $parts ) ) { + $database = $this->unquote_sqlite_identifier( $this->translate( $parts[0] ) ); + if ( 0 !== strcasecmp( $database, $this->main_db_name ) ) { + return null; + } + array_shift( $parts ); + } + if ( count( $parts ) > 2 ) { + return null; + } + $column_name = $this->unquote_sqlite_identifier( $this->translate( end( $parts ) ) ); + $target = $table_alias ?? $table_name; + + // A qualified column, such as "t.col". A derived table has no table name. + if ( 2 === count( $parts ) ) { + $qualifier = $this->unquote_sqlite_identifier( $this->translate( $parts[0] ) ); + if ( 0 === strcasecmp( $qualifier, $target ) ) { + return $column_map[ strtolower( $column_name ) ]['DATA_TYPE'] ?? null; + } + $other_table = $table_alias_map[ $qualifier ]['table_name'] ?? null; + return null === $other_table ? null : $this->get_table_column_data_type( $other_table, $column_name ); + } + + // An unqualified column of the target table. + if ( isset( $column_map[ strtolower( $column_name ) ] ) ) { + return $column_map[ strtolower( $column_name ) ]['DATA_TYPE']; + } + + // An unqualified column of another table. It must be unambiguous. + $data_types = array(); + foreach ( $table_alias_map as $alias => $data ) { + if ( $alias === $target || null === $data['table_name'] ) { + continue; + } + $data_type = $this->get_table_column_data_type( $data['table_name'], $column_name ); + if ( null !== $data_type ) { + $data_types[] = $data_type; + } + } + return 1 === count( $data_types ) ? $data_types[0] : null; + } + /** * Emulate MySQL type casting for values to be saved to the database * using INSERT, REPLACE, or UPDATE statements. * - * @param string $mysql_data_type The MySQL data type. - * @param string $translated_value The original translated value. - * @return string The translated value. + * @param string $mysql_data_type The MySQL data type. + * @param string $translated_value The original translated value. + * @param bool|null $is_string_source Optional. Whether the value comes from a string column, when + * it is a plain column reference. Defaults to null (no column). + * @return string The translated value. */ private function cast_value_for_saving( string $mysql_data_type, - string $translated_value + string $translated_value, + ?bool $is_string_source = null ): string { // TODO: This is also a good place to implement checks for maximum column // lengths with truncating or bailing out depending on the SQL mode. @@ -7102,25 +7402,53 @@ private function cast_value_for_saving( * The YEAR type in MySQL only uses 1 byte and therefore * covers only 256 values from 1901 to 2155 included. * Additionally: - * - Numbers from 0 to 69 correspond to years 2000 to 2069. + * - Numbers from 1 to 69 correspond to years 2001 to 2069. * - Numbers from 70 to 99 correspond to years 1970 to 1999. + * - The number 0 is the year 0000. + * - A string whose number rounds to 0 is the year 2000, unless + * it is 4 bytes long. E.g., '0', '00', or '0.0' is 2000, but + * '0000' is 0000. Like MySQL, the conversion skips leading + * spaces and tabs, and it needs a number at the start. + * + * Values of JSON, temporal, and other non-string columns are + * stored as text in SQLite, but MySQL converts them to numbers. + * For example, a JSON 0 or a DATE '0000-00-00' is the year 0000. + * Cast them to integers, so that the string rule doesn't apply. + * This also applies to columns whose data type is unknown. */ + $raw_value = $translated_value; + if ( false === $is_string_source ) { + $raw_value = sprintf( 'CAST(%s AS INTEGER)', $translated_value ); + } return sprintf( "( SELECT CASE WHEN value IS NULL THEN NULL + WHEN typeof(raw) = 'text' + AND ROUND(CAST(raw AS REAL)) = 0 + AND LENGTH(CAST(raw AS BLOB)) <> 4 + AND ( + trimmed GLOB '[0-9]*' + OR trimmed GLOB '.[0-9]*' + OR trimmed GLOB '[+-][0-9]*' + OR trimmed GLOB '[+-].[0-9]*' + ) + THEN 2000 WHEN value = 0 THEN '0000' WHEN value BETWEEN 1901 AND 2155 THEN value WHEN value BETWEEN 1 AND 69 THEN 2000 + value WHEN value BETWEEN 70 AND 99 THEN 1900 + value ELSE %s END - FROM (SELECT CAST(%s AS INTEGER) AS value) + FROM ( + SELECT raw, CAST(raw AS INTEGER) AS value, LTRIM(raw, ' ' || CHAR(9)) AS trimmed + FROM (SELECT %s AS raw) + ) )", $is_strict_mode ? sprintf( "THROW('Out of range value: ''' || %s || '''')", $translated_value ) : "'0000'", - $translated_value + $raw_value ); } diff --git a/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-builder.php b/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-builder.php index 4e5379952..59625f255 100644 --- a/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-builder.php +++ b/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-builder.php @@ -351,6 +351,16 @@ class WP_SQLite_Information_Schema_Builder { */ private $temporary_information_schema_exists = false; + /** + * Whether to keep the string zero defaults of YEAR columns as written. + * + * This is used when reconstructing the information schema of an existing + * SQLite table, as the table keeps such defaults as written as well. + * + * @var bool + */ + private $keep_year_string_zero_defaults = false; + /** * An instance of the SQLite connection. * @@ -512,6 +522,24 @@ public function ensure_temporary_information_schema_tables(): void { $this->temporary_information_schema_exists = true; } + /** + * Record the information schema of an existing SQLite table. + * + * This works like record_create_table(), but it keeps the string zero + * defaults of YEAR columns, such as '0', as written. Older driver versions + * stored such defaults as written, so the SQLite table uses them as well. + * + * @param WP_Parser_Node $node The "createStatement" AST node with "createTable" child. + */ + public function record_reconstructed_table( WP_Parser_Node $node ): void { + $this->keep_year_string_zero_defaults = true; + try { + $this->record_create_table( $node ); + } finally { + $this->keep_year_string_zero_defaults = false; + } + } + /** * Analyze CREATE TABLE statement and record data in the information schema. * @@ -2339,10 +2367,13 @@ private function get_literal_default( WP_Parser_Node $literal, string $data_type /* * Normalize numeric zero defaults to MySQL's temporal zero values. * Also normalize string zeros, even where strict MySQL rejects them. - * Preserve YEAR strings '0' and '00', which MySQL interprets as 2000. + * YEAR strings that are zero follow their own rule, e.g., '0' is 2000. */ if ( 'year' === $data_type && $literal->has_child_node( 'textLiteral' ) ) { - return $default; + if ( $this->keep_year_string_zero_defaults ) { + return $default; + } + return $this->get_year_string_zero_value( $default ) ?? $default; } return $this->get_temporal_zero_value( $data_type, $default, $datetime_precision ) ?? $default; } @@ -2422,6 +2453,25 @@ private function format_binary_default( string $bytes ): string { return '' === $bytes ? '' : '0x' . strtoupper( bin2hex( $bytes ) ); } + /** + * Get the year of a YEAR string default when the string is zero. + * + * MySQL stores a string whose number rounds to 0 as the year 2000, unless + * the string is 4 bytes long. For example, '0', '00', and '0.4' are 2000, + * while '0000' is 0000. Spaces and tabs around the number are allowed, and + * they count toward the length. The number 0, which is not a string, is 0000. + * + * @param string $default_value The YEAR column default value of a string literal. + * @return string|null The year, or null when the string is not a number that rounds to 0. + */ + private function get_year_string_zero_value( string $default_value ): ?string { + $number = trim( $default_value, " \t" ); + if ( trim( $number ) !== $number || ! is_numeric( $number ) || 0.0 !== round( (float) $number ) ) { + return null; + } + return 4 === strlen( $default_value ) ? '0000' : '2000'; + } + /** * Get the zero value of a temporal column when its default is zero. * diff --git a/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-reconstructor.php b/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-reconstructor.php index e00e439cd..f9bd91c01 100644 --- a/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-reconstructor.php +++ b/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-information-schema-reconstructor.php @@ -93,7 +93,7 @@ public function ensure_correct_information_schema(): void { */ $this->record_drop_table( $table ); - $this->schema_builder->record_create_table( $ast ); + $this->schema_builder->record_reconstructed_table( $ast ); } // Remove information schema records for tables that don't exist. diff --git a/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php b/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php index cacaa542b..bcfd5a792 100644 --- a/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php +++ b/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php @@ -8987,8 +8987,8 @@ public function testShowCreateTableWithTemporalZeroDefaults(): void { " `col_string_zero` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',", " `col_time_string_zero` time NOT NULL DEFAULT '00:00:00',", " `col_year_false` year NOT NULL DEFAULT '0000',", - " `col_year_string_zero` year NOT NULL DEFAULT '0',", - " `col_year_string_double_zero` year NOT NULL DEFAULT '00',", + " `col_year_string_zero` year NOT NULL DEFAULT '2000',", + " `col_year_string_double_zero` year NOT NULL DEFAULT '2000',", ' `col_expression` datetime NOT NULL DEFAULT (0),', " `col_int` int NOT NULL DEFAULT '0',", " `col_varchar` varchar(10) NOT NULL DEFAULT '0',", @@ -9058,6 +9058,294 @@ public function testInsertUsesTemporalZeroDefaults(): void { ); } + /** + * @dataProvider yearZeroValues + */ + public function testSavesYearZeroValues( string $value, string $expected_year ): void { + $this->assertQuery( 'CREATE TABLE _tmp_table (id INT NOT NULL, y YEAR, source VARCHAR(10))' ); + + // A number stored in the VARCHAR column becomes a string, so only strings are read from it. + $is_string = "'" === $value[0] || 0 === strpos( $value, 'CONCAT(' ); + + foreach ( array( 'STRICT_TRANS_TABLES', '' ) as $sql_mode ) { + $this->assertQuery( "SET sql_mode = '$sql_mode'" ); + $this->assertQuery( 'DELETE FROM _tmp_table' ); + + // INSERT and UPDATE with the value. + $this->assertQuery( "INSERT INTO _tmp_table (id, y) VALUES (1, $value)" ); + $this->assertQuery( 'INSERT INTO _tmp_table (id, y) VALUES (2, 1999)' ); + $this->assertQuery( "UPDATE _tmp_table SET y = $value WHERE id = 2" ); + + // INSERT ... SELECT and UPDATE with the value read from a column. + if ( $is_string ) { + $this->assertQuery( "INSERT INTO _tmp_table (id, y, source) VALUES (3, 1999, $value)" ); + $this->assertQuery( 'UPDATE _tmp_table SET y = source WHERE id = 3' ); + $this->assertQuery( 'INSERT INTO _tmp_table (id, y) SELECT 4, source FROM _tmp_table WHERE id = 3' ); + } + + $this->assertQuery( 'SELECT y FROM _tmp_table ORDER BY id' ); + $this->assertSame( + array_fill( 0, $is_string ? 4 : 2, $expected_year ), + array_column( $this->last_result, 'y' ), + "SQL mode: '$sql_mode'" + ); + } + } + + public static function yearZeroValues(): array { + /* + * MySQL stores a string whose number rounds to 0 as the year 2000, unless + * the string is 4 bytes long. The number 0 is the year 0000. + * The expected values are from MySQL 8.0.46. + */ + return array( + 'number 0' => array( '0', '0000' ), + 'number 0.4' => array( '0.4', '0000' ), + 'number 0e0' => array( '0e0', '0000' ), + 'FALSE' => array( 'FALSE', '0000' ), + "'0'" => array( "'0'", '2000' ), + "'00'" => array( "'00'", '2000' ), + "'000'" => array( "'000'", '2000' ), + "'00000'" => array( "'00000'", '2000' ), + "'0.0'" => array( "'0.0'", '2000' ), + "'.0'" => array( "'.0'", '2000' ), + "'0.4'" => array( "'0.4'", '2000' ), + "'0e0'" => array( "'0e0'", '2000' ), + "'-0'" => array( "'-0'", '2000' ), + "'+0'" => array( "'+0'", '2000' ), + "' 0'" => array( "' 0'", '2000' ), + "'0 '" => array( "'0 '", '2000' ), + 'tab and 0' => array( "CONCAT(CHAR(9), '0')", '2000' ), + "CONCAT('0', '')" => array( "CONCAT('0', '')", '2000' ), + "'0000'" => array( "'0000'", '0000' ), + "'0.00'" => array( "'0.00'", '0000' ), + "'5'" => array( "'5'", '2005' ), + "'70'" => array( "'70'", '1970' ), + ); + } + + public function testSavesYearStringsWithoutNumberAsZero(): void { + $this->assertQuery( 'CREATE TABLE _tmp_table (id INT NOT NULL, y YEAR)' ); + + // MySQL reads these as 0000 in non-strict mode, as no number starts the string. + $this->assertQuery( "SET sql_mode = ''" ); + $this->assertQuery( + "INSERT INTO _tmp_table (id, y) VALUES + (1, 'abc'), + (2, ''), + (3, '-'), + (4, CONCAT(CHAR(10), '0')), + (5, '0abc'), + (6, '00abc')" + ); + + $this->assertQuery( 'SELECT y FROM _tmp_table ORDER BY id' ); + $this->assertSame( + array( '0000', '0000', '0000', '0000', '0000', '2000' ), + array_column( $this->last_result, 'y' ) + ); + } + + public function testSavesYearZeroFromNonStringColumns(): void { + /* + * JSON and temporal values are stored as text in SQLite, but MySQL reads + * them as numbers, so their zeros are the year 0000. Only a string column, + * or an expression such as CONCAT(), gives 2000. The expected values are + * from MySQL 8.0.46. + */ + $this->assertQuery( "SET sql_mode = ''" ); + $this->assertQuery( 'CREATE TABLE _tmp_table (id INT PRIMARY KEY, y YEAR, j JSON, j_dec JSON, d DATE, dt DATETIME, t TIME, v VARCHAR(10), tx TEXT)' ); + $this->assertQuery( 'CREATE TABLE _tmp_other (id INT PRIMARY KEY, y YEAR)' ); + $this->assertQuery( "INSERT INTO _tmp_table VALUES (1, NULL, '0', '0.0', '0000-00-00', '0000-00-00 00:00:00', '00:00:00', '0', '0')" ); + + $statements = array( + 'UPDATE' => array( '_tmp_table', 'UPDATE _tmp_table SET y = %s' ), + 'UPDATE with qualified column' => array( '_tmp_table', 'UPDATE _tmp_table SET y = (_tmp_table.%s)' ), + 'UPDATE with table alias' => array( '_tmp_table', 'UPDATE _tmp_table AS a SET a.y = a.%s' ), + 'ON DUPLICATE KEY UPDATE' => array( '_tmp_table', 'INSERT INTO _tmp_table (id) VALUES (1) ON DUPLICATE KEY UPDATE y = _tmp_table.%s' ), + 'UPDATE with database name' => array( '_tmp_table', 'UPDATE _tmp_table SET y = wp._tmp_table.%s' ), + 'UPDATE with JOIN' => array( '_tmp_other', 'UPDATE _tmp_other JOIN _tmp_table AS s ON s.id = _tmp_other.id SET _tmp_other.y = s.%s' ), + 'UPDATE with other table column' => array( '_tmp_other', 'UPDATE _tmp_other, _tmp_table SET _tmp_other.y = %s WHERE _tmp_table.id = _tmp_other.id' ), + 'INSERT ... SELECT' => array( '_tmp_other', 'INSERT INTO _tmp_other (id, y) SELECT 2, %s FROM _tmp_table' ), + 'INSERT ... SELECT with an alias' => array( '_tmp_other', 'INSERT INTO _tmp_other (id, y) SELECT 2, %s AS y FROM _tmp_table' ), + 'INSERT ... SELECT, quoted alias' => array( '_tmp_other', "INSERT INTO _tmp_other (id, y) SELECT 2, %s AS 'x' FROM _tmp_table" ), + 'INSERT ... SELECT, subquery' => array( '_tmp_other', 'INSERT INTO _tmp_other (id, y) SELECT 2, q.x FROM (SELECT %s AS x FROM _tmp_table) q' ), + 'INSERT ... SELECT, same alias' => array( '_tmp_other', 'INSERT INTO _tmp_other (id, y) SELECT 2, %s AS %s FROM _tmp_table' ), + 'INSERT ... SELECT with EXISTS' => array( '_tmp_other', 'INSERT INTO _tmp_other (id, y) SELECT 2, %s FROM _tmp_table WHERE EXISTS (SELECT v AS j, j AS v FROM _tmp_table)' ), + 'INSERT ... SELECT from a CTE' => array( '_tmp_other', 'INSERT INTO _tmp_other (id, y) WITH c AS (SELECT %s AS x FROM _tmp_table) SELECT 2, x AS z FROM c' ), + 'INSERT ... SELECT, (column)' => array( '_tmp_other', 'INSERT INTO _tmp_other (id, y) SELECT 2, (%s) FROM _tmp_table' ), + 'Derived table, same alias' => array( '_tmp_other', 'INSERT INTO _tmp_other (id, y) SELECT 2, q.%s AS %s FROM (SELECT %s FROM _tmp_table) q' ), + ); + + // SQLite versions before 3.33.0 do not support UPDATE with FROM. + if ( version_compare( $this->engine->get_sqlite_version(), '3.33.0', '<' ) ) { + unset( $statements['UPDATE with JOIN'], $statements['UPDATE with other table column'] ); + } + + $expected_years = array( + 'j' => '0000', + 'j_dec' => '0000', + 'd' => '0000', + 'dt' => '0000', + 't' => '0000', + 'v' => '2000', + 'tx' => '2000', + ); + + foreach ( array( 'STRICT_TRANS_TABLES', '' ) as $sql_mode ) { + $this->assertQuery( "SET sql_mode = '$sql_mode'" ); + foreach ( $expected_years as $column => $expected_year ) { + foreach ( $statements as $name => list( $table, $statement ) ) { + $this->assertQuery( 'UPDATE _tmp_table SET y = NULL' ); + $this->assertQuery( 'DELETE FROM _tmp_other' ); + $this->assertQuery( 'INSERT INTO _tmp_other (id, y) VALUES (1, NULL)' ); + + $this->assertQuery( str_replace( '%s', $column, $statement ) ); + $this->assertQuery( "SELECT y FROM $table ORDER BY id DESC LIMIT 1" ); + $this->assertSame( $expected_year, $this->last_result[0]->y, "$name, column $column, SQL mode: '$sql_mode'" ); + } + } + + // An expression is a string, even when it reads a JSON column. + // The aliases of the derived table lead to the VARCHAR column "v". + $this->assertQuery( 'DELETE FROM _tmp_other' ); + $this->assertQuery( 'UPDATE _tmp_table SET y = CONCAT(j)' ); + $this->assertQuery( 'INSERT INTO _tmp_other (id, y) SELECT 2, CONCAT(j) FROM _tmp_table' ); + $this->assertQuery( 'INSERT INTO _tmp_other (id, y) SELECT 3, q.j FROM (SELECT v AS j, j AS v FROM _tmp_table) q' ); + + $this->assertQuery( 'INSERT INTO _tmp_other (id, y) SELECT 4, CONCAT(j) AS j FROM _tmp_table' ); + + // An alias in a subquery of the SELECT list doesn't change the derived table column. + $this->assertQuery( 'INSERT INTO _tmp_other (id, y) SELECT (SELECT MAX(s.id) + 4 FROM (SELECT id, j AS x FROM _tmp_table) s), q.x FROM (SELECT v AS x FROM _tmp_table) q' ); + + $this->assertQuery( 'SELECT y FROM _tmp_table UNION ALL SELECT y FROM _tmp_other WHERE id IN (2, 3, 4, 5)' ); + $this->assertSame( array( '2000', '2000', '2000', '2000', '2000' ), array_column( $this->last_result, 'y' ), "SQL mode: '$sql_mode'" ); + + // Aliases that can't be followed to one data type are cast as on trunk. + $this->assertQuery( 'DELETE FROM _tmp_other' ); + $this->assertQuery( 'INSERT INTO _tmp_other (id, y) SELECT 2, q.v FROM (SELECT r.v AS j, r.j AS v FROM (SELECT j, v FROM _tmp_table) r) q' ); + $this->assertQuery( 'INSERT INTO _tmp_other (id, y) SELECT 3, b.x FROM (SELECT v AS x FROM _tmp_table) a JOIN (SELECT j AS x FROM _tmp_table) b ON 1 = 1' ); + $this->assertQuery( 'INSERT INTO _tmp_other (id, y) SELECT 4, a.x FROM (SELECT j AS x FROM _tmp_table) a JOIN (SELECT v AS x FROM _tmp_table) b ON 1 = 1' ); + + // Each alias is followed one derived table at a time. + $this->assertQuery( 'INSERT INTO _tmp_other (id, y) SELECT 5, q.j FROM (SELECT r.v AS j FROM (SELECT j AS v FROM _tmp_table) r) q' ); + + $this->assertQuery( 'SELECT y FROM _tmp_other ORDER BY id' ); + $this->assertSame( array( '0000', '0000', '0000', '0000' ), array_column( $this->last_result, 'y' ), "SQL mode: '$sql_mode'" ); + + // A derived table column in a multi-table UPDATE has an unknown data type, + // so it is cast to an integer, as on trunk. MySQL also gives 0000 here. + if ( version_compare( $this->engine->get_sqlite_version(), '3.33.0', '>=' ) ) { + foreach ( array( 'j', 'j_dec', 'd', 'dt', 't' ) as $column ) { + $this->assertQuery( 'DELETE FROM _tmp_other' ); + $this->assertQuery( 'INSERT INTO _tmp_other (id, y) VALUES (1, NULL)' ); + $this->assertQuery( "UPDATE _tmp_other JOIN (SELECT $column FROM _tmp_table) q ON 1 = 1 SET _tmp_other.y = q.$column" ); + $this->assertQuery( 'SELECT y FROM _tmp_other' ); + $this->assertSame( '0000', $this->last_result[0]->y, "UPDATE with a derived table, column $column, SQL mode: '$sql_mode'" ); + } + } + } + } + + public function testYearStringZeroDefaults(): void { + $this->assertQuery( + "CREATE TABLE _tmp_table ( + id INT NOT NULL, + year_zero YEAR NOT NULL DEFAULT '0', + year_double_zero YEAR NOT NULL DEFAULT '00', + year_decimal_zero YEAR NOT NULL DEFAULT '0.0', + year_padded_zero YEAR NOT NULL DEFAULT ' 0', + year_four_zeros YEAR NOT NULL DEFAULT '0000', + year_four_char_zero YEAR NOT NULL DEFAULT '0.00', + year_number_zero YEAR NOT NULL DEFAULT 0, + year_altered YEAR NOT NULL DEFAULT '1999' + )" + ); + $this->assertQuery( "ALTER TABLE _tmp_table ALTER COLUMN year_altered SET DEFAULT '0'" ); + + $this->assertQuery( 'SHOW CREATE TABLE _tmp_table' ); + $this->assertSame( + implode( + "\n", + array( + 'CREATE TABLE `_tmp_table` (', + ' `id` int NOT NULL,', + " `year_zero` year NOT NULL DEFAULT '2000',", + " `year_double_zero` year NOT NULL DEFAULT '2000',", + " `year_decimal_zero` year NOT NULL DEFAULT '2000',", + " `year_padded_zero` year NOT NULL DEFAULT '2000',", + " `year_four_zeros` year NOT NULL DEFAULT '0000',", + " `year_four_char_zero` year NOT NULL DEFAULT '0000',", + " `year_number_zero` year NOT NULL DEFAULT '0000',", + " `year_altered` year NOT NULL DEFAULT '2000'", + ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci', + ) + ), + $this->last_result[0]->{'Create Table'} + ); + + $this->assertQuery( + "SELECT column_name, column_default FROM information_schema.columns + WHERE table_name = '_tmp_table' AND column_name IN ('year_zero', 'year_four_zeros') + ORDER BY ordinal_position" + ); + $this->assertEquals( + array( + (object) array( + 'COLUMN_NAME' => 'year_zero', + 'COLUMN_DEFAULT' => '2000', + ), + (object) array( + 'COLUMN_NAME' => 'year_four_zeros', + 'COLUMN_DEFAULT' => '0000', + ), + ), + $this->last_result + ); + + // New rows get the defaults, and so does "column = DEFAULT". + $this->assertQuery( 'INSERT INTO _tmp_table (id) VALUES (1)' ); + $this->assertQuery( "INSERT INTO _tmp_table (id, year_zero) VALUES (2, '1999')" ); + $this->assertQuery( 'UPDATE _tmp_table SET year_zero = DEFAULT WHERE id = 2' ); + $this->assertQuery( 'SELECT * FROM _tmp_table ORDER BY id' ); + $expected_row = array( + 'year_zero' => '2000', + 'year_double_zero' => '2000', + 'year_decimal_zero' => '2000', + 'year_padded_zero' => '2000', + 'year_four_zeros' => '0000', + 'year_four_char_zero' => '0000', + 'year_number_zero' => '0000', + 'year_altered' => '2000', + ); + $this->assertEquals( + array( + (object) array_merge( array( 'id' => '1' ), $expected_row ), + (object) array_merge( array( 'id' => '2' ), $expected_row ), + ), + $this->last_result + ); + } + + public function testUpdateToStoredYearZeroDefault(): void { + // Driver 3.1.x and older stored both DEFAULT 0 and DEFAULT '0' of a YEAR column as '0'. + $this->assertQuery( 'CREATE TABLE _tmp_table (id INT PRIMARY KEY, y YEAR NOT NULL DEFAULT 0)' ); + $this->sqlite->exec( + "UPDATE _wp_sqlite_mysql_information_schema_columns + SET column_default = '0' + WHERE table_name = '_tmp_table' AND column_name = 'y'" + ); + $this->assertQuery( 'OPTIMIZE TABLE _tmp_table' ); + + // Setting the column to its default still stores 0000, not 2000. + $this->assertQuery( 'INSERT INTO _tmp_table (id, y) VALUES (1, 1999), (2, 1999)' ); + $this->assertQuery( 'UPDATE _tmp_table SET y = DEFAULT WHERE id = 1' ); + $this->assertQuery( 'INSERT INTO _tmp_table (id, y) VALUES (2, 1999) ON DUPLICATE KEY UPDATE y = DEFAULT' ); + + $this->assertQuery( 'SELECT y FROM _tmp_table ORDER BY id' ); + $this->assertSame( array( '0000', '0000' ), array_column( $this->last_result, 'y' ) ); + } + public function testAlterTableWithTemporalZeroDefaults(): void { $this->assertQuery( 'CREATE TABLE _tmp_table ( @@ -9099,7 +9387,7 @@ public function testAlterTableWithTemporalZeroDefaults(): void { " `updated_on` date NOT NULL DEFAULT '0000-00-00',", " `duration` time(2) NOT NULL DEFAULT '00:00:00.00',", " `year_number` year NOT NULL DEFAULT '0000',", - " `year_string` year NOT NULL DEFAULT '0',", + " `year_string` year NOT NULL DEFAULT '2000',", " `parenthesized_zero` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',", " `false_value` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',", " `string_zero` time NOT NULL DEFAULT '00:00:00',",