Add SQLite access and numbered migrations

This commit is contained in:
iamdoubz committed 2026-11-05 16:08:28 -06:00
1 parent 38a6d9e1d7
commit 54d3cdd704
1 file changed
+57
+57
View File
@@ -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)