Skip to content

Commit

Permalink
feat(postgres): Support DIV() func for integer division
Browse files Browse the repository at this point in the history
  • Loading branch information
VaggelisD committed Jun 5, 2024
1 parent ff55ec1 commit 6d065b2
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 0 deletions.
4 changes: 4 additions & 0 deletions sqlglot/dialects/postgres.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
Dialect,
JSON_EXTRACT_TYPE,
any_value_to_max_sql,
binary_from_function,
bool_xor_sql,
datestrtodate_sql,
build_formatted_time,
Expand Down Expand Up @@ -338,6 +339,7 @@ class Tokenizer(tokens.Tokenizer):
"REGTYPE": TokenType.OBJECT_IDENTIFIER,
"FLOAT": TokenType.DOUBLE,
}
KEYWORDS.pop("DIV")

SINGLE_TOKENS = {
**tokens.Tokenizer.SINGLE_TOKENS,
Expand All @@ -356,6 +358,7 @@ class Parser(parser.Parser):
FUNCTIONS = {
**parser.Parser.FUNCTIONS,
"DATE_TRUNC": build_timestamp_trunc,
"DIV": binary_from_function(exp.IntDiv),
"GENERATE_SERIES": _build_generate_series,
"JSON_EXTRACT_PATH": build_json_extract_path(exp.JSONExtract),
"JSON_EXTRACT_PATH_TEXT": build_json_extract_path(exp.JSONExtractScalar),
Expand Down Expand Up @@ -504,6 +507,7 @@ class Generator(generator.Generator):
exp.DateSub: _date_add_sql("-"),
exp.Explode: rename_func("UNNEST"),
exp.GroupConcat: _string_agg_sql,
exp.IntDiv: rename_func("DIV"),
exp.JSONExtract: _json_extract_sql("JSON_EXTRACT_PATH", "->"),
exp.JSONExtractScalar: _json_extract_sql("JSON_EXTRACT_PATH_TEXT", "->>"),
exp.JSONBExtract: lambda self, e: self.binary(e, "#>"),
Expand Down
5 changes: 5 additions & 0 deletions tests/dialects/test_bigquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -1083,9 +1083,14 @@ def test_bigquery(self):
)
self.validate_all(
"DIV(x, y)",
read={
"duckdb": "x // y",
"postgres": "DIV(x, y)",
},
write={
"bigquery": "DIV(x, y)",
"duckdb": "x // y",
"postgres": "DIV(x, y)",
},
)
self.validate_all(
Expand Down
1 change: 1 addition & 0 deletions tests/dialects/test_postgres.py
Original file line number Diff line number Diff line change
Expand Up @@ -723,6 +723,7 @@ def test_postgres(self):
self.validate_identity("cast(a as FLOAT)", "CAST(a AS DOUBLE PRECISION)")
self.validate_identity("cast(a as FLOAT8)", "CAST(a AS DOUBLE PRECISION)")
self.validate_identity("cast(a as FLOAT4)", "CAST(a AS REAL)")
self.validate_identity("DIV(5, 4)").assert_is(exp.IntDiv)

def test_ddl(self):
# Checks that user-defined types are parsed into DataType instead of Identifier
Expand Down

0 comments on commit 6d065b2

Please sign in to comment.