Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions sqlmesh/core/plan/evaluator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
31 changes: 26 additions & 5 deletions sqlmesh/core/plan/explainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
111 changes: 106 additions & 5 deletions sqlmesh/core/plan/stages.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
]

Expand Down Expand Up @@ -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,
)
)

Expand Down
28 changes: 28 additions & 0 deletions sqlmesh/core/snapshot/evaluator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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)
Expand All @@ -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
Expand All @@ -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(),
Expand Down Expand Up @@ -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
Expand All @@ -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}
)
Expand Down
Loading