Skip to content

Commit

Permalink
Fix(snowflake): Handle form of CONVERT_TIMEZONE with a source TZ (tob…
Browse files Browse the repository at this point in the history
…ymao#1598)

* Fix(snowflake): Handle form of CONVERT_TIMEZONE with a source TZ

Snowflake's [CONVERT_TIMEZONE](https://docs.snowflake.com/en/sql-reference/functions/convert_timezone) allows optionally specifying a source timezone for columns without timezone information. This currently causes incorrect SQL to be generated when parsed and re-rendered.

* Address code review comments
  • Loading branch information
pmsanford authored and adrianisk committed Jun 21, 2023
1 parent 698653c commit 85aca66
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
11 changes: 7 additions & 4 deletions sqlglot/dialects/snowflake.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,12 @@ def _datatype_sql(self: generator.Generator, expression: exp.DataType) -> str:
return self.datatype_sql(expression)


def _parse_convert_timezone(args: t.Sequence) -> exp.Expression:
if len(args) == 3:
return exp.Anonymous(this="CONVERT_TIMEZONE", expressions=args)
return exp.AtTimeZone(this=seq_get(args, 1), zone=seq_get(args, 0))


class Snowflake(Dialect):
null_ordering = "nulls_are_large"
time_format = "'yyyy-mm-dd hh24:mi:ss'"
Expand Down Expand Up @@ -184,10 +190,7 @@ class Parser(parser.Parser):
"ARRAYAGG": exp.ArrayAgg.from_arg_list,
"ARRAY_CONSTRUCT": exp.Array.from_arg_list,
"ARRAY_TO_STRING": exp.ArrayJoin.from_arg_list,
"CONVERT_TIMEZONE": lambda args: exp.AtTimeZone(
this=seq_get(args, 1),
zone=seq_get(args, 0),
),
"CONVERT_TIMEZONE": _parse_convert_timezone,
"DATE_TRUNC": date_trunc_to_time,
"DATEADD": lambda args: exp.DateAdd(
this=seq_get(args, 2),
Expand Down
1 change: 1 addition & 0 deletions tests/dialects/test_snowflake.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ def test_snowflake(self):
'COPY INTO NEW_TABLE ("foo", "bar") FROM (SELECT $1, $2, $3, $4 FROM @%old_table)'
)
self.validate_identity("COMMENT IF EXISTS ON TABLE foo IS 'bar'")
self.validate_identity("SELECT CONVERT_TIMEZONE('UTC', 'America/Los_Angeles', col)")

self.validate_all(
"SELECT i, p, o FROM qt QUALIFY ROW_NUMBER() OVER (PARTITION BY p ORDER BY o) = 1",
Expand Down

0 comments on commit 85aca66

Please sign in to comment.