registry.py
2.38 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
"""按数据源取连接器,并缓存 engine。
每建一次 engine 就等于开一个新连接池,内省和问答是高频操作,不能每次都新建。
缓存键带上凭据哈希:用户改了口令/主机,旧连接器会自动作废。
"""
from __future__ import annotations
import hashlib
import threading
from ...core import envs
from .base import Connector
from .mysql import MySQLConnector
from .postgres import PostgresConnector
from .sqlite_file import SQLiteFileConnector
# 键就是 sqlglot 的方言名:guard 与执行都按它解析 SQL。MariaDB 用 mysql。
_REGISTRY: dict[str, type[Connector]] = {
"mysql": MySQLConnector,
"postgres": PostgresConnector,
"sqlite": SQLiteFileConnector, # 本地文件(CSV / Excel / JSON 导入)
}
_lock = threading.RLock()
# 键带上环境:演示快照里同一个数据源 id 指向的是快照库,不能和开发环境共用连接池
_cache: dict[tuple[str, int], tuple[str, Connector]] = {}
def supported_types() -> list[str]:
return sorted(_REGISTRY)
def _fingerprint(ds: dict, password: str) -> str:
raw = f"{ds.get('ds_type')}|{ds.get('host')}|{ds.get('port')}|{ds.get('db_name')}|" \
f"{ds.get('username')}|{password}"
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def build(ds: dict, password: str) -> Connector:
"""不走缓存地新建一个(测试连接时用,避免把坏配置塞进缓存)。"""
cls = _REGISTRY.get(str(ds.get("ds_type") or "").lower())
if cls is None:
raise ValueError(f"暂不支持的数据源类型:{ds.get('ds_type')}(当前支持 {'、'.join(supported_types())})")
return cls(ds, password)
def get(ds: dict, password: str) -> Connector:
"""取缓存的连接器;凭据变了就换掉旧的。"""
key = (envs.current(), int(ds["id"]))
fp = _fingerprint(ds, password)
with _lock:
hit = _cache.get(key)
if hit and hit[0] == fp:
return hit[1]
if hit:
try:
hit[1].dispose()
except Exception: # noqa: BLE001
pass
conn = build(ds, password)
_cache[key] = (fp, conn)
return conn
def evict(ds_id: int) -> None:
with _lock:
hit = _cache.pop((envs.current(), int(ds_id)), None)
if hit:
try:
hit[1].dispose()
except Exception: # noqa: BLE001
pass