Public repository: timo / mitch

Reader

A migration stitcher (therefore mitch) for PostgreSQL, SQLite, MariaDB, and others

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.
Changeset20354bfd2ef51f47e544b4fbb2066f0b4e9e7888
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parents90b46d696d4a
Children
Pushlog
by timo via ssh

modified src/mitch/cli/log.py +4 −1

@@ -60,8 +60,11 @@
6060
 
6161
     with connection_for(database_url) as connection:
6262
         runner = Runner(connection)
63
+        project_local_id = runner.project_local_id_for(project.id)
6364
         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(
6568
                 runner.migration_table.c.applied_at,
6669
                 runner.migration_table.c.id,
6770
             )

modified src/mitch/cli/status.py +4 −1

@@ -26,7 +26,10 @@
2626
     selected_ids: set[str] | None = None,
2727
 ) -> IntegrityReport:
2828
     # 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
+    )
3033
     if selected_ids is not None:
3134
         query = query.where(runner.migration_table.c.id.in_(selected_ids))
3235
     query = query.order_by(runner.migration_table.c.id)

modified src/mitch/migration.py +5 −0

@@ -1,6 +1,10 @@
11
 from dataclasses import dataclass, field
22
 from datetime import date, datetime
33
 from pathlib import Path
4
+from typing import TYPE_CHECKING
5
+
6
+if TYPE_CHECKING:
7
+    from .project import Project
48
 
59
 
610
 @dataclass(frozen=True)
@@ -17,3 +21,4 @@
1721
 
1822
     dependencies: set[str] = field(compare=False, default_factory=set, repr=False)
1923
     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 @@
7777
                 idempotent=config.get("idempotent", False),
7878
                 created_at=self._created_at_from_config(config.get("created_at"), config_file),
7979
                 dependencies={*config.get("dependencies", [])},
80
+                project=self,
8081
             )
8182
             self.migrations.append(migration)
8283
 

modified src/mitch/runner.py +69 −5

@@ -18,6 +18,7 @@
1818
     def __init__(self, connection: Connection) -> None:
1919
         self._pending_work = []
2020
         self.connection = connection
21
+        self._project_local_ids: dict[str, int] = {}
2122
         sa.event.listen(self.connection, "commit", self._on_commit)
2223
         sa.event.listen(self.connection, "rollback", self._on_rollback)
2324
         
@@ -94,19 +95,29 @@
9495
         else:
9596
             self.metadata = sa.MetaData()
9697
 
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
+
97105
         self.migration_table = sa.Table(
98106
             'migrations' if self.metadata.schema == 'mitch' else 'mitch_migrations',
99107
             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),
101110
             sa.Column('raw_hash', sa.String, nullable=False),
102111
             sa.Column('normalized_hash', sa.String, nullable=False),
103112
             sa.Column('applied_at', sa.DateTime, server_default=sa.func.current_timestamp()),
113
+            sa.PrimaryKeyConstraint('project_id', 'id'),
104114
         )
105115
 
106116
         self.audit_table = sa.Table(
107117
             'migration_audit' if self.metadata.schema == 'mitch' else 'mitch_migration_audit',
108118
             self.metadata,
109119
             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),
110121
             sa.Column('migration_id', sa.String, nullable=False),
111122
             sa.Column('action', sa.String, nullable=False),  # 'applied' or 'reverted'
112123
             sa.Column('timestamp', sa.DateTime, server_default=sa.func.current_timestamp())
@@ -114,6 +125,50 @@
114125
 
115126
         self.metadata.create_all(self.connection, checkfirst=True)
116127
         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
+        )
117172
 
118173
     def _commit_transaction_if_open_but_empty(self) -> None:
119174
         if (
@@ -136,10 +191,12 @@
136191
                 transaction.commit()
137192
 
138193
     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)
139196
         deployment = self.connection.execute(
140197
             self.migration_table
141198
                 .select()
142
-                .where(self.migration_table.c.id == migration.id)
199
+                .where(self._migration_scope_for_id(project_local_id, migration.id))
143200
             ).first()
144201
 
145202
         if deployment is None:
@@ -158,7 +215,7 @@
158215
                 # Update the stored raw_hash to reflect the new formatting.
159216
                 self.connection.execute(
160217
                     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))
162219
                         .values(raw_hash=raw_hash)
163220
                 )
164221
                 return 'applied'
@@ -168,7 +225,7 @@
168225
                 # Update the stored normalized_hash to reflect the new normalization.
169226
                 self.connection.execute(
170227
                     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))
172229
                         .values(normalized_hash=normalized_hash)
173230
                 )
174231
                 return 'applied'
@@ -194,6 +251,8 @@
194251
                 self._revert_migration(migration)
195252
 
196253
     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)
197256
         sql = migration.up_script.read_text(encoding="utf-8")
198257
         statements = list(self._split_statements(sql))
199258
 
@@ -208,6 +267,7 @@
208267
 
209268
         self.connection.execute(
210269
             self.migration_table.insert().values(
270
+                project_id=project_local_id,
211271
                 id=migration.id,
212272
                 raw_hash=raw_hash,
213273
                 normalized_hash=normalized_hash,
@@ -217,6 +277,7 @@
217277
 
218278
         self.connection.execute(
219279
             self.audit_table.insert().values(
280
+                project_id=project_local_id,
220281
                 migration_id=migration.id,
221282
                 action='applied',
222283
                 timestamp=applied_at
@@ -224,17 +285,20 @@
224285
         )
225286
 
226287
     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)
227290
         for statement in self._statements_from_file(migration.down_script):
228291
             self.connection.execute(sa.text(statement))
229292
 
230293
         self._pending_work.append(f'reverted migration {migration.id}')
231294
 
232295
         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))
234297
         )
235298
 
236299
         self.connection.execute(
237300
             self.audit_table.insert().values(
301
+                project_id=project_local_id,
238302
                 migration_id=migration.id,
239303
                 action='reverted',
240304
                 timestamp=datetime.now(timezone.utc)

modified tests/test_runner.py +73 −7

@@ -2,6 +2,7 @@
22
 import tempfile
33
 from contextlib import nullcontext
44
 from pathlib import Path
5
+from types import SimpleNamespace
56
 
67
 import pytest
78
 import sqlalchemy as sa
@@ -37,6 +38,10 @@
3738
 @pytest.fixture
3839
 def runner(connection):
3940
     yield Runner(connection)
41
+
42
+
43
+def _project_ref(project_id: str = "tests-runner") -> SimpleNamespace:
44
+    return SimpleNamespace(id=project_id)
4045
 
4146
 
4247
 
@@ -71,7 +76,7 @@
7176
 
7277
     up_script = tmp_path / "001-create.up.sql"
7378
     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"))
7580
 
7681
     with engine.connect() as connection:
7782
         runner = Runner(connection)
@@ -101,7 +106,12 @@
101106
     down_script = tmp_path / "001-create.down.sql"
102107
     up_script.write_text("CREATE TABLE reverted_with_batching (id int);", encoding="utf-8")
103108
     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
+    )
105115
 
106116
     with engine.connect() as connection:
107117
         runner = Runner(connection)
@@ -124,6 +134,51 @@
124134
     assert table is None
125135
 
126136
 
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
+
127182
 def test_runner_split_statements_drops_empty(runner):
128183
     statements = list(runner._split_statements("\n-- only a comment\n     \n"))
129184
     assert statements == []
@@ -222,17 +277,18 @@
222277
 def test_runner_deployment_status_updates_normalized_hash(cloned_project, runner, connection):
223278
     migration = cloned_project.by_id("001-init")
224279
     runner.apply_migration(migration)
280
+    project_local_id = runner.project_local_id_for(migration.project.id)
225281
 
226282
     connection.execute(
227283
         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))
229285
             .values(normalized_hash="bad-hash")
230286
     )
231287
 
232288
     assert runner.deployment_status(migration) == "applied"
233289
 
234290
     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))
236292
     ).first()
237293
     assert updated.normalized_hash != "bad-hash"
238294
 
@@ -243,7 +299,12 @@
243299
     up_script.write_text("CREATE TABLE revert_table (id int);", encoding="utf-8")
244300
     down_script.write_text("DROP TABLE revert_table;", encoding="utf-8")
245301
 
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
+    )
247308
 
248309
     runner.apply_migration(migration)
249310
     runner.revert_migration(migration)
@@ -254,7 +315,7 @@
254315
 def test_runner_revert_migration_pending_is_noop(tmp_path, runner):
255316
     up_script = tmp_path / "020-noop.up.sql"
256317
     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"))
258319
 
259320
     runner.revert_migration(migration)
260321
 
@@ -267,7 +328,12 @@
267328
     up_script.write_text("CREATE TABLE mod_table (id int);", encoding="utf-8")
268329
     down_script.write_text("DROP TABLE mod_table;", encoding="utf-8")
269330
 
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
+    )
271337
     runner.apply_migration(migration)
272338
 
273339
     up_script.write_text("CREATE TABLE mod_table (id int, name text);", encoding="utf-8")