Repository navigation
feat(validation): reject queries in portable expressions and parse query sources - #698
403pagelabs wants to merge 12 commits into
Conversation
…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
left a comment
There was a problem hiding this comment.
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.
MrBlack1995
left a comment
There was a problem hiding this comment.
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:
-
More
Selectclauses pass the check than_QUERY_CLAUSESlists. On sqlglot 30.21 these validate as OSSIE_SQL_2026 metrics today:Expression Selectarg setSUM(x) OVER w WINDOW w AS (PARTITION BY y)windowsSUM(x) LATERAL VIEW explode(a) t AS blateralsSUM(x) INTO tintoSUM(x) CLUSTER BY y/SORT BY y/DISTRIBUTE BY ycluster/sort/distributeWITH t AS (SELECT 1) SELECT 1with_(@kayemkim's point)Since the
SELECT {expr}wrapper only ever setsexpressions, an allowlist may be more robust than a denylist: any other non-empty arg on the rootSelectcame 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 ...)andARRAY_AGG(... ORDER BY ...)cases still pass, and none of the 16 YAMLs inexamples/andcompliance/trips it. It also stops depending on sqlglot's arg names (fromvsfrom_,withvswith_), and it would rejectSELECT DISTINCT x, thedistinctarg, which is one of the shapes from @kayemkim's second point. It does not help with a plainSELECT SUM(x), which still needs the wrap flag from #647 as he says. -
Set operations are reported as a subquery.
SUM(x) UNION SELECT 1is rejected (good), but the message says "contains a subquery". Anexp.Union/exp.SetOperationroot could say "is a set operation (UNION)" instead, so the author knows what to remove. Minor. -
Source detection (non-blocking, warning only).
_QUERY_SOURCEskips a few query sources, so they are not parsed: a leading comment (-- note\nSELECT ...), double parentheses,VALUES (1), (2)andTABLE 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.
|
Thanks both. Merged main and took the allowlist: any non-empty argument on the root SELECT other than The bare |
orca-review-bot
left a comment
There was a problem hiding this comment.
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.
…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.
|
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 832 passed, 1 skipped on sqlglot 30.33. If there is room I would like this on the 0.3.0-incubating milestone. |
christianeu-db
left a comment
There was a problem hiding this comment.
Thanks @403pagelabs! I'd like the inline note fixed before I approve. +1 to @kayemkim's point as well
…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.
|
Thanks Chris. The inline note is fixed in @kayemkim's open point is Main is merged in at |
expression_language.mdlists subqueries and the standaloneWHEREclause under Not Supported in Expressions, butvalidate.pypasses anOSSIE_SQL_2026metric 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_2026field or metric expression that is a query is an error naming what made it one: a subquery or aVALUESlist anywhere in the tree, a set operation, a projection list, or any clause on the rootSELECT(WITH,FROM,JOIN,WHERE,GROUP BY,HAVING,QUALIFY,ORDER BY,LIMIT,OFFSET,DISTINCTand the rest, named from the parsed tree).FILTER (WHERE ...)on an aggregate, window frames,CASEand scalar expressions are unchanged. Every other dialect is left alone,ANSI_SQLincluded, since the expression language definesOSSIE_SQL_2026only. The check runs on the tree_parse_sql_expressionalready builds, so there is no second parse.A query source parses.
Dataset.sourceis a table reference or a query. A source that starts withSELECTorWITHis 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 ofvalidate_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 itsSELECT, a query inANSI_SQLand in a vendor dialect left alone, the expression shapes that stay valid (includingFILTER (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. ForOSSIE_SQL_2026this 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
2b1f9bfand again at99c21c2; 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).