@ginkgolab/datasources 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/certified.js +3 -109
- package/dist/chunk-IJOM466W.js +324 -0
- package/dist/chunk-K2QVVHDO.js +482 -0
- package/dist/chunk-NTJXQDHH.js +21 -0
- package/dist/chunk-XX5MM5RN.js +51 -0
- package/dist/chunk-YDPLKNPL.js +113 -0
- package/dist/chunk-YU3RO2LC.js +63 -0
- package/dist/gateway.js +6 -523
- package/dist/index.js +40 -991
- package/dist/parseToolResult.js +4 -16
- package/dist/schema/card.js +17 -306
- package/dist/schema/store.js +6 -46
- package/dist/sqlGuard.js +5 -57
- package/package.json +1 -1
- package/dist/manager-BLTs1PDe.d.ts +0 -362
|
@@ -0,0 +1,482 @@
|
|
|
1
|
+
import {
|
|
2
|
+
assertReadOnlySql
|
|
3
|
+
} from "./chunk-YU3RO2LC.js";
|
|
4
|
+
import {
|
|
5
|
+
parseToolResult
|
|
6
|
+
} from "./chunk-NTJXQDHH.js";
|
|
7
|
+
|
|
8
|
+
// src/gateway/queryCache.ts
|
|
9
|
+
import { createHash } from "crypto";
|
|
10
|
+
function normalizeSqlForCache(sql) {
|
|
11
|
+
const trimmed = sql.trim().replace(/;+\s*$/, "");
|
|
12
|
+
const LITERAL_RE = /('(?:[^']|'')*'|"(?:[^"]|"")*")/g;
|
|
13
|
+
const parts = [];
|
|
14
|
+
let last = 0;
|
|
15
|
+
let m;
|
|
16
|
+
while ((m = LITERAL_RE.exec(trimmed)) !== null) {
|
|
17
|
+
parts.push(trimmed.slice(last, m.index).replace(/\s+/g, " ").toLowerCase());
|
|
18
|
+
parts.push(m[0]);
|
|
19
|
+
last = m.index + m[0].length;
|
|
20
|
+
}
|
|
21
|
+
parts.push(trimmed.slice(last).replace(/\s+/g, " ").toLowerCase());
|
|
22
|
+
return parts.join("");
|
|
23
|
+
}
|
|
24
|
+
function computeQueryHashKey(sourceId, sql, params) {
|
|
25
|
+
const normSql = normalizeSqlForCache(sql);
|
|
26
|
+
const sqlHash = createHash("sha256").update(normSql).digest("hex");
|
|
27
|
+
const paramsHash = createHash("sha256").update(JSON.stringify(params ?? [])).digest("hex");
|
|
28
|
+
return {
|
|
29
|
+
sourceId,
|
|
30
|
+
sqlHash,
|
|
31
|
+
paramsHash
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
function formatCacheKey(key) {
|
|
35
|
+
return `${key.sourceId}:${key.sqlHash}:${key.paramsHash}`;
|
|
36
|
+
}
|
|
37
|
+
function formatCacheKeyDisplay(key) {
|
|
38
|
+
return `${key.sourceId}:${key.sqlHash.slice(0, 16)}:${key.paramsHash.slice(0, 8)}`;
|
|
39
|
+
}
|
|
40
|
+
var QueryCacheManager = class {
|
|
41
|
+
cache = /* @__PURE__ */ new Map();
|
|
42
|
+
maxEntries;
|
|
43
|
+
defaultTtlMs;
|
|
44
|
+
constructor(options) {
|
|
45
|
+
this.maxEntries = options?.maxEntries ?? 500;
|
|
46
|
+
this.defaultTtlMs = options?.defaultTtlMs ?? 15 * 60 * 1e3;
|
|
47
|
+
}
|
|
48
|
+
get(key) {
|
|
49
|
+
const formatted = formatCacheKey(key);
|
|
50
|
+
const entry = this.cache.get(formatted);
|
|
51
|
+
if (!entry) return null;
|
|
52
|
+
const now = Date.now();
|
|
53
|
+
if (now - entry.cachedAt > entry.ttlMs) {
|
|
54
|
+
this.cache.delete(formatted);
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
this.cache.delete(formatted);
|
|
58
|
+
this.cache.set(formatted, entry);
|
|
59
|
+
return {
|
|
60
|
+
data: entry.data,
|
|
61
|
+
cachedAt: entry.cachedAt
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
set(key, data, ttlMs) {
|
|
65
|
+
const formatted = formatCacheKey(key);
|
|
66
|
+
const now = Date.now();
|
|
67
|
+
if (this.cache.size >= this.maxEntries) {
|
|
68
|
+
const firstKey = this.cache.keys().next().value;
|
|
69
|
+
if (firstKey) this.cache.delete(firstKey);
|
|
70
|
+
}
|
|
71
|
+
this.cache.set(formatted, {
|
|
72
|
+
key: formatted,
|
|
73
|
+
data,
|
|
74
|
+
cachedAt: now,
|
|
75
|
+
ttlMs: ttlMs ?? this.defaultTtlMs
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* 清除特定数据源或全部缓存
|
|
80
|
+
*/
|
|
81
|
+
invalidate(sourceId) {
|
|
82
|
+
if (!sourceId) {
|
|
83
|
+
this.cache.clear();
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const prefix = `${sourceId}:`;
|
|
87
|
+
for (const k of this.cache.keys()) {
|
|
88
|
+
if (k.startsWith(prefix)) {
|
|
89
|
+
this.cache.delete(k);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
size() {
|
|
94
|
+
return this.cache.size;
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
// src/gateway/explainGuard.ts
|
|
99
|
+
var DEFAULT_BUDGET = 1e6;
|
|
100
|
+
var SQL_FAULT_RE = /syntax error|parse error|does not exist|unknown (column|table|identifier)|no such (table|column)|undefined (table|column|parameter)|ambiguous|42P01|42P02|42703|ER_(NO_SUCH_TABLE|BAD_FIELD_ERROR|PARSE_ERROR)|1146|1054|1064/i;
|
|
101
|
+
function parsePostgresPlan(plan) {
|
|
102
|
+
let totalRows = Number(plan["Plan Rows"] ?? 0);
|
|
103
|
+
let hasSeqScan = plan["Node Type"] === "Seq Scan";
|
|
104
|
+
const seqScanTables = [];
|
|
105
|
+
if (hasSeqScan && plan["Relation Name"]) {
|
|
106
|
+
seqScanTables.push(String(plan["Relation Name"]));
|
|
107
|
+
}
|
|
108
|
+
const plans = plan["Plans"] || [];
|
|
109
|
+
for (const subPlan of plans) {
|
|
110
|
+
const sub = parsePostgresPlan(subPlan);
|
|
111
|
+
totalRows = Math.max(totalRows, sub.totalRows);
|
|
112
|
+
if (sub.hasSeqScan) hasSeqScan = true;
|
|
113
|
+
seqScanTables.push(...sub.seqScanTables);
|
|
114
|
+
}
|
|
115
|
+
return { totalRows, hasSeqScan, seqScanTables };
|
|
116
|
+
}
|
|
117
|
+
function parseMysqlPlan(obj) {
|
|
118
|
+
let totalRows = 0;
|
|
119
|
+
let hasAllScan = false;
|
|
120
|
+
const allScanTables = [];
|
|
121
|
+
function walk(node) {
|
|
122
|
+
if (!node || typeof node !== "object") return;
|
|
123
|
+
const rec = node;
|
|
124
|
+
if (rec["table"] && typeof rec["table"] === "object") {
|
|
125
|
+
const tableObj = rec["table"];
|
|
126
|
+
const rows = Number(tableObj["rows_examined_per_scan"] ?? tableObj["rows"] ?? 0);
|
|
127
|
+
totalRows += rows;
|
|
128
|
+
if (tableObj["access_type"] === "ALL") {
|
|
129
|
+
hasAllScan = true;
|
|
130
|
+
if (tableObj["table_name"]) {
|
|
131
|
+
allScanTables.push(String(tableObj["table_name"]));
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
for (const v of Object.values(rec)) {
|
|
136
|
+
if (Array.isArray(v)) {
|
|
137
|
+
v.forEach(walk);
|
|
138
|
+
} else if (v && typeof v === "object") {
|
|
139
|
+
walk(v);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
walk(obj);
|
|
144
|
+
return { totalRows, hasAllScan, allScanTables };
|
|
145
|
+
}
|
|
146
|
+
async function dryRunExplain(client, dbType, sql, options, params) {
|
|
147
|
+
const budget = options?.maxScanRowsBudget ?? DEFAULT_BUDGET;
|
|
148
|
+
const blockFullTableScan = options?.blockFullTableScan ?? true;
|
|
149
|
+
const cleanSql = sql.trim().replace(/;+$/, "");
|
|
150
|
+
try {
|
|
151
|
+
let explainSql = "";
|
|
152
|
+
if (dbType === "postgres") {
|
|
153
|
+
explainSql = `EXPLAIN (FORMAT JSON) ${cleanSql}`;
|
|
154
|
+
} else if (dbType === "mysql") {
|
|
155
|
+
explainSql = `EXPLAIN FORMAT=JSON ${cleanSql}`;
|
|
156
|
+
} else if (dbType === "sqlite") {
|
|
157
|
+
explainSql = `EXPLAIN QUERY PLAN ${cleanSql}`;
|
|
158
|
+
} else if (dbType === "duckdb") {
|
|
159
|
+
explainSql = `EXPLAIN ${cleanSql}`;
|
|
160
|
+
} else if (dbType === "clickhouse") {
|
|
161
|
+
explainSql = `EXPLAIN ESTIMATE ${cleanSql}`;
|
|
162
|
+
} else {
|
|
163
|
+
explainSql = `EXPLAIN ${cleanSql}`;
|
|
164
|
+
}
|
|
165
|
+
const res = await client.query(explainSql, params);
|
|
166
|
+
const rows = res.rows;
|
|
167
|
+
let estimatedRows = 0;
|
|
168
|
+
let isFullTableScan = false;
|
|
169
|
+
let scanTargetDetail = "";
|
|
170
|
+
if (dbType === "postgres" && rows.length > 0) {
|
|
171
|
+
const rawJson = Object.values(rows[0])[0];
|
|
172
|
+
const parsed = typeof rawJson === "string" ? JSON.parse(rawJson) : rawJson;
|
|
173
|
+
const planRoot = Array.isArray(parsed) ? parsed[0]?.Plan : parsed?.Plan;
|
|
174
|
+
if (planRoot) {
|
|
175
|
+
const { totalRows, hasSeqScan, seqScanTables } = parsePostgresPlan(planRoot);
|
|
176
|
+
estimatedRows = totalRows;
|
|
177
|
+
isFullTableScan = hasSeqScan && estimatedRows > 5e3;
|
|
178
|
+
if (seqScanTables.length > 0) {
|
|
179
|
+
scanTargetDetail = `\uFF08\u8868: ${seqScanTables.join(", ")}\uFF09`;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
} else if (dbType === "mysql" && rows.length > 0) {
|
|
183
|
+
const rawJson = Object.values(rows[0])[0];
|
|
184
|
+
const parsed = typeof rawJson === "string" ? JSON.parse(rawJson) : rawJson;
|
|
185
|
+
if (parsed) {
|
|
186
|
+
const { totalRows, hasAllScan, allScanTables } = parseMysqlPlan(parsed);
|
|
187
|
+
estimatedRows = totalRows;
|
|
188
|
+
isFullTableScan = hasAllScan && estimatedRows > 5e3;
|
|
189
|
+
if (allScanTables.length > 0) {
|
|
190
|
+
scanTargetDetail = `\uFF08\u8868: ${allScanTables.join(", ")}\uFF09`;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
} else if (dbType === "sqlite") {
|
|
194
|
+
for (const row of rows) {
|
|
195
|
+
const detail = String(row["detail"] || Object.values(row)[0] || "");
|
|
196
|
+
if (detail.includes("SCAN TABLE") && !detail.includes("USING INDEX")) {
|
|
197
|
+
isFullTableScan = true;
|
|
198
|
+
scanTargetDetail = `\uFF08${detail}\uFF09`;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
} else if (dbType === "duckdb") {
|
|
202
|
+
for (const row of rows) {
|
|
203
|
+
const detail = String(row["explain_value"] || Object.values(row)[0] || "");
|
|
204
|
+
if (detail.includes("SEQ_SCAN")) {
|
|
205
|
+
isFullTableScan = true;
|
|
206
|
+
scanTargetDetail = `\uFF08SEQ_SCAN\uFF09`;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
} else if (dbType === "clickhouse") {
|
|
210
|
+
for (const row of rows) {
|
|
211
|
+
const line = String(Object.values(row)[0] || "");
|
|
212
|
+
const match = line.match(/rows:\s*(\d+)/i);
|
|
213
|
+
if (match) {
|
|
214
|
+
estimatedRows = Number(match[1]);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
const exceedsBudget = estimatedRows > budget;
|
|
219
|
+
let costWarning;
|
|
220
|
+
if (exceedsBudget) {
|
|
221
|
+
costWarning = `\u6210\u672C\u95E8\u7981\u62E6\u622A\uFF1A\u9884\u4F30\u626B\u63CF\u884C\u6570 (${estimatedRows.toLocaleString()}) \u8D85\u8FC7\u5B89\u5168\u9884\u7B97\u4E0A\u9650 (${budget.toLocaleString()})\u3002\u8BF7\u5728 SQL \u4E2D\u8865\u5145\u5408\u9002\u7684\u65F6\u95F4\u5206\u533A\u6761\u4EF6\uFF08\u5982 WHERE date >= ...\uFF09\u6216\u589E\u52A0 LIMIT\u3002`;
|
|
222
|
+
} else if (isFullTableScan && blockFullTableScan && estimatedRows > budget / 2) {
|
|
223
|
+
costWarning = `\u6210\u672C\u95E8\u7981\u8B66\u544A\uFF1A\u68C0\u6D4B\u5230\u5927\u89C4\u6A21\u5168\u8868\u626B\u63CF\u98CE\u9669 ${scanTargetDetail}\uFF0C\u9884\u4F30\u626B\u63CF\u884C\u6570\u7EA6 ${estimatedRows.toLocaleString()}\u3002\u5EFA\u8BAE\u8865\u5145\u9488\u5BF9\u7D22\u5F15\u5B57\u6BB5\u7684\u8FC7\u6EE4\u6761\u4EF6\u3002`;
|
|
224
|
+
}
|
|
225
|
+
return {
|
|
226
|
+
isValid: true,
|
|
227
|
+
estimatedRows,
|
|
228
|
+
isFullTableScan,
|
|
229
|
+
exceedsBudget,
|
|
230
|
+
costWarning,
|
|
231
|
+
planRaw: rows.slice(0, 5)
|
|
232
|
+
};
|
|
233
|
+
} catch (err) {
|
|
234
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
235
|
+
if (SQL_FAULT_RE.test(message)) {
|
|
236
|
+
return {
|
|
237
|
+
isValid: false,
|
|
238
|
+
estimatedRows: 0,
|
|
239
|
+
isFullTableScan: false,
|
|
240
|
+
exceedsBudget: false,
|
|
241
|
+
syntaxError: message,
|
|
242
|
+
costWarning: `\u6267\u884C\u8BA1\u5212\u9884\u68C0\u5931\u8D25\uFF08\u8BED\u6CD5\u6216\u8868/\u5B57\u6BB5\u4E0D\u5B58\u5728\uFF09\uFF1A${message}`
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
return {
|
|
246
|
+
isValid: true,
|
|
247
|
+
estimatedRows: 0,
|
|
248
|
+
isFullTableScan: false,
|
|
249
|
+
exceedsBudget: false,
|
|
250
|
+
degraded: true,
|
|
251
|
+
costWarning: `EXPLAIN \u9884\u68C0\u4E0D\u53EF\u7528\uFF0C\u5DF2\u964D\u7EA7\u4E3A\u76F4\u63A5\u6267\u884C\uFF08\u4ECD\u53D7\u53EA\u8BFB\u4E0E\u884C\u6570\u5C01\u9876\u4FDD\u62A4\uFF09\uFF1A${message}`
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// src/gateway/queryPipeline.ts
|
|
257
|
+
async function executeSqlWithGuards(opts) {
|
|
258
|
+
const sql = opts.sql.trim();
|
|
259
|
+
assertReadOnlySql(sql);
|
|
260
|
+
const cacheKey = computeQueryHashKey(opts.sourceId, sql, opts.params);
|
|
261
|
+
if (!opts.skipCache) {
|
|
262
|
+
const cached = opts.cache.get(cacheKey);
|
|
263
|
+
if (cached) {
|
|
264
|
+
if (opts.logPrefix) {
|
|
265
|
+
console.log(
|
|
266
|
+
`[${opts.logPrefix}] \u547D\u4E2D MCP \u7F51\u5173\u67E5\u8BE2\u7F13\u5B58 (SQL Hash: ${cacheKey.sqlHash.slice(0, 8)})`
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
return {
|
|
270
|
+
data: cached.data,
|
|
271
|
+
cacheHit: true,
|
|
272
|
+
cachedAt: cached.cachedAt
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
let explainReport;
|
|
277
|
+
if (opts.dialectClient && !opts.bypassExplain) {
|
|
278
|
+
explainReport = await dryRunExplain(
|
|
279
|
+
opts.dialectClient.client,
|
|
280
|
+
opts.dialectClient.dbType,
|
|
281
|
+
sql,
|
|
282
|
+
opts.explainOptions,
|
|
283
|
+
opts.params
|
|
284
|
+
);
|
|
285
|
+
if (explainReport.degraded && opts.logPrefix) {
|
|
286
|
+
console.warn(
|
|
287
|
+
`[${opts.logPrefix}] EXPLAIN \u9884\u68C0\u964D\u7EA7\u653E\u884C: ${explainReport.costWarning}`
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
if (!explainReport.isValid) {
|
|
291
|
+
throw new Error(
|
|
292
|
+
explainReport.costWarning || `SQL \u6267\u884C\u8BA1\u5212\u8BED\u6CD5\u9884\u68C0\u5931\u8D25: ${explainReport.syntaxError}`
|
|
293
|
+
);
|
|
294
|
+
}
|
|
295
|
+
if (explainReport.exceedsBudget) {
|
|
296
|
+
throw new Error(
|
|
297
|
+
explainReport.costWarning || "SQL \u626B\u63CF\u6570\u636E\u884C\u6570\u8D85\u8FC7\u5355\u6B21\u67E5\u8BE2\u9884\u7B97\uFF0C\u5DF2\u89E6\u53D1\u7194\u65AD\u4FDD\u62A4\uFF01"
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
const data = await opts.execute();
|
|
302
|
+
opts.cache.set(cacheKey, data, opts.cacheTtlMs);
|
|
303
|
+
return { data, cacheHit: false, explainReport };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// src/gateway/queryGateway.ts
|
|
307
|
+
var TABLE_IDENTIFIER_RE = /^[A-Za-z_][\w$]*(\.[A-Za-z_][\w$]*)*$/;
|
|
308
|
+
var QueryGateway = class {
|
|
309
|
+
cache;
|
|
310
|
+
manager;
|
|
311
|
+
config;
|
|
312
|
+
constructor(manager, config, sharedCache) {
|
|
313
|
+
this.manager = manager;
|
|
314
|
+
this.config = config ?? {};
|
|
315
|
+
this.cache = sharedCache ?? new QueryCacheManager({
|
|
316
|
+
maxEntries: config?.maxCacheEntries,
|
|
317
|
+
defaultTtlMs: config?.defaultCacheTtlMs
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* 按数据源 ID 与工具原名检索已绑定的工具调用契约
|
|
322
|
+
*/
|
|
323
|
+
async getTool(sourceId, toolName) {
|
|
324
|
+
const conf = this.manager.get(sourceId);
|
|
325
|
+
if (!conf || conf.enabled === false) return void 0;
|
|
326
|
+
const tools = await this.manager.tools(conf);
|
|
327
|
+
return tools.find(
|
|
328
|
+
(t) => t.originalName === toolName || t.name === `${sourceId}_${toolName}`
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* 核心方法:执行 SQL 查询(流经共享守卫管线)
|
|
333
|
+
*/
|
|
334
|
+
async executeQuery(args) {
|
|
335
|
+
const { sourceId, sql, params, skipCache, bypassExplain, cacheTtlMs } = args;
|
|
336
|
+
const startTime = Date.now();
|
|
337
|
+
const conf = this.manager.get(sourceId);
|
|
338
|
+
if (!conf || conf.enabled === false) {
|
|
339
|
+
throw new Error(`\u6570\u636E\u6E90 [${sourceId}] \u672A\u5C31\u7EEA\u6216\u672A\u542F\u7528`);
|
|
340
|
+
}
|
|
341
|
+
const result = await executeSqlWithGuards({
|
|
342
|
+
sourceId,
|
|
343
|
+
sql,
|
|
344
|
+
params,
|
|
345
|
+
skipCache,
|
|
346
|
+
bypassExplain,
|
|
347
|
+
cacheTtlMs,
|
|
348
|
+
dialectClient: this.manager.getDialectClient?.(sourceId),
|
|
349
|
+
cache: this.cache,
|
|
350
|
+
explainOptions: this.config.explainOptions,
|
|
351
|
+
logPrefix: `Gateway ${sourceId}`,
|
|
352
|
+
execute: async () => {
|
|
353
|
+
const toolBinding = await this.getTool(sourceId, "execute_sql");
|
|
354
|
+
if (!toolBinding) {
|
|
355
|
+
throw new Error(`\u6570\u636E\u6E90 [${sourceId}] \u672A\u66B4\u9732 execute_sql \u5DE5\u5177\u63A5\u53E3`);
|
|
356
|
+
}
|
|
357
|
+
const conn = await this.manager.connect(conf);
|
|
358
|
+
const raw = await conn.callTool("execute_sql", {
|
|
359
|
+
sql,
|
|
360
|
+
...params !== void 0 ? { params } : {}
|
|
361
|
+
});
|
|
362
|
+
const parsed = parseToolResult(raw, "tool execute_sql");
|
|
363
|
+
let rows = [];
|
|
364
|
+
let rowCount = 0;
|
|
365
|
+
if (parsed && typeof parsed === "object") {
|
|
366
|
+
if (!Array.isArray(parsed) && Array.isArray(parsed.rows)) {
|
|
367
|
+
rows = parsed.rows;
|
|
368
|
+
rowCount = typeof parsed.rowCount === "number" ? parsed.rowCount : rows.length;
|
|
369
|
+
} else if (Array.isArray(parsed)) {
|
|
370
|
+
rows = parsed;
|
|
371
|
+
rowCount = rows.length;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
return { rows, rowCount };
|
|
375
|
+
}
|
|
376
|
+
});
|
|
377
|
+
return {
|
|
378
|
+
rows: result.data.rows,
|
|
379
|
+
rowCount: result.data.rowCount,
|
|
380
|
+
cacheHit: result.cacheHit,
|
|
381
|
+
cachedAt: result.cachedAt,
|
|
382
|
+
durationMs: Date.now() - startTime,
|
|
383
|
+
explainReport: result.explainReport
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* 两阶段发现第一阶段:获取全量数据源及其表名概览(不含详细字段,防上下文撑爆)
|
|
388
|
+
*/
|
|
389
|
+
async listCatalogs() {
|
|
390
|
+
const list = this.manager.list().filter((c) => c.enabled !== false);
|
|
391
|
+
const results = [];
|
|
392
|
+
for (const item of list) {
|
|
393
|
+
const listTool = await this.getTool(item.id, "list_tables");
|
|
394
|
+
let tables = [];
|
|
395
|
+
if (listTool) {
|
|
396
|
+
try {
|
|
397
|
+
const res = await listTool.call({});
|
|
398
|
+
if (res && Array.isArray(res.tables)) {
|
|
399
|
+
tables = res.tables.map(
|
|
400
|
+
(t) => typeof t === "string" ? t : String(t?.table ?? "")
|
|
401
|
+
).filter(Boolean);
|
|
402
|
+
}
|
|
403
|
+
} catch {
|
|
404
|
+
tables = [];
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
results.push({
|
|
408
|
+
sourceId: item.id,
|
|
409
|
+
name: item.name,
|
|
410
|
+
type: item.dbType ?? item.kind,
|
|
411
|
+
tables
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
return results;
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* 两阶段发现第二阶段:按需拉取特定表的详细 Schema 与前 3 条样本数据
|
|
418
|
+
*/
|
|
419
|
+
async describeTableResource(sourceId, tableName) {
|
|
420
|
+
if (!TABLE_IDENTIFIER_RE.test(tableName)) {
|
|
421
|
+
throw new Error(`\u975E\u6CD5\u8868\u540D\u6807\u8BC6\u7B26: ${tableName}`);
|
|
422
|
+
}
|
|
423
|
+
const describeTool = await this.getTool(sourceId, "describe_table");
|
|
424
|
+
if (!describeTool) {
|
|
425
|
+
throw new Error(`\u6570\u636E\u6E90 [${sourceId}] \u672A\u63D0\u4F9B describe_table \u5DE5\u5177`);
|
|
426
|
+
}
|
|
427
|
+
const descRes = await describeTool.call({
|
|
428
|
+
table_name: tableName,
|
|
429
|
+
table: tableName
|
|
430
|
+
});
|
|
431
|
+
const columns = [];
|
|
432
|
+
if (descRes && Array.isArray(descRes.columns)) {
|
|
433
|
+
for (const col of descRes.columns) {
|
|
434
|
+
columns.push({
|
|
435
|
+
name: String(col.column || col.name),
|
|
436
|
+
type: String(col.type || "string"),
|
|
437
|
+
comment: col.comment ? String(col.comment) : void 0
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
let sampleRows = [];
|
|
442
|
+
try {
|
|
443
|
+
const sampleRes = await this.executeQuery({
|
|
444
|
+
sourceId,
|
|
445
|
+
sql: `SELECT * FROM ${tableName} LIMIT 3`,
|
|
446
|
+
skipCache: false,
|
|
447
|
+
bypassExplain: true
|
|
448
|
+
});
|
|
449
|
+
sampleRows = sampleRes.rows;
|
|
450
|
+
} catch {
|
|
451
|
+
sampleRows = [];
|
|
452
|
+
}
|
|
453
|
+
return {
|
|
454
|
+
sourceId,
|
|
455
|
+
tableName,
|
|
456
|
+
columns,
|
|
457
|
+
sampleRows
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* 清除网关缓存(共享实例时等同清除该源的全部缓存)
|
|
462
|
+
*/
|
|
463
|
+
invalidateCache(sourceId) {
|
|
464
|
+
this.cache.invalidate(sourceId);
|
|
465
|
+
}
|
|
466
|
+
getCacheManager() {
|
|
467
|
+
return this.cache;
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
var McpGateway = QueryGateway;
|
|
471
|
+
|
|
472
|
+
export {
|
|
473
|
+
normalizeSqlForCache,
|
|
474
|
+
computeQueryHashKey,
|
|
475
|
+
formatCacheKey,
|
|
476
|
+
formatCacheKeyDisplay,
|
|
477
|
+
QueryCacheManager,
|
|
478
|
+
dryRunExplain,
|
|
479
|
+
executeSqlWithGuards,
|
|
480
|
+
QueryGateway,
|
|
481
|
+
McpGateway
|
|
482
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// src/parseToolResult.ts
|
|
2
|
+
function parseToolResult(res, toolLabel) {
|
|
3
|
+
const r = res ?? {};
|
|
4
|
+
const contentList = Array.isArray(r.content) ? r.content : [];
|
|
5
|
+
if (r.isError) {
|
|
6
|
+
const errorText = contentList.map((c) => c.text || "").join("\n");
|
|
7
|
+
throw new Error(errorText || `${toolLabel} execution failed`);
|
|
8
|
+
}
|
|
9
|
+
const textOutput = contentList.filter((c) => c.type === "text").map((c) => c.text || "").join("\n");
|
|
10
|
+
try {
|
|
11
|
+
return JSON.parse(textOutput);
|
|
12
|
+
} catch {
|
|
13
|
+
return textOutput;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
var parseMcpToolResult = parseToolResult;
|
|
17
|
+
|
|
18
|
+
export {
|
|
19
|
+
parseToolResult,
|
|
20
|
+
parseMcpToolResult
|
|
21
|
+
};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CARD_STORE_MAX_BYTES
|
|
3
|
+
} from "./chunk-IJOM466W.js";
|
|
4
|
+
|
|
5
|
+
// src/schema/store.ts
|
|
6
|
+
import fs from "fs/promises";
|
|
7
|
+
import path from "path";
|
|
8
|
+
var ID_RE = /^[\w-]+$/;
|
|
9
|
+
function isValidSourceId(id) {
|
|
10
|
+
return ID_RE.test(id) && id.length <= 100;
|
|
11
|
+
}
|
|
12
|
+
function isSchemaCard(value) {
|
|
13
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
14
|
+
return false;
|
|
15
|
+
}
|
|
16
|
+
const v = value;
|
|
17
|
+
return typeof v.sourceId === "string" && typeof v.generatedAt === "number" && (v.kind === "db-like" || v.kind === "tools-only" || v.kind === "mcp") && Array.isArray(v.tables) && typeof v.truncated === "boolean";
|
|
18
|
+
}
|
|
19
|
+
async function readSchemaCard(dir, sourceId) {
|
|
20
|
+
if (!isValidSourceId(sourceId)) return null;
|
|
21
|
+
try {
|
|
22
|
+
const raw = await fs.readFile(path.join(dir, `${sourceId}.json`), "utf-8");
|
|
23
|
+
const parsed = JSON.parse(raw);
|
|
24
|
+
return isSchemaCard(parsed) ? parsed : null;
|
|
25
|
+
} catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
async function writeSchemaCard(dir, card) {
|
|
30
|
+
if (!isValidSourceId(card.sourceId)) {
|
|
31
|
+
throw new Error(`\u975E\u6CD5 sourceId: ${card.sourceId}`);
|
|
32
|
+
}
|
|
33
|
+
const text = JSON.stringify(card, null, 2);
|
|
34
|
+
if (Buffer.byteLength(text, "utf-8") > CARD_STORE_MAX_BYTES) {
|
|
35
|
+
throw new Error(
|
|
36
|
+
`\u7ED3\u6784\u5361\u8D85\u8FC7 ${CARD_STORE_MAX_BYTES} \u5B57\u8282\u4E0A\u9650\uFF08\u6784\u5EFA\u9884\u7B97\u5931\u5B88\uFF09: ${card.sourceId}`
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
await fs.mkdir(dir, { recursive: true });
|
|
40
|
+
await fs.writeFile(path.join(dir, `${card.sourceId}.json`), text, "utf-8");
|
|
41
|
+
}
|
|
42
|
+
async function deleteSchemaCard(dir, sourceId) {
|
|
43
|
+
if (!isValidSourceId(sourceId)) return;
|
|
44
|
+
await fs.rm(path.join(dir, `${sourceId}.json`), { force: true });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export {
|
|
48
|
+
readSchemaCard,
|
|
49
|
+
writeSchemaCard,
|
|
50
|
+
deleteSchemaCard
|
|
51
|
+
};
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// src/certified/certifiedStore.ts
|
|
2
|
+
import fs from "fs";
|
|
3
|
+
import path from "path";
|
|
4
|
+
var CertifiedQueryStore = class {
|
|
5
|
+
queries = /* @__PURE__ */ new Map();
|
|
6
|
+
configPath;
|
|
7
|
+
initialQueries = [];
|
|
8
|
+
lastMtimeMs = 0;
|
|
9
|
+
constructor(options) {
|
|
10
|
+
this.configPath = options?.configPath;
|
|
11
|
+
if (options?.initialQueries) {
|
|
12
|
+
this.initialQueries = options.initialQueries;
|
|
13
|
+
for (const q of options.initialQueries) {
|
|
14
|
+
this.queries.set(q.id, q);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
if (this.configPath) {
|
|
18
|
+
this.loadFromFile(this.configPath);
|
|
19
|
+
this.touchMtime();
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
touchMtime() {
|
|
23
|
+
try {
|
|
24
|
+
this.lastMtimeMs = this.configPath ? fs.statSync(this.configPath).mtimeMs : 0;
|
|
25
|
+
} catch {
|
|
26
|
+
this.lastMtimeMs = 0;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* 配置文件 mtime 热加载:文件变更后重建内存索引(含 initialQueries 垫底)。
|
|
31
|
+
* 每次语义路由前调用一次(一次 stat 的成本),免去改配置必须重启进程。
|
|
32
|
+
*/
|
|
33
|
+
reloadIfChanged() {
|
|
34
|
+
if (!this.configPath) return;
|
|
35
|
+
let mtime = 0;
|
|
36
|
+
try {
|
|
37
|
+
mtime = fs.statSync(this.configPath).mtimeMs;
|
|
38
|
+
} catch {
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
if (mtime === this.lastMtimeMs) return;
|
|
42
|
+
this.lastMtimeMs = mtime;
|
|
43
|
+
this.queries.clear();
|
|
44
|
+
for (const q of this.initialQueries) {
|
|
45
|
+
this.queries.set(q.id, q);
|
|
46
|
+
}
|
|
47
|
+
this.loadFromFile(this.configPath);
|
|
48
|
+
}
|
|
49
|
+
loadFromFile(filePath) {
|
|
50
|
+
try {
|
|
51
|
+
if (!fs.existsSync(filePath)) return;
|
|
52
|
+
const content = fs.readFileSync(filePath, "utf-8");
|
|
53
|
+
const parsed = JSON.parse(content);
|
|
54
|
+
if (Array.isArray(parsed)) {
|
|
55
|
+
for (const item of parsed) {
|
|
56
|
+
if (item && item.id && item.sqlTemplate) {
|
|
57
|
+
this.queries.set(item.id, item);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
} catch (err) {
|
|
62
|
+
console.warn(`[CertifiedQueryStore] \u52A0\u8F7D\u8BA4\u8BC1\u67E5\u8BE2\u914D\u7F6E\u5931\u8D25 (${filePath}):`, err);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
saveToFile(filePath) {
|
|
66
|
+
const target = filePath || this.configPath;
|
|
67
|
+
if (!target) return;
|
|
68
|
+
try {
|
|
69
|
+
const dir = path.dirname(target);
|
|
70
|
+
if (!fs.existsSync(dir)) {
|
|
71
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
72
|
+
}
|
|
73
|
+
const data = Array.from(this.queries.values());
|
|
74
|
+
fs.writeFileSync(target, JSON.stringify(data, null, 2), "utf-8");
|
|
75
|
+
} catch (err) {
|
|
76
|
+
console.warn(`[CertifiedQueryStore] \u4FDD\u5B58\u8BA4\u8BC1\u67E5\u8BE2\u914D\u7F6E\u5931\u8D25 (${target}):`, err);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
list(sourceId) {
|
|
80
|
+
const all = Array.from(this.queries.values());
|
|
81
|
+
if (!sourceId) return all;
|
|
82
|
+
return all.filter((q) => q.sourceId === "*" || q.sourceId === sourceId);
|
|
83
|
+
}
|
|
84
|
+
get(id) {
|
|
85
|
+
return this.queries.get(id);
|
|
86
|
+
}
|
|
87
|
+
upsert(query) {
|
|
88
|
+
this.queries.set(query.id, {
|
|
89
|
+
...query,
|
|
90
|
+
certifiedAt: query.certifiedAt ?? Date.now()
|
|
91
|
+
});
|
|
92
|
+
if (this.configPath) {
|
|
93
|
+
this.saveToFile();
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
delete(id) {
|
|
97
|
+
const res = this.queries.delete(id);
|
|
98
|
+
if (res && this.configPath) {
|
|
99
|
+
this.saveToFile();
|
|
100
|
+
}
|
|
101
|
+
return res;
|
|
102
|
+
}
|
|
103
|
+
clear() {
|
|
104
|
+
this.queries.clear();
|
|
105
|
+
}
|
|
106
|
+
size() {
|
|
107
|
+
return this.queries.size;
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
export {
|
|
112
|
+
CertifiedQueryStore
|
|
113
|
+
};
|