"""数据库访问层。 对外只暴露很小的接口(execute / query / executemany),业务代码统一使用 `?` 占位符;内部按方言把 `?` 翻译成 `%s`。这样从 DuckDB 切换到 PostgreSQL 只需要 改 `SZ_DATABASE_URL`,业务 SQL 不用动。 """ from __future__ import annotations import threading from contextlib import contextmanager from typing import Any, Iterable, Sequence from . import config class DatabaseError(RuntimeError): pass class Database: def __init__(self, url: str | None = None) -> None: self.url = url or config.DATABASE_URL if self.url.startswith("duckdb://"): self.dialect = "duckdb" raw = self.url[len("duckdb://"):] # duckdb:///D:/x.duckdb -> /D:/x.duckdb -> D:/x.duckdb if raw.startswith("/") and len(raw) > 2 and raw[2] == ":": raw = raw[1:] self.path = raw elif self.url.startswith("postgresql://") or self.url.startswith("postgres://"): self.dialect = "postgresql" self.path = self.url else: raise DatabaseError(f"不支持的数据库连接串:{self.url}") self._lock = threading.RLock() self._conn = None # ------------------------------------------------------------------ 连接 def connect(self): with self._lock: if self._conn is not None: return self._conn if self.dialect == "duckdb": import duckdb self._conn = duckdb.connect(self.path) else: try: import psycopg # type: ignore except ImportError as exc: # pragma: no cover raise DatabaseError( "使用 PostgreSQL 需要先安装驱动:pip install 'psycopg[binary]'" ) from exc self._conn = psycopg.connect(self.path, autocommit=True) return self._conn def close(self) -> None: with self._lock: if self._conn is not None: self._conn.close() self._conn = None @contextmanager def cursor(self): with self._lock: conn = self.connect() if self.dialect == "duckdb": # DuckDB 的 cursor() 会新开一个连接,注册的临时视图不可见, # 因此直接用主连接(外层有 RLock 串行化)。 yield conn else: cur = conn.cursor() try: yield cur finally: cur.close() # ------------------------------------------------------------------ SQL def _sql(self, sql: str) -> str: if self.dialect == "postgresql": return sql.replace("?", "%s") return sql def execute(self, sql: str, params: Sequence[Any] = ()) -> int: with self.cursor() as cur: cur.execute(self._sql(sql), tuple(params)) return getattr(cur, "rowcount", -1) or -1 def executemany(self, sql: str, seq: Iterable[Sequence[Any]]) -> int: rows = list(seq) if not rows: return 0 with self.cursor() as cur: cur.executemany(self._sql(sql), rows) return len(rows) def query(self, sql: str, params: Sequence[Any] = ()) -> list[dict[str, Any]]: with self.cursor() as cur: cur.execute(self._sql(sql), tuple(params)) cols = [d[0] for d in (cur.description or [])] return [dict(zip(cols, row)) for row in cur.fetchall()] def query_one(self, sql: str, params: Sequence[Any] = ()) -> dict[str, Any] | None: rows = self.query(sql, params) return rows[0] if rows else None def scalar(self, sql: str, params: Sequence[Any] = ()) -> Any: row = self.query_one(sql, params) return next(iter(row.values())) if row else None def query_frame(self, sql: str, params: Sequence[Any] = ()): """返回 polars DataFrame(DuckDB 走 Arrow,零拷贝;PG 走通用查询)。""" import polars as pl with self._lock: conn = self.connect() if self.dialect == "duckdb": import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") try: rel = conn.sql(self._sql(sql), params=tuple(params)) tbl = rel.to_arrow_table() except TypeError: # 旧版本 duckdb 的 sql() 不支持 params tbl = conn.execute(self._sql(sql), tuple(params)).to_arrow_table() return pl.from_arrow(tbl) rows = self.query(sql, params) return pl.DataFrame(rows) if rows else pl.DataFrame() # ------------------------------------------------------------------ 元数据 def table_exists(self, name: str) -> bool: if self.dialect == "duckdb": sql = "SELECT count(*) AS c FROM information_schema.tables WHERE table_name = ?" else: sql = "SELECT count(*) AS c FROM information_schema.tables WHERE table_name = ?" return bool(self.scalar(sql, (name,))) def init_schema(self) -> None: from .schema import create_statements for stmt in create_statements(self.dialect): self.execute(stmt) _db: Database | None = None def get_db() -> Database: """进程内单例,FastAPI(Web)与 CLI 共用。""" global _db if _db is None: _db = Database() _db.init_schema() return _db