Add table mitch_projects, so that multiple projects can be applied against the same database.
public
Add table mitch_projects, so that multiple projects can be applied against the same database.
| Changeset | 20354bfd2ef51f47e544b4fbb2066f0b4e9e7888 |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@gmail.com>, |
| Parents | 90b46d696d4a |
| Children | |
| Pushlog | by timo via ssh |
modified src/mitch/cli/log.py +4 −1
| @@ -60,8 +60,11 @@ | ||
| 60 | 60 | |
| 61 | 61 | with connection_for(database_url) as connection: |
| 62 | 62 | runner = Runner(connection) |
| 63 | + project_local_id = runner.project_local_id_for(project.id) | |
| 63 | 64 | rows = connection.execute( |
| 64 | - runner.migration_table.select().order_by( | |
| 65 | + runner.migration_table.select().where( | |
| 66 | + runner.migration_table.c.project_id == project_local_id | |
| 67 | + ).order_by( | |
| 65 | 68 | runner.migration_table.c.applied_at, |
| 66 | 69 | runner.migration_table.c.id, |
| 67 | 70 | ) |
modified src/mitch/cli/status.py +4 −1
| @@ -26,7 +26,10 @@ | ||
| 26 | 26 | selected_ids: set[str] | None = None, |
| 27 | 27 | ) -> IntegrityReport: |
| 28 | 28 | # Retrieve applied migration IDs from the database, optionally filtered by selected IDs, sorted by ID. |
| 29 | - query = select(runner.migration_table.c.id) | |
| 29 | + project_local_id = runner.project_local_id_for(project.id) | |
| 30 | + query = select(runner.migration_table.c.id).where( | |
| 31 | + runner.migration_table.c.project_id == project_local_id | |
| 32 | + ) | |
| 30 | 33 | if selected_ids is not None: |
| 31 | 34 | query = query.where(runner.migration_table.c.id.in_(selected_ids)) |
| 32 | 35 | query = query.order_by(runner.migration_table.c.id) |
modified src/mitch/migration.py +5 −0
| @@ -1,6 +1,10 @@ | ||
| 1 | 1 | from dataclasses import dataclass, field |
| 2 | 2 | from datetime import date, datetime |
| 3 | 3 | from pathlib import Path |
| 4 | +from typing import TYPE_CHECKING | |
| 5 | + | |
| 6 | +if TYPE_CHECKING: | |
| 7 | + from .project import Project | |
| 4 | 8 | |
| 5 | 9 | |
| 6 | 10 | @dataclass(frozen=True) |
| @@ -17,3 +21,4 @@ | ||
| 17 | 21 | |
| 18 | 22 | dependencies: set[str] = field(compare=False, default_factory=set, repr=False) |
| 19 | 23 | dependants: set[str] = field(compare=False, default_factory=set, repr=False) |
| 24 | + project: "Project | None" = field(compare=False, default=None, repr=False) | |
modified src/mitch/project.py +1 −0
| @@ -77,6 +77,7 @@ | ||
| 77 | 77 | idempotent=config.get("idempotent", False), |
| 78 | 78 | created_at=self._created_at_from_config(config.get("created_at"), config_file), |
| 79 | 79 | dependencies={*config.get("dependencies", [])}, |
| 80 | + project=self, | |
| 80 | 81 | ) |
| 81 | 82 | self.migrations.append(migration) |
| 82 | 83 | |
modified src/mitch/runner.py +69 −5
| @@ -18,6 +18,7 @@ | ||
| 18 | 18 | def __init__(self, connection: Connection) -> None: |
| 19 | 19 | self._pending_work = [] |
| 20 | 20 | self.connection = connection |
| 21 | + self._project_local_ids: dict[str, int] = {} | |
| 21 | 22 | sa.event.listen(self.connection, "commit", self._on_commit) |
| 22 | 23 | sa.event.listen(self.connection, "rollback", self._on_rollback) |
| 23 | 24 | |
| @@ -94,19 +95,29 @@ | ||
| 94 | 95 | else: |
| 95 | 96 | self.metadata = sa.MetaData() |
| 96 | 97 | |
| 98 | + self.project_table = sa.Table( | |
| 99 | + 'projects' if self.metadata.schema == 'mitch' else 'mitch_projects', | |
| 100 | + self.metadata, | |
| 101 | + sa.Column('local_id', sa.Integer, primary_key=True, autoincrement=True), | |
| 102 | + sa.Column('id', sa.String, nullable=False, unique=True), | |
| 103 | + ) | |
| 104 | + | |
| 97 | 105 | self.migration_table = sa.Table( |
| 98 | 106 | 'migrations' if self.metadata.schema == 'mitch' else 'mitch_migrations', |
| 99 | 107 | self.metadata, |
| 100 | - sa.Column('id', sa.String, primary_key=True), | |
| 108 | + sa.Column('project_id', sa.Integer, sa.ForeignKey(self.project_table.c.local_id), nullable=False), | |
| 109 | + sa.Column('id', sa.String, nullable=False), | |
| 101 | 110 | sa.Column('raw_hash', sa.String, nullable=False), |
| 102 | 111 | sa.Column('normalized_hash', sa.String, nullable=False), |
| 103 | 112 | sa.Column('applied_at', sa.DateTime, server_default=sa.func.current_timestamp()), |
| 113 | + sa.PrimaryKeyConstraint('project_id', 'id'), | |
| 104 | 114 | ) |
| 105 | 115 | |
| 106 | 116 | self.audit_table = sa.Table( |
| 107 | 117 | 'migration_audit' if self.metadata.schema == 'mitch' else 'mitch_migration_audit', |
| 108 | 118 | self.metadata, |
| 109 | 119 | sa.Column('id', sa.Integer, primary_key=True, autoincrement=True), |
| 120 | + sa.Column('project_id', sa.Integer, sa.ForeignKey(self.project_table.c.local_id), nullable=False), | |
| 110 | 121 | sa.Column('migration_id', sa.String, nullable=False), |
| 111 | 122 | sa.Column('action', sa.String, nullable=False), # 'applied' or 'reverted' |
| 112 | 123 | sa.Column('timestamp', sa.DateTime, server_default=sa.func.current_timestamp()) |
| @@ -114,6 +125,50 @@ | ||
| 114 | 125 | |
| 115 | 126 | self.metadata.create_all(self.connection, checkfirst=True) |
| 116 | 127 | self._pending_work.append('initialized migration tables') |
| 128 | + | |
| 129 | + def _ensure_project_registration(self, project_id: str) -> int: | |
| 130 | + if project_id in self._project_local_ids: | |
| 131 | + return self._project_local_ids[project_id] | |
| 132 | + | |
| 133 | + def _lookup_or_insert() -> int: | |
| 134 | + project_row = self.connection.execute( | |
| 135 | + sa.select(self.project_table.c.local_id).where(self.project_table.c.id == project_id) | |
| 136 | + ).first() | |
| 137 | + if project_row is None: | |
| 138 | + self.connection.execute( | |
| 139 | + self.project_table.insert().values(id=project_id) | |
| 140 | + ) | |
| 141 | + project_row = self.connection.execute( | |
| 142 | + sa.select(self.project_table.c.local_id).where(self.project_table.c.id == project_id) | |
| 143 | + ).first() | |
| 144 | + assert project_row is not None | |
| 145 | + return project_row.local_id | |
| 146 | + | |
| 147 | + if self.connection.in_transaction(): | |
| 148 | + local_id = _lookup_or_insert() | |
| 149 | + else: | |
| 150 | + with self.connection.begin(): | |
| 151 | + local_id = _lookup_or_insert() | |
| 152 | + | |
| 153 | + self._project_local_ids[project_id] = local_id | |
| 154 | + return local_id | |
| 155 | + | |
| 156 | + def project_local_id_for(self, project_id: str) -> int: | |
| 157 | + return self._ensure_project_registration(project_id) | |
| 158 | + | |
| 159 | + def _project_id_for_migration(self, migration: Migration) -> str: | |
| 160 | + if migration.project is None: | |
| 161 | + raise ValueError( | |
| 162 | + f"Migration '{migration.id}' has no parent project. " | |
| 163 | + "Load migrations through Project so they carry migration.project." | |
| 164 | + ) | |
| 165 | + return migration.project.id | |
| 166 | + | |
| 167 | + def _migration_scope_for_id(self, project_local_id: int, migration_id: str): | |
| 168 | + return sa.and_( | |
| 169 | + self.migration_table.c.project_id == project_local_id, | |
| 170 | + self.migration_table.c.id == migration_id, | |
| 171 | + ) | |
| 117 | 172 | |
| 118 | 173 | def _commit_transaction_if_open_but_empty(self) -> None: |
| 119 | 174 | if ( |
| @@ -136,10 +191,12 @@ | ||
| 136 | 191 | transaction.commit() |
| 137 | 192 | |
| 138 | 193 | def deployment_status(self, migration: Migration) -> DeploymentStatus: |
| 194 | + project_id = self._project_id_for_migration(migration) | |
| 195 | + project_local_id = self._ensure_project_registration(project_id) | |
| 139 | 196 | deployment = self.connection.execute( |
| 140 | 197 | self.migration_table |
| 141 | 198 | .select() |
| 142 | - .where(self.migration_table.c.id == migration.id) | |
| 199 | + .where(self._migration_scope_for_id(project_local_id, migration.id)) | |
| 143 | 200 | ).first() |
| 144 | 201 | |
| 145 | 202 | if deployment is None: |
| @@ -158,7 +215,7 @@ | ||
| 158 | 215 | # Update the stored raw_hash to reflect the new formatting. |
| 159 | 216 | self.connection.execute( |
| 160 | 217 | self.migration_table.update() |
| 161 | - .where(self.migration_table.c.id == migration.id) | |
| 218 | + .where(self._migration_scope_for_id(project_local_id, migration.id)) | |
| 162 | 219 | .values(raw_hash=raw_hash) |
| 163 | 220 | ) |
| 164 | 221 | return 'applied' |
| @@ -168,7 +225,7 @@ | ||
| 168 | 225 | # Update the stored normalized_hash to reflect the new normalization. |
| 169 | 226 | self.connection.execute( |
| 170 | 227 | self.migration_table.update() |
| 171 | - .where(self.migration_table.c.id == migration.id) | |
| 228 | + .where(self._migration_scope_for_id(project_local_id, migration.id)) | |
| 172 | 229 | .values(normalized_hash=normalized_hash) |
| 173 | 230 | ) |
| 174 | 231 | return 'applied' |
| @@ -194,6 +251,8 @@ | ||
| 194 | 251 | self._revert_migration(migration) |
| 195 | 252 | |
| 196 | 253 | def _apply_migration(self, migration: Migration) -> None: |
| 254 | + project_id = self._project_id_for_migration(migration) | |
| 255 | + project_local_id = self._ensure_project_registration(project_id) | |
| 197 | 256 | sql = migration.up_script.read_text(encoding="utf-8") |
| 198 | 257 | statements = list(self._split_statements(sql)) |
| 199 | 258 | |
| @@ -208,6 +267,7 @@ | ||
| 208 | 267 | |
| 209 | 268 | self.connection.execute( |
| 210 | 269 | self.migration_table.insert().values( |
| 270 | + project_id=project_local_id, | |
| 211 | 271 | id=migration.id, |
| 212 | 272 | raw_hash=raw_hash, |
| 213 | 273 | normalized_hash=normalized_hash, |
| @@ -217,6 +277,7 @@ | ||
| 217 | 277 | |
| 218 | 278 | self.connection.execute( |
| 219 | 279 | self.audit_table.insert().values( |
| 280 | + project_id=project_local_id, | |
| 220 | 281 | migration_id=migration.id, |
| 221 | 282 | action='applied', |
| 222 | 283 | timestamp=applied_at |
| @@ -224,17 +285,20 @@ | ||
| 224 | 285 | ) |
| 225 | 286 | |
| 226 | 287 | def _revert_migration(self, migration: Migration) -> None: |
| 288 | + project_id = self._project_id_for_migration(migration) | |
| 289 | + project_local_id = self._ensure_project_registration(project_id) | |
| 227 | 290 | for statement in self._statements_from_file(migration.down_script): |
| 228 | 291 | self.connection.execute(sa.text(statement)) |
| 229 | 292 | |
| 230 | 293 | self._pending_work.append(f'reverted migration {migration.id}') |
| 231 | 294 | |
| 232 | 295 | self.connection.execute( |
| 233 | - self.migration_table.delete().where(self.migration_table.c.id == migration.id) | |
| 296 | + self.migration_table.delete().where(self._migration_scope_for_id(project_local_id, migration.id)) | |
| 234 | 297 | ) |
| 235 | 298 | |
| 236 | 299 | self.connection.execute( |
| 237 | 300 | self.audit_table.insert().values( |
| 301 | + project_id=project_local_id, | |
| 238 | 302 | migration_id=migration.id, |
| 239 | 303 | action='reverted', |
| 240 | 304 | timestamp=datetime.now(timezone.utc) |
modified tests/test_runner.py +73 −7
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | import tempfile |
| 3 | 3 | from contextlib import nullcontext |
| 4 | 4 | from pathlib import Path |
| 5 | +from types import SimpleNamespace | |
| 5 | 6 | |
| 6 | 7 | import pytest |
| 7 | 8 | import sqlalchemy as sa |
| @@ -37,6 +38,10 @@ | ||
| 37 | 38 | @pytest.fixture |
| 38 | 39 | def runner(connection): |
| 39 | 40 | yield Runner(connection) |
| 41 | + | |
| 42 | + | |
| 43 | +def _project_ref(project_id: str = "tests-runner") -> SimpleNamespace: | |
| 44 | + return SimpleNamespace(id=project_id) | |
| 40 | 45 | |
| 41 | 46 | |
| 42 | 47 | |
| @@ -71,7 +76,7 @@ | ||
| 71 | 76 | |
| 72 | 77 | up_script = tmp_path / "001-create.up.sql" |
| 73 | 78 | up_script.write_text("CREATE TABLE deployed_with_batching (id int);", encoding="utf-8") |
| 74 | - migration = Migration(id="001-create", up_script=up_script) | |
| 79 | + migration = Migration(id="001-create", up_script=up_script, project=_project_ref("deploy-batches")) | |
| 75 | 80 | |
| 76 | 81 | with engine.connect() as connection: |
| 77 | 82 | runner = Runner(connection) |
| @@ -101,7 +106,12 @@ | ||
| 101 | 106 | down_script = tmp_path / "001-create.down.sql" |
| 102 | 107 | up_script.write_text("CREATE TABLE reverted_with_batching (id int);", encoding="utf-8") |
| 103 | 108 | down_script.write_text("DROP TABLE reverted_with_batching;", encoding="utf-8") |
| 104 | - migration = Migration(id="001-create", up_script=up_script, down_script=down_script) | |
| 109 | + migration = Migration( | |
| 110 | + id="001-create", | |
| 111 | + up_script=up_script, | |
| 112 | + down_script=down_script, | |
| 113 | + project=_project_ref("revert-batches"), | |
| 114 | + ) | |
| 105 | 115 | |
| 106 | 116 | with engine.connect() as connection: |
| 107 | 117 | runner = Runner(connection) |
| @@ -124,6 +134,51 @@ | ||
| 124 | 134 | assert table is None |
| 125 | 135 | |
| 126 | 136 | |
| 137 | +def test_runner_scopes_migration_ids_per_project(tmp_path): | |
| 138 | + db_path = tmp_path / "runner-project-scope.db" | |
| 139 | + engine = create_engine(f"sqlite:///{db_path}") | |
| 140 | + | |
| 141 | + migration_path = tmp_path / "001-shared.up.sql" | |
| 142 | + migration_path.write_text("SELECT 1;", encoding="utf-8") | |
| 143 | + migration_a = Migration( | |
| 144 | + id="001-shared", | |
| 145 | + up_script=migration_path, | |
| 146 | + project=SimpleNamespace(id="project-a"), | |
| 147 | + ) | |
| 148 | + migration_b = Migration( | |
| 149 | + id="001-shared", | |
| 150 | + up_script=migration_path, | |
| 151 | + project=SimpleNamespace(id="project-b"), | |
| 152 | + ) | |
| 153 | + | |
| 154 | + with engine.connect() as connection: | |
| 155 | + runner = Runner(connection) | |
| 156 | + runner.deploy_migrations([migration_a]) | |
| 157 | + runner.deploy_migrations([migration_b]) | |
| 158 | + | |
| 159 | + rows = connection.execute( | |
| 160 | + sa.text("SELECT id FROM mitch_migrations WHERE id = '001-shared'") | |
| 161 | + ).fetchall() | |
| 162 | + | |
| 163 | + engine.dispose() | |
| 164 | + | |
| 165 | + assert len(rows) == 2 | |
| 166 | + | |
| 167 | + | |
| 168 | +def test_runner_uses_project_scoped_primary_key(runner): | |
| 169 | + assert runner.project_table.name == "mitch_projects" | |
| 170 | + assert [column.name for column in runner.migration_table.primary_key.columns] == ["project_id", "id"] | |
| 171 | + | |
| 172 | + | |
| 173 | +def test_runner_requires_parent_project_on_migrations(tmp_path, runner): | |
| 174 | + up_script = tmp_path / "001-orphan.up.sql" | |
| 175 | + up_script.write_text("SELECT 1;", encoding="utf-8") | |
| 176 | + orphan = Migration(id="001-orphan", up_script=up_script) | |
| 177 | + | |
| 178 | + with pytest.raises(ValueError): | |
| 179 | + runner.deploy_migrations([orphan]) | |
| 180 | + | |
| 181 | + | |
| 127 | 182 | def test_runner_split_statements_drops_empty(runner): |
| 128 | 183 | statements = list(runner._split_statements("\n-- only a comment\n \n")) |
| 129 | 184 | assert statements == [] |
| @@ -222,17 +277,18 @@ | ||
| 222 | 277 | def test_runner_deployment_status_updates_normalized_hash(cloned_project, runner, connection): |
| 223 | 278 | migration = cloned_project.by_id("001-init") |
| 224 | 279 | runner.apply_migration(migration) |
| 280 | + project_local_id = runner.project_local_id_for(migration.project.id) | |
| 225 | 281 | |
| 226 | 282 | connection.execute( |
| 227 | 283 | runner.migration_table.update() |
| 228 | - .where(runner.migration_table.c.id == migration.id) | |
| 284 | + .where(runner._migration_scope_for_id(project_local_id, migration.id)) | |
| 229 | 285 | .values(normalized_hash="bad-hash") |
| 230 | 286 | ) |
| 231 | 287 | |
| 232 | 288 | assert runner.deployment_status(migration) == "applied" |
| 233 | 289 | |
| 234 | 290 | updated = connection.execute( |
| 235 | - runner.migration_table.select().where(runner.migration_table.c.id == migration.id) | |
| 291 | + runner.migration_table.select().where(runner._migration_scope_for_id(project_local_id, migration.id)) | |
| 236 | 292 | ).first() |
| 237 | 293 | assert updated.normalized_hash != "bad-hash" |
| 238 | 294 | |
| @@ -243,7 +299,12 @@ | ||
| 243 | 299 | up_script.write_text("CREATE TABLE revert_table (id int);", encoding="utf-8") |
| 244 | 300 | down_script.write_text("DROP TABLE revert_table;", encoding="utf-8") |
| 245 | 301 | |
| 246 | - migration = Migration(id="010-create", up_script=up_script, down_script=down_script) | |
| 302 | + migration = Migration( | |
| 303 | + id="010-create", | |
| 304 | + up_script=up_script, | |
| 305 | + down_script=down_script, | |
| 306 | + project=_project_ref("revert-applied"), | |
| 307 | + ) | |
| 247 | 308 | |
| 248 | 309 | runner.apply_migration(migration) |
| 249 | 310 | runner.revert_migration(migration) |
| @@ -254,7 +315,7 @@ | ||
| 254 | 315 | def test_runner_revert_migration_pending_is_noop(tmp_path, runner): |
| 255 | 316 | up_script = tmp_path / "020-noop.up.sql" |
| 256 | 317 | up_script.write_text("CREATE TABLE noop_table (id int);", encoding="utf-8") |
| 257 | - migration = Migration(id="020-noop", up_script=up_script) | |
| 318 | + migration = Migration(id="020-noop", up_script=up_script, project=_project_ref("revert-noop")) | |
| 258 | 319 | |
| 259 | 320 | runner.revert_migration(migration) |
| 260 | 321 | |
| @@ -267,7 +328,12 @@ | ||
| 267 | 328 | up_script.write_text("CREATE TABLE mod_table (id int);", encoding="utf-8") |
| 268 | 329 | down_script.write_text("DROP TABLE mod_table;", encoding="utf-8") |
| 269 | 330 | |
| 270 | - migration = Migration(id="030-modified", up_script=up_script, down_script=down_script) | |
| 331 | + migration = Migration( | |
| 332 | + id="030-modified", | |
| 333 | + up_script=up_script, | |
| 334 | + down_script=down_script, | |
| 335 | + project=_project_ref("revert-modified"), | |
| 336 | + ) | |
| 271 | 337 | runner.apply_migration(migration) |
| 272 | 338 | |
| 273 | 339 | up_script.write_text("CREATE TABLE mod_table (id int, name text);", encoding="utf-8") |