Skip to content

Commit f3cb2fa

Browse files
authored
Fix: cast NULLs in VALUES clause (df->values) to avoid coercion issues (#2856)
1 parent 0ac5726 commit f3cb2fa

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

sqlmesh/core/dialect.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -897,6 +897,14 @@ def select_from_values_for_batch_range(
897897
]
898898

899899
values_exp = exp.values(expressions, alias=alias, columns=columns_to_types)
900+
if values:
901+
# BigQuery crashes on `SELECT CAST(x AS TIMESTAMP) FROM UNNEST([NULL]) AS x`, but not
902+
# on `SELECT CAST(x AS TIMESTAMP) FROM UNNEST([CAST(NULL AS TIMESTAMP)]) AS x`. This
903+
# ensures nulls under the `Values` expression are cast to avoid similar issues.
904+
for value, kind in zip(values_exp.expressions[0].expressions, columns_to_types.values()):
905+
if isinstance(value, exp.Null):
906+
value.replace(exp.cast(value, to=kind))
907+
900908
return exp.select(*casted_columns).from_(values_exp, copy=False).where(where, copy=False)
901909

902910

tests/core/test_dialect.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,20 @@ def test_select_from_values_for_batch_range_json():
375375
)
376376

377377

378+
def test_select_from_values_that_include_null():
379+
values = [(1, exp.null())]
380+
columns_to_types = {
381+
"id": exp.DataType.build("int", dialect="bigquery"),
382+
"ts": exp.DataType.build("timestamp", dialect="bigquery"),
383+
}
384+
385+
values_expr = select_from_values_for_batch_range(values, columns_to_types, 0, len(values))
386+
assert values_expr.sql(dialect="bigquery") == (
387+
"SELECT CAST(id AS INT64) AS id, CAST(ts AS TIMESTAMP) AS ts FROM "
388+
"UNNEST([STRUCT(1 AS id, CAST(NULL AS TIMESTAMP) AS ts)]) AS t"
389+
)
390+
391+
378392
@pytest.fixture(params=["mysql", "duckdb", "postgres", "snowflake"])
379393
def normalization_dialect(request):
380394
if request.param == "duckdb":

0 commit comments

Comments
 (0)