Skip to content
Open
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
26 changes: 16 additions & 10 deletions sqlmesh/core/model/meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
model_kind_validator,
OnAdditiveChange,
)
from sqlmesh.core.node import _Node, str_or_exp_to_str
from sqlmesh.core.node import _Node, description_to_str, str_or_exp_to_str
from sqlmesh.core.reference import Reference
from sqlmesh.utils.date import TimeLike
from sqlmesh.utils.errors import ConfigError
Expand Down Expand Up @@ -305,6 +305,11 @@ def _columns_validator(

return v

@field_validator("description", mode="before")
@classmethod
def _description_validator(cls, v: t.Any) -> t.Optional[str]:
return description_to_str(v)

@field_validator("column_descriptions_", mode="before")
def _column_descriptions_validator(
cls, vs: t.Any, info: ValidationInfo
Expand All @@ -323,16 +328,17 @@ def _column_descriptions_validator(

# Normalize each part while it is still an identifier, so that a quoted
# column keeps its case on dialects where quoting makes it significant.
col_descriptions = (
{normalize_identifiers(k, dialect=dialect).name: v for k, v in vs.items()}
if isinstance(vs, dict)
else {
".".join(
normalize_identifiers(part, dialect=dialect).name for part in v.this.parts
): v.expression.name
for v in vs
if isinstance(vs, dict):
col_descriptions = {
normalize_identifiers(k, dialect=dialect).name: v for k, v in vs.items()
}
)
else:
col_descriptions = {}
for v in vs:
column = ".".join(
normalize_identifiers(part, dialect=dialect).name for part in v.this.parts
)
col_descriptions[column] = description_to_str(v.expression, column=column)

columns_to_types = data.get("columns_to_types_")
if columns_to_types:
Expand Down
31 changes: 31 additions & 0 deletions sqlmesh/core/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -564,3 +564,34 @@ def str_or_exp_to_str(v: t.Any) -> t.Optional[str]:
if isinstance(v, exp.Expr):
return v.name
return str(v) if v is not None else None


def description_to_str(v: t.Any, column: t.Optional[str] = None) -> t.Optional[str]:
"""Converts a description to a string, rejecting expressions whose text would be lost.

`.name` is "" for compound expressions such as `exp.Concat`, so this raises when an expression
would be stored as "" even though it contains a boolean or a non-empty string. Values that are
empty anyway, such as `''` or `N''`, still load.
"""
if (
isinstance(v, exp.Expr)
and not v.name
and (
v.find(exp.Boolean) is not None
or any(
node.name
for node in v.find_all(
exp.Literal,
exp.National,
exp.RawString,
exp.ByteString,
exp.HexString,
exp.UnicodeString,
exp.BitString,
)
)
)
):
target = f"The description of column '{column}'" if column else "The model description"
raise ConfigError(f"{target} must be a single string literal, got: {v.sql()}")
return str_or_exp_to_str(v)
14 changes: 14 additions & 0 deletions tests/core/test_audit.py
Original file line number Diff line number Diff line change
Expand Up @@ -1438,3 +1438,17 @@ def test_audit_formatting_flag_serde():

deserialized_audit = ModelAudit.parse_raw(audit_json)
assert deserialized_audit.dict() == audit.dict()


def test_standalone_audit_description_is_not_checked():
# The check that rejects silently blanked descriptions (#6289) applies to models only, so a
# standalone audit keeps the previous conversion.
audit = load_audit(
parse(
"AUDIT (name a, standalone TRUE, dialect bigquery, description 'it''s'); SELECT 1",
default_dialect="bigquery",
),
dialect="bigquery",
)
assert isinstance(audit, StandaloneAudit)
assert audit.description == ""
77 changes: 77 additions & 0 deletions tests/core/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -1070,6 +1070,83 @@ def test_column_descriptions_dotted_identifier():
}


def _load_with_description(field: str, value: str, dialect: str):
"""Loads a model that sets the given description field to a raw SQL value."""
meta = (
f"description {value}" if field == "description" else f"column_descriptions (c = {value})"
)
expressions = d.parse(
f"MODEL (name db.m, dialect {dialect}, {meta}); SELECT 1 AS c", default_dialect=dialect
)
return load_sql_based_model(expressions, dialect=dialect, variables={"v": "hello"})


@pytest.mark.parametrize("field", ["description", "column_descriptions"])
@pytest.mark.parametrize(
"dialect, value, expected",
[
("bigquery", "'plain'", "plain"),
("bigquery", r"'it\'s'", "it's"),
("duckdb", "'it''s'", "it's"),
("bigquery", "some_ident", "some_ident"),
("bigquery", "''", ""),
# Values that are empty anyway must keep loading as "".
("tsql", "N''", ""),
("postgres", "$$$$", ""),
("bigquery", "@v", "hello"),
],
)
def test_description_values_load_unchanged(field, dialect, value, expected):
model = _load_with_description(field, value, dialect)
if field == "description":
assert model.description == expected
else:
assert model.column_descriptions == {"c": expected}


@pytest.mark.parametrize("field", ["description", "column_descriptions"])
@pytest.mark.parametrize(
"dialect, value, rendered",
[
("bigquery", "'it''s'", "CONCAT('it', 's')"),
("bigquery", "'first half' 'second half'", "CONCAT('first half', 'second half')"),
("bigquery", "TRUE", "TRUE"),
("bigquery", "FALSE", "FALSE"),
("bigquery", "'' 'x'", "CONCAT('', 'x')"),
("bigquery", "('it' 's')", "(CONCAT('it', 's'))"),
("bigquery", "(TRUE)", "(TRUE)"),
("duckdb", "'first half' 'second half'", "CONCAT('first half', 'second half')"),
],
)
def test_description_compound_expression_raises(field, dialect, value, rendered):
subject = "model description" if field == "description" else "description of column 'c'"
with pytest.raises(
ConfigError,
match=rf"{subject} must be a single string literal, got: {re.escape(rendered)}$",
):
_load_with_description(field, value, dialect)


@pytest.mark.parametrize("field", ["description", "column_descriptions"])
@pytest.mark.parametrize(
"dialect, value",
[
("tsql", "CONCAT(N'a', N'b')"),
("postgres", "CONCAT(E'a', E'b')"),
("postgres", "CONCAT($$a$$, $$b$$)"),
("bigquery", "CONCAT(r'a', r'b')"),
("mysql", "CONCAT(x'ab', '')"),
("trino", "CONCAT(U&'a', U&'b')"),
("postgres", "CONCAT(B'01', '')"),
],
)
def test_description_dialect_string_types_raise(field, dialect, value):
"""Text in each dialect-specific string type counts as text that would be lost."""
subject = "model description" if field == "description" else "description of column 'c'"
with pytest.raises(ConfigError, match=f"{subject} must be a single string literal"):
_load_with_description(field, value, dialect)


def test_model_jinja_macro_reference_extraction():
@macro()
def test_macro(**kwargs) -> None:
Expand Down