base.py
3.04 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
"""连接器抽象。
首期只有 MySQL,但接口按「能再加一种就加一种」的粒度切好:
方言名、连接测试、schema 内省、只读执行。P3 加 PG/Doris 时只要再实现一个子类。
注意这些连接完全独立于 `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 dispose(self) -> None:
pass