fdb2 1.0.13 → 1.0.15

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 (313) hide show
  1. package/README.md +9 -2
  2. package/bin/docker/.env +4 -0
  3. package/package.json +26 -18
  4. package/public/favicon.ico +0 -0
  5. package/public/favicon.png +0 -0
  6. package/view/modules/header.tpl +1 -1
  7. package/.dockerignore +0 -21
  8. package/.editorconfig +0 -11
  9. package/.eslintrc.cjs +0 -14
  10. package/.eslintrc.json +0 -7
  11. package/.prettierrc.js +0 -3
  12. package/.tpl.env +0 -22
  13. package/.vscodeignore +0 -45
  14. package/dist/package.json +0 -115
  15. package/dist/pnpm-lock.yaml +0 -8135
  16. package/dist/public/.vite/manifest.json +0 -82
  17. package/dist/public/bootstrap-icons.woff +0 -0
  18. package/dist/public/bootstrap-icons.woff2 +0 -0
  19. package/dist/public/bootstrap.css +0 -14152
  20. package/dist/public/bootstrap.js +0 -5038
  21. package/dist/public/explorer.css +0 -2379
  22. package/dist/public/explorer.js +0 -50586
  23. package/dist/public/index.css +0 -1099
  24. package/dist/public/index.js +0 -12862
  25. package/dist/public/layout.css +0 -318
  26. package/dist/public/layout.js +0 -25
  27. package/dist/public/vue.css +0 -1
  28. package/dist/public/vue.js +0 -9110
  29. package/dist/scripts/preinstall.js +0 -112
  30. package/dist/server/index.d.ts +0 -2
  31. package/dist/server/index.d.ts.map +0 -1
  32. package/dist/server/index.js +0 -601
  33. package/dist/server/index.js.map +0 -1
  34. package/dist/server/index.ts +0 -681
  35. package/dist/server/model/connection.entity.d.ts +0 -55
  36. package/dist/server/model/connection.entity.d.ts.map +0 -1
  37. package/dist/server/model/connection.entity.js +0 -59
  38. package/dist/server/model/connection.entity.js.map +0 -1
  39. package/dist/server/model/connection.entity.ts +0 -66
  40. package/dist/server/model/database.entity.d.ts +0 -203
  41. package/dist/server/model/database.entity.d.ts.map +0 -1
  42. package/dist/server/model/database.entity.js +0 -211
  43. package/dist/server/model/database.entity.js.map +0 -1
  44. package/dist/server/model/database.entity.ts +0 -246
  45. package/dist/server/service/connection.service.d.ts +0 -84
  46. package/dist/server/service/connection.service.d.ts.map +0 -1
  47. package/dist/server/service/connection.service.js +0 -369
  48. package/dist/server/service/connection.service.js.map +0 -1
  49. package/dist/server/service/connection.service.ts +0 -359
  50. package/dist/server/service/database/base.service.d.ts +0 -183
  51. package/dist/server/service/database/base.service.d.ts.map +0 -1
  52. package/dist/server/service/database/base.service.js +0 -253
  53. package/dist/server/service/database/base.service.js.map +0 -1
  54. package/dist/server/service/database/base.service.ts +0 -407
  55. package/dist/server/service/database/cockroachdb.service.d.ts +0 -116
  56. package/dist/server/service/database/cockroachdb.service.d.ts.map +0 -1
  57. package/dist/server/service/database/cockroachdb.service.js +0 -812
  58. package/dist/server/service/database/cockroachdb.service.js.map +0 -1
  59. package/dist/server/service/database/cockroachdb.service.ts +0 -871
  60. package/dist/server/service/database/database.service.d.ts +0 -495
  61. package/dist/server/service/database/database.service.d.ts.map +0 -1
  62. package/dist/server/service/database/database.service.js +0 -711
  63. package/dist/server/service/database/database.service.js.map +0 -1
  64. package/dist/server/service/database/database.service.ts +0 -776
  65. package/dist/server/service/database/index.d.ts +0 -8
  66. package/dist/server/service/database/index.d.ts.map +0 -1
  67. package/dist/server/service/database/index.js +0 -18
  68. package/dist/server/service/database/index.js.map +0 -1
  69. package/dist/server/service/database/index.ts +0 -7
  70. package/dist/server/service/database/mongodb.service.d.ts +0 -121
  71. package/dist/server/service/database/mongodb.service.d.ts.map +0 -1
  72. package/dist/server/service/database/mongodb.service.js +0 -502
  73. package/dist/server/service/database/mongodb.service.js.map +0 -1
  74. package/dist/server/service/database/mongodb.service.ts +0 -501
  75. package/dist/server/service/database/mssql.service.d.ts +0 -118
  76. package/dist/server/service/database/mssql.service.d.ts.map +0 -1
  77. package/dist/server/service/database/mssql.service.js +0 -871
  78. package/dist/server/service/database/mssql.service.js.map +0 -1
  79. package/dist/server/service/database/mssql.service.ts +0 -932
  80. package/dist/server/service/database/mysql.service.d.ts +0 -114
  81. package/dist/server/service/database/mysql.service.d.ts.map +0 -1
  82. package/dist/server/service/database/mysql.service.js +0 -960
  83. package/dist/server/service/database/mysql.service.js.map +0 -1
  84. package/dist/server/service/database/mysql.service.ts +0 -1026
  85. package/dist/server/service/database/oracle.service.d.ts +0 -126
  86. package/dist/server/service/database/oracle.service.d.ts.map +0 -1
  87. package/dist/server/service/database/oracle.service.js +0 -963
  88. package/dist/server/service/database/oracle.service.js.map +0 -1
  89. package/dist/server/service/database/oracle.service.ts +0 -1036
  90. package/dist/server/service/database/postgres.service.d.ts +0 -122
  91. package/dist/server/service/database/postgres.service.d.ts.map +0 -1
  92. package/dist/server/service/database/postgres.service.js +0 -882
  93. package/dist/server/service/database/postgres.service.js.map +0 -1
  94. package/dist/server/service/database/postgres.service.ts +0 -961
  95. package/dist/server/service/database/sap.service.d.ts +0 -115
  96. package/dist/server/service/database/sap.service.d.ts.map +0 -1
  97. package/dist/server/service/database/sap.service.js +0 -868
  98. package/dist/server/service/database/sap.service.js.map +0 -1
  99. package/dist/server/service/database/sap.service.ts +0 -922
  100. package/dist/server/service/database/sqlite.service.d.ts +0 -112
  101. package/dist/server/service/database/sqlite.service.d.ts.map +0 -1
  102. package/dist/server/service/database/sqlite.service.js +0 -723
  103. package/dist/server/service/database/sqlite.service.js.map +0 -1
  104. package/dist/server/service/database/sqlite.service.ts +0 -787
  105. package/dist/server/service/session.service.ts +0 -158
  106. package/dist/view/index.html +0 -45
  107. package/env.d.ts +0 -1
  108. package/packages/vscode/.vscodeignore +0 -44
  109. package/packages/vscode/README.md +0 -62
  110. package/packages/vscode/out/database-services/base.service.js +0 -236
  111. package/packages/vscode/out/database-services/base.service.js.map +0 -1
  112. package/packages/vscode/out/database-services/cockroachdb.service.js +0 -634
  113. package/packages/vscode/out/database-services/cockroachdb.service.js.map +0 -1
  114. package/packages/vscode/out/database-services/connection.service.js +0 -346
  115. package/packages/vscode/out/database-services/connection.service.js.map +0 -1
  116. package/packages/vscode/out/database-services/database.service.js +0 -571
  117. package/packages/vscode/out/database-services/database.service.js.map +0 -1
  118. package/packages/vscode/out/database-services/index.js +0 -18
  119. package/packages/vscode/out/database-services/index.js.map +0 -1
  120. package/packages/vscode/out/database-services/model/connection.entity.js +0 -11
  121. package/packages/vscode/out/database-services/model/connection.entity.js.map +0 -1
  122. package/packages/vscode/out/database-services/model/database.entity.js +0 -35
  123. package/packages/vscode/out/database-services/model/database.entity.js.map +0 -1
  124. package/packages/vscode/out/database-services/mongodb.service.js +0 -458
  125. package/packages/vscode/out/database-services/mongodb.service.js.map +0 -1
  126. package/packages/vscode/out/database-services/mssql.service.js +0 -694
  127. package/packages/vscode/out/database-services/mssql.service.js.map +0 -1
  128. package/packages/vscode/out/database-services/mysql.service.js +0 -735
  129. package/packages/vscode/out/database-services/mysql.service.js.map +0 -1
  130. package/packages/vscode/out/database-services/oracle.service.js +0 -787
  131. package/packages/vscode/out/database-services/oracle.service.js.map +0 -1
  132. package/packages/vscode/out/database-services/postgres.service.js +0 -696
  133. package/packages/vscode/out/database-services/postgres.service.js.map +0 -1
  134. package/packages/vscode/out/database-services/sap.service.js +0 -695
  135. package/packages/vscode/out/database-services/sap.service.js.map +0 -1
  136. package/packages/vscode/out/database-services/sqlite.service.js +0 -532
  137. package/packages/vscode/out/database-services/sqlite.service.js.map +0 -1
  138. package/packages/vscode/out/extension.js +0 -93
  139. package/packages/vscode/out/extension.js.map +0 -1
  140. package/packages/vscode/out/provider/DatabaseTreeProvider.js +0 -159
  141. package/packages/vscode/out/provider/DatabaseTreeProvider.js.map +0 -1
  142. package/packages/vscode/out/provider/WebViewProvider.js +0 -259
  143. package/packages/vscode/out/provider/WebViewProvider.js.map +0 -1
  144. package/packages/vscode/out/service/ConnectionManager.js +0 -105
  145. package/packages/vscode/out/service/ConnectionManager.js.map +0 -1
  146. package/packages/vscode/out/service/DatabaseServiceBridge.js +0 -395
  147. package/packages/vscode/out/service/DatabaseServiceBridge.js.map +0 -1
  148. package/packages/vscode/out/typings/connection.js +0 -3
  149. package/packages/vscode/out/typings/connection.js.map +0 -1
  150. package/packages/vscode/package.json +0 -144
  151. package/packages/vscode/resources/icon.svg +0 -5
  152. package/packages/vscode/resources/webview/_plugin-vue_export-helper.js +0 -6529
  153. package/packages/vscode/resources/webview/_plugin-vue_export-helper.js.map +0 -1
  154. package/packages/vscode/resources/webview/connection.css +0 -69
  155. package/packages/vscode/resources/webview/connection.js +0 -228
  156. package/packages/vscode/resources/webview/connection.js.map +0 -1
  157. package/packages/vscode/resources/webview/database.css +0 -259
  158. package/packages/vscode/resources/webview/database.js +0 -275
  159. package/packages/vscode/resources/webview/database.js.map +0 -1
  160. package/packages/vscode/resources/webview/favicon.ico +0 -0
  161. package/packages/vscode/resources/webview/index.html +0 -9
  162. package/packages/vscode/resources/webview/modules/header.tpl +0 -14
  163. package/packages/vscode/resources/webview/modules/initial_state.tpl +0 -55
  164. package/packages/vscode/resources/webview/query.css +0 -162
  165. package/packages/vscode/resources/webview/query.js +0 -198
  166. package/packages/vscode/resources/webview/query.js.map +0 -1
  167. package/packages/vscode/src/database-services/base.service.js.map +0 -1
  168. package/packages/vscode/src/database-services/base.service.ts +0 -363
  169. package/packages/vscode/src/database-services/cockroachdb.service.js.map +0 -1
  170. package/packages/vscode/src/database-services/cockroachdb.service.ts +0 -659
  171. package/packages/vscode/src/database-services/connection.service.ts +0 -341
  172. package/packages/vscode/src/database-services/database.service.ts +0 -630
  173. package/packages/vscode/src/database-services/index.ts +0 -7
  174. package/packages/vscode/src/database-services/model/connection.entity.js +0 -11
  175. package/packages/vscode/src/database-services/model/connection.entity.js.map +0 -1
  176. package/packages/vscode/src/database-services/model/connection.entity.ts +0 -66
  177. package/packages/vscode/src/database-services/model/database.entity.js +0 -35
  178. package/packages/vscode/src/database-services/model/database.entity.js.map +0 -1
  179. package/packages/vscode/src/database-services/model/database.entity.ts +0 -246
  180. package/packages/vscode/src/database-services/mongodb.service.js.map +0 -1
  181. package/packages/vscode/src/database-services/mongodb.service.ts +0 -454
  182. package/packages/vscode/src/database-services/mssql.service.js.map +0 -1
  183. package/packages/vscode/src/database-services/mssql.service.ts +0 -723
  184. package/packages/vscode/src/database-services/mysql.service.js.map +0 -1
  185. package/packages/vscode/src/database-services/mysql.service.ts +0 -761
  186. package/packages/vscode/src/database-services/oracle.service.js.map +0 -1
  187. package/packages/vscode/src/database-services/oracle.service.ts +0 -832
  188. package/packages/vscode/src/database-services/postgres.service.js.map +0 -1
  189. package/packages/vscode/src/database-services/postgres.service.ts +0 -741
  190. package/packages/vscode/src/database-services/sap.service.js.map +0 -1
  191. package/packages/vscode/src/database-services/sap.service.ts +0 -713
  192. package/packages/vscode/src/database-services/sqlite.service.js.map +0 -1
  193. package/packages/vscode/src/database-services/sqlite.service.ts +0 -558
  194. package/packages/vscode/src/extension.ts +0 -76
  195. package/packages/vscode/src/provider/DatabaseTreeProvider.ts +0 -167
  196. package/packages/vscode/src/provider/WebViewProvider.ts +0 -277
  197. package/packages/vscode/src/service/DatabaseServiceBridge.ts +0 -414
  198. package/packages/vscode/src/typings/connection.ts +0 -90
  199. package/packages/vscode/tsconfig.json +0 -21
  200. package/scripts/preinstall.js +0 -112
  201. package/server/index.ts +0 -681
  202. package/server/model/connection.entity.js +0 -11
  203. package/server/model/connection.entity.js.map +0 -1
  204. package/server/model/connection.entity.ts +0 -66
  205. package/server/model/database.entity.js +0 -35
  206. package/server/model/database.entity.js.map +0 -1
  207. package/server/model/database.entity.ts +0 -246
  208. package/server/service/connection.service.ts +0 -359
  209. package/server/service/database/base.service.ts +0 -407
  210. package/server/service/database/cockroachdb.service.ts +0 -871
  211. package/server/service/database/database.service.ts +0 -776
  212. package/server/service/database/index.ts +0 -7
  213. package/server/service/database/mongodb.service.ts +0 -501
  214. package/server/service/database/mssql.service.ts +0 -932
  215. package/server/service/database/mysql.service.ts +0 -1026
  216. package/server/service/database/oracle.service.ts +0 -1036
  217. package/server/service/database/postgres.service.ts +0 -961
  218. package/server/service/database/sap.service.ts +0 -922
  219. package/server/service/database/sqlite.service.ts +0 -787
  220. package/server/service/session.service.ts +0 -158
  221. package/server/tsconfig.json +0 -20
  222. package/src/adapter/ajax.ts +0 -135
  223. package/src/assets/base.css +0 -1
  224. package/src/assets/database.css +0 -950
  225. package/src/assets/images/collapse.png +0 -0
  226. package/src/assets/images/no-login.png +0 -0
  227. package/src/assets/images/svg/illustrations/illustration-1.svg +0 -1
  228. package/src/assets/images/svg/illustrations/illustration-2.svg +0 -2
  229. package/src/assets/images/svg/illustrations/illustration-3.svg +0 -50
  230. package/src/assets/images/svg/illustrations/illustration-4.svg +0 -1
  231. package/src/assets/images/svg/illustrations/illustration-5.svg +0 -73
  232. package/src/assets/images/svg/illustrations/illustration-6.svg +0 -89
  233. package/src/assets/images/svg/illustrations/illustration-7.svg +0 -39
  234. package/src/assets/images/svg/illustrations/illustration-8.svg +0 -1
  235. package/src/assets/images/svg/separators/curve-2.svg +0 -3
  236. package/src/assets/images/svg/separators/curve.svg +0 -3
  237. package/src/assets/images/svg/separators/line.svg +0 -3
  238. package/src/assets/images/theme/light/screen-1-1000x800.jpg +0 -0
  239. package/src/assets/images/theme/light/screen-2-1000x800.jpg +0 -0
  240. package/src/assets/login/bg.jpg +0 -0
  241. package/src/assets/login/bg.png +0 -0
  242. package/src/assets/login/left.jpg +0 -0
  243. package/src/assets/logo.svg +0 -73
  244. package/src/assets/logo.webp +0 -0
  245. package/src/assets/main.css +0 -1
  246. package/src/base/config.ts +0 -20
  247. package/src/base/detect.ts +0 -134
  248. package/src/base/entity.ts +0 -92
  249. package/src/base/eventBus.ts +0 -37
  250. package/src/components/connection-editor/index.vue +0 -589
  251. package/src/components/dataGrid/index.vue +0 -163
  252. package/src/components/dataGrid/pagination.vue +0 -106
  253. package/src/components/loading/index.vue +0 -43
  254. package/src/components/modal/index.ts +0 -181
  255. package/src/components/modal/index.vue +0 -560
  256. package/src/components/toast/index.ts +0 -44
  257. package/src/components/toast/toast.vue +0 -58
  258. package/src/components/user/name.vue +0 -104
  259. package/src/components/user/selector.vue +0 -416
  260. package/src/domain/SysConfig.ts +0 -74
  261. package/src/platform/App.vue +0 -8
  262. package/src/platform/database/components/connection-detail.vue +0 -1153
  263. package/src/platform/database/components/data-editor.vue +0 -478
  264. package/src/platform/database/components/data-import-export.vue +0 -1602
  265. package/src/platform/database/components/database-detail.vue +0 -1199
  266. package/src/platform/database/components/database-monitor.vue +0 -1086
  267. package/src/platform/database/components/db-tools.vue +0 -1265
  268. package/src/platform/database/components/query-history.vue +0 -1349
  269. package/src/platform/database/components/sql-executor.vue +0 -738
  270. package/src/platform/database/components/sql-query-editor.vue +0 -1046
  271. package/src/platform/database/components/table-data-grid.vue +0 -273
  272. package/src/platform/database/components/table-detail.vue +0 -1173
  273. package/src/platform/database/components/table-editor.vue +0 -917
  274. package/src/platform/database/explorer.vue +0 -1840
  275. package/src/platform/database/index.vue +0 -1193
  276. package/src/platform/database/layout.vue +0 -367
  277. package/src/platform/database/router.ts +0 -37
  278. package/src/platform/database/styles/common.scss +0 -602
  279. package/src/platform/database/types/common.ts +0 -445
  280. package/src/platform/database/utils/export.ts +0 -232
  281. package/src/platform/database/utils/helpers.ts +0 -437
  282. package/src/platform/index.ts +0 -33
  283. package/src/platform/router.ts +0 -41
  284. package/src/platform/vscode/bridge.ts +0 -121
  285. package/src/platform/vscode/components/ConnectionPanel.vue +0 -272
  286. package/src/platform/vscode/components/DatabasePanel.vue +0 -532
  287. package/src/platform/vscode/components/QueryPanel.vue +0 -371
  288. package/src/platform/vscode/entry/connection.ts +0 -13
  289. package/src/platform/vscode/entry/database.ts +0 -13
  290. package/src/platform/vscode/entry/query.ts +0 -13
  291. package/src/platform/vscode/index.ts +0 -5
  292. package/src/service/base.ts +0 -134
  293. package/src/service/database.ts +0 -506
  294. package/src/service/login.ts +0 -121
  295. package/src/shims-vue.d.ts +0 -7
  296. package/src/stores/connection.ts +0 -266
  297. package/src/stores/session.ts +0 -87
  298. package/src/typings/database-types.ts +0 -413
  299. package/src/typings/database.ts +0 -364
  300. package/src/typings/global.d.ts +0 -58
  301. package/src/typings/pinia.d.ts +0 -8
  302. package/src/utils/clipboard.ts +0 -30
  303. package/src/utils/database-types.ts +0 -243
  304. package/src/utils/modal.ts +0 -124
  305. package/src/utils/request.ts +0 -55
  306. package/src/utils/sleep.ts +0 -4
  307. package/src/utils/toast.ts +0 -73
  308. package/src/utils/util.ts +0 -171
  309. package/src/utils/xlsx.ts +0 -228
  310. package/tsconfig.json +0 -33
  311. package/tsconfig.server.json +0 -19
  312. package/vite.config.ts +0 -424
  313. package/vite.config.vscode.ts +0 -47
@@ -1,961 +0,0 @@
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
- '' as collation,
43
- obj_description(c.oid) as comment
44
- FROM information_schema.tables t
45
- LEFT JOIN pg_class c ON c.relname = t.table_name
46
- WHERE t.table_schema NOT IN ('information_schema', 'pg_catalog')
47
- AND t.table_type = 'BASE TABLE'
48
- `);
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
- collation: row.collation,
57
- comment: row.comment || ''
58
- }));
59
- }
60
-
61
- /**
62
- * 获取PostgreSQL列信息
63
- */
64
- async getColumns(dataSource: DataSource, database: string, table: string): Promise<ColumnEntity[]> {
65
- // 使用兼容的SQL查询,移除可能不兼容的精度字段
66
- const result = await dataSource.query(`
67
- SELECT
68
- column_name as name,
69
- data_type as type,
70
- is_nullable as nullable,
71
- column_default as defaultValue,
72
- character_maximum_length as length
73
- FROM information_schema.columns
74
- WHERE table_name = $1
75
- `, [table]);
76
-
77
- // 获取主键信息
78
- const primaryKeys = await this.getPrimaryKeys(dataSource, table);
79
-
80
- // 获取 IDENTITY 列信息(PostgreSQL 10+)
81
- const identityColumns = await this.getIdentityColumns(dataSource, table);
82
-
83
- // 从data_type中解析精度信息
84
- return result.map((row: any) => {
85
- const dataType = row.type || '';
86
- let precision = undefined;
87
- let scale = undefined;
88
-
89
- // 解析DECIMAL(M,D)或NUMERIC(M,D)类型的精度
90
- const decimalMatch = dataType.match(/(DECIMAL|NUMERIC)\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)/i);
91
- if (decimalMatch) {
92
- precision = parseInt(decimalMatch[2]);
93
- scale = parseInt(decimalMatch[3]);
94
- }
95
-
96
- // 检查是否为自增列(SERIAL 或 IDENTITY)
97
- const isAutoIncrement = row.defaultValue?.includes('nextval') ||
98
- identityColumns.includes(row.name);
99
-
100
- return {
101
- name: row.name,
102
- type: row.type,
103
- nullable: row.nullable === 'YES',
104
- defaultValue: row.defaultValue,
105
- isPrimary: primaryKeys.includes(row.name),
106
- isAutoIncrement: isAutoIncrement,
107
- length: row.length,
108
- precision: precision,
109
- scale: scale
110
- };
111
- });
112
- }
113
-
114
- /**
115
- * 获取PostgreSQL索引信息
116
- */
117
- async getIndexes(dataSource: DataSource, database: string, table: string): Promise<IndexEntity[]> {
118
- const result = await dataSource.query(`
119
- SELECT
120
- indexname as name,
121
- indexdef as definition
122
- FROM pg_indexes
123
- WHERE tablename = $1
124
- `, [table]);
125
-
126
- return result.map((row: any) => ({
127
- name: row.name,
128
- type: 'INDEX',
129
- columns: [], // 需要解析definition
130
- unique: row.definition.toLowerCase().includes('unique')
131
- }));
132
- }
133
-
134
- /**
135
- * 获取PostgreSQL外键信息
136
- */
137
- async getForeignKeys(dataSource: DataSource, database: string, table: string): Promise<ForeignKeyEntity[]> {
138
- const result = await dataSource.query(`
139
- SELECT
140
- tc.constraint_name as name,
141
- kcu.column_name as column,
142
- ccu.table_name as referencedTable,
143
- ccu.column_name as referencedColumn,
144
- rc.delete_rule as onDelete
145
- FROM information_schema.table_constraints tc
146
- JOIN information_schema.key_column_usage kcu
147
- ON tc.constraint_name = kcu.constraint_name
148
- JOIN information_schema.constraint_column_usage ccu
149
- ON ccu.constraint_name = tc.constraint_name
150
- JOIN information_schema.referential_constraints rc
151
- ON tc.constraint_name = rc.constraint_name
152
- WHERE tc.constraint_type = 'FOREIGN KEY'
153
- AND tc.table_name = $1
154
- `, [table]);
155
-
156
- return result.map((row: any) => ({
157
- name: row.name,
158
- column: row.column,
159
- referencedTable: row.referencedtable,
160
- referencedColumn: row.referencedcolumn,
161
- onDelete: row.ondelete,
162
- onUpdate: 'NO ACTION'
163
- }));
164
- }
165
-
166
- /**
167
- * 获取PostgreSQL数据库大小
168
- */
169
- async getDatabaseSize(dataSource: DataSource, database: string): Promise<number> {
170
- const result = await dataSource.query(`
171
- SELECT pg_database_size($1) as size
172
- `, [database]);
173
- return result[0]?.size || 0;
174
- }
175
-
176
- /**
177
- * 获取主键信息
178
- */
179
- private async getPrimaryKeys(dataSource: DataSource, table: string): Promise<string[]> {
180
- const result = await dataSource.query(`
181
- SELECT column_name
182
- FROM information_schema.table_constraints tc
183
- JOIN information_schema.key_column_usage kcu
184
- ON tc.constraint_name = kcu.constraint_name
185
- WHERE tc.constraint_type = 'PRIMARY KEY'
186
- AND tc.table_name = $1
187
- `, [table]);
188
- return result.map((row: any) => row.column_name);
189
- }
190
-
191
- /**
192
- * 获取PostgreSQL IDENTITY列信息(PostgreSQL 10+)
193
- */
194
- private async getIdentityColumns(dataSource: DataSource, table: string): Promise<string[]> {
195
- try {
196
- const result = await dataSource.query(`
197
- SELECT column_name
198
- FROM information_schema.columns
199
- WHERE table_name = $1
200
- AND is_identity = 'YES'
201
- `, [table]);
202
- return result.map((row: any) => row.column_name);
203
- } catch (error) {
204
- // 如果查询失败(PostgreSQL 版本低于 10),返回空数组
205
- return [];
206
- }
207
- }
208
-
209
- /**
210
- * PostgreSQL使用双引号标识符
211
- */
212
- public quoteIdentifier(identifier: string): string {
213
- return `"${identifier}"`;
214
- }
215
-
216
- /**
217
- * 获取PostgreSQL视图列表
218
- */
219
- async getViews(dataSource: DataSource, database: string): Promise<any[]> {
220
- const result = await dataSource.query(`
221
- SELECT
222
- table_name as name,
223
- COALESCE(obj_description(c.oid), '') as comment,
224
- table_schema as schemaName
225
- FROM information_schema.views v
226
- LEFT JOIN pg_class c ON c.relname = v.table_name
227
- WHERE v.table_schema NOT IN ('information_schema', 'pg_catalog')
228
- ORDER BY v.table_name
229
- `);
230
-
231
- return result.map((row: any) => ({
232
- name: row.name,
233
- comment: row.comment || '',
234
- schemaName: row.schemaname
235
- }));
236
- }
237
-
238
- /**
239
- * 获取PostgreSQL视图定义
240
- */
241
- async getViewDefinition(dataSource: DataSource, database: string, viewName: string): Promise<string> {
242
- const result = await dataSource.query(`
243
- SELECT view_definition as definition
244
- FROM information_schema.views
245
- WHERE table_name = $1
246
- AND table_schema NOT IN ('information_schema', 'pg_catalog')
247
- `, [viewName]);
248
-
249
- return result[0]?.definition || '';
250
- }
251
-
252
- /**
253
- * 获取PostgreSQL存储过程列表
254
- */
255
- async getProcedures(dataSource: DataSource, database: string): Promise<any[]> {
256
- const result = await dataSource.query(`
257
- SELECT
258
- routine_name as name,
259
- '' as comment,
260
- routine_type as type,
261
- COALESCE(data_type, '') as returnType,
262
- external_language as language
263
- FROM information_schema.routines
264
- WHERE routine_schema NOT IN ('information_schema', 'pg_catalog')
265
- ORDER BY routine_name
266
- `);
267
-
268
- return result.map((row: any) => ({
269
- name: row.name,
270
- comment: row.comment || '',
271
- type: row.type,
272
- returnType: row.returntype || '',
273
- language: row.language || 'SQL'
274
- }));
275
- }
276
-
277
- /**
278
- * 获取PostgreSQL存储过程定义
279
- */
280
- async getProcedureDefinition(dataSource: DataSource, database: string, procedureName: string): Promise<string> {
281
- const result = await dataSource.query(`
282
- SELECT routine_definition as definition
283
- FROM information_schema.routines
284
- WHERE routine_name = $1
285
- AND routine_schema NOT IN ('information_schema', 'pg_catalog')
286
- `, [procedureName]);
287
-
288
- return result[0]?.definition || '';
289
- }
290
-
291
- /**
292
- * 创建PostgreSQL数据库
293
- */
294
- async createDatabase(dataSource: DataSource, databaseName: string, options?: any): Promise<void> {
295
- let sql = `CREATE DATABASE ${this.quoteIdentifier(databaseName)}`;
296
-
297
- if (options) {
298
- const clauses = [];
299
-
300
- if (options.owner) {
301
- clauses.push(`OWNER ${options.owner}`);
302
- }
303
-
304
- if (options.template) {
305
- clauses.push(`TEMPLATE ${options.template}`);
306
- }
307
-
308
- if (options.encoding) {
309
- clauses.push(`ENCODING '${options.encoding}'`);
310
- }
311
-
312
- if (options.lcCollate) {
313
- clauses.push(`LC_COLLATE '${options.lcCollate}'`);
314
- }
315
-
316
- if (options.lcCtype) {
317
- clauses.push(`LC_CTYPE '${options.lcCtype}'`);
318
- }
319
-
320
- if (options.tablespace) {
321
- clauses.push(`TABLESPACE ${options.tablespace}`);
322
- }
323
-
324
- if (options.allowConnections !== undefined) {
325
- clauses.push(`ALLOW_CONNECTIONS ${options.allowConnections}`);
326
- }
327
-
328
- if (options.connectionLimit !== undefined) {
329
- clauses.push(`CONNECTION LIMIT ${options.connectionLimit}`);
330
- }
331
-
332
- if (clauses.length > 0) {
333
- sql += ' ' + clauses.join(' ');
334
- }
335
- }
336
-
337
- await dataSource.query(sql);
338
- }
339
-
340
- /**
341
- * 删除PostgreSQL数据库
342
- */
343
- async dropDatabase(dataSource: DataSource, databaseName: string): Promise<void> {
344
- const sql = `DROP DATABASE ${this.quoteIdentifier(databaseName)}`;
345
- await dataSource.query(sql);
346
- }
347
-
348
- /**
349
- * 导出数据库架构
350
- */
351
- async exportSchema(dataSource: DataSource, databaseName: string): Promise<string> {
352
- // 获取所有表
353
- const tables = await this.getTables(dataSource, databaseName);
354
- let schemaSql = `-- 数据库架构导出 - ${databaseName}\n`;
355
- schemaSql += `-- 导出时间: ${new Date().toISOString()}\n\n`;
356
-
357
- // 为每个表生成CREATE TABLE语句
358
- for (const table of tables) {
359
- // 获取表结构
360
- const columns = await this.getColumns(dataSource, databaseName, table.name);
361
- const indexes = await this.getIndexes(dataSource, databaseName, table.name);
362
- const foreignKeys = await this.getForeignKeys(dataSource, databaseName, table.name);
363
-
364
- // 生成CREATE TABLE语句
365
- schemaSql += `-- 表结构: ${table.name}\n`;
366
- schemaSql += `CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(table.name)} (\n`;
367
-
368
- // 添加列定义
369
- const columnDefinitions = columns.map(column => {
370
- let definition = ` ${this.quoteIdentifier(column.name)} ${column.type}`;
371
- if (!column.nullable) definition += ' NOT NULL';
372
- if (column.defaultValue !== undefined) {
373
- // 特殊关键字处理
374
- const upperDefault = column.defaultValue.toString().toUpperCase();
375
- if (upperDefault === 'CURRENT_TIMESTAMP' || upperDefault === 'NOW()' || upperDefault === 'CURRENT_DATE') {
376
- definition += ` DEFAULT ${upperDefault}`;
377
- } else {
378
- definition += ` DEFAULT ${column.defaultValue === null ? 'NULL' : `'${column.defaultValue}'`}`;
379
- }
380
- }
381
- if (column.isAutoIncrement) definition += ' SERIAL';
382
- return definition;
383
- });
384
-
385
- // 添加主键
386
- const primaryKeyColumns = columns.filter(column => column.isPrimary);
387
- if (primaryKeyColumns.length > 0) {
388
- const primaryKeyNames = primaryKeyColumns.map(column => this.quoteIdentifier(column.name)).join(', ');
389
- columnDefinitions.push(` PRIMARY KEY (${primaryKeyNames})`);
390
- }
391
-
392
- schemaSql += columnDefinitions.join(',\n');
393
- schemaSql += '\n);\n\n';
394
-
395
- // 添加索引
396
- for (const index of indexes) {
397
- if (index.type === 'PRIMARY' || index.name.toUpperCase() === 'PRIMARY') continue; // 跳过主键索引
398
- schemaSql += `-- 索引: ${index.name} on ${table.name}\n`;
399
- schemaSql += `CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX ${this.quoteIdentifier(index.name)} ON ${this.quoteIdentifier(table.name)} (${index.columns.map(col => this.quoteIdentifier(col)).join(', ')})\n`;
400
- }
401
-
402
- if (indexes.length > 0) schemaSql += '\n';
403
-
404
- // 添加外键
405
- for (const foreignKey of foreignKeys) {
406
- schemaSql += `-- 外键: ${foreignKey.name} on ${table.name}\n`;
407
- 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`;
408
- }
409
-
410
- if (foreignKeys.length > 0) schemaSql += '\n';
411
- }
412
-
413
- return schemaSql;
414
- }
415
-
416
- /**
417
- * 查看数据库日志
418
- */
419
- async viewLogs(dataSource: DataSource, database?: string, limit: number = 100): Promise<any[]> {
420
- // PostgreSQL查看日志
421
- try {
422
- // 尝试查看PostgreSQL日志设置
423
- const logs = await dataSource.query(`SELECT name, setting FROM pg_settings WHERE name LIKE '%log%' LIMIT ${limit}`);
424
- return logs;
425
- } catch (error) {
426
- try {
427
- // 尝试查看最近的连接日志
428
- const logs = await dataSource.query(`SELECT * FROM pg_stat_activity LIMIT ${limit}`);
429
- return logs;
430
- } catch (e) {
431
- return [{ message: '无法获取PostgreSQL日志,请确保具有适当的权限' }];
432
- }
433
- }
434
- }
435
-
436
- /**
437
- * 备份数据库
438
- */
439
- async backupDatabase(dataSource: DataSource, databaseName: string, options?: any): Promise<string> {
440
- // PostgreSQL备份数据库
441
- try {
442
- // 使用pg_dump命令备份
443
- const backupPath = options?.path || path.join(__dirname, '..', '..', 'backups');
444
-
445
- // 确保备份目录存在
446
- if (!fs.existsSync(backupPath)) {
447
- fs.mkdirSync(backupPath, { recursive: true });
448
- }
449
-
450
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
451
- const backupFile = path.join(backupPath, `${databaseName}_${timestamp}.sql`);
452
-
453
- // 执行备份命令
454
- const connectionOptions = dataSource.options as any;
455
- const host = connectionOptions.host || 'localhost';
456
- const port = connectionOptions.port || 5432;
457
- const user = connectionOptions.username;
458
- const password = connectionOptions.password;
459
-
460
- // 构建pg_dump命令
461
- let command = `pg_dump -h ${host} -p ${port} -U ${user} -d ${databaseName} > ${backupFile}`;
462
-
463
- // 执行命令
464
- execSync(command, { env: { ...process.env, PGPASSWORD: password } });
465
-
466
- return `备份成功:${backupFile}`;
467
- } catch (error) {
468
- console.error('PostgreSQL备份失败:', error);
469
- throw new Error(`备份失败: ${error.message}`);
470
- }
471
- }
472
-
473
- /**
474
- * 恢复数据库
475
- */
476
- async restoreDatabase(dataSource: DataSource, databaseName: string, filePath: string, options?: any): Promise<void> {
477
- // PostgreSQL恢复数据库
478
- try {
479
- // 执行恢复命令
480
- const connectionOptions = dataSource.options as any;
481
- const host = connectionOptions.host || 'localhost';
482
- const port = connectionOptions.port || 5432;
483
- const user = connectionOptions.username;
484
- const password = connectionOptions.password;
485
-
486
- // 构建psql命令
487
- let command = `psql -h ${host} -p ${port} -U ${user} -d ${databaseName} -f ${filePath}`;
488
-
489
- // 执行命令
490
- execSync(command, { env: { ...process.env, PGPASSWORD: password } });
491
- } catch (error) {
492
- console.error('PostgreSQL恢复失败:', error);
493
- throw new Error(`恢复失败: ${error.message}`);
494
- }
495
- }
496
-
497
- /**
498
- * 导出表数据到 SQL 文件
499
- */
500
- async exportTableDataToSQL(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
501
- try {
502
- // 创建导出目录
503
- const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
504
- if (!fs.existsSync(exportPath)) {
505
- fs.mkdirSync(exportPath, { recursive: true });
506
- }
507
-
508
- // 生成文件名
509
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
510
- const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.sql`);
511
-
512
- // 获取表结构
513
- const columns = await this.getColumns(dataSource, databaseName, tableName);
514
- const columnNames = columns.map(column => column.name);
515
-
516
- // 生成文件头部
517
- const header = `-- 表数据导出 - ${tableName}\n` +
518
- `-- 导出时间: ${new Date().toISOString()}\n\n`;
519
- fs.writeFileSync(exportFile, header, 'utf8');
520
-
521
- // 分批处理数据,避免一次性加载大量数据到内存
522
- const batchSize = options?.batchSize || 10000; // 每批处理10000行
523
- let offset = 0;
524
- let hasMoreData = true;
525
-
526
- while (hasMoreData) {
527
- // 分批查询数据
528
- const query = `SELECT * FROM ${this.quoteIdentifier(tableName)} LIMIT ${batchSize} OFFSET ${offset}`;
529
- const data = await dataSource.query(query);
530
-
531
- if (data.length === 0) {
532
- hasMoreData = false;
533
- break;
534
- }
535
-
536
- // 生成当前批次的 INSERT 语句
537
- let batchSql = '';
538
- data.forEach((row: any) => {
539
- const values = columnNames.map(column => {
540
- const value = row[column];
541
- if (value === null || value === undefined) {
542
- return 'NULL';
543
- } else if (typeof value === 'string') {
544
- return `'${value.replace(/'/g, "''")}'`;
545
- } else if (typeof value === 'boolean') {
546
- return value ? 'TRUE' : 'FALSE';
547
- } else if (value instanceof Date) {
548
- return `'${value.toISOString()}'`;
549
- } else if (typeof value === 'object' && value !== null) {
550
- // 处理JSON类型
551
- try {
552
- return `'${JSON.stringify(value).replace(/'/g, "''")}'`;
553
- } catch {
554
- return `'${String(value).replace(/'/g, "''")}'`;
555
- }
556
- } else {
557
- return String(value);
558
- }
559
- });
560
-
561
- batchSql += `INSERT INTO ${this.quoteIdentifier(tableName)} (${columnNames.map(col => this.quoteIdentifier(col)).join(', ')}) VALUES (${values.join(', ')});\n`;
562
- });
563
-
564
- // 追加写入文件
565
- fs.appendFileSync(exportFile, batchSql, 'utf8');
566
-
567
- // 增加偏移量
568
- offset += batchSize;
569
-
570
- // 打印进度信息
571
- console.log(`PostgreSQL导出表数据进度: ${tableName} - 已处理 ${offset} 行`);
572
- }
573
-
574
- return exportFile;
575
- } catch (error) {
576
- console.error('PostgreSQL导出表数据失败:', error);
577
- throw new Error(`导出表数据失败: ${error.message}`);
578
- }
579
- }
580
-
581
- /**
582
- * 导出表数据到 CSV 文件
583
- */
584
- async exportTableDataToCSV(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
585
- try {
586
- // 创建导出目录
587
- const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
588
- if (!fs.existsSync(exportPath)) {
589
- fs.mkdirSync(exportPath, { recursive: true });
590
- }
591
-
592
- // 生成文件名
593
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
594
- const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.csv`);
595
-
596
- // 获取表结构
597
- const columns = await this.getColumns(dataSource, databaseName, tableName);
598
- const columnNames = columns.map(column => column.name);
599
-
600
- // 写入 CSV 头部(包含 UTF-8 BOM)
601
- const bom = Buffer.from([0xEF, 0xBB, 0xBF]);
602
- fs.writeFileSync(exportFile, bom);
603
- fs.appendFileSync(exportFile, columnNames.map(name => `"${name}"`).join(',') + '\n', 'utf8');
604
-
605
- // 分批处理数据,避免一次性加载大量数据到内存
606
- const batchSize = options?.batchSize || 10000; // 每批处理10000行
607
- let offset = 0;
608
- let hasMoreData = true;
609
-
610
- while (hasMoreData) {
611
- // 分批查询数据
612
- const query = `SELECT * FROM ${this.quoteIdentifier(tableName)} LIMIT ${batchSize} OFFSET ${offset}`;
613
- const data = await dataSource.query(query);
614
-
615
- if (data.length === 0) {
616
- hasMoreData = false;
617
- break;
618
- }
619
-
620
- // 生成当前批次的 CSV 行
621
- let batchCsv = '';
622
- data.forEach((row: any) => {
623
- const values = columnNames.map(column => {
624
- const value = row[column];
625
- if (value === null || value === undefined) {
626
- return '';
627
- } else if (typeof value === 'string') {
628
- // 转义双引号并包裹在双引号中
629
- return `"${value.replace(/"/g, '""')}"`;
630
- } else if (value instanceof Date) {
631
- return `"${value.toISOString().slice(0, 19).replace('T', ' ')}"`;
632
- } else if (typeof value === 'object' && value !== null) {
633
- // 处理JSON类型
634
- try {
635
- return `"${JSON.stringify(value).replace(/"/g, '""')}"`;
636
- } catch {
637
- return `"${String(value).replace(/"/g, '""')}"`;
638
- }
639
- } else {
640
- return String(value);
641
- }
642
- });
643
-
644
- batchCsv += values.join(',') + '\n';
645
- });
646
-
647
- // 追加写入文件
648
- fs.appendFileSync(exportFile, batchCsv, 'utf8');
649
-
650
- // 增加偏移量
651
- offset += batchSize;
652
-
653
- // 打印进度信息
654
- console.log(`PostgreSQL导出表数据到CSV进度: ${tableName} - 已处理 ${offset} 行`);
655
- }
656
-
657
- return exportFile;
658
- } catch (error) {
659
- console.error('PostgreSQL导出表数据到CSV失败:', error);
660
- throw new Error(`导出表数据到CSV失败: ${error.message}`);
661
- }
662
- }
663
-
664
- /**
665
- * 导出表数据到 JSON 文件
666
- */
667
- async exportTableDataToJSON(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
668
- try {
669
- // 创建导出目录
670
- const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
671
- if (!fs.existsSync(exportPath)) {
672
- fs.mkdirSync(exportPath, { recursive: true });
673
- }
674
-
675
- // 生成文件名
676
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
677
- const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.json`);
678
-
679
- // 写入 JSON 头部
680
- fs.writeFileSync(exportFile, '[\n', 'utf8');
681
-
682
- // 分批处理数据,避免一次性加载大量数据到内存
683
- const batchSize = options?.batchSize || 10000; // 每批处理10000行
684
- let offset = 0;
685
- let hasMoreData = true;
686
- let isFirstBatch = true;
687
-
688
- while (hasMoreData) {
689
- // 分批查询数据
690
- const query = `SELECT * FROM ${this.quoteIdentifier(tableName)} LIMIT ${batchSize} OFFSET ${offset}`;
691
- const data = await dataSource.query(query);
692
-
693
- if (data.length === 0) {
694
- hasMoreData = false;
695
- break;
696
- }
697
-
698
- // 生成当前批次的 JSON 数据
699
- let batchJson = '';
700
- data.forEach((row: any, index: number) => {
701
- if (!isFirstBatch || index > 0) {
702
- batchJson += ',\n';
703
- }
704
- batchJson += JSON.stringify(row);
705
- });
706
-
707
- // 追加写入文件
708
- fs.appendFileSync(exportFile, batchJson, 'utf8');
709
-
710
- // 增加偏移量
711
- offset += batchSize;
712
- isFirstBatch = false;
713
-
714
- // 打印进度信息
715
- console.log(`PostgreSQL导出表数据到JSON进度: ${tableName} - 已处理 ${offset} 行`);
716
- }
717
-
718
- // 写入 JSON 尾部
719
- fs.appendFileSync(exportFile, '\n]', 'utf8');
720
-
721
- return exportFile;
722
- } catch (error) {
723
- console.error('PostgreSQL导出表数据到JSON失败:', error);
724
- throw new Error(`导出表数据到JSON失败: ${error.message}`);
725
- }
726
- }
727
-
728
- /**
729
- * 导出表数据到 Excel 文件
730
- */
731
- async exportTableDataToExcel(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
732
- try {
733
- // 由于 Excel 文件格式复杂,这里我们先导出为 CSV,然后可以考虑使用库来转换
734
- // 或者直接调用其他服务来处理 Excel 导出
735
- return this.exportTableDataToCSV(dataSource, databaseName, tableName, options);
736
- } catch (error) {
737
- console.error('PostgreSQL导出表数据到Excel失败:', error);
738
- throw new Error(`导出表数据到Excel失败: ${error.message}`);
739
- }
740
- }
741
-
742
- /**
743
- * 修改表结构
744
- */
745
- async alterTable(dataSource: DataSource, databaseName: string, tableDiff: any): Promise<any> {
746
- try {
747
- const tableName = tableDiff.tableName;
748
- const sqlStatements: string[] = [];
749
-
750
- // 修改表注释
751
- if (tableDiff.tableCommentChanged) {
752
- sqlStatements.push(`COMMENT ON TABLE "${tableName}" IS '${tableDiff.tableComment}';`);
753
- }
754
-
755
- // 添加新列
756
- tableDiff.addedColumns.forEach((column: any) => {
757
- // 检查type是否已经包含长度信息(括号)
758
- const typeHasLength = /\(\d+\)/.test(column.type);
759
-
760
- let columnSQL = `ALTER TABLE "${tableName}" ADD COLUMN "${column.name}" ${column.type}`;
761
-
762
- // 处理长度和精度(仅当type中没有指定长度时才添加)
763
- if (!typeHasLength) {
764
- if (column.length) {
765
- columnSQL += `(${column.length})`;
766
- } else if (column.precision) {
767
- if (column.scale) {
768
- columnSQL += `(${column.precision},${column.scale})`;
769
- } else {
770
- columnSQL += `(${column.precision})`;
771
- }
772
- }
773
- }
774
-
775
- // 处理NULL约束
776
- if (!column.nullable) {
777
- columnSQL += ' NOT NULL';
778
- }
779
-
780
- // 处理默认值
781
- if (column.defaultValue) {
782
- const upperDefault = column.defaultValue.toString().toUpperCase();
783
- if (['CURRENT_TIMESTAMP', 'NOW()', 'CURRENT_DATE', 'CURRENT_TIME'].includes(upperDefault)) {
784
- columnSQL += ` DEFAULT ${upperDefault}`;
785
- } else {
786
- columnSQL += ` DEFAULT '${column.defaultValue}'`;
787
- }
788
- }
789
-
790
- // 处理自增(PostgreSQL使用SERIAL或GENERATED AS IDENTITY)
791
- if (column.isAutoIncrement) {
792
- if (column.type.toLowerCase().includes('serial') || column.type.toLowerCase().includes('bigserial')) {
793
- // 类型已经包含自增
794
- } else {
795
- columnSQL += ' GENERATED ALWAYS AS IDENTITY';
796
- }
797
- }
798
-
799
- sqlStatements.push(columnSQL + ';');
800
-
801
- // 添加列注释
802
- if (column.comment) {
803
- sqlStatements.push(`COMMENT ON COLUMN "${tableName}"."${column.name}" IS '${column.comment}';`);
804
- }
805
- });
806
-
807
- // 修改列
808
- tableDiff.modifiedColumns.forEach((modification: any) => {
809
- const { oldColumn, newColumn } = modification;
810
-
811
- // 检查type是否已经包含长度信息(括号)
812
- const typeHasLength = /\(\d+\)/.test(newColumn.type);
813
-
814
- let columnSQL = `ALTER TABLE "${tableName}" ALTER COLUMN "${newColumn.name}" SET DATA TYPE ${newColumn.type}`;
815
-
816
- // 处理长度和精度(仅当type中没有指定长度时才添加)
817
- if (!typeHasLength) {
818
- if (newColumn.length) {
819
- columnSQL += `(${newColumn.length})`;
820
- } else if (newColumn.precision) {
821
- if (newColumn.scale) {
822
- columnSQL += `(${newColumn.precision},${newColumn.scale})`;
823
- } else {
824
- columnSQL += `(${newColumn.precision})`;
825
- }
826
- }
827
- }
828
-
829
- sqlStatements.push(columnSQL + ';');
830
-
831
- // 修改NULL约束
832
- if (!newColumn.nullable) {
833
- sqlStatements.push(`ALTER TABLE "${tableName}" ALTER COLUMN "${newColumn.name}" SET NOT NULL;`);
834
- } else {
835
- sqlStatements.push(`ALTER TABLE "${tableName}" ALTER COLUMN "${newColumn.name}" DROP NOT NULL;`);
836
- }
837
-
838
- // 修改默认值
839
- if (newColumn.defaultValue) {
840
- const upperDefault = newColumn.defaultValue.toString().toUpperCase();
841
- if (['CURRENT_TIMESTAMP', 'NOW()', 'CURRENT_DATE', 'CURRENT_TIME'].includes(upperDefault)) {
842
- sqlStatements.push(`ALTER TABLE "${tableName}" ALTER COLUMN "${newColumn.name}" SET DEFAULT ${upperDefault};`);
843
- } else {
844
- sqlStatements.push(`ALTER TABLE "${tableName}" ALTER COLUMN "${newColumn.name}" SET DEFAULT '${newColumn.defaultValue}';`);
845
- }
846
- } else {
847
- sqlStatements.push(`ALTER TABLE "${tableName}" ALTER COLUMN "${newColumn.name}" DROP DEFAULT;`);
848
- }
849
-
850
- // 修改列注释
851
- if (newColumn.comment) {
852
- sqlStatements.push(`COMMENT ON COLUMN "${tableName}"."${newColumn.name}" IS '${newColumn.comment}';`);
853
- }
854
- });
855
-
856
- // 删除列
857
- tableDiff.deletedColumns.forEach((column: any) => {
858
- sqlStatements.push(`ALTER TABLE "${tableName}" DROP COLUMN "${column.name}";`);
859
- });
860
-
861
- // 执行SQL语句
862
- if (sqlStatements.length > 0) {
863
- await this.executeBatchQuery(dataSource, sqlStatements, { useTransaction: true });
864
- }
865
-
866
- return { ret: 0, message: '表结构修改成功' };
867
- } catch (error) {
868
- console.error('PostgreSQL修改表结构失败:', error);
869
- return { ret: 1, message: `修改表结构失败: ${error instanceof Error ? error.message : String(error)}` };
870
- }
871
- }
872
-
873
- /**
874
- * 批量插入数据
875
- */
876
- async bulkInsert(dataSource: DataSource, databaseName: string, tableName: string, data: any[]): Promise<void> {
877
- if (data.length === 0) return;
878
-
879
- const columns = Object.keys(data[0]);
880
- const placeholders = data.map((_, index) =>
881
- `(${columns.map((_, colIndex) => `$${index * columns.length + colIndex + 1}`).join(', ')})`
882
- ).join(', ');
883
-
884
- const values = data.flatMap(row =>
885
- columns.map(column => row[column])
886
- );
887
-
888
- const sql = `INSERT INTO "${tableName}" (${columns.map(col => `"${col}"`).join(', ')}) VALUES ${placeholders}`;
889
-
890
- await dataSource.query(sql, values);
891
- }
892
-
893
- /**
894
- * 插入单条数据
895
- */
896
- async insertData(dataSource: DataSource, databaseName: string, tableName: string, data: any): Promise<void> {
897
- const columns = Object.keys(data);
898
- const placeholders = columns.map((_, index) => `$${index + 1}`).join(', ');
899
- const values = columns.map(column => data[column]);
900
-
901
- const sql = `INSERT INTO "${tableName}" (${columns.map(col => `"${col}"`).join(', ')}) VALUES (${placeholders})`;
902
-
903
- await dataSource.query(sql, values);
904
- }
905
-
906
- /**
907
- * 删除表
908
- */
909
- async dropTable(dataSource: DataSource, databaseName: string, tableName: string): Promise<void> {
910
- const sql = `DROP TABLE IF EXISTS "${tableName}"`;
911
- await dataSource.query(sql);
912
- }
913
-
914
- /**
915
- * 创建表
916
- */
917
- async createTable(dataSource: DataSource, databaseName: string, table: any): Promise<void> {
918
- const { name, columns, comment } = table;
919
-
920
- let sql = `CREATE TABLE "${name}" (\n`;
921
- const columnDefs: string[] = [];
922
-
923
- columns.forEach((column: any) => {
924
- let columnDef = ` "${column.name}" ${column.type}`;
925
-
926
- if (!column.nullable) {
927
- columnDef += ' NOT NULL';
928
- }
929
-
930
- if (column.defaultValue) {
931
- const upperDefault = column.defaultValue.toString().toUpperCase();
932
- if (['CURRENT_TIMESTAMP', 'NOW()', 'CURRENT_DATE', 'CURRENT_TIME'].includes(upperDefault)) {
933
- columnDef += ` DEFAULT ${upperDefault}`;
934
- } else {
935
- columnDef += ` DEFAULT '${column.defaultValue}'`;
936
- }
937
- }
938
-
939
- if (column.isAutoIncrement) {
940
- columnDef += ' SERIAL';
941
- }
942
-
943
- if (column.comment) {
944
- columnDef += ` COMMENT '${column.comment}'`;
945
- }
946
-
947
- columnDefs.push(columnDef);
948
- });
949
-
950
- sql += columnDefs.join(',\n');
951
- sql += '\n)';
952
-
953
- if (comment) {
954
- sql += ` COMMENT '${comment}'`;
955
- }
956
-
957
- sql += ';';
958
-
959
- await dataSource.query(sql);
960
- }
961
- }