Skip to content

Commit

Permalink
Fix(bigquery): type-annotated array literal logic edge case
Browse files Browse the repository at this point in the history
  • Loading branch information
georgesittas committed Feb 10, 2025
1 parent f7e22d4 commit 0458b3f
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
7 changes: 6 additions & 1 deletion sqlglot/dialects/bigquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -1245,7 +1245,12 @@ def contains_sql(self, expression: exp.Contains) -> str:
def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
this = expression.this

# This ensures that inline type-annotated ARRAY literals like ARRAY<INT64>[1, 2, 3]
# are roundtripped unaffected. The inner check excludes ARRAY(SELECT ...) expressions,
# because they aren't literals and so the above syntax is invalid BigQuery.
if isinstance(this, exp.Array):
return f"{self.sql(expression, 'to')}{self.sql(this)}"
elem = seq_get(this.expressions, 0)
if not (elem and elem.find(exp.Query)):
return f"{self.sql(expression, 'to')}{self.sql(this)}"

return super().cast_sql(expression, safe_prefix=safe_prefix)
4 changes: 4 additions & 0 deletions tests/dialects/test_bigquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,10 @@ def test_bigquery(self):
self.validate_identity(
"CREATE OR REPLACE VIEW test (tenant_id OPTIONS (description='Test description on table creation')) AS SELECT 1 AS tenant_id, 1 AS customer_id",
)
self.validate_identity(
"ARRAY(SELECT AS STRUCT e.x AS y, e.z AS bla FROM UNNEST(bob))::ARRAY<STRUCT<y STRING, bro NUMERIC>>",
"CAST(ARRAY(SELECT AS STRUCT e.x AS y, e.z AS bla FROM UNNEST(bob)) AS ARRAY<STRUCT<y STRING, bro NUMERIC>>)",
)
self.validate_identity(
"SELECT * FROM `proj.dataset.INFORMATION_SCHEMA.SOME_VIEW`",
"SELECT * FROM `proj.dataset.INFORMATION_SCHEMA.SOME_VIEW` AS `proj.dataset.INFORMATION_SCHEMA.SOME_VIEW`",
Expand Down

0 comments on commit 0458b3f

Please sign in to comment.