Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 106 additions & 8 deletions validation/tests/test_validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -1926,6 +1926,99 @@ def test_dataset_scoped_metric_count_star_references_no_field() -> None:
assert _VALIDATE.validate_metric_scoping(doc) == []


def test_dataset_scoped_metric_reads_a_date_part_as_a_unit_not_a_field() -> None:
# sqlglot's default parser reads the unit of DATEDIFF as a column, so the
# check walks iter_columns like the reference checks do.
doc = _orders_with(
fields=[
{"name": "opened_at", "expression": _ds_expr("opened_at")},
{"name": "closed_at", "expression": _ds_expr("closed_at")},
],
metrics=[
{"name": "days_open", "expression": _ds_expr("MAX(DATEDIFF(day, opened_at, closed_at))")},
{"name": "source_days_open", "expression": _ds_expr("MAX(DATEDIFF(day, source.opened_at, source.closed_at))")},
{"name": "minutes_since_open", "expression": _ds_expr("DATEDIFF(MINUTE, MAX(opened_at), CURRENT_TIMESTAMP)")},
{"name": "ansi_days_open", "expression": _ds_expr("MAX(DATEDIFF(day, opened_at, closed_at))", "ANSI_SQL")},

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.

These tests only cover OSSIE_SQL_2026 and ANSI_SQL, the two dialects that go through sqlglot default parser. The regressions above are in SNOWFLAKE and BIGQUERY, which aren't covered.

Could we add scoping cases for those two dialects? One case should declare a field named like a date part next to a unit sqlglot doesn't alias (ISOWEEK, NANOSECONDS). Another should use a non-Var unit like WEEK(MONDAY) with an undeclared field.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added in bbbe42d: a test where ISOWEEK next to a field day (BIGQUERY) and nanoseconds next to a field d (SNOWFLAKE) pass, and one where WEEK(MONDAY) with day undeclared (BIGQUERY) reports 'day'. Both pass on main and fail on 8655cbe.

],
)

assert _VALIDATE.validate_metric_scoping(doc) == []


def test_dataset_scoped_metric_reads_a_column_in_the_unit_slot_as_a_field() -> None:
# Under the default parser the last DATEDIFF argument lands in `unit`, so an
# undeclared field there must still be reported.
doc = _orders_with(
fields=[{"name": "opened_at", "expression": _ds_expr("opened_at")}],
metrics=[{"name": "days_open", "expression": _ds_expr("MAX(DATEDIFF(day, opened_at, closed_at))")}],
)

errors = _VALIDATE.validate_metric_scoping(doc)

assert len(errors) == 1
assert errors[0].startswith("[Scope]") and "'CLOSED_AT'" in errors[0] and "'day'" not in errors[0]


def test_dataset_scoped_metric_still_reports_a_bare_field_named_like_a_unit() -> None:
doc = _orders_with(
fields=[{"name": "amount", "expression": _ds_expr("amount")}],
metrics=[{"name": "total_minutes", "expression": _ds_expr("SUM(minute)")}],
)

errors = _VALIDATE.validate_metric_scoping(doc)

assert len(errors) == 1
assert errors[0].startswith("[Scope]") and "'minute'" in errors[0]


def test_dataset_scoped_metric_still_rejects_a_qualified_star() -> None:

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.

The description lists this test as failing on main, but it passes there: main find_all(exp.Column) walk already reports customers.*. It's still a good guard for the switch to iter_columns.

Could we update the description so it doesn't read as reproducing a bug?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Right. The description now lists it with the tests that pass on main.

# iter_columns skips every `*`; a qualified one names a dataset, or the
# source, and keeps the scoping rule.
doc = _orders_with(
metrics=[
{"name": "n_customers", "expression": _ds_expr("COUNT(customers.*)")},
{"name": "n_source", "expression": _ds_expr("COUNT(source.*)")},
],
)

errors = _VALIDATE.validate_metric_scoping(doc)

assert len(errors) == 1
assert errors[0].startswith("[Scope]") and "'customers'" in errors[0]


def test_dataset_scoped_metric_under_a_parser_that_knows_the_unit_reads_every_column_as_a_field() -> None:
# Snowflake and BigQuery put the unit in `unit` themselves, so a field named
# like a date part next to a unit the alias table lacks is still a field.
doc = _orders_with(
fields=[
{"name": "opened_at", "expression": _ds_expr("opened_at", "SNOWFLAKE")},
{"name": "d", "expression": _ds_expr("delivered_at", "SNOWFLAKE")},
{"name": "day", "expression": _ds_expr("delivered_day", "BIGQUERY")},
],
metrics=[
{"name": "ns_open", "expression": _ds_expr("MAX(DATEDIFF(nanoseconds, opened_at, d))", "SNOWFLAKE")},
{"name": "weeks_open", "expression": _ds_expr("MAX(DATE_DIFF(day, opened_at, ISOWEEK))", "BIGQUERY")},
],
)

assert _VALIDATE.validate_metric_scoping(doc) == []


def test_dataset_scoped_metric_under_a_parser_that_knows_the_unit_reports_the_date_argument() -> None:
# BigQuery puts `WEEK(MONDAY)` in `unit`, so `day` in `this` is the date
# argument and is reported when undeclared.
doc = _orders_with(
fields=[{"name": "opened_at", "expression": _ds_expr("opened_at", "BIGQUERY")}],
metrics=[{"name": "open", "expression": _ds_expr("MAX(DATE_DIFF(day, opened_at, WEEK(MONDAY)))", "BIGQUERY")}],
)

errors = _VALIDATE.validate_metric_scoping(doc)

assert len(errors) == 1
assert errors[0].startswith("[Scope]") and "undeclared field(s) 'day'." in errors[0]


def test_dataset_scoped_metric_scoping_skips_dialects_sqlglot_cannot_parse() -> None:
doc = _orders_with(
metrics=[{"name": "total", "expression": _ds_expr("SUM(orders.amount)", "MDX")}],
Expand Down Expand Up @@ -2616,12 +2709,13 @@ def test_a_parser_that_knows_the_unit_leaves_the_date_arguments_as_columns() ->
document = _renamed_model(metrics=[
_metric("ok", "SUM(DATEDIFF(day, orders.total_usd, orders.total_usd))", dialect="SNOWFLAKE"),
_metric("bad", "SUM(DATEDIFF(day, orders.total_usd, d))", dialect="SNOWFLAKE"),
_metric("unlisted", "SUM(DATEDIFF(nanoseconds, orders.total_usd, d))", dialect="SNOWFLAKE"),
])

errors = _VALIDATE.validate_metric_references(document)

assert len(errors) == 1
assert "'d' is not qualified" in errors[0]
assert len(errors) == 2
assert all("'d' is not qualified" in e for e in errors)


def test_metric_check_still_reports_a_bare_column_named_like_a_unit() -> None:
Expand Down Expand Up @@ -2795,18 +2889,22 @@ def test_a_repeated_reference_is_reported_once_per_expression() -> None:
]


@pytest.mark.parametrize("dialect", ["ANSI_SQL", "SNOWFLAKE"])
def test_date_add_reads_its_unit_as_a_unit_and_its_date_as_a_column(dialect) -> None:
# The default parser keeps DATE_ADD's unit in `this` and its date in `unit`.
@pytest.mark.parametrize(
("function", "dialect", "reported"),
[("DATE_ADD", "ANSI_SQL", "'SHIPPED'"), ("DATEADD", "SNOWFLAKE", "'shipped'")],
)
def test_date_add_reads_its_unit_as_a_unit_and_its_date_as_a_column(function, dialect, reported) -> None:
# The default parser keeps DATE_ADD's unit in `this` and its date in `unit`;
# Snowflake's reads DATEADD's date into `this` and keeps its spelling.
document = _renamed_model(metrics=[
_metric("ok", "MAX(DATE_ADD(day, 1, orders.total_usd))", dialect=dialect),
_metric("bad", "MAX(DATE_ADD(day, 1, shipped))", dialect=dialect),
_metric("ok", f"MAX({function}(day, 1, orders.total_usd))", dialect=dialect),
_metric("bad", f"MAX({function}(day, 1, shipped))", dialect=dialect),
])

errors = _VALIDATE.validate_metric_references(document)

assert [e.split(": ", 2)[2] for e in errors] == [
"'SHIPPED' is not qualified; metric expressions refer to fields as dataset.field",
f"{reported} is not qualified; metric expressions refer to fields as dataset.field",
]


Expand Down
57 changes: 37 additions & 20 deletions validation/validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,7 +535,14 @@ def is_date_part_name(name: str) -> bool:
return name.upper() in parts or name.upper() in parts.values()


def is_date_part(column) -> bool:
def uses_default_parser(dialect: str) -> bool:
"""Whether sqlglot reads this dialect with its default parser, which does
not know the unit of DATEDIFF, DATE_ADD or TIMESTAMPDIFF. `dialect` is one
of SQLGLOT_DIALECTS: the checks parse no other."""
return SQLGLOT_DIALECTS[dialect] is None


def is_date_part(column, dialect: str) -> bool:
"""Whether a bare name is the unit argument of a date function.

Only the unit position counts, since the alias table also holds short
Expand All @@ -548,12 +555,13 @@ def is_date_part(column) -> bool:
argument is itself named like one, the two readings cannot be told apart
and the column in ``this`` is reported. Functions the parser leaves
anonymous carry the unit as their first argument. DATE_TRUNC and its kin
never parse the unit as a column.
never parse the unit as a column. Under a dialect sqlglot parses with its
own parser, a column in ``this`` is a column.
"""
parent = column.parent
if column.table or not is_date_part_name(column.name):
return False
if isinstance(parent, UNIT_SLOT_FUNCTIONS):
if isinstance(parent, UNIT_SLOT_FUNCTIONS) and uses_default_parser(dialect):
unit = parent.args.get("unit")
unit_consumed = isinstance(unit, exp.Var) and is_date_part_name(unit.name)
return column.arg_key == "this" and unit is not None and not unit_consumed
Expand All @@ -562,22 +570,24 @@ def is_date_part(column) -> bool:
return False


def iter_columns(tree) -> Iterator["exp.Column"]:
"""The column references of a parsed expression, read the same way by both
reference checks: `*` references no column, the unit of a date function
is not one, and a unit slot the parser filled with a column is read as that
column. The default parser does not know DATEDIFF's unit, so in
`DATEDIFF(day, opened_at, closed_at)` it leaves `day` in `this` as a column
and reads `closed_at` into `unit` as a Var. When `this` is a bare column
named like a date part and `unit` is a Var that is not one, the Var is the
column, in the upper-cased spelling the parser keeps; a literal there, or a
unit the alias table lacks under a parser that knows the function, is left
alone.
def iter_columns(tree, dialect: str) -> Iterator["exp.Column"]:
"""The column references of a parsed expression, read the same way by the
reference checks and the scoping check: `*` references no column, the unit
of a date function is not one, and a unit slot the parser filled with a
column is read as that column. The default parser does not know DATEDIFF's
unit, so in `DATEDIFF(day, opened_at, closed_at)` it leaves `day` in `this`
as a column and reads `closed_at` into `unit` as a Var. When `this` is a
bare column named like a date part and `unit` is a Var that is not one, the
Var is the column, in the upper-cased spelling the parser keeps; a literal
there is left alone. Under a dialect sqlglot parses with its own parser,
nothing is read back from `unit`.
"""
for column in tree.find_all(exp.Column):
if isinstance(column.this, exp.Star) or is_date_part(column):
if isinstance(column.this, exp.Star) or is_date_part(column, dialect):
continue
yield column
if not uses_default_parser(dialect):
return
for node in tree.find_all(*UNIT_SLOT_FUNCTIONS):
first, unit = node.this, node.args.get("unit")
if (
Expand Down Expand Up @@ -621,7 +631,7 @@ def validate_metric_references(data: dict) -> list[str]:
if tree is None:
continue
seen = set()
for column in iter_columns(tree):
for column in iter_columns(tree, expression.dialect):
key = tuple(part.name.casefold() for part in column.parts)
if key in seen:
continue
Expand Down Expand Up @@ -698,7 +708,7 @@ def passes_through(tree, name: str) -> bool:
tree = parse_tree(expression.text, expression.dialect, context)
if tree is None:
continue
names = [c.name for c in iter_columns(tree) if not c.table]
names = [c.name for c in iter_columns(tree, expression.dialect) if not c.table]
for name in dict.fromkeys(names):
other = by_name.get(name.casefold())
if other is None or other["name"].casefold() == field["name"].casefold():
Expand Down Expand Up @@ -1008,8 +1018,8 @@ def validate_metric_scoping(data: dict) -> list[str]:
* No other qualified reference (`dataset.field`): that is model-scoped and
belongs in the model-root metrics.
* Every unqualified name must be a declared field of the dataset. A bare name
is compared case-insensitively; `COUNT(*)` and literals reference no field
and are fine.
is compared case-insensitively; `COUNT(*)`, literals and the unit of a
date function reference no field and are fine.
* `source.column` is not allowed when the dataset declares a field named
`source`, since the field takes precedence over the qualifier.

Expand All @@ -1032,7 +1042,14 @@ def scope_errors(expression: Expression) -> list[str]:
qualifiers = set()
undeclared = set()
uses_source = False
for col in tree.find_all(exp.Column):
# iter_columns skips every `*`; a qualified one, `customers.*`, still
# names a dataset or the source and is checked like any other
# qualified reference.
qualified_stars = (
col for col in tree.find_all(exp.Column)
if isinstance(col.this, exp.Star) and col.table
)
for col in (*iter_columns(tree, expression.dialect), *qualified_stars):
parts = [part.name for part in col.parts]
if len(parts) == 2 and parts[0].casefold() == SOURCE_QUALIFIER:
uses_source = True
Expand Down
Loading