Coverage for downtify/sqlite_utils.py: 100%
18 statements
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
1"""Shared SQLite connection tuning."""
3from __future__ import annotations
5import sqlite3
6from types import TracebackType
7from typing import Optional
9_BUSY_TIMEOUT_MS = 30_000
12class ClosingConnection(sqlite3.Connection):
13 """A connection that closes itself when its ``with`` block ends.
15 ``with conn:`` on a plain connection only commits or rolls back. On
16 Python 3.11+ the connection then lingers - file descriptors for the
17 database, ``-wal`` and ``-shm`` files included - until the cyclic GC
18 gets to it, so a loop of short lookups can exhaust the process's
19 descriptor limit (``OSError: [Errno 24]``).
20 """
22 def __exit__(
23 self,
24 exc_type: Optional[type[BaseException]],
25 exc: Optional[BaseException],
26 tb: Optional[TracebackType],
27 ) -> bool:
28 try:
29 return super().__exit__(exc_type, exc, tb)
30 finally:
31 self.close()
34def connect_sqlite(
35 path: str,
36 *,
37 row_factory: bool = False,
38) -> sqlite3.Connection:
39 conn = sqlite3.connect(
40 path, check_same_thread=False, factory=ClosingConnection
41 )
42 if row_factory:
43 conn.row_factory = sqlite3.Row
44 conn.execute('PRAGMA journal_mode=WAL')
45 conn.execute(f'PRAGMA busy_timeout={_BUSY_TIMEOUT_MS}')
46 conn.execute('PRAGMA synchronous=NORMAL')
47 return conn