Skip to content

Commit

Permalink
fix(mysql): TIMESTAMP -> CAST (#2223)
Browse files Browse the repository at this point in the history
* fix(mysql): TIMESTAMP -> CAST

* fixup

* move to generator
  • Loading branch information
barakalon authored Sep 15, 2023
1 parent 2fa4043 commit 857e380
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 0 deletions.
1 change: 1 addition & 0 deletions sqlglot/dialects/presto.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,7 @@ class Generator(generator.Generator):
exp.WithinGroup: transforms.preprocess(
[transforms.remove_within_group_for_percentiles]
),
exp.Timestamp: transforms.preprocess([transforms.timestamp_to_cast]),
}

def interval_sql(self, expression: exp.Interval) -> str:
Expand Down
4 changes: 4 additions & 0 deletions sqlglot/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -4372,6 +4372,10 @@ class Extract(Func):
arg_types = {"this": True, "expression": True}


class Timestamp(Func):
arg_types = {"this": False, "expression": False}


class TimestampAdd(Func, TimeUnit):
arg_types = {"this": True, "expression": True, "unit": False}

Expand Down
9 changes: 9 additions & 0 deletions sqlglot/transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,3 +327,12 @@ def _to_sql(self, expression: exp.Expression) -> str:
raise ValueError(f"Unsupported expression type {expression.__class__.__name__}.")

return _to_sql


def timestamp_to_cast(expression: exp.Expression) -> exp.Expression:
if isinstance(expression, exp.Timestamp) and not expression.expression:
return exp.cast(
expression.this,
to=exp.DataType.Type.TIMESTAMP,
)
return expression
4 changes: 4 additions & 0 deletions tests/dialects/test_presto.py
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,10 @@ def test_time(self):
write={"presto": "CAST(x AS TIMESTAMP)"},
read={"mysql": "CAST(x AS DATETIME)", "clickhouse": "CAST(x AS DATETIME64)"},
)
self.validate_all(
"CAST(x AS TIMESTAMP)",
read={"mysql": "TIMESTAMP(x)"},
)

def test_ddl(self):
self.validate_all(
Expand Down

0 comments on commit 857e380

Please sign in to comment.