Skip to content

fix(dialect): treat a CTE with no main statement as a degraded parse (#698) - #701

Merged
macbre merged 3 commits into
macbre:masterfrom
Yuren0312:fix-698-cte-no-main-statement
Oct 15, 2026
Merged

macbre merged 3 commits into
macbre:masterfrom
Yuren0312:fix-698-cte-no-main-statement

Conversation

@Yuren0312

Copy link
Copy Markdown
Contributor

Summary

Fixes #698 — valid multi-CTE queries that use a map/array subscript such as
m['key'] or ARRAY_JOIN(m['key'], ' ') raise
InvalidQueryDefinition("WITH clause without a main statement is not valid SQL").

Root cause

When the SQL contains a [ (map/array element access), DialectParser._detect_dialects
selects the TSQL BracketedTableDialect first. Under that dialect sqlglot's WARN-mode
parse misreads the [ as a bracket-quoted identifier and silently drops the trailing
main SELECT
, leaving a bare top-level exp.With node.

DialectParser._is_degraded only checked for an opaque exp.Command or bad
table/column names, so this broken parse was accepted as the winning result — and the
missing main statement surfaced later as InvalidQueryDefinition when .tables/.columns
were accessed.

Change

DialectParser._is_degraded now also returns True when the root AST node is a
top-level exp.With (a CTE with no main statement). A complete query always parses to
its main statement (Select/Insert/…) with the CTE attached as a with argument, so a
bare top-level With is unambiguously a degraded result. _try_dialects then falls
through to the next candidate dialect, which parses the query correctly.

Verification

  • Added a regression test (test_with_map_subscript_in_cte_does_not_drop_main_statement)
    covering ARRAY_JOIN(m['k'], ' '), a plain m['k'] subscript, and an arr[1] subscript
    inside a non-first CTE. All now return the correct tables instead of raising.
  • Full suite: 270 passed, with the only 4 failures being pre-existing and unrelated
    (they fail identically on the unmodified code — test_comments.py / test_query_type.py
    DROP/DELETE-with-comment cases, caused by sqlglot version drift, not this change).

@macbre
macbre enabled auto-merge (squash) October 15, 2026 10:39
@macbre
macbre merged commit 87ace09 into macbre:master Oct 15, 2026
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Can not use ARRAY_JOIN(map['key'], ' ') within WITH (in Trino)

2 participants