Skip to content

feat(validation): reject queries in portable expressions and parse query sources - #698

Open
403pagelabs wants to merge 12 commits into
apache:mainfrom
403pagelabs:validation-expression-shape
Open

403pagelabs wants to merge 12 commits into
apache:mainfrom
403pagelabs:validation-expression-shape

Conversation

@403pagelabs

@403pagelabs 403pagelabs commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

expression_language.md lists subqueries and the standalone WHERE clause under Not Supported in Expressions, but validate.py passes an OSSIE_SQL_2026 metric written as a scalar subquery or as a full query (SELECT SUM(x) FROM orders), because sqlglot parses both as SQL. This PR is adding two checks.

Portable expressions are expressions. An OSSIE_SQL_2026 field or metric expression that is a query is an error naming what made it one: a subquery or a VALUES list anywhere in the tree, a set operation, a projection list, or any clause on the root SELECT (WITH, FROM, JOIN, WHERE, GROUP BY, HAVING, QUALIFY, ORDER BY, LIMIT, OFFSET, DISTINCT and the rest, named from the parsed tree). FILTER (WHERE ...) on an aggregate, window frames, CASE and scalar expressions are unchanged. Every other dialect is left alone, ANSI_SQL included, since the expression language defines OSSIE_SQL_2026 only. The check runs on the tree _parse_sql_expression already builds, so there is no second parse.

A query source parses. Dataset.source is a table reference or a query. A source that starts with SELECT or WITH is now parsed with the default reader; one that does not parse, or holds two statements, is a warning (not an error, because a source declares no dialect and a vendor-dialect query may not read with the default reader). A table reference is not parsed. The check is part of validate_semantic_model, so it runs on a mapping's embedded semantic model too.

Tests: each query shape as an error in OSSIE_SQL_2026, written in full and without its SELECT, a query in ANSI_SQL and in a vendor dialect left alone, the expression shapes that stay valid (including FILTER (WHERE ...) and a window frame), a field expression, and for sources a table reference, queries and a CTE that pass plus a broken query, a query behind a leading comment and a two-statement source that warn. The examples still validate.

On top of #647: its statement check reports DDL, DML, session statements and anything that is not one bare projection once wrapped, so a query written without its SELECT (SUM(x) FROM orders) is already an error in every dialect. For OSSIE_SQL_2026 this PR makes that error name what made the text a query, in the same words as the query written in full; other dialects keep #647's message. What this PR adds is the query written in full or nested, which #647 leaves alone by design.

Found while exporting the GASP Standard to Ossie. Eleven probe documents were run against the validator at 2b1f9bf and again at 99c21c2; after #595 and #608 these were the two gaps left (the third, a metric naming an unknown dataset, is a warning by #608's design and is not changed here).

…ery sources

expression_language.md lists subqueries and the standalone WHERE clause under
Not Supported in Expressions, but validate.py passed a metric written as a
scalar subquery, or followed by FROM, WHERE or GROUP BY, because sqlglot parses
all of them. An OSSIE_SQL_2026 or ANSI_SQL field or metric expression that is a
query is now an error naming the clause or the subquery. FILTER (WHERE ...),
window frames, CASE and scalar expressions are unchanged, and vendor dialects
are not shape-checked since the language does not govern them.

A dataset source written as a query (SELECT or WITH) is now parsed with the
default reader; one that does not parse, or holds two statements, is a warning,
since a source declares no dialect.

Found while exporting the GASP Standard: eleven probe documents against the
validator at 2b1f9bf and again at 99c21c2 (docs/ossie-spike.md in GASP) left
these two gaps once apache#595 and apache#608 closed the rest.

@kayemkim kayemkim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two shapes still pass the check, and a note on #647.

WITH t AS (SELECT 1) SELECT 1 validates. validate.py pins sqlglot>=30.12.0, and from 30 the CTE sits in args["with_"], the same rename as from_; _QUERY_CLAUSES lists with only, so the WITH row never fires on the version the script runs, and the subquery scan reads the projections, not the CTE. ("with_", "WITH") beside ("from_", "FROM") catches it (suggested inline). None of the five query shapes in the tests starts with WITH, which is how it got through.

SELECT SUM(orders.customer_id), SELECT DISTINCT orders.customer_id and SELECT orders.customer_id AS total validate too. parse_one reads each as a Select with no clause, which is also the shape the SELECT {expr} wrapper produces, and nothing in the tree says which of the two it was; expression_language.md lists SELECT itself under Not Supported. The information is in #647: its wrapped_select() knows when the wrap happened, which is what this check needs to reject a SELECT the author wrote. That also bears on the ordering in the description: the two PRs conflict in validate_sql_expression (merge-tree of b518339 and #647's head), so whichever lands second rebases that function, and if #647 goes first this one can take the wrap flag from it.

Everything else I probed holds as described: both portable dialects, FILTER, a window frame, WITHIN GROUP, IN, EXISTS and ANY subqueries, a subquery inside FILTER, FROM in a comment or a string literal, and for sources a lowercase select, parentheses, a trailing semicolon, UNION and an aliased subquery; the examples and compliance fixtures hold no expression starting with SELECT or WITH.

Comment thread validation/validate.py Resolved
@jbonofre
jbonofre self-requested a review November 5, 2026 04:27

@MrBlack1995 MrBlack1995 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, it closes a real gap: expression_language.md has listed subqueries as not supported for a while, and the validator let them through. I ran the suite on b518339 (325 passed with sqlglot 30.21) and probed a few more shapes on top of the ones @kayemkim covered. One suggestion, which would also cover his WITH point, and two small notes:

  1. More Select clauses pass the check than _QUERY_CLAUSES lists. On sqlglot 30.21 these validate as OSSIE_SQL_2026 metrics today:

    Expression Select arg set
    SUM(x) OVER w WINDOW w AS (PARTITION BY y) windows
    SUM(x) LATERAL VIEW explode(a) t AS b laterals
    SUM(x) INTO t into
    SUM(x) CLUSTER BY y / SORT BY y / DISTRIBUTE BY y cluster / sort / distribute
    WITH t AS (SELECT 1) SELECT 1 with_ (@kayemkim's point)

    Since the SELECT {expr} wrapper only ever sets expressions, an allowlist may be more robust than a denylist: any other non-empty arg on the root Select came from the expression text. Roughly:

    for arg, value in tree.args.items():
        if value and arg != "expressions":
            clause = dict(_QUERY_CLAUSES).get(arg, arg.rstrip("_").upper())
            return f"[SQL] {context}: contains a {clause} clause; ..."

    I tried this locally: the suite still passes (325), every shape above is rejected, the FILTER (WHERE ...), window, WITHIN GROUP, STRING_AGG(... ORDER BY ...) and ARRAY_AGG(... ORDER BY ...) cases still pass, and none of the 16 YAMLs in examples/ and compliance/ trips it. It also stops depending on sqlglot's arg names (from vs from_, with vs with_), and it would reject SELECT DISTINCT x, the distinct arg, which is one of the shapes from @kayemkim's second point. It does not help with a plain SELECT SUM(x), which still needs the wrap flag from #647 as he says.

  2. Set operations are reported as a subquery. SUM(x) UNION SELECT 1 is rejected (good), but the message says "contains a subquery". An exp.Union/exp.SetOperation root could say "is a set operation (UNION)" instead, so the author knows what to remove. Minor.

  3. Source detection (non-blocking, warning only). _QUERY_SOURCE skips a few query sources, so they are not parsed: a leading comment (-- note\nSELECT ...), double parentheses, VALUES (1), (2) and TABLE db.s.orders. The comment case is the one I'd expect in practice. Stripping leading comments before the match would cover it; the rest seem fine to leave.

The two checks fit well with #642, which grades the portable expression.sql form as OSSIE_SQL_2026: with this in, a sql expression that is a query fails validation before it is graded.

…tions, read sources behind comments

Review of apache#698 (kayemkim, MrBlack1995): `WITH t AS (SELECT 1) SELECT 1` passed
because sqlglot 30 names the argument `with_` and the clause list said `with`,
and `windows`, `laterals`, `into`, `cluster`, `sort`, `distribute` and
`distinct` were not listed at all. The `SELECT {expr}` wrapper sets only
`expressions`, so any other non-empty argument on the root SELECT came from the
expression text: report it, named from the argument, instead of matching a
list. A root that is a set operation is reported as one (`SUM(x) UNION SELECT
1` is a set operation, not a subquery). A query source behind leading `--` or
`/* */` comments, or in doubled parentheses, is now parsed.

A bare `SELECT SUM(x)` still parses to the wrapper's tree and is left to apache#647,
whose wrap flag tells the two apart; the docstring says so.
@403pagelabs

Copy link
Copy Markdown
Contributor Author

Thanks both. Merged main and took the allowlist: any non-empty argument on the root SELECT other than expressions is reported as the clause it holds, named from the argument, so the check no longer depends on sqlglot's argument names. A root set operation is reported as one. Leading comments are stripped before a source is matched, and doubled parentheses match. Each shape from the two reviews is a test: 609 passed, 1 skipped on sqlglot 30.30, and examples/, the compliance fixtures and GASP's export validate.

The bare SELECT SUM(x) is #647's: its wrap flag is the only thing that tells it from the wrapper's output, and the docstring says so. Whichever of the two lands second rebases validate_sql_expression.

Comment thread validation/validate.py Resolved
Comment thread validation/validate.py Resolved
Comment thread validation/validate.py Resolved
Comment thread validation/validate.py Resolved
Comment thread validation/tests/test_validate.py Resolved

@orca-review-bot orca-review-bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. I probed this at head: IN (SELECT 1), EXCEPT, LIMIT and FOR UPDATE are all rejected, and FILTER, window frames and CASE still pass. The tests and examples validate. No spec, schema or version change, so there's no generated-type drift. Two test gaps, both small: can we pin EXCEPT and orders.product_id IN (SELECT 1) in the parametrized error list? The spec calls out IN-subqueries at expression_language.md:135. The rest is nits inline.

🤖 AI-generated review comment — agents make mistakes, so please verify before acting on it.

Comment thread validation/validate.py Resolved
Comment thread validation/validate.py Resolved
Comment thread validation/tests/test_validate.py Resolved
…on lists reported, one statement count

Review round on apache#698.

- The shape check runs on OSSIE_SQL_2026 alone. Every other dialect is
  opaque to Ossie, ANSI_SQL included, so a subquery in an ANSI_SQL
  expression validates as it did before.
- A projection list (SUM(a), SUM(b)) is reported: the wrapper adds one
  projection, so a second came from the expression text.
- A VALUES list is reported, at the root and below it. sqlglot parses it
  with no SELECT underneath, so the subquery search now looks for a Query
  or a Values node.
- A comment after the last semicolon is not a statement. _statements is
  the one copy of the count, used by the expression check and the dataset
  source check.
- A locking clause (FOR UPDATE) is named as such; EXCEPT and IN (SELECT)
  are pinned in the tests; the source test that needs sqlglot is skipped
  without it; the source docstring says which sources are parsed.
…-shape

validate_sql_expression keeps the statement checks from apache#647 and runs the
portable shape check on what they accept. validate_dataset_sources joins
validate_semantic_model (apache#760), so an embedded semantic model's query
sources are parsed too.
apache#647's statements

After apache#647 a query written without its SELECT (SUM(x) FROM t) is reported
as a statement in every dialect before the shape check runs. The shape
rows now write the query in full, which the statement check accepts, and
a second test pins the fragments to the statement message in both
OSSIE_SQL_2026 and ANSI_SQL.
… is written without SELECT

The statement check from apache#647 reports a text that parses only wrapped in
SELECT, and is then more than one bare projection, as 'expected an
expression, found a statement'. For OSSIE_SQL_2026 that error now comes from
query_shape_error, so SUM(x) FROM t 'contains a FROM clause' and
SUM(x), SUM(y) 'holds 2 expressions', the same words as the query written in
full. Other dialects keep the statement error.
@403pagelabs

Copy link
Copy Markdown
Contributor Author

Thanks JB. All five are answered in their threads - the branch is merged with main now that #647 and #760 are in.

On #647: its statement check catches a query written without its SELECT (SUM(x) FROM orders) in every dialect. For OSSIE_SQL_2026 I made that error say what made the text a query, so it reads "contains a FROM clause" as the same query written in full does. That is four lines in _parse_sql_expression; every other dialect keeps #647's message and none of its tests change. What this PR adds beyond #647 is what main still accepts as OSSIE_SQL_2026: a query written in full (SELECT SUM(x) FROM orders), a subquery (x IN (SELECT 1)), a set operation, a VALUES list. The source check sits in validate_semantic_model, so #760 runs it on embedded models too.

832 passed, 1 skipped on sqlglot 30.33. If there is room I would like this on the 0.3.0-incubating milestone.

@403pagelabs
403pagelabs requested a review from jbonofre November 18, 2026 21:01

@christianeu-db christianeu-db left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @403pagelabs! I'd like the inline note fixed before I approve. +1 to @kayemkim's point as well

Comment thread validation/validate.py Resolved
…llows it

parse_one returns `DROP TABLE orders; -- cleanup` as a Block of the Drop and
the comment's Semicolon. _statements counts that as one statement, so the count
check passed it and the kind check read the Block, not the Drop: the statement
validated as an expression. The bare parse and the SELECT wrap now unwrap a
Block to its one statement, and the first-token-quoted retry counts with
_statements so `drop * 2; -- c` stays valid.
… SELECT

`SELECT SUM(x)` parses to the tree the `SELECT {expr}` wrapper produces, so
query_shape_error could not tell the two apart and passed both. The parse can:
text that parses alone was not wrapped. In OSSIE_SQL_2026 a root SELECT from the
bare parse is now reported, by its clause when it has one and as a SELECT when
it has a single projection and nothing else (expression_language.md, Not
Supported in Expressions). Other dialects are unchanged.
@403pagelabs

Copy link
Copy Markdown
Contributor Author

Thanks Chris. The inline note is fixed in ed019bb and answered in its thread.

@kayemkim's open point is e8b71fd. Now that #647 is in, the parse knows whether it had to wrap the text, so a SELECT the author wrote is an error in OSSIE_SQL_2026. SELECT SUM(orders.customer_id) and SELECT orders.customer_id AS total report "is written as a SELECT". A SELECT with a clause keeps the clause's name, as before. Other dialects are untouched. I kept it as its own commit in case you would rather see it as a follow-up.

Main is merged in at 8bbffde. validation/tests/ gives 951 passed, 1 skipped on sqlglot 30.33, the Python and scripts suites pass and the examples validate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants