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.
- package/.dockerignore +21 -0
- package/.editorconfig +11 -0
- package/.eslintrc.cjs +14 -0
- package/.eslintrc.json +7 -0
- package/.prettierrc.js +3 -0
- package/.tpl.env +22 -0
- package/README.md +260 -0
- package/bin/build.sh +28 -0
- package/bin/deploy.sh +8 -0
- package/bin/dev.sh +10 -0
- package/bin/docker/.env +4 -0
- package/bin/docker/dev-docker-compose.yml +43 -0
- package/bin/docker/dev.Dockerfile +24 -0
- package/bin/docker/prod-docker-compose.yml +17 -0
- package/bin/docker/prod.Dockerfile +29 -0
- package/bin/fdb2.js +142 -0
- package/data/connections.demo.json +32 -0
- package/env.d.ts +1 -0
- package/nw-build.js +120 -0
- package/nw-dev.js +65 -0
- package/package.json +114 -0
- package/public/favicon.ico +0 -0
- package/public/index.html +9 -0
- package/public/modules/header.tpl +14 -0
- package/public/modules/initial_state.tpl +55 -0
- package/server/index.ts +677 -0
- package/server/model/connection.entity.ts +66 -0
- package/server/model/database.entity.ts +246 -0
- package/server/service/connection.service.ts +334 -0
- package/server/service/database/base.service.ts +363 -0
- package/server/service/database/database.service.ts +510 -0
- package/server/service/database/index.ts +7 -0
- package/server/service/database/mssql.service.ts +723 -0
- package/server/service/database/mysql.service.ts +761 -0
- package/server/service/database/oracle.service.ts +839 -0
- package/server/service/database/postgres.service.ts +744 -0
- package/server/service/database/sqlite.service.ts +559 -0
- package/server/service/session.service.ts +158 -0
- package/server.js +128 -0
- package/src/adapter/ajax.ts +135 -0
- package/src/assets/base.css +1 -0
- package/src/assets/database.css +950 -0
- package/src/assets/images/collapse.png +0 -0
- package/src/assets/images/no-login.png +0 -0
- package/src/assets/images/svg/illustrations/illustration-1.svg +1 -0
- package/src/assets/images/svg/illustrations/illustration-2.svg +2 -0
- package/src/assets/images/svg/illustrations/illustration-3.svg +50 -0
- package/src/assets/images/svg/illustrations/illustration-4.svg +1 -0
- package/src/assets/images/svg/illustrations/illustration-5.svg +73 -0
- package/src/assets/images/svg/illustrations/illustration-6.svg +89 -0
- package/src/assets/images/svg/illustrations/illustration-7.svg +39 -0
- package/src/assets/images/svg/illustrations/illustration-8.svg +1 -0
- package/src/assets/images/svg/separators/curve-2.svg +3 -0
- package/src/assets/images/svg/separators/curve.svg +3 -0
- package/src/assets/images/svg/separators/line.svg +3 -0
- package/src/assets/images/theme/light/screen-1-1000x800.jpg +0 -0
- package/src/assets/images/theme/light/screen-2-1000x800.jpg +0 -0
- package/src/assets/login/bg.jpg +0 -0
- package/src/assets/login/bg.png +0 -0
- package/src/assets/login/left.jpg +0 -0
- package/src/assets/logo.svg +73 -0
- package/src/assets/logo.webp +0 -0
- package/src/assets/main.css +1 -0
- package/src/base/config.ts +20 -0
- package/src/base/detect.ts +134 -0
- package/src/base/entity.ts +92 -0
- package/src/base/eventBus.ts +37 -0
- package/src/base//345/237/272/347/241/200/345/261/202.md +7 -0
- package/src/components/connection-editor/index.vue +590 -0
- package/src/components/dataGrid/index.vue +105 -0
- package/src/components/dataGrid/pagination.vue +106 -0
- package/src/components/loading/index.vue +43 -0
- package/src/components/modal/index.ts +181 -0
- package/src/components/modal/index.vue +560 -0
- package/src/components/toast/index.ts +44 -0
- package/src/components/toast/toast.vue +58 -0
- package/src/components/user/name.vue +104 -0
- package/src/components/user/selector.vue +416 -0
- package/src/domain/SysConfig.ts +74 -0
- package/src/platform/App.vue +8 -0
- package/src/platform/database/components/connection-detail.vue +1154 -0
- package/src/platform/database/components/data-editor.vue +478 -0
- package/src/platform/database/components/data-import-export.vue +1602 -0
- package/src/platform/database/components/database-detail.vue +1173 -0
- package/src/platform/database/components/database-monitor.vue +1086 -0
- package/src/platform/database/components/db-tools.vue +577 -0
- package/src/platform/database/components/query-history.vue +1349 -0
- package/src/platform/database/components/sql-executor.vue +738 -0
- package/src/platform/database/components/sql-query-editor.vue +1046 -0
- package/src/platform/database/components/table-detail.vue +1376 -0
- package/src/platform/database/components/table-editor.vue +690 -0
- package/src/platform/database/explorer.vue +1840 -0
- package/src/platform/database/index.vue +1193 -0
- package/src/platform/database/layout.vue +367 -0
- package/src/platform/database/router.ts +37 -0
- package/src/platform/database/styles/common.scss +602 -0
- package/src/platform/database/types/common.ts +445 -0
- package/src/platform/database/utils/export.ts +232 -0
- package/src/platform/database/utils/helpers.ts +437 -0
- package/src/platform/index.ts +33 -0
- package/src/platform/router.ts +41 -0
- package/src/service/base.ts +128 -0
- package/src/service/database.ts +500 -0
- package/src/service/login.ts +121 -0
- package/src/shims-vue.d.ts +7 -0
- package/src/stores/connection.ts +266 -0
- package/src/stores/session.ts +87 -0
- package/src/typings/database-types.ts +413 -0
- package/src/typings/database.ts +364 -0
- package/src/typings/global.d.ts +58 -0
- package/src/typings/pinia.d.ts +8 -0
- package/src/utils/clipboard.ts +30 -0
- package/src/utils/database-types.ts +243 -0
- package/src/utils/modal.ts +124 -0
- package/src/utils/request.ts +55 -0
- package/src/utils/sleep.ts +4 -0
- package/src/utils/toast.ts +73 -0
- package/src/utils/util.ts +171 -0
- package/src/utils/xlsx.ts +228 -0
- package/tsconfig.json +33 -0
- package/tsconfig.server.json +19 -0
- package/view/index.html +9 -0
- package/view/modules/header.tpl +14 -0
- package/view/modules/initial_state.tpl +20 -0
- package/vite.config.ts +384 -0
|
@@ -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: 0, // SQLite需要额外查询
|
|
47
|
+
dataSize: 0,
|
|
48
|
+
indexSize: 0
|
|
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
|
+
}
|