Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions sql_metadata/column_extractor.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,27 @@ def _is_date_part_unit(node: exp.Column) -> bool:
return False


def _is_limit_all(node: exp.Column) -> bool:
"""Return ``True`` if *node* is the ``ALL`` keyword of ``LIMIT ALL``.

Outside the PostgreSQL dialect, sqlglot parses ``LIMIT ALL`` as a
``Limit`` whose expression is an ``exp.Column`` named ``ALL``. It
means "no limit", not a column reference, so it must be skipped.

:param node: A column AST node to inspect.
:type node: exp.Column
:rtype: bool
"""
if not isinstance(node.parent, exp.Limit) or node.table:
return False
ident = node.this
return (
isinstance(ident, exp.Identifier)
and not ident.quoted
and ident.name.upper() == "ALL"
)


# ---------------------------------------------------------------------------
# Collector — accumulates results during AST walk
# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -733,6 +754,10 @@ def _handle_column(self, col: exp.Column, clause: str) -> None:
"""
c = self._collector

if _is_limit_all(col):
# e.g. LIMIT ALL — "ALL" is a keyword, not a column
return

star = col.find(exp.Star)
if star:
# e.g. SELECT t.* — table-qualified star
Expand Down Expand Up @@ -1092,8 +1117,8 @@ def _collect_column_from_node(
"""
if isinstance(child, exp.Column):
# e.g. SELECT t.col, DATEDIFF(day, a, b)
if _is_date_part_unit(child):
# e.g. DATEDIFF(day, ...) — "day" is a unit keyword, not a column
if _is_date_part_unit(child) or _is_limit_all(child):
# e.g. DATEDIFF(day, ...) or LIMIT ALL — keywords, not columns
return None
star = child.find(exp.Star)
if star:
Expand Down
24 changes: 24 additions & 0 deletions test/test_getting_columns.py
Original file line number Diff line number Diff line change
Expand Up @@ -790,3 +790,27 @@ def test_cte_with_table_star_in_body():
)
assert p.columns == ["t.*"]
assert p.columns_aliases_names == ["a"]


def test_limit_all_is_not_a_column():
"""LIMIT ALL means no limit; ALL must not be reported as a column."""
p = Parser("SELECT a FROM t ORDER BY a LIMIT ALL")
assert p.columns == ["a"]
assert p.columns_dict == {"select": ["a"], "order_by": ["a"]}

p = Parser("SELECT a FROM t LIMIT ALL OFFSET 5")
assert p.columns == ["a"]

p = Parser(
"WITH cte AS (SELECT a FROM t LIMIT ALL) SELECT a FROM cte"
)
assert p.columns == ["a"]

p = Parser("SELECT * FROM (SELECT id FROM t LIMIT 10, 20) AS sub LIMIT ALL")
assert p.columns == ["*", "id"]


def test_quoted_all_in_where_is_still_a_column():
"""A real column named "all" outside LIMIT is still extracted."""
p = Parser('SELECT "all" FROM t WHERE "all" > 1')
assert p.columns == ["all"]