Add SQLite database adapter with versioned migrations
Open, create, migrate or reject a file by user_version; reject newer files before switching to WAL. transaction() gives one BEGIN IMMEDIATE per operation. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
71d2befb4f
commit
499d8a5ae8
4 files changed
+379
No files matched your search
@@ -0,0 +1 @@
|
|||||||
|
"""SQLite adapter."""
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
"""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()
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
"""Schema migrations. The schema version of a file is the number of applied migrations."""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from typing import Final
|
||||||
|
|
||||||
|
type Migration = Sequence[str]
|
||||||
|
"""One migration: SQL statements, applied together in one transaction."""
|
||||||
|
|
||||||
|
MIGRATIONS: Final[tuple[Migration, ...]] = ()
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
import shutil
|
||||||
|
import sqlite3
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from contextlib import closing
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from chemenu.adapters.sqlite.database import (
|
||||||
|
Database,
|
||||||
|
DatabaseTooNewError,
|
||||||
|
WalUnavailableError,
|
||||||
|
)
|
||||||
|
from chemenu.adapters.sqlite.migrations import MIGRATIONS, Migration
|
||||||
|
|
||||||
|
M1: Migration = ["CREATE TABLE a (x INTEGER)"]
|
||||||
|
M2: Migration = ["CREATE TABLE b (y INTEGER)", "INSERT INTO b VALUES (1)"]
|
||||||
|
|
||||||
|
|
||||||
|
def _version(path: Path) -> int:
|
||||||
|
conn = sqlite3.connect(path)
|
||||||
|
try:
|
||||||
|
return int(conn.execute("PRAGMA user_version").fetchone()[0])
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _tables(path: Path) -> set[str]:
|
||||||
|
conn = sqlite3.connect(path)
|
||||||
|
try:
|
||||||
|
rows = conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
|
||||||
|
return {r[0] for r in rows}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _journal_mode(path: Path) -> str:
|
||||||
|
with closing(sqlite3.connect(path)) as conn:
|
||||||
|
return str(conn.execute("PRAGMA journal_mode").fetchone()[0])
|
||||||
|
|
||||||
|
|
||||||
|
def _no_sidecars(path: Path) -> None:
|
||||||
|
assert not Path(f"{path}-wal").exists()
|
||||||
|
assert not Path(f"{path}-shm").exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_file_is_created(tmp_path: Path) -> None:
|
||||||
|
path = tmp_path / "db.sqlite"
|
||||||
|
Database(path, [M1, M2])
|
||||||
|
assert _version(path) == 2
|
||||||
|
assert _tables(path) == {"a", "b"}
|
||||||
|
assert _journal_mode(path) == "wal"
|
||||||
|
_no_sidecars(path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_older_schema_is_migrated(tmp_path: Path) -> None:
|
||||||
|
path = tmp_path / "db.sqlite"
|
||||||
|
db = Database(path, [M1])
|
||||||
|
with db.transaction() as conn:
|
||||||
|
conn.execute("INSERT INTO a VALUES (7)")
|
||||||
|
assert _version(path) == 1
|
||||||
|
migrated = Database(path, [M1, M2])
|
||||||
|
with migrated.transaction() as conn:
|
||||||
|
assert conn.execute("SELECT x FROM a").fetchall() == [(7,)]
|
||||||
|
assert _version(path) == 2
|
||||||
|
assert _tables(path) == {"a", "b"}
|
||||||
|
_no_sidecars(path)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("wal", [False, True])
|
||||||
|
def test_newer_schema_is_rejected_unchanged(tmp_path: Path, *, wal: bool) -> None:
|
||||||
|
path = tmp_path / "db.sqlite"
|
||||||
|
conn = sqlite3.connect(path, autocommit=True)
|
||||||
|
conn.execute(f"PRAGMA journal_mode={'WAL' if wal else 'DELETE'}")
|
||||||
|
conn.execute("CREATE TABLE a (x INTEGER)")
|
||||||
|
conn.execute("CREATE TABLE b (y INTEGER)")
|
||||||
|
conn.execute("PRAGMA user_version = 2")
|
||||||
|
conn.close()
|
||||||
|
before = path.read_bytes()
|
||||||
|
with pytest.raises(DatabaseTooNewError):
|
||||||
|
Database(path, [M1])
|
||||||
|
assert path.read_bytes() == before
|
||||||
|
if not wal:
|
||||||
|
_no_sidecars(path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_newer_schema_with_leftover_wal_is_rejected_unchanged(tmp_path: Path) -> None:
|
||||||
|
source = tmp_path / "source.sqlite"
|
||||||
|
path = tmp_path / "db.sqlite"
|
||||||
|
with closing(sqlite3.connect(source, autocommit=True)) as conn:
|
||||||
|
conn.execute("PRAGMA journal_mode=WAL")
|
||||||
|
conn.execute("PRAGMA user_version = 2")
|
||||||
|
# Copy while open: this is what a crash leaves behind.
|
||||||
|
for suffix in ("", "-wal"):
|
||||||
|
shutil.copy(f"{source}{suffix}", f"{path}{suffix}")
|
||||||
|
wal = Path(f"{path}-wal")
|
||||||
|
before = (path.read_bytes(), wal.read_bytes())
|
||||||
|
with pytest.raises(DatabaseTooNewError):
|
||||||
|
Database(path, [M1])
|
||||||
|
assert (path.read_bytes(), wal.read_bytes()) == before
|
||||||
|
|
||||||
|
|
||||||
|
def test_failed_migration_rolls_back(tmp_path: Path) -> None:
|
||||||
|
path = tmp_path / "db.sqlite"
|
||||||
|
Database(path, [M1])
|
||||||
|
bad: Migration = ["CREATE TABLE c (z INTEGER)", "THIS IS NOT SQL"]
|
||||||
|
with pytest.raises(sqlite3.Error):
|
||||||
|
Database(path, [M1, bad])
|
||||||
|
assert _version(path) == 1
|
||||||
|
assert _tables(path) == {"a"}
|
||||||
|
_no_sidecars(path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_concurrent_first_open(tmp_path: Path) -> None:
|
||||||
|
path = tmp_path / "db.sqlite"
|
||||||
|
count = 6
|
||||||
|
barrier = threading.Barrier(count)
|
||||||
|
errors: list[BaseException] = []
|
||||||
|
migrations: list[Migration] = [["CREATE TABLE a (x INTEGER)"], ["CREATE TABLE b (y INTEGER)"]]
|
||||||
|
|
||||||
|
def work() -> None:
|
||||||
|
try:
|
||||||
|
barrier.wait(timeout=10)
|
||||||
|
Database(path, migrations)
|
||||||
|
except BaseException as exc:
|
||||||
|
errors.append(exc)
|
||||||
|
|
||||||
|
threads = [threading.Thread(target=work) for _ in range(count)]
|
||||||
|
for t in threads:
|
||||||
|
t.start()
|
||||||
|
for t in threads:
|
||||||
|
t.join()
|
||||||
|
assert errors == []
|
||||||
|
assert _version(path) == 2
|
||||||
|
assert _tables(path) == {"a", "b"}
|
||||||
|
_no_sidecars(path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_open_waits_for_lock_on_first_open(tmp_path: Path) -> None:
|
||||||
|
path = tmp_path / "db.sqlite"
|
||||||
|
locked = threading.Event()
|
||||||
|
|
||||||
|
def hold_lock() -> None:
|
||||||
|
with closing(sqlite3.connect(path, autocommit=True)) as conn:
|
||||||
|
conn.execute("BEGIN IMMEDIATE")
|
||||||
|
locked.set()
|
||||||
|
time.sleep(0.2)
|
||||||
|
conn.execute("ROLLBACK")
|
||||||
|
|
||||||
|
holder = threading.Thread(target=hold_lock)
|
||||||
|
holder.start()
|
||||||
|
assert locked.wait(timeout=10)
|
||||||
|
Database(path, [M1])
|
||||||
|
holder.join()
|
||||||
|
assert _version(path) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_open_gives_up_when_lock_is_held(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
path = tmp_path / "db.sqlite"
|
||||||
|
monkeypatch.setattr("chemenu.adapters.sqlite.database._TIMEOUT_SECONDS", 0.1)
|
||||||
|
with closing(sqlite3.connect(path, autocommit=True)) as conn:
|
||||||
|
# A write lock leaves reading the version possible but blocks the WAL switch.
|
||||||
|
conn.execute("BEGIN IMMEDIATE")
|
||||||
|
with pytest.raises(sqlite3.OperationalError, match="locked"):
|
||||||
|
Database(path, [M1])
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_wal_support_is_rejected(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
connect = sqlite3.connect
|
||||||
|
|
||||||
|
def in_memory(*_args: object, **_kwargs: object) -> sqlite3.Connection:
|
||||||
|
return connect(":memory:", autocommit=True)
|
||||||
|
|
||||||
|
monkeypatch.setattr("chemenu.adapters.sqlite.database.sqlite3.connect", in_memory)
|
||||||
|
with pytest.raises(WalUnavailableError):
|
||||||
|
Database(tmp_path / "db.sqlite", [M1])
|
||||||
|
|
||||||
|
|
||||||
|
def test_relative_path_survives_chdir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
monkeypatch.chdir(tmp_path)
|
||||||
|
db = Database(Path("db.sqlite"), [M1])
|
||||||
|
(tmp_path / "sub").mkdir()
|
||||||
|
monkeypatch.chdir(tmp_path / "sub")
|
||||||
|
with db.transaction() as conn:
|
||||||
|
conn.execute("INSERT INTO a VALUES (1)")
|
||||||
|
assert list((tmp_path / "sub").iterdir()) == []
|
||||||
|
|
||||||
|
|
||||||
|
def _begin(db: Database) -> None:
|
||||||
|
with db.transaction():
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def test_file_missing_at_runtime_is_not_recreated(tmp_path: Path) -> None:
|
||||||
|
path = tmp_path / "db.sqlite"
|
||||||
|
db = Database(path, [M1])
|
||||||
|
path.unlink()
|
||||||
|
with pytest.raises(sqlite3.OperationalError):
|
||||||
|
_begin(db)
|
||||||
|
assert not path.exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_path_with_special_characters(tmp_path: Path) -> None:
|
||||||
|
path = tmp_path / "a b%20?#ä.sqlite"
|
||||||
|
_begin(Database(path, [M1]))
|
||||||
|
assert [p.name for p in tmp_path.iterdir()] == [path.name]
|
||||||
|
|
||||||
|
|
||||||
|
def test_migrations_are_statement_sequences() -> None:
|
||||||
|
# A forgotten comma makes a one-statement migration a plain string.
|
||||||
|
assert all(not isinstance(migration, str) for migration in MIGRATIONS)
|
||||||
|
|
||||||
|
|
||||||
|
def _insert_then_raise(db: Database, value: int, exc: type[BaseException]) -> None:
|
||||||
|
with db.transaction() as conn:
|
||||||
|
conn.execute("INSERT INTO a VALUES (?)", (value,))
|
||||||
|
raise exc
|
||||||
|
|
||||||
|
|
||||||
|
def _roll_back_then_raise(db: Database) -> None:
|
||||||
|
with db.transaction() as conn:
|
||||||
|
# SQLite rolls back on its own on errors such as a full disk.
|
||||||
|
conn.execute("ROLLBACK")
|
||||||
|
raise ValueError("original")
|
||||||
|
|
||||||
|
|
||||||
|
def test_transaction_rolls_back_on_error(tmp_path: Path) -> None:
|
||||||
|
path = tmp_path / "db.sqlite"
|
||||||
|
db = Database(path, [M1])
|
||||||
|
with db.transaction() as conn:
|
||||||
|
conn.execute("INSERT INTO a VALUES (1)")
|
||||||
|
with pytest.raises(KeyboardInterrupt):
|
||||||
|
_insert_then_raise(db, 2, KeyboardInterrupt)
|
||||||
|
with pytest.raises(RuntimeError):
|
||||||
|
_insert_then_raise(db, 3, RuntimeError)
|
||||||
|
with db.transaction() as conn:
|
||||||
|
rows = conn.execute("SELECT x FROM a").fetchall()
|
||||||
|
assert rows == [(1,)]
|
||||||
|
_no_sidecars(path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_error_is_not_masked_when_sqlite_already_rolled_back(tmp_path: Path) -> None:
|
||||||
|
db = Database(tmp_path / "db.sqlite", [M1])
|
||||||
|
with pytest.raises(ValueError, match="original"):
|
||||||
|
_roll_back_then_raise(db)
|
||||||
Reference in new issue
Block a user