Skip to content

Commit

Permalink
Feat(duckdb): support TO_JSON (#1803)
Browse files Browse the repository at this point in the history
* Feat(duckdb): support TO_JSON

* remove type logic
  • Loading branch information
r1b authored Jun 19, 2023
1 parent 4da37aa commit a2bf084
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 0 deletions.
6 changes: 6 additions & 0 deletions sqlglot/dialects/duckdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,11 @@ def _regexp_extract_sql(self: generator.Generator, expression: exp.RegexpExtract
)


def _json_format_sql(self: generator.Generator, expression: exp.JSONFormat) -> str:
sql = self.func("TO_JSON", expression.this, expression.args.get("options"))
return f"CAST({sql} AS TEXT)"


class DuckDB(Dialect):
NULL_ORDERING = "nulls_are_last"

Expand Down Expand Up @@ -195,6 +200,7 @@ class Generator(generator.Generator):
exp.IntDiv: lambda self, e: self.binary(e, "//"),
exp.JSONExtract: arrow_json_extract_sql,
exp.JSONExtractScalar: arrow_json_extract_scalar_sql,
exp.JSONFormat: _json_format_sql,
exp.JSONBExtract: arrow_json_extract_sql,
exp.JSONBExtractScalar: arrow_json_extract_scalar_sql,
exp.LogicalOr: rename_func("BOOL_OR"),
Expand Down
1 change: 1 addition & 0 deletions tests/dialects/test_bigquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,7 @@ def test_bigquery(self):
read={"bigquery": "TO_JSON_STRING(x)"},
write={
"bigquery": "TO_JSON_STRING(x)",
"duckdb": "CAST(TO_JSON(x) AS TEXT)",
"presto": "JSON_FORMAT(x)",
"spark": "TO_JSON(x)",
},
Expand Down
2 changes: 2 additions & 0 deletions tests/dialects/test_presto.py
Original file line number Diff line number Diff line change
Expand Up @@ -665,6 +665,7 @@ def test_presto(self):
},
write={
"bigquery": "TO_JSON_STRING(x)",
"duckdb": "CAST(TO_JSON(x) AS TEXT)",
"presto": "JSON_FORMAT(x)",
"spark": "TO_JSON(x)",
},
Expand All @@ -674,6 +675,7 @@ def test_presto(self):
"JSON_FORMAT(JSON 'x')",
write={
"bigquery": "TO_JSON_STRING(CAST('x' AS JSON))",
"duckdb": "CAST(TO_JSON(CAST('x' AS JSON)) AS TEXT)",
"presto": "JSON_FORMAT(CAST('x' AS JSON))",
"spark": "TO_JSON('x')",
},
Expand Down

0 comments on commit a2bf084

Please sign in to comment.