/
mssql.spec.js
391 lines (344 loc) · 14.2 KB
/
mssql.spec.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
const { expect } = require('chai');
const { getAllDbs, getKnexForDb } = require('../util/knex-instance-provider');
async function fetchDefaultConstraint(knex, table, column) {
const [result] = await knex.schema.raw(`
SELECT default_constraints.name, default_constraints.definition
FROM sys.all_columns
INNER JOIN sys.tables
ON all_columns.object_id = tables.object_id
INNER JOIN sys.schemas
ON tables.schema_id = schemas.schema_id
INNER JOIN sys.default_constraints
ON all_columns.default_object_id = default_constraints.object_id
WHERE schemas.name = 'dbo'
AND tables.name = '${table}'
AND all_columns.name = '${column}'
`);
return result || { name: null, definition: null };
}
describe('MSSQL dialect', () => {
getAllDbs()
.filter((db) => db.startsWith('mssql'))
.forEach((db) => {
describe(db, () => {
let knex;
before(async () => {
knex = getKnexForDb(db);
});
beforeEach(async () => {
await knex.schema.createTable('test', function () {
this.increments('id').primary();
});
});
after(async () => {
await knex.destroy();
});
afterEach(async () => {
await knex.schema.dropTable('test');
});
describe('column default handling', () => {
describe('changing default value', () => {
beforeEach(async () => {
await knex.schema.alterTable('test', function () {
this.string('name').defaultTo('test');
});
});
it('can change the default value', async () => {
await knex.schema.alterTable('test', function () {
this.string('name').defaultTo('test2').alter();
});
const { definition } = await fetchDefaultConstraint(
knex,
'test',
'name'
);
expect(definition).to.equal("('test2')");
});
});
it('names default constraint', async () => {
await knex.schema.alterTable('test', function () {
this.string('name').defaultTo('knex');
});
const { name } = await fetchDefaultConstraint(knex, 'test', 'name');
expect(name).to.equal('test_name_default');
});
it('names default constraint with supplied name', async () => {
const constraintName = 'DF_test_name';
await knex.schema.alterTable('test', function () {
this.string('name').defaultTo('knex', { constraintName });
});
const { name } = await fetchDefaultConstraint(knex, 'test', 'name');
expect(name).to.equal('DF_test_name');
});
it("doesn't name default constraint", async () => {
const constraintName = '';
await knex.schema.alterTable('test', function () {
this.string('name').defaultTo('knex', { constraintName });
});
const { name } = await fetchDefaultConstraint(knex, 'test', 'name');
// this is the default patten used by mssql if no constraint is defined
expect(name).to.match(/^DF__test__name__[0-9A-Z]+$/);
});
});
describe('comment limits', () => {
// NOTE: We are using varchar, not nvarchar, so we can hit an odd number of bytes with our characters.
const byteCount0 = "''";
const byteCount7500 = "'" + 'X'.repeat(7500) + "'";
const byteCountOver7500 = "'" + 'X'.repeat(7501) + "'";
const tableTarget = { schemaName: 'dbo', tableName: 'test' };
it('supports table comments of max 7500 bytes', async () => {
// 0 works
await expect(comment(knex, 'add', byteCount0, tableTarget)).to
.eventually.be.fulfilled;
// 7500 works
await expect(comment(knex, 'update', byteCount7500, tableTarget)).to
.eventually.be.fulfilled;
// Over 7500 fails
await expect(
comment(knex, 'update', byteCountOver7500, tableTarget)
).to.eventually.be.rejectedWith(
'The size associated with an extended property cannot be more than 7,500 bytes.'
);
});
const columnTarget = { ...tableTarget, columnName: 'id' };
it('supports column comments of max 7500 bytes', async () => {
// 0 works
await expect(comment(knex, 'add', byteCount0, columnTarget)).to
.eventually.be.fulfilled;
// 7500 works
await expect(comment(knex, 'update', byteCount7500, columnTarget))
.to.eventually.be.fulfilled;
// Over 7500 fails
await expect(
comment(knex, 'update', byteCountOver7500, columnTarget)
).to.eventually.be.rejectedWith(
'The size associated with an extended property cannot be more than 7,500 bytes.'
);
});
// Characters in the supplementary plane need 4 bytes in UTF-16.
// (They also happen to need 4 in UTF-8, so this estimate is a useful worst-case for a UTF-8 collation, as well.)
const N = 7500 / 4;
it(`worst-case allows at most ${N} characters with string length ${
2 * N
} in an nvarchar`, async () => {
const astralPlaneCharacter = '\u{1D306}';
const worstCaseComment = astralPlaneCharacter.repeat(N);
// This works out because characters outside the BMP are counted as having length 2 by JavaScript's string.
expect(worstCaseComment).to.have.property('length', 2 * N);
// This length is the "shortest (in string.length), longest (in byte length)" comment that will fit.
// Thus, for anything larger than 7500/2, we need to warn that the comment might be too many bytes.
const asNvarcharLiteral = (text) => `N'${text}'`;
await expect(
comment(
knex,
'add',
asNvarcharLiteral(worstCaseComment),
columnTarget
)
).to.eventually.be.fulfilled;
// One more JS char (2 more bytes) is too much!
const oneMoreCharIsTooMuch = 'X' + worstCaseComment;
expect(oneMoreCharIsTooMuch).to.have.property('length', 2 * N + 1);
await expect(
comment(
knex,
'update',
asNvarcharLiteral(oneMoreCharIsTooMuch),
columnTarget
)
).to.eventually.be.rejectedWith(
'The size associated with an extended property cannot be more than 7,500 bytes.'
);
});
});
describe('unique table index with options object', () => {
const tableName = 'test_unique_index_options';
before(async () => {
await knex.schema.createTable(tableName, function () {
this.integer('x').notNull();
this.integer('y').notNull();
});
});
after(async () => {
await knex.schema.dropTable(tableName);
});
it('accepts indexName in options object', async () => {
const indexName = `AK_${tableName}_x_y`;
await knex.schema.alterTable(tableName, function () {
this.unique(['x', 'y'], { indexName });
});
expect(
knex
.insert([
{ x: 1, y: 1 },
{ x: 1, y: 1 },
])
.into(tableName)
).to.eventually.be.rejectedWith(new RegExp(indexName));
});
});
describe('unique table constraint with options object', () => {
const tableName = 'test_unique_constraint_options';
before(async () => {
await knex.schema.createTable(tableName, function () {
this.integer('x').notNull();
this.integer('y').notNull();
});
});
after(async () => {
await knex.schema.dropTable(tableName);
});
it('accepts indexName and constraint in options object', async () => {
const indexName = `UK_${tableName}_x_y`;
await knex.schema.alterTable(tableName, function () {
this.unique(['x', 'y'], {
indexName: indexName,
constraint: true,
});
});
expect(
knex
.insert([
{ x: 1, y: 1 },
{ x: 1, y: 1 },
])
.into(tableName)
).to.eventually.be.rejectedWith(new RegExp(indexName));
});
});
describe('comment support', () => {
const schemaName = 'dbo';
const tableName = 'test_attaches_comments';
const columnName = 'column_with_comment';
const columnWithoutComment = 'column_without_comment';
// Comments intentionally include single quotes, which require escaping in strings.
const tableComment = "table's comment";
const columnComment = "``column comment''";
const tableWithoutComment = 'table_without_comment';
before(async () => {
await knex.schema.createTable(tableName, function () {
this.comment(tableComment);
this.string(columnName).comment(columnComment);
this.string(columnWithoutComment);
});
await knex.schema.createTable(tableWithoutComment, function () {
this.increments();
});
});
after(async () => {
await knex.schema.dropTable(tableName);
await knex.schema.dropTable(tableWithoutComment);
});
it('attaches table comments', async () => {
const commentText = await commentFor(knex, {
schemaName,
tableName,
});
expect(commentText).to.equal(tableComment);
});
it('attaches column comments', async () => {
const commentText = await commentFor(knex, {
schemaName,
tableName,
columnName,
});
expect(commentText).to.equal(columnComment);
});
it('updates table comments', async () => {
const updatedTableComment = 'updated table comment';
await knex.schema.alterTable(tableName, function () {
this.comment(updatedTableComment);
});
const commentText = await commentFor(knex, {
schemaName,
tableName,
});
expect(commentText).to.equal(updatedTableComment);
});
it('updates column comments', async () => {
const updatedColumnComment = 'updated column comment';
await knex.schema.alterTable(tableName, function () {
this.string(columnName).comment(updatedColumnComment).alter();
});
const commentText = await commentFor(knex, {
schemaName,
tableName,
columnName,
});
expect(commentText).to.equal(updatedColumnComment);
});
it('adds column comments when altering and no pre-existing comment', async () => {
const expectedComment = 'well it has a comment now';
await knex.schema.alterTable(tableName, function () {
this.string(columnWithoutComment)
.comment(expectedComment)
.alter();
});
const commentText = await commentFor(knex, {
schemaName,
tableName,
columnName: columnWithoutComment,
});
expect(commentText).to.equal(expectedComment);
});
it('adds table comments when updating and no pre-existing comment', async () => {
const tableName = tableWithoutComment;
const expectedComment = 'comment';
await knex.schema.alterTable(tableName, function () {
this.comment(expectedComment);
});
const commentText = await commentFor(knex, {
schemaName,
tableName,
});
expect(commentText).to.equal(expectedComment);
});
/**
* Returns the comment for `target`, if any.
*
* @param {Knex} knex
* @param {{schemaName: string, tableName: string, columnName?: string}} target
* @returns {Promise<string|undefined>}
*/
async function commentFor(knex, target) {
const columnSpecifier = target.columnName
? `N'Column', :columnName`
: 'NULL, NULL';
const result = await knex
.from(
knex.raw(
`fn_listextendedproperty(N'MS_Description', N'Schema', :schemaName, N'Table', :tableName, ${columnSpecifier})`,
target
)
)
.select('value AS comment')
.first();
return result ? result.comment : undefined;
}
});
});
});
});
/**
*
* @param {Knex} knex
* @param {'add' | 'update' | 'drop'} action
* @param {string} rawQuotedComment No escaping is done. This should include any needed quote marks.
* @param {{schemaName: string, tableName: string, columnName?: string}} target
*/
const comment = async (knex, action, rawQuotedComment, target) => {
const { schemaName, tableName } = target;
// NOTE: This does not escape any embedded single quotes!
// (Since we control all the inputs here, we know we don't need to.)
const lines = [
`EXEC sp_${action}extendedproperty`,
" @name = N'MS_Description'",
action !== 'drop' ? `, @value = ${rawQuotedComment}` : '',
`, @level0type = N'Schema', @level0name = N'${schemaName}'`,
`, @level1type = N'Table', @level1name = N'${tableName}'`,
target.columnName !== undefined
? `, @level2type = N'Column', @level2name = N'${target.columnName}'`
: '',
];
return await knex.schema.raw(lines.join(''));
};