fdb2 1.0.0 → 1.0.2

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.
@@ -0,0 +1,713 @@
1
+ import { DataSource } from 'typeorm';
2
+ import { BaseDatabaseService } from './base.service';
3
+ import {
4
+ DatabaseEntity,
5
+ TableEntity,
6
+ ColumnEntity,
7
+ IndexEntity,
8
+ ForeignKeyEntity
9
+ } from '../../model/database.entity';
10
+ import * as fs from 'fs';
11
+ import * as path from 'path';
12
+
13
+ /**
14
+ * SAP HANA数据库服务实现
15
+ * SAP HANA 是 SAP 公司的高性能内存数据库
16
+ */
17
+ export class SAPHANADatabaseService extends BaseDatabaseService {
18
+
19
+ getDatabaseType() {
20
+ return 'sap';
21
+ }
22
+
23
+ /**
24
+ * 获取SAP HANA数据库列表
25
+ */
26
+ async getDatabases(dataSource: DataSource): Promise<string[]> {
27
+ try {
28
+ const result = await dataSource.query(`
29
+ SELECT
30
+ SCHEMA_NAME as name
31
+ FROM
32
+ SCHEMAS
33
+ WHERE
34
+ SCHEMA_NAME NOT IN ('SYS', 'SYS_BI', 'SYS_EPM', 'SYS_REPO', 'SYS_RT', '_SYS_BIC', '_SYS_BI', '_SYS_DI', '_SYS_REPO', '_SYS_STATISTICS', '_SYS_TASK', '_SYS_XS')
35
+ ORDER BY
36
+ SCHEMA_NAME
37
+ `);
38
+ return result.map((row: any) => row.name);
39
+ } catch (error) {
40
+ console.error('获取SAP HANA数据库列表失败:', error);
41
+ return [];
42
+ }
43
+ }
44
+
45
+ /**
46
+ * 获取SAP HANA表列表
47
+ */
48
+ async getTables(dataSource: DataSource, database: string): Promise<TableEntity[]> {
49
+ try {
50
+ const result = await dataSource.query(`
51
+ SELECT
52
+ TABLE_NAME as name,
53
+ 'table' as type,
54
+ COMMENTS as comment
55
+ FROM
56
+ TABLES
57
+ WHERE
58
+ SCHEMA_NAME = ?
59
+ AND IS_VALID = 'TRUE'
60
+ ORDER BY
61
+ TABLE_NAME
62
+ `, [database]);
63
+
64
+ return result.map((row: any) => ({
65
+ name: row.name,
66
+ type: row.type,
67
+ comment: row.comment || '',
68
+ rowCount: undefined,
69
+ dataSize: undefined,
70
+ indexSize: undefined
71
+ }));
72
+ } catch (error) {
73
+ console.error('获取SAP HANA表列表失败:', error);
74
+ return [];
75
+ }
76
+ }
77
+
78
+ /**
79
+ * 获取SAP HANA列信息
80
+ */
81
+ async getColumns(dataSource: DataSource, database: string, table: string): Promise<ColumnEntity[]> {
82
+ try {
83
+ const result = await dataSource.query(`
84
+ SELECT
85
+ COLUMN_NAME as name,
86
+ DATA_TYPE_NAME as type,
87
+ IS_NULLABLE as nullable,
88
+ DEFAULT_VALUE as defaultValue,
89
+ COLUMN_ID as position
90
+ FROM
91
+ TABLE_COLUMNS
92
+ WHERE
93
+ SCHEMA_NAME = ?
94
+ AND TABLE_NAME = ?
95
+ ORDER BY
96
+ POSITION
97
+ `, [database, table]);
98
+
99
+ const primaryKeyResult = await dataSource.query(`
100
+ SELECT
101
+ COLUMN_NAME
102
+ FROM
103
+ CONSTRAINTS
104
+ WHERE
105
+ SCHEMA_NAME = ?
106
+ AND TABLE_NAME = ?
107
+ AND CONSTRAINT_TYPE = 'PRIMARY KEY'
108
+ `, [database, table]);
109
+
110
+ const primaryKeys = new Set(primaryKeyResult.map((row: any) => row.COLUMN_NAME));
111
+
112
+ return result.map((row: any) => ({
113
+ name: row.name,
114
+ type: row.type,
115
+ nullable: row.nullable === 'TRUE',
116
+ defaultValue: row.defaultValue,
117
+ isPrimary: primaryKeys.has(row.name),
118
+ isAutoIncrement: row.type.toUpperCase().includes('IDENTITY')
119
+ }));
120
+ } catch (error) {
121
+ console.error('获取SAP HANA列信息失败:', error);
122
+ return [];
123
+ }
124
+ }
125
+
126
+ /**
127
+ * 获取SAP HANA索引信息
128
+ */
129
+ async getIndexes(dataSource: DataSource, database: string, table: string): Promise<IndexEntity[]> {
130
+ try {
131
+ const result = await dataSource.query(`
132
+ SELECT
133
+ INDEX_NAME as name,
134
+ 'INDEX' as type,
135
+ IS_UNIQUE as unique
136
+ FROM
137
+ INDEXES
138
+ WHERE
139
+ SCHEMA_NAME = ?
140
+ AND TABLE_NAME = ?
141
+ ORDER BY
142
+ INDEX_NAME
143
+ `, [database, table]);
144
+
145
+ const indexDetails = await Promise.all(result.map(async (index: any) => {
146
+ const columnsResult = await dataSource.query(`
147
+ SELECT
148
+ COLUMN_NAME
149
+ FROM
150
+ INDEX_COLUMNS
151
+ WHERE
152
+ SCHEMA_NAME = ?
153
+ AND TABLE_NAME = ?
154
+ AND INDEX_NAME = ?
155
+ ORDER BY
156
+ POSITION
157
+ `, [database, table, index.name]);
158
+
159
+ return {
160
+ name: index.name,
161
+ type: index.unique === 'TRUE' ? 'UNIQUE' : 'INDEX',
162
+ columns: columnsResult.map((col: any) => col.COLUMN_NAME),
163
+ unique: index.unique === 'TRUE'
164
+ };
165
+ }));
166
+
167
+ return indexDetails;
168
+ } catch (error) {
169
+ console.error('获取SAP HANA索引信息失败:', error);
170
+ return [];
171
+ }
172
+ }
173
+
174
+ /**
175
+ * 获取SAP HANA外键信息
176
+ */
177
+ async getForeignKeys(dataSource: DataSource, database: string, table: string): Promise<ForeignKeyEntity[]> {
178
+ try {
179
+ const result = await dataSource.query(`
180
+ SELECT
181
+ CONSTRAINT_NAME as name,
182
+ COLUMN_NAME as column,
183
+ REFERENCED_SCHEMA_NAME as referencedSchema,
184
+ REFERENCED_TABLE_NAME as referencedTable,
185
+ REFERENCED_COLUMN_NAME as referencedColumn,
186
+ DELETE_RULE as onDelete,
187
+ UPDATE_RULE as onUpdate
188
+ FROM
189
+ REFERENTIAL_CONSTRAINTS
190
+ WHERE
191
+ SCHEMA_NAME = ?
192
+ AND TABLE_NAME = ?
193
+ ORDER BY
194
+ CONSTRAINT_NAME
195
+ `, [database, table]);
196
+
197
+ return result.map((row: any) => ({
198
+ name: row.name,
199
+ column: row.column,
200
+ referencedTable: row.referencedSchema ? `${row.referencedSchema}.${row.referencedTable}` : row.referencedTable,
201
+ referencedColumn: row.referencedColumn,
202
+ onDelete: row.onDelete || 'NO ACTION',
203
+ onUpdate: row.onUpdate || 'NO ACTION'
204
+ }));
205
+ } catch (error) {
206
+ console.error('获取SAP HANA外键信息失败:', error);
207
+ return [];
208
+ }
209
+ }
210
+
211
+ /**
212
+ * 获取SAP HANA数据库大小
213
+ */
214
+ async getDatabaseSize(dataSource: DataSource, database: string): Promise<number> {
215
+ try {
216
+ const result = await dataSource.query(`
217
+ SELECT
218
+ SUM(MEMORY_SIZE_IN_TOTAL) as size
219
+ FROM
220
+ M_TABLES
221
+ WHERE
222
+ SCHEMA_NAME = ?
223
+ `, [database]);
224
+ return result[0]?.size || 0;
225
+ } catch (error) {
226
+ console.error('获取SAP HANA数据库大小失败:', error);
227
+ return 0;
228
+ }
229
+ }
230
+
231
+ /**
232
+ * 获取SAP HANA视图列表
233
+ */
234
+ async getViews(dataSource: DataSource, database: string): Promise<any[]> {
235
+ try {
236
+ const result = await dataSource.query(`
237
+ SELECT
238
+ VIEW_NAME as name,
239
+ DEFINITION as definition
240
+ FROM
241
+ VIEWS
242
+ WHERE
243
+ SCHEMA_NAME = ?
244
+ AND IS_VALID = 'TRUE'
245
+ ORDER BY
246
+ VIEW_NAME
247
+ `, [database]);
248
+
249
+ return result.map((row: any) => ({
250
+ name: row.name,
251
+ comment: '',
252
+ schemaName: database,
253
+ definition: row.definition
254
+ }));
255
+ } catch (error) {
256
+ console.error('获取SAP HANA视图列表失败:', error);
257
+ return [];
258
+ }
259
+ }
260
+
261
+ /**
262
+ * 获取SAP HANA视图定义
263
+ */
264
+ async getViewDefinition(dataSource: DataSource, database: string, viewName: string): Promise<string> {
265
+ try {
266
+ const result = await dataSource.query(`
267
+ SELECT
268
+ DEFINITION as definition
269
+ FROM
270
+ VIEWS
271
+ WHERE
272
+ SCHEMA_NAME = ?
273
+ AND VIEW_NAME = ?
274
+ `, [database, viewName]);
275
+ return result[0]?.definition || '';
276
+ } catch (error) {
277
+ console.error('获取SAP HANA视图定义失败:', error);
278
+ return '';
279
+ }
280
+ }
281
+
282
+ /**
283
+ * 获取SAP HANA存储过程列表
284
+ */
285
+ async getProcedures(dataSource: DataSource, database: string): Promise<any[]> {
286
+ try {
287
+ const result = await dataSource.query(`
288
+ SELECT
289
+ PROCEDURE_NAME as name,
290
+ DEFINITION as definition
291
+ FROM
292
+ PROCEDURES
293
+ WHERE
294
+ SCHEMA_NAME = ?
295
+ AND IS_VALID = 'TRUE'
296
+ ORDER BY
297
+ PROCEDURE_NAME
298
+ `, [database]);
299
+
300
+ return result.map((row: any) => ({
301
+ name: row.name,
302
+ owner: database,
303
+ definition: row.definition
304
+ }));
305
+ } catch (error) {
306
+ console.error('获取SAP HANA存储过程列表失败:', error);
307
+ return [];
308
+ }
309
+ }
310
+
311
+ /**
312
+ * 获取SAP HANA存储过程定义
313
+ */
314
+ async getProcedureDefinition(dataSource: DataSource, database: string, procedureName: string): Promise<string> {
315
+ try {
316
+ const result = await dataSource.query(`
317
+ SELECT
318
+ DEFINITION as definition
319
+ FROM
320
+ PROCEDURES
321
+ WHERE
322
+ SCHEMA_NAME = ?
323
+ AND PROCEDURE_NAME = ?
324
+ `, [database, procedureName]);
325
+ return result[0]?.definition || '';
326
+ } catch (error) {
327
+ console.error('获取SAP HANA存储过程定义失败:', error);
328
+ return '';
329
+ }
330
+ }
331
+
332
+ /**
333
+ * 创建SAP HANA数据库(实际上是创建Schema)
334
+ */
335
+ async createDatabase(dataSource: DataSource, databaseName: string, options?: any): Promise<void> {
336
+ try {
337
+ await dataSource.query(`CREATE SCHEMA ${this.quoteIdentifier(databaseName)}`);
338
+ } catch (error) {
339
+ console.error('创建SAP HANA数据库失败:', error);
340
+ throw new Error(`创建数据库失败: ${error.message}`);
341
+ }
342
+ }
343
+
344
+ /**
345
+ * 删除SAP HANA数据库(实际上是删除Schema)
346
+ */
347
+ async dropDatabase(dataSource: DataSource, databaseName: string): Promise<void> {
348
+ try {
349
+ await dataSource.query(`DROP SCHEMA ${this.quoteIdentifier(databaseName)} CASCADE`);
350
+ } catch (error) {
351
+ console.error('删除SAP HANA数据库失败:', error);
352
+ throw new Error(`删除数据库失败: ${error.message}`);
353
+ }
354
+ }
355
+
356
+ /**
357
+ * 导出数据库架构
358
+ */
359
+ async exportSchema(dataSource: DataSource, databaseName: string): Promise<string> {
360
+ const tables = await this.getTables(dataSource, databaseName);
361
+ let schemaSql = `-- SAP HANA数据库架构导出 - ${databaseName}\n`;
362
+ schemaSql += `-- 导出时间: ${new Date().toISOString()}\n\n`;
363
+
364
+ for (const table of tables) {
365
+ const columns = await this.getColumns(dataSource, databaseName, table.name);
366
+ const indexes = await this.getIndexes(dataSource, databaseName, table.name);
367
+ const foreignKeys = await this.getForeignKeys(dataSource, databaseName, table.name);
368
+
369
+ schemaSql += `-- 表结构: ${table.name}\n`;
370
+ schemaSql += `CREATE COLUMN TABLE ${this.quoteIdentifier(table.name)} (\n`;
371
+
372
+ const columnDefinitions = columns.map(column => {
373
+ let definition = ` ${this.quoteIdentifier(column.name)} ${column.type}`;
374
+ if (!column.nullable)
375
+ definition += ' NOT NULL';
376
+ if (column.defaultValue !== undefined) {
377
+ const upperDefault = column.defaultValue.toString().toUpperCase();
378
+ if (upperDefault === 'CURRENT_TIMESTAMP' || upperDefault === 'NOW()' || upperDefault === 'CURRENT_DATE') {
379
+ definition += ` DEFAULT ${upperDefault}`;
380
+ } else {
381
+ definition += ` DEFAULT ${column.defaultValue === null ? 'NULL' : `'${column.defaultValue}'`}`;
382
+ }
383
+ }
384
+ if (column.isPrimary)
385
+ definition += ' PRIMARY KEY';
386
+ return definition;
387
+ });
388
+
389
+ schemaSql += columnDefinitions.join(',\n');
390
+ schemaSql += '\n);\n\n';
391
+
392
+ for (const index of indexes) {
393
+ if (index.type === 'PRIMARY' || index.name.toUpperCase() === 'PRIMARY')
394
+ continue;
395
+ schemaSql += `CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX ${this.quoteIdentifier(index.name)} ON ${this.quoteIdentifier(table.name)} (${index.columns.map(col => this.quoteIdentifier(col)).join(', ')});\n`;
396
+ }
397
+
398
+ if (indexes.length > 0)
399
+ schemaSql += '\n';
400
+
401
+ for (const foreignKey of foreignKeys) {
402
+ 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`;
403
+ }
404
+
405
+ if (foreignKeys.length > 0)
406
+ schemaSql += '\n';
407
+ }
408
+
409
+ return schemaSql;
410
+ }
411
+
412
+ /**
413
+ * 查看SAP HANA日志
414
+ */
415
+ async viewLogs(dataSource: DataSource, database?: string, limit: number = 100): Promise<any[]> {
416
+ try {
417
+ const result = await dataSource.query(`
418
+ SELECT
419
+ HOST,
420
+ PORT,
421
+ CONNECTION_ID,
422
+ TRANSACTION_ID,
423
+ STATEMENT,
424
+ START_TIME,
425
+ DURATION_MICROSECONDS
426
+ FROM
427
+ M_ACTIVE_TRANSACTIONS
428
+ ORDER BY
429
+ START_TIME DESC
430
+ LIMIT ?
431
+ `, [limit]);
432
+ return result;
433
+ } catch (error) {
434
+ console.error('获取SAP HANA日志失败:', error);
435
+ return [{ message: 'SAP HANA日志功能需要管理员权限,请检查数据库配置' }];
436
+ }
437
+ }
438
+
439
+ /**
440
+ * 备份SAP HANA数据库
441
+ */
442
+ async backupDatabase(dataSource: DataSource, databaseName: string, options?: any): Promise<string> {
443
+ try {
444
+ const backupPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'backups');
445
+ if (!fs.existsSync(backupPath)) {
446
+ fs.mkdirSync(backupPath, { recursive: true });
447
+ }
448
+
449
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
450
+ const backupFile = path.join(backupPath, `${databaseName}_${timestamp}.sql`);
451
+
452
+ const schema = await this.exportSchema(dataSource, databaseName);
453
+ fs.writeFileSync(backupFile, schema, 'utf8');
454
+
455
+ return `备份成功:${backupFile}`;
456
+ } catch (error) {
457
+ console.error('SAP HANA备份失败:', error);
458
+ throw new Error(`备份失败: ${error.message}`);
459
+ }
460
+ }
461
+
462
+ /**
463
+ * 恢复SAP HANA数据库
464
+ */
465
+ async restoreDatabase(dataSource: DataSource, databaseName: string, filePath: string, options?: any): Promise<void> {
466
+ try {
467
+ await this.executeSqlFile(dataSource, filePath);
468
+ } catch (error) {
469
+ console.error('SAP HANA恢复失败:', error);
470
+ throw new Error(`恢复失败: ${error.message}`);
471
+ }
472
+ }
473
+
474
+ /**
475
+ * 导出表数据到 SQL 文件
476
+ */
477
+ async exportTableDataToSQL(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
478
+ try {
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;
495
+ let offset = 0;
496
+ let hasMoreData = true;
497
+
498
+ while (hasMoreData) {
499
+ const query = `SELECT * FROM ${this.quoteIdentifier(tableName)} LIMIT ${batchSize} OFFSET ${offset}`;
500
+ const data = await dataSource.query(query);
501
+
502
+ if (data.length === 0) {
503
+ hasMoreData = false;
504
+ break;
505
+ }
506
+
507
+ let batchSql = '';
508
+ data.forEach((row) => {
509
+ const values = columnNames.map(column => {
510
+ const value = row[column];
511
+ if (value === null || value === undefined) {
512
+ return 'NULL';
513
+ } else if (typeof value === 'string') {
514
+ return `'${value.replace(/'/g, "''")}'`;
515
+ } else if (typeof value === 'boolean') {
516
+ return value ? '1' : '0';
517
+ } else if (value instanceof Date) {
518
+ return `'${value.toISOString().slice(0, 19).replace('T', ' ')}'`;
519
+ } else if (typeof value === 'object') {
520
+ try {
521
+ const stringValue = JSON.stringify(value);
522
+ return `'${stringValue.replace(/'/g, "''")}'`;
523
+ } catch {
524
+ return `'${String(value).replace(/'/g, "''")}'`;
525
+ }
526
+ } else {
527
+ return String(value);
528
+ }
529
+ });
530
+ batchSql += `INSERT INTO ${this.quoteIdentifier(tableName)} (${columnNames.map(col => this.quoteIdentifier(col)).join(', ')}) VALUES (${values.join(', ')});\n`;
531
+ });
532
+
533
+ fs.appendFileSync(exportFile, batchSql, 'utf8');
534
+ offset += batchSize;
535
+ console.log(`SAP HANA导出表数据进度: ${tableName} - 已处理 ${offset} 行`);
536
+ }
537
+
538
+ return exportFile;
539
+ } catch (error) {
540
+ console.error('SAP HANA导出表数据失败:', error);
541
+ throw new Error(`导出表数据失败: ${error.message}`);
542
+ }
543
+ }
544
+
545
+ /**
546
+ * 导出表数据到 CSV 文件
547
+ */
548
+ async exportTableDataToCSV(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
549
+ try {
550
+ const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
551
+ if (!fs.existsSync(exportPath)) {
552
+ fs.mkdirSync(exportPath, { recursive: true });
553
+ }
554
+
555
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
556
+ const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.csv`);
557
+
558
+ const columns = await this.getColumns(dataSource, databaseName, tableName);
559
+ const columnNames = columns.map(column => column.name);
560
+
561
+ const bom = Buffer.from([0xEF, 0xBB, 0xBF]);
562
+ fs.writeFileSync(exportFile, bom);
563
+ fs.appendFileSync(exportFile, columnNames.map(name => `"${name}"`).join(',') + '\n', 'utf8');
564
+
565
+ const batchSize = options?.batchSize || 10000;
566
+ let offset = 0;
567
+ let hasMoreData = true;
568
+
569
+ while (hasMoreData) {
570
+ const query = `SELECT * FROM ${this.quoteIdentifier(tableName)} LIMIT ${batchSize} OFFSET ${offset}`;
571
+ const data = await dataSource.query(query);
572
+
573
+ if (data.length === 0) {
574
+ hasMoreData = false;
575
+ break;
576
+ }
577
+
578
+ let batchCsv = '';
579
+ data.forEach((row) => {
580
+ const values = columnNames.map(column => {
581
+ const value = row[column];
582
+ if (value === null || value === undefined) {
583
+ return '';
584
+ } else if (typeof value === 'string') {
585
+ return `"${value.replace(/"/g, '""')}"`;
586
+ } else if (value instanceof Date) {
587
+ return `"${value.toISOString().slice(0, 19).replace('T', ' ')}"`;
588
+ } else if (typeof value === 'object' && value !== null) {
589
+ try {
590
+ return `"${JSON.stringify(value).replace(/"/g, '""')}"`;
591
+ } catch {
592
+ return `"${String(value).replace(/"/g, '""')}"`;
593
+ }
594
+ } else {
595
+ return String(value);
596
+ }
597
+ });
598
+ batchCsv += values.join(',') + '\n';
599
+ });
600
+
601
+ fs.appendFileSync(exportFile, batchCsv, 'utf8');
602
+ offset += batchSize;
603
+ console.log(`SAP HANA导出表数据到CSV进度: ${tableName} - 已处理 ${offset} 行`);
604
+ }
605
+
606
+ return exportFile;
607
+ } catch (error) {
608
+ console.error('SAP HANA导出表数据到CSV失败:', error);
609
+ throw new Error(`导出表数据到CSV失败: ${error.message}`);
610
+ }
611
+ }
612
+
613
+ /**
614
+ * 导出表数据到 JSON 文件
615
+ */
616
+ async exportTableDataToJSON(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
617
+ try {
618
+ const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
619
+ if (!fs.existsSync(exportPath)) {
620
+ fs.mkdirSync(exportPath, { recursive: true });
621
+ }
622
+
623
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
624
+ const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.json`);
625
+
626
+ const batchSize = options?.batchSize || 10000;
627
+ let offset = 0;
628
+ let hasMoreData = true;
629
+ let allData: any[] = [];
630
+
631
+ while (hasMoreData) {
632
+ const query = `SELECT * FROM ${this.quoteIdentifier(tableName)} LIMIT ${batchSize} OFFSET ${offset}`;
633
+ const data = await dataSource.query(query);
634
+
635
+ if (data.length === 0) {
636
+ hasMoreData = false;
637
+ break;
638
+ }
639
+
640
+ allData = allData.concat(data);
641
+ offset += batchSize;
642
+ console.log(`SAP HANA导出表数据到JSON进度: ${tableName} - 已处理 ${offset} 行`);
643
+ }
644
+
645
+ fs.writeFileSync(exportFile, JSON.stringify(allData, null, 2), 'utf8');
646
+ return exportFile;
647
+ } catch (error) {
648
+ console.error('SAP HANA导出表数据到JSON失败:', error);
649
+ throw new Error(`导出表数据到JSON失败: ${error.message}`);
650
+ }
651
+ }
652
+
653
+ /**
654
+ * 导出表数据到 Excel 文件
655
+ */
656
+ async exportTableDataToExcel(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
657
+ try {
658
+ const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
659
+ if (!fs.existsSync(exportPath)) {
660
+ fs.mkdirSync(exportPath, { recursive: true });
661
+ }
662
+
663
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
664
+ const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.xlsx`);
665
+
666
+ const columns = await this.getColumns(dataSource, databaseName, tableName);
667
+ const columnNames = columns.map(column => column.name);
668
+
669
+ const batchSize = options?.batchSize || 10000;
670
+ let offset = 0;
671
+ let hasMoreData = true;
672
+ let allData: any[] = [];
673
+
674
+ while (hasMoreData) {
675
+ const query = `SELECT * FROM ${this.quoteIdentifier(tableName)} LIMIT ${batchSize} OFFSET ${offset}`;
676
+ const data = await dataSource.query(query);
677
+
678
+ if (data.length === 0) {
679
+ hasMoreData = false;
680
+ break;
681
+ }
682
+
683
+ allData = allData.concat(data);
684
+ offset += batchSize;
685
+ console.log(`SAP HANA导出表数据到Excel进度: ${tableName} - 已处理 ${offset} 行`);
686
+ }
687
+
688
+ const ExcelJS = require('exceljs');
689
+ const workbook = new ExcelJS.Workbook();
690
+ const worksheet = workbook.addWorksheet(tableName);
691
+
692
+ worksheet.columns = columnNames.map(name => ({
693
+ header: name,
694
+ key: name
695
+ }));
696
+
697
+ worksheet.addRows(allData);
698
+
699
+ await workbook.xlsx.writeFile(exportFile);
700
+ return exportFile;
701
+ } catch (error) {
702
+ console.error('SAP HANA导出表数据到Excel失败:', error);
703
+ throw new Error(`导出表数据到Excel失败: ${error.message}`);
704
+ }
705
+ }
706
+
707
+ /**
708
+ * SAP HANA使用双引号作为标识符
709
+ */
710
+ public quoteIdentifier(identifier: string): string {
711
+ return `"${identifier}"`;
712
+ }
713
+ }