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