Skip to content

Conversation

@georgesittas
Copy link
Collaborator

@georgesittas georgesittas commented May 30, 2025

Fixes #5127

Today, we convert TIMESTAMP into DATETIME for MySQL. This is incorrect, and I'll use the following example to explain why:

mysql> CREATE TABLE foo (ts TIMESTAMP, dt DATETIME);
Query OK, 0 rows affected (0.028 sec)

mysql> INSERT INTO foo (ts, dt) VALUES ('2025-05-30 12:00:00', '2025-05-30 12:00:00');
Query OK, 1 row affected (0.005 sec)

mysql> SELECT * FROM foo WHERE ts = '2025-05-30 12:00:00';
+---------------------+---------------------+
| ts                  | dt                  |
+---------------------+---------------------+
| 2025-05-30 12:00:00 | 2025-05-30 12:00:00 |
+---------------------+---------------------+
1 row in set (0.001 sec)

mysql> SELECT * FROM foo WHERE dt = '2025-05-30 12:00:00';
+---------------------+---------------------+
| ts                  | dt                  |
+---------------------+---------------------+
| 2025-05-30 12:00:00 | 2025-05-30 12:00:00 |
+---------------------+---------------------+
1 row in set (0.001 sec)

mysql> SET time_zone = '-05:00'; -- TIMESTAMP values are time-zone aware, so this impacts them
Query OK, 0 rows affected (0.001 sec)

mysql> SELECT * FROM foo WHERE ts = '2025-05-30 12:00:00'; -- Notice how this doesn't return anything now
Empty set (0.001 sec)

mysql> SELECT * FROM foo WHERE dt = '2025-05-30 12:00:00'; -- Notice how DATETIME values are unaffected
+---------------------+---------------------+
| ts                  | dt                  |
+---------------------+---------------------+
| 2025-05-30 04:00:00 | 2025-05-30 12:00:00 |
+---------------------+---------------------+
1 row in set (0.000 sec)

By transpiling TIMESTAMP into DATETIME, SQLGlot incorrectly changes the type semantics. Specifically, with this transformation, the 2nd-to-last query would return 1 row if we used SQLGlot's transformed DDL, because we'd essentially be running the last query (ts and dt would be both DATETIME values).

Reference: https://dev.mysql.com/doc/refman/8.4/en/datetime.html

@georgesittas georgesittas merged commit e73ddb7 into main May 30, 2025
6 checks passed
@georgesittas georgesittas deleted the jo/fix_mysql_timestamp branch May 30, 2025 15:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

transpile changes the column type

4 participants