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