| 1 | import shutil |
| 2 | import tempfile |
| 3 | from contextlib import nullcontext |
| 4 | from pathlib import Path |
| 5 | from types import SimpleNamespace |
| 6 | |
| 7 | import pytest |
| 8 | import sqlalchemy as sa |
| 9 | from sqlalchemy import create_engine |
| 10 | |
| 11 | from mitch.helpers import batch_transactional_migrations |
| 12 | from mitch.migration import Migration |
| 13 | from mitch.project import Project |
| 14 | from mitch.runner import Runner |
| 15 | |
| 16 | |
| 17 | @pytest.fixture |
| 18 | def project(): |
| 19 | yield Project.from_path(Path("tests/migrations")) |
| 20 | |
| 21 | |
| 22 | @pytest.fixture |
| 23 | def cloned_project(tmp_path): |
| 24 | source = Path("tests/migrations") |
| 25 | dest = tmp_path / "migrations" |
| 26 | shutil.copytree(source, dest) |
| 27 | yield Project.from_path(dest) |
| 28 | |
| 29 | |
| 30 | @pytest.fixture |
| 31 | def connection(): |
| 32 | engine = create_engine("sqlite:///:memory:", isolation_level="AUTOCOMMIT") |
| 33 | with engine.connect() as conn: |
| 34 | yield conn |
| 35 | engine.dispose() |
| 36 | |
| 37 | |
| 38 | @pytest.fixture |
| 39 | def runner(connection): |
| 40 | yield Runner(connection) |
| 41 | |
| 42 | |
| 43 | def _project_ref(project_id: str = "tests-runner") -> SimpleNamespace: |
| 44 | return SimpleNamespace(id=project_id) |
| 45 | |
| 46 | |
| 47 | |
| 48 | def test_runner_apply_migration(project, runner, connection): |
| 49 | due_migrations = list(project.by_ids_with_dependencies(["001-init"])) |
| 50 | |
| 51 | # Check that the migrations are marked as applied |
| 52 | for migration in due_migrations: |
| 53 | assert 'pending' == runner.deployment_status(migration) |
| 54 | |
| 55 | # Apply migrations |
| 56 | for transactional, migrations in batch_transactional_migrations(due_migrations): |
| 57 | with runner.transaction() if transactional else nullcontext(): |
| 58 | runner.autocommit = not transactional |
| 59 | for migration in migrations: |
| 60 | runner.apply_migration(migration) |
| 61 | |
| 62 | # Check that the migrations are marked as applied |
| 63 | for migration in due_migrations: |
| 64 | assert 'applied' == runner.deployment_status(migration) |
| 65 | |
| 66 | # Check if some_table exists |
| 67 | result = connection.execute(sa.text("SELECT name FROM sqlite_schema WHERE type='table' AND name='some_table'")) |
| 68 | table = result.fetchone() |
| 69 | assert table is not None |
| 70 | assert table[0] == 'some_table' |
| 71 | |
| 72 | |
| 73 | def test_runner_deploy_migrations_batches_and_commits(tmp_path): |
| 74 | db_path = tmp_path / "runner-deploy.db" |
| 75 | engine = create_engine(f"sqlite:///{db_path}") |
| 76 | |
| 77 | up_script = tmp_path / "001-create.up.sql" |
| 78 | up_script.write_text("CREATE TABLE deployed_with_batching (id int);", encoding="utf-8") |
| 79 | migration = Migration(id="001-create", up_script=up_script, project=_project_ref("deploy-batches")) |
| 80 | |
| 81 | with engine.connect() as connection: |
| 82 | runner = Runner(connection) |
| 83 | runner.deploy_migrations([migration]) |
| 84 | |
| 85 | with engine.connect() as connection: |
| 86 | row = connection.execute( |
| 87 | sa.text("SELECT id FROM mitch_migrations WHERE id = '001-create'") |
| 88 | ).first() |
| 89 | table = connection.execute( |
| 90 | sa.text( |
| 91 | "SELECT name FROM sqlite_schema WHERE type='table' AND name='deployed_with_batching'" |
| 92 | ) |
| 93 | ).first() |
| 94 | |
| 95 | engine.dispose() |
| 96 | |
| 97 | assert row is not None |
| 98 | assert table is not None |
| 99 | |
| 100 | |
| 101 | def test_runner_revert_migrations_batches_and_commits(tmp_path): |
| 102 | db_path = tmp_path / "runner-revert.db" |
| 103 | engine = create_engine(f"sqlite:///{db_path}") |
| 104 | |
| 105 | up_script = tmp_path / "001-create.up.sql" |
| 106 | down_script = tmp_path / "001-create.down.sql" |
| 107 | up_script.write_text("CREATE TABLE reverted_with_batching (id int);", encoding="utf-8") |
| 108 | down_script.write_text("DROP TABLE reverted_with_batching;", encoding="utf-8") |
| 109 | migration = Migration( |
| 110 | id="001-create", |
| 111 | up_script=up_script, |
| 112 | down_script=down_script, |
| 113 | project=_project_ref("revert-batches"), |
| 114 | ) |
| 115 | |
| 116 | with engine.connect() as connection: |
| 117 | runner = Runner(connection) |
| 118 | runner.deploy_migrations([migration]) |
| 119 | runner.revert_migrations([migration]) |
| 120 | |
| 121 | with engine.connect() as connection: |
| 122 | row = connection.execute( |
| 123 | sa.text("SELECT id FROM mitch_migrations WHERE id = '001-create'") |
| 124 | ).first() |
| 125 | table = connection.execute( |
| 126 | sa.text( |
| 127 | "SELECT name FROM sqlite_schema WHERE type='table' AND name='reverted_with_batching'" |
| 128 | ) |
| 129 | ).first() |
| 130 | |
| 131 | engine.dispose() |
| 132 | |
| 133 | assert row is None |
| 134 | assert table is None |
| 135 | |
| 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 | |
| 182 | def test_runner_split_statements_drops_empty(runner): |
| 183 | statements = list(runner._split_statements("\n-- only a comment\n \n")) |
| 184 | assert statements == [] |
| 185 | |
| 186 | |
| 187 | def test_setup_project_copies_migrations_isolated(cloned_project): |
| 188 | original_sql = Path("tests/migrations/001-init.up.sql").read_text(encoding="utf-8") |
| 189 | |
| 190 | assert cloned_project.path.is_relative_to(Path(tempfile.gettempdir())) |
| 191 | migration = cloned_project.by_id("001-init") |
| 192 | modified_sql = original_sql + "\n-- mutated during test\n" |
| 193 | migration.up_script.write_text(modified_sql, encoding="utf-8") |
| 194 | assert migration.up_script.read_text(encoding="utf-8") == modified_sql |
| 195 | |
| 196 | unchanged_sql = Path("tests/migrations/001-init.up.sql").read_text(encoding="utf-8") |
| 197 | assert unchanged_sql == original_sql |
| 198 | |
| 199 | |
| 200 | def test_runner_reapply_modified_migration_raises(cloned_project, runner): |
| 201 | migration = cloned_project.by_id("001-init") |
| 202 | runner.apply_migration(migration) |
| 203 | |
| 204 | modified_sql = ( |
| 205 | migration.up_script.read_text(encoding="utf-8") |
| 206 | + "\nALTER TABLE some_table ADD COLUMN extra_col INTEGER;\n" |
| 207 | ) |
| 208 | migration.up_script.write_text(modified_sql, encoding="utf-8") |
| 209 | |
| 210 | with pytest.raises(RuntimeError): |
| 211 | runner.apply_migration(migration) |
| 212 | |
| 213 | |
| 214 | def test_runner_reapply_with_only_comments_or_whitespace_is_ok(cloned_project, runner): |
| 215 | migration = cloned_project.by_id("001-init") |
| 216 | runner.apply_migration(migration) |
| 217 | |
| 218 | original_sql = migration.up_script.read_text(encoding="utf-8") |
| 219 | modified_sql = original_sql + "\n\n-- harmless comment\n\n" |
| 220 | migration.up_script.write_text(modified_sql, encoding="utf-8") |
| 221 | |
| 222 | assert runner.deployment_status(migration) == "applied" |
| 223 | runner.apply_migration(migration) |
| 224 | |
| 225 | |
| 226 | def test_runner_autocommit_toggles_isolation_level(): |
| 227 | class StubConnection: |
| 228 | def __init__(self): |
| 229 | self.default_isolation_level = "SERIALIZABLE" |
| 230 | self._isolation_level = self.default_isolation_level |
| 231 | self._in_tx = False |
| 232 | self._in_nested = False |
| 233 | |
| 234 | def get_isolation_level(self): |
| 235 | return self._isolation_level |
| 236 | |
| 237 | def execution_options(self, isolation_level): |
| 238 | self._isolation_level = isolation_level |
| 239 | return self |
| 240 | |
| 241 | def in_transaction(self): |
| 242 | return self._in_tx |
| 243 | |
| 244 | def in_nested_transaction(self): |
| 245 | return self._in_nested |
| 246 | |
| 247 | def commit(self): |
| 248 | return None |
| 249 | |
| 250 | runner = Runner.__new__(Runner) |
| 251 | runner.connection = StubConnection() |
| 252 | runner._pending_work = [] |
| 253 | |
| 254 | assert runner.autocommit is False |
| 255 | runner.autocommit = True |
| 256 | assert runner.autocommit is True |
| 257 | runner.autocommit = False |
| 258 | assert runner.autocommit is False |
| 259 | |
| 260 | |
| 261 | def test_runner_statements_from_file_requires_existing_path(tmp_path, runner): |
| 262 | missing = tmp_path / "missing.sql" |
| 263 | with pytest.raises(FileExistsError): |
| 264 | list(runner._statements_from_file(missing)) |
| 265 | |
| 266 | sql_file = tmp_path / "valid.sql" |
| 267 | sql_file.write_text("SELECT 1; -- comment\n\n", encoding="utf-8") |
| 268 | assert list(runner._statements_from_file(sql_file)) == ["select 1"] |
| 269 | |
| 270 | |
| 271 | def test_runner_transaction_rolls_back_on_error(runner): |
| 272 | with pytest.raises(RuntimeError): |
| 273 | with runner.transaction(): |
| 274 | raise RuntimeError("boom") |
| 275 | |
| 276 | |
| 277 | def test_runner_deployment_status_updates_normalized_hash(cloned_project, runner, connection): |
| 278 | migration = cloned_project.by_id("001-init") |
| 279 | runner.apply_migration(migration) |
| 280 | project_local_id = runner.project_local_id_for(migration.project.id) |
| 281 | |
| 282 | connection.execute( |
| 283 | runner.migration_table.update() |
| 284 | .where(runner._migration_scope_for_id(project_local_id, migration.id)) |
| 285 | .values(normalized_hash="bad-hash") |
| 286 | ) |
| 287 | |
| 288 | assert runner.deployment_status(migration) == "applied" |
| 289 | |
| 290 | updated = connection.execute( |
| 291 | runner.migration_table.select().where(runner._migration_scope_for_id(project_local_id, migration.id)) |
| 292 | ).first() |
| 293 | assert updated.normalized_hash != "bad-hash" |
| 294 | |
| 295 | |
| 296 | def test_runner_revert_migration_applied(tmp_path, runner): |
| 297 | up_script = tmp_path / "010-create.up.sql" |
| 298 | down_script = tmp_path / "010-create.down.sql" |
| 299 | up_script.write_text("CREATE TABLE revert_table (id int);", encoding="utf-8") |
| 300 | down_script.write_text("DROP TABLE revert_table;", encoding="utf-8") |
| 301 | |
| 302 | migration = Migration( |
| 303 | id="010-create", |
| 304 | up_script=up_script, |
| 305 | down_script=down_script, |
| 306 | project=_project_ref("revert-applied"), |
| 307 | ) |
| 308 | |
| 309 | runner.apply_migration(migration) |
| 310 | runner.revert_migration(migration) |
| 311 | |
| 312 | assert runner.deployment_status(migration) == "pending" |
| 313 | |
| 314 | |
| 315 | def test_runner_revert_migration_pending_is_noop(tmp_path, runner): |
| 316 | up_script = tmp_path / "020-noop.up.sql" |
| 317 | up_script.write_text("CREATE TABLE noop_table (id int);", encoding="utf-8") |
| 318 | migration = Migration(id="020-noop", up_script=up_script, project=_project_ref("revert-noop")) |
| 319 | |
| 320 | runner.revert_migration(migration) |
| 321 | |
| 322 | assert runner.deployment_status(migration) == "pending" |
| 323 | |
| 324 | |
| 325 | def test_runner_revert_migration_modified(tmp_path, runner): |
| 326 | up_script = tmp_path / "030-modified.up.sql" |
| 327 | down_script = tmp_path / "030-modified.down.sql" |
| 328 | up_script.write_text("CREATE TABLE mod_table (id int);", encoding="utf-8") |
| 329 | down_script.write_text("DROP TABLE mod_table;", encoding="utf-8") |
| 330 | |
| 331 | migration = Migration( |
| 332 | id="030-modified", |
| 333 | up_script=up_script, |
| 334 | down_script=down_script, |
| 335 | project=_project_ref("revert-modified"), |
| 336 | ) |
| 337 | runner.apply_migration(migration) |
| 338 | |
| 339 | up_script.write_text("CREATE TABLE mod_table (id int, name text);", encoding="utf-8") |
| 340 | assert runner.deployment_status(migration) == "modified" |
| 341 | |
| 342 | runner.revert_migration(migration) |
| 343 | |
| 344 | assert runner.deployment_status(migration) == "pending" |
| 345 | |
| 346 | |
| 347 | def test_runner_apply_migration_ignores_unknown_status(monkeypatch, runner): |
| 348 | migration = Migration(id="999-unknown", up_script=Path("999-unknown.up.sql")) |
| 349 | monkeypatch.setattr(runner, "deployment_status", lambda _migration: "unknown") |
| 350 | |
| 351 | runner.apply_migration(migration) |
| 352 | |
| 353 | |
| 354 | def test_runner_revert_migration_ignores_unknown_status(monkeypatch, runner): |
| 355 | migration = Migration(id="998-unknown", up_script=Path("998-unknown.up.sql")) |
| 356 | monkeypatch.setattr(runner, "deployment_status", lambda _migration: "unknown") |
| 357 | |
| 358 | runner.revert_migration(migration) |
| 359 | |
| 360 | |
| 361 | def test_runner_ensure_migration_tables_with_schema_support(monkeypatch): |
| 362 | class FakeDialect: |
| 363 | supports_schemas = True |
| 364 | name = "postgresql" |
| 365 | |
| 366 | def has_schema(self, _connection, _schema_name): |
| 367 | return False |
| 368 | |
| 369 | class FakeConnection: |
| 370 | def __init__(self): |
| 371 | self.dialect = FakeDialect() |
| 372 | self.executed = [] |
| 373 | |
| 374 | def execute(self, statement): |
| 375 | self.executed.append(str(statement)) |
| 376 | return None |
| 377 | |
| 378 | runner = Runner.__new__(Runner) |
| 379 | runner.connection = FakeConnection() |
| 380 | runner._pending_work = [] |
| 381 | |
| 382 | monkeypatch.setattr(sa.MetaData, "create_all", lambda self, conn, checkfirst=True: None) |
| 383 | |
| 384 | runner._ensure_migration_tables() |
| 385 | |
| 386 | assert runner.metadata.schema == "mitch" |
| 387 | assert "CREATE SCHEMA mitch" in runner.connection.executed[0] |
| 388 | |
| 389 | |
| 390 | def test_runner_ensure_migration_tables_schema_already_exists(monkeypatch): |
| 391 | class FakeDialect: |
| 392 | supports_schemas = True |
| 393 | name = "postgresql" |
| 394 | |
| 395 | def has_schema(self, _connection, _schema_name): |
| 396 | return True |
| 397 | |
| 398 | class FakeConnection: |
| 399 | def __init__(self): |
| 400 | self.dialect = FakeDialect() |
| 401 | self.executed = [] |
| 402 | |
| 403 | def execute(self, statement): |
| 404 | self.executed.append(str(statement)) |
| 405 | return None |
| 406 | |
| 407 | runner = Runner.__new__(Runner) |
| 408 | runner.connection = FakeConnection() |
| 409 | runner._pending_work = [] |
| 410 | |
| 411 | monkeypatch.setattr(sa.MetaData, "create_all", lambda self, conn, checkfirst=True: None) |
| 412 | |
| 413 | runner._ensure_migration_tables() |
| 414 | |
| 415 | assert runner.metadata.schema == "mitch" |
| 416 | assert runner.connection.executed == [] |