fdb2 1.0.40 → 1.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +14 -4
  2. package/dist/public/.vite/manifest.json +111 -1
  3. package/dist/public/database-monitor.css +468 -0
  4. package/dist/public/database-monitor.js +725 -0
  5. package/dist/public/database.css +740 -0
  6. package/dist/public/database.js +594 -0
  7. package/dist/public/database2.js +344 -0
  8. package/dist/public/echarts.js +79307 -0
  9. package/dist/public/explorer.css +1067 -366
  10. package/dist/public/explorer.js +3893 -35071
  11. package/dist/public/export.js +54831 -0
  12. package/dist/public/helpers.js +27 -0
  13. package/dist/public/index.js +399 -38
  14. package/dist/public/layout.css +98 -65
  15. package/dist/public/layout.js +59 -22
  16. package/dist/public/modal.js +168 -0
  17. package/dist/public/query-history.css +651 -0
  18. package/dist/public/query-history.js +526 -0
  19. package/dist/public/sql-query-editor.css +503 -0
  20. package/dist/public/sql-query-editor.js +655 -0
  21. package/dist/scripts/verify-db-support.cjs +93 -7
  22. package/dist/server/__tests__/excel-export.test.ts +136 -0
  23. package/dist/server/__tests__/export-progress.test.ts +80 -0
  24. package/dist/server/__tests__/health-check.test.ts +67 -0
  25. package/dist/server/__tests__/import-normalize.test.ts +79 -0
  26. package/dist/server/__tests__/query-metrics.test.ts +96 -0
  27. package/dist/server/__tests__/remote-proxy.test.ts +76 -0
  28. package/dist/server/__tests__/sql-safety.test.ts +36 -0
  29. package/dist/server/core/dialect.d.ts +3 -0
  30. package/dist/server/core/dialect.d.ts.map +1 -1
  31. package/dist/server/core/dialect.js +17 -0
  32. package/dist/server/core/dialect.js.map +1 -1
  33. package/dist/server/core/dialect.ts +20 -0
  34. package/dist/server/core/query-metrics.d.ts +33 -0
  35. package/dist/server/core/query-metrics.d.ts.map +1 -0
  36. package/dist/server/core/query-metrics.js +117 -0
  37. package/dist/server/core/query-metrics.js.map +1 -0
  38. package/dist/server/core/query-metrics.ts +137 -0
  39. package/dist/server/core/schema/__tests__/ddl-emitter.test.ts +152 -0
  40. package/dist/server/core/schema/canonical.d.ts.map +1 -1
  41. package/dist/server/core/schema/canonical.js +4 -1
  42. package/dist/server/core/schema/canonical.js.map +1 -1
  43. package/dist/server/core/schema/canonical.ts +4 -1
  44. package/dist/server/core/schema/ddl-emitter.d.ts +3 -0
  45. package/dist/server/core/schema/ddl-emitter.d.ts.map +1 -1
  46. package/dist/server/core/schema/ddl-emitter.js +126 -12
  47. package/dist/server/core/schema/ddl-emitter.js.map +1 -1
  48. package/dist/server/core/schema/ddl-emitter.ts +137 -11
  49. package/dist/server/core/sql-safety.d.ts +9 -0
  50. package/dist/server/core/sql-safety.d.ts.map +1 -0
  51. package/dist/server/core/sql-safety.js +74 -0
  52. package/dist/server/core/sql-safety.js.map +1 -0
  53. package/dist/server/core/sql-safety.ts +72 -0
  54. package/dist/server/index.d.ts +22 -0
  55. package/dist/server/index.d.ts.map +1 -1
  56. package/dist/server/index.js +500 -33
  57. package/dist/server/index.js.map +1 -1
  58. package/dist/server/index.ts +519 -35
  59. package/dist/server/service/database/base.service.d.ts +15 -0
  60. package/dist/server/service/database/base.service.d.ts.map +1 -1
  61. package/dist/server/service/database/base.service.js +108 -0
  62. package/dist/server/service/database/base.service.js.map +1 -1
  63. package/dist/server/service/database/base.service.ts +99 -6
  64. package/dist/server/service/database/clickhouse.service.d.ts.map +1 -1
  65. package/dist/server/service/database/clickhouse.service.js +9 -35
  66. package/dist/server/service/database/clickhouse.service.js.map +1 -1
  67. package/dist/server/service/database/clickhouse.service.ts +9 -44
  68. package/dist/server/service/database/cockroachdb.service.d.ts.map +1 -1
  69. package/dist/server/service/database/cockroachdb.service.js +10 -39
  70. package/dist/server/service/database/cockroachdb.service.js.map +1 -1
  71. package/dist/server/service/database/cockroachdb.service.ts +11 -50
  72. package/dist/server/service/database/database.service.d.ts +37 -8
  73. package/dist/server/service/database/database.service.d.ts.map +1 -1
  74. package/dist/server/service/database/database.service.js +651 -54
  75. package/dist/server/service/database/database.service.js.map +1 -1
  76. package/dist/server/service/database/database.service.ts +662 -66
  77. package/dist/server/service/database/export-progress.d.ts +43 -0
  78. package/dist/server/service/database/export-progress.d.ts.map +1 -0
  79. package/dist/server/service/database/export-progress.js +117 -0
  80. package/dist/server/service/database/export-progress.js.map +1 -0
  81. package/dist/server/service/database/export-progress.ts +125 -0
  82. package/dist/server/service/database/mongodb.service.d.ts +3 -1
  83. package/dist/server/service/database/mongodb.service.d.ts.map +1 -1
  84. package/dist/server/service/database/mongodb.service.js +97 -49
  85. package/dist/server/service/database/mongodb.service.js.map +1 -1
  86. package/dist/server/service/database/mongodb.service.ts +94 -48
  87. package/dist/server/service/database/mssql.service.d.ts.map +1 -1
  88. package/dist/server/service/database/mssql.service.js +14 -13
  89. package/dist/server/service/database/mssql.service.js.map +1 -1
  90. package/dist/server/service/database/mssql.service.ts +14 -13
  91. package/dist/server/service/database/mysql.service.js +10 -10
  92. package/dist/server/service/database/mysql.service.js.map +1 -1
  93. package/dist/server/service/database/mysql.service.ts +10 -10
  94. package/dist/server/service/database/oracle.service.d.ts +9 -1
  95. package/dist/server/service/database/oracle.service.d.ts.map +1 -1
  96. package/dist/server/service/database/oracle.service.js +55 -47
  97. package/dist/server/service/database/oracle.service.js.map +1 -1
  98. package/dist/server/service/database/oracle.service.ts +57 -57
  99. package/dist/server/service/database/postgres.service.d.ts.map +1 -1
  100. package/dist/server/service/database/postgres.service.js +10 -9
  101. package/dist/server/service/database/postgres.service.js.map +1 -1
  102. package/dist/server/service/database/postgres.service.ts +10 -9
  103. package/dist/server/service/database/sap.service.d.ts +8 -0
  104. package/dist/server/service/database/sap.service.d.ts.map +1 -1
  105. package/dist/server/service/database/sap.service.js +37 -38
  106. package/dist/server/service/database/sap.service.js.map +1 -1
  107. package/dist/server/service/database/sap.service.ts +39 -49
  108. package/dist/server/service/database/sqlite.service.d.ts.map +1 -1
  109. package/dist/server/service/database/sqlite.service.js +15 -11
  110. package/dist/server/service/database/sqlite.service.js.map +1 -1
  111. package/dist/server/service/database/sqlite.service.ts +15 -11
  112. package/package.json +1 -1
  113. package/public/fdb2.png +0 -0
  114. package/scripts/verify-db-support.cjs +93 -7
  115. package/server.js +15 -2
@@ -1,8 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DatabaseService = void 0;
4
+ exports.normalizeImportRows = normalizeImportRows;
5
+ exports.normalizeSyncRowForRelational = normalizeSyncRowForRelational;
6
+ exports.normalizeSyncRowsForRelational = normalizeSyncRowsForRelational;
4
7
  const connection_service_1 = require("../connection.service");
5
8
  const dialect_1 = require("../../core/dialect");
9
+ const query_builder_1 = require("../../core/query-builder");
10
+ const sql_safety_1 = require("../../core/sql-safety");
11
+ const query_metrics_1 = require("../../core/query-metrics");
6
12
  const canonical_1 = require("../../core/schema/canonical");
7
13
  const diff_1 = require("../../core/schema/diff");
8
14
  const ddl_emitter_1 = require("../../core/schema/ddl-emitter");
@@ -15,6 +21,138 @@ const cockroachdb_service_1 = require("./cockroachdb.service");
15
21
  const mongodb_service_1 = require("./mongodb.service");
16
22
  const sap_service_1 = require("./sap.service");
17
23
  const clickhouse_service_1 = require("./clickhouse.service");
24
+ const IMPORT_TEXT_TYPE_RE = /\b(?:character|varchar|nvarchar|char|nchar|text|ntext|clob|longtext|mediumtext|tinytext)\b/i;
25
+ const IMPORT_NUMERIC_TYPE_RE = /\b(?:integer|int|bigint|smallint|tinyint|mediumint|decimal|numeric|dec|fixed|float|double|real|money|number)\b/i;
26
+ const IMPORT_BOOL_TYPE_RE = /\b(?:bool|boolean)\b/i;
27
+ const IMPORT_NUMERIC_STRING_RE = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/;
28
+ function importSignificantDigits(raw) {
29
+ return raw.replace(/^[+-]/, '').replace('.', '').replace(/^0+/, '').replace(/0+$/, '').length;
30
+ }
31
+ function coerceImportValue(value, columnType) {
32
+ if (value === null || value === undefined)
33
+ return null;
34
+ const type = String(columnType || '').toLowerCase();
35
+ const isText = IMPORT_TEXT_TYPE_RE.test(type);
36
+ // 空串只对非文本列表示缺失;文本列必须保留用户显式输入的 ''。
37
+ if (value === '')
38
+ return isText ? '' : null;
39
+ if (isText)
40
+ return value;
41
+ if (IMPORT_BOOL_TYPE_RE.test(type)) {
42
+ if (value === true || value === 1)
43
+ return true;
44
+ if (value === false || value === 0)
45
+ return false;
46
+ if (typeof value === 'string') {
47
+ const normalized = value.trim().toLowerCase();
48
+ if (normalized === 'true' || normalized === '1')
49
+ return true;
50
+ if (normalized === 'false' || normalized === '0')
51
+ return false;
52
+ }
53
+ return value;
54
+ }
55
+ if (IMPORT_NUMERIC_TYPE_RE.test(type) && typeof value === 'string') {
56
+ const raw = value.trim();
57
+ if (!IMPORT_NUMERIC_STRING_RE.test(raw))
58
+ return value;
59
+ const number = Number(raw);
60
+ if (Number.isNaN(number))
61
+ return value;
62
+ // 大整数超出安全范围、高精度小数有效位超过 15 位时保留原字符串,避免 Number() 静默丢精度。
63
+ if (Number.isInteger(number) ? !Number.isSafeInteger(number) : importSignificantDigits(raw) > 15) {
64
+ return value;
65
+ }
66
+ return number;
67
+ }
68
+ if (typeof value === 'string') {
69
+ if (value === 'true')
70
+ return true;
71
+ if (value === 'false')
72
+ return false;
73
+ }
74
+ return value;
75
+ }
76
+ /** 纯函数:把导入行按 getColumns 的列全集归一化,供测试与 importData 共用。 */
77
+ function normalizeImportRows(rows, columns) {
78
+ if (!Array.isArray(rows))
79
+ return [];
80
+ const definitions = (Array.isArray(columns) ? columns : [])
81
+ .map((column) => ({
82
+ name: String(column?.name ?? '').trim(),
83
+ type: String(column?.type ?? ''),
84
+ isAutoIncrement: !!column?.isAutoIncrement
85
+ }))
86
+ // 自增/identity 列不能显式写值,否则 PG/CRDB/MSSQL/Oracle 会直接拒绝整批导入。
87
+ .filter((column) => column.name && !column.isAutoIncrement);
88
+ const names = definitions.map((column) => column.name);
89
+ const types = new Map(definitions.map((column) => [column.name, column.type]));
90
+ const normalized = [];
91
+ for (const row of rows) {
92
+ const out = {};
93
+ for (const name of names)
94
+ out[name] = null;
95
+ if (!row || typeof row !== 'object') {
96
+ normalized.push(out);
97
+ continue;
98
+ }
99
+ for (const key of Object.keys(row)) {
100
+ const name = key.trim();
101
+ if (!types.has(name))
102
+ continue;
103
+ out[name] = coerceImportValue(row[key], types.get(name) || '');
104
+ }
105
+ normalized.push(out);
106
+ }
107
+ return normalized;
108
+ }
109
+ /** 同步到关系库时,把文档库里的 BSON/嵌套值转成驱动可绑定的标量。 */
110
+ function normalizeSyncRowForRelational(row) {
111
+ const out = {};
112
+ if (!row || typeof row !== 'object' || Array.isArray(row))
113
+ return out;
114
+ for (const [key, value] of Object.entries(row)) {
115
+ if (value === null || value === undefined) {
116
+ out[key] = null;
117
+ }
118
+ else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
119
+ out[key] = value;
120
+ }
121
+ else if (Buffer.isBuffer(value) || value instanceof Date) {
122
+ out[key] = value;
123
+ }
124
+ else if (typeof value.toHexString === 'function' || value._bsontype === 'ObjectId') {
125
+ out[key] = String(value);
126
+ }
127
+ else if (typeof value === 'object') {
128
+ out[key] = JSON.stringify(value);
129
+ }
130
+ else {
131
+ out[key] = String(value);
132
+ }
133
+ }
134
+ return out;
135
+ }
136
+ /** 同一批次按字段并集补齐,避免 bulkInsert 只取首行字段导致后续文档字段丢失。 */
137
+ function normalizeSyncRowsForRelational(rows) {
138
+ const normalized = (Array.isArray(rows) ? rows : []).map(normalizeSyncRowForRelational);
139
+ const keys = [];
140
+ const seen = new Set();
141
+ for (const row of normalized) {
142
+ for (const key of Object.keys(row)) {
143
+ if (!seen.has(key)) {
144
+ seen.add(key);
145
+ keys.push(key);
146
+ }
147
+ }
148
+ }
149
+ return normalized.map((row) => {
150
+ const out = {};
151
+ for (const key of keys)
152
+ out[key] = Object.prototype.hasOwnProperty.call(row, key) ? row[key] : null;
153
+ return out;
154
+ });
155
+ }
18
156
  /**
19
157
  * 数据库服务管理类
20
158
  * 负责根据数据库类型选择相应的服务实现
@@ -124,12 +262,43 @@ class DatabaseService {
124
262
  return databaseService.getTableData(dataSource, databaseName, tableName, page, pageSize, where, orderBy);
125
263
  }
126
264
  /**
127
- * 执行SQL查询
265
+ * 执行SQL查询。source='editor' 的查询会进入进程内慢查询采样,不写磁盘。
128
266
  */
129
- async executeQuery(connectionId, sql, databaseName) {
130
- const dataSource = await this.connectionService.getActiveConnection(connectionId, databaseName);
131
- const databaseService = this.getDatabaseService(dataSource.options.type);
132
- return databaseService.executeQuery(dataSource, sql);
267
+ async executeQuery(connectionId, sql, databaseName, source = 'internal') {
268
+ const startedAt = Date.now();
269
+ let dialect = 'unknown';
270
+ let rowCount = null;
271
+ let success = false;
272
+ let errorMessage;
273
+ try {
274
+ const dataSource = await this.connectionService.getActiveConnection(connectionId, databaseName);
275
+ dialect = String(dataSource.options.type || '');
276
+ const databaseService = this.getDatabaseService(dialect);
277
+ const result = await databaseService.executeQuery(dataSource, sql);
278
+ rowCount = Array.isArray(result) ? result.length : null;
279
+ success = true;
280
+ return result;
281
+ }
282
+ catch (error) {
283
+ errorMessage = error?.message ? String(error.message).split('\n')[0] : String(error);
284
+ throw error;
285
+ }
286
+ finally {
287
+ // 所有经 executeQuery 的语句都参与采样:编辑器查询与表数据 CRUD/DDL 都可能成为慢查询。
288
+ const kind = (0, query_builder_1.classifySql)(sql).kind;
289
+ (0, query_metrics_1.recordQuery)({
290
+ connectionId,
291
+ database: databaseName,
292
+ dialect,
293
+ sql,
294
+ type: kind === 'select' || kind === 'write' || kind === 'ddl' ? kind : 'other',
295
+ durationMs: Date.now() - startedAt,
296
+ success,
297
+ rowCount,
298
+ errorMessage,
299
+ source
300
+ });
301
+ }
133
302
  }
134
303
  // ---- 表列表缓存 ----
135
304
  // 预览在用户每次输入后(防抖)都会触发,全量 getTables 对大库是重操作;
@@ -309,21 +478,31 @@ class DatabaseService {
309
478
  if (changeSet.primaryKey && !caps.alterPrimaryKey) {
310
479
  error = `该数据库类型(${kind})不支持修改主键`;
311
480
  }
312
- // SQL Server:删除现有主键必须知道真实的约束名(PK__<table>__<hash>),回查系统表获取。
481
+ // SQL Server / SAP HANA:删除现有主键必须知道真实的约束名,回查系统表获取。
313
482
  // 仅在「已有主键需要 DROP」时才必需;纯新增主键的约束名由我们自己指定。
483
+ const needsPkDrop = !!changeSet.primaryKey && changeSet.primaryKey.from.length > 0;
314
484
  let mssqlPkConstraintName;
315
- if (!error && kind === 'mssql' && changeSet.primaryKey && changeSet.primaryKey.from.length > 0) {
485
+ let sapPkConstraintName;
486
+ if (!error && needsPkDrop && (kind === 'mssql' || kind === 'sap')) {
316
487
  const svc = dbService;
317
488
  if (typeof svc.getPrimaryKeyConstraintName === 'function') {
318
- mssqlPkConstraintName = (await svc.getPrimaryKeyConstraintName(dataSource, databaseName, tableName)) || undefined;
489
+ const constraintName = (await svc.getPrimaryKeyConstraintName(dataSource, databaseName, tableName)) || undefined;
490
+ if (kind === 'mssql')
491
+ mssqlPkConstraintName = constraintName;
492
+ else
493
+ sapPkConstraintName = constraintName;
319
494
  }
320
- if (!mssqlPkConstraintName) {
495
+ if (kind === 'mssql' ? !mssqlPkConstraintName : !sapPkConstraintName) {
321
496
  error = '无法定位该表的主键约束名,无法修改主键';
322
497
  }
323
498
  }
324
- const statements = error
325
- ? []
326
- : (0, ddl_emitter_1.emitAlterDdl)(kind, original, desired, mssqlPkConstraintName ? { mssqlPkConstraintName } : undefined);
499
+ const alterDdlOptions = mssqlPkConstraintName || sapPkConstraintName
500
+ ? {
501
+ ...(mssqlPkConstraintName ? { mssqlPkConstraintName } : {}),
502
+ ...(sapPkConstraintName ? { sapPkConstraintName } : {})
503
+ }
504
+ : undefined;
505
+ const statements = error ? [] : (0, ddl_emitter_1.emitAlterDdl)(kind, original, desired, alterDdlOptions);
327
506
  return {
328
507
  dataSource,
329
508
  kind,
@@ -461,28 +640,31 @@ class DatabaseService {
461
640
  tableSyncResult.messages.push(`开始同步表数据: ${sourceTableName} -> ${target.tableName}`);
462
641
  // 获取源表数据(分批获取,避免内存问题)
463
642
  const batchSize = 1000;
464
- let offset = 0;
643
+ let page = 1;
465
644
  let totalRows = 0;
466
645
  while (true) {
467
- const sourceData = await sourceService.query(sourceDataSource, {
468
- sql: `SELECT * FROM ${sourceService.quoteIdentifier(sourceTableName)} LIMIT ? OFFSET ?`,
469
- params: [batchSize, offset]
470
- });
646
+ // 统一走 getTableData 而不是自己拼 LIMIT/OFFSET:
647
+ // 各方言分页语法不同(MSSQL/Oracle 用 OFFSET/FETCH,MongoDB 根本没有 SQL),
648
+ // 这里复用各服务已实现的分页读取,避免同步功能只对 MySQL/SQLite 可用。
649
+ const sourceData = (await sourceService.getTableData(sourceDataSource, source.database, sourceTableName, page, batchSize)).data;
471
650
  if (sourceData.length === 0) {
472
651
  break;
473
652
  }
474
- // 插入数据到目标表
653
+ // 插入数据到目标表;文档库的 ObjectId/嵌套对象不能直接绑定给关系库驱动。
654
+ const rowsForTarget = targetService.getDatabaseType() === 'mongodb'
655
+ ? sourceData
656
+ : normalizeSyncRowsForRelational(sourceData);
475
657
  if (options.bulkInsert) {
476
- await targetService.bulkInsert(targetDataSource, targetDatabaseName, target.tableName, sourceData, options.overrideExisting);
658
+ await targetService.bulkInsert(targetDataSource, targetDatabaseName, target.tableName, rowsForTarget, options.overrideExisting);
477
659
  }
478
660
  else {
479
- for (const row of sourceData) {
661
+ for (const row of rowsForTarget) {
480
662
  await targetService.insertData(targetDataSource, targetDatabaseName, target.tableName, row, options.overrideExisting);
481
663
  }
482
664
  }
483
665
  totalRows += sourceData.length;
484
666
  tableSyncResult.messages.push(`已同步 ${totalRows} 行数据`);
485
- offset += batchSize;
667
+ page += 1;
486
668
  }
487
669
  tableSyncResult.dataSynced = true;
488
670
  tableSyncResult.rowsSynced = totalRows;
@@ -667,7 +849,8 @@ class DatabaseService {
667
849
  label: 'MongoDB',
668
850
  icon: 'bi-database',
669
851
  defaultPort: 27017,
670
- description: 'MongoDB文档数据库',
852
+ description: 'MongoDB文档数据库(实验性)',
853
+ experimental: true,
671
854
  features: {
672
855
  supportSchemas: false,
673
856
  supportProcedures: false,
@@ -782,7 +965,10 @@ class DatabaseService {
782
965
  async backupDatabase(connectionId, databaseName, options) {
783
966
  const dataSource = await this.connectionService.getActiveConnection(connectionId, databaseName);
784
967
  const databaseService = this.getDatabaseService(dataSource.options.type);
785
- return databaseService.backupDatabase(dataSource, databaseName, options);
968
+ const result = await databaseService.backupDatabase(dataSource, databaseName, options);
969
+ const scheduleId = options?.scheduleId;
970
+ // 让定时任务的 scheduleId 在返回提示中可见,便于定位是哪条计划产生的备份。
971
+ return scheduleId ? `${result}[schedule:${scheduleId}]` : result;
786
972
  }
787
973
  /**
788
974
  * 恢复数据库
@@ -812,61 +998,472 @@ class DatabaseService {
812
998
  };
813
999
  }
814
1000
  /**
815
- * 优化数据库
1001
+ * 维护操作(OPTIMIZE / ANALYZE / REPAIR)的方言适配。
1002
+ *
1003
+ * 原先三个方法对所有连接都拼 MySQL 语法,PostgreSQL/SQLite/MongoDB 等
1004
+ * 必然报错;CLI 侧早已明确拒绝非 MySQL。这里按方言给出等价语句或清晰
1005
+ * 的「不支持」结果,而不是让驱动抛原始 SQL 错误。
816
1006
  */
817
- async optimizeDatabase(connectionId, databaseName) {
1007
+ async runMaintenance(connectionId, databaseName, action) {
818
1008
  const dataSource = await this.connectionService.getActiveConnection(connectionId, databaseName);
819
- const databaseService = this.getDatabaseService(dataSource.options.type);
1009
+ const type = String(dataSource.options.type || '');
1010
+ const info = (0, dialect_1.getDialectInfo)(type);
1011
+ const databaseService = this.getDatabaseService(type);
820
1012
  const tables = await databaseService.getTables(dataSource, databaseName);
1013
+ const q = (name) => (0, dialect_1.quoteIdentifier)(type, name);
1014
+ const unsupported = (table) => ({
1015
+ table,
1016
+ success: false,
1017
+ error: `${action} 暂不支持 ${info.label}(仅 MySQL / PostgreSQL / SQLite 提供等价操作)`
1018
+ });
1019
+ // SQLite 的 VACUUM / integrity_check 作用于整库,不能按表重复执行
1020
+ if (info.kind === 'sqlite' && action !== 'analyze') {
1021
+ const sql = action === 'optimize' ? 'VACUUM' : 'PRAGMA integrity_check';
1022
+ try {
1023
+ const result = await dataSource.query(sql);
1024
+ return { results: [{ table: '*', success: true, sql, result }], dialect: info.kind };
1025
+ }
1026
+ catch (e) {
1027
+ return { results: [{ table: '*', success: false, sql, error: e?.message || String(e) }], dialect: info.kind };
1028
+ }
1029
+ }
1030
+ const statementFor = (table) => {
1031
+ switch (info.kind) {
1032
+ case 'mysql':
1033
+ return `${action.toUpperCase()} TABLE ${q(table)}`;
1034
+ case 'postgres':
1035
+ case 'cockroachdb':
1036
+ if (action === 'analyze')
1037
+ return `ANALYZE ${q(table)}`;
1038
+ if (action === 'optimize')
1039
+ return `VACUUM ANALYZE ${q(table)}`;
1040
+ return null;
1041
+ case 'sqlite':
1042
+ return action === 'analyze' ? `ANALYZE ${q(table)}` : null;
1043
+ default:
1044
+ return null;
1045
+ }
1046
+ };
821
1047
  const results = [];
822
1048
  for (const table of tables) {
1049
+ const sql = statementFor(table.name);
1050
+ if (!sql) {
1051
+ results.push(unsupported(table.name));
1052
+ continue;
1053
+ }
823
1054
  try {
824
- const result = await dataSource.query(`OPTIMIZE TABLE \`${table.name}\``);
825
- results.push({ table: table.name, success: true, result });
1055
+ const result = await dataSource.query(sql);
1056
+ results.push({ table: table.name, success: true, sql, result });
826
1057
  }
827
- catch (error) {
828
- results.push({ table: table.name, success: false, error: error.message });
1058
+ catch (e) {
1059
+ results.push({ table: table.name, success: false, sql, error: e?.message || String(e) });
829
1060
  }
830
1061
  }
831
- return { results };
1062
+ return { results, dialect: info.kind };
832
1063
  }
833
1064
  /**
834
- * 分析表
1065
+ * 批量导入:文件解析在浏览器完成,这里接收行数组并走各方言 bulkInsert。
1066
+ * 按表结构过滤未知列并做轻量类型转换(CSV 里一切都是字符串)。
835
1067
  */
1068
+ async importData(connectionId, databaseName, tableName, rows) {
1069
+ if (!Array.isArray(rows))
1070
+ throw new Error('rows must be an array');
1071
+ const dataSource = await this.connectionService.getActiveConnection(connectionId, databaseName);
1072
+ const type = String(dataSource.options.type || '');
1073
+ const service = this.getDatabaseService(type);
1074
+ // MongoDB 是 schemaless:空集合 getColumns 返回空,不能按列归一化把全部文档过滤掉。
1075
+ if (type === 'mongodb') {
1076
+ const docs = rows.filter((row) => row && typeof row === 'object' && !Array.isArray(row));
1077
+ if (docs.length === 0)
1078
+ return { imported: 0, table: tableName };
1079
+ await service.bulkInsert(dataSource, databaseName, tableName, docs);
1080
+ return { imported: docs.length, table: tableName };
1081
+ }
1082
+ const columns = await service.getColumns(dataSource, databaseName, tableName);
1083
+ const knownNames = new Set((Array.isArray(columns) ? columns : [])
1084
+ .map((column) => String(column?.name ?? '').trim())
1085
+ .filter(Boolean));
1086
+ // 纯函数保留所有输入行的列全集;导入时仍需跳过完全不含已知列的空行。
1087
+ const clean = normalizeImportRows(rows, columns).filter((_, index) => {
1088
+ const row = rows[index];
1089
+ return !!row && typeof row === 'object' &&
1090
+ Object.keys(row).some((key) => knownNames.has(key.trim()));
1091
+ });
1092
+ if (clean.length === 0)
1093
+ return { imported: 0, table: tableName };
1094
+ await service.bulkInsert(dataSource, databaseName, tableName, clean);
1095
+ return { imported: clean.length, table: tableName };
1096
+ }
1097
+ /** 优化数据库 */
1098
+ async optimizeDatabase(connectionId, databaseName) {
1099
+ return this.runMaintenance(connectionId, databaseName, 'optimize');
1100
+ }
1101
+ /** 分析表 */
836
1102
  async analyzeTables(connectionId, databaseName) {
1103
+ return this.runMaintenance(connectionId, databaseName, 'analyze');
1104
+ }
1105
+ /** 修复表 */
1106
+ async repairTables(connectionId, databaseName) {
1107
+ return this.runMaintenance(connectionId, databaseName, 'repair');
1108
+ }
1109
+ /**
1110
+ * 只读健康检查:能执行完整性检查的方言执行真实检查,其余明确降级为索引有效性或 unsupported。
1111
+ * 不调用任何 repair/optimize 操作,避免把健康检查变成写操作。
1112
+ */
1113
+ async checkDatabaseHealth(connectionId, databaseName) {
1114
+ const startedAt = Date.now();
837
1115
  const dataSource = await this.connectionService.getActiveConnection(connectionId, databaseName);
838
- const databaseService = this.getDatabaseService(dataSource.options.type);
839
- const tables = await databaseService.getTables(dataSource, databaseName);
840
- const results = [];
841
- for (const table of tables) {
1116
+ const type = String(dataSource.options.type || '');
1117
+ const info = (0, dialect_1.getDialectInfo)(type);
1118
+ const service = this.getDatabaseService(type);
1119
+ const mode = (0, dialect_1.getHealthCheckMode)(info.kind);
1120
+ const checks = [];
1121
+ const maxTables = 50;
1122
+ const reasonOf = (error) => {
1123
+ const message = error?.message ? String(error.message) : String(error);
1124
+ return message.split('\n')[0] ?? '';
1125
+ };
1126
+ const push = (checkKey, status, detail, target) => {
1127
+ checks.push({
1128
+ checkKey,
1129
+ status,
1130
+ ...(target ? { target } : {}),
1131
+ ...(detail ? { detail } : {}),
1132
+ durationMs: Date.now() - startedAt
1133
+ });
1134
+ };
1135
+ try {
1136
+ const connected = info.kind === 'mongodb'
1137
+ ? Array.isArray(await service.getDatabases(dataSource))
1138
+ : await service.testConnection(dataSource);
1139
+ if (!connected)
1140
+ throw new Error('连通性检查失败');
1141
+ push('connectivity', 'healthy');
1142
+ }
1143
+ catch (error) {
1144
+ push('connectivity', 'error', { reasonCode: 'CONNECTIVITY_FAILED', reason: reasonOf(error) });
1145
+ }
1146
+ let tables = [];
1147
+ let inventoryOk = false;
1148
+ try {
1149
+ tables = (await service.getTables(dataSource, databaseName)) || [];
1150
+ inventoryOk = true;
1151
+ push('table_inventory', 'healthy', { tableCount: tables.length });
1152
+ }
1153
+ catch (error) {
1154
+ push('table_inventory', 'error', { reasonCode: 'TABLE_LIST_UNAVAILABLE', reason: reasonOf(error) });
1155
+ }
1156
+ const visibleTables = tables.slice(0, maxTables);
1157
+ if (!inventoryOk) {
1158
+ push('index_stats', 'skipped', { reasonCode: 'TABLE_LIST_UNAVAILABLE', reason: '表清单不可用,跳过索引统计' });
1159
+ }
1160
+ else {
842
1161
  try {
843
- const result = await dataSource.query(`ANALYZE TABLE \`${table.name}\``);
844
- results.push({ table: table.name, success: true, result });
1162
+ let indexCount = 0;
1163
+ for (const table of visibleTables) {
1164
+ const indexes = await service.getIndexes(dataSource, databaseName, table.name);
1165
+ indexCount += Array.isArray(indexes) ? indexes.length : 0;
1166
+ }
1167
+ push('index_stats', 'healthy', {
1168
+ tableCount: visibleTables.length,
1169
+ totalTableCount: tables.length,
1170
+ indexCount,
1171
+ partial: tables.length > maxTables
1172
+ });
845
1173
  }
846
1174
  catch (error) {
847
- results.push({ table: table.name, success: false, error: error.message });
1175
+ push('index_stats', 'error', { reason: reasonOf(error) });
1176
+ }
1177
+ }
1178
+ if (!inventoryOk) {
1179
+ push(mode === 'index-only' ? 'index_validity' : 'table_integrity', 'skipped', { reasonCode: 'TABLE_LIST_UNAVAILABLE', reason: '表清单不可用,跳过明细检查' });
1180
+ }
1181
+ else if (mode === 'integrity') {
1182
+ switch (info.kind) {
1183
+ case 'sqlite': {
1184
+ try {
1185
+ const result = await dataSource.query('PRAGMA integrity_check');
1186
+ const first = Array.isArray(result) && result.length ? result[0] : undefined;
1187
+ const value = first ? (first.integrity_check ?? Object.values(first)[0]) : undefined;
1188
+ const ok = String(value ?? '').toLowerCase() === 'ok';
1189
+ push('table_integrity', ok ? 'healthy' : 'error', {
1190
+ ...(ok ? {} : { raw: result, reasonCode: 'SQLITE_INTEGRITY_CHECK_FAILED', reason: 'integrity_check 未返回 ok' })
1191
+ }, '*');
1192
+ }
1193
+ catch (error) {
1194
+ push('table_integrity', 'error', { reason: reasonOf(error) }, '*');
1195
+ }
1196
+ break;
1197
+ }
1198
+ case 'mysql':
1199
+ for (const table of visibleTables) {
1200
+ const sql = `CHECK TABLE ${(0, dialect_1.quoteIdentifier)(type, String(table.name))}`;
1201
+ try {
1202
+ const result = await dataSource.query(sql);
1203
+ const rows = Array.isArray(result) ? result : result ? [result] : [];
1204
+ const failures = rows.filter((row) => /error/i.test(String(row?.Msg_type ?? '')) || /error/i.test(String(row?.Msg_text ?? '')));
1205
+ if (failures.length > 0) {
1206
+ push('table_integrity', 'error', {
1207
+ sql,
1208
+ raw: failures,
1209
+ reasonCode: 'MYSQL_CHECK_TABLE_ERROR',
1210
+ reason: String(failures[0]?.Msg_text || 'CHECK TABLE 返回错误')
1211
+ }, String(table.name));
1212
+ }
1213
+ else {
1214
+ push('table_integrity', 'healthy', { raw: result }, String(table.name));
1215
+ }
1216
+ }
1217
+ catch (error) {
1218
+ push('table_integrity', 'error', { sql, reason: reasonOf(error) }, String(table.name));
1219
+ }
1220
+ }
1221
+ break;
1222
+ case 'mssql':
1223
+ for (const table of visibleTables) {
1224
+ const name = String(table.name).replace(/'/g, "''");
1225
+ const sql = `DBCC CHECKTABLE('${name}') WITH NO_INFOMSGS`;
1226
+ try {
1227
+ const result = await dataSource.query(sql);
1228
+ push('table_integrity', 'healthy', { raw: result }, String(table.name));
1229
+ }
1230
+ catch (error) {
1231
+ push('table_integrity', 'error', { sql, reason: reasonOf(error) }, String(table.name));
1232
+ }
1233
+ }
1234
+ break;
1235
+ case 'mongodb':
1236
+ for (const table of visibleTables) {
1237
+ try {
1238
+ const nativeDb = dataSource.driver?.queryRunner?.databaseConnection?.db?.(databaseName);
1239
+ if (!nativeDb)
1240
+ throw new Error('无法获取 MongoDB 原生数据库句柄');
1241
+ const result = await nativeDb.collection(String(table.name)).validate();
1242
+ const ok = result?.valid !== false && result?.ok !== 0;
1243
+ push('table_integrity', ok ? 'healthy' : 'error', ok ? undefined : { raw: result }, String(table.name));
1244
+ }
1245
+ catch (error) {
1246
+ push('table_integrity', 'error', { reason: reasonOf(error) }, String(table.name));
1247
+ }
1248
+ }
1249
+ break;
1250
+ }
1251
+ }
1252
+ else if (mode === 'index-only') {
1253
+ if (info.kind === 'cockroachdb') {
1254
+ push('unsupported', 'unsupported', {
1255
+ reasonCode: 'COCKROACH_INDEX_VALIDITY_UNSUPPORTED',
1256
+ reason: 'CockroachDB 未提供等价的只读索引有效性检查'
1257
+ });
1258
+ }
1259
+ else {
1260
+ try {
1261
+ const rows = await dataSource.query(`
1262
+ SELECT COUNT(*) AS invalid_indexes
1263
+ FROM pg_index i
1264
+ JOIN pg_class c ON c.oid = i.indrelid
1265
+ JOIN pg_namespace n ON n.oid = c.relnamespace
1266
+ WHERE NOT i.indisvalid
1267
+ AND n.nspname NOT IN ('pg_catalog', 'information_schema')
1268
+ AND c.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = current_schema())
1269
+ `);
1270
+ const first = Array.isArray(rows) && rows.length ? rows[0] : {};
1271
+ const invalid = Number(first.invalid_indexes ?? first.count ?? 0);
1272
+ push('index_validity', invalid === 0 ? 'healthy' : 'error', { invalidIndexes: invalid });
1273
+ }
1274
+ catch (error) {
1275
+ push('index_validity', 'error', { reason: reasonOf(error) });
1276
+ }
848
1277
  }
849
1278
  }
850
- return { results };
1279
+ else {
1280
+ const reasonCode = info.kind === 'clickhouse'
1281
+ ? 'CLICKHOUSE_INTEGRITY_UNSUPPORTED'
1282
+ : info.kind === 'oracle'
1283
+ ? 'ORACLE_INTEGRITY_UNSUPPORTED'
1284
+ : 'INTEGRITY_UNSUPPORTED';
1285
+ const reason = info.kind === 'clickhouse'
1286
+ ? 'ClickHouse 的 CHECK TABLE 不能经当前 SQL 通道执行,暂不提供只读完整性检查'
1287
+ : info.kind === 'oracle'
1288
+ ? 'Oracle 结构校验需要额外权限且开销较大,健康检查暂不执行'
1289
+ : '当前数据库类型没有可用的只读完整性检查';
1290
+ push('unsupported', 'unsupported', { reasonCode, reason });
1291
+ }
1292
+ const summary = {
1293
+ healthy: checks.filter((check) => check.status === 'healthy').length,
1294
+ error: checks.filter((check) => check.status === 'error').length,
1295
+ unsupported: checks.filter((check) => check.status === 'unsupported').length,
1296
+ skipped: checks.filter((check) => check.status === 'skipped').length
1297
+ };
1298
+ const overallStatus = summary.error > 0
1299
+ ? 'error'
1300
+ : summary.unsupported > 0 ? 'unsupported'
1301
+ : summary.skipped > 0 ? 'skipped' : 'healthy';
1302
+ return {
1303
+ dialect: info.kind,
1304
+ mode,
1305
+ integritySupported: mode === 'integrity',
1306
+ checks,
1307
+ summary,
1308
+ overallStatus,
1309
+ truncated: tables.length > maxTables,
1310
+ checkedAt: new Date().toISOString(),
1311
+ durationMs: Date.now() - startedAt
1312
+ };
851
1313
  }
852
- /**
853
- * 修复表
854
- */
855
- async repairTables(connectionId, databaseName) {
1314
+ /** 本进程采集的慢查询(按耗时倒序) */
1315
+ getSlowQueries(connectionId, minDurationMs, limit) {
1316
+ if (!connectionId)
1317
+ throw new Error('Missing connection id');
1318
+ return (0, query_metrics_1.listSlowQueries)({ connectionId, minDurationMs, limit });
1319
+ }
1320
+ clearSlowQueries(connectionId) {
1321
+ if (!connectionId)
1322
+ throw new Error('Missing connection id');
1323
+ return (0, query_metrics_1.clearSlowQueries)(connectionId);
1324
+ }
1325
+ /** 只读 EXPLAIN:拒绝写语句和多语句,避免 EXPLAIN ANALYZE 造成副作用 */
1326
+ async explainQuery(connectionId, sql, databaseName) {
1327
+ if (!(0, sql_safety_1.isSafeReadOnlySql)(sql)) {
1328
+ return {
1329
+ supported: false,
1330
+ reasonCode: 'EXPLAIN_UNSAFE_SQL',
1331
+ reason: '只能分析单条无副作用的 SELECT/WITH/SHOW/EXPLAIN 语句'
1332
+ };
1333
+ }
856
1334
  const dataSource = await this.connectionService.getActiveConnection(connectionId, databaseName);
857
- const databaseService = this.getDatabaseService(dataSource.options.type);
858
- const tables = await databaseService.getTables(dataSource, databaseName);
859
- const results = [];
860
- for (const table of tables) {
861
- try {
862
- const result = await dataSource.query(`REPAIR TABLE \`${table.name}\``);
863
- results.push({ table: table.name, success: true, result });
1335
+ const type = String(dataSource.options.type || '');
1336
+ const info = (0, dialect_1.getDialectInfo)(type);
1337
+ const statement = String(sql).trim();
1338
+ const base = { dialect: info.kind, sql: statement };
1339
+ if (info.kind === 'mongodb') {
1340
+ return {
1341
+ ...base,
1342
+ supported: false,
1343
+ reasonCode: 'EXPLAIN_MONGODB_UNSUPPORTED',
1344
+ reason: 'MongoDB 不支持 SQL EXPLAIN,请使用聚合管道的 explain'
1345
+ };
1346
+ }
1347
+ let explainSql = '';
1348
+ if (/^EXPLAIN\b/i.test(statement)) {
1349
+ explainSql = statement;
1350
+ }
1351
+ else {
1352
+ switch (info.kind) {
1353
+ case 'mysql':
1354
+ explainSql = `EXPLAIN ${statement}`;
1355
+ break;
1356
+ case 'postgres':
1357
+ case 'cockroachdb':
1358
+ explainSql = `EXPLAIN (FORMAT JSON) ${statement}`;
1359
+ break;
1360
+ case 'sqlite':
1361
+ explainSql = `EXPLAIN QUERY PLAN ${statement}`;
1362
+ break;
1363
+ case 'clickhouse':
1364
+ explainSql = `EXPLAIN ${statement}`;
1365
+ break;
1366
+ default:
1367
+ return {
1368
+ ...base,
1369
+ supported: false,
1370
+ reasonCode: 'EXPLAIN_DIALECT_UNSUPPORTED',
1371
+ reason: '当前数据库类型暂未提供安全的 EXPLAIN 通道'
1372
+ };
864
1373
  }
865
- catch (error) {
866
- results.push({ table: table.name, success: false, error: error.message });
1374
+ }
1375
+ try {
1376
+ const plan = await dataSource.query(explainSql);
1377
+ return { ...base, explainSql, supported: true, plan };
1378
+ }
1379
+ catch (error) {
1380
+ const reason = error?.message ? String(error.message).split('\n')[0] : String(error);
1381
+ return { ...base, explainSql, supported: false, reasonCode: 'EXPLAIN_FAILED', reason };
1382
+ }
1383
+ }
1384
+ /** 资源指标:只取允许的只读指标,无权限/无等价物时逐项降级 */
1385
+ async getResourceMetrics(connectionId, databaseName) {
1386
+ const dataSource = await this.connectionService.getActiveConnection(connectionId, databaseName);
1387
+ const type = String(dataSource.options.type || '');
1388
+ const info = (0, dialect_1.getDialectInfo)(type);
1389
+ const service = this.getDatabaseService(type);
1390
+ const dbName = databaseName || String(dataSource.options.database || '');
1391
+ const metric = (value, supported, reason, reasonCode) => ({
1392
+ value: supported ? value : null,
1393
+ supported,
1394
+ ...(supported ? {} : {
1395
+ reasonCode: reasonCode || 'METRIC_UNAVAILABLE',
1396
+ reason: reason || '当前数据库类型未提供该指标'
1397
+ })
1398
+ });
1399
+ const firstNumber = (rows, keys) => {
1400
+ if (!Array.isArray(rows) || rows.length === 0)
1401
+ return 0;
1402
+ const row = rows[0] || {};
1403
+ for (const key of keys) {
1404
+ if (row[key] !== undefined && row[key] !== null)
1405
+ return Number(row[key]) || 0;
1406
+ }
1407
+ const values = Object.values(row);
1408
+ return Number(values[0]) || 0;
1409
+ };
1410
+ let databaseSizeBytes = metric(null, false, '数据库大小不可用', 'METRIC_DATABASE_SIZE_UNAVAILABLE');
1411
+ try {
1412
+ databaseSizeBytes = metric(Number(await service.getDatabaseSize(dataSource, dbName)) || 0, true);
1413
+ }
1414
+ catch (error) {
1415
+ databaseSizeBytes = metric(null, false, error?.message ? String(error.message).split('\n')[0] : String(error), 'METRIC_QUERY_FAILED');
1416
+ }
1417
+ let activeConnections = metric(null, false, '当前数据库类型未提供连接数指标', 'METRIC_ACTIVE_CONNECTIONS_UNSUPPORTED');
1418
+ try {
1419
+ let value = null;
1420
+ switch (info.kind) {
1421
+ case 'mysql': {
1422
+ const rows = await dataSource.query("SHOW STATUS LIKE 'Threads_connected'");
1423
+ const row = Array.isArray(rows) ? rows.find((item) => item?.Variable_name === 'Threads_connected') || rows[0] : null;
1424
+ value = row ? Number(row.Value ?? row.value ?? Object.values(row)[0]) || 0 : 0;
1425
+ break;
1426
+ }
1427
+ case 'postgres':
1428
+ case 'cockroachdb':
1429
+ value = firstNumber(await dataSource.query('SELECT COUNT(*) AS active FROM pg_stat_activity'), ['active']);
1430
+ break;
1431
+ case 'mssql':
1432
+ value = firstNumber(await dataSource.query('SELECT COUNT(*) AS active FROM sys.dm_exec_sessions'), ['active']);
1433
+ break;
1434
+ case 'oracle':
1435
+ value = firstNumber(await dataSource.query('SELECT COUNT(*) AS active FROM v$session'), ['active']);
1436
+ break;
1437
+ case 'clickhouse':
1438
+ value = firstNumber(await dataSource.query('SELECT COUNT() AS active FROM system.processes'), ['active']);
1439
+ break;
1440
+ case 'mongodb': {
1441
+ const nativeDb = dataSource.driver?.queryRunner?.databaseConnection?.db?.(dbName);
1442
+ if (!nativeDb)
1443
+ throw new Error('无法获取 MongoDB 原生数据库句柄');
1444
+ const status = await nativeDb.admin().serverStatus();
1445
+ value = Number(status?.connections?.current) || 0;
1446
+ break;
1447
+ }
867
1448
  }
1449
+ if (value !== null)
1450
+ activeConnections = metric(value, true);
868
1451
  }
869
- return { results };
1452
+ catch (error) {
1453
+ activeConnections = metric(null, false, error?.message ? String(error.message).split('\n')[0] : String(error), 'METRIC_QUERY_FAILED');
1454
+ }
1455
+ const unavailable = '该指标需要数据库侧系统视图或额外权限,当前未提供';
1456
+ return {
1457
+ dialect: info.kind,
1458
+ collectedAt: new Date().toISOString(),
1459
+ activeConnections,
1460
+ databaseSizeBytes,
1461
+ diskUsedBytes: databaseSizeBytes,
1462
+ cpuPercent: metric(null, false, unavailable, 'METRIC_SYSTEM_VIEW_REQUIRED'),
1463
+ memoryUsedBytes: metric(null, false, unavailable, 'METRIC_SYSTEM_VIEW_REQUIRED'),
1464
+ networkBytesPerSec: metric(null, false, unavailable, 'METRIC_SYSTEM_VIEW_REQUIRED'),
1465
+ notes: ['指标来自当前服务进程可见的只读查询;不支持或未授权的项目会明确降级']
1466
+ };
870
1467
  }
871
1468
  /**
872
1469
  * 导出表数据到 SQL 文件