Skip to content

Commit 6fbe985

Browse files
committed
scope Snowflake positional refs to pivot source
1 parent b9426cc commit 6fbe985

2 files changed

Lines changed: 39 additions & 1 deletion

File tree

sqlglot/optimizer/qualify_columns.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -670,14 +670,28 @@ def _qualify_columns(
670670
and position.is_int
671671
):
672672
# Preserve references whose source shape cannot be resolved losslessly.
673+
scope_pivot = next(
674+
(pivot for pivot in scope.pivots if pivot.alias == column_table), None
675+
)
676+
if not scope_pivot:
677+
scope_pivot = next(
678+
(
679+
pivot
680+
for pivot in reversed(scope.pivots)
681+
if pivot.parent and pivot.parent.alias_or_name == column_table
682+
),
683+
None,
684+
)
673685
if (
674686
pivots
675-
or scope.pivots
687+
or scope_pivot
676688
or (isinstance(column_source, exp.Table) and column_source.alias_column_names)
677689
or (isinstance(column_source, Scope) and column_source.outer_columns)
678690
or not source_columns
679691
or "*" in source_columns
680692
):
693+
if scope_pivot:
694+
column.set("table", exp.to_identifier(scope_pivot.alias))
681695
continue
682696

683697
positional_columns = resolver.get_source_columns(column_table, only_visible=True)

tests/test_optimizer.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1200,6 +1200,30 @@ def test_qualify_snowflake_positional_columns_preserve_unresolved(self):
12001200
("P.$2 AS _COL_0",),
12011201
{},
12021202
),
1203+
(
1204+
"aliasless PIVOT",
1205+
"WITH t AS (SELECT 1 AS id, 2 AS v, 'a' AS k) "
1206+
"SELECT t.$2 FROM t PIVOT(SUM(v) FOR k IN ('a' AS a))",
1207+
("_0.$2 AS _COL_0",),
1208+
{},
1209+
),
1210+
(
1211+
"chained aliasless PIVOT",
1212+
"WITH t AS (SELECT 1 AS id, 2 AS v, 'a' AS k) "
1213+
"SELECT t.$1 FROM t PIVOT(SUM(v) FOR k IN ('a' AS a)) "
1214+
"UNPIVOT(v2 FOR k2 IN (a))",
1215+
("T.$1 AS _COL_0",),
1216+
{},
1217+
),
1218+
(
1219+
"unrelated PIVOT",
1220+
"WITH t AS (SELECT 1 AS x), "
1221+
"s AS (SELECT 1 AS id, 2 AS v, 'a' AS k) "
1222+
"SELECT t.$1, p.$2 FROM t CROSS JOIN "
1223+
"s PIVOT(SUM(v) FOR k IN ('a' AS a)) AS p",
1224+
("T.X AS X", "P.$2 AS _COL_1"),
1225+
{},
1226+
),
12031227
(
12041228
"unknown source",
12051229
"SELECT t.$1 FROM source AS t",

0 commit comments

Comments
 (0)