diff --git a/sqlmesh/core/model/meta.py b/sqlmesh/core/model/meta.py index 67ea32f9d9..54538c86ab 100644 --- a/sqlmesh/core/model/meta.py +++ b/sqlmesh/core/model/meta.py @@ -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 @@ -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 @@ -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: diff --git a/sqlmesh/core/node.py b/sqlmesh/core/node.py index 73e4a31940..d31cd285ec 100644 --- a/sqlmesh/core/node.py +++ b/sqlmesh/core/node.py @@ -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) diff --git a/tests/core/test_audit.py b/tests/core/test_audit.py index 288d6280e0..3c86280a93 100644 --- a/tests/core/test_audit.py +++ b/tests/core/test_audit.py @@ -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 == "" diff --git a/tests/core/test_model.py b/tests/core/test_model.py index 34bb5d1d1d..8b67ed1d20 100644 --- a/tests/core/test_model.py +++ b/tests/core/test_model.py @@ -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: