# SPDX-License-Identifier: AGPL-3.0-or-later """Update-Ablauf gegen eine echte PostgreSQL-Datenbank (nur in der CI).""" from __future__ import annotations import shutil from pathlib import Path import pytest pytest.importorskip("alembic") from sqlalchemy import text from surveybox import db from surveybox.settings import Settings from surveybox.upgrade import ( MIGRATION_LOCK_KEY, MIGRATIONS_DIR, UpgradeError, current_revision, head_revision, run_upgrade, ) pytestmark = pytest.mark.db MIGRATION_OK = ''' import sqlalchemy as sa from alembic import op revision = "9001_test_ok" down_revision = "{down}" branch_labels = None depends_on = None def upgrade() -> None: op.create_table("test_ok", sa.Column("id", sa.Integer(), primary_key=True)) op.execute("INSERT INTO test_ok (id) VALUES (1)") def downgrade() -> None: op.drop_table("test_ok") ''' MIGRATION_BROKEN = ''' import sqlalchemy as sa from alembic import op revision = "9002_test_broken" down_revision = "9001_test_ok" branch_labels = None depends_on = None def upgrade() -> None: op.create_table("test_half", sa.Column("id", sa.Integer(), primary_key=True)) op.add_column("test_ok", sa.Column("extra", sa.Text())) op.execute("SELECT * FROM gibt_es_nicht") # schlägt fehl def downgrade() -> None: pass ''' def _script_dir(tmp_path: Path, *extra: str) -> Path: target = tmp_path / "migrations" shutil.copytree(MIGRATIONS_DIR, target, ignore=shutil.ignore_patterns("__pycache__")) real_head = head_revision() for i, body in enumerate(extra): (target / "versions" / f"9{i:03d}_test.py").write_text(body.replace("{down}", real_head)) return target def _table_exists(name: str) -> bool: with db.get_engine().connect() as conn: return bool(conn.execute(text("SELECT to_regclass(:n) IS NOT NULL"), {"n": name}).scalar()) def test_fresh_install_then_current(db_settings: Settings) -> None: engine = db.get_engine() first = run_upgrade(db_settings, engine) assert first.action == "installed" assert first.backup_file is None assert _table_exists("app_setting") and _table_exists("job_state") second = run_upgrade(db_settings, engine) assert second.action == "current" def test_upgrade_makes_backup_and_failed_upgrade_changes_nothing( db_settings: Settings, tmp_path: Path ) -> None: engine = db.get_engine() run_upgrade(db_settings, engine) ok_dir = _script_dir(tmp_path / "a", MIGRATION_OK) result = run_upgrade(db_settings, engine, ok_dir) assert result.action == "upgraded" assert result.backup_file is not None and result.backup_file.is_file() assert "pre-upgrade" in result.backup_file.name broken_dir = _script_dir(tmp_path / "b", MIGRATION_OK, MIGRATION_BROKEN) with pytest.raises(UpgradeError, match="zurückgerollt"): run_upgrade(db_settings, engine, broken_dir) assert not _table_exists("test_half") with engine.connect() as conn: assert current_revision(conn) == "9001_test_ok" columns = conn.execute( text( "SELECT column_name FROM information_schema.columns " "WHERE table_schema = 'surveybox' AND table_name = 'test_ok'" ) ).scalars().all() assert "extra" not in columns def test_refuses_newer_database(db_settings: Settings) -> None: engine = db.get_engine() run_upgrade(db_settings, engine) with engine.begin() as conn: conn.execute(text("UPDATE alembic_version SET version_num = '9999_from_the_future'")) with pytest.raises(UpgradeError, match="nicht kennt"): run_upgrade(db_settings, engine) def test_refuses_foreign_tables(db_settings: Settings) -> None: engine = db.get_engine() with engine.begin() as conn: conn.execute(text(f"CREATE SCHEMA {db.DB_SCHEMA}")) conn.execute(text(f"CREATE TABLE {db.DB_SCHEMA}.fremd (x int)")) with pytest.raises(UpgradeError, match="keine Versionsangabe"): run_upgrade(db_settings, engine) def test_waits_for_migration_lock(db_settings: Settings) -> None: engine = db.get_engine() impatient = db_settings.model_copy(update={"migration_lock_timeout": 1}) with engine.connect() as holder: holder.execute(text("SELECT pg_advisory_lock(:k)"), {"k": MIGRATION_LOCK_KEY}) with pytest.raises(UpgradeError, match="Migrationssperre"): run_upgrade(impatient, engine) holder.execute(text("SELECT pg_advisory_unlock(:k)"), {"k": MIGRATION_LOCK_KEY}) assert run_upgrade(db_settings, engine).action == "installed" def test_migrations_match_models(db_settings: Settings) -> None: """Die Migrationen erzeugen genau das Schema, das die Modelle beschreiben.""" from alembic.autogenerate import compare_metadata from alembic.migration import MigrationContext from surveybox.models import Base engine = db.get_engine() run_upgrade(db_settings, engine) with engine.connect() as conn: context = MigrationContext.configure( conn, opts={ "include_schemas": False, "compare_type": True, "compare_server_default": False, }, ) diff = compare_metadata(context, Base.metadata) assert diff == [], diff