forked from sequelize/sequelize
/
query-generator.js
2357 lines (2037 loc) · 78.3 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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
var Utils = require('../../utils')
, SqlString = require('../../sql-string')
, Model = require('../../model')
, DataTypes = require('../../data-types')
, _ = require('lodash')
, util = require('util')
, Dottie = require('dottie')
, BelongsTo = require('../../associations/belongs-to')
, uuid = require('node-uuid')
, semver = require('semver');
/* istanbul ignore next */
var throwMethodUndefined = function(methodName) {
throw new Error('The method "' + methodName + '" is not defined! Please add it to your sql dialect.');
};
var QueryGenerator = {
options: {},
extractTableDetails: function(tableName, options) {
options = options || {};
tableName = tableName || {};
return {
schema: tableName.schema || options.schema || 'public',
tableName: _.isPlainObject(tableName) ? tableName.tableName : tableName,
delimiter: tableName.delimiter || options.delimiter || '.'
};
},
addSchema: function(param) {
var self = this;
if (!param.$schema) return param.tableName || param;
return {
tableName: param.tableName || param,
table: param.tableName || param,
name: param.name || param,
schema: param.$schema,
delimiter: param.$schemaDelimiter || '.',
toString: function() {
return self.quoteTable(this);
}
};
},
/*
Returns a query for dropping a schema
*/
dropSchema: function(tableName, options) {
return this.dropTableQuery(tableName, options);
},
/*
Returns a query for creating a table.
Parameters:
- tableName: Name of the new table.
- attributes: An object with containing attribute-attributeType-pairs.
Attributes should have the format:
{attributeName: type, attr2: type2}
--> e.g. {title: 'VARCHAR(255)'}
- options: An object with options.
Defaults: { engine: 'InnoDB', charset: null }
*/
/* istanbul ignore next */
createTableQuery: function(tableName, attributes, options) {
throwMethodUndefined('createTableQuery');
},
versionQuery: function(tableName, attributes, options) {
throwMethodUndefined('versionQuery');
},
describeTableQuery: function(tableName, schema, schemaDelimiter) {
var table = this.quoteTable(
this.addSchema({
tableName: tableName,
$schema: schema,
$schemaDelimiter: schemaDelimiter
})
);
return 'DESCRIBE ' + table + ';';
},
/*
Returns a query for dropping a table.
*/
dropTableQuery: function(tableName, options) {
options = options || {};
var query = 'DROP TABLE IF EXISTS <%= table %>;';
return Utils._.template(query)({
table: this.quoteTable(tableName)
});
},
/*
Returns a rename table query.
Parameters:
- originalTableName: Name of the table before execution.
- futureTableName: Name of the table after execution.
*/
renameTableQuery: function(before, after) {
var query = 'ALTER TABLE <%= before %> RENAME TO <%= after %>;';
return Utils._.template(query)({
before: this.quoteTable(before),
after: this.quoteTable(after)
});
},
/*
Returns a query, which gets all available table names in the database.
*/
/* istanbul ignore next */
showTablesQuery: function() {
throwMethodUndefined('showTablesQuery');
},
/*
Returns a query, which adds an attribute to an existing table.
Parameters:
- tableName: Name of the existing table.
- attributes: A hash with attribute-attributeOptions-pairs.
- key: attributeName
- value: A hash with attribute specific options:
- type: DataType
- defaultValue: A String with the default value
- allowNull: Boolean
*/
/* istanbul ignore next */
addColumnQuery: function(tableName, attributes) {
throwMethodUndefined('addColumnQuery');
},
/*
Returns a query, which removes an attribute from an existing table.
Parameters:
- tableName: Name of the existing table
- attributeName: Name of the obsolete attribute.
*/
/* istanbul ignore next */
removeColumnQuery: function(tableName, attributeName) {
throwMethodUndefined('removeColumnQuery');
},
/*
Returns a query, which modifies an existing attribute from a table.
Parameters:
- tableName: Name of the existing table.
- attributes: A hash with attribute-attributeOptions-pairs.
- key: attributeName
- value: A hash with attribute specific options:
- type: DataType
- defaultValue: A String with the default value
- allowNull: Boolean
*/
/* istanbul ignore next */
changeColumnQuery: function(tableName, attributes) {
throwMethodUndefined('changeColumnQuery');
},
/*
Returns a query, which renames an existing attribute.
Parameters:
- tableName: Name of an existing table.
- attrNameBefore: The name of the attribute, which shall be renamed.
- attrNameAfter: The name of the attribute, after renaming.
*/
/* istanbul ignore next */
renameColumnQuery: function(tableName, attrNameBefore, attrNameAfter) {
throwMethodUndefined('renameColumnQuery');
},
/*
Returns an insert into command. Parameters: table name + hash of attribute-value-pairs.
*/
insertQuery: function(table, valueHash, modelAttributes, options) {
options = options || {};
var query
, valueQuery = '<%= tmpTable %>INSERT<%= ignore %> INTO <%= table %> (<%= attributes %>)<%= output %> VALUES (<%= values %>)'
, emptyQuery = '<%= tmpTable %>INSERT<%= ignore %> INTO <%= table %><%= output %>'
, outputFragment
, fields = []
, values = []
, key
, value
, identityWrapperRequired = false
, modelAttributeMap = {}
, tmpTable = '' //tmpTable declaration for trigger
, selectFromTmp = '' //Select statement for trigger
, tmpColumns = '' //Columns for temp table for trigger
, outputColumns = '' //Columns to capture into temp table for trigger
, attribute //Model attribute holder
, modelKey; //key for model
if (modelAttributes) {
Utils._.each(modelAttributes, function(attribute, key) {
modelAttributeMap[key] = attribute;
if (attribute.field) {
modelAttributeMap[attribute.field] = attribute;
}
});
}
if (this._dialect.supports['DEFAULT VALUES']) {
emptyQuery += ' DEFAULT VALUES';
} else if (this._dialect.supports['VALUES ()']) {
emptyQuery += ' VALUES ()';
}
if (this._dialect.supports.returnValues && options.returning) {
if (!!this._dialect.supports.returnValues.returning) {
valueQuery += ' RETURNING *';
emptyQuery += ' RETURNING *';
} else if (!!this._dialect.supports.returnValues.output) {
outputFragment = ' OUTPUT INSERTED.*';
//To capture output rows when there is a trigger on MSSQL DB
if (modelAttributes && options.hasTrigger && this._dialect.supports.tmpTableTrigger) {
tmpTable = 'declare @tmp table (<%= columns %>); ';
for (modelKey in modelAttributes){
attribute = modelAttributes[modelKey];
if(!(attribute.type instanceof DataTypes.VIRTUAL)){
if (tmpColumns.length > 0){
tmpColumns += ',';
outputColumns += ',';
}
tmpColumns += this.quoteIdentifier(attribute.field) + ' ' + attribute.type.toSql();
outputColumns += 'INSERTED.' + this.quoteIdentifier(attribute.field);
}
}
var replacement ={
columns : tmpColumns
};
tmpTable = Utils._.template(tmpTable)(replacement).trim();
outputFragment = ' OUTPUT ' + outputColumns + ' into @tmp';
selectFromTmp = ';select * from @tmp';
valueQuery += selectFromTmp;
emptyQuery += selectFromTmp;
}
}
}
if (this._dialect.supports.EXCEPTION && options.exception) {
// Mostly for internal use, so we expect the user to know what he's doing!
// pg_temp functions are private per connection, so we never risk this function interfering with another one.
if (semver.gte(this.sequelize.options.databaseVersion, '9.2.0')) {
// >= 9.2 - Use a UUID but prefix with 'func_' (numbers first not allowed)
var delimiter = '$func_' + uuid.v4().replace(/-/g, '') + '$';
options.exception = 'WHEN unique_violation THEN GET STACKED DIAGNOSTICS sequelize_caught_exception = PG_EXCEPTION_DETAIL;';
valueQuery = 'CREATE OR REPLACE FUNCTION pg_temp.testfunc(OUT response <%= table %>, OUT sequelize_caught_exception text) RETURNS RECORD AS ' + delimiter +
' BEGIN ' + valueQuery + ' INTO response; EXCEPTION ' + options.exception + ' END ' + delimiter +
' LANGUAGE plpgsql; SELECT (testfunc.response).*, testfunc.sequelize_caught_exception FROM pg_temp.testfunc(); DROP FUNCTION IF EXISTS pg_temp.testfunc()';
} else {
options.exception = 'WHEN unique_violation THEN NULL;';
valueQuery = 'CREATE OR REPLACE FUNCTION pg_temp.testfunc() RETURNS SETOF <%= table %> AS $body$ BEGIN RETURN QUERY ' + valueQuery + '; EXCEPTION ' + options.exception + ' END; $body$ LANGUAGE plpgsql; SELECT * FROM pg_temp.testfunc(); DROP FUNCTION IF EXISTS pg_temp.testfunc();';
}
}
if (this._dialect.supports['ON DUPLICATE KEY'] && options.onDuplicate) {
valueQuery += ' ON DUPLICATE KEY ' + options.onDuplicate;
emptyQuery += ' ON DUPLICATE KEY ' + options.onDuplicate;
}
valueHash = Utils.removeNullValuesFromHash(valueHash, this.options.omitNull);
for (key in valueHash) {
if (valueHash.hasOwnProperty(key)) {
value = valueHash[key];
fields.push(this.quoteIdentifier(key));
// SERIALS' can't be NULL in postgresql, use DEFAULT where supported
if (modelAttributeMap && modelAttributeMap[key] && modelAttributeMap[key].autoIncrement === true && !value) {
if (!this._dialect.supports.autoIncrement.defaultValue) {
fields.splice(-1,1);
} else if (this._dialect.supports.DEFAULT) {
values.push('DEFAULT');
} else {
values.push(this.escape(null));
}
} else {
if (modelAttributeMap && modelAttributeMap[key] && modelAttributeMap[key].autoIncrement === true) {
identityWrapperRequired = true;
}
values.push(this.escape(value, (modelAttributeMap && modelAttributeMap[key]) || undefined, { context: 'INSERT' }));
}
}
}
var replacements = {
ignore: options.ignore ? this._dialect.supports.IGNORE : '',
table: this.quoteTable(table),
attributes: fields.join(','),
output: outputFragment,
values: values.join(','),
tmpTable: tmpTable
};
query = (replacements.attributes.length ? valueQuery : emptyQuery) + ';';
if (identityWrapperRequired && this._dialect.supports.autoIncrement.identityInsert) {
query = [
'SET IDENTITY_INSERT', this.quoteTable(table), 'ON;',
query,
'SET IDENTITY_INSERT', this.quoteTable(table), 'OFF;',
].join(' ');
}
return Utils._.template(query)(replacements);
},
/*
Returns an insert into command for multiple values.
Parameters: table name + list of hashes of attribute-value-pairs.
*/
bulkInsertQuery: function(tableName, attrValueHashes, options, rawAttributes) {
options = options || {};
rawAttributes = rawAttributes || {};
var query = 'INSERT<%= ignoreDuplicates %> INTO <%= table %> (<%= attributes %>) VALUES <%= tuples %><%= onDuplicateKeyUpdate %><%= returning %>;'
, tuples = []
, serials = []
, allAttributes = []
, onDuplicateKeyUpdate = '';
attrValueHashes.forEach(function(attrValueHash) {
_.forOwn(attrValueHash, function(value, key) {
if (allAttributes.indexOf(key) === -1) {
allAttributes.push(key);
}
if (rawAttributes[key] && rawAttributes[key].autoIncrement === true) {
serials.push(key);
}
});
});
attrValueHashes.forEach(function(attrValueHash) {
tuples.push('(' +
allAttributes.map(function(key) {
if (this._dialect.supports.bulkDefault && serials.indexOf(key) !== -1) {
return attrValueHash[key] || 'DEFAULT';
}
return this.escape(attrValueHash[key], rawAttributes[key], { context: 'INSERT' });
}, this).join(',') +
')');
}, this);
if (this._dialect.supports.updateOnDuplicate && options.updateOnDuplicate) {
onDuplicateKeyUpdate += ' ON DUPLICATE KEY UPDATE ' + options.updateOnDuplicate.map(function(attr) {
var field = rawAttributes && rawAttributes[attr] && rawAttributes[attr].field || attr;
var key = this.quoteIdentifier(field);
return key + '=VALUES(' + key + ')';
}, this).join(',');
}
var replacements = {
ignoreDuplicates: options.ignoreDuplicates ? this._dialect.supports.ignoreDuplicates : '',
table: this.quoteTable(tableName),
attributes: allAttributes.map(function(attr) {
return this.quoteIdentifier(attr);
}, this).join(','),
tuples: tuples.join(','),
onDuplicateKeyUpdate: onDuplicateKeyUpdate,
returning: this._dialect.supports.returnValues && options.returning ? ' RETURNING *' : ''
};
return _.template(query)(replacements);
},
/*
Returns an update query.
Parameters:
- tableName -> Name of the table
- values -> A hash with attribute-value-pairs
- where -> A hash with conditions (e.g. {name: 'foo'})
OR an ID as integer
OR a string with conditions (e.g. 'name="foo"').
If you use a string, you have to escape it on your own.
*/
updateQuery: function(tableName, attrValueHash, where, options, attributes) {
options = options || {};
_.defaults(options, this.options);
attrValueHash = Utils.removeNullValuesFromHash(attrValueHash, options.omitNull, options);
var query
, values = []
, outputFragment
, modelAttributeMap = {}
, tmpTable = '' //tmpTable declaration for trigger
, selectFromTmp = '' //Select statement for trigger
, tmpColumns = '' //Columns for temp table for trigger
, outputColumns = '' //Columns to capture into temp table for trigger
, attribute //Model attribute holder
, modelKey; //key for model
query = '<%= tmpTable %>UPDATE <%= table %> SET <%= values %><%= output %> <%= where %>';
if (this._dialect.supports['LIMIT ON UPDATE'] && options.limit) {
query += ' LIMIT ' + this.escape(options.limit) + ' ';
}
if (this._dialect.supports.returnValues) {
if (!!this._dialect.supports.returnValues.output) {
// we always need this for mssql
outputFragment = ' OUTPUT INSERTED.*';
//To capture output rows when there is a trigger on MSSQL DB
if (attributes && options.hasTrigger && this._dialect.supports.tmpTableTrigger) {
tmpTable = 'declare @tmp table (<%= columns %>); ';
for (modelKey in attributes){
attribute = attributes[modelKey];
if(!(attribute.type instanceof DataTypes.VIRTUAL)){
if (tmpColumns.length > 0){
tmpColumns += ',';
outputColumns += ',';
}
tmpColumns += this.quoteIdentifier(attribute.field) + ' ' + attribute.type.toSql();
outputColumns += 'INSERTED.' + this.quoteIdentifier(attribute.field);
}
}
var replacement ={
columns : tmpColumns
};
tmpTable = Utils._.template(tmpTable)(replacement).trim();
outputFragment = ' OUTPUT ' + outputColumns + ' into @tmp';
selectFromTmp = ';select * from @tmp';
query += selectFromTmp;
}
} else if (this._dialect.supports.returnValues && options.returning) {
// ensure that the return output is properly mapped to model fields.
options.mapToModel = true;
query += ' RETURNING *';
}
}
if (attributes) {
Utils._.each(attributes, function(attribute, key) {
modelAttributeMap[key] = attribute;
if (attribute.field) {
modelAttributeMap[attribute.field] = attribute;
}
});
}
for (var key in attrValueHash) {
if (modelAttributeMap && modelAttributeMap[key] &&
modelAttributeMap[key].autoIncrement === true &&
!this._dialect.supports.autoIncrement.update) {
// not allowed to update identity column
continue;
}
var value = attrValueHash[key];
values.push(this.quoteIdentifier(key) + '=' + this.escape(value, (modelAttributeMap && modelAttributeMap[key] || undefined), { context: 'UPDATE' }));
}
var replacements = {
table: this.quoteTable(tableName),
values: values.join(','),
output: outputFragment,
where: this.whereQuery(where),
tmpTable: tmpTable
};
if (values.length === 0) {
return '';
}
return Utils._.template(query)(replacements).trim();
},
/*
Returns an upsert query.
*/
upsertQuery: function (tableName, insertValues, updateValues, where, rawAttributes, options) {
throwMethodUndefined('upsertQuery');
},
/*
Returns a deletion query.
Parameters:
- tableName -> Name of the table
- where -> A hash with conditions (e.g. {name: 'foo'})
OR an ID as integer
OR a string with conditions (e.g. 'name="foo"').
If you use a string, you have to escape it on your own.
Options:
- limit -> Maximaum count of lines to delete
- truncate -> boolean - whether to use an 'optimized' mechanism (i.e. TRUNCATE) if available,
note that this should not be the default behaviour because TRUNCATE does not
always play nicely (e.g. InnoDB tables with FK constraints)
(@see http://dev.mysql.com/doc/refman/5.6/en/truncate-table.html).
Note that truncate must ignore limit and where
*/
/* istanbul ignore next */
deleteQuery: function(tableName, where, options) {
throwMethodUndefined('deleteQuery');
},
/*
Returns an update query.
Parameters:
- tableName -> Name of the table
- values -> A hash with attribute-value-pairs
- where -> A hash with conditions (e.g. {name: 'foo'})
OR an ID as integer
OR a string with conditions (e.g. 'name="foo"').
If you use a string, you have to escape it on your own.
*/
incrementQuery: function(tableName, attrValueHash, where, options) {
attrValueHash = Utils.removeNullValuesFromHash(attrValueHash, this.options.omitNull);
var query
, key
, value
, values = []
, outputFragment;
query = 'UPDATE <%= table %> SET <%= values %><%= output %> <%= where %>';
if (this._dialect.supports.returnValues) {
if (!!this._dialect.supports.returnValues.returning) {
query += ' RETURNING *';
} else if (!!this._dialect.supports.returnValues.output) {
outputFragment = ' OUTPUT INSERTED.*';
}
}
for (key in attrValueHash) {
value = attrValueHash[key];
values.push(this.quoteIdentifier(key) + '=' + this.quoteIdentifier(key) + ' + ' + this.escape(value));
}
options = options || {};
for (key in options) {
value = options[key];
values.push(this.quoteIdentifier(key) + '=' + this.escape(value));
}
var replacements = {
table: this.quoteTable(tableName),
values: values.join(','),
output: outputFragment,
where: this.whereQuery(where)
};
return Utils._.template(query)(replacements);
},
nameIndexes: function (indexes, rawTablename) {
return Utils._.map(indexes, function (index) {
if (!index.hasOwnProperty('name')) {
var onlyAttributeNames = index.fields.map(function(field) {
return (typeof field === 'string') ? field : (field.name || field.attribute);
}.bind(this));
index.name = Utils.inflection.underscore(rawTablename + '_' + onlyAttributeNames.join('_'));
}
return index;
});
},
/*
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
- rawTablename, the name of the table, without schema. Used to create the name of the index
*/
addIndexQuery: function(tableName, attributes, options, rawTablename) {
var fieldsSql;
options = options || {};
if (!Array.isArray(attributes)) {
options = attributes;
attributes = undefined;
} else {
options.fields = attributes;
}
// Backwards compatability
if (options.indexName) {
options.name = options.indexName;
}
if (options.indicesType) {
options.type = options.indicesType;
}
if (options.indexType || options.method) {
options.using = options.indexType || options.method;
}
options.prefix = options.prefix || rawTablename || tableName;
if (options.prefix && _.isString(options.prefix)) {
options.prefix = options.prefix.replace(/\./g, '_');
options.prefix = options.prefix.replace(/(\"|\')/g, '');
}
fieldsSql = options.fields.map(function(field) {
if (typeof field === 'string') {
return this.quoteIdentifier(field);
} else if (field._isSequelizeMethod) {
return this.handleSequelizeMethod(field);
} else {
var 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.collate && field.collate) {
result += ' COLLATE ' + this.quoteIdentifier(field.collate);
}
if (this._dialect.supports.index.length && field.length) {
result += '(' + field.length + ')';
}
if (field.order) {
result += ' ' + field.order;
}
return result;
}
}.bind(this));
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 = this.nameIndexes([options], options.prefix)[0];
}
options = Model.prototype.$conformIndex(options);
if (!this._dialect.supports.index.type) {
delete options.type;
}
if (options.where) {
options.where = this.whereQuery(options.where);
}
if (_.isString(tableName)) {
tableName = this.quoteIdentifiers(tableName);
} else {
tableName = this.quoteTable(tableName);
}
var concurrently = this._dialect.supports.index.concurrently && options.concurrently ? 'CONCURRENTLY' : undefined
, ind;
if (this._dialect.supports.indexViaAlter) {
ind = [
'ALTER TABLE',
tableName,
concurrently,
'ADD'
];
} else {
ind = ['CREATE'];
}
ind = ind.concat(
options.unique ? 'UNIQUE' : '',
options.type, 'INDEX',
!this._dialect.supports.indexViaAlter ? concurrently : undefined,
this.quoteIdentifiers(options.name),
this._dialect.supports.index.using === 1 && options.using ? 'USING ' + options.using : '',
!this._dialect.supports.indexViaAlter ? 'ON ' + tableName : undefined,
this._dialect.supports.index.using === 2 && options.using ? 'USING ' + options.using : '',
'(' + fieldsSql.join(', ') + (options.operator ? ' '+options.operator : '') + ')',
(this._dialect.supports.index.parser && options.parser ? 'WITH PARSER ' + options.parser : undefined),
(this._dialect.supports.index.where && options.where ? options.where : undefined)
);
return Utils._.compact(ind).join(' ');
},
/*
Returns a query listing indexes for a given table.
Parameters:
- tableName: Name of an existing table.
- options:
- database: Name of the database.
*/
/* istanbul ignore next */
showIndexesQuery: function(tableName, options) {
throwMethodUndefined('showIndexesQuery');
},
/*
Returns a remove index query.
Parameters:
- tableName: Name of an existing table.
- indexNameOrAttributes: The name of the index as string or an array of attribute names.
*/
/* istanbul ignore next */
removeIndexQuery: function(tableName, indexNameOrAttributes) {
throwMethodUndefined('removeIndexQuery');
},
/*
This method transforms an array of attribute hashes into equivalent
sql attribute definition.
*/
/* istanbul ignore next */
attributesToSQL: function(attributes) {
throwMethodUndefined('attributesToSQL');
},
/*
Returns all auto increment fields of a factory.
*/
/* istanbul ignore next */
findAutoIncrementField: function(factory) {
throwMethodUndefined('findAutoIncrementField');
},
quoteTable: function(param, as) {
var table = '';
if (as === true) {
as = param.as || param.name || param;
}
if (_.isObject(param)) {
if (this._dialect.supports.schemas) {
if (param.schema) {
table += this.quoteIdentifier(param.schema) + '.';
}
table += this.quoteIdentifier(param.tableName);
} else {
if (param.schema) {
table += param.schema + (param.delimiter || '.');
}
table += param.tableName;
table = this.quoteIdentifier(table);
}
} else {
table = this.quoteIdentifier(param);
}
if (as) {
table += ' AS ' + this.quoteIdentifier(as);
}
return table;
},
/*
Quote an object based on its type. This is a more general version of quoteIdentifiers
Strings: should proxy to quoteIdentifiers
Arrays:
* Expects array in the form: [<model> (optional), <model> (optional),... String, String (optional)]
Each <model> can be a model or an object {model: Model, as: String}, matching include
* Zero or more models can be included in the array and are used to trace a path through the tree of
included nested associations. This produces the correct table name for the ORDER BY/GROUP BY SQL
and quotes it.
* If a single string is appended to end of array, it is quoted.
If two strings appended, the 1st string is quoted, the 2nd string unquoted.
Objects:
* If raw is set, that value should be returned verbatim, without quoting
* If fn is set, the string should start with the value of fn, starting paren, followed by
the values of cols (which is assumed to be an array), quoted and joined with ', ',
unless they are themselves objects
* If direction is set, should be prepended
Currently this function is only used for ordering / grouping columns and Sequelize.col(), but it could
potentially also be used for other places where we want to be able to call SQL functions (e.g. as default values)
*/
quote: function(obj, parent, force) {
if (Utils._.isString(obj)) {
return this.quoteIdentifiers(obj, force);
} else if (Array.isArray(obj)) {
// loop through array, adding table names of models to quoted
// (checking associations to see if names should be singularised or not)
var tableNames = []
, parentAssociation
, len = obj.length
, item
, model
, as
, association;
for (var i = 0; i < len - 1; i++) {
item = obj[i];
if (item._modelAttribute || Utils._.isString(item) || item._isSequelizeMethod || 'raw' in item) {
break;
}
if (item instanceof Model) {
model = item;
as = undefined;
} else {
model = item.model;
as = item.as;
}
// check if model provided is through table
if (!as && parentAssociation && parentAssociation.through && parentAssociation.through.model === model) {
association = {as: model.name};
} else {
// find applicable association for linking parent to this model
association = parent.getAssociation(model, as);
}
if (association) {
tableNames[i] = association.as;
parent = model;
parentAssociation = association;
} else {
tableNames[i] = model.tableName;
throw new Error('\'' + tableNames.join('.') + '\' in order / group clause is not valid association');
}
}
// add 1st string as quoted, 2nd as unquoted raw
var sql = (i > 0 ? this.quoteIdentifier(tableNames.join('.')) + '.' : (Utils._.isString(obj[0]) && parent ? this.quoteIdentifier(parent.name) + '.' : '')) + this.quote(obj[i], parent, force);
if (i < len - 1) {
if (obj[i + 1]._isSequelizeMethod) {
sql += this.handleSequelizeMethod(obj[i + 1]);
} else {
sql += ' ' + obj[i + 1];
}
}
return sql;
} else if (obj._modelAttribute) {
return this.quoteTable(obj.Model.name) + '.' + obj.fieldName;
} else if (obj._isSequelizeMethod) {
return this.handleSequelizeMethod(obj);
} else if (Utils._.isObject(obj) && 'raw' in obj) {
return obj.raw;
} else {
throw new Error('Unknown structure passed to order / group: ' + JSON.stringify(obj));
}
},
/*
Create a trigger
*/
/* istanbul ignore next */
createTrigger: function(tableName, triggerName, timingType, fireOnArray, functionName, functionParams, optionsArray) {
throwMethodUndefined('createTrigger');
},
/*
Drop a trigger
*/
/* istanbul ignore next */
dropTrigger: function(tableName, triggerName) {
throwMethodUndefined('dropTrigger');
},
/*
Rename a trigger
*/
/* istanbul ignore next */
renameTrigger: function(tableName, oldTriggerName, newTriggerName) {
throwMethodUndefined('renameTrigger');
},
/*
Create a function
*/
/* istanbul ignore next */
createFunction: function(functionName, params, returnType, language, body, options) {
throwMethodUndefined('createFunction');
},
/*
Drop a function
*/
/* istanbul ignore next */
dropFunction: function(functionName, params) {
throwMethodUndefined('dropFunction');
},
/*
Rename a function
*/
/* istanbul ignore next */
renameFunction: function(oldFunctionName, params, newFunctionName) {
throwMethodUndefined('renameFunction');
},
/*
Escape an identifier (e.g. a table or attribute name)
*/
/* istanbul ignore next */
quoteIdentifier: function(identifier, force) {
throwMethodUndefined('quoteIdentifier');
},
/*
Split an identifier into .-separated tokens and quote each part
*/
quoteIdentifiers: function(identifiers, force) {
if (identifiers.indexOf('.') !== -1) {
identifiers = identifiers.split('.');
return this.quoteIdentifier(identifiers.slice(0, identifiers.length - 1).join('.')) + '.' + this.quoteIdentifier(identifiers[identifiers.length - 1]);
} else {
return this.quoteIdentifier(identifiers);
}
},
/*
Escape a value (e.g. a string, number or date)
*/
escape: function(value, field, options) {
options = options || {};
if (value !== null && value !== undefined) {
if (value._isSequelizeMethod) {
return this.handleSequelizeMethod(value);
} else {
if (field && field.type) {
if (['INSERT', 'UPDATE'].indexOf(options.context) !== -1 && this.typeValidation && field && field.type && value) {
if (field.type.validate) {
field.type.validate(value);
}
}
if (field.type.stringify) {
// Users shouldn't have to worry about these args - just give them a function that takes a single arg
var simpleEscape = _.partialRight(SqlString.escape, this.options.timezone, this.dialect);
value = field.type.stringify(value, { escape: simpleEscape, field: field, timezone: this.options.timezone });
if (field.type.escape === false) {
// The data-type already did the required escaping
return value;
}
}
}
}
}
return SqlString.escape(value, this.options.timezone, this.dialect);
},
/**
* Generates an SQL query that returns all foreign keys of a table.
*
* @param {String} tableName The name of the table.
* @param {String} schemaName The name of the schema.
* @return {String} The generated sql query.
*/
/* istanbul ignore next */
getForeignKeysQuery: function(tableName, schemaName) {
throwMethodUndefined('getForeignKeysQuery');
},
/**
* 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.
* @return {String} The generated sql query.
*/
/* istanbul ignore next */
dropForeignKeyQuery: function(tableName, foreignKey) {
throwMethodUndefined('dropForeignKeyQuery');
},