Skip to content

Commit

Permalink
Feat!: transpile postgres DATE_BIN function to duckdb TIME_BUCKET (#4681
Browse files Browse the repository at this point in the history
)

* translate postgres DATE_BIN function to duckdb TIME_BUCKET

* styling

* Update sqlglot/dialects/postgres.py

Co-authored-by: Jo <46752250+georgesittas@users.noreply.github.com>

* cr fixes

---------

Co-authored-by: Jo <46752250+georgesittas@users.noreply.github.com>
  • Loading branch information
dor-bernstein and georgesittas authored Jan 29, 2025
1 parent 69680c1 commit f6482fb
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 0 deletions.
2 changes: 2 additions & 0 deletions sqlglot/dialects/duckdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,7 @@ class Parser(parser.Parser):
"STRUCT_PACK": exp.Struct.from_arg_list,
"STR_SPLIT": exp.Split.from_arg_list,
"STR_SPLIT_REGEX": exp.RegexpSplit.from_arg_list,
"TIME_BUCKET": exp.DateBin.from_arg_list,
"TO_TIMESTAMP": exp.UnixToTime.from_arg_list,
"UNNEST": exp.Explode.from_arg_list,
"XOR": binary_from_function(exp.BitwiseXor),
Expand Down Expand Up @@ -664,6 +665,7 @@ class Generator(generator.Generator):
),
exp.JSONObjectAgg: rename_func("JSON_GROUP_OBJECT"),
exp.JSONBObjectAgg: rename_func("JSON_GROUP_OBJECT"),
exp.DateBin: rename_func("TIME_BUCKET"),
}

SUPPORTED_JSON_PATH_PARTS = {
Expand Down
4 changes: 4 additions & 0 deletions sqlglot/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5640,6 +5640,10 @@ class DateAdd(Func, IntervalOp):
arg_types = {"this": True, "expression": True, "unit": False}


class DateBin(Func, IntervalOp):
arg_types = {"this": True, "expression": True, "unit": False, "zone": False}


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

Expand Down
8 changes: 8 additions & 0 deletions tests/dialects/test_postgres.py
Original file line number Diff line number Diff line change
Expand Up @@ -857,6 +857,14 @@ def test_postgres(self):
},
)

self.validate_all(
"SELECT DATE_BIN('30 days', timestamp_col, (SELECT MIN(TIMESTAMP) from table)) FROM table",
write={
"postgres": "SELECT DATE_BIN('30 days', timestamp_col, (SELECT MIN(TIMESTAMP) FROM table)) FROM table",
"duckdb": 'SELECT TIME_BUCKET(\'30 days\', timestamp_col, (SELECT MIN(TIMESTAMP) FROM "table")) FROM "table"',
},
)

def test_ddl(self):
# Checks that user-defined types are parsed into DataType instead of Identifier
self.parse_one("CREATE TABLE t (a udt)").this.expressions[0].args["kind"].assert_is(
Expand Down

0 comments on commit f6482fb

Please sign in to comment.