diff --git a/sqlmesh/core/plan/stages.py b/sqlmesh/core/plan/stages.py index 3d034cf6a1..5e7ed1ca1c 100644 --- a/sqlmesh/core/plan/stages.py +++ b/sqlmesh/core/plan/stages.py @@ -263,7 +263,6 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]: if plan.is_dev: before_promote_snapshots = all_selected_for_backfill_snapshots after_promote_snapshots = set() - snapshots_with_schema_migration = [] else: before_promote_snapshots = { s.snapshot_id @@ -274,23 +273,48 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]: after_promote_snapshots = all_selected_for_backfill_snapshots - before_promote_snapshots deployability_index = DeployabilityIndex.all_deployable() + snapshots_to_intervals = self._missing_intervals( + plan, snapshots_by_name, deployability_index + ) + needs_backfill = ( + not plan.empty_backfill and not plan.skip_backfill and bool(snapshots_to_intervals) + ) + missing_intervals_before_promote: SnapshotToIntervals = {} + missing_intervals_after_promote: SnapshotToIntervals = {} + if needs_backfill: + for snapshot, intervals in snapshots_to_intervals.items(): + if snapshot.snapshot_id in before_promote_snapshots: + missing_intervals_before_promote[snapshot] = intervals + elif snapshot.snapshot_id in after_promote_snapshots: + missing_intervals_after_promote[snapshot] = intervals + + if plan.is_dev: + snapshots_with_schema_migration = [] + else: snapshot_ids_with_schema_migration = [ s.snapshot_id for s in snapshots.values() if s.requires_schema_migration_in_prod ] # 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)) - # Migrating a view replaces it, and engines like Postgres drop its dependent views with CASCADE, - # so those are migrated too to be recreated + # Migrating a view replaces it, and Postgres-family engines drop its dependent views with CASCADE, + # so those are migrated too to be recreated unless they will be created in a subsequent backfill + cascade_view_ids: t.Set[SnapshotId] = set() for s_id in dag: snapshot = snapshots[s_id] - if snapshot.is_view and any( - p_id in snapshot_ids_to_migrate - and snapshots[p_id].is_view - and snapshots[p_id].supports_schema_migration_in_prod - for p_id in snapshot.parents + if ( + snapshot.is_view + and snapshot not in missing_intervals_after_promote + and any( + (p_id in snapshot_ids_to_migrate or p_id in cascade_view_ids) + and snapshots[p_id].is_view + and snapshots[p_id].supports_schema_migration_in_prod + and snapshots[p_id].model.dialect in ("postgres", "risingwave", "redshift") + for p_id in snapshot.parents + ) ): - snapshot_ids_to_migrate.add(s_id) + cascade_view_ids.add(s_id) + snapshot_ids_to_migrate.update(cascade_view_ids) snapshots_with_schema_migration = [ snapshots[s_id] for s_id in dag @@ -298,21 +322,6 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]: and snapshots[s_id].supports_schema_migration_in_prod ] - snapshots_to_intervals = self._missing_intervals( - plan, snapshots_by_name, deployability_index - ) - needs_backfill = ( - not plan.empty_backfill and not plan.skip_backfill and bool(snapshots_to_intervals) - ) - missing_intervals_before_promote: SnapshotToIntervals = {} - missing_intervals_after_promote: SnapshotToIntervals = {} - if needs_backfill: - for snapshot, intervals in snapshots_to_intervals.items(): - if snapshot.snapshot_id in before_promote_snapshots: - missing_intervals_before_promote[snapshot] = intervals - elif snapshot.snapshot_id in after_promote_snapshots: - missing_intervals_after_promote[snapshot] = intervals - promoted_snapshots, demoted_snapshots, demoted_environment_naming_info = ( self._get_promoted_demoted_snapshots(plan, existing_environment) ) diff --git a/tests/core/test_plan_stages.py b/tests/core/test_plan_stages.py index 5bfa3e2fc9..21deb1796a 100644 --- a/tests/core/test_plan_stages.py +++ b/tests/core/test_plan_stages.py @@ -1693,7 +1693,12 @@ def test_build_plan_stages_migrates_views_downstream_of_migrated_view( snapshot_a: Snapshot, make_snapshot, mocker: MockerFixture, base_view_unpaused: bool ) -> None: base_view = make_snapshot( - SqlModel(name="base_view", query=parse_one("select * from a"), kind=ModelKindName.VIEW), + SqlModel( + name="base_view", + query=parse_one("select * from a"), + kind=ModelKindName.VIEW, + dialect="postgres", + ), nodes={'"a"': snapshot_a.model}, ) base_view.categorize_as(SnapshotChangeCategory.BREAKING) @@ -1701,7 +1706,10 @@ def test_build_plan_stages_migrates_views_downstream_of_migrated_view( base_view.unpaused_ts = 1 public_view = make_snapshot( SqlModel( - name="public_view", query=parse_one("select * from base_view"), kind=ModelKindName.VIEW + name="public_view", + query=parse_one("select * from base_view"), + kind=ModelKindName.VIEW, + dialect="postgres", ), nodes={'"a"': snapshot_a.model, '"base_view"': base_view.model}, ) @@ -1737,7 +1745,7 @@ def test_build_plan_stages_migrates_views_downstream_of_migrated_view( new_snapshots=snapshots, environment=environment, no_gaps=False, - skip_backfill=False, + skip_backfill=True, empty_backfill=False, restatements={}, restate_all_snapshots=False, @@ -1767,6 +1775,122 @@ def test_build_plan_stages_migrates_views_downstream_of_migrated_view( assert {s.snapshot_id for s in migrate_stage.snapshots} == {s.snapshot_id for s in expected} +@pytest.mark.parametrize("dialect", ["duckdb", "postgres", "risingwave"]) +@pytest.mark.parametrize("after_promote", [False, True]) +def test_build_plan_stages_skips_downstream_materialized_view_when_not_needed( + snapshot_a: Snapshot, + make_snapshot, + mocker: MockerFixture, + dialect: str, + after_promote: bool, +) -> None: + if after_promote: + upstream = make_snapshot( + SqlModel( + name="a", + query=parse_one("select 1, '2023-01-01'::date as ds"), + kind=dict( + name=ModelKindName.INCREMENTAL_BY_TIME_RANGE, + time_column="ds", + forward_only=True, + ), + dialect=dialect, + ), + ) + upstream.categorize_as(SnapshotChangeCategory.BREAKING) + else: + upstream = snapshot_a + + base_view = make_snapshot( + SqlModel( + name="base_view", + query=parse_one("select * from a"), + kind=ModelKindName.VIEW, + dialect=dialect, + ), + nodes={'"a"': upstream.model}, + ) + if after_promote: + base_view.categorize_as(SnapshotChangeCategory.INDIRECT_NON_BREAKING) + base_view.previous_versions = (base_view.data_version,) + else: + base_view.categorize_as(SnapshotChangeCategory.BREAKING) + + mv = make_snapshot( + SqlModel( + name="mv", + query=parse_one("select * from base_view"), + kind=dict(name=ModelKindName.VIEW, materialized=True), + dialect=dialect, + ), + nodes={'"a"': upstream.model, '"base_view"': base_view.model}, + ) + mv.categorize_as(SnapshotChangeCategory.BREAKING) + forward_only = make_snapshot( + SqlModel( + name="forward_only", + query=parse_one("select 1, ds from base_view"), + kind=dict( + name=ModelKindName.INCREMENTAL_BY_TIME_RANGE, time_column="ds", forward_only=True + ), + dialect=dialect, + ), + nodes={'"a"': upstream.model, '"base_view"': base_view.model}, + ) + forward_only.categorize_as(SnapshotChangeCategory.BREAKING) + snapshots = [upstream, base_view, mv, forward_only] + + state_reader = mocker.Mock(spec=StateReader) + state_reader.get_snapshots.return_value = {} + state_reader.get_environment.return_value = None + + environment = Environment( + 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=None, + promoted_snapshot_ids=[s.snapshot_id for s in snapshots], + ) + plan = EvaluatablePlan( + start="2023-01-01", + end="2023-01-02", + new_snapshots=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=[s.snapshot_id for s in snapshots], + indirectly_modified_snapshots={}, + metadata_updated_snapshots=[], + removed_snapshots=[], + requires_backfill=True, + models_to_backfill=None, + execution_time="2023-01-02", + disabled_restatement_models=set(), + environment_statements=None, + user_provided_flags=None, + ) + + stages = build_plan_stages(plan, state_reader, None) + + migrate_stage = next(s for s in stages if isinstance(s, MigrateSchemasStage)) + if dialect in ("postgres", "risingwave") and not after_promote: + expected = snapshots + else: + expected = [upstream, base_view, forward_only] + assert {s.snapshot_id for s in migrate_stage.snapshots} == {s.snapshot_id for s in expected} + + def test_build_plan_stages_virtual_environment_mode_filtering( make_snapshot, mocker: MockerFixture ) -> None: