diff --git a/sqlmesh/cli/main.py b/sqlmesh/cli/main.py index 896b47abd7..296f33a8d1 100644 --- a/sqlmesh/cli/main.py +++ b/sqlmesh/cli/main.py @@ -46,6 +46,19 @@ OPTIONAL_LOCAL_COMMANDS = ("lint", "test") +def _is_restate_arg(arg: str) -> bool: + """Whether ``arg`` is a ``--restate-model`` / ``-r`` option token. + + Covers the four spellings Click accepts: ``--restate-model VALUE``, + ``--restate-model=VALUE``, ``-r VALUE`` and ``-rVALUE``. + """ + if arg == "--restate-model" or arg.startswith("--restate-model="): + return True + if arg == "-r" or (arg.startswith("-r") and not arg.startswith("--")): + return True + return False + + class _SQLMeshGroup(click.Group): def parse_args(self, ctx: click.Context, args: t.List[str]) -> t.List[str]: rest = super().parse_args(ctx, args) @@ -151,6 +164,14 @@ def cli( if ctx.invoked_subcommand == "lint": load = False + # `plan --restate-model` operates entirely against state, so a project with no + # local model definitions should still be allowed to run (parity with `run`). + # Local loading itself stays on so that backfill expansion, unit tests, and the + # linter continue to work when model files are present. + restating = ctx.invoked_subcommand == "plan" and any( + _is_restate_arg(arg) for arg in ctx.meta["subcommand_args"] + ) + configs = load_configs(config, Context.CONFIG_TYPE, paths, dotenv_path=dotenv) log_limit = list(configs.values())[0].log_limit @@ -169,7 +190,7 @@ def cli( logger.exception("Failed to initialize SQLMesh context") raise - if load and not context.models: + if load and not context.models and not restating: raise click.ClickException( f"`{paths}` doesn't seem to have any models... cd into the proper directory or specify the path(s) with -p." ) diff --git a/sqlmesh/core/context.py b/sqlmesh/core/context.py index fd7f8ad071..a8ff8719ac 100644 --- a/sqlmesh/core/context.py +++ b/sqlmesh/core/context.py @@ -1771,7 +1771,23 @@ def plan_builder( expanded_restate_models = None if restate_models is not None: - expanded_restate_models = model_selector.expand_model_selections(restate_models) + # Restatements operate entirely against state. Build a dedicated + # selector over the union of local and environment models so that + # both name lookup and upstream expansion (e.g. ``-r '+model'``) + # reach dependencies that only exist in the target environment. + env_models_for_restate = model_selector._load_env_models( + environment, + fallback_env_name=create_from or c.PROD, + ensure_finalized_snapshots=self.config.plan.use_finalized_state, + ) + restate_models_combined: UniqueKeyDict[str, Model] = UniqueKeyDict("models") + for fqn, model in {**env_models_for_restate, **self._models}.items(): + restate_models_combined[fqn] = model + restate_dag: DAG[str] = DAG() + for fqn, model in restate_models_combined.items(): + restate_dag.add(fqn, model.depends_on) + restate_selector = self._new_selector(models=restate_models_combined, dag=restate_dag) + expanded_restate_models = restate_selector.expand_model_selections(restate_models) if (restate_models is not None and not expanded_restate_models) or ( backfill_models is not None and not backfill_models and not selected_deletion_fqns diff --git a/tests/cli/test_cli.py b/tests/cli/test_cli.py index 1602dc3b11..790e98afa6 100644 --- a/tests/cli/test_cli.py +++ b/tests/cli/test_cli.py @@ -370,6 +370,141 @@ def test_plan_restate_model(runner, tmp_path): assert "Virtual layer updated" not in result.output +@pytest.mark.parametrize( + "restate_args", + [ + pytest.param(["--restate-model", "sqlmesh_example.full_model"], id="long-space"), + pytest.param(["--restate-model=sqlmesh_example.full_model"], id="long-equals"), + pytest.param(["-r", "sqlmesh_example.full_model"], id="short-space"), + pytest.param(["-rsqlmesh_example.full_model"], id="short-attached"), + ], +) +def test_plan_restate_model_without_local_definitions(runner, tmp_path, restate_args): + """`plan --restate-model` should work against state alone, like `run`. + + Reproduces https://github.com/SQLMesh/sqlmesh/issues/3260. Each + parametrization covers one of the spellings Click accepts for the + option so the empty-project bypass tracks whatever form the user types. + """ + create_example_project(tmp_path) + init_prod_and_backfill(runner, tmp_path) + + # Wipe every local project directory, keeping only config.yaml + db.db. + for subdir in ("models", "seeds", "tests", "audits", "macros", ".cache"): + rmtree(tmp_path / subdir, ignore_errors=True) + assert not (tmp_path / "models").exists() + + result = runner.invoke( + cli, + [ + "--log-file-dir", + tmp_path, + "--paths", + tmp_path, + "plan", + *restate_args, + "--start", + "", + "--end", + "", + "--auto-apply", + ], + ) + assert result.exit_code == 0, result.output + assert "doesn't seem to have any models" not in result.output + assert "Models selected for restatement" in result.output + assert "sqlmesh_example.full_model" in result.output + assert_model_batches_executed(result) + + +def test_plan_without_restate_and_no_local_models_still_errors(runner, tmp_path): + """A non-restatement plan against an empty project must still error out.""" + create_example_project(tmp_path) + init_prod_and_backfill(runner, tmp_path) + + for subdir in ("models", "seeds", "tests", "audits", "macros", ".cache"): + rmtree(tmp_path / subdir, ignore_errors=True) + + result = runner.invoke( + cli, + ["--log-file-dir", tmp_path, "--paths", tmp_path, "plan"], + ) + assert result.exit_code == 1 + assert "doesn't seem to have any models" in result.output + + +def test_plan_restate_upstream_models_without_local_definitions(runner, tmp_path): + """``-r '+'`` should restate upstream deployed models even without local files.""" + create_example_project(tmp_path) + init_prod_and_backfill(runner, tmp_path) + + for subdir in ("models", "seeds", "tests", "audits", "macros", ".cache"): + rmtree(tmp_path / subdir, ignore_errors=True) + + result = runner.invoke( + cli, + [ + "--log-file-dir", + tmp_path, + "--paths", + tmp_path, + "plan", + "--restate-model", + "+sqlmesh_example.full_model", + "--start", + "", + "--end", + "", + "--auto-apply", + ], + ) + assert result.exit_code == 0, result.output + assert "Models selected for restatement" in result.output + # full_model depends on incremental_model, which depends on seed_model; + # a `+` selector must pick both upstream dependencies from state. + assert "sqlmesh_example.full_model" in result.output + assert "sqlmesh_example.incremental_model" in result.output + assert_model_batches_executed(result) + + +def test_plan_restate_model_with_backfill_model_and_skip_linter(runner, tmp_path): + """Restatements with local models and ``--backfill-model`` must still expand selectors. + + With local model files present, ``plan --skip-linter --restate-model X + --backfill-model Y`` has to run both selector expansions against the + local project. Keeping local loading enabled for restate plans is what + makes this case work. + """ + create_example_project(tmp_path) + init_prod_and_backfill(runner, tmp_path) + + result = runner.invoke( + cli, + [ + "--log-file-dir", + tmp_path, + "--paths", + tmp_path, + "plan", + "--skip-linter", + "--restate-model", + "sqlmesh_example.full_model", + "--backfill-model", + "sqlmesh_example.*", + "--start", + "", + "--end", + "", + "--auto-apply", + ], + ) + assert result.exit_code == 0, result.output + assert "Selector did not return any models" not in result.output + assert "Models selected for restatement" in result.output + assert "sqlmesh_example.full_model" in result.output + assert_model_batches_executed(result) + + @pytest.mark.parametrize("flag", ["--skip-backfill", "--dry-run"]) def test_plan_skip_backfill(runner, tmp_path, flag): create_example_project(tmp_path)