Skip to content

Commit 1f96a72

Browse files
authored
fix(cli): let plan --restate-model run without local model files (#6219)
Signed-off-by: mokashang <shangmengjiajiajia@gmail.com>
1 parent 28d53c2 commit 1f96a72

3 files changed

Lines changed: 174 additions & 2 deletions

File tree

‎sqlmesh/cli/main.py‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,19 @@
4646
OPTIONAL_LOCAL_COMMANDS = ("lint", "test")
4747

4848

49+
def _is_restate_arg(arg: str) -> bool:
50+
"""Whether ``arg`` is a ``--restate-model`` / ``-r`` option token.
51+
52+
Covers the four spellings Click accepts: ``--restate-model VALUE``,
53+
``--restate-model=VALUE``, ``-r VALUE`` and ``-rVALUE``.
54+
"""
55+
if arg == "--restate-model" or arg.startswith("--restate-model="):
56+
return True
57+
if arg == "-r" or (arg.startswith("-r") and not arg.startswith("--")):
58+
return True
59+
return False
60+
61+
4962
class _SQLMeshGroup(click.Group):
5063
def parse_args(self, ctx: click.Context, args: t.List[str]) -> t.List[str]:
5164
rest = super().parse_args(ctx, args)
@@ -151,6 +164,14 @@ def cli(
151164
if ctx.invoked_subcommand == "lint":
152165
load = False
153166

167+
# `plan --restate-model` operates entirely against state, so a project with no
168+
# local model definitions should still be allowed to run (parity with `run`).
169+
# Local loading itself stays on so that backfill expansion, unit tests, and the
170+
# linter continue to work when model files are present.
171+
restating = ctx.invoked_subcommand == "plan" and any(
172+
_is_restate_arg(arg) for arg in ctx.meta["subcommand_args"]
173+
)
174+
154175
configs = load_configs(config, Context.CONFIG_TYPE, paths, dotenv_path=dotenv)
155176
log_limit = list(configs.values())[0].log_limit
156177

@@ -169,7 +190,7 @@ def cli(
169190
logger.exception("Failed to initialize SQLMesh context")
170191
raise
171192

172-
if load and not context.models:
193+
if load and not context.models and not restating:
173194
raise click.ClickException(
174195
f"`{paths}` doesn't seem to have any models... cd into the proper directory or specify the path(s) with -p."
175196
)

‎sqlmesh/core/context.py‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1771,7 +1771,23 @@ def plan_builder(
17711771

17721772
expanded_restate_models = None
17731773
if restate_models is not None:
1774-
expanded_restate_models = model_selector.expand_model_selections(restate_models)
1774+
# Restatements operate entirely against state. Build a dedicated
1775+
# selector over the union of local and environment models so that
1776+
# both name lookup and upstream expansion (e.g. ``-r '+model'``)
1777+
# reach dependencies that only exist in the target environment.
1778+
env_models_for_restate = model_selector._load_env_models(
1779+
environment,
1780+
fallback_env_name=create_from or c.PROD,
1781+
ensure_finalized_snapshots=self.config.plan.use_finalized_state,
1782+
)
1783+
restate_models_combined: UniqueKeyDict[str, Model] = UniqueKeyDict("models")
1784+
for fqn, model in {**env_models_for_restate, **self._models}.items():
1785+
restate_models_combined[fqn] = model
1786+
restate_dag: DAG[str] = DAG()
1787+
for fqn, model in restate_models_combined.items():
1788+
restate_dag.add(fqn, model.depends_on)
1789+
restate_selector = self._new_selector(models=restate_models_combined, dag=restate_dag)
1790+
expanded_restate_models = restate_selector.expand_model_selections(restate_models)
17751791

17761792
if (restate_models is not None and not expanded_restate_models) or (
17771793
backfill_models is not None and not backfill_models and not selected_deletion_fqns

‎tests/cli/test_cli.py‎

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,141 @@ def test_plan_restate_model(runner, tmp_path):
370370
assert "Virtual layer updated" not in result.output
371371

372372

373+
@pytest.mark.parametrize(
374+
"restate_args",
375+
[
376+
pytest.param(["--restate-model", "sqlmesh_example.full_model"], id="long-space"),
377+
pytest.param(["--restate-model=sqlmesh_example.full_model"], id="long-equals"),
378+
pytest.param(["-r", "sqlmesh_example.full_model"], id="short-space"),
379+
pytest.param(["-rsqlmesh_example.full_model"], id="short-attached"),
380+
],
381+
)
382+
def test_plan_restate_model_without_local_definitions(runner, tmp_path, restate_args):
383+
"""`plan --restate-model` should work against state alone, like `run`.
384+
385+
Reproduces https://github.com/SQLMesh/sqlmesh/issues/3260. Each
386+
parametrization covers one of the spellings Click accepts for the
387+
option so the empty-project bypass tracks whatever form the user types.
388+
"""
389+
create_example_project(tmp_path)
390+
init_prod_and_backfill(runner, tmp_path)
391+
392+
# Wipe every local project directory, keeping only config.yaml + db.db.
393+
for subdir in ("models", "seeds", "tests", "audits", "macros", ".cache"):
394+
rmtree(tmp_path / subdir, ignore_errors=True)
395+
assert not (tmp_path / "models").exists()
396+
397+
result = runner.invoke(
398+
cli,
399+
[
400+
"--log-file-dir",
401+
tmp_path,
402+
"--paths",
403+
tmp_path,
404+
"plan",
405+
*restate_args,
406+
"--start",
407+
"",
408+
"--end",
409+
"",
410+
"--auto-apply",
411+
],
412+
)
413+
assert result.exit_code == 0, result.output
414+
assert "doesn't seem to have any models" not in result.output
415+
assert "Models selected for restatement" in result.output
416+
assert "sqlmesh_example.full_model" in result.output
417+
assert_model_batches_executed(result)
418+
419+
420+
def test_plan_without_restate_and_no_local_models_still_errors(runner, tmp_path):
421+
"""A non-restatement plan against an empty project must still error out."""
422+
create_example_project(tmp_path)
423+
init_prod_and_backfill(runner, tmp_path)
424+
425+
for subdir in ("models", "seeds", "tests", "audits", "macros", ".cache"):
426+
rmtree(tmp_path / subdir, ignore_errors=True)
427+
428+
result = runner.invoke(
429+
cli,
430+
["--log-file-dir", tmp_path, "--paths", tmp_path, "plan"],
431+
)
432+
assert result.exit_code == 1
433+
assert "doesn't seem to have any models" in result.output
434+
435+
436+
def test_plan_restate_upstream_models_without_local_definitions(runner, tmp_path):
437+
"""``-r '+<model>'`` should restate upstream deployed models even without local files."""
438+
create_example_project(tmp_path)
439+
init_prod_and_backfill(runner, tmp_path)
440+
441+
for subdir in ("models", "seeds", "tests", "audits", "macros", ".cache"):
442+
rmtree(tmp_path / subdir, ignore_errors=True)
443+
444+
result = runner.invoke(
445+
cli,
446+
[
447+
"--log-file-dir",
448+
tmp_path,
449+
"--paths",
450+
tmp_path,
451+
"plan",
452+
"--restate-model",
453+
"+sqlmesh_example.full_model",
454+
"--start",
455+
"",
456+
"--end",
457+
"",
458+
"--auto-apply",
459+
],
460+
)
461+
assert result.exit_code == 0, result.output
462+
assert "Models selected for restatement" in result.output
463+
# full_model depends on incremental_model, which depends on seed_model;
464+
# a `+` selector must pick both upstream dependencies from state.
465+
assert "sqlmesh_example.full_model" in result.output
466+
assert "sqlmesh_example.incremental_model" in result.output
467+
assert_model_batches_executed(result)
468+
469+
470+
def test_plan_restate_model_with_backfill_model_and_skip_linter(runner, tmp_path):
471+
"""Restatements with local models and ``--backfill-model`` must still expand selectors.
472+
473+
With local model files present, ``plan --skip-linter --restate-model X
474+
--backfill-model Y`` has to run both selector expansions against the
475+
local project. Keeping local loading enabled for restate plans is what
476+
makes this case work.
477+
"""
478+
create_example_project(tmp_path)
479+
init_prod_and_backfill(runner, tmp_path)
480+
481+
result = runner.invoke(
482+
cli,
483+
[
484+
"--log-file-dir",
485+
tmp_path,
486+
"--paths",
487+
tmp_path,
488+
"plan",
489+
"--skip-linter",
490+
"--restate-model",
491+
"sqlmesh_example.full_model",
492+
"--backfill-model",
493+
"sqlmesh_example.*",
494+
"--start",
495+
"",
496+
"--end",
497+
"",
498+
"--auto-apply",
499+
],
500+
)
501+
assert result.exit_code == 0, result.output
502+
assert "Selector did not return any models" not in result.output
503+
assert "Models selected for restatement" in result.output
504+
assert "sqlmesh_example.full_model" in result.output
505+
assert_model_batches_executed(result)
506+
507+
373508
@pytest.mark.parametrize("flag", ["--skip-backfill", "--dry-run"])
374509
def test_plan_skip_backfill(runner, tmp_path, flag):
375510
create_example_project(tmp_path)

0 commit comments

Comments
 (0)