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