1+ from __future__ import annotations
2+
13import typing as t
24
3- from dataclasses import dataclass
5+ from dataclasses import dataclass , field
46from sqlmesh .core import constants as c
57from sqlmesh .core .environment import EnvironmentStatements , EnvironmentNamingInfo , Environment
68from sqlmesh .core .plan .common import should_force_rebuild
1416 SnapshotId ,
1517 snapshots_to_dag ,
1618)
19+ from sqlmesh .utils .dag import DAG
1720from sqlmesh .utils .errors import PlanError
1821
1922
@@ -154,11 +157,17 @@ class MigrateSchemasStage:
154157 snapshots: Snapshots to migrate schemas for.
155158 all_snapshots: All snapshots in the plan by snapshot ID.
156159 deployability_index: Deployability index for this stage.
160+ grants_only_snapshot_ids: Snapshot IDs that only need physical grants synchronized
161+ without recreating or altering their physical objects.
162+ create_only_snapshot_ids: Snapshot IDs that should only be created if their physical
163+ object does not yet exist, without being migrated or recreated if it already exists.
157164 """
158165
159166 snapshots : t .List [Snapshot ]
160167 all_snapshots : t .Dict [SnapshotId , Snapshot ]
161168 deployability_index : DeployabilityIndex
169+ grants_only_snapshot_ids : t .Set [SnapshotId ] = field (default_factory = set )
170+ create_only_snapshot_ids : t .Set [SnapshotId ] = field (default_factory = set )
162171
163172
164173@dataclass
@@ -263,7 +272,6 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]:
263272 if plan .is_dev :
264273 before_promote_snapshots = all_selected_for_backfill_snapshots
265274 after_promote_snapshots = set ()
266- snapshots_with_schema_migration = []
267275 else :
268276 before_promote_snapshots = {
269277 s .snapshot_id
@@ -274,30 +282,6 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]:
274282 after_promote_snapshots = all_selected_for_backfill_snapshots - before_promote_snapshots
275283 deployability_index = DeployabilityIndex .all_deployable ()
276284
277- snapshot_ids_with_schema_migration = [
278- s .snapshot_id for s in snapshots .values () if s .requires_schema_migration_in_prod
279- ]
280- # Include all upstream dependencies of snapshots that require schema migration to make sure
281- # the upstream tables are created before the schema updates are applied
282- snapshot_ids_to_migrate = set (dag .subdag (* snapshot_ids_with_schema_migration ))
283- # Migrating a view replaces it, and engines like Postgres drop its dependent views with CASCADE,
284- # so those are migrated too to be recreated
285- for s_id in dag :
286- snapshot = snapshots [s_id ]
287- if snapshot .is_view and any (
288- p_id in snapshot_ids_to_migrate
289- and snapshots [p_id ].is_view
290- and snapshots [p_id ].supports_schema_migration_in_prod
291- for p_id in snapshot .parents
292- ):
293- snapshot_ids_to_migrate .add (s_id )
294- snapshots_with_schema_migration = [
295- snapshots [s_id ]
296- for s_id in dag
297- if s_id in snapshot_ids_to_migrate
298- and snapshots [s_id ].supports_schema_migration_in_prod
299- ]
300-
301285 snapshots_to_intervals = self ._missing_intervals (
302286 plan , snapshots_by_name , deployability_index
303287 )
@@ -387,14 +371,12 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]:
387371 )
388372 )
389373
390- if snapshots_with_schema_migration :
391- stages .append (
392- MigrateSchemasStage (
393- snapshots = snapshots_with_schema_migration ,
394- all_snapshots = snapshots ,
395- deployability_index = deployability_index ,
396- )
374+ if not plan .is_dev :
375+ migrate_schemas_stage = self ._get_migrate_schemas_stage (
376+ snapshots , dag , existing_environment , deployability_index , needs_backfill
397377 )
378+ if migrate_schemas_stage :
379+ stages .append (migrate_schemas_stage )
398380
399381 if not plan .is_dev and not plan .ensure_finalized_snapshots and promoted_snapshots :
400382 # Only unpause at this point if we don't have to use the finalized snapshots
@@ -507,6 +489,170 @@ def _get_physical_layer_update_stage(
507489 deployability_index = deployability_index ,
508490 )
509491
492+ def _get_migrate_schemas_stage (
493+ self ,
494+ snapshots : t .Dict [SnapshotId , Snapshot ],
495+ dag : DAG [SnapshotId ],
496+ existing_environment : t .Optional [Environment ],
497+ deployability_index : DeployabilityIndex ,
498+ needs_backfill : bool ,
499+ ) -> t .Optional [MigrateSchemasStage ]:
500+ if existing_environment and not existing_environment .expired :
501+ if existing_environment .finalized_ts :
502+ prod_baselines : t .List [t .Dict [str , SnapshotTableInfo ]] = [
503+ {s .name : s for s in existing_environment .snapshots }
504+ ]
505+ elif existing_environment .previous_finalized_snapshots :
506+ # Unfinalized prod environment: the previous failed plan may have stopped either
507+ # before or after MigrateSchemasStage, so the live physical MV could match either
508+ # previous_finalized_snapshots or existing_environment.snapshots. Only skip
509+ # recreation when the candidate matches both baselines.
510+ prod_baselines = [
511+ {s .name : s for s in existing_environment .previous_finalized_snapshots },
512+ {s .name : s for s in existing_environment .snapshots },
513+ ]
514+ else :
515+ prod_baselines = []
516+ else :
517+ prod_baselines = []
518+
519+ candidate_mv_old_ids : t .Set [SnapshotId ] = {
520+ baseline [s .name ].snapshot_id
521+ for s in snapshots .values ()
522+ if s .requires_schema_migration_in_prod and s .is_materialized_view
523+ for baseline in prod_baselines
524+ if s .name in baseline
525+ }
526+ old_snapshots_by_id : t .Dict [SnapshotId , Snapshot ] = {}
527+ if candidate_mv_old_ids :
528+ missing_old_ids = [s_id for s_id in candidate_mv_old_ids if s_id not in snapshots ]
529+ fetched_old_snapshots = (
530+ self .state_reader .get_snapshots (missing_old_ids ) if missing_old_ids else {}
531+ )
532+ for s_id in candidate_mv_old_ids :
533+ old_snapshot = snapshots .get (s_id ) or fetched_old_snapshots .get (s_id )
534+ if old_snapshot :
535+ old_snapshots_by_id [s_id ] = old_snapshot
536+
537+ def _matches_baseline (s : Snapshot , baseline : t .Dict [str , SnapshotTableInfo ]) -> bool :
538+ existing = baseline .get (s .name )
539+ if existing is None or not existing .is_model or existing .is_symbolic :
540+ return False
541+ if existing .table_name (is_deployable = True ) != s .table_name (is_deployable = True ):
542+ return False
543+ old = old_snapshots_by_id .get (existing .snapshot_id )
544+ if old is not None :
545+ if not old .is_model or s .is_directly_modified (old ):
546+ return False
547+ elif existing .fingerprint .data_hash != s .fingerprint .data_hash :
548+ return False
549+ if existing .fingerprint .parent_data_hash != s .fingerprint .parent_data_hash :
550+ return False
551+ parents_to_check = list (s .parents )
552+ visited_parents : t .Set [SnapshotId ] = set ()
553+ while parents_to_check :
554+ p_id = parents_to_check .pop ()
555+ if p_id in visited_parents :
556+ continue
557+ visited_parents .add (p_id )
558+ parent = snapshots .get (p_id )
559+ if parent is None :
560+ return False
561+ if parent .is_symbolic :
562+ parents_to_check .extend (parent .parents )
563+ continue
564+ if not parent .is_model :
565+ return False
566+ existing_parent = baseline .get (parent .name )
567+ if (
568+ existing_parent is None
569+ or not existing_parent .is_model
570+ or existing_parent .is_symbolic
571+ or existing_parent .table_name (is_deployable = True )
572+ != parent .table_name (is_deployable = True )
573+ ):
574+ return False
575+ return True
576+
577+ def _is_metadata_only_in_prod (s : Snapshot ) -> bool :
578+ return bool (prod_baselines ) and all (
579+ _matches_baseline (s , baseline ) for baseline in prod_baselines
580+ )
581+
582+ schema_migration_snapshot_ids : t .List [SnapshotId ] = []
583+ grants_only_snapshot_ids : t .Set [SnapshotId ] = set ()
584+ metadata_only_create_ids : t .Set [SnapshotId ] = set ()
585+ for s in snapshots .values ():
586+ if not s .requires_schema_migration_in_prod :
587+ continue
588+ if s .is_materialized_view and _is_metadata_only_in_prod (s ):
589+ targets_physical_grants = s .model .grants is not None and (
590+ s .model .grants_target_layer .is_all
591+ or s .model .grants_target_layer .is_physical
592+ or s .model .virtual_environment_mode .is_dev_only
593+ )
594+ grants_changed = any (
595+ (old := old_snapshots_by_id .get (baseline [s .name ].snapshot_id )) is None
596+ or not old .is_model
597+ or s .model .grants != old .model .grants
598+ or s .model .grants_target_layer != old .model .grants_target_layer
599+ for baseline in prod_baselines
600+ )
601+ if targets_physical_grants and grants_changed :
602+ grants_only_snapshot_ids .add (s .snapshot_id )
603+ elif needs_backfill :
604+ # When backfill runs, PhysicalLayerUpdateStage is skipped. Route metadata-only
605+ # MVs to create-only handling so a missing physical MV is still created while an
606+ # existing MV is untouched.
607+ metadata_only_create_ids .add (s .snapshot_id )
608+ continue
609+ schema_migration_snapshot_ids .append (s .snapshot_id )
610+
611+ # Include all upstream dependencies of snapshots that require schema migration to make sure
612+ # the upstream tables are created before the schema updates are applied
613+ snapshot_ids_to_migrate = set (dag .subdag (* schema_migration_snapshot_ids ))
614+ upstream_only_ids = snapshot_ids_to_migrate - set (schema_migration_snapshot_ids )
615+ create_only_snapshot_ids = {
616+ s_id
617+ for s_id in upstream_only_ids
618+ if s_id not in grants_only_snapshot_ids
619+ and snapshots [s_id ].is_materialized_view
620+ and snapshots [s_id ].supports_schema_migration_in_prod
621+ } | metadata_only_create_ids
622+ snapshot_ids_to_migrate |= metadata_only_create_ids
623+ # Migrating a view replaces it, and engines like Postgres drop its dependent views with CASCADE,
624+ # so those are migrated too to be recreated
625+ for s_id in dag :
626+ snapshot = snapshots [s_id ]
627+ if snapshot .is_view and any (
628+ p_id in snapshot_ids_to_migrate
629+ and p_id not in create_only_snapshot_ids
630+ and p_id not in grants_only_snapshot_ids
631+ and snapshots [p_id ].is_view
632+ and snapshots [p_id ].supports_schema_migration_in_prod
633+ for p_id in snapshot .parents
634+ ):
635+ snapshot_ids_to_migrate .add (s_id )
636+ grants_only_snapshot_ids .discard (s_id )
637+ create_only_snapshot_ids .discard (s_id )
638+
639+ all_migrate_stage_ids = snapshot_ids_to_migrate | grants_only_snapshot_ids
640+ snapshots_with_schema_migration = [
641+ snapshots [s_id ]
642+ for s_id in dag
643+ if s_id in all_migrate_stage_ids and snapshots [s_id ].supports_schema_migration_in_prod
644+ ]
645+ if not snapshots_with_schema_migration :
646+ return None
647+
648+ return MigrateSchemasStage (
649+ snapshots = snapshots_with_schema_migration ,
650+ all_snapshots = snapshots ,
651+ deployability_index = deployability_index ,
652+ grants_only_snapshot_ids = grants_only_snapshot_ids ,
653+ create_only_snapshot_ids = create_only_snapshot_ids ,
654+ )
655+
510656 def _get_virtual_layer_update_stage (
511657 self ,
512658 promoted_snapshots : t .Set [SnapshotTableInfo ],
0 commit comments