"""SQLite transactions for the single-host testing deployment.""" from contextlib import contextmanager from pathlib import Path import sqlite3 class Connection: sqlite = True def __init__(self, raw): self.raw = raw def execute(self, sql, args=()): return self.raw.execute(sql.replace('%s', '?'), args) class Database: def __init__(self, url): if not url.startswith('sqlite:///'): raise ValueError('This testing deployment uses a local SQLite database') self.path = Path(url.removeprefix('sqlite:///')) self.path.parent.mkdir(parents=True, exist_ok=True) @contextmanager def transaction(self): raw = sqlite3.connect(self.path, timeout=15) raw.row_factory = sqlite3.Row raw.execute('PRAGMA foreign_keys=ON') raw.execute('BEGIN IMMEDIATE') try: yield Connection(raw) raw.commit() except BaseException: raw.rollback() raise finally: raw.close() def migrate(self): with sqlite3.connect(self.path) as raw: raw.execute('PRAGMA journal_mode=WAL') sql = Path(__file__).with_name('schema.sql').read_text() with self.transaction() as c: for statement in sql.split(';'): if statement.strip(): c.execute(statement) @staticmethod def submission_lock(c): # BEGIN IMMEDIATE already serializes the quota check and insert. pass