From 1a7281cbfb9ee07c5a68438b12f1ea614567a777 Mon Sep 17 00:00:00 2001 From: 403Page Date: Mon, 2 Nov 2026 12:27:20 +0000 Subject: [PATCH 1/7] feat(validation): reject queries in portable expressions and parse query 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 #595 and #608 closed the rest. --- validation/tests/test_validate.py | 110 ++++++++++++++++++++++++++++++ validation/validate.py | 100 ++++++++++++++++++++++++++- 2 files changed, 209 insertions(+), 1 deletion(-) diff --git a/validation/tests/test_validate.py b/validation/tests/test_validate.py index 8211246c0..d1105696c 100644 --- a/validation/tests/test_validate.py +++ b/validation/tests/test_validate.py @@ -2802,3 +2802,113 @@ def test_invalid_sql_is_reported_under_postgres() -> None: @pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") def test_invalid_sql_is_reported_under_redshift() -> None: assert _is_error_not_warning(_VALIDATE.validate_sql(_unparseable_document("REDSHIFT"))) + + +# ── Portable expressions are expressions, not queries ────────────────────────── + + +def _metric_document(expression: str, dialect: str = "OSSIE_SQL_2026") -> dict: + document = _document([_ORDERS], []) + document["metrics"] = [_metric("m1", expression, dialect)] + return document + + +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +@pytest.mark.parametrize( + "expression, reported", + [ + ("(SELECT SUM(orders.customer_id) FROM orders)", "contains a subquery"), + ("SUM(orders.customer_id) + (SELECT 1)", "contains a subquery"), + ("SUM(orders.customer_id) FROM orders", "contains a FROM clause"), + ("SUM(orders.customer_id) WHERE orders.product_id = 1", "contains a WHERE clause"), + ("SUM(orders.customer_id) FROM orders GROUP BY orders.product_id", "contains a FROM clause"), + ], +) +def test_a_portable_expression_that_is_a_query_is_an_error(expression: str, reported: str) -> None: + result = _VALIDATE.validate_sql(_metric_document(expression)) + assert _is_error_not_warning(result) + assert len(result) == 1 + assert reported in result[0] + assert "Metric 'm1'" in result[0] + + +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +@pytest.mark.parametrize("dialect", ["OSSIE_SQL_2026", "ANSI_SQL"]) +def test_the_shape_check_covers_both_portable_dialects(dialect: str) -> None: + result = _VALIDATE.validate_sql(_metric_document("(SELECT 1)", dialect)) + assert _is_error_not_warning(result) + + +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +@pytest.mark.parametrize( + "expression", + [ + "SUM(orders.customer_id) FILTER (WHERE orders.product_id = 1)", + "COUNT(*) FILTER (WHERE orders.product_id IN (1, 2))", + "COUNT(DISTINCT orders.customer_id) FILTER (WHERE orders.product_id IS NOT NULL)", + "SUM(orders.customer_id) OVER (PARTITION BY orders.product_id ORDER BY orders.variant_id)", + "CASE WHEN orders.product_id = 1 THEN orders.customer_id ELSE 0 END", + "CAST(SUM(orders.customer_id) AS DECIMAL) / NULLIF(COUNT(orders.product_id), 0)", + "orders.customer_id", + ], +) +def test_filters_windows_and_scalars_are_expressions(expression: str) -> None: + assert _VALIDATE.validate_sql(_metric_document(expression)) == [] + + +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +def test_a_vendor_dialect_query_is_not_shape_checked() -> None: + # expression_language.md governs the portable dialects; a vendor dialect is opaque to Ossie. + assert _VALIDATE.validate_sql(_metric_document("(SELECT SUM(customer_id) FROM orders)", "SNOWFLAKE")) == [] + + +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +def test_a_field_expression_is_shape_checked_too() -> None: + document = _document([_ORDERS], []) + document["datasets"][0]["fields"].append(_field("total", "(SELECT 1)", "OSSIE_SQL_2026")) + result = _VALIDATE.validate_sql(document) + assert _is_error_not_warning(result) + assert "Field 'orders.total'" in result[0] + + +# ── A dataset source written as a query parses ───────────────────────────────── + + +def _source_document(source: str) -> dict: + return _document([{**_ORDERS, "source": source}], []) + + +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +@pytest.mark.parametrize( + "source", + [ + "db.s.orders", + "SELECT customer_id, product_id, variant_id FROM db.s.orders WHERE product_id IS NOT NULL", + "(SELECT customer_id, product_id, variant_id FROM db.s.orders)", + "WITH o AS (SELECT * FROM db.s.orders) SELECT * FROM o", + ], +) +def test_a_table_reference_or_a_query_that_parses_is_accepted(source: str) -> None: + assert _VALIDATE.validate_dataset_sources(_source_document(source)) == [] + + +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +def test_a_query_source_that_does_not_parse_is_a_warning() -> None: + result = _VALIDATE.validate_dataset_sources(_source_document("SELECT customer_id FROM WHERE (((")) + assert len(result) == 1 + assert isinstance(result[0], _VALIDATE.ValidationWarning) + assert "Dataset 'orders'" in result[0] + assert "source query does not parse" in result[0] + + +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +def test_a_source_holding_two_statements_is_a_warning() -> None: + result = _VALIDATE.validate_dataset_sources(_source_document("SELECT 1; SELECT 2")) + assert len(result) == 1 + assert "more than one statement" in result[0] + + +def test_dataset_sources_are_checked_by_validate_document(core_schema: dict) -> None: + document = _source_document("SELECT customer_id FROM WHERE (((") + result = _VALIDATE.validate_document(document, core_schema) + assert any("source query does not parse" in item for item in result) diff --git a/validation/validate.py b/validation/validate.py index dfadc5f7b..a8a823b0c 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -35,6 +35,11 @@ 3. Valid relationship references 4. Relationship column arity (from_columns and to_columns lengths match) 5. SQL syntax (using sqlglot) +6. Portable expressions are expressions: an OSSIE_SQL_2026 or ANSI_SQL field or + metric expression that is a query (a subquery, or a FROM, WHERE or other + clause) is an error (expression_language.md, Not Supported in Expressions) +7. A dataset `source` written as a query parses as SQL (a warning when it does not, + since a source declares no dialect) Ontology documents (--schema ontology/ontology.json) are checked for unique concept and relationship names, and for extends, identify_by, roles and QName @@ -67,6 +72,7 @@ import importlib.util import json import os +import re import stat import sys import traceback @@ -114,6 +120,10 @@ # specification defines. PORTABLE_DIALECT = "OSSIE_SQL_2026" +# The dialects expression_language.md governs. An expression in one of them is +# an aggregate or scalar expression over fields; a query is not an expression. +PORTABLE_DIALECTS = frozenset({"ANSI_SQL", PORTABLE_DIALECT}) + # Ossie dialects sqlglot can parse, each mapped to the sqlglot dialect to parse it # as. None is sqlglot's default (ANSI) dialect. SQLGLOT_DIALECTS = { @@ -812,10 +822,97 @@ def holds_no_statement(sql: str) -> bool: def validate_sql_expression(expr: str, dialect: str, context: str) -> str | None: """Validate a single SQL expression. Returns error message or None if valid.""" - _tree, error = _parse_sql_expression(expr, dialect, context) + tree, error = _parse_sql_expression(expr, dialect, context) + if error is None and tree is not None and dialect in PORTABLE_DIALECTS: + return query_shape_error(tree, context) return error +# Clauses that make a SELECT a query. `FILTER (WHERE ...)` on an aggregate is a +# modifier the language requires (exp.Filter), not a WHERE clause, and a window +# frame (exp.Window) is likewise part of the expression. +_QUERY_CLAUSES = ( + # sqlglot names the FROM argument `from_` from 28 on and `from` before that. + ("with", "WITH"), ("from_", "FROM"), ("from", "FROM"), ("joins", "JOIN"), ("where", "WHERE"), + ("group", "GROUP BY"), ("having", "HAVING"), ("qualify", "QUALIFY"), + ("order", "ORDER BY"), ("limit", "LIMIT"), ("offset", "OFFSET"), +) + + +def query_shape_error(tree, context: str) -> str | None: + """The reason a parsed portable expression is a query rather than an + expression, or None when it is an expression. + + expression_language.md lists subqueries and the standalone WHERE clause under + Not Supported in Expressions: a field or metric expression is one aggregate or + scalar expression over fields, and the consuming query supplies the FROM, + WHERE and GROUP BY. _parse_sql_expression wraps an expression that does not + parse alone in `SELECT {expr}`, so the root may be that wrapper: its + projections are the expression and any clause on it came from the expression + text (`SUM(x) FROM t`, `SUM(x) WHERE y = 1`). Any SELECT below the root is a + subquery. + """ + if isinstance(tree, exp.Select): + for arg, clause in _QUERY_CLAUSES: + if tree.args.get(arg): + return ( + f"[SQL] {context}: contains a {clause} clause; an expression is an " + f"aggregate or scalar expression over fields, not a query " + f"(expression_language.md, Not Supported in Expressions)" + ) + inner = list(tree.expressions) + else: + inner = [tree] + for node in inner: + if node is not None and node.find(exp.Select) is not None: + return ( + f"[SQL] {context}: contains a subquery; the expression language does " + f"not support subqueries (expression_language.md, Not Supported in " + f"Expressions)" + ) + return None + + +# A source that is a query rather than a table reference: it starts with SELECT +# or WITH, possibly in parentheses. +_QUERY_SOURCE = re.compile(r"^\s*\(?\s*(SELECT|WITH)\b", re.IGNORECASE) + + +def validate_dataset_sources(data: dict) -> list[str]: + """Warn when a dataset `source` written as a query does not parse as SQL. + + `Dataset.source` is a table reference (database.schema.table) or a query + (ossie-schema.json). A table reference is not parsed. A query is read with + sqlglot's default reader because a source declares no dialect, so a query in + a vendor dialect the default reader cannot read is reported as a warning + rather than an error. + """ + if not SQLGLOT_AVAILABLE or not isinstance(data, dict) or "datasets" not in data: + return [] + model_name = data.get("name", "") + warnings = [] + for dataset in as_list(data.get("datasets")): + if not isinstance(dataset, dict): + continue + source = dataset.get("source") + if not isinstance(source, str) or not _QUERY_SOURCE.match(source): + continue + context = f"Dataset '{dataset.get('name', '')}' in model '{model_name}'" + try: + statements = sqlglot.parse(source) + except (ParseError, TokenError, RecursionError) as e: + warnings.append(ValidationWarning( + f"[SQL] Warning: {context}: source query does not parse: " + f"{str(e).split(chr(10))[0]}" + )) + continue + if len([statement for statement in statements if statement is not None]) != 1: + warnings.append(ValidationWarning( + f"[SQL] Warning: {context}: source query holds more than one statement" + )) + return warnings + + def parse_tree(expr: str, dialect: str, context: str): """The parsed tree of one expression, or None when it does not parse: for the checks that read the columns and leave the error to the SQL check.""" @@ -1770,6 +1867,7 @@ def clean() -> bool: errors.extend(validate_field_shadowing(data)) errors.extend(validate_metric_scoping(data)) errors.extend(validate_sql(data)) + errors.extend(validate_dataset_sources(data)) if clean() and isinstance(data, dict) and "ontology" in data: errors.extend(validate_ontology(data)) if clean() and isinstance(data, dict) and "concept_mappings" in data: From 998ddf88348dd75d6da0f2334c4b5dfcd0bc6201 Mon Sep 17 00:00:00 2001 From: 403Page Date: Sat, 7 Nov 2026 08:38:37 +0000 Subject: [PATCH 2/7] fix(validation): name any clause on the root SELECT, report set operations, read sources behind comments Review of #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 #647, whose wrap flag tells the two apart; the docstring says so. --- validation/tests/test_validate.py | 26 +++++++++++ validation/validate.py | 73 +++++++++++++++++++++---------- 2 files changed, 77 insertions(+), 22 deletions(-) diff --git a/validation/tests/test_validate.py b/validation/tests/test_validate.py index 067a60071..a960e25c9 100644 --- a/validation/tests/test_validate.py +++ b/validation/tests/test_validate.py @@ -3213,6 +3213,17 @@ def _metric_document(expression: str, dialect: str = "OSSIE_SQL_2026") -> dict: ("SUM(orders.customer_id) FROM orders", "contains a FROM clause"), ("SUM(orders.customer_id) WHERE orders.product_id = 1", "contains a WHERE clause"), ("SUM(orders.customer_id) FROM orders GROUP BY orders.product_id", "contains a FROM clause"), + # Arguments the wrapper never sets, so they came from the expression text (review of #698). + ("WITH t AS (SELECT 1) SELECT 1", "contains a WITH clause"), + ("SUM(orders.customer_id) OVER w WINDOW w AS (PARTITION BY orders.product_id)", "contains a WINDOW clause"), + ("SUM(orders.customer_id) LATERAL VIEW explode(orders.product_id) t AS b", "contains a LATERAL VIEW clause"), + ("SUM(orders.customer_id) INTO t", "contains an INTO clause"), + ("SUM(orders.customer_id) CLUSTER BY orders.product_id", "contains a CLUSTER BY clause"), + ("SUM(orders.customer_id) SORT BY orders.product_id", "contains a SORT BY clause"), + ("SUM(orders.customer_id) DISTRIBUTE BY orders.product_id", "contains a DISTRIBUTE BY clause"), + ("SELECT DISTINCT orders.customer_id", "contains a DISTINCT clause"), + ("SUM(orders.customer_id) UNION SELECT 1", "is a set operation (UNION)"), + ("SUM(orders.customer_id) INTERSECT SELECT 1", "is a set operation (INTERSECT)"), ], ) def test_a_portable_expression_that_is_a_query_is_an_error(expression: str, reported: str) -> None: @@ -3241,6 +3252,11 @@ def test_the_shape_check_covers_both_portable_dialects(dialect: str) -> None: "CASE WHEN orders.product_id = 1 THEN orders.customer_id ELSE 0 END", "CAST(SUM(orders.customer_id) AS DECIMAL) / NULLIF(COUNT(orders.product_id), 0)", "orders.customer_id", + "SUM(orders.customer_id) OVER (ORDER BY orders.variant_id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)", + "PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY orders.customer_id)", + "STRING_AGG(CAST(orders.customer_id AS VARCHAR), ',' ORDER BY orders.customer_id)", + "ARRAY_AGG(orders.customer_id ORDER BY orders.variant_id)", + "orders.product_id IN (1, 2)", ], ) def test_filters_windows_and_scalars_are_expressions(expression: str) -> None: @@ -3277,6 +3293,9 @@ def _source_document(source: str) -> dict: "SELECT customer_id, product_id, variant_id FROM db.s.orders WHERE product_id IS NOT NULL", "(SELECT customer_id, product_id, variant_id FROM db.s.orders)", "WITH o AS (SELECT * FROM db.s.orders) SELECT * FROM o", + "-- the orders with a product\nSELECT customer_id FROM db.s.orders WHERE product_id IS NOT NULL", + "/* orders */ SELECT customer_id FROM db.s.orders", + "((SELECT customer_id FROM db.s.orders))", ], ) def test_a_table_reference_or_a_query_that_parses_is_accepted(source: str) -> None: @@ -3292,6 +3311,13 @@ def test_a_query_source_that_does_not_parse_is_a_warning() -> None: assert "source query does not parse" in result[0] +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +def test_a_query_source_behind_a_leading_comment_is_still_checked() -> None: + result = _VALIDATE.validate_dataset_sources(_source_document("-- note\nSELECT customer_id FROM WHERE (((")) + assert len(result) == 1 + assert "source query does not parse" in result[0] + + @pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") def test_a_source_holding_two_statements_is_a_warning() -> None: result = _VALIDATE.validate_dataset_sources(_source_document("SELECT 1; SELECT 2")) diff --git a/validation/validate.py b/validation/validate.py index 86e4616d2..b6097548c 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -37,8 +37,9 @@ 5. SQL syntax (using sqlglot) 6. Metric dialect agreement and expression purity (warnings; GitHub issue #279) 7. Portable expressions are expressions: an OSSIE_SQL_2026 or ANSI_SQL field or - metric expression that is a query (a subquery, or a FROM, WHERE or other - clause) is an error (expression_language.md, Not Supported in Expressions) + metric expression that is a query (a subquery, a set operation, or a FROM, + WHERE or other clause) is an error (expression_language.md, Not Supported in + Expressions) 8. A dataset `source` written as a query parses as SQL (a warning when it does not, since a source declares no dialect) @@ -832,15 +833,20 @@ def validate_sql_expression(expr: str, dialect: str, context: str) -> str | None return error -# Clauses that make a SELECT a query. `FILTER (WHERE ...)` on an aggregate is a -# modifier the language requires (exp.Filter), not a WHERE clause, and a window -# frame (exp.Window) is likewise part of the expression. -_QUERY_CLAUSES = ( - # sqlglot names the FROM argument `from_` from 28 on and `from` before that. - ("with", "WITH"), ("from_", "FROM"), ("from", "FROM"), ("joins", "JOIN"), ("where", "WHERE"), - ("group", "GROUP BY"), ("having", "HAVING"), ("qualify", "QUALIFY"), - ("order", "ORDER BY"), ("limit", "LIMIT"), ("offset", "OFFSET"), -) +# How a clause is named in the error, where the name of the sqlglot argument +# that holds it does not read as the clause. sqlglot renamed `from` to `from_` +# and `with` to `with_` from version 28 on; both spellings are listed. Any other +# argument is named from the argument itself (`into` is INTO, `having` is HAVING). +_CLAUSE_NAMES = { + "with": "WITH", "with_": "WITH", "from": "FROM", "from_": "FROM", "joins": "JOIN", + "group": "GROUP BY", "order": "ORDER BY", "distinct": "DISTINCT", "windows": "WINDOW", + "laterals": "LATERAL VIEW", "cluster": "CLUSTER BY", "sort": "SORT BY", + "distribute": "DISTRIBUTE BY", "hint": "hint", +} + + +def _clause_name(arg: str) -> str: + return _CLAUSE_NAMES.get(arg, arg.rstrip("_").replace("_", " ").upper()) def query_shape_error(tree, context: str) -> str | None: @@ -851,16 +857,34 @@ def query_shape_error(tree, context: str) -> str | None: Not Supported in Expressions: a field or metric expression is one aggregate or scalar expression over fields, and the consuming query supplies the FROM, WHERE and GROUP BY. _parse_sql_expression wraps an expression that does not - parse alone in `SELECT {expr}`, so the root may be that wrapper: its - projections are the expression and any clause on it came from the expression - text (`SUM(x) FROM t`, `SUM(x) WHERE y = 1`). Any SELECT below the root is a - subquery. + parse alone in `SELECT {expr}`, so the root may be that wrapper. The wrapper + sets only the projections (`expressions`), so any other argument on the root + SELECT came from the expression text: `SUM(x) FROM t`, `SUM(x) WHERE y = 1`, + `WITH t AS (...) SELECT 1`, `SUM(x) OVER w WINDOW w AS (...)`. Naming every + argument rather than listing clauses keeps the check independent of sqlglot's + argument names. A root that is a set operation (`SUM(x) UNION SELECT 1`) is a + query too, and any SELECT below the root is a subquery. `FILTER (WHERE ...)` + on an aggregate is a modifier the language requires (exp.Filter), not a WHERE + clause, and a window frame (exp.Window) is likewise part of the expression; + neither sets an argument on the root. + + A bare `SELECT SUM(x)` parses to the same tree as the wrapped `SUM(x)` and is + not told apart here; #647 knows when the wrap happened. """ + set_operation = getattr(exp, "SetOperation", exp.Union) + if isinstance(tree, set_operation): + return ( + f"[SQL] {context}: is a set operation ({tree.key.upper()}); an expression is an " + f"aggregate or scalar expression over fields, not a query " + f"(expression_language.md, Not Supported in Expressions)" + ) if isinstance(tree, exp.Select): - for arg, clause in _QUERY_CLAUSES: - if tree.args.get(arg): + for arg, value in tree.args.items(): + if value and arg != "expressions": + clause = _clause_name(arg) + article = "an" if clause[0] in "AEIOU" else "a" return ( - f"[SQL] {context}: contains a {clause} clause; an expression is an " + f"[SQL] {context}: contains {article} {clause} clause; an expression is an " f"aggregate or scalar expression over fields, not a query " f"(expression_language.md, Not Supported in Expressions)" ) @@ -877,9 +901,14 @@ def query_shape_error(tree, context: str) -> str | None: return None -# A source that is a query rather than a table reference: it starts with SELECT -# or WITH, possibly in parentheses. -_QUERY_SOURCE = re.compile(r"^\s*\(?\s*(SELECT|WITH)\b", re.IGNORECASE) +# A source that is a query rather than a table reference: after any leading +# comments it starts with SELECT or WITH, possibly in parentheses. +_LEADING_COMMENTS = re.compile(r"^(?:\s*(?:--[^\n]*(?:\n|$)|/\*.*?\*/))*", re.DOTALL) +_QUERY_SOURCE = re.compile(r"^\s*(?:\(\s*)*(SELECT|WITH)\b", re.IGNORECASE) + + +def _is_query_source(source: str) -> bool: + return _QUERY_SOURCE.match(_LEADING_COMMENTS.sub("", source, count=1)) is not None def validate_dataset_sources(data: dict) -> list[str]: @@ -899,7 +928,7 @@ def validate_dataset_sources(data: dict) -> list[str]: if not isinstance(dataset, dict): continue source = dataset.get("source") - if not isinstance(source, str) or not _QUERY_SOURCE.match(source): + if not isinstance(source, str) or not _is_query_source(source): continue context = f"Dataset '{dataset.get('name', '')}' in model '{model_name}'" try: From fc905a9c469655866d186da20c6e734325617585 Mon Sep 17 00:00:00 2001 From: 403Page Date: Fri, 13 Nov 2026 13:17:11 +0000 Subject: [PATCH 3/7] Validator: shape check limited to OSSIE_SQL_2026, VALUES and projection lists reported, one statement count Review round on #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. --- validation/tests/test_validate.py | 45 +++++++++++++---- validation/validate.py | 82 ++++++++++++++++++++----------- 2 files changed, 87 insertions(+), 40 deletions(-) diff --git a/validation/tests/test_validate.py b/validation/tests/test_validate.py index be73e7ec4..e977e8c24 100644 --- a/validation/tests/test_validate.py +++ b/validation/tests/test_validate.py @@ -3708,6 +3708,18 @@ def _metric_document(expression: str, dialect: str = "OSSIE_SQL_2026") -> dict: ("SELECT DISTINCT orders.customer_id", "contains a DISTINCT clause"), ("SUM(orders.customer_id) UNION SELECT 1", "is a set operation (UNION)"), ("SUM(orders.customer_id) INTERSECT SELECT 1", "is a set operation (INTERSECT)"), + ("SUM(orders.customer_id) EXCEPT SELECT 1", "is a set operation (EXCEPT)"), + ("orders.product_id IN (SELECT 1)", "contains a subquery"), + ("SUM(orders.customer_id) FOR UPDATE", "contains a locking clause"), + # The wrapper adds one projection, so a second one came from the expression text. + ("SUM(orders.customer_id), SUM(orders.product_id)", "holds 2 expressions"), + ("SELECT SUM(orders.customer_id), SUM(orders.product_id)", "holds 2 expressions"), + ("SUM(orders.customer_id), SUM(orders.product_id) FROM orders", "contains a FROM clause"), + # A VALUES list is a query with no SELECT under it. + ("SUM(orders.customer_id) * (VALUES (2))", "contains a subquery"), + ("orders.product_id = ANY (VALUES 1)", "contains a subquery"), + ("EXISTS (VALUES (1))", "contains a subquery"), + ("VALUES (1)", "is a VALUES list"), ], ) def test_a_portable_expression_that_is_a_query_is_an_error(expression: str, reported: str) -> None: @@ -3718,13 +3730,6 @@ def test_a_portable_expression_that_is_a_query_is_an_error(expression: str, repo assert "Metric 'm1'" in result[0] -@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") -@pytest.mark.parametrize("dialect", ["OSSIE_SQL_2026", "ANSI_SQL"]) -def test_the_shape_check_covers_both_portable_dialects(dialect: str) -> None: - result = _VALIDATE.validate_sql(_metric_document("(SELECT 1)", dialect)) - assert _is_error_not_warning(result) - - @pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") @pytest.mark.parametrize( "expression", @@ -3741,6 +3746,10 @@ def test_the_shape_check_covers_both_portable_dialects(dialect: str) -> None: "STRING_AGG(CAST(orders.customer_id AS VARCHAR), ',' ORDER BY orders.customer_id)", "ARRAY_AGG(orders.customer_id ORDER BY orders.variant_id)", "orders.product_id IN (1, 2)", + "COALESCE(orders.customer_id, orders.product_id)", + # A comment after the last semicolon is not a second statement. + "SUM(orders.customer_id); -- the order count", + "SUM(orders.customer_id) /* orders */;", ], ) def test_filters_windows_and_scalars_are_expressions(expression: str) -> None: @@ -3748,9 +3757,18 @@ def test_filters_windows_and_scalars_are_expressions(expression: str) -> None: @pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") -def test_a_vendor_dialect_query_is_not_shape_checked() -> None: - # expression_language.md governs the portable dialects; a vendor dialect is opaque to Ossie. - assert _VALIDATE.validate_sql(_metric_document("(SELECT SUM(customer_id) FROM orders)", "SNOWFLAKE")) == [] +@pytest.mark.parametrize("dialect", ["SNOWFLAKE", "ANSI_SQL"]) +def test_a_query_in_another_dialect_is_not_shape_checked(dialect: str) -> None: + # expression_language.md governs OSSIE_SQL_2026 alone; every other dialect is opaque + # to Ossie (extensions/dialects.md), ANSI_SQL included. + assert _VALIDATE.validate_sql(_metric_document("(SELECT SUM(customer_id) FROM orders)", dialect)) == [] + + +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +def test_only_semicolons_and_a_comment_is_an_empty_expression() -> None: + result = _VALIDATE.validate_sql(_metric_document("; -- nothing here")) + assert _is_error_not_warning(result) + assert "expression is empty" in result[0] @pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") @@ -3780,6 +3798,12 @@ def _source_document(source: str) -> dict: "-- the orders with a product\nSELECT customer_id FROM db.s.orders WHERE product_id IS NOT NULL", "/* orders */ SELECT customer_id FROM db.s.orders", "((SELECT customer_id FROM db.s.orders))", + # A comment after the last semicolon is not a second statement. + "SELECT customer_id FROM db.s.orders;\n-- end of query", + "SELECT customer_id FROM db.s.orders; /* end */", + # Not read as queries, so not parsed. + "VALUES (1), (2)", + "TABLE db.s.orders", ], ) def test_a_table_reference_or_a_query_that_parses_is_accepted(source: str) -> None: @@ -3809,6 +3833,7 @@ def test_a_source_holding_two_statements_is_a_warning() -> None: assert "more than one statement" in result[0] +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") def test_dataset_sources_are_checked_by_validate_document(core_schema: dict) -> None: document = _source_document("SELECT customer_id FROM WHERE (((") result = _VALIDATE.validate_document(document, core_schema) diff --git a/validation/validate.py b/validation/validate.py index 322ba247d..cfa73856d 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -39,10 +39,10 @@ 4. Relationship column arity (from_columns and to_columns lengths match) 5. SQL syntax (using sqlglot) 6. Metric dialect agreement and expression purity (warnings; GitHub issue #279) -7. Portable expressions are expressions: an OSSIE_SQL_2026 or ANSI_SQL field or - metric expression that is a query (a subquery, a set operation, or a FROM, - WHERE or other clause) is an error (expression_language.md, Not Supported in - Expressions) +7. Portable expressions are expressions: an OSSIE_SQL_2026 field or metric + expression that is a query (a subquery, a set operation, a VALUES list, a + projection list, or a FROM, WHERE or other clause) is an error + (expression_language.md, Not Supported in Expressions) 8. A dataset `source` written as a query parses as SQL (a warning when it does not, since a source declares no dialect) @@ -143,10 +143,6 @@ # specification defines. PORTABLE_DIALECT = "OSSIE_SQL_2026" -# The dialects expression_language.md governs. An expression in one of them is -# an aggregate or scalar expression over fields; a query is not an expression. -PORTABLE_DIALECTS = frozenset({"ANSI_SQL", PORTABLE_DIALECT}) - # Ossie dialects sqlglot can parse, each mapped to the sqlglot dialect to parse it # as. None is sqlglot's default (ANSI) dialect. SQLGLOT_DIALECTS = { @@ -964,6 +960,20 @@ def passes_through(tree, name: str) -> bool: return warnings +def _statements(parsed: list) -> list: + """The statements in a `sqlglot.parse` result. + + `sqlglot.parse` returns one entry per statement, None for an empty one (a + stray semicolon) and a `Semicolon` node for a comment that follows the last + semicolon. Neither is a statement, so `amount;`, `amount;;` and + `amount; -- note` each hold one, and `; -- note` holds none. A semicolon + inside a string literal or a comment does not split. This is the one copy of + the rule: the expression check and the dataset source check both count with + it. + """ + return [s for s in parsed if s is not None and not isinstance(s, exp.Semicolon)] + + def _parse_sql_expression( expr: str, dialect: str, context: str ) -> tuple[object | None, str | None]: @@ -993,17 +1003,13 @@ def statement_count_error(sql: str) -> str | None: `parse_one` accepts a statement list and returns one `Block` spanning it, so `amount; DROP TABLE t` parses and would otherwise validate as an - expression. A semicolon inside a string literal or comment does not - split, so this only rejects a real statement list. Stray semicolons parse - as empty statements and are not counted, so `amount;` and `amount;;` are - both a single expression. Parse failures return None; the checks below - report those. + expression. `_statements` says what counts as a statement. Parse failures + return None; the checks below report those. """ try: - statements = sqlglot.parse(sql, dialect=sqlglot_dialect) + count = len(_statements(sqlglot.parse(sql, dialect=sqlglot_dialect))) except (ParseError, TokenError, RecursionError): return None - count = len([statement for statement in statements if statement is not None]) if count > 1: return ( f"[SQL] {context}: expected a single expression but found " @@ -1021,10 +1027,9 @@ def holds_no_statement(sql: str) -> bool: the retry. Parse failures return False; the retry reports those. """ try: - statements = sqlglot.parse(sql, dialect=sqlglot_dialect) + return not _statements(sqlglot.parse(sql, dialect=sqlglot_dialect)) except (ParseError, TokenError, RecursionError): return False - return all(statement is None for statement in statements) try: # Try parsing as expression first (for field expressions like "column_name") @@ -1054,7 +1059,7 @@ def holds_no_statement(sql: str) -> bool: def validate_sql_expression(expr: str, dialect: str, context: str) -> str | None: """Validate a single SQL expression. Returns error message or None if valid.""" tree, error = _parse_sql_expression(expr, dialect, context) - if error is None and tree is not None and dialect in PORTABLE_DIALECTS: + if error is None and tree is not None and dialect == PORTABLE_DIALECT: return query_shape_error(tree, context) return error @@ -1067,7 +1072,7 @@ def validate_sql_expression(expr: str, dialect: str, context: str) -> str | None "with": "WITH", "with_": "WITH", "from": "FROM", "from_": "FROM", "joins": "JOIN", "group": "GROUP BY", "order": "ORDER BY", "distinct": "DISTINCT", "windows": "WINDOW", "laterals": "LATERAL VIEW", "cluster": "CLUSTER BY", "sort": "SORT BY", - "distribute": "DISTRIBUTE BY", "hint": "hint", + "distribute": "DISTRIBUTE BY", "hint": "hint", "locks": "locking", } @@ -1088,11 +1093,14 @@ def query_shape_error(tree, context: str) -> str | None: SELECT came from the expression text: `SUM(x) FROM t`, `SUM(x) WHERE y = 1`, `WITH t AS (...) SELECT 1`, `SUM(x) OVER w WINDOW w AS (...)`. Naming every argument rather than listing clauses keeps the check independent of sqlglot's - argument names. A root that is a set operation (`SUM(x) UNION SELECT 1`) is a - query too, and any SELECT below the root is a subquery. `FILTER (WHERE ...)` - on an aggregate is a modifier the language requires (exp.Filter), not a WHERE - clause, and a window frame (exp.Window) is likewise part of the expression; - neither sets an argument on the root. + argument names. The wrapper also adds exactly one projection, so a root + SELECT with more than one holds a projection list (`SUM(x), SUM(y)`). A root + that is a set operation (`SUM(x) UNION SELECT 1`) or a VALUES list is a query + too, and any query below the root is a subquery: a SELECT, or a VALUES list, + which sqlglot parses with no SELECT under it (`x = ANY (VALUES 1)`). + `FILTER (WHERE ...)` on an aggregate is a modifier the language requires + (exp.Filter), not a WHERE clause, and a window frame (exp.Window) is likewise + part of the expression; neither sets an argument on the root. A bare `SELECT SUM(x)` parses to the same tree as the wrapped `SUM(x)` and is not told apart here; #647 knows when the wrap happened. @@ -1104,6 +1112,12 @@ def query_shape_error(tree, context: str) -> str | None: f"aggregate or scalar expression over fields, not a query " f"(expression_language.md, Not Supported in Expressions)" ) + if isinstance(tree, exp.Values): + return ( + f"[SQL] {context}: is a VALUES list; an expression is an aggregate or scalar " + f"expression over fields, not a query (expression_language.md, Not Supported " + f"in Expressions)" + ) if isinstance(tree, exp.Select): for arg, value in tree.args.items(): if value and arg != "expressions": @@ -1114,11 +1128,17 @@ def query_shape_error(tree, context: str) -> str | None: f"aggregate or scalar expression over fields, not a query " f"(expression_language.md, Not Supported in Expressions)" ) + if len(tree.expressions) != 1: + return ( + f"[SQL] {context}: holds {len(tree.expressions)} expressions; an expression is " + f"one aggregate or scalar expression over fields, not a projection list " + f"(expression_language.md, Not Supported in Expressions)" + ) inner = list(tree.expressions) else: inner = [tree] for node in inner: - if node is not None and node.find(exp.Select) is not None: + if node is not None and node.find(exp.Query, exp.Values) is not None: return ( f"[SQL] {context}: contains a subquery; the expression language does " f"not support subqueries (expression_language.md, Not Supported in " @@ -1141,10 +1161,12 @@ def validate_dataset_sources(data: dict) -> list[str]: """Warn when a dataset `source` written as a query does not parse as SQL. `Dataset.source` is a table reference (database.schema.table) or a query - (ossie-schema.json). A table reference is not parsed. A query is read with - sqlglot's default reader because a source declares no dialect, so a query in - a vendor dialect the default reader cannot read is reported as a warning - rather than an error. + (ossie-schema.json). A source is read as a query when, after any leading + comments and parentheses, it starts with SELECT or WITH; anything else, + a table reference and a `VALUES (...)` or `TABLE t` source alike, is not + parsed. A query is read with sqlglot's default reader because a source + declares no dialect, so a query in a vendor dialect the default reader cannot + read is reported as a warning rather than an error. """ if not SQLGLOT_AVAILABLE or not isinstance(data, dict) or "datasets" not in data: return [] @@ -1165,7 +1187,7 @@ def validate_dataset_sources(data: dict) -> list[str]: f"{str(e).split(chr(10))[0]}" )) continue - if len([statement for statement in statements if statement is not None]) != 1: + if len(_statements(statements)) != 1: warnings.append(ValidationWarning( f"[SQL] Warning: {context}: source query holds more than one statement" )) From dd510a4cc75ee70465085ae6a175e0a0d32ad00c Mon Sep 17 00:00:00 2001 From: 403Page Date: Wed, 18 Nov 2026 20:08:19 +0000 Subject: [PATCH 4/7] test(validation): query shapes written in full are named, fragments are #647's statements After #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. --- validation/tests/test_validate.py | 57 +++++++++++++++++++++++-------- validation/validate.py | 28 ++++++++------- 2 files changed, 58 insertions(+), 27 deletions(-) diff --git a/validation/tests/test_validate.py b/validation/tests/test_validate.py index 80213735d..3da9aca44 100644 --- a/validation/tests/test_validate.py +++ b/validation/tests/test_validate.py @@ -4066,27 +4066,26 @@ def _metric_document(expression: str, dialect: str = "OSSIE_SQL_2026") -> dict: [ ("(SELECT SUM(orders.customer_id) FROM orders)", "contains a subquery"), ("SUM(orders.customer_id) + (SELECT 1)", "contains a subquery"), - ("SUM(orders.customer_id) FROM orders", "contains a FROM clause"), - ("SUM(orders.customer_id) WHERE orders.product_id = 1", "contains a WHERE clause"), - ("SUM(orders.customer_id) FROM orders GROUP BY orders.product_id", "contains a FROM clause"), - # Arguments the wrapper never sets, so they came from the expression text (review of #698). + ("SELECT SUM(orders.customer_id) FROM orders", "contains a FROM clause"), + ("SELECT SUM(orders.customer_id) WHERE orders.product_id = 1", "contains a WHERE clause"), + ("SELECT SUM(orders.customer_id) FROM orders GROUP BY orders.product_id", "contains a FROM clause"), + # Every clause on the root SELECT is named from the sqlglot argument that holds it (review of #698). ("WITH t AS (SELECT 1) SELECT 1", "contains a WITH clause"), - ("SUM(orders.customer_id) OVER w WINDOW w AS (PARTITION BY orders.product_id)", "contains a WINDOW clause"), - ("SUM(orders.customer_id) LATERAL VIEW explode(orders.product_id) t AS b", "contains a LATERAL VIEW clause"), - ("SUM(orders.customer_id) INTO t", "contains an INTO clause"), - ("SUM(orders.customer_id) CLUSTER BY orders.product_id", "contains a CLUSTER BY clause"), - ("SUM(orders.customer_id) SORT BY orders.product_id", "contains a SORT BY clause"), - ("SUM(orders.customer_id) DISTRIBUTE BY orders.product_id", "contains a DISTRIBUTE BY clause"), + ("SELECT SUM(orders.customer_id) OVER w WINDOW w AS (PARTITION BY orders.product_id)", "contains a WINDOW clause"), + ("SELECT SUM(orders.customer_id) LATERAL VIEW explode(orders.product_id) t AS b", "contains a LATERAL VIEW clause"), + ("SELECT SUM(orders.customer_id) INTO t", "contains an INTO clause"), + ("SELECT SUM(orders.customer_id) CLUSTER BY orders.product_id", "contains a CLUSTER BY clause"), + ("SELECT SUM(orders.customer_id) SORT BY orders.product_id", "contains a SORT BY clause"), + ("SELECT SUM(orders.customer_id) DISTRIBUTE BY orders.product_id", "contains a DISTRIBUTE BY clause"), ("SELECT DISTINCT orders.customer_id", "contains a DISTINCT clause"), ("SUM(orders.customer_id) UNION SELECT 1", "is a set operation (UNION)"), ("SUM(orders.customer_id) INTERSECT SELECT 1", "is a set operation (INTERSECT)"), ("SUM(orders.customer_id) EXCEPT SELECT 1", "is a set operation (EXCEPT)"), ("orders.product_id IN (SELECT 1)", "contains a subquery"), - ("SUM(orders.customer_id) FOR UPDATE", "contains a locking clause"), - # The wrapper adds one projection, so a second one came from the expression text. - ("SUM(orders.customer_id), SUM(orders.product_id)", "holds 2 expressions"), + ("SELECT SUM(orders.customer_id) FOR UPDATE", "contains a locking clause"), + # One expression, so a second projection is a projection list. ("SELECT SUM(orders.customer_id), SUM(orders.product_id)", "holds 2 expressions"), - ("SUM(orders.customer_id), SUM(orders.product_id) FROM orders", "contains a FROM clause"), + ("SELECT SUM(orders.customer_id), SUM(orders.product_id) FROM orders", "contains a FROM clause"), # A VALUES list is a query with no SELECT under it. ("SUM(orders.customer_id) * (VALUES (2))", "contains a subquery"), ("orders.product_id = ANY (VALUES 1)", "contains a subquery"), @@ -4099,6 +4098,36 @@ def test_a_portable_expression_that_is_a_query_is_an_error(expression: str, repo assert _is_error_not_warning(result) assert len(result) == 1 assert reported in result[0] + + +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +@pytest.mark.parametrize( + "fragment", + [ + "SUM(orders.customer_id) FROM orders", + "SUM(orders.customer_id) WHERE orders.product_id = 1", + "SUM(orders.customer_id) FROM orders GROUP BY orders.product_id", + "SUM(orders.customer_id) OVER w WINDOW w AS (PARTITION BY orders.product_id)", + "SUM(orders.customer_id) LATERAL VIEW explode(orders.product_id) t AS b", + "SUM(orders.customer_id) INTO t", + "SUM(orders.customer_id) CLUSTER BY orders.product_id", + "SUM(orders.customer_id) SORT BY orders.product_id", + "SUM(orders.customer_id) DISTRIBUTE BY orders.product_id", + "SUM(orders.customer_id) FOR UPDATE", + "SUM(orders.customer_id), SUM(orders.product_id)", + "SUM(orders.customer_id), SUM(orders.product_id) FROM orders", + ], +) +@pytest.mark.parametrize("dialect", ["OSSIE_SQL_2026", "ANSI_SQL"]) +def test_a_query_written_without_its_select_is_a_statement_in_any_dialect(fragment: str, dialect: str) -> None: + """The statement check from #647 reports these before the shape check runs: + the text parses only once it is wrapped in SELECT and the result is more than + one bare projection. The same query written in full is named clause by clause + in the test above, in the portable dialect only.""" + result = _VALIDATE.validate_sql(_metric_document(fragment, dialect)) + assert _is_error_not_warning(result) + assert len(result) == 1 + assert "expected an expression, found a statement" in result[0] assert "Metric 'm1'" in result[0] diff --git a/validation/validate.py b/validation/validate.py index fd5bb61bd..38c376c6f 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -1313,23 +1313,25 @@ def query_shape_error(tree, context: str) -> str | None: expression_language.md lists subqueries and the standalone WHERE clause under Not Supported in Expressions: a field or metric expression is one aggregate or scalar expression over fields, and the consuming query supplies the FROM, - WHERE and GROUP BY. _parse_sql_expression wraps an expression that does not - parse alone in `SELECT {expr}`, so the root may be that wrapper. The wrapper - sets only the projections (`expressions`), so any other argument on the root - SELECT came from the expression text: `SUM(x) FROM t`, `SUM(x) WHERE y = 1`, - `WITH t AS (...) SELECT 1`, `SUM(x) OVER w WINDOW w AS (...)`. Naming every - argument rather than listing clauses keeps the check independent of sqlglot's - argument names. The wrapper also adds exactly one projection, so a root - SELECT with more than one holds a projection list (`SUM(x), SUM(y)`). A root - that is a set operation (`SUM(x) UNION SELECT 1`) or a VALUES list is a query - too, and any query below the root is a subquery: a SELECT, or a VALUES list, - which sqlglot parses with no SELECT under it (`x = ANY (VALUES 1)`). + WHERE and GROUP BY. _parse_sql_expression hands back a root SELECT in two + cases. One is the wrapper it puts around an expression that does not parse + alone, which reaches this check only as one bare projection: it reports any + other wrapped result as a statement (`SUM(x) FROM t`, `SUM(x), SUM(y)`). The + other is a query the text spells out, `SELECT SUM(x) FROM t` or + `WITH t AS (...) SELECT 1`, which parses alone and is not a statement to that + check. So an argument on the root SELECT other than the projections + (`expressions`) is a clause of a written query, and more than one projection + is a projection list (`SELECT SUM(x), SUM(y)`). Naming every argument rather + than listing clauses keeps the check independent of sqlglot's argument names. + A root that is a set operation (`SUM(x) UNION SELECT 1`) or a VALUES list is a + query too, and any query below the root is a subquery: a SELECT, or a VALUES + list, which sqlglot parses with no SELECT under it (`x = ANY (VALUES 1)`). `FILTER (WHERE ...)` on an aggregate is a modifier the language requires (exp.Filter), not a WHERE clause, and a window frame (exp.Window) is likewise part of the expression; neither sets an argument on the root. - A bare `SELECT SUM(x)` parses to the same tree as the wrapped `SUM(x)` and is - not told apart here; #647 knows when the wrap happened. + A bare `SELECT SUM(x)` parses to the same tree as the wrapper around an + expression that needed one, so it is not told apart here and still passes. """ set_operation = getattr(exp, "SetOperation", exp.Union) if isinstance(tree, set_operation): From d8cc73a02d8ba9fa2d0e2f50309017d935495bc5 Mon Sep 17 00:00:00 2001 From: 403Page Date: Wed, 18 Nov 2026 20:51:21 +0000 Subject: [PATCH 5/7] fix(validation): name what made a portable expression a query when it is written without SELECT The statement check from #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. --- validation/tests/test_validate.py | 60 ++++++++++++++++++------------- validation/validate.py | 29 +++++++++------ 2 files changed, 54 insertions(+), 35 deletions(-) diff --git a/validation/tests/test_validate.py b/validation/tests/test_validate.py index 3da9aca44..c0e5627e8 100644 --- a/validation/tests/test_validate.py +++ b/validation/tests/test_validate.py @@ -4100,31 +4100,43 @@ def test_a_portable_expression_that_is_a_query_is_an_error(expression: str, repo assert reported in result[0] +_QUERIES_WITHOUT_SELECT = [ + ("SUM(orders.customer_id) FROM orders", "contains a FROM clause"), + ("SUM(orders.customer_id) WHERE orders.product_id = 1", "contains a WHERE clause"), + ("SUM(orders.customer_id) FROM orders GROUP BY orders.product_id", "contains a FROM clause"), + ("SUM(orders.customer_id) OVER w WINDOW w AS (PARTITION BY orders.product_id)", "contains a WINDOW clause"), + ("SUM(orders.customer_id) LATERAL VIEW explode(orders.product_id) t AS b", "contains a LATERAL VIEW clause"), + ("SUM(orders.customer_id) INTO t", "contains an INTO clause"), + ("SUM(orders.customer_id) CLUSTER BY orders.product_id", "contains a CLUSTER BY clause"), + ("SUM(orders.customer_id) SORT BY orders.product_id", "contains a SORT BY clause"), + ("SUM(orders.customer_id) DISTRIBUTE BY orders.product_id", "contains a DISTRIBUTE BY clause"), + ("SUM(orders.customer_id) FOR UPDATE", "contains a locking clause"), + ("SUM(orders.customer_id), SUM(orders.product_id)", "holds 2 expressions"), + ("SUM(orders.customer_id), SUM(orders.product_id) FROM orders", "contains a FROM clause"), +] + + @pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") -@pytest.mark.parametrize( - "fragment", - [ - "SUM(orders.customer_id) FROM orders", - "SUM(orders.customer_id) WHERE orders.product_id = 1", - "SUM(orders.customer_id) FROM orders GROUP BY orders.product_id", - "SUM(orders.customer_id) OVER w WINDOW w AS (PARTITION BY orders.product_id)", - "SUM(orders.customer_id) LATERAL VIEW explode(orders.product_id) t AS b", - "SUM(orders.customer_id) INTO t", - "SUM(orders.customer_id) CLUSTER BY orders.product_id", - "SUM(orders.customer_id) SORT BY orders.product_id", - "SUM(orders.customer_id) DISTRIBUTE BY orders.product_id", - "SUM(orders.customer_id) FOR UPDATE", - "SUM(orders.customer_id), SUM(orders.product_id)", - "SUM(orders.customer_id), SUM(orders.product_id) FROM orders", - ], -) -@pytest.mark.parametrize("dialect", ["OSSIE_SQL_2026", "ANSI_SQL"]) -def test_a_query_written_without_its_select_is_a_statement_in_any_dialect(fragment: str, dialect: str) -> None: - """The statement check from #647 reports these before the shape check runs: - the text parses only once it is wrapped in SELECT and the result is more than - one bare projection. The same query written in full is named clause by clause - in the test above, in the portable dialect only.""" - result = _VALIDATE.validate_sql(_metric_document(fragment, dialect)) +@pytest.mark.parametrize(("fragment", "reported"), _QUERIES_WITHOUT_SELECT) +def test_a_portable_query_written_without_its_select_is_named_too(fragment: str, reported: str) -> None: + """The text parses only once it is wrapped in SELECT and the result is more + than one bare projection, which the statement check from #647 rejects. In + the portable dialect that error says what made the text a query, as it does + for the same query written in full in the test above.""" + result = _VALIDATE.validate_sql(_metric_document(fragment, "OSSIE_SQL_2026")) + assert _is_error_not_warning(result) + assert len(result) == 1 + assert reported in result[0] + assert "found a statement" not in result[0] + assert "Metric 'm1'" in result[0] + + +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +@pytest.mark.parametrize("fragment", [fragment for fragment, _ in _QUERIES_WITHOUT_SELECT]) +def test_a_query_written_without_its_select_stays_a_statement_in_another_dialect(fragment: str) -> None: + """The specification defines no expression language for ANSI_SQL, so #647's + statement error is left as it is there.""" + result = _VALIDATE.validate_sql(_metric_document(fragment, "ANSI_SQL")) assert _is_error_not_warning(result) assert len(result) == 1 assert "expected an expression, found a statement" in result[0] diff --git a/validation/validate.py b/validation/validate.py index 38c376c6f..9e61ab83b 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -1271,6 +1271,12 @@ def wrapped_select() -> tuple[object | None, str | None]: return None, wrap_error if wrapped is not None and _is_bare_projection(wrapped): return wrapped, None + if wrapped is not None and dialect == PORTABLE_DIALECT: + # The portable dialect has a defined expression language, so say what + # made the text a query (`SUM(x) FROM t` contains a FROM clause). + shape_error = query_shape_error(wrapped, context) + if shape_error: + return None, shape_error return None, f"[SQL] {context}: expected an expression, found a statement" @@ -1281,8 +1287,9 @@ def validate_sql_expression(expr: str, dialect: str, context: str) -> str | None statement. Multi-statement strings and DDL/DML/session statements are rejected for every dialect sqlglot parses. A query (a subquery, a set operation, VALUES, a clause on the root SELECT or a projection list) is - rejected in OSSIE_SQL_2026 only; the other dialects are opaque to the - specification. + rejected in OSSIE_SQL_2026 only, with or without its SELECT, and the error + names what made it one; the other dialects are opaque to the specification, + where only a query written without its SELECT is reported, as a statement. """ tree, error = _parse_sql_expression(expr, dialect, context) if error is None and tree is not None and dialect == PORTABLE_DIALECT: @@ -1313,15 +1320,15 @@ def query_shape_error(tree, context: str) -> str | None: expression_language.md lists subqueries and the standalone WHERE clause under Not Supported in Expressions: a field or metric expression is one aggregate or scalar expression over fields, and the consuming query supplies the FROM, - WHERE and GROUP BY. _parse_sql_expression hands back a root SELECT in two - cases. One is the wrapper it puts around an expression that does not parse - alone, which reaches this check only as one bare projection: it reports any - other wrapped result as a statement (`SUM(x) FROM t`, `SUM(x), SUM(y)`). The - other is a query the text spells out, `SELECT SUM(x) FROM t` or - `WITH t AS (...) SELECT 1`, which parses alone and is not a statement to that - check. So an argument on the root SELECT other than the projections - (`expressions`) is a clause of a written query, and more than one projection - is a projection list (`SELECT SUM(x), SUM(y)`). Naming every argument rather + WHERE and GROUP BY. A root SELECT reaches this check two ways. One is the + wrapper _parse_sql_expression puts around an expression that does not parse + alone: a wrapped result that is one bare projection is an expression, and any + other (`SUM(x) FROM t`, `SUM(x), SUM(y)`) is passed here by the statement + check so the error names what made it a query. The other is a query the text + spells out, `SELECT SUM(x) FROM t` or `WITH t AS (...) SELECT 1`, which parses + alone and is not a statement to that check. Either way an argument on the root + SELECT other than the projections (`expressions`) is a clause of a query, and + more than one projection is a projection list. Naming every argument rather than listing clauses keeps the check independent of sqlglot's argument names. A root that is a set operation (`SUM(x) UNION SELECT 1`) or a VALUES list is a query too, and any query below the root is a subquery: a SELECT, or a VALUES From ed019bb2ddb9a8b519e9544a4946dbf23e888b13 Mon Sep 17 00:00:00 2001 From: 403Page Date: Thu, 19 Nov 2026 17:58:13 +0000 Subject: [PATCH 6/7] fix(validation): check the statement inside a Block when a comment follows 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. --- validation/tests/test_validate.py | 44 +++++++++++++++++++++++++++++++ validation/validate.py | 25 +++++++++++++----- 2 files changed, 63 insertions(+), 6 deletions(-) diff --git a/validation/tests/test_validate.py b/validation/tests/test_validate.py index a7406f954..810ee61d6 100644 --- a/validation/tests/test_validate.py +++ b/validation/tests/test_validate.py @@ -1255,6 +1255,50 @@ def test_rejects_a_sql_statement_in_ossie_sql_2026() -> None: assert error == "[SQL] ctx: expected an expression, found a DROP statement" +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +@pytest.mark.parametrize("dialect", ["ANSI_SQL", "OSSIE_SQL_2026", "SNOWFLAKE"]) +@pytest.mark.parametrize( + ("expression", "kind"), + [ + ("DROP TABLE orders; -- cleanup", "DROP"), + ("DELETE FROM orders; -- x", "DELETE"), + ("DROP TABLE orders; /* cleanup */", "DROP"), + ("TRUNCATE TABLE orders;\n-- cleanup", "TRUNCATE TABLE"), + ("GRANT SELECT ON orders TO public;; -- x", "GRANT"), + ], + ids=["drop", "delete", "block-comment", "comment-on-next-line", "two-semicolons"], +) +def test_rejects_a_statement_followed_by_a_comment( + expression: str, kind: str, dialect: str +) -> None: + """`parse_one` returns the statement and the comment's Semicolon in a Block. + + That is one statement to the count check, so the kind check has to read the + statement inside the Block. + """ + error = _VALIDATE.validate_sql_expression(expression, dialect, "ctx") + + assert error == f"[SQL] ctx: expected an expression, found a {kind} statement" + + +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +@pytest.mark.parametrize("dialect", ["ANSI_SQL", "OSSIE_SQL_2026"]) +@pytest.mark.parametrize( + "expression", + [ + "amount; -- note", + "SUM(amount); /* total */", + "commit; -- a column named commit", + "drop * 2; -- c", + "comment IS NOT NULL; -- c", + ], + ids=["column", "aggregate", "keyword-column", "first-token-quoted", "select-wrap"], +) +def test_accepts_an_expression_followed_by_a_comment(expression: str, dialect: str) -> None: + """A comment after the semicolon leaves one expression, keyword-named columns included.""" + assert _VALIDATE.validate_sql_expression(expression, dialect, "ctx") is None + + @pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") @pytest.mark.parametrize( ("expression", "dialect", "kind"), diff --git a/validation/validate.py b/validation/validate.py index 6fc2fde1b..c333ec64b 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -331,11 +331,7 @@ def _expression_with_first_token_quoted(sql: str, dialect: object) -> object | N quoted = exp.to_identifier(text, quoted=True).sql(dialect=dialect) rewritten = sql[: first.start] + quoted + sql[first.end + 1 :] try: - statements = [ - statement - for statement in sqlglot.parse(rewritten, dialect=dialect) - if statement is not None - ] + statements = _statements(sqlglot.parse(rewritten, dialect=dialect)) except (ParseError, TokenError, RecursionError): return None if len(statements) != 1: @@ -1262,6 +1258,21 @@ def _statements(parsed: list) -> list: return [s for s in parsed if s is not None and not isinstance(s, exp.Semicolon)] +def _sole_statement(tree: object) -> object: + """The statement a `parse_one` result holds when a comment follows it. + + `parse_one` returns `DROP TABLE t; -- note` as a `Block` of the `Drop` and + the comment's `Semicolon`. That is one statement to `_statements`, so the + count check passes it, and the checks after it have to read the `Drop`, not + the `Block` around it. Any other tree is returned as it is. + """ + if isinstance(tree, exp.Block): + statements = _statements(tree.expressions) + if len(statements) == 1: + return statements[0] + return tree + + def _parse_sql_expression( expr: str, dialect: str, context: str ) -> tuple[object | None, str | None]: @@ -1350,7 +1361,7 @@ def wrapped_select() -> tuple[object | None, str | None]: count_error = statement_count_error(f"SELECT {expr}") if count_error: return None, count_error - return wrapped, None + return _sole_statement(wrapped), None try: # Try parsing as expression first (for field expressions like "column_name") @@ -1366,6 +1377,8 @@ def wrapped_select() -> tuple[object | None, str | None]: count_error = statement_count_error(expr) if count_error: return None, count_error + # One statement followed by a comment is a Block; check the statement. + tree = _sole_statement(tree) kind_error = statement_kind_error(tree) if kind_error: ident = _single_identifier_text(expr, sqlglot_dialect) From e8b71fde89edb7a6a96529faeb7283dc93f8428f Mon Sep 17 00:00:00 2001 From: 403Page Date: Thu, 19 Nov 2026 18:00:42 +0000 Subject: [PATCH 7/7] feat(validation): reject a portable expression written behind its own 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. --- validation/tests/test_validate.py | 45 +++++++++++++++++++++++++++++++ validation/validate.py | 17 ++++++++++-- 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/validation/tests/test_validate.py b/validation/tests/test_validate.py index 810ee61d6..644b4b794 100644 --- a/validation/tests/test_validate.py +++ b/validation/tests/test_validate.py @@ -4395,6 +4395,51 @@ def test_a_portable_expression_that_is_a_query_is_an_error(expression: str, repo assert reported in result[0] +_EXPRESSIONS_BEHIND_A_SELECT = [ + "SELECT SUM(orders.customer_id)", + "SELECT orders.customer_id", + "SELECT orders.customer_id AS total", + "select sum(orders.customer_id)", + "SELECT SUM(orders.customer_id);", + "SELECT SUM(orders.customer_id); -- total", + "-- total\nSELECT SUM(orders.customer_id)", +] + + +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +@pytest.mark.parametrize("expression", _EXPRESSIONS_BEHIND_A_SELECT) +def test_a_portable_expression_written_behind_a_select_is_rejected(expression: str) -> None: + """A SELECT with one projection and no clause is the tree the `SELECT {expr}` + wrapper produces, so the tree cannot say who wrote the SELECT. The parse can: + text that parses alone was not wrapped. expression_language.md lists SELECT + under Not Supported in Expressions.""" + result = _VALIDATE.validate_sql(_metric_document(expression, "OSSIE_SQL_2026")) + assert _is_error_not_warning(result) + assert len(result) == 1 + assert "is written as a SELECT" in result[0] + assert "Metric 'm1'" in result[0] + + +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +@pytest.mark.parametrize("dialect", ["SNOWFLAKE", "ANSI_SQL"]) +@pytest.mark.parametrize("expression", _EXPRESSIONS_BEHIND_A_SELECT) +def test_an_expression_behind_a_select_in_another_dialect_is_not_shape_checked( + expression: str, dialect: str +) -> None: + assert _VALIDATE.validate_sql(_metric_document(expression, dialect)) == [] + + +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +@pytest.mark.parametrize( + "expression", + ["SUM(orders.customer_id)", "comment IS NOT NULL", "drop * 2", "commit"], + ids=["parses-alone", "select-wrap", "first-token-quoted", "keyword-column"], +) +def test_a_portable_expression_the_validator_wraps_itself_still_passes(expression: str) -> None: + """The SELECT the validator adds to parse an expression is not the author's.""" + assert _VALIDATE.validate_sql_expression(expression, "OSSIE_SQL_2026", "ctx") is None + + _QUERIES_WITHOUT_SELECT = [ ("SUM(orders.customer_id) FROM orders", "contains a FROM clause"), ("SUM(orders.customer_id) WHERE orders.product_id = 1", "contains a WHERE clause"), diff --git a/validation/validate.py b/validation/validate.py index c333ec64b..7b43824b8 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -1393,6 +1393,16 @@ def wrapped_select() -> tuple[object | None, str | None]: if quoted is not None: return quoted, None return None, kind_error + if dialect == PORTABLE_DIALECT and isinstance(tree, exp.Select): + # The text parsed alone, so the author wrote this SELECT: the + # wrapper below was not used. Name a clause if it has one; a + # SELECT with a single projection and no clause is still a + # SELECT (expression_language.md, Not Supported in Expressions). + return None, query_shape_error(tree, context) or ( + f"[SQL] {context}: is written as a SELECT; an expression is an " + f"aggregate or scalar expression over fields, not a query " + f"(expression_language.md, Not Supported in Expressions)" + ) return tree, None wrapped, wrap_error = wrapped_select() @@ -1417,7 +1427,8 @@ def validate_sql_expression(expr: str, dialect: str, context: str) -> str | None rejected for every dialect sqlglot parses. A query (a subquery, a set operation, VALUES, a clause on the root SELECT or a projection list) is rejected in OSSIE_SQL_2026 only, with or without its SELECT, and the error - names what made it one; the other dialects are opaque to the specification, + names what made it one. So is an expression written behind its own SELECT + (`SELECT SUM(x)`). The other dialects are opaque to the specification, where only a query written without its SELECT is reported, as a statement. """ tree, error = _parse_sql_expression(expr, dialect, context) @@ -1467,7 +1478,9 @@ def query_shape_error(tree, context: str) -> str | None: part of the expression; neither sets an argument on the root. A bare `SELECT SUM(x)` parses to the same tree as the wrapper around an - expression that needed one, so it is not told apart here and still passes. + expression that needed one, so it is not told apart here. The parse knows + which of the two it was: _parse_sql_expression reports a SELECT the text + spells out and hands this check a wrapped tree only. """ set_operation = getattr(exp, "SetOperation", exp.Union) if isinstance(tree, set_operation):