fdb2 1.0.7 → 1.0.9

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 (234) hide show
  1. package/.dockerignore +21 -21
  2. package/.editorconfig +11 -11
  3. package/.eslintrc.cjs +14 -14
  4. package/.eslintrc.json +7 -7
  5. package/.prettierrc.js +3 -3
  6. package/.tpl.env +21 -21
  7. package/.vscodeignore +45 -45
  8. package/README.md +312 -312
  9. package/bin/build.sh +28 -28
  10. package/bin/deploy.sh +8 -8
  11. package/bin/dev.sh +10 -10
  12. package/bin/docker/dev-docker-compose.yml +43 -43
  13. package/bin/docker/dev.Dockerfile +24 -24
  14. package/bin/docker/prod-docker-compose.yml +17 -17
  15. package/bin/docker/prod.Dockerfile +29 -29
  16. package/bin/fdb2.js +220 -220
  17. package/dist/package.json +29 -29
  18. package/dist/pnpm-lock.yaml +1042 -354
  19. package/dist/public/explorer.css +1464 -1437
  20. package/dist/public/explorer.js +764 -226
  21. package/dist/public/index.css +1026 -1026
  22. package/dist/public/index.js +15 -9
  23. package/dist/public/layout.css +221 -221
  24. package/dist/public/layout.js +1 -1
  25. package/dist/public/vue.js +8 -2
  26. package/dist/scripts/preinstall.js +112 -112
  27. package/dist/server/index.d.ts.map +1 -1
  28. package/dist/server/index.js +8 -0
  29. package/dist/server/index.js.map +1 -1
  30. package/dist/server/index.ts +680 -671
  31. package/dist/server/model/connection.entity.ts +65 -65
  32. package/dist/server/model/database.entity.ts +245 -245
  33. package/dist/server/service/connection.service.d.ts +6 -1
  34. package/dist/server/service/connection.service.d.ts.map +1 -1
  35. package/dist/server/service/connection.service.js +15 -0
  36. package/dist/server/service/connection.service.js.map +1 -1
  37. package/dist/server/service/connection.service.ts +356 -341
  38. package/dist/server/service/database/base.service.d.ts +27 -0
  39. package/dist/server/service/database/base.service.d.ts.map +1 -1
  40. package/dist/server/service/database/base.service.js +17 -0
  41. package/dist/server/service/database/base.service.js.map +1 -1
  42. package/dist/server/service/database/base.service.ts +406 -367
  43. package/dist/server/service/database/cockroachdb.service.d.ts +16 -0
  44. package/dist/server/service/database/cockroachdb.service.d.ts.map +1 -1
  45. package/dist/server/service/database/cockroachdb.service.js +220 -154
  46. package/dist/server/service/database/cockroachdb.service.js.map +1 -1
  47. package/dist/server/service/database/cockroachdb.service.ts +871 -782
  48. package/dist/server/service/database/database.service.d.ts +4 -0
  49. package/dist/server/service/database/database.service.d.ts.map +1 -1
  50. package/dist/server/service/database/database.service.js +123 -0
  51. package/dist/server/service/database/database.service.js.map +1 -1
  52. package/dist/server/service/database/database.service.ts +775 -638
  53. package/dist/server/service/database/index.ts +6 -6
  54. package/dist/server/service/database/mongodb.service.d.ts +16 -0
  55. package/dist/server/service/database/mongodb.service.d.ts.map +1 -1
  56. package/dist/server/service/database/mongodb.service.js +35 -0
  57. package/dist/server/service/database/mongodb.service.js.map +1 -1
  58. package/dist/server/service/database/mongodb.service.ts +39 -1
  59. package/dist/server/service/database/mssql.service.d.ts +16 -0
  60. package/dist/server/service/database/mssql.service.d.ts.map +1 -1
  61. package/dist/server/service/database/mssql.service.js +168 -96
  62. package/dist/server/service/database/mssql.service.js.map +1 -1
  63. package/dist/server/service/database/mssql.service.ts +931 -840
  64. package/dist/server/service/database/mysql.service.d.ts +16 -0
  65. package/dist/server/service/database/mysql.service.d.ts.map +1 -1
  66. package/dist/server/service/database/mysql.service.js +189 -80
  67. package/dist/server/service/database/mysql.service.js.map +1 -1
  68. package/dist/server/service/database/mysql.service.ts +1025 -890
  69. package/dist/server/service/database/oracle.service.d.ts +16 -0
  70. package/dist/server/service/database/oracle.service.d.ts.map +1 -1
  71. package/dist/server/service/database/oracle.service.js +182 -120
  72. package/dist/server/service/database/oracle.service.js.map +1 -1
  73. package/dist/server/service/database/oracle.service.ts +1035 -959
  74. package/dist/server/service/database/postgres.service.d.ts +16 -0
  75. package/dist/server/service/database/postgres.service.d.ts.map +1 -1
  76. package/dist/server/service/database/postgres.service.js +154 -88
  77. package/dist/server/service/database/postgres.service.js.map +1 -1
  78. package/dist/server/service/database/postgres.service.ts +960 -871
  79. package/dist/server/service/database/sap.service.d.ts +16 -0
  80. package/dist/server/service/database/sap.service.d.ts.map +1 -1
  81. package/dist/server/service/database/sap.service.js +66 -0
  82. package/dist/server/service/database/sap.service.js.map +1 -1
  83. package/dist/server/service/database/sap.service.ts +89 -0
  84. package/dist/server/service/database/sqlite.service.d.ts +16 -0
  85. package/dist/server/service/database/sqlite.service.d.ts.map +1 -1
  86. package/dist/server/service/database/sqlite.service.js +77 -18
  87. package/dist/server/service/database/sqlite.service.js.map +1 -1
  88. package/dist/server/service/database/sqlite.service.ts +787 -708
  89. package/dist/server/service/session.service.ts +158 -158
  90. package/dist/view/index.html +38 -38
  91. package/env.d.ts +1 -1
  92. package/package.json +1 -1
  93. package/packages/vscode/.vscodeignore +44 -44
  94. package/packages/vscode/README.md +62 -62
  95. package/packages/vscode/out/database-services/cockroachdb.service.js +154 -154
  96. package/packages/vscode/out/database-services/mssql.service.js +96 -96
  97. package/packages/vscode/out/database-services/mysql.service.js +80 -80
  98. package/packages/vscode/out/database-services/oracle.service.js +120 -120
  99. package/packages/vscode/out/database-services/postgres.service.js +88 -88
  100. package/packages/vscode/out/database-services/sqlite.service.js +18 -18
  101. package/packages/vscode/out/provider/WebViewProvider.js +32 -32
  102. package/packages/vscode/package.json +142 -142
  103. package/packages/vscode/resources/icon.svg +5 -5
  104. package/packages/vscode/resources/webview/connection.css +41 -41
  105. package/packages/vscode/resources/webview/database.css +163 -163
  106. package/packages/vscode/resources/webview/index.html +9 -9
  107. package/packages/vscode/resources/webview/modules/header.tpl +13 -13
  108. package/packages/vscode/resources/webview/modules/initial_state.tpl +54 -54
  109. package/packages/vscode/resources/webview/query.css +104 -104
  110. package/packages/vscode/src/database-services/base.service.ts +362 -362
  111. package/packages/vscode/src/database-services/cockroachdb.service.ts +659 -659
  112. package/packages/vscode/src/database-services/connection.service.ts +340 -340
  113. package/packages/vscode/src/database-services/database.service.ts +629 -629
  114. package/packages/vscode/src/database-services/index.ts +6 -6
  115. package/packages/vscode/src/database-services/model/connection.entity.ts +65 -65
  116. package/packages/vscode/src/database-services/model/database.entity.ts +245 -245
  117. package/packages/vscode/src/database-services/mssql.service.ts +722 -722
  118. package/packages/vscode/src/database-services/mysql.service.ts +760 -760
  119. package/packages/vscode/src/database-services/oracle.service.ts +831 -831
  120. package/packages/vscode/src/database-services/postgres.service.ts +740 -740
  121. package/packages/vscode/src/database-services/sqlite.service.ts +558 -558
  122. package/packages/vscode/src/extension.ts +76 -76
  123. package/packages/vscode/src/provider/DatabaseTreeProvider.ts +167 -167
  124. package/packages/vscode/src/provider/WebViewProvider.ts +277 -277
  125. package/packages/vscode/src/service/DatabaseServiceBridge.ts +414 -414
  126. package/packages/vscode/src/typings/connection.ts +90 -90
  127. package/packages/vscode/tsconfig.json +21 -21
  128. package/public/index.html +9 -9
  129. package/public/modules/header.tpl +13 -13
  130. package/public/modules/initial_state.tpl +54 -54
  131. package/scripts/preinstall.js +112 -112
  132. package/server/index.ts +680 -671
  133. package/server/model/connection.entity.ts +65 -65
  134. package/server/model/database.entity.ts +245 -245
  135. package/server/service/connection.service.ts +356 -341
  136. package/server/service/database/base.service.ts +406 -367
  137. package/server/service/database/cockroachdb.service.ts +871 -782
  138. package/server/service/database/database.service.ts +775 -638
  139. package/server/service/database/index.ts +6 -6
  140. package/server/service/database/mongodb.service.ts +39 -1
  141. package/server/service/database/mssql.service.ts +931 -840
  142. package/server/service/database/mysql.service.ts +1025 -890
  143. package/server/service/database/oracle.service.ts +1035 -959
  144. package/server/service/database/postgres.service.ts +960 -871
  145. package/server/service/database/sap.service.ts +89 -0
  146. package/server/service/database/sqlite.service.ts +787 -708
  147. package/server/service/session.service.ts +158 -158
  148. package/server/tsconfig.json +20 -20
  149. package/server.js +149 -149
  150. package/server.pid +1 -0
  151. package/src/adapter/ajax.ts +135 -135
  152. package/src/assets/base.css +1 -1
  153. package/src/assets/database.css +949 -949
  154. package/src/assets/images/svg/illustrations/illustration-1.svg +1 -1
  155. package/src/assets/images/svg/illustrations/illustration-2.svg +2 -2
  156. package/src/assets/images/svg/illustrations/illustration-3.svg +50 -50
  157. package/src/assets/images/svg/illustrations/illustration-4.svg +1 -1
  158. package/src/assets/images/svg/illustrations/illustration-5.svg +73 -73
  159. package/src/assets/images/svg/illustrations/illustration-6.svg +89 -89
  160. package/src/assets/images/svg/illustrations/illustration-7.svg +39 -39
  161. package/src/assets/images/svg/separators/curve-2.svg +3 -3
  162. package/src/assets/images/svg/separators/curve.svg +3 -3
  163. package/src/assets/images/svg/separators/line.svg +3 -3
  164. package/src/assets/logo.svg +73 -73
  165. package/src/assets/main.css +1 -1
  166. package/src/base/config.ts +20 -20
  167. package/src/base/detect.ts +134 -134
  168. package/src/base/entity.ts +92 -92
  169. package/src/base/eventBus.ts +36 -36
  170. package/src/components/connection-editor/index.vue +588 -588
  171. package/src/components/dataGrid/index.vue +104 -104
  172. package/src/components/dataGrid/pagination.vue +105 -105
  173. package/src/components/loading/index.vue +42 -42
  174. package/src/components/modal/index.ts +180 -180
  175. package/src/components/modal/index.vue +560 -560
  176. package/src/components/toast/index.ts +43 -43
  177. package/src/components/toast/toast.vue +57 -57
  178. package/src/components/user/name.vue +103 -103
  179. package/src/components/user/selector.vue +416 -416
  180. package/src/domain/SysConfig.ts +74 -74
  181. package/src/platform/App.vue +7 -7
  182. package/src/platform/database/components/connection-detail.vue +1153 -1154
  183. package/src/platform/database/components/data-editor.vue +477 -477
  184. package/src/platform/database/components/database-detail.vue +1173 -1172
  185. package/src/platform/database/components/database-monitor.vue +1085 -1085
  186. package/src/platform/database/components/db-tools.vue +1264 -816
  187. package/src/platform/database/components/query-history.vue +1348 -1348
  188. package/src/platform/database/components/sql-executor.vue +737 -737
  189. package/src/platform/database/components/sql-query-editor.vue +1045 -1045
  190. package/src/platform/database/components/table-detail.vue +1375 -1376
  191. package/src/platform/database/components/table-editor.vue +916 -916
  192. package/src/platform/database/explorer.vue +1839 -1839
  193. package/src/platform/database/index.vue +1192 -1192
  194. package/src/platform/database/layout.vue +366 -366
  195. package/src/platform/database/router.ts +36 -36
  196. package/src/platform/database/styles/common.scss +601 -601
  197. package/src/platform/database/types/common.ts +444 -444
  198. package/src/platform/database/utils/export.ts +231 -231
  199. package/src/platform/database/utils/helpers.ts +436 -436
  200. package/src/platform/index.ts +32 -32
  201. package/src/platform/router.ts +40 -40
  202. package/src/platform/vscode/bridge.ts +121 -121
  203. package/src/platform/vscode/components/ConnectionPanel.vue +272 -272
  204. package/src/platform/vscode/components/DatabasePanel.vue +532 -532
  205. package/src/platform/vscode/components/QueryPanel.vue +371 -371
  206. package/src/platform/vscode/entry/connection.ts +13 -13
  207. package/src/platform/vscode/entry/database.ts +13 -13
  208. package/src/platform/vscode/entry/query.ts +13 -13
  209. package/src/platform/vscode/index.ts +5 -5
  210. package/src/service/base.ts +133 -127
  211. package/src/service/database.ts +505 -495
  212. package/src/service/login.ts +120 -120
  213. package/src/shims-vue.d.ts +6 -6
  214. package/src/stores/connection.ts +266 -266
  215. package/src/stores/session.ts +87 -87
  216. package/src/typings/database-types.ts +412 -412
  217. package/src/typings/database.ts +363 -363
  218. package/src/typings/global.d.ts +58 -58
  219. package/src/typings/pinia.d.ts +7 -7
  220. package/src/utils/clipboard.ts +29 -29
  221. package/src/utils/database-types.ts +242 -242
  222. package/src/utils/modal.ts +123 -123
  223. package/src/utils/request.ts +55 -55
  224. package/src/utils/sleep.ts +3 -3
  225. package/src/utils/toast.ts +73 -73
  226. package/src/utils/util.ts +171 -171
  227. package/src/utils/xlsx.ts +228 -228
  228. package/tsconfig.json +33 -33
  229. package/view/index.html +9 -9
  230. package/view/modules/header.tpl +13 -13
  231. package/view/modules/initial_state.tpl +19 -19
  232. package/vite.config.ts +424 -424
  233. package/vite.config.vscode.ts +47 -47
  234. package/server/backups/db_ai_breakout_2026-03-11T08-38-48-677Z.sql +0 -0
@@ -1,841 +1,932 @@
1
- import { DataSource } from 'typeorm';
2
- import * as fs from 'fs';
3
- import * as path from 'path';
4
- import { BaseDatabaseService } from './base.service';
5
- import {
6
- TableEntity,
7
- ColumnEntity,
8
- IndexEntity,
9
- ForeignKeyEntity
10
- } from '../../model/database.entity';
11
-
12
- /**
13
- * SQL Server数据库服务实现
14
- */
15
- export class SQLServerService extends BaseDatabaseService {
16
-
17
- getDatabaseType(): string {
18
- return 'mssql';
19
- }
20
-
21
- /**
22
- * 获取SQL Server数据库列表
23
- */
24
- async getDatabases(dataSource: DataSource): Promise<string[]> {
25
- const result = await dataSource.query(`
26
- SELECT name
27
- FROM sys.databases
28
- WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb')
29
- AND state = 0
30
- ORDER BY name
31
- `);
32
- return result.map((row: any) => row.name);
33
- }
34
-
35
- /**
36
- * 获取SQL Server表列表
37
- */
38
- async getTables(dataSource: DataSource, database: string): Promise<TableEntity[]> {
39
- const result = await dataSource.query(`
40
- SELECT
41
- t.name,
42
- 'BASE TABLE' as type,
43
- p.rows as rowCount,
44
- SUM(a.total_pages) * 8 * 1024 as dataSize
45
- FROM ${this.quoteIdentifier(database)}.sys.tables t
46
- INNER JOIN ${this.quoteIdentifier(database)}.sys.partitions p ON t.object_id = p.object_id
47
- INNER JOIN ${this.quoteIdentifier(database)}.sys.allocation_units a ON p.partition_id = a.container_id
48
- WHERE t.is_ms_shipped = 0
49
- AND p.index_id IN (0, 1)
50
- GROUP BY t.name, p.rows
51
- ORDER BY t.name
52
- `);
53
-
54
- return result.map((row: any) => ({
55
- name: row.name,
56
- type: row.type,
57
- rowCount: row.rowCount || 0,
58
- dataSize: row.dataSize || 0,
59
- indexSize: 0 // SQL Server索引大小计算较复杂,这里简化处理
60
- }));
61
- }
62
-
63
- /**
64
- * 获取SQL Server列信息
65
- */
66
- async getColumns(dataSource: DataSource, database: string, table: string): Promise<ColumnEntity[]> {
67
- // 使用兼容的SQL查询,避免使用可能不兼容的函数
68
- const result = await dataSource.query(`
69
- SELECT
70
- c.name,
71
- t.name as type,
72
- c.max_length as length,
73
- c.precision,
74
- c.scale,
75
- c.is_nullable as nullable,
76
- c.default_object_id,
77
- COLUMNPROPERTY(c.object_id, c.name, 'IsIdentity') as isIdentity
78
- FROM ${this.quoteIdentifier(database)}.sys.columns c
79
- INNER JOIN ${this.quoteIdentifier(database)}.sys.types t ON c.user_type_id = t.user_type_id
80
- WHERE c.object_id = OBJECT_ID(?)
81
- ORDER BY c.column_id
82
- `, [`${database}.${table}`]);
83
-
84
- // 获取主键信息
85
- const primaryKeys = await this.getPrimaryKeys(dataSource, database, table);
86
-
87
- return result.map((row: any) => ({
88
- name: row.name,
89
- type: row.type,
90
- nullable: row.nullable,
91
- defaultValue: row.default_object_id ? 'DEFAULT' : null,
92
- isPrimary: primaryKeys.includes(row.name),
93
- isAutoIncrement: row.isIdentity === 1,
94
- length: row.length,
95
- precision: row.precision,
96
- scale: row.scale
97
- }));
98
- }
99
-
100
- /**
101
- * 获取SQL Server索引信息
102
- */
103
- async getIndexes(dataSource: DataSource, database: string, table: string): Promise<IndexEntity[]> {
104
- const result = await dataSource.query(`
105
- SELECT
106
- i.name,
107
- i.type_desc as type,
108
- c.name as column,
109
- i.is_unique as isUnique
110
- FROM ${this.quoteIdentifier(database)}.sys.indexes i
111
- INNER JOIN ${this.quoteIdentifier(database)}.sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
112
- INNER JOIN ${this.quoteIdentifier(database)}.sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
113
- WHERE i.object_id = OBJECT_ID(?)
114
- AND i.is_primary_key = 0
115
- ORDER BY i.name, ic.key_ordinal
116
- `, [`${database}.${table}`]);
117
-
118
- // 按索引名分组
119
- const indexMap = new Map<string, IndexEntity>();
120
- result.forEach((row: any) => {
121
- if (!indexMap.has(row.name)) {
122
- indexMap.set(row.name, {
123
- name: row.name,
124
- type: row.type,
125
- columns: [],
126
- unique: row.isUnique
127
- });
128
- }
129
- indexMap.get(row.name)!.columns.push(row.column);
130
- });
131
-
132
- return Array.from(indexMap.values());
133
- }
134
-
135
- /**
136
- * 获取SQL Server外键信息
137
- */
138
- async getForeignKeys(dataSource: DataSource, database: string, table: string): Promise<ForeignKeyEntity[]> {
139
- const result = await dataSource.query(`
140
- SELECT
141
- fk.name as name,
142
- c.name as column,
143
- rt.name as referencedTable,
144
- rc.name as referencedColumn,
145
- fk.delete_action_desc as onDelete,
146
- fk.update_action_desc as onUpdate
147
- FROM ${this.quoteIdentifier(database)}.sys.foreign_keys fk
148
- INNER JOIN ${this.quoteIdentifier(database)}.sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_id
149
- INNER JOIN ${this.quoteIdentifier(database)}.sys.columns c ON fkc.parent_object_id = c.object_id AND fkc.parent_column_id = c.column_id
150
- INNER JOIN ${this.quoteIdentifier(database)}.sys.columns rc ON fkc.referenced_object_id = rc.object_id AND fkc.referenced_column_id = rc.column_id
151
- INNER JOIN ${this.quoteIdentifier(database)}.sys.tables rt ON fkc.referenced_object_id = rt.object_id
152
- WHERE fkc.parent_object_id = OBJECT_ID(?)
153
- `, [`${database}.${table}`]);
154
-
155
- return result.map((row: any) => ({
156
- name: row.name,
157
- column: row.column,
158
- referencedTable: row.referencedTable,
159
- referencedColumn: row.referencedColumn,
160
- onDelete: row.onDelete,
161
- onUpdate: row.onUpdate
162
- }));
163
- }
164
-
165
- /**
166
- * 获取SQL Server数据库大小
167
- */
168
- async getDatabaseSize(dataSource: DataSource, database: string): Promise<number> {
169
- const result = await dataSource.query(`
170
- SELECT SUM(size * 8 * 1024) as size
171
- FROM sys.master_files
172
- WHERE database_id = DB_ID(?)
173
- `, [database]);
174
- return result[0]?.size || 0;
175
- }
176
-
177
- /**
178
- * 获取主键信息
179
- */
180
- private async getPrimaryKeys(dataSource: DataSource, database: string, table: string): Promise<string[]> {
181
- const result = await dataSource.query(`
182
- SELECT c.name
183
- FROM ${this.quoteIdentifier(database)}.sys.key_constraints k
184
- INNER JOIN ${this.quoteIdentifier(database)}.sys.index_columns ic ON k.parent_object_id = ic.object_id AND k.unique_index_id = ic.index_id
185
- INNER JOIN ${this.quoteIdentifier(database)}.sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
186
- WHERE k.type = 'PK'
187
- AND k.parent_object_id = OBJECT_ID(?)
188
- ORDER BY ic.key_ordinal
189
- `, [`${database}.${table}`]);
190
- return result.map((row: any) => row.name);
191
- }
192
-
193
- /**
194
- * SQL Server的标识符引用方式
195
- */
196
- public quoteIdentifier(identifier: string): string {
197
- return `[${identifier}]`;
198
- }
199
-
200
- /**
201
- * 获取SQL Server视图列表
202
- */
203
- async getViews(dataSource: DataSource, database: string): Promise<any[]> {
204
- const result = await dataSource.query(`
205
- SELECT
206
- TABLE_NAME as name,
207
- '' as comment,
208
- TABLE_SCHEMA as schemaName
209
- FROM ${this.quoteIdentifier(database)}.INFORMATION_SCHEMA.VIEWS
210
- ORDER BY TABLE_NAME
211
- `);
212
-
213
- return result.map((row: any) => ({
214
- name: row.name,
215
- comment: row.comment || '',
216
- schemaName: row.schemaname
217
- }));
218
- }
219
-
220
- /**
221
- * 获取SQL Server视图定义
222
- */
223
- async getViewDefinition(dataSource: DataSource, database: string, viewName: string): Promise<string> {
224
- const result = await dataSource.query(`
225
- SELECT VIEW_DEFINITION as definition
226
- FROM ${this.quoteIdentifier(database)}.INFORMATION_SCHEMA.VIEWS
227
- WHERE TABLE_NAME = ?
228
- `, [viewName]);
229
-
230
- return result[0]?.definition || '';
231
- }
232
-
233
- /**
234
- * 获取SQL Server存储过程列表
235
- */
236
- async getProcedures(dataSource: DataSource, database: string): Promise<any[]> {
237
- const result = await dataSource.query(`
238
- SELECT
239
- ROUTINE_NAME as name,
240
- '' as comment,
241
- ROUTINE_TYPE as type,
242
- '' as returnType,
243
- 'SQL' as language
244
- FROM ${this.quoteIdentifier(database)}.INFORMATION_SCHEMA.ROUTINES
245
- WHERE ROUTINE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA')
246
- ORDER BY ROUTINE_NAME
247
- `);
248
-
249
- return result.map((row: any) => ({
250
- name: row.name,
251
- comment: row.comment || '',
252
- type: row.type,
253
- returnType: row.returnType || '',
254
- language: row.language || 'SQL'
255
- }));
256
- }
257
-
258
- /**
259
- * 获取SQL Server存储过程定义
260
- */
261
- async getProcedureDefinition(dataSource: DataSource, database: string, procedureName: string): Promise<string> {
262
- const result = await dataSource.query(`
263
- SELECT ROUTINE_DEFINITION as definition
264
- FROM ${this.quoteIdentifier(database)}.INFORMATION_SCHEMA.ROUTINES
265
- WHERE ROUTINE_NAME = ?
266
- `, [procedureName]);
267
-
268
- return result[0]?.definition || '';
269
- }
270
-
271
- /**
272
- * 创建SQL Server数据库
273
- */
274
- async createDatabase(dataSource: DataSource, databaseName: string, options?: any): Promise<void> {
275
- let sql = `CREATE DATABASE ${this.quoteIdentifier(databaseName)}`;
276
-
277
- if (options) {
278
- const clauses = [] as Array<string>;
279
-
280
- if (options.collation) {
281
- clauses.push(`COLLATE ${options.collation}`);
282
- }
283
-
284
- if (options.containment) {
285
- clauses.push(`CONTAINMENT = ${options.containment}`);
286
- }
287
-
288
- if (options.compatibilityLevel) {
289
- clauses.push(`COMPATIBILITY_LEVEL = ${options.compatibilityLevel}`);
290
- }
291
-
292
- // 添加数据文件配置
293
- if (options.dataFiles) {
294
- const fileClauses = options.dataFiles.map((file: any) => {
295
- let fileClause = `(NAME = '${file.name}', FILENAME = '${file.filename}'`;
296
- if (file.size) fileClause += `, SIZE = ${file.size}`;
297
- if (file.maxSize) fileClause += `, MAXSIZE = ${file.maxSize}`;
298
- if (file.growth) fileClause += `, FILEGROWTH = ${file.growth}`;
299
- fileClause += ')';
300
- return fileClause;
301
- });
302
- clauses.push(`ON ${fileClauses.join(', ')}`);
303
- }
304
-
305
- // 添加日志文件配置
306
- if (options.logFiles) {
307
- const logClauses = options.logFiles.map((log: any) => {
308
- let logClause = `(NAME = '${log.name}', FILENAME = '${log.filename}'`;
309
- if (log.size) logClause += `, SIZE = ${log.size}`;
310
- if (log.maxSize) logClause += `, MAXSIZE = ${log.maxSize}`;
311
- if (log.growth) logClause += `, FILEGROWTH = ${log.growth}`;
312
- logClause += ')';
313
- return logClause;
314
- });
315
- clauses.push(`LOG ON ${logClauses.join(', ')}`);
316
- }
317
-
318
- if (clauses.length > 0) {
319
- sql += ' ' + clauses.join(' ');
320
- }
321
- }
322
-
323
- await dataSource.query(sql);
324
- }
325
-
326
- /**
327
- * 删除SQL Server数据库
328
- */
329
- async dropDatabase(dataSource: DataSource, databaseName: string): Promise<void> {
330
- const sql = `DROP DATABASE ${this.quoteIdentifier(databaseName)}`;
331
- await dataSource.query(sql);
332
- }
333
-
334
- /**
335
- * 导出数据库架构
336
- */
337
- async exportSchema(dataSource: DataSource, databaseName: string): Promise<string> {
338
- // 获取所有表
339
- const tables = await this.getTables(dataSource, databaseName);
340
- let schemaSql = `-- 数据库架构导出 - ${databaseName}\n`;
341
- schemaSql += `-- 导出时间: ${new Date().toISOString()}\n\n`;
342
-
343
- // 为每个表生成CREATE TABLE语句
344
- for (const table of tables) {
345
- // 获取表结构
346
- const columns = await this.getColumns(dataSource, databaseName, table.name);
347
- const indexes = await this.getIndexes(dataSource, databaseName, table.name);
348
- const foreignKeys = await this.getForeignKeys(dataSource, databaseName, table.name);
349
-
350
- // 生成CREATE TABLE语句
351
- schemaSql += `-- 表结构: ${table.name}\n`;
352
- schemaSql += `CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(table.name)} (\n`;
353
-
354
- // 添加列定义
355
- const columnDefinitions = columns.map(column => {
356
- let definition = ` ${this.quoteIdentifier(column.name)} ${column.type}`;
357
- if (!column.nullable) definition += ' NOT NULL';
358
- if (column.defaultValue !== undefined) {
359
- // 特殊关键字处理
360
- const upperDefault = column.defaultValue.toString().toUpperCase();
361
- if (upperDefault === 'CURRENT_TIMESTAMP' || upperDefault === 'NOW()' || upperDefault === 'CURRENT_DATE') {
362
- definition += ` DEFAULT ${upperDefault}`;
363
- } else {
364
- definition += ` DEFAULT ${column.defaultValue === null ? 'NULL' : `'${column.defaultValue}'`}`;
365
- }
366
- }
367
- if (column.isAutoIncrement) definition += ' IDENTITY(1,1)';
368
- return definition;
369
- });
370
-
371
- // 添加主键
372
- const primaryKeyColumns = columns.filter(column => column.isPrimary);
373
- if (primaryKeyColumns.length > 0) {
374
- const primaryKeyNames = primaryKeyColumns.map(column => this.quoteIdentifier(column.name)).join(', ');
375
- columnDefinitions.push(` PRIMARY KEY (${primaryKeyNames})`);
376
- }
377
-
378
- schemaSql += columnDefinitions.join(',\n');
379
- schemaSql += '\n);\n\n';
380
-
381
- // 添加索引
382
- for (const index of indexes) {
383
- if (index.type === 'PRIMARY' || index.name.toUpperCase() === 'PRIMARY') continue; // 跳过主键索引
384
- schemaSql += `-- 索引: ${index.name} on ${table.name}\n`;
385
- schemaSql += `CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX ${this.quoteIdentifier(index.name)} ON ${this.quoteIdentifier(table.name)} (${index.columns.map(col => this.quoteIdentifier(col)).join(', ')});\n`;
386
- }
387
-
388
- if (indexes.length > 0) schemaSql += '\n';
389
-
390
- // 添加外键
391
- for (const foreignKey of foreignKeys) {
392
- schemaSql += `-- 外键: ${foreignKey.name} on ${table.name}\n`;
393
- 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`;
394
- }
395
-
396
- if (foreignKeys.length > 0) schemaSql += '\n';
397
- }
398
-
399
- return schemaSql;
400
- }
401
-
402
- /**
403
- * 查看数据库日志
404
- */
405
- async viewLogs(dataSource: DataSource, database?: string, limit: number = 100): Promise<any[]> {
406
- // SQL Server查看日志
407
- try {
408
- // 尝试查看SQL Server错误日志
409
- const logs = await dataSource.query(`EXEC xp_readerrorlog 0, 1, NULL, NULL, NULL, NULL, 'DESC'`);
410
- return logs.slice(0, limit);
411
- } catch (error) {
412
- try {
413
- // 尝试查看SQL Server事务日志
414
- const logs = await dataSource.query(`SELECT TOP ${limit} * FROM fn_dblog(NULL, NULL)`);
415
- return logs;
416
- } catch (e) {
417
- return [{ message: '无法获取SQL Server日志,请确保具有适当的权限' }];
418
- }
419
- }
420
- }
421
-
422
- /**
423
- * 备份数据库
424
- */
425
- async backupDatabase(dataSource: DataSource, databaseName: string, options?: any): Promise<string> {
426
- // SQL Server备份数据库
427
- try {
428
- // 使用BACKUP DATABASE命令备份
429
- const backupPath = options?.path || path.join(__dirname, '..', '..', 'backups');
430
-
431
- // 确保备份目录存在
432
- if (!fs.existsSync(backupPath)) {
433
- fs.mkdirSync(backupPath, { recursive: true });
434
- }
435
-
436
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
437
- const backupFile = path.join(backupPath, `${databaseName}_${timestamp}.bak`);
438
-
439
- // 执行备份命令
440
- const backupSql = `BACKUP DATABASE ${this.quoteIdentifier(databaseName)} TO DISK = '${backupFile}' WITH INIT`;
441
- await dataSource.query(backupSql);
442
-
443
- return `备份成功:${backupFile}`;
444
- } catch (error) {
445
- console.error('SQL Server备份失败:', error);
446
- // @ts-ignore
447
- throw new Error(`备份失败: ${error.message}`);
448
- }
449
- }
450
-
451
- /**
452
- * 恢复数据库
453
- */
454
- async restoreDatabase(dataSource: DataSource, databaseName: string, filePath: string, options?: any): Promise<void> {
455
- // SQL Server恢复数据库
456
- try {
457
- // 断开所有连接
458
- await dataSource.query(`ALTER DATABASE ${this.quoteIdentifier(databaseName)} SET SINGLE_USER WITH ROLLBACK IMMEDIATE`);
459
-
460
- // 执行恢复命令
461
- const restoreSql = `RESTORE DATABASE ${this.quoteIdentifier(databaseName)} FROM DISK = '${filePath}' WITH REPLACE`;
462
- await dataSource.query(restoreSql);
463
-
464
- // 恢复多用户模式
465
- await dataSource.query(`ALTER DATABASE ${this.quoteIdentifier(databaseName)} SET MULTI_USER`);
466
- } catch (error) {
467
- console.error('SQL Server恢复失败:', error);
468
- // @ts-ignore
469
- throw new Error(`恢复失败: ${error.message}`);
470
- }
471
- }
472
-
473
- /**
474
- * 导出表数据到 SQL 文件
475
- */
476
- async exportTableDataToSQL(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
477
- try {
478
- const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
479
- if (!fs.existsSync(exportPath)) fs.mkdirSync(exportPath, { recursive: true });
480
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
481
- const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.sql`);
482
-
483
- const columns = await this.getColumns(dataSource, databaseName, tableName);
484
- const columnNames = columns.map(column => column.name);
485
-
486
- // 生成文件头部
487
- const header = `-- 表数据导出 - ${tableName}\n` +
488
- `-- 导出时间: ${new Date().toISOString()}\n\n`;
489
- fs.writeFileSync(exportFile, header, 'utf8');
490
-
491
- // 分批处理数据,避免一次性加载大量数据到内存
492
- const batchSize = options?.batchSize || 10000; // 每批处理10000行
493
- let offset = 0;
494
- let hasMoreData = true;
495
-
496
- while (hasMoreData) {
497
- // 分批查询数据(SQL Server 使用 OFFSET FETCH 语法)
498
- const query = `SELECT * FROM ${this.quoteIdentifier(databaseName)}.${this.quoteIdentifier(tableName)} ORDER BY (SELECT NULL) OFFSET ${offset} ROWS FETCH NEXT ${batchSize} ROWS ONLY`;
499
- const data = await dataSource.query(query);
500
-
501
- if (data.length === 0) {
502
- hasMoreData = false;
503
- break;
504
- }
505
-
506
- // 生成当前批次的 INSERT 语句
507
- let batchSql = '';
508
- data.forEach((row: any) => {
509
- const values = columnNames.map(column => {
510
- const value = row[column];
511
- if (value === null || value === undefined) return 'NULL';
512
- if (typeof value === 'string') {
513
- // 处理字符串,转义单引号
514
- return `'${value.replace(/'/g, "''")}'`;
515
- }
516
- if (typeof value === 'boolean') {
517
- // SQL Server 使用 BIT 类型,1 表示 true,0 表示 false
518
- return value ? '1' : '0';
519
- }
520
- if (value instanceof Date) {
521
- // 格式化日期为 SQL Server 兼容格式
522
- const year = value.getFullYear();
523
- const month = String(value.getMonth() + 1).padStart(2, '0');
524
- const day = String(value.getDate()).padStart(2, '0');
525
- const hours = String(value.getHours()).padStart(2, '0');
526
- const minutes = String(value.getMinutes()).padStart(2, '0');
527
- const seconds = String(value.getSeconds()).padStart(2, '0');
528
- return `'${year}-${month}-${day} ${hours}:${minutes}:${seconds}'`;
529
- }
530
- if (typeof value === 'object') {
531
- // 处理对象类型
532
- try {
533
- const stringValue = JSON.stringify(value);
534
- return `'${stringValue.replace(/'/g, "''")}'`;
535
- } catch {
536
- return `'${String(value).replace(/'/g, "''")}'`;
537
- }
538
- }
539
- // 其他类型直接转换为字符串
540
- return String(value);
541
- });
542
-
543
- batchSql += `INSERT INTO ${this.quoteIdentifier(databaseName)}.${this.quoteIdentifier(tableName)} (${columnNames.map(col => this.quoteIdentifier(col)).join(', ')}) VALUES (${values.join(', ')});\n`;
544
- });
545
-
546
- // 追加写入文件
547
- fs.appendFileSync(exportFile, batchSql, 'utf8');
548
-
549
- // 增加偏移量
550
- offset += batchSize;
551
-
552
- // 打印进度信息
553
- console.log(`SQL Server导出表数据进度: ${tableName} - 已处理 ${offset} 行`);
554
- }
555
-
556
- return exportFile;
557
- } catch (error) {
558
- console.error('SQL Server导出表数据失败:', error);
559
- // @ts-ignore
560
- throw new Error(`导出表数据失败: ${error.message}`);
561
- }
562
- }
563
-
564
- /**
565
- * 导出表数据到 CSV 文件
566
- */
567
- async exportTableDataToCSV(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
568
- try {
569
- const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
570
- if (!fs.existsSync(exportPath)) fs.mkdirSync(exportPath, { recursive: true });
571
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
572
- const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.csv`);
573
-
574
- const columns = await this.getColumns(dataSource, databaseName, tableName);
575
- const columnNames = columns.map(column => column.name);
576
-
577
- // 写入 CSV 头部(包含 UTF-8 BOM)
578
- const bom = Buffer.from([0xEF, 0xBB, 0xBF]);
579
- fs.writeFileSync(exportFile, bom);
580
- fs.appendFileSync(exportFile, columnNames.map(name => `"${name}"`).join(',') + '\n', 'utf8');
581
-
582
- // 分批处理数据,避免一次性加载大量数据到内存
583
- const batchSize = options?.batchSize || 10000; // 每批处理10000行
584
- let offset = 0;
585
- let hasMoreData = true;
586
-
587
- while (hasMoreData) {
588
- // 分批查询数据(SQL Server 使用 OFFSET FETCH 语法)
589
- const query = `SELECT * FROM ${this.quoteIdentifier(databaseName)}.${this.quoteIdentifier(tableName)} ORDER BY (SELECT NULL) OFFSET ${offset} ROWS FETCH NEXT ${batchSize} ROWS ONLY`;
590
- const data = await dataSource.query(query);
591
-
592
- if (data.length === 0) {
593
- hasMoreData = false;
594
- break;
595
- }
596
-
597
- // 生成当前批次的 CSV 行
598
- let batchCsv = '';
599
- data.forEach((row: any) => {
600
- const values = columnNames.map(column => {
601
- const value = row[column];
602
- if (value === null || value === undefined) {
603
- return '';
604
- } else if (typeof value === 'string') {
605
- // 转义双引号并包裹在双引号中
606
- return `"${value.replace(/"/g, '""')}"`;
607
- } else if (value instanceof Date) {
608
- // 格式化日期为 SQL Server 兼容格式
609
- const year = value.getFullYear();
610
- const month = String(value.getMonth() + 1).padStart(2, '0');
611
- const day = String(value.getDate()).padStart(2, '0');
612
- const hours = String(value.getHours()).padStart(2, '0');
613
- const minutes = String(value.getMinutes()).padStart(2, '0');
614
- const seconds = String(value.getSeconds()).padStart(2, '0');
615
- return `"${year}-${month}-${day} ${hours}:${minutes}:${seconds}"`;
616
- } else if (typeof value === 'object' && value !== null) {
617
- // 处理对象类型
618
- try {
619
- return `"${JSON.stringify(value).replace(/"/g, '""')}"`;
620
- } catch {
621
- return `"${String(value).replace(/"/g, '""')}"`;
622
- }
623
- } else {
624
- return String(value);
625
- }
626
- });
627
-
628
- batchCsv += values.join(',') + '\n';
629
- });
630
-
631
- // 追加写入文件
632
- fs.appendFileSync(exportFile, batchCsv, 'utf8');
633
-
634
- // 增加偏移量
635
- offset += batchSize;
636
-
637
- // 打印进度信息
638
- console.log(`SQL Server导出表数据到CSV进度: ${tableName} - 已处理 ${offset} 行`);
639
- }
640
-
641
- return exportFile;
642
- } catch (error) {
643
- console.error('SQL Server导出表数据到CSV失败:', error);
644
- // @ts-ignore
645
- throw new Error(`导出表数据到CSV失败: ${error.message}`);
646
- }
647
- }
648
-
649
- /**
650
- * 导出表数据到 JSON 文件
651
- */
652
- async exportTableDataToJSON(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
653
- try {
654
- const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
655
- if (!fs.existsSync(exportPath)) fs.mkdirSync(exportPath, { recursive: true });
656
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
657
- const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.json`);
658
-
659
- // 写入 JSON 头部
660
- fs.writeFileSync(exportFile, '[\n', 'utf8');
661
-
662
- // 分批处理数据,避免一次性加载大量数据到内存
663
- const batchSize = options?.batchSize || 10000; // 每批处理10000行
664
- let offset = 0;
665
- let hasMoreData = true;
666
- let isFirstBatch = true;
667
-
668
- while (hasMoreData) {
669
- // 分批查询数据(SQL Server 使用 OFFSET FETCH 语法)
670
- const query = `SELECT * FROM ${this.quoteIdentifier(databaseName)}.${this.quoteIdentifier(tableName)} ORDER BY (SELECT NULL) OFFSET ${offset} ROWS FETCH NEXT ${batchSize} ROWS ONLY`;
671
- const data = await dataSource.query(query);
672
-
673
- if (data.length === 0) {
674
- hasMoreData = false;
675
- break;
676
- }
677
-
678
- // 生成当前批次的 JSON 数据
679
- let batchJson = '';
680
- data.forEach((row: any, index: number) => {
681
- if (!isFirstBatch || index > 0) {
682
- batchJson += ',\n';
683
- }
684
- batchJson += JSON.stringify(row);
685
- });
686
-
687
- // 追加写入文件
688
- fs.appendFileSync(exportFile, batchJson, 'utf8');
689
-
690
- // 增加偏移量
691
- offset += batchSize;
692
- isFirstBatch = false;
693
-
694
- // 打印进度信息
695
- console.log(`SQL Server导出表数据到JSON进度: ${tableName} - 已处理 ${offset} 行`);
696
- }
697
-
698
- // 写入 JSON 尾部
699
- fs.appendFileSync(exportFile, '\n]', 'utf8');
700
-
701
- return exportFile;
702
- } catch (error) {
703
- console.error('SQL Server导出表数据到JSON失败:', error);
704
- // @ts-ignore
705
- throw new Error(`导出表数据到JSON失败: ${error.message}`);
706
- }
707
- }
708
-
709
- /**
710
- * 导出表数据到 Excel 文件
711
- */
712
- async exportTableDataToExcel(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
713
- try {
714
- // 由于 Excel 文件格式复杂,这里我们先导出为 CSV,然后可以考虑使用库来转换
715
- // 或者直接调用其他服务来处理 Excel 导出
716
- return this.exportTableDataToCSV(dataSource, databaseName, tableName, options);
717
- } catch (error) {
718
- console.error('SQL Server导出表数据到Excel失败:', error);
719
- // @ts-ignore
720
- throw new Error(`导出表数据到Excel失败: ${error.message}`);
721
- }
722
- }
723
-
724
- /**
725
- * 修改表结构
726
- */
727
- async alterTable(dataSource: DataSource, databaseName: string, tableDiff: any): Promise<any> {
728
- try {
729
- const tableName = tableDiff.tableName;
730
- const sqlStatements: string[] = [];
731
-
732
- // 修改表注释(使用扩展属性)
733
- if (tableDiff.tableCommentChanged) {
734
- sqlStatements.push(`EXEC sp_addextendedproperty @name = N'MS_Description', @value = '${tableDiff.tableComment}', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'${tableName}';`);
735
- }
736
-
737
- // 添加新列
738
- tableDiff.addedColumns.forEach((column: any) => {
739
- // 检查type是否已经包含长度信息(括号)
740
- const typeHasLength = /\(\d+\)/.test(column.type);
741
-
742
- let columnSQL = `ALTER TABLE [${databaseName}].[dbo].[${tableName}] ADD [${column.name}] ${column.type}`;
743
-
744
- // 处理长度和精度(仅当type中没有指定长度时才添加)
745
- if (!typeHasLength) {
746
- if (column.length) {
747
- columnSQL += `(${column.length})`;
748
- } else if (column.precision) {
749
- if (column.scale) {
750
- columnSQL += `(${column.precision},${column.scale})`;
751
- } else {
752
- columnSQL += `(${column.precision})`;
753
- }
754
- }
755
- }
756
-
757
- // 处理NULL约束
758
- if (!column.nullable) {
759
- columnSQL += ' NOT NULL';
760
- }
761
-
762
- // 处理默认值
763
- if (column.defaultValue) {
764
- const upperDefault = column.defaultValue.toString().toUpperCase();
765
- if (['GETDATE()', 'GETUTCDATE()', 'CURRENT_TIMESTAMP', 'SYSDATETIME()'].includes(upperDefault)) {
766
- columnSQL += ` DEFAULT ${upperDefault}`;
767
- } else {
768
- columnSQL += ` DEFAULT '${column.defaultValue}'`;
769
- }
770
- }
771
-
772
- // 处理自增(MSSQL使用IDENTITY)
773
- if (column.isAutoIncrement) {
774
- if (column.type.toLowerCase().includes('int') || column.type.toLowerCase().includes('bigint')) {
775
- columnSQL += ' IDENTITY(1,1)';
776
- }
777
- }
778
-
779
- sqlStatements.push(columnSQL + ';');
780
-
781
- // 添加列注释
782
- if (column.comment) {
783
- sqlStatements.push(`EXEC sp_addextendedproperty @name = N'MS_Description', @value = '${column.comment}', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'${tableName}', @level2type = N'COLUMN', @level2name = N'${column.name}';`);
784
- }
785
- });
786
-
787
- // 修改列
788
- tableDiff.modifiedColumns.forEach((modification: any) => {
789
- const { oldColumn, newColumn } = modification;
790
-
791
- // 检查type是否已经包含长度信息(括号)
792
- const typeHasLength = /\(\d+\)/.test(newColumn.type);
793
-
794
- // 修改列类型和长度
795
- let columnSQL = `ALTER TABLE [${databaseName}].[dbo].[${tableName}] ALTER COLUMN [${newColumn.name}] ${newColumn.type}`;
796
-
797
- // 处理长度和精度(仅当type中没有指定长度时才添加)
798
- if (!typeHasLength) {
799
- if (newColumn.length) {
800
- columnSQL += `(${newColumn.length})`;
801
- } else if (newColumn.precision) {
802
- if (newColumn.scale) {
803
- columnSQL += `(${newColumn.precision},${newColumn.scale})`;
804
- } else {
805
- columnSQL += `(${newColumn.precision})`;
806
- }
807
- }
808
- }
809
-
810
- // 处理NULL约束
811
- if (!newColumn.nullable) {
812
- columnSQL += ' NOT NULL';
813
- } else {
814
- columnSQL += ' NULL';
815
- }
816
-
817
- sqlStatements.push(columnSQL + ';');
818
-
819
- // 修改列注释
820
- if (newColumn.comment) {
821
- sqlStatements.push(`EXEC sp_addextendedproperty @name = N'MS_Description', @value = '${newColumn.comment}', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'${tableName}', @level2type = N'COLUMN', @level2name = N'${newColumn.name}';`);
822
- }
823
- });
824
-
825
- // 删除列
826
- tableDiff.deletedColumns.forEach((column: any) => {
827
- sqlStatements.push(`ALTER TABLE [${databaseName}].[dbo].[${tableName}] DROP COLUMN [${column.name}];`);
828
- });
829
-
830
- // 执行SQL语句
831
- if (sqlStatements.length > 0) {
832
- await this.executeBatchQuery(dataSource, sqlStatements, { useTransaction: true });
833
- }
834
-
835
- return { ret: 0, message: '表结构修改成功' };
836
- } catch (error) {
837
- console.error('SQL Server修改表结构失败:', error);
838
- return { ret: 1, message: `修改表结构失败: ${error instanceof Error ? error.message : String(error)}` };
839
- }
840
- }
1
+ import { DataSource } from 'typeorm';
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+ import { BaseDatabaseService } from './base.service';
5
+ import {
6
+ TableEntity,
7
+ ColumnEntity,
8
+ IndexEntity,
9
+ ForeignKeyEntity
10
+ } from '../../model/database.entity';
11
+
12
+ /**
13
+ * SQL Server数据库服务实现
14
+ */
15
+ export class SQLServerService extends BaseDatabaseService {
16
+
17
+ getDatabaseType(): string {
18
+ return 'mssql';
19
+ }
20
+
21
+ /**
22
+ * 获取SQL Server数据库列表
23
+ */
24
+ async getDatabases(dataSource: DataSource): Promise<string[]> {
25
+ const result = await dataSource.query(`
26
+ SELECT name
27
+ FROM sys.databases
28
+ WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb')
29
+ AND state = 0
30
+ ORDER BY name
31
+ `);
32
+ return result.map((row: any) => row.name);
33
+ }
34
+
35
+ /**
36
+ * 获取SQL Server表列表
37
+ */
38
+ async getTables(dataSource: DataSource, database: string): Promise<TableEntity[]> {
39
+ const result = await dataSource.query(`
40
+ SELECT
41
+ t.name,
42
+ 'BASE TABLE' as type,
43
+ p.rows as rowCount,
44
+ SUM(a.total_pages) * 8 * 1024 as dataSize
45
+ FROM ${this.quoteIdentifier(database)}.sys.tables t
46
+ INNER JOIN ${this.quoteIdentifier(database)}.sys.partitions p ON t.object_id = p.object_id
47
+ INNER JOIN ${this.quoteIdentifier(database)}.sys.allocation_units a ON p.partition_id = a.container_id
48
+ WHERE t.is_ms_shipped = 0
49
+ AND p.index_id IN (0, 1)
50
+ GROUP BY t.name, p.rows
51
+ ORDER BY t.name
52
+ `);
53
+
54
+ return result.map((row: any) => ({
55
+ name: row.name,
56
+ type: row.type,
57
+ rowCount: row.rowCount || 0,
58
+ dataSize: row.dataSize || 0,
59
+ indexSize: 0 // SQL Server索引大小计算较复杂,这里简化处理
60
+ }));
61
+ }
62
+
63
+ /**
64
+ * 获取SQL Server列信息
65
+ */
66
+ async getColumns(dataSource: DataSource, database: string, table: string): Promise<ColumnEntity[]> {
67
+ // 使用兼容的SQL查询,避免使用可能不兼容的函数
68
+ const result = await dataSource.query(`
69
+ SELECT
70
+ c.name,
71
+ t.name as type,
72
+ c.max_length as length,
73
+ c.precision,
74
+ c.scale,
75
+ c.is_nullable as nullable,
76
+ c.default_object_id,
77
+ COLUMNPROPERTY(c.object_id, c.name, 'IsIdentity') as isIdentity
78
+ FROM ${this.quoteIdentifier(database)}.sys.columns c
79
+ INNER JOIN ${this.quoteIdentifier(database)}.sys.types t ON c.user_type_id = t.user_type_id
80
+ WHERE c.object_id = OBJECT_ID(?)
81
+ ORDER BY c.column_id
82
+ `, [`${database}.${table}`]);
83
+
84
+ // 获取主键信息
85
+ const primaryKeys = await this.getPrimaryKeys(dataSource, database, table);
86
+
87
+ return result.map((row: any) => ({
88
+ name: row.name,
89
+ type: row.type,
90
+ nullable: row.nullable,
91
+ defaultValue: row.default_object_id ? 'DEFAULT' : null,
92
+ isPrimary: primaryKeys.includes(row.name),
93
+ isAutoIncrement: row.isIdentity === 1,
94
+ length: row.length,
95
+ precision: row.precision,
96
+ scale: row.scale
97
+ }));
98
+ }
99
+
100
+ /**
101
+ * 获取SQL Server索引信息
102
+ */
103
+ async getIndexes(dataSource: DataSource, database: string, table: string): Promise<IndexEntity[]> {
104
+ const result = await dataSource.query(`
105
+ SELECT
106
+ i.name,
107
+ i.type_desc as type,
108
+ c.name as column,
109
+ i.is_unique as isUnique
110
+ FROM ${this.quoteIdentifier(database)}.sys.indexes i
111
+ INNER JOIN ${this.quoteIdentifier(database)}.sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
112
+ INNER JOIN ${this.quoteIdentifier(database)}.sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
113
+ WHERE i.object_id = OBJECT_ID(?)
114
+ AND i.is_primary_key = 0
115
+ ORDER BY i.name, ic.key_ordinal
116
+ `, [`${database}.${table}`]);
117
+
118
+ // 按索引名分组
119
+ const indexMap = new Map<string, IndexEntity>();
120
+ result.forEach((row: any) => {
121
+ if (!indexMap.has(row.name)) {
122
+ indexMap.set(row.name, {
123
+ name: row.name,
124
+ type: row.type,
125
+ columns: [],
126
+ unique: row.isUnique
127
+ });
128
+ }
129
+ indexMap.get(row.name)!.columns.push(row.column);
130
+ });
131
+
132
+ return Array.from(indexMap.values());
133
+ }
134
+
135
+ /**
136
+ * 获取SQL Server外键信息
137
+ */
138
+ async getForeignKeys(dataSource: DataSource, database: string, table: string): Promise<ForeignKeyEntity[]> {
139
+ const result = await dataSource.query(`
140
+ SELECT
141
+ fk.name as name,
142
+ c.name as column,
143
+ rt.name as referencedTable,
144
+ rc.name as referencedColumn,
145
+ fk.delete_action_desc as onDelete,
146
+ fk.update_action_desc as onUpdate
147
+ FROM ${this.quoteIdentifier(database)}.sys.foreign_keys fk
148
+ INNER JOIN ${this.quoteIdentifier(database)}.sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_id
149
+ INNER JOIN ${this.quoteIdentifier(database)}.sys.columns c ON fkc.parent_object_id = c.object_id AND fkc.parent_column_id = c.column_id
150
+ INNER JOIN ${this.quoteIdentifier(database)}.sys.columns rc ON fkc.referenced_object_id = rc.object_id AND fkc.referenced_column_id = rc.column_id
151
+ INNER JOIN ${this.quoteIdentifier(database)}.sys.tables rt ON fkc.referenced_object_id = rt.object_id
152
+ WHERE fkc.parent_object_id = OBJECT_ID(?)
153
+ `, [`${database}.${table}`]);
154
+
155
+ return result.map((row: any) => ({
156
+ name: row.name,
157
+ column: row.column,
158
+ referencedTable: row.referencedTable,
159
+ referencedColumn: row.referencedColumn,
160
+ onDelete: row.onDelete,
161
+ onUpdate: row.onUpdate
162
+ }));
163
+ }
164
+
165
+ /**
166
+ * 获取SQL Server数据库大小
167
+ */
168
+ async getDatabaseSize(dataSource: DataSource, database: string): Promise<number> {
169
+ const result = await dataSource.query(`
170
+ SELECT SUM(size * 8 * 1024) as size
171
+ FROM sys.master_files
172
+ WHERE database_id = DB_ID(?)
173
+ `, [database]);
174
+ return result[0]?.size || 0;
175
+ }
176
+
177
+ /**
178
+ * 获取主键信息
179
+ */
180
+ private async getPrimaryKeys(dataSource: DataSource, database: string, table: string): Promise<string[]> {
181
+ const result = await dataSource.query(`
182
+ SELECT c.name
183
+ FROM ${this.quoteIdentifier(database)}.sys.key_constraints k
184
+ INNER JOIN ${this.quoteIdentifier(database)}.sys.index_columns ic ON k.parent_object_id = ic.object_id AND k.unique_index_id = ic.index_id
185
+ INNER JOIN ${this.quoteIdentifier(database)}.sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
186
+ WHERE k.type = 'PK'
187
+ AND k.parent_object_id = OBJECT_ID(?)
188
+ ORDER BY ic.key_ordinal
189
+ `, [`${database}.${table}`]);
190
+ return result.map((row: any) => row.name);
191
+ }
192
+
193
+ /**
194
+ * SQL Server的标识符引用方式
195
+ */
196
+ public quoteIdentifier(identifier: string): string {
197
+ return `[${identifier}]`;
198
+ }
199
+
200
+ /**
201
+ * 获取SQL Server视图列表
202
+ */
203
+ async getViews(dataSource: DataSource, database: string): Promise<any[]> {
204
+ const result = await dataSource.query(`
205
+ SELECT
206
+ TABLE_NAME as name,
207
+ '' as comment,
208
+ TABLE_SCHEMA as schemaName
209
+ FROM ${this.quoteIdentifier(database)}.INFORMATION_SCHEMA.VIEWS
210
+ ORDER BY TABLE_NAME
211
+ `);
212
+
213
+ return result.map((row: any) => ({
214
+ name: row.name,
215
+ comment: row.comment || '',
216
+ schemaName: row.schemaname
217
+ }));
218
+ }
219
+
220
+ /**
221
+ * 获取SQL Server视图定义
222
+ */
223
+ async getViewDefinition(dataSource: DataSource, database: string, viewName: string): Promise<string> {
224
+ const result = await dataSource.query(`
225
+ SELECT VIEW_DEFINITION as definition
226
+ FROM ${this.quoteIdentifier(database)}.INFORMATION_SCHEMA.VIEWS
227
+ WHERE TABLE_NAME = ?
228
+ `, [viewName]);
229
+
230
+ return result[0]?.definition || '';
231
+ }
232
+
233
+ /**
234
+ * 获取SQL Server存储过程列表
235
+ */
236
+ async getProcedures(dataSource: DataSource, database: string): Promise<any[]> {
237
+ const result = await dataSource.query(`
238
+ SELECT
239
+ ROUTINE_NAME as name,
240
+ '' as comment,
241
+ ROUTINE_TYPE as type,
242
+ '' as returnType,
243
+ 'SQL' as language
244
+ FROM ${this.quoteIdentifier(database)}.INFORMATION_SCHEMA.ROUTINES
245
+ WHERE ROUTINE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA')
246
+ ORDER BY ROUTINE_NAME
247
+ `);
248
+
249
+ return result.map((row: any) => ({
250
+ name: row.name,
251
+ comment: row.comment || '',
252
+ type: row.type,
253
+ returnType: row.returnType || '',
254
+ language: row.language || 'SQL'
255
+ }));
256
+ }
257
+
258
+ /**
259
+ * 获取SQL Server存储过程定义
260
+ */
261
+ async getProcedureDefinition(dataSource: DataSource, database: string, procedureName: string): Promise<string> {
262
+ const result = await dataSource.query(`
263
+ SELECT ROUTINE_DEFINITION as definition
264
+ FROM ${this.quoteIdentifier(database)}.INFORMATION_SCHEMA.ROUTINES
265
+ WHERE ROUTINE_NAME = ?
266
+ `, [procedureName]);
267
+
268
+ return result[0]?.definition || '';
269
+ }
270
+
271
+ /**
272
+ * 创建SQL Server数据库
273
+ */
274
+ async createDatabase(dataSource: DataSource, databaseName: string, options?: any): Promise<void> {
275
+ let sql = `CREATE DATABASE ${this.quoteIdentifier(databaseName)}`;
276
+
277
+ if (options) {
278
+ const clauses = [] as Array<string>;
279
+
280
+ if (options.collation) {
281
+ clauses.push(`COLLATE ${options.collation}`);
282
+ }
283
+
284
+ if (options.containment) {
285
+ clauses.push(`CONTAINMENT = ${options.containment}`);
286
+ }
287
+
288
+ if (options.compatibilityLevel) {
289
+ clauses.push(`COMPATIBILITY_LEVEL = ${options.compatibilityLevel}`);
290
+ }
291
+
292
+ // 添加数据文件配置
293
+ if (options.dataFiles) {
294
+ const fileClauses = options.dataFiles.map((file: any) => {
295
+ let fileClause = `(NAME = '${file.name}', FILENAME = '${file.filename}'`;
296
+ if (file.size) fileClause += `, SIZE = ${file.size}`;
297
+ if (file.maxSize) fileClause += `, MAXSIZE = ${file.maxSize}`;
298
+ if (file.growth) fileClause += `, FILEGROWTH = ${file.growth}`;
299
+ fileClause += ')';
300
+ return fileClause;
301
+ });
302
+ clauses.push(`ON ${fileClauses.join(', ')}`);
303
+ }
304
+
305
+ // 添加日志文件配置
306
+ if (options.logFiles) {
307
+ const logClauses = options.logFiles.map((log: any) => {
308
+ let logClause = `(NAME = '${log.name}', FILENAME = '${log.filename}'`;
309
+ if (log.size) logClause += `, SIZE = ${log.size}`;
310
+ if (log.maxSize) logClause += `, MAXSIZE = ${log.maxSize}`;
311
+ if (log.growth) logClause += `, FILEGROWTH = ${log.growth}`;
312
+ logClause += ')';
313
+ return logClause;
314
+ });
315
+ clauses.push(`LOG ON ${logClauses.join(', ')}`);
316
+ }
317
+
318
+ if (clauses.length > 0) {
319
+ sql += ' ' + clauses.join(' ');
320
+ }
321
+ }
322
+
323
+ await dataSource.query(sql);
324
+ }
325
+
326
+ /**
327
+ * 删除SQL Server数据库
328
+ */
329
+ async dropDatabase(dataSource: DataSource, databaseName: string): Promise<void> {
330
+ const sql = `DROP DATABASE ${this.quoteIdentifier(databaseName)}`;
331
+ await dataSource.query(sql);
332
+ }
333
+
334
+ /**
335
+ * 导出数据库架构
336
+ */
337
+ async exportSchema(dataSource: DataSource, databaseName: string): Promise<string> {
338
+ // 获取所有表
339
+ const tables = await this.getTables(dataSource, databaseName);
340
+ let schemaSql = `-- 数据库架构导出 - ${databaseName}\n`;
341
+ schemaSql += `-- 导出时间: ${new Date().toISOString()}\n\n`;
342
+
343
+ // 为每个表生成CREATE TABLE语句
344
+ for (const table of tables) {
345
+ // 获取表结构
346
+ const columns = await this.getColumns(dataSource, databaseName, table.name);
347
+ const indexes = await this.getIndexes(dataSource, databaseName, table.name);
348
+ const foreignKeys = await this.getForeignKeys(dataSource, databaseName, table.name);
349
+
350
+ // 生成CREATE TABLE语句
351
+ schemaSql += `-- 表结构: ${table.name}\n`;
352
+ schemaSql += `CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(table.name)} (\n`;
353
+
354
+ // 添加列定义
355
+ const columnDefinitions = columns.map(column => {
356
+ let definition = ` ${this.quoteIdentifier(column.name)} ${column.type}`;
357
+ if (!column.nullable) definition += ' NOT NULL';
358
+ if (column.defaultValue !== undefined) {
359
+ // 特殊关键字处理
360
+ const upperDefault = column.defaultValue.toString().toUpperCase();
361
+ if (upperDefault === 'CURRENT_TIMESTAMP' || upperDefault === 'NOW()' || upperDefault === 'CURRENT_DATE') {
362
+ definition += ` DEFAULT ${upperDefault}`;
363
+ } else {
364
+ definition += ` DEFAULT ${column.defaultValue === null ? 'NULL' : `'${column.defaultValue}'`}`;
365
+ }
366
+ }
367
+ if (column.isAutoIncrement) definition += ' IDENTITY(1,1)';
368
+ return definition;
369
+ });
370
+
371
+ // 添加主键
372
+ const primaryKeyColumns = columns.filter(column => column.isPrimary);
373
+ if (primaryKeyColumns.length > 0) {
374
+ const primaryKeyNames = primaryKeyColumns.map(column => this.quoteIdentifier(column.name)).join(', ');
375
+ columnDefinitions.push(` PRIMARY KEY (${primaryKeyNames})`);
376
+ }
377
+
378
+ schemaSql += columnDefinitions.join(',\n');
379
+ schemaSql += '\n);\n\n';
380
+
381
+ // 添加索引
382
+ for (const index of indexes) {
383
+ if (index.type === 'PRIMARY' || index.name.toUpperCase() === 'PRIMARY') continue; // 跳过主键索引
384
+ schemaSql += `-- 索引: ${index.name} on ${table.name}\n`;
385
+ schemaSql += `CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX ${this.quoteIdentifier(index.name)} ON ${this.quoteIdentifier(table.name)} (${index.columns.map(col => this.quoteIdentifier(col)).join(', ')});\n`;
386
+ }
387
+
388
+ if (indexes.length > 0) schemaSql += '\n';
389
+
390
+ // 添加外键
391
+ for (const foreignKey of foreignKeys) {
392
+ schemaSql += `-- 外键: ${foreignKey.name} on ${table.name}\n`;
393
+ 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`;
394
+ }
395
+
396
+ if (foreignKeys.length > 0) schemaSql += '\n';
397
+ }
398
+
399
+ return schemaSql;
400
+ }
401
+
402
+ /**
403
+ * 查看数据库日志
404
+ */
405
+ async viewLogs(dataSource: DataSource, database?: string, limit: number = 100): Promise<any[]> {
406
+ // SQL Server查看日志
407
+ try {
408
+ // 尝试查看SQL Server错误日志
409
+ const logs = await dataSource.query(`EXEC xp_readerrorlog 0, 1, NULL, NULL, NULL, NULL, 'DESC'`);
410
+ return logs.slice(0, limit);
411
+ } catch (error) {
412
+ try {
413
+ // 尝试查看SQL Server事务日志
414
+ const logs = await dataSource.query(`SELECT TOP ${limit} * FROM fn_dblog(NULL, NULL)`);
415
+ return logs;
416
+ } catch (e) {
417
+ return [{ message: '无法获取SQL Server日志,请确保具有适当的权限' }];
418
+ }
419
+ }
420
+ }
421
+
422
+ /**
423
+ * 备份数据库
424
+ */
425
+ async backupDatabase(dataSource: DataSource, databaseName: string, options?: any): Promise<string> {
426
+ // SQL Server备份数据库
427
+ try {
428
+ // 使用BACKUP DATABASE命令备份
429
+ const backupPath = options?.path || path.join(__dirname, '..', '..', 'backups');
430
+
431
+ // 确保备份目录存在
432
+ if (!fs.existsSync(backupPath)) {
433
+ fs.mkdirSync(backupPath, { recursive: true });
434
+ }
435
+
436
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
437
+ const backupFile = path.join(backupPath, `${databaseName}_${timestamp}.bak`);
438
+
439
+ // 执行备份命令
440
+ const backupSql = `BACKUP DATABASE ${this.quoteIdentifier(databaseName)} TO DISK = '${backupFile}' WITH INIT`;
441
+ await dataSource.query(backupSql);
442
+
443
+ return `备份成功:${backupFile}`;
444
+ } catch (error) {
445
+ console.error('SQL Server备份失败:', error);
446
+ // @ts-ignore
447
+ throw new Error(`备份失败: ${error.message}`);
448
+ }
449
+ }
450
+
451
+ /**
452
+ * 恢复数据库
453
+ */
454
+ async restoreDatabase(dataSource: DataSource, databaseName: string, filePath: string, options?: any): Promise<void> {
455
+ // SQL Server恢复数据库
456
+ try {
457
+ // 断开所有连接
458
+ await dataSource.query(`ALTER DATABASE ${this.quoteIdentifier(databaseName)} SET SINGLE_USER WITH ROLLBACK IMMEDIATE`);
459
+
460
+ // 执行恢复命令
461
+ const restoreSql = `RESTORE DATABASE ${this.quoteIdentifier(databaseName)} FROM DISK = '${filePath}' WITH REPLACE`;
462
+ await dataSource.query(restoreSql);
463
+
464
+ // 恢复多用户模式
465
+ await dataSource.query(`ALTER DATABASE ${this.quoteIdentifier(databaseName)} SET MULTI_USER`);
466
+ } catch (error) {
467
+ console.error('SQL Server恢复失败:', error);
468
+ // @ts-ignore
469
+ throw new Error(`恢复失败: ${error.message}`);
470
+ }
471
+ }
472
+
473
+ /**
474
+ * 导出表数据到 SQL 文件
475
+ */
476
+ async exportTableDataToSQL(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
477
+ try {
478
+ const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
479
+ if (!fs.existsSync(exportPath)) fs.mkdirSync(exportPath, { recursive: true });
480
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
481
+ const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.sql`);
482
+
483
+ const columns = await this.getColumns(dataSource, databaseName, tableName);
484
+ const columnNames = columns.map(column => column.name);
485
+
486
+ // 生成文件头部
487
+ const header = `-- 表数据导出 - ${tableName}\n` +
488
+ `-- 导出时间: ${new Date().toISOString()}\n\n`;
489
+ fs.writeFileSync(exportFile, header, 'utf8');
490
+
491
+ // 分批处理数据,避免一次性加载大量数据到内存
492
+ const batchSize = options?.batchSize || 10000; // 每批处理10000行
493
+ let offset = 0;
494
+ let hasMoreData = true;
495
+
496
+ while (hasMoreData) {
497
+ // 分批查询数据(SQL Server 使用 OFFSET FETCH 语法)
498
+ const query = `SELECT * FROM ${this.quoteIdentifier(databaseName)}.${this.quoteIdentifier(tableName)} ORDER BY (SELECT NULL) OFFSET ${offset} ROWS FETCH NEXT ${batchSize} ROWS ONLY`;
499
+ const data = await dataSource.query(query);
500
+
501
+ if (data.length === 0) {
502
+ hasMoreData = false;
503
+ break;
504
+ }
505
+
506
+ // 生成当前批次的 INSERT 语句
507
+ let batchSql = '';
508
+ data.forEach((row: any) => {
509
+ const values = columnNames.map(column => {
510
+ const value = row[column];
511
+ if (value === null || value === undefined) return 'NULL';
512
+ if (typeof value === 'string') {
513
+ // 处理字符串,转义单引号
514
+ return `'${value.replace(/'/g, "''")}'`;
515
+ }
516
+ if (typeof value === 'boolean') {
517
+ // SQL Server 使用 BIT 类型,1 表示 true,0 表示 false
518
+ return value ? '1' : '0';
519
+ }
520
+ if (value instanceof Date) {
521
+ // 格式化日期为 SQL Server 兼容格式
522
+ const year = value.getFullYear();
523
+ const month = String(value.getMonth() + 1).padStart(2, '0');
524
+ const day = String(value.getDate()).padStart(2, '0');
525
+ const hours = String(value.getHours()).padStart(2, '0');
526
+ const minutes = String(value.getMinutes()).padStart(2, '0');
527
+ const seconds = String(value.getSeconds()).padStart(2, '0');
528
+ return `'${year}-${month}-${day} ${hours}:${minutes}:${seconds}'`;
529
+ }
530
+ if (typeof value === 'object') {
531
+ // 处理对象类型
532
+ try {
533
+ const stringValue = JSON.stringify(value);
534
+ return `'${stringValue.replace(/'/g, "''")}'`;
535
+ } catch {
536
+ return `'${String(value).replace(/'/g, "''")}'`;
537
+ }
538
+ }
539
+ // 其他类型直接转换为字符串
540
+ return String(value);
541
+ });
542
+
543
+ batchSql += `INSERT INTO ${this.quoteIdentifier(databaseName)}.${this.quoteIdentifier(tableName)} (${columnNames.map(col => this.quoteIdentifier(col)).join(', ')}) VALUES (${values.join(', ')});\n`;
544
+ });
545
+
546
+ // 追加写入文件
547
+ fs.appendFileSync(exportFile, batchSql, 'utf8');
548
+
549
+ // 增加偏移量
550
+ offset += batchSize;
551
+
552
+ // 打印进度信息
553
+ console.log(`SQL Server导出表数据进度: ${tableName} - 已处理 ${offset} 行`);
554
+ }
555
+
556
+ return exportFile;
557
+ } catch (error) {
558
+ console.error('SQL Server导出表数据失败:', error);
559
+ // @ts-ignore
560
+ throw new Error(`导出表数据失败: ${error.message}`);
561
+ }
562
+ }
563
+
564
+ /**
565
+ * 导出表数据到 CSV 文件
566
+ */
567
+ async exportTableDataToCSV(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
568
+ try {
569
+ const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
570
+ if (!fs.existsSync(exportPath)) fs.mkdirSync(exportPath, { recursive: true });
571
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
572
+ const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.csv`);
573
+
574
+ const columns = await this.getColumns(dataSource, databaseName, tableName);
575
+ const columnNames = columns.map(column => column.name);
576
+
577
+ // 写入 CSV 头部(包含 UTF-8 BOM)
578
+ const bom = Buffer.from([0xEF, 0xBB, 0xBF]);
579
+ fs.writeFileSync(exportFile, bom);
580
+ fs.appendFileSync(exportFile, columnNames.map(name => `"${name}"`).join(',') + '\n', 'utf8');
581
+
582
+ // 分批处理数据,避免一次性加载大量数据到内存
583
+ const batchSize = options?.batchSize || 10000; // 每批处理10000行
584
+ let offset = 0;
585
+ let hasMoreData = true;
586
+
587
+ while (hasMoreData) {
588
+ // 分批查询数据(SQL Server 使用 OFFSET FETCH 语法)
589
+ const query = `SELECT * FROM ${this.quoteIdentifier(databaseName)}.${this.quoteIdentifier(tableName)} ORDER BY (SELECT NULL) OFFSET ${offset} ROWS FETCH NEXT ${batchSize} ROWS ONLY`;
590
+ const data = await dataSource.query(query);
591
+
592
+ if (data.length === 0) {
593
+ hasMoreData = false;
594
+ break;
595
+ }
596
+
597
+ // 生成当前批次的 CSV 行
598
+ let batchCsv = '';
599
+ data.forEach((row: any) => {
600
+ const values = columnNames.map(column => {
601
+ const value = row[column];
602
+ if (value === null || value === undefined) {
603
+ return '';
604
+ } else if (typeof value === 'string') {
605
+ // 转义双引号并包裹在双引号中
606
+ return `"${value.replace(/"/g, '""')}"`;
607
+ } else if (value instanceof Date) {
608
+ // 格式化日期为 SQL Server 兼容格式
609
+ const year = value.getFullYear();
610
+ const month = String(value.getMonth() + 1).padStart(2, '0');
611
+ const day = String(value.getDate()).padStart(2, '0');
612
+ const hours = String(value.getHours()).padStart(2, '0');
613
+ const minutes = String(value.getMinutes()).padStart(2, '0');
614
+ const seconds = String(value.getSeconds()).padStart(2, '0');
615
+ return `"${year}-${month}-${day} ${hours}:${minutes}:${seconds}"`;
616
+ } else if (typeof value === 'object' && value !== null) {
617
+ // 处理对象类型
618
+ try {
619
+ return `"${JSON.stringify(value).replace(/"/g, '""')}"`;
620
+ } catch {
621
+ return `"${String(value).replace(/"/g, '""')}"`;
622
+ }
623
+ } else {
624
+ return String(value);
625
+ }
626
+ });
627
+
628
+ batchCsv += values.join(',') + '\n';
629
+ });
630
+
631
+ // 追加写入文件
632
+ fs.appendFileSync(exportFile, batchCsv, 'utf8');
633
+
634
+ // 增加偏移量
635
+ offset += batchSize;
636
+
637
+ // 打印进度信息
638
+ console.log(`SQL Server导出表数据到CSV进度: ${tableName} - 已处理 ${offset} 行`);
639
+ }
640
+
641
+ return exportFile;
642
+ } catch (error) {
643
+ console.error('SQL Server导出表数据到CSV失败:', error);
644
+ // @ts-ignore
645
+ throw new Error(`导出表数据到CSV失败: ${error.message}`);
646
+ }
647
+ }
648
+
649
+ /**
650
+ * 导出表数据到 JSON 文件
651
+ */
652
+ async exportTableDataToJSON(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
653
+ try {
654
+ const exportPath = options?.path || path.join(__dirname, '..', '..', '..', 'data', 'exports');
655
+ if (!fs.existsSync(exportPath)) fs.mkdirSync(exportPath, { recursive: true });
656
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
657
+ const exportFile = path.join(exportPath, `${tableName}_data_${timestamp}.json`);
658
+
659
+ // 写入 JSON 头部
660
+ fs.writeFileSync(exportFile, '[\n', 'utf8');
661
+
662
+ // 分批处理数据,避免一次性加载大量数据到内存
663
+ const batchSize = options?.batchSize || 10000; // 每批处理10000行
664
+ let offset = 0;
665
+ let hasMoreData = true;
666
+ let isFirstBatch = true;
667
+
668
+ while (hasMoreData) {
669
+ // 分批查询数据(SQL Server 使用 OFFSET FETCH 语法)
670
+ const query = `SELECT * FROM ${this.quoteIdentifier(databaseName)}.${this.quoteIdentifier(tableName)} ORDER BY (SELECT NULL) OFFSET ${offset} ROWS FETCH NEXT ${batchSize} ROWS ONLY`;
671
+ const data = await dataSource.query(query);
672
+
673
+ if (data.length === 0) {
674
+ hasMoreData = false;
675
+ break;
676
+ }
677
+
678
+ // 生成当前批次的 JSON 数据
679
+ let batchJson = '';
680
+ data.forEach((row: any, index: number) => {
681
+ if (!isFirstBatch || index > 0) {
682
+ batchJson += ',\n';
683
+ }
684
+ batchJson += JSON.stringify(row);
685
+ });
686
+
687
+ // 追加写入文件
688
+ fs.appendFileSync(exportFile, batchJson, 'utf8');
689
+
690
+ // 增加偏移量
691
+ offset += batchSize;
692
+ isFirstBatch = false;
693
+
694
+ // 打印进度信息
695
+ console.log(`SQL Server导出表数据到JSON进度: ${tableName} - 已处理 ${offset} 行`);
696
+ }
697
+
698
+ // 写入 JSON 尾部
699
+ fs.appendFileSync(exportFile, '\n]', 'utf8');
700
+
701
+ return exportFile;
702
+ } catch (error) {
703
+ console.error('SQL Server导出表数据到JSON失败:', error);
704
+ // @ts-ignore
705
+ throw new Error(`导出表数据到JSON失败: ${error.message}`);
706
+ }
707
+ }
708
+
709
+ /**
710
+ * 导出表数据到 Excel 文件
711
+ */
712
+ async exportTableDataToExcel(dataSource: DataSource, databaseName: string, tableName: string, options?: any): Promise<string> {
713
+ try {
714
+ // 由于 Excel 文件格式复杂,这里我们先导出为 CSV,然后可以考虑使用库来转换
715
+ // 或者直接调用其他服务来处理 Excel 导出
716
+ return this.exportTableDataToCSV(dataSource, databaseName, tableName, options);
717
+ } catch (error) {
718
+ console.error('SQL Server导出表数据到Excel失败:', error);
719
+ // @ts-ignore
720
+ throw new Error(`导出表数据到Excel失败: ${error.message}`);
721
+ }
722
+ }
723
+
724
+ /**
725
+ * 修改表结构
726
+ */
727
+ async alterTable(dataSource: DataSource, databaseName: string, tableDiff: any): Promise<any> {
728
+ try {
729
+ const tableName = tableDiff.tableName;
730
+ const sqlStatements: string[] = [];
731
+
732
+ // 修改表注释(使用扩展属性)
733
+ if (tableDiff.tableCommentChanged) {
734
+ sqlStatements.push(`EXEC sp_addextendedproperty @name = N'MS_Description', @value = '${tableDiff.tableComment}', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'${tableName}';`);
735
+ }
736
+
737
+ // 添加新列
738
+ tableDiff.addedColumns.forEach((column: any) => {
739
+ // 检查type是否已经包含长度信息(括号)
740
+ const typeHasLength = /\(\d+\)/.test(column.type);
741
+
742
+ let columnSQL = `ALTER TABLE [${databaseName}].[dbo].[${tableName}] ADD [${column.name}] ${column.type}`;
743
+
744
+ // 处理长度和精度(仅当type中没有指定长度时才添加)
745
+ if (!typeHasLength) {
746
+ if (column.length) {
747
+ columnSQL += `(${column.length})`;
748
+ } else if (column.precision) {
749
+ if (column.scale) {
750
+ columnSQL += `(${column.precision},${column.scale})`;
751
+ } else {
752
+ columnSQL += `(${column.precision})`;
753
+ }
754
+ }
755
+ }
756
+
757
+ // 处理NULL约束
758
+ if (!column.nullable) {
759
+ columnSQL += ' NOT NULL';
760
+ }
761
+
762
+ // 处理默认值
763
+ if (column.defaultValue) {
764
+ const upperDefault = column.defaultValue.toString().toUpperCase();
765
+ if (['GETDATE()', 'GETUTCDATE()', 'CURRENT_TIMESTAMP', 'SYSDATETIME()'].includes(upperDefault)) {
766
+ columnSQL += ` DEFAULT ${upperDefault}`;
767
+ } else {
768
+ columnSQL += ` DEFAULT '${column.defaultValue}'`;
769
+ }
770
+ }
771
+
772
+ // 处理自增(MSSQL使用IDENTITY)
773
+ if (column.isAutoIncrement) {
774
+ if (column.type.toLowerCase().includes('int') || column.type.toLowerCase().includes('bigint')) {
775
+ columnSQL += ' IDENTITY(1,1)';
776
+ }
777
+ }
778
+
779
+ sqlStatements.push(columnSQL + ';');
780
+
781
+ // 添加列注释
782
+ if (column.comment) {
783
+ sqlStatements.push(`EXEC sp_addextendedproperty @name = N'MS_Description', @value = '${column.comment}', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'${tableName}', @level2type = N'COLUMN', @level2name = N'${column.name}';`);
784
+ }
785
+ });
786
+
787
+ // 修改列
788
+ tableDiff.modifiedColumns.forEach((modification: any) => {
789
+ const { oldColumn, newColumn } = modification;
790
+
791
+ // 检查type是否已经包含长度信息(括号)
792
+ const typeHasLength = /\(\d+\)/.test(newColumn.type);
793
+
794
+ // 修改列类型和长度
795
+ let columnSQL = `ALTER TABLE [${databaseName}].[dbo].[${tableName}] ALTER COLUMN [${newColumn.name}] ${newColumn.type}`;
796
+
797
+ // 处理长度和精度(仅当type中没有指定长度时才添加)
798
+ if (!typeHasLength) {
799
+ if (newColumn.length) {
800
+ columnSQL += `(${newColumn.length})`;
801
+ } else if (newColumn.precision) {
802
+ if (newColumn.scale) {
803
+ columnSQL += `(${newColumn.precision},${newColumn.scale})`;
804
+ } else {
805
+ columnSQL += `(${newColumn.precision})`;
806
+ }
807
+ }
808
+ }
809
+
810
+ // 处理NULL约束
811
+ if (!newColumn.nullable) {
812
+ columnSQL += ' NOT NULL';
813
+ } else {
814
+ columnSQL += ' NULL';
815
+ }
816
+
817
+ sqlStatements.push(columnSQL + ';');
818
+
819
+ // 修改列注释
820
+ if (newColumn.comment) {
821
+ sqlStatements.push(`EXEC sp_addextendedproperty @name = N'MS_Description', @value = '${newColumn.comment}', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'${tableName}', @level2type = N'COLUMN', @level2name = N'${newColumn.name}';`);
822
+ }
823
+ });
824
+
825
+ // 删除列
826
+ tableDiff.deletedColumns.forEach((column: any) => {
827
+ sqlStatements.push(`ALTER TABLE [${databaseName}].[dbo].[${tableName}] DROP COLUMN [${column.name}];`);
828
+ });
829
+
830
+ // 执行SQL语句
831
+ if (sqlStatements.length > 0) {
832
+ await this.executeBatchQuery(dataSource, sqlStatements, { useTransaction: true });
833
+ }
834
+
835
+ return { ret: 0, message: '表结构修改成功' };
836
+ } catch (error) {
837
+ console.error('SQL Server修改表结构失败:', error);
838
+ return { ret: 1, message: `修改表结构失败: ${error instanceof Error ? error.message : String(error)}` };
839
+ }
840
+ }
841
+
842
+ /**
843
+ * 批量插入数据
844
+ */
845
+ async bulkInsert(dataSource: DataSource, databaseName: string, tableName: string, data: any[]): Promise<void> {
846
+ if (data.length === 0) return;
847
+
848
+ const columns = Object.keys(data[0]);
849
+ const placeholders = data.map((_, index) =>
850
+ `(${columns.map((_, colIndex) => `@p${index}_${colIndex}`).join(', ')})`
851
+ ).join(', ');
852
+
853
+ const sql = `INSERT INTO [${databaseName}].[dbo].[${tableName}] (${columns.map(col => `[${col}]`).join(', ')}) VALUES ${placeholders}`;
854
+
855
+ // MSSQL需要单独处理参数化查询
856
+ for (let i = 0; i< data.length; i++) {
857
+ const params: any = {};
858
+ columns.forEach((column, colIndex) =>{
859
+ params[`p${i}_${colIndex}`] = data[i][column];
860
+ });
861
+ await dataSource.query(sql, params);
862
+ }
863
+ }
864
+
865
+ /**
866
+ * 插入单条数据
867
+ */
868
+ async insertData(dataSource: DataSource, databaseName: string, tableName: string, data: any): Promise<void> {
869
+ const columns = Object.keys(data);
870
+ const placeholders = columns.map((_, index) => `@p${index}`).join(', ');
871
+ const params: any = {};
872
+
873
+ columns.forEach((column, index) => {
874
+ params[`p${index}`] = data[column];
875
+ });
876
+
877
+ const sql = `INSERT INTO [${databaseName}].[dbo].[${tableName}] (${columns.map(col => `[${col}]`).join(', ')}) VALUES (${placeholders})`;
878
+
879
+ await dataSource.query(sql, params);
880
+ }
881
+
882
+ /**
883
+ * 删除表
884
+ */
885
+ async dropTable(dataSource: DataSource, databaseName: string, tableName: string): Promise<void> {
886
+ const sql = `DROP TABLE IF EXISTS [${databaseName}].[dbo].[${tableName}]`;
887
+ await dataSource.query(sql);
888
+ }
889
+
890
+ /**
891
+ * 创建表
892
+ */
893
+ async createTable(dataSource: DataSource, databaseName: string, table: any): Promise<void> {
894
+ const { name, columns, comment } = table;
895
+
896
+ let sql = `CREATE TABLE [${databaseName}].[dbo].[${name}] (\n`;
897
+ const columnDefs: string[] = [];
898
+
899
+ columns.forEach((column: any) => {
900
+ let columnDef = ` [${column.name}] ${column.type}`;
901
+
902
+ if (!column.nullable) {
903
+ columnDef += ' NOT NULL';
904
+ }
905
+
906
+ if (column.defaultValue) {
907
+ const upperDefault = column.defaultValue.toString().toUpperCase();
908
+ if (['CURRENT_TIMESTAMP', 'GETDATE()', 'CURRENT_DATE', 'CURRENT_TIME'].includes(upperDefault)) {
909
+ columnDef += ` DEFAULT ${upperDefault}`;
910
+ } else {
911
+ columnDef += ` DEFAULT '${column.defaultValue}'`;
912
+ }
913
+ }
914
+
915
+ if (column.isAutoIncrement) {
916
+ columnDef += ' IDENTITY(1,1)';
917
+ }
918
+
919
+ columnDefs.push(columnDef);
920
+ });
921
+
922
+ sql += columnDefs.join(',\n');
923
+ sql += '\n)';
924
+
925
+ await dataSource.query(sql);
926
+
927
+ // 添加表注释
928
+ if (comment) {
929
+ await dataSource.query(`EXEC sp_addextendedproperty @name = N'MS_Description', @value = '${comment}', @level0type = N'SCHEMA', @level0name = N'dbo', @level1type = N'TABLE', @level1name = N'${name}';`);
930
+ }
931
+ }
841
932
  }