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
@@ -5,11 +5,11 @@ import {
5
5
  DatabaseEntity,
6
6
  TableEntity
7
7
  } from '../../model/database.entity';
8
- import { getDialectInfo } from '../../core/dialect';
8
+ import { getDialectInfo, quoteIdentifier } from '../../core/dialect';
9
9
  import { canonicalizeTableEntity, canonicalizeTableSpec } from '../../core/schema/canonical';
10
10
  import { diffTable } from '../../core/schema/diff';
11
11
  import { ddlCapabilities, emitAlterDdl, emitCreateDdl, tableNameEquals } from '../../core/schema/ddl-emitter';
12
- import type { DdlCapability, DdlPreview, TableSpec } from '../../model/ddl-spec';
12
+ import type { DdlCapability, DdlExecuteResult, DdlPreview, TableSpec } from '../../model/ddl-spec';
13
13
  import { MySQLService } from './mysql.service';
14
14
  import { PostgreSQLService } from './postgres.service';
15
15
  import { SQLiteService } from './sqlite.service';
@@ -20,6 +20,129 @@ import { MongoDBService } from './mongodb.service';
20
20
  import { SAPHANADatabaseService } from './sap.service';
21
21
  import { ClickHouseService } from './clickhouse.service';
22
22
 
23
+ const IMPORT_TEXT_TYPE_RE = /\b(?:character|varchar|nvarchar|char|nchar|text|ntext|clob|longtext|mediumtext|tinytext)\b/i;
24
+ const IMPORT_NUMERIC_TYPE_RE = /\b(?:integer|int|bigint|smallint|tinyint|mediumint|decimal|numeric|dec|fixed|float|double|real|money|number)\b/i;
25
+ const IMPORT_BOOL_TYPE_RE = /\b(?:bool|boolean)\b/i;
26
+ const IMPORT_NUMERIC_STRING_RE = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/;
27
+
28
+ function importSignificantDigits(raw: string): number {
29
+ return raw.replace(/^[+-]/, '').replace('.', '').replace(/^0+/, '').replace(/0+$/, '').length;
30
+ }
31
+
32
+ function coerceImportValue(value: any, columnType: string): any {
33
+ if (value === null || value === undefined) return null;
34
+ const type = String(columnType || '').toLowerCase();
35
+ const isText = IMPORT_TEXT_TYPE_RE.test(type);
36
+
37
+ // 空串只对非文本列表示缺失;文本列必须保留用户显式输入的 ''。
38
+ if (value === '') return isText ? '' : null;
39
+ if (isText) return value;
40
+
41
+ if (IMPORT_BOOL_TYPE_RE.test(type)) {
42
+ if (value === true || value === 1) return true;
43
+ if (value === false || value === 0) return false;
44
+ if (typeof value === 'string') {
45
+ const normalized = value.trim().toLowerCase();
46
+ if (normalized === 'true' || normalized === '1') return true;
47
+ if (normalized === 'false' || normalized === '0') return false;
48
+ }
49
+ return value;
50
+ }
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)) return value;
55
+ const number = Number(raw);
56
+ if (Number.isNaN(number)) return value;
57
+ // 大整数超出安全范围、高精度小数有效位超过 15 位时保留原字符串,避免 Number() 静默丢精度。
58
+ if (Number.isInteger(number) ? !Number.isSafeInteger(number) : importSignificantDigits(raw) > 15) {
59
+ return value;
60
+ }
61
+ return number;
62
+ }
63
+
64
+ if (typeof value === 'string') {
65
+ if (value === 'true') return true;
66
+ if (value === 'false') return false;
67
+ }
68
+ return value;
69
+ }
70
+
71
+ /** 纯函数:把导入行按 getColumns 的列全集归一化,供测试与 importData 共用。 */
72
+ export function normalizeImportRows(rows: any[], columns: any[]): any[] {
73
+ if (!Array.isArray(rows)) return [];
74
+ const definitions = (Array.isArray(columns) ? columns : [])
75
+ .map((column: any) => ({
76
+ name: String(column?.name ?? '').trim(),
77
+ type: String(column?.type ?? ''),
78
+ isAutoIncrement: !!column?.isAutoIncrement
79
+ }))
80
+ // 自增/identity 列不能显式写值,否则 PG/CRDB/MSSQL/Oracle 会直接拒绝整批导入。
81
+ .filter((column) => column.name && !column.isAutoIncrement);
82
+ const names = definitions.map((column) => column.name);
83
+ const types = new Map(definitions.map((column) => [column.name, column.type]));
84
+
85
+ const normalized: any[] = [];
86
+ for (const row of rows) {
87
+ const out: Record<string, any> = {};
88
+ for (const name of names) out[name] = null;
89
+ if (!row || typeof row !== 'object') {
90
+ normalized.push(out);
91
+ continue;
92
+ }
93
+
94
+ for (const key of Object.keys(row)) {
95
+ const name = key.trim();
96
+ if (!types.has(name)) continue;
97
+ out[name] = coerceImportValue((row as any)[key], types.get(name) || '');
98
+ }
99
+ normalized.push(out);
100
+ }
101
+ return normalized;
102
+ }
103
+
104
+ /** 同步到关系库时,把文档库里的 BSON/嵌套值转成驱动可绑定的标量。 */
105
+ export function normalizeSyncRowForRelational(row: any): Record<string, any> {
106
+ const out: Record<string, any> = {};
107
+ if (!row || typeof row !== 'object' || Array.isArray(row)) return out;
108
+ for (const [key, value] of Object.entries(row)) {
109
+ if (value === null || value === undefined) {
110
+ out[key] = null;
111
+ } else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
112
+ out[key] = value;
113
+ } else if (Buffer.isBuffer(value) || value instanceof Date) {
114
+ out[key] = value;
115
+ } else if (typeof (value as any).toHexString === 'function' || (value as any)._bsontype === 'ObjectId') {
116
+ out[key] = String(value);
117
+ } else if (typeof value === 'object') {
118
+ out[key] = JSON.stringify(value);
119
+ } else {
120
+ out[key] = String(value);
121
+ }
122
+ }
123
+ return out;
124
+ }
125
+
126
+ /** 同一批次按字段并集补齐,避免 bulkInsert 只取首行字段导致后续文档字段丢失。 */
127
+ export function normalizeSyncRowsForRelational(rows: any[]): Record<string, any>[] {
128
+ const normalized = (Array.isArray(rows) ? rows : []).map(normalizeSyncRowForRelational);
129
+ const keys: string[] = [];
130
+ const seen = new Set<string>();
131
+ for (const row of normalized) {
132
+ for (const key of Object.keys(row)) {
133
+ if (!seen.has(key)) {
134
+ seen.add(key);
135
+ keys.push(key);
136
+ }
137
+ }
138
+ }
139
+ return normalized.map((row) => {
140
+ const out: Record<string, any> = {};
141
+ for (const key of keys) out[key] = Object.prototype.hasOwnProperty.call(row, key) ? row[key] : null;
142
+ return out;
143
+ });
144
+ }
145
+
23
146
  /**
24
147
  * 数据库服务管理类
25
148
  * 负责根据数据库类型选择相应的服务实现
@@ -202,19 +325,22 @@ export class DatabaseService {
202
325
  /**
203
326
  * 目标态 TableSpec 的静态校验(建表/改表共用)
204
327
  */
205
- private validateTableSpec(spec: TableSpec): string {
328
+ private validateTableSpec(spec: TableSpec, requireColumns = true): string {
206
329
  if (!spec || typeof spec.name !== 'string' || !spec.name.trim()) {
207
330
  throw new Error('目标表名不能为空');
208
331
  }
209
- if (!Array.isArray(spec.columns) || spec.columns.length === 0) {
332
+ // 无模式方言(MongoDB 建集合)没有列定义,不强制要求至少一列
333
+ if (requireColumns && (!Array.isArray(spec.columns) || spec.columns.length === 0)) {
210
334
  throw new Error('目标结构至少需要一列');
211
335
  }
212
- const names = new Set(spec.columns.map((c) => c.name));
213
- if (names.size !== spec.columns.length) {
214
- throw new Error('目标结构存在重名列');
215
- }
216
- for (const pk of spec.primaryKey || []) {
217
- if (!names.has(pk)) throw new Error(`主键列 "${pk}" 不在目标结构中`);
336
+ if (Array.isArray(spec.columns) && spec.columns.length > 0) {
337
+ const names = new Set(spec.columns.map((c) => c.name));
338
+ if (names.size !== spec.columns.length) {
339
+ throw new Error('目标结构存在重名列');
340
+ }
341
+ for (const pk of spec.primaryKey || []) {
342
+ if (!names.has(pk)) throw new Error(`主键列 "${pk}" 不在目标结构中`);
343
+ }
218
344
  }
219
345
  return spec.name.trim();
220
346
  }
@@ -230,28 +356,35 @@ export class DatabaseService {
230
356
  spec: TableSpec,
231
357
  forceRefresh = false
232
358
  ) {
233
- const tableName = this.validateTableSpec(spec);
234
359
  const dataSource = await this.connectionService.getActiveConnection(connectionId, databaseName);
235
360
  const type = dataSource.options.type as string;
236
361
  const kind = getDialectInfo(type).kind;
237
362
  const dbService = this.getDatabaseService(type);
238
363
  const caps = ddlCapabilities(kind);
364
+ // 无模式方言(MongoDB):走驱动原生建集合——不生成 CREATE TABLE SQL,也不需要列定义
365
+ const driverCreate = caps.createStrategy === 'driver';
366
+ const tableName = this.validateTableSpec(spec, !driverCreate);
239
367
 
240
368
  // 方言不支持建表:作为计划内错误返回(而非抛出)——capabilities 仍要带回前端用于禁用 UI
241
369
  if (!caps.createTable) {
242
- return { dataSource, kind, caps, dbService, statements: [] as string[], error: `该数据库类型(${kind})不支持通过 SQL 建表` };
370
+ return { dataSource, kind, caps, dbService, tableName, statements: [] as string[], error: `该数据库类型(${kind})不支持通过 SQL 建表` };
243
371
  }
244
372
 
245
373
  // 重名检测:目标态与实时结构冲突(等价 409 语义)。
246
374
  // 预览走缓存避免每次输入都全量拉表;执行前必须 force 刷新,否则缓存会让重名检测失效。
247
375
  const tables = await this.getTableList(connectionId, databaseName, forceRefresh);
248
376
  if (tables.some((t) => tableNameEquals(kind, String(t?.name ?? ''), tableName))) {
249
- return { dataSource, kind, caps, dbService, statements: [] as string[], error: `表 "${tableName}" 已存在` };
377
+ return { dataSource, kind, caps, dbService, tableName, statements: [] as string[], error: `表 "${tableName}" 已存在` };
378
+ }
379
+
380
+ // 驱动路径:无列定义、无 SQL 语句,执行阶段直接调 dbService.createTable
381
+ if (driverCreate) {
382
+ return { dataSource, kind, caps, dbService, tableName, statements: [] as string[], error: '' };
250
383
  }
251
384
 
252
385
  const desired = canonicalizeTableSpec(spec);
253
386
  const statements = emitCreateDdl(kind, desired, { mssqlDatabase: databaseName });
254
- return { dataSource, kind, caps, dbService, statements, error: '' };
387
+ return { dataSource, kind, caps, dbService, tableName, statements, error: '' };
255
388
  }
256
389
 
257
390
  /**
@@ -266,13 +399,21 @@ export class DatabaseService {
266
399
  spec: TableSpec
267
400
  ): Promise<DdlPreview & { capabilities: DdlCapability }> {
268
401
  const plan = await this.buildCreatePlan(connectionId, databaseName, spec);
269
- if (plan.error) throw new Error(plan.error);
270
- const previewText = plan.statements.length > 0 ? plan.statements.join(';\n') + ';' : '';
402
+ // 注意:计划级非致命错误(方言不支持建表、表已存在)不能抛——否则 capabilities 不会返回,
403
+ // 前端无法据此禁用提交按钮。错误以注释形式写入预览,并由前端 submitDisabledHint 展示。
404
+ const previewText = plan.statements.length > 0
405
+ ? plan.statements.join(';\n') + ';'
406
+ : plan.error
407
+ ? `-- ${plan.error}`
408
+ : (plan.caps.createStrategy === 'driver'
409
+ ? `-- 创建集合 "${plan.tableName}"(无模式集合,不生成建表 SQL)`
410
+ : '');
271
411
  return {
272
412
  statements: plan.statements,
273
413
  preview: previewText,
274
414
  changeSet: null,
275
- capabilities: plan.caps
415
+ capabilities: plan.caps,
416
+ error: plan.error || null
276
417
  };
277
418
  }
278
419
 
@@ -283,10 +424,24 @@ export class DatabaseService {
283
424
  connectionId: string,
284
425
  databaseName: string,
285
426
  spec: TableSpec
286
- ): Promise<{ statements: string[] }> {
427
+ ): Promise<DdlExecuteResult> {
287
428
  // 执行前强制刷新表列表:重名检测必须基于最新结构,不能用预览的缓存
288
429
  const plan = await this.buildCreatePlan(connectionId, databaseName, spec, true);
289
430
  if (plan.error) throw new Error(plan.error);
431
+
432
+ // 无模式方言(MongoDB):没有建表 SQL,直接走驱动原生建集合
433
+ if (plan.caps.createStrategy === 'driver') {
434
+ try {
435
+ await plan.dbService.createTable(plan.dataSource, databaseName, { name: plan.tableName });
436
+ } catch (error) {
437
+ console.error('执行创建集合失败:', error);
438
+ throw new Error(`创建集合失败: ${error instanceof Error ? error.message : String(error)}`);
439
+ }
440
+ this.invalidateTableList(connectionId, databaseName); // 集合列表已变化
441
+ // native: 无 SQL 语句但集合已实际创建——前端据此与"无修改"区分
442
+ return { statements: plan.statements, native: true };
443
+ }
444
+
290
445
  if (plan.statements.length === 0) throw new Error('未能生成建表语句');
291
446
  try {
292
447
  await plan.dbService.executeBatchQuery(plan.dataSource, plan.statements, { useTransaction: true });
@@ -342,22 +497,30 @@ export class DatabaseService {
342
497
  error = `该数据库类型(${kind})不支持修改主键`;
343
498
  }
344
499
 
345
- // SQL Server:删除现有主键必须知道真实的约束名(PK__<table>__<hash>),回查系统表获取。
500
+ // SQL Server / SAP HANA:删除现有主键必须知道真实的约束名,回查系统表获取。
346
501
  // 仅在「已有主键需要 DROP」时才必需;纯新增主键的约束名由我们自己指定。
502
+ const needsPkDrop = !!changeSet.primaryKey && changeSet.primaryKey.from.length > 0;
347
503
  let mssqlPkConstraintName: string | undefined;
348
- if (!error && kind === 'mssql' && changeSet.primaryKey && changeSet.primaryKey.from.length > 0) {
504
+ let sapPkConstraintName: string | undefined;
505
+ if (!error && needsPkDrop && (kind === 'mssql' || kind === 'sap')) {
349
506
  const svc = dbService as any;
350
507
  if (typeof svc.getPrimaryKeyConstraintName === 'function') {
351
- mssqlPkConstraintName = (await svc.getPrimaryKeyConstraintName(dataSource, databaseName, tableName)) || undefined;
508
+ const constraintName = (await svc.getPrimaryKeyConstraintName(dataSource, databaseName, tableName)) || undefined;
509
+ if (kind === 'mssql') mssqlPkConstraintName = constraintName;
510
+ else sapPkConstraintName = constraintName;
352
511
  }
353
- if (!mssqlPkConstraintName) {
512
+ if (kind === 'mssql' ? !mssqlPkConstraintName : !sapPkConstraintName) {
354
513
  error = '无法定位该表的主键约束名,无法修改主键';
355
514
  }
356
515
  }
357
516
 
358
- const statements = error
359
- ? []
360
- : emitAlterDdl(kind, original, desired, mssqlPkConstraintName ? { mssqlPkConstraintName } : undefined);
517
+ const alterDdlOptions = mssqlPkConstraintName || sapPkConstraintName
518
+ ? {
519
+ ...(mssqlPkConstraintName ? { mssqlPkConstraintName } : {}),
520
+ ...(sapPkConstraintName ? { sapPkConstraintName } : {})
521
+ }
522
+ : undefined;
523
+ const statements = error ? [] : emitAlterDdl(kind, original, desired, alterDdlOptions);
361
524
  return {
362
525
  dataSource,
363
526
  kind,
@@ -384,13 +547,16 @@ export class DatabaseService {
384
547
  spec: TableSpec
385
548
  ): Promise<DdlPreview & { capabilities: DdlCapability }> {
386
549
  const plan = await this.buildAlterPlan(connectionId, databaseName, tableName, spec);
387
- if (plan.error) throw new Error(plan.error);
388
- const previewText = plan.statements.length > 0 ? plan.statements.join(';\n') + ';' : '';
550
+ // 与 previewCreateTable 同理:计划级非致命错误不抛,确保 capabilities 返回以驱动 UI 禁用。
551
+ const previewText = plan.statements.length > 0
552
+ ? plan.statements.join(';\n') + ';'
553
+ : (plan.error ? `-- ${plan.error}` : '');
389
554
  return {
390
555
  statements: plan.statements,
391
556
  preview: previewText,
392
557
  changeSet: plan.changeSet,
393
- capabilities: plan.caps
558
+ capabilities: plan.caps,
559
+ error: plan.error || null
394
560
  };
395
561
  }
396
562
 
@@ -512,31 +678,40 @@ export class DatabaseService {
512
678
 
513
679
  // 获取源表数据(分批获取,避免内存问题)
514
680
  const batchSize = 1000;
515
- let offset = 0;
681
+ let page = 1;
516
682
  let totalRows = 0;
517
683
 
518
684
  while (true) {
519
- const sourceData = await sourceService.query(sourceDataSource, {
520
- sql: `SELECT * FROM ${sourceService.quoteIdentifier(sourceTableName)} LIMIT ? OFFSET ?`,
521
- params: [batchSize, offset]
522
- });
685
+ // 统一走 getTableData 而不是自己拼 LIMIT/OFFSET:
686
+ // 各方言分页语法不同(MSSQL/Oracle 用 OFFSET/FETCH,MongoDB 根本没有 SQL),
687
+ // 这里复用各服务已实现的分页读取,避免同步功能只对 MySQL/SQLite 可用。
688
+ const sourceData = (await sourceService.getTableData(
689
+ sourceDataSource,
690
+ source.database,
691
+ sourceTableName,
692
+ page,
693
+ batchSize
694
+ )).data;
523
695
 
524
696
  if (sourceData.length === 0) {
525
697
  break;
526
698
  }
527
699
 
528
- // 插入数据到目标表
700
+ // 插入数据到目标表;文档库的 ObjectId/嵌套对象不能直接绑定给关系库驱动。
701
+ const rowsForTarget = targetService.getDatabaseType() === 'mongodb'
702
+ ? sourceData
703
+ : normalizeSyncRowsForRelational(sourceData);
529
704
  if (options.bulkInsert) {
530
- await targetService.bulkInsert(targetDataSource, targetDatabaseName, target.tableName, sourceData, options.overrideExisting);
705
+ await targetService.bulkInsert(targetDataSource, targetDatabaseName, target.tableName, rowsForTarget, options.overrideExisting);
531
706
  } else {
532
- for (const row of sourceData) {
707
+ for (const row of rowsForTarget) {
533
708
  await targetService.insertData(targetDataSource, targetDatabaseName, target.tableName, row, options.overrideExisting);
534
709
  }
535
710
  }
536
711
 
537
712
  totalRows += sourceData.length;
538
713
  tableSyncResult.messages.push(`已同步 ${totalRows} 行数据`);
539
- offset += batchSize;
714
+ page += 1;
540
715
  }
541
716
 
542
717
  tableSyncResult.dataSynced = true;
@@ -735,7 +910,10 @@ export class DatabaseService {
735
910
  supportJson: true,
736
911
  supportArrays: true,
737
912
  supportDocuments: true,
738
- supportNoSQL: true
913
+ supportNoSQL: true,
914
+ // 数据层能力:文档型、无 SQL 编辑器(前端据此切文档模式 UI)
915
+ dataModel: 'document',
916
+ supportSqlEditor: false
739
917
  }
740
918
  },
741
919
  {
@@ -743,7 +921,11 @@ export class DatabaseService {
743
921
  label: 'SAP HANA',
744
922
  icon: 'bi-database',
745
923
  defaultPort: 39013,
746
- description: 'SAP HANA内存数据库',
924
+ description: 'SAP HANA内存数据库(实验性)',
925
+ // 实验性:依赖未随默认依赖安装的 @sap/hana-client 驱动,且官方无免费 Docker 镜像,
926
+ // 本仓库尚未做端到端运行验证。驱动缺失时会给出明确的安装提示。
927
+ experimental: true,
928
+ driverPackage: '@sap/hana-client',
747
929
  features: {
748
930
  supportSchemas: true,
749
931
  supportProcedures: true,
@@ -789,7 +971,11 @@ export class DatabaseService {
789
971
  supportJson: false
790
972
  }
791
973
  }
792
- ];
974
+ ].map((t: any) => ({
975
+ ...t,
976
+ // 数据层能力默认值:关系型 + 支持 SQL;文档型(MongoDB)在自身 features 中覆盖
977
+ features: { dataModel: 'relational', supportSqlEditor: true, ...(t.features || {}) }
978
+ }));
793
979
  }
794
980
 
795
981
  /**
@@ -834,7 +1020,10 @@ export class DatabaseService {
834
1020
  async backupDatabase(connectionId: string, databaseName: string, options?: any): Promise<string> {
835
1021
  const dataSource = await this.connectionService.getActiveConnection(connectionId, databaseName);
836
1022
  const databaseService = this.getDatabaseService(dataSource.options.type as string);
837
- return databaseService.backupDatabase(dataSource, databaseName, options);
1023
+ const result = await databaseService.backupDatabase(dataSource, databaseName, options);
1024
+ const scheduleId = options?.scheduleId;
1025
+ // 让定时任务的 scheduleId 在返回提示中可见,便于定位是哪条计划产生的备份。
1026
+ return scheduleId ? `${result}[schedule:${scheduleId}]` : result;
838
1027
  }
839
1028
 
840
1029
  /**
@@ -869,69 +1058,127 @@ export class DatabaseService {
869
1058
  }
870
1059
 
871
1060
  /**
872
- * 优化数据库
1061
+ * 维护操作(OPTIMIZE / ANALYZE / REPAIR)的方言适配。
1062
+ *
1063
+ * 原先三个方法对所有连接都拼 MySQL 语法,PostgreSQL/SQLite/MongoDB 等
1064
+ * 必然报错;CLI 侧早已明确拒绝非 MySQL。这里按方言给出等价语句或清晰
1065
+ * 的「不支持」结果,而不是让驱动抛原始 SQL 错误。
873
1066
  */
874
- async optimizeDatabase(connectionId: string, databaseName: string): Promise<any> {
1067
+ private async runMaintenance(
1068
+ connectionId: string,
1069
+ databaseName: string,
1070
+ action: 'optimize' | 'analyze' | 'repair'
1071
+ ): Promise<any> {
875
1072
  const dataSource = await this.connectionService.getActiveConnection(connectionId, databaseName);
876
- const databaseService = this.getDatabaseService(dataSource.options.type as string);
877
-
1073
+ const type = String(dataSource.options.type || '');
1074
+ const info = getDialectInfo(type);
1075
+ const databaseService = this.getDatabaseService(type);
878
1076
  const tables = await databaseService.getTables(dataSource, databaseName);
879
- const results = [];
880
-
881
- for (const table of tables) {
1077
+ const q = (name: string) => quoteIdentifier(type, name);
1078
+ const unsupported = (table: string) => ({
1079
+ table,
1080
+ success: false,
1081
+ error: `${action} 暂不支持 ${info.label}(仅 MySQL / PostgreSQL / SQLite 提供等价操作)`
1082
+ });
1083
+
1084
+ // SQLite 的 VACUUM / integrity_check 作用于整库,不能按表重复执行
1085
+ if (info.kind === 'sqlite' && action !== 'analyze') {
1086
+ const sql = action === 'optimize' ? 'VACUUM' : 'PRAGMA integrity_check';
882
1087
  try {
883
- const result = await dataSource.query(`OPTIMIZE TABLE \`${table.name}\``);
884
- results.push({ table: table.name, success: true, result });
885
- } catch (error) {
886
- results.push({ table: table.name, success: false, error: error.message });
1088
+ const result = await dataSource.query(sql);
1089
+ return { results: [{ table: '*', success: true, sql, result }], dialect: info.kind };
1090
+ } catch (e: any) {
1091
+ return { results: [{ table: '*', success: false, sql, error: e?.message || String(e) }], dialect: info.kind };
887
1092
  }
888
1093
  }
889
-
890
- return { results };
891
- }
892
1094
 
893
- /**
894
- * 分析表
895
- */
896
- async analyzeTables(connectionId: string, databaseName: string): Promise<any> {
897
- const dataSource = await this.connectionService.getActiveConnection(connectionId, databaseName);
898
- const databaseService = this.getDatabaseService(dataSource.options.type as string);
899
-
900
- const tables = await databaseService.getTables(dataSource, databaseName);
901
- const results = [];
902
-
1095
+ const statementFor = (table: string): string | null => {
1096
+ switch (info.kind) {
1097
+ case 'mysql':
1098
+ return `${action.toUpperCase()} TABLE ${q(table)}`;
1099
+ case 'postgres':
1100
+ case 'cockroachdb':
1101
+ if (action === 'analyze') return `ANALYZE ${q(table)}`;
1102
+ if (action === 'optimize') return `VACUUM ANALYZE ${q(table)}`;
1103
+ return null;
1104
+ case 'sqlite':
1105
+ return action === 'analyze' ? `ANALYZE ${q(table)}` : null;
1106
+ default:
1107
+ return null;
1108
+ }
1109
+ };
1110
+
1111
+ const results: any[] = [];
903
1112
  for (const table of tables) {
1113
+ const sql = statementFor(table.name);
1114
+ if (!sql) {
1115
+ results.push(unsupported(table.name));
1116
+ continue;
1117
+ }
904
1118
  try {
905
- const result = await dataSource.query(`ANALYZE TABLE \`${table.name}\``);
906
- results.push({ table: table.name, success: true, result });
907
- } catch (error) {
908
- results.push({ table: table.name, success: false, error: error.message });
1119
+ const result = await dataSource.query(sql);
1120
+ results.push({ table: table.name, success: true, sql, result });
1121
+ } catch (e: any) {
1122
+ results.push({ table: table.name, success: false, sql, error: e?.message || String(e) });
909
1123
  }
910
1124
  }
911
-
912
- return { results };
1125
+ return { results, dialect: info.kind };
913
1126
  }
914
1127
 
915
1128
  /**
916
- * 修复表
1129
+ * 批量导入:文件解析在浏览器完成,这里接收行数组并走各方言 bulkInsert。
1130
+ * 按表结构过滤未知列并做轻量类型转换(CSV 里一切都是字符串)。
917
1131
  */
918
- async repairTables(connectionId: string, databaseName: string): Promise<any> {
1132
+ async importData(
1133
+ connectionId: string,
1134
+ databaseName: string,
1135
+ tableName: string,
1136
+ rows: any[]
1137
+ ): Promise<{ imported: number; table: string }> {
1138
+ if (!Array.isArray(rows)) throw new Error('rows must be an array');
919
1139
  const dataSource = await this.connectionService.getActiveConnection(connectionId, databaseName);
920
- const databaseService = this.getDatabaseService(dataSource.options.type as string);
921
-
922
- const tables = await databaseService.getTables(dataSource, databaseName);
923
- const results = [];
924
-
925
- for (const table of tables) {
926
- try {
927
- const result = await dataSource.query(`REPAIR TABLE \`${table.name}\``);
928
- results.push({ table: table.name, success: true, result });
929
- } catch (error) {
930
- results.push({ table: table.name, success: false, error: error.message });
931
- }
1140
+ const type = String(dataSource.options.type || '');
1141
+ const service = this.getDatabaseService(type);
1142
+
1143
+ // MongoDB 是 schemaless:空集合 getColumns 返回空,不能按列归一化把全部文档过滤掉。
1144
+ if (type === 'mongodb') {
1145
+ const docs = rows.filter((row) => row && typeof row === 'object' && !Array.isArray(row));
1146
+ if (docs.length === 0) return { imported: 0, table: tableName };
1147
+ await service.bulkInsert(dataSource, databaseName, tableName, docs);
1148
+ return { imported: docs.length, table: tableName };
932
1149
  }
933
-
934
- return { results };
1150
+
1151
+ const columns = await service.getColumns(dataSource, databaseName, tableName);
1152
+ const knownNames = new Set(
1153
+ (Array.isArray(columns) ? columns : [])
1154
+ .map((column: any) => String(column?.name ?? '').trim())
1155
+ .filter(Boolean)
1156
+ );
1157
+ // 纯函数保留所有输入行的列全集;导入时仍需跳过完全不含已知列的空行。
1158
+ const clean = normalizeImportRows(rows, columns).filter((_, index) => {
1159
+ const row = rows[index];
1160
+ return !!row && typeof row === 'object' &&
1161
+ Object.keys(row).some((key) => knownNames.has(key.trim()));
1162
+ });
1163
+
1164
+ if (clean.length === 0) return { imported: 0, table: tableName };
1165
+ await service.bulkInsert(dataSource, databaseName, tableName, clean);
1166
+ return { imported: clean.length, table: tableName };
1167
+ }
1168
+
1169
+ /** 优化数据库 */
1170
+ async optimizeDatabase(connectionId: string, databaseName: string): Promise<any> {
1171
+ return this.runMaintenance(connectionId, databaseName, 'optimize');
1172
+ }
1173
+
1174
+ /** 分析表 */
1175
+ async analyzeTables(connectionId: string, databaseName: string): Promise<any> {
1176
+ return this.runMaintenance(connectionId, databaseName, 'analyze');
1177
+ }
1178
+
1179
+ /** 修复表 */
1180
+ async repairTables(connectionId: string, databaseName: string): Promise<any> {
1181
+ return this.runMaintenance(connectionId, databaseName, 'repair');
935
1182
  }
936
1183
 
937
1184
  /**