fdb2 1.0.39 → 1.0.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +6 -5
  2. package/dist/public/.vite/manifest.json +109 -1
  3. package/dist/public/database-monitor.css +445 -0
  4. package/dist/public/database-monitor.js +605 -0
  5. package/dist/public/database.css +740 -0
  6. package/dist/public/database.js +555 -0
  7. package/dist/public/database2.js +344 -0
  8. package/dist/public/echarts.js +79307 -0
  9. package/dist/public/explorer.css +1109 -436
  10. package/dist/public/explorer.js +4049 -34891
  11. package/dist/public/export.js +54831 -0
  12. package/dist/public/helpers.js +27 -0
  13. package/dist/public/index.js +545 -51
  14. package/dist/public/layout.css +98 -65
  15. package/dist/public/layout.js +59 -22
  16. package/dist/public/query-history.css +651 -0
  17. package/dist/public/query-history.js +526 -0
  18. package/dist/public/sql-query-editor.css +503 -0
  19. package/dist/public/sql-query-editor.js +638 -0
  20. package/dist/public/theme.js +82 -0
  21. package/dist/scripts/verify-db-support.cjs +239 -0
  22. package/dist/server/__tests__/import-normalize.test.ts +79 -0
  23. package/dist/server/__tests__/remote-proxy.test.ts +62 -0
  24. package/dist/server/core/dialect.d.ts +9 -0
  25. package/dist/server/core/dialect.d.ts.map +1 -1
  26. package/dist/server/core/dialect.js +24 -9
  27. package/dist/server/core/dialect.js.map +1 -1
  28. package/dist/server/core/dialect.ts +29 -9
  29. package/dist/server/core/schema/__tests__/ddl-emitter.test.ts +159 -3
  30. package/dist/server/core/schema/canonical.d.ts.map +1 -1
  31. package/dist/server/core/schema/canonical.js +4 -1
  32. package/dist/server/core/schema/canonical.js.map +1 -1
  33. package/dist/server/core/schema/canonical.ts +4 -1
  34. package/dist/server/core/schema/ddl-emitter.d.ts +3 -0
  35. package/dist/server/core/schema/ddl-emitter.d.ts.map +1 -1
  36. package/dist/server/core/schema/ddl-emitter.js +158 -24
  37. package/dist/server/core/schema/ddl-emitter.js.map +1 -1
  38. package/dist/server/core/schema/ddl-emitter.ts +171 -22
  39. package/dist/server/index.d.ts +20 -0
  40. package/dist/server/index.d.ts.map +1 -1
  41. package/dist/server/index.js +375 -25
  42. package/dist/server/index.js.map +1 -1
  43. package/dist/server/index.ts +392 -27
  44. package/dist/server/model/ddl-spec.d.ts +9 -0
  45. package/dist/server/model/ddl-spec.d.ts.map +1 -1
  46. package/dist/server/model/ddl-spec.ts +9 -0
  47. package/dist/server/service/connection.service.d.ts +8 -0
  48. package/dist/server/service/connection.service.d.ts.map +1 -1
  49. package/dist/server/service/connection.service.js +75 -17
  50. package/dist/server/service/connection.service.js.map +1 -1
  51. package/dist/server/service/connection.service.ts +74 -17
  52. package/dist/server/service/database/base.service.d.ts +45 -0
  53. package/dist/server/service/database/base.service.d.ts.map +1 -1
  54. package/dist/server/service/database/base.service.js +120 -7
  55. package/dist/server/service/database/base.service.js.map +1 -1
  56. package/dist/server/service/database/base.service.ts +143 -8
  57. package/dist/server/service/database/cockroachdb.service.d.ts +9 -0
  58. package/dist/server/service/database/cockroachdb.service.d.ts.map +1 -1
  59. package/dist/server/service/database/cockroachdb.service.js +68 -57
  60. package/dist/server/service/database/cockroachdb.service.js.map +1 -1
  61. package/dist/server/service/database/cockroachdb.service.ts +67 -58
  62. package/dist/server/service/database/database.service.d.ts +25 -227
  63. package/dist/server/service/database/database.service.d.ts.map +1 -1
  64. package/dist/server/service/database/database.service.js +323 -78
  65. package/dist/server/service/database/database.service.js.map +1 -1
  66. package/dist/server/service/database/database.service.ts +334 -87
  67. package/dist/server/service/database/mongodb.service.d.ts +58 -3
  68. package/dist/server/service/database/mongodb.service.d.ts.map +1 -1
  69. package/dist/server/service/database/mongodb.service.js +264 -54
  70. package/dist/server/service/database/mongodb.service.js.map +1 -1
  71. package/dist/server/service/database/mongodb.service.ts +288 -60
  72. package/dist/server/service/database/mssql.service.d.ts +8 -0
  73. package/dist/server/service/database/mssql.service.d.ts.map +1 -1
  74. package/dist/server/service/database/mssql.service.js +45 -40
  75. package/dist/server/service/database/mssql.service.js.map +1 -1
  76. package/dist/server/service/database/mssql.service.ts +49 -44
  77. package/dist/server/service/database/oracle.service.d.ts +29 -1
  78. package/dist/server/service/database/oracle.service.d.ts.map +1 -1
  79. package/dist/server/service/database/oracle.service.js +166 -137
  80. package/dist/server/service/database/oracle.service.js.map +1 -1
  81. package/dist/server/service/database/oracle.service.ts +166 -146
  82. package/dist/server/service/database/sap.service.d.ts +8 -0
  83. package/dist/server/service/database/sap.service.d.ts.map +1 -1
  84. package/dist/server/service/database/sap.service.js +28 -0
  85. package/dist/server/service/database/sap.service.js.map +1 -1
  86. package/dist/server/service/database/sap.service.ts +29 -0
  87. package/dist/server/service/database/sqlite.service.d.ts.map +1 -1
  88. package/dist/server/service/database/sqlite.service.js +6 -3
  89. package/dist/server/service/database/sqlite.service.js.map +1 -1
  90. package/dist/server/service/database/sqlite.service.ts +6 -3
  91. package/package.json +8 -8
  92. package/public/fdb2.png +0 -0
  93. package/scripts/verify-db-support.cjs +239 -0
@@ -1,6 +1,9 @@
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");
6
9
  const canonical_1 = require("../../core/schema/canonical");
@@ -15,6 +18,138 @@ const cockroachdb_service_1 = require("./cockroachdb.service");
15
18
  const mongodb_service_1 = require("./mongodb.service");
16
19
  const sap_service_1 = require("./sap.service");
17
20
  const clickhouse_service_1 = require("./clickhouse.service");
21
+ const IMPORT_TEXT_TYPE_RE = /\b(?:character|varchar|nvarchar|char|nchar|text|ntext|clob|longtext|mediumtext|tinytext)\b/i;
22
+ const IMPORT_NUMERIC_TYPE_RE = /\b(?:integer|int|bigint|smallint|tinyint|mediumint|decimal|numeric|dec|fixed|float|double|real|money|number)\b/i;
23
+ const IMPORT_BOOL_TYPE_RE = /\b(?:bool|boolean)\b/i;
24
+ const IMPORT_NUMERIC_STRING_RE = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/;
25
+ function importSignificantDigits(raw) {
26
+ return raw.replace(/^[+-]/, '').replace('.', '').replace(/^0+/, '').replace(/0+$/, '').length;
27
+ }
28
+ function coerceImportValue(value, columnType) {
29
+ if (value === null || value === undefined)
30
+ return null;
31
+ const type = String(columnType || '').toLowerCase();
32
+ const isText = IMPORT_TEXT_TYPE_RE.test(type);
33
+ // 空串只对非文本列表示缺失;文本列必须保留用户显式输入的 ''。
34
+ if (value === '')
35
+ return isText ? '' : null;
36
+ if (isText)
37
+ return value;
38
+ if (IMPORT_BOOL_TYPE_RE.test(type)) {
39
+ if (value === true || value === 1)
40
+ return true;
41
+ if (value === false || value === 0)
42
+ return false;
43
+ if (typeof value === 'string') {
44
+ const normalized = value.trim().toLowerCase();
45
+ if (normalized === 'true' || normalized === '1')
46
+ return true;
47
+ if (normalized === 'false' || normalized === '0')
48
+ return false;
49
+ }
50
+ return value;
51
+ }
52
+ if (IMPORT_NUMERIC_TYPE_RE.test(type) && typeof value === 'string') {
53
+ const raw = value.trim();
54
+ if (!IMPORT_NUMERIC_STRING_RE.test(raw))
55
+ return value;
56
+ const number = Number(raw);
57
+ if (Number.isNaN(number))
58
+ return value;
59
+ // 大整数超出安全范围、高精度小数有效位超过 15 位时保留原字符串,避免 Number() 静默丢精度。
60
+ if (Number.isInteger(number) ? !Number.isSafeInteger(number) : importSignificantDigits(raw) > 15) {
61
+ return value;
62
+ }
63
+ return number;
64
+ }
65
+ if (typeof value === 'string') {
66
+ if (value === 'true')
67
+ return true;
68
+ if (value === 'false')
69
+ return false;
70
+ }
71
+ return value;
72
+ }
73
+ /** 纯函数:把导入行按 getColumns 的列全集归一化,供测试与 importData 共用。 */
74
+ function normalizeImportRows(rows, columns) {
75
+ if (!Array.isArray(rows))
76
+ return [];
77
+ const definitions = (Array.isArray(columns) ? columns : [])
78
+ .map((column) => ({
79
+ name: String(column?.name ?? '').trim(),
80
+ type: String(column?.type ?? ''),
81
+ isAutoIncrement: !!column?.isAutoIncrement
82
+ }))
83
+ // 自增/identity 列不能显式写值,否则 PG/CRDB/MSSQL/Oracle 会直接拒绝整批导入。
84
+ .filter((column) => column.name && !column.isAutoIncrement);
85
+ const names = definitions.map((column) => column.name);
86
+ const types = new Map(definitions.map((column) => [column.name, column.type]));
87
+ const normalized = [];
88
+ for (const row of rows) {
89
+ const out = {};
90
+ for (const name of names)
91
+ out[name] = null;
92
+ if (!row || typeof row !== 'object') {
93
+ normalized.push(out);
94
+ continue;
95
+ }
96
+ for (const key of Object.keys(row)) {
97
+ const name = key.trim();
98
+ if (!types.has(name))
99
+ continue;
100
+ out[name] = coerceImportValue(row[key], types.get(name) || '');
101
+ }
102
+ normalized.push(out);
103
+ }
104
+ return normalized;
105
+ }
106
+ /** 同步到关系库时,把文档库里的 BSON/嵌套值转成驱动可绑定的标量。 */
107
+ function normalizeSyncRowForRelational(row) {
108
+ const out = {};
109
+ if (!row || typeof row !== 'object' || Array.isArray(row))
110
+ return out;
111
+ for (const [key, value] of Object.entries(row)) {
112
+ if (value === null || value === undefined) {
113
+ out[key] = null;
114
+ }
115
+ else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
116
+ out[key] = value;
117
+ }
118
+ else if (Buffer.isBuffer(value) || value instanceof Date) {
119
+ out[key] = value;
120
+ }
121
+ else if (typeof value.toHexString === 'function' || value._bsontype === 'ObjectId') {
122
+ out[key] = String(value);
123
+ }
124
+ else if (typeof value === 'object') {
125
+ out[key] = JSON.stringify(value);
126
+ }
127
+ else {
128
+ out[key] = String(value);
129
+ }
130
+ }
131
+ return out;
132
+ }
133
+ /** 同一批次按字段并集补齐,避免 bulkInsert 只取首行字段导致后续文档字段丢失。 */
134
+ function normalizeSyncRowsForRelational(rows) {
135
+ const normalized = (Array.isArray(rows) ? rows : []).map(normalizeSyncRowForRelational);
136
+ const keys = [];
137
+ const seen = new Set();
138
+ for (const row of normalized) {
139
+ for (const key of Object.keys(row)) {
140
+ if (!seen.has(key)) {
141
+ seen.add(key);
142
+ keys.push(key);
143
+ }
144
+ }
145
+ }
146
+ return normalized.map((row) => {
147
+ const out = {};
148
+ for (const key of keys)
149
+ out[key] = Object.prototype.hasOwnProperty.call(row, key) ? row[key] : null;
150
+ return out;
151
+ });
152
+ }
18
153
  /**
19
154
  * 数据库服务管理类
20
155
  * 负责根据数据库类型选择相应的服务实现
@@ -165,20 +300,23 @@ class DatabaseService {
165
300
  /**
166
301
  * 目标态 TableSpec 的静态校验(建表/改表共用)
167
302
  */
168
- validateTableSpec(spec) {
303
+ validateTableSpec(spec, requireColumns = true) {
169
304
  if (!spec || typeof spec.name !== 'string' || !spec.name.trim()) {
170
305
  throw new Error('目标表名不能为空');
171
306
  }
172
- if (!Array.isArray(spec.columns) || spec.columns.length === 0) {
307
+ // 无模式方言(MongoDB 建集合)没有列定义,不强制要求至少一列
308
+ if (requireColumns && (!Array.isArray(spec.columns) || spec.columns.length === 0)) {
173
309
  throw new Error('目标结构至少需要一列');
174
310
  }
175
- const names = new Set(spec.columns.map((c) => c.name));
176
- if (names.size !== spec.columns.length) {
177
- throw new Error('目标结构存在重名列');
178
- }
179
- for (const pk of spec.primaryKey || []) {
180
- if (!names.has(pk))
181
- throw new Error(`主键列 "${pk}" 不在目标结构中`);
311
+ if (Array.isArray(spec.columns) && spec.columns.length > 0) {
312
+ const names = new Set(spec.columns.map((c) => c.name));
313
+ if (names.size !== spec.columns.length) {
314
+ throw new Error('目标结构存在重名列');
315
+ }
316
+ for (const pk of spec.primaryKey || []) {
317
+ if (!names.has(pk))
318
+ throw new Error(`主键列 "${pk}" 不在目标结构中`);
319
+ }
182
320
  }
183
321
  return spec.name.trim();
184
322
  }
@@ -188,25 +326,31 @@ class DatabaseService {
188
326
  * 前端建表全部走同一渲染出口,CREATE TABLE 不再有第二份方言实现。
189
327
  */
190
328
  async buildCreatePlan(connectionId, databaseName, spec, forceRefresh = false) {
191
- const tableName = this.validateTableSpec(spec);
192
329
  const dataSource = await this.connectionService.getActiveConnection(connectionId, databaseName);
193
330
  const type = dataSource.options.type;
194
331
  const kind = (0, dialect_1.getDialectInfo)(type).kind;
195
332
  const dbService = this.getDatabaseService(type);
196
333
  const caps = (0, ddl_emitter_1.ddlCapabilities)(kind);
334
+ // 无模式方言(MongoDB):走驱动原生建集合——不生成 CREATE TABLE SQL,也不需要列定义
335
+ const driverCreate = caps.createStrategy === 'driver';
336
+ const tableName = this.validateTableSpec(spec, !driverCreate);
197
337
  // 方言不支持建表:作为计划内错误返回(而非抛出)——capabilities 仍要带回前端用于禁用 UI
198
338
  if (!caps.createTable) {
199
- return { dataSource, kind, caps, dbService, statements: [], error: `该数据库类型(${kind})不支持通过 SQL 建表` };
339
+ return { dataSource, kind, caps, dbService, tableName, statements: [], error: `该数据库类型(${kind})不支持通过 SQL 建表` };
200
340
  }
201
341
  // 重名检测:目标态与实时结构冲突(等价 409 语义)。
202
342
  // 预览走缓存避免每次输入都全量拉表;执行前必须 force 刷新,否则缓存会让重名检测失效。
203
343
  const tables = await this.getTableList(connectionId, databaseName, forceRefresh);
204
344
  if (tables.some((t) => (0, ddl_emitter_1.tableNameEquals)(kind, String(t?.name ?? ''), tableName))) {
205
- return { dataSource, kind, caps, dbService, statements: [], error: `表 "${tableName}" 已存在` };
345
+ return { dataSource, kind, caps, dbService, tableName, statements: [], error: `表 "${tableName}" 已存在` };
346
+ }
347
+ // 驱动路径:无列定义、无 SQL 语句,执行阶段直接调 dbService.createTable
348
+ if (driverCreate) {
349
+ return { dataSource, kind, caps, dbService, tableName, statements: [], error: '' };
206
350
  }
207
351
  const desired = (0, canonical_1.canonicalizeTableSpec)(spec);
208
352
  const statements = (0, ddl_emitter_1.emitCreateDdl)(kind, desired, { mssqlDatabase: databaseName });
209
- return { dataSource, kind, caps, dbService, statements, error: '' };
353
+ return { dataSource, kind, caps, dbService, tableName, statements, error: '' };
210
354
  }
211
355
  /**
212
356
  * 预览建表:纯计算不执行。与执行同一出口生成语句,所见即所得。
@@ -216,14 +360,21 @@ class DatabaseService {
216
360
  */
217
361
  async previewCreateTable(connectionId, databaseName, spec) {
218
362
  const plan = await this.buildCreatePlan(connectionId, databaseName, spec);
219
- if (plan.error)
220
- throw new Error(plan.error);
221
- const previewText = plan.statements.length > 0 ? plan.statements.join(';\n') + ';' : '';
363
+ // 注意:计划级非致命错误(方言不支持建表、表已存在)不能抛——否则 capabilities 不会返回,
364
+ // 前端无法据此禁用提交按钮。错误以注释形式写入预览,并由前端 submitDisabledHint 展示。
365
+ const previewText = plan.statements.length > 0
366
+ ? plan.statements.join(';\n') + ';'
367
+ : plan.error
368
+ ? `-- ${plan.error}`
369
+ : (plan.caps.createStrategy === 'driver'
370
+ ? `-- 创建集合 "${plan.tableName}"(无模式集合,不生成建表 SQL)`
371
+ : '');
222
372
  return {
223
373
  statements: plan.statements,
224
374
  preview: previewText,
225
375
  changeSet: null,
226
- capabilities: plan.caps
376
+ capabilities: plan.caps,
377
+ error: plan.error || null
227
378
  };
228
379
  }
229
380
  /**
@@ -234,6 +385,19 @@ class DatabaseService {
234
385
  const plan = await this.buildCreatePlan(connectionId, databaseName, spec, true);
235
386
  if (plan.error)
236
387
  throw new Error(plan.error);
388
+ // 无模式方言(MongoDB):没有建表 SQL,直接走驱动原生建集合
389
+ if (plan.caps.createStrategy === 'driver') {
390
+ try {
391
+ await plan.dbService.createTable(plan.dataSource, databaseName, { name: plan.tableName });
392
+ }
393
+ catch (error) {
394
+ console.error('执行创建集合失败:', error);
395
+ throw new Error(`创建集合失败: ${error instanceof Error ? error.message : String(error)}`);
396
+ }
397
+ this.invalidateTableList(connectionId, databaseName); // 集合列表已变化
398
+ // native: 无 SQL 语句但集合已实际创建——前端据此与"无修改"区分
399
+ return { statements: plan.statements, native: true };
400
+ }
237
401
  if (plan.statements.length === 0)
238
402
  throw new Error('未能生成建表语句');
239
403
  try {
@@ -280,21 +444,31 @@ class DatabaseService {
280
444
  if (changeSet.primaryKey && !caps.alterPrimaryKey) {
281
445
  error = `该数据库类型(${kind})不支持修改主键`;
282
446
  }
283
- // SQL Server:删除现有主键必须知道真实的约束名(PK__<table>__<hash>),回查系统表获取。
447
+ // SQL Server / SAP HANA:删除现有主键必须知道真实的约束名,回查系统表获取。
284
448
  // 仅在「已有主键需要 DROP」时才必需;纯新增主键的约束名由我们自己指定。
449
+ const needsPkDrop = !!changeSet.primaryKey && changeSet.primaryKey.from.length > 0;
285
450
  let mssqlPkConstraintName;
286
- if (!error && kind === 'mssql' && changeSet.primaryKey && changeSet.primaryKey.from.length > 0) {
451
+ let sapPkConstraintName;
452
+ if (!error && needsPkDrop && (kind === 'mssql' || kind === 'sap')) {
287
453
  const svc = dbService;
288
454
  if (typeof svc.getPrimaryKeyConstraintName === 'function') {
289
- mssqlPkConstraintName = (await svc.getPrimaryKeyConstraintName(dataSource, databaseName, tableName)) || undefined;
455
+ const constraintName = (await svc.getPrimaryKeyConstraintName(dataSource, databaseName, tableName)) || undefined;
456
+ if (kind === 'mssql')
457
+ mssqlPkConstraintName = constraintName;
458
+ else
459
+ sapPkConstraintName = constraintName;
290
460
  }
291
- if (!mssqlPkConstraintName) {
461
+ if (kind === 'mssql' ? !mssqlPkConstraintName : !sapPkConstraintName) {
292
462
  error = '无法定位该表的主键约束名,无法修改主键';
293
463
  }
294
464
  }
295
- const statements = error
296
- ? []
297
- : (0, ddl_emitter_1.emitAlterDdl)(kind, original, desired, mssqlPkConstraintName ? { mssqlPkConstraintName } : undefined);
465
+ const alterDdlOptions = mssqlPkConstraintName || sapPkConstraintName
466
+ ? {
467
+ ...(mssqlPkConstraintName ? { mssqlPkConstraintName } : {}),
468
+ ...(sapPkConstraintName ? { sapPkConstraintName } : {})
469
+ }
470
+ : undefined;
471
+ const statements = error ? [] : (0, ddl_emitter_1.emitAlterDdl)(kind, original, desired, alterDdlOptions);
298
472
  return {
299
473
  dataSource,
300
474
  kind,
@@ -315,14 +489,16 @@ class DatabaseService {
315
489
  */
316
490
  async previewAlterTable(connectionId, databaseName, tableName, spec) {
317
491
  const plan = await this.buildAlterPlan(connectionId, databaseName, tableName, spec);
318
- if (plan.error)
319
- throw new Error(plan.error);
320
- const previewText = plan.statements.length > 0 ? plan.statements.join(';\n') + ';' : '';
492
+ // 与 previewCreateTable 同理:计划级非致命错误不抛,确保 capabilities 返回以驱动 UI 禁用。
493
+ const previewText = plan.statements.length > 0
494
+ ? plan.statements.join(';\n') + ';'
495
+ : (plan.error ? `-- ${plan.error}` : '');
321
496
  return {
322
497
  statements: plan.statements,
323
498
  preview: previewText,
324
499
  changeSet: plan.changeSet,
325
- capabilities: plan.caps
500
+ capabilities: plan.caps,
501
+ error: plan.error || null
326
502
  };
327
503
  }
328
504
  /**
@@ -430,28 +606,31 @@ class DatabaseService {
430
606
  tableSyncResult.messages.push(`开始同步表数据: ${sourceTableName} -> ${target.tableName}`);
431
607
  // 获取源表数据(分批获取,避免内存问题)
432
608
  const batchSize = 1000;
433
- let offset = 0;
609
+ let page = 1;
434
610
  let totalRows = 0;
435
611
  while (true) {
436
- const sourceData = await sourceService.query(sourceDataSource, {
437
- sql: `SELECT * FROM ${sourceService.quoteIdentifier(sourceTableName)} LIMIT ? OFFSET ?`,
438
- params: [batchSize, offset]
439
- });
612
+ // 统一走 getTableData 而不是自己拼 LIMIT/OFFSET:
613
+ // 各方言分页语法不同(MSSQL/Oracle 用 OFFSET/FETCH,MongoDB 根本没有 SQL),
614
+ // 这里复用各服务已实现的分页读取,避免同步功能只对 MySQL/SQLite 可用。
615
+ const sourceData = (await sourceService.getTableData(sourceDataSource, source.database, sourceTableName, page, batchSize)).data;
440
616
  if (sourceData.length === 0) {
441
617
  break;
442
618
  }
443
- // 插入数据到目标表
619
+ // 插入数据到目标表;文档库的 ObjectId/嵌套对象不能直接绑定给关系库驱动。
620
+ const rowsForTarget = targetService.getDatabaseType() === 'mongodb'
621
+ ? sourceData
622
+ : normalizeSyncRowsForRelational(sourceData);
444
623
  if (options.bulkInsert) {
445
- await targetService.bulkInsert(targetDataSource, targetDatabaseName, target.tableName, sourceData, options.overrideExisting);
624
+ await targetService.bulkInsert(targetDataSource, targetDatabaseName, target.tableName, rowsForTarget, options.overrideExisting);
446
625
  }
447
626
  else {
448
- for (const row of sourceData) {
627
+ for (const row of rowsForTarget) {
449
628
  await targetService.insertData(targetDataSource, targetDatabaseName, target.tableName, row, options.overrideExisting);
450
629
  }
451
630
  }
452
631
  totalRows += sourceData.length;
453
632
  tableSyncResult.messages.push(`已同步 ${totalRows} 行数据`);
454
- offset += batchSize;
633
+ page += 1;
455
634
  }
456
635
  tableSyncResult.dataSynced = true;
457
636
  tableSyncResult.rowsSynced = totalRows;
@@ -646,7 +825,10 @@ class DatabaseService {
646
825
  supportJson: true,
647
826
  supportArrays: true,
648
827
  supportDocuments: true,
649
- supportNoSQL: true
828
+ supportNoSQL: true,
829
+ // 数据层能力:文档型、无 SQL 编辑器(前端据此切文档模式 UI)
830
+ dataModel: 'document',
831
+ supportSqlEditor: false
650
832
  }
651
833
  },
652
834
  {
@@ -654,7 +836,11 @@ class DatabaseService {
654
836
  label: 'SAP HANA',
655
837
  icon: 'bi-database',
656
838
  defaultPort: 39013,
657
- description: 'SAP HANA内存数据库',
839
+ description: 'SAP HANA内存数据库(实验性)',
840
+ // 实验性:依赖未随默认依赖安装的 @sap/hana-client 驱动,且官方无免费 Docker 镜像,
841
+ // 本仓库尚未做端到端运行验证。驱动缺失时会给出明确的安装提示。
842
+ experimental: true,
843
+ driverPackage: '@sap/hana-client',
658
844
  features: {
659
845
  supportSchemas: true,
660
846
  supportProcedures: true,
@@ -700,7 +886,11 @@ class DatabaseService {
700
886
  supportJson: false
701
887
  }
702
888
  }
703
- ];
889
+ ].map((t) => ({
890
+ ...t,
891
+ // 数据层能力默认值:关系型 + 支持 SQL;文档型(MongoDB)在自身 features 中覆盖
892
+ features: { dataModel: 'relational', supportSqlEditor: true, ...(t.features || {}) }
893
+ }));
704
894
  }
705
895
  /**
706
896
  * 创建数据库
@@ -740,7 +930,10 @@ class DatabaseService {
740
930
  async backupDatabase(connectionId, databaseName, options) {
741
931
  const dataSource = await this.connectionService.getActiveConnection(connectionId, databaseName);
742
932
  const databaseService = this.getDatabaseService(dataSource.options.type);
743
- return databaseService.backupDatabase(dataSource, databaseName, options);
933
+ const result = await databaseService.backupDatabase(dataSource, databaseName, options);
934
+ const scheduleId = options?.scheduleId;
935
+ // 让定时任务的 scheduleId 在返回提示中可见,便于定位是哪条计划产生的备份。
936
+ return scheduleId ? `${result}[schedule:${scheduleId}]` : result;
744
937
  }
745
938
  /**
746
939
  * 恢复数据库
@@ -770,61 +963,113 @@ class DatabaseService {
770
963
  };
771
964
  }
772
965
  /**
773
- * 优化数据库
966
+ * 维护操作(OPTIMIZE / ANALYZE / REPAIR)的方言适配。
967
+ *
968
+ * 原先三个方法对所有连接都拼 MySQL 语法,PostgreSQL/SQLite/MongoDB 等
969
+ * 必然报错;CLI 侧早已明确拒绝非 MySQL。这里按方言给出等价语句或清晰
970
+ * 的「不支持」结果,而不是让驱动抛原始 SQL 错误。
774
971
  */
775
- async optimizeDatabase(connectionId, databaseName) {
972
+ async runMaintenance(connectionId, databaseName, action) {
776
973
  const dataSource = await this.connectionService.getActiveConnection(connectionId, databaseName);
777
- const databaseService = this.getDatabaseService(dataSource.options.type);
974
+ const type = String(dataSource.options.type || '');
975
+ const info = (0, dialect_1.getDialectInfo)(type);
976
+ const databaseService = this.getDatabaseService(type);
778
977
  const tables = await databaseService.getTables(dataSource, databaseName);
779
- const results = [];
780
- for (const table of tables) {
978
+ const q = (name) => (0, dialect_1.quoteIdentifier)(type, name);
979
+ const unsupported = (table) => ({
980
+ table,
981
+ success: false,
982
+ error: `${action} 暂不支持 ${info.label}(仅 MySQL / PostgreSQL / SQLite 提供等价操作)`
983
+ });
984
+ // SQLite 的 VACUUM / integrity_check 作用于整库,不能按表重复执行
985
+ if (info.kind === 'sqlite' && action !== 'analyze') {
986
+ const sql = action === 'optimize' ? 'VACUUM' : 'PRAGMA integrity_check';
781
987
  try {
782
- const result = await dataSource.query(`OPTIMIZE TABLE \`${table.name}\``);
783
- results.push({ table: table.name, success: true, result });
988
+ const result = await dataSource.query(sql);
989
+ return { results: [{ table: '*', success: true, sql, result }], dialect: info.kind };
784
990
  }
785
- catch (error) {
786
- results.push({ table: table.name, success: false, error: error.message });
991
+ catch (e) {
992
+ return { results: [{ table: '*', success: false, sql, error: e?.message || String(e) }], dialect: info.kind };
787
993
  }
788
994
  }
789
- return { results };
790
- }
791
- /**
792
- * 分析表
793
- */
794
- async analyzeTables(connectionId, databaseName) {
795
- const dataSource = await this.connectionService.getActiveConnection(connectionId, databaseName);
796
- const databaseService = this.getDatabaseService(dataSource.options.type);
797
- const tables = await databaseService.getTables(dataSource, databaseName);
995
+ const statementFor = (table) => {
996
+ switch (info.kind) {
997
+ case 'mysql':
998
+ return `${action.toUpperCase()} TABLE ${q(table)}`;
999
+ case 'postgres':
1000
+ case 'cockroachdb':
1001
+ if (action === 'analyze')
1002
+ return `ANALYZE ${q(table)}`;
1003
+ if (action === 'optimize')
1004
+ return `VACUUM ANALYZE ${q(table)}`;
1005
+ return null;
1006
+ case 'sqlite':
1007
+ return action === 'analyze' ? `ANALYZE ${q(table)}` : null;
1008
+ default:
1009
+ return null;
1010
+ }
1011
+ };
798
1012
  const results = [];
799
1013
  for (const table of tables) {
1014
+ const sql = statementFor(table.name);
1015
+ if (!sql) {
1016
+ results.push(unsupported(table.name));
1017
+ continue;
1018
+ }
800
1019
  try {
801
- const result = await dataSource.query(`ANALYZE TABLE \`${table.name}\``);
802
- results.push({ table: table.name, success: true, result });
1020
+ const result = await dataSource.query(sql);
1021
+ results.push({ table: table.name, success: true, sql, result });
803
1022
  }
804
- catch (error) {
805
- results.push({ table: table.name, success: false, error: error.message });
1023
+ catch (e) {
1024
+ results.push({ table: table.name, success: false, sql, error: e?.message || String(e) });
806
1025
  }
807
1026
  }
808
- return { results };
1027
+ return { results, dialect: info.kind };
809
1028
  }
810
1029
  /**
811
- * 修复表
1030
+ * 批量导入:文件解析在浏览器完成,这里接收行数组并走各方言 bulkInsert。
1031
+ * 按表结构过滤未知列并做轻量类型转换(CSV 里一切都是字符串)。
812
1032
  */
813
- async repairTables(connectionId, databaseName) {
1033
+ async importData(connectionId, databaseName, tableName, rows) {
1034
+ if (!Array.isArray(rows))
1035
+ throw new Error('rows must be an array');
814
1036
  const dataSource = await this.connectionService.getActiveConnection(connectionId, databaseName);
815
- const databaseService = this.getDatabaseService(dataSource.options.type);
816
- const tables = await databaseService.getTables(dataSource, databaseName);
817
- const results = [];
818
- for (const table of tables) {
819
- try {
820
- const result = await dataSource.query(`REPAIR TABLE \`${table.name}\``);
821
- results.push({ table: table.name, success: true, result });
822
- }
823
- catch (error) {
824
- results.push({ table: table.name, success: false, error: error.message });
825
- }
1037
+ const type = String(dataSource.options.type || '');
1038
+ const service = this.getDatabaseService(type);
1039
+ // MongoDB 是 schemaless:空集合 getColumns 返回空,不能按列归一化把全部文档过滤掉。
1040
+ if (type === 'mongodb') {
1041
+ const docs = rows.filter((row) => row && typeof row === 'object' && !Array.isArray(row));
1042
+ if (docs.length === 0)
1043
+ return { imported: 0, table: tableName };
1044
+ await service.bulkInsert(dataSource, databaseName, tableName, docs);
1045
+ return { imported: docs.length, table: tableName };
826
1046
  }
827
- return { results };
1047
+ const columns = await service.getColumns(dataSource, databaseName, tableName);
1048
+ const knownNames = new Set((Array.isArray(columns) ? columns : [])
1049
+ .map((column) => String(column?.name ?? '').trim())
1050
+ .filter(Boolean));
1051
+ // 纯函数保留所有输入行的列全集;导入时仍需跳过完全不含已知列的空行。
1052
+ const clean = normalizeImportRows(rows, columns).filter((_, index) => {
1053
+ const row = rows[index];
1054
+ return !!row && typeof row === 'object' &&
1055
+ Object.keys(row).some((key) => knownNames.has(key.trim()));
1056
+ });
1057
+ if (clean.length === 0)
1058
+ return { imported: 0, table: tableName };
1059
+ await service.bulkInsert(dataSource, databaseName, tableName, clean);
1060
+ return { imported: clean.length, table: tableName };
1061
+ }
1062
+ /** 优化数据库 */
1063
+ async optimizeDatabase(connectionId, databaseName) {
1064
+ return this.runMaintenance(connectionId, databaseName, 'optimize');
1065
+ }
1066
+ /** 分析表 */
1067
+ async analyzeTables(connectionId, databaseName) {
1068
+ return this.runMaintenance(connectionId, databaseName, 'analyze');
1069
+ }
1070
+ /** 修复表 */
1071
+ async repairTables(connectionId, databaseName) {
1072
+ return this.runMaintenance(connectionId, databaseName, 'repair');
828
1073
  }
829
1074
  /**
830
1075
  * 导出表数据到 SQL 文件