Skip to content

Commit b918ff1

Browse files
authored
Fix(bigquery): type-annotated array literal logic edge case (#4724)
1 parent f7e22d4 commit b918ff1

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

sqlglot/dialects/bigquery.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1245,7 +1245,12 @@ def contains_sql(self, expression: exp.Contains) -> str:
12451245
def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
12461246
this = expression.this
12471247

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

12511256
return super().cast_sql(expression, safe_prefix=safe_prefix)

tests/dialects/test_bigquery.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,10 @@ def test_bigquery(self):
234234
self.validate_identity(
235235
"CREATE OR REPLACE VIEW test (tenant_id OPTIONS (description='Test description on table creation')) AS SELECT 1 AS tenant_id, 1 AS customer_id",
236236
)
237+
self.validate_identity(
238+
"ARRAY(SELECT AS STRUCT e.x AS y, e.z AS bla FROM UNNEST(bob))::ARRAY<STRUCT<y STRING, bro NUMERIC>>",
239+
"CAST(ARRAY(SELECT AS STRUCT e.x AS y, e.z AS bla FROM UNNEST(bob)) AS ARRAY<STRUCT<y STRING, bro NUMERIC>>)",
240+
)
237241
self.validate_identity(
238242
"SELECT * FROM `proj.dataset.INFORMATION_SCHEMA.SOME_VIEW`",
239243
"SELECT * FROM `proj.dataset.INFORMATION_SCHEMA.SOME_VIEW` AS `proj.dataset.INFORMATION_SCHEMA.SOME_VIEW`",

0 commit comments

Comments
 (0)