257 lines
9.1 KiB
Python
257 lines
9.1 KiB
Python
"""SQLite access layer: connection factory, schema, and small shared helpers.
|
|
|
|
The project deliberately uses the standard library ``sqlite3`` instead of an ORM.
|
|
Every request gets its own short lived connection so the WAL journal can serve
|
|
readers while a writer is committing.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import sqlite3
|
|
from contextlib import contextmanager
|
|
from datetime import datetime, timezone
|
|
from typing import Any, Iterable, Iterator
|
|
|
|
from . import config
|
|
|
|
SCHEMA = """
|
|
CREATE TABLE IF NOT EXISTS layers (
|
|
id TEXT PRIMARY KEY,
|
|
name TEXT NOT NULL,
|
|
short_name TEXT NOT NULL DEFAULT '',
|
|
color TEXT NOT NULL DEFAULT '#0d9488',
|
|
description TEXT NOT NULL DEFAULT '',
|
|
sort_order INTEGER NOT NULL DEFAULT 0
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS systems (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
key TEXT NOT NULL UNIQUE,
|
|
name TEXT NOT NULL,
|
|
layer_id TEXT REFERENCES layers(id) ON DELETE SET NULL,
|
|
dept TEXT NOT NULL DEFAULT '',
|
|
status TEXT NOT NULL DEFAULT 'unknown',
|
|
tech TEXT NOT NULL DEFAULT '',
|
|
url TEXT NOT NULL DEFAULT '',
|
|
domain TEXT NOT NULL DEFAULT '',
|
|
owner TEXT NOT NULL DEFAULT '',
|
|
description TEXT NOT NULL DEFAULT '',
|
|
tier INTEGER NOT NULL DEFAULT 2,
|
|
-- Manual position on the data-flow canvas; NULL means "let the layout engine place it".
|
|
flow_x REAL,
|
|
flow_y REAL,
|
|
-- When the system went live. Free form: '2024-06' and '2023 Q4 上线' are both valid.
|
|
impl_time TEXT NOT NULL DEFAULT '',
|
|
-- Whether the panorama overview offers a jump button for this system.
|
|
entry_enabled INTEGER NOT NULL DEFAULT 1,
|
|
sort_order INTEGER NOT NULL DEFAULT 0,
|
|
created_at TEXT NOT NULL DEFAULT '',
|
|
updated_at TEXT NOT NULL DEFAULT ''
|
|
);
|
|
CREATE INDEX IF NOT EXISTS idx_systems_layer ON systems(layer_id);
|
|
|
|
CREATE TABLE IF NOT EXISTS flow_types (
|
|
id TEXT PRIMARY KEY,
|
|
name TEXT NOT NULL,
|
|
color TEXT NOT NULL DEFAULT '#64748b',
|
|
line_style TEXT NOT NULL DEFAULT 'solid',
|
|
default_interval INTEGER NOT NULL DEFAULT 3600,
|
|
description TEXT NOT NULL DEFAULT '',
|
|
sort_order INTEGER NOT NULL DEFAULT 0
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS data_flows (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
source_key TEXT NOT NULL,
|
|
target_key TEXT NOT NULL,
|
|
flow_type_id TEXT NOT NULL REFERENCES flow_types(id) ON DELETE CASCADE,
|
|
label TEXT NOT NULL DEFAULT '',
|
|
payload TEXT NOT NULL DEFAULT '',
|
|
direction TEXT NOT NULL DEFAULT 'forward',
|
|
interval_sec INTEGER NOT NULL DEFAULT 3600,
|
|
records_per_batch INTEGER NOT NULL DEFAULT 1,
|
|
avg_payload_kb REAL NOT NULL DEFAULT 1.0,
|
|
latency_ms INTEGER NOT NULL DEFAULT 120,
|
|
reliability TEXT NOT NULL DEFAULT 'sync',
|
|
peak_hours TEXT NOT NULL DEFAULT '1,2,3,4,5,6,7,8',
|
|
enabled INTEGER NOT NULL DEFAULT 1,
|
|
note TEXT NOT NULL DEFAULT '',
|
|
sort_order INTEGER NOT NULL DEFAULT 0,
|
|
created_at TEXT NOT NULL DEFAULT '',
|
|
updated_at TEXT NOT NULL DEFAULT ''
|
|
);
|
|
CREATE INDEX IF NOT EXISTS idx_flows_source ON data_flows(source_key);
|
|
CREATE INDEX IF NOT EXISTS idx_flows_target ON data_flows(target_key);
|
|
|
|
-- Hourly aggregate per flow. hour_bucket is a local date string 'YYYY-MM-DD'.
|
|
CREATE TABLE IF NOT EXISTS flow_metrics (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
flow_id INTEGER NOT NULL REFERENCES data_flows(id) ON DELETE CASCADE,
|
|
day TEXT NOT NULL,
|
|
hour INTEGER NOT NULL,
|
|
batches INTEGER NOT NULL DEFAULT 0,
|
|
records INTEGER NOT NULL DEFAULT 0,
|
|
bytes INTEGER NOT NULL DEFAULT 0,
|
|
errors INTEGER NOT NULL DEFAULT 0,
|
|
latency_ms INTEGER NOT NULL DEFAULT 0,
|
|
UNIQUE(flow_id, day, hour)
|
|
);
|
|
CREATE INDEX IF NOT EXISTS idx_metrics_day ON flow_metrics(day);
|
|
|
|
CREATE TABLE IF NOT EXISTS settings (
|
|
key TEXT PRIMARY KEY,
|
|
value TEXT NOT NULL,
|
|
updated_at TEXT NOT NULL DEFAULT ''
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS audit_logs (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
actor TEXT NOT NULL DEFAULT '匿名',
|
|
entity TEXT NOT NULL,
|
|
entity_id TEXT NOT NULL DEFAULT '',
|
|
action TEXT NOT NULL,
|
|
summary TEXT NOT NULL DEFAULT '',
|
|
created_at TEXT NOT NULL DEFAULT ''
|
|
);
|
|
CREATE INDEX IF NOT EXISTS idx_audit_created ON audit_logs(created_at);
|
|
"""
|
|
|
|
|
|
def utcnow() -> str:
|
|
return datetime.now(timezone.utc).astimezone().replace(microsecond=0).isoformat(sep=" ")
|
|
|
|
|
|
def connect() -> sqlite3.Connection:
|
|
# Resolved through the module (not a captured name) so a patched config takes effect
|
|
# for connections opened later, including tests that swap the database per case.
|
|
path = config.db_path()
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
# check_same_thread=False is required because FastAPI resolves sync dependencies and
|
|
# runs the endpoint body on different threadpool threads. Safety is preserved because
|
|
# every request gets its own connection and never shares it with another request.
|
|
conn = sqlite3.connect(path, timeout=15.0, isolation_level=None, check_same_thread=False)
|
|
conn.row_factory = sqlite3.Row
|
|
conn.execute("PRAGMA journal_mode=WAL;")
|
|
conn.execute("PRAGMA foreign_keys=ON;")
|
|
conn.execute("PRAGMA busy_timeout=8000;")
|
|
return conn
|
|
|
|
|
|
# Columns added after the first release, backfilled on older database files.
|
|
MIGRATIONS: tuple[tuple[str, str, str], ...] = (
|
|
("systems", "flow_x", "REAL"),
|
|
("systems", "flow_y", "REAL"),
|
|
("systems", "impl_time", "TEXT NOT NULL DEFAULT ''"),
|
|
("systems", "entry_enabled", "INTEGER NOT NULL DEFAULT 1"),
|
|
)
|
|
|
|
|
|
def migrate(conn: sqlite3.Connection) -> None:
|
|
# The shape is read once per table so a migration can target any table, and a table
|
|
# that gains several columns at once is only queried once.
|
|
seen: dict[str, set[str]] = {}
|
|
for table, column, ddl in MIGRATIONS:
|
|
if table not in seen:
|
|
seen[table] = {row["name"] for row in conn.execute(f"PRAGMA table_info({table})")}
|
|
if column in seen[table]:
|
|
continue
|
|
try:
|
|
conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {ddl}")
|
|
except sqlite3.OperationalError as exc:
|
|
# Two processes starting at the same instant both see the missing column;
|
|
# whichever loses the race has nothing left to add.
|
|
if "duplicate column name" not in str(exc):
|
|
raise
|
|
seen[table].add(column)
|
|
|
|
|
|
def init_db() -> None:
|
|
conn = connect()
|
|
try:
|
|
conn.executescript(SCHEMA)
|
|
migrate(conn)
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
@contextmanager
|
|
def transaction(conn: sqlite3.Connection) -> Iterator[sqlite3.Connection]:
|
|
"""Explicit write transaction.
|
|
|
|
The connections run with ``isolation_level=None`` so reads stay autocommit, which
|
|
also means the bare ``with conn:`` idiom would silently provide no atomicity.
|
|
"""
|
|
conn.execute("BEGIN IMMEDIATE")
|
|
try:
|
|
yield conn
|
|
except BaseException:
|
|
conn.execute("ROLLBACK")
|
|
raise
|
|
else:
|
|
conn.execute("COMMIT")
|
|
|
|
|
|
def get_db() -> Iterator[sqlite3.Connection]:
|
|
"""FastAPI dependency handing out one connection per request."""
|
|
conn = connect()
|
|
try:
|
|
yield conn
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# Row helpers
|
|
# --------------------------------------------------------------------------
|
|
|
|
def rows_to_dicts(rows: Iterable[sqlite3.Row]) -> list[dict[str, Any]]:
|
|
return [dict(row) for row in rows]
|
|
|
|
|
|
def one(conn: sqlite3.Connection, sql: str, params: Iterable[Any] = ()) -> dict[str, Any] | None:
|
|
row = conn.execute(sql, tuple(params)).fetchone()
|
|
return dict(row) if row else None
|
|
|
|
|
|
def all_(conn: sqlite3.Connection, sql: str, params: Iterable[Any] = ()) -> list[dict[str, Any]]:
|
|
return rows_to_dicts(conn.execute(sql, tuple(params)).fetchall())
|
|
|
|
|
|
def json_dump(value: Any) -> str:
|
|
return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
|
|
|
|
|
|
def setting(conn: sqlite3.Connection, key: str, default: Any = None) -> Any:
|
|
row = conn.execute("SELECT value FROM settings WHERE key = ?", (key,)).fetchone()
|
|
if row is None:
|
|
return default
|
|
try:
|
|
return json.loads(row["value"])
|
|
except json.JSONDecodeError:
|
|
return default
|
|
|
|
|
|
def set_setting(conn: sqlite3.Connection, key: str, value: Any) -> None:
|
|
conn.execute(
|
|
"""INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)
|
|
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at""",
|
|
(key, json_dump(value), utcnow()),
|
|
)
|
|
|
|
|
|
def log_audit(
|
|
conn: sqlite3.Connection,
|
|
*,
|
|
actor: str,
|
|
entity: str,
|
|
entity_id: Any = "",
|
|
action: str,
|
|
summary: str = "",
|
|
) -> None:
|
|
conn.execute(
|
|
"""INSERT INTO audit_logs (actor, entity, entity_id, action, summary, created_at)
|
|
VALUES (?, ?, ?, ?, ?, ?)""",
|
|
(actor[:40] or "匿名", entity, str(entity_id), action, summary[:300], utcnow()),
|
|
)
|