Skip to content

Commit b7f3a2b

Browse files
authored
Fix: improve error handling when SQL model query is invalid (#4551)
1 parent 68def30 commit b7f3a2b

File tree

2 files changed

+27
-13
lines changed

2 files changed

+27
-13
lines changed

sqlmesh/core/model/definition.py

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2173,24 +2173,18 @@ def load_sql_based_model(
21732173
**meta_fields,
21742174
)
21752175

2176-
if query_or_seed_insert is not None and (
2177-
isinstance(query_or_seed_insert, (exp.Query, d.JinjaQuery))
2178-
or (
2179-
# Macro functions are allowed in place of model queries only when there are no
2180-
# other statements in the model definition, otherwise they would be ambiguous
2181-
isinstance(query_or_seed_insert, d.MacroFunc)
2182-
and (query_or_seed_insert.this.name.lower() == "union" or len(expressions) == 2)
2183-
)
2184-
):
2176+
kind = common_kwargs.pop("kind", ModelMeta.all_field_infos()["kind"].default)
2177+
2178+
if kind.name != ModelKindName.SEED:
21852179
return create_sql_model(
21862180
name,
21872181
query_or_seed_insert,
2182+
kind=kind,
21882183
time_column_format=time_column_format,
21892184
**common_kwargs,
21902185
)
2191-
seed_properties = {
2192-
p.name.lower(): p.args.get("value") for p in common_kwargs.pop("kind").expressions
2193-
}
2186+
2187+
seed_properties = {p.name.lower(): p.args.get("value") for p in kind.expressions}
21942188
return create_seed_model(
21952189
name,
21962190
SeedKind(**seed_properties),
@@ -2200,7 +2194,7 @@ def load_sql_based_model(
22002194

22012195
def create_sql_model(
22022196
name: TableName,
2203-
query: exp.Expression,
2197+
query: t.Optional[exp.Expression],
22042198
**kwargs: t.Any,
22052199
) -> Model:
22062200
"""Creates a SQL model.
@@ -2215,6 +2209,7 @@ def create_sql_model(
22152209
"A query is required and must be a SELECT statement, a UNION statement, or a JINJA_QUERY block",
22162210
kwargs.get("path"),
22172211
)
2212+
assert isinstance(query, (exp.Query, d.JinjaQuery, d.MacroFunc))
22182213

22192214
return _create_model(SqlModel, name, query=query, **kwargs)
22202215

tests/core/test_model.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10150,3 +10150,22 @@ def getenv_macro(evaluator):
1015010150

1015110151
monkeypatch.chdir(tmp_path)
1015210152
ctx = Context(paths=tmp_path)
10153+
10154+
10155+
def test_invalid_sql_model_query() -> None:
10156+
for kind in ("", ", KIND FULL"):
10157+
expressions = d.parse(
10158+
f"""
10159+
MODEL (name db.table{kind});
10160+
10161+
JINJA_STATEMENT_BEGIN;
10162+
SELECT 1 AS c;
10163+
JINJA_END;
10164+
"""
10165+
)
10166+
10167+
with pytest.raises(
10168+
ConfigError,
10169+
match=r"^A query is required and must be a SELECT statement, a UNION statement, or a JINJA_QUERY block.*",
10170+
):
10171+
load_sql_based_model(expressions)

0 commit comments

Comments
 (0)