fdb2 1.0.40 → 1.0.42

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.
Files changed (115) hide show
  1. package/README.md +14 -4
  2. package/dist/public/.vite/manifest.json +111 -1
  3. package/dist/public/database-monitor.css +468 -0
  4. package/dist/public/database-monitor.js +725 -0
  5. package/dist/public/database.css +740 -0
  6. package/dist/public/database.js +594 -0
  7. package/dist/public/database2.js +344 -0
  8. package/dist/public/echarts.js +79307 -0
  9. package/dist/public/explorer.css +1067 -366
  10. package/dist/public/explorer.js +3893 -35071
  11. package/dist/public/export.js +54831 -0
  12. package/dist/public/helpers.js +27 -0
  13. package/dist/public/index.js +399 -38
  14. package/dist/public/layout.css +98 -65
  15. package/dist/public/layout.js +59 -22
  16. package/dist/public/modal.js +168 -0
  17. package/dist/public/query-history.css +651 -0
  18. package/dist/public/query-history.js +526 -0
  19. package/dist/public/sql-query-editor.css +503 -0
  20. package/dist/public/sql-query-editor.js +655 -0
  21. package/dist/scripts/verify-db-support.cjs +93 -7
  22. package/dist/server/__tests__/excel-export.test.ts +136 -0
  23. package/dist/server/__tests__/export-progress.test.ts +80 -0
  24. package/dist/server/__tests__/health-check.test.ts +67 -0
  25. package/dist/server/__tests__/import-normalize.test.ts +79 -0
  26. package/dist/server/__tests__/query-metrics.test.ts +96 -0
  27. package/dist/server/__tests__/remote-proxy.test.ts +76 -0
  28. package/dist/server/__tests__/sql-safety.test.ts +36 -0
  29. package/dist/server/core/dialect.d.ts +3 -0
  30. package/dist/server/core/dialect.d.ts.map +1 -1
  31. package/dist/server/core/dialect.js +17 -0
  32. package/dist/server/core/dialect.js.map +1 -1
  33. package/dist/server/core/dialect.ts +20 -0
  34. package/dist/server/core/query-metrics.d.ts +33 -0
  35. package/dist/server/core/query-metrics.d.ts.map +1 -0
  36. package/dist/server/core/query-metrics.js +117 -0
  37. package/dist/server/core/query-metrics.js.map +1 -0
  38. package/dist/server/core/query-metrics.ts +137 -0
  39. package/dist/server/core/schema/__tests__/ddl-emitter.test.ts +152 -0
  40. package/dist/server/core/schema/canonical.d.ts.map +1 -1
  41. package/dist/server/core/schema/canonical.js +4 -1
  42. package/dist/server/core/schema/canonical.js.map +1 -1
  43. package/dist/server/core/schema/canonical.ts +4 -1
  44. package/dist/server/core/schema/ddl-emitter.d.ts +3 -0
  45. package/dist/server/core/schema/ddl-emitter.d.ts.map +1 -1
  46. package/dist/server/core/schema/ddl-emitter.js +126 -12
  47. package/dist/server/core/schema/ddl-emitter.js.map +1 -1
  48. package/dist/server/core/schema/ddl-emitter.ts +137 -11
  49. package/dist/server/core/sql-safety.d.ts +9 -0
  50. package/dist/server/core/sql-safety.d.ts.map +1 -0
  51. package/dist/server/core/sql-safety.js +74 -0
  52. package/dist/server/core/sql-safety.js.map +1 -0
  53. package/dist/server/core/sql-safety.ts +72 -0
  54. package/dist/server/index.d.ts +22 -0
  55. package/dist/server/index.d.ts.map +1 -1
  56. package/dist/server/index.js +500 -33
  57. package/dist/server/index.js.map +1 -1
  58. package/dist/server/index.ts +519 -35
  59. package/dist/server/service/database/base.service.d.ts +15 -0
  60. package/dist/server/service/database/base.service.d.ts.map +1 -1
  61. package/dist/server/service/database/base.service.js +108 -0
  62. package/dist/server/service/database/base.service.js.map +1 -1
  63. package/dist/server/service/database/base.service.ts +99 -6
  64. package/dist/server/service/database/clickhouse.service.d.ts.map +1 -1
  65. package/dist/server/service/database/clickhouse.service.js +9 -35
  66. package/dist/server/service/database/clickhouse.service.js.map +1 -1
  67. package/dist/server/service/database/clickhouse.service.ts +9 -44
  68. package/dist/server/service/database/cockroachdb.service.d.ts.map +1 -1
  69. package/dist/server/service/database/cockroachdb.service.js +10 -39
  70. package/dist/server/service/database/cockroachdb.service.js.map +1 -1
  71. package/dist/server/service/database/cockroachdb.service.ts +11 -50
  72. package/dist/server/service/database/database.service.d.ts +37 -8
  73. package/dist/server/service/database/database.service.d.ts.map +1 -1
  74. package/dist/server/service/database/database.service.js +651 -54
  75. package/dist/server/service/database/database.service.js.map +1 -1
  76. package/dist/server/service/database/database.service.ts +662 -66
  77. package/dist/server/service/database/export-progress.d.ts +43 -0
  78. package/dist/server/service/database/export-progress.d.ts.map +1 -0
  79. package/dist/server/service/database/export-progress.js +117 -0
  80. package/dist/server/service/database/export-progress.js.map +1 -0
  81. package/dist/server/service/database/export-progress.ts +125 -0
  82. package/dist/server/service/database/mongodb.service.d.ts +3 -1
  83. package/dist/server/service/database/mongodb.service.d.ts.map +1 -1
  84. package/dist/server/service/database/mongodb.service.js +97 -49
  85. package/dist/server/service/database/mongodb.service.js.map +1 -1
  86. package/dist/server/service/database/mongodb.service.ts +94 -48
  87. package/dist/server/service/database/mssql.service.d.ts.map +1 -1
  88. package/dist/server/service/database/mssql.service.js +14 -13
  89. package/dist/server/service/database/mssql.service.js.map +1 -1
  90. package/dist/server/service/database/mssql.service.ts +14 -13
  91. package/dist/server/service/database/mysql.service.js +10 -10
  92. package/dist/server/service/database/mysql.service.js.map +1 -1
  93. package/dist/server/service/database/mysql.service.ts +10 -10
  94. package/dist/server/service/database/oracle.service.d.ts +9 -1
  95. package/dist/server/service/database/oracle.service.d.ts.map +1 -1
  96. package/dist/server/service/database/oracle.service.js +55 -47
  97. package/dist/server/service/database/oracle.service.js.map +1 -1
  98. package/dist/server/service/database/oracle.service.ts +57 -57
  99. package/dist/server/service/database/postgres.service.d.ts.map +1 -1
  100. package/dist/server/service/database/postgres.service.js +10 -9
  101. package/dist/server/service/database/postgres.service.js.map +1 -1
  102. package/dist/server/service/database/postgres.service.ts +10 -9
  103. package/dist/server/service/database/sap.service.d.ts +8 -0
  104. package/dist/server/service/database/sap.service.d.ts.map +1 -1
  105. package/dist/server/service/database/sap.service.js +37 -38
  106. package/dist/server/service/database/sap.service.js.map +1 -1
  107. package/dist/server/service/database/sap.service.ts +39 -49
  108. package/dist/server/service/database/sqlite.service.d.ts.map +1 -1
  109. package/dist/server/service/database/sqlite.service.js +15 -11
  110. package/dist/server/service/database/sqlite.service.js.map +1 -1
  111. package/dist/server/service/database/sqlite.service.ts +15 -11
  112. package/package.json +1 -1
  113. package/public/fdb2.png +0 -0
  114. package/scripts/verify-db-support.cjs +93 -7
  115. package/server.js +15 -2
@@ -33,17 +33,84 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.extractConnId = extractConnId;
37
+ exports.splitProxyId = splitProxyId;
38
+ exports.buildRemoteHeaders = buildRemoteHeaders;
39
+ exports.normalizeProxyBase = normalizeProxyBase;
40
+ exports.hasProxyLoop = hasProxyLoop;
41
+ exports.isProxyHopLimitReached = isProxyHopLimitReached;
42
+ exports.chainFromHeaders = chainFromHeaders;
36
43
  exports.handleDatabaseRoutes = handleDatabaseRoutes;
37
44
  const http = __importStar(require("node:http"));
38
45
  const https = __importStar(require("node:https"));
46
+ const fs = __importStar(require("node:fs"));
39
47
  const connection_service_1 = require("./service/connection.service");
40
48
  const database_service_1 = require("./service/database/database.service");
49
+ const export_progress_1 = require("./service/database/export-progress");
41
50
  const dialect_1 = require("./core/dialect");
51
+ const data_dir_1 = require("./utils/data-dir");
42
52
  // 远程代理相关常量
43
53
  const REMOTE_ID_SEP = '::';
44
54
  const REMOTE_TOKEN_HEADER = 'x-db-tool-token';
45
- // 代理请求标记:用于识别"本请求本身来自代理",避免远程地址指向自身(或互指)时无限递归合并
55
+ // 代理请求标记:旧版单行兼容——收到该标记的 getConnections 只返回本服务本地连接。
56
+ // 新版多级链路改用 x-db-tool-proxy-chain 记录经过的 URL,既能递归合并又能防环。
46
57
  const REMOTE_PROXY_HEADER = 'x-db-tool-proxy';
58
+ const REMOTE_CHAIN_HEADER = 'x-db-tool-proxy-chain';
59
+ const MAX_PROXY_HOPS = 5;
60
+ /** 通用路由参数闸门:只有非空字符串能作为 id/库名/表名进入服务层。 */
61
+ function requireStringParam(value, name) {
62
+ if (typeof value !== 'string' || value.trim() === '')
63
+ throw Error(`Missing parameter: ${name}`);
64
+ return value;
65
+ }
66
+ const REQUIRED_STRING_PARAMS = {
67
+ '/api/database/executeQuery': ['id', 'sql'],
68
+ '/api/database/getSlowQueries': ['id'],
69
+ '/api/database/clearSlowQueries': ['id'],
70
+ '/api/database/explainQuery': ['id', 'sql'],
71
+ '/api/database/getResourceMetrics': ['id'],
72
+ '/api/database/checkHealth': ['id', 'databaseName'],
73
+ '/api/database/getDatabases': ['id'],
74
+ '/api/database/getDatabaseInfo': ['id', 'database'],
75
+ '/api/database/getTables': ['id', 'database'],
76
+ '/api/database/getTableInfo': ['id', 'database', 'table'],
77
+ '/api/database/getIndexes': ['id', 'database', 'table'],
78
+ '/api/database/createIndex': ['id', 'database', 'table'],
79
+ '/api/database/dropIndex': ['id', 'database', 'table', 'indexName'],
80
+ '/api/database/aggregate': ['id', 'database', 'table'],
81
+ '/api/database/getTableData': ['id', 'database', 'table'],
82
+ '/api/database/insertData': ['id', 'database', 'table'],
83
+ '/api/database/updateData': ['id', 'database', 'table'],
84
+ '/api/database/deleteData': ['id', 'database', 'table'],
85
+ '/api/database/importData': ['id', 'database', 'table'],
86
+ '/api/database/exportTableData': ['id', 'database', 'table'],
87
+ '/api/database/exportTableDataToSQL': ['id', 'database', 'table'],
88
+ '/api/database/exportTableDataToCSV': ['id', 'database', 'table'],
89
+ '/api/database/exportTableDataToJSON': ['id', 'database', 'table'],
90
+ '/api/database/exportTableDataToExcel': ['id', 'database', 'table'],
91
+ '/api/database/getExportProgress': ['jobId'],
92
+ '/api/database/createDatabase': ['id', 'databaseName'],
93
+ '/api/database/dropDatabase': ['id', 'databaseName'],
94
+ '/api/database/restore': ['id', 'databaseName', 'filePath'],
95
+ '/api/database/backup': ['id', 'databaseName'],
96
+ '/api/database/optimize': ['id', 'databaseName'],
97
+ '/api/database/analyze': ['id', 'databaseName'],
98
+ '/api/database/repair': ['id', 'databaseName'],
99
+ '/api/database/getViews': ['id', 'database'],
100
+ '/api/database/getViewDefinition': ['id', 'database', 'viewName'],
101
+ '/api/database/createView': ['id', 'database', 'viewName', 'definition'],
102
+ '/api/database/dropView': ['id', 'database', 'viewName'],
103
+ '/api/database/getProcedures': ['id', 'database'],
104
+ '/api/database/getProcedureDefinition': ['id', 'database', 'procedureName']
105
+ };
106
+ function validateStringParams(pathname, body) {
107
+ for (const name of REQUIRED_STRING_PARAMS[pathname] || []) {
108
+ requireStringParam(body?.[name], name);
109
+ }
110
+ // 可选库名一旦提供也必须是字符串,避免对象被拼进 SQL/代理路径。
111
+ if (body?.database !== undefined && body.database !== null)
112
+ requireStringParam(body.database, 'database');
113
+ }
47
114
  // 永不转发的路由:只作用于本地连接配置(无远程对应物或需要本地语义)
48
115
  const LOCAL_ONLY_ROUTES = new Set([
49
116
  '/api/database/getConnection',
@@ -63,12 +130,54 @@ const CONNECTION_CONFIG_ROUTES = new Set([
63
130
  function isRemoteConnection(conn) {
64
131
  return !!conn && conn.type === 'remote';
65
132
  }
133
+ /** 监控类接口只允许本地页面/扩展宿主调用,阻止任意网页读取本机 SQL 样本。 */
134
+ function isTrustedLocalRequest(headers) {
135
+ const origin = headers?.origin || headers?.Origin;
136
+ if (!origin)
137
+ return true; // Electron / VSCode 内进程调用没有 Origin
138
+ try {
139
+ const url = new URL(String(origin));
140
+ if (['localhost', '127.0.0.1', '::1'].includes(url.hostname))
141
+ return true;
142
+ return ['vscode-webview:', 'vscode:', 'file:'].includes(url.protocol);
143
+ }
144
+ catch {
145
+ return false;
146
+ }
147
+ }
148
+ /** 深拷贝连接 options,并移除不应下发的远程访问令牌(混合版本兼容) */
149
+ function cloneOptionsWithoutRemoteToken(options) {
150
+ if (!options || typeof options !== 'object')
151
+ return options;
152
+ let cloned;
153
+ try {
154
+ cloned = JSON.parse(JSON.stringify(options));
155
+ }
156
+ catch {
157
+ cloned = Array.isArray(options) ? [...options] : { ...options };
158
+ }
159
+ if (cloned && typeof cloned === 'object' && !Array.isArray(cloned)) {
160
+ delete cloned.remoteToken;
161
+ }
162
+ return cloned;
163
+ }
66
164
  /** 从请求中取出被操作连接的 id(body 或路径段) */
67
165
  function extractConnId(pathname, body) {
68
166
  if (pathname.startsWith('/api/database/truncateTable/') || pathname.startsWith('/api/database/dropTable/')) {
69
167
  const parts = pathname.split('/').filter(Boolean);
70
168
  return parts[3];
71
169
  }
170
+ // health 路径允许 body 为空:复合 id 必须在路径段中可读;有 body.id 时仍保持旧优先级。
171
+ if (pathname.startsWith('/api/database/health/') && body && typeof body.id === 'string')
172
+ return body.id;
173
+ if (pathname.startsWith('/api/database/health/')) {
174
+ const parts = pathname.split('/').filter(Boolean);
175
+ return parts[3];
176
+ }
177
+ if (pathname.startsWith('/api/database/checkHealth/')) {
178
+ const parts = pathname.split('/').filter(Boolean);
179
+ return parts[3];
180
+ }
72
181
  if (body && typeof body.id === 'string')
73
182
  return body.id;
74
183
  return undefined;
@@ -160,7 +269,7 @@ function postRemoteByNodeHttp(url, body, headers, timeoutMs) {
160
269
  port: target.port || (target.protocol === 'https:' ? 443 : 80),
161
270
  path: (target.pathname || '/') + (target.search || ''),
162
271
  method: 'POST',
163
- headers: { ...headers, 'Content-Length': payload.length }
272
+ headers: { 'Content-Type': 'application/json', ...headers, 'Content-Length': payload.length }
164
273
  }, (res) => {
165
274
  let raw = '';
166
275
  res.setEncoding('utf8');
@@ -188,19 +297,61 @@ async function postRemote(url, body, headers, timeoutMs) {
188
297
  }
189
298
  return await postRemoteByNodeHttp(url, body, headers, timeoutMs);
190
299
  }
191
- /** 构造带令牌与代理标记的请求头 */
192
- function buildRemoteHeaders(proxyConn) {
193
- const headers = { [REMOTE_PROXY_HEADER]: '1' };
300
+ /** 构造带令牌与链路信息的请求头。proxyMarker=false 时允许对端递归合并自己的代理。 */
301
+ function buildRemoteHeaders(proxyConn, opts = {}) {
302
+ const headers = {};
303
+ if (opts.proxyMarker !== false)
304
+ headers[REMOTE_PROXY_HEADER] = '1';
305
+ const chain = opts.chain || [];
306
+ if (chain.length > 0)
307
+ headers[REMOTE_CHAIN_HEADER] = chain.join(',');
194
308
  const token = proxyConn?.options?.remoteToken;
195
309
  if (token)
196
310
  headers[REMOTE_TOKEN_HEADER] = String(token);
197
311
  return headers;
198
312
  }
313
+ /** URL 归一化:忽略协议/主机大小写、默认端口与 localhost/127.0.0.1 别名,专用于环路判定。 */
314
+ function normalizeProxyBase(base) {
315
+ try {
316
+ const url = new URL(String(base || ''));
317
+ const hostname = url.hostname.toLowerCase();
318
+ const loopback = ['localhost', '127.0.0.1', '[::1]', '::1'].includes(hostname);
319
+ const host = loopback ? 'loopback' : hostname;
320
+ const defaultPort = (url.protocol === 'https:' && url.port === '443')
321
+ || (url.protocol === 'http:' && url.port === '80');
322
+ const port = url.port && !defaultPort ? `:${url.port}` : '';
323
+ const pathname = url.pathname.replace(/\/+$/, '');
324
+ return `${url.protocol.toLowerCase()}//${host}${port}${pathname}`;
325
+ }
326
+ catch {
327
+ return String(base || '').replace(/\/+$/, '');
328
+ }
329
+ }
330
+ /** 纯判断:base 是否已出现在链路中(用于阻止代理互指导致的递归) */
331
+ function hasProxyLoop(base, chain) {
332
+ const key = normalizeProxyBase(base);
333
+ return !!key && chain.some((item) => normalizeProxyBase(item) === key);
334
+ }
335
+ /** 纯判断:链路深度是否已达到 5 跳上限(当前 URL 尚未加入 chain) */
336
+ function isProxyHopLimitReached(chain) {
337
+ return chain.length >= MAX_PROXY_HOPS;
338
+ }
339
+ function remoteBaseOf(proxyConn) {
340
+ return String(proxyConn?.options?.remoteUrl || '').replace(/\/+$/, '');
341
+ }
342
+ function chainFromHeaders(headers) {
343
+ return String(headers?.[REMOTE_CHAIN_HEADER] || '').split(',').map((s) => s.trim()).filter(Boolean);
344
+ }
199
345
  /** 把请求原样转发到远程 db_tool 服务端(自动解包远程响应,避免二次包装) */
200
- async function proxyToRemote(proxyConn, remoteConnId, pathname, body) {
201
- const base = String(proxyConn.options?.remoteUrl || '').replace(/\/+$/, '');
346
+ async function proxyToRemote(proxyConn, remoteConnId, pathname, body, chain = []) {
347
+ const base = remoteBaseOf(proxyConn);
202
348
  if (!base)
203
349
  throw new Error('远程代理连接缺少 remoteUrl');
350
+ if (hasProxyLoop(base, chain))
351
+ throw new Error(`检测到代理环路:${base}`);
352
+ if (isProxyHopLimitReached(chain))
353
+ throw new Error(`代理链路超过 ${MAX_PROXY_HOPS} 跳,已中止以防环`);
354
+ const nextChain = [...chain, base];
204
355
  let targetPath = pathname;
205
356
  if (pathname.startsWith('/api/database/truncateTable/') || pathname.startsWith('/api/database/dropTable/')) {
206
357
  const parts = pathname.split('/').filter(Boolean);
@@ -210,19 +361,28 @@ async function proxyToRemote(proxyConn, remoteConnId, pathname, body) {
210
361
  targetPath = '/' + parts.join('/');
211
362
  }
212
363
  const targetBody = { ...body, id: remoteConnId };
213
- const env = await postRemote(`${base}${targetPath}`, targetBody, buildRemoteHeaders(proxyConn), 60000);
364
+ // 大表导出可能远超默认 60s,避免代理链路先把请求掐断
365
+ const timeoutMs = /\/api\/database\/exportTableDataTo/i.test(pathname) ? 30 * 60 * 1000 : 60000;
366
+ const env = await postRemote(`${base}${targetPath}`, targetBody, buildRemoteHeaders(proxyConn, { proxyMarker: false, chain: nextChain }), timeoutMs);
214
367
  if (env && typeof env === 'object' && env.ret && env.ret !== 0) {
215
368
  throw new Error(env.msg || '远程服务执行失败');
216
369
  }
217
370
  return env?.data;
218
371
  }
219
- /** 拉取远程服务上的连接列表(用于网关模式合并,单层、过滤嵌套代理配置) */
220
- async function fetchRemoteConnections(proxyConn) {
221
- const base = String(proxyConn.options?.remoteUrl || '').replace(/\/+$/, '');
372
+ /**
373
+ * 拉取远程服务上的连接列表。不发送旧版 proxy 标记,因此远程端会递归合并它自己的代理;
374
+ * 通过 chain 记录已访问的 URL,detect 到环路或超过跳数上限时停止,避免无限递归。
375
+ */
376
+ async function fetchRemoteConnections(proxyConn, chain = []) {
377
+ const base = remoteBaseOf(proxyConn);
222
378
  if (!base)
223
379
  return { list: [], error: '缺少 remoteUrl' };
380
+ if (hasProxyLoop(base, chain))
381
+ return { list: [], error: `检测到代理环路:${base}` };
382
+ if (isProxyHopLimitReached(chain))
383
+ return { list: [], error: `代理链路超过 ${MAX_PROXY_HOPS} 跳` };
224
384
  try {
225
- const env = await postRemote(`${base}/api/database/getConnections`, {}, buildRemoteHeaders(proxyConn), 10000);
385
+ const env = await postRemote(`${base}/api/database/getConnections`, {}, buildRemoteHeaders(proxyConn, { proxyMarker: false, chain: [...chain, base] }), 10000);
226
386
  if (env && env.ret && env.ret !== 0) {
227
387
  console.warn('[remote] 获取远程连接列表失败:', env.msg);
228
388
  return { list: [], error: env.msg || '远程服务返回错误' };
@@ -234,11 +394,12 @@ async function fetchRemoteConnections(proxyConn) {
234
394
  return { list: [], error: e?.message || '远程服务不可达' };
235
395
  }
236
396
  }
237
- /** 网关模式:本地连接列表 = 本地连接 + 远程代理暴露的连接 */
238
- async function handleGetConnectionsWithProxy() {
397
+ /** 网关模式:本地连接列表 = 本地连接 + 各级远程代理暴露的连接(支持 A→B→C 多级链路) */
398
+ async function handleGetConnectionsWithProxy(headers) {
239
399
  const locals = await connectionService.getAllConnections();
400
+ const chain = chainFromHeaders(headers);
240
401
  // 并行拉取各远程服务,避免多个远程时串行等待
241
- const remoteResults = await Promise.all(locals.map(conn => (isRemoteConnection(conn) ? fetchRemoteConnections(conn) : Promise.resolve(null))));
402
+ const remoteResults = await Promise.all(locals.map(conn => (isRemoteConnection(conn) ? fetchRemoteConnections(conn, chain) : Promise.resolve(null))));
242
403
  const result = [];
243
404
  locals.forEach((conn, index) => {
244
405
  if (!isRemoteConnection(conn)) {
@@ -249,16 +410,23 @@ async function handleGetConnectionsWithProxy() {
249
410
  // 代理配置本身保留(用于编辑/删除),标记 _isProxy
250
411
  result.push({ ...conn, _isProxy: true, _remoteError: remote?.error });
251
412
  for (const rc of remote?.list || []) {
413
+ // 代理配置本身(含 remoteUrl/token)不能作为可操作的数据库连接暴露;
414
+ // 旧版本可能只靠 type='remote' 标记,混合版本下两种标记都要过滤。
252
415
  if (rc.type === 'remote' || rc._isProxy)
253
- continue; // 不暴露嵌套代理配置
416
+ continue;
254
417
  const safe = { ...rc };
255
418
  delete safe.password; // 不把远程库的密码下发到客户端
419
+ if (safe.options !== undefined)
420
+ safe.options = cloneOptionsWithoutRemoteToken(safe.options);
421
+ // 保留远程端已拼好的代理链:A::B::C,而不是把中间跳数丢掉
422
+ const proxyChain = rc._proxyId ? `${conn.id}${REMOTE_ID_SEP}${rc._proxyId}` : conn.id;
256
423
  result.push({
257
424
  ...safe,
258
425
  id: `${conn.id}${REMOTE_ID_SEP}${rc.id}`,
259
- _proxyId: conn.id,
426
+ _proxyId: proxyChain,
260
427
  _remote: true,
261
- _remoteName: conn.name
428
+ _remoteName: rc._remoteName ? `${conn.name} → ${rc._remoteName}` : conn.name,
429
+ _hops: (Number(rc._hops) || 0) + 1
262
430
  });
263
431
  }
264
432
  });
@@ -277,6 +445,113 @@ async function testRemoteConnection(conn) {
277
445
  // 初始化服务实例
278
446
  const connectionService = new connection_service_1.ConnectionService();
279
447
  const databaseService = new database_service_1.DatabaseService();
448
+ const BACKUP_SCHEDULE_FILE = 'backup-schedules.json';
449
+ function loadBackupSchedules() {
450
+ try {
451
+ const raw = fs.readFileSync((0, data_dir_1.getDataPath)(BACKUP_SCHEDULE_FILE), 'utf8');
452
+ const parsed = JSON.parse(raw);
453
+ return Array.isArray(parsed) ? parsed.filter((s) => s && s.id && s.connectionId) : [];
454
+ }
455
+ catch {
456
+ return [];
457
+ }
458
+ }
459
+ // 所有备份计划的 load-modify-save(增删改/手动执行/定时扫描)共用一条串行队列,避免并发覆盖。
460
+ let scheduleTaskQueue = Promise.resolve();
461
+ function enqueueScheduleTask(task) {
462
+ const result = scheduleTaskQueue.then(task);
463
+ scheduleTaskQueue = result.then(() => undefined, () => undefined);
464
+ return result;
465
+ }
466
+ function saveBackupSchedules(schedules) {
467
+ (0, data_dir_1.ensureDataDir)();
468
+ const target = (0, data_dir_1.getDataPath)(BACKUP_SCHEDULE_FILE);
469
+ const temp = `${target}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
470
+ try {
471
+ fs.writeFileSync(temp, JSON.stringify(schedules, null, 2), 'utf8');
472
+ fs.renameSync(temp, target);
473
+ }
474
+ catch (e) {
475
+ try {
476
+ fs.unlinkSync(temp);
477
+ }
478
+ catch {
479
+ // 临时文件可能尚未创建或已被清理,忽略二次错误
480
+ }
481
+ throw e;
482
+ }
483
+ }
484
+ const inFlightScheduleIds = new Set();
485
+ /** 执行单个计划:成功才更新 lastRunAt,失败时保留原值供下一分钟重试。 */
486
+ async function executeBackupSchedule(schedule) {
487
+ if (inFlightScheduleIds.has(schedule.id))
488
+ throw new Error(`备份计划正在执行: ${schedule.id}`);
489
+ inFlightScheduleIds.add(schedule.id);
490
+ try {
491
+ const result = await databaseService.backupDatabase(schedule.connectionId, schedule.databaseName, {
492
+ scheduleId: schedule.id
493
+ });
494
+ schedule.lastRunAt = Date.now();
495
+ return result;
496
+ }
497
+ finally {
498
+ inFlightScheduleIds.delete(schedule.id);
499
+ }
500
+ }
501
+ let backupSweepRunning = false;
502
+ /** 每分钟检查一次到期的计划;仅在本服务进程存活期间运行。 */
503
+ async function runDueBackups() {
504
+ if (backupSweepRunning)
505
+ return; // 全局重入保护:上一轮未结束(含备份 I/O)时直接跳过本次 tick
506
+ backupSweepRunning = true;
507
+ try {
508
+ await enqueueScheduleTask(async () => {
509
+ const schedules = loadBackupSchedules();
510
+ const now = Date.now();
511
+ let changed = false;
512
+ for (const s of schedules) {
513
+ if (!s.enabled || inFlightScheduleIds.has(s.id))
514
+ continue;
515
+ const intervalMs = Math.max(1, Number(s.intervalMinutes) || 60) * 60 * 1000;
516
+ if (now - (s.lastRunAt || 0) < intervalMs)
517
+ continue;
518
+ try {
519
+ await executeBackupSchedule(s);
520
+ changed = true;
521
+ }
522
+ catch (e) {
523
+ console.warn(`[backup-schedule] ${s.connectionId}/${s.databaseName} 备份失败:`, e?.message || e);
524
+ }
525
+ }
526
+ if (changed)
527
+ saveBackupSchedules(schedules);
528
+ });
529
+ }
530
+ finally {
531
+ backupSweepRunning = false;
532
+ }
533
+ }
534
+ const backupScheduler = setInterval(() => {
535
+ runDueBackups().catch((e) => {
536
+ console.warn('[backup-schedule] 定时检查失败:', e?.message || e);
537
+ });
538
+ }, 60 * 1000);
539
+ // 不阻止进程退出(VSCode 扩展宿主 / CLI 也会导入本模块)
540
+ backupScheduler.unref?.();
541
+ /** 包一层导出调用:保持原有「返回文件路径」的响应契约,同时记录可轮询的进度。 */
542
+ async function runTableExport(options, exportFn) {
543
+ const jobId = typeof options?.jobId === 'string' ? options.jobId : undefined;
544
+ (0, export_progress_1.startExportJob)(jobId);
545
+ try {
546
+ const result = await exportFn({ ...(options || {}), jobId });
547
+ (0, export_progress_1.finishExportJob)(jobId, 'completed', { path: typeof result === 'string' ? result : undefined });
548
+ return result;
549
+ }
550
+ catch (error) {
551
+ (0, export_progress_1.finishExportJob)(jobId, 'failed', { message: error?.message || String(error) });
552
+ throw error;
553
+ }
554
+ }
280
555
  // 数据库相关路由处理
281
556
  async function handleDatabaseRoutes(pathname, body, headers) {
282
557
  try {
@@ -288,13 +563,19 @@ async function handleDatabaseRoutes(pathname, body, headers) {
288
563
  throw new Error('远程访问令牌无效');
289
564
  }
290
565
  }
566
+ validateStringParams(pathname, body);
567
+ if (pathname.startsWith('/api/database/checkHealth/')) {
568
+ const parts = pathname.split('/').filter(Boolean);
569
+ requireStringParam(parts[3], 'id');
570
+ requireStringParam(parts[4], 'databaseName');
571
+ }
291
572
  // 网关模式:合并远程服务暴露的连接
292
573
  if (pathname === '/api/database/getConnections') {
293
574
  // 请求本身来自代理时不再二次合并,避免远程地址指向自身(或互指)造成无限递归
294
575
  if (headers && headers[REMOTE_PROXY_HEADER]) {
295
576
  return await connectionService.getAllConnections();
296
577
  }
297
- return await handleGetConnectionsWithProxy();
578
+ return await handleGetConnectionsWithProxy(headers);
298
579
  }
299
580
  // 远程代理连接本身的测试:直接探活远程服务
300
581
  if (pathname === '/api/database/testConnection' && body && isRemoteConnection(body)) {
@@ -304,7 +585,22 @@ async function handleDatabaseRoutes(pathname, body, headers) {
304
585
  // 覆盖数据操作(查询/建表/改结构等)与连接配置的增删改
305
586
  const proxy = await resolveRemoteProxy(pathname, body);
306
587
  if (proxy) {
307
- return await proxyToRemote(proxy.proxyConn, proxy.remoteConnId, pathname, body);
588
+ // 远程导出:本地登记 job 并记录路由,让客户端轮询能转发到真正写文件的远程服务
589
+ const localJobId = /\/api\/database\/exportTableDataTo/i.test(pathname)
590
+ ? (typeof body?.options?.jobId === 'string' ? body.options.jobId : undefined)
591
+ : undefined;
592
+ let forwardedBody = body;
593
+ if (localJobId) {
594
+ (0, export_progress_1.startExportJob)(localJobId);
595
+ const remoteJobId = `${proxy.proxyConn.id}::${localJobId}`;
596
+ (0, export_progress_1.linkExportJob)(localJobId, {
597
+ proxyConnId: proxy.proxyConn.id,
598
+ remoteConnId: proxy.remoteConnId,
599
+ remoteJobId
600
+ });
601
+ forwardedBody = { ...body, options: { ...(body.options || {}), jobId: remoteJobId } };
602
+ }
603
+ return await proxyToRemote(proxy.proxyConn, proxy.remoteConnId, pathname, forwardedBody, chainFromHeaders(headers));
308
604
  }
309
605
  // 对「远程代理配置」本身做数据操作时给出明确提示(配置本身的增删改是允许的)
310
606
  if (!CONNECTION_CONFIG_ROUTES.has(pathname)) {
@@ -350,6 +646,25 @@ async function handleDatabaseRoutes(pathname, body, headers) {
350
646
  const result = await connectionService.testConnection(body);
351
647
  return result;
352
648
  }
649
+ // /api/database/health/:id/:database(或 ?id=...)——连通性探活。
650
+ // 客户端 checkDatabaseHealth 早在 UI 前就声明了此路由,但此前服务端没有实现。
651
+ if (pathname === '/api/database/health' || pathname.startsWith('/api/database/health/')) {
652
+ const parts = pathname.split('/').filter(Boolean);
653
+ const id = extractConnId(pathname, body);
654
+ if (!id)
655
+ throw Error('Missing parameter: id');
656
+ const database = body?.database || parts[4];
657
+ if (database) {
658
+ // 指定库时真正连接并读取库信息,失败由 getDatabaseInfo 抛出异常返回。
659
+ const info = await databaseService.getDatabaseInfo(id, database);
660
+ if (!info)
661
+ throw Error(`数据库不存在: ${database}`);
662
+ return { healthy: true, database };
663
+ }
664
+ // 未指定库时保留列库检查,适用于关系型与文档型;不执行方言专有 SQL。
665
+ const databases = await databaseService.getDatabases(id);
666
+ return { healthy: true, databaseCount: Array.isArray(databases) ? databases.length : 0 };
667
+ }
353
668
  // /api/database/getDatabases
354
669
  if (pathname === '/api/database/getDatabases') {
355
670
  const { id } = body;
@@ -436,9 +751,45 @@ async function handleDatabaseRoutes(pathname, body, headers) {
436
751
  throw Error('Missing parameters: id, sql');
437
752
  if (!sql.trim())
438
753
  throw Error('SQL语句不能为空');
439
- const result = await databaseService.executeQuery(id, sql, database);
754
+ const result = await databaseService.executeQuery(id, sql, database, 'editor');
440
755
  return result;
441
756
  }
757
+ // /api/database/getSlowQueries —— 本进程采集的慢查询(仅本地、仅指定连接)
758
+ if (pathname === '/api/database/getSlowQueries') {
759
+ if (!isTrustedLocalRequest(headers))
760
+ throw Error('Forbidden origin');
761
+ const { id, minDurationMs = 2000, limit = 50 } = body;
762
+ if (!id)
763
+ throw Error('Missing parameter: id');
764
+ return databaseService.getSlowQueries(id, Number(minDurationMs), Number(limit));
765
+ }
766
+ // /api/database/clearSlowQueries
767
+ if (pathname === '/api/database/clearSlowQueries') {
768
+ if (!isTrustedLocalRequest(headers))
769
+ throw Error('Forbidden origin');
770
+ const { id } = body;
771
+ if (!id)
772
+ throw Error('Missing parameter: id');
773
+ return { cleared: databaseService.clearSlowQueries(id) };
774
+ }
775
+ // /api/database/explainQuery —— 只读执行计划
776
+ if (pathname === '/api/database/explainQuery') {
777
+ if (!isTrustedLocalRequest(headers))
778
+ throw Error('Forbidden origin');
779
+ const { id, sql, database } = body;
780
+ if (!id || !sql)
781
+ throw Error('Missing parameters: id, sql');
782
+ return await databaseService.explainQuery(id, sql, database);
783
+ }
784
+ // /api/database/getResourceMetrics —— 只读资源指标(逐项降级)
785
+ if (pathname === '/api/database/getResourceMetrics') {
786
+ if (!isTrustedLocalRequest(headers))
787
+ throw Error('Forbidden origin');
788
+ const { id, database } = body;
789
+ if (!id)
790
+ throw Error('Missing parameter: id');
791
+ return await databaseService.getResourceMetrics(id, database);
792
+ }
442
793
  // /api/database/closeConnection
443
794
  if (pathname === '/api/database/closeConnection') {
444
795
  const { id } = body;
@@ -493,6 +844,79 @@ async function handleDatabaseRoutes(pathname, body, headers) {
493
844
  const result = await databaseService.backupDatabase(id, databaseName, options);
494
845
  return { success: true, result };
495
846
  }
847
+ // 定时备份计划:配置持久化在数据目录,调度由本进程每分钟检查一次
848
+ if (pathname === '/api/database/getBackupSchedules') {
849
+ return { schedules: loadBackupSchedules() };
850
+ }
851
+ if (pathname === '/api/database/addBackupSchedule') {
852
+ const { connectionId, databaseName, intervalMinutes = 60, enabled = true } = body || {};
853
+ if (!connectionId || !databaseName)
854
+ throw Error('Missing parameters: connectionId, databaseName');
855
+ return await enqueueScheduleTask(async () => {
856
+ const schedules = loadBackupSchedules();
857
+ const item = {
858
+ id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
859
+ connectionId,
860
+ databaseName,
861
+ intervalMinutes: Math.max(1, Math.floor(Number(intervalMinutes) || 60)),
862
+ enabled: !!enabled,
863
+ createdAt: Date.now()
864
+ };
865
+ schedules.push(item);
866
+ saveBackupSchedules(schedules);
867
+ return { schedule: item };
868
+ });
869
+ }
870
+ if (pathname === '/api/database/updateBackupSchedule') {
871
+ const { id, ...updates } = body || {};
872
+ if (!id)
873
+ throw Error('Missing parameter: id');
874
+ return await enqueueScheduleTask(async () => {
875
+ const schedules = loadBackupSchedules();
876
+ const item = schedules.find((s) => s.id === id);
877
+ if (!item)
878
+ throw Error(`备份计划不存在: ${id}`);
879
+ // 只接受可编辑字段,禁止外部改写 lastRunAt / createdAt / id 等运行时字段。
880
+ if (updates.connectionId !== undefined)
881
+ item.connectionId = String(updates.connectionId);
882
+ if (updates.databaseName !== undefined)
883
+ item.databaseName = String(updates.databaseName);
884
+ if (updates.intervalMinutes !== undefined) {
885
+ item.intervalMinutes = Math.max(1, Math.floor(Number(updates.intervalMinutes) || 60));
886
+ }
887
+ if (updates.enabled !== undefined)
888
+ item.enabled = !!updates.enabled;
889
+ saveBackupSchedules(schedules);
890
+ return { schedule: item };
891
+ });
892
+ }
893
+ if (pathname === '/api/database/deleteBackupSchedule') {
894
+ const { id } = body || {};
895
+ if (!id)
896
+ throw Error('Missing parameter: id');
897
+ return await enqueueScheduleTask(async () => {
898
+ const schedules = loadBackupSchedules();
899
+ const kept = schedules.filter((s) => s.id !== id);
900
+ if (kept.length === schedules.length)
901
+ throw Error(`备份计划不存在: ${id}`);
902
+ saveBackupSchedules(kept);
903
+ return { success: true };
904
+ });
905
+ }
906
+ if (pathname === '/api/database/runBackupSchedule') {
907
+ const { id } = body || {};
908
+ if (!id)
909
+ throw Error('Missing parameter: id');
910
+ return await enqueueScheduleTask(async () => {
911
+ const schedules = loadBackupSchedules();
912
+ const schedule = schedules.find((s) => s.id === id);
913
+ if (!schedule)
914
+ throw Error(`备份计划不存在: ${id}`);
915
+ const result = await executeBackupSchedule(schedule);
916
+ saveBackupSchedules(schedules);
917
+ return { success: true, result };
918
+ });
919
+ }
496
920
  // /api/database/restore
497
921
  if (pathname === '/api/database/restore') {
498
922
  const { id, databaseName, filePath, options } = body;
@@ -533,6 +957,16 @@ async function handleDatabaseRoutes(pathname, body, headers) {
533
957
  const results = await databaseService.repairTables(id, databaseName);
534
958
  return { success: true, results };
535
959
  }
960
+ // /api/database/checkHealth —— 只读健康检查(完整性/索引有效性/明确降级)
961
+ // 同时接受 POST body 与 /checkHealth/:id/:database 路径,和旧 health 路由风格保持一致。
962
+ if (pathname === '/api/database/checkHealth' || pathname.startsWith('/api/database/checkHealth/')) {
963
+ const parts = pathname.split('/').filter(Boolean);
964
+ const id = extractConnId(pathname, body);
965
+ const databaseName = body?.databaseName || body?.database || parts[4];
966
+ if (!id || !databaseName)
967
+ throw Error('Missing parameters: id, databaseName');
968
+ return await databaseService.checkDatabaseHealth(id, databaseName);
969
+ }
536
970
  // /api/database/exportTableData
537
971
  if (pathname === '/api/database/exportTableData') {
538
972
  const { id, database, table, format = 'json', where } = body;
@@ -542,41 +976,59 @@ async function handleDatabaseRoutes(pathname, body, headers) {
542
976
  const result = await databaseService.getTableData(id, database, table, 1, 10000, where);
543
977
  return result;
544
978
  }
979
+ // /api/database/getExportProgress —— 导出进行中时由客户端轮询
980
+ if (pathname === '/api/database/getExportProgress') {
981
+ const localJobId = body?.jobId;
982
+ const route = (0, export_progress_1.getExportJobRoute)(localJobId);
983
+ if (route) {
984
+ try {
985
+ const proxyConn = await connectionService.getConnectionById(route.proxyConnId);
986
+ if (proxyConn && isRemoteConnection(proxyConn)) {
987
+ const remote = await proxyToRemote(proxyConn, route.remoteConnId, '/api/database/getExportProgress', { jobId: route.remoteJobId }, chainFromHeaders(headers));
988
+ if (remote) {
989
+ // 同步到本地 job:即使转发暂时失败,客户端也能拿到最近一次快照
990
+ (0, export_progress_1.reportExportRows)(localJobId, Number(remote.rows) || 0, remote.phase);
991
+ if (remote.status === 'completed')
992
+ (0, export_progress_1.finishExportJob)(localJobId, 'completed', { path: remote.path });
993
+ else if (remote.status === 'failed')
994
+ (0, export_progress_1.finishExportJob)(localJobId, 'failed', { message: remote.message });
995
+ }
996
+ return remote;
997
+ }
998
+ }
999
+ catch {
1000
+ // 代理配置缺失或转发失败时回落到本地快照
1001
+ }
1002
+ }
1003
+ return (0, export_progress_1.getExportProgress)(localJobId);
1004
+ }
545
1005
  // /api/database/exportTableDataToSQL
546
1006
  if (pathname === '/api/database/exportTableDataToSQL') {
547
1007
  const { id, database, table, options } = body;
548
1008
  if (!id || !database || !table)
549
1009
  throw Error('Missing parameters: id, database, table');
550
- // 调用数据库服务导出表数据到SQL文件
551
- const exportPath = await databaseService.exportTableDataToSQL(id, database, table, options);
552
- return exportPath;
1010
+ return await runTableExport(options, (opts) => databaseService.exportTableDataToSQL(id, database, table, opts));
553
1011
  }
554
1012
  // /api/database/exportTableDataToCSV
555
1013
  if (pathname === '/api/database/exportTableDataToCSV') {
556
1014
  const { id, database, table, options } = body;
557
1015
  if (!id || !database || !table)
558
1016
  throw Error('Missing parameters: id, database, table');
559
- // 调用数据库服务导出表数据到CSV文件
560
- const exportPath = await databaseService.exportTableDataToCSV(id, database, table, options);
561
- return exportPath;
1017
+ return await runTableExport(options, (opts) => databaseService.exportTableDataToCSV(id, database, table, opts));
562
1018
  }
563
1019
  // /api/database/exportTableDataToJSON
564
1020
  if (pathname === '/api/database/exportTableDataToJSON') {
565
1021
  const { id, database, table, options } = body;
566
1022
  if (!id || !database || !table)
567
1023
  throw Error('Missing parameters: id, database, table');
568
- // 调用数据库服务导出表数据到JSON文件
569
- const exportPath = await databaseService.exportTableDataToJSON(id, database, table, options);
570
- return exportPath;
1024
+ return await runTableExport(options, (opts) => databaseService.exportTableDataToJSON(id, database, table, opts));
571
1025
  }
572
1026
  // /api/database/exportTableDataToExcel
573
1027
  if (pathname === '/api/database/exportTableDataToExcel') {
574
1028
  const { id, database, table, options } = body;
575
1029
  if (!id || !database || !table)
576
1030
  throw Error('Missing parameters: id, database, table');
577
- // 调用数据库服务导出表数据到Excel文件
578
- const exportPath = await databaseService.exportTableDataToExcel(id, database, table, options);
579
- return exportPath;
1031
+ return await runTableExport(options, (opts) => databaseService.exportTableDataToExcel(id, database, table, opts));
580
1032
  }
581
1033
  // /api/database/refreshTableCache(手动全量拉取表列表,忽略预览缓存)
582
1034
  if (pathname === '/api/database/refreshTableCache') {
@@ -626,6 +1078,13 @@ async function handleDatabaseRoutes(pathname, body, headers) {
626
1078
  const result = await databaseService.syncTable(id, syncConfig);
627
1079
  return result;
628
1080
  }
1081
+ // /api/database/importData:浏览器解析文件后按批提交行数组,服务端按方言 bulkInsert
1082
+ if (pathname === '/api/database/importData') {
1083
+ const { id, database, table, rows } = body;
1084
+ if (!id || !database || !table || !Array.isArray(rows))
1085
+ throw Error('Missing parameters: id, database, table, rows');
1086
+ return await databaseService.importData(id, database, table, rows);
1087
+ }
629
1088
  // /api/database/insertData
630
1089
  if (pathname === '/api/database/insertData') {
631
1090
  const { id, database, table, data } = body;
@@ -853,6 +1312,11 @@ function generateUpdateSQL(dbType, tableName, data, where, dbService) {
853
1312
  return `${dbService.quoteIdentifier(key)} = ${formatValue(dbType, value)}`;
854
1313
  })
855
1314
  .join(' AND ');
1315
+ // ClickHouse 的 MergeTree 不支持标准 UPDATE;必须用 ALTER TABLE ... UPDATE(DELETE 同理)。
1316
+ // mutation 默认是异步的,加 mutations_sync=1 等待完成,避免 UI 立即刷新仍读到旧值。
1317
+ if (dbType === 'clickhouse') {
1318
+ return `ALTER TABLE ${dbService.quoteIdentifier(tableName)} UPDATE ${setClause} WHERE ${whereClause} SETTINGS mutations_sync = 1;`;
1319
+ }
856
1320
  return `UPDATE ${dbService.quoteIdentifier(tableName)} SET ${setClause} WHERE ${whereClause};`;
857
1321
  }
858
1322
  function generateDeleteSQL(dbType, tableName, where, dbService) {
@@ -864,6 +1328,9 @@ function generateDeleteSQL(dbType, tableName, where, dbService) {
864
1328
  return `${dbService.quoteIdentifier(key)} = ${formatValue(dbType, value)}`;
865
1329
  })
866
1330
  .join(' AND ');
1331
+ if (dbType === 'clickhouse') {
1332
+ return `ALTER TABLE ${dbService.quoteIdentifier(tableName)} DELETE WHERE ${whereClause} SETTINGS mutations_sync = 1;`;
1333
+ }
867
1334
  return `DELETE FROM ${dbService.quoteIdentifier(tableName)} WHERE ${whereClause};`;
868
1335
  }
869
1336
  function formatValue(dbType, value) {