From f474aa5d0ecc85d831a882af14ae05aa951c2781 Mon Sep 17 00:00:00 2001 From: vignesh_A Date: Fri, 20 Nov 2026 17:05:44 +0530 Subject: [PATCH] fix(validation): reject INTERVAL, empty IN, alias, and bare DISTINCT sqlglot parses eight of the fifteen expressions in compliance/expressions/invalid.txt, so validate.py printed Validation PASSED for portable sql that the grammar and expression_language.md reject: juxtaposition (`a b`, `a IS`), an empty IN list, INTERVAL date arithmetic, and DISTINCT with no argument. The grammar tests already run both fixture files. Wire them into the validator tests too, and after a successful parse of OSSIE_SQL_2026 walk the tree for those constructs. SELECT a FROM t stays deferred. Vendor dialects are left alone, so a Postgres INTERVAL or BigQuery DATE_ADD with INTERVAL still passes. --- validation/tests/test_validate.py | 106 ++++++++++++++++++++++++++++++ validation/validate.py | 52 ++++++++++++++- 2 files changed, 155 insertions(+), 3 deletions(-) diff --git a/validation/tests/test_validate.py b/validation/tests/test_validate.py index f9f77706..d759bd17 100644 --- a/validation/tests/test_validate.py +++ b/validation/tests/test_validate.py @@ -975,6 +975,112 @@ def test_flags_an_invalid_ossie_sql_2026_expression() -> None: assert error.startswith("[SQL] ctx:") +_COMPLIANCE_EXPRESSIONS = Path(__file__).parents[2] / "compliance" / "expressions" +# Query-shaped fixture line. expression_language.md lists SELECT as unsupported +# in expressions; rejecting it is a separate change from these construct checks. +_INVALID_QUERY_EXPRESSION = "SELECT a FROM t" + + +def _compliance_expressions(name: str) -> list[str]: + """One expression per line; blank lines and '#' comments are skipped.""" + text = (_COMPLIANCE_EXPRESSIONS / name).read_text(encoding="utf-8") + return [line for line in text.splitlines() if line.strip() and not line.startswith("#")] + + +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +@pytest.mark.parametrize("expression", _compliance_expressions("valid.txt")) +def test_valid_compliance_expressions_are_accepted(expression: str) -> None: + assert _VALIDATE.validate_sql_expression(expression, "OSSIE_SQL_2026", "ctx") is None + + +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +@pytest.mark.parametrize( + "expression", + [ + line + for line in _compliance_expressions("invalid.txt") + if line != _INVALID_QUERY_EXPRESSION + ], +) +def test_invalid_compliance_expressions_are_rejected(expression: str) -> None: + error = _VALIDATE.validate_sql_expression(expression, "OSSIE_SQL_2026", "ctx") + + assert error is not None + assert error.startswith("[SQL] ctx:") + + +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +@pytest.mark.parametrize( + ("expression", "detail"), + [ + ("order_date + INTERVAL '7 days'", "INTERVAL is not part of OSSIE_SQL_2026"), + ("DATE_ADD(d, INTERVAL 7 DAY)", "INTERVAL is not part of OSSIE_SQL_2026"), + ("INTERVAL '7 days'", "INTERVAL is not part of OSSIE_SQL_2026"), + ("x IN ()", "IN list must contain at least one value"), + ("x NOT IN ()", "IN list must contain at least one value"), + ("a b", "expected an expression, found an alias"), + ("a IS", "expected an expression, found an alias"), + ("a AS b", "expected an expression, found an alias"), + ("SUM(DISTINCT)", "DISTINCT requires an argument"), + ("COUNT(DISTINCT)", "DISTINCT requires an argument"), + ("AVG(DISTINCT)", "DISTINCT requires an argument"), + ], + ids=[ + "interval-add", + "date-add-interval", + "bare-interval", + "empty-in", + "empty-not-in", + "juxtaposition", + "dangling-is", + "explicit-alias", + "sum-distinct", + "count-distinct", + "avg-distinct", + ], +) +def test_rejects_portable_sql_constructs_sqlglot_still_parses( + expression: str, detail: str +) -> None: + error = _VALIDATE.validate_sql_expression(expression, "OSSIE_SQL_2026", "ctx") + + assert error == f"[SQL] ctx: {detail}" + + +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +@pytest.mark.parametrize( + ("expression", "dialect"), + [ + ("order_date + INTERVAL '7 days'", "POSTGRES"), + ("DATE_ADD(d, INTERVAL 7 DAY)", "BIGQUERY"), + ], + ids=["postgres-interval", "bigquery-date-add-interval"], +) +def test_interval_stays_valid_in_vendor_dialects(expression: str, dialect: str) -> None: + assert _VALIDATE.validate_sql_expression(expression, dialect, "ctx") is None + + +@pytest.mark.skipif(not _VALIDATE.SQLGLOT_AVAILABLE, reason="sqlglot is not installed") +def test_validate_sql_rejects_portable_interval_on_sql() -> None: + dataset = { + **_ORDERS, + "fields": [ + { + "name": "week_later", + "expression": {"sql": "order_date + INTERVAL '7 days'"}, + } + ], + "metrics": [{"name": "distinct_none", "expression": {"sql": "SUM(DISTINCT)"}}], + } + + assert _VALIDATE.validate_sql(_document([dataset], [])) == [ + "[SQL] Field 'orders.week_later' in model 'm' (OSSIE_SQL_2026): " + "INTERVAL is not part of OSSIE_SQL_2026", + "[SQL] Metric 'orders.distinct_none' in model 'm' (OSSIE_SQL_2026): " + "DISTINCT requires an argument", + ] + + def _parse_ossie_sql(expression: str): """Parse *expression* the way the validator parses an OSSIE_SQL_2026 body.""" return _VALIDATE.sqlglot.parse_one( diff --git a/validation/validate.py b/validation/validate.py index d52583ac..f78c8a87 100644 --- a/validation/validate.py +++ b/validation/validate.py @@ -1437,15 +1437,61 @@ def wrapped_select() -> tuple[object | None, str | None]: return None, f"[SQL] {context}: expected an expression, found a statement" +def _portable_sql_construct_error(tree: object, context: str) -> str | None: + """Reject OSSIE_SQL_2026 constructs sqlglot parses that the language does not. + + compliance/expressions/invalid.txt is the must-reject list for a parser of + OSSIE_SQL_2026. sqlglot still accepts INTERVAL (Postgres / BigQuery date + arithmetic; portable date add is DATEADD), an empty IN list, juxtaposition + parsed as an alias (`a b`, `a IS`), and DISTINCT with no argument. SELECT + stays deferred. Vendor dialects are not checked here, so a Postgres + INTERVAL or BigQuery DATE_ADD(..., INTERVAL ...) dialect entry still + passes. getattr skips names a given sqlglot version does not ship. + """ + if not SQLGLOT_AVAILABLE or not hasattr(tree, "find_all"): + return None + + interval_cls = getattr(exp, "Interval", None) + if interval_cls is not None and next(tree.find_all(interval_cls), None) is not None: + return f"[SQL] {context}: INTERVAL is not part of OSSIE_SQL_2026" + + in_cls = getattr(exp, "In", None) + if in_cls is not None: + for node in tree.find_all(in_cls): + # A subquery IN stores the query and has no value list; empty IN () + # is the list with no expressions. Subqueries stay deferred. + if node.args.get("query") is not None: + continue + if not node.args.get("expressions"): + return f"[SQL] {context}: IN list must contain at least one value" + + alias_cls = getattr(exp, "Alias", None) + if alias_cls is not None and next(tree.find_all(alias_cls), None) is not None: + return f"[SQL] {context}: expected an expression, found an alias" + + distinct_cls = getattr(exp, "Distinct", None) + if distinct_cls is not None: + for node in tree.find_all(distinct_cls): + if node.args.get("this") is None and not node.args.get("expressions"): + return f"[SQL] {context}: DISTINCT requires an argument" + return None + + def validate_sql_expression(expr: str, dialect: str, context: str) -> str | None: """Validate a single SQL expression. Returns error message or None if valid. A field or metric holds one expression (spec.md Fields / Metrics), not a statement. Multi-statement strings and DDL/DML/session statements are - rejected. Top-level SELECT is not rejected here. + rejected. Top-level SELECT is not rejected here. OSSIE_SQL_2026 is also + checked against the portable language: INTERVAL, an empty IN list, an + alias, and DISTINCT with no argument are errors. """ - _tree, error = _parse_sql_expression(expr, dialect, context) - return error + tree, error = _parse_sql_expression(expr, dialect, context) + if error: + return error + if tree is not None and dialect == PORTABLE_DIALECT: + return _portable_sql_construct_error(tree, context) + return None def parse_tree(expr: str, dialect: str, context: str):