fdb2 1.0.2 → 1.0.4

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 (94) hide show
  1. package/bin/fdb2.js +11 -3
  2. package/dist/public/.vite/manifest.json +82 -0
  3. package/dist/public/bootstrap-icons.woff +0 -0
  4. package/dist/public/bootstrap-icons.woff2 +0 -0
  5. package/dist/public/bootstrap.css +14152 -0
  6. package/dist/public/bootstrap.js +5038 -0
  7. package/dist/public/explorer.css +2137 -0
  8. package/dist/public/explorer.js +49846 -0
  9. package/dist/public/index.css +1071 -0
  10. package/dist/public/index.js +12811 -0
  11. package/dist/public/layout.css +318 -0
  12. package/dist/public/layout.js +25 -0
  13. package/dist/public/vue.css +1 -0
  14. package/dist/public/vue.js +9111 -0
  15. package/dist/server/index.d.ts +2 -0
  16. package/dist/server/index.d.ts.map +1 -0
  17. package/dist/server/index.js +598 -0
  18. package/dist/server/index.js.map +1 -0
  19. package/dist/server/index.ts +677 -0
  20. package/dist/server/model/connection.entity.d.ts +55 -0
  21. package/dist/server/model/connection.entity.d.ts.map +1 -0
  22. package/dist/server/model/connection.entity.js +59 -0
  23. package/dist/server/model/connection.entity.js.map +1 -0
  24. package/dist/server/model/connection.entity.ts +66 -0
  25. package/dist/server/model/database.entity.d.ts +203 -0
  26. package/dist/server/model/database.entity.d.ts.map +1 -0
  27. package/dist/server/model/database.entity.js +211 -0
  28. package/dist/server/model/database.entity.js.map +1 -0
  29. package/dist/server/model/database.entity.ts +246 -0
  30. package/dist/server/service/connection.service.d.ts +79 -0
  31. package/dist/server/service/connection.service.d.ts.map +1 -0
  32. package/dist/server/service/connection.service.js +351 -0
  33. package/dist/server/service/connection.service.js.map +1 -0
  34. package/dist/server/service/connection.service.ts +341 -0
  35. package/dist/server/service/database/base.service.d.ts +152 -0
  36. package/dist/server/service/database/base.service.d.ts.map +1 -0
  37. package/dist/server/service/database/base.service.js +236 -0
  38. package/dist/server/service/database/base.service.js.map +1 -0
  39. package/dist/server/service/database/base.service.ts +363 -0
  40. package/dist/server/service/database/cockroachdb.service.d.ts +95 -0
  41. package/dist/server/service/database/cockroachdb.service.d.ts.map +1 -0
  42. package/dist/server/service/database/cockroachdb.service.js +634 -0
  43. package/dist/server/service/database/cockroachdb.service.js.map +1 -0
  44. package/dist/server/service/database/cockroachdb.service.ts +659 -0
  45. package/dist/server/service/database/database.service.d.ts +487 -0
  46. package/dist/server/service/database/database.service.d.ts.map +1 -0
  47. package/dist/server/service/database/database.service.js +580 -0
  48. package/dist/server/service/database/database.service.js.map +1 -0
  49. package/dist/server/service/database/database.service.ts +630 -0
  50. package/dist/server/service/database/index.d.ts +8 -0
  51. package/dist/server/service/database/index.d.ts.map +1 -0
  52. package/dist/server/service/database/index.js +18 -0
  53. package/dist/server/service/database/index.js.map +1 -0
  54. package/dist/server/service/database/index.ts +7 -0
  55. package/dist/server/service/database/mongodb.service.d.ts +99 -0
  56. package/dist/server/service/database/mongodb.service.d.ts.map +1 -0
  57. package/dist/server/service/database/mongodb.service.js +459 -0
  58. package/dist/server/service/database/mongodb.service.js.map +1 -0
  59. package/dist/server/service/database/mongodb.service.ts +454 -0
  60. package/dist/server/service/database/mssql.service.d.ts +98 -0
  61. package/dist/server/service/database/mssql.service.d.ts.map +1 -0
  62. package/dist/server/service/database/mssql.service.js +694 -0
  63. package/dist/server/service/database/mssql.service.js.map +1 -0
  64. package/dist/server/service/database/mssql.service.ts +723 -0
  65. package/dist/server/service/database/mysql.service.d.ts +94 -0
  66. package/dist/server/service/database/mysql.service.d.ts.map +1 -0
  67. package/dist/server/service/database/mysql.service.js +735 -0
  68. package/dist/server/service/database/mysql.service.js.map +1 -0
  69. package/dist/server/service/database/mysql.service.ts +761 -0
  70. package/dist/server/service/database/oracle.service.d.ts +106 -0
  71. package/dist/server/service/database/oracle.service.d.ts.map +1 -0
  72. package/dist/server/service/database/oracle.service.js +787 -0
  73. package/dist/server/service/database/oracle.service.js.map +1 -0
  74. package/dist/server/service/database/oracle.service.ts +832 -0
  75. package/dist/server/service/database/postgres.service.d.ts +102 -0
  76. package/dist/server/service/database/postgres.service.d.ts.map +1 -0
  77. package/dist/server/service/database/postgres.service.js +696 -0
  78. package/dist/server/service/database/postgres.service.js.map +1 -0
  79. package/dist/server/service/database/postgres.service.ts +741 -0
  80. package/dist/server/service/database/sap.service.d.ts +95 -0
  81. package/dist/server/service/database/sap.service.d.ts.map +1 -0
  82. package/dist/server/service/database/sap.service.js +695 -0
  83. package/dist/server/service/database/sap.service.js.map +1 -0
  84. package/dist/server/service/database/sap.service.ts +713 -0
  85. package/dist/server/service/database/sqlite.service.d.ts +92 -0
  86. package/dist/server/service/database/sqlite.service.d.ts.map +1 -0
  87. package/dist/server/service/database/sqlite.service.js +532 -0
  88. package/dist/server/service/database/sqlite.service.js.map +1 -0
  89. package/dist/server/service/database/sqlite.service.ts +559 -0
  90. package/dist/server/service/session.service.ts +158 -0
  91. package/dist/view/index.html +45 -0
  92. package/package.json +2 -1
  93. package/scripts/preinstall.js +38 -0
  94. package/server.pid +0 -1
@@ -0,0 +1,559 @@
1
+ import { DataSource } from 'typeorm';
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+ import { BaseDatabaseService } from './base.service';
5
+ import {
6
+ TableEntity,
7
+ ColumnEntity,
8
+ IndexEntity,
9
+ ForeignKeyEntity
10
+ } from '../../model/database.entity';
11
+ import 'sqlite3';
12
+
13
+ /**
14
+ * SQLite数据库服务实现
15
+ */
16
+ export class SQLiteService extends BaseDatabaseService {
17
+
18
+ getDatabaseType(): string {
19
+ return 'sqlite';
20
+ }
21
+
22
+ /**
23
+ * 获取SQLite数据库列表
24
+ */
25
+ async getDatabases(dataSource: DataSource): Promise<string[]> {
26
+ // SQLite只有一个主数据库
27
+ return ['main'];
28
+ }
29
+
30
+ /**
31
+ * 获取SQLite表列表
32
+ */
33
+ async getTables(dataSource: DataSource, database: string): Promise<TableEntity[]> {
34
+ const result = await dataSource.query(`
35
+ SELECT
36
+ tbl_name as name,
37
+ 'table' as type,
38
+ sql as definition
39
+ FROM sqlite_master
40
+ WHERE type = 'table' AND tbl_name NOT LIKE 'sqlite_%'
41
+ `);
42
+
43
+ return result.map((row: any) => ({
44
+ name: row.name,
45
+ type: row.type,
46
+ rowCount: undefined,
47
+ dataSize: undefined,
48
+ indexSize: undefined
49
+ }));
50
+ }
51
+
52
+ /**
53
+ * 获取SQLite列信息
54
+ */
55
+ async getColumns(dataSource: DataSource, database: string, table: string): Promise<ColumnEntity[]> {
56
+ const result = await dataSource.query(`PRAGMA table_info(${table})`);
57
+
58
+ // 获取自增列信息
59
+ const xinfoResult = await dataSource.query(`PRAGMA table_xinfo(${table})`);
60
+ const autoIncrementColumns = new Set(
61
+ xinfoResult
62
+ .filter((row: any) => row.hidden === 2 && row.pk === 1)
63
+ .map((row: any) => row.name)
64
+ );
65
+
66
+ return result.map((row: any) => ({
67
+ name: row.name,
68
+ type: row.type,
69
+ nullable: row.notnull === 0,
70
+ defaultValue: row.dflt_value,
71
+ isPrimary: row.pk === 1,
72
+ isAutoIncrement: autoIncrementColumns.has(row.name)
73
+ }));
74
+ }
75
+
76
+ /**
77
+ * 获取SQLite索引信息
78
+ */
79
+ async getIndexes(dataSource: DataSource, database: string, table: string): Promise<IndexEntity[]> {
80
+ const result = await dataSource.query(`PRAGMA index_list(${table})`);
81
+
82
+ return result.map((row: any) => ({
83
+ name: row.name,
84
+ type: row.unique ? 'UNIQUE' : 'INDEX',
85
+ columns: [], // 需要额外查询
86
+ unique: row.unique === 1
87
+ }));
88
+ }
89
+
90
+ /**
91
+ * 获取SQLite外键信息
92
+ */
93
+ async getForeignKeys(dataSource: DataSource, database: string, table: string): Promise<ForeignKeyEntity[]> {
94
+ const result = await dataSource.query(`PRAGMA foreign_key_list(${table})`);
95
+
96
+ return result.map((row: any) => ({
97
+ name: `fk_${table}_${row.table}`,
98
+ column: row.from,
99
+ referencedTable: row.table,
100
+ referencedColumn: row.to,
101
+ onDelete: row.on_delete || 'NO ACTION',
102
+ onUpdate: row.on_update || 'NO ACTION'
103
+ }));
104
+ }
105
+
106
+ /**
107
+ * 获取SQLite数据库大小
108
+ */
109
+ async getDatabaseSize(dataSource: DataSource, database: string): Promise<number> {
110
+ // SQLite数据库大小需要通过文件系统获取,这里返回0
111
+ return 0;
112
+ }
113
+
114
+ /**
115
+ * 获取SQLite视图列表
116
+ */
117
+ async getViews(dataSource: DataSource, database: string): Promise<any[]> {
118
+ const result = await dataSource.query(`
119
+ SELECT
120
+ name,
121
+ sql as definition
122
+ FROM sqlite_master
123
+ WHERE type = 'view' AND name NOT LIKE 'sqlite_%'
124
+ ORDER BY name
125
+ `);
126
+
127
+ return result.map((row: any) => ({
128
+ name: row.name,
129
+ comment: '',
130
+ schemaName: 'main',
131
+ definition: row.definition
132
+ }));
133
+ }
134
+
135
+ /**
136
+ * 获取SQLite视图定义
137
+ */
138
+ async getViewDefinition(dataSource: DataSource, database: string, viewName: string): Promise<string> {
139
+ const result = await dataSource.query(`
140
+ SELECT sql as definition
141
+ FROM sqlite_master
142
+ WHERE type = 'view' AND name = $1
143
+ `, [viewName]);
144
+
145
+ return result[0]?.definition || '';
146
+ }
147
+
148
+ /**
149
+ * SQLite不支持存储过程
150
+ */
151
+ async getProcedures(dataSource: DataSource, database: string): Promise<any[]> {
152
+ // SQLite不支持存储过程,返回空数组
153
+ return [];
154
+ }
155
+
156
+ /**
157
+ * SQLite不支持存储过程
158
+ */
159
+ async getProcedureDefinition(dataSource: DataSource, database: string, procedureName: string): Promise<string> {
160
+ throw new Error('SQLite不支持存储过程');
161
+ }
162
+
163
+ /**
164
+ * 创建SQLite数据库
165
+ * 注意:SQLite的"数据库"实际上是文件,所以这个方法只是创建一个空文件
166
+ */
167
+ async createDatabase(dataSource: DataSource, databaseName: string, options?: any): Promise<void> {
168
+ // SQLite中数据库是文件,通常在连接时指定文件路径
169
+ // 这里只是创建一个空文件,实际使用时需要连接到这个文件
170
+ throw new Error('SQLite数据库创建需要指定文件路径,请在连接配置中设置数据库文件路径');
171
+ }
172
+
173
+ /**
174
+ * 删除SQLite数据库
175
+ */
176
+ async dropDatabase(dataSource: DataSource, databaseName: string): Promise<void> {
177
+ // SQLite中删除数据库需要删除文件
178
+ throw new Error('SQLite数据库删除需要手动删除数据库文件');
179
+ }
180
+
181
+ /**
182
+ * 导出数据库架构
183
+ */
184
+ async exportSchema(dataSource: DataSource, databaseName: string): Promise<string> {
185
+ // 获取所有表
186
+ const tables = await this.getTables(dataSource, databaseName);
187
+ let schemaSql = `-- 数据库架构导出 - ${databaseName}\n`;
188
+ schemaSql += `-- 导出时间: ${new Date().toISOString()}\n\n`;
189
+
190
+ // 为每个表生成CREATE TABLE语句
191
+ for (const table of tables) {
192
+ // 获取表结构
193
+ const columns = await this.getColumns(dataSource, databaseName, table.name);
194
+ const indexes = await this.getIndexes(dataSource, databaseName, table.name);
195
+ const foreignKeys = await this.getForeignKeys(dataSource, databaseName, table.name);
196
+
197
+ // 生成CREATE TABLE语句
198
+ schemaSql += `-- 表结构: ${table.name}\n`;
199
+ schemaSql += `CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(table.name)} (\n`;
200
+
201
+ // 添加列定义
202
+ const columnDefinitions = columns.map(column => {
203
+ let definition = ` ${this.quoteIdentifier(column.name)} ${column.type}`;
204
+ if (!column.nullable) definition += ' NOT NULL';
205
+ if (column.defaultValue !== undefined) {
206
+ // 特殊关键字处理
207
+ const upperDefault = column.defaultValue.toString().toUpperCase();
208
+ if (upperDefault === 'CURRENT_TIMESTAMP' || upperDefault === 'NOW()' || upperDefault === 'CURRENT_DATE') {
209
+ definition += ` DEFAULT ${upperDefault}`;
210
+ } else {
211
+ definition += ` DEFAULT ${column.defaultValue === null ? 'NULL' : `'${column.defaultValue}'`}`;
212
+ }
213
+ }
214
+ if (column.isPrimary && column.isAutoIncrement) definition += ' PRIMARY KEY AUTOINCREMENT';
215
+ else if (column.isPrimary) definition += ' PRIMARY KEY';
216
+ return definition;
217
+ });
218
+
219
+ schemaSql += columnDefinitions.join(',\n');
220
+ schemaSql += '\n);\n\n';
221
+
222
+ // 添加索引
223
+ for (const index of indexes) {
224
+ if (index.type === 'PRIMARY' || index.name.toUpperCase() === 'PRIMARY') continue; // 跳过主键索引
225
+ schemaSql += `-- 索引: ${index.name} on ${table.name}\n`;
226
+ schemaSql += `CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX IF NOT EXISTS ${this.quoteIdentifier(index.name)} ON ${this.quoteIdentifier(table.name)} (${index.columns.map(col => this.quoteIdentifier(col)).join(', ')})\n`;
227
+ }
228
+
229
+ if (indexes.length > 0) schemaSql += '\n';
230
+
231
+ // 添加外键
232
+ for (const foreignKey of foreignKeys) {
233
+ schemaSql += `-- 外键: ${foreignKey.name} on ${table.name}\n`;
234
+ 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`;
235
+ }
236
+
237
+ if (foreignKeys.length > 0) schemaSql += '\n';
238
+ }
239
+
240
+ return schemaSql;
241
+ }
242
+
243
+ /**
244
+ * 查看数据库日志
245
+ */
246
+ async viewLogs(dataSource: DataSource, database?: string, limit: number = 100): Promise<any[]> {
247
+ // SQLite查看日志
248
+ try {
249
+ // 尝试查看SQLite配置
250
+ const logs = await dataSource.query(`PRAGMA compile_options;`);
251
+ return logs;
252
+ } catch (error) {
253
+ return [{ message: 'SQLite数据库日志功能有限,请检查数据库文件状态' }];
254
+ }
255
+ }
256
+
257
+ /**
258
+ * 备份数据库
259
+ */
260
+ async backupDatabase(dataSource: DataSource, databaseName: string, options?: any): Promise<string> {
261
+ // SQLite备份数据库
262
+ try {
263
+ // SQLite备份就是复制数据库文件
264
+ const backupPath = options?.path || path.join(__dirname, '..', '..', 'backups');
265
+
266
+ // 确保备份目录存在
267
+ if (!fs.existsSync(backupPath)) {
268
+ fs.mkdirSync(backupPath, { recursive: true });
269
+ }
270
+
271
+ // 获取SQLite数据库文件路径
272
+ const connectionOptions = dataSource.options as any;
273
+ const dbPath = connectionOptions.database;
274
+
275
+ if (!dbPath) {
276
+ throw new Error('SQLite数据库文件路径未找到');
277
+ }
278
+
279
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
280
+ const backupFile = path.join(backupPath, `${databaseName}_${timestamp}.db`);
281
+
282
+ // 复制数据库文件
283
+ fs.copyFileSync(dbPath, backupFile);
284
+
285
+ return `备份成功:${backupFile}`;
286
+ } catch (error) {
287
+ console.error('SQLite备份失败:', error);
288
+ throw new Error(`备份失败: ${error.message}`);
289
+ }
290
+ }
291
+
292
+ /**
293
+ * 恢复数据库
294
+ */
295
+ async restoreDatabase(dataSource: DataSource, databaseName: string, filePath: string, options?: any): Promise<void> {
296
+ // SQLite恢复数据库
297
+ try {
298
+ // SQLite恢复就是复制备份文件到数据库文件路径
299
+ const connectionOptions = dataSource.options as any;
300
+ const dbPath = connectionOptions.database;
301
+
302
+ if (!dbPath) {
303
+ throw new Error('SQLite数据库文件路径未找到');
304
+ }
305
+
306
+ // 复制备份文件到数据库路径
307
+ fs.copyFileSync(filePath, dbPath);
308
+ } catch (error) {
309
+ console.error('SQLite恢复失败:', error);
310
+ throw new Error(`恢复失败: ${error.message}`);
311
+ }
312
+ }
313
+
314
+ /**
315
+ * 导出表数据到 SQL 文件
316
+ */
317
+ async exportTableDataToSQL(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
318
+ try {
319
+ // 创建导出目录
320
+ const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
321
+ if (!fs.existsSync(exportPath)) {
322
+ fs.mkdirSync(exportPath, { recursive: true });
323
+ }
324
+
325
+ // 生成文件名
326
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
327
+ const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.sql`);
328
+
329
+ // 获取表结构
330
+ const columns = await this.getColumns(dataSource, databaseName, tableName);
331
+ const columnNames = columns.map(column => column.name);
332
+
333
+ // 生成文件头部
334
+ const header = `-- 表数据导出 - ${tableName}\n` +
335
+ `-- 导出时间: ${new Date().toISOString()}\n\n`;
336
+ fs.writeFileSync(exportFile, header, 'utf8');
337
+
338
+ // 分批处理数据,避免一次性加载大量数据到内存
339
+ const batchSize = options?.batchSize || 10000; // 每批处理10000行
340
+ let offset = 0;
341
+ let hasMoreData = true;
342
+
343
+ while (hasMoreData) {
344
+ // 分批查询数据(SQLite 使用 LIMIT OFFSET 语法)
345
+ const query = `SELECT * FROM ${this.quoteIdentifier(tableName)} LIMIT ${batchSize} OFFSET ${offset}`;
346
+ const data = await dataSource.query(query);
347
+
348
+ if (data.length === 0) {
349
+ hasMoreData = false;
350
+ break;
351
+ }
352
+
353
+ // 生成当前批次的 INSERT 语句
354
+ let batchSql = '';
355
+ data.forEach((row: any) => {
356
+ const values = columnNames.map(column => {
357
+ const value = row[column];
358
+ if (value === null || value === undefined) {
359
+ return 'NULL';
360
+ } else if (typeof value === 'string') {
361
+ return `'${value.replace(/'/g, "''")}'`;
362
+ } else if (typeof value === 'boolean') {
363
+ return value ? '1' : '0';
364
+ } else if (value instanceof Date) {
365
+ return `'${value.toISOString().slice(0, 19).replace('T', ' ')}'`;
366
+ } else if (typeof value === 'object') {
367
+ // 处理JSON类型和其他对象类型
368
+ try {
369
+ const stringValue = JSON.stringify(value);
370
+ return `'${stringValue.replace(/'/g, "''")}'`;
371
+ } catch {
372
+ return `'${String(value).replace(/'/g, "''")}'`;
373
+ }
374
+ } else {
375
+ return String(value);
376
+ }
377
+ });
378
+
379
+ batchSql += `INSERT INTO ${this.quoteIdentifier(tableName)} (${columnNames.map(col => this.quoteIdentifier(col)).join(', ')}) VALUES (${values.join(', ')});\n`;
380
+ });
381
+
382
+ // 追加写入文件
383
+ fs.appendFileSync(exportFile, batchSql, 'utf8');
384
+
385
+ // 增加偏移量
386
+ offset += batchSize;
387
+
388
+ // 打印进度信息
389
+ console.log(`SQLite导出表数据进度: ${tableName} - 已处理 ${offset} 行`);
390
+ }
391
+
392
+ return exportFile;
393
+ } catch (error) {
394
+ console.error('SQLite导出表数据失败:', error);
395
+ throw new Error(`导出表数据失败: ${error.message}`);
396
+ }
397
+ }
398
+
399
+ /**
400
+ * 导出表数据到 CSV 文件
401
+ */
402
+ async exportTableDataToCSV(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
403
+ try {
404
+ // 创建导出目录
405
+ const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
406
+ if (!fs.existsSync(exportPath)) {
407
+ fs.mkdirSync(exportPath, { recursive: true });
408
+ }
409
+
410
+ // 生成文件名
411
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
412
+ const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.csv`);
413
+
414
+ // 获取表结构
415
+ const columns = await this.getColumns(dataSource, databaseName, tableName);
416
+ const columnNames = columns.map(column => column.name);
417
+
418
+ // 写入 CSV 头部(包含 UTF-8 BOM)
419
+ const bom = Buffer.from([0xEF, 0xBB, 0xBF]);
420
+ fs.writeFileSync(exportFile, bom);
421
+ fs.appendFileSync(exportFile, columnNames.map(name => `"${name}"`).join(',') + '\n', 'utf8');
422
+
423
+ // 分批处理数据,避免一次性加载大量数据到内存
424
+ const batchSize = options?.batchSize || 10000; // 每批处理10000行
425
+ let offset = 0;
426
+ let hasMoreData = true;
427
+
428
+ while (hasMoreData) {
429
+ // 分批查询数据(SQLite 使用 LIMIT OFFSET 语法)
430
+ const query = `SELECT * FROM ${this.quoteIdentifier(tableName)} LIMIT ${batchSize} OFFSET ${offset}`;
431
+ const data = await dataSource.query(query);
432
+
433
+ if (data.length === 0) {
434
+ hasMoreData = false;
435
+ break;
436
+ }
437
+
438
+ // 生成当前批次的 CSV 行
439
+ let batchCsv = '';
440
+ data.forEach((row: any) => {
441
+ const values = columnNames.map(column => {
442
+ const value = row[column];
443
+ if (value === null || value === undefined) {
444
+ return '';
445
+ } else if (typeof value === 'string') {
446
+ // 转义双引号并包裹在双引号中
447
+ return `"${value.replace(/"/g, '""')}"`;
448
+ } else if (value instanceof Date) {
449
+ return `"${value.toISOString().slice(0, 19).replace('T', ' ')}"`;
450
+ } else if (typeof value === 'object' && value !== null) {
451
+ // 处理JSON类型和其他对象类型
452
+ try {
453
+ return `"${JSON.stringify(value).replace(/"/g, '""')}"`;
454
+ } catch {
455
+ return `"${String(value).replace(/"/g, '""')}"`;
456
+ }
457
+ } else {
458
+ return String(value);
459
+ }
460
+ });
461
+
462
+ batchCsv += values.join(',') + '\n';
463
+ });
464
+
465
+ // 追加写入文件
466
+ fs.appendFileSync(exportFile, batchCsv, 'utf8');
467
+
468
+ // 增加偏移量
469
+ offset += batchSize;
470
+
471
+ // 打印进度信息
472
+ console.log(`SQLite导出表数据到CSV进度: ${tableName} - 已处理 ${offset} 行`);
473
+ }
474
+
475
+ return exportFile;
476
+ } catch (error) {
477
+ console.error('SQLite导出表数据到CSV失败:', error);
478
+ throw new Error(`导出表数据到CSV失败: ${error.message}`);
479
+ }
480
+ }
481
+
482
+ /**
483
+ * 导出表数据到 JSON 文件
484
+ */
485
+ async exportTableDataToJSON(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
486
+ try {
487
+ // 创建导出目录
488
+ const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
489
+ if (!fs.existsSync(exportPath)) {
490
+ fs.mkdirSync(exportPath, { recursive: true });
491
+ }
492
+
493
+ // 生成文件名
494
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
495
+ const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.json`);
496
+
497
+ // 写入 JSON 头部
498
+ fs.writeFileSync(exportFile, '[\n', 'utf8');
499
+
500
+ // 分批处理数据,避免一次性加载大量数据到内存
501
+ const batchSize = options?.batchSize || 10000; // 每批处理10000行
502
+ let offset = 0;
503
+ let hasMoreData = true;
504
+ let isFirstBatch = true;
505
+
506
+ while (hasMoreData) {
507
+ // 分批查询数据(SQLite 使用 LIMIT OFFSET 语法)
508
+ const query = `SELECT * FROM ${this.quoteIdentifier(tableName)} LIMIT ${batchSize} OFFSET ${offset}`;
509
+ const data = await dataSource.query(query);
510
+
511
+ if (data.length === 0) {
512
+ hasMoreData = false;
513
+ break;
514
+ }
515
+
516
+ // 生成当前批次的 JSON 数据
517
+ let batchJson = '';
518
+ data.forEach((row: any, index: number) => {
519
+ if (!isFirstBatch || index > 0) {
520
+ batchJson += ',\n';
521
+ }
522
+ batchJson += JSON.stringify(row);
523
+ });
524
+
525
+ // 追加写入文件
526
+ fs.appendFileSync(exportFile, batchJson, 'utf8');
527
+
528
+ // 增加偏移量
529
+ offset += batchSize;
530
+ isFirstBatch = false;
531
+
532
+ // 打印进度信息
533
+ console.log(`SQLite导出表数据到JSON进度: ${tableName} - 已处理 ${offset} 行`);
534
+ }
535
+
536
+ // 写入 JSON 尾部
537
+ fs.appendFileSync(exportFile, '\n]', 'utf8');
538
+
539
+ return exportFile;
540
+ } catch (error) {
541
+ console.error('SQLite导出表数据到JSON失败:', error);
542
+ throw new Error(`导出表数据到JSON失败: ${error.message}`);
543
+ }
544
+ }
545
+
546
+ /**
547
+ * 导出表数据到 Excel 文件
548
+ */
549
+ async exportTableDataToExcel(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
550
+ try {
551
+ // 由于 Excel 文件格式复杂,这里我们先导出为 CSV,然后可以考虑使用库来转换
552
+ // 或者直接调用其他服务来处理 Excel 导出
553
+ return this.exportTableDataToCSV(dataSource, databaseName, tableName, options);
554
+ } catch (error) {
555
+ console.error('SQLite导出表数据到Excel失败:', error);
556
+ throw new Error(`导出表数据到Excel失败: ${error.message}`);
557
+ }
558
+ }
559
+ }