Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions sqlglot/generators/postgres.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,19 @@ def func(self: PostgresGenerator, expression: DATE_ADD_OR_SUB) -> str:
return func


def _extract_sql(part: str) -> t.Callable[[PostgresGenerator, exp.Func], str]:
def func(self: PostgresGenerator, expression: exp.Func) -> str:
this = expression.this
if this.is_type(*exp.DataType.INTEGER_TYPES):
self.unsupported(f"Cannot transpile {part} of an integer value to Postgres")
if not this.is_type(exp.DType.DATE):
this = exp.cast(this, exp.DType.DATE)

return self.sql(exp.Extract(this=exp.var(part), expression=this))

return func


def _date_diff_sql(self: PostgresGenerator, expression: exp.DateDiff | exp.TsOrDsDiff) -> str:
unit = expression.text("unit").upper()
factor = DATE_DIFF_FACTOR.get(unit)
Expand Down Expand Up @@ -306,6 +319,9 @@ def lateral_sql(self, expression: exp.Lateral) -> str:
exp.DateDiff: _date_diff_sql,
exp.DateStrToDate: datestrtodate_sql,
exp.DateSub: _date_add_sql("-"),
exp.Day: _extract_sql("DAY"),
exp.Month: _extract_sql("MONTH"),
exp.Year: _extract_sql("YEAR"),
exp.Explode: rename_func("UNNEST"),
exp.ExplodingGenerateSeries: rename_func("GENERATE_SERIES"),
exp.GenerateSeries: generate_series_sql("GENERATE_SERIES"),
Expand Down
24 changes: 23 additions & 1 deletion tests/dialects/test_postgres.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from sqlglot import ParseError, UnsupportedError, exp, transpile
from sqlglot import ErrorLevel, ParseError, UnsupportedError, exp, parse_one, transpile
from sqlglot.helper import logger as helper_logger
from sqlglot.optimizer.annotate_types import annotate_types
from tests.dialects.test_dialect import Validator


Expand Down Expand Up @@ -1765,6 +1766,27 @@ def test_round(self):
"ROUND(CAST(x AS DECIMAL(18, 3)), 4)", read={"duckdb": "ROUND(x::DECIMAL, 4)"}
)

def test_extract_date_parts(self):
# T-SQL DAY/MONTH/YEAR accept non-date inputs, so the argument is cast to DATE
self.validate_all(
"SELECT EXTRACT(DAY FROM CAST(x AS DATE)), EXTRACT(MONTH FROM CAST(x AS DATE)), EXTRACT(YEAR FROM CAST(x AS DATE))",
read={
"tsql": "SELECT DAY(x), MONTH(x), YEAR(x)",
},
)

# An argument already typed as DATE is not cast again
self.assertEqual(
annotate_types(parse_one("SELECT DAY(CAST(x AS DATE))", read="tsql")).sql("postgres"),
"SELECT EXTRACT(DAY FROM CAST(x AS DATE))",
)

# Integer arguments rely on T-SQL's 1900-01-01 epoch and aren't supported yet
with self.assertRaises(UnsupportedError):
annotate_types(parse_one("SELECT DAY(0)", read="tsql")).sql(
"postgres", unsupported_level=ErrorLevel.RAISE
)

def test_datatype(self):
self.assertEqual(exp.DataType.build("XML", dialect="postgres").sql("postgres"), "XML")
self.validate_identity("CREATE TABLE foo (data XML)")
Expand Down
Loading