base.py
4.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
"""连接器抽象。
已有 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 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 write_row(self, table: str, values: dict[str, Any], key_column: str = "", key: Any = None) -> int:
"""写回业务库:key 为 None 时 INSERT,否则按主键 UPDATE。返回影响行数。
run_sql 永远只读;只有数据源开启了「写回业务库」、并且是审批通过的动作,才会走到这里
(调用方 kernel/objects 负责校验)。表名、列名走 SQLAlchemy 的标识符转义,值全部参数化。
"""
from sqlalchemy import column, insert, table as sa_table, update
t = sa_table(table, *[column(c) for c in dict.fromkeys([*values, key_column]) if c])
engine = getattr(self, "engine", None)
if engine is None:
raise QueryFailed(f"{self.dialect} 数据源不支持写回")
with engine.begin() as c:
if key is None:
return c.execute(insert(t).values(**values)).rowcount or 0
return c.execute(update(t).where(t.c[key_column] == key).values(**values)).rowcount or 0
def delete_row(self, table: str, key_column: str, key: Any) -> int:
"""只用于撤销「在业务库新建」的动作。"""
from sqlalchemy import column, delete, table as sa_table
t = sa_table(table, column(key_column))
with self.engine.begin() as c: # type: ignore[attr-defined]
return c.execute(delete(t).where(t.c[key_column] == key)).rowcount or 0
def dispose(self) -> None:
pass