base.py 6.45 KB
"""连接器抽象。

已有 MySQL(含 MariaDB)、PostgreSQL、本地文件(导入 SQLite)。接口按「能再加一种就加一种」的粒度切好:
方言名、连接测试、schema 内省、只读执行。再加一种(Doris、ClickHouse……)只要再实现一个子类。

注意这些连接完全独立于 `core.db.engine`(那个是本系统自己的元数据库)。
业务库的凭据、权限、超时都是另一套,绝不能混用同一个 engine。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any


@dataclass
class ColumnInfo:
    name: str
    data_type: str
    nullable: bool = True
    comment: str = ""
    default: str = ""


@dataclass
class TableInfo:
    name: str
    kind: str = "table"              # table / view
    comment: str = ""
    row_count_est: int = 0
    primary_key: list[str] = field(default_factory=list)
    columns: list[ColumnInfo] = field(default_factory=list)


@dataclass
class ForeignKeyInfo:
    from_table: str
    from_column: str
    to_table: str
    to_column: str
    name: str = ""


@dataclass
class Introspection:
    tables: list[TableInfo] = field(default_factory=list)
    foreign_keys: list[ForeignKeyInfo] = field(default_factory=list)


@dataclass
class QueryResult:
    columns: list[str] = field(default_factory=list)
    rows: list[list[Any]] = field(default_factory=list)
    row_count: int = 0
    duration_ms: int = 0
    truncated: bool = False          # 撞到行数上限被截断


class ConnectionFailed(RuntimeError):
    """连不上 / 认证失败。和「SQL 本身有问题」区分开,前端提示不一样。"""


class QueryFailed(RuntimeError):
    """SQL 执行报错。消息会原样喂给自愈重试,所以别包装得太厚。"""


class Connector:
    """一个数据源的连接句柄。实现类必须保证 run_sql 是只读的。"""

    dialect: str = ""                # sqlglot 方言名

    def __init__(self, ds: dict, password: str):
        self.ds = ds
        self.password = password

    def test(self) -> dict:
        """连通性 + 权限探测。返回给前端展示的摘要(版本、库名、是否只读账号等)。"""
        raise NotImplementedError

    def introspect(self) -> Introspection:
        raise NotImplementedError

    def list_tables(self) -> list[TableInfo]:
        """只列表(名称、类型、注释、行数估计),不读列。新建数据源时给人勾选用,要快。"""
        return [TableInfo(name=t.name, kind=t.kind, comment=t.comment, row_count_est=t.row_count_est)
                for t in self.introspect().tables]

    def sample_values(self, table: str, column: str, limit: int, max_distinct: int) -> tuple[list[str], int]:
        """返回 (取值列表, distinct 总数)。distinct 超过 max_distinct 就认为不是枚举列,返回空列表。"""
        raise NotImplementedError

    def null_ratios(self, table: str, columns: list[str], sample: int) -> dict[str, float]:
        """抽样统计每列的空值比例。返回 {列名: 0~1},拿不到就返回空 dict。

        用来揪出「整列都是 NULL」的列 —— 那种列留在语义模型里,
        模型迟早会拿它写过滤条件,然后查出 0 行还以为是没数据。
        """
        raise NotImplementedError

    def run_sql(self, sql: str, row_limit: int, timeout_ms: int) -> QueryResult:
        raise NotImplementedError

    def transaction(self):
        """一个写事务(SQLAlchemy 连接,退出时提交,出异常回滚)。多张表的写入放进同一个事务:
        新建采购单 + 明细行 + 改缺件单,任何一步失败就全部回滚,业务库里不会留下半张单子。"""
        engine = getattr(self, "engine", None)
        if engine is None:
            raise QueryFailed(f"{self.dialect} 数据源不支持写回")
        return engine.begin()

    def write_row(self, table: str, values: dict[str, Any], key_column: str = "", key: Any = None,
                  conn: Any = None) -> int:
        """写回业务库:key 为 None 时 INSERT,否则按主键 UPDATE。返回影响行数。
        conn:已经开着的事务(transaction()),不给就自己开一个只含这一句的事务。

        run_sql 永远只读;只有数据源开启了「写回业务库」、并且是审批通过的动作,才会走到这里
        (调用方 kernel/objects 负责校验)。表名、列名走 SQLAlchemy 的标识符转义,值全部参数化。
        """
        from sqlalchemy import column, table as sa_table, update
        if key is None:
            return 1 if self.insert_row(table, values, conn=conn) is not False else 0
        t = sa_table(table, *[column(c) for c in dict.fromkeys([*values, key_column]) if c])
        if conn is not None:
            return conn.execute(update(t).where(t.c[key_column] == key).values(**values)).rowcount or 0
        with self.transaction() as c:
            return c.execute(update(t).where(t.c[key_column] == key).values(**values)).rowcount or 0

    def insert_row(self, table: str, values: dict[str, Any], key_column: str = "", conn: Any = None) -> Any:
        """INSERT 一行,返回这一行的主键:values 里给了主键就是它,没给(自增)就取数据库生成的。"""
        from sqlalchemy import column, insert, table as sa_table
        t = sa_table(table, *[column(c) for c in dict.fromkeys([*values, key_column]) if c])

        def go(c: Any) -> Any:
            if key_column and key_column not in values and self.dialect == "postgres":
                return c.execute(insert(t).values(**values).returning(t.c[key_column])).scalar()
            res = c.execute(insert(t).values(**values))
            if key_column and key_column in values:
                return values[key_column]
            return getattr(res, "lastrowid", None)
        if conn is not None:
            return go(conn)
        with self.transaction() as c:
            return go(c)

    def delete_row(self, table: str, key_column: str, key: Any, conn: Any = None) -> int:
        """只用于撤销「在业务库新建」的动作。"""
        from sqlalchemy import column, delete, table as sa_table
        t = sa_table(table, column(key_column))
        if conn is not None:
            return conn.execute(delete(t).where(t.c[key_column] == key)).rowcount or 0
        with self.transaction() as c:
            return c.execute(delete(t).where(t.c[key_column] == key)).rowcount or 0

    def dispose(self) -> None:
        pass