|
| 1 | +"""Versioned schema migrations over ``PRAGMA user_version`` (plan v2.4 |
| 2 | +Phase 2; section 6 "versioned SQL migrations", section 11 ``schema.sql``). |
| 3 | +
|
| 4 | +Mechanism - deterministic, repeatable, auditable: |
| 5 | +
|
| 6 | +- The DDL for schema v1 lives in ``schema.sql`` next to this module (the |
| 7 | + file name the plan's directory structure specifies) and is registered as |
| 8 | + migration v1. Future migrations append to :data:`MIGRATIONS` in version |
| 9 | + order; nothing is ever edited in place. |
| 10 | +- ``PRAGMA user_version`` is the single version marker. It is written |
| 11 | + **inside the same transaction** as its migration's DDL, so version and |
| 12 | + schema can never disagree after a failure. |
| 13 | +- Each migration executes as one explicit ``BEGIN IMMEDIATE ... COMMIT`` |
| 14 | + script (autocommit connection, no implicit transactions). Any statement |
| 15 | + failure rolls the whole migration back: ``user_version`` is unchanged and |
| 16 | + no partial objects remain (:class:`MigrationError`). |
| 17 | +- A database whose ``user_version`` exceeds the supported set fails loudly |
| 18 | + with :class:`UnsupportedSchemaVersionError` - never a destructive reset, |
| 19 | + never a silent downgrade (Phase 2 task sections 3.5/3.6). |
| 20 | +- Running :func:`initialize` on an up-to-date database is a no-op |
| 21 | + (idempotent); a registry that is not contiguous from v1 is rejected before |
| 22 | + a single statement runs (invalid migration state). |
| 23 | +- Partial/half-initialized files (schema objects present while |
| 24 | + ``user_version`` is still 0) fail loudly: baseline DDL uses plain |
| 25 | + ``CREATE`` statements, so conflicts surface as :class:`MigrationError` |
| 26 | + instead of silently adopting unknown state. |
| 27 | +
|
| 28 | +Migration SQL is trusted code (reviewed, committed): it must not contain |
| 29 | +transaction-control statements - the runner owns BEGIN/COMMIT/ROLLBACK. |
| 30 | +""" |
| 31 | + |
| 32 | +from __future__ import annotations |
| 33 | + |
| 34 | +import sqlite3 |
| 35 | +from collections.abc import Sequence |
| 36 | +from dataclasses import dataclass |
| 37 | +from pathlib import Path |
| 38 | + |
| 39 | +from rag_platform.db.sqlite import StorageError, open_db |
| 40 | + |
| 41 | + |
| 42 | +class MigrationError(StorageError): |
| 43 | + """A migration failed (and was rolled back) or the registry is invalid.""" |
| 44 | + |
| 45 | + |
| 46 | +class UnsupportedSchemaVersionError(MigrationError): |
| 47 | + """The database reports a schema version newer than this code supports.""" |
| 48 | + |
| 49 | + |
| 50 | +@dataclass(frozen=True) |
| 51 | +class Migration: |
| 52 | + """One schema migration: strictly increasing versions starting at 1.""" |
| 53 | + |
| 54 | + version: int |
| 55 | + name: str |
| 56 | + sql: str |
| 57 | + |
| 58 | + |
| 59 | +_SCHEMA_SQL_PATH = Path(__file__).with_name("schema.sql") |
| 60 | + |
| 61 | + |
| 62 | +def _load_baseline_sql() -> str: |
| 63 | + sql = _SCHEMA_SQL_PATH.read_text(encoding="utf-8") |
| 64 | + if not sql.strip(): |
| 65 | + raise MigrationError(f"baseline schema file is empty: {_SCHEMA_SQL_PATH}") |
| 66 | + return sql |
| 67 | + |
| 68 | + |
| 69 | +#: The registry this code supports. v1 is the Phase 2 baseline. |
| 70 | +MIGRATIONS: tuple[Migration, ...] = ( |
| 71 | + Migration(1, "baseline_schema", _load_baseline_sql()), |
| 72 | +) |
| 73 | + |
| 74 | +#: Version of the newest migration in :data:`MIGRATIONS`. |
| 75 | +SCHEMA_VERSION = MIGRATIONS[-1].version |
| 76 | + |
| 77 | + |
| 78 | +def _validate_registry(registry: Sequence[Migration]) -> None: |
| 79 | + if not registry: |
| 80 | + raise MigrationError("migration registry is empty") |
| 81 | + for expected, migration in enumerate(registry, start=1): |
| 82 | + if migration.version != expected: |
| 83 | + raise MigrationError( |
| 84 | + "migration registry must be contiguous from v1; " |
| 85 | + f"expected v{expected}, got v{migration.version} ({migration.name})" |
| 86 | + ) |
| 87 | + if not migration.sql.strip(): |
| 88 | + raise MigrationError( |
| 89 | + f"migration v{migration.version} ({migration.name}) contains no SQL" |
| 90 | + ) |
| 91 | + |
| 92 | + |
| 93 | +def user_version(conn: sqlite3.Connection) -> int: |
| 94 | + """Current ``PRAGMA user_version`` of *conn* as ``int``.""" |
| 95 | + return int(conn.execute("PRAGMA user_version").fetchone()[0]) |
| 96 | + |
| 97 | + |
| 98 | +def initialize( |
| 99 | + conn: sqlite3.Connection, |
| 100 | + *, |
| 101 | + migrations: Sequence[Migration] | None = None, |
| 102 | +) -> int: |
| 103 | + """Bring *conn* up to the newest supported schema version; return it. |
| 104 | +
|
| 105 | + With *migrations* omitted the shipped :data:`MIGRATIONS` registry is |
| 106 | + used; passing an explicit registry is the seam used by the migration |
| 107 | + tests to exercise sequencing and failure rollback. |
| 108 | +
|
| 109 | + Raises :class:`UnsupportedSchemaVersionError` when the database is newer |
| 110 | + than the registry, and :class:`MigrationError` when a step fails or the |
| 111 | + registry/state is invalid. Requires a connection with no open |
| 112 | + transaction (the runner owns transaction control). |
| 113 | + """ |
| 114 | + registry = tuple(migrations) if migrations is not None else MIGRATIONS |
| 115 | + _validate_registry(registry) |
| 116 | + if conn.in_transaction: |
| 117 | + raise MigrationError( |
| 118 | + "initialize() requires a connection with no open transaction" |
| 119 | + ) |
| 120 | + current = user_version(conn) |
| 121 | + supported = registry[-1].version |
| 122 | + if current > supported: |
| 123 | + raise UnsupportedSchemaVersionError( |
| 124 | + f"database schema v{current} is newer than supported v{supported}; " |
| 125 | + "refusing to modify it (no downgrade, no reset)" |
| 126 | + ) |
| 127 | + for migration in registry[current:]: |
| 128 | + script = ( |
| 129 | + "BEGIN IMMEDIATE;\n" |
| 130 | + f"{migration.sql}\n" |
| 131 | + f"PRAGMA user_version = {migration.version};\n" |
| 132 | + "COMMIT;" |
| 133 | + ) |
| 134 | + try: |
| 135 | + conn.executescript(script) |
| 136 | + except sqlite3.Error as exc: |
| 137 | + if conn.in_transaction: |
| 138 | + conn.execute("ROLLBACK") |
| 139 | + raise MigrationError( |
| 140 | + f"migration v{migration.version} ({migration.name}) failed and was " |
| 141 | + f"rolled back; user_version remains {user_version(conn)}" |
| 142 | + ) from exc |
| 143 | + return user_version(conn) |
| 144 | + |
| 145 | + |
| 146 | +def initialize_database( |
| 147 | + path: str | Path, |
| 148 | + *, |
| 149 | + migrations: Sequence[Migration] | None = None, |
| 150 | +) -> sqlite3.Connection: |
| 151 | + """Open *path* (contained, WAL pragmas) and migrate it; return the open connection. |
| 152 | +
|
| 153 | + The caller owns the connection and must close it. On migration failure |
| 154 | + the connection is closed before the error propagates - a failed |
| 155 | + initialization leaves no open handle and no partial schema state. |
| 156 | + """ |
| 157 | + conn = open_db(path) |
| 158 | + try: |
| 159 | + initialize(conn, migrations=migrations) |
| 160 | + except BaseException: # includes KeyboardInterrupt - never leak the handle |
| 161 | + conn.close() |
| 162 | + raise |
| 163 | + return conn |
0 commit comments