Coverage for downtify/db/runtime.py: 92%

48 statements  

« prev     ^ index     » next       coverage.py v7.17.4, created at 2026-11-21 22:18 +0000

1"""Pick the database for one store group at runtime. 

2 

3``db_target`` reads the environment when it is called: with 

4``DATABASE_URL`` set it returns one shared PostgreSQL ``Database`` (after 

5the schema migrations ran once for this process), otherwise the SQLite 

6file path the group has always used under ``DATABASE_DIR``. 

7""" 

8 

9from __future__ import annotations 

10 

11import threading 

12from dataclasses import replace 

13from pathlib import Path 

14 

15from downtify.db.config import DbConfig, Dialect 

16from downtify.db.core import Database 

17from downtify.db.migrations.runner import run_migrations 

18 

19_LOCK = threading.Lock() 

20#: Migrations already applied in this process, per (url, search_path). 

21_MIGRATED: set[tuple[str, str | None]] = set() 

22#: Databases this process opened; ``shutdown`` closes them. 

23_OPENED: dict[tuple[str, str | None], Database] = {} 

24 

25 

26def _key(cfg: DbConfig) -> tuple[str, str | None]: 

27 assert cfg.url is not None 

28 return (cfg.url, cfg.search_path) 

29 

30 

31def db_target(group: str, data_dir: Path | None = None) -> Path | Database: 

32 """Return where the store for ``group`` keeps its data. 

33 

34 ``data_dir``, when given, overrides ``DATABASE_DIR`` for SQLite. On 

35 PostgreSQL the result is a ``Database`` shared by every group. 

36 """ 

37 cfg = DbConfig.from_env() 

38 if data_dir is not None: 

39 cfg = replace(cfg, data_dir=Path(data_dir)) 

40 if cfg.dialect is Dialect.SQLITE: 

41 return cfg.sqlite_path(group) 

42 

43 key = _key(cfg) 

44 with _LOCK: 

45 db = _OPENED.get(key) 

46 if db is None: 

47 db = Database.for_group(cfg, group) 

48 _OPENED[key] = db 

49 if key not in _MIGRATED: 

50 run_migrations(db) 

51 _MIGRATED.add(key) 

52 return db 

53 

54 

55def shutdown() -> None: 

56 """Close every PostgreSQL pool this process opened.""" 

57 with _LOCK: 

58 opened = list(_OPENED.values()) 

59 _OPENED.clear() 

60 _MIGRATED.clear() 

61 for db in opened: 

62 db.close() 

63 

64 

65def healthcheck() -> bool | None: 

66 """True/False for the PostgreSQL server; None on SQLite.""" 

67 cfg = DbConfig.from_env() 

68 if cfg.dialect is Dialect.SQLITE: 

69 return None 

70 with _LOCK: 

71 db = _OPENED.get(_key(cfg)) 

72 if db is None: 

73 db = Database.for_group(cfg, 'library') 

74 try: 

75 return db.healthcheck() 

76 finally: 

77 db.close() 

78 return db.healthcheck()