Skip to content

Commit e4b8bf4

Browse files
committed
Fix: qualify all columns in the table diff source/target query scope
1 parent be92ff8 commit e4b8bf4

2 files changed

Lines changed: 11 additions & 4 deletions

File tree

sqlmesh/core/table_diff.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from sqlglot.helper import ensure_list
1313
from sqlglot.optimizer.normalize_identifiers import normalize_identifiers
1414
from sqlglot.optimizer.qualify_columns import quote_identifiers
15+
from sqlglot.optimizer.scope import find_all_in_scope
1516

1617
from sqlmesh.utils.pydantic import PydanticModel
1718

@@ -314,21 +315,27 @@ def name(e: exp.Expression) -> str:
314315

315316
source_query = (
316317
exp.select(
317-
*(exp.column(c, "s") for c in source_schema),
318+
*(exp.column(c) for c in source_schema),
318319
self.source_key_expression.as_(SQLMESH_JOIN_KEY_COL),
319320
)
320321
.from_(self.source_table.as_("s"))
321322
.where(self.where)
322323
)
323324
target_query = (
324325
exp.select(
325-
*(exp.column(c, "t") for c in target_schema),
326+
*(exp.column(c) for c in target_schema),
326327
self.target_key_expression.as_(SQLMESH_JOIN_KEY_COL),
327328
)
328329
.from_(self.target_table.as_("t"))
329330
.where(self.where)
330331
)
331332

333+
# Ensure every column is qualified with the alias in the source and target queries
334+
for col in find_all_in_scope(source_query, exp.Column):
335+
col.set("table", exp.to_identifier("s"))
336+
for col in find_all_in_scope(target_query, exp.Column):
337+
col.set("table", exp.to_identifier("t"))
338+
332339
source_table = exp.table_("__source")
333340
target_table = exp.table_("__target")
334341
stats_table = exp.table_("__stats")

tests/core/engine_adapter/integration/test_integration_bigquery.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -415,7 +415,7 @@ def test_table_diff_table_name_matches_column_name(ctx: TestContext):
415415
#
416416
# This is a problem, because we compare the columns of the source and target tables using the
417417
# equality operator (=), which is not defined for struct values in BigQuery, leading to an error.
418-
query: exp.Query = exp.maybe_parse("SELECT 1 AS id, 2 AS source, 3 AS target")
418+
query: exp.Query = exp.maybe_parse("SELECT 1 AS s, 2 AS source, 3 AS target")
419419

420420
ctx.engine_adapter.ctas(src_table, query)
421421
ctx.engine_adapter.ctas(target_table, query)
@@ -424,7 +424,7 @@ def test_table_diff_table_name_matches_column_name(ctx: TestContext):
424424
adapter=ctx.engine_adapter,
425425
source=exp.table_name(src_table),
426426
target=exp.table_name(target_table),
427-
on=["id"],
427+
on=["s"],
428428
)
429429

430430
row_diff = table_diff.row_diff()

0 commit comments

Comments
 (0)