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,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