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
|
@@ -5,12 +5,13 @@
|
|
|
5
5
|
* 建连 -> getDatabases -> getTables -> 建表 -> getColumns -> 插入 -> 查数据
|
|
6
6
|
* -> 改表/校验 -> 导出schema -> 删表
|
|
7
7
|
*
|
|
8
|
-
* 关系型(postgres/cockroachdb/oracle/mssql/sqlite)走 DDL spec 建表/改表 + SQL 查询;
|
|
8
|
+
* 关系型(postgres/cockroachdb/oracle/mssql/sqlite/clickhouse)走 DDL spec 建表/改表 + SQL 查询;
|
|
9
9
|
* MongoDB 走服务自身的集合方法(文档库无 SQL DDL)。
|
|
10
10
|
*
|
|
11
11
|
* 用法:
|
|
12
12
|
* DB_TOOL_DATA_DIR=/tmp/dbtool-verify node scripts/verify-db-support.cjs [type ...]
|
|
13
|
-
* type ∈ postgres cockroachdb oracle mssql mongodb sqlite
|
|
13
|
+
* type ∈ postgres cockroachdb oracle mssql mongodb clickhouse sqlite
|
|
14
|
+
* VERIFY_SKIP_TYPES=clickhouse 可从默认列表跳过指定类型(无数据库服务的环境使用)
|
|
14
15
|
*/
|
|
15
16
|
'use strict';
|
|
16
17
|
|
|
@@ -37,6 +38,9 @@ const CONN = {
|
|
|
37
38
|
|
|
38
39
|
const TABLE = 'verify_tbl';
|
|
39
40
|
|
|
41
|
+
let passCount = 0;
|
|
42
|
+
let failCount = 0;
|
|
43
|
+
|
|
40
44
|
function specBase() {
|
|
41
45
|
return {
|
|
42
46
|
name: TABLE, comment: 'verify table',
|
|
@@ -57,8 +61,9 @@ function specAltered() {
|
|
|
57
61
|
function step(name, fn) {
|
|
58
62
|
return Promise.resolve()
|
|
59
63
|
.then(fn)
|
|
60
|
-
.then(r => { console.log(` [PASS] ${name}`); return r; })
|
|
64
|
+
.then(r => { passCount += 1; console.log(` [PASS] ${name}`); return r; })
|
|
61
65
|
.catch(e => {
|
|
66
|
+
failCount += 1;
|
|
62
67
|
const msg = e && e.message ? e.message.split('\n')[0] : String(e);
|
|
63
68
|
console.log(` [FAIL] ${name} -> ${msg}`);
|
|
64
69
|
return { __error: msg };
|
|
@@ -67,7 +72,7 @@ function step(name, fn) {
|
|
|
67
72
|
|
|
68
73
|
async function runType(type) {
|
|
69
74
|
const cfg = CONN[type];
|
|
70
|
-
if (!cfg) { console.log(`未知类型: ${type}`); return; }
|
|
75
|
+
if (!cfg) { failCount += 1; console.log(`未知类型: ${type}`); return; }
|
|
71
76
|
const isMongo = type === 'mongodb';
|
|
72
77
|
console.log(`\n==================== ${type} ====================`);
|
|
73
78
|
const connService = new ConnectionService();
|
|
@@ -101,6 +106,37 @@ async function runType(type) {
|
|
|
101
106
|
return list;
|
|
102
107
|
});
|
|
103
108
|
|
|
109
|
+
await step('checkDatabaseHealth', async () => {
|
|
110
|
+
const report = await dispatcher.checkDatabaseHealth(id, db);
|
|
111
|
+
if (!report || !Array.isArray(report.checks) || report.checks.length === 0) {
|
|
112
|
+
throw new Error('健康检查报告为空');
|
|
113
|
+
}
|
|
114
|
+
const connectivity = report.checks.find(c => c.checkKey === 'connectivity');
|
|
115
|
+
if (!connectivity || connectivity.status !== 'healthy') {
|
|
116
|
+
throw new Error('健康检查连通性失败: ' + (connectivity?.detail?.reason || 'unknown'));
|
|
117
|
+
}
|
|
118
|
+
if (Number(report.summary?.error || 0) > 0) {
|
|
119
|
+
const failed = report.checks.filter(c => c.status === 'error').map(c => c.checkKey).join(', ');
|
|
120
|
+
throw new Error('健康检查存在失败项: ' + failed);
|
|
121
|
+
}
|
|
122
|
+
return { dialect: report.dialect, mode: report.mode, summary: report.summary };
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
await step('explainQuery', async () => {
|
|
126
|
+
const result = await dispatcher.explainQuery(id, 'SELECT 1', db);
|
|
127
|
+
if (!result || typeof result.supported !== 'boolean') throw new Error('执行计划返回结构无效');
|
|
128
|
+
if (result.supported && !result.explainSql) throw new Error('支持执行计划但未返回实际语句');
|
|
129
|
+
return { dialect: result.dialect, supported: result.supported, reason: result.reason };
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
await step('getResourceMetrics', async () => {
|
|
133
|
+
const metrics = await dispatcher.getResourceMetrics(id, db);
|
|
134
|
+
if (!metrics || !metrics.activeConnections || !metrics.databaseSizeBytes) {
|
|
135
|
+
throw new Error('资源指标返回结构无效');
|
|
136
|
+
}
|
|
137
|
+
return { dialect: metrics.dialect, active: metrics.activeConnections.supported, size: metrics.databaseSizeBytes.supported };
|
|
138
|
+
});
|
|
139
|
+
|
|
104
140
|
// 清理残留
|
|
105
141
|
await (async () => {
|
|
106
142
|
try { const { ds, base } = await baseOf(db); await base.dropTable(ds, db, TABLE); } catch (e) { /* ignore */ }
|
|
@@ -139,6 +175,54 @@ async function runType(type) {
|
|
|
139
175
|
if (!s || !s.trim()) throw new Error('schema 为空');
|
|
140
176
|
return s;
|
|
141
177
|
});
|
|
178
|
+
const IDX_NAME = 'idx_verify_name';
|
|
179
|
+
const IDX_KEYS = { name: 1 };
|
|
180
|
+
|
|
181
|
+
await step('createIndex', async () => {
|
|
182
|
+
const { ds, base } = await baseOf(db);
|
|
183
|
+
const name = await base.createIndex(ds, db, TABLE, IDX_KEYS, { name: IDX_NAME });
|
|
184
|
+
if (name !== IDX_NAME) throw new Error('createIndex 返回索引名不符: ' + name);
|
|
185
|
+
return name;
|
|
186
|
+
});
|
|
187
|
+
await step('getIndexes(建索引后)', async () => {
|
|
188
|
+
const { ds, base } = await baseOf(db);
|
|
189
|
+
const indexes = await base.getIndexes(ds, db, TABLE);
|
|
190
|
+
const idx = indexes.find(i => i.name === IDX_NAME);
|
|
191
|
+
if (!idx) throw new Error('未找到索引 ' + IDX_NAME);
|
|
192
|
+
if (!Array.isArray(idx.columns) || !idx.columns.includes('name')) {
|
|
193
|
+
throw new Error('索引列不符: ' + JSON.stringify(idx.columns));
|
|
194
|
+
}
|
|
195
|
+
return indexes;
|
|
196
|
+
});
|
|
197
|
+
await step('createIndex(重复创建幂等)', async () => {
|
|
198
|
+
const { ds, base } = await baseOf(db);
|
|
199
|
+
const name = await base.createIndex(ds, db, TABLE, IDX_KEYS, { name: IDX_NAME });
|
|
200
|
+
if (name !== IDX_NAME) throw new Error('重复创建返回的索引名变化: ' + name);
|
|
201
|
+
const indexes = await base.getIndexes(ds, db, TABLE);
|
|
202
|
+
const dup = indexes.filter(i => i.name === IDX_NAME);
|
|
203
|
+
if (dup.length !== 1) throw new Error('重复创建后出现重复索引: ' + dup.length);
|
|
204
|
+
return indexes;
|
|
205
|
+
});
|
|
206
|
+
await step('aggregate($match/$group)', async () => {
|
|
207
|
+
const { ds, base } = await baseOf(db);
|
|
208
|
+
const rows = await base.aggregate(ds, db, TABLE, [
|
|
209
|
+
{ $match: { age: { $gt: 25 } } },
|
|
210
|
+
{ $group: { _id: null, count: { $sum: 1 }, totalAge: { $sum: '$age' } } }
|
|
211
|
+
]);
|
|
212
|
+
if (!Array.isArray(rows) || rows.length !== 1) throw new Error('聚合结果行数不符: ' + JSON.stringify(rows));
|
|
213
|
+
if (rows[0].count !== 1 || rows[0].totalAge !== 30) {
|
|
214
|
+
throw new Error('$match/$group 结果不符: ' + JSON.stringify(rows[0]));
|
|
215
|
+
}
|
|
216
|
+
return rows;
|
|
217
|
+
});
|
|
218
|
+
await step('dropIndex', async () => {
|
|
219
|
+
const { ds, base } = await baseOf(db);
|
|
220
|
+
await base.dropIndex(ds, db, TABLE, IDX_NAME);
|
|
221
|
+
const indexes = await base.getIndexes(ds, db, TABLE);
|
|
222
|
+
if (indexes.some(i => i.name === IDX_NAME)) throw new Error('索引未删除: ' + IDX_NAME);
|
|
223
|
+
if (!indexes.some(i => i.name === '_id_')) throw new Error('默认 _id_ 索引被误删');
|
|
224
|
+
return indexes;
|
|
225
|
+
});
|
|
142
226
|
await step('dropTable(清理)', async () => {
|
|
143
227
|
const { ds, base } = await baseOf(db);
|
|
144
228
|
await base.dropTable(ds, db, TABLE);
|
|
@@ -231,9 +315,11 @@ async function runType(type) {
|
|
|
231
315
|
|
|
232
316
|
(async () => {
|
|
233
317
|
const args = process.argv.slice(2);
|
|
234
|
-
const
|
|
318
|
+
const DEFAULT_TYPES = ['postgres', 'cockroachdb', 'oracle', 'mssql', 'mongodb', 'clickhouse', 'sqlite'];
|
|
319
|
+
const skipTypes = new Set((process.env.VERIFY_SKIP_TYPES || '').split(',').map(s => s.trim()).filter(Boolean));
|
|
320
|
+
const types = args.length ? args : DEFAULT_TYPES.filter(t => !skipTypes.has(t));
|
|
235
321
|
console.log('数据目录:', dataDir);
|
|
236
322
|
for (const t of types) { await runType(t); }
|
|
237
|
-
console.log(
|
|
238
|
-
process.exit(0);
|
|
323
|
+
console.log(`\n==================== 完成: ${passCount} PASS, ${failCount} FAIL ====================`);
|
|
324
|
+
process.exit(failCount ? 1 : 0);
|
|
239
325
|
})().catch(e => { console.error('harness 崩溃:', e); process.exit(1); });
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as os from 'os';
|
|
3
|
+
import * as path from 'path';
|
|
4
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
5
|
+
import { MySQLService } from '../service/database/mysql.service';
|
|
6
|
+
import { PostgreSQLService } from '../service/database/postgres.service';
|
|
7
|
+
import { SQLiteService } from '../service/database/sqlite.service';
|
|
8
|
+
import { SQLServerService } from '../service/database/mssql.service';
|
|
9
|
+
import { OracleService } from '../service/database/oracle.service';
|
|
10
|
+
import { ClickHouseService } from '../service/database/clickhouse.service';
|
|
11
|
+
import { CockroachDBService } from '../service/database/cockroachdb.service';
|
|
12
|
+
import { SAPHANADatabaseService } from '../service/database/sap.service';
|
|
13
|
+
import { MongoDBService } from '../service/database/mongodb.service';
|
|
14
|
+
|
|
15
|
+
const ExcelJS = require('exceljs');
|
|
16
|
+
|
|
17
|
+
describe('exportTableDataToExcel', () => {
|
|
18
|
+
let exportDir: string;
|
|
19
|
+
|
|
20
|
+
beforeEach(() => {
|
|
21
|
+
exportDir = fs.mkdtempSync(path.join(os.tmpdir(), 'fdb2-excel-export-'));
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
afterEach(() => {
|
|
25
|
+
vi.restoreAllMocks();
|
|
26
|
+
fs.rmSync(exportDir, { recursive: true, force: true });
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
const cases: Array<[string, () => any]> = [
|
|
30
|
+
['MySQL', () => new MySQLService()],
|
|
31
|
+
['PostgreSQL', () => new PostgreSQLService()],
|
|
32
|
+
['SQLite', () => new SQLiteService()],
|
|
33
|
+
['SQL Server', () => new SQLServerService()],
|
|
34
|
+
['Oracle', () => new OracleService()],
|
|
35
|
+
['ClickHouse', () => new ClickHouseService()],
|
|
36
|
+
['CockroachDB', () => new CockroachDBService()],
|
|
37
|
+
['SAP HANA', () => new SAPHANADatabaseService()]
|
|
38
|
+
];
|
|
39
|
+
|
|
40
|
+
for (const [label, createService] of cases) {
|
|
41
|
+
it(`${label} 导出真正的 xlsx 文件而不是 CSV`, async () => {
|
|
42
|
+
const service = createService();
|
|
43
|
+
vi.spyOn(service, 'getColumns').mockResolvedValue([
|
|
44
|
+
{ name: 'id', type: 'int' },
|
|
45
|
+
{ name: 'name', type: 'varchar(50)' }
|
|
46
|
+
]);
|
|
47
|
+
|
|
48
|
+
let calls = 0;
|
|
49
|
+
const dataSource = {
|
|
50
|
+
query: vi.fn(async () => {
|
|
51
|
+
calls += 1;
|
|
52
|
+
return calls === 1 ? [{ id: 1, name: 'Ada' }] : [];
|
|
53
|
+
})
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const file = await service.exportTableDataToExcel(dataSource, 'demo', 'users', { path: exportDir });
|
|
57
|
+
|
|
58
|
+
expect(file.endsWith('.xlsx')).toBe(true);
|
|
59
|
+
expect(fs.existsSync(file)).toBe(true);
|
|
60
|
+
|
|
61
|
+
const workbook = new ExcelJS.Workbook();
|
|
62
|
+
await workbook.xlsx.readFile(file);
|
|
63
|
+
const sheet = workbook.getWorksheet('users');
|
|
64
|
+
expect(sheet).toBeTruthy();
|
|
65
|
+
expect(sheet!.getCell('A1').value).toBe('id');
|
|
66
|
+
expect(sheet!.getCell('B1').value).toBe('name');
|
|
67
|
+
expect(sheet!.getCell('A2').value).toBe(1);
|
|
68
|
+
expect(sheet!.getCell('B2').value).toBe('Ada');
|
|
69
|
+
expect(dataSource.query).toHaveBeenCalledTimes(2);
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
it('Oracle 分页导出的外层只投影真实列,不暴露 RNUM', async () => {
|
|
74
|
+
const service = new OracleService();
|
|
75
|
+
vi.spyOn(service, 'getColumns').mockResolvedValue([
|
|
76
|
+
{ name: 'id', type: 'number' },
|
|
77
|
+
{ name: 'name', type: 'varchar2' }
|
|
78
|
+
]);
|
|
79
|
+
|
|
80
|
+
const queries: string[] = [];
|
|
81
|
+
const dataSource = {
|
|
82
|
+
query: vi.fn(async (sql: string) => {
|
|
83
|
+
queries.push(sql);
|
|
84
|
+
return queries.length === 1 ? [{ id: 1, name: 'Ada', rnum: 99 }] : [];
|
|
85
|
+
})
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const file = await service.exportTableDataToExcel(dataSource, 'demo', 'users', { path: exportDir });
|
|
89
|
+
const workbook = new ExcelJS.Workbook();
|
|
90
|
+
await workbook.xlsx.readFile(file);
|
|
91
|
+
const sheet = workbook.getWorksheet('users');
|
|
92
|
+
|
|
93
|
+
expect(queries[0]).toContain('SELECT "ID", "NAME" FROM');
|
|
94
|
+
expect(sheet?.getCell('C1').value).toBeNull();
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it('MongoDB 空集合 CSV 保留表头,且游标被关闭', async () => {
|
|
98
|
+
const service = new MongoDBService();
|
|
99
|
+
vi.spyOn(service, 'getColumns').mockResolvedValue([{ name: 'id', type: 'objectId' }]);
|
|
100
|
+
const close = vi.fn(async () => undefined);
|
|
101
|
+
const cursor = { next: vi.fn(async () => null), close };
|
|
102
|
+
const dataSource: any = {
|
|
103
|
+
driver: {
|
|
104
|
+
queryRunner: {
|
|
105
|
+
databaseConnection: {
|
|
106
|
+
db: () => ({ collection: () => ({ find: () => ({ batchSize: () => cursor }) }) })
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
const file = await service.exportTableDataToCSV(dataSource, 'demo', 'empty', { path: exportDir });
|
|
113
|
+
expect(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '')).toBe('"id"\n');
|
|
114
|
+
expect(close).toHaveBeenCalledTimes(1);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it('MongoDB 游标读取异常时也会关闭游标', async () => {
|
|
118
|
+
const service = new MongoDBService();
|
|
119
|
+
vi.spyOn(service, 'getColumns').mockResolvedValue([{ name: 'id', type: 'objectId' }]);
|
|
120
|
+
const close = vi.fn(async () => undefined);
|
|
121
|
+
const cursor = { next: vi.fn(async () => { throw new Error('cursor failed'); }), close };
|
|
122
|
+
const dataSource: any = {
|
|
123
|
+
driver: {
|
|
124
|
+
queryRunner: {
|
|
125
|
+
databaseConnection: {
|
|
126
|
+
db: () => ({ collection: () => ({ find: () => ({ batchSize: () => cursor }) }) })
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
await expect(service.exportTableDataToExcel(dataSource, 'demo', 'broken', { path: exportDir }))
|
|
133
|
+
.rejects.toThrow('cursor failed');
|
|
134
|
+
expect(close).toHaveBeenCalledTimes(1);
|
|
135
|
+
});
|
|
136
|
+
});
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import {
|
|
3
|
+
startExportJob,
|
|
4
|
+
reportExportRows,
|
|
5
|
+
addExportRows,
|
|
6
|
+
finishExportJob,
|
|
7
|
+
getExportProgress,
|
|
8
|
+
linkExportJob,
|
|
9
|
+
getExportJobRoute
|
|
10
|
+
} from '../service/database/export-progress';
|
|
11
|
+
import { handleDatabaseRoutes } from '../index';
|
|
12
|
+
|
|
13
|
+
describe('导出进度注册表', () => {
|
|
14
|
+
it('按每批实际行数累计,最后一批不足 batchSize 时不虚高', () => {
|
|
15
|
+
const jobId = 'test_partial_batch';
|
|
16
|
+
startExportJob(jobId);
|
|
17
|
+
addExportRows(jobId, 10000);
|
|
18
|
+
addExportRows(jobId, 1);
|
|
19
|
+
expect(getExportProgress(jobId)?.rows).toBe(10001);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it('绝对上报取最大值,并记录完成/失败终态', () => {
|
|
23
|
+
const jobId = 'test_terminal_state';
|
|
24
|
+
startExportJob(jobId);
|
|
25
|
+
reportExportRows(jobId, 5, 'writing');
|
|
26
|
+
reportExportRows(jobId, 3, 'writing');
|
|
27
|
+
expect(getExportProgress(jobId)).toMatchObject({ rows: 5, phase: 'writing', status: 'running' });
|
|
28
|
+
|
|
29
|
+
finishExportJob(jobId, 'completed', { path: '/tmp/export.xlsx' });
|
|
30
|
+
expect(getExportProgress(jobId)).toMatchObject({ status: 'completed', phase: 'done', path: '/tmp/export.xlsx' });
|
|
31
|
+
|
|
32
|
+
const failedId = 'test_failed_state';
|
|
33
|
+
startExportJob(failedId);
|
|
34
|
+
finishExportJob(failedId, 'failed', { message: 'boom' });
|
|
35
|
+
expect(getExportProgress(failedId)).toMatchObject({ status: 'failed', phase: 'error', message: 'boom' });
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('远程代理任务可被本地检索并转发轮询', () => {
|
|
39
|
+
const jobId = 'test_proxy_route';
|
|
40
|
+
startExportJob(jobId);
|
|
41
|
+
linkExportJob(jobId, {
|
|
42
|
+
proxyConnId: 'proxy-1',
|
|
43
|
+
remoteConnId: 'remote-1',
|
|
44
|
+
remoteJobId: `proxy-1::${jobId}`
|
|
45
|
+
});
|
|
46
|
+
expect(getExportJobRoute(jobId)).toMatchObject({
|
|
47
|
+
proxyConnId: 'proxy-1',
|
|
48
|
+
remoteConnId: 'remote-1',
|
|
49
|
+
remoteJobId: `proxy-1::${jobId}`
|
|
50
|
+
});
|
|
51
|
+
expect(getExportJobRoute('missing')).toBeNull();
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('代理配置缺失时轮询回落到本地快照', async () => {
|
|
55
|
+
const jobId = 'test_proxy_fallback';
|
|
56
|
+
startExportJob(jobId);
|
|
57
|
+
reportExportRows(jobId, 7, 'scanning');
|
|
58
|
+
linkExportJob(jobId, {
|
|
59
|
+
proxyConnId: 'missing-proxy',
|
|
60
|
+
remoteConnId: 'remote-1',
|
|
61
|
+
remoteJobId: `missing-proxy::${jobId}`
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
const snapshot: any = await handleDatabaseRoutes('/api/database/getExportProgress', { jobId });
|
|
65
|
+
expect(snapshot).toMatchObject({ status: 'running', rows: 7 });
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('getExportProgress 路由返回快照', async () => {
|
|
69
|
+
const jobId = 'test_progress_route';
|
|
70
|
+
startExportJob(jobId);
|
|
71
|
+
reportExportRows(jobId, 42, 'scanning');
|
|
72
|
+
|
|
73
|
+
const running: any = await handleDatabaseRoutes('/api/database/getExportProgress', { jobId });
|
|
74
|
+
expect(running).toMatchObject({ status: 'running', rows: 42, phase: 'scanning' });
|
|
75
|
+
|
|
76
|
+
finishExportJob(jobId, 'completed', { path: '/tmp/out.csv' });
|
|
77
|
+
const done: any = await handleDatabaseRoutes('/api/database/getExportProgress', { jobId });
|
|
78
|
+
expect(done).toMatchObject({ status: 'completed', rows: 42, path: '/tmp/out.csv' });
|
|
79
|
+
});
|
|
80
|
+
});
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { getHealthCheckMode } from '../core/dialect';
|
|
3
|
+
import { DatabaseService } from '../service/database/database.service';
|
|
4
|
+
|
|
5
|
+
describe('getHealthCheckMode', () => {
|
|
6
|
+
it('对支持只读完整性检查的方言返回 integrity', () => {
|
|
7
|
+
for (const kind of ['mysql', 'sqlite', 'mssql', 'mongodb']) {
|
|
8
|
+
expect(getHealthCheckMode(kind)).toBe('integrity');
|
|
9
|
+
}
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
it('PostgreSQL 系列只做索引有效性检查', () => {
|
|
13
|
+
expect(getHealthCheckMode('postgres')).toBe('index-only');
|
|
14
|
+
expect(getHealthCheckMode('cockroachdb')).toBe('index-only');
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
it('其余方言明确降级,不谎报完整性检查', () => {
|
|
18
|
+
for (const kind of ['oracle', 'clickhouse', 'sap']) {
|
|
19
|
+
expect(getHealthCheckMode(kind)).toBe('unsupported');
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
describe('checkDatabaseHealth', () => {
|
|
25
|
+
it('MySQL CHECK TABLE 返回 error 行时判为错误,不因不抛异常误报 healthy', async () => {
|
|
26
|
+
const service = new DatabaseService() as any;
|
|
27
|
+
const ds = {
|
|
28
|
+
options: { type: 'mysql' },
|
|
29
|
+
query: vi.fn().mockResolvedValue([
|
|
30
|
+
{ Table: 'db.users', Op: 'check', Msg_type: 'error', Msg_text: 'Table is marked as crashed' }
|
|
31
|
+
])
|
|
32
|
+
};
|
|
33
|
+
service.connectionService = { getActiveConnection: vi.fn().mockResolvedValue(ds) };
|
|
34
|
+
service.getDatabaseService = () => ({
|
|
35
|
+
testConnection: vi.fn().mockResolvedValue(true),
|
|
36
|
+
getTables: vi.fn().mockResolvedValue([{ name: 'users' }]),
|
|
37
|
+
getIndexes: vi.fn().mockResolvedValue([])
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const report = await service.checkDatabaseHealth('conn', 'db');
|
|
41
|
+
const integrity = report.checks.find((check: any) => check.checkKey === 'table_integrity');
|
|
42
|
+
expect(integrity?.status).toBe('error');
|
|
43
|
+
expect(integrity?.detail?.reasonCode).toBe('MYSQL_CHECK_TABLE_ERROR');
|
|
44
|
+
expect(integrity?.detail?.reason).toContain('crashed');
|
|
45
|
+
expect(report.summary.error).toBe(1);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it('表清单失败时跳过依赖检查,不继续报 healthy', async () => {
|
|
49
|
+
const service = new DatabaseService() as any;
|
|
50
|
+
const ds = { options: { type: 'mysql' }, query: vi.fn() };
|
|
51
|
+
service.connectionService = { getActiveConnection: vi.fn().mockResolvedValue(ds) };
|
|
52
|
+
service.getDatabaseService = () => ({
|
|
53
|
+
testConnection: vi.fn().mockResolvedValue(true),
|
|
54
|
+
getTables: vi.fn().mockRejectedValue(new Error('tables unavailable')),
|
|
55
|
+
getIndexes: vi.fn()
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
const report = await service.checkDatabaseHealth('conn', 'db');
|
|
59
|
+
expect(report.checks.find((check: any) => check.checkKey === 'index_stats')).toMatchObject({
|
|
60
|
+
status: 'skipped', detail: { reasonCode: 'TABLE_LIST_UNAVAILABLE' }
|
|
61
|
+
});
|
|
62
|
+
expect(report.checks.find((check: any) => check.checkKey === 'table_integrity')).toMatchObject({
|
|
63
|
+
status: 'skipped', detail: { reasonCode: 'TABLE_LIST_UNAVAILABLE' }
|
|
64
|
+
});
|
|
65
|
+
expect(report.overallStatus).toBe('error');
|
|
66
|
+
});
|
|
67
|
+
});
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { normalizeImportRows } from '../service/database/database.service';
|
|
3
|
+
|
|
4
|
+
const columns = [
|
|
5
|
+
{ name: 'id', type: 'bigint' },
|
|
6
|
+
{ name: 'amount', type: 'decimal(30,10)' },
|
|
7
|
+
{ name: 'name', type: 'varchar(50)' },
|
|
8
|
+
{ name: 'created_at', type: 'datetime' },
|
|
9
|
+
{ name: 'active', type: 'boolean' }
|
|
10
|
+
];
|
|
11
|
+
|
|
12
|
+
describe('normalizeImportRows', () => {
|
|
13
|
+
it('大整数与高精度 decimal 字符串保留原值,避免静默丢精度', () => {
|
|
14
|
+
const [row] = normalizeImportRows([{
|
|
15
|
+
id: '9007199254740993',
|
|
16
|
+
amount: '12345678901234567890.1234567890',
|
|
17
|
+
name: 'order-1'
|
|
18
|
+
}], columns);
|
|
19
|
+
|
|
20
|
+
expect(row.id).toBe('9007199254740993');
|
|
21
|
+
expect(row.amount).toBe('12345678901234567890.1234567890');
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
it('安全范围内的数值仍转成 number', () => {
|
|
25
|
+
const [row] = normalizeImportRows([{ id: '42', amount: '12.34' }], columns);
|
|
26
|
+
expect(row.id).toBe(42);
|
|
27
|
+
expect(row.amount).toBe(12.34);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('空串只对非文本列转 null,文本列保留空串', () => {
|
|
31
|
+
const [row] = normalizeImportRows([{
|
|
32
|
+
name: '',
|
|
33
|
+
created_at: '',
|
|
34
|
+
active: '',
|
|
35
|
+
amount: ''
|
|
36
|
+
}], columns);
|
|
37
|
+
|
|
38
|
+
expect(row.name).toBe('');
|
|
39
|
+
expect(row.created_at).toBeNull();
|
|
40
|
+
expect(row.active).toBeNull();
|
|
41
|
+
expect(row.amount).toBeNull();
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('所有行按 getColumns 的列全集对齐,缺失列补 null', () => {
|
|
45
|
+
const rows = normalizeImportRows([
|
|
46
|
+
{},
|
|
47
|
+
{ name: 'first' },
|
|
48
|
+
{ id: '7', amount: '1.5' }
|
|
49
|
+
], columns);
|
|
50
|
+
const expectedKeys = columns.map((column) => column.name);
|
|
51
|
+
|
|
52
|
+
expect(rows).toHaveLength(3);
|
|
53
|
+
expect(rows.every((row) => Object.keys(row).join(',') === expectedKeys.join(','))).toBe(true);
|
|
54
|
+
expect(rows[0]).toEqual(Object.fromEntries(expectedKeys.map((key) => [key, null])));
|
|
55
|
+
expect(rows[1]).toEqual({
|
|
56
|
+
id: null,
|
|
57
|
+
amount: null,
|
|
58
|
+
name: 'first',
|
|
59
|
+
created_at: null,
|
|
60
|
+
active: null
|
|
61
|
+
});
|
|
62
|
+
expect(rows[2]).toEqual({
|
|
63
|
+
id: 7,
|
|
64
|
+
amount: 1.5,
|
|
65
|
+
name: null,
|
|
66
|
+
created_at: null,
|
|
67
|
+
active: null
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('跳过自增/identity 列,避免显式写值导致整批导入失败', () => {
|
|
72
|
+
const columnsWithIdentity = [...columns, { name: 'auto_id', type: 'bigint', isAutoIncrement: true }];
|
|
73
|
+
const [row] = normalizeImportRows([{ auto_id: '99', name: 'order-2' }], columnsWithIdentity);
|
|
74
|
+
|
|
75
|
+
expect(row).not.toHaveProperty('auto_id');
|
|
76
|
+
expect(row.id).toBeNull();
|
|
77
|
+
expect(row.name).toBe('order-2');
|
|
78
|
+
});
|
|
79
|
+
});
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { clearSlowQueries, listSlowQueries, recordQuery, redactSqlForMetrics } from '../core/query-metrics';
|
|
3
|
+
import { DatabaseService } from '../service/database/database.service';
|
|
4
|
+
|
|
5
|
+
describe('query-metrics', () => {
|
|
6
|
+
beforeEach(() => {
|
|
7
|
+
clearSlowQueries();
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
it('只返回满足最小耗时和连接条件的采样,并按耗时倒序', () => {
|
|
11
|
+
recordQuery({
|
|
12
|
+
connectionId: 'a', dialect: 'mysql', sql: 'SELECT 1', type: 'select',
|
|
13
|
+
durationMs: 100, success: true, rowCount: 1, source: 'editor'
|
|
14
|
+
});
|
|
15
|
+
recordQuery({
|
|
16
|
+
connectionId: 'b', dialect: 'mysql', sql: 'SELECT 2', type: 'select',
|
|
17
|
+
durationMs: 3000, success: true, rowCount: 1, source: 'editor'
|
|
18
|
+
});
|
|
19
|
+
recordQuery({
|
|
20
|
+
connectionId: 'a', dialect: 'mysql', sql: 'SELECT 3', type: 'select',
|
|
21
|
+
durationMs: 2500, success: true, rowCount: 1, source: 'editor'
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
const rows = listSlowQueries({ connectionId: 'a', minDurationMs: 2000 });
|
|
25
|
+
expect(rows).toHaveLength(1);
|
|
26
|
+
expect(rows[0]?.durationMs).toBe(2500);
|
|
27
|
+
expect(listSlowQueries({ minDurationMs: 2000 })).toHaveLength(2);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('按连接清空,不影响其他连接', () => {
|
|
31
|
+
recordQuery({
|
|
32
|
+
connectionId: 'a', dialect: 'sqlite', sql: 'SELECT 1', type: 'select',
|
|
33
|
+
durationMs: 1, success: true, rowCount: 1, source: 'editor'
|
|
34
|
+
});
|
|
35
|
+
recordQuery({
|
|
36
|
+
connectionId: 'b', dialect: 'sqlite', sql: 'SELECT 2', type: 'select',
|
|
37
|
+
durationMs: 1, success: true, rowCount: 1, source: 'editor'
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
expect(clearSlowQueries('a')).toBe(1);
|
|
41
|
+
expect(listSlowQueries()).toHaveLength(1);
|
|
42
|
+
expect(listSlowQueries()[0]?.connectionId).toBe('b');
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('SQL 文本被截断,避免长语句占用过多内存', () => {
|
|
46
|
+
recordQuery({
|
|
47
|
+
connectionId: 'a', dialect: 'mysql', sql: 'x'.repeat(5000), type: 'other',
|
|
48
|
+
durationMs: 1, success: true, rowCount: null, source: 'internal'
|
|
49
|
+
});
|
|
50
|
+
expect(listSlowQueries()[0]?.sql).toHaveLength(2000);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('字符串字面量和注释在采样前被脱敏', () => {
|
|
54
|
+
const redacted = redactSqlForMetrics("SELECT * FROM users WHERE name = 'alice' /* secret */");
|
|
55
|
+
expect(redacted).toContain('SELECT * FROM users WHERE name = ?');
|
|
56
|
+
expect(redacted).not.toContain('alice');
|
|
57
|
+
expect(redacted).not.toContain('secret');
|
|
58
|
+
|
|
59
|
+
recordQuery({
|
|
60
|
+
connectionId: 'a', dialect: 'mysql', sql: "SELECT * FROM users WHERE name = 'alice'", type: 'select',
|
|
61
|
+
durationMs: 5000, success: true, rowCount: 1, source: 'editor'
|
|
62
|
+
});
|
|
63
|
+
expect(listSlowQueries()[0]?.sql).not.toContain('alice');
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('limit 与 minDurationMs 被限幅,按耗时而非插入顺序排序', () => {
|
|
67
|
+
recordQuery({
|
|
68
|
+
connectionId: 'a', dialect: 'mysql', sql: 'SELECT 1', type: 'select',
|
|
69
|
+
durationMs: 10, success: true, rowCount: 1, source: 'editor'
|
|
70
|
+
});
|
|
71
|
+
recordQuery({
|
|
72
|
+
connectionId: 'a', dialect: 'mysql', sql: 'SELECT 2', type: 'select',
|
|
73
|
+
durationMs: 5000, success: true, rowCount: 1, source: 'editor'
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
expect(listSlowQueries({ limit: 9999 })).toHaveLength(2);
|
|
77
|
+
expect(listSlowQueries({ minDurationMs: -100 })).toHaveLength(2);
|
|
78
|
+
expect(listSlowQueries()[0]?.durationMs).toBe(5000);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('表数据 CRUD/DDL 经 executeQuery 时也会进入采样', async () => {
|
|
82
|
+
const service = new DatabaseService() as any;
|
|
83
|
+
service.connectionService = {
|
|
84
|
+
getActiveConnection: vi.fn(async () => ({ options: { type: 'mysql' } }))
|
|
85
|
+
};
|
|
86
|
+
service.getDatabaseService = vi.fn(() => ({ executeQuery: vi.fn(async () => []) }));
|
|
87
|
+
|
|
88
|
+
await service.executeQuery('conn-write', 'UPDATE users SET active = 1 WHERE id = 7', 'demo');
|
|
89
|
+
|
|
90
|
+
expect(listSlowQueries({ connectionId: 'conn-write' })[0]).toMatchObject({
|
|
91
|
+
type: 'write',
|
|
92
|
+
source: 'internal',
|
|
93
|
+
sql: 'UPDATE users SET active = ? WHERE id = ?'
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
});
|