fdb2 1.0.8 → 1.0.10

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 (235) hide show
  1. package/.dockerignore +21 -21
  2. package/.editorconfig +11 -11
  3. package/.eslintrc.cjs +14 -14
  4. package/.eslintrc.json +7 -7
  5. package/.prettierrc.js +3 -3
  6. package/.tpl.env +21 -21
  7. package/.vscodeignore +45 -45
  8. package/README.md +312 -312
  9. package/bin/build.sh +28 -28
  10. package/bin/deploy.sh +8 -8
  11. package/bin/dev.sh +10 -10
  12. package/bin/docker/dev-docker-compose.yml +43 -43
  13. package/bin/docker/dev.Dockerfile +24 -24
  14. package/bin/docker/prod-docker-compose.yml +17 -17
  15. package/bin/docker/prod.Dockerfile +29 -29
  16. package/bin/fdb2.js +220 -220
  17. package/dist/package.json +29 -29
  18. package/dist/pnpm-lock.yaml +1042 -354
  19. package/dist/public/explorer.css +1464 -1437
  20. package/dist/public/explorer.js +759 -223
  21. package/dist/public/index.css +1026 -1026
  22. package/dist/public/index.js +15 -9
  23. package/dist/public/layout.css +221 -221
  24. package/dist/public/layout.js +1 -1
  25. package/dist/public/vue.js +8 -2
  26. package/dist/scripts/preinstall.js +112 -112
  27. package/dist/server/index.d.ts.map +1 -1
  28. package/dist/server/index.js +8 -0
  29. package/dist/server/index.js.map +1 -1
  30. package/dist/server/index.ts +680 -671
  31. package/dist/server/model/connection.entity.ts +65 -65
  32. package/dist/server/model/database.entity.ts +245 -245
  33. package/dist/server/service/connection.service.d.ts +6 -1
  34. package/dist/server/service/connection.service.d.ts.map +1 -1
  35. package/dist/server/service/connection.service.js +18 -1
  36. package/dist/server/service/connection.service.js.map +1 -1
  37. package/dist/server/service/connection.service.ts +358 -341
  38. package/dist/server/service/database/base.service.d.ts +27 -0
  39. package/dist/server/service/database/base.service.d.ts.map +1 -1
  40. package/dist/server/service/database/base.service.js +17 -0
  41. package/dist/server/service/database/base.service.js.map +1 -1
  42. package/dist/server/service/database/base.service.ts +406 -367
  43. package/dist/server/service/database/cockroachdb.service.d.ts +16 -0
  44. package/dist/server/service/database/cockroachdb.service.d.ts.map +1 -1
  45. package/dist/server/service/database/cockroachdb.service.js +220 -154
  46. package/dist/server/service/database/cockroachdb.service.js.map +1 -1
  47. package/dist/server/service/database/cockroachdb.service.ts +871 -782
  48. package/dist/server/service/database/database.service.d.ts +4 -0
  49. package/dist/server/service/database/database.service.d.ts.map +1 -1
  50. package/dist/server/service/database/database.service.js +123 -0
  51. package/dist/server/service/database/database.service.js.map +1 -1
  52. package/dist/server/service/database/database.service.ts +775 -638
  53. package/dist/server/service/database/index.ts +6 -6
  54. package/dist/server/service/database/mongodb.service.d.ts +16 -0
  55. package/dist/server/service/database/mongodb.service.d.ts.map +1 -1
  56. package/dist/server/service/database/mongodb.service.js +35 -0
  57. package/dist/server/service/database/mongodb.service.js.map +1 -1
  58. package/dist/server/service/database/mongodb.service.ts +39 -1
  59. package/dist/server/service/database/mssql.service.d.ts +16 -0
  60. package/dist/server/service/database/mssql.service.d.ts.map +1 -1
  61. package/dist/server/service/database/mssql.service.js +168 -96
  62. package/dist/server/service/database/mssql.service.js.map +1 -1
  63. package/dist/server/service/database/mssql.service.ts +931 -840
  64. package/dist/server/service/database/mysql.service.d.ts +16 -0
  65. package/dist/server/service/database/mysql.service.d.ts.map +1 -1
  66. package/dist/server/service/database/mysql.service.js +189 -80
  67. package/dist/server/service/database/mysql.service.js.map +1 -1
  68. package/dist/server/service/database/mysql.service.ts +1025 -890
  69. package/dist/server/service/database/oracle.service.d.ts +16 -0
  70. package/dist/server/service/database/oracle.service.d.ts.map +1 -1
  71. package/dist/server/service/database/oracle.service.js +182 -120
  72. package/dist/server/service/database/oracle.service.js.map +1 -1
  73. package/dist/server/service/database/oracle.service.ts +1035 -959
  74. package/dist/server/service/database/postgres.service.d.ts +16 -0
  75. package/dist/server/service/database/postgres.service.d.ts.map +1 -1
  76. package/dist/server/service/database/postgres.service.js +154 -88
  77. package/dist/server/service/database/postgres.service.js.map +1 -1
  78. package/dist/server/service/database/postgres.service.ts +960 -871
  79. package/dist/server/service/database/sap.service.d.ts +16 -0
  80. package/dist/server/service/database/sap.service.d.ts.map +1 -1
  81. package/dist/server/service/database/sap.service.js +66 -0
  82. package/dist/server/service/database/sap.service.js.map +1 -1
  83. package/dist/server/service/database/sap.service.ts +89 -0
  84. package/dist/server/service/database/sqlite.service.d.ts +17 -1
  85. package/dist/server/service/database/sqlite.service.d.ts.map +1 -1
  86. package/dist/server/service/database/sqlite.service.js +78 -19
  87. package/dist/server/service/database/sqlite.service.js.map +1 -1
  88. package/dist/server/service/database/sqlite.service.ts +787 -708
  89. package/dist/server/service/session.service.ts +158 -158
  90. package/dist/view/index.html +38 -38
  91. package/env.d.ts +1 -1
  92. package/package.json +7 -2
  93. package/packages/vscode/.vscodeignore +44 -44
  94. package/packages/vscode/README.md +62 -62
  95. package/packages/vscode/out/database-services/cockroachdb.service.js +154 -154
  96. package/packages/vscode/out/database-services/mssql.service.js +96 -96
  97. package/packages/vscode/out/database-services/mysql.service.js +80 -80
  98. package/packages/vscode/out/database-services/oracle.service.js +120 -120
  99. package/packages/vscode/out/database-services/postgres.service.js +88 -88
  100. package/packages/vscode/out/database-services/sqlite.service.js +18 -18
  101. package/packages/vscode/out/provider/WebViewProvider.js +32 -32
  102. package/packages/vscode/package.json +142 -142
  103. package/packages/vscode/resources/icon.svg +5 -5
  104. package/packages/vscode/resources/webview/connection.css +41 -41
  105. package/packages/vscode/resources/webview/database.css +163 -163
  106. package/packages/vscode/resources/webview/index.html +9 -9
  107. package/packages/vscode/resources/webview/modules/header.tpl +13 -13
  108. package/packages/vscode/resources/webview/modules/initial_state.tpl +54 -54
  109. package/packages/vscode/resources/webview/query.css +104 -104
  110. package/packages/vscode/src/database-services/base.service.ts +362 -362
  111. package/packages/vscode/src/database-services/cockroachdb.service.ts +659 -659
  112. package/packages/vscode/src/database-services/connection.service.ts +340 -340
  113. package/packages/vscode/src/database-services/database.service.ts +629 -629
  114. package/packages/vscode/src/database-services/index.ts +6 -6
  115. package/packages/vscode/src/database-services/model/connection.entity.ts +65 -65
  116. package/packages/vscode/src/database-services/model/database.entity.ts +245 -245
  117. package/packages/vscode/src/database-services/mssql.service.ts +722 -722
  118. package/packages/vscode/src/database-services/mysql.service.ts +760 -760
  119. package/packages/vscode/src/database-services/oracle.service.ts +831 -831
  120. package/packages/vscode/src/database-services/postgres.service.ts +740 -740
  121. package/packages/vscode/src/database-services/sqlite.service.ts +558 -558
  122. package/packages/vscode/src/extension.ts +76 -76
  123. package/packages/vscode/src/provider/DatabaseTreeProvider.ts +167 -167
  124. package/packages/vscode/src/provider/WebViewProvider.ts +277 -277
  125. package/packages/vscode/src/service/DatabaseServiceBridge.ts +414 -414
  126. package/packages/vscode/src/typings/connection.ts +90 -90
  127. package/packages/vscode/tsconfig.json +21 -21
  128. package/public/index.html +9 -9
  129. package/public/modules/header.tpl +13 -13
  130. package/public/modules/initial_state.tpl +54 -54
  131. package/scripts/preinstall.js +112 -112
  132. package/server/index.ts +680 -671
  133. package/server/model/connection.entity.ts +65 -65
  134. package/server/model/database.entity.ts +245 -245
  135. package/server/service/connection.service.ts +358 -341
  136. package/server/service/database/base.service.ts +406 -367
  137. package/server/service/database/cockroachdb.service.ts +871 -782
  138. package/server/service/database/database.service.ts +775 -638
  139. package/server/service/database/index.ts +6 -6
  140. package/server/service/database/mongodb.service.ts +39 -1
  141. package/server/service/database/mssql.service.ts +931 -840
  142. package/server/service/database/mysql.service.ts +1025 -890
  143. package/server/service/database/oracle.service.ts +1035 -959
  144. package/server/service/database/postgres.service.ts +960 -871
  145. package/server/service/database/sap.service.ts +89 -0
  146. package/server/service/database/sqlite.service.ts +787 -708
  147. package/server/service/session.service.ts +158 -158
  148. package/server/tsconfig.json +20 -20
  149. package/server.js +149 -149
  150. package/server.pid +1 -0
  151. package/src/adapter/ajax.ts +135 -135
  152. package/src/assets/base.css +1 -1
  153. package/src/assets/database.css +949 -949
  154. package/src/assets/images/svg/illustrations/illustration-1.svg +1 -1
  155. package/src/assets/images/svg/illustrations/illustration-2.svg +2 -2
  156. package/src/assets/images/svg/illustrations/illustration-3.svg +50 -50
  157. package/src/assets/images/svg/illustrations/illustration-4.svg +1 -1
  158. package/src/assets/images/svg/illustrations/illustration-5.svg +73 -73
  159. package/src/assets/images/svg/illustrations/illustration-6.svg +89 -89
  160. package/src/assets/images/svg/illustrations/illustration-7.svg +39 -39
  161. package/src/assets/images/svg/separators/curve-2.svg +3 -3
  162. package/src/assets/images/svg/separators/curve.svg +3 -3
  163. package/src/assets/images/svg/separators/line.svg +3 -3
  164. package/src/assets/logo.svg +73 -73
  165. package/src/assets/main.css +1 -1
  166. package/src/base/config.ts +20 -20
  167. package/src/base/detect.ts +134 -134
  168. package/src/base/entity.ts +92 -92
  169. package/src/base/eventBus.ts +36 -36
  170. package/src/components/connection-editor/index.vue +588 -588
  171. package/src/components/dataGrid/index.vue +104 -104
  172. package/src/components/dataGrid/pagination.vue +105 -105
  173. package/src/components/loading/index.vue +42 -42
  174. package/src/components/modal/index.ts +180 -180
  175. package/src/components/modal/index.vue +560 -560
  176. package/src/components/toast/index.ts +43 -43
  177. package/src/components/toast/toast.vue +57 -57
  178. package/src/components/user/name.vue +103 -103
  179. package/src/components/user/selector.vue +416 -416
  180. package/src/domain/SysConfig.ts +74 -74
  181. package/src/platform/App.vue +7 -7
  182. package/src/platform/database/components/connection-detail.vue +1153 -1154
  183. package/src/platform/database/components/data-editor.vue +477 -477
  184. package/src/platform/database/components/database-detail.vue +1173 -1172
  185. package/src/platform/database/components/database-monitor.vue +1085 -1085
  186. package/src/platform/database/components/db-tools.vue +1264 -816
  187. package/src/platform/database/components/query-history.vue +1348 -1348
  188. package/src/platform/database/components/sql-executor.vue +737 -737
  189. package/src/platform/database/components/sql-query-editor.vue +1045 -1045
  190. package/src/platform/database/components/table-detail.vue +1375 -1376
  191. package/src/platform/database/components/table-editor.vue +916 -916
  192. package/src/platform/database/explorer.vue +1839 -1839
  193. package/src/platform/database/index.vue +1192 -1192
  194. package/src/platform/database/layout.vue +366 -366
  195. package/src/platform/database/router.ts +36 -36
  196. package/src/platform/database/styles/common.scss +601 -601
  197. package/src/platform/database/types/common.ts +444 -444
  198. package/src/platform/database/utils/export.ts +231 -231
  199. package/src/platform/database/utils/helpers.ts +436 -436
  200. package/src/platform/index.ts +32 -32
  201. package/src/platform/router.ts +40 -40
  202. package/src/platform/vscode/bridge.ts +121 -121
  203. package/src/platform/vscode/components/ConnectionPanel.vue +272 -272
  204. package/src/platform/vscode/components/DatabasePanel.vue +532 -532
  205. package/src/platform/vscode/components/QueryPanel.vue +371 -371
  206. package/src/platform/vscode/entry/connection.ts +13 -13
  207. package/src/platform/vscode/entry/database.ts +13 -13
  208. package/src/platform/vscode/entry/query.ts +13 -13
  209. package/src/platform/vscode/index.ts +5 -5
  210. package/src/service/base.ts +133 -127
  211. package/src/service/database.ts +505 -495
  212. package/src/service/login.ts +120 -120
  213. package/src/shims-vue.d.ts +6 -6
  214. package/src/stores/connection.ts +266 -266
  215. package/src/stores/session.ts +87 -87
  216. package/src/typings/database-types.ts +412 -412
  217. package/src/typings/database.ts +363 -363
  218. package/src/typings/global.d.ts +58 -58
  219. package/src/typings/pinia.d.ts +7 -7
  220. package/src/utils/clipboard.ts +29 -29
  221. package/src/utils/database-types.ts +242 -242
  222. package/src/utils/modal.ts +123 -123
  223. package/src/utils/request.ts +55 -55
  224. package/src/utils/sleep.ts +3 -3
  225. package/src/utils/toast.ts +73 -73
  226. package/src/utils/util.ts +171 -171
  227. package/src/utils/xlsx.ts +228 -228
  228. package/tsconfig.json +33 -33
  229. package/view/index.html +9 -9
  230. package/view/modules/header.tpl +13 -13
  231. package/view/modules/initial_state.tpl +19 -19
  232. package/vite.config.ts +424 -424
  233. package/vite.config.vscode.ts +47 -47
  234. package/fdb2.server.pid +0 -1
  235. package/server/backups/db_ai_breakout_2026-03-11T08-38-48-677Z.sql +0 -0
@@ -1,960 +1,1036 @@
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
- * Oracle数据库服务实现
15
- */
16
- export class OracleService extends BaseDatabaseService {
17
-
18
- getDatabaseType(): string {
19
- return 'oracle';
20
- }
21
-
22
- /**
23
- * 获取Oracle数据库列表(用户schema)
24
- */
25
- async getDatabases(dataSource: DataSource): Promise<string[]> {
26
- const result = await dataSource.query(`
27
- SELECT username as name
28
- FROM all_users
29
- WHERE username NOT IN ('SYS', 'SYSTEM', 'XDB', 'OUTLN')
30
- ORDER BY username
31
- `);
32
- return result.map((row: any) => row.name);
33
- }
34
-
35
- /**
36
- * 获取Oracle表列表
37
- */
38
- async getTables(dataSource: DataSource, database: string): Promise<TableEntity[]> {
39
- const result = await dataSource.query(`
40
- SELECT
41
- table_name as name,
42
- 'TABLE' as type
43
- FROM all_tables
44
- WHERE owner = ?
45
- AND table_name NOT LIKE 'BIN$%'
46
- AND temporary = 'N'
47
- ORDER BY table_name
48
- `, [database.toUpperCase()]);
49
-
50
- return result.map((row: any) => ({
51
- name: row.name,
52
- type: row.type,
53
- rowCount: undefined,
54
- dataSize: undefined,
55
- indexSize: undefined
56
- }));
57
- }
58
-
59
- /**
60
- * 获取Oracle列信息
61
- */
62
- async getColumns(dataSource: DataSource, database: string, table: string): Promise<ColumnEntity[]> {
63
- // 使用兼容的SQL查询,移除可能不兼容的字段
64
- const result = await dataSource.query(`
65
- SELECT
66
- column_name as name,
67
- data_type as type,
68
- data_length as length,
69
- nullable as nullable,
70
- data_default as defaultValue
71
- FROM all_tab_columns
72
- WHERE owner = ?
73
- AND table_name = ?
74
- ORDER BY column_id
75
- `, [
76
- database.toUpperCase(),
77
- table.toUpperCase()
78
- ]);
79
-
80
- // 获取主键信息
81
- const primaryKeys = await this.getPrimaryKeys(dataSource, database, table);
82
-
83
- // 获取序列信息(Oracle使用序列实现自增)
84
- const sequenceColumns = await this.getSequenceColumns(dataSource, database, 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)或NUMBER(M,D)类型的精度
93
- const decimalMatch = dataType.match(/(DECIMAL|NUMBER)\s*\(\s*(\d+)\s*(,\s*(\d+)\s*)?\s*\)/i);
94
- if (decimalMatch) {
95
- precision = parseInt(decimalMatch[2]);
96
- if (decimalMatch[3]) {
97
- scale = parseInt(decimalMatch[3].replace(/\D/g, ''));
98
- }
99
- }
100
-
101
- return {
102
- name: row.name,
103
- type: row.type + (row.length ? `(${row.length})` : ''),
104
- nullable: row.nullable === 'Y',
105
- defaultValue: row.defaultValue,
106
- isPrimary: primaryKeys.includes(row.name),
107
- isAutoIncrement: sequenceColumns.includes(row.name),
108
- length: row.length,
109
- precision: precision,
110
- scale: scale
111
- };
112
- });
113
- }
114
-
115
- /**
116
- * 获取Oracle索引信息
117
- */
118
- async getIndexes(dataSource: DataSource, database: string, table: string): Promise<IndexEntity[]> {
119
- const result = await dataSource.query(`
120
- SELECT DISTINCT
121
- i.index_name as name,
122
- DECODE(i.uniqueness, 'UNIQUE', 'UNIQUE INDEX', 'INDEX') as type,
123
- ic.column_name as column
124
- FROM all_indexes i
125
- JOIN all_ind_columns ic ON i.index_name = ic.index_name
126
- WHERE i.table_owner = ?
127
- AND i.table_name = ?
128
- AND i.index_name NOT IN (SELECT constraint_name
129
- FROM all_constraints
130
- WHERE constraint_type = 'P'
131
- AND table_owner = ?)
132
- ORDER BY i.index_name, ic.column_position
133
- `, [
134
- database.toUpperCase(),
135
- table.toUpperCase(),
136
- database.toUpperCase()
137
- ]);
138
-
139
- // 按索引名分组
140
- const indexMap = new Map<string, IndexEntity>();
141
- result.forEach((row: any) => {
142
- if (!indexMap.has(row.name)) {
143
- indexMap.set(row.name, {
144
- name: row.name,
145
- type: row.type,
146
- columns: [],
147
- unique: row.type.includes('UNIQUE')
148
- });
149
- }
150
- indexMap.get(row.name)!.columns.push(row.column);
151
- });
152
-
153
- return Array.from(indexMap.values());
154
- }
155
-
156
- /**
157
- * 获取Oracle外键信息
158
- */
159
- async getForeignKeys(dataSource: DataSource, database: string, table: string): Promise<ForeignKeyEntity[]> {
160
- const result = await dataSource.query(`
161
- SELECT
162
- c.constraint_name as name,
163
- cc.column_name as column,
164
- r.table_name as referencedTable,
165
- rc.column_name as referencedColumn,
166
- c.delete_rule as onDelete
167
- FROM all_constraints c
168
- JOIN all_cons_columns cc ON c.constraint_name = cc.constraint_name
169
- JOIN all_constraints r ON c.r_constraint_name = r.constraint_name
170
- JOIN all_cons_columns rc ON r.constraint_name = rc.constraint_name AND cc.position = rc.position
171
- WHERE c.constraint_type = 'R'
172
- AND c.owner = ?
173
- AND c.table_name = ?
174
- `, [
175
- database.toUpperCase(),
176
- table.toUpperCase()
177
- ]);
178
-
179
- return result.map((row: any) => ({
180
- name: row.name,
181
- column: row.column,
182
- referencedTable: row.referencedTable,
183
- referencedColumn: row.referencedColumn,
184
- onDelete: row.onDelete || 'NO ACTION',
185
- onUpdate: 'NO ACTION' // Oracle不支持ON UPDATE
186
- }));
187
- }
188
-
189
- /**
190
- * 获取Oracle数据库大小(用户schema大小)
191
- */
192
- async getDatabaseSize(dataSource: DataSource, database: string): Promise<number> {
193
- const result = await dataSource.query(`
194
- SELECT SUM(bytes) as size
195
- FROM user_segments
196
- `);
197
- return result[0]?.size || 0;
198
- }
199
-
200
- /**
201
- * 获取表统计信息
202
- */
203
- private async getTableStats(dataSource: DataSource, database: string, table: string): Promise<any> {
204
- try {
205
- const result = await dataSource.query(`
206
- SELECT
207
- num_rows as rowCount,
208
- (SELECT SUM(bytes) FROM user_segments WHERE segment_name = ?) as dataSize
209
- FROM all_tables
210
- WHERE owner = ? AND table_name = ?
211
- `, [
212
- table.toUpperCase(),
213
- database.toUpperCase(),
214
- table.toUpperCase()
215
- ]);
216
-
217
- return {
218
- rowCount: result[0]?.rowCount || 0,
219
- dataSize: result[0]?.dataSize || 0,
220
- indexSize: 0 // Oracle索引大小计算较复杂,这里简化处理
221
- };
222
- } catch (error) {
223
- // 如果没有统计信息,返回默认值
224
- return {
225
- rowCount: 0,
226
- dataSize: 0,
227
- indexSize: 0
228
- };
229
- }
230
- }
231
-
232
- /**
233
- * 获取主键信息
234
- */
235
- private async getPrimaryKeys(dataSource: DataSource, database: string, table: string): Promise<string[]> {
236
- const result = await dataSource.query(`
237
- SELECT column_name
238
- FROM all_cons_columns cc
239
- JOIN all_constraints c ON cc.constraint_name = c.constraint_name
240
- WHERE c.constraint_type = 'P'
241
- AND c.owner = ?
242
- AND c.table_name = ?
243
- ORDER BY cc.position
244
- `, [
245
- database.toUpperCase(),
246
- table.toUpperCase()
247
- ]);
248
- return result.map((row: any) => row.column_name);
249
- }
250
-
251
- /**
252
- * 获取Oracle序列信息(用于检测自增列)
253
- */
254
- private async getSequenceColumns(dataSource: DataSource, database: string, table: string): Promise<string[]> {
255
- try {
256
- const result = await dataSource.query(`
257
- SELECT acc.column_name
258
- FROM all_tab_columns acc
259
- JOIN all_triggers at ON acc.table_name = at.table_name
260
- AND acc.owner = at.owner
261
- JOIN all_sequences seq ON at.trigger_name LIKE seq.sequence_name || '%'
262
- WHERE acc.owner = ?
263
- AND acc.table_name = ?
264
- AND acc.data_default IS NOT NULL
265
- AND acc.data_default LIKE seq.sequence_name || '.nextval'
266
- `, [
267
- database.toUpperCase(),
268
- table.toUpperCase()
269
- ]);
270
- return result.map((row: any) => row.column_name);
271
- } catch (error) {
272
- // 如果查询失败,返回空数组
273
- return [];
274
- }
275
- }
276
-
277
- /**
278
- * Oracle的标识符引用方式
279
- */
280
- public quoteIdentifier(identifier: string): string {
281
- return `"${identifier.toUpperCase()}"`;
282
- }
283
-
284
- /**
285
- * 获取Oracle视图列表
286
- */
287
- async getViews(dataSource: DataSource, database: string): Promise<any[]> {
288
- const result = await dataSource.query(`
289
- SELECT
290
- view_name as name,
291
- '' as comment
292
- FROM all_views
293
- WHERE owner = ?
294
- ORDER BY view_name
295
- `, [database.toUpperCase()]);
296
-
297
- return result.map((row: any) => ({
298
- name: row.name,
299
- comment: row.comment || '',
300
- schemaName: database
301
- }));
302
- }
303
-
304
- /**
305
- * 获取Oracle视图定义
306
- */
307
- async getViewDefinition(dataSource: DataSource, database: string, viewName: string): Promise<string> {
308
- const result = await dataSource.query(`
309
- SELECT text as definition
310
- FROM all_views
311
- WHERE owner = ?
312
- AND view_name = ?
313
- `, [database.toUpperCase(), viewName.toUpperCase()]);
314
-
315
- return result[0]?.definition || '';
316
- }
317
-
318
- /**
319
- * 获取Oracle存储过程列表
320
- */
321
- async getProcedures(dataSource: DataSource, database: string): Promise<any[]> {
322
- const result = await dataSource.query(`
323
- SELECT
324
- object_name as name,
325
- '' as comment,
326
- 'PROCEDURE' as type,
327
- '' as returnType,
328
- 'PL/SQL' as language
329
- FROM all_objects
330
- WHERE owner = ?
331
- AND object_type IN ('PROCEDURE', 'FUNCTION')
332
- AND status = 'VALID'
333
- ORDER BY object_name
334
- `, [database.toUpperCase()]);
335
-
336
- return result.map((row: any) => ({
337
- name: row.name,
338
- comment: row.comment || '',
339
- type: row.type,
340
- returnType: row.returnType || '',
341
- language: row.language || 'PL/SQL'
342
- }));
343
- }
344
-
345
- /**
346
- * 获取Oracle存储过程定义
347
- */
348
- async getProcedureDefinition(dataSource: DataSource, database: string, procedureName: string): Promise<string> {
349
- const result = await dataSource.query(`
350
- SELECT text as definition
351
- FROM all_source
352
- WHERE owner = ?
353
- AND name = ?
354
- ORDER BY line
355
- `, [database.toUpperCase(), procedureName.toUpperCase()]);
356
-
357
- return result.map((row: any) => row.definition).join('\n') || '';
358
- }
359
-
360
- /**
361
- * 创建Oracle数据库
362
- */
363
- async createDatabase(dataSource: DataSource, databaseName: string, options?: any): Promise<void> {
364
- // Oracle数据库创建比较复杂,通常需要DBA权限
365
- // 这里提供基本的创建语法
366
- let sql = `CREATE DATABASE ${this.quoteIdentifier(databaseName)}`;
367
-
368
- if (options) {
369
- const clauses = [];
370
-
371
- if (options.user) {
372
- clauses.push(`USER ${options.user}`);
373
- }
374
-
375
- if (options.password) {
376
- clauses.push(`IDENTIFIED BY ${options.password}`);
377
- }
378
-
379
- if (options.defaultTablespace) {
380
- clauses.push(`DEFAULT TABLESPACE ${options.defaultTablespace}`);
381
- }
382
-
383
- if (options.tempTablespace) {
384
- clauses.push(`TEMPORARY TABLESPACE ${options.tempTablespace}`);
385
- }
386
-
387
- if (options.datafile) {
388
- clauses.push(`DATAFILE '${options.datafile}'`);
389
- }
390
-
391
- if (options.size) {
392
- clauses.push(`SIZE ${options.size}`);
393
- }
394
-
395
- if (options.autoExtend) {
396
- clauses.push(`AUTOEXTEND ON`);
397
- }
398
-
399
- if (clauses.length > 0) {
400
- sql += ' ' + clauses.join(' ');
401
- }
402
- }
403
-
404
- await dataSource.query(sql);
405
- }
406
-
407
- /**
408
- * 删除Oracle数据库
409
- */
410
- async dropDatabase(dataSource: DataSource, databaseName: string): Promise<void> {
411
- const sql = `DROP DATABASE ${this.quoteIdentifier(databaseName)}`;
412
- await dataSource.query(sql);
413
- }
414
-
415
- /**
416
- * 导出数据库架构
417
- */
418
- async exportSchema(dataSource: DataSource, databaseName: string): Promise<string> {
419
- // 获取所有表
420
- const tables = await this.getTables(dataSource, databaseName);
421
- let schemaSql = `-- 数据库架构导出 - ${databaseName}\n`;
422
- schemaSql += `-- 导出时间: ${new Date().toISOString()}\n\n`;
423
-
424
- // 为每个表生成CREATE TABLE语句
425
- for (const table of tables) {
426
- // 获取表结构
427
- const columns = await this.getColumns(dataSource, databaseName, table.name);
428
- const indexes = await this.getIndexes(dataSource, databaseName, table.name);
429
- const foreignKeys = await this.getForeignKeys(dataSource, databaseName, table.name);
430
-
431
- // 生成CREATE TABLE语句
432
- schemaSql += `-- 表结构: ${table.name}\n`;
433
- schemaSql += `CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(table.name)} (\n`;
434
-
435
- // 添加列定义
436
- const columnDefinitions = columns.map(column => {
437
- let definition = ` ${this.quoteIdentifier(column.name)} ${column.type}`;
438
- if (!column.nullable) definition += ' NOT NULL';
439
- if (column.defaultValue !== undefined) {
440
- // 特殊关键字处理
441
- const upperDefault = column.defaultValue.toString().toUpperCase();
442
- if (upperDefault === 'CURRENT_TIMESTAMP' || upperDefault === 'NOW()' || upperDefault === 'CURRENT_DATE') {
443
- definition += ` DEFAULT ${upperDefault}`;
444
- } else {
445
- definition += ` DEFAULT ${column.defaultValue === null ? 'NULL' : `'${column.defaultValue}'`}`;
446
- }
447
- }
448
- if (column.isAutoIncrement) definition += ' GENERATED ALWAYS AS IDENTITY';
449
- return definition;
450
- });
451
-
452
- // 添加主键
453
- const primaryKeyColumns = columns.filter(column => column.isPrimary);
454
- if (primaryKeyColumns.length > 0) {
455
- const primaryKeyNames = primaryKeyColumns.map(column => this.quoteIdentifier(column.name)).join(', ');
456
- columnDefinitions.push(` PRIMARY KEY (${primaryKeyNames})`);
457
- }
458
-
459
- schemaSql += columnDefinitions.join(',\n');
460
- schemaSql += '\n);\n\n';
461
-
462
- // 添加索引
463
- for (const index of indexes) {
464
- if (index.type === 'PRIMARY' || index.name.toUpperCase() === 'PRIMARY') continue; // 跳过主键索引
465
- schemaSql += `-- 索引: ${index.name} on ${table.name}\n`;
466
- schemaSql += `CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX ${this.quoteIdentifier(index.name)} ON ${this.quoteIdentifier(table.name)} (${index.columns.map(col => this.quoteIdentifier(col)).join(', ')})\n`;
467
- }
468
-
469
- if (indexes.length > 0) schemaSql += '\n';
470
-
471
- // 添加外键
472
- for (const foreignKey of foreignKeys) {
473
- schemaSql += `-- 外键: ${foreignKey.name} on ${table.name}\n`;
474
- 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`;
475
- }
476
-
477
- if (foreignKeys.length > 0) schemaSql += '\n';
478
- }
479
-
480
- return schemaSql;
481
- }
482
-
483
- /**
484
- * 查看数据库日志
485
- */
486
- async viewLogs(dataSource: DataSource, database?: string, limit: number = 100): Promise<any[]> {
487
- // Oracle查看日志
488
- try {
489
- // 尝试查看Oracle警告日志
490
- const logs = await dataSource.query(`
491
- SELECT * FROM v$diag_info WHERE name LIKE '%Log%'
492
- `);
493
- return logs;
494
- } catch (error) {
495
- try {
496
- // 尝试查看Oracle系统事件
497
- const logs = await dataSource.query(`
498
- SELECT * FROM v$event_name WHERE name LIKE '%log%' LIMIT ${limit}
499
- `);
500
- return logs;
501
- } catch (e) {
502
- return [{ message: '无法获取Oracle日志,请确保具有适当的权限' }];
503
- }
504
- }
505
- }
506
-
507
- /**
508
- * 备份数据库
509
- */
510
- async backupDatabase(dataSource: DataSource, databaseName: string, options?: any): Promise<string> {
511
- // Oracle备份数据库
512
- try {
513
- // 使用RMAN命令备份
514
- const backupPath = options?.path || path.join(__dirname, '..', '..', 'backups');
515
-
516
- // 确保备份目录存在
517
- if (!fs.existsSync(backupPath)) {
518
- fs.mkdirSync(backupPath, { recursive: true });
519
- }
520
-
521
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
522
- const backupFile = path.join(backupPath, `${databaseName}_${timestamp}.bkp`);
523
-
524
- // 执行RMAN备份命令
525
- const connectionOptions = dataSource.options as any;
526
- const host = connectionOptions.host || 'localhost';
527
- const port = connectionOptions.port || 1521;
528
- const user = connectionOptions.username;
529
- const password = connectionOptions.password;
530
- const serviceName = connectionOptions.database || databaseName;
531
-
532
- // 构建RMAN命令
533
- const rmanCommand = `rman target ${user}/${password}@${host}:${port}/${serviceName} cmdfile=${backupPath}/backup.rman`;
534
-
535
- // 创建RMAN命令文件
536
- const rmanScript = `BACKUP DATABASE TO DISK '${backupFile}';`;
537
- fs.writeFileSync(path.join(backupPath, 'backup.rman'), rmanScript);
538
-
539
- // 执行命令
540
- execSync(rmanCommand);
541
-
542
- return `备份成功:${backupFile}`;
543
- } catch (error) {
544
- console.error('Oracle备份失败:', error);
545
- throw new Error(`备份失败: ${error.message}`);
546
- }
547
- }
548
-
549
- /**
550
- * 恢复数据库
551
- */
552
- async restoreDatabase(dataSource: DataSource, databaseName: string, filePath: string, options?: any): Promise<void> {
553
- // Oracle恢复数据库
554
- try {
555
- // 使用RMAN命令恢复
556
- const backupPath = path.dirname(filePath);
557
-
558
- // 执行RMAN恢复命令
559
- const connectionOptions = dataSource.options as any;
560
- const host = connectionOptions.host || 'localhost';
561
- const port = connectionOptions.port || 1521;
562
- const user = connectionOptions.username;
563
- const password = connectionOptions.password;
564
- const serviceName = connectionOptions.database || databaseName;
565
-
566
- // 构建RMAN命令
567
- const rmanCommand = `rman target ${user}/${password}@${host}:${port}/${serviceName} cmdfile=${backupPath}/restore.rman`;
568
-
569
- // 创建RMAN命令文件
570
- const rmanScript = `
571
- SHUTDOWN IMMEDIATE;
572
- STARTUP MOUNT;
573
- RESTORE DATABASE FROM DISK '${filePath}';
574
- RECOVER DATABASE;
575
- ALTER DATABASE OPEN;
576
- `;
577
- fs.writeFileSync(path.join(backupPath, 'restore.rman'), rmanScript);
578
-
579
- // 执行命令
580
- execSync(rmanCommand);
581
- } catch (error) {
582
- console.error('Oracle恢复失败:', error);
583
- throw new Error(`恢复失败: ${error.message}`);
584
- }
585
- }
586
-
587
- /**
588
- * 导出表数据到 SQL 文件
589
- */
590
- async exportTableDataToSQL(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
591
- try {
592
- const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
593
- if (!fs.existsSync(exportPath)) fs.mkdirSync(exportPath, { recursive: true });
594
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
595
- const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.sql`);
596
-
597
- const columns = await this.getColumns(dataSource, databaseName, tableName);
598
- const columnNames = columns.map(column => column.name);
599
-
600
- // 生成文件头部
601
- const header = `-- 表数据导出 - ${tableName}\n` +
602
- `-- 导出时间: ${new Date().toISOString()}\n\n`;
603
- fs.writeFileSync(exportFile, header, 'utf8');
604
-
605
- // 分批处理数据,避免一次性加载大量数据到内存
606
- const batchSize = options?.batchSize || 10000; // 每批处理10000行
607
- let offset = 0;
608
- let hasMoreData = true;
609
-
610
- while (hasMoreData) {
611
- // 分批查询数据(Oracle 使用 ROWNUM 语法)
612
- const query = `SELECT * FROM (SELECT a.*, ROWNUM rnum FROM (SELECT * FROM ${this.quoteIdentifier(tableName)}) a WHERE ROWNUM <= ${offset + batchSize}) WHERE rnum > ${offset}`;
613
- const data = await dataSource.query(query);
614
-
615
- if (data.length === 0) {
616
- hasMoreData = false;
617
- break;
618
- }
619
-
620
- // 生成当前批次的 INSERT 语句
621
- let batchSql = '';
622
- data.forEach((row: any) => {
623
- const values = columnNames.map(column => {
624
- const value = row[column];
625
- if (value === null || value === undefined) return 'NULL';
626
- if (typeof value === 'string') {
627
- // 处理字符串,转义单引号
628
- return `'${value.replace(/'/g, "''")}'`;
629
- }
630
- if (typeof value === 'boolean') {
631
- // Oracle 使用 NUMBER(1) 存储布尔值,1 表示 true,0 表示 false
632
- return value ? '1' : '0';
633
- }
634
- if (value instanceof Date) {
635
- // 格式化日期为 Oracle 兼容格式
636
- const year = value.getFullYear();
637
- const month = String(value.getMonth() + 1).padStart(2, '0');
638
- const day = String(value.getDate()).padStart(2, '0');
639
- const hours = String(value.getHours()).padStart(2, '0');
640
- const minutes = String(value.getMinutes()).padStart(2, '0');
641
- const seconds = String(value.getSeconds()).padStart(2, '0');
642
- return `TO_TIMESTAMP('${year}-${month}-${day} ${hours}:${minutes}:${seconds}', 'YYYY-MM-DD HH24:MI:SS')`;
643
- }
644
- if (typeof value === 'object') {
645
- // 处理对象类型,如 CLOB
646
- try {
647
- const stringValue = JSON.stringify(value);
648
- return `'${stringValue.replace(/'/g, "''")}'`;
649
- } catch {
650
- return `'${String(value).replace(/'/g, "''")}'`;
651
- }
652
- }
653
- // 其他类型直接转换为字符串
654
- return String(value);
655
- });
656
- batchSql += `INSERT INTO ${this.quoteIdentifier(tableName)} (${columnNames.map(col => this.quoteIdentifier(col)).join(', ')}) VALUES (${values.join(', ')});\n`;
657
- });
658
-
659
- // 追加写入文件
660
- fs.appendFileSync(exportFile, batchSql, 'utf8');
661
-
662
- // 增加偏移量
663
- offset += batchSize;
664
-
665
- // 打印进度信息
666
- console.log(`Oracle导出表数据进度: ${tableName} - 已处理 ${offset} 行`);
667
- }
668
-
669
- return exportFile;
670
- } catch (error) {
671
- console.error('Oracle导出表数据失败:', error);
672
- throw new Error(`导出表数据失败: ${error.message}`);
673
- }
674
- }
675
-
676
- /**
677
- * 导出表数据到 CSV 文件
678
- */
679
- async exportTableDataToCSV(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
680
- try {
681
- const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
682
- if (!fs.existsSync(exportPath)) fs.mkdirSync(exportPath, { recursive: true });
683
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
684
- const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.csv`);
685
-
686
- const columns = await this.getColumns(dataSource, databaseName, tableName);
687
- const columnNames = columns.map(column => column.name);
688
-
689
- // 写入 CSV 头部(包含 UTF-8 BOM)
690
- const bom = Buffer.from([0xEF, 0xBB, 0xBF]);
691
- fs.writeFileSync(exportFile, bom);
692
- fs.appendFileSync(exportFile, columnNames.map(name => `"${name}"`).join(',') + '\n', 'utf8');
693
-
694
- // 分批处理数据,避免一次性加载大量数据到内存
695
- const batchSize = options?.batchSize || 10000; // 每批处理10000行
696
- let offset = 0;
697
- let hasMoreData = true;
698
-
699
- while (hasMoreData) {
700
- // 分批查询数据(Oracle 使用 ROWNUM 语法)
701
- const query = `SELECT * FROM (SELECT a.*, ROWNUM rnum FROM (SELECT * FROM ${this.quoteIdentifier(tableName)}) a WHERE ROWNUM <= ${offset + batchSize}) WHERE rnum > ${offset}`;
702
- const data = await dataSource.query(query);
703
-
704
- if (data.length === 0) {
705
- hasMoreData = false;
706
- break;
707
- }
708
-
709
- // 生成当前批次的 CSV 行
710
- let batchCsv = '';
711
- data.forEach((row: any) => {
712
- const values = columnNames.map(column => {
713
- const value = row[column];
714
- if (value === null || value === undefined) {
715
- return '';
716
- } else if (typeof value === 'string') {
717
- // 转义双引号并包裹在双引号中
718
- return `"${value.replace(/"/g, '""')}"`;
719
- } else if (value instanceof Date) {
720
- // 格式化日期为 Oracle 兼容格式
721
- const year = value.getFullYear();
722
- const month = String(value.getMonth() + 1).padStart(2, '0');
723
- const day = String(value.getDate()).padStart(2, '0');
724
- const hours = String(value.getHours()).padStart(2, '0');
725
- const minutes = String(value.getMinutes()).padStart(2, '0');
726
- const seconds = String(value.getSeconds()).padStart(2, '0');
727
- return `"${year}-${month}-${day} ${hours}:${minutes}:${seconds}"`;
728
- } else if (typeof value === 'object' && value !== null) {
729
- // 处理对象类型,如 CLOB
730
- try {
731
- return `"${JSON.stringify(value).replace(/"/g, '""')}"`;
732
- } catch {
733
- return `"${String(value).replace(/"/g, '""')}"`;
734
- }
735
- } else {
736
- return String(value);
737
- }
738
- });
739
-
740
- batchCsv += values.join(',') + '\n';
741
- });
742
-
743
- // 追加写入文件
744
- fs.appendFileSync(exportFile, batchCsv, 'utf8');
745
-
746
- // 增加偏移量
747
- offset += batchSize;
748
-
749
- // 打印进度信息
750
- console.log(`Oracle导出表数据到CSV进度: ${tableName} - 已处理 ${offset} 行`);
751
- }
752
-
753
- return exportFile;
754
- } catch (error) {
755
- console.error('Oracle导出表数据到CSV失败:', error);
756
- throw new Error(`导出表数据到CSV失败: ${error.message}`);
757
- }
758
- }
759
-
760
- /**
761
- * 导出表数据到 JSON 文件
762
- */
763
- async exportTableDataToJSON(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
764
- try {
765
- const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
766
- if (!fs.existsSync(exportPath)) fs.mkdirSync(exportPath, { recursive: true });
767
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
768
- const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.json`);
769
-
770
- // 写入 JSON 头部
771
- fs.writeFileSync(exportFile, '[\n', 'utf8');
772
-
773
- // 分批处理数据,避免一次性加载大量数据到内存
774
- const batchSize = options?.batchSize || 10000; // 每批处理10000行
775
- let offset = 0;
776
- let hasMoreData = true;
777
- let isFirstBatch = true;
778
-
779
- while (hasMoreData) {
780
- // 分批查询数据(Oracle 使用 ROWNUM 语法)
781
- const query = `SELECT * FROM (SELECT a.*, ROWNUM rnum FROM (SELECT * FROM ${this.quoteIdentifier(tableName)}) a WHERE ROWNUM <= ${offset + batchSize}) WHERE rnum > ${offset}`;
782
- const data = await dataSource.query(query);
783
-
784
- if (data.length === 0) {
785
- hasMoreData = false;
786
- break;
787
- }
788
-
789
- // 生成当前批次的 JSON 数据
790
- let batchJson = '';
791
- data.forEach((row: any, index: number) => {
792
- if (!isFirstBatch || index > 0) {
793
- batchJson += ',\n';
794
- }
795
- batchJson += JSON.stringify(row);
796
- });
797
-
798
- // 追加写入文件
799
- fs.appendFileSync(exportFile, batchJson, 'utf8');
800
-
801
- // 增加偏移量
802
- offset += batchSize;
803
- isFirstBatch = false;
804
-
805
- // 打印进度信息
806
- console.log(`Oracle导出表数据到JSON进度: ${tableName} - 已处理 ${offset} 行`);
807
- }
808
-
809
- // 写入 JSON 尾部
810
- fs.appendFileSync(exportFile, '\n]', 'utf8');
811
-
812
- return exportFile;
813
- } catch (error) {
814
- console.error('Oracle导出表数据到JSON失败:', error);
815
- throw new Error(`导出表数据到JSON失败: ${error.message}`);
816
- }
817
- }
818
-
819
- /**
820
- * 导出表数据到 Excel 文件
821
- */
822
- async exportTableDataToExcel(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
823
- try {
824
- // 由于 Excel 文件格式复杂,这里我们先导出为 CSV,然后可以考虑使用库来转换
825
- // 或者直接调用其他服务来处理 Excel 导出
826
- return this.exportTableDataToCSV(dataSource, databaseName, tableName, options);
827
- } catch (error) {
828
- console.error('Oracle导出表数据到Excel失败:', error);
829
- throw new Error(`导出表数据到Excel失败: ${error.message}`);
830
- }
831
- }
832
-
833
- /**
834
- * 修改表结构
835
- */
836
- async alterTable(dataSource: DataSource, databaseName: string, tableDiff: any): Promise<any> {
837
- try {
838
- const tableName = tableDiff.tableName;
839
- const sqlStatements: string[] = [];
840
-
841
- // 修改表注释
842
- if (tableDiff.tableCommentChanged) {
843
- sqlStatements.push(`COMMENT ON TABLE "${tableName}" IS '${tableDiff.tableComment}';`);
844
- }
845
-
846
- // 添加新列
847
- tableDiff.addedColumns.forEach((column: any) => {
848
- // 检查type是否已经包含长度信息(括号)
849
- const typeHasLength = /\(\d+\)/.test(column.type);
850
-
851
- let columnSQL = `ALTER TABLE "${tableName}" ADD ("${column.name}" ${column.type}`;
852
-
853
- // 处理长度和精度(仅当type中没有指定长度时才添加)
854
- if (!typeHasLength) {
855
- if (column.length) {
856
- columnSQL += `(${column.length})`;
857
- } else if (column.precision) {
858
- if (column.scale) {
859
- columnSQL += `(${column.precision},${column.scale})`;
860
- } else {
861
- columnSQL += `(${column.precision})`;
862
- }
863
- }
864
- }
865
-
866
- // 处理NULL约束
867
- if (!column.nullable) {
868
- columnSQL += ' NOT NULL';
869
- }
870
-
871
- // 处理默认值
872
- if (column.defaultValue) {
873
- const upperDefault = column.defaultValue.toString().toUpperCase();
874
- if (['SYSDATE', 'SYSTIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIMESTAMP'].includes(upperDefault)) {
875
- columnSQL += ` DEFAULT ${upperDefault}`;
876
- } else {
877
- columnSQL += ` DEFAULT '${column.defaultValue}'`;
878
- }
879
- }
880
-
881
- // 处理自增(Oracle使用GENERATED ALWAYS AS IDENTITY或SEQUENCE)
882
- if (column.isAutoIncrement) {
883
- if (column.type.toLowerCase().includes('number')) {
884
- columnSQL += ' GENERATED ALWAYS AS IDENTITY';
885
- }
886
- }
887
-
888
- columnSQL += ')';
889
- sqlStatements.push(columnSQL + ';');
890
-
891
- // 添加列注释
892
- if (column.comment) {
893
- sqlStatements.push(`COMMENT ON COLUMN "${tableName}"."${column.name}" IS '${column.comment}';`);
894
- }
895
- });
896
-
897
- // 修改列
898
- tableDiff.modifiedColumns.forEach((modification: any) => {
899
- const { oldColumn, newColumn } = modification;
900
-
901
- // 检查type是否已经包含长度信息(括号)
902
- const typeHasLength = /\(\d+\)/.test(newColumn.type);
903
-
904
- // 修改列类型和长度
905
- let columnSQL = `ALTER TABLE "${tableName}" MODIFY ("${newColumn.name}" ${newColumn.type}`;
906
-
907
- // 处理长度和精度(仅当type中没有指定长度时才添加)
908
- if (!typeHasLength) {
909
- if (newColumn.length) {
910
- columnSQL += `(${newColumn.length})`;
911
- } else if (newColumn.precision) {
912
- if (newColumn.scale) {
913
- columnSQL += `(${newColumn.precision},${newColumn.scale})`;
914
- } else {
915
- columnSQL += `(${newColumn.precision})`;
916
- }
917
- }
918
- }
919
-
920
- // 处理NULL约束
921
- if (!newColumn.nullable) {
922
- columnSQL += ' NOT NULL';
923
- }
924
-
925
- // 处理默认值
926
- if (newColumn.defaultValue) {
927
- const upperDefault = newColumn.defaultValue.toString().toUpperCase();
928
- if (['SYSDATE', 'SYSTIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIMESTAMP'].includes(upperDefault)) {
929
- columnSQL += ` DEFAULT ${upperDefault}`;
930
- } else {
931
- columnSQL += ` DEFAULT '${newColumn.defaultValue}'`;
932
- }
933
- }
934
-
935
- columnSQL += ')';
936
- sqlStatements.push(columnSQL + ';');
937
-
938
- // 修改列注释
939
- if (newColumn.comment) {
940
- sqlStatements.push(`COMMENT ON COLUMN "${tableName}"."${newColumn.name}" IS '${newColumn.comment}';`);
941
- }
942
- });
943
-
944
- // 删除列
945
- tableDiff.deletedColumns.forEach((column: any) => {
946
- sqlStatements.push(`ALTER TABLE "${tableName}" DROP COLUMN "${column.name}";`);
947
- });
948
-
949
- // 执行SQL语句
950
- if (sqlStatements.length > 0) {
951
- await this.executeBatchQuery(dataSource, sqlStatements, { useTransaction: true });
952
- }
953
-
954
- return { ret: 0, message: '表结构修改成功' };
955
- } catch (error) {
956
- console.error('Oracle修改表结构失败:', error);
957
- return { ret: 1, message: `修改表结构失败: ${error instanceof Error ? error.message : String(error)}` };
958
- }
959
- }
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
+ * Oracle数据库服务实现
15
+ */
16
+ export class OracleService extends BaseDatabaseService {
17
+
18
+ getDatabaseType(): string {
19
+ return 'oracle';
20
+ }
21
+
22
+ /**
23
+ * 获取Oracle数据库列表(用户schema)
24
+ */
25
+ async getDatabases(dataSource: DataSource): Promise<string[]> {
26
+ const result = await dataSource.query(`
27
+ SELECT username as name
28
+ FROM all_users
29
+ WHERE username NOT IN ('SYS', 'SYSTEM', 'XDB', 'OUTLN')
30
+ ORDER BY username
31
+ `);
32
+ return result.map((row: any) => row.name);
33
+ }
34
+
35
+ /**
36
+ * 获取Oracle表列表
37
+ */
38
+ async getTables(dataSource: DataSource, database: string): Promise<TableEntity[]> {
39
+ const result = await dataSource.query(`
40
+ SELECT
41
+ table_name as name,
42
+ 'TABLE' as type
43
+ FROM all_tables
44
+ WHERE owner = ?
45
+ AND table_name NOT LIKE 'BIN$%'
46
+ AND temporary = 'N'
47
+ ORDER BY table_name
48
+ `, [database.toUpperCase()]);
49
+
50
+ return result.map((row: any) => ({
51
+ name: row.name,
52
+ type: row.type,
53
+ rowCount: undefined,
54
+ dataSize: undefined,
55
+ indexSize: undefined
56
+ }));
57
+ }
58
+
59
+ /**
60
+ * 获取Oracle列信息
61
+ */
62
+ async getColumns(dataSource: DataSource, database: string, table: string): Promise<ColumnEntity[]> {
63
+ // 使用兼容的SQL查询,移除可能不兼容的字段
64
+ const result = await dataSource.query(`
65
+ SELECT
66
+ column_name as name,
67
+ data_type as type,
68
+ data_length as length,
69
+ nullable as nullable,
70
+ data_default as defaultValue
71
+ FROM all_tab_columns
72
+ WHERE owner = ?
73
+ AND table_name = ?
74
+ ORDER BY column_id
75
+ `, [
76
+ database.toUpperCase(),
77
+ table.toUpperCase()
78
+ ]);
79
+
80
+ // 获取主键信息
81
+ const primaryKeys = await this.getPrimaryKeys(dataSource, database, table);
82
+
83
+ // 获取序列信息(Oracle使用序列实现自增)
84
+ const sequenceColumns = await this.getSequenceColumns(dataSource, database, 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)或NUMBER(M,D)类型的精度
93
+ const decimalMatch = dataType.match(/(DECIMAL|NUMBER)\s*\(\s*(\d+)\s*(,\s*(\d+)\s*)?\s*\)/i);
94
+ if (decimalMatch) {
95
+ precision = parseInt(decimalMatch[2]);
96
+ if (decimalMatch[3]) {
97
+ scale = parseInt(decimalMatch[3].replace(/\D/g, ''));
98
+ }
99
+ }
100
+
101
+ return {
102
+ name: row.name,
103
+ type: row.type + (row.length ? `(${row.length})` : ''),
104
+ nullable: row.nullable === 'Y',
105
+ defaultValue: row.defaultValue,
106
+ isPrimary: primaryKeys.includes(row.name),
107
+ isAutoIncrement: sequenceColumns.includes(row.name),
108
+ length: row.length,
109
+ precision: precision,
110
+ scale: scale
111
+ };
112
+ });
113
+ }
114
+
115
+ /**
116
+ * 获取Oracle索引信息
117
+ */
118
+ async getIndexes(dataSource: DataSource, database: string, table: string): Promise<IndexEntity[]> {
119
+ const result = await dataSource.query(`
120
+ SELECT DISTINCT
121
+ i.index_name as name,
122
+ DECODE(i.uniqueness, 'UNIQUE', 'UNIQUE INDEX', 'INDEX') as type,
123
+ ic.column_name as column
124
+ FROM all_indexes i
125
+ JOIN all_ind_columns ic ON i.index_name = ic.index_name
126
+ WHERE i.table_owner = ?
127
+ AND i.table_name = ?
128
+ AND i.index_name NOT IN (SELECT constraint_name
129
+ FROM all_constraints
130
+ WHERE constraint_type = 'P'
131
+ AND table_owner = ?)
132
+ ORDER BY i.index_name, ic.column_position
133
+ `, [
134
+ database.toUpperCase(),
135
+ table.toUpperCase(),
136
+ database.toUpperCase()
137
+ ]);
138
+
139
+ // 按索引名分组
140
+ const indexMap = new Map<string, IndexEntity>();
141
+ result.forEach((row: any) => {
142
+ if (!indexMap.has(row.name)) {
143
+ indexMap.set(row.name, {
144
+ name: row.name,
145
+ type: row.type,
146
+ columns: [],
147
+ unique: row.type.includes('UNIQUE')
148
+ });
149
+ }
150
+ indexMap.get(row.name)!.columns.push(row.column);
151
+ });
152
+
153
+ return Array.from(indexMap.values());
154
+ }
155
+
156
+ /**
157
+ * 获取Oracle外键信息
158
+ */
159
+ async getForeignKeys(dataSource: DataSource, database: string, table: string): Promise<ForeignKeyEntity[]> {
160
+ const result = await dataSource.query(`
161
+ SELECT
162
+ c.constraint_name as name,
163
+ cc.column_name as column,
164
+ r.table_name as referencedTable,
165
+ rc.column_name as referencedColumn,
166
+ c.delete_rule as onDelete
167
+ FROM all_constraints c
168
+ JOIN all_cons_columns cc ON c.constraint_name = cc.constraint_name
169
+ JOIN all_constraints r ON c.r_constraint_name = r.constraint_name
170
+ JOIN all_cons_columns rc ON r.constraint_name = rc.constraint_name AND cc.position = rc.position
171
+ WHERE c.constraint_type = 'R'
172
+ AND c.owner = ?
173
+ AND c.table_name = ?
174
+ `, [
175
+ database.toUpperCase(),
176
+ table.toUpperCase()
177
+ ]);
178
+
179
+ return result.map((row: any) => ({
180
+ name: row.name,
181
+ column: row.column,
182
+ referencedTable: row.referencedTable,
183
+ referencedColumn: row.referencedColumn,
184
+ onDelete: row.onDelete || 'NO ACTION',
185
+ onUpdate: 'NO ACTION' // Oracle不支持ON UPDATE
186
+ }));
187
+ }
188
+
189
+ /**
190
+ * 获取Oracle数据库大小(用户schema大小)
191
+ */
192
+ async getDatabaseSize(dataSource: DataSource, database: string): Promise<number> {
193
+ const result = await dataSource.query(`
194
+ SELECT SUM(bytes) as size
195
+ FROM user_segments
196
+ `);
197
+ return result[0]?.size || 0;
198
+ }
199
+
200
+ /**
201
+ * 获取表统计信息
202
+ */
203
+ private async getTableStats(dataSource: DataSource, database: string, table: string): Promise<any> {
204
+ try {
205
+ const result = await dataSource.query(`
206
+ SELECT
207
+ num_rows as rowCount,
208
+ (SELECT SUM(bytes) FROM user_segments WHERE segment_name = ?) as dataSize
209
+ FROM all_tables
210
+ WHERE owner = ? AND table_name = ?
211
+ `, [
212
+ table.toUpperCase(),
213
+ database.toUpperCase(),
214
+ table.toUpperCase()
215
+ ]);
216
+
217
+ return {
218
+ rowCount: result[0]?.rowCount || 0,
219
+ dataSize: result[0]?.dataSize || 0,
220
+ indexSize: 0 // Oracle索引大小计算较复杂,这里简化处理
221
+ };
222
+ } catch (error) {
223
+ // 如果没有统计信息,返回默认值
224
+ return {
225
+ rowCount: 0,
226
+ dataSize: 0,
227
+ indexSize: 0
228
+ };
229
+ }
230
+ }
231
+
232
+ /**
233
+ * 获取主键信息
234
+ */
235
+ private async getPrimaryKeys(dataSource: DataSource, database: string, table: string): Promise<string[]> {
236
+ const result = await dataSource.query(`
237
+ SELECT column_name
238
+ FROM all_cons_columns cc
239
+ JOIN all_constraints c ON cc.constraint_name = c.constraint_name
240
+ WHERE c.constraint_type = 'P'
241
+ AND c.owner = ?
242
+ AND c.table_name = ?
243
+ ORDER BY cc.position
244
+ `, [
245
+ database.toUpperCase(),
246
+ table.toUpperCase()
247
+ ]);
248
+ return result.map((row: any) => row.column_name);
249
+ }
250
+
251
+ /**
252
+ * 获取Oracle序列信息(用于检测自增列)
253
+ */
254
+ private async getSequenceColumns(dataSource: DataSource, database: string, table: string): Promise<string[]> {
255
+ try {
256
+ const result = await dataSource.query(`
257
+ SELECT acc.column_name
258
+ FROM all_tab_columns acc
259
+ JOIN all_triggers at ON acc.table_name = at.table_name
260
+ AND acc.owner = at.owner
261
+ JOIN all_sequences seq ON at.trigger_name LIKE seq.sequence_name || '%'
262
+ WHERE acc.owner = ?
263
+ AND acc.table_name = ?
264
+ AND acc.data_default IS NOT NULL
265
+ AND acc.data_default LIKE seq.sequence_name || '.nextval'
266
+ `, [
267
+ database.toUpperCase(),
268
+ table.toUpperCase()
269
+ ]);
270
+ return result.map((row: any) => row.column_name);
271
+ } catch (error) {
272
+ // 如果查询失败,返回空数组
273
+ return [];
274
+ }
275
+ }
276
+
277
+ /**
278
+ * Oracle的标识符引用方式
279
+ */
280
+ public quoteIdentifier(identifier: string): string {
281
+ return `"${identifier.toUpperCase()}"`;
282
+ }
283
+
284
+ /**
285
+ * 获取Oracle视图列表
286
+ */
287
+ async getViews(dataSource: DataSource, database: string): Promise<any[]> {
288
+ const result = await dataSource.query(`
289
+ SELECT
290
+ view_name as name,
291
+ '' as comment
292
+ FROM all_views
293
+ WHERE owner = ?
294
+ ORDER BY view_name
295
+ `, [database.toUpperCase()]);
296
+
297
+ return result.map((row: any) => ({
298
+ name: row.name,
299
+ comment: row.comment || '',
300
+ schemaName: database
301
+ }));
302
+ }
303
+
304
+ /**
305
+ * 获取Oracle视图定义
306
+ */
307
+ async getViewDefinition(dataSource: DataSource, database: string, viewName: string): Promise<string> {
308
+ const result = await dataSource.query(`
309
+ SELECT text as definition
310
+ FROM all_views
311
+ WHERE owner = ?
312
+ AND view_name = ?
313
+ `, [database.toUpperCase(), viewName.toUpperCase()]);
314
+
315
+ return result[0]?.definition || '';
316
+ }
317
+
318
+ /**
319
+ * 获取Oracle存储过程列表
320
+ */
321
+ async getProcedures(dataSource: DataSource, database: string): Promise<any[]> {
322
+ const result = await dataSource.query(`
323
+ SELECT
324
+ object_name as name,
325
+ '' as comment,
326
+ 'PROCEDURE' as type,
327
+ '' as returnType,
328
+ 'PL/SQL' as language
329
+ FROM all_objects
330
+ WHERE owner = ?
331
+ AND object_type IN ('PROCEDURE', 'FUNCTION')
332
+ AND status = 'VALID'
333
+ ORDER BY object_name
334
+ `, [database.toUpperCase()]);
335
+
336
+ return result.map((row: any) => ({
337
+ name: row.name,
338
+ comment: row.comment || '',
339
+ type: row.type,
340
+ returnType: row.returnType || '',
341
+ language: row.language || 'PL/SQL'
342
+ }));
343
+ }
344
+
345
+ /**
346
+ * 获取Oracle存储过程定义
347
+ */
348
+ async getProcedureDefinition(dataSource: DataSource, database: string, procedureName: string): Promise<string> {
349
+ const result = await dataSource.query(`
350
+ SELECT text as definition
351
+ FROM all_source
352
+ WHERE owner = ?
353
+ AND name = ?
354
+ ORDER BY line
355
+ `, [database.toUpperCase(), procedureName.toUpperCase()]);
356
+
357
+ return result.map((row: any) => row.definition).join('\n') || '';
358
+ }
359
+
360
+ /**
361
+ * 创建Oracle数据库
362
+ */
363
+ async createDatabase(dataSource: DataSource, databaseName: string, options?: any): Promise<void> {
364
+ // Oracle数据库创建比较复杂,通常需要DBA权限
365
+ // 这里提供基本的创建语法
366
+ let sql = `CREATE DATABASE ${this.quoteIdentifier(databaseName)}`;
367
+
368
+ if (options) {
369
+ const clauses = [];
370
+
371
+ if (options.user) {
372
+ clauses.push(`USER ${options.user}`);
373
+ }
374
+
375
+ if (options.password) {
376
+ clauses.push(`IDENTIFIED BY ${options.password}`);
377
+ }
378
+
379
+ if (options.defaultTablespace) {
380
+ clauses.push(`DEFAULT TABLESPACE ${options.defaultTablespace}`);
381
+ }
382
+
383
+ if (options.tempTablespace) {
384
+ clauses.push(`TEMPORARY TABLESPACE ${options.tempTablespace}`);
385
+ }
386
+
387
+ if (options.datafile) {
388
+ clauses.push(`DATAFILE '${options.datafile}'`);
389
+ }
390
+
391
+ if (options.size) {
392
+ clauses.push(`SIZE ${options.size}`);
393
+ }
394
+
395
+ if (options.autoExtend) {
396
+ clauses.push(`AUTOEXTEND ON`);
397
+ }
398
+
399
+ if (clauses.length > 0) {
400
+ sql += ' ' + clauses.join(' ');
401
+ }
402
+ }
403
+
404
+ await dataSource.query(sql);
405
+ }
406
+
407
+ /**
408
+ * 删除Oracle数据库
409
+ */
410
+ async dropDatabase(dataSource: DataSource, databaseName: string): Promise<void> {
411
+ const sql = `DROP DATABASE ${this.quoteIdentifier(databaseName)}`;
412
+ await dataSource.query(sql);
413
+ }
414
+
415
+ /**
416
+ * 导出数据库架构
417
+ */
418
+ async exportSchema(dataSource: DataSource, databaseName: string): Promise<string> {
419
+ // 获取所有表
420
+ const tables = await this.getTables(dataSource, databaseName);
421
+ let schemaSql = `-- 数据库架构导出 - ${databaseName}\n`;
422
+ schemaSql += `-- 导出时间: ${new Date().toISOString()}\n\n`;
423
+
424
+ // 为每个表生成CREATE TABLE语句
425
+ for (const table of tables) {
426
+ // 获取表结构
427
+ const columns = await this.getColumns(dataSource, databaseName, table.name);
428
+ const indexes = await this.getIndexes(dataSource, databaseName, table.name);
429
+ const foreignKeys = await this.getForeignKeys(dataSource, databaseName, table.name);
430
+
431
+ // 生成CREATE TABLE语句
432
+ schemaSql += `-- 表结构: ${table.name}\n`;
433
+ schemaSql += `CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(table.name)} (\n`;
434
+
435
+ // 添加列定义
436
+ const columnDefinitions = columns.map(column => {
437
+ let definition = ` ${this.quoteIdentifier(column.name)} ${column.type}`;
438
+ if (!column.nullable) definition += ' NOT NULL';
439
+ if (column.defaultValue !== undefined) {
440
+ // 特殊关键字处理
441
+ const upperDefault = column.defaultValue.toString().toUpperCase();
442
+ if (upperDefault === 'CURRENT_TIMESTAMP' || upperDefault === 'NOW()' || upperDefault === 'CURRENT_DATE') {
443
+ definition += ` DEFAULT ${upperDefault}`;
444
+ } else {
445
+ definition += ` DEFAULT ${column.defaultValue === null ? 'NULL' : `'${column.defaultValue}'`}`;
446
+ }
447
+ }
448
+ if (column.isAutoIncrement) definition += ' GENERATED ALWAYS AS IDENTITY';
449
+ return definition;
450
+ });
451
+
452
+ // 添加主键
453
+ const primaryKeyColumns = columns.filter(column => column.isPrimary);
454
+ if (primaryKeyColumns.length > 0) {
455
+ const primaryKeyNames = primaryKeyColumns.map(column => this.quoteIdentifier(column.name)).join(', ');
456
+ columnDefinitions.push(` PRIMARY KEY (${primaryKeyNames})`);
457
+ }
458
+
459
+ schemaSql += columnDefinitions.join(',\n');
460
+ schemaSql += '\n);\n\n';
461
+
462
+ // 添加索引
463
+ for (const index of indexes) {
464
+ if (index.type === 'PRIMARY' || index.name.toUpperCase() === 'PRIMARY') continue; // 跳过主键索引
465
+ schemaSql += `-- 索引: ${index.name} on ${table.name}\n`;
466
+ schemaSql += `CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX ${this.quoteIdentifier(index.name)} ON ${this.quoteIdentifier(table.name)} (${index.columns.map(col => this.quoteIdentifier(col)).join(', ')})\n`;
467
+ }
468
+
469
+ if (indexes.length > 0) schemaSql += '\n';
470
+
471
+ // 添加外键
472
+ for (const foreignKey of foreignKeys) {
473
+ schemaSql += `-- 外键: ${foreignKey.name} on ${table.name}\n`;
474
+ 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`;
475
+ }
476
+
477
+ if (foreignKeys.length > 0) schemaSql += '\n';
478
+ }
479
+
480
+ return schemaSql;
481
+ }
482
+
483
+ /**
484
+ * 查看数据库日志
485
+ */
486
+ async viewLogs(dataSource: DataSource, database?: string, limit: number = 100): Promise<any[]> {
487
+ // Oracle查看日志
488
+ try {
489
+ // 尝试查看Oracle警告日志
490
+ const logs = await dataSource.query(`
491
+ SELECT * FROM v$diag_info WHERE name LIKE '%Log%'
492
+ `);
493
+ return logs;
494
+ } catch (error) {
495
+ try {
496
+ // 尝试查看Oracle系统事件
497
+ const logs = await dataSource.query(`
498
+ SELECT * FROM v$event_name WHERE name LIKE '%log%' LIMIT ${limit}
499
+ `);
500
+ return logs;
501
+ } catch (e) {
502
+ return [{ message: '无法获取Oracle日志,请确保具有适当的权限' }];
503
+ }
504
+ }
505
+ }
506
+
507
+ /**
508
+ * 备份数据库
509
+ */
510
+ async backupDatabase(dataSource: DataSource, databaseName: string, options?: any): Promise<string> {
511
+ // Oracle备份数据库
512
+ try {
513
+ // 使用RMAN命令备份
514
+ const backupPath = options?.path || path.join(__dirname, '..', '..', 'backups');
515
+
516
+ // 确保备份目录存在
517
+ if (!fs.existsSync(backupPath)) {
518
+ fs.mkdirSync(backupPath, { recursive: true });
519
+ }
520
+
521
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
522
+ const backupFile = path.join(backupPath, `${databaseName}_${timestamp}.bkp`);
523
+
524
+ // 执行RMAN备份命令
525
+ const connectionOptions = dataSource.options as any;
526
+ const host = connectionOptions.host || 'localhost';
527
+ const port = connectionOptions.port || 1521;
528
+ const user = connectionOptions.username;
529
+ const password = connectionOptions.password;
530
+ const serviceName = connectionOptions.database || databaseName;
531
+
532
+ // 构建RMAN命令
533
+ const rmanCommand = `rman target ${user}/${password}@${host}:${port}/${serviceName} cmdfile=${backupPath}/backup.rman`;
534
+
535
+ // 创建RMAN命令文件
536
+ const rmanScript = `BACKUP DATABASE TO DISK '${backupFile}';`;
537
+ fs.writeFileSync(path.join(backupPath, 'backup.rman'), rmanScript);
538
+
539
+ // 执行命令
540
+ execSync(rmanCommand);
541
+
542
+ return `备份成功:${backupFile}`;
543
+ } catch (error) {
544
+ console.error('Oracle备份失败:', error);
545
+ throw new Error(`备份失败: ${error.message}`);
546
+ }
547
+ }
548
+
549
+ /**
550
+ * 恢复数据库
551
+ */
552
+ async restoreDatabase(dataSource: DataSource, databaseName: string, filePath: string, options?: any): Promise<void> {
553
+ // Oracle恢复数据库
554
+ try {
555
+ // 使用RMAN命令恢复
556
+ const backupPath = path.dirname(filePath);
557
+
558
+ // 执行RMAN恢复命令
559
+ const connectionOptions = dataSource.options as any;
560
+ const host = connectionOptions.host || 'localhost';
561
+ const port = connectionOptions.port || 1521;
562
+ const user = connectionOptions.username;
563
+ const password = connectionOptions.password;
564
+ const serviceName = connectionOptions.database || databaseName;
565
+
566
+ // 构建RMAN命令
567
+ const rmanCommand = `rman target ${user}/${password}@${host}:${port}/${serviceName} cmdfile=${backupPath}/restore.rman`;
568
+
569
+ // 创建RMAN命令文件
570
+ const rmanScript = `
571
+ SHUTDOWN IMMEDIATE;
572
+ STARTUP MOUNT;
573
+ RESTORE DATABASE FROM DISK '${filePath}';
574
+ RECOVER DATABASE;
575
+ ALTER DATABASE OPEN;
576
+ `;
577
+ fs.writeFileSync(path.join(backupPath, 'restore.rman'), rmanScript);
578
+
579
+ // 执行命令
580
+ execSync(rmanCommand);
581
+ } catch (error) {
582
+ console.error('Oracle恢复失败:', error);
583
+ throw new Error(`恢复失败: ${error.message}`);
584
+ }
585
+ }
586
+
587
+ /**
588
+ * 导出表数据到 SQL 文件
589
+ */
590
+ async exportTableDataToSQL(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
591
+ try {
592
+ const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
593
+ if (!fs.existsSync(exportPath)) fs.mkdirSync(exportPath, { recursive: true });
594
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
595
+ const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.sql`);
596
+
597
+ const columns = await this.getColumns(dataSource, databaseName, tableName);
598
+ const columnNames = columns.map(column => column.name);
599
+
600
+ // 生成文件头部
601
+ const header = `-- 表数据导出 - ${tableName}\n` +
602
+ `-- 导出时间: ${new Date().toISOString()}\n\n`;
603
+ fs.writeFileSync(exportFile, header, 'utf8');
604
+
605
+ // 分批处理数据,避免一次性加载大量数据到内存
606
+ const batchSize = options?.batchSize || 10000; // 每批处理10000行
607
+ let offset = 0;
608
+ let hasMoreData = true;
609
+
610
+ while (hasMoreData) {
611
+ // 分批查询数据(Oracle 使用 ROWNUM 语法)
612
+ const query = `SELECT * FROM (SELECT a.*, ROWNUM rnum FROM (SELECT * FROM ${this.quoteIdentifier(tableName)}) a WHERE ROWNUM <= ${offset + batchSize}) WHERE rnum > ${offset}`;
613
+ const data = await dataSource.query(query);
614
+
615
+ if (data.length === 0) {
616
+ hasMoreData = false;
617
+ break;
618
+ }
619
+
620
+ // 生成当前批次的 INSERT 语句
621
+ let batchSql = '';
622
+ data.forEach((row: any) => {
623
+ const values = columnNames.map(column => {
624
+ const value = row[column];
625
+ if (value === null || value === undefined) return 'NULL';
626
+ if (typeof value === 'string') {
627
+ // 处理字符串,转义单引号
628
+ return `'${value.replace(/'/g, "''")}'`;
629
+ }
630
+ if (typeof value === 'boolean') {
631
+ // Oracle 使用 NUMBER(1) 存储布尔值,1 表示 true,0 表示 false
632
+ return value ? '1' : '0';
633
+ }
634
+ if (value instanceof Date) {
635
+ // 格式化日期为 Oracle 兼容格式
636
+ const year = value.getFullYear();
637
+ const month = String(value.getMonth() + 1).padStart(2, '0');
638
+ const day = String(value.getDate()).padStart(2, '0');
639
+ const hours = String(value.getHours()).padStart(2, '0');
640
+ const minutes = String(value.getMinutes()).padStart(2, '0');
641
+ const seconds = String(value.getSeconds()).padStart(2, '0');
642
+ return `TO_TIMESTAMP('${year}-${month}-${day} ${hours}:${minutes}:${seconds}', 'YYYY-MM-DD HH24:MI:SS')`;
643
+ }
644
+ if (typeof value === 'object') {
645
+ // 处理对象类型,如 CLOB
646
+ try {
647
+ const stringValue = JSON.stringify(value);
648
+ return `'${stringValue.replace(/'/g, "''")}'`;
649
+ } catch {
650
+ return `'${String(value).replace(/'/g, "''")}'`;
651
+ }
652
+ }
653
+ // 其他类型直接转换为字符串
654
+ return String(value);
655
+ });
656
+ batchSql += `INSERT INTO ${this.quoteIdentifier(tableName)} (${columnNames.map(col => this.quoteIdentifier(col)).join(', ')}) VALUES (${values.join(', ')});\n`;
657
+ });
658
+
659
+ // 追加写入文件
660
+ fs.appendFileSync(exportFile, batchSql, 'utf8');
661
+
662
+ // 增加偏移量
663
+ offset += batchSize;
664
+
665
+ // 打印进度信息
666
+ console.log(`Oracle导出表数据进度: ${tableName} - 已处理 ${offset} 行`);
667
+ }
668
+
669
+ return exportFile;
670
+ } catch (error) {
671
+ console.error('Oracle导出表数据失败:', error);
672
+ throw new Error(`导出表数据失败: ${error.message}`);
673
+ }
674
+ }
675
+
676
+ /**
677
+ * 导出表数据到 CSV 文件
678
+ */
679
+ async exportTableDataToCSV(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
680
+ try {
681
+ const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
682
+ if (!fs.existsSync(exportPath)) fs.mkdirSync(exportPath, { recursive: true });
683
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
684
+ const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.csv`);
685
+
686
+ const columns = await this.getColumns(dataSource, databaseName, tableName);
687
+ const columnNames = columns.map(column => column.name);
688
+
689
+ // 写入 CSV 头部(包含 UTF-8 BOM)
690
+ const bom = Buffer.from([0xEF, 0xBB, 0xBF]);
691
+ fs.writeFileSync(exportFile, bom);
692
+ fs.appendFileSync(exportFile, columnNames.map(name => `"${name}"`).join(',') + '\n', 'utf8');
693
+
694
+ // 分批处理数据,避免一次性加载大量数据到内存
695
+ const batchSize = options?.batchSize || 10000; // 每批处理10000行
696
+ let offset = 0;
697
+ let hasMoreData = true;
698
+
699
+ while (hasMoreData) {
700
+ // 分批查询数据(Oracle 使用 ROWNUM 语法)
701
+ const query = `SELECT * FROM (SELECT a.*, ROWNUM rnum FROM (SELECT * FROM ${this.quoteIdentifier(tableName)}) a WHERE ROWNUM <= ${offset + batchSize}) WHERE rnum > ${offset}`;
702
+ const data = await dataSource.query(query);
703
+
704
+ if (data.length === 0) {
705
+ hasMoreData = false;
706
+ break;
707
+ }
708
+
709
+ // 生成当前批次的 CSV 行
710
+ let batchCsv = '';
711
+ data.forEach((row: any) => {
712
+ const values = columnNames.map(column => {
713
+ const value = row[column];
714
+ if (value === null || value === undefined) {
715
+ return '';
716
+ } else if (typeof value === 'string') {
717
+ // 转义双引号并包裹在双引号中
718
+ return `"${value.replace(/"/g, '""')}"`;
719
+ } else if (value instanceof Date) {
720
+ // 格式化日期为 Oracle 兼容格式
721
+ const year = value.getFullYear();
722
+ const month = String(value.getMonth() + 1).padStart(2, '0');
723
+ const day = String(value.getDate()).padStart(2, '0');
724
+ const hours = String(value.getHours()).padStart(2, '0');
725
+ const minutes = String(value.getMinutes()).padStart(2, '0');
726
+ const seconds = String(value.getSeconds()).padStart(2, '0');
727
+ return `"${year}-${month}-${day} ${hours}:${minutes}:${seconds}"`;
728
+ } else if (typeof value === 'object' && value !== null) {
729
+ // 处理对象类型,如 CLOB
730
+ try {
731
+ return `"${JSON.stringify(value).replace(/"/g, '""')}"`;
732
+ } catch {
733
+ return `"${String(value).replace(/"/g, '""')}"`;
734
+ }
735
+ } else {
736
+ return String(value);
737
+ }
738
+ });
739
+
740
+ batchCsv += values.join(',') + '\n';
741
+ });
742
+
743
+ // 追加写入文件
744
+ fs.appendFileSync(exportFile, batchCsv, 'utf8');
745
+
746
+ // 增加偏移量
747
+ offset += batchSize;
748
+
749
+ // 打印进度信息
750
+ console.log(`Oracle导出表数据到CSV进度: ${tableName} - 已处理 ${offset} 行`);
751
+ }
752
+
753
+ return exportFile;
754
+ } catch (error) {
755
+ console.error('Oracle导出表数据到CSV失败:', error);
756
+ throw new Error(`导出表数据到CSV失败: ${error.message}`);
757
+ }
758
+ }
759
+
760
+ /**
761
+ * 导出表数据到 JSON 文件
762
+ */
763
+ async exportTableDataToJSON(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
764
+ try {
765
+ const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
766
+ if (!fs.existsSync(exportPath)) fs.mkdirSync(exportPath, { recursive: true });
767
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
768
+ const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.json`);
769
+
770
+ // 写入 JSON 头部
771
+ fs.writeFileSync(exportFile, '[\n', 'utf8');
772
+
773
+ // 分批处理数据,避免一次性加载大量数据到内存
774
+ const batchSize = options?.batchSize || 10000; // 每批处理10000行
775
+ let offset = 0;
776
+ let hasMoreData = true;
777
+ let isFirstBatch = true;
778
+
779
+ while (hasMoreData) {
780
+ // 分批查询数据(Oracle 使用 ROWNUM 语法)
781
+ const query = `SELECT * FROM (SELECT a.*, ROWNUM rnum FROM (SELECT * FROM ${this.quoteIdentifier(tableName)}) a WHERE ROWNUM <= ${offset + batchSize}) WHERE rnum > ${offset}`;
782
+ const data = await dataSource.query(query);
783
+
784
+ if (data.length === 0) {
785
+ hasMoreData = false;
786
+ break;
787
+ }
788
+
789
+ // 生成当前批次的 JSON 数据
790
+ let batchJson = '';
791
+ data.forEach((row: any, index: number) => {
792
+ if (!isFirstBatch || index > 0) {
793
+ batchJson += ',\n';
794
+ }
795
+ batchJson += JSON.stringify(row);
796
+ });
797
+
798
+ // 追加写入文件
799
+ fs.appendFileSync(exportFile, batchJson, 'utf8');
800
+
801
+ // 增加偏移量
802
+ offset += batchSize;
803
+ isFirstBatch = false;
804
+
805
+ // 打印进度信息
806
+ console.log(`Oracle导出表数据到JSON进度: ${tableName} - 已处理 ${offset} 行`);
807
+ }
808
+
809
+ // 写入 JSON 尾部
810
+ fs.appendFileSync(exportFile, '\n]', 'utf8');
811
+
812
+ return exportFile;
813
+ } catch (error) {
814
+ console.error('Oracle导出表数据到JSON失败:', error);
815
+ throw new Error(`导出表数据到JSON失败: ${error.message}`);
816
+ }
817
+ }
818
+
819
+ /**
820
+ * 导出表数据到 Excel 文件
821
+ */
822
+ async exportTableDataToExcel(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
823
+ try {
824
+ // 由于 Excel 文件格式复杂,这里我们先导出为 CSV,然后可以考虑使用库来转换
825
+ // 或者直接调用其他服务来处理 Excel 导出
826
+ return this.exportTableDataToCSV(dataSource, databaseName, tableName, options);
827
+ } catch (error) {
828
+ console.error('Oracle导出表数据到Excel失败:', error);
829
+ throw new Error(`导出表数据到Excel失败: ${error.message}`);
830
+ }
831
+ }
832
+
833
+ /**
834
+ * 修改表结构
835
+ */
836
+ async alterTable(dataSource: DataSource, databaseName: string, tableDiff: any): Promise<any> {
837
+ try {
838
+ const tableName = tableDiff.tableName;
839
+ const sqlStatements: string[] = [];
840
+
841
+ // 修改表注释
842
+ if (tableDiff.tableCommentChanged) {
843
+ sqlStatements.push(`COMMENT ON TABLE "${tableName}" IS '${tableDiff.tableComment}';`);
844
+ }
845
+
846
+ // 添加新列
847
+ tableDiff.addedColumns.forEach((column: any) => {
848
+ // 检查type是否已经包含长度信息(括号)
849
+ const typeHasLength = /\(\d+\)/.test(column.type);
850
+
851
+ let columnSQL = `ALTER TABLE "${tableName}" ADD ("${column.name}" ${column.type}`;
852
+
853
+ // 处理长度和精度(仅当type中没有指定长度时才添加)
854
+ if (!typeHasLength) {
855
+ if (column.length) {
856
+ columnSQL += `(${column.length})`;
857
+ } else if (column.precision) {
858
+ if (column.scale) {
859
+ columnSQL += `(${column.precision},${column.scale})`;
860
+ } else {
861
+ columnSQL += `(${column.precision})`;
862
+ }
863
+ }
864
+ }
865
+
866
+ // 处理NULL约束
867
+ if (!column.nullable) {
868
+ columnSQL += ' NOT NULL';
869
+ }
870
+
871
+ // 处理默认值
872
+ if (column.defaultValue) {
873
+ const upperDefault = column.defaultValue.toString().toUpperCase();
874
+ if (['SYSDATE', 'SYSTIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIMESTAMP'].includes(upperDefault)) {
875
+ columnSQL += ` DEFAULT ${upperDefault}`;
876
+ } else {
877
+ columnSQL += ` DEFAULT '${column.defaultValue}'`;
878
+ }
879
+ }
880
+
881
+ // 处理自增(Oracle使用GENERATED ALWAYS AS IDENTITY或SEQUENCE)
882
+ if (column.isAutoIncrement) {
883
+ if (column.type.toLowerCase().includes('number')) {
884
+ columnSQL += ' GENERATED ALWAYS AS IDENTITY';
885
+ }
886
+ }
887
+
888
+ columnSQL += ')';
889
+ sqlStatements.push(columnSQL + ';');
890
+
891
+ // 添加列注释
892
+ if (column.comment) {
893
+ sqlStatements.push(`COMMENT ON COLUMN "${tableName}"."${column.name}" IS '${column.comment}';`);
894
+ }
895
+ });
896
+
897
+ // 修改列
898
+ tableDiff.modifiedColumns.forEach((modification: any) => {
899
+ const { oldColumn, newColumn } = modification;
900
+
901
+ // 检查type是否已经包含长度信息(括号)
902
+ const typeHasLength = /\(\d+\)/.test(newColumn.type);
903
+
904
+ // 修改列类型和长度
905
+ let columnSQL = `ALTER TABLE "${tableName}" MODIFY ("${newColumn.name}" ${newColumn.type}`;
906
+
907
+ // 处理长度和精度(仅当type中没有指定长度时才添加)
908
+ if (!typeHasLength) {
909
+ if (newColumn.length) {
910
+ columnSQL += `(${newColumn.length})`;
911
+ } else if (newColumn.precision) {
912
+ if (newColumn.scale) {
913
+ columnSQL += `(${newColumn.precision},${newColumn.scale})`;
914
+ } else {
915
+ columnSQL += `(${newColumn.precision})`;
916
+ }
917
+ }
918
+ }
919
+
920
+ // 处理NULL约束
921
+ if (!newColumn.nullable) {
922
+ columnSQL += ' NOT NULL';
923
+ }
924
+
925
+ // 处理默认值
926
+ if (newColumn.defaultValue) {
927
+ const upperDefault = newColumn.defaultValue.toString().toUpperCase();
928
+ if (['SYSDATE', 'SYSTIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIMESTAMP'].includes(upperDefault)) {
929
+ columnSQL += ` DEFAULT ${upperDefault}`;
930
+ } else {
931
+ columnSQL += ` DEFAULT '${newColumn.defaultValue}'`;
932
+ }
933
+ }
934
+
935
+ columnSQL += ')';
936
+ sqlStatements.push(columnSQL + ';');
937
+
938
+ // 修改列注释
939
+ if (newColumn.comment) {
940
+ sqlStatements.push(`COMMENT ON COLUMN "${tableName}"."${newColumn.name}" IS '${newColumn.comment}';`);
941
+ }
942
+ });
943
+
944
+ // 删除列
945
+ tableDiff.deletedColumns.forEach((column: any) => {
946
+ sqlStatements.push(`ALTER TABLE "${tableName}" DROP COLUMN "${column.name}";`);
947
+ });
948
+
949
+ // 执行SQL语句
950
+ if (sqlStatements.length > 0) {
951
+ await this.executeBatchQuery(dataSource, sqlStatements, { useTransaction: true });
952
+ }
953
+
954
+ return { ret: 0, message: '表结构修改成功' };
955
+ } catch (error) {
956
+ console.error('Oracle修改表结构失败:', error);
957
+ return { ret: 1, message: `修改表结构失败: ${error instanceof Error ? error.message : String(error)}` };
958
+ }
959
+ }
960
+
961
+ /**
962
+ * 批量插入数据
963
+ */
964
+ async bulkInsert(dataSource: DataSource, databaseName: string, tableName: string, data: any[]): Promise<void> {
965
+ if (data.length === 0) return;
966
+
967
+ // Oracle不支持标准的批量插入语法,需要使用FORALL或多次插入
968
+ for (const row of data) {
969
+ await this.insertData(dataSource, databaseName, tableName, row);
970
+ }
971
+ }
972
+
973
+ /**
974
+ * 插入单条数据
975
+ */
976
+ async insertData(dataSource: DataSource, databaseName: string, tableName: string, data: any): Promise<void> {
977
+ const columns = Object.keys(data);
978
+ const placeholders = columns.map((_, index) => `:${index + 1}`).join(', ');
979
+ const values = columns.map(column => data[column]);
980
+
981
+ const sql = `INSERT INTO "${tableName}" (${columns.map(col => `"${col}"`).join(', ')}) VALUES (${placeholders})`;
982
+
983
+ await dataSource.query(sql, values);
984
+ }
985
+
986
+ /**
987
+ * 删除表
988
+ */
989
+ async dropTable(dataSource: DataSource, databaseName: string, tableName: string): Promise<void> {
990
+ const sql = `DROP TABLE "${tableName}"`;
991
+ await dataSource.query(sql);
992
+ }
993
+
994
+ /**
995
+ * 创建表
996
+ */
997
+ async createTable(dataSource: DataSource, databaseName: string, table: any): Promise<void> {
998
+ const { name, columns, comment } = table;
999
+
1000
+ let sql = `CREATE TABLE "${name}" (\n`;
1001
+ const columnDefs: string[] = [];
1002
+
1003
+ columns.forEach((column: any) => {
1004
+ let columnDef = ` "${column.name}" ${column.type}`;
1005
+
1006
+ if (!column.nullable) {
1007
+ columnDef += ' NOT NULL';
1008
+ }
1009
+
1010
+ if (column.defaultValue) {
1011
+ const upperDefault = column.defaultValue.toString().toUpperCase();
1012
+ if (['SYSDATE', 'CURRENT_TIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIME'].includes(upperDefault)) {
1013
+ columnDef += ` DEFAULT ${upperDefault}`;
1014
+ } else {
1015
+ columnDef += ` DEFAULT '${column.defaultValue}'`;
1016
+ }
1017
+ }
1018
+
1019
+ if (column.isAutoIncrement) {
1020
+ columnDef += ' GENERATED BY DEFAULT ON NULL AS IDENTITY';
1021
+ }
1022
+
1023
+ columnDefs.push(columnDef);
1024
+ });
1025
+
1026
+ sql += columnDefs.join(',\n');
1027
+ sql += '\n)';
1028
+
1029
+ await dataSource.query(sql);
1030
+
1031
+ // 添加表注释
1032
+ if (comment) {
1033
+ await dataSource.query(`COMMENT ON TABLE "${name}" IS '${comment}';`);
1034
+ }
1035
+ }
960
1036
  }