@mikro-orm/mssql 7.0.4 → 7.0.5-dev.1

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.
@@ -1,71 +1,71 @@
1
- import { EnumType, SchemaHelper, StringType, TextType, Utils } from '@mikro-orm/sql';
1
+ import { EnumType, SchemaHelper, StringType, TextType, Utils, } from '@mikro-orm/sql';
2
2
  import { UnicodeStringType } from './UnicodeStringType.js';
3
3
  /** Schema introspection helper for Microsoft SQL Server. */
4
4
  export class MsSqlSchemaHelper extends SchemaHelper {
5
- static DEFAULT_VALUES = {
6
- true: ['1'],
7
- false: ['0'],
8
- 'getdate()': ['current_timestamp'],
9
- };
10
- getManagementDbName() {
11
- return 'master';
12
- }
13
- disableForeignKeysSQL() {
14
- return `exec sp_MSforeachtable 'alter table ? nocheck constraint all';`;
15
- }
16
- enableForeignKeysSQL() {
17
- return `exec sp_MSforeachtable 'alter table ? check constraint all';`;
18
- }
19
- getDatabaseExistsSQL(name) {
20
- return `select 1 from sys.databases where name = N'${name}'`;
21
- }
22
- getListTablesSQL() {
23
- return `select t.name as table_name, schema_name(t2.schema_id) schema_name, ep.value as table_comment
5
+ static DEFAULT_VALUES = {
6
+ true: ['1'],
7
+ false: ['0'],
8
+ 'getdate()': ['current_timestamp'],
9
+ };
10
+ getManagementDbName() {
11
+ return 'master';
12
+ }
13
+ disableForeignKeysSQL() {
14
+ return `exec sp_MSforeachtable 'alter table ? nocheck constraint all';`;
15
+ }
16
+ enableForeignKeysSQL() {
17
+ return `exec sp_MSforeachtable 'alter table ? check constraint all';`;
18
+ }
19
+ getDatabaseExistsSQL(name) {
20
+ return `select 1 from sys.databases where name = N'${name}'`;
21
+ }
22
+ getListTablesSQL() {
23
+ return `select t.name as table_name, schema_name(t2.schema_id) schema_name, ep.value as table_comment
24
24
  from sysobjects t
25
25
  inner join sys.tables t2 on t2.object_id = t.id
26
26
  left join sys.extended_properties ep on ep.major_id = t.id and ep.name = 'MS_Description' and ep.minor_id = 0
27
27
  order by schema_name(t2.schema_id), t.name`;
28
- }
29
- getListViewsSQL() {
30
- return `select v.name as view_name, schema_name(v.schema_id) as schema_name, m.definition as view_definition
28
+ }
29
+ getListViewsSQL() {
30
+ return `select v.name as view_name, schema_name(v.schema_id) as schema_name, m.definition as view_definition
31
31
  from sys.views v
32
32
  inner join sys.sql_modules m on v.object_id = m.object_id
33
33
  order by schema_name(v.schema_id), v.name`;
34
- }
35
- async loadViews(schema, connection) {
36
- const views = await connection.execute(this.getListViewsSQL());
37
- for (const view of views) {
38
- // Extract SELECT statement from CREATE VIEW ... AS SELECT ...
39
- const match = /\bAS\s+(.+)$/is.exec(view.view_definition);
40
- const definition = match?.[1]?.trim();
41
- if (definition) {
42
- const schemaName = view.schema_name === this.platform.getDefaultSchemaName() ? undefined : view.schema_name;
43
- schema.addView(view.view_name, schemaName, definition);
44
- }
45
- }
46
- }
47
- async getNamespaces(connection) {
48
- const sql = `select name as schema_name from sys.schemas order by name`;
49
- const res = await connection.execute(sql);
50
- return res.map(row => row.schema_name);
51
- }
52
- normalizeDefaultValue(defaultValue, length, defaultValues = {}, stripQuotes = false) {
53
- let match = /^\((.*)\)$/.exec(defaultValue);
54
- if (match) {
55
- defaultValue = match[1];
56
- }
57
- match = /^\((.*)\)$/.exec(defaultValue);
58
- if (match) {
59
- defaultValue = match[1];
60
- }
61
- match = /^'(.*)'$/.exec(defaultValue);
62
- if (stripQuotes && match) {
63
- defaultValue = match[1];
64
- }
65
- return super.normalizeDefaultValue(defaultValue, length, MsSqlSchemaHelper.DEFAULT_VALUES);
66
- }
67
- async getAllColumns(connection, tablesBySchemas) {
68
- const sql = `select table_name as table_name,
34
+ }
35
+ async loadViews(schema, connection) {
36
+ const views = await connection.execute(this.getListViewsSQL());
37
+ for (const view of views) {
38
+ // Extract SELECT statement from CREATE VIEW ... AS SELECT ...
39
+ const match = /\bAS\s+(.+)$/is.exec(view.view_definition);
40
+ const definition = match?.[1]?.trim();
41
+ if (definition) {
42
+ const schemaName = view.schema_name === this.platform.getDefaultSchemaName() ? undefined : view.schema_name;
43
+ schema.addView(view.view_name, schemaName, definition);
44
+ }
45
+ }
46
+ }
47
+ async getNamespaces(connection) {
48
+ const sql = `select name as schema_name from sys.schemas order by name`;
49
+ const res = await connection.execute(sql);
50
+ return res.map(row => row.schema_name);
51
+ }
52
+ normalizeDefaultValue(defaultValue, length, defaultValues = {}, stripQuotes = false) {
53
+ let match = /^\((.*)\)$/.exec(defaultValue);
54
+ if (match) {
55
+ defaultValue = match[1];
56
+ }
57
+ match = /^\((.*)\)$/.exec(defaultValue);
58
+ if (match) {
59
+ defaultValue = match[1];
60
+ }
61
+ match = /^'(.*)'$/.exec(defaultValue);
62
+ if (stripQuotes && match) {
63
+ defaultValue = match[1];
64
+ }
65
+ return super.normalizeDefaultValue(defaultValue, length, MsSqlSchemaHelper.DEFAULT_VALUES);
66
+ }
67
+ async getAllColumns(connection, tablesBySchemas) {
68
+ const sql = `select table_name as table_name,
69
69
  table_schema as schema_name,
70
70
  column_name as column_name,
71
71
  column_default as column_default,
@@ -87,57 +87,57 @@ export class MsSqlSchemaHelper extends SchemaHelper {
87
87
  left join sys.default_constraints t5 on sc.default_object_id = t5.object_id
88
88
  where (${[...tablesBySchemas.entries()].map(([schema, tables]) => `(ic.table_name in (${tables.map(t => this.platform.quoteValue(t.table_name)).join(',')}) and ic.table_schema = '${schema}')`).join(' or ')})
89
89
  order by ordinal_position`;
90
- const allColumns = await connection.execute(sql);
91
- const str = val => (val != null ? '' + val : val);
92
- const ret = {};
93
- for (const col of allColumns) {
94
- const mappedType = this.platform.getMappedType(col.data_type);
95
- const defaultValue = str(this.normalizeDefaultValue(col.column_default, col.length, {}, true));
96
- const increments = col.is_identity === 1 && connection.getPlatform().isNumericColumn(mappedType);
97
- const key = this.getTableKey(col);
98
- /* v8 ignore next */
99
- const generated = col.generation_expression
100
- ? `${col.generation_expression}${col.is_persisted ? ' persisted' : ''}`
101
- : undefined;
102
- let type = col.data_type;
103
- if (['varchar', 'nvarchar', 'char', 'nchar', 'varbinary'].includes(col.data_type)) {
104
- col.length = col.character_maximum_length;
105
- }
106
- if (['timestamp', 'datetime', 'datetime2', 'time', 'datetimeoffset'].includes(col.data_type)) {
107
- col.length = col.datetime_precision;
108
- }
109
- if (col.length != null && !type.endsWith(`(${col.length})`) && !['text', 'date'].includes(type)) {
110
- type += `(${col.length === -1 ? 'max' : col.length})`;
111
- }
112
- if (type === 'numeric' && col.numeric_precision != null && col.numeric_scale != null) {
113
- type += `(${col.numeric_precision},${col.numeric_scale})`;
114
- }
115
- if (type === 'float' && col.numeric_precision != null) {
116
- type += `(${col.numeric_precision})`;
117
- }
118
- ret[key] ??= [];
119
- ret[key].push({
120
- name: col.column_name,
121
- type: this.platform.isNumericColumn(mappedType)
122
- ? col.data_type.replace(/ unsigned$/, '').replace(/\(\d+\)$/, '')
123
- : type,
124
- mappedType,
125
- unsigned: col.data_type.endsWith(' unsigned'),
126
- length: col.length,
127
- default: this.wrap(defaultValue, mappedType),
128
- defaultConstraint: col.column_default_name,
129
- nullable: col.is_nullable === 'YES',
130
- autoincrement: increments,
131
- precision: col.numeric_precision,
132
- scale: col.numeric_scale,
133
- comment: col.column_comment,
134
- generated,
135
- });
136
- }
137
- return ret;
138
- }
139
- async getAllIndexes(connection, tablesBySchemas) {
140
- const sql = `select t.name as table_name,
90
+ const allColumns = await connection.execute(sql);
91
+ const str = (val) => (val != null ? '' + val : val);
92
+ const ret = {};
93
+ for (const col of allColumns) {
94
+ const mappedType = this.platform.getMappedType(col.data_type);
95
+ const defaultValue = str(this.normalizeDefaultValue(col.column_default, col.length, {}, true));
96
+ const increments = col.is_identity === 1 && connection.getPlatform().isNumericColumn(mappedType);
97
+ const key = this.getTableKey(col);
98
+ /* v8 ignore next */
99
+ const generated = col.generation_expression
100
+ ? `${col.generation_expression}${col.is_persisted ? ' persisted' : ''}`
101
+ : undefined;
102
+ let type = col.data_type;
103
+ if (['varchar', 'nvarchar', 'char', 'nchar', 'varbinary'].includes(col.data_type)) {
104
+ col.length = col.character_maximum_length;
105
+ }
106
+ if (['timestamp', 'datetime', 'datetime2', 'time', 'datetimeoffset'].includes(col.data_type)) {
107
+ col.length = col.datetime_precision;
108
+ }
109
+ if (col.length != null && !type.endsWith(`(${col.length})`) && !['text', 'date'].includes(type)) {
110
+ type += `(${col.length === -1 ? 'max' : col.length})`;
111
+ }
112
+ if (type === 'numeric' && col.numeric_precision != null && col.numeric_scale != null) {
113
+ type += `(${col.numeric_precision},${col.numeric_scale})`;
114
+ }
115
+ if (type === 'float' && col.numeric_precision != null) {
116
+ type += `(${col.numeric_precision})`;
117
+ }
118
+ ret[key] ??= [];
119
+ ret[key].push({
120
+ name: col.column_name,
121
+ type: this.platform.isNumericColumn(mappedType)
122
+ ? col.data_type.replace(/ unsigned$/, '').replace(/\(\d+\)$/, '')
123
+ : type,
124
+ mappedType,
125
+ unsigned: col.data_type.endsWith(' unsigned'),
126
+ length: col.length,
127
+ default: this.wrap(defaultValue, mappedType),
128
+ defaultConstraint: col.column_default_name,
129
+ nullable: col.is_nullable === 'YES',
130
+ autoincrement: increments,
131
+ precision: col.numeric_precision,
132
+ scale: col.numeric_scale,
133
+ comment: col.column_comment,
134
+ generated,
135
+ });
136
+ }
137
+ return ret;
138
+ }
139
+ async getAllIndexes(connection, tablesBySchemas) {
140
+ const sql = `select t.name as table_name,
141
141
  ind.name as index_name,
142
142
  is_unique as is_unique,
143
143
  ind.is_primary_key as is_primary_key,
@@ -156,60 +156,60 @@ export class MsSqlSchemaHelper extends SchemaHelper {
156
156
  where
157
157
  (${[...tablesBySchemas.entries()].map(([schema, tables]) => `(t.name in (${tables.map(t => this.platform.quoteValue(t.table_name)).join(',')}) and schema_name(t.schema_id) = '${schema}')`).join(' OR ')})
158
158
  order by t.name, ind.name, ic.is_included_column, ic.key_ordinal`;
159
- const allIndexes = await connection.execute(sql);
160
- const ret = {};
161
- for (const index of allIndexes) {
162
- const key = this.getTableKey(index);
163
- const isIncluded = index.is_included_column;
164
- const indexDef = {
165
- columnNames: isIncluded ? [] : [index.column_name],
166
- keyName: index.index_name,
167
- unique: index.is_unique,
168
- primary: index.is_primary_key,
169
- constraint: index.is_unique,
170
- };
171
- // Capture INCLUDE columns
172
- if (isIncluded) {
173
- indexDef.include = [index.column_name];
174
- }
175
- // Capture sort order for key columns
176
- if (!isIncluded && index.is_descending_key) {
177
- indexDef.columns = [{ name: index.column_name, sort: 'DESC' }];
178
- }
179
- // Capture disabled flag
180
- if (index.is_disabled) {
181
- indexDef.disabled = true;
182
- }
183
- // Capture clustered flag (type 1 = clustered)
184
- if (index.index_type === 1 && !index.is_primary_key) {
185
- indexDef.clustered = true;
186
- }
187
- // Capture fill factor (0 means default, so only set if non-zero)
188
- if (index.fill_factor > 0) {
189
- indexDef.fillFactor = index.fill_factor;
190
- }
191
- if (index.column_name?.match(/[(): ,"'`]/) || index.expression?.match(/where /i)) {
192
- indexDef.expression = index.expression; // required for the `getCreateIndexSQL()` call
193
- indexDef.expression = this.getCreateIndexSQL(index.table_name, indexDef, !!index.expression);
194
- }
195
- ret[key] ??= [];
196
- ret[key].push(indexDef);
197
- }
198
- for (const key of Object.keys(ret)) {
199
- ret[key] = await this.mapIndexes(ret[key]);
200
- }
201
- return ret;
202
- }
203
- mapForeignKeys(fks, tableName, schemaName) {
204
- const ret = super.mapForeignKeys(fks, tableName, schemaName);
205
- for (const fk of Utils.values(ret)) {
206
- fk.columnNames = Utils.unique(fk.columnNames);
207
- fk.referencedColumnNames = Utils.unique(fk.referencedColumnNames);
208
- }
209
- return ret;
210
- }
211
- async getAllForeignKeys(connection, tablesBySchemas) {
212
- const sql = `select ccu.constraint_name, ccu.table_name, ccu.table_schema schema_name, ccu.column_name,
159
+ const allIndexes = await connection.execute(sql);
160
+ const ret = {};
161
+ for (const index of allIndexes) {
162
+ const key = this.getTableKey(index);
163
+ const isIncluded = index.is_included_column;
164
+ const indexDef = {
165
+ columnNames: isIncluded ? [] : [index.column_name],
166
+ keyName: index.index_name,
167
+ unique: index.is_unique,
168
+ primary: index.is_primary_key,
169
+ constraint: index.is_unique,
170
+ };
171
+ // Capture INCLUDE columns
172
+ if (isIncluded) {
173
+ indexDef.include = [index.column_name];
174
+ }
175
+ // Capture sort order for key columns
176
+ if (!isIncluded && index.is_descending_key) {
177
+ indexDef.columns = [{ name: index.column_name, sort: 'DESC' }];
178
+ }
179
+ // Capture disabled flag
180
+ if (index.is_disabled) {
181
+ indexDef.disabled = true;
182
+ }
183
+ // Capture clustered flag (type 1 = clustered)
184
+ if (index.index_type === 1 && !index.is_primary_key) {
185
+ indexDef.clustered = true;
186
+ }
187
+ // Capture fill factor (0 means default, so only set if non-zero)
188
+ if (index.fill_factor > 0) {
189
+ indexDef.fillFactor = index.fill_factor;
190
+ }
191
+ if (index.column_name?.match(/[(): ,"'`]/) || index.expression?.match(/where /i)) {
192
+ indexDef.expression = index.expression; // required for the `getCreateIndexSQL()` call
193
+ indexDef.expression = this.getCreateIndexSQL(index.table_name, indexDef, !!index.expression);
194
+ }
195
+ ret[key] ??= [];
196
+ ret[key].push(indexDef);
197
+ }
198
+ for (const key of Object.keys(ret)) {
199
+ ret[key] = await this.mapIndexes(ret[key]);
200
+ }
201
+ return ret;
202
+ }
203
+ mapForeignKeys(fks, tableName, schemaName) {
204
+ const ret = super.mapForeignKeys(fks, tableName, schemaName);
205
+ for (const fk of Utils.values(ret)) {
206
+ fk.columnNames = Utils.unique(fk.columnNames);
207
+ fk.referencedColumnNames = Utils.unique(fk.referencedColumnNames);
208
+ }
209
+ return ret;
210
+ }
211
+ async getAllForeignKeys(connection, tablesBySchemas) {
212
+ const sql = `select ccu.constraint_name, ccu.table_name, ccu.table_schema schema_name, ccu.column_name,
213
213
  kcu.constraint_schema referenced_schema_name,
214
214
  kcu.column_name referenced_column_name,
215
215
  kcu.table_name referenced_table_name,
@@ -220,40 +220,40 @@ export class MsSqlSchemaHelper extends SchemaHelper {
220
220
  inner join information_schema.key_column_usage kcu on kcu.constraint_name = rc.unique_constraint_name and rc.unique_constraint_schema = kcu.constraint_schema
221
221
  where (${[...tablesBySchemas.entries()].map(([schema, tables]) => `(ccu.table_name in (${tables.map(t => this.platform.quoteValue(t.table_name)).join(',')}) and ccu.table_schema = '${schema}')`).join(' or ')})
222
222
  order by kcu.table_schema, kcu.table_name, kcu.ordinal_position, kcu.constraint_name`;
223
- const allFks = await connection.execute(sql);
224
- const ret = {};
225
- for (const fk of allFks) {
226
- const key = this.getTableKey(fk);
227
- ret[key] ??= [];
228
- ret[key].push(fk);
229
- }
230
- Object.keys(ret).forEach(key => {
231
- const [schemaName, tableName] = key.split('.');
232
- ret[key] = this.mapForeignKeys(ret[key], tableName, schemaName);
233
- });
234
- return ret;
235
- }
236
- getEnumDefinitions(checks) {
237
- return checks.reduce((o, item, index) => {
238
- // check constraints are defined as
239
- // `([type]='owner' OR [type]='manager' OR [type]='employee')`
240
- const m1 = item.definition?.match(/^check \((.*)\)/);
241
- let items = m1?.[1].split(' OR ');
242
- /* v8 ignore next */
243
- const hasItems = (items?.length ?? 0) > 0;
244
- if (item.columnName && hasItems) {
245
- items = items
246
- .map(val => /^\(?'(.*)'/.exec(val.trim().replace(`[${item.columnName}]=`, ''))?.[1])
247
- .filter(Boolean);
248
- if (items.length > 0) {
249
- o[item.columnName] = items.reverse();
250
- }
251
- }
252
- return o;
253
- }, {});
254
- }
255
- getChecksSQL(tablesBySchemas) {
256
- return `select con.name as name,
223
+ const allFks = await connection.execute(sql);
224
+ const ret = {};
225
+ for (const fk of allFks) {
226
+ const key = this.getTableKey(fk);
227
+ ret[key] ??= [];
228
+ ret[key].push(fk);
229
+ }
230
+ Object.keys(ret).forEach(key => {
231
+ const [schemaName, tableName] = key.split('.');
232
+ ret[key] = this.mapForeignKeys(ret[key], tableName, schemaName);
233
+ });
234
+ return ret;
235
+ }
236
+ getEnumDefinitions(checks) {
237
+ return checks.reduce((o, item, index) => {
238
+ // check constraints are defined as
239
+ // `([type]='owner' OR [type]='manager' OR [type]='employee')`
240
+ const m1 = item.definition?.match(/^check \((.*)\)/);
241
+ let items = m1?.[1].split(' OR ');
242
+ /* v8 ignore next */
243
+ const hasItems = (items?.length ?? 0) > 0;
244
+ if (item.columnName && hasItems) {
245
+ items = items
246
+ .map(val => /^\(?'(.*)'/.exec(val.trim().replace(`[${item.columnName}]=`, ''))?.[1])
247
+ .filter(Boolean);
248
+ if (items.length > 0) {
249
+ o[item.columnName] = items.reverse();
250
+ }
251
+ }
252
+ return o;
253
+ }, {});
254
+ }
255
+ getChecksSQL(tablesBySchemas) {
256
+ return `select con.name as name,
257
257
  schema_name(t.schema_id) schema_name,
258
258
  t.name table_name,
259
259
  col.name column_name,
@@ -263,339 +263,324 @@ export class MsSqlSchemaHelper extends SchemaHelper {
263
263
  left outer join sys.all_columns col on con.parent_column_id = col.column_id and con.parent_object_id = col.object_id
264
264
  where (${[...tablesBySchemas.entries()].map(([schema, tables]) => `t.name in (${tables.map(t => this.platform.quoteValue(t.table_name)).join(',')}) and schema_name(t.schema_id) = '${schema}'`).join(' or ')})
265
265
  order by con.name`;
266
- }
267
- async getAllChecks(connection, tablesBySchemas) {
268
- const sql = this.getChecksSQL(tablesBySchemas);
269
- const allChecks = await connection.execute(sql);
270
- const ret = {};
271
- for (const check of allChecks) {
272
- const key = this.getTableKey(check);
273
- ret[key] ??= [];
274
- const expression = check.expression.replace(/^\((.*)\)$/, '$1');
275
- ret[key].push({
276
- name: check.name,
277
- columnName: check.column_name,
278
- definition: `check (${expression})`,
279
- expression,
280
- });
281
- }
282
- return ret;
283
- }
284
- async loadInformationSchema(schema, connection, tables) {
285
- if (tables.length === 0) {
286
- return;
287
- }
288
- const tablesBySchema = this.getTablesGroupedBySchemas(tables);
289
- const columns = await this.getAllColumns(connection, tablesBySchema);
290
- const indexes = await this.getAllIndexes(connection, tablesBySchema);
291
- const checks = await this.getAllChecks(connection, tablesBySchema);
292
- const fks = await this.getAllForeignKeys(connection, tablesBySchema);
293
- for (const t of tables) {
294
- const key = this.getTableKey(t);
295
- const table = schema.addTable(t.table_name, t.schema_name, t.table_comment);
296
- const pks = await this.getPrimaryKeys(connection, indexes[key], table.name, table.schema);
297
- const enums = this.getEnumDefinitions(checks[key] ?? []);
298
- table.init(columns[key], indexes[key], checks[key], pks, fks[key], enums);
299
- }
300
- }
301
- getPreAlterTable(tableDiff, safe) {
302
- const ret = [];
303
- const indexes = tableDiff.fromTable.getIndexes();
304
- const parts = tableDiff.name.split('.');
305
- const tableName = parts.pop();
306
- const schemaName = parts.pop();
307
- /* v8 ignore next */
308
- const name =
309
- (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
310
- const quotedName = this.quote(name);
311
- // indexes need to be first dropped to be able to change a column type
312
- const changedTypes = Object.values(tableDiff.changedColumns).filter(col => col.changedProperties.has('type'));
313
- for (const col of changedTypes) {
314
- for (const index of indexes) {
315
- if (index.columnNames.includes(col.column.name)) {
316
- ret.push(this.getDropIndexSQL(name, index));
317
- }
318
- }
319
- // convert to string first if it's not already a string or has a smaller length
320
- const type = this.platform.extractSimpleType(col.fromColumn.type);
321
- if (!['varchar', 'nvarchar', 'varbinary'].includes(type) || col.fromColumn.length < col.column.length) {
322
- ret.push(`alter table ${quotedName} alter column [${col.oldColumnName}] nvarchar(max)`);
323
- }
324
- }
325
- return ret;
326
- }
327
- getPostAlterTable(tableDiff, safe) {
328
- const ret = [];
329
- const indexes = tableDiff.fromTable.getIndexes();
330
- const parts = tableDiff.name.split('.');
331
- const tableName = parts.pop();
332
- const schemaName = parts.pop();
333
- /* v8 ignore next */
334
- const name =
335
- (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
336
- // indexes need to be first dropped to be able to change a column type
337
- const changedTypes = Object.values(tableDiff.changedColumns).filter(col => col.changedProperties.has('type'));
338
- for (const col of changedTypes) {
339
- for (const index of indexes) {
340
- if (index.columnNames.includes(col.column.name)) {
341
- this.append(ret, this.getCreateIndexSQL(name, index));
342
- }
343
- }
344
- }
345
- return ret;
346
- }
347
- getCreateNamespaceSQL(name) {
348
- return `if (schema_id(${this.platform.quoteValue(name)}) is null) begin exec ('create schema ${this.quote(name)} authorization [dbo]') end`;
349
- }
350
- getDropNamespaceSQL(name) {
351
- return `drop schema if exists ${this.quote(name)}`;
352
- }
353
- getDropIndexSQL(tableName, index) {
354
- return `drop index ${this.quote(index.keyName)} on ${this.quote(tableName)}`;
355
- }
356
- dropIndex(table, index, oldIndexName = index.keyName) {
357
- if (index.primary) {
358
- return `alter table ${this.quote(table)} drop constraint ${this.quote(oldIndexName)}`;
359
- }
360
- return `drop index ${this.quote(oldIndexName)} on ${this.quote(table)}`;
361
- }
362
- getDropColumnsSQL(tableName, columns, schemaName) {
363
- /* v8 ignore next */
364
- const tableNameRaw = this.quote(
365
- (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName,
366
- );
367
- const drops = [];
368
- const constraints = this.getDropDefaultsSQL(tableName, columns, schemaName);
369
- for (const column of columns) {
370
- drops.push(this.quote(column.name));
371
- }
372
- return `${constraints.join(';\n')};\nalter table ${tableNameRaw} drop column ${drops.join(', ')}`;
373
- }
374
- getDropDefaultsSQL(tableName, columns, schemaName) {
375
- /* v8 ignore next */
376
- const tableNameRaw = this.quote(
377
- (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName,
378
- );
379
- const constraints = [];
380
- schemaName ??= this.platform.getDefaultSchemaName();
381
- for (const column of columns) {
382
- if (column.defaultConstraint) {
383
- constraints.push(`alter table ${tableNameRaw} drop constraint ${this.quote(column.defaultConstraint)}`);
384
- continue;
385
- }
386
- const i = globalThis.idx;
387
- globalThis.idx++;
388
- constraints.push(
389
- `declare @constraint${i} varchar(100) = (select default_constraints.name from sys.all_columns` +
390
- ' join sys.tables on all_columns.object_id = tables.object_id' +
391
- ' join sys.schemas on tables.schema_id = schemas.schema_id' +
392
- ' join sys.default_constraints on all_columns.default_object_id = default_constraints.object_id' +
393
- ` where schemas.name = '${schemaName}' and tables.name = '${tableName}' and all_columns.name = '${column.name}')` +
394
- ` if @constraint${i} is not null exec('alter table ${tableNameRaw} drop constraint ' + @constraint${i})`,
395
- );
396
- }
397
- return constraints;
398
- }
399
- getRenameColumnSQL(tableName, oldColumnName, to, schemaName) {
400
- /* v8 ignore next */
401
- const oldName =
402
- (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') +
403
- tableName +
404
- '.' +
405
- oldColumnName;
406
- const columnName = this.platform.quoteValue(to.name);
407
- return `exec sp_rename ${this.platform.quoteValue(oldName)}, ${columnName}, 'COLUMN'`;
408
- }
409
- createTableColumn(column, table, changedProperties) {
410
- const compositePK = table.getPrimaryKey()?.composite;
411
- const primaryKey = !changedProperties && !this.hasNonDefaultPrimaryKeyName(table);
412
- const columnType = column.generated ? `as ${column.generated}` : column.type;
413
- const col = [this.quote(column.name)];
414
- if (
415
- column.autoincrement &&
416
- !column.generated &&
417
- !compositePK &&
418
- (!changedProperties || changedProperties.has('autoincrement') || changedProperties.has('type'))
419
- ) {
420
- col.push(column.mappedType.getColumnType({ autoincrement: true }, this.platform));
421
- } else {
422
- col.push(columnType);
423
- }
424
- Utils.runIfNotEmpty(() => col.push('identity(1,1)'), column.autoincrement);
425
- Utils.runIfNotEmpty(() => col.push('null'), column.nullable);
426
- Utils.runIfNotEmpty(() => col.push('not null'), !column.nullable && !column.generated);
427
- if (
428
- column.autoincrement &&
429
- !column.generated &&
430
- !compositePK &&
431
- (!changedProperties || changedProperties.has('autoincrement') || changedProperties.has('type'))
432
- ) {
433
- Utils.runIfNotEmpty(() => col.push('primary key'), primaryKey && column.primary);
434
- }
435
- const useDefault = changedProperties
436
- ? false
437
- : column.default != null && column.default !== 'null' && !column.autoincrement;
438
- const defaultName = this.platform.getConfig().getNamingStrategy().indexName(table.name, [column.name], 'default');
439
- Utils.runIfNotEmpty(() => col.push(`constraint ${this.quote(defaultName)} default ${column.default}`), useDefault);
440
- return col.join(' ');
441
- }
442
- alterTableColumn(column, table, changedProperties) {
443
- const parts = [];
444
- if (changedProperties.has('default')) {
445
- const [constraint] = this.getDropDefaultsSQL(table.name, [column], table.schema);
446
- parts.push(constraint);
447
- }
448
- if (changedProperties.has('type') || changedProperties.has('nullable')) {
449
- const col = this.createTableColumn(column, table, changedProperties);
450
- parts.push(`alter table ${table.getQuotedName()} alter column ${col}`);
451
- }
452
- if (changedProperties.has('default') && column.default != null) {
453
- const defaultName = this.platform.getConfig().getNamingStrategy().indexName(table.name, [column.name], 'default');
454
- parts.push(
455
- `alter table ${table.getQuotedName()} add constraint ${this.quote(defaultName)} default ${column.default} for ${this.quote(column.name)}`,
456
- );
457
- }
458
- return parts;
459
- }
460
- getCreateIndexSQL(tableName, index, partialExpression = false) {
461
- /* v8 ignore next */
462
- if (index.expression && !partialExpression) {
463
- return index.expression;
464
- }
465
- if (index.fillFactor != null && (index.fillFactor < 0 || index.fillFactor > 100)) {
466
- throw new Error(`fillFactor must be between 0 and 100, got ${index.fillFactor} for index '${index.keyName}'`);
467
- }
468
- const keyName = this.quote(index.keyName);
469
- // Only add clustered keyword when explicitly requested, otherwise omit (defaults to nonclustered)
470
- const clustered = index.clustered ? 'clustered ' : '';
471
- let sql = `create ${index.unique ? 'unique ' : ''}${clustered}index ${keyName} on ${this.quote(tableName)} `;
472
- if (index.expression && partialExpression) {
473
- return sql + `(${index.expression})` + this.getMsSqlIndexSuffix(index);
474
- }
475
- // Build column list with advanced options
476
- const columns = this.getIndexColumns(index);
477
- sql += `(${columns})`;
478
- // Add INCLUDE clause for covering indexes
479
- if (index.include?.length) {
480
- sql += ` include (${index.include.map(c => this.quote(c)).join(', ')})`;
481
- }
482
- sql += this.getMsSqlIndexSuffix(index);
483
- // Disabled indexes need to be created first, then disabled
484
- if (index.disabled) {
485
- sql += `;\nalter index ${keyName} on ${this.quote(tableName)} disable`;
486
- }
487
- return sql;
488
- }
489
- /**
490
- * Build the column list for a MSSQL index.
491
- */
492
- getIndexColumns(index) {
493
- if (index.columns?.length) {
494
- return index.columns
495
- .map(col => {
496
- let colDef = this.quote(col.name);
497
- // MSSQL supports sort order
498
- if (col.sort) {
499
- colDef += ` ${col.sort}`;
500
- }
501
- return colDef;
266
+ }
267
+ async getAllChecks(connection, tablesBySchemas) {
268
+ const sql = this.getChecksSQL(tablesBySchemas);
269
+ const allChecks = await connection.execute(sql);
270
+ const ret = {};
271
+ for (const check of allChecks) {
272
+ const key = this.getTableKey(check);
273
+ ret[key] ??= [];
274
+ const expression = check.expression.replace(/^\((.*)\)$/, '$1');
275
+ ret[key].push({
276
+ name: check.name,
277
+ columnName: check.column_name,
278
+ definition: `check (${expression})`,
279
+ expression,
280
+ });
281
+ }
282
+ return ret;
283
+ }
284
+ async loadInformationSchema(schema, connection, tables) {
285
+ if (tables.length === 0) {
286
+ return;
287
+ }
288
+ const tablesBySchema = this.getTablesGroupedBySchemas(tables);
289
+ const columns = await this.getAllColumns(connection, tablesBySchema);
290
+ const indexes = await this.getAllIndexes(connection, tablesBySchema);
291
+ const checks = await this.getAllChecks(connection, tablesBySchema);
292
+ const fks = await this.getAllForeignKeys(connection, tablesBySchema);
293
+ for (const t of tables) {
294
+ const key = this.getTableKey(t);
295
+ const table = schema.addTable(t.table_name, t.schema_name, t.table_comment);
296
+ const pks = await this.getPrimaryKeys(connection, indexes[key], table.name, table.schema);
297
+ const enums = this.getEnumDefinitions(checks[key] ?? []);
298
+ table.init(columns[key], indexes[key], checks[key], pks, fks[key], enums);
299
+ }
300
+ }
301
+ getPreAlterTable(tableDiff, safe) {
302
+ const ret = [];
303
+ const indexes = tableDiff.fromTable.getIndexes();
304
+ const parts = tableDiff.name.split('.');
305
+ const tableName = parts.pop();
306
+ const schemaName = parts.pop();
307
+ /* v8 ignore next */
308
+ const name = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
309
+ const quotedName = this.quote(name);
310
+ // indexes need to be first dropped to be able to change a column type
311
+ const changedTypes = Object.values(tableDiff.changedColumns).filter(col => col.changedProperties.has('type'));
312
+ for (const col of changedTypes) {
313
+ for (const index of indexes) {
314
+ if (index.columnNames.includes(col.column.name)) {
315
+ ret.push(this.getDropIndexSQL(name, index));
316
+ }
317
+ }
318
+ // convert to string first if it's not already a string or has a smaller length
319
+ const type = this.platform.extractSimpleType(col.fromColumn.type);
320
+ if (!['varchar', 'nvarchar', 'varbinary'].includes(type) || col.fromColumn.length < col.column.length) {
321
+ ret.push(`alter table ${quotedName} alter column [${col.oldColumnName}] nvarchar(max)`);
322
+ }
323
+ }
324
+ return ret;
325
+ }
326
+ getPostAlterTable(tableDiff, safe) {
327
+ const ret = [];
328
+ const indexes = tableDiff.fromTable.getIndexes();
329
+ const parts = tableDiff.name.split('.');
330
+ const tableName = parts.pop();
331
+ const schemaName = parts.pop();
332
+ /* v8 ignore next */
333
+ const name = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
334
+ // indexes need to be first dropped to be able to change a column type
335
+ const changedTypes = Object.values(tableDiff.changedColumns).filter(col => col.changedProperties.has('type'));
336
+ for (const col of changedTypes) {
337
+ for (const index of indexes) {
338
+ if (index.columnNames.includes(col.column.name)) {
339
+ this.append(ret, this.getCreateIndexSQL(name, index));
340
+ }
341
+ }
342
+ }
343
+ return ret;
344
+ }
345
+ getCreateNamespaceSQL(name) {
346
+ return `if (schema_id(${this.platform.quoteValue(name)}) is null) begin exec ('create schema ${this.quote(name)} authorization [dbo]') end`;
347
+ }
348
+ getDropNamespaceSQL(name) {
349
+ return `drop schema if exists ${this.quote(name)}`;
350
+ }
351
+ getDropIndexSQL(tableName, index) {
352
+ return `drop index ${this.quote(index.keyName)} on ${this.quote(tableName)}`;
353
+ }
354
+ dropIndex(table, index, oldIndexName = index.keyName) {
355
+ if (index.primary) {
356
+ return `alter table ${this.quote(table)} drop constraint ${this.quote(oldIndexName)}`;
357
+ }
358
+ return `drop index ${this.quote(oldIndexName)} on ${this.quote(table)}`;
359
+ }
360
+ getDropColumnsSQL(tableName, columns, schemaName) {
361
+ /* v8 ignore next */
362
+ const tableNameRaw = this.quote((schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName);
363
+ const drops = [];
364
+ const constraints = this.getDropDefaultsSQL(tableName, columns, schemaName);
365
+ for (const column of columns) {
366
+ drops.push(this.quote(column.name));
367
+ }
368
+ return `${constraints.join(';\n')};\nalter table ${tableNameRaw} drop column ${drops.join(', ')}`;
369
+ }
370
+ getDropDefaultsSQL(tableName, columns, schemaName) {
371
+ /* v8 ignore next */
372
+ const tableNameRaw = this.quote((schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName);
373
+ const constraints = [];
374
+ schemaName ??= this.platform.getDefaultSchemaName();
375
+ for (const column of columns) {
376
+ if (column.defaultConstraint) {
377
+ constraints.push(`alter table ${tableNameRaw} drop constraint ${this.quote(column.defaultConstraint)}`);
378
+ continue;
379
+ }
380
+ const i = globalThis.idx;
381
+ globalThis.idx++;
382
+ constraints.push(`declare @constraint${i} varchar(100) = (select default_constraints.name from sys.all_columns` +
383
+ ' join sys.tables on all_columns.object_id = tables.object_id' +
384
+ ' join sys.schemas on tables.schema_id = schemas.schema_id' +
385
+ ' join sys.default_constraints on all_columns.default_object_id = default_constraints.object_id' +
386
+ ` where schemas.name = '${schemaName}' and tables.name = '${tableName}' and all_columns.name = '${column.name}')` +
387
+ ` if @constraint${i} is not null exec('alter table ${tableNameRaw} drop constraint ' + @constraint${i})`);
388
+ }
389
+ return constraints;
390
+ }
391
+ getRenameColumnSQL(tableName, oldColumnName, to, schemaName) {
392
+ /* v8 ignore next */
393
+ const oldName = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') +
394
+ tableName +
395
+ '.' +
396
+ oldColumnName;
397
+ const columnName = this.platform.quoteValue(to.name);
398
+ return `exec sp_rename ${this.platform.quoteValue(oldName)}, ${columnName}, 'COLUMN'`;
399
+ }
400
+ createTableColumn(column, table, changedProperties) {
401
+ const compositePK = table.getPrimaryKey()?.composite;
402
+ const primaryKey = !changedProperties && !this.hasNonDefaultPrimaryKeyName(table);
403
+ const columnType = column.generated ? `as ${column.generated}` : column.type;
404
+ const col = [this.quote(column.name)];
405
+ if (column.autoincrement &&
406
+ !column.generated &&
407
+ !compositePK &&
408
+ (!changedProperties || changedProperties.has('autoincrement') || changedProperties.has('type'))) {
409
+ col.push(column.mappedType.getColumnType({ autoincrement: true }, this.platform));
410
+ }
411
+ else {
412
+ col.push(columnType);
413
+ }
414
+ Utils.runIfNotEmpty(() => col.push('identity(1,1)'), column.autoincrement);
415
+ Utils.runIfNotEmpty(() => col.push('null'), column.nullable);
416
+ Utils.runIfNotEmpty(() => col.push('not null'), !column.nullable && !column.generated);
417
+ if (column.autoincrement &&
418
+ !column.generated &&
419
+ !compositePK &&
420
+ (!changedProperties || changedProperties.has('autoincrement') || changedProperties.has('type'))) {
421
+ Utils.runIfNotEmpty(() => col.push('primary key'), primaryKey && column.primary);
422
+ }
423
+ const useDefault = changedProperties
424
+ ? false
425
+ : column.default != null && column.default !== 'null' && !column.autoincrement;
426
+ const defaultName = this.platform.getConfig().getNamingStrategy().indexName(table.name, [column.name], 'default');
427
+ Utils.runIfNotEmpty(() => col.push(`constraint ${this.quote(defaultName)} default ${column.default}`), useDefault);
428
+ return col.join(' ');
429
+ }
430
+ alterTableColumn(column, table, changedProperties) {
431
+ const parts = [];
432
+ if (changedProperties.has('default')) {
433
+ const [constraint] = this.getDropDefaultsSQL(table.name, [column], table.schema);
434
+ parts.push(constraint);
435
+ }
436
+ if (changedProperties.has('type') || changedProperties.has('nullable')) {
437
+ const col = this.createTableColumn(column, table, changedProperties);
438
+ parts.push(`alter table ${table.getQuotedName()} alter column ${col}`);
439
+ }
440
+ if (changedProperties.has('default') && column.default != null) {
441
+ const defaultName = this.platform.getConfig().getNamingStrategy().indexName(table.name, [column.name], 'default');
442
+ parts.push(`alter table ${table.getQuotedName()} add constraint ${this.quote(defaultName)} default ${column.default} for ${this.quote(column.name)}`);
443
+ }
444
+ return parts;
445
+ }
446
+ getCreateIndexSQL(tableName, index, partialExpression = false) {
447
+ /* v8 ignore next */
448
+ if (index.expression && !partialExpression) {
449
+ return index.expression;
450
+ }
451
+ if (index.fillFactor != null && (index.fillFactor < 0 || index.fillFactor > 100)) {
452
+ throw new Error(`fillFactor must be between 0 and 100, got ${index.fillFactor} for index '${index.keyName}'`);
453
+ }
454
+ const keyName = this.quote(index.keyName);
455
+ // Only add clustered keyword when explicitly requested, otherwise omit (defaults to nonclustered)
456
+ const clustered = index.clustered ? 'clustered ' : '';
457
+ let sql = `create ${index.unique ? 'unique ' : ''}${clustered}index ${keyName} on ${this.quote(tableName)} `;
458
+ if (index.expression && partialExpression) {
459
+ return sql + `(${index.expression})` + this.getMsSqlIndexSuffix(index);
460
+ }
461
+ // Build column list with advanced options
462
+ const columns = this.getIndexColumns(index);
463
+ sql += `(${columns})`;
464
+ // Add INCLUDE clause for covering indexes
465
+ if (index.include?.length) {
466
+ sql += ` include (${index.include.map(c => this.quote(c)).join(', ')})`;
467
+ }
468
+ sql += this.getMsSqlIndexSuffix(index);
469
+ // Disabled indexes need to be created first, then disabled
470
+ if (index.disabled) {
471
+ sql += `;\nalter index ${keyName} on ${this.quote(tableName)} disable`;
472
+ }
473
+ return sql;
474
+ }
475
+ /**
476
+ * Build the column list for a MSSQL index.
477
+ */
478
+ getIndexColumns(index) {
479
+ if (index.columns?.length) {
480
+ return index.columns
481
+ .map(col => {
482
+ let colDef = this.quote(col.name);
483
+ // MSSQL supports sort order
484
+ if (col.sort) {
485
+ colDef += ` ${col.sort}`;
486
+ }
487
+ return colDef;
488
+ })
489
+ .join(', ');
490
+ }
491
+ return index.columnNames.map(c => this.quote(c)).join(', ');
492
+ }
493
+ /**
494
+ * Get MSSQL-specific index WITH options like fill factor.
495
+ */
496
+ getMsSqlIndexSuffix(index) {
497
+ const withOptions = [];
498
+ if (index.fillFactor != null) {
499
+ withOptions.push(`fillfactor = ${index.fillFactor}`);
500
+ }
501
+ if (withOptions.length > 0) {
502
+ return ` with (${withOptions.join(', ')})`;
503
+ }
504
+ return '';
505
+ }
506
+ createIndex(index, table, createPrimary = false) {
507
+ if (index.primary) {
508
+ return '';
509
+ }
510
+ if (index.expression) {
511
+ return index.expression;
512
+ }
513
+ const needsWhereClause = index.unique && index.columnNames.some(column => table.getColumn(column)?.nullable);
514
+ if (!needsWhereClause) {
515
+ return this.getCreateIndexSQL(table.getShortestName(), index);
516
+ }
517
+ // Generate without disabled suffix, insert WHERE clause, then re-add disabled
518
+ let sql = this.getCreateIndexSQL(table.getShortestName(), { ...index, disabled: false });
519
+ sql += ' where ' + index.columnNames.map(c => `${this.quote(c)} is not null`).join(' and ');
520
+ if (index.disabled) {
521
+ sql += `;\nalter index ${this.quote(index.keyName)} on ${table.getQuotedName()} disable`;
522
+ }
523
+ return sql;
524
+ }
525
+ dropForeignKey(tableName, constraintName) {
526
+ return `alter table ${this.quote(tableName)} drop constraint ${this.quote(constraintName)}`;
527
+ }
528
+ dropTableIfExists(name, schema) {
529
+ if (schema === this.platform.getDefaultSchemaName()) {
530
+ schema = undefined;
531
+ }
532
+ return `if object_id('${this.quote(schema, name)}', 'U') is not null drop table ${this.quote(schema, name)}`;
533
+ }
534
+ dropViewIfExists(name, schema) {
535
+ const viewName = this.quote(this.getTableName(name, schema));
536
+ return `if object_id('${viewName}', 'V') is not null drop view ${viewName}`;
537
+ }
538
+ getAddColumnsSQL(table, columns) {
539
+ const adds = columns
540
+ .map(column => {
541
+ return this.createTableColumn(column, table);
502
542
  })
503
- .join(', ');
504
- }
505
- return index.columnNames.map(c => this.quote(c)).join(', ');
506
- }
507
- /**
508
- * Get MSSQL-specific index WITH options like fill factor.
509
- */
510
- getMsSqlIndexSuffix(index) {
511
- const withOptions = [];
512
- if (index.fillFactor != null) {
513
- withOptions.push(`fillfactor = ${index.fillFactor}`);
514
- }
515
- if (withOptions.length > 0) {
516
- return ` with (${withOptions.join(', ')})`;
517
- }
518
- return '';
519
- }
520
- createIndex(index, table, createPrimary = false) {
521
- if (index.primary) {
522
- return '';
523
- }
524
- if (index.expression) {
525
- return index.expression;
526
- }
527
- const needsWhereClause = index.unique && index.columnNames.some(column => table.getColumn(column)?.nullable);
528
- if (!needsWhereClause) {
529
- return this.getCreateIndexSQL(table.getShortestName(), index);
530
- }
531
- // Generate without disabled suffix, insert WHERE clause, then re-add disabled
532
- let sql = this.getCreateIndexSQL(table.getShortestName(), { ...index, disabled: false });
533
- sql += ' where ' + index.columnNames.map(c => `${this.quote(c)} is not null`).join(' and ');
534
- if (index.disabled) {
535
- sql += `;\nalter index ${this.quote(index.keyName)} on ${table.getQuotedName()} disable`;
536
- }
537
- return sql;
538
- }
539
- dropForeignKey(tableName, constraintName) {
540
- return `alter table ${this.quote(tableName)} drop constraint ${this.quote(constraintName)}`;
541
- }
542
- dropTableIfExists(name, schema) {
543
- if (schema === this.platform.getDefaultSchemaName()) {
544
- schema = undefined;
545
- }
546
- return `if object_id('${this.quote(schema, name)}', 'U') is not null drop table ${this.quote(schema, name)}`;
547
- }
548
- dropViewIfExists(name, schema) {
549
- const viewName = this.quote(this.getTableName(name, schema));
550
- return `if object_id('${viewName}', 'V') is not null drop view ${viewName}`;
551
- }
552
- getAddColumnsSQL(table, columns) {
553
- const adds = columns
554
- .map(column => {
555
- return this.createTableColumn(column, table);
556
- })
557
- .join(', ');
558
- return [`alter table ${table.getQuotedName()} add ${adds}`];
559
- }
560
- appendComments(table) {
561
- const sql = [];
562
- const schema = this.platform.quoteValue(table.schema);
563
- const tableName = this.platform.quoteValue(table.name);
564
- if (table.comment) {
565
- const comment = this.platform.quoteValue(table.comment);
566
- sql.push(`if exists(select * from sys.fn_listextendedproperty(N'MS_Description', N'Schema', N${schema}, N'Table', N${tableName}, null, null))
543
+ .join(', ');
544
+ return [`alter table ${table.getQuotedName()} add ${adds}`];
545
+ }
546
+ appendComments(table) {
547
+ const sql = [];
548
+ const schema = this.platform.quoteValue(table.schema);
549
+ const tableName = this.platform.quoteValue(table.name);
550
+ if (table.comment) {
551
+ const comment = this.platform.quoteValue(table.comment);
552
+ sql.push(`if exists(select * from sys.fn_listextendedproperty(N'MS_Description', N'Schema', N${schema}, N'Table', N${tableName}, null, null))
567
553
  exec sys.sp_updateextendedproperty N'MS_Description', N${comment}, N'Schema', N${schema}, N'Table', N${tableName}
568
554
  else
569
555
  exec sys.sp_addextendedproperty N'MS_Description', N${comment}, N'Schema', N${schema}, N'Table', N${tableName}`);
570
- }
571
- for (const column of table.getColumns()) {
572
- if (column.comment) {
573
- const comment = this.platform.quoteValue(column.comment);
574
- const columnName = this.platform.quoteValue(column.name);
575
- sql.push(`if exists(select * from sys.fn_listextendedproperty(N'MS_Description', N'Schema', N${schema}, N'Table', N${tableName}, N'Column', N${columnName}))
556
+ }
557
+ for (const column of table.getColumns()) {
558
+ if (column.comment) {
559
+ const comment = this.platform.quoteValue(column.comment);
560
+ const columnName = this.platform.quoteValue(column.name);
561
+ sql.push(`if exists(select * from sys.fn_listextendedproperty(N'MS_Description', N'Schema', N${schema}, N'Table', N${tableName}, N'Column', N${columnName}))
576
562
  exec sys.sp_updateextendedproperty N'MS_Description', N${comment}, N'Schema', N${schema}, N'Table', N${tableName}, N'Column', N${columnName}
577
563
  else
578
564
  exec sys.sp_addextendedproperty N'MS_Description', N${comment}, N'Schema', N${schema}, N'Table', N${tableName}, N'Column', N${columnName}`);
579
- }
580
- }
581
- return sql;
582
- }
583
- inferLengthFromColumnType(type) {
584
- const match = /^(\w+)\s*\(\s*(-?\d+|max)\s*\)/.exec(type);
585
- if (!match) {
586
- return;
587
- }
588
- if (match[2] === 'max') {
589
- return -1;
590
- }
591
- return +match[2];
592
- }
593
- wrap(val, type) {
594
- const stringType =
595
- type instanceof StringType ||
596
- type instanceof TextType ||
597
- type instanceof EnumType ||
598
- type instanceof UnicodeStringType;
599
- return typeof val === 'string' && val.length > 0 && stringType ? this.platform.quoteValue(val) : val;
600
- }
565
+ }
566
+ }
567
+ return sql;
568
+ }
569
+ inferLengthFromColumnType(type) {
570
+ const match = /^(\w+)\s*\(\s*(-?\d+|max)\s*\)/.exec(type);
571
+ if (!match) {
572
+ return;
573
+ }
574
+ if (match[2] === 'max') {
575
+ return -1;
576
+ }
577
+ return +match[2];
578
+ }
579
+ wrap(val, type) {
580
+ const stringType = type instanceof StringType ||
581
+ type instanceof TextType ||
582
+ type instanceof EnumType ||
583
+ type instanceof UnicodeStringType;
584
+ return typeof val === 'string' && val.length > 0 && stringType ? this.platform.quoteValue(val) : val;
585
+ }
601
586
  }