Skip to content

Commit 53b06e4

Browse files
authored
Chore: Ensure model search fails gracefully (#4535)
1 parent 909548b commit 53b06e4

2 files changed

Lines changed: 35 additions & 6 deletions

File tree

sqlmesh/core/context.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -869,7 +869,12 @@ def get_model(
869869
Returns:
870870
The expected model.
871871
"""
872-
if isinstance(model_or_snapshot, str):
872+
if isinstance(model_or_snapshot, Snapshot):
873+
return model_or_snapshot.model
874+
if not isinstance(model_or_snapshot, str):
875+
return model_or_snapshot
876+
877+
try:
873878
# We should try all dialects referenced in the project for cases when models use mixed dialects.
874879
for dialect in self._all_dialects:
875880
normalized_name = normalize_model_name(
@@ -879,13 +884,16 @@ def get_model(
879884
)
880885
if normalized_name in self._models:
881886
return self._models[normalized_name]
882-
elif isinstance(model_or_snapshot, Snapshot):
883-
return model_or_snapshot.model
884-
else:
885-
return model_or_snapshot
887+
except:
888+
pass
886889

887890
if raise_if_missing:
888-
raise SQLMeshError(f"Cannot find model for '{model_or_snapshot}'")
891+
if model_or_snapshot.endswith((".sql", ".py")):
892+
msg = "Resolving models by path is not supported, please pass in the model name instead."
893+
else:
894+
msg = f"Cannot find model with name '{model_or_snapshot}'"
895+
896+
raise SQLMeshError(msg)
889897

890898
return None
891899

tests/core/test_integration.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6148,3 +6148,24 @@ def test_missing_connection_config():
61486148
ctx = Context(
61496149
config=Config(gateways={"default": GatewayConfig(connection=DuckDBConnectionConfig())})
61506150
)
6151+
6152+
6153+
@use_terminal_console
6154+
def test_render_path_instead_of_model(tmp_path: Path):
6155+
create_temp_file(tmp_path, Path("models/test.sql"), "MODEL (name test_model); SELECT 1 AS col")
6156+
ctx = Context(paths=tmp_path, config=Config())
6157+
6158+
# Case 1: Fail gracefully when the user is passing in a path instead of a model name
6159+
for test_model in ["models/test.sql", "models/test.py"]:
6160+
with pytest.raises(
6161+
SQLMeshError,
6162+
match="Resolving models by path is not supported, please pass in the model name instead.",
6163+
):
6164+
ctx.render(test_model)
6165+
6166+
# Case 2: Fail gracefully when the model name is not found
6167+
with pytest.raises(SQLMeshError, match="Cannot find model with name 'incorrect_model'"):
6168+
ctx.render("incorrect_model")
6169+
6170+
# Case 3: Render the model successfully
6171+
assert ctx.render("test_model").sql() == 'SELECT 1 AS "col"'

0 commit comments

Comments
 (0)