refactor: 小学版 db 也接到 core(clock/store/ensure_columns)
This commit is contained in:
+6
-38
@@ -11,11 +11,11 @@ from __future__ import annotations
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import uuid
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
TZ = timezone(timedelta(hours=8)) # Asia/Shanghai,与提醒时间一致
|
||||
from core.clock import TZ, add_days, new_id, now, today
|
||||
from core.store import ensure_columns, open_db, row_to_dict, rows_to_list
|
||||
|
||||
DB_PATH = Path(os.environ.get("QINGLING_DB", Path(__file__).resolve().parent.parent / "data" / "app.db"))
|
||||
|
||||
SCHEMA = """
|
||||
@@ -258,25 +258,9 @@ CREATE INDEX IF NOT EXISTS idx_questions_paper ON questions(paper_id, seq);
|
||||
"""
|
||||
|
||||
|
||||
def now() -> str:
|
||||
return datetime.now(TZ).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def today() -> str:
|
||||
return datetime.now(TZ).date().isoformat()
|
||||
|
||||
|
||||
def new_id(prefix: str) -> str:
|
||||
return f"{prefix}_{uuid.uuid4().hex[:12]}"
|
||||
|
||||
|
||||
def connect(path: str | Path | None = None) -> sqlite3.Connection:
|
||||
p = Path(path or DB_PATH)
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
conn = sqlite3.connect(str(p), isolation_level=None) # 自己管事务
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.execute("PRAGMA foreign_keys=ON")
|
||||
return conn
|
||||
"""连接本产品的库(时间/ID 来自 core.clock,连接来自 core.store)。"""
|
||||
return open_db(path or DB_PATH)
|
||||
|
||||
|
||||
def init_db(conn: sqlite3.Connection) -> None:
|
||||
@@ -289,10 +273,7 @@ def _migrate(conn: sqlite3.Connection) -> None:
|
||||
want = {"questions": ["options", "kp"], "mistakes": ["options", "kp"],
|
||||
"guardians": ["phone"], "papers": ["clean_path", "image_path"]}
|
||||
for table, cols in want.items():
|
||||
have = {r["name"] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()}
|
||||
for c in cols:
|
||||
if c not in have:
|
||||
conn.execute(f"ALTER TABLE {table} ADD COLUMN {c} TEXT")
|
||||
ensure_columns(conn, table, {c: "TEXT" for c in cols})
|
||||
|
||||
|
||||
def reset_db(conn: sqlite3.Connection) -> None:
|
||||
@@ -309,21 +290,8 @@ def reset_db(conn: sqlite3.Connection) -> None:
|
||||
init_db(conn)
|
||||
|
||||
|
||||
def row_to_dict(row: sqlite3.Row | None) -> dict | None:
|
||||
return dict(row) if row is not None else None
|
||||
|
||||
|
||||
def rows_to_list(rows) -> list[dict]:
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
def log_event(conn: sqlite3.Connection, name: str, child_id: str | None = None, **payload) -> None:
|
||||
conn.execute(
|
||||
"INSERT INTO events (child_id, name, payload, created_at) VALUES (?,?,?,?)",
|
||||
(child_id, name, json.dumps(payload, ensure_ascii=False), now()),
|
||||
)
|
||||
|
||||
|
||||
def add_days(days: int, base: str | None = None) -> str:
|
||||
d = date.fromisoformat(base) if base else date.fromisoformat(today())
|
||||
return (d + timedelta(days=days)).isoformat()
|
||||
|
||||
Reference in New Issue
Block a user