feat: add ordering constraints via `after`
public
feat: add ordering constraints via `after` Order migrations without pulling their targets onto a deployment. Constraints are stored as edges of kind `ordering`, so a late target is detected even when the declaring project isn't loaded. Default warns and proceeds; --restore-order reverts and re-applies in one transaction (--allow-autocommit for non-transactional ones). Refs #2
| Changeset | c8f11ab639692f4e441c5ff666e365b5f67f251f |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@gmail.com>, |
| Parents | 606f4271c456 |
| Children | |
| Pushlog | by timo via ssh |
modified src/mitch/cli/deploy.py +118 −14
| @@ -1,3 +1,4 @@ | ||
| 1 | +from contextlib import nullcontext | |
| 1 | 2 | from enum import Enum |
| 2 | 3 | from pathlib import Path |
| 3 | 4 | from typing import Annotated, Callable, Iterable |
| @@ -6,13 +7,13 @@ | ||
| 6 | 7 | import typer |
| 7 | 8 | from rich.prompt import Confirm |
| 8 | 9 | |
| 9 | -from ..errors import CannotAddLinkedMigrationError | |
| 10 | +from ..errors import BlockedRevertError, CannotAddLinkedMigrationError | |
| 10 | 11 | from ..helpers import connection_for |
| 11 | -from ..migration import Migration | |
| 12 | +from ..migration import Migration, MigrationKey | |
| 12 | 13 | from ..project import Project |
| 13 | 14 | from ..runner import DeploymentStatus, Runner |
| 14 | 15 | from ..watcher import EventType |
| 15 | -from .revert import refuse_revert_if_blocked | |
| 16 | +from .revert import ensure_rebuild_is_safe, refuse_revert_if_blocked | |
| 16 | 17 | |
| 17 | 18 | |
| 18 | 19 | class IfModifiedOption(str, Enum): |
| @@ -23,6 +24,22 @@ | ||
| 23 | 24 | |
| 24 | 25 | |
| 25 | 26 | app = typer.Typer() |
| 27 | + | |
| 28 | +RestoreOrderOption = Annotated[ | |
| 29 | + bool, | |
| 30 | + typer.Option( | |
| 31 | + "--restore-order", | |
| 32 | + help="When a migration arrives after migrations ordered after it, revert and re-apply those instead of warning.", | |
| 33 | + ), | |
| 34 | +] | |
| 35 | + | |
| 36 | +AllowAutocommitOption = Annotated[ | |
| 37 | + bool, | |
| 38 | + typer.Option( | |
| 39 | + "--allow-autocommit", | |
| 40 | + help="Allow reverting and re-applying around a change in autocommit mode when non-transactional migrations take part.", | |
| 41 | + ), | |
| 42 | +] | |
| 26 | 43 | |
| 27 | 44 | LateDependenciesOption = Annotated[ |
| 28 | 45 | bool, |
| @@ -129,11 +146,58 @@ | ||
| 129 | 146 | ) |
| 130 | 147 | |
| 131 | 148 | |
| 149 | +def _late_arrivals(runner: Runner, to_apply: list[Migration]) -> dict[Migration, set[MigrationKey]]: | |
| 150 | + """Pending migrations that applied migrations are ordered after, with those migrations' keys.""" | |
| 151 | + late = {} | |
| 152 | + for migration in to_apply: | |
| 153 | + if runner.deployment_status(migration) == "pending": | |
| 154 | + ordered_after = runner.applied_dependants(migration, kind="ordering") | |
| 155 | + if ordered_after: | |
| 156 | + late[migration] = ordered_after | |
| 157 | + return late | |
| 158 | + | |
| 159 | + | |
| 160 | +def _key_name(project: Project, key: MigrationKey) -> str: | |
| 161 | + loaded = {m.key: m for m in project.all_migrations} | |
| 162 | + return project.display_name(loaded[key]) if key in loaded else f"{key[0]}:{key[1]}" | |
| 163 | + | |
| 164 | + | |
| 165 | +def _restore_order( | |
| 166 | + project: Project, | |
| 167 | + runner: Runner, | |
| 168 | + to_apply: list[Migration], | |
| 169 | + late: dict[Migration, set[MigrationKey]], | |
| 170 | + allow_autocommit: bool, | |
| 171 | +) -> tuple[set[Migration], set[Migration]]: | |
| 172 | + """Revert the migrations ordered after late arrivals. | |
| 173 | + | |
| 174 | + Returns the reverted migrations and those among them that were applied for their own sake. | |
| 175 | + """ | |
| 176 | + loaded = {m.key: m for m in project.all_migrations} | |
| 177 | + keys = set().union(*late.values()) | |
| 178 | + if unknown := {key for key in keys if key not in loaded}: | |
| 179 | + raise BlockedRevertError(unknown) | |
| 180 | + to_revert = [m for m in project.with_dependants(loaded[key] for key in keys) if runner.is_recorded(m)] | |
| 181 | + refuse_revert_if_blocked(project, runner, to_revert) | |
| 182 | + ensure_rebuild_is_safe(project, to_revert, to_apply, allow_autocommit) | |
| 183 | + requested = {m for m in to_revert if not runner.is_pulled_in(m)} | |
| 184 | + _revert_with_feedback( | |
| 185 | + runner, | |
| 186 | + to_revert, | |
| 187 | + lambda migration, status: ( | |
| 188 | + f"[blue]Reverting:[/blue] Migration '{project.display_name(migration)}' ({status}) to restore the order." | |
| 189 | + ), | |
| 190 | + ) | |
| 191 | + return set(to_revert), requested | |
| 192 | + | |
| 193 | + | |
| 132 | 194 | def _apply_planned_migrations( |
| 133 | 195 | project: Project, |
| 134 | 196 | runner: Runner, |
| 135 | 197 | covered_migrations: set[Migration], |
| 136 | 198 | redeploy: set[Migration], |
| 199 | + restore_order: bool = False, | |
| 200 | + allow_autocommit: bool = False, | |
| 137 | 201 | ) -> None: |
| 138 | 202 | to_revert = list(project.with_dependants(redeploy)) |
| 139 | 203 | refuse_revert_if_blocked(project, runner, to_revert) |
| @@ -153,14 +217,32 @@ | ||
| 153 | 217 | if runner.deployment_status(migration) == "pending" |
| 154 | 218 | } |
| 155 | 219 | to_apply = list(project.with_dependencies(pending | redeploy)) |
| 156 | - _deploy_with_feedback( | |
| 157 | - project, | |
| 158 | - runner, | |
| 159 | - to_apply, | |
| 160 | - lambda migration, status: ( | |
| 161 | - f"[green]Deploying:[/green] Migration '{project.display_name(migration)}' ({status})" | |
| 162 | - ), | |
| 163 | - ) | |
| 220 | + | |
| 221 | + def deploy(migrations: list[Migration]) -> None: | |
| 222 | + _deploy_with_feedback( | |
| 223 | + project, | |
| 224 | + runner, | |
| 225 | + migrations, | |
| 226 | + lambda migration, status: ( | |
| 227 | + f"[green]Deploying:[/green] Migration '{project.display_name(migration)}' ({status})" | |
| 228 | + ), | |
| 229 | + ) | |
| 230 | + | |
| 231 | + late = _late_arrivals(runner, to_apply) | |
| 232 | + if late and restore_order: | |
| 233 | + transactional = not allow_autocommit | |
| 234 | + with runner.atomic() if transactional else nullcontext(): | |
| 235 | + reverted, requested = _restore_order(project, runner, to_apply, late, allow_autocommit) | |
| 236 | + requested_before |= requested | |
| 237 | + deploy(list(project.with_dependencies(set(to_apply) | reverted))) | |
| 238 | + else: | |
| 239 | + for migration, keys in late.items(): | |
| 240 | + rich.print( | |
| 241 | + f"[yellow]Warning:[/yellow] Applying '{project.display_name(migration)}' after " | |
| 242 | + f"{', '.join(repr(_key_name(project, key)) for key in sorted(keys))}, which are ordered after it. " | |
| 243 | + f"The order deviates from the graph; use --restore-order to revert and re-apply them." | |
| 244 | + ) | |
| 245 | + deploy(to_apply) | |
| 164 | 246 | runner.mark_requested(m for m in requested_before if runner.is_recorded(m)) |
| 165 | 247 | |
| 166 | 248 | |
| @@ -223,6 +305,8 @@ | ||
| 223 | 305 | watch: bool, |
| 224 | 306 | allow_new_migrations: bool, |
| 225 | 307 | late_dependencies: bool = False, |
| 308 | + restore_order: bool = False, | |
| 309 | + allow_autocommit: bool = False, | |
| 226 | 310 | ) -> None: |
| 227 | 311 | project = Project.from_path(root) |
| 228 | 312 | requested = project.resolve_all(migration_ids) |
| @@ -236,7 +320,9 @@ | ||
| 236 | 320 | runner = Runner(connection) |
| 237 | 321 | runner.sync_edges(project.all_migrations) |
| 238 | 322 | redeploy = _collect_redeploy_migrations(project, runner, covered_migrations, if_modified, late_dependencies) |
| 239 | - _apply_planned_migrations(project, runner, covered_migrations, redeploy) | |
| 323 | + _apply_planned_migrations( | |
| 324 | + project, runner, covered_migrations, redeploy, restore_order=restore_order, allow_autocommit=allow_autocommit | |
| 325 | + ) | |
| 240 | 326 | runner.mark_requested(m for m in requested if runner.is_recorded(m)) |
| 241 | 327 | |
| 242 | 328 | if not watch: |
| @@ -278,9 +364,21 @@ | ||
| 278 | 364 | typer.Option("--watch", help="Watch the project and re-run deployments on changes."), |
| 279 | 365 | ] = False, |
| 280 | 366 | late_dependencies: LateDependenciesOption = False, |
| 367 | + restore_order: RestoreOrderOption = False, | |
| 368 | + allow_autocommit: AllowAutocommitOption = False, | |
| 281 | 369 | ) -> None: |
| 282 | 370 | """Apply the specified migrations in the project.""" |
| 283 | - run_deploy(migration_ids, root, database_url, if_modified, watch, allow_new_migrations=False, late_dependencies=late_dependencies) | |
| 371 | + run_deploy( | |
| 372 | + migration_ids, | |
| 373 | + root, | |
| 374 | + database_url, | |
| 375 | + if_modified, | |
| 376 | + watch, | |
| 377 | + allow_new_migrations=False, | |
| 378 | + late_dependencies=late_dependencies, | |
| 379 | + restore_order=restore_order, | |
| 380 | + allow_autocommit=allow_autocommit, | |
| 381 | + ) | |
| 284 | 382 | |
| 285 | 383 | |
| 286 | 384 | def run_up( |
| @@ -289,6 +387,8 @@ | ||
| 289 | 387 | if_modified: IfModifiedOption | None = None, |
| 290 | 388 | watch: bool = False, |
| 291 | 389 | late_dependencies: bool = False, |
| 390 | + restore_order: bool = False, | |
| 391 | + allow_autocommit: bool = False, | |
| 292 | 392 | ) -> None: |
| 293 | 393 | project = Project.from_path(root) |
| 294 | 394 | run_deploy( |
| @@ -299,6 +399,8 @@ | ||
| 299 | 399 | watch, |
| 300 | 400 | allow_new_migrations=True, |
| 301 | 401 | late_dependencies=late_dependencies, |
| 402 | + restore_order=restore_order, | |
| 403 | + allow_autocommit=allow_autocommit, | |
| 302 | 404 | ) |
| 303 | 405 | |
| 304 | 406 | |
| @@ -322,6 +424,8 @@ | ||
| 322 | 424 | typer.Option("--watch", help="Watch the project and re-run deployments on changes."), |
| 323 | 425 | ] = False, |
| 324 | 426 | late_dependencies: LateDependenciesOption = False, |
| 427 | + restore_order: RestoreOrderOption = False, | |
| 428 | + allow_autocommit: AllowAutocommitOption = False, | |
| 325 | 429 | ) -> None: |
| 326 | 430 | """Apply all pending migrations in the project, plus the linked migrations they require.""" |
| 327 | - run_up(root, database_url, if_modified, watch, late_dependencies) | |
| 431 | + run_up(root, database_url, if_modified, watch, late_dependencies, restore_order, allow_autocommit) | |
modified src/mitch/cli/revert.py +16 −1
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | import rich |
| 5 | 5 | import typer |
| 6 | 6 | |
| 7 | -from ..errors import BlockedRevertError | |
| 7 | +from ..errors import BlockedRevertError, UnsafeRebuildError | |
| 8 | 8 | from ..helpers import connection_for |
| 9 | 9 | from ..migration import Migration |
| 10 | 10 | from ..project import Project |
| @@ -46,6 +46,21 @@ | ||
| 46 | 46 | raise BlockedRevertError(blockers) |
| 47 | 47 | |
| 48 | 48 | |
| 49 | +def ensure_rebuild_is_safe( | |
| 50 | + project: Project, to_revert: list[Migration], to_apply: list[Migration], allow_autocommit: bool | |
| 51 | +) -> None: | |
| 52 | + """A rebuild is all or nothing: everything reverted needs a down script, and everything must run in | |
| 53 | + one transaction unless autocommit is explicitly allowed (ADR runner/rebuild-dependants-through-the-migration-graph).""" | |
| 54 | + without_down = [project.display_name(m) for m in to_revert if m.down_script is None] | |
| 55 | + if without_down: | |
| 56 | + raise UnsafeRebuildError("no down script", without_down) | |
| 57 | + non_transactional = [project.display_name(m) for m in {*to_revert, *to_apply} if not m.transactional] | |
| 58 | + if non_transactional and not allow_autocommit: | |
| 59 | + raise UnsafeRebuildError( | |
| 60 | + "non-transactional migrations cannot be rolled back (allow with --allow-autocommit)", non_transactional | |
| 61 | + ) | |
| 62 | + | |
| 63 | + | |
| 49 | 64 | def revert_orphans(project: Project, runner: Runner) -> None: |
| 50 | 65 | """Revert linked migrations that were pulled in and are no longer needed by any applied migration.""" |
| 51 | 66 | while orphans := [ |
modified src/mitch/errors.py +8 −0
| @@ -102,3 +102,11 @@ | ||
| 102 | 102 | f"Cannot revert: applied migrations of projects that are not loaded depend on it: {listed}. " |
| 103 | 103 | f"Revert them from their own projects first." |
| 104 | 104 | ) |
| 105 | + | |
| 106 | + | |
| 107 | +class UnsafeRebuildError(MitchError): | |
| 108 | + """Raised when migrations would have to be reverted and re-applied, but that cannot be done safely.""" | |
| 109 | + | |
| 110 | + def __init__(self, reason: str, migrations: Iterable[str]): | |
| 111 | + listed = ", ".join(sorted(migrations)) | |
| 112 | + super().__init__(f"Cannot revert and re-apply around this change: {reason}: {listed}.") | |
modified src/mitch/migration.py +3 −0
| @@ -25,10 +25,13 @@ | ||
| 25 | 25 | |
| 26 | 26 | # References as written in the config: own migration IDs or qualified IDs (`alias:migration`). |
| 27 | 27 | dependencies: set[str] = field(default_factory=set, repr=False) |
| 28 | + # Ordering constraints: run after these when they are applied or in the same run, without requiring them. | |
| 29 | + after: set[str] = field(default_factory=set, repr=False) | |
| 28 | 30 | project: "Project | None" = field(default=None, repr=False) |
| 29 | 31 | |
| 30 | 32 | # Filled in when the project graph is built. |
| 31 | 33 | resolved_dependencies: set["Migration"] = field(default_factory=set, repr=False) |
| 34 | + resolved_after: set["Migration"] = field(default_factory=set, repr=False) | |
| 32 | 35 | |
| 33 | 36 | @property |
| 34 | 37 | def project_id(self) -> str | None: |
modified src/mitch/project.py +39 −17
| @@ -140,6 +140,7 @@ | ||
| 140 | 140 | idempotent=config.get("idempotent", False), |
| 141 | 141 | created_at=self._created_at_from_config(config.get("created_at"), config_file), |
| 142 | 142 | dependencies={*config.get("dependencies", [])}, |
| 143 | + after={*config.get("after", [])}, | |
| 143 | 144 | project=self, |
| 144 | 145 | ) |
| 145 | 146 | ) |
| @@ -215,35 +216,54 @@ | ||
| 215 | 216 | self._canonical = canonical |
| 216 | 217 | |
| 217 | 218 | self._dependants: dict[Migration, set[Migration]] = defaultdict(set) |
| 219 | + self._ordered_after: dict[Migration, set[Migration]] = defaultdict(set) | |
| 218 | 220 | for migration in canonical.values(): |
| 219 | 221 | migration.resolved_dependencies.clear() |
| 220 | - assert migration.project is not None | |
| 221 | - for reference in migration.dependencies: | |
| 222 | - try: | |
| 223 | - target = migration.project._resolve_in_scope(reference, canonical) | |
| 224 | - except (UnknownAliasError, MissingMigrationError) as error: | |
| 225 | - if self._loader.strict: | |
| 226 | - raise | |
| 227 | - self.warnings.append(str(error)) | |
| 228 | - continue | |
| 229 | - migration.resolved_dependencies.add(target) | |
| 230 | - self._dependants[target].add(migration) | |
| 222 | + migration.resolved_after.clear() | |
| 223 | + for dependency in self._resolve_references(migration, migration.dependencies, canonical): | |
| 224 | + migration.resolved_dependencies.add(dependency) | |
| 225 | + self._dependants[dependency].add(migration) | |
| 226 | + for predecessor in self._resolve_references(migration, migration.after, canonical): | |
| 227 | + migration.resolved_after.add(predecessor) | |
| 228 | + self._ordered_after[predecessor].add(migration) | |
| 231 | 229 | |
| 232 | 230 | # Copies must also agree on what a migration depends on, or consumers would keep rewriting its edges. |
| 233 | 231 | for copy in copies: |
| 234 | 232 | assert copy.project is not None |
| 235 | 233 | original = canonical[copy.key] |
| 236 | 234 | try: |
| 237 | - copy_dependencies = {copy.project._resolve_in_scope(r, canonical).key for r in copy.dependencies} | |
| 235 | + copy_references = ( | |
| 236 | + {copy.project._resolve_in_scope(r, canonical).key for r in copy.dependencies}, | |
| 237 | + {copy.project._resolve_in_scope(r, canonical).key for r in copy.after}, | |
| 238 | + ) | |
| 238 | 239 | except (UnknownAliasError, MissingMigrationError): |
| 239 | - copy_dependencies = None | |
| 240 | - if copy_dependencies != {d.key for d in original.resolved_dependencies}: | |
| 240 | + copy_references = None | |
| 241 | + original_references = ( | |
| 242 | + {d.key for d in original.resolved_dependencies}, | |
| 243 | + {a.key for a in original.resolved_after}, | |
| 244 | + ) | |
| 245 | + if copy_references != original_references: | |
| 241 | 246 | raise ConflictingCopiesError(copy.project_id or "", copy.id, original.up_script, copy.up_script) |
| 242 | 247 | |
| 243 | 248 | try: |
| 244 | - TopologicalSorter({m: m.resolved_dependencies for m in canonical.values()}).prepare() | |
| 249 | + TopologicalSorter({m: m.resolved_dependencies | m.resolved_after for m in canonical.values()}).prepare() | |
| 245 | 250 | except CycleError as error: |
| 246 | 251 | raise MigrationCycleError(self.display_name(m) for m in error.args[1]) from None |
| 252 | + | |
| 253 | + def _resolve_references( | |
| 254 | + self, migration: Migration, references: Iterable[str], canonical: dict[MigrationKey, Migration] | |
| 255 | + ) -> list[Migration]: | |
| 256 | + """Resolve references written in `migration`'s project; in lenient mode, skip and warn.""" | |
| 257 | + assert migration.project is not None | |
| 258 | + resolved = [] | |
| 259 | + for reference in references: | |
| 260 | + try: | |
| 261 | + resolved.append(migration.project._resolve_in_scope(reference, canonical)) | |
| 262 | + except (UnknownAliasError, MissingMigrationError) as error: | |
| 263 | + if self._loader.strict: | |
| 264 | + raise | |
| 265 | + self.warnings.append(str(error)) | |
| 266 | + return resolved | |
| 247 | 267 | |
| 248 | 268 | def _resolve_in_scope(self, reference: str, canonical: dict[MigrationKey, Migration]) -> Migration: |
| 249 | 269 | """Resolve a reference as written inside this project.""" |
| @@ -393,12 +413,14 @@ | ||
| 393 | 413 | def with_dependencies(self, migrations: Iterable[Migration]) -> Iterable[Migration]: |
| 394 | 414 | """The migrations plus everything they transitively depend on, dependencies first.""" |
| 395 | 415 | nodes = self._closure(migrations, lambda m: m.resolved_dependencies) |
| 396 | - yield from self._iter_sorted({m: m.resolved_dependencies & nodes for m in nodes}) | |
| 416 | + yield from self._iter_sorted({m: (m.resolved_dependencies | m.resolved_after) & nodes for m in nodes}) | |
| 397 | 417 | |
| 398 | 418 | def with_dependants(self, migrations: Iterable[Migration]) -> Iterable[Migration]: |
| 399 | 419 | """The migrations plus everything that transitively depends on them, dependants first.""" |
| 400 | 420 | nodes = self._closure(migrations, lambda m: self._dependants.get(m, set())) |
| 401 | - yield from self._iter_sorted({m: self._dependants.get(m, set()) & nodes for m in nodes}) | |
| 421 | + yield from self._iter_sorted( | |
| 422 | + {m: (self._dependants.get(m, set()) | self._ordered_after.get(m, set())) & nodes for m in nodes} | |
| 423 | + ) | |
| 402 | 424 | |
| 403 | 425 | def __iter__(self) -> Generator[Migration, None, None]: |
| 404 | 426 | yield from self.with_dependencies(self.migrations) |
modified src/mitch/runner.py +32 −14
| @@ -11,11 +11,13 @@ | ||
| 11 | 11 | from .sql import script_hashes, split_statements |
| 12 | 12 | |
| 13 | 13 | DeploymentStatus: TypeAlias = Literal["pending", "applied", "modified"] |
| 14 | +EdgeKind: TypeAlias = Literal["dependency", "ordering"] | |
| 14 | 15 | |
| 15 | 16 | |
| 16 | 17 | class Runner: |
| 17 | 18 | def __init__(self, connection: Connection) -> None: |
| 18 | - self._pending_work = [] | |
| 19 | + self._pending_work: list[str] = [] | |
| 20 | + self._atomic = False | |
| 19 | 21 | self.connection = connection |
| 20 | 22 | self._project_local_ids: dict[str, int] = {} |
| 21 | 23 | sa.event.listen(self.connection, "commit", self._on_commit) |
| @@ -182,7 +184,21 @@ | ||
| 182 | 184 | self.connection.commit() |
| 183 | 185 | |
| 184 | 186 | @contextmanager |
| 187 | + def atomic(self): | |
| 188 | + """Run everything inside in one transaction, including reverts and applies that open their own.""" | |
| 189 | + self._commit_transaction_if_open_but_empty() | |
| 190 | + with self.connection.begin(): | |
| 191 | + self._atomic = True | |
| 192 | + try: | |
| 193 | + yield self | |
| 194 | + finally: | |
| 195 | + self._atomic = False | |
| 196 | + | |
| 197 | + @contextmanager | |
| 185 | 198 | def transaction(self): |
| 199 | + if self._atomic: | |
| 200 | + yield self | |
| 201 | + return | |
| 186 | 202 | self._commit_transaction_if_open_but_empty() |
| 187 | 203 | with self.connection.begin() as transaction: |
| 188 | 204 | try: |
| @@ -255,21 +271,20 @@ | ||
| 255 | 271 | # ------------------------------------------------------------------ dependency edges |
| 256 | 272 | |
| 257 | 273 | def _write_edges(self, migration: Migration) -> None: |
| 274 | + """Replace the recorded dependencies and ordering constraints of `migration` with its source.""" | |
| 258 | 275 | local_key = self._local_key(migration) |
| 259 | - self.connection.execute( | |
| 260 | - self.edge_table.delete().where( | |
| 261 | - sa.and_(self._key_filter(self.edge_table, local_key), self.edge_table.c.kind == 'dependency') | |
| 262 | - ) | |
| 263 | - ) | |
| 264 | - for dependency in migration.resolved_dependencies: | |
| 265 | - dependency_local_id, dependency_id = self._local_key(dependency) | |
| 276 | + self.connection.execute(self.edge_table.delete().where(self._key_filter(self.edge_table, local_key))) | |
| 277 | + edges = [(d, 'dependency') for d in migration.resolved_dependencies] | |
| 278 | + edges += [(a, 'ordering') for a in migration.resolved_after] | |
| 279 | + for other, kind in edges: | |
| 280 | + other_local_id, other_id = self._local_key(other) | |
| 266 | 281 | self.connection.execute( |
| 267 | 282 | self.edge_table.insert().values( |
| 268 | 283 | project_id=local_key[0], |
| 269 | 284 | migration_id=local_key[1], |
| 270 | - dependency_project_id=dependency_local_id, | |
| 271 | - dependency_migration_id=dependency_id, | |
| 272 | - kind='dependency', | |
| 285 | + dependency_project_id=other_local_id, | |
| 286 | + dependency_migration_id=other_id, | |
| 287 | + kind=kind, | |
| 273 | 288 | ) |
| 274 | 289 | ) |
| 275 | 290 | |
| @@ -280,8 +295,11 @@ | ||
| 280 | 295 | if self.is_recorded(migration): |
| 281 | 296 | self._write_edges(migration) |
| 282 | 297 | |
| 283 | - def applied_dependants(self, migration: Migration) -> set[MigrationKey]: | |
| 284 | - """(project ID, migration ID) of applied migrations recorded as depending on `migration`.""" | |
| 298 | + def applied_dependants(self, migration: Migration, kind: EdgeKind = 'dependency') -> set[MigrationKey]: | |
| 299 | + """(project ID, migration ID) of applied migrations recorded as depending on `migration`. | |
| 300 | + | |
| 301 | + With kind 'ordering': applied migrations recorded as ordered after `migration`. | |
| 302 | + """ | |
| 285 | 303 | project_local_id, migration_id = self._local_key(migration) |
| 286 | 304 | dependant_project = self.project_table.alias('dependant_project') |
| 287 | 305 | rows = self.connection.execute( |
| @@ -301,7 +319,7 @@ | ||
| 301 | 319 | sa.and_( |
| 302 | 320 | self.edge_table.c.dependency_project_id == project_local_id, |
| 303 | 321 | self.edge_table.c.dependency_migration_id == migration_id, |
| 304 | - self.edge_table.c.kind == 'dependency', | |
| 322 | + self.edge_table.c.kind == kind, | |
| 305 | 323 | ) |
| 306 | 324 | ) |
| 307 | 325 | ) |
modified src/mitch/transition.py +1 −0
| @@ -20,6 +20,7 @@ | ||
| 20 | 20 | _normalized(migration.up_script), |
| 21 | 21 | _normalized(migration.down_script), |
| 22 | 22 | tuple(sorted(migration.dependencies)), |
| 23 | + tuple(sorted(migration.after)), | |
| 23 | 24 | migration.transactional, |
| 24 | 25 | migration.idempotent, |
| 25 | 26 | ) |
modified tests/test_rework.py +81 −0
| @@ -92,3 +92,84 @@ | ||
| 92 | 92 | assert result.exit_code == 0, result.output |
| 93 | 93 | assert audit(tmp_path)[history_before:] == [("answer@2", "reverted")] |
| 94 | 94 | assert applied_ids(tmp_path) == {"answer", "reader"} |
| 95 | + | |
| 96 | + | |
| 97 | +# ---------------------------------------------------------------- ordering constraints | |
| 98 | + | |
| 99 | + | |
| 100 | +def table(name: str) -> tuple[str, str]: | |
| 101 | + return f"CREATE TABLE {name} (id int);", f"DROP TABLE {name};" | |
| 102 | + | |
| 103 | + | |
| 104 | +def test_ordering_constraint_runs_a_migration_after_another_in_the_same_run(tmp_path): | |
| 105 | + root = new_project(tmp_path / "app") | |
| 106 | + # Without the constraint, "early" would sort first by creation time. | |
| 107 | + write_migration(root, "late", *table("late"), 'created_at = 2026-02-01\n') | |
| 108 | + write_migration(root, "early", *table("early"), 'created_at = 2026-01-01\nafter = ["late"]\n') | |
| 109 | + | |
| 110 | + result = mitch("up", "-p", str(root), "-d", db_url(tmp_path)) | |
| 111 | + | |
| 112 | + assert result.exit_code == 0, result.output | |
| 113 | + assert [m for m, _ in audit(tmp_path)] == ["late", "early"] | |
| 114 | + | |
| 115 | + | |
| 116 | +def test_ordering_constraint_does_not_pull_in_its_target(tmp_path): | |
| 117 | + root = new_project(tmp_path / "app") | |
| 118 | + write_migration(root, "optional", *table("optional")) | |
| 119 | + write_migration(root, "main", *table("main"), 'after = ["optional"]\n') | |
| 120 | + | |
| 121 | + result = mitch("add", "main", "-p", str(root), "-d", db_url(tmp_path)) | |
| 122 | + | |
| 123 | + assert result.exit_code == 0, result.output | |
| 124 | + assert applied_ids(tmp_path) == {"main"} | |
| 125 | + | |
| 126 | + | |
| 127 | +def test_cycle_of_dependency_and_ordering_constraint_is_an_error(tmp_path): | |
| 128 | + root = new_project(tmp_path / "app") | |
| 129 | + write_migration(root, "a", *table("a"), 'after = ["b"]\n') | |
| 130 | + write_migration(root, "b", *table("b"), 'dependencies = ["a"]\n') | |
| 131 | + | |
| 132 | + result = mitch("up", "-p", str(root), "-d", db_url(tmp_path)) | |
| 133 | + | |
| 134 | + assert result.exit_code == 1 | |
| 135 | + assert "cycle" in result.output | |
| 136 | + | |
| 137 | + | |
| 138 | +def test_late_target_of_ordering_constraint_is_applied_with_a_warning(tmp_path): | |
| 139 | + root = new_project(tmp_path / "app") | |
| 140 | + write_migration(root, "optional", *table("optional")) | |
| 141 | + write_migration(root, "main", *table("main"), 'after = ["optional"]\n') | |
| 142 | + mitch("add", "main", "-p", str(root), "-d", db_url(tmp_path)) | |
| 143 | + | |
| 144 | + result = mitch("add", "optional", "-p", str(root), "-d", db_url(tmp_path)) | |
| 145 | + | |
| 146 | + assert result.exit_code == 0, result.output | |
| 147 | + assert "Warning" in result.output and "main" in result.output | |
| 148 | + assert audit(tmp_path) == [("main", "applied"), ("optional", "applied")] | |
| 149 | + | |
| 150 | + | |
| 151 | +def test_restore_order_reverts_and_reapplies_around_a_late_target(tmp_path): | |
| 152 | + root = new_project(tmp_path / "app") | |
| 153 | + write_migration(root, "optional", *table("optional")) | |
| 154 | + write_migration(root, "main", *table("main"), 'after = ["optional"]\n') | |
| 155 | + mitch("add", "main", "-p", str(root), "-d", db_url(tmp_path)) | |
| 156 | + | |
| 157 | + result = mitch("add", "optional", "--restore-order", "-p", str(root), "-d", db_url(tmp_path)) | |
| 158 | + | |
| 159 | + assert result.exit_code == 0, result.output | |
| 160 | + assert audit(tmp_path)[1:] == [("main", "reverted"), ("optional", "applied"), ("main", "applied")] | |
| 161 | + | |
| 162 | + | |
| 163 | +def test_late_target_is_detected_through_the_recorded_constraint_of_a_project_not_loaded(tmp_path): | |
| 164 | + users = new_project(tmp_path / "users", "org.example.users") | |
| 165 | + write_migration(users, "create-users", *table("users")) | |
| 166 | + reports = new_project(tmp_path / "reports", "org.example.reports") | |
| 167 | + (reports / "mitch.toml").write_text('[project]\nid = "org.example.reports"\n\n[projects]\nu = "../users"\n', encoding="utf-8") | |
| 168 | + write_migration(reports, "report", *table("report"), 'after = ["u:create-users"]\n') | |
| 169 | + mitch("up", "-p", str(reports), "-d", db_url(tmp_path)) | |
| 170 | + assert applied_ids(tmp_path) == {"report"} | |
| 171 | + | |
| 172 | + result = mitch("up", "-p", str(users), "-d", db_url(tmp_path)) | |
| 173 | + | |
| 174 | + assert result.exit_code == 0, result.output | |
| 175 | + assert "Warning" in result.output and "org.example.reports:report" in result.output | |