Files
AgentLab/backend/tests/test_datasource.py
T
ThearchyHelios 39e7a5b014 数据源接入:MySQL / Oracle / PostgreSQL / SQLite
阶段①。产品原先能取数的只有 http_request 和沙箱里自己写代码——面对"分析上季度
华东区销量下滑"这类需求,用户得自己知道数据在哪张表、字段叫什么,再手写 SQL 塞进
代码节点。最难的部分留给了用户。

## 连接层(app/data/)

方言差异全收敛在 engine.py 一处:Oracle 要 service_name/sid、MySQL 要 charset、
各家默认端口不同。三个驱动都是 asyncio 原生且免装客户端——oracledb 走 thin 模式,
不需要 Instant Client。密码复用 app/core/crypto 的 Fernet,和 Provider 同一套;
build_url 默认把密码替换成星号,日志和错误信息里用这个版本。

introspect.py 产出两种粒度:summary()(表名+代表字段,几百 token,给 Copilot 的
system prompt 用)和 describe_table()(单表完整字段,按需取)。分两种是因为一个
中等业务库全量塞进 prompt 轻松几万 token,既贵又会把真正的需求淹掉。

## 守卫(app/data/guard.py)

这是唯一不能出错的地方:SQL 由模型生成,模型会写出什么事前无法穷举,防线不能
建立在"它应该不会这么干"上。三层:

- 只读判定用**白名单**而非黑名单——黑名单永远漏,MERGE/CALL/GRANT/各家私货写不完
- 多语句在到达驱动前就断掉,不赌驱动默认只跑第一条(MySQL 开了
  CLIENT_MULTI_STATEMENTS 就会全跑)
- 行数/字节/超时三重上限,一条 SELECT * 不该把内存和模型上下文一起打爆

刻意不引 sqlparse:完整解析 SQL 方言是无底洞,而这里的判断很窄——"首关键字是
什么"和"有没有第二条语句"。窄问题用窄解法。难点是不能误杀:`SELECT ';'` 只是
一条语句,简单 split(";") 会把它切两半然后拒掉,那比漏杀更让人无从下手。

## 工具(app/tools/datasource.py)

每个数据源动态生成一对 db_query__<源> / db_schema__<源>,而不是一个通用工具带
datasource 参数:工具名自带语义,模型不会把查销售库的 SQL 发给财务库;description
里直接塞表清单,省掉"先问有哪些表"那一轮。接进 registry.build_tools 作为第四来源
(前三个是内置/MCP/自定义)。

查询结果落 put_json(kind="query_snapshot"),把 SQL 原文 + 结果集 + 数据源一起存,
出具体系的数字回指能下钻到"这个数是哪条 SQL 查出来的"。

## 实测

真实 SQLite 业务库(600 行订单,埋了华东 6 月断崖的信号)+ 真实模型:
agent 8 轮自主查询——列表 → 查三张表结构 → 探数据时间范围 → 查地区维度 →
按月汇总 → 按地区+月份下钻,准确定位到华东 6 月从 1187 件跌到 354 件。
只读守卫在 agent 路径上同样生效(UPDATE/DROP/多语句全被拒且数据未变)。

测试 55 项:守卫 30 项(含"字符串里的分号不能误杀")、连接与探查 15 项、
URL 构造 6 项、Copilot 流式 4 项。
2026-09-17 10:39:23 +08:00

152 lines
5.5 KiB
Python

"""数据源连接层与工具层。
用真实的 SQLite 库跑——SQLAlchemy 统一了方言,SQLite 走的是和 MySQL/Oracle
同一套代码路径,所以这里验证的不只是 SQLite。各驱动特有的差异(Oracle 的
service_name、MySQL 的 charset)在 URL 构造那组用例里覆盖。
"""
from __future__ import annotations
import json
import sqlite3
from types import SimpleNamespace
import pytest
from app.data.engine import build_url, run_query, test_connection
from app.data.guard import QueryLimits, SqlRejected
from app.data.introspect import describe_table, introspect, summary, table_names
@pytest.fixture
def shop_db(tmp_path):
"""一个最小但真实的业务库:地区 / 商品 / 订单。"""
path = tmp_path / "shop.db"
db = sqlite3.connect(path)
db.executescript("""
CREATE TABLE regions (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE orders (
id INTEGER PRIMARY KEY, region_id INTEGER NOT NULL,
qty INTEGER NOT NULL, amount REAL NOT NULL, ordered_at TEXT NOT NULL
);
""")
db.executemany("INSERT INTO regions(id,name) VALUES(?,?)",
[(1, "华东"), (2, "华北")])
db.executemany(
"INSERT INTO orders(id,region_id,qty,amount,ordered_at) VALUES(?,?,?,?,?)",
[(i, 1 + i % 2, i, i * 10.5, "2026-06-15") for i in range(1, 101)],
)
db.commit()
db.close()
return str(path)
@pytest.fixture
def source(shop_db):
return SimpleNamespace(
id="test-src", name="sales", kind="sqlite", database=shop_db,
host=None, port=None, username=None, password=None, options={},
readonly=True, description="测试销售库", schema_cache={},
)
async def test_connection_and_introspect(source):
assert (await test_connection(source))["ok"]
source.schema_cache = await introspect(source)
assert set(table_names(source)) == {"regions", "orders"}
orders = source.schema_cache["tables"]["orders"]
assert [c["name"] for c in orders["columns"]] == [
"id", "region_id", "qty", "amount", "ordered_at"
]
assert orders["primary_key"] == ["id"]
async def test_summary_is_compact_enough_for_a_prompt(source):
source.schema_cache = await introspect(source)
text = summary(source)
assert "orders" in text and "amount" in text
# 摘要要能塞进 system prompt——超出这个量级就该改成按需探查
assert len(text) < 2000
async def test_summary_says_so_when_never_introspected(source):
"""没探查过就明说,别让 Copilot 对着空气编表名。"""
assert "尚未探查" in summary(source)
async def test_describe_table_lists_unknown_table_options(source):
source.schema_cache = await introspect(source)
out = describe_table(source, "没有这张表")
assert "现有的表" in out and "orders" in out
async def test_query_returns_rows(source):
result = await run_query(source, "SELECT COUNT(*) AS c FROM orders")
assert result.rows[0][0] == 100
assert result.columns == ["c"]
async def test_readonly_guard_applies_on_real_connection(source):
"""守卫不能只在单测里生效——真实连接路径上也必须拦住。"""
for sql in ("UPDATE orders SET qty=0", "DROP TABLE orders", "SELECT 1; DROP TABLE orders"):
with pytest.raises(SqlRejected):
await run_query(source, sql)
# 数据确实没被动过
assert (await run_query(source, "SELECT COUNT(*) FROM orders")).rows[0][0] == 100
async def test_result_set_is_capped(source):
"""一条 SELECT * 不该把内存和模型上下文一起打爆。"""
result = await run_query(source, "SELECT * FROM orders", limits=QueryLimits(max_rows=10))
assert result.row_count == 10
assert result.truncated is True
async def test_rows_are_json_serializable(source):
"""Decimal / date / bytes 在真实业务数据里遍地都是,不处理等于不可用。"""
result = await run_query(source, "SELECT amount, ordered_at FROM orders LIMIT 3")
json.dumps(result.to_payload()) # 不抛就算过
# --------------------------------------------------------------------------
# URL 构造:各驱动的方言差异
# --------------------------------------------------------------------------
def _src(kind, **kw):
base = dict(id="x", name="n", readonly=True, host="db", port=None,
database=None, username="u", password="p", options={})
base.update(kw)
return SimpleNamespace(kind=kind, **base)
@pytest.mark.parametrize("kind,expect", [
("mysql", "mysql+aiomysql://"),
("postgres", "postgresql+asyncpg://"),
("oracle", "oracle+oracledb://"),
])
def test_url_uses_async_drivers(kind, expect):
opts = {"service_name": "ORCL"} if kind == "oracle" else {}
assert build_url(_src(kind, database="d", options=opts)).startswith(expect)
def test_password_is_masked_by_default():
"""密码不该出现在日志、事件流或任何返回给前端的地方。"""
url = build_url(_src("mysql", database="d"))
assert "***" in url and ":p@" not in url
def test_oracle_requires_service_name_or_sid():
"""Oracle 最常见的配错点,要给明确提示而不是让驱动报晦涩的 ORA 错误。"""
with pytest.raises(ValueError, match="service_name"):
build_url(_src("oracle"))
def test_oracle_accepts_database_as_service_name():
assert "service_name=ORCLPDB1" in build_url(_src("oracle", database="ORCLPDB1"))
def test_unknown_kind_is_rejected():
with pytest.raises(ValueError, match="不支持"):
build_url(_src("mongodb"))