fdb2 1.0.12 → 1.0.14

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 +19 -9
  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 -113
  101. package/dist/server/service/database/sqlite.service.d.ts.map +0 -1
  102. package/dist/server/service/database/sqlite.service.js +0 -724
  103. package/dist/server/service/database/sqlite.service.js.map +0 -1
  104. package/dist/server/service/database/sqlite.service.ts +0 -788
  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 -142
  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 -559
  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 -788
  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,871 +0,0 @@
1
- import { DataSource } from 'typeorm';
2
- import { BaseDatabaseService } from './base.service';
3
- import {
4
- DatabaseEntity,
5
- TableEntity,
6
- ColumnEntity,
7
- IndexEntity,
8
- ForeignKeyEntity
9
- } from '../../model/database.entity';
10
- import * as fs from 'fs';
11
- import * as path from 'path';
12
-
13
- /**
14
- * CockroachDB数据库服务实现
15
- * CockroachDB 是一个兼容 PostgreSQL 的分布式 SQL 数据库
16
- */
17
- export class CockroachDBService extends BaseDatabaseService {
18
-
19
- getDatabaseType() {
20
- return 'cockroachdb';
21
- }
22
-
23
- /**
24
- * 获取CockroachDB数据库列表
25
- */
26
- async getDatabases(dataSource: DataSource): Promise<string[]> {
27
- const result = await dataSource.query(`
28
- SELECT
29
- database_name as name
30
- FROM
31
- information_schema.databases
32
- WHERE
33
- database_name NOT IN ('system', 'pg_catalog', 'information_schema', 'crdb_internal')
34
- ORDER BY
35
- database_name
36
- `);
37
- return result.map((row: any) => row.name);
38
- }
39
-
40
- /**
41
- * 获取CockroachDB表列表
42
- */
43
- async getTables(dataSource: DataSource, database: string): Promise<TableEntity[]> {
44
- const result = await dataSource.query(`
45
- SELECT
46
- t.table_name as name,
47
- 'table' as type,
48
- obj_description(t.oid) as comment
49
- FROM
50
- information_schema.tables t
51
- WHERE
52
- t.table_schema = $1
53
- AND t.table_type = 'BASE TABLE'
54
- ORDER BY
55
- t.table_name
56
- `, [database]);
57
-
58
- return result.map((row: any) => ({
59
- name: row.name,
60
- type: row.type,
61
- comment: row.comment || '',
62
- rowCount: undefined,
63
- dataSize: undefined,
64
- indexSize: undefined
65
- }));
66
- }
67
-
68
- /**
69
- * 获取CockroachDB列信息
70
- */
71
- async getColumns(dataSource: DataSource, database: string, table: string): Promise<ColumnEntity[]> {
72
- const result = await dataSource.query(`
73
- SELECT
74
- column_name as name,
75
- data_type as type,
76
- is_nullable as nullable,
77
- column_default as defaultValue,
78
- CASE
79
- WHEN column_name IN (
80
- SELECT column_name
81
- FROM information_schema.key_column_usage
82
- WHERE table_schema = $1
83
- AND table_name = $2
84
- AND constraint_name LIKE '%_pkey'
85
- ) THEN true
86
- ELSE false
87
- END as isPrimary,
88
- CASE
89
- WHEN data_type LIKE '%serial%' OR data_type LIKE '%identity%'
90
- THEN true
91
- ELSE false
92
- END as isAutoIncrement
93
- FROM
94
- information_schema.columns
95
- WHERE
96
- table_schema = $1
97
- AND table_name = $2
98
- ORDER BY
99
- ordinal_position
100
- `, [database, table]);
101
-
102
- return result.map((row: any) => ({
103
- name: row.name,
104
- type: row.type,
105
- nullable: row.nullable === 'YES',
106
- defaultValue: row.defaultValue,
107
- isPrimary: row.isPrimary,
108
- isAutoIncrement: row.isAutoIncrement
109
- }));
110
- }
111
-
112
- /**
113
- * 获取CockroachDB索引信息
114
- */
115
- async getIndexes(dataSource: DataSource, database: string, table: string): Promise<IndexEntity[]> {
116
- const result = await dataSource.query(`
117
- SELECT
118
- i.relname as name,
119
- CASE
120
- WHEN i.indisunique THEN 'UNIQUE'
121
- ELSE 'INDEX'
122
- END as type,
123
- array_agg(a.attname ORDER BY k.n) as columns,
124
- i.indisunique as unique
125
- FROM
126
- pg_index i
127
- JOIN pg_class t ON t.oid = i.indrelid
128
- JOIN pg_namespace n ON n.oid = t.relnamespace
129
- JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(i.indkey)
130
- CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(n, ord) ON true
131
- WHERE
132
- n.nspname = $1
133
- AND t.relname = $2
134
- GROUP BY
135
- i.relname, i.indisunique
136
- ORDER BY
137
- i.relname
138
- `, [database, table]);
139
-
140
- return result.map((row: any) => ({
141
- name: row.name,
142
- type: row.type,
143
- columns: row.columns || [],
144
- unique: row.unique
145
- }));
146
- }
147
-
148
- /**
149
- * 获取CockroachDB外键信息
150
- */
151
- async getForeignKeys(dataSource: DataSource, database: string, table: string): Promise<ForeignKeyEntity[]> {
152
- const result = await dataSource.query(`
153
- SELECT
154
- tc.constraint_name as name,
155
- kcu.column_name as column,
156
- ccu.table_name as referencedTable,
157
- ccu.column_name as referencedColumn,
158
- rc.update_rule as onUpdate,
159
- rc.delete_rule as onDelete
160
- FROM
161
- information_schema.table_constraints tc
162
- JOIN information_schema.key_column_usage kcu
163
- ON tc.constraint_name = kcu.constraint_name
164
- AND tc.table_schema = kcu.table_schema
165
- JOIN information_schema.constraint_column_usage ccu
166
- ON ccu.constraint_name = tc.constraint_name
167
- AND ccu.table_schema = tc.table_schema
168
- JOIN information_schema.referential_constraints rc
169
- ON rc.constraint_name = tc.constraint_name
170
- WHERE
171
- tc.constraint_type = 'FOREIGN KEY'
172
- AND tc.table_schema = $1
173
- AND tc.table_name = $2
174
- ORDER BY
175
- tc.constraint_name
176
- `, [database, table]);
177
-
178
- return result.map((row: any) => ({
179
- name: row.name,
180
- column: row.column,
181
- referencedTable: row.referencedTable,
182
- referencedColumn: row.referencedColumn,
183
- onDelete: row.onDelete || 'NO ACTION',
184
- onUpdate: row.onUpdate || 'NO ACTION'
185
- }));
186
- }
187
-
188
- /**
189
- * 获取CockroachDB数据库大小
190
- */
191
- async getDatabaseSize(dataSource: DataSource, database: string): Promise<number> {
192
- try {
193
- const result = await dataSource.query(`
194
- SELECT
195
- pg_database_size(datname) as size
196
- FROM
197
- pg_database
198
- WHERE
199
- datname = $1
200
- `, [database]);
201
- return result[0]?.size || 0;
202
- } catch (error) {
203
- return 0;
204
- }
205
- }
206
-
207
- /**
208
- * 获取CockroachDB视图列表
209
- */
210
- async getViews(dataSource: DataSource, database: string): Promise<any[]> {
211
- const result = await dataSource.query(`
212
- SELECT
213
- table_name as name,
214
- view_definition as definition
215
- FROM
216
- information_schema.views
217
- WHERE
218
- table_schema = $1
219
- ORDER BY
220
- table_name
221
- `, [database]);
222
-
223
- return result.map((row: any) => ({
224
- name: row.name,
225
- comment: '',
226
- schemaName: database,
227
- definition: row.definition
228
- }));
229
- }
230
-
231
- /**
232
- * 获取CockroachDB视图定义
233
- */
234
- async getViewDefinition(dataSource: DataSource, database: string, viewName: string): Promise<string> {
235
- const result = await dataSource.query(`
236
- SELECT
237
- view_definition as definition
238
- FROM
239
- information_schema.views
240
- WHERE
241
- table_schema = $1
242
- AND table_name = $2
243
- `, [database, viewName]);
244
- return result[0]?.definition || '';
245
- }
246
-
247
- /**
248
- * 获取CockroachDB存储过程列表
249
- */
250
- async getProcedures(dataSource: DataSource, database: string): Promise<any[]> {
251
- const result = await dataSource.query(`
252
- SELECT
253
- p.proname as name,
254
- pg_get_userbyid(p.proowner).usename as owner,
255
- pg_get_functiondef(p.oid) as definition
256
- FROM
257
- pg_proc p
258
- JOIN pg_namespace n ON n.oid = p.pronamespace
259
- WHERE
260
- n.nspname = $1
261
- AND p.prokind = 'f'
262
- ORDER BY
263
- p.proname
264
- `, [database]);
265
-
266
- return result.map((row: any) => ({
267
- name: row.name,
268
- owner: row.owner,
269
- definition: row.definition
270
- }));
271
- }
272
-
273
- /**
274
- * 获取CockroachDB存储过程定义
275
- */
276
- async getProcedureDefinition(dataSource: DataSource, database: string, procedureName: string): Promise<string> {
277
- const result = await dataSource.query(`
278
- SELECT
279
- pg_get_functiondef(p.oid) as definition
280
- FROM
281
- pg_proc p
282
- JOIN pg_namespace n ON n.oid = p.pronamespace
283
- WHERE
284
- n.nspname = $1
285
- AND p.proname = $2
286
- `, [database, procedureName]);
287
- return result[0]?.definition || '';
288
- }
289
-
290
- /**
291
- * 创建CockroachDB数据库
292
- */
293
- async createDatabase(dataSource: DataSource, databaseName: string, options?: any): Promise<void> {
294
- await dataSource.query(`CREATE DATABASE ${this.quoteIdentifier(databaseName)}`);
295
- }
296
-
297
- /**
298
- * 删除CockroachDB数据库
299
- */
300
- async dropDatabase(dataSource: DataSource, databaseName: string): Promise<void> {
301
- await dataSource.query(`DROP DATABASE IF EXISTS ${this.quoteIdentifier(databaseName)}`);
302
- }
303
-
304
- /**
305
- * 导出数据库架构
306
- */
307
- async exportSchema(dataSource: DataSource, databaseName: string): Promise<string> {
308
- const tables = await this.getTables(dataSource, databaseName);
309
- let schemaSql = `-- CockroachDB数据库架构导出 - ${databaseName}\n`;
310
- schemaSql += `-- 导出时间: ${new Date().toISOString()}\n\n`;
311
-
312
- for (const table of tables) {
313
- const columns = await this.getColumns(dataSource, databaseName, table.name);
314
- const indexes = await this.getIndexes(dataSource, databaseName, table.name);
315
- const foreignKeys = await this.getForeignKeys(dataSource, databaseName, table.name);
316
-
317
- schemaSql += `-- 表结构: ${table.name}\n`;
318
- schemaSql += `CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(table.name)} (\n`;
319
-
320
- const columnDefinitions = columns.map(column => {
321
- let definition = ` ${this.quoteIdentifier(column.name)} ${column.type}`;
322
- if (!column.nullable)
323
- definition += ' NOT NULL';
324
- if (column.defaultValue !== undefined) {
325
- const upperDefault = column.defaultValue.toString().toUpperCase();
326
- if (upperDefault === 'CURRENT_TIMESTAMP' || upperDefault === 'NOW()' || upperDefault === 'CURRENT_DATE') {
327
- definition += ` DEFAULT ${upperDefault}`;
328
- } else {
329
- definition += ` DEFAULT ${column.defaultValue === null ? 'NULL' : `'${column.defaultValue}'`}`;
330
- }
331
- }
332
- if (column.isPrimary)
333
- definition += ' PRIMARY KEY';
334
- return definition;
335
- });
336
-
337
- schemaSql += columnDefinitions.join(',\n');
338
- schemaSql += '\n);\n\n';
339
-
340
- for (const index of indexes) {
341
- if (index.type === 'PRIMARY' || index.name.toUpperCase() === 'PRIMARY')
342
- continue;
343
- schemaSql += `CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX IF NOT EXISTS ${this.quoteIdentifier(index.name)} ON ${this.quoteIdentifier(table.name)} (${index.columns.map(col => this.quoteIdentifier(col)).join(', ')});\n`;
344
- }
345
-
346
- if (indexes.length > 0)
347
- schemaSql += '\n';
348
-
349
- for (const foreignKey of foreignKeys) {
350
- 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`;
351
- }
352
-
353
- if (foreignKeys.length > 0)
354
- schemaSql += '\n';
355
- }
356
-
357
- return schemaSql;
358
- }
359
-
360
- /**
361
- * 查看CockroachDB日志
362
- */
363
- async viewLogs(dataSource: DataSource, database?: string, limit: number = 100): Promise<any[]> {
364
- try {
365
- const result = await dataSource.query(`
366
- SELECT
367
- log_time,
368
- user_name,
369
- database_name,
370
- error_severity,
371
- message
372
- FROM
373
- crdb_internal.statement_statistics
374
- ORDER BY
375
- log_time DESC
376
- LIMIT $1
377
- `, [limit]);
378
- return result;
379
- } catch (error) {
380
- return [{ message: 'CockroachDB日志功能有限,请使用 SHOW CLUSTER SETTINGS 查看配置' }];
381
- }
382
- }
383
-
384
- /**
385
- * 备份CockroachDB数据库
386
- */
387
- async backupDatabase(dataSource: DataSource, databaseName: string, options?: any): Promise<string> {
388
- try {
389
- const backupPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'backups');
390
- if (!fs.existsSync(backupPath)) {
391
- fs.mkdirSync(backupPath, { recursive: true });
392
- }
393
-
394
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
395
- const backupFile = path.join(backupPath, `${databaseName}_${timestamp}.sql`);
396
-
397
- const schema = await this.exportSchema(dataSource, databaseName);
398
- fs.writeFileSync(backupFile, schema, 'utf8');
399
-
400
- return `备份成功:${backupFile}`;
401
- } catch (error) {
402
- console.error('CockroachDB备份失败:', error);
403
- throw new Error(`备份失败: ${error.message}`);
404
- }
405
- }
406
-
407
- /**
408
- * 恢复CockroachDB数据库
409
- */
410
- async restoreDatabase(dataSource: DataSource, databaseName: string, filePath: string, options?: any): Promise<void> {
411
- try {
412
- const sqlContent = fs.readFileSync(filePath, 'utf8');
413
- await this.executeSqlFile(dataSource, filePath);
414
- } catch (error) {
415
- console.error('CockroachDB恢复失败:', error);
416
- throw new Error(`恢复失败: ${error.message}`);
417
- }
418
- }
419
-
420
- /**
421
- * 导出表数据到 SQL 文件
422
- */
423
- async exportTableDataToSQL(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
424
- try {
425
- const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
426
- if (!fs.existsSync(exportPath)) {
427
- fs.mkdirSync(exportPath, { recursive: true });
428
- }
429
-
430
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
431
- const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.sql`);
432
-
433
- const columns = await this.getColumns(dataSource, databaseName, tableName);
434
- const columnNames = columns.map(column => column.name);
435
-
436
- const header = `-- 表数据导出 - ${tableName}\n` +
437
- `-- 导出时间: ${new Date().toISOString()}\n\n`;
438
- fs.writeFileSync(exportFile, header, 'utf8');
439
-
440
- const batchSize = options?.batchSize || 10000;
441
- let offset = 0;
442
- let hasMoreData = true;
443
-
444
- while (hasMoreData) {
445
- const query = `SELECT * FROM ${this.quoteIdentifier(tableName)} LIMIT ${batchSize} OFFSET ${offset}`;
446
- const data = await dataSource.query(query);
447
-
448
- if (data.length === 0) {
449
- hasMoreData = false;
450
- break;
451
- }
452
-
453
- let batchSql = '';
454
- data.forEach((row) => {
455
- const values = columnNames.map(column => {
456
- const value = row[column];
457
- if (value === null || value === undefined) {
458
- return 'NULL';
459
- } else if (typeof value === 'string') {
460
- return `'${value.replace(/'/g, "''")}'`;
461
- } else if (typeof value === 'boolean') {
462
- return value ? 'true' : 'false';
463
- } else if (value instanceof Date) {
464
- return `'${value.toISOString()}'`;
465
- } else if (typeof value === 'object') {
466
- try {
467
- const stringValue = JSON.stringify(value);
468
- return `'${stringValue.replace(/'/g, "''")}'`;
469
- } catch {
470
- return `'${String(value).replace(/'/g, "''")}'`;
471
- }
472
- } else {
473
- return String(value);
474
- }
475
- });
476
- batchSql += `INSERT INTO ${this.quoteIdentifier(tableName)} (${columnNames.map(col => this.quoteIdentifier(col)).join(', ')}) VALUES (${values.join(', ')});\n`;
477
- });
478
-
479
- fs.appendFileSync(exportFile, batchSql, 'utf8');
480
- offset += batchSize;
481
- console.log(`CockroachDB导出表数据进度: ${tableName} - 已处理 ${offset} 行`);
482
- }
483
-
484
- return exportFile;
485
- } catch (error) {
486
- console.error('CockroachDB导出表数据失败:', error);
487
- throw new Error(`导出表数据失败: ${error.message}`);
488
- }
489
- }
490
-
491
- /**
492
- * 导出表数据到 CSV 文件
493
- */
494
- async exportTableDataToCSV(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
495
- try {
496
- const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
497
- if (!fs.existsSync(exportPath)) {
498
- fs.mkdirSync(exportPath, { recursive: true });
499
- }
500
-
501
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
502
- const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.csv`);
503
-
504
- const columns = await this.getColumns(dataSource, databaseName, tableName);
505
- const columnNames = columns.map(column => column.name);
506
-
507
- const bom = Buffer.from([0xEF, 0xBB, 0xBF]);
508
- fs.writeFileSync(exportFile, bom);
509
- fs.appendFileSync(exportFile, columnNames.map(name => `"${name}"`).join(',') + '\n', 'utf8');
510
-
511
- const batchSize = options?.batchSize || 10000;
512
- let offset = 0;
513
- let hasMoreData = true;
514
-
515
- while (hasMoreData) {
516
- const query = `SELECT * FROM ${this.quoteIdentifier(tableName)} LIMIT ${batchSize} OFFSET ${offset}`;
517
- const data = await dataSource.query(query);
518
-
519
- if (data.length === 0) {
520
- hasMoreData = false;
521
- break;
522
- }
523
-
524
- let batchCsv = '';
525
- data.forEach((row) => {
526
- const values = columnNames.map(column => {
527
- const value = row[column];
528
- if (value === null || value === undefined) {
529
- return '';
530
- } else if (typeof value === 'string') {
531
- return `"${value.replace(/"/g, '""')}"`;
532
- } else if (value instanceof Date) {
533
- return `"${value.toISOString()}"`;
534
- } else if (typeof value === 'object' && value !== null) {
535
- try {
536
- return `"${JSON.stringify(value).replace(/"/g, '""')}"`;
537
- } catch {
538
- return `"${String(value).replace(/"/g, '""')}"`;
539
- }
540
- } else {
541
- return String(value);
542
- }
543
- });
544
- batchCsv += values.join(',') + '\n';
545
- });
546
-
547
- fs.appendFileSync(exportFile, batchCsv, 'utf8');
548
- offset += batchSize;
549
- console.log(`CockroachDB导出表数据到CSV进度: ${tableName} - 已处理 ${offset} 行`);
550
- }
551
-
552
- return exportFile;
553
- } catch (error) {
554
- console.error('CockroachDB导出表数据到CSV失败:', error);
555
- throw new Error(`导出表数据到CSV失败: ${error.message}`);
556
- }
557
- }
558
-
559
- /**
560
- * 导出表数据到 JSON 文件
561
- */
562
- async exportTableDataToJSON(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
563
- try {
564
- const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
565
- if (!fs.existsSync(exportPath)) {
566
- fs.mkdirSync(exportPath, { recursive: true });
567
- }
568
-
569
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
570
- const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.json`);
571
-
572
- const batchSize = options?.batchSize || 10000;
573
- let offset = 0;
574
- let hasMoreData = true;
575
- let allData: any[] = [];
576
-
577
- while (hasMoreData) {
578
- const query = `SELECT * FROM ${this.quoteIdentifier(tableName)} LIMIT ${batchSize} OFFSET ${offset}`;
579
- const data = await dataSource.query(query);
580
-
581
- if (data.length === 0) {
582
- hasMoreData = false;
583
- break;
584
- }
585
-
586
- allData = allData.concat(data);
587
- offset += batchSize;
588
- console.log(`CockroachDB导出表数据到JSON进度: ${tableName} - 已处理 ${offset} 行`);
589
- }
590
-
591
- fs.writeFileSync(exportFile, JSON.stringify(allData, null, 2), 'utf8');
592
- return exportFile;
593
- } catch (error) {
594
- console.error('CockroachDB导出表数据到JSON失败:', error);
595
- throw new Error(`导出表数据到JSON失败: ${error.message}`);
596
- }
597
- }
598
-
599
- /**
600
- * 导出表数据到 Excel 文件
601
- */
602
- async exportTableDataToExcel(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
603
- try {
604
- const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
605
- if (!fs.existsSync(exportPath)) {
606
- fs.mkdirSync(exportPath, { recursive: true });
607
- }
608
-
609
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
610
- const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.xlsx`);
611
-
612
- const columns = await this.getColumns(dataSource, databaseName, tableName);
613
- const columnNames = columns.map(column => column.name);
614
-
615
- const batchSize = options?.batchSize || 10000;
616
- let offset = 0;
617
- let hasMoreData = true;
618
- let allData: any[] = [];
619
-
620
- while (hasMoreData) {
621
- const query = `SELECT * FROM ${this.quoteIdentifier(tableName)} LIMIT ${batchSize} OFFSET ${offset}`;
622
- const data = await dataSource.query(query);
623
-
624
- if (data.length === 0) {
625
- hasMoreData = false;
626
- break;
627
- }
628
-
629
- allData = allData.concat(data);
630
- offset += batchSize;
631
- console.log(`CockroachDB导出表数据到Excel进度: ${tableName} - 已处理 ${offset} 行`);
632
- }
633
-
634
- const ExcelJS = require('exceljs');
635
- const workbook = new ExcelJS.Workbook();
636
- const worksheet = workbook.addWorksheet(tableName);
637
-
638
- worksheet.columns = columnNames.map(name => ({
639
- header: name,
640
- key: name
641
- }));
642
-
643
- worksheet.addRows(allData);
644
-
645
- await workbook.xlsx.writeFile(exportFile);
646
- return exportFile;
647
- } catch (error) {
648
- console.error('CockroachDB导出表数据到Excel失败:', error);
649
- throw new Error(`导出表数据到Excel失败: ${error.message}`);
650
- }
651
- }
652
-
653
- /**
654
- * CockroachDB使用双引号作为标识符
655
- */
656
- public quoteIdentifier(identifier: string): string {
657
- return `"${identifier}"`;
658
- }
659
-
660
- /**
661
- * 修改表结构
662
- * CockroachDB与PostgreSQL兼容,使用类似的语法
663
- */
664
- async alterTable(dataSource: DataSource, databaseName: string, tableDiff: any): Promise<any> {
665
- try {
666
- const tableName = tableDiff.tableName;
667
- const sqlStatements: string[] = [];
668
-
669
- // 修改表注释
670
- if (tableDiff.tableCommentChanged) {
671
- sqlStatements.push(`COMMENT ON TABLE "${tableName}" IS '${tableDiff.tableComment}';`);
672
- }
673
-
674
- // 添加新列
675
- tableDiff.addedColumns.forEach((column: any) => {
676
- // 检查type是否已经包含长度信息(括号)
677
- const typeHasLength = /\(\d+\)/.test(column.type);
678
-
679
- let columnSQL = `ALTER TABLE "${tableName}" ADD COLUMN "${column.name}" ${column.type}`;
680
-
681
- // 处理长度和精度(仅当type中没有指定长度时才添加)
682
- if (!typeHasLength) {
683
- if (column.length) {
684
- columnSQL += `(${column.length})`;
685
- } else if (column.precision) {
686
- if (column.scale) {
687
- columnSQL += `(${column.precision},${column.scale})`;
688
- } else {
689
- columnSQL += `(${column.precision})`;
690
- }
691
- }
692
- }
693
-
694
- // 处理NULL约束
695
- if (!column.nullable) {
696
- columnSQL += ' NOT NULL';
697
- }
698
-
699
- // 处理默认值
700
- if (column.defaultValue) {
701
- const upperDefault = column.defaultValue.toString().toUpperCase();
702
- if (['CURRENT_TIMESTAMP', 'NOW()', 'CURRENT_DATE', 'CURRENT_TIME'].includes(upperDefault)) {
703
- columnSQL += ` DEFAULT ${upperDefault}`;
704
- } else {
705
- columnSQL += ` DEFAULT '${column.defaultValue}'`;
706
- }
707
- }
708
-
709
- sqlStatements.push(columnSQL + ';');
710
-
711
- // 添加列注释
712
- if (column.comment) {
713
- sqlStatements.push(`COMMENT ON COLUMN "${tableName}"."${column.name}" IS '${column.comment}';`);
714
- }
715
- });
716
-
717
- // 修改列
718
- tableDiff.modifiedColumns.forEach((modification: any) => {
719
- const { oldColumn, newColumn } = modification;
720
-
721
- // 检查type是否已经包含长度信息(括号)
722
- const typeHasLength = /\(\d+\)/.test(newColumn.type);
723
-
724
- let columnSQL = `ALTER TABLE "${tableName}" ALTER COLUMN "${newColumn.name}" SET DATA TYPE ${newColumn.type}`;
725
-
726
- // 处理长度和精度(仅当type中没有指定长度时才添加)
727
- if (!typeHasLength) {
728
- if (newColumn.length) {
729
- columnSQL += `(${newColumn.length})`;
730
- } else if (newColumn.precision) {
731
- if (newColumn.scale) {
732
- columnSQL += `(${newColumn.precision},${newColumn.scale})`;
733
- } else {
734
- columnSQL += `(${newColumn.precision})`;
735
- }
736
- }
737
- }
738
-
739
- sqlStatements.push(columnSQL + ';');
740
-
741
- // 修改NULL约束
742
- if (!newColumn.nullable) {
743
- sqlStatements.push(`ALTER TABLE "${tableName}" ALTER COLUMN "${newColumn.name}" SET NOT NULL;`);
744
- } else {
745
- sqlStatements.push(`ALTER TABLE "${tableName}" ALTER COLUMN "${newColumn.name}" DROP NOT NULL;`);
746
- }
747
-
748
- // 修改默认值
749
- if (newColumn.defaultValue) {
750
- const upperDefault = newColumn.defaultValue.toString().toUpperCase();
751
- if (['CURRENT_TIMESTAMP', 'NOW()', 'CURRENT_DATE', 'CURRENT_TIME'].includes(upperDefault)) {
752
- sqlStatements.push(`ALTER TABLE "${tableName}" ALTER COLUMN "${newColumn.name}" SET DEFAULT ${upperDefault};`);
753
- } else {
754
- sqlStatements.push(`ALTER TABLE "${tableName}" ALTER COLUMN "${newColumn.name}" SET DEFAULT '${newColumn.defaultValue}';`);
755
- }
756
- } else {
757
- sqlStatements.push(`ALTER TABLE "${tableName}" ALTER COLUMN "${newColumn.name}" DROP DEFAULT;`);
758
- }
759
-
760
- // 修改列注释
761
- if (newColumn.comment) {
762
- sqlStatements.push(`COMMENT ON COLUMN "${tableName}"."${newColumn.name}" IS '${newColumn.comment}';`);
763
- }
764
- });
765
-
766
- // 删除列
767
- tableDiff.deletedColumns.forEach((column: any) => {
768
- sqlStatements.push(`ALTER TABLE "${tableName}" DROP COLUMN "${column.name}";`);
769
- });
770
-
771
- // 执行SQL语句
772
- if (sqlStatements.length > 0) {
773
- await this.executeBatchQuery(dataSource, sqlStatements, { useTransaction: true });
774
- }
775
-
776
- return { ret: 0, message: '表结构修改成功' };
777
- } catch (error) {
778
- console.error('CockroachDB修改表结构失败:', error);
779
- return { ret: 1, message: `修改表结构失败: ${error instanceof Error ? error.message : String(error)}` };
780
- }
781
- }
782
-
783
- /**
784
- * 批量插入数据
785
- */
786
- async bulkInsert(dataSource: DataSource, databaseName: string, tableName: string, data: any[]): Promise<void> {
787
- if (data.length === 0) return;
788
-
789
- const columns = Object.keys(data[0]);
790
- const placeholders = data.map((_, index) =>
791
- `(${columns.map((_, colIndex) => `$${index * columns.length + colIndex + 1}`).join(', ')})`
792
- ).join(', ');
793
-
794
- const values = data.flatMap(row =>
795
- columns.map(column => row[column])
796
- );
797
-
798
- const sql = `INSERT INTO "${tableName}" (${columns.map(col => `"${col}"`).join(', ')}) VALUES ${placeholders}`;
799
-
800
- await dataSource.query(sql, values);
801
- }
802
-
803
- /**
804
- * 插入单条数据
805
- */
806
- async insertData(dataSource: DataSource, databaseName: string, tableName: string, data: any): Promise<void> {
807
- const columns = Object.keys(data);
808
- const placeholders = columns.map((_, index) => `$${index + 1}`).join(', ');
809
- const values = columns.map(column => data[column]);
810
-
811
- const sql = `INSERT INTO "${tableName}" (${columns.map(col => `"${col}"`).join(', ')}) VALUES (${placeholders})`;
812
-
813
- await dataSource.query(sql, values);
814
- }
815
-
816
- /**
817
- * 删除表
818
- */
819
- async dropTable(dataSource: DataSource, databaseName: string, tableName: string): Promise<void> {
820
- const sql = `DROP TABLE IF EXISTS "${tableName}"`;
821
- await dataSource.query(sql);
822
- }
823
-
824
- /**
825
- * 创建表
826
- */
827
- async createTable(dataSource: DataSource, databaseName: string, table: any): Promise<void> {
828
- const { name, columns, comment } = table;
829
-
830
- let sql = `CREATE TABLE "${name}" (\n`;
831
- const columnDefs: string[] = [];
832
-
833
- columns.forEach((column: any) => {
834
- let columnDef = ` "${column.name}" ${column.type}`;
835
-
836
- if (!column.nullable) {
837
- columnDef += ' NOT NULL';
838
- }
839
-
840
- if (column.defaultValue) {
841
- const upperDefault = column.defaultValue.toString().toUpperCase();
842
- if (['CURRENT_TIMESTAMP', 'NOW()', 'CURRENT_DATE', 'CURRENT_TIME'].includes(upperDefault)) {
843
- columnDef += ` DEFAULT ${upperDefault}`;
844
- } else {
845
- columnDef += ` DEFAULT '${column.defaultValue}'`;
846
- }
847
- }
848
-
849
- if (column.isAutoIncrement) {
850
- columnDef += ' SERIAL';
851
- }
852
-
853
- if (column.comment) {
854
- columnDef += ` COMMENT '${column.comment}'`;
855
- }
856
-
857
- columnDefs.push(columnDef);
858
- });
859
-
860
- sql += columnDefs.join(',\n');
861
- sql += '\n)';
862
-
863
- if (comment) {
864
- sql += ` COMMENT '${comment}'`;
865
- }
866
-
867
- sql += ';';
868
-
869
- await dataSource.query(sql);
870
- }
871
- }