fdb2 1.0.39 → 1.0.41
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/README.md +6 -5
- package/dist/public/.vite/manifest.json +109 -1
- package/dist/public/database-monitor.css +445 -0
- package/dist/public/database-monitor.js +605 -0
- package/dist/public/database.css +740 -0
- package/dist/public/database.js +555 -0
- package/dist/public/database2.js +344 -0
- package/dist/public/echarts.js +79307 -0
- package/dist/public/explorer.css +1109 -436
- package/dist/public/explorer.js +4049 -34891
- package/dist/public/export.js +54831 -0
- package/dist/public/helpers.js +27 -0
- package/dist/public/index.js +545 -51
- package/dist/public/layout.css +98 -65
- package/dist/public/layout.js +59 -22
- package/dist/public/query-history.css +651 -0
- package/dist/public/query-history.js +526 -0
- package/dist/public/sql-query-editor.css +503 -0
- package/dist/public/sql-query-editor.js +638 -0
- package/dist/public/theme.js +82 -0
- package/dist/scripts/verify-db-support.cjs +239 -0
- package/dist/server/__tests__/import-normalize.test.ts +79 -0
- package/dist/server/__tests__/remote-proxy.test.ts +62 -0
- package/dist/server/core/dialect.d.ts +9 -0
- package/dist/server/core/dialect.d.ts.map +1 -1
- package/dist/server/core/dialect.js +24 -9
- package/dist/server/core/dialect.js.map +1 -1
- package/dist/server/core/dialect.ts +29 -9
- package/dist/server/core/schema/__tests__/ddl-emitter.test.ts +159 -3
- package/dist/server/core/schema/canonical.d.ts.map +1 -1
- package/dist/server/core/schema/canonical.js +4 -1
- package/dist/server/core/schema/canonical.js.map +1 -1
- package/dist/server/core/schema/canonical.ts +4 -1
- package/dist/server/core/schema/ddl-emitter.d.ts +3 -0
- package/dist/server/core/schema/ddl-emitter.d.ts.map +1 -1
- package/dist/server/core/schema/ddl-emitter.js +158 -24
- package/dist/server/core/schema/ddl-emitter.js.map +1 -1
- package/dist/server/core/schema/ddl-emitter.ts +171 -22
- package/dist/server/index.d.ts +20 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +375 -25
- package/dist/server/index.js.map +1 -1
- package/dist/server/index.ts +392 -27
- package/dist/server/model/ddl-spec.d.ts +9 -0
- package/dist/server/model/ddl-spec.d.ts.map +1 -1
- package/dist/server/model/ddl-spec.ts +9 -0
- package/dist/server/service/connection.service.d.ts +8 -0
- package/dist/server/service/connection.service.d.ts.map +1 -1
- package/dist/server/service/connection.service.js +75 -17
- package/dist/server/service/connection.service.js.map +1 -1
- package/dist/server/service/connection.service.ts +74 -17
- package/dist/server/service/database/base.service.d.ts +45 -0
- package/dist/server/service/database/base.service.d.ts.map +1 -1
- package/dist/server/service/database/base.service.js +120 -7
- package/dist/server/service/database/base.service.js.map +1 -1
- package/dist/server/service/database/base.service.ts +143 -8
- package/dist/server/service/database/cockroachdb.service.d.ts +9 -0
- package/dist/server/service/database/cockroachdb.service.d.ts.map +1 -1
- package/dist/server/service/database/cockroachdb.service.js +68 -57
- package/dist/server/service/database/cockroachdb.service.js.map +1 -1
- package/dist/server/service/database/cockroachdb.service.ts +67 -58
- package/dist/server/service/database/database.service.d.ts +25 -227
- package/dist/server/service/database/database.service.d.ts.map +1 -1
- package/dist/server/service/database/database.service.js +323 -78
- package/dist/server/service/database/database.service.js.map +1 -1
- package/dist/server/service/database/database.service.ts +334 -87
- package/dist/server/service/database/mongodb.service.d.ts +58 -3
- package/dist/server/service/database/mongodb.service.d.ts.map +1 -1
- package/dist/server/service/database/mongodb.service.js +264 -54
- package/dist/server/service/database/mongodb.service.js.map +1 -1
- package/dist/server/service/database/mongodb.service.ts +288 -60
- package/dist/server/service/database/mssql.service.d.ts +8 -0
- package/dist/server/service/database/mssql.service.d.ts.map +1 -1
- package/dist/server/service/database/mssql.service.js +45 -40
- package/dist/server/service/database/mssql.service.js.map +1 -1
- package/dist/server/service/database/mssql.service.ts +49 -44
- package/dist/server/service/database/oracle.service.d.ts +29 -1
- package/dist/server/service/database/oracle.service.d.ts.map +1 -1
- package/dist/server/service/database/oracle.service.js +166 -137
- package/dist/server/service/database/oracle.service.js.map +1 -1
- package/dist/server/service/database/oracle.service.ts +166 -146
- package/dist/server/service/database/sap.service.d.ts +8 -0
- package/dist/server/service/database/sap.service.d.ts.map +1 -1
- package/dist/server/service/database/sap.service.js +28 -0
- package/dist/server/service/database/sap.service.js.map +1 -1
- package/dist/server/service/database/sap.service.ts +29 -0
- package/dist/server/service/database/sqlite.service.d.ts.map +1 -1
- package/dist/server/service/database/sqlite.service.js +6 -3
- package/dist/server/service/database/sqlite.service.js.map +1 -1
- package/dist/server/service/database/sqlite.service.ts +6 -3
- package/package.json +8 -8
- package/public/fdb2.png +0 -0
- package/scripts/verify-db-support.cjs +239 -0
package/dist/server/index.js
CHANGED
|
@@ -33,16 +33,28 @@ 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.hasProxyLoop = hasProxyLoop;
|
|
40
|
+
exports.isProxyHopLimitReached = isProxyHopLimitReached;
|
|
41
|
+
exports.chainFromHeaders = chainFromHeaders;
|
|
36
42
|
exports.handleDatabaseRoutes = handleDatabaseRoutes;
|
|
37
43
|
const http = __importStar(require("node:http"));
|
|
38
44
|
const https = __importStar(require("node:https"));
|
|
45
|
+
const fs = __importStar(require("node:fs"));
|
|
39
46
|
const connection_service_1 = require("./service/connection.service");
|
|
40
47
|
const database_service_1 = require("./service/database/database.service");
|
|
48
|
+
const dialect_1 = require("./core/dialect");
|
|
49
|
+
const data_dir_1 = require("./utils/data-dir");
|
|
41
50
|
// 远程代理相关常量
|
|
42
51
|
const REMOTE_ID_SEP = '::';
|
|
43
52
|
const REMOTE_TOKEN_HEADER = 'x-db-tool-token';
|
|
44
|
-
//
|
|
53
|
+
// 代理请求标记:旧版单行兼容——收到该标记的 getConnections 只返回本服务本地连接。
|
|
54
|
+
// 新版多级链路改用 x-db-tool-proxy-chain 记录经过的 URL,既能递归合并又能防环。
|
|
45
55
|
const REMOTE_PROXY_HEADER = 'x-db-tool-proxy';
|
|
56
|
+
const REMOTE_CHAIN_HEADER = 'x-db-tool-proxy-chain';
|
|
57
|
+
const MAX_PROXY_HOPS = 5;
|
|
46
58
|
// 永不转发的路由:只作用于本地连接配置(无远程对应物或需要本地语义)
|
|
47
59
|
const LOCAL_ONLY_ROUTES = new Set([
|
|
48
60
|
'/api/database/getConnection',
|
|
@@ -62,12 +74,35 @@ const CONNECTION_CONFIG_ROUTES = new Set([
|
|
|
62
74
|
function isRemoteConnection(conn) {
|
|
63
75
|
return !!conn && conn.type === 'remote';
|
|
64
76
|
}
|
|
77
|
+
/** 深拷贝连接 options,并移除不应下发的远程访问令牌(混合版本兼容) */
|
|
78
|
+
function cloneOptionsWithoutRemoteToken(options) {
|
|
79
|
+
if (!options || typeof options !== 'object')
|
|
80
|
+
return options;
|
|
81
|
+
let cloned;
|
|
82
|
+
try {
|
|
83
|
+
cloned = JSON.parse(JSON.stringify(options));
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
cloned = Array.isArray(options) ? [...options] : { ...options };
|
|
87
|
+
}
|
|
88
|
+
if (cloned && typeof cloned === 'object' && !Array.isArray(cloned)) {
|
|
89
|
+
delete cloned.remoteToken;
|
|
90
|
+
}
|
|
91
|
+
return cloned;
|
|
92
|
+
}
|
|
65
93
|
/** 从请求中取出被操作连接的 id(body 或路径段) */
|
|
66
94
|
function extractConnId(pathname, body) {
|
|
67
95
|
if (pathname.startsWith('/api/database/truncateTable/') || pathname.startsWith('/api/database/dropTable/')) {
|
|
68
96
|
const parts = pathname.split('/').filter(Boolean);
|
|
69
97
|
return parts[3];
|
|
70
98
|
}
|
|
99
|
+
// health 路径允许 body 为空:复合 id 必须在路径段中可读;有 body.id 时仍保持旧优先级。
|
|
100
|
+
if (pathname.startsWith('/api/database/health/') && body && typeof body.id === 'string')
|
|
101
|
+
return body.id;
|
|
102
|
+
if (pathname.startsWith('/api/database/health/')) {
|
|
103
|
+
const parts = pathname.split('/').filter(Boolean);
|
|
104
|
+
return parts[3];
|
|
105
|
+
}
|
|
71
106
|
if (body && typeof body.id === 'string')
|
|
72
107
|
return body.id;
|
|
73
108
|
return undefined;
|
|
@@ -187,19 +222,43 @@ async function postRemote(url, body, headers, timeoutMs) {
|
|
|
187
222
|
}
|
|
188
223
|
return await postRemoteByNodeHttp(url, body, headers, timeoutMs);
|
|
189
224
|
}
|
|
190
|
-
/**
|
|
191
|
-
function buildRemoteHeaders(proxyConn) {
|
|
192
|
-
const headers = {
|
|
225
|
+
/** 构造带令牌与链路信息的请求头。proxyMarker=false 时允许对端递归合并自己的代理。 */
|
|
226
|
+
function buildRemoteHeaders(proxyConn, opts = {}) {
|
|
227
|
+
const headers = {};
|
|
228
|
+
if (opts.proxyMarker !== false)
|
|
229
|
+
headers[REMOTE_PROXY_HEADER] = '1';
|
|
230
|
+
const chain = opts.chain || [];
|
|
231
|
+
if (chain.length > 0)
|
|
232
|
+
headers[REMOTE_CHAIN_HEADER] = chain.join(',');
|
|
193
233
|
const token = proxyConn?.options?.remoteToken;
|
|
194
234
|
if (token)
|
|
195
235
|
headers[REMOTE_TOKEN_HEADER] = String(token);
|
|
196
236
|
return headers;
|
|
197
237
|
}
|
|
238
|
+
/** 纯判断:base 是否已出现在链路中(用于阻止代理互指导致的递归) */
|
|
239
|
+
function hasProxyLoop(base, chain) {
|
|
240
|
+
return !!base && chain.includes(base);
|
|
241
|
+
}
|
|
242
|
+
/** 纯判断:链路深度是否已达到 5 跳上限(当前 URL 尚未加入 chain) */
|
|
243
|
+
function isProxyHopLimitReached(chain) {
|
|
244
|
+
return chain.length >= MAX_PROXY_HOPS;
|
|
245
|
+
}
|
|
246
|
+
function remoteBaseOf(proxyConn) {
|
|
247
|
+
return String(proxyConn?.options?.remoteUrl || '').replace(/\/+$/, '');
|
|
248
|
+
}
|
|
249
|
+
function chainFromHeaders(headers) {
|
|
250
|
+
return String(headers?.[REMOTE_CHAIN_HEADER] || '').split(',').map((s) => s.trim()).filter(Boolean);
|
|
251
|
+
}
|
|
198
252
|
/** 把请求原样转发到远程 db_tool 服务端(自动解包远程响应,避免二次包装) */
|
|
199
|
-
async function proxyToRemote(proxyConn, remoteConnId, pathname, body) {
|
|
200
|
-
const base =
|
|
253
|
+
async function proxyToRemote(proxyConn, remoteConnId, pathname, body, chain = []) {
|
|
254
|
+
const base = remoteBaseOf(proxyConn);
|
|
201
255
|
if (!base)
|
|
202
256
|
throw new Error('远程代理连接缺少 remoteUrl');
|
|
257
|
+
if (hasProxyLoop(base, chain))
|
|
258
|
+
throw new Error(`检测到代理环路:${base}`);
|
|
259
|
+
if (isProxyHopLimitReached(chain))
|
|
260
|
+
throw new Error(`代理链路超过 ${MAX_PROXY_HOPS} 跳,已中止以防环`);
|
|
261
|
+
const nextChain = [...chain, base];
|
|
203
262
|
let targetPath = pathname;
|
|
204
263
|
if (pathname.startsWith('/api/database/truncateTable/') || pathname.startsWith('/api/database/dropTable/')) {
|
|
205
264
|
const parts = pathname.split('/').filter(Boolean);
|
|
@@ -209,19 +268,26 @@ async function proxyToRemote(proxyConn, remoteConnId, pathname, body) {
|
|
|
209
268
|
targetPath = '/' + parts.join('/');
|
|
210
269
|
}
|
|
211
270
|
const targetBody = { ...body, id: remoteConnId };
|
|
212
|
-
const env = await postRemote(`${base}${targetPath}`, targetBody, buildRemoteHeaders(proxyConn), 60000);
|
|
271
|
+
const env = await postRemote(`${base}${targetPath}`, targetBody, buildRemoteHeaders(proxyConn, { proxyMarker: false, chain: nextChain }), 60000);
|
|
213
272
|
if (env && typeof env === 'object' && env.ret && env.ret !== 0) {
|
|
214
273
|
throw new Error(env.msg || '远程服务执行失败');
|
|
215
274
|
}
|
|
216
275
|
return env?.data;
|
|
217
276
|
}
|
|
218
|
-
/**
|
|
219
|
-
|
|
220
|
-
|
|
277
|
+
/**
|
|
278
|
+
* 拉取远程服务上的连接列表。不发送旧版 proxy 标记,因此远程端会递归合并它自己的代理;
|
|
279
|
+
* 通过 chain 记录已访问的 URL,detect 到环路或超过跳数上限时停止,避免无限递归。
|
|
280
|
+
*/
|
|
281
|
+
async function fetchRemoteConnections(proxyConn, chain = []) {
|
|
282
|
+
const base = remoteBaseOf(proxyConn);
|
|
221
283
|
if (!base)
|
|
222
284
|
return { list: [], error: '缺少 remoteUrl' };
|
|
285
|
+
if (hasProxyLoop(base, chain))
|
|
286
|
+
return { list: [], error: `检测到代理环路:${base}` };
|
|
287
|
+
if (isProxyHopLimitReached(chain))
|
|
288
|
+
return { list: [], error: `代理链路超过 ${MAX_PROXY_HOPS} 跳` };
|
|
223
289
|
try {
|
|
224
|
-
const env = await postRemote(`${base}/api/database/getConnections`, {}, buildRemoteHeaders(proxyConn), 10000);
|
|
290
|
+
const env = await postRemote(`${base}/api/database/getConnections`, {}, buildRemoteHeaders(proxyConn, { proxyMarker: false, chain: [...chain, base] }), 10000);
|
|
225
291
|
if (env && env.ret && env.ret !== 0) {
|
|
226
292
|
console.warn('[remote] 获取远程连接列表失败:', env.msg);
|
|
227
293
|
return { list: [], error: env.msg || '远程服务返回错误' };
|
|
@@ -233,11 +299,12 @@ async function fetchRemoteConnections(proxyConn) {
|
|
|
233
299
|
return { list: [], error: e?.message || '远程服务不可达' };
|
|
234
300
|
}
|
|
235
301
|
}
|
|
236
|
-
/** 网关模式:本地连接列表 = 本地连接 +
|
|
237
|
-
async function handleGetConnectionsWithProxy() {
|
|
302
|
+
/** 网关模式:本地连接列表 = 本地连接 + 各级远程代理暴露的连接(支持 A→B→C 多级链路) */
|
|
303
|
+
async function handleGetConnectionsWithProxy(headers) {
|
|
238
304
|
const locals = await connectionService.getAllConnections();
|
|
305
|
+
const chain = chainFromHeaders(headers);
|
|
239
306
|
// 并行拉取各远程服务,避免多个远程时串行等待
|
|
240
|
-
const remoteResults = await Promise.all(locals.map(conn => (isRemoteConnection(conn) ? fetchRemoteConnections(conn) : Promise.resolve(null))));
|
|
307
|
+
const remoteResults = await Promise.all(locals.map(conn => (isRemoteConnection(conn) ? fetchRemoteConnections(conn, chain) : Promise.resolve(null))));
|
|
241
308
|
const result = [];
|
|
242
309
|
locals.forEach((conn, index) => {
|
|
243
310
|
if (!isRemoteConnection(conn)) {
|
|
@@ -248,16 +315,23 @@ async function handleGetConnectionsWithProxy() {
|
|
|
248
315
|
// 代理配置本身保留(用于编辑/删除),标记 _isProxy
|
|
249
316
|
result.push({ ...conn, _isProxy: true, _remoteError: remote?.error });
|
|
250
317
|
for (const rc of remote?.list || []) {
|
|
318
|
+
// 代理配置本身(含 remoteUrl/token)不能作为可操作的数据库连接暴露;
|
|
319
|
+
// 旧版本可能只靠 type='remote' 标记,混合版本下两种标记都要过滤。
|
|
251
320
|
if (rc.type === 'remote' || rc._isProxy)
|
|
252
|
-
continue;
|
|
321
|
+
continue;
|
|
253
322
|
const safe = { ...rc };
|
|
254
323
|
delete safe.password; // 不把远程库的密码下发到客户端
|
|
324
|
+
if (safe.options !== undefined)
|
|
325
|
+
safe.options = cloneOptionsWithoutRemoteToken(safe.options);
|
|
326
|
+
// 保留远程端已拼好的代理链:A::B::C,而不是把中间跳数丢掉
|
|
327
|
+
const proxyChain = rc._proxyId ? `${conn.id}${REMOTE_ID_SEP}${rc._proxyId}` : conn.id;
|
|
255
328
|
result.push({
|
|
256
329
|
...safe,
|
|
257
330
|
id: `${conn.id}${REMOTE_ID_SEP}${rc.id}`,
|
|
258
|
-
_proxyId:
|
|
331
|
+
_proxyId: proxyChain,
|
|
259
332
|
_remote: true,
|
|
260
|
-
_remoteName: conn.name
|
|
333
|
+
_remoteName: rc._remoteName ? `${conn.name} → ${rc._remoteName}` : conn.name,
|
|
334
|
+
_hops: (Number(rc._hops) || 0) + 1
|
|
261
335
|
});
|
|
262
336
|
}
|
|
263
337
|
});
|
|
@@ -276,6 +350,99 @@ async function testRemoteConnection(conn) {
|
|
|
276
350
|
// 初始化服务实例
|
|
277
351
|
const connectionService = new connection_service_1.ConnectionService();
|
|
278
352
|
const databaseService = new database_service_1.DatabaseService();
|
|
353
|
+
const BACKUP_SCHEDULE_FILE = 'backup-schedules.json';
|
|
354
|
+
function loadBackupSchedules() {
|
|
355
|
+
try {
|
|
356
|
+
const raw = fs.readFileSync((0, data_dir_1.getDataPath)(BACKUP_SCHEDULE_FILE), 'utf8');
|
|
357
|
+
const parsed = JSON.parse(raw);
|
|
358
|
+
return Array.isArray(parsed) ? parsed.filter((s) => s && s.id && s.connectionId) : [];
|
|
359
|
+
}
|
|
360
|
+
catch {
|
|
361
|
+
return [];
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
// 所有备份计划的 load-modify-save(增删改/手动执行/定时扫描)共用一条串行队列,避免并发覆盖。
|
|
365
|
+
let scheduleTaskQueue = Promise.resolve();
|
|
366
|
+
function enqueueScheduleTask(task) {
|
|
367
|
+
const result = scheduleTaskQueue.then(task);
|
|
368
|
+
scheduleTaskQueue = result.then(() => undefined, () => undefined);
|
|
369
|
+
return result;
|
|
370
|
+
}
|
|
371
|
+
function saveBackupSchedules(schedules) {
|
|
372
|
+
(0, data_dir_1.ensureDataDir)();
|
|
373
|
+
const target = (0, data_dir_1.getDataPath)(BACKUP_SCHEDULE_FILE);
|
|
374
|
+
const temp = `${target}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
375
|
+
try {
|
|
376
|
+
fs.writeFileSync(temp, JSON.stringify(schedules, null, 2), 'utf8');
|
|
377
|
+
fs.renameSync(temp, target);
|
|
378
|
+
}
|
|
379
|
+
catch (e) {
|
|
380
|
+
try {
|
|
381
|
+
fs.unlinkSync(temp);
|
|
382
|
+
}
|
|
383
|
+
catch {
|
|
384
|
+
// 临时文件可能尚未创建或已被清理,忽略二次错误
|
|
385
|
+
}
|
|
386
|
+
throw e;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
const inFlightScheduleIds = new Set();
|
|
390
|
+
/** 执行单个计划:成功才更新 lastRunAt,失败时保留原值供下一分钟重试。 */
|
|
391
|
+
async function executeBackupSchedule(schedule) {
|
|
392
|
+
if (inFlightScheduleIds.has(schedule.id))
|
|
393
|
+
throw new Error(`备份计划正在执行: ${schedule.id}`);
|
|
394
|
+
inFlightScheduleIds.add(schedule.id);
|
|
395
|
+
try {
|
|
396
|
+
const result = await databaseService.backupDatabase(schedule.connectionId, schedule.databaseName, {
|
|
397
|
+
scheduleId: schedule.id
|
|
398
|
+
});
|
|
399
|
+
schedule.lastRunAt = Date.now();
|
|
400
|
+
return result;
|
|
401
|
+
}
|
|
402
|
+
finally {
|
|
403
|
+
inFlightScheduleIds.delete(schedule.id);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
let backupSweepRunning = false;
|
|
407
|
+
/** 每分钟检查一次到期的计划;仅在本服务进程存活期间运行。 */
|
|
408
|
+
async function runDueBackups() {
|
|
409
|
+
if (backupSweepRunning)
|
|
410
|
+
return; // 全局重入保护:上一轮未结束(含备份 I/O)时直接跳过本次 tick
|
|
411
|
+
backupSweepRunning = true;
|
|
412
|
+
try {
|
|
413
|
+
await enqueueScheduleTask(async () => {
|
|
414
|
+
const schedules = loadBackupSchedules();
|
|
415
|
+
const now = Date.now();
|
|
416
|
+
let changed = false;
|
|
417
|
+
for (const s of schedules) {
|
|
418
|
+
if (!s.enabled || inFlightScheduleIds.has(s.id))
|
|
419
|
+
continue;
|
|
420
|
+
const intervalMs = Math.max(1, Number(s.intervalMinutes) || 60) * 60 * 1000;
|
|
421
|
+
if (now - (s.lastRunAt || 0) < intervalMs)
|
|
422
|
+
continue;
|
|
423
|
+
try {
|
|
424
|
+
await executeBackupSchedule(s);
|
|
425
|
+
changed = true;
|
|
426
|
+
}
|
|
427
|
+
catch (e) {
|
|
428
|
+
console.warn(`[backup-schedule] ${s.connectionId}/${s.databaseName} 备份失败:`, e?.message || e);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
if (changed)
|
|
432
|
+
saveBackupSchedules(schedules);
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
finally {
|
|
436
|
+
backupSweepRunning = false;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
const backupScheduler = setInterval(() => {
|
|
440
|
+
runDueBackups().catch((e) => {
|
|
441
|
+
console.warn('[backup-schedule] 定时检查失败:', e?.message || e);
|
|
442
|
+
});
|
|
443
|
+
}, 60 * 1000);
|
|
444
|
+
// 不阻止进程退出(VSCode 扩展宿主 / CLI 也会导入本模块)
|
|
445
|
+
backupScheduler.unref?.();
|
|
279
446
|
// 数据库相关路由处理
|
|
280
447
|
async function handleDatabaseRoutes(pathname, body, headers) {
|
|
281
448
|
try {
|
|
@@ -293,7 +460,7 @@ async function handleDatabaseRoutes(pathname, body, headers) {
|
|
|
293
460
|
if (headers && headers[REMOTE_PROXY_HEADER]) {
|
|
294
461
|
return await connectionService.getAllConnections();
|
|
295
462
|
}
|
|
296
|
-
return await handleGetConnectionsWithProxy();
|
|
463
|
+
return await handleGetConnectionsWithProxy(headers);
|
|
297
464
|
}
|
|
298
465
|
// 远程代理连接本身的测试:直接探活远程服务
|
|
299
466
|
if (pathname === '/api/database/testConnection' && body && isRemoteConnection(body)) {
|
|
@@ -303,7 +470,7 @@ async function handleDatabaseRoutes(pathname, body, headers) {
|
|
|
303
470
|
// 覆盖数据操作(查询/建表/改结构等)与连接配置的增删改
|
|
304
471
|
const proxy = await resolveRemoteProxy(pathname, body);
|
|
305
472
|
if (proxy) {
|
|
306
|
-
return await proxyToRemote(proxy.proxyConn, proxy.remoteConnId, pathname, body);
|
|
473
|
+
return await proxyToRemote(proxy.proxyConn, proxy.remoteConnId, pathname, body, chainFromHeaders(headers));
|
|
307
474
|
}
|
|
308
475
|
// 对「远程代理配置」本身做数据操作时给出明确提示(配置本身的增删改是允许的)
|
|
309
476
|
if (!CONNECTION_CONFIG_ROUTES.has(pathname)) {
|
|
@@ -349,6 +516,25 @@ async function handleDatabaseRoutes(pathname, body, headers) {
|
|
|
349
516
|
const result = await connectionService.testConnection(body);
|
|
350
517
|
return result;
|
|
351
518
|
}
|
|
519
|
+
// /api/database/health/:id/:database(或 ?id=...)——连通性探活。
|
|
520
|
+
// 客户端 checkDatabaseHealth 早在 UI 前就声明了此路由,但此前服务端没有实现。
|
|
521
|
+
if (pathname === '/api/database/health' || pathname.startsWith('/api/database/health/')) {
|
|
522
|
+
const parts = pathname.split('/').filter(Boolean);
|
|
523
|
+
const id = extractConnId(pathname, body);
|
|
524
|
+
if (!id)
|
|
525
|
+
throw Error('Missing parameter: id');
|
|
526
|
+
const database = body?.database || parts[4];
|
|
527
|
+
if (database) {
|
|
528
|
+
// 指定库时真正连接并读取库信息,失败由 getDatabaseInfo 抛出异常返回。
|
|
529
|
+
const info = await databaseService.getDatabaseInfo(id, database);
|
|
530
|
+
if (!info)
|
|
531
|
+
throw Error(`数据库不存在: ${database}`);
|
|
532
|
+
return { healthy: true, database };
|
|
533
|
+
}
|
|
534
|
+
// 未指定库时保留列库检查,适用于关系型与文档型;不执行方言专有 SQL。
|
|
535
|
+
const databases = await databaseService.getDatabases(id);
|
|
536
|
+
return { healthy: true, databaseCount: Array.isArray(databases) ? databases.length : 0 };
|
|
537
|
+
}
|
|
352
538
|
// /api/database/getDatabases
|
|
353
539
|
if (pathname === '/api/database/getDatabases') {
|
|
354
540
|
const { id } = body;
|
|
@@ -381,6 +567,45 @@ async function handleDatabaseRoutes(pathname, body, headers) {
|
|
|
381
567
|
const result = await databaseService.getTableInfo(id, database, table);
|
|
382
568
|
return result;
|
|
383
569
|
}
|
|
570
|
+
// ---- 文档型(MongoDB)索引与聚合:统一走方言 service,未实现的方言会明确报错 ----
|
|
571
|
+
// /api/database/getIndexes
|
|
572
|
+
if (pathname === '/api/database/getIndexes') {
|
|
573
|
+
const { id, database, table } = body;
|
|
574
|
+
if (!id || !database || !table)
|
|
575
|
+
throw Error('Missing parameters: id, database, table');
|
|
576
|
+
const dataSource = await databaseService['connectionService'].getActiveConnection(id, database);
|
|
577
|
+
const dbService = databaseService['getDatabaseService'](dataSource.options.type);
|
|
578
|
+
return await dbService.getIndexes(dataSource, database, table);
|
|
579
|
+
}
|
|
580
|
+
// /api/database/createIndex
|
|
581
|
+
if (pathname === '/api/database/createIndex') {
|
|
582
|
+
const { id, database, table, keys, options } = body;
|
|
583
|
+
if (!id || !database || !table || !keys)
|
|
584
|
+
throw Error('Missing parameters: id, database, table, keys');
|
|
585
|
+
const dataSource = await databaseService['connectionService'].getActiveConnection(id, database);
|
|
586
|
+
const dbService = databaseService['getDatabaseService'](dataSource.options.type);
|
|
587
|
+
const name = await dbService.createIndex(dataSource, database, table, keys, options);
|
|
588
|
+
return { success: true, name };
|
|
589
|
+
}
|
|
590
|
+
// /api/database/dropIndex
|
|
591
|
+
if (pathname === '/api/database/dropIndex') {
|
|
592
|
+
const { id, database, table, indexName } = body;
|
|
593
|
+
if (!id || !database || !table || !indexName)
|
|
594
|
+
throw Error('Missing parameters: id, database, table, indexName');
|
|
595
|
+
const dataSource = await databaseService['connectionService'].getActiveConnection(id, database);
|
|
596
|
+
const dbService = databaseService['getDatabaseService'](dataSource.options.type);
|
|
597
|
+
await dbService.dropIndex(dataSource, database, table, indexName);
|
|
598
|
+
return { success: true };
|
|
599
|
+
}
|
|
600
|
+
// /api/database/aggregate
|
|
601
|
+
if (pathname === '/api/database/aggregate') {
|
|
602
|
+
const { id, database, table, pipeline } = body;
|
|
603
|
+
if (!id || !database || !table || !pipeline)
|
|
604
|
+
throw Error('Missing parameters: id, database, table, pipeline');
|
|
605
|
+
const dataSource = await databaseService['connectionService'].getActiveConnection(id, database);
|
|
606
|
+
const dbService = databaseService['getDatabaseService'](dataSource.options.type);
|
|
607
|
+
return await dbService.aggregate(dataSource, database, table, pipeline);
|
|
608
|
+
}
|
|
384
609
|
// /api/database/getTableData
|
|
385
610
|
if (pathname === '/api/database/getTableData') {
|
|
386
611
|
const { id, database, table, page = 1, pageSize = 100, where, orderBy } = body;
|
|
@@ -453,6 +678,79 @@ async function handleDatabaseRoutes(pathname, body, headers) {
|
|
|
453
678
|
const result = await databaseService.backupDatabase(id, databaseName, options);
|
|
454
679
|
return { success: true, result };
|
|
455
680
|
}
|
|
681
|
+
// 定时备份计划:配置持久化在数据目录,调度由本进程每分钟检查一次
|
|
682
|
+
if (pathname === '/api/database/getBackupSchedules') {
|
|
683
|
+
return { schedules: loadBackupSchedules() };
|
|
684
|
+
}
|
|
685
|
+
if (pathname === '/api/database/addBackupSchedule') {
|
|
686
|
+
const { connectionId, databaseName, intervalMinutes = 60, enabled = true } = body || {};
|
|
687
|
+
if (!connectionId || !databaseName)
|
|
688
|
+
throw Error('Missing parameters: connectionId, databaseName');
|
|
689
|
+
return await enqueueScheduleTask(async () => {
|
|
690
|
+
const schedules = loadBackupSchedules();
|
|
691
|
+
const item = {
|
|
692
|
+
id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
|
|
693
|
+
connectionId,
|
|
694
|
+
databaseName,
|
|
695
|
+
intervalMinutes: Math.max(1, Math.floor(Number(intervalMinutes) || 60)),
|
|
696
|
+
enabled: !!enabled,
|
|
697
|
+
createdAt: Date.now()
|
|
698
|
+
};
|
|
699
|
+
schedules.push(item);
|
|
700
|
+
saveBackupSchedules(schedules);
|
|
701
|
+
return { schedule: item };
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
if (pathname === '/api/database/updateBackupSchedule') {
|
|
705
|
+
const { id, ...updates } = body || {};
|
|
706
|
+
if (!id)
|
|
707
|
+
throw Error('Missing parameter: id');
|
|
708
|
+
return await enqueueScheduleTask(async () => {
|
|
709
|
+
const schedules = loadBackupSchedules();
|
|
710
|
+
const item = schedules.find((s) => s.id === id);
|
|
711
|
+
if (!item)
|
|
712
|
+
throw Error(`备份计划不存在: ${id}`);
|
|
713
|
+
// 只接受可编辑字段,禁止外部改写 lastRunAt / createdAt / id 等运行时字段。
|
|
714
|
+
if (updates.connectionId !== undefined)
|
|
715
|
+
item.connectionId = String(updates.connectionId);
|
|
716
|
+
if (updates.databaseName !== undefined)
|
|
717
|
+
item.databaseName = String(updates.databaseName);
|
|
718
|
+
if (updates.intervalMinutes !== undefined) {
|
|
719
|
+
item.intervalMinutes = Math.max(1, Math.floor(Number(updates.intervalMinutes) || 60));
|
|
720
|
+
}
|
|
721
|
+
if (updates.enabled !== undefined)
|
|
722
|
+
item.enabled = !!updates.enabled;
|
|
723
|
+
saveBackupSchedules(schedules);
|
|
724
|
+
return { schedule: item };
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
if (pathname === '/api/database/deleteBackupSchedule') {
|
|
728
|
+
const { id } = body || {};
|
|
729
|
+
if (!id)
|
|
730
|
+
throw Error('Missing parameter: id');
|
|
731
|
+
return await enqueueScheduleTask(async () => {
|
|
732
|
+
const schedules = loadBackupSchedules();
|
|
733
|
+
const kept = schedules.filter((s) => s.id !== id);
|
|
734
|
+
if (kept.length === schedules.length)
|
|
735
|
+
throw Error(`备份计划不存在: ${id}`);
|
|
736
|
+
saveBackupSchedules(kept);
|
|
737
|
+
return { success: true };
|
|
738
|
+
});
|
|
739
|
+
}
|
|
740
|
+
if (pathname === '/api/database/runBackupSchedule') {
|
|
741
|
+
const { id } = body || {};
|
|
742
|
+
if (!id)
|
|
743
|
+
throw Error('Missing parameter: id');
|
|
744
|
+
return await enqueueScheduleTask(async () => {
|
|
745
|
+
const schedules = loadBackupSchedules();
|
|
746
|
+
const schedule = schedules.find((s) => s.id === id);
|
|
747
|
+
if (!schedule)
|
|
748
|
+
throw Error(`备份计划不存在: ${id}`);
|
|
749
|
+
const result = await executeBackupSchedule(schedule);
|
|
750
|
+
saveBackupSchedules(schedules);
|
|
751
|
+
return { success: true, result };
|
|
752
|
+
});
|
|
753
|
+
}
|
|
456
754
|
// /api/database/restore
|
|
457
755
|
if (pathname === '/api/database/restore') {
|
|
458
756
|
const { id, databaseName, filePath, options } = body;
|
|
@@ -586,6 +884,13 @@ async function handleDatabaseRoutes(pathname, body, headers) {
|
|
|
586
884
|
const result = await databaseService.syncTable(id, syncConfig);
|
|
587
885
|
return result;
|
|
588
886
|
}
|
|
887
|
+
// /api/database/importData:浏览器解析文件后按批提交行数组,服务端按方言 bulkInsert
|
|
888
|
+
if (pathname === '/api/database/importData') {
|
|
889
|
+
const { id, database, table, rows } = body;
|
|
890
|
+
if (!id || !database || !table || !Array.isArray(rows))
|
|
891
|
+
throw Error('Missing parameters: id, database, table, rows');
|
|
892
|
+
return await databaseService.importData(id, database, table, rows);
|
|
893
|
+
}
|
|
589
894
|
// /api/database/insertData
|
|
590
895
|
if (pathname === '/api/database/insertData') {
|
|
591
896
|
const { id, database, table, data } = body;
|
|
@@ -594,6 +899,13 @@ async function handleDatabaseRoutes(pathname, body, headers) {
|
|
|
594
899
|
// 获取数据库服务实例以使用正确的语法
|
|
595
900
|
const dataSource = await databaseService['connectionService'].getActiveConnection(id, database);
|
|
596
901
|
const dbService = databaseService['getDatabaseService'](dataSource.options.type);
|
|
902
|
+
// 文档型(MongoDB):直接插入文档,不拼 INSERT SQL
|
|
903
|
+
if ((0, dialect_1.dataModelOf)(dataSource.options.type) === 'document') {
|
|
904
|
+
const result = Array.isArray(data)
|
|
905
|
+
? await dbService.bulkInsert(dataSource, database, table, data)
|
|
906
|
+
: await dbService.insertDocument(dataSource, database, table, data);
|
|
907
|
+
return { success: true, result };
|
|
908
|
+
}
|
|
597
909
|
// 获取表的列信息,用于过滤自增字段
|
|
598
910
|
const columns = await dbService.getColumns(dataSource, database, table);
|
|
599
911
|
const sql = generateInsertSQL(dataSource.options.type, table, data, dbService, columns);
|
|
@@ -602,24 +914,42 @@ async function handleDatabaseRoutes(pathname, body, headers) {
|
|
|
602
914
|
}
|
|
603
915
|
// /api/database/updateData
|
|
604
916
|
if (pathname === '/api/database/updateData') {
|
|
605
|
-
const { id, database, table, data, where } = body;
|
|
606
|
-
if (!id || !database || !table || !data
|
|
917
|
+
const { id, database, table, data, where, docId } = body;
|
|
918
|
+
if (!id || !database || !table || !data)
|
|
607
919
|
throw Error('Missing parameters');
|
|
608
920
|
// 获取数据库服务实例以使用正确的语法
|
|
609
921
|
const dataSource = await databaseService['connectionService'].getActiveConnection(id, database);
|
|
610
922
|
const dbService = databaseService['getDatabaseService'](dataSource.options.type);
|
|
923
|
+
// 文档型(MongoDB):按 _id 更新,不拼 UPDATE SQL
|
|
924
|
+
if ((0, dialect_1.dataModelOf)(dataSource.options.type) === 'document') {
|
|
925
|
+
if (!docId)
|
|
926
|
+
throw Error('Missing parameters: docId');
|
|
927
|
+
await dbService.updateDocument(dataSource, database, table, docId, data);
|
|
928
|
+
return { success: true };
|
|
929
|
+
}
|
|
930
|
+
if (!where)
|
|
931
|
+
throw Error('Missing parameters');
|
|
611
932
|
const sql = generateUpdateSQL(dataSource.options.type, table, data, where, dbService);
|
|
612
933
|
const result = await databaseService.executeQuery(id, sql, database);
|
|
613
934
|
return { sql, result };
|
|
614
935
|
}
|
|
615
936
|
// /api/database/deleteData
|
|
616
937
|
if (pathname === '/api/database/deleteData') {
|
|
617
|
-
const { id, database, table, where } = body;
|
|
618
|
-
if (!id || !database || !table
|
|
938
|
+
const { id, database, table, where, docId } = body;
|
|
939
|
+
if (!id || !database || !table)
|
|
619
940
|
throw Error('Missing parameters');
|
|
620
941
|
// 获取数据库服务实例以使用正确的语法
|
|
621
942
|
const dataSource = await databaseService['connectionService'].getActiveConnection(id, database);
|
|
622
943
|
const dbService = databaseService['getDatabaseService'](dataSource.options.type);
|
|
944
|
+
// 文档型(MongoDB):按 _id 删除,不拼 DELETE SQL
|
|
945
|
+
if ((0, dialect_1.dataModelOf)(dataSource.options.type) === 'document') {
|
|
946
|
+
if (!docId)
|
|
947
|
+
throw Error('Missing parameters: docId');
|
|
948
|
+
await dbService.deleteDocument(dataSource, database, table, docId);
|
|
949
|
+
return { success: true };
|
|
950
|
+
}
|
|
951
|
+
if (!where)
|
|
952
|
+
throw Error('Missing parameters');
|
|
623
953
|
const sql = generateDeleteSQL(dataSource.options.type, table, where, dbService);
|
|
624
954
|
const result = await databaseService.executeQuery(id, sql, database);
|
|
625
955
|
return { success: true, sql, result };
|
|
@@ -634,9 +964,15 @@ async function handleDatabaseRoutes(pathname, body, headers) {
|
|
|
634
964
|
const table = parts[5];
|
|
635
965
|
if (!id || !database || !table)
|
|
636
966
|
throw Error('Missing parameters');
|
|
637
|
-
//
|
|
967
|
+
// 获取数据库服务实例以使用正确的语法
|
|
638
968
|
const dataSource = await databaseService['connectionService'].getActiveConnection(id, database);
|
|
639
969
|
const dbService = databaseService['getDatabaseService'](dataSource.options.type);
|
|
970
|
+
// 文档型(MongoDB):deleteMany({}),无 TRUNCATE 语法
|
|
971
|
+
if ((0, dialect_1.dataModelOf)(dataSource.options.type) === 'document') {
|
|
972
|
+
const deleted = await dbService.truncateCollection(dataSource, database, table);
|
|
973
|
+
return { success: true, deleted };
|
|
974
|
+
}
|
|
975
|
+
// 使用数据库服务生成正确的TRUNCATE语法
|
|
640
976
|
const sql = `TRUNCATE TABLE ${dbService['quoteIdentifier'](table)}`;
|
|
641
977
|
const result = await databaseService.executeQuery(id, sql, database);
|
|
642
978
|
return { success: true, sql, result };
|
|
@@ -651,9 +987,15 @@ async function handleDatabaseRoutes(pathname, body, headers) {
|
|
|
651
987
|
const table = parts[5];
|
|
652
988
|
if (!id || !database || !table)
|
|
653
989
|
throw Error('Missing parameters');
|
|
654
|
-
//
|
|
990
|
+
// 获取数据库服务实例以使用正确的语法
|
|
655
991
|
const dataSource = await databaseService['connectionService'].getActiveConnection(id, database);
|
|
656
992
|
const dbService = databaseService['getDatabaseService'](dataSource.options.type);
|
|
993
|
+
// 文档型(MongoDB):collection.drop(),无 DROP TABLE 语法
|
|
994
|
+
if ((0, dialect_1.dataModelOf)(dataSource.options.type) === 'document') {
|
|
995
|
+
await dbService.dropTable(dataSource, database, table);
|
|
996
|
+
return { success: true };
|
|
997
|
+
}
|
|
998
|
+
// 使用数据库服务生成正确的DROP语法
|
|
657
999
|
const sql = `DROP TABLE ${dbService['quoteIdentifier'](table)}`;
|
|
658
1000
|
const result = await databaseService.executeQuery(id, sql, database);
|
|
659
1001
|
return { success: true, sql, result };
|
|
@@ -776,6 +1118,11 @@ function generateUpdateSQL(dbType, tableName, data, where, dbService) {
|
|
|
776
1118
|
return `${dbService.quoteIdentifier(key)} = ${formatValue(dbType, value)}`;
|
|
777
1119
|
})
|
|
778
1120
|
.join(' AND ');
|
|
1121
|
+
// ClickHouse 的 MergeTree 不支持标准 UPDATE;必须用 ALTER TABLE ... UPDATE(DELETE 同理)。
|
|
1122
|
+
// mutation 默认是异步的,加 mutations_sync=1 等待完成,避免 UI 立即刷新仍读到旧值。
|
|
1123
|
+
if (dbType === 'clickhouse') {
|
|
1124
|
+
return `ALTER TABLE ${dbService.quoteIdentifier(tableName)} UPDATE ${setClause} WHERE ${whereClause} SETTINGS mutations_sync = 1;`;
|
|
1125
|
+
}
|
|
779
1126
|
return `UPDATE ${dbService.quoteIdentifier(tableName)} SET ${setClause} WHERE ${whereClause};`;
|
|
780
1127
|
}
|
|
781
1128
|
function generateDeleteSQL(dbType, tableName, where, dbService) {
|
|
@@ -787,6 +1134,9 @@ function generateDeleteSQL(dbType, tableName, where, dbService) {
|
|
|
787
1134
|
return `${dbService.quoteIdentifier(key)} = ${formatValue(dbType, value)}`;
|
|
788
1135
|
})
|
|
789
1136
|
.join(' AND ');
|
|
1137
|
+
if (dbType === 'clickhouse') {
|
|
1138
|
+
return `ALTER TABLE ${dbService.quoteIdentifier(tableName)} DELETE WHERE ${whereClause} SETTINGS mutations_sync = 1;`;
|
|
1139
|
+
}
|
|
790
1140
|
return `DELETE FROM ${dbService.quoteIdentifier(tableName)} WHERE ${whereClause};`;
|
|
791
1141
|
}
|
|
792
1142
|
function formatValue(dbType, value) {
|