|
| 1 | +"""Versioned schema migrations for JustWiki. |
| 2 | +
|
| 3 | +Why not Alembic: JustWiki's core pitch is "single SQLite file, no external |
| 4 | +deps." Alembic would add a CLI, a versions/ directory, an alembic.ini, and a |
| 5 | +separate `alembic upgrade head` step in every deploy — extra weight that buys |
| 6 | +us very little on a schema this small. Instead we keep the work in-process: |
| 7 | +migrations are plain async functions in this module, identified by a |
| 8 | +monotonically increasing integer version, recorded in `schema_migrations`, |
| 9 | +and run once on startup by init_db(). |
| 10 | +
|
| 11 | +Ground rules: |
| 12 | + * Append-only. Never renumber or rewrite a shipped migration — existing |
| 13 | + deployments have already recorded the version. |
| 14 | + * Each migration must be idempotent at the SQL level (IF NOT EXISTS, column |
| 15 | + probes, etc.) so partial re-runs are safe if a crash happens mid-run. |
| 16 | + * Use `run_migrations` as the single entry point. It returns the list of |
| 17 | + versions applied in this invocation; callers can use that signal to |
| 18 | + decide whether expensive follow-up work (full-text rebuild etc.) is |
| 19 | + needed. |
| 20 | +""" |
| 21 | +import logging |
| 22 | +from typing import Awaitable, Callable |
| 23 | + |
| 24 | +import aiosqlite |
| 25 | + |
| 26 | +logger = logging.getLogger(__name__) |
| 27 | + |
| 28 | +MigrationFn = Callable[[aiosqlite.Connection], Awaitable[None]] |
| 29 | +Migration = tuple[int, str, MigrationFn] |
| 30 | + |
| 31 | + |
| 32 | +async def _column_exists(db: aiosqlite.Connection, table: str, col: str) -> bool: |
| 33 | + rows = await db.execute_fetchall(f"PRAGMA table_info({table})") |
| 34 | + return any(r["name"] == col for r in rows) |
| 35 | + |
| 36 | + |
| 37 | +# ── Migration functions ──────────────────────────────────────────────────── |
| 38 | +# New migrations go at the bottom. Never renumber or edit a shipped migration. |
| 39 | + |
| 40 | + |
| 41 | +async def _m001_user_profile_columns(db: aiosqlite.Connection) -> None: |
| 42 | + if not await _column_exists(db, "users", "display_name"): |
| 43 | + await db.execute("ALTER TABLE users ADD COLUMN display_name TEXT DEFAULT ''") |
| 44 | + if not await _column_exists(db, "users", "email"): |
| 45 | + await db.execute("ALTER TABLE users ADD COLUMN email TEXT DEFAULT ''") |
| 46 | + |
| 47 | + |
| 48 | +async def _m002_user_soft_delete(db: aiosqlite.Connection) -> None: |
| 49 | + if not await _column_exists(db, "users", "deleted_at"): |
| 50 | + await db.execute("ALTER TABLE users ADD COLUMN deleted_at TIMESTAMP") |
| 51 | + if not await _column_exists(db, "users", "original_username"): |
| 52 | + await db.execute("ALTER TABLE users ADD COLUMN original_username TEXT") |
| 53 | + |
| 54 | + |
| 55 | +async def _m003_page_version_counter(db: aiosqlite.Connection) -> None: |
| 56 | + if not await _column_exists(db, "pages", "version"): |
| 57 | + await db.execute( |
| 58 | + "ALTER TABLE pages ADD COLUMN version INTEGER NOT NULL DEFAULT 1" |
| 59 | + ) |
| 60 | + |
| 61 | + |
| 62 | +async def _m004_page_soft_delete(db: aiosqlite.Connection) -> None: |
| 63 | + if not await _column_exists(db, "pages", "deleted_at"): |
| 64 | + await db.execute("ALTER TABLE pages ADD COLUMN deleted_at TIMESTAMP") |
| 65 | + |
| 66 | + |
| 67 | +async def _m005_page_is_public(db: aiosqlite.Connection) -> None: |
| 68 | + if not await _column_exists(db, "pages", "is_public"): |
| 69 | + await db.execute( |
| 70 | + "ALTER TABLE pages ADD COLUMN is_public INTEGER NOT NULL DEFAULT 0" |
| 71 | + ) |
| 72 | + |
| 73 | + |
| 74 | +MIGRATIONS: list[Migration] = [ |
| 75 | + (1, "user_profile_columns", _m001_user_profile_columns), |
| 76 | + (2, "user_soft_delete", _m002_user_soft_delete), |
| 77 | + (3, "page_version_counter", _m003_page_version_counter), |
| 78 | + (4, "page_soft_delete", _m004_page_soft_delete), |
| 79 | + (5, "page_is_public", _m005_page_is_public), |
| 80 | +] |
| 81 | + |
| 82 | + |
| 83 | +# ── Post-migration index invariants ──────────────────────────────────────── |
| 84 | +# These indexes reference columns added by migrations, so they can't live in |
| 85 | +# SCHEMA_SQL (which runs first and would hit "no such column" on an upgrade). |
| 86 | +# They can't live in the migration bodies either: when a fresh DB boots, |
| 87 | +# every migration is detected as pre-applied and skipped, so an index baked |
| 88 | +# into a migration body would never run. Treating them as always-ensure |
| 89 | +# invariants after migrations is idempotent and covers both paths. |
| 90 | +_INDEX_INVARIANTS = ( |
| 91 | + "CREATE INDEX IF NOT EXISTS idx_users_deleted ON users(deleted_at)", |
| 92 | + "CREATE INDEX IF NOT EXISTS idx_pages_deleted ON pages(deleted_at)", |
| 93 | + "CREATE INDEX IF NOT EXISTS idx_pages_public ON pages(slug) WHERE is_public = 1", |
| 94 | +) |
| 95 | + |
| 96 | + |
| 97 | +async def _ensure_indexes(db: aiosqlite.Connection) -> None: |
| 98 | + for stmt in _INDEX_INVARIANTS: |
| 99 | + await db.execute(stmt) |
| 100 | + await db.commit() |
| 101 | + |
| 102 | + |
| 103 | +# ── Runner ───────────────────────────────────────────────────────────────── |
| 104 | + |
| 105 | + |
| 106 | +async def _ensure_ledger(db: aiosqlite.Connection) -> None: |
| 107 | + await db.execute( |
| 108 | + """ |
| 109 | + CREATE TABLE IF NOT EXISTS schema_migrations ( |
| 110 | + version INTEGER PRIMARY KEY, |
| 111 | + name TEXT NOT NULL, |
| 112 | + applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP |
| 113 | + ) |
| 114 | + """ |
| 115 | + ) |
| 116 | + await db.commit() |
| 117 | + |
| 118 | + |
| 119 | +async def _applied_versions(db: aiosqlite.Connection) -> set[int]: |
| 120 | + rows = await db.execute_fetchall("SELECT version FROM schema_migrations") |
| 121 | + return {r["version"] for r in rows} |
| 122 | + |
| 123 | + |
| 124 | +async def _detect_preexisting(db: aiosqlite.Connection) -> set[int]: |
| 125 | + """Infer which shipped migrations are already effectively applied. |
| 126 | +
|
| 127 | + Needed for databases created before this module existed: the schema may |
| 128 | + already carry columns added by earlier in-place ALTERs. Backfilling the |
| 129 | + ledger here keeps the upgrade silent — no re-running of idempotent DDL, |
| 130 | + no spurious log lines about "applying migration v3". |
| 131 | +
|
| 132 | + Only probes for artifacts the migration actually creates; anything more |
| 133 | + ambitious (row counts, index options) gets fragile fast. |
| 134 | + """ |
| 135 | + applied: set[int] = set() |
| 136 | + if await _column_exists(db, "users", "display_name") and await _column_exists( |
| 137 | + db, "users", "email" |
| 138 | + ): |
| 139 | + applied.add(1) |
| 140 | + if await _column_exists(db, "users", "deleted_at") and await _column_exists( |
| 141 | + db, "users", "original_username" |
| 142 | + ): |
| 143 | + applied.add(2) |
| 144 | + if await _column_exists(db, "pages", "version"): |
| 145 | + applied.add(3) |
| 146 | + if await _column_exists(db, "pages", "deleted_at"): |
| 147 | + applied.add(4) |
| 148 | + if await _column_exists(db, "pages", "is_public"): |
| 149 | + applied.add(5) |
| 150 | + return applied |
| 151 | + |
| 152 | + |
| 153 | +async def run_migrations(db: aiosqlite.Connection) -> list[int]: |
| 154 | + """Apply any pending migrations. Returns the versions applied this run. |
| 155 | +
|
| 156 | + Also ensures schema-invariant indexes (see `_INDEX_INVARIANTS`) regardless |
| 157 | + of whether any migration ran, so fresh DBs get them too. |
| 158 | + """ |
| 159 | + await _ensure_ledger(db) |
| 160 | + |
| 161 | + applied = await _applied_versions(db) |
| 162 | + # First run against a pre-existing DB: backfill the ledger from what's |
| 163 | + # observable in the schema, so we don't re-announce "applying v1…v5". |
| 164 | + if not applied: |
| 165 | + inferred = await _detect_preexisting(db) |
| 166 | + for v in sorted(inferred): |
| 167 | + name = next((n for (ver, n, _) in MIGRATIONS if ver == v), f"legacy_{v}") |
| 168 | + await db.execute( |
| 169 | + "INSERT OR IGNORE INTO schema_migrations (version, name) VALUES (?, ?)", |
| 170 | + (v, name), |
| 171 | + ) |
| 172 | + if inferred: |
| 173 | + await db.commit() |
| 174 | + applied = inferred |
| 175 | + |
| 176 | + just_applied: list[int] = [] |
| 177 | + for version, name, fn in MIGRATIONS: |
| 178 | + if version in applied: |
| 179 | + continue |
| 180 | + logger.info("Applying schema migration %03d: %s", version, name) |
| 181 | + try: |
| 182 | + await fn(db) |
| 183 | + await db.execute( |
| 184 | + "INSERT INTO schema_migrations (version, name) VALUES (?, ?)", |
| 185 | + (version, name), |
| 186 | + ) |
| 187 | + await db.commit() |
| 188 | + except Exception: |
| 189 | + # Leave the half-applied state on disk so an operator can inspect |
| 190 | + # it. The next startup will retry from this same migration. |
| 191 | + logger.exception("Schema migration %03d (%s) failed", version, name) |
| 192 | + raise |
| 193 | + just_applied.append(version) |
| 194 | + |
| 195 | + await _ensure_indexes(db) |
| 196 | + return just_applied |
0 commit comments