Source code for imednet.utils.db

"""Centralized database connection utilities."""

import sqlite3
import threading
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path

_db_init_locks: dict[str, threading.RLock] = {}
_db_init_locks_guard = threading.RLock()
_SQLITE_HEADER_MAGIC = b"SQLite format 3\x00"
_SQLITE_WAL_VERSION_BYTES = b"\x02\x02"


def _get_db_init_lock(resolved_path: Path) -> threading.RLock:
    """Return a thread-safe lock for initializing a specific database file."""
    key = str(Path(resolved_path).expanduser().resolve())
    with _db_init_locks_guard:
        return _db_init_locks.setdefault(key, threading.RLock())


[docs]def get_db_init_lock(db_path: str | Path) -> threading.RLock: """Return the reentrant initialization lock for ``db_path``.""" return _get_db_init_lock(Path(db_path))
def _has_persistent_wal_header(path: Path) -> bool: """Return True when ``path`` is an existing SQLite database already persisted in WAL mode.""" try: if not path.is_file(): return False with path.open("rb") as handle: header = handle.read(20) except OSError: return False return ( len(header) >= 20 and header[:16] == _SQLITE_HEADER_MAGIC and header[18:20] == _SQLITE_WAL_VERSION_BYTES ) def _configure_sqlite_connection( conn: sqlite3.Connection, *, busy_timeout_ms: int, enable_wal: bool, foreign_keys: bool, ) -> sqlite3.Connection: """Apply connection-scoped SQLite pragmas and close ``conn`` if setup fails.""" try: conn.row_factory = sqlite3.Row if busy_timeout_ms: conn.execute(f"PRAGMA busy_timeout={busy_timeout_ms};") if enable_wal: conn.execute("PRAGMA journal_mode=WAL;") conn.execute("PRAGMA synchronous=NORMAL;") if foreign_keys: conn.execute("PRAGMA foreign_keys=ON;") except BaseException: conn.close() raise return conn def _connect_sqlite( resolved_path: Path, *, timeout: float, check_same_thread: bool, ) -> sqlite3.Connection: """Open a raw SQLite connection while preserving default call signatures.""" if check_same_thread: return sqlite3.connect(resolved_path, timeout=timeout) return sqlite3.connect(resolved_path, timeout=timeout, check_same_thread=False)
[docs]def get_sqlite_connection( db_path: str | Path, timeout: float = 30.0, busy_timeout_ms: int = 30000, foreign_keys: bool = False, *, check_same_thread: bool = True, ) -> sqlite3.Connection: """Return a SQLite connection configured for concurrent access.""" resolved_path = Path(db_path).expanduser() resolved_path.parent.mkdir(parents=True, exist_ok=True) if _has_persistent_wal_header(resolved_path): try: conn = _connect_sqlite( resolved_path, timeout=timeout, check_same_thread=check_same_thread, ) except sqlite3.Error as exc: raise sqlite3.OperationalError(f"Unable to open sqlite database: {exc}") from exc return _configure_sqlite_connection( conn, busy_timeout_ms=busy_timeout_ms, enable_wal=False, foreign_keys=foreign_keys, ) lock = _get_db_init_lock(resolved_path) with lock: already_wal = _has_persistent_wal_header(resolved_path) try: conn = _connect_sqlite( resolved_path, timeout=timeout, check_same_thread=check_same_thread, ) except sqlite3.Error as exc: raise sqlite3.OperationalError(f"Unable to open sqlite database: {exc}") from exc return _configure_sqlite_connection( conn, busy_timeout_ms=busy_timeout_ms, enable_wal=not already_wal, foreign_keys=foreign_keys, )
[docs]@contextmanager def sqlite_connection( db_path: str | Path, timeout: float = 30.0, busy_timeout_ms: int = 30000, foreign_keys: bool = False, *, check_same_thread: bool = True, ) -> Iterator[sqlite3.Connection]: """Context manager yielding a safely configured SQLite connection.""" conn = get_sqlite_connection( db_path, timeout=timeout, busy_timeout_ms=busy_timeout_ms, foreign_keys=foreign_keys, check_same_thread=check_same_thread, ) try: yield conn finally: conn.close()