Files

50 lines
1.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""sqlite 的公共部分:连库、行转字典、补列(老库升级用)。
刻意不碰「建表」:两个产品的表结构不一样,SCHEMA 留在各自包里。
"""
from __future__ import annotations
import sqlite3
from pathlib import Path
def open_db(path: str | Path, *, timeout: float = 15,
check_same_thread: bool = False) -> sqlite3.Connection:
"""打开一个「自己管事务」的库:isolation_level=None。
两个产品都在 services 里显式 BEGIN/COMMIT(tx()),如果这里再开自动事务,
会撞上 `sqlite3.OperationalError: cannot start a transaction within a transaction`。
"""
p = Path(path)
p.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(str(p), timeout=timeout,
check_same_thread=check_same_thread,
isolation_level=None)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys=ON")
return conn
def row_to_dict(row) -> 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 ensure_columns(conn: sqlite3.Connection, table: str, cols: dict[str, str]) -> list[str]:
"""给老库补列:`CREATE TABLE IF NOT EXISTS` 不会改已存在的表。
:param cols: {列名: 类型},例如 {"kp": "TEXT"}
:return: 真正补上的列名
"""
have = {r["name"] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()}
added = []
for name, ctype in cols.items():
if name not in have:
conn.execute(f"ALTER TABLE {table} ADD COLUMN {name} {ctype}")
added.append(name)
return added