/
query-generator.js
810 lines (656 loc) · 25.7 KB
/
query-generator.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
'use strict';
import { underscore } from 'inflection';
import { rejectInvalidOptions } from '../../utils/check';
import { addTicks } from '../../utils/dialect';
import { Cast, Json, SequelizeMethod } from '../../utils/sequelize-method';
import { nameIndex, removeTrailingSemicolon } from '../../utils/string';
import { defaultValueSchemable } from '../../utils/query-builder-utils';
import { attributeTypeToSql, normalizeDataType } from '../abstract/data-types-utils';
import {
CREATE_SCHEMA_QUERY_SUPPORTABLE_OPTIONS,
DROP_TABLE_QUERY_SUPPORTABLE_OPTIONS,
ADD_COLUMN_QUERY_SUPPORTABLE_OPTIONS,
REMOVE_COLUMN_QUERY_SUPPORTABLE_OPTIONS,
} from '../abstract/query-generator';
const util = require('node:util');
const _ = require('lodash');
const { IBMiQueryGeneratorTypeScript } = require('./query-generator-typescript');
const DataTypes = require('../../data-types');
const { Model } = require('../../model');
const SqlString = require('../../sql-string');
const typeWithoutDefault = new Set(['BLOB']);
const CREATE_SCHEMA_QUERY_SUPPORTED_OPTIONS = new Set();
const DROP_TABLE_QUERY_SUPPORTED_OPTIONS = new Set();
const ADD_COLUMN_QUERY_SUPPORTED_OPTIONS = new Set();
const REMOVE_COLUMN_QUERY_SUPPORTED_OPTIONS = new Set();
export class IBMiQueryGenerator extends IBMiQueryGeneratorTypeScript {
// Version queries
versionQuery() {
return 'SELECT CONCAT(OS_VERSION, CONCAT(\'.\', OS_RELEASE)) AS VERSION FROM SYSIBMADM.ENV_SYS_INFO';
}
// Schema queries
createSchemaQuery(schema, options) {
if (options) {
rejectInvalidOptions(
'createSchemaQuery',
this.dialect.name,
CREATE_SCHEMA_QUERY_SUPPORTABLE_OPTIONS,
CREATE_SCHEMA_QUERY_SUPPORTED_OPTIONS,
options,
);
}
return `CREATE SCHEMA "${schema}"`;
}
dropSchemaQuery(schema) {
return `BEGIN IF EXISTS (SELECT * FROM SYSIBM.SQLSCHEMAS WHERE TABLE_SCHEM = ${schema ? `'${schema}'` : 'CURRENT SCHEMA'}) THEN SET TRANSACTION ISOLATION LEVEL NO COMMIT; DROP SCHEMA "${schema ? `${schema}` : 'CURRENT SCHEMA'}"; COMMIT; END IF; END`;
}
listSchemasQuery(options) {
let skippedSchemas = '';
if (options?.skip) {
for (let i = 0; i < options.skip.length; i++) {
skippedSchemas += ` AND SCHEMA_NAME != ${this.escape(options.skip[i])}`;
}
}
return `SELECT DISTINCT SCHEMA_NAME AS "schema_name" FROM QSYS2.SYSSCHEMAAUTH WHERE GRANTEE = CURRENT USER${skippedSchemas}`;
}
// Table queries
createTableQuery(tableName, attributes, options) {
const primaryKeys = [];
const foreignKeys = Object.create(null);
const attrStr = [];
for (const attr in attributes) {
if (!Object.prototype.hasOwnProperty.call(attributes, attr)) {
continue;
}
const dataType = attributes[attr];
if (dataType.includes('PRIMARY KEY')) {
primaryKeys.push(attr);
attrStr.push(`${this.quoteIdentifier(attr)} ${dataType.replace('PRIMARY KEY', '')}`);
} else {
attrStr.push(`${this.quoteIdentifier(attr)} ${dataType}`);
}
}
let attributesClause = attrStr.join(', ');
const pkString = primaryKeys.map(pk => this.quoteIdentifier(pk)).join(', ');
if (options.uniqueKeys) {
// only need to sort primary keys once, don't do it in place
const sortedPrimaryKeys = [...primaryKeys];
sortedPrimaryKeys.sort();
_.each(options.uniqueKeys, (columns, indexName) => {
// sort the columns for each unique key, so they can be easily compared
// with the sorted primary key fields
const sortedColumnFields = [...columns.fields];
sortedColumnFields.sort();
// if primary keys === unique keys, then skip adding new constraint
const uniqueIsPrimary
= sortedColumnFields.length === primaryKeys.length
&& sortedColumnFields.every((value, index) => {
return value === sortedPrimaryKeys[index];
});
if (uniqueIsPrimary) {
return true;
}
if (columns.customIndex) {
if (typeof indexName !== 'string') {
indexName = `uniq_${tableName}_${columns.fields.join('_')}`;
}
attributesClause += `, CONSTRAINT ${this.quoteIdentifier(indexName)} UNIQUE (${columns.fields.map(field => this.quoteIdentifier(field)).join(', ')})`;
}
});
}
if (pkString.length > 0) {
attributesClause += `, PRIMARY KEY (${pkString})`;
}
for (const fkey in foreignKeys) {
if (Object.prototype.hasOwnProperty.call(foreignKeys, fkey)) {
attributesClause += `, FOREIGN KEY (${this.quoteIdentifier(fkey)}) ${foreignKeys[fkey]}`;
}
}
let tableObject;
if (typeof tableName === 'string') {
tableObject = { table: tableName };
} else {
tableObject = tableName;
}
return `BEGIN
DECLARE CONTINUE HANDLER FOR SQLSTATE VALUE '42710'
BEGIN END;
CREATE TABLE ${tableName.schema ? `"${tableObject.schema}".` : ''}"${tableObject.table ? tableObject.table : tableObject.tableName}" (${attributesClause});
END`;
}
dropTableQuery(tableName, options) {
if (options) {
rejectInvalidOptions(
'dropTableQuery',
this.dialect.name,
DROP_TABLE_QUERY_SUPPORTABLE_OPTIONS,
DROP_TABLE_QUERY_SUPPORTED_OPTIONS,
options,
);
}
return `DROP TABLE IF EXISTS ${this.quoteTable(tableName)}`;
}
showTablesQuery(schema) {
return `SELECT TABLE_NAME FROM SYSIBM.SQLTABLES WHERE TABLE_TYPE = 'TABLE' AND TABLE_SCHEM = ${schema ? `'${schema}'` : 'CURRENT SCHEMA'}`;
}
addColumnQuery(table, key, dataType, options) {
if (options) {
rejectInvalidOptions(
'addColumnQuery',
this.dialect.name,
ADD_COLUMN_QUERY_SUPPORTABLE_OPTIONS,
ADD_COLUMN_QUERY_SUPPORTED_OPTIONS,
options,
);
}
dataType = {
...dataType,
// TODO: attributeToSQL SHOULD be using attributes in addColumnQuery
// but instead we need to pass the key along as the field here
field: key,
type: normalizeDataType(dataType.type, this.dialect),
};
const definition = this.attributeToSQL(dataType, {
context: 'addColumn',
tableName: table,
foreignKey: key,
});
return `ALTER TABLE ${this.quoteTable(table)} ADD ${this.quoteIdentifier(key)} ${definition}`;
}
removeColumnQuery(tableName, attributeName, options) {
if (options) {
rejectInvalidOptions(
'removeColumnQuery',
this.dialect.name,
REMOVE_COLUMN_QUERY_SUPPORTABLE_OPTIONS,
REMOVE_COLUMN_QUERY_SUPPORTED_OPTIONS,
options,
);
}
return `ALTER TABLE ${this.quoteTable(tableName)} DROP COLUMN ${this.quoteIdentifier(attributeName)}`;
}
changeColumnQuery(tableName, attributes) {
const attrString = [];
const constraintString = [];
for (const attributeName in attributes) {
let definition = attributes[attributeName];
if (definition.includes('REFERENCES')) {
const attrName = this.quoteIdentifier(attributeName);
definition = definition.replace(/.+?(?=REFERENCES)/, '');
const foreignKey = this.quoteIdentifier(`${attributeName}`);
constraintString.push(`${foreignKey} FOREIGN KEY (${attrName}) ${definition}`);
} else {
attrString.push(`"${attributeName}" SET DATA TYPE ${definition}`);
}
}
let finalQuery = '';
if (attrString.length) {
finalQuery += `ALTER COLUMN ${attrString.join(', ')}`;
finalQuery += constraintString.length ? ' ' : '';
}
if (constraintString.length) {
finalQuery += `ADD CONSTRAINT ${constraintString.join(', ')}`;
}
return `ALTER TABLE ${this.quoteTable(tableName)} ${finalQuery}`;
}
renameTableQuery(before, after) {
return `RENAME TABLE ${this.quoteTable(before)} TO ${this.quoteTable(after)}`;
}
renameColumnQuery(tableName, attrBefore, attributes) {
const attrString = [];
for (const attrName in attributes) {
const definition = attributes[attrName];
attrString.push(`\`${attrBefore}\` \`${attrName}\` ${definition}`);
}
return `ALTER TABLE ${this.quoteTable(tableName)} RENAME COLUMN ${attrString.join(', ')};`;
}
handleSequelizeMethod(smth, tableName, factory, options, prepend) {
if (smth instanceof Json) {
// Parse nested object
if (smth.conditions) {
const conditions = this.parseConditionObject(smth.conditions).map(condition => `${this.quoteIdentifier(condition.path[0])}->>'$.${_.tail(condition.path).join('.')}' = '${condition.value}'`);
return conditions.join(' and ');
}
if (smth.path) {
let str;
// Allow specifying conditions using the sqlite json functions
if (this._checkValidJsonStatement(smth.path)) {
str = smth.path;
} else {
// Also support json dot notation
let path = smth.path;
let startWithDot = true;
// Convert .number. to [number].
path = path.replace(/\.(\d+)\./g, '[$1].');
// Convert .number$ to [number]
path = path.replace(/\.(\d+)$/, '[$1]');
path = path.split('.');
let columnName = path.shift();
const match = columnName.match(/\[\d+\]$/);
// If columnName ends with [\d+]
if (match !== null) {
path.unshift(columnName.slice(match.index));
columnName = columnName.slice(0, Math.max(0, match.index));
startWithDot = false;
}
str = `${this.quoteIdentifier(columnName)}->>'$${startWithDot ? '.' : ''}${path.join('.')}'`;
}
if (smth.value) {
str += util.format(' = %s', this.escape(smth.value, undefined, { replacements: options.replacements }));
}
return str;
}
} else if (smth instanceof Cast) {
if (/timestamp/i.test(smth.type)) {
smth.type = 'timestamp';
} else if (smth.json && /boolean/i.test(smth.type)) {
// true or false cannot be casted as booleans within a JSON structure
smth.type = 'char';
} else if (/double precision/i.test(smth.type) || /boolean/i.test(smth.type) || /integer/i.test(smth.type)) {
smth.type = 'integer';
} else if (/text/i.test(smth.type)) {
smth.type = 'char';
}
}
return super.handleSequelizeMethod(smth, tableName, factory, options, prepend);
}
escape(value, field, options) {
if (value instanceof SequelizeMethod) {
return this.handleSequelizeMethod(value, undefined, undefined, { replacements: options.replacements });
}
if (value == null || field?.type == null || typeof field.type === 'string') {
const format = (value === null && options.where);
// use default escape mechanism instead of the DataType's.
return SqlString.escape(value, this.options.timezone, this.dialect, format);
}
field.type = field.type.toDialectDataType(this.dialect);
if (options.isList && Array.isArray(value)) {
const escapeOptions = { ...options, isList: false };
return `(${value.map(valueItem => {
return this.escape(valueItem, field, escapeOptions);
}).join(', ')})`;
}
this.validate(value, field);
return field.type.escape(value, {
// Users shouldn't have to worry about these args - just give them a function that takes a single arg
escape: this.simpleEscape,
field,
timezone: this.options.timezone,
operation: options.operation,
dialect: this.dialect,
});
}
/*
Returns an add index query.
Parameters:
- tableName -> Name of an existing table, possibly with schema.
- options:
- type: UNIQUE|FULLTEXT|SPATIAL
- name: The name of the index. Default is <table>_<attr1>_<attr2>
- fields: An array of attributes as string or as hash.
If the attribute is a hash, it must have the following content:
- name: The name of the attribute/column
- length: An integer. Optional
- order: 'ASC' or 'DESC'. Optional
- parser
- using
- operator
- concurrently: Pass CONCURRENT so other operations run while the index is created
- rawTablename, the name of the table, without schema. Used to create the name of the index
@private
*/
addIndexQuery(tableName, _attributes, _options, rawTablename) {
let options = _options || Object.create(null);
if (!Array.isArray(_attributes)) {
options = _attributes;
} else {
options.fields = _attributes;
}
options.prefix = options.prefix || rawTablename || tableName;
if (options.prefix && typeof options.prefix === 'string') {
options.prefix = options.prefix.replace(/\./g, '_');
}
const fieldsSql = options.fields.map(field => {
if (typeof field === 'string') {
return this.quoteIdentifier(field);
}
if (field instanceof SequelizeMethod) {
return this.handleSequelizeMethod(field);
}
let result = '';
if (field.attribute) {
field.name = field.attribute;
}
if (!field.name) {
throw new Error(`The following index field has no name: ${util.inspect(field)}`);
}
result += this.quoteIdentifier(field.name);
if (this.dialect.supports.index.length && field.length) {
result += `(${field.length})`;
}
if (field.order) {
result += ` ${field.order}`;
}
return result;
});
if (options.include) {
throw new Error(`The include attribute for indexes is not supported by ${this.dialect.name} dialect`);
}
if (!options.name) {
// Mostly for cases where addIndex is called directly by the user without an options object (for example in migrations)
// All calls that go through sequelize should already have a name
options = nameIndex(options, options.prefix);
}
options = Model._conformIndex(options);
if (!this.dialect.supports.index.type) {
delete options.type;
}
if (options.where) {
options.where = this.whereQuery(options.where);
}
tableName = this.quoteTable(tableName);
let schema;
// TODO: drop this option in favor of passing the schema through tableName
if (typeof options.schema === 'string') {
schema = this.quoteIdentifiers(options.schema);
}
// Although the function is 'addIndex', and the values are passed through
// the 'indexes' key of a table, Db2 for i doesn't allow REFERENCES to
// work against a UNIQUE INDEX, only a UNIQUE constraint.
if (options.unique) {
return `BEGIN
DECLARE CONTINUE HANDLER FOR SQLSTATE VALUE '42891'
BEGIN END;
ALTER TABLE ${tableName} ADD CONSTRAINT ${this.quoteIdentifiers(options.name)} UNIQUE (${fieldsSql.join(', ')}${options.operator ? ` ${options.operator}` : ''})${options.where ? ` ${options.where}` : ''};
END`;
}
return `CREATE${options.unique ? ' UNIQUE' : ''} INDEX ${schema ? ` ${schema}.` : ''}${this.quoteIdentifiers(options.name)} ON ${tableName} (${fieldsSql.join(', ')}${options.operator ? ` ${options.operator}` : ''})${options.where ? ` ${options.where}` : ''}`;
}
addConstraintQuery(tableName, options) {
const query = super.addConstraintQuery(tableName, options);
return query.replace(/;$/, '');
}
// _toJSONValue(value) {
// // true/false are stored as strings in mysql
// if (typeof value === 'boolean') {
// return value.toString();
// }
// // null is stored as a string in mysql
// if (value === null) {
// return 'null';
// }
// return value;
// }
updateQuery(tableName, attrValueHash, where, options, columnDefinitions) {
const out = super.updateQuery(tableName, attrValueHash, where, options, columnDefinitions);
out.query = removeTrailingSemicolon(out.query);
return out;
}
arithmeticQuery(operator, tableName, where, incrementAmountsByField, extraAttributesToBeUpdated, options) {
return removeTrailingSemicolon(super.arithmeticQuery(operator, tableName, where, incrementAmountsByField, extraAttributesToBeUpdated, options));
}
upsertQuery(tableName, insertValues, updateValues, where, model, options) {
const aliasTable = `temp_${this.quoteTable(tableName)}`;
let query = `MERGE INTO ${this.quoteTable(tableName)} `;
const usingClause = `USING (
SELECT * FROM (${this.quoteTable(tableName)}
VALUES(42)
) AS ${aliasTable}("id") ON (${aliasTable}."id" = ${this.quoteTable(tableName)}."id")`;
query += usingClause;
query += ` WHEN MATCHED THEN ${this.updateQuery(tableName, tableName, where, options, updateValues)}
WHEN NOT MATCHED THEN ${this.insertQuery(tableName, insertValues, model, options).sql}`;
return query;
}
insertQuery(table, valueHash, modelAttributes, options) {
// remove the final semi-colon
const query = super.insertQuery(table, valueHash, modelAttributes, options);
if (query.query[query.query.length - 1] === ';') {
query.query = query.query.slice(0, -1);
query.query = `SELECT * FROM FINAL TABLE (${query.query})`;
}
return query;
}
selectQuery(tableName, options, model) {
// remove the final semi-colon
let query = super.selectQuery(tableName, options, model);
if (query[query.length - 1] === ';') {
query = query.slice(0, -1);
}
return query;
}
bulkInsertQuery(tableName, fieldValueHashes, options, fieldMappedAttributes) {
// remove the final semi-colon
let query = super.bulkInsertQuery(tableName, fieldValueHashes, options, fieldMappedAttributes);
if (query[query.length - 1] === ';') {
query = query.slice(0, -1);
query = `SELECT * FROM FINAL TABLE (${query})`;
}
return query;
}
truncateTableQuery(tableName) {
return `TRUNCATE TABLE ${this.quoteTable(tableName)} IMMEDIATE`;
}
deleteQuery(tableName, where, options = {}, model) {
let query = `DELETE FROM ${this.quoteTable(tableName)}`;
where = this.getWhereConditions(where, null, model, options);
if (where) {
query += ` WHERE ${where}`;
}
if (options.offset || options.limit) {
query += this.addLimitAndOffset(options, model);
}
return query;
}
/**
* Returns an SQL fragment for adding result constraints.
*
* @param {object} options An object with selectQuery options.
* @returns {string} The generated sql query.
* @private
*/
addLimitAndOffset(options) {
let fragment = '';
if (options.offset) {
fragment += ` OFFSET ${this.escape(options.offset, undefined, options)} ROWS`;
}
if (options.limit) {
fragment += ` FETCH NEXT ${this.escape(options.limit, undefined, options)} ROWS ONLY`;
}
return fragment;
}
// Indexes and constraints
showConstraintsQuery(table, constraintName) {
const tableName = table.tableName || table;
const schemaName = table.schema;
let sql = [
'SELECT CONSTRAINT_NAME AS "constraintName",',
'CONSTRAINT_SCHEMA AS "constraintSchema",',
'CONSTRAINT_TYPE AS "constraintType",',
'TABLE_NAME AS "tableName",',
'TABLE_SCHEMA AS "tableSchema"',
'from QSYS2.SYSCST',
`WHERE table_name='${tableName}'`,
].join(' ');
if (constraintName) {
sql += ` AND CONSTRAINT_NAME = '${constraintName}'`;
}
if (schemaName) {
sql += ` AND TABLE_SCHEMA = '${schemaName}'`;
}
return sql;
}
// bindParam(bind) {
// return value => {
// bind.push(value);
// return '?';
// };
// }
attributeToSQL(attribute, options) {
if (!_.isPlainObject(attribute)) {
attribute = {
type: attribute,
};
}
const attributeString = attribute.type.toString({ escape: this.escape.bind(this), dialect: this.dialect });
let template = attributeString;
if (attribute.type instanceof DataTypes.ENUM) {
// enums are a special case
template = attribute.type.toSql({ dialect: this.dialect });
if (options && options.context) {
template += options.context === 'changeColumn' ? ' ADD' : '';
}
template += ` CHECK (${this.quoteIdentifier(attribute.field)} IN(${attribute.type.options.values.map(value => {
return this.escape(value, undefined, { replacements: options?.replacements });
}).join(', ')}))`;
} else {
template = attributeTypeToSql(attribute.type, { dialect: this.dialect });
}
if (attribute.allowNull === false) {
template += ' NOT NULL';
} else if (attribute.allowNull === true && (options && options.context === 'changeColumn')) {
template += ' DROP NOT NULL';
}
if (attribute.autoIncrement) {
template += ' GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1)';
}
// BLOB cannot have a default value
if (!typeWithoutDefault.has(attributeString)
&& attribute.type._binary !== true
&& defaultValueSchemable(attribute.defaultValue)) {
if (attribute.defaultValue === true) {
attribute.defaultValue = 1;
} else if (attribute.defaultValue === false) {
attribute.defaultValue = 0;
}
template += ` DEFAULT ${this.escape(attribute.defaultValue, undefined, { replacements: options?.replacements })}`;
}
if (attribute.unique === true && !attribute.primaryKey) {
template += ' UNIQUE';
}
if (attribute.primaryKey) {
template += ' PRIMARY KEY';
}
// Db2 for i comments are a mess
// if (attribute.comment) {
// template += ` ${options.context === 'changeColumn' ? 'ADD ' : ''}COMMENT ${this.escape(attribute.comment)}`;
// }
if (attribute.first) {
template += ' FIRST';
}
if (attribute.after) {
template += ` AFTER ${this.quoteIdentifier(attribute.after)}`;
}
if (attribute.references) {
if (options && options.context === 'addColumn' && options.foreignKey) {
const attrName = this.quoteIdentifier(options.foreignKey);
const fkName = this.quoteIdentifier(`${options.tableName}_${attrName}_foreign_idx`);
template += ` ADD CONSTRAINT ${fkName} FOREIGN KEY (${attrName})`;
}
template += ` REFERENCES ${this.quoteTable(attribute.references.model)}`;
if (attribute.references.key) {
template += ` (${this.quoteIdentifier(attribute.references.key)})`;
} else {
template += ` (${this.quoteIdentifier('id')})`;
}
if (attribute.onDelete) {
template += ` ON DELETE ${attribute.onDelete.toUpperCase()}`;
}
if (attribute.onUpdate && attribute.onUpdate.toUpperCase() !== 'CASCADE') {
template += ` ON UPDATE ${attribute.onUpdate.toUpperCase()}`;
}
}
return template;
}
attributesToSQL(attributes, options) {
const result = Object.create(null);
for (const key in attributes) {
const attribute = attributes[key];
attribute.field = attribute.field || key;
result[attribute.field || key] = this.attributeToSQL(attribute, options);
}
return result;
}
/**
* Generates an SQL query that returns all foreign keys of a table.
*
* @param {object} table The table.
* @param {string} schemaName The name of the schema.
* @returns {string} The generated sql query.
* @private
*/
getForeignKeysQuery(table, schemaName) {
const quotedSchemaName = schemaName ? wrapSingleQuote(schemaName) : 'CURRENT SCHEMA';
const quotedTableName = wrapSingleQuote(table.tableName || table);
const sql = [
'SELECT FK_NAME AS "constraintName",',
'PKTABLE_CAT AS "referencedTableCatalog",',
'PKTABLE_SCHEM AS "referencedTableSchema",',
'PKTABLE_NAME AS "referencedTableName",',
'PKCOLUMN_NAME AS "referencedColumnName",',
'FKTABLE_CAT AS "tableCatalog",',
'FKTABLE_SCHEM AS "tableSchema",',
'FKTABLE_NAME AS "tableName",',
'FKTABLE_SCHEM AS "tableSchema",',
'FKCOLUMN_NAME AS "columnName"',
'FROM SYSIBM.SQLFOREIGNKEYS',
`WHERE FKTABLE_SCHEM = ${quotedSchemaName}`,
`AND FKTABLE_NAME = ${quotedTableName}`,
].join(' ');
return sql;
}
/**
* Generates an SQL query that returns the foreign key constraint of a given column.
*
* @param {object} table The table.
* @param {string} columnName The name of the column.
* @returns {string} The generated sql query.
* @private
*/
getForeignKeyQuery(table, columnName) {
const quotedSchemaName = table.schema ? wrapSingleQuote(table.schema) : 'CURRENT SCHEMA';
const quotedTableName = wrapSingleQuote(table.tableName || table);
const quotedColumnName = wrapSingleQuote(columnName);
const sql = [
'SELECT FK_NAME AS "constraintName",',
'PKTABLE_CAT AS "referencedTableCatalog",',
'PKTABLE_SCHEM AS "referencedTableSchema",',
'PKTABLE_NAME AS "referencedTableName",',
'PKCOLUMN_NAME AS "referencedColumnName",',
'FKTABLE_CAT AS "tableCatalog",',
'FKTABLE_SCHEM AS "tableSchema",',
'FKTABLE_NAME AS "tableName",',
'FKTABLE_SCHEM AS "tableSchema",',
'FKCOLUMN_NAME AS "columnName"',
'FROM SYSIBM.SQLFOREIGNKEYS',
`WHERE FKTABLE_SCHEM = ${quotedSchemaName}`,
`AND FKTABLE_NAME = ${quotedTableName}`,
`AND FKCOLUMN_NAME = ${quotedColumnName}`,
].join(' ');
return sql;
}
/**
* Generates an SQL query that removes a foreign key from a table.
*
* @param {string} tableName The name of the table.
* @param {string} foreignKey The name of the foreign key constraint.
* @returns {string} The generated sql query.
* @private
*/
dropForeignKeyQuery(tableName, foreignKey) {
return `ALTER TABLE ${this.quoteTable(tableName)}
DROP FOREIGN KEY ${this.quoteIdentifier(foreignKey)};`;
}
booleanValue(value) {
if (value) {
return 1;
}
return 0;
}
}
/**
* @param {string} identifier
* @deprecated use "escape" or "escapeString" on QueryGenerator
*/
function wrapSingleQuote(identifier) {
return addTicks(identifier, '\'');
}