From 54d3cdd7046e35a0b60dded31792eaebf5b4c9e2 Mon Sep 17 00:00:00 2001 From: iamdoubz <> Date: Thu, 5 Nov 2026 16:08:28 -0600 Subject: [PATCH] Add SQLite access and numbered migrations --- parentcalendar/db.py | 57 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 parentcalendar/db.py diff --git a/parentcalendar/db.py b/parentcalendar/db.py new file mode 100644 index 0000000..dde3490 --- /dev/null +++ b/parentcalendar/db.py @@ -0,0 +1,57 @@ +"""SQLite access: one connection per request or job, numbered SQL migrations tracked in PRAGMA user_version.""" +import json +import sqlite3 +from pathlib import Path + +from parentcalendar import config + +MIGRATIONS = Path(__file__).parent / "migrations" +JSON_COLUMNS = {"source_ids", "ignore_labels", "image_keys", "items", "flags", "cell_bbox", "before", "after", + "child_ids"} # child_ids comes from json_group_array() subqueries +BOOL_COLUMNS = {"double_read", "all_day", "applies", "include", "no_lunch"} + + +def connect(path=None): + conn = sqlite3.connect(path or config.DB_PATH, timeout=30) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA foreign_keys = ON") + conn.execute("PRAGMA journal_mode = WAL") + return conn + + +def migrate(conn): + version = conn.execute("PRAGMA user_version").fetchone()[0] + for path in sorted(MIGRATIONS.glob("*.sql")): + number = int(path.name.split("_")[0]) + if number > version: + conn.executescript(path.read_text(encoding="utf-8")) + conn.execute(f"PRAGMA user_version = {number}") + conn.commit() + + +def as_dict(row): + """A row as a plain dict, with JSON columns decoded and 0/1 columns as booleans.""" + if row is None: + return None + d = dict(row) + for k, v in d.items(): + if k in JSON_COLUMNS and isinstance(v, str): + d[k] = json.loads(v) + elif k in BOOL_COLUMNS and v is not None: + d[k] = bool(v) + return d + + +def all_dicts(cursor): + return [as_dict(r) for r in cursor.fetchall()] + + +def one(conn, sql, args=()): + return as_dict(conn.execute(sql, args).fetchone()) + + +def setup(): + config.DATA_DIR.mkdir(parents=True, exist_ok=True) + config.IMAGES_DIR.mkdir(parents=True, exist_ok=True) + with connect() as conn: + migrate(conn)