fdb2 1.0.2 → 1.0.3

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 (91) hide show
  1. package/dist/public/.vite/manifest.json +82 -0
  2. package/dist/public/bootstrap-icons.woff +0 -0
  3. package/dist/public/bootstrap-icons.woff2 +0 -0
  4. package/dist/public/bootstrap.css +14152 -0
  5. package/dist/public/bootstrap.js +5038 -0
  6. package/dist/public/explorer.css +2137 -0
  7. package/dist/public/explorer.js +49846 -0
  8. package/dist/public/index.css +1071 -0
  9. package/dist/public/index.js +12811 -0
  10. package/dist/public/layout.css +318 -0
  11. package/dist/public/layout.js +25 -0
  12. package/dist/public/vue.css +1 -0
  13. package/dist/public/vue.js +9111 -0
  14. package/dist/server/index.d.ts +2 -0
  15. package/dist/server/index.d.ts.map +1 -0
  16. package/dist/server/index.js +598 -0
  17. package/dist/server/index.js.map +1 -0
  18. package/dist/server/index.ts +677 -0
  19. package/dist/server/model/connection.entity.d.ts +55 -0
  20. package/dist/server/model/connection.entity.d.ts.map +1 -0
  21. package/dist/server/model/connection.entity.js +59 -0
  22. package/dist/server/model/connection.entity.js.map +1 -0
  23. package/dist/server/model/connection.entity.ts +66 -0
  24. package/dist/server/model/database.entity.d.ts +203 -0
  25. package/dist/server/model/database.entity.d.ts.map +1 -0
  26. package/dist/server/model/database.entity.js +211 -0
  27. package/dist/server/model/database.entity.js.map +1 -0
  28. package/dist/server/model/database.entity.ts +246 -0
  29. package/dist/server/service/connection.service.d.ts +79 -0
  30. package/dist/server/service/connection.service.d.ts.map +1 -0
  31. package/dist/server/service/connection.service.js +351 -0
  32. package/dist/server/service/connection.service.js.map +1 -0
  33. package/dist/server/service/connection.service.ts +341 -0
  34. package/dist/server/service/database/base.service.d.ts +152 -0
  35. package/dist/server/service/database/base.service.d.ts.map +1 -0
  36. package/dist/server/service/database/base.service.js +236 -0
  37. package/dist/server/service/database/base.service.js.map +1 -0
  38. package/dist/server/service/database/base.service.ts +363 -0
  39. package/dist/server/service/database/cockroachdb.service.d.ts +95 -0
  40. package/dist/server/service/database/cockroachdb.service.d.ts.map +1 -0
  41. package/dist/server/service/database/cockroachdb.service.js +634 -0
  42. package/dist/server/service/database/cockroachdb.service.js.map +1 -0
  43. package/dist/server/service/database/cockroachdb.service.ts +659 -0
  44. package/dist/server/service/database/database.service.d.ts +487 -0
  45. package/dist/server/service/database/database.service.d.ts.map +1 -0
  46. package/dist/server/service/database/database.service.js +580 -0
  47. package/dist/server/service/database/database.service.js.map +1 -0
  48. package/dist/server/service/database/database.service.ts +630 -0
  49. package/dist/server/service/database/index.d.ts +8 -0
  50. package/dist/server/service/database/index.d.ts.map +1 -0
  51. package/dist/server/service/database/index.js +18 -0
  52. package/dist/server/service/database/index.js.map +1 -0
  53. package/dist/server/service/database/index.ts +7 -0
  54. package/dist/server/service/database/mongodb.service.d.ts +99 -0
  55. package/dist/server/service/database/mongodb.service.d.ts.map +1 -0
  56. package/dist/server/service/database/mongodb.service.js +459 -0
  57. package/dist/server/service/database/mongodb.service.js.map +1 -0
  58. package/dist/server/service/database/mongodb.service.ts +454 -0
  59. package/dist/server/service/database/mssql.service.d.ts +98 -0
  60. package/dist/server/service/database/mssql.service.d.ts.map +1 -0
  61. package/dist/server/service/database/mssql.service.js +694 -0
  62. package/dist/server/service/database/mssql.service.js.map +1 -0
  63. package/dist/server/service/database/mssql.service.ts +723 -0
  64. package/dist/server/service/database/mysql.service.d.ts +94 -0
  65. package/dist/server/service/database/mysql.service.d.ts.map +1 -0
  66. package/dist/server/service/database/mysql.service.js +735 -0
  67. package/dist/server/service/database/mysql.service.js.map +1 -0
  68. package/dist/server/service/database/mysql.service.ts +761 -0
  69. package/dist/server/service/database/oracle.service.d.ts +106 -0
  70. package/dist/server/service/database/oracle.service.d.ts.map +1 -0
  71. package/dist/server/service/database/oracle.service.js +787 -0
  72. package/dist/server/service/database/oracle.service.js.map +1 -0
  73. package/dist/server/service/database/oracle.service.ts +832 -0
  74. package/dist/server/service/database/postgres.service.d.ts +102 -0
  75. package/dist/server/service/database/postgres.service.d.ts.map +1 -0
  76. package/dist/server/service/database/postgres.service.js +696 -0
  77. package/dist/server/service/database/postgres.service.js.map +1 -0
  78. package/dist/server/service/database/postgres.service.ts +741 -0
  79. package/dist/server/service/database/sap.service.d.ts +95 -0
  80. package/dist/server/service/database/sap.service.d.ts.map +1 -0
  81. package/dist/server/service/database/sap.service.js +695 -0
  82. package/dist/server/service/database/sap.service.js.map +1 -0
  83. package/dist/server/service/database/sap.service.ts +713 -0
  84. package/dist/server/service/database/sqlite.service.d.ts +92 -0
  85. package/dist/server/service/database/sqlite.service.d.ts.map +1 -0
  86. package/dist/server/service/database/sqlite.service.js +532 -0
  87. package/dist/server/service/database/sqlite.service.js.map +1 -0
  88. package/dist/server/service/database/sqlite.service.ts +559 -0
  89. package/dist/server/service/session.service.ts +158 -0
  90. package/dist/view/index.html +45 -0
  91. package/package.json +1 -1
@@ -0,0 +1,696 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.PostgreSQLService = void 0;
37
+ const fs = __importStar(require("fs"));
38
+ const path = __importStar(require("path"));
39
+ const child_process_1 = require("child_process");
40
+ const base_service_1 = require("./base.service");
41
+ /**
42
+ * PostgreSQL数据库服务实现
43
+ */
44
+ class PostgreSQLService extends base_service_1.BaseDatabaseService {
45
+ getDatabaseType() {
46
+ return 'postgres';
47
+ }
48
+ /**
49
+ * 获取PostgreSQL数据库列表
50
+ */
51
+ async getDatabases(dataSource) {
52
+ const result = await dataSource.query(`
53
+ SELECT datname as name
54
+ FROM pg_database
55
+ WHERE datistemplate = false
56
+ `);
57
+ return result.map((row) => row.name);
58
+ }
59
+ /**
60
+ * 获取PostgreSQL表列表
61
+ */
62
+ async getTables(dataSource, database) {
63
+ const result = await dataSource.query(`
64
+ SELECT
65
+ t.table_name as name,
66
+ 'BASE TABLE' as type,
67
+ '' as collation,
68
+ obj_description(c.oid) as comment
69
+ FROM information_schema.tables t
70
+ LEFT JOIN pg_class c ON c.relname = t.table_name
71
+ WHERE t.table_schema NOT IN ('information_schema', 'pg_catalog')
72
+ AND t.table_type = 'BASE TABLE'
73
+ `);
74
+ return result.map((row) => ({
75
+ name: row.name,
76
+ type: row.type,
77
+ rowCount: undefined,
78
+ dataSize: undefined,
79
+ indexSize: undefined,
80
+ collation: row.collation,
81
+ comment: row.comment || ''
82
+ }));
83
+ }
84
+ /**
85
+ * 获取PostgreSQL列信息
86
+ */
87
+ async getColumns(dataSource, database, table) {
88
+ // 使用兼容的SQL查询,移除可能不兼容的精度字段
89
+ const result = await dataSource.query(`
90
+ SELECT
91
+ column_name as name,
92
+ data_type as type,
93
+ is_nullable as nullable,
94
+ column_default as defaultValue,
95
+ character_maximum_length as length
96
+ FROM information_schema.columns
97
+ WHERE table_name = $1
98
+ `, [table]);
99
+ // 获取主键信息
100
+ const primaryKeys = await this.getPrimaryKeys(dataSource, table);
101
+ // 获取 IDENTITY 列信息(PostgreSQL 10+)
102
+ const identityColumns = await this.getIdentityColumns(dataSource, table);
103
+ // 从data_type中解析精度信息
104
+ return result.map((row) => {
105
+ const dataType = row.type || '';
106
+ let precision = undefined;
107
+ let scale = undefined;
108
+ // 解析DECIMAL(M,D)或NUMERIC(M,D)类型的精度
109
+ const decimalMatch = dataType.match(/(DECIMAL|NUMERIC)\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)/i);
110
+ if (decimalMatch) {
111
+ precision = parseInt(decimalMatch[2]);
112
+ scale = parseInt(decimalMatch[3]);
113
+ }
114
+ // 检查是否为自增列(SERIAL 或 IDENTITY)
115
+ const isAutoIncrement = row.defaultValue?.includes('nextval') ||
116
+ identityColumns.includes(row.name);
117
+ return {
118
+ name: row.name,
119
+ type: row.type,
120
+ nullable: row.nullable === 'YES',
121
+ defaultValue: row.defaultValue,
122
+ isPrimary: primaryKeys.includes(row.name),
123
+ isAutoIncrement: isAutoIncrement,
124
+ length: row.length,
125
+ precision: precision,
126
+ scale: scale
127
+ };
128
+ });
129
+ }
130
+ /**
131
+ * 获取PostgreSQL索引信息
132
+ */
133
+ async getIndexes(dataSource, database, table) {
134
+ const result = await dataSource.query(`
135
+ SELECT
136
+ indexname as name,
137
+ indexdef as definition
138
+ FROM pg_indexes
139
+ WHERE tablename = $1
140
+ `, [table]);
141
+ return result.map((row) => ({
142
+ name: row.name,
143
+ type: 'INDEX',
144
+ columns: [], // 需要解析definition
145
+ unique: row.definition.toLowerCase().includes('unique')
146
+ }));
147
+ }
148
+ /**
149
+ * 获取PostgreSQL外键信息
150
+ */
151
+ async getForeignKeys(dataSource, database, table) {
152
+ const result = await dataSource.query(`
153
+ SELECT
154
+ tc.constraint_name as name,
155
+ kcu.column_name as column,
156
+ ccu.table_name as referencedTable,
157
+ ccu.column_name as referencedColumn,
158
+ rc.delete_rule as onDelete
159
+ FROM information_schema.table_constraints tc
160
+ JOIN information_schema.key_column_usage kcu
161
+ ON tc.constraint_name = kcu.constraint_name
162
+ JOIN information_schema.constraint_column_usage ccu
163
+ ON ccu.constraint_name = tc.constraint_name
164
+ JOIN information_schema.referential_constraints rc
165
+ ON tc.constraint_name = rc.constraint_name
166
+ WHERE tc.constraint_type = 'FOREIGN KEY'
167
+ AND tc.table_name = $1
168
+ `, [table]);
169
+ return result.map((row) => ({
170
+ name: row.name,
171
+ column: row.column,
172
+ referencedTable: row.referencedtable,
173
+ referencedColumn: row.referencedcolumn,
174
+ onDelete: row.ondelete,
175
+ onUpdate: 'NO ACTION'
176
+ }));
177
+ }
178
+ /**
179
+ * 获取PostgreSQL数据库大小
180
+ */
181
+ async getDatabaseSize(dataSource, database) {
182
+ const result = await dataSource.query(`
183
+ SELECT pg_database_size($1) as size
184
+ `, [database]);
185
+ return result[0]?.size || 0;
186
+ }
187
+ /**
188
+ * 获取主键信息
189
+ */
190
+ async getPrimaryKeys(dataSource, table) {
191
+ const result = await dataSource.query(`
192
+ SELECT column_name
193
+ FROM information_schema.table_constraints tc
194
+ JOIN information_schema.key_column_usage kcu
195
+ ON tc.constraint_name = kcu.constraint_name
196
+ WHERE tc.constraint_type = 'PRIMARY KEY'
197
+ AND tc.table_name = $1
198
+ `, [table]);
199
+ return result.map((row) => row.column_name);
200
+ }
201
+ /**
202
+ * 获取PostgreSQL IDENTITY列信息(PostgreSQL 10+)
203
+ */
204
+ async getIdentityColumns(dataSource, table) {
205
+ try {
206
+ const result = await dataSource.query(`
207
+ SELECT column_name
208
+ FROM information_schema.columns
209
+ WHERE table_name = $1
210
+ AND is_identity = 'YES'
211
+ `, [table]);
212
+ return result.map((row) => row.column_name);
213
+ }
214
+ catch (error) {
215
+ // 如果查询失败(PostgreSQL 版本低于 10),返回空数组
216
+ return [];
217
+ }
218
+ }
219
+ /**
220
+ * PostgreSQL使用双引号标识符
221
+ */
222
+ quoteIdentifier(identifier) {
223
+ return `"${identifier}"`;
224
+ }
225
+ /**
226
+ * 获取PostgreSQL视图列表
227
+ */
228
+ async getViews(dataSource, database) {
229
+ const result = await dataSource.query(`
230
+ SELECT
231
+ table_name as name,
232
+ COALESCE(obj_description(c.oid), '') as comment,
233
+ table_schema as schemaName
234
+ FROM information_schema.views v
235
+ LEFT JOIN pg_class c ON c.relname = v.table_name
236
+ WHERE v.table_schema NOT IN ('information_schema', 'pg_catalog')
237
+ ORDER BY v.table_name
238
+ `);
239
+ return result.map((row) => ({
240
+ name: row.name,
241
+ comment: row.comment || '',
242
+ schemaName: row.schemaname
243
+ }));
244
+ }
245
+ /**
246
+ * 获取PostgreSQL视图定义
247
+ */
248
+ async getViewDefinition(dataSource, database, viewName) {
249
+ const result = await dataSource.query(`
250
+ SELECT view_definition as definition
251
+ FROM information_schema.views
252
+ WHERE table_name = $1
253
+ AND table_schema NOT IN ('information_schema', 'pg_catalog')
254
+ `, [viewName]);
255
+ return result[0]?.definition || '';
256
+ }
257
+ /**
258
+ * 获取PostgreSQL存储过程列表
259
+ */
260
+ async getProcedures(dataSource, database) {
261
+ const result = await dataSource.query(`
262
+ SELECT
263
+ routine_name as name,
264
+ '' as comment,
265
+ routine_type as type,
266
+ COALESCE(data_type, '') as returnType,
267
+ external_language as language
268
+ FROM information_schema.routines
269
+ WHERE routine_schema NOT IN ('information_schema', 'pg_catalog')
270
+ ORDER BY routine_name
271
+ `);
272
+ return result.map((row) => ({
273
+ name: row.name,
274
+ comment: row.comment || '',
275
+ type: row.type,
276
+ returnType: row.returntype || '',
277
+ language: row.language || 'SQL'
278
+ }));
279
+ }
280
+ /**
281
+ * 获取PostgreSQL存储过程定义
282
+ */
283
+ async getProcedureDefinition(dataSource, database, procedureName) {
284
+ const result = await dataSource.query(`
285
+ SELECT routine_definition as definition
286
+ FROM information_schema.routines
287
+ WHERE routine_name = $1
288
+ AND routine_schema NOT IN ('information_schema', 'pg_catalog')
289
+ `, [procedureName]);
290
+ return result[0]?.definition || '';
291
+ }
292
+ /**
293
+ * 创建PostgreSQL数据库
294
+ */
295
+ async createDatabase(dataSource, databaseName, options) {
296
+ let sql = `CREATE DATABASE ${this.quoteIdentifier(databaseName)}`;
297
+ if (options) {
298
+ const clauses = [];
299
+ if (options.owner) {
300
+ clauses.push(`OWNER ${options.owner}`);
301
+ }
302
+ if (options.template) {
303
+ clauses.push(`TEMPLATE ${options.template}`);
304
+ }
305
+ if (options.encoding) {
306
+ clauses.push(`ENCODING '${options.encoding}'`);
307
+ }
308
+ if (options.lcCollate) {
309
+ clauses.push(`LC_COLLATE '${options.lcCollate}'`);
310
+ }
311
+ if (options.lcCtype) {
312
+ clauses.push(`LC_CTYPE '${options.lcCtype}'`);
313
+ }
314
+ if (options.tablespace) {
315
+ clauses.push(`TABLESPACE ${options.tablespace}`);
316
+ }
317
+ if (options.allowConnections !== undefined) {
318
+ clauses.push(`ALLOW_CONNECTIONS ${options.allowConnections}`);
319
+ }
320
+ if (options.connectionLimit !== undefined) {
321
+ clauses.push(`CONNECTION LIMIT ${options.connectionLimit}`);
322
+ }
323
+ if (clauses.length > 0) {
324
+ sql += ' ' + clauses.join(' ');
325
+ }
326
+ }
327
+ await dataSource.query(sql);
328
+ }
329
+ /**
330
+ * 删除PostgreSQL数据库
331
+ */
332
+ async dropDatabase(dataSource, databaseName) {
333
+ const sql = `DROP DATABASE ${this.quoteIdentifier(databaseName)}`;
334
+ await dataSource.query(sql);
335
+ }
336
+ /**
337
+ * 导出数据库架构
338
+ */
339
+ async exportSchema(dataSource, databaseName) {
340
+ // 获取所有表
341
+ const tables = await this.getTables(dataSource, databaseName);
342
+ let schemaSql = `-- 数据库架构导出 - ${databaseName}\n`;
343
+ schemaSql += `-- 导出时间: ${new Date().toISOString()}\n\n`;
344
+ // 为每个表生成CREATE TABLE语句
345
+ for (const table of tables) {
346
+ // 获取表结构
347
+ const columns = await this.getColumns(dataSource, databaseName, table.name);
348
+ const indexes = await this.getIndexes(dataSource, databaseName, table.name);
349
+ const foreignKeys = await this.getForeignKeys(dataSource, databaseName, table.name);
350
+ // 生成CREATE TABLE语句
351
+ schemaSql += `-- 表结构: ${table.name}\n`;
352
+ schemaSql += `CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(table.name)} (\n`;
353
+ // 添加列定义
354
+ const columnDefinitions = columns.map(column => {
355
+ let definition = ` ${this.quoteIdentifier(column.name)} ${column.type}`;
356
+ if (!column.nullable)
357
+ definition += ' NOT NULL';
358
+ if (column.defaultValue !== undefined) {
359
+ // 特殊关键字处理
360
+ const upperDefault = column.defaultValue.toString().toUpperCase();
361
+ if (upperDefault === 'CURRENT_TIMESTAMP' || upperDefault === 'NOW()' || upperDefault === 'CURRENT_DATE') {
362
+ definition += ` DEFAULT ${upperDefault}`;
363
+ }
364
+ else {
365
+ definition += ` DEFAULT ${column.defaultValue === null ? 'NULL' : `'${column.defaultValue}'`}`;
366
+ }
367
+ }
368
+ if (column.isAutoIncrement)
369
+ definition += ' SERIAL';
370
+ return definition;
371
+ });
372
+ // 添加主键
373
+ const primaryKeyColumns = columns.filter(column => column.isPrimary);
374
+ if (primaryKeyColumns.length > 0) {
375
+ const primaryKeyNames = primaryKeyColumns.map(column => this.quoteIdentifier(column.name)).join(', ');
376
+ columnDefinitions.push(` PRIMARY KEY (${primaryKeyNames})`);
377
+ }
378
+ schemaSql += columnDefinitions.join(',\n');
379
+ schemaSql += '\n);\n\n';
380
+ // 添加索引
381
+ for (const index of indexes) {
382
+ if (index.type === 'PRIMARY' || index.name.toUpperCase() === 'PRIMARY')
383
+ continue; // 跳过主键索引
384
+ schemaSql += `-- 索引: ${index.name} on ${table.name}\n`;
385
+ schemaSql += `CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX ${this.quoteIdentifier(index.name)} ON ${this.quoteIdentifier(table.name)} (${index.columns.map(col => this.quoteIdentifier(col)).join(', ')})\n`;
386
+ }
387
+ if (indexes.length > 0)
388
+ schemaSql += '\n';
389
+ // 添加外键
390
+ for (const foreignKey of foreignKeys) {
391
+ schemaSql += `-- 外键: ${foreignKey.name} on ${table.name}\n`;
392
+ 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`;
393
+ }
394
+ if (foreignKeys.length > 0)
395
+ schemaSql += '\n';
396
+ }
397
+ return schemaSql;
398
+ }
399
+ /**
400
+ * 查看数据库日志
401
+ */
402
+ async viewLogs(dataSource, database, limit = 100) {
403
+ // PostgreSQL查看日志
404
+ try {
405
+ // 尝试查看PostgreSQL日志设置
406
+ const logs = await dataSource.query(`SELECT name, setting FROM pg_settings WHERE name LIKE '%log%' LIMIT ${limit}`);
407
+ return logs;
408
+ }
409
+ catch (error) {
410
+ try {
411
+ // 尝试查看最近的连接日志
412
+ const logs = await dataSource.query(`SELECT * FROM pg_stat_activity LIMIT ${limit}`);
413
+ return logs;
414
+ }
415
+ catch (e) {
416
+ return [{ message: '无法获取PostgreSQL日志,请确保具有适当的权限' }];
417
+ }
418
+ }
419
+ }
420
+ /**
421
+ * 备份数据库
422
+ */
423
+ async backupDatabase(dataSource, databaseName, options) {
424
+ // PostgreSQL备份数据库
425
+ try {
426
+ // 使用pg_dump命令备份
427
+ const backupPath = options?.path || path.join(__dirname, '..', '..', 'backups');
428
+ // 确保备份目录存在
429
+ if (!fs.existsSync(backupPath)) {
430
+ fs.mkdirSync(backupPath, { recursive: true });
431
+ }
432
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
433
+ const backupFile = path.join(backupPath, `${databaseName}_${timestamp}.sql`);
434
+ // 执行备份命令
435
+ const connectionOptions = dataSource.options;
436
+ const host = connectionOptions.host || 'localhost';
437
+ const port = connectionOptions.port || 5432;
438
+ const user = connectionOptions.username;
439
+ const password = connectionOptions.password;
440
+ // 构建pg_dump命令
441
+ let command = `pg_dump -h ${host} -p ${port} -U ${user} -d ${databaseName} > ${backupFile}`;
442
+ // 执行命令
443
+ (0, child_process_1.execSync)(command, { env: { ...process.env, PGPASSWORD: password } });
444
+ return `备份成功:${backupFile}`;
445
+ }
446
+ catch (error) {
447
+ console.error('PostgreSQL备份失败:', error);
448
+ throw new Error(`备份失败: ${error.message}`);
449
+ }
450
+ }
451
+ /**
452
+ * 恢复数据库
453
+ */
454
+ async restoreDatabase(dataSource, databaseName, filePath, options) {
455
+ // PostgreSQL恢复数据库
456
+ try {
457
+ // 执行恢复命令
458
+ const connectionOptions = dataSource.options;
459
+ const host = connectionOptions.host || 'localhost';
460
+ const port = connectionOptions.port || 5432;
461
+ const user = connectionOptions.username;
462
+ const password = connectionOptions.password;
463
+ // 构建psql命令
464
+ let command = `psql -h ${host} -p ${port} -U ${user} -d ${databaseName} -f ${filePath}`;
465
+ // 执行命令
466
+ (0, child_process_1.execSync)(command, { env: { ...process.env, PGPASSWORD: password } });
467
+ }
468
+ catch (error) {
469
+ console.error('PostgreSQL恢复失败:', error);
470
+ throw new Error(`恢复失败: ${error.message}`);
471
+ }
472
+ }
473
+ /**
474
+ * 导出表数据到 SQL 文件
475
+ */
476
+ async exportTableDataToSQL(dataSource, databaseName, tableName, options) {
477
+ try {
478
+ // 创建导出目录
479
+ const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
480
+ if (!fs.existsSync(exportPath)) {
481
+ fs.mkdirSync(exportPath, { recursive: true });
482
+ }
483
+ // 生成文件名
484
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
485
+ const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.sql`);
486
+ // 获取表结构
487
+ const columns = await this.getColumns(dataSource, databaseName, tableName);
488
+ const columnNames = columns.map(column => column.name);
489
+ // 生成文件头部
490
+ const header = `-- 表数据导出 - ${tableName}\n` +
491
+ `-- 导出时间: ${new Date().toISOString()}\n\n`;
492
+ fs.writeFileSync(exportFile, header, 'utf8');
493
+ // 分批处理数据,避免一次性加载大量数据到内存
494
+ const batchSize = options?.batchSize || 10000; // 每批处理10000行
495
+ let offset = 0;
496
+ let hasMoreData = true;
497
+ while (hasMoreData) {
498
+ // 分批查询数据
499
+ const query = `SELECT * FROM ${this.quoteIdentifier(tableName)} LIMIT ${batchSize} OFFSET ${offset}`;
500
+ const data = await dataSource.query(query);
501
+ if (data.length === 0) {
502
+ hasMoreData = false;
503
+ break;
504
+ }
505
+ // 生成当前批次的 INSERT 语句
506
+ let batchSql = '';
507
+ data.forEach((row) => {
508
+ const values = columnNames.map(column => {
509
+ const value = row[column];
510
+ if (value === null || value === undefined) {
511
+ return 'NULL';
512
+ }
513
+ else if (typeof value === 'string') {
514
+ return `'${value.replace(/'/g, "''")}'`;
515
+ }
516
+ else if (typeof value === 'boolean') {
517
+ return value ? 'TRUE' : 'FALSE';
518
+ }
519
+ else if (value instanceof Date) {
520
+ return `'${value.toISOString()}'`;
521
+ }
522
+ else if (typeof value === 'object' && value !== null) {
523
+ // 处理JSON类型
524
+ try {
525
+ return `'${JSON.stringify(value).replace(/'/g, "''")}'`;
526
+ }
527
+ catch {
528
+ return `'${String(value).replace(/'/g, "''")}'`;
529
+ }
530
+ }
531
+ else {
532
+ return String(value);
533
+ }
534
+ });
535
+ batchSql += `INSERT INTO ${this.quoteIdentifier(tableName)} (${columnNames.map(col => this.quoteIdentifier(col)).join(', ')}) VALUES (${values.join(', ')});\n`;
536
+ });
537
+ // 追加写入文件
538
+ fs.appendFileSync(exportFile, batchSql, 'utf8');
539
+ // 增加偏移量
540
+ offset += batchSize;
541
+ // 打印进度信息
542
+ console.log(`PostgreSQL导出表数据进度: ${tableName} - 已处理 ${offset} 行`);
543
+ }
544
+ return exportFile;
545
+ }
546
+ catch (error) {
547
+ console.error('PostgreSQL导出表数据失败:', error);
548
+ throw new Error(`导出表数据失败: ${error.message}`);
549
+ }
550
+ }
551
+ /**
552
+ * 导出表数据到 CSV 文件
553
+ */
554
+ async exportTableDataToCSV(dataSource, databaseName, tableName, options) {
555
+ try {
556
+ // 创建导出目录
557
+ const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
558
+ if (!fs.existsSync(exportPath)) {
559
+ fs.mkdirSync(exportPath, { recursive: true });
560
+ }
561
+ // 生成文件名
562
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
563
+ const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.csv`);
564
+ // 获取表结构
565
+ const columns = await this.getColumns(dataSource, databaseName, tableName);
566
+ const columnNames = columns.map(column => column.name);
567
+ // 写入 CSV 头部(包含 UTF-8 BOM)
568
+ const bom = Buffer.from([0xEF, 0xBB, 0xBF]);
569
+ fs.writeFileSync(exportFile, bom);
570
+ fs.appendFileSync(exportFile, columnNames.map(name => `"${name}"`).join(',') + '\n', 'utf8');
571
+ // 分批处理数据,避免一次性加载大量数据到内存
572
+ const batchSize = options?.batchSize || 10000; // 每批处理10000行
573
+ let offset = 0;
574
+ let hasMoreData = true;
575
+ while (hasMoreData) {
576
+ // 分批查询数据
577
+ const query = `SELECT * FROM ${this.quoteIdentifier(tableName)} LIMIT ${batchSize} OFFSET ${offset}`;
578
+ const data = await dataSource.query(query);
579
+ if (data.length === 0) {
580
+ hasMoreData = false;
581
+ break;
582
+ }
583
+ // 生成当前批次的 CSV 行
584
+ let batchCsv = '';
585
+ data.forEach((row) => {
586
+ const values = columnNames.map(column => {
587
+ const value = row[column];
588
+ if (value === null || value === undefined) {
589
+ return '';
590
+ }
591
+ else if (typeof value === 'string') {
592
+ // 转义双引号并包裹在双引号中
593
+ return `"${value.replace(/"/g, '""')}"`;
594
+ }
595
+ else if (value instanceof Date) {
596
+ return `"${value.toISOString().slice(0, 19).replace('T', ' ')}"`;
597
+ }
598
+ else if (typeof value === 'object' && value !== null) {
599
+ // 处理JSON类型
600
+ try {
601
+ return `"${JSON.stringify(value).replace(/"/g, '""')}"`;
602
+ }
603
+ catch {
604
+ return `"${String(value).replace(/"/g, '""')}"`;
605
+ }
606
+ }
607
+ else {
608
+ return String(value);
609
+ }
610
+ });
611
+ batchCsv += values.join(',') + '\n';
612
+ });
613
+ // 追加写入文件
614
+ fs.appendFileSync(exportFile, batchCsv, 'utf8');
615
+ // 增加偏移量
616
+ offset += batchSize;
617
+ // 打印进度信息
618
+ console.log(`PostgreSQL导出表数据到CSV进度: ${tableName} - 已处理 ${offset} 行`);
619
+ }
620
+ return exportFile;
621
+ }
622
+ catch (error) {
623
+ console.error('PostgreSQL导出表数据到CSV失败:', error);
624
+ throw new Error(`导出表数据到CSV失败: ${error.message}`);
625
+ }
626
+ }
627
+ /**
628
+ * 导出表数据到 JSON 文件
629
+ */
630
+ async exportTableDataToJSON(dataSource, databaseName, tableName, options) {
631
+ try {
632
+ // 创建导出目录
633
+ const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
634
+ if (!fs.existsSync(exportPath)) {
635
+ fs.mkdirSync(exportPath, { recursive: true });
636
+ }
637
+ // 生成文件名
638
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
639
+ const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.json`);
640
+ // 写入 JSON 头部
641
+ fs.writeFileSync(exportFile, '[\n', 'utf8');
642
+ // 分批处理数据,避免一次性加载大量数据到内存
643
+ const batchSize = options?.batchSize || 10000; // 每批处理10000行
644
+ let offset = 0;
645
+ let hasMoreData = true;
646
+ let isFirstBatch = true;
647
+ while (hasMoreData) {
648
+ // 分批查询数据
649
+ const query = `SELECT * FROM ${this.quoteIdentifier(tableName)} LIMIT ${batchSize} OFFSET ${offset}`;
650
+ const data = await dataSource.query(query);
651
+ if (data.length === 0) {
652
+ hasMoreData = false;
653
+ break;
654
+ }
655
+ // 生成当前批次的 JSON 数据
656
+ let batchJson = '';
657
+ data.forEach((row, index) => {
658
+ if (!isFirstBatch || index > 0) {
659
+ batchJson += ',\n';
660
+ }
661
+ batchJson += JSON.stringify(row);
662
+ });
663
+ // 追加写入文件
664
+ fs.appendFileSync(exportFile, batchJson, 'utf8');
665
+ // 增加偏移量
666
+ offset += batchSize;
667
+ isFirstBatch = false;
668
+ // 打印进度信息
669
+ console.log(`PostgreSQL导出表数据到JSON进度: ${tableName} - 已处理 ${offset} 行`);
670
+ }
671
+ // 写入 JSON 尾部
672
+ fs.appendFileSync(exportFile, '\n]', 'utf8');
673
+ return exportFile;
674
+ }
675
+ catch (error) {
676
+ console.error('PostgreSQL导出表数据到JSON失败:', error);
677
+ throw new Error(`导出表数据到JSON失败: ${error.message}`);
678
+ }
679
+ }
680
+ /**
681
+ * 导出表数据到 Excel 文件
682
+ */
683
+ async exportTableDataToExcel(dataSource, databaseName, tableName, options) {
684
+ try {
685
+ // 由于 Excel 文件格式复杂,这里我们先导出为 CSV,然后可以考虑使用库来转换
686
+ // 或者直接调用其他服务来处理 Excel 导出
687
+ return this.exportTableDataToCSV(dataSource, databaseName, tableName, options);
688
+ }
689
+ catch (error) {
690
+ console.error('PostgreSQL导出表数据到Excel失败:', error);
691
+ throw new Error(`导出表数据到Excel失败: ${error.message}`);
692
+ }
693
+ }
694
+ }
695
+ exports.PostgreSQLService = PostgreSQLService;
696
+ //# sourceMappingURL=postgres.service.js.map