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

Abierto Apto para principiantes
#9,300 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
74/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
python
Área
compilers

Línea de trabajo

Empieza en sqlglot/parser.py en _parse_limit (~línea 6035), y usa la sobrescritura de Snowflake en sqlglot/parsers/snowflake.py (~línea 1239) como modelo para proteger TOP. Revisa los tokenizers de sqlglot/dialects/tsql.py (~188), teradata.py (~74) y redshift.py (~57) para confirmar que TOP es un token ID_VAR. Reproduce con sqlglot.parse_one("SELECT top FROM t", read="tsql"), luego añade tests de dialecto que verifiquen que top, top.x y top, x hacen round-trip en los tres dialectos mientras que las formas existentes TOP 5, TOP (5), TOP 10 PERCENT y TOP %s de Redshift permanecen sin cambios; ejecuta los tests de dialecto y pytest tests.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

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.

Lenguaje dominante
Python
Estrellas
9.8k
Forks
1.4k
Merge medio
10 h 52 min
PR fusionados (30 d)
303

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de tobymao/sqlglot

Todos los issues de tobymao/sqlglot

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.