Get or create a connection for the given database path. Args: db_path: Path to the SQLite database file. Returns: An open SQLite connection.
(self, db_path: str)
| 231 | self._lock = threading.Lock() |
| 232 | |
| 233 | def get(self, db_path: str) -> sqlite3.Connection: |
| 234 | """Get or create a connection for the given database path. |
| 235 | |
| 236 | Args: |
| 237 | db_path: Path to the SQLite database file. |
| 238 | |
| 239 | Returns: |
| 240 | An open SQLite connection. |
| 241 | """ |
| 242 | key = str(Path(db_path).resolve()) |
| 243 | with self._lock: |
| 244 | if key in self._pool: |
| 245 | self._pool.move_to_end(key) |
| 246 | return self._pool[key] |
| 247 | |
| 248 | # Evict LRU if full |
| 249 | while len(self._pool) >= self._max_size: |
| 250 | evict_key, evict_conn = self._pool.popitem(last=False) |
| 251 | try: |
| 252 | evict_conn.close() |
| 253 | except sqlite3.Error: |
| 254 | logger.debug("Failed to close evicted connection: %s", evict_key) |
| 255 | logger.debug("Evicted connection: %s", evict_key) |
| 256 | |
| 257 | conn = sqlite3.connect( |
| 258 | key, timeout=30, check_same_thread=False, |
| 259 | isolation_level=None, |
| 260 | ) |
| 261 | conn.row_factory = sqlite3.Row |
| 262 | conn.execute("PRAGMA journal_mode=WAL") |
| 263 | conn.execute("PRAGMA busy_timeout=5000") |
| 264 | self._pool[key] = conn |
| 265 | return conn |
| 266 | |
| 267 | def close_all(self) -> None: |
| 268 | """Close all connections in the pool.""" |