1
0

[loop-cycle-50] refactor: replace bare sqlite3.connect() with context managers batch 2 (#157) (#180)

This commit is contained in:
2026-03-15 11:58:43 -04:00
parent bea2749158
commit bcd6d7e321
16 changed files with 512 additions and 510 deletions

View File

@@ -10,7 +10,8 @@ regenerates the briefing every 6 hours.
import logging
import sqlite3
from contextlib import closing
from collections.abc import Generator
from contextlib import closing, contextmanager
from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
from pathlib import Path
@@ -57,25 +58,26 @@ class Briefing:
# ---------------------------------------------------------------------------
def _get_cache_conn(db_path: Path = _DEFAULT_DB) -> sqlite3.Connection:
@contextmanager
def _get_cache_conn(db_path: Path = _DEFAULT_DB) -> Generator[sqlite3.Connection, None, None]:
db_path.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(str(db_path))
conn.row_factory = sqlite3.Row
conn.execute("""
CREATE TABLE IF NOT EXISTS briefings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
generated_at TEXT NOT NULL,
period_start TEXT NOT NULL,
period_end TEXT NOT NULL,
summary TEXT NOT NULL
)
""")
conn.commit()
return conn
with closing(sqlite3.connect(str(db_path))) as conn:
conn.row_factory = sqlite3.Row
conn.execute("""
CREATE TABLE IF NOT EXISTS briefings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
generated_at TEXT NOT NULL,
period_start TEXT NOT NULL,
period_end TEXT NOT NULL,
summary TEXT NOT NULL
)
""")
conn.commit()
yield conn
def _save_briefing(briefing: Briefing, db_path: Path = _DEFAULT_DB) -> None:
with closing(_get_cache_conn(db_path)) as conn:
with _get_cache_conn(db_path) as conn:
conn.execute(
"""
INSERT INTO briefings (generated_at, period_start, period_end, summary)
@@ -93,7 +95,7 @@ def _save_briefing(briefing: Briefing, db_path: Path = _DEFAULT_DB) -> None:
def _load_latest(db_path: Path = _DEFAULT_DB) -> Briefing | None:
"""Load the most-recently cached briefing, or None if there is none."""
with closing(_get_cache_conn(db_path)) as conn:
with _get_cache_conn(db_path) as conn:
row = conn.execute("SELECT * FROM briefings ORDER BY generated_at DESC LIMIT 1").fetchone()
if row is None:
return None