Skip to content

Commit

Permalink
feat(postgres): Support JSONB_EXISTS (#4302)
Browse files Browse the repository at this point in the history
  • Loading branch information
VaggelisD authored Oct 28, 2024
1 parent a66e721 commit efd9b4e
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 0 deletions.
1 change: 1 addition & 0 deletions sqlglot/dialects/duckdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -536,6 +536,7 @@ class Generator(generator.Generator):
exp.IntDiv: lambda self, e: self.binary(e, "//"),
exp.IsInf: rename_func("ISINF"),
exp.IsNan: rename_func("ISNAN"),
exp.JSONBExists: rename_func("JSON_EXISTS"),
exp.JSONExtract: _arrow_json_extract_sql,
exp.JSONExtractScalar: _arrow_json_extract_sql,
exp.JSONFormat: _json_format_sql,
Expand Down
9 changes: 9 additions & 0 deletions sqlglot/dialects/postgres.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,7 @@ class Parser(parser.Parser):
FUNCTION_PARSERS = {
**parser.Parser.FUNCTION_PARSERS,
"DATE_PART": lambda self: self._parse_date_part(),
"JSONB_EXISTS": lambda self: self._parse_jsonb_exists(),
}

BITWISE = {
Expand Down Expand Up @@ -443,6 +444,14 @@ def _parse_date_part(self) -> exp.Expression:
def _parse_unique_key(self) -> t.Optional[exp.Expression]:
return None

def _parse_jsonb_exists(self) -> exp.JSONBExists:
return self.expression(
exp.JSONBExists,
this=self._parse_bitwise(),
path=self._match(TokenType.COMMA)
and self.dialect.to_json_path(self._parse_bitwise()),
)

class Generator(generator.Generator):
SINGLE_STRING_INTERVAL = True
RENAME_TABLE_WITH_DB = False
Expand Down
5 changes: 5 additions & 0 deletions sqlglot/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5960,6 +5960,11 @@ class JSONBContains(Binary, Func):
_sql_names = ["JSONB_CONTAINS"]


class JSONBExists(Func):
arg_types = {"this": True, "path": True}
_sql_names = ["JSONB_EXISTS"]


class JSONExtract(Binary, Func):
arg_types = {
"this": True,
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 @@ -797,6 +797,14 @@ def test_postgres(self):
self.validate_identity("SELECT OVERLAY(a PLACING b FROM 1 FOR 1)")
self.validate_identity("ARRAY[1, 2, 3] && ARRAY[1, 2]").assert_is(exp.ArrayOverlaps)

self.validate_all(
"""SELECT JSONB_EXISTS('{"a": [1,2,3]}', 'a')""",
write={
"postgres": """SELECT JSONB_EXISTS('{"a": [1,2,3]}', 'a')""",
"duckdb": """SELECT JSON_EXISTS('{"a": [1,2,3]}', '$.a')""",
},
)

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 efd9b4e

Please sign in to comment.