|
5 | 5 | import aiosqlite |
6 | 6 | import asyncio |
7 | 7 | import logging |
| 8 | +import threading |
8 | 9 | from pathlib import Path |
9 | 10 | from typing import AsyncIterator |
10 | 11 | from contextlib import asynccontextmanager |
| 12 | +from datetime import datetime, timezone, timedelta |
11 | 13 |
|
12 | 14 | from src.config import DB_PATH |
13 | 15 |
|
14 | 16 | logger = logging.getLogger(__name__) |
15 | 17 |
|
16 | 18 | # Module-level connection pool (single shared connection with WAL mode) |
17 | 19 | _db: aiosqlite.Connection | None = None |
18 | | -_lock = asyncio.Lock() |
| 20 | +_initializing = False |
19 | 21 |
|
20 | 22 | # Schema version for consistency tracking |
21 | 23 | SCHEMA_VERSION = 1 |
22 | 24 |
|
23 | 25 |
|
| 26 | +def _now() -> str: |
| 27 | + return datetime.now(timezone.utc).isoformat() |
| 28 | + |
| 29 | + |
24 | 30 | async def get_db() -> aiosqlite.Connection: |
25 | 31 | """Return the shared async database connection, initializing it if needed.""" |
26 | | - global _db |
27 | | - if _db is None: |
28 | | - async with _lock: |
29 | | - if _db is None: |
30 | | - Path(DB_PATH).parent.mkdir(parents=True, exist_ok=True) |
31 | | - _db = await aiosqlite.connect(DB_PATH) |
32 | | - _db.row_factory = aiosqlite.Row |
33 | | - # WAL mode: allows concurrent reads while writing |
34 | | - await _db.execute("PRAGMA journal_mode=WAL") |
35 | | - await _db.execute("PRAGMA foreign_keys=ON") |
36 | | - await init_schema(_db) |
37 | | - logger.info(f"Database initialized at {DB_PATH}") |
| 32 | + global _db, _initializing |
| 33 | + if _db is None and not _initializing: |
| 34 | + _initializing = True |
| 35 | + try: |
| 36 | + Path(DB_PATH).parent.mkdir(parents=True, exist_ok=True) |
| 37 | + _db = await aiosqlite.connect(DB_PATH) |
| 38 | + _db.row_factory = aiosqlite.Row |
| 39 | + # WAL mode: allows concurrent reads while writing |
| 40 | + await _db.execute("PRAGMA journal_mode=WAL") |
| 41 | + await _db.execute("PRAGMA foreign_keys=ON") |
| 42 | + await init_schema(_db) |
| 43 | + logger.info(f"Database initialized at {DB_PATH}") |
| 44 | + finally: |
| 45 | + _initializing = False |
38 | 46 | return _db |
39 | 47 |
|
40 | 48 |
|
@@ -247,4 +255,38 @@ async def init_schema(db: aiosqlite.Connection) -> None: |
247 | 255 | except Exception: |
248 | 256 | pass |
249 | 257 |
|
250 | | - logger.info("Schema initialized.") |
| 258 | + # Record current schema version |
| 259 | + await db.execute( |
| 260 | + "INSERT OR REPLACE INTO schema_version (version, applied_at) VALUES (?, ?)", |
| 261 | + (SCHEMA_VERSION, _now()) |
| 262 | + ) |
| 263 | + await db.commit() |
| 264 | + |
| 265 | + logger.info(f"Schema initialized (version {SCHEMA_VERSION}).") |
| 266 | + |
| 267 | + |
| 268 | +async def get_schema_version(db: aiosqlite.Connection) -> int | None: |
| 269 | + """Get the current schema version from the database.""" |
| 270 | + try: |
| 271 | + async with db.execute("SELECT version FROM schema_version ORDER BY version DESC LIMIT 1") as cur: |
| 272 | + row = await cur.fetchone() |
| 273 | + return row["version"] if row else None |
| 274 | + except Exception: |
| 275 | + return None |
| 276 | + |
| 277 | + |
| 278 | +async def verify_schema_consistency(db: aiosqlite.Connection) -> tuple[bool, str]: |
| 279 | + """Verify that the database schema matches the expected version. |
| 280 | + |
| 281 | + Returns: |
| 282 | + (is_consistent, message) |
| 283 | + """ |
| 284 | + try: |
| 285 | + current_version = await get_schema_version(db) |
| 286 | + if current_version is None: |
| 287 | + return False, "Schema version table not found" |
| 288 | + if current_version != SCHEMA_VERSION: |
| 289 | + return False, f"Schema version mismatch: expected {SCHEMA_VERSION}, got {current_version}" |
| 290 | + return True, f"Schema version {SCHEMA_VERSION} is consistent" |
| 291 | + except Exception as e: |
| 292 | + return False, f"Error checking schema: {e}" |
0 commit comments