"""SQLite database: open, create, migrate or reject a file; per-operation transactions.""" import sqlite3 import time from collections.abc import Generator, Sequence from contextlib import closing, contextmanager from pathlib import Path from typing import Literal from chemenu.adapters.sqlite.migrations import MIGRATIONS, Migration _TIMEOUT_SECONDS = 5 _RETRY_SECONDS = 0.01 class DatabaseTooNewError(Exception): """The database file has a newer schema than this code knows.""" class WalUnavailableError(Exception): """SQLite cannot use WAL here, for example on a network file system.""" def _user_version(conn: sqlite3.Connection) -> int: row = conn.execute("PRAGMA user_version").fetchone() return int(row[0]) def _switch_to_wal(conn: sqlite3.Connection) -> None: """Switch to WAL, retrying while the file is locked. SQLite can report a lock here without waiting for the connection's timeout. """ deadline = time.monotonic() + _TIMEOUT_SECONDS while True: try: row = conn.execute("PRAGMA journal_mode=WAL").fetchone() except sqlite3.OperationalError as error: # The low byte is the primary code; extended codes such as # SQLITE_BUSY_RECOVERY are retried too. busy = error.sqlite_errorcode & 0xFF == sqlite3.SQLITE_BUSY if not busy or time.monotonic() >= deadline: raise time.sleep(_RETRY_SECONDS) else: # Without WAL support the pragma does not fail but keeps the old mode. if row[0] != "wal": raise WalUnavailableError(f"journal mode is {row[0]!r}") return def _rollback(conn: sqlite3.Connection) -> None: """Roll back unless SQLite already did, which would mask the original error.""" if conn.in_transaction: conn.execute("ROLLBACK") class Database: """One database file; the constructor creates, migrates or rejects it.""" def __init__(self, path: Path, migrations: Sequence[Migration] = MIGRATIONS) -> None: self._path = path.resolve() self._migrations = migrations self._open_and_migrate() def _connect(self, mode: Literal["rw", "rwc"]) -> sqlite3.Connection: uri = f"{self._path.as_uri()}?mode={mode}" return sqlite3.connect(uri, uri=True, autocommit=True, timeout=_TIMEOUT_SECONDS) def _too_new(self, version: int) -> DatabaseTooNewError: return DatabaseTooNewError( f"{self._path}: schema version {version} is newer than the " f"{len(self._migrations)} known migrations" ) def _open_and_migrate(self) -> None: target = len(self._migrations) with closing(self._connect("rwc")) as conn: # Reject before touching the file: both switching the journal mode and # checkpointing a leftover WAL on close would modify it. conn.setconfig(sqlite3.SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, True) version = _user_version(conn) if version > target: raise self._too_new(version) conn.setconfig(sqlite3.SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, False) _switch_to_wal(conn) while version < target: version = self._apply_next(conn) def _apply_next(self, conn: sqlite3.Connection) -> int: """Apply the next pending migration; return the resulting schema version.""" conn.execute("BEGIN IMMEDIATE") try: # Re-read inside the write lock: another opener may have migrated meanwhile. version = _user_version(conn) if version > len(self._migrations): raise self._too_new(version) if version < len(self._migrations): for statement in self._migrations[version]: conn.execute(statement) version += 1 conn.execute(f"PRAGMA user_version = {version}") conn.execute("COMMIT") except BaseException: _rollback(conn) raise return version @contextmanager def transaction(self) -> Generator[sqlite3.Connection]: """Yield a connection inside BEGIN IMMEDIATE; commit, or roll back on any exception.""" # Never create here: an empty file without the schema would hide the loss. conn = self._connect("rw") try: conn.execute("BEGIN IMMEDIATE") try: yield conn except BaseException: _rollback(conn) raise conn.execute("COMMIT") finally: conn.close()