BigQuery -> Snowflake: UNNEST WITH OFFSET column becomes x['off'] when the UNNEST is the only source

Aperta Adatta ai principianti
#9,311 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
78/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python, sql
Ambito
compilers

Direzione di ricerca

Inizia da _qualify_unnested_columns in sqlglot/generators/snowflake.py. Riproduci il problema con la transpilazione su una riga presente nell'issue, poi verifica come viene gestito l'identificatore di offset dell'unnest quando UNNEST è l'unica sorgente. Aggiungi un test per WITH OFFSET accanto ai test unnest esistenti in tests/dialects/test_bigquery.py e tests/dialects/test_snowflake.py. È completato quando la colonna di offset resta non qualificata nell'output di Snowflake, i campi di struct diventano ancora x['name'] e i test dei dialetti passano.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

When a BigQuery UNNEST ... WITH OFFSET is the only source of the query, the Snowflake output reads the offset column as a field of the unnested value. Checked on main (089891f25).

import sqlglot
sql = "SELECT x, off FROM UNNEST([10, 20]) AS x WITH OFFSET AS off ORDER BY off"
print(sqlglot.transpile(sql, read="bigquery", write="snowflake")[0])

Output:

SELECT x, x['off'] AS off FROM TABLE(FLATTEN(INPUT => [10, 20])) AS _t0(seq, key, path, off, x, this) ORDER BY x['off'] NULLS FIRST

Expected (off is the FLATTEN INDEX column, already aliased in _t0):

SELECT x, off FROM TABLE(FLATTEN(INPUT => [10, 20])) AS _t0(seq, key, path, off, x, this) ORDER BY off NULLS FIRST

The same happens with a bare WITH OFFSET (x['offset']). With a joined table (FROM t, UNNEST(t.arr) AS x WITH OFFSET AS off) the output is right.

The cause is _qualify_unnested_columns in sqlglot/generators/snowflake.py. With a single source it qualifies every unqualified column with the unnest alias, so that struct fields work (SELECT name FROM UNNEST([STRUCT(1 AS name)]) AS x). The offset name isn't excluded. This change fixes it for me:

diff --git a/sqlglot/generators/snowflake.py b/sqlglot/generators/snowflake.py
index c224f5ffb..7db7eb608 100644
--- a/sqlglot/generators/snowflake.py
+++ b/sqlglot/generators/snowflake.py
@@ -255,12 +255,18 @@ def _qualify_unnested_columns(expression: exp.Expr) -> exp.Expr:
         unnest_to_identifier: dict[exp.Unnest, exp.Identifier] = {}
 
         unnest_identifier: exp.Identifier | None = None
+        offset_names: set[str] = set()
         orig_expression = expression.copy()
 
         for unnest in unnests:
             if not isinstance(unnest.parent, (exp.From, exp.Join)):
                 continue
 
+            # The WITH OFFSET column is produced by the unnest, it's not a field of the unnested value
+            offset = unnest.args.get("offset")
+            if isinstance(offset, exp.Identifier):
+                offset_names.add(offset.name.lower())
+
             # Try to infer column names produced by an unnest operator. This is only possible
             # when we can peek into the (statically known) contents of the unnested value.
             unnest_columns: set[str] = set()
@@ -309,7 +315,7 @@ def _qualify_unnested_columns(expression: exp.Expr) -> exp.Expr:
             column_source.update({c.lower(): unnest_identifier for c in unnest_columns})
 
         for column in scope.columns:
-            if column.table:
+            if column.table or column.name.lower() in offset_names:
                 continue
 
             table = column_source.get(column.name.lower())

With it, struct fields still become x['name'], the offset stays a plain column, and SKIP_INTEGRATION=1 python -m unittest passes, except for 3 DuckDB (execute) cases in test_optimizer that fail the same way on main for me. I have a test for test_unnest_with_offset too if it helps.

Docs: BigQuery UNNEST with OFFSET, Snowflake FLATTEN output columns.

I used Claude Code to find and check this.

Lingua principale
Python
Stelle
9.8k
Fork
1.4k
Merge medio
11h 3m
PR unite (30g)
292

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di tobymao/sqlglot

Tutte le issue di tobymao/sqlglot

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.