diff --git a/sqlglot/generators/mysql.py b/sqlglot/generators/mysql.py index 005f129420..69064f7256 100644 --- a/sqlglot/generators/mysql.py +++ b/sqlglot/generators/mysql.py @@ -210,6 +210,7 @@ class MySQLGenerator(generator.Generator): ), exp.TimestampSub: date_add_interval_sql("DATE", "SUB"), exp.TimeStrToUnix: rename_func("UNIX_TIMESTAMP"), + exp.TimeToUnix: rename_func("UNIX_TIMESTAMP"), exp.TimeStrToTime: lambda self, e: timestrtotime_sql( self, e, diff --git a/sqlglot/parsers/mysql.py b/sqlglot/parsers/mysql.py index 9e12db7478..8662abb925 100644 --- a/sqlglot/parsers/mysql.py +++ b/sqlglot/parsers/mysql.py @@ -33,6 +33,16 @@ def _has_time_specifier(date_format: str) -> bool: return False +def _build_unix_timestamp(args: list) -> exp.TimeToUnix: + # UNIX_TIMESTAMP(): with no arg, convert the current timestamp to epoch seconds + if not args: + return exp.TimeToUnix(this=exp.CurrentTimestamp()) + + # UNIX_TIMESTAMP(ts): the arg may be a string, so cast it to a timestamp first + # and then convert to epoch seconds + return exp.TimeToUnix(this=exp.TsOrDsToTimestamp(this=args[0])) + + def _str_to_date(args: list) -> exp.StrToDate | exp.StrToTime: mysql_date_format = seq_get(args, 1) date_format = Dialect["mysql"].format_time(mysql_date_format) @@ -143,6 +153,7 @@ class MySQLParser(parser.Parser): ) + 1 ), + "UNIX_TIMESTAMP": _build_unix_timestamp, "VERSION": exp.CurrentVersion.from_arg_list, "WEEK": lambda args: exp.Week( this=exp.TsOrDsToDate(this=seq_get(args, 0)), mode=seq_get(args, 1) diff --git a/tests/dialects/test_mysql.py b/tests/dialects/test_mysql.py index b1eb4f455a..c0c766cd92 100644 --- a/tests/dialects/test_mysql.py +++ b/tests/dialects/test_mysql.py @@ -488,6 +488,27 @@ def test_canonical_functions(self): "tsql": "CHAR(10)", }, ) + self.validate_all( + "SELECT UNIX_TIMESTAMP(ts)", + write={ + "mysql": "SELECT UNIX_TIMESTAMP(CAST(ts AS DATETIME))", + "duckdb": "SELECT EPOCH(CAST(ts AS TIMESTAMP))", + }, + ) + self.validate_all( + "SELECT UNIX_TIMESTAMP('2021-01-01 00:00:00')", + write={ + "mysql": "SELECT UNIX_TIMESTAMP(CAST('2021-01-01 00:00:00' AS DATETIME))", + "duckdb": "SELECT EPOCH(CAST('2021-01-01 00:00:00' AS TIMESTAMP))", + }, + ) + self.validate_all( + "SELECT UNIX_TIMESTAMP()", + write={ + "mysql": "SELECT UNIX_TIMESTAMP(CURRENT_TIMESTAMP())", + "duckdb": "SELECT EPOCH(CURRENT_TIMESTAMP)", + }, + ) self.validate_identity("CREATE TABLE t (foo VARBINARY(5))") self.validate_all( "CREATE TABLE t (foo BLOB)",