fdb2 1.0.0

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 (125) hide show
  1. package/.dockerignore +21 -0
  2. package/.editorconfig +11 -0
  3. package/.eslintrc.cjs +14 -0
  4. package/.eslintrc.json +7 -0
  5. package/.prettierrc.js +3 -0
  6. package/.tpl.env +22 -0
  7. package/README.md +260 -0
  8. package/bin/build.sh +28 -0
  9. package/bin/deploy.sh +8 -0
  10. package/bin/dev.sh +10 -0
  11. package/bin/docker/.env +4 -0
  12. package/bin/docker/dev-docker-compose.yml +43 -0
  13. package/bin/docker/dev.Dockerfile +24 -0
  14. package/bin/docker/prod-docker-compose.yml +17 -0
  15. package/bin/docker/prod.Dockerfile +29 -0
  16. package/bin/fdb2.js +142 -0
  17. package/data/connections.demo.json +32 -0
  18. package/env.d.ts +1 -0
  19. package/nw-build.js +120 -0
  20. package/nw-dev.js +65 -0
  21. package/package.json +114 -0
  22. package/public/favicon.ico +0 -0
  23. package/public/index.html +9 -0
  24. package/public/modules/header.tpl +14 -0
  25. package/public/modules/initial_state.tpl +55 -0
  26. package/server/index.ts +677 -0
  27. package/server/model/connection.entity.ts +66 -0
  28. package/server/model/database.entity.ts +246 -0
  29. package/server/service/connection.service.ts +334 -0
  30. package/server/service/database/base.service.ts +363 -0
  31. package/server/service/database/database.service.ts +510 -0
  32. package/server/service/database/index.ts +7 -0
  33. package/server/service/database/mssql.service.ts +723 -0
  34. package/server/service/database/mysql.service.ts +761 -0
  35. package/server/service/database/oracle.service.ts +839 -0
  36. package/server/service/database/postgres.service.ts +744 -0
  37. package/server/service/database/sqlite.service.ts +559 -0
  38. package/server/service/session.service.ts +158 -0
  39. package/server.js +128 -0
  40. package/src/adapter/ajax.ts +135 -0
  41. package/src/assets/base.css +1 -0
  42. package/src/assets/database.css +950 -0
  43. package/src/assets/images/collapse.png +0 -0
  44. package/src/assets/images/no-login.png +0 -0
  45. package/src/assets/images/svg/illustrations/illustration-1.svg +1 -0
  46. package/src/assets/images/svg/illustrations/illustration-2.svg +2 -0
  47. package/src/assets/images/svg/illustrations/illustration-3.svg +50 -0
  48. package/src/assets/images/svg/illustrations/illustration-4.svg +1 -0
  49. package/src/assets/images/svg/illustrations/illustration-5.svg +73 -0
  50. package/src/assets/images/svg/illustrations/illustration-6.svg +89 -0
  51. package/src/assets/images/svg/illustrations/illustration-7.svg +39 -0
  52. package/src/assets/images/svg/illustrations/illustration-8.svg +1 -0
  53. package/src/assets/images/svg/separators/curve-2.svg +3 -0
  54. package/src/assets/images/svg/separators/curve.svg +3 -0
  55. package/src/assets/images/svg/separators/line.svg +3 -0
  56. package/src/assets/images/theme/light/screen-1-1000x800.jpg +0 -0
  57. package/src/assets/images/theme/light/screen-2-1000x800.jpg +0 -0
  58. package/src/assets/login/bg.jpg +0 -0
  59. package/src/assets/login/bg.png +0 -0
  60. package/src/assets/login/left.jpg +0 -0
  61. package/src/assets/logo.svg +73 -0
  62. package/src/assets/logo.webp +0 -0
  63. package/src/assets/main.css +1 -0
  64. package/src/base/config.ts +20 -0
  65. package/src/base/detect.ts +134 -0
  66. package/src/base/entity.ts +92 -0
  67. package/src/base/eventBus.ts +37 -0
  68. package/src/base//345/237/272/347/241/200/345/261/202.md +7 -0
  69. package/src/components/connection-editor/index.vue +590 -0
  70. package/src/components/dataGrid/index.vue +105 -0
  71. package/src/components/dataGrid/pagination.vue +106 -0
  72. package/src/components/loading/index.vue +43 -0
  73. package/src/components/modal/index.ts +181 -0
  74. package/src/components/modal/index.vue +560 -0
  75. package/src/components/toast/index.ts +44 -0
  76. package/src/components/toast/toast.vue +58 -0
  77. package/src/components/user/name.vue +104 -0
  78. package/src/components/user/selector.vue +416 -0
  79. package/src/domain/SysConfig.ts +74 -0
  80. package/src/platform/App.vue +8 -0
  81. package/src/platform/database/components/connection-detail.vue +1154 -0
  82. package/src/platform/database/components/data-editor.vue +478 -0
  83. package/src/platform/database/components/data-import-export.vue +1602 -0
  84. package/src/platform/database/components/database-detail.vue +1173 -0
  85. package/src/platform/database/components/database-monitor.vue +1086 -0
  86. package/src/platform/database/components/db-tools.vue +577 -0
  87. package/src/platform/database/components/query-history.vue +1349 -0
  88. package/src/platform/database/components/sql-executor.vue +738 -0
  89. package/src/platform/database/components/sql-query-editor.vue +1046 -0
  90. package/src/platform/database/components/table-detail.vue +1376 -0
  91. package/src/platform/database/components/table-editor.vue +690 -0
  92. package/src/platform/database/explorer.vue +1840 -0
  93. package/src/platform/database/index.vue +1193 -0
  94. package/src/platform/database/layout.vue +367 -0
  95. package/src/platform/database/router.ts +37 -0
  96. package/src/platform/database/styles/common.scss +602 -0
  97. package/src/platform/database/types/common.ts +445 -0
  98. package/src/platform/database/utils/export.ts +232 -0
  99. package/src/platform/database/utils/helpers.ts +437 -0
  100. package/src/platform/index.ts +33 -0
  101. package/src/platform/router.ts +41 -0
  102. package/src/service/base.ts +128 -0
  103. package/src/service/database.ts +500 -0
  104. package/src/service/login.ts +121 -0
  105. package/src/shims-vue.d.ts +7 -0
  106. package/src/stores/connection.ts +266 -0
  107. package/src/stores/session.ts +87 -0
  108. package/src/typings/database-types.ts +413 -0
  109. package/src/typings/database.ts +364 -0
  110. package/src/typings/global.d.ts +58 -0
  111. package/src/typings/pinia.d.ts +8 -0
  112. package/src/utils/clipboard.ts +30 -0
  113. package/src/utils/database-types.ts +243 -0
  114. package/src/utils/modal.ts +124 -0
  115. package/src/utils/request.ts +55 -0
  116. package/src/utils/sleep.ts +4 -0
  117. package/src/utils/toast.ts +73 -0
  118. package/src/utils/util.ts +171 -0
  119. package/src/utils/xlsx.ts +228 -0
  120. package/tsconfig.json +33 -0
  121. package/tsconfig.server.json +19 -0
  122. package/view/index.html +9 -0
  123. package/view/modules/header.tpl +14 -0
  124. package/view/modules/initial_state.tpl +20 -0
  125. package/vite.config.ts +384 -0
@@ -0,0 +1,839 @@
1
+ import { DataSource } from 'typeorm';
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+ import { execSync } from 'child_process';
5
+ import { BaseDatabaseService } from './base.service';
6
+ import {
7
+ TableEntity,
8
+ ColumnEntity,
9
+ IndexEntity,
10
+ ForeignKeyEntity
11
+ } from '../../model/database.entity';
12
+
13
+ /**
14
+ * Oracle数据库服务实现
15
+ */
16
+ export class OracleService extends BaseDatabaseService {
17
+
18
+ getDatabaseType(): string {
19
+ return 'oracle';
20
+ }
21
+
22
+ /**
23
+ * 获取Oracle数据库列表(用户schema)
24
+ */
25
+ async getDatabases(dataSource: DataSource): Promise<string[]> {
26
+ const result = await dataSource.query(`
27
+ SELECT username as name
28
+ FROM all_users
29
+ WHERE username NOT IN ('SYS', 'SYSTEM', 'XDB', 'OUTLN')
30
+ ORDER BY username
31
+ `);
32
+ return result.map((row: any) => row.name);
33
+ }
34
+
35
+ /**
36
+ * 获取Oracle表列表
37
+ */
38
+ async getTables(dataSource: DataSource, database: string): Promise<TableEntity[]> {
39
+ const result = await dataSource.query(`
40
+ SELECT
41
+ table_name as name,
42
+ 'TABLE' as type
43
+ FROM all_tables
44
+ WHERE owner = ?
45
+ AND table_name NOT LIKE 'BIN$%'
46
+ AND temporary = 'N'
47
+ ORDER BY table_name
48
+ `, [database.toUpperCase()]);
49
+
50
+ // 获取表的统计信息
51
+ const tablesWithStats = [];
52
+ for (const table of result) {
53
+ const stats = await this.getTableStats(dataSource, database, table.name);
54
+ tablesWithStats.push({
55
+ name: table.name,
56
+ type: table.type,
57
+ rowCount: stats.rowCount,
58
+ dataSize: stats.dataSize,
59
+ indexSize: stats.indexSize
60
+ });
61
+ }
62
+
63
+ return tablesWithStats;
64
+ }
65
+
66
+ /**
67
+ * 获取Oracle列信息
68
+ */
69
+ async getColumns(dataSource: DataSource, database: string, table: string): Promise<ColumnEntity[]> {
70
+ // 使用兼容的SQL查询,移除可能不兼容的字段
71
+ const result = await dataSource.query(`
72
+ SELECT
73
+ column_name as name,
74
+ data_type as type,
75
+ data_length as length,
76
+ nullable as nullable,
77
+ data_default as defaultValue
78
+ FROM all_tab_columns
79
+ WHERE owner = ?
80
+ AND table_name = ?
81
+ ORDER BY column_id
82
+ `, [
83
+ database.toUpperCase(),
84
+ table.toUpperCase()
85
+ ]);
86
+
87
+ // 获取主键信息
88
+ const primaryKeys = await this.getPrimaryKeys(dataSource, database, table);
89
+
90
+ // 获取序列信息(Oracle使用序列实现自增)
91
+ const sequenceColumns = await this.getSequenceColumns(dataSource, database, table);
92
+
93
+ // 从data_type中解析精度信息
94
+ return result.map((row: any) => {
95
+ const dataType = row.type || '';
96
+ let precision = undefined;
97
+ let scale = undefined;
98
+
99
+ // 解析DECIMAL(M,D)或NUMBER(M,D)类型的精度
100
+ const decimalMatch = dataType.match(/(DECIMAL|NUMBER)\s*\(\s*(\d+)\s*(,\s*(\d+)\s*)?\s*\)/i);
101
+ if (decimalMatch) {
102
+ precision = parseInt(decimalMatch[2]);
103
+ if (decimalMatch[3]) {
104
+ scale = parseInt(decimalMatch[3].replace(/\D/g, ''));
105
+ }
106
+ }
107
+
108
+ return {
109
+ name: row.name,
110
+ type: row.type + (row.length ? `(${row.length})` : ''),
111
+ nullable: row.nullable === 'Y',
112
+ defaultValue: row.defaultValue,
113
+ isPrimary: primaryKeys.includes(row.name),
114
+ isAutoIncrement: sequenceColumns.includes(row.name),
115
+ length: row.length,
116
+ precision: precision,
117
+ scale: scale
118
+ };
119
+ });
120
+ }
121
+
122
+ /**
123
+ * 获取Oracle索引信息
124
+ */
125
+ async getIndexes(dataSource: DataSource, database: string, table: string): Promise<IndexEntity[]> {
126
+ const result = await dataSource.query(`
127
+ SELECT DISTINCT
128
+ i.index_name as name,
129
+ DECODE(i.uniqueness, 'UNIQUE', 'UNIQUE INDEX', 'INDEX') as type,
130
+ ic.column_name as column
131
+ FROM all_indexes i
132
+ JOIN all_ind_columns ic ON i.index_name = ic.index_name
133
+ WHERE i.table_owner = ?
134
+ AND i.table_name = ?
135
+ AND i.index_name NOT IN (SELECT constraint_name
136
+ FROM all_constraints
137
+ WHERE constraint_type = 'P'
138
+ AND table_owner = ?)
139
+ ORDER BY i.index_name, ic.column_position
140
+ `, [
141
+ database.toUpperCase(),
142
+ table.toUpperCase(),
143
+ database.toUpperCase()
144
+ ]);
145
+
146
+ // 按索引名分组
147
+ const indexMap = new Map<string, IndexEntity>();
148
+ result.forEach((row: any) => {
149
+ if (!indexMap.has(row.name)) {
150
+ indexMap.set(row.name, {
151
+ name: row.name,
152
+ type: row.type,
153
+ columns: [],
154
+ unique: row.type.includes('UNIQUE')
155
+ });
156
+ }
157
+ indexMap.get(row.name)!.columns.push(row.column);
158
+ });
159
+
160
+ return Array.from(indexMap.values());
161
+ }
162
+
163
+ /**
164
+ * 获取Oracle外键信息
165
+ */
166
+ async getForeignKeys(dataSource: DataSource, database: string, table: string): Promise<ForeignKeyEntity[]> {
167
+ const result = await dataSource.query(`
168
+ SELECT
169
+ c.constraint_name as name,
170
+ cc.column_name as column,
171
+ r.table_name as referencedTable,
172
+ rc.column_name as referencedColumn,
173
+ c.delete_rule as onDelete
174
+ FROM all_constraints c
175
+ JOIN all_cons_columns cc ON c.constraint_name = cc.constraint_name
176
+ JOIN all_constraints r ON c.r_constraint_name = r.constraint_name
177
+ JOIN all_cons_columns rc ON r.constraint_name = rc.constraint_name AND cc.position = rc.position
178
+ WHERE c.constraint_type = 'R'
179
+ AND c.owner = ?
180
+ AND c.table_name = ?
181
+ `, [
182
+ database.toUpperCase(),
183
+ table.toUpperCase()
184
+ ]);
185
+
186
+ return result.map((row: any) => ({
187
+ name: row.name,
188
+ column: row.column,
189
+ referencedTable: row.referencedTable,
190
+ referencedColumn: row.referencedColumn,
191
+ onDelete: row.onDelete || 'NO ACTION',
192
+ onUpdate: 'NO ACTION' // Oracle不支持ON UPDATE
193
+ }));
194
+ }
195
+
196
+ /**
197
+ * 获取Oracle数据库大小(用户schema大小)
198
+ */
199
+ async getDatabaseSize(dataSource: DataSource, database: string): Promise<number> {
200
+ const result = await dataSource.query(`
201
+ SELECT SUM(bytes) as size
202
+ FROM user_segments
203
+ `);
204
+ return result[0]?.size || 0;
205
+ }
206
+
207
+ /**
208
+ * 获取表统计信息
209
+ */
210
+ private async getTableStats(dataSource: DataSource, database: string, table: string): Promise<any> {
211
+ try {
212
+ const result = await dataSource.query(`
213
+ SELECT
214
+ num_rows as rowCount,
215
+ (SELECT SUM(bytes) FROM user_segments WHERE segment_name = ?) as dataSize
216
+ FROM all_tables
217
+ WHERE owner = ? AND table_name = ?
218
+ `, [
219
+ table.toUpperCase(),
220
+ database.toUpperCase(),
221
+ table.toUpperCase()
222
+ ]);
223
+
224
+ return {
225
+ rowCount: result[0]?.rowCount || 0,
226
+ dataSize: result[0]?.dataSize || 0,
227
+ indexSize: 0 // Oracle索引大小计算较复杂,这里简化处理
228
+ };
229
+ } catch (error) {
230
+ // 如果没有统计信息,返回默认值
231
+ return {
232
+ rowCount: 0,
233
+ dataSize: 0,
234
+ indexSize: 0
235
+ };
236
+ }
237
+ }
238
+
239
+ /**
240
+ * 获取主键信息
241
+ */
242
+ private async getPrimaryKeys(dataSource: DataSource, database: string, table: string): Promise<string[]> {
243
+ const result = await dataSource.query(`
244
+ SELECT column_name
245
+ FROM all_cons_columns cc
246
+ JOIN all_constraints c ON cc.constraint_name = c.constraint_name
247
+ WHERE c.constraint_type = 'P'
248
+ AND c.owner = ?
249
+ AND c.table_name = ?
250
+ ORDER BY cc.position
251
+ `, [
252
+ database.toUpperCase(),
253
+ table.toUpperCase()
254
+ ]);
255
+ return result.map((row: any) => row.column_name);
256
+ }
257
+
258
+ /**
259
+ * 获取Oracle序列信息(用于检测自增列)
260
+ */
261
+ private async getSequenceColumns(dataSource: DataSource, database: string, table: string): Promise<string[]> {
262
+ try {
263
+ const result = await dataSource.query(`
264
+ SELECT acc.column_name
265
+ FROM all_tab_columns acc
266
+ JOIN all_triggers at ON acc.table_name = at.table_name
267
+ AND acc.owner = at.owner
268
+ JOIN all_sequences seq ON at.trigger_name LIKE seq.sequence_name || '%'
269
+ WHERE acc.owner = ?
270
+ AND acc.table_name = ?
271
+ AND acc.data_default IS NOT NULL
272
+ AND acc.data_default LIKE seq.sequence_name || '.nextval'
273
+ `, [
274
+ database.toUpperCase(),
275
+ table.toUpperCase()
276
+ ]);
277
+ return result.map((row: any) => row.column_name);
278
+ } catch (error) {
279
+ // 如果查询失败,返回空数组
280
+ return [];
281
+ }
282
+ }
283
+
284
+ /**
285
+ * Oracle的标识符引用方式
286
+ */
287
+ public quoteIdentifier(identifier: string): string {
288
+ return `"${identifier.toUpperCase()}"`;
289
+ }
290
+
291
+ /**
292
+ * 获取Oracle视图列表
293
+ */
294
+ async getViews(dataSource: DataSource, database: string): Promise<any[]> {
295
+ const result = await dataSource.query(`
296
+ SELECT
297
+ view_name as name,
298
+ '' as comment
299
+ FROM all_views
300
+ WHERE owner = ?
301
+ ORDER BY view_name
302
+ `, [database.toUpperCase()]);
303
+
304
+ return result.map((row: any) => ({
305
+ name: row.name,
306
+ comment: row.comment || '',
307
+ schemaName: database
308
+ }));
309
+ }
310
+
311
+ /**
312
+ * 获取Oracle视图定义
313
+ */
314
+ async getViewDefinition(dataSource: DataSource, database: string, viewName: string): Promise<string> {
315
+ const result = await dataSource.query(`
316
+ SELECT text as definition
317
+ FROM all_views
318
+ WHERE owner = ?
319
+ AND view_name = ?
320
+ `, [database.toUpperCase(), viewName.toUpperCase()]);
321
+
322
+ return result[0]?.definition || '';
323
+ }
324
+
325
+ /**
326
+ * 获取Oracle存储过程列表
327
+ */
328
+ async getProcedures(dataSource: DataSource, database: string): Promise<any[]> {
329
+ const result = await dataSource.query(`
330
+ SELECT
331
+ object_name as name,
332
+ '' as comment,
333
+ 'PROCEDURE' as type,
334
+ '' as returnType,
335
+ 'PL/SQL' as language
336
+ FROM all_objects
337
+ WHERE owner = ?
338
+ AND object_type IN ('PROCEDURE', 'FUNCTION')
339
+ AND status = 'VALID'
340
+ ORDER BY object_name
341
+ `, [database.toUpperCase()]);
342
+
343
+ return result.map((row: any) => ({
344
+ name: row.name,
345
+ comment: row.comment || '',
346
+ type: row.type,
347
+ returnType: row.returnType || '',
348
+ language: row.language || 'PL/SQL'
349
+ }));
350
+ }
351
+
352
+ /**
353
+ * 获取Oracle存储过程定义
354
+ */
355
+ async getProcedureDefinition(dataSource: DataSource, database: string, procedureName: string): Promise<string> {
356
+ const result = await dataSource.query(`
357
+ SELECT text as definition
358
+ FROM all_source
359
+ WHERE owner = ?
360
+ AND name = ?
361
+ ORDER BY line
362
+ `, [database.toUpperCase(), procedureName.toUpperCase()]);
363
+
364
+ return result.map((row: any) => row.definition).join('\n') || '';
365
+ }
366
+
367
+ /**
368
+ * 创建Oracle数据库
369
+ */
370
+ async createDatabase(dataSource: DataSource, databaseName: string, options?: any): Promise<void> {
371
+ // Oracle数据库创建比较复杂,通常需要DBA权限
372
+ // 这里提供基本的创建语法
373
+ let sql = `CREATE DATABASE ${this.quoteIdentifier(databaseName)}`;
374
+
375
+ if (options) {
376
+ const clauses = [];
377
+
378
+ if (options.user) {
379
+ clauses.push(`USER ${options.user}`);
380
+ }
381
+
382
+ if (options.password) {
383
+ clauses.push(`IDENTIFIED BY ${options.password}`);
384
+ }
385
+
386
+ if (options.defaultTablespace) {
387
+ clauses.push(`DEFAULT TABLESPACE ${options.defaultTablespace}`);
388
+ }
389
+
390
+ if (options.tempTablespace) {
391
+ clauses.push(`TEMPORARY TABLESPACE ${options.tempTablespace}`);
392
+ }
393
+
394
+ if (options.datafile) {
395
+ clauses.push(`DATAFILE '${options.datafile}'`);
396
+ }
397
+
398
+ if (options.size) {
399
+ clauses.push(`SIZE ${options.size}`);
400
+ }
401
+
402
+ if (options.autoExtend) {
403
+ clauses.push(`AUTOEXTEND ON`);
404
+ }
405
+
406
+ if (clauses.length > 0) {
407
+ sql += ' ' + clauses.join(' ');
408
+ }
409
+ }
410
+
411
+ await dataSource.query(sql);
412
+ }
413
+
414
+ /**
415
+ * 删除Oracle数据库
416
+ */
417
+ async dropDatabase(dataSource: DataSource, databaseName: string): Promise<void> {
418
+ const sql = `DROP DATABASE ${this.quoteIdentifier(databaseName)}`;
419
+ await dataSource.query(sql);
420
+ }
421
+
422
+ /**
423
+ * 导出数据库架构
424
+ */
425
+ async exportSchema(dataSource: DataSource, databaseName: string): Promise<string> {
426
+ // 获取所有表
427
+ const tables = await this.getTables(dataSource, databaseName);
428
+ let schemaSql = `-- 数据库架构导出 - ${databaseName}\n`;
429
+ schemaSql += `-- 导出时间: ${new Date().toISOString()}\n\n`;
430
+
431
+ // 为每个表生成CREATE TABLE语句
432
+ for (const table of tables) {
433
+ // 获取表结构
434
+ const columns = await this.getColumns(dataSource, databaseName, table.name);
435
+ const indexes = await this.getIndexes(dataSource, databaseName, table.name);
436
+ const foreignKeys = await this.getForeignKeys(dataSource, databaseName, table.name);
437
+
438
+ // 生成CREATE TABLE语句
439
+ schemaSql += `-- 表结构: ${table.name}\n`;
440
+ schemaSql += `CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(table.name)} (\n`;
441
+
442
+ // 添加列定义
443
+ const columnDefinitions = columns.map(column => {
444
+ let definition = ` ${this.quoteIdentifier(column.name)} ${column.type}`;
445
+ if (!column.nullable) definition += ' NOT NULL';
446
+ if (column.defaultValue !== undefined) {
447
+ // 特殊关键字处理
448
+ const upperDefault = column.defaultValue.toString().toUpperCase();
449
+ if (upperDefault === 'CURRENT_TIMESTAMP' || upperDefault === 'NOW()' || upperDefault === 'CURRENT_DATE') {
450
+ definition += ` DEFAULT ${upperDefault}`;
451
+ } else {
452
+ definition += ` DEFAULT ${column.defaultValue === null ? 'NULL' : `'${column.defaultValue}'`}`;
453
+ }
454
+ }
455
+ if (column.isAutoIncrement) definition += ' GENERATED ALWAYS AS IDENTITY';
456
+ return definition;
457
+ });
458
+
459
+ // 添加主键
460
+ const primaryKeyColumns = columns.filter(column => column.isPrimary);
461
+ if (primaryKeyColumns.length > 0) {
462
+ const primaryKeyNames = primaryKeyColumns.map(column => this.quoteIdentifier(column.name)).join(', ');
463
+ columnDefinitions.push(` PRIMARY KEY (${primaryKeyNames})`);
464
+ }
465
+
466
+ schemaSql += columnDefinitions.join(',\n');
467
+ schemaSql += '\n);\n\n';
468
+
469
+ // 添加索引
470
+ for (const index of indexes) {
471
+ if (index.type === 'PRIMARY' || index.name.toUpperCase() === 'PRIMARY') continue; // 跳过主键索引
472
+ schemaSql += `-- 索引: ${index.name} on ${table.name}\n`;
473
+ schemaSql += `CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX ${this.quoteIdentifier(index.name)} ON ${this.quoteIdentifier(table.name)} (${index.columns.map(col => this.quoteIdentifier(col)).join(', ')})\n`;
474
+ }
475
+
476
+ if (indexes.length > 0) schemaSql += '\n';
477
+
478
+ // 添加外键
479
+ for (const foreignKey of foreignKeys) {
480
+ schemaSql += `-- 外键: ${foreignKey.name} on ${table.name}\n`;
481
+ schemaSql += `ALTER TABLE ${this.quoteIdentifier(table.name)} ADD CONSTRAINT ${this.quoteIdentifier(foreignKey.name)} FOREIGN KEY (${this.quoteIdentifier(foreignKey.column)}) REFERENCES ${this.quoteIdentifier(foreignKey.referencedTable)} (${this.quoteIdentifier(foreignKey.referencedColumn)})${foreignKey.onDelete ? ` ON DELETE ${foreignKey.onDelete}` : ''}${foreignKey.onUpdate ? ` ON UPDATE ${foreignKey.onUpdate}` : ''};\n`;
482
+ }
483
+
484
+ if (foreignKeys.length > 0) schemaSql += '\n';
485
+ }
486
+
487
+ return schemaSql;
488
+ }
489
+
490
+ /**
491
+ * 查看数据库日志
492
+ */
493
+ async viewLogs(dataSource: DataSource, database?: string, limit: number = 100): Promise<any[]> {
494
+ // Oracle查看日志
495
+ try {
496
+ // 尝试查看Oracle警告日志
497
+ const logs = await dataSource.query(`
498
+ SELECT * FROM v$diag_info WHERE name LIKE '%Log%'
499
+ `);
500
+ return logs;
501
+ } catch (error) {
502
+ try {
503
+ // 尝试查看Oracle系统事件
504
+ const logs = await dataSource.query(`
505
+ SELECT * FROM v$event_name WHERE name LIKE '%log%' LIMIT ${limit}
506
+ `);
507
+ return logs;
508
+ } catch (e) {
509
+ return [{ message: '无法获取Oracle日志,请确保具有适当的权限' }];
510
+ }
511
+ }
512
+ }
513
+
514
+ /**
515
+ * 备份数据库
516
+ */
517
+ async backupDatabase(dataSource: DataSource, databaseName: string, options?: any): Promise<string> {
518
+ // Oracle备份数据库
519
+ try {
520
+ // 使用RMAN命令备份
521
+ const backupPath = options?.path || path.join(__dirname, '..', '..', 'backups');
522
+
523
+ // 确保备份目录存在
524
+ if (!fs.existsSync(backupPath)) {
525
+ fs.mkdirSync(backupPath, { recursive: true });
526
+ }
527
+
528
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
529
+ const backupFile = path.join(backupPath, `${databaseName}_${timestamp}.bkp`);
530
+
531
+ // 执行RMAN备份命令
532
+ const connectionOptions = dataSource.options as any;
533
+ const host = connectionOptions.host || 'localhost';
534
+ const port = connectionOptions.port || 1521;
535
+ const user = connectionOptions.username;
536
+ const password = connectionOptions.password;
537
+ const serviceName = connectionOptions.database || databaseName;
538
+
539
+ // 构建RMAN命令
540
+ const rmanCommand = `rman target ${user}/${password}@${host}:${port}/${serviceName} cmdfile=${backupPath}/backup.rman`;
541
+
542
+ // 创建RMAN命令文件
543
+ const rmanScript = `BACKUP DATABASE TO DISK '${backupFile}';`;
544
+ fs.writeFileSync(path.join(backupPath, 'backup.rman'), rmanScript);
545
+
546
+ // 执行命令
547
+ execSync(rmanCommand);
548
+
549
+ return `备份成功:${backupFile}`;
550
+ } catch (error) {
551
+ console.error('Oracle备份失败:', error);
552
+ throw new Error(`备份失败: ${error.message}`);
553
+ }
554
+ }
555
+
556
+ /**
557
+ * 恢复数据库
558
+ */
559
+ async restoreDatabase(dataSource: DataSource, databaseName: string, filePath: string, options?: any): Promise<void> {
560
+ // Oracle恢复数据库
561
+ try {
562
+ // 使用RMAN命令恢复
563
+ const backupPath = path.dirname(filePath);
564
+
565
+ // 执行RMAN恢复命令
566
+ const connectionOptions = dataSource.options as any;
567
+ const host = connectionOptions.host || 'localhost';
568
+ const port = connectionOptions.port || 1521;
569
+ const user = connectionOptions.username;
570
+ const password = connectionOptions.password;
571
+ const serviceName = connectionOptions.database || databaseName;
572
+
573
+ // 构建RMAN命令
574
+ const rmanCommand = `rman target ${user}/${password}@${host}:${port}/${serviceName} cmdfile=${backupPath}/restore.rman`;
575
+
576
+ // 创建RMAN命令文件
577
+ const rmanScript = `
578
+ SHUTDOWN IMMEDIATE;
579
+ STARTUP MOUNT;
580
+ RESTORE DATABASE FROM DISK '${filePath}';
581
+ RECOVER DATABASE;
582
+ ALTER DATABASE OPEN;
583
+ `;
584
+ fs.writeFileSync(path.join(backupPath, 'restore.rman'), rmanScript);
585
+
586
+ // 执行命令
587
+ execSync(rmanCommand);
588
+ } catch (error) {
589
+ console.error('Oracle恢复失败:', error);
590
+ throw new Error(`恢复失败: ${error.message}`);
591
+ }
592
+ }
593
+
594
+ /**
595
+ * 导出表数据到 SQL 文件
596
+ */
597
+ async exportTableDataToSQL(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
598
+ try {
599
+ const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
600
+ if (!fs.existsSync(exportPath)) fs.mkdirSync(exportPath, { recursive: true });
601
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
602
+ const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.sql`);
603
+
604
+ const columns = await this.getColumns(dataSource, databaseName, tableName);
605
+ const columnNames = columns.map(column => column.name);
606
+
607
+ // 生成文件头部
608
+ const header = `-- 表数据导出 - ${tableName}\n` +
609
+ `-- 导出时间: ${new Date().toISOString()}\n\n`;
610
+ fs.writeFileSync(exportFile, header, 'utf8');
611
+
612
+ // 分批处理数据,避免一次性加载大量数据到内存
613
+ const batchSize = options?.batchSize || 10000; // 每批处理10000行
614
+ let offset = 0;
615
+ let hasMoreData = true;
616
+
617
+ while (hasMoreData) {
618
+ // 分批查询数据(Oracle 使用 ROWNUM 语法)
619
+ const query = `SELECT * FROM (SELECT a.*, ROWNUM rnum FROM (SELECT * FROM ${this.quoteIdentifier(tableName)}) a WHERE ROWNUM <= ${offset + batchSize}) WHERE rnum > ${offset}`;
620
+ const data = await dataSource.query(query);
621
+
622
+ if (data.length === 0) {
623
+ hasMoreData = false;
624
+ break;
625
+ }
626
+
627
+ // 生成当前批次的 INSERT 语句
628
+ let batchSql = '';
629
+ data.forEach((row: any) => {
630
+ const values = columnNames.map(column => {
631
+ const value = row[column];
632
+ if (value === null || value === undefined) return 'NULL';
633
+ if (typeof value === 'string') {
634
+ // 处理字符串,转义单引号
635
+ return `'${value.replace(/'/g, "''")}'`;
636
+ }
637
+ if (typeof value === 'boolean') {
638
+ // Oracle 使用 NUMBER(1) 存储布尔值,1 表示 true,0 表示 false
639
+ return value ? '1' : '0';
640
+ }
641
+ if (value instanceof Date) {
642
+ // 格式化日期为 Oracle 兼容格式
643
+ const year = value.getFullYear();
644
+ const month = String(value.getMonth() + 1).padStart(2, '0');
645
+ const day = String(value.getDate()).padStart(2, '0');
646
+ const hours = String(value.getHours()).padStart(2, '0');
647
+ const minutes = String(value.getMinutes()).padStart(2, '0');
648
+ const seconds = String(value.getSeconds()).padStart(2, '0');
649
+ return `TO_TIMESTAMP('${year}-${month}-${day} ${hours}:${minutes}:${seconds}', 'YYYY-MM-DD HH24:MI:SS')`;
650
+ }
651
+ if (typeof value === 'object') {
652
+ // 处理对象类型,如 CLOB
653
+ try {
654
+ const stringValue = JSON.stringify(value);
655
+ return `'${stringValue.replace(/'/g, "''")}'`;
656
+ } catch {
657
+ return `'${String(value).replace(/'/g, "''")}'`;
658
+ }
659
+ }
660
+ // 其他类型直接转换为字符串
661
+ return String(value);
662
+ });
663
+ batchSql += `INSERT INTO ${this.quoteIdentifier(tableName)} (${columnNames.map(col => this.quoteIdentifier(col)).join(', ')}) VALUES (${values.join(', ')});\n`;
664
+ });
665
+
666
+ // 追加写入文件
667
+ fs.appendFileSync(exportFile, batchSql, 'utf8');
668
+
669
+ // 增加偏移量
670
+ offset += batchSize;
671
+
672
+ // 打印进度信息
673
+ console.log(`Oracle导出表数据进度: ${tableName} - 已处理 ${offset} 行`);
674
+ }
675
+
676
+ return exportFile;
677
+ } catch (error) {
678
+ console.error('Oracle导出表数据失败:', error);
679
+ throw new Error(`导出表数据失败: ${error.message}`);
680
+ }
681
+ }
682
+
683
+ /**
684
+ * 导出表数据到 CSV 文件
685
+ */
686
+ async exportTableDataToCSV(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
687
+ try {
688
+ const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
689
+ if (!fs.existsSync(exportPath)) fs.mkdirSync(exportPath, { recursive: true });
690
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
691
+ const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.csv`);
692
+
693
+ const columns = await this.getColumns(dataSource, databaseName, tableName);
694
+ const columnNames = columns.map(column => column.name);
695
+
696
+ // 写入 CSV 头部(包含 UTF-8 BOM)
697
+ const bom = Buffer.from([0xEF, 0xBB, 0xBF]);
698
+ fs.writeFileSync(exportFile, bom);
699
+ fs.appendFileSync(exportFile, columnNames.map(name => `"${name}"`).join(',') + '\n', 'utf8');
700
+
701
+ // 分批处理数据,避免一次性加载大量数据到内存
702
+ const batchSize = options?.batchSize || 10000; // 每批处理10000行
703
+ let offset = 0;
704
+ let hasMoreData = true;
705
+
706
+ while (hasMoreData) {
707
+ // 分批查询数据(Oracle 使用 ROWNUM 语法)
708
+ const query = `SELECT * FROM (SELECT a.*, ROWNUM rnum FROM (SELECT * FROM ${this.quoteIdentifier(tableName)}) a WHERE ROWNUM <= ${offset + batchSize}) WHERE rnum > ${offset}`;
709
+ const data = await dataSource.query(query);
710
+
711
+ if (data.length === 0) {
712
+ hasMoreData = false;
713
+ break;
714
+ }
715
+
716
+ // 生成当前批次的 CSV 行
717
+ let batchCsv = '';
718
+ data.forEach((row: any) => {
719
+ const values = columnNames.map(column => {
720
+ const value = row[column];
721
+ if (value === null || value === undefined) {
722
+ return '';
723
+ } else if (typeof value === 'string') {
724
+ // 转义双引号并包裹在双引号中
725
+ return `"${value.replace(/"/g, '""')}"`;
726
+ } else if (value instanceof Date) {
727
+ // 格式化日期为 Oracle 兼容格式
728
+ const year = value.getFullYear();
729
+ const month = String(value.getMonth() + 1).padStart(2, '0');
730
+ const day = String(value.getDate()).padStart(2, '0');
731
+ const hours = String(value.getHours()).padStart(2, '0');
732
+ const minutes = String(value.getMinutes()).padStart(2, '0');
733
+ const seconds = String(value.getSeconds()).padStart(2, '0');
734
+ return `"${year}-${month}-${day} ${hours}:${minutes}:${seconds}"`;
735
+ } else if (typeof value === 'object' && value !== null) {
736
+ // 处理对象类型,如 CLOB
737
+ try {
738
+ return `"${JSON.stringify(value).replace(/"/g, '""')}"`;
739
+ } catch {
740
+ return `"${String(value).replace(/"/g, '""')}"`;
741
+ }
742
+ } else {
743
+ return String(value);
744
+ }
745
+ });
746
+
747
+ batchCsv += values.join(',') + '\n';
748
+ });
749
+
750
+ // 追加写入文件
751
+ fs.appendFileSync(exportFile, batchCsv, 'utf8');
752
+
753
+ // 增加偏移量
754
+ offset += batchSize;
755
+
756
+ // 打印进度信息
757
+ console.log(`Oracle导出表数据到CSV进度: ${tableName} - 已处理 ${offset} 行`);
758
+ }
759
+
760
+ return exportFile;
761
+ } catch (error) {
762
+ console.error('Oracle导出表数据到CSV失败:', error);
763
+ throw new Error(`导出表数据到CSV失败: ${error.message}`);
764
+ }
765
+ }
766
+
767
+ /**
768
+ * 导出表数据到 JSON 文件
769
+ */
770
+ async exportTableDataToJSON(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
771
+ try {
772
+ const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
773
+ if (!fs.existsSync(exportPath)) fs.mkdirSync(exportPath, { recursive: true });
774
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
775
+ const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.json`);
776
+
777
+ // 写入 JSON 头部
778
+ fs.writeFileSync(exportFile, '[\n', 'utf8');
779
+
780
+ // 分批处理数据,避免一次性加载大量数据到内存
781
+ const batchSize = options?.batchSize || 10000; // 每批处理10000行
782
+ let offset = 0;
783
+ let hasMoreData = true;
784
+ let isFirstBatch = true;
785
+
786
+ while (hasMoreData) {
787
+ // 分批查询数据(Oracle 使用 ROWNUM 语法)
788
+ const query = `SELECT * FROM (SELECT a.*, ROWNUM rnum FROM (SELECT * FROM ${this.quoteIdentifier(tableName)}) a WHERE ROWNUM <= ${offset + batchSize}) WHERE rnum > ${offset}`;
789
+ const data = await dataSource.query(query);
790
+
791
+ if (data.length === 0) {
792
+ hasMoreData = false;
793
+ break;
794
+ }
795
+
796
+ // 生成当前批次的 JSON 数据
797
+ let batchJson = '';
798
+ data.forEach((row: any, index: number) => {
799
+ if (!isFirstBatch || index > 0) {
800
+ batchJson += ',\n';
801
+ }
802
+ batchJson += JSON.stringify(row);
803
+ });
804
+
805
+ // 追加写入文件
806
+ fs.appendFileSync(exportFile, batchJson, 'utf8');
807
+
808
+ // 增加偏移量
809
+ offset += batchSize;
810
+ isFirstBatch = false;
811
+
812
+ // 打印进度信息
813
+ console.log(`Oracle导出表数据到JSON进度: ${tableName} - 已处理 ${offset} 行`);
814
+ }
815
+
816
+ // 写入 JSON 尾部
817
+ fs.appendFileSync(exportFile, '\n]', 'utf8');
818
+
819
+ return exportFile;
820
+ } catch (error) {
821
+ console.error('Oracle导出表数据到JSON失败:', error);
822
+ throw new Error(`导出表数据到JSON失败: ${error.message}`);
823
+ }
824
+ }
825
+
826
+ /**
827
+ * 导出表数据到 Excel 文件
828
+ */
829
+ async exportTableDataToExcel(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
830
+ try {
831
+ // 由于 Excel 文件格式复杂,这里我们先导出为 CSV,然后可以考虑使用库来转换
832
+ // 或者直接调用其他服务来处理 Excel 导出
833
+ return this.exportTableDataToCSV(dataSource, databaseName, tableName, options);
834
+ } catch (error) {
835
+ console.error('Oracle导出表数据到Excel失败:', error);
836
+ throw new Error(`导出表数据到Excel失败: ${error.message}`);
837
+ }
838
+ }
839
+ }