[tsql, teradata, redshift] SELECT top FROM t still raises ParseError after #9295

Aperta Adatta ai principianti
#9,300 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
74/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python
Ambito
compilers

Direzione di ricerca

Inizia in sqlglot/parser.py da _parse_limit (~riga 6035) e usa l'override di Snowflake in sqlglot/parsers/snowflake.py (~riga 1239) come modello per proteggere TOP. Controlla i tokenizer in sqlglot/dialects/tsql.py (~188), teradata.py (~74) e redshift.py (~57) per confermare che TOP sia un token ID_VAR. Riproduci con sqlglot.parse_one("SELECT top FROM t", read="tsql"), poi aggiungi test di dialetto che verifichino che top, top.x e top, x facciano round-trip su tutti e tre i dialetti mentre le forme esistenti TOP 5, TOP (5), TOP 10 PERCENT e TOP %s di Redshift restano invariate; esegui i test di dialetto e pytest tests.

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

Descrizione

Before you file an issue

  • read dialect: tsql, teradata, redshift
  • write dialect: same as read
  • still present on main @ 089891f2521780e2c5b243005017af9db62f25a6 (2026-11-21), i.e. after #9295 (a014c534)

Fully reproducible code snippet

#9295 fixed #9284 for Snowflake and Oracle. The generic Parser._parse_limit(top=True) still matches TOP unconditionally, so the other three dialects that tokenize it behave as before:

import sqlglot

for dialect in ("tsql", "teradata", "redshift"):
    sqlglot.parse_one("SELECT top FROM t", read=dialect)
    # ParseError: Required keyword: 'expression' missing for <class 'sqlglot.expressions.query.Limit'>

    print(dialect, sqlglot.parse_one("SELECT top, x FROM t", read=dialect).sql(dialect=dialect))
    # tsql      SELECT TOP (x) FROM t    projections: []
    # teradata  SELECT TOP (x) FROM t    projections: []
    # redshift  SELECT FROM t LIMIT x    projections: []

SELECT top.x FROM t raises the same ParseError on all three. Each of them tokenizes "TOP": TokenType.TOP (sqlglot/dialects/tsql.py:188, teradata.py:74, redshift.py:57), and Parser.ID_VAR_TOKENS includes TokenType.TOP, so top is meant to be usable as an identifier — the same argument #9284 made for Snowflake.

Where it comes from

_parse_limit (sqlglot/parser.py:6035) matches TOP, then builds exp.Limit(expression=None) when no count follows. Snowflake now has a guard in its own override (sqlglot/parsers/snowflake.py:1239) and Oracle stopped tokenizing TOP; the base parser has neither.

Retreating to the saved token index when no count is parsed covers all three, and unlike a "next token must be NUMBER" guard it leaves Redshift's TOP %s / TOP %(n)s placeholders alone:

     def _parse_limit(
         ...
     ) -> exp.Expr | None:
+        index = self._index
         if skip_limit_token or self._match(TokenType.TOP if top else TokenType.LIMIT):
             ...
                 expression = (
                     self._parse_term() or self._parse_select()
                     if limit_paren
                     else self._parse_number()
                 )
 
+                if expression is None:
+                    # TOP is also a valid identifier, e.g. SELECT top FROM t
+                    self._retreat(index)
+                    return this
+
                 if limit_paren:
                     self._match_r_paren()

Verified on 089891f: with the patch, top, top.x, top, x round-trip on tsql/teradata/redshift; every existing TOP form is unchanged (TOP 5, TOP (5), TOP (@n), TOP 10 PERCENT, WITH TIES, DISTINCT TOP 3, set operations, ORDER BY/OFFSET/FETCH, Redshift TOP %s); pytest tests gives 1666 passed, 25818 subtests passed. The three new dialect tests fail on 089891f without the patch.

Not covered here

  • SELECT top(5), x FROM t still loses the projection (SELECT TOP (5, x)). TOP (expr) is valid T-SQL and Snowflake accepts only a constant, so this needs a dialect split; #9295 already sends Snowflake's TOP(x) to function-call parsing.
  • SELECT fetch FROM t is a separate root cause (FETCH clause). Mentioned only so it is not mistaken for part of this report.

Official Documentation


Prepared with AI assistance; every snippet above was run against main @ 089891f.

Lingua principale
Python
Stelle
9.8k
Fork
1.4k
Merge medio
10h 52m
PR unite (30g)
303

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.