Skip to content

Commit

Permalink
PR Feedback 1
Browse files Browse the repository at this point in the history
  • Loading branch information
geooo109 committed Dec 19, 2024
1 parent d654ee8 commit 79e92c3
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 11 deletions.
11 changes: 6 additions & 5 deletions sqlglot/dialects/tsql.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,14 +370,14 @@ def _timestrtotime_sql(self: TSQL.Generator, expression: exp.TimeStrToTime):
return sql


def _parse_datetrunc(args: t.List) -> exp.TimestampTrunc:
def _build_datetrunc(args: t.List) -> exp.TimestampTrunc:
unit = seq_get(args, 0)
this = seq_get(args, 1)

if isinstance(this, exp.Expression) and this.is_string:
this = exp.TimeStrToTime(this=this)
if this and this.is_string:
this = exp.cast(this, exp.DataType.Type.DATETIME2)

return exp.TimestampTrunc(unit=unit, this=this)
return exp.TimestampTrunc(this=this, unit=unit)


class TSQL(Dialect):
Expand Down Expand Up @@ -580,7 +580,7 @@ class Parser(parser.Parser):
"SUSER_SNAME": exp.CurrentUser.from_arg_list,
"SYSTEM_USER": exp.CurrentUser.from_arg_list,
"TIMEFROMPARTS": _build_timefromparts,
"DATETRUNC": _parse_datetrunc,
"DATETRUNC": _build_datetrunc,
}

JOIN_HINTS = {"LOOP", "HASH", "MERGE", "REMOTE"}
Expand Down Expand Up @@ -947,6 +947,7 @@ class Generator(generator.Generator):
exp.Trim: trim_sql,
exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True),
exp.TsOrDsDiff: date_delta_sql("DATEDIFF"),
exp.TimestampTrunc: lambda self, e: self.func("DATETRUNC", e.unit, e.this),
}

TRANSFORMS.pop(exp.ReturnsProperty)
Expand Down
20 changes: 14 additions & 6 deletions tests/dialects/test_tsql.py
Original file line number Diff line number Diff line change
Expand Up @@ -2091,18 +2091,26 @@ def test_next_value_for(self):
},
)

# string literals in the DATETRUNC are casted as DATETIME2
def test_datetrunc(self):
self.validate_all(
"SELECT DATETRUNC(month, '2021-12-08 11:30:15.1234567')",
"SELECT DATETRUNC(month, 'foo')",
write={
"duckdb": "SELECT DATE_TRUNC('MONTH', CAST('2021-12-08 11:30:15.1234567' AS TIMESTAMP))"
"duckdb": "SELECT DATE_TRUNC('MONTH', CAST('foo' AS TIMESTAMP))",
"tsql": "SELECT DATETRUNC(MONTH, CAST('foo' AS DATETIME2))",
},
)
self.validate_all(
"SELECT DATETRUNC(year, DATEFROMPARTS(2010, 12, 31))",
write={"duckdb": "SELECT DATE_TRUNC('YEAR', MAKE_DATE(2010, 12, 31))"},
"SELECT DATETRUNC(month, foo)",
write={
"duckdb": "SELECT DATE_TRUNC('MONTH', foo)",
"tsql": "SELECT DATETRUNC(MONTH, foo)",
},
)
self.validate_all(
"SELECT DATETRUNC(year, CAST('2021-12-08' AS date))",
write={"duckdb": "SELECT DATE_TRUNC('YEAR', CAST('2021-12-08' AS DATE))"},
"SELECT DATETRUNC(year, CAST('foo1' AS date))",
write={
"duckdb": "SELECT DATE_TRUNC('YEAR', CAST('foo1' AS DATE))",
"tsql": "SELECT DATETRUNC(YEAR, CAST('foo1' AS DATE))",
},
)

0 comments on commit 79e92c3

Please sign in to comment.