diff --git a/sqlmesh/core/plan/evaluator.py b/sqlmesh/core/plan/evaluator.py index 71e5285d63..4c23827b5b 100644 --- a/sqlmesh/core/plan/evaluator.py +++ b/sqlmesh/core/plan/evaluator.py @@ -382,6 +382,8 @@ def visit_migrate_schemas_stage( allow_destructive_snapshots=plan.allow_destructive_models, allow_additive_snapshots=plan.allow_additive_models, deployability_index=stage.deployability_index, + grants_only_snapshot_ids=stage.grants_only_snapshot_ids, + create_only_snapshot_ids=stage.create_only_snapshot_ids, ) except NodeExecutionFailedError as ex: raise PlanError(str(ex.__cause__) if ex.__cause__ else str(ex)) diff --git a/sqlmesh/core/plan/explainer.py b/sqlmesh/core/plan/explainer.py index 6e3fb8f9c3..578d52cad8 100644 --- a/sqlmesh/core/plan/explainer.py +++ b/sqlmesh/core/plan/explainer.py @@ -315,14 +315,35 @@ def visit_backfill_stage(self, stage: stages.BackfillStage) -> Tree: tree.add(f"{display_name} \\[standalone audit]") return tree - def visit_migrate_schemas_stage(self, stage: stages.MigrateSchemasStage) -> Tree: - tree = Tree( - "[bold]Update schemas (add, drop, alter columns) of production physical tables to reflect forward-only changes[/bold]" - ) + def visit_migrate_schemas_stage(self, stage: stages.MigrateSchemasStage) -> t.Optional[Tree]: + migrated_snapshots = [ + s + for s in stage.snapshots + if s.snapshot_id not in stage.grants_only_snapshot_ids + and s.snapshot_id not in stage.create_only_snapshot_ids + ] + grants_only_snapshots = [ + s for s in stage.snapshots if s.snapshot_id in stage.grants_only_snapshot_ids + ] + if not migrated_snapshots and not grants_only_snapshots: + return None + + if migrated_snapshots: + tree = Tree( + "[bold]Update schemas (add, drop, alter columns) of production physical tables to reflect forward-only changes[/bold]" + ) + else: + tree = Tree("[bold]Sync grants on production physical tables[/bold]") + for snapshot in stage.snapshots: + if snapshot.snapshot_id in stage.create_only_snapshot_ids: + continue display_name = self._display_name(snapshot) table_name = snapshot.table_name(True) - tree.add(f"{display_name} -> {table_name}") + if snapshot.snapshot_id in stage.grants_only_snapshot_ids: + tree.add(f"{display_name} -> {table_name} (sync grants)") + else: + tree.add(f"{display_name} -> {table_name}") return tree def visit_virtual_layer_update_stage(self, stage: stages.VirtualLayerUpdateStage) -> Tree: diff --git a/sqlmesh/core/plan/stages.py b/sqlmesh/core/plan/stages.py index 3d034cf6a1..a0376dc165 100644 --- a/sqlmesh/core/plan/stages.py +++ b/sqlmesh/core/plan/stages.py @@ -1,6 +1,6 @@ import typing as t -from dataclasses import dataclass +from dataclasses import dataclass, field from sqlmesh.core import constants as c from sqlmesh.core.environment import EnvironmentStatements, EnvironmentNamingInfo, Environment from sqlmesh.core.plan.common import should_force_rebuild @@ -154,11 +154,17 @@ class MigrateSchemasStage: snapshots: Snapshots to migrate schemas for. all_snapshots: All snapshots in the plan by snapshot ID. deployability_index: Deployability index for this stage. + grants_only_snapshot_ids: Snapshot IDs that only need physical grants synchronized + without recreating or altering their physical objects. + create_only_snapshot_ids: Snapshot IDs that should only be created if their physical + object does not yet exist, without being migrated or recreated if it already exists. """ snapshots: t.List[Snapshot] all_snapshots: t.Dict[SnapshotId, Snapshot] deployability_index: DeployabilityIndex + grants_only_snapshot_ids: t.Set[SnapshotId] = field(default_factory=set) + create_only_snapshot_ids: t.Set[SnapshotId] = field(default_factory=set) @dataclass @@ -264,6 +270,8 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]: before_promote_snapshots = all_selected_for_backfill_snapshots after_promote_snapshots = set() snapshots_with_schema_migration = [] + grants_only_snapshot_ids: t.Set[SnapshotId] = set() + create_only_snapshot_ids: t.Set[SnapshotId] = set() else: before_promote_snapshots = { s.snapshot_id @@ -274,27 +282,118 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]: after_promote_snapshots = all_selected_for_backfill_snapshots - before_promote_snapshots deployability_index = DeployabilityIndex.all_deployable() - snapshot_ids_with_schema_migration = [ - s.snapshot_id for s in snapshots.values() if s.requires_schema_migration_in_prod + if existing_environment and not existing_environment.expired: + finalized_prod_table_infos: t.List[SnapshotTableInfo] = ( + existing_environment.snapshots + if existing_environment.finalized_ts + else (existing_environment.previous_finalized_snapshots or []) + ) + else: + finalized_prod_table_infos = [] + finalized_prod_by_name = {s.name: s for s in finalized_prod_table_infos} + + candidate_mv_old_ids = [ + finalized_prod_by_name[s.name].snapshot_id + for s in snapshots.values() + if s.requires_schema_migration_in_prod + and s.is_materialized_view + and s.name in finalized_prod_by_name ] + old_snapshots_by_name: t.Dict[str, Snapshot] = {} + if candidate_mv_old_ids: + missing_old_ids = [s_id for s_id in candidate_mv_old_ids if s_id not in snapshots] + fetched_old_snapshots = ( + self.state_reader.get_snapshots(missing_old_ids) if missing_old_ids else {} + ) + for s_id in candidate_mv_old_ids: + old_snapshot = snapshots.get(s_id) or fetched_old_snapshots.get(s_id) + if old_snapshot: + old_snapshots_by_name[old_snapshot.name] = old_snapshot + + def _is_metadata_only_in_prod(s: Snapshot) -> bool: + existing = finalized_prod_by_name.get(s.name) + if existing is None or existing.is_symbolic: + return False + if existing.table_name(is_deployable=True) != s.table_name(is_deployable=True): + return False + old = old_snapshots_by_name.get(s.name) + if old is not None: + if s.is_directly_modified(old): + return False + elif existing.fingerprint.data_hash != s.fingerprint.data_hash: + return False + if existing.fingerprint.parent_data_hash != s.fingerprint.parent_data_hash: + return False + for p_id in s.parents: + parent = snapshots.get(p_id) + if parent is None: + return False + if parent.is_symbolic: + continue + existing_parent = finalized_prod_by_name.get(parent.name) + if ( + existing_parent is None + or existing_parent.is_symbolic + or existing_parent.table_name(is_deployable=True) + != parent.table_name(is_deployable=True) + ): + return False + return True + + schema_migration_snapshot_ids: t.List[SnapshotId] = [] + grants_only_snapshot_ids = set() + for s in snapshots.values(): + if not s.requires_schema_migration_in_prod: + continue + if s.is_materialized_view and _is_metadata_only_in_prod(s): + old = old_snapshots_by_name.get(s.name) + targets_physical_grants = s.model.grants is not None and ( + s.model.grants_target_layer.is_all + or s.model.grants_target_layer.is_physical + or s.model.virtual_environment_mode.is_dev_only + ) + grants_changed = ( + old is None + or s.model.grants != old.model.grants + or s.model.grants_target_layer != old.model.grants_target_layer + ) + if targets_physical_grants and grants_changed: + grants_only_snapshot_ids.add(s.snapshot_id) + continue + schema_migration_snapshot_ids.append(s.snapshot_id) + # Include all upstream dependencies of snapshots that require schema migration to make sure # the upstream tables are created before the schema updates are applied - snapshot_ids_to_migrate = set(dag.subdag(*snapshot_ids_with_schema_migration)) + snapshot_ids_to_migrate = set(dag.subdag(*schema_migration_snapshot_ids)) + upstream_only_ids = snapshot_ids_to_migrate - set(schema_migration_snapshot_ids) + create_only_snapshot_ids = { + s_id + for s_id in upstream_only_ids + if s_id not in grants_only_snapshot_ids + and snapshots[s_id].is_materialized_view + and snapshots[s_id].supports_schema_migration_in_prod + } # Migrating a view replaces it, and engines like Postgres drop its dependent views with CASCADE, # so those are migrated too to be recreated for s_id in dag: snapshot = snapshots[s_id] if snapshot.is_view and any( p_id in snapshot_ids_to_migrate + and p_id not in create_only_snapshot_ids + and p_id not in grants_only_snapshot_ids and snapshots[p_id].is_view and snapshots[p_id].supports_schema_migration_in_prod for p_id in snapshot.parents ): snapshot_ids_to_migrate.add(s_id) + grants_only_snapshot_ids.discard(s_id) + create_only_snapshot_ids.discard(s_id) + + all_migrate_stage_ids = snapshot_ids_to_migrate | grants_only_snapshot_ids snapshots_with_schema_migration = [ snapshots[s_id] for s_id in dag - if s_id in snapshot_ids_to_migrate + if s_id in all_migrate_stage_ids and snapshots[s_id].supports_schema_migration_in_prod ] @@ -393,6 +492,8 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]: snapshots=snapshots_with_schema_migration, all_snapshots=snapshots, deployability_index=deployability_index, + grants_only_snapshot_ids=grants_only_snapshot_ids, + create_only_snapshot_ids=create_only_snapshot_ids, ) ) diff --git a/sqlmesh/core/snapshot/evaluator.py b/sqlmesh/core/snapshot/evaluator.py index 345f8816e6..86294b1f7f 100644 --- a/sqlmesh/core/snapshot/evaluator.py +++ b/sqlmesh/core/snapshot/evaluator.py @@ -488,6 +488,8 @@ def migrate( allow_destructive_snapshots: t.Optional[t.Set[str]] = None, allow_additive_snapshots: t.Optional[t.Set[str]] = None, deployability_index: t.Optional[DeployabilityIndex] = None, + grants_only_snapshot_ids: t.Optional[t.Set[SnapshotId]] = None, + create_only_snapshot_ids: t.Optional[t.Set[SnapshotId]] = None, ) -> None: """Alters a physical snapshot table to match its snapshot's schema for the given collection of snapshots. @@ -497,6 +499,10 @@ def migrate( allow_destructive_snapshots: Set of snapshots that are allowed to have destructive schema changes. allow_additive_snapshots: Set of snapshots that are allowed to have additive schema changes. deployability_index: Determines snapshots that are deployable in the context of this evaluation. + grants_only_snapshot_ids: Snapshot IDs for which only physical grants should be synced if + the physical object already exists. + create_only_snapshot_ids: Snapshot IDs that should only be created if their physical + object does not yet exist. """ deployability_index = deployability_index or DeployabilityIndex.all_deployable() target_data_objects = self._get_physical_data_objects(target_snapshots, deployability_index) @@ -508,6 +514,8 @@ def migrate( allow_destructive_snapshots = allow_destructive_snapshots or set() allow_additive_snapshots = allow_additive_snapshots or set() + grants_only_snapshot_ids = grants_only_snapshot_ids or set() + create_only_snapshot_ids = create_only_snapshot_ids or set() snapshots_by_name = {s.name: s for s in snapshots.values()} with self.concurrent_context(): # Only migrate snapshots for which there's an existing data object @@ -521,6 +529,8 @@ def migrate( allow_additive_snapshots, self.get_adapter(s.model_gateway), deployability_index, + grants_only=s.snapshot_id in grants_only_snapshot_ids, + create_only=s.snapshot_id in create_only_snapshot_ids, ), self.ddl_concurrent_tasks, context_factory=execution_context_factory(), @@ -1164,6 +1174,8 @@ def _migrate_snapshot( allow_additive_snapshots: t.Set[str], adapter: EngineAdapter, deployability_index: DeployabilityIndex, + grants_only: bool = False, + create_only: bool = False, ) -> None: if not snapshot.is_model or snapshot.is_symbolic: return @@ -1179,6 +1191,22 @@ def _migrate_snapshot( update_execution(target=target_table_name, existed=target_data_object is not None) evaluation_strategy = _evaluation_strategy(snapshot, adapter) + if target_data_object is not None: + if grants_only: + with ( + adapter.transaction(), + adapter.session(snapshot.model.render_session_properties(**render_kwargs)), + ): + evaluation_strategy._apply_grants( + snapshot.model, + target_table_name, + GrantsTargetLayer.PHYSICAL, + is_snapshot_deployable=True, + ) + return + if create_only: + return + evaluation_strategy.run_pre_statements( snapshot=snapshot, render_kwargs={**render_kwargs, "inside_transaction": False} ) diff --git a/tests/core/integration/test_forward_only.py b/tests/core/integration/test_forward_only.py index 2dddf18efd..2d9068e001 100644 --- a/tests/core/integration/test_forward_only.py +++ b/tests/core/integration/test_forward_only.py @@ -1495,3 +1495,255 @@ def test_new_forward_only_model_same_dev_environment(init_and_plan_context: t.Ca df = context.fetchdf("SELECT * FROM memory.sushi__dev.new_model").replace({np.nan: None}) assert df.to_dict() == {"ds": {0: "2023-01-07"}, "b": {0: 1}} + + +def _init_mv_context(tmp_path): + from sqlmesh.core.config import Config, DuckDBConnectionConfig, GatewayConfig + from tests.utils.test_filesystem import create_temp_file + + models_dir = tmp_path / "models" + create_temp_file( + tmp_path, + models_dir / "src.sql", + """ + MODEL ( + name db.src, + kind FULL, + ); + SELECT 1 AS a, '2023-01-01' AS ds; + """, + ) + create_temp_file( + tmp_path, + models_dir / "mv.sql", + """ + MODEL ( + name db.mv, + kind VIEW (materialized true), + ); + SELECT a, ds FROM db.src; + """, + ) + config = Config( + gateways={"": GatewayConfig(connection=DuckDBConnectionConfig())}, + default_gateway="", + ) + return Context(paths=tmp_path, config=config) + + +def test_materialized_view_metadata_only_no_recreate(tmp_path, mocker): + from sqlmesh.core.engine_adapter.duckdb import DuckDBEngineAdapter + from tests.utils.test_filesystem import create_temp_file + + context = _init_mv_context(tmp_path) + create_view_spy = mocker.spy(DuckDBEngineAdapter, "create_view") + drop_view_spy = mocker.spy(DuckDBEngineAdapter, "drop_view") + + # Initial prod deploy builds the physical MV once + context.plan("prod", auto_apply=True, no_prompts=True, skip_tests=True) + mv_creates = [c for c in create_view_spy.call_args_list if c.kwargs.get("materialized")] + assert len(mv_creates) == 1 + assert context.engine_adapter.fetchall("SELECT a FROM db.mv") == [(1,)] + + models_dir = tmp_path / "models" + + # 1. Metadata-only change in prod (owner + tags + SQL comment) -> zero physical MV recreate/drop + create_view_spy.reset_mock() + drop_view_spy.reset_mock() + create_temp_file( + tmp_path, + models_dir / "mv.sql", + """ + MODEL ( + name db.mv, + kind VIEW (materialized true), + owner alice, + tags ['analytics'], + ); + SELECT a, ds FROM db.src -- trailing doc comment + """, + ) + context.load() + context.plan("prod", auto_apply=True, no_prompts=True, skip_tests=True) + assert [c for c in create_view_spy.call_args_list if c.kwargs.get("materialized")] == [] + assert drop_view_spy.call_count == 0 + assert context.engine_adapter.fetchall("SELECT a FROM db.mv") == [(1,)] + + # 2. Dev -> prod metadata-only change -> zero physical MV recreate/drop on prod deploy + create_temp_file( + tmp_path, + models_dir / "mv.sql", + """ + MODEL ( + name db.mv, + kind VIEW (materialized true), + owner bob, + tags ['analytics', 'core'], + ); + SELECT a, ds FROM db.src -- updated doc comment + """, + ) + context.load() + context.plan("dev", auto_apply=True, no_prompts=True, skip_tests=True) + + create_view_spy.reset_mock() + drop_view_spy.reset_mock() + context.plan("prod", auto_apply=True, no_prompts=True, skip_tests=True) + assert [c for c in create_view_spy.call_args_list if c.kwargs.get("materialized")] == [] + assert drop_view_spy.call_count == 0 + assert context.engine_adapter.fetchall("SELECT a FROM db.mv") == [(1,)] + + # 3. Rollback in prod to previous metadata-only snapshot -> zero physical MV recreate/drop + create_view_spy.reset_mock() + drop_view_spy.reset_mock() + create_temp_file( + tmp_path, + models_dir / "mv.sql", + """ + MODEL ( + name db.mv, + kind VIEW (materialized true), + owner alice, + tags ['analytics'], + ); + SELECT a, ds FROM db.src -- trailing doc comment + """, + ) + context.load() + context.plan("prod", auto_apply=True, no_prompts=True, skip_tests=True) + assert [c for c in create_view_spy.call_args_list if c.kwargs.get("materialized")] == [] + assert drop_view_spy.call_count == 0 + + # 4. Physical grants sync (add, update, revoke-all) -> sync_grants_config without MV recreation + mocker.patch.object(DuckDBEngineAdapter, "SUPPORTS_GRANTS", True) + sync_grants_mock = mocker.patch.object(DuckDBEngineAdapter, "sync_grants_config") + for grants_sql, expected_grants in [ + ("grants ('select' = ['analyst'])", {"select": ["analyst"]}), + ("grants ('select' = ['analyst', 'viewer'])", {"select": ["analyst", "viewer"]}), + ("grants ()", {}), + ]: + create_view_spy.reset_mock() + drop_view_spy.reset_mock() + sync_grants_mock.reset_mock() + create_temp_file( + tmp_path, + models_dir / "mv.sql", + f""" + MODEL ( + name db.mv, + kind VIEW (materialized true), + owner alice, + grants_target_layer physical, + {grants_sql}, + ); + SELECT a, ds FROM db.src -- trailing doc comment + """, + ) + context.load() + context.plan("prod", auto_apply=True, no_prompts=True, skip_tests=True) + assert [c for c in create_view_spy.call_args_list if c.kwargs.get("materialized")] == [] + assert drop_view_spy.call_count == 0 + assert sync_grants_mock.call_count == 1 + assert sync_grants_mock.call_args[0][1] == expected_grants + + # 5. Stacked dev forward-only SQL change + metadata-only change -> prod MUST migrate MV + create_temp_file( + tmp_path, + models_dir / "mv.sql", + """ + MODEL ( + name db.mv, + kind VIEW (materialized true), + owner alice, + ); + SELECT a + 10 AS a, ds FROM db.src + """, + ) + context.load() + context.plan("dev", forward_only=True, auto_apply=True, no_prompts=True, skip_tests=True) + + create_temp_file( + tmp_path, + models_dir / "mv.sql", + """ + MODEL ( + name db.mv, + kind VIEW (materialized true), + owner charlie, + ); + SELECT a + 10 AS a, ds FROM db.src + """, + ) + context.load() + context.plan("dev", auto_apply=True, no_prompts=True, skip_tests=True) + + create_view_spy.reset_mock() + context.plan("prod", auto_apply=True, no_prompts=True, skip_tests=True) + mv_creates = [c for c in create_view_spy.call_args_list if c.kwargs.get("materialized")] + assert len(mv_creates) == 1 + assert context.engine_adapter.fetchall("SELECT a FROM db.mv") == [(11,)] + + +def test_materialized_view_upstream_breaking_with_downstream_forward_only_created_once( + tmp_path, mocker +): + from sqlmesh.core.engine_adapter.duckdb import DuckDBEngineAdapter + from tests.utils.test_filesystem import create_temp_file + + context = _init_mv_context(tmp_path) + models_dir = tmp_path / "models" + create_temp_file( + tmp_path, + models_dir / "downstream.sql", + """ + MODEL ( + name db.downstream, + kind INCREMENTAL_BY_TIME_RANGE ( + time_column ds, + forward_only true, + ), + start '2023-01-01', + ); + SELECT a, ds FROM db.mv; + """, + ) + context.load() + context.plan("prod", auto_apply=True, no_prompts=True, skip_tests=True) + + create_view_spy = mocker.spy(DuckDBEngineAdapter, "create_view") + # Breaking change on upstream MV + forward_only downstream table + create_temp_file( + tmp_path, + models_dir / "mv.sql", + """ + MODEL ( + name db.mv, + kind VIEW (materialized true), + ); + SELECT a * 2 AS a, 99 AS b, ds FROM db.src; + """, + ) + create_temp_file( + tmp_path, + models_dir / "downstream.sql", + """ + MODEL ( + name db.downstream, + kind INCREMENTAL_BY_TIME_RANGE ( + time_column ds, + forward_only true, + ), + start '2023-01-01', + ); + SELECT a, b, ds FROM db.mv; + """, + ) + context.load() + context.plan("prod", auto_apply=True, no_prompts=True, skip_tests=True) + + mv_creates = [c for c in create_view_spy.call_args_list if c.kwargs.get("materialized")] + # Upstream MV must be created once (during BackfillStage), NOT recreated during MigrateSchemasStage + assert len(mv_creates) == 1 + assert context.engine_adapter.fetchall("SELECT a, b FROM db.mv") == [(2, 99)] + # Downstream forward-only table had column `b` added without re-backfilling historical intervals + assert context.engine_adapter.fetchall("SELECT a, b FROM db.downstream") == [(1, None)] diff --git a/tests/core/test_plan_stages.py b/tests/core/test_plan_stages.py index 5bfa3e2fc9..41c9ff98d8 100644 --- a/tests/core/test_plan_stages.py +++ b/tests/core/test_plan_stages.py @@ -2267,3 +2267,694 @@ def test_adjust_intervals_should_force_rebuild(make_snapshot, mocker: MockerFixt (snapshot, intervals) = next(iter(backfill_stages[0].snapshot_to_intervals.items())) assert not snapshot.intervals assert intervals == [(to_timestamp("2023-01-01"), to_timestamp("2023-01-02"))] + + +def _build_prod_plan_for_mv( + snapshots: t.List[Snapshot], + new_snapshots: t.List[Snapshot], + existing_environment: t.Optional[Environment], + stored_snapshots: t.Dict[SnapshotId, Snapshot], + mocker: MockerFixture, +) -> t.List[t.Any]: + state_reader = mocker.Mock(spec=StateReader) + state_reader.get_snapshots.side_effect = lambda ids: { + s_id: stored_snapshots[s_id] + for s_id in (x.snapshot_id for x in ids) + if s_id in stored_snapshots + } + state_reader.get_environment.return_value = existing_environment + + environment = Environment( + name="prod", + snapshots=[s.table_info for s in snapshots], + start_at="2023-01-01", + end_at="2023-01-02", + plan_id="test_plan", + previous_plan_id=existing_environment.plan_id if existing_environment else None, + promoted_snapshot_ids=None, + ) + plan = EvaluatablePlan( + start="2023-01-01", + end="2023-01-02", + new_snapshots=new_snapshots, + environment=environment, + no_gaps=False, + skip_backfill=False, + empty_backfill=False, + restatements={}, + restate_all_snapshots=False, + is_dev=False, + allow_destructive_models=set(), + allow_additive_models=set(), + forward_only=False, + end_bounded=False, + ensure_finalized_snapshots=False, + ignore_cron=False, + directly_modified_snapshots=[], + indirectly_modified_snapshots={}, + metadata_updated_snapshots=[s.snapshot_id for s in new_snapshots if s.is_metadata], + removed_snapshots=[], + requires_backfill=False, + models_to_backfill=None, + execution_time="2023-01-02", + disabled_restatement_models=set(), + environment_statements=None, + user_provided_flags=None, + ) + return build_plan_stages(plan, state_reader, None) + + +@pytest.mark.parametrize( + "change_type", + ["tags", "owner", "sql_comment", "metadata_only_macro"], +) +def test_build_plan_stages_mv_metadata_only_skips_migrate( + make_snapshot, mocker: MockerFixture, change_type: str +) -> None: + from sqlmesh.core.dialect import parse as parse_sql + from sqlmesh.core.macros import macro + from sqlmesh.core.model import load_sql_based_model + + if change_type == "metadata_only_macro": + try: + macro.get_registry().pop("my_meta_macro", None) + + @macro(metadata_only=True) + def my_meta_macro(evaluator): # type: ignore + return "1" + + mv_v1 = make_snapshot( + load_sql_based_model( + parse_sql( + "MODEL (name db.mv, kind VIEW (materialized true)); " + "SELECT @my_meta_macro() AS a" + ), + macros=macro.get_registry(), + ) + ) + mv_v1.categorize_as(SnapshotChangeCategory.BREAKING) + mv_v1.unpaused_ts = to_timestamp("2023-01-02") + + macro.get_registry().pop("my_meta_macro", None) + + @macro(metadata_only=True) + def my_meta_macro(evaluator): # type: ignore + # Comment changed inside metadata_only macro body + return "1" + + mv_v2 = make_snapshot( + load_sql_based_model( + parse_sql( + "MODEL (name db.mv, kind VIEW (materialized true)); " + "SELECT @my_meta_macro() AS a" + ), + macros=macro.get_registry(), + ) + ) + finally: + macro.get_registry().pop("my_meta_macro", None) + else: + base_sql = "MODEL (name db.mv, kind VIEW (materialized true)); SELECT 1 AS a" + mv_v1 = make_snapshot(load_sql_based_model(parse_sql(base_sql))) + mv_v1.categorize_as(SnapshotChangeCategory.BREAKING) + mv_v1.unpaused_ts = to_timestamp("2023-01-02") + + if change_type == "tags": + updated_sql = ( + "MODEL (name db.mv, kind VIEW (materialized true), tags ['analytics']); " + "SELECT 1 AS a" + ) + elif change_type == "owner": + updated_sql = ( + "MODEL (name db.mv, kind VIEW (materialized true), owner alice); SELECT 1 AS a" + ) + else: + updated_sql = ( + "MODEL (name db.mv, kind VIEW (materialized true)); " + "SELECT 1 AS a -- column doc comment" + ) + mv_v2 = make_snapshot(load_sql_based_model(parse_sql(updated_sql))) + + mv_v2.previous_versions = mv_v1.all_versions + mv_v2.categorize_as(SnapshotChangeCategory.METADATA) + assert mv_v2.requires_schema_migration_in_prod + + existing_prod = Environment( + name="prod", + snapshots=[mv_v1.table_info], + start_at="2023-01-01", + end_at="2023-01-02", + plan_id="prev_plan", + finalized_ts=to_timestamp("2023-01-02"), + ) + + stages = _build_prod_plan_for_mv( + snapshots=[mv_v2], + new_snapshots=[mv_v2], + existing_environment=existing_prod, + stored_snapshots={mv_v1.snapshot_id: mv_v1}, + mocker=mocker, + ) + + assert not any(isinstance(s, MigrateSchemasStage) for s in stages) + + +def test_build_plan_stages_mv_unfinalized_failed_forward_only_retry_migrates( + make_snapshot, mocker: MockerFixture +) -> None: + mv_v1 = make_snapshot( + SqlModel( + name="db.mv", + query=parse_one("SELECT 1 AS a"), + kind=dict(name=ModelKindName.VIEW, materialized=True), + ) + ) + mv_v1.categorize_as(SnapshotChangeCategory.BREAKING) + mv_v1.unpaused_ts = to_timestamp("2023-01-02") + + mv_v2 = make_snapshot( + SqlModel( + name="db.mv", + query=parse_one("SELECT 2 AS a"), + kind=dict(name=ModelKindName.VIEW, materialized=True), + ) + ) + mv_v2.previous_versions = mv_v1.all_versions + mv_v2.categorize_as(SnapshotChangeCategory.NON_BREAKING, forward_only=True) + + # Previous prod plan failed after EnvironmentRecordUpdateStage (finalized_ts is None) + unfinalized_prod = Environment( + name="prod", + snapshots=[mv_v2.table_info], + previous_finalized_snapshots=[mv_v1.table_info], + start_at="2023-01-01", + end_at="2023-01-02", + plan_id="failed_plan", + finalized_ts=None, + ) + + stages = _build_prod_plan_for_mv( + snapshots=[mv_v2], + new_snapshots=[], + existing_environment=unfinalized_prod, + stored_snapshots={mv_v1.snapshot_id: mv_v1, mv_v2.snapshot_id: mv_v2}, + mocker=mocker, + ) + + migrate_stages = [s for s in stages if isinstance(s, MigrateSchemasStage)] + assert len(migrate_stages) == 1 + assert [s.snapshot_id for s in migrate_stages[0].snapshots] == [mv_v2.snapshot_id] + assert migrate_stages[0].grants_only_snapshot_ids == set() + assert migrate_stages[0].create_only_snapshot_ids == set() + + +def test_build_plan_stages_mv_unfinalized_failed_metadata_only_retry_skips_migrate( + make_snapshot, mocker: MockerFixture +) -> None: + mv_v1 = make_snapshot( + SqlModel( + name="db.mv", + query=parse_one("SELECT 1 AS a"), + kind=dict(name=ModelKindName.VIEW, materialized=True), + ) + ) + mv_v1.categorize_as(SnapshotChangeCategory.BREAKING) + mv_v1.unpaused_ts = to_timestamp("2023-01-02") + + mv_v2 = make_snapshot(mv_v1.model.copy(update={"owner": "alice"})) + mv_v2.previous_versions = mv_v1.all_versions + mv_v2.categorize_as(SnapshotChangeCategory.METADATA) + + unfinalized_prod = Environment( + name="prod", + snapshots=[mv_v2.table_info], + previous_finalized_snapshots=[mv_v1.table_info], + start_at="2023-01-01", + end_at="2023-01-02", + plan_id="failed_plan", + finalized_ts=None, + ) + + stages = _build_prod_plan_for_mv( + snapshots=[mv_v2], + new_snapshots=[], + existing_environment=unfinalized_prod, + stored_snapshots={mv_v1.snapshot_id: mv_v1, mv_v2.snapshot_id: mv_v2}, + mocker=mocker, + ) + + assert not any(isinstance(s, MigrateSchemasStage) for s in stages) + + +def test_build_plan_stages_mv_never_finalized_or_expired_migrates( + make_snapshot, mocker: MockerFixture +) -> None: + mv_v1 = make_snapshot( + SqlModel( + name="db.mv", + query=parse_one("SELECT 1 AS a"), + kind=dict(name=ModelKindName.VIEW, materialized=True), + ) + ) + mv_v1.categorize_as(SnapshotChangeCategory.BREAKING) + + mv_v2 = make_snapshot(mv_v1.model.copy(update={"owner": "alice"})) + mv_v2.previous_versions = mv_v1.all_versions + mv_v2.categorize_as(SnapshotChangeCategory.METADATA) + + # Case 1: unfinalized with previous_finalized_snapshots=None (never finalized) + never_finalized = Environment( + name="prod", + snapshots=[mv_v1.table_info], + previous_finalized_snapshots=None, + start_at="2023-01-01", + end_at="2023-01-02", + plan_id="failed_initial", + finalized_ts=None, + ) + stages = _build_prod_plan_for_mv( + snapshots=[mv_v2], + new_snapshots=[mv_v2], + existing_environment=never_finalized, + stored_snapshots={mv_v1.snapshot_id: mv_v1}, + mocker=mocker, + ) + migrate_stages = [s for s in stages if isinstance(s, MigrateSchemasStage)] + assert len(migrate_stages) == 1 + assert [s.snapshot_id for s in migrate_stages[0].snapshots] == [mv_v2.snapshot_id] + + # Case 2: expired environment + expired_env = Environment( + name="prod", + snapshots=[mv_v1.table_info], + start_at="2023-01-01", + end_at="2023-01-02", + plan_id="expired_plan", + finalized_ts=to_timestamp("2023-01-02"), + expiration_ts=1, + ) + stages_expired = _build_prod_plan_for_mv( + snapshots=[mv_v2], + new_snapshots=[mv_v2], + existing_environment=expired_env, + stored_snapshots={mv_v1.snapshot_id: mv_v1}, + mocker=mocker, + ) + migrate_stages_expired = [s for s in stages_expired if isinstance(s, MigrateSchemasStage)] + assert len(migrate_stages_expired) == 1 + assert [s.snapshot_id for s in migrate_stages_expired[0].snapshots] == [mv_v2.snapshot_id] + + +def test_build_plan_stages_mv_stacked_dev_forward_only_plus_metadata_migrates( + make_snapshot, mocker: MockerFixture +) -> None: + mv_v1 = make_snapshot( + SqlModel( + name="db.mv", + query=parse_one("SELECT 1 AS a"), + kind=dict(name=ModelKindName.VIEW, materialized=True), + ) + ) + mv_v1.categorize_as(SnapshotChangeCategory.BREAKING) + mv_v1.unpaused_ts = to_timestamp("2023-01-02") + + # Dev step 1: forward-only SQL change (never deployed to prod) + mv_v2 = make_snapshot( + SqlModel( + name="db.mv", + query=parse_one("SELECT 2 AS a"), + kind=dict(name=ModelKindName.VIEW, materialized=True), + ) + ) + mv_v2.previous_versions = mv_v1.all_versions + mv_v2.categorize_as(SnapshotChangeCategory.NON_BREAKING, forward_only=True) + + # Dev step 2: metadata-only change stacked on top of v2 + mv_v3 = make_snapshot(mv_v2.model.copy(update={"owner": "bob"})) + mv_v3.previous_versions = mv_v2.all_versions + mv_v3.categorize_as(SnapshotChangeCategory.METADATA) + + existing_prod = Environment( + name="prod", + snapshots=[mv_v1.table_info], + start_at="2023-01-01", + end_at="2023-01-02", + plan_id="prod_v1", + finalized_ts=to_timestamp("2023-01-02"), + ) + + stages = _build_prod_plan_for_mv( + snapshots=[mv_v3], + new_snapshots=[], + existing_environment=existing_prod, + stored_snapshots={mv_v1.snapshot_id: mv_v1, mv_v3.snapshot_id: mv_v3}, + mocker=mocker, + ) + + migrate_stages = [s for s in stages if isinstance(s, MigrateSchemasStage)] + assert len(migrate_stages) == 1 + assert [s.snapshot_id for s in migrate_stages[0].snapshots] == [mv_v3.snapshot_id] + assert migrate_stages[0].grants_only_snapshot_ids == set() + assert migrate_stages[0].create_only_snapshot_ids == set() + + +@pytest.mark.parametrize( + "mode", + ["physical_version", "vde_dev_only"], +) +def test_build_plan_stages_mv_physical_version_and_vde_dev_only( + make_snapshot, mocker: MockerFixture, mode: str +) -> None: + kwargs: t.Dict[str, t.Any] = ( + {"physical_version": "v1"} + if mode == "physical_version" + else {"virtual_environment_mode": VirtualEnvironmentMode.DEV_ONLY} + ) + mv_v1 = make_snapshot( + SqlModel( + name="db.mv", + query=parse_one("SELECT 1 AS a"), + kind=dict(name=ModelKindName.VIEW, materialized=True), + **kwargs, + ) + ) + mv_v1.categorize_as(SnapshotChangeCategory.BREAKING) + mv_v1.unpaused_ts = to_timestamp("2023-01-02") + + existing_prod = Environment( + name="prod", + snapshots=[mv_v1.table_info], + start_at="2023-01-01", + end_at="2023-01-02", + plan_id="prod_v1", + finalized_ts=to_timestamp("2023-01-02"), + ) + + # Metadata-only change: must skip MigrateSchemasStage + mv_meta = make_snapshot(mv_v1.model.copy(update={"owner": "alice"})) + mv_meta.previous_versions = mv_v1.all_versions + mv_meta.categorize_as(SnapshotChangeCategory.METADATA) + + stages_meta = _build_prod_plan_for_mv( + snapshots=[mv_meta], + new_snapshots=[mv_meta], + existing_environment=existing_prod, + stored_snapshots={mv_v1.snapshot_id: mv_v1}, + mocker=mocker, + ) + assert not any(isinstance(s, MigrateSchemasStage) for s in stages_meta) + + # Data change (or physical_version bump): must still emit MigrateSchemasStage + mv_changed = make_snapshot( + SqlModel( + name="db.mv", + query=parse_one("SELECT 1 AS a" if mode == "physical_version" else "SELECT 2 AS a"), + kind=dict(name=ModelKindName.VIEW, materialized=True), + **( + {"physical_version": "v2"} + if mode == "physical_version" + else {"virtual_environment_mode": VirtualEnvironmentMode.DEV_ONLY} + ), + ) + ) + mv_changed.previous_versions = mv_v1.all_versions + mv_changed.categorize_as(SnapshotChangeCategory.BREAKING) + + stages_changed = _build_prod_plan_for_mv( + snapshots=[mv_changed], + new_snapshots=[mv_changed], + existing_environment=existing_prod, + stored_snapshots={mv_v1.snapshot_id: mv_v1}, + mocker=mocker, + ) + migrate_stages = [s for s in stages_changed if isinstance(s, MigrateSchemasStage)] + assert len(migrate_stages) == 1 + assert [s.snapshot_id for s in migrate_stages[0].snapshots] == [mv_changed.snapshot_id] + assert migrate_stages[0].grants_only_snapshot_ids == set() + + +@pytest.mark.parametrize( + "old_grants,old_layer,new_grants,new_layer,vde_mode,expect_grants_only", + [ + # Add physical grants + (None, "physical", {"select": ["u1"]}, "physical", VirtualEnvironmentMode.FULL, True), + # Add grants targeting ALL layers + (None, "all", {"select": ["u1"]}, "all", VirtualEnvironmentMode.FULL, True), + # Update physical grants + ( + {"select": ["u1"]}, + "physical", + {"select": ["u2"]}, + "physical", + VirtualEnvironmentMode.FULL, + True, + ), + # Revoke all physical grants ({} != None) + ({"select": ["u1"]}, "physical", {}, "physical", VirtualEnvironmentMode.FULL, True), + # Switch grants_target_layer from virtual -> physical + ( + {"select": ["u1"]}, + "virtual", + {"select": ["u1"]}, + "physical", + VirtualEnvironmentMode.FULL, + True, + ), + # VDE=DEV_ONLY with virtual layer still targets physical in prod + ( + None, + "virtual", + {"select": ["u1"]}, + "virtual", + VirtualEnvironmentMode.DEV_ONLY, + True, + ), + # Unchanged physical grants (only owner changed) -> skip MigrateSchemasStage + ( + {"select": ["u1"]}, + "physical", + {"select": ["u1"]}, + "physical", + VirtualEnvironmentMode.FULL, + False, + ), + # Virtual-only grants change under FULL VDE -> handled in virtual layer only + ( + None, + "virtual", + {"select": ["u1"]}, + "virtual", + VirtualEnvironmentMode.FULL, + False, + ), + ], +) +def test_build_plan_stages_mv_grants_only_sync( + make_snapshot, + mocker: MockerFixture, + old_grants: t.Optional[t.Dict[str, t.List[str]]], + old_layer: str, + new_grants: t.Optional[t.Dict[str, t.List[str]]], + new_layer: str, + vde_mode: VirtualEnvironmentMode, + expect_grants_only: bool, +) -> None: + from sqlmesh.core.model.meta import GrantsTargetLayer + + v1_kwargs: t.Dict[str, t.Any] = { + "grants_target_layer": GrantsTargetLayer(old_layer), + "virtual_environment_mode": vde_mode, + } + if old_grants is not None: + v1_kwargs["grants"] = old_grants + + mv_v1 = make_snapshot( + SqlModel( + name="db.mv", + query=parse_one("SELECT 1 AS a"), + kind=dict(name=ModelKindName.VIEW, materialized=True), + **v1_kwargs, + ) + ) + mv_v1.categorize_as(SnapshotChangeCategory.BREAKING) + mv_v1.unpaused_ts = to_timestamp("2023-01-02") + + v2_kwargs: t.Dict[str, t.Any] = { + "grants_target_layer": GrantsTargetLayer(new_layer), + "virtual_environment_mode": vde_mode, + "owner": "alice", + } + if new_grants is not None: + v2_kwargs["grants"] = new_grants + + mv_v2 = make_snapshot( + SqlModel( + name="db.mv", + query=parse_one("SELECT 1 AS a"), + kind=dict(name=ModelKindName.VIEW, materialized=True), + **v2_kwargs, + ) + ) + mv_v2.previous_versions = mv_v1.all_versions + mv_v2.categorize_as(SnapshotChangeCategory.METADATA) + + existing_prod = Environment( + name="prod", + snapshots=[mv_v1.table_info], + start_at="2023-01-01", + end_at="2023-01-02", + plan_id="prod_v1", + finalized_ts=to_timestamp("2023-01-02"), + ) + + stages = _build_prod_plan_for_mv( + snapshots=[mv_v2], + new_snapshots=[mv_v2], + existing_environment=existing_prod, + stored_snapshots={mv_v1.snapshot_id: mv_v1}, + mocker=mocker, + ) + + migrate_stages = [s for s in stages if isinstance(s, MigrateSchemasStage)] + if expect_grants_only: + assert len(migrate_stages) == 1 + assert [s.snapshot_id for s in migrate_stages[0].snapshots] == [mv_v2.snapshot_id] + assert migrate_stages[0].grants_only_snapshot_ids == {mv_v2.snapshot_id} + assert migrate_stages[0].create_only_snapshot_ids == set() + else: + assert len(migrate_stages) == 0 + + +def test_build_plan_stages_mv_upstream_subdag_create_only( + make_snapshot, mocker: MockerFixture +) -> None: + mv_upstream = make_snapshot( + SqlModel( + name="db.mv_upstream", + query=parse_one("SELECT 1 AS a, '2023-01-01' AS ds"), + kind=dict(name=ModelKindName.VIEW, materialized=True), + ) + ) + mv_upstream.categorize_as(SnapshotChangeCategory.BREAKING) + + # Sibling downstream MV that should NOT be cascaded into MigrateSchemasStage + mv_sibling = make_snapshot( + SqlModel( + name="db.mv_sibling", + query=parse_one("SELECT a FROM db.mv_upstream"), + kind=dict(name=ModelKindName.VIEW, materialized=True), + ), + nodes={mv_upstream.name: mv_upstream.model}, + ) + mv_sibling.categorize_as(SnapshotChangeCategory.BREAKING) + + downstream_fo = make_snapshot( + SqlModel( + name="db.downstream_fo", + query=parse_one("SELECT a, ds FROM db.mv_upstream"), + kind=dict( + name=ModelKindName.INCREMENTAL_BY_TIME_RANGE, time_column="ds", forward_only=True + ), + ), + nodes={mv_upstream.name: mv_upstream.model}, + ) + downstream_fo.categorize_as(SnapshotChangeCategory.BREAKING) + + stages = _build_prod_plan_for_mv( + snapshots=[mv_upstream, mv_sibling, downstream_fo], + new_snapshots=[mv_upstream, mv_sibling, downstream_fo], + existing_environment=None, + stored_snapshots={}, + mocker=mocker, + ) + + migrate_stage = next(s for s in stages if isinstance(s, MigrateSchemasStage)) + assert {s.snapshot_id for s in migrate_stage.snapshots} == { + mv_upstream.snapshot_id, + downstream_fo.snapshot_id, + } + assert migrate_stage.create_only_snapshot_ids == {mv_upstream.snapshot_id} + assert migrate_stage.grants_only_snapshot_ids == set() + + +def test_plan_explainer_migrate_schemas_stage_grants_and_create_only( + make_snapshot, +) -> None: + from rich.console import Console as RichConsole + from sqlmesh.core.environment import EnvironmentNamingInfo + from sqlmesh.core.plan.explainer import RichExplainerConsole + + mv_grants = make_snapshot( + SqlModel( + name="db.mv_grants", + query=parse_one("SELECT 1 AS a"), + kind=dict(name=ModelKindName.VIEW, materialized=True), + ) + ) + mv_grants.categorize_as(SnapshotChangeCategory.BREAKING) + + mv_create_only = make_snapshot( + SqlModel( + name="db.mv_create_only", + query=parse_one("SELECT 1 AS a"), + kind=dict(name=ModelKindName.VIEW, materialized=True), + ) + ) + mv_create_only.categorize_as(SnapshotChangeCategory.BREAKING) + + tbl_migrated = make_snapshot( + SqlModel( + name="db.tbl_migrated", + query=parse_one("SELECT 1 AS a, '2023-01-01' AS ds"), + kind=dict( + name=ModelKindName.INCREMENTAL_BY_TIME_RANGE, time_column="ds", forward_only=True + ), + ) + ) + tbl_migrated.categorize_as(SnapshotChangeCategory.BREAKING) + + explainer = RichExplainerConsole( + environment_naming_info=EnvironmentNamingInfo(name="prod"), + dialect="duckdb", + default_catalog=None, + console=RichConsole(record=True), + ) + + # 1. Grants-only stage + grants_stage = MigrateSchemasStage( + snapshots=[mv_grants], + all_snapshots={mv_grants.snapshot_id: mv_grants}, + deployability_index=DeployabilityIndex.all_deployable(), + grants_only_snapshot_ids={mv_grants.snapshot_id}, + ) + grants_tree = explainer.visit_migrate_schemas_stage(grants_stage) + assert grants_tree is not None + assert "Sync grants" in str(grants_tree.label) + assert len(grants_tree.children) == 1 + assert "(sync grants)" in str(grants_tree.children[0].label) + + # 2. Mixed stage: regular migration + grants-only + create-only (create-only hidden) + mixed_stage = MigrateSchemasStage( + snapshots=[mv_create_only, mv_grants, tbl_migrated], + all_snapshots={s.snapshot_id: s for s in (mv_create_only, mv_grants, tbl_migrated)}, + deployability_index=DeployabilityIndex.all_deployable(), + grants_only_snapshot_ids={mv_grants.snapshot_id}, + create_only_snapshot_ids={mv_create_only.snapshot_id}, + ) + mixed_tree = explainer.visit_migrate_schemas_stage(mixed_stage) + assert mixed_tree is not None + assert "Update schemas" in str(mixed_tree.label) + child_labels = [str(c.label) for c in mixed_tree.children] + assert len(child_labels) == 2 + assert any("mv_grants" in lbl and "(sync grants)" in lbl for lbl in child_labels) + assert any("tbl_migrated" in lbl and "(sync grants)" not in lbl for lbl in child_labels) + assert not any("mv_create_only" in lbl for lbl in child_labels) + + # 3. Create-only stage returns None + create_only_stage = MigrateSchemasStage( + snapshots=[mv_create_only], + all_snapshots={mv_create_only.snapshot_id: mv_create_only}, + deployability_index=DeployabilityIndex.all_deployable(), + create_only_snapshot_ids={mv_create_only.snapshot_id}, + ) + assert explainer.visit_migrate_schemas_stage(create_only_stage) is None diff --git a/tests/core/test_snapshot_evaluator.py b/tests/core/test_snapshot_evaluator.py index 0955af331d..b77ff4b8fc 100644 --- a/tests/core/test_snapshot_evaluator.py +++ b/tests/core/test_snapshot_evaluator.py @@ -6113,3 +6113,134 @@ def observer(phase, facts, error): consumer.reset(token) action = "schema_migration" if operation == "migrate" else operation assert events == [("start", action, None), ("finish", action, None)] + + +@pytest.mark.parametrize( + "grants_config", + [ + {"select": ["user1"]}, + {}, + ], +) +def test_migrate_grants_only_snapshot_ids( + mocker: MockerFixture, adapter_mock, make_snapshot, grants_config +): + from sqlmesh.core.model.meta import GrantsTargetLayer + + adapter_mock.SUPPORTS_GRANTS = True + sync_grants_mock = mocker.patch.object(adapter_mock, "sync_grants_config") + + model = SqlModel( + name="db.mv", + query=parse_one("SELECT 1 AS a"), + kind=ViewKind(materialized=True), + grants=grants_config, + grants_target_layer=GrantsTargetLayer.PHYSICAL, + pre_statements=[parse_one("SELECT 'pre'")], + post_statements=[parse_one("SELECT 'post'")], + ) + snapshot = make_snapshot(model, version="1") + snapshot.categorize_as(SnapshotChangeCategory.METADATA) + + evaluator = SnapshotEvaluator(adapter_mock) + mocker.patch.object( + evaluator, + "_get_physical_data_objects", + return_value={ + snapshot.snapshot_id: DataObject( + schema="sqlmesh__db", + name="db__mv__1", + type=DataObjectType.MATERIALIZED_VIEW, + ) + }, + ) + + evaluator.migrate( + [snapshot], + {snapshot.snapshot_id: snapshot}, + grants_only_snapshot_ids={snapshot.snapshot_id}, + ) + + sync_grants_mock.assert_called_once_with( + exp.to_table(snapshot.table_name(), dialect=adapter_mock.dialect), + grants_config, + DataObjectType.MATERIALIZED_VIEW, + ) + adapter_mock.create_view.assert_not_called() + adapter_mock.drop_view.assert_not_called() + adapter_mock.drop_table.assert_not_called() + adapter_mock.drop_data_object_on_type_mismatch.assert_not_called() + adapter_mock.execute.assert_not_called() + + +def test_migrate_create_only_snapshot_ids_skips_when_exists_creates_when_missing( + mocker: MockerFixture, adapter_mock, make_snapshot +): + mv_model = SqlModel( + name="db.mv", + query=parse_one("SELECT 1 AS a"), + kind=ViewKind(materialized=True), + pre_statements=[parse_one("SELECT 'pre'")], + post_statements=[parse_one("SELECT 'post'")], + ) + mv_snapshot = make_snapshot(mv_model, version="1") + mv_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + + evaluator = SnapshotEvaluator(adapter_mock) + + # Case 1: Physical MV already exists -> complete no-op + mocker.patch.object( + evaluator, + "_get_physical_data_objects", + return_value={ + mv_snapshot.snapshot_id: DataObject( + schema="sqlmesh__db", + name="db__mv__1", + type=DataObjectType.MATERIALIZED_VIEW, + ) + }, + ) + evaluator.migrate( + [mv_snapshot], + {mv_snapshot.snapshot_id: mv_snapshot}, + create_only_snapshot_ids={mv_snapshot.snapshot_id}, + ) + adapter_mock.create_view.assert_not_called() + adapter_mock.drop_view.assert_not_called() + adapter_mock.drop_data_object_on_type_mismatch.assert_not_called() + adapter_mock.execute.assert_not_called() + + # Case 2: Physical MV is missing while downstream exists -> falls through to _execute_create + downstream = make_snapshot( + SqlModel( + name="db.downstream", + query=parse_one("SELECT a FROM db.mv"), + kind=FullKind(), + ), + nodes={mv_snapshot.name: mv_snapshot.model}, + version="1", + ) + downstream.categorize_as(SnapshotChangeCategory.BREAKING) + mocker.patch.object( + evaluator, + "_get_physical_data_objects", + return_value={ + downstream.snapshot_id: DataObject( + schema="sqlmesh__db", + name="db__downstream__1", + type=DataObjectType.TABLE, + ) + }, + ) + execute_create_spy = mocker.spy(evaluator, "_execute_create") + mocker.patch.object(evaluator, "_migrate_target_table") + adapter_mock.drop_data_object_on_type_mismatch.return_value = False + + evaluator.migrate( + [mv_snapshot, downstream], + {mv_snapshot.snapshot_id: mv_snapshot, downstream.snapshot_id: downstream}, + create_only_snapshot_ids={mv_snapshot.snapshot_id}, + ) + + assert execute_create_spy.call_count == 1 + assert execute_create_spy.call_args.kwargs["snapshot"].snapshot_id == mv_snapshot.snapshot_id