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 json
|
||||||
import os
|
import os
|
||||||
import sqlite3
|
import sqlite3
|
||||||
import uuid
|
|
||||||
from datetime import date, datetime, timedelta, timezone
|
|
||||||
from pathlib import Path
|
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"))
|
DB_PATH = Path(os.environ.get("QINGLING_DB", Path(__file__).resolve().parent.parent / "data" / "app.db"))
|
||||||
|
|
||||||
SCHEMA = """
|
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:
|
def connect(path: str | Path | None = None) -> sqlite3.Connection:
|
||||||
p = Path(path or DB_PATH)
|
"""连接本产品的库(时间/ID 来自 core.clock,连接来自 core.store)。"""
|
||||||
p.parent.mkdir(parents=True, exist_ok=True)
|
return open_db(path or DB_PATH)
|
||||||
conn = sqlite3.connect(str(p), isolation_level=None) # 自己管事务
|
|
||||||
conn.row_factory = sqlite3.Row
|
|
||||||
conn.execute("PRAGMA foreign_keys=ON")
|
|
||||||
return conn
|
|
||||||
|
|
||||||
|
|
||||||
def init_db(conn: sqlite3.Connection) -> None:
|
def init_db(conn: sqlite3.Connection) -> None:
|
||||||
@@ -289,10 +273,7 @@ def _migrate(conn: sqlite3.Connection) -> None:
|
|||||||
want = {"questions": ["options", "kp"], "mistakes": ["options", "kp"],
|
want = {"questions": ["options", "kp"], "mistakes": ["options", "kp"],
|
||||||
"guardians": ["phone"], "papers": ["clean_path", "image_path"]}
|
"guardians": ["phone"], "papers": ["clean_path", "image_path"]}
|
||||||
for table, cols in want.items():
|
for table, cols in want.items():
|
||||||
have = {r["name"] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()}
|
ensure_columns(conn, table, {c: "TEXT" for c in cols})
|
||||||
for c in cols:
|
|
||||||
if c not in have:
|
|
||||||
conn.execute(f"ALTER TABLE {table} ADD COLUMN {c} TEXT")
|
|
||||||
|
|
||||||
|
|
||||||
def reset_db(conn: sqlite3.Connection) -> None:
|
def reset_db(conn: sqlite3.Connection) -> None:
|
||||||
@@ -309,21 +290,8 @@ def reset_db(conn: sqlite3.Connection) -> None:
|
|||||||
init_db(conn)
|
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:
|
def log_event(conn: sqlite3.Connection, name: str, child_id: str | None = None, **payload) -> None:
|
||||||
conn.execute(
|
conn.execute(
|
||||||
"INSERT INTO events (child_id, name, payload, created_at) VALUES (?,?,?,?)",
|
"INSERT INTO events (child_id, name, payload, created_at) VALUES (?,?,?,?)",
|
||||||
(child_id, name, json.dumps(payload, ensure_ascii=False), now()),
|
(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()
|
|
||||||
|
|||||||
@@ -9,6 +9,9 @@ import os
|
|||||||
import sys
|
import sys
|
||||||
import tempfile
|
import tempfile
|
||||||
import unittest
|
import unittest
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
from core.clock import TZ
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
@@ -76,7 +79,7 @@ class SchedulerTest(unittest.TestCase):
|
|||||||
self.assertEqual(s["status"], "careless")
|
self.assertEqual(s["status"], "careless")
|
||||||
|
|
||||||
def test_later_correct_is_e3(self):
|
def test_later_correct_is_e3(self):
|
||||||
old = (dbm.datetime.now(dbm.TZ) - dbm.timedelta(days=3)).isoformat(timespec="seconds")
|
old = (datetime.now(TZ) - timedelta(days=3)).isoformat(timespec="seconds")
|
||||||
s = scheduler.on_attempt(self.base(created_at=old), True)
|
s = scheduler.on_attempt(self.base(created_at=old), True)
|
||||||
self.assertEqual((s["status"], s["wrong_code"]), ("queued", "E3"))
|
self.assertEqual((s["status"], s["wrong_code"]), ("queued", "E3"))
|
||||||
self.assertEqual(s["interval_days"], 3)
|
self.assertEqual(s["interval_days"], 3)
|
||||||
|
|||||||
Reference in New Issue
Block a user