-
-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathmodel.js
4313 lines (3765 loc) · 183 KB
/
model.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';
const assert = require('assert');
const _ = require('lodash');
const Dottie = require('dottie');
const Utils = require('./utils');
const logger = require('./utils/logger');
const BelongsTo = require('./associations/belongs-to');
const BelongsToMany = require('./associations/belongs-to-many');
const InstanceValidator = require('./instance-validator');
const QueryTypes = require('./query-types');
const sequelizeErrors = require('./errors');
const Promise = require('./promise');
const Association = require('./associations/base');
const HasMany = require('./associations/has-many');
const DataTypes = require('./data-types');
const Hooks = require('./hooks');
const associationsMixin = require('./associations/mixin');
const Op = require('./operators');
/**
* A Model represents a table in the database. Instances of this class represent a database row.
*
* Model instances operate with the concept of a `dataValues` property, which stores the actual values represented by the instance.
* By default, the values from dataValues can also be accessed directly from the Instance, that is:
* ```js
* instance.field
* // is the same as
* instance.get('field')
* // is the same as
* instance.getDataValue('field')
* ```
* However, if getters and/or setters are defined for `field` they will be invoked, instead of returning the value from `dataValues`.
* Accessing properties directly or using `get` is preferred for regular use, `getDataValue` should only be used for custom getters.
*
* @see {@link Sequelize#define} for more information about getters and setters
* @class Model
* @mixes Hooks
*/
class Model {
static get QueryInterface() {
return this.sequelize.getQueryInterface();
}
static get QueryGenerator() {
return this.QueryInterface.QueryGenerator;
}
/**
* A reference to the sequelize instance
*
* @see {@link Sequelize}
*
* @property sequelize
*
* @returns {Sequelize}
*/
get sequelize() {
return this.constructor.sequelize;
}
/**
* Builds a new model instance.
*
* @param {Object} [values={}] an object of key value pairs
* @param {Object} [options] instance construction options
* @param {boolean} [options.raw=false] If set to true, values will ignore field and virtual setters.
* @param {boolean} [options.isNewRecord=true] Is this a new record
* @param {Array} [options.include] an array of include options - Used to build prefetched/included model instances. See `set`
*/
constructor(values = {}, options = {}) {
options = Object.assign({
isNewRecord: true,
_schema: this.constructor._schema,
_schemaDelimiter: this.constructor._schemaDelimiter
}, options || {});
if (options.attributes) {
options.attributes = options.attributes.map(attribute => Array.isArray(attribute) ? attribute[1] : attribute);
}
if (!options.includeValidated) {
this.constructor._conformOptions(options, this.constructor);
if (options.include) {
this.constructor._expandIncludeAll(options);
this.constructor._validateIncludedElements(options);
}
}
this.dataValues = {};
this._previousDataValues = {};
this._changed = {};
this._modelOptions = this.constructor.options;
this._options = options || {};
/**
* Returns true if this instance has not yet been persisted to the database
* @property isNewRecord
* @returns {boolean}
*/
this.isNewRecord = options.isNewRecord;
this._initValues(values, options);
}
_initValues(values, options) {
let defaults;
let key;
values = values && _.clone(values) || {};
if (options.isNewRecord) {
defaults = {};
if (this.constructor._hasDefaultValues) {
defaults = _.mapValues(this.constructor._defaultValues, valueFn => {
const value = valueFn();
return value && value instanceof Utils.SequelizeMethod ? value : _.cloneDeep(value);
});
}
// set id to null if not passed as value, a newly created dao has no id
// removing this breaks bulkCreate
// do after default values since it might have UUID as a default value
if (this.constructor.primaryKeyAttribute && !defaults.hasOwnProperty(this.constructor.primaryKeyAttribute)) {
defaults[this.constructor.primaryKeyAttribute] = null;
}
if (this.constructor._timestampAttributes.createdAt && defaults[this.constructor._timestampAttributes.createdAt]) {
this.dataValues[this.constructor._timestampAttributes.createdAt] = Utils.toDefaultValue(defaults[this.constructor._timestampAttributes.createdAt], this.sequelize.options.dialect);
delete defaults[this.constructor._timestampAttributes.createdAt];
}
if (this.constructor._timestampAttributes.updatedAt && defaults[this.constructor._timestampAttributes.updatedAt]) {
this.dataValues[this.constructor._timestampAttributes.updatedAt] = Utils.toDefaultValue(defaults[this.constructor._timestampAttributes.updatedAt], this.sequelize.options.dialect);
delete defaults[this.constructor._timestampAttributes.updatedAt];
}
if (this.constructor._timestampAttributes.deletedAt && defaults[this.constructor._timestampAttributes.deletedAt]) {
this.dataValues[this.constructor._timestampAttributes.deletedAt] = Utils.toDefaultValue(defaults[this.constructor._timestampAttributes.deletedAt], this.sequelize.options.dialect);
delete defaults[this.constructor._timestampAttributes.deletedAt];
}
if (Object.keys(defaults).length) {
for (key in defaults) {
if (values[key] === undefined) {
this.set(key, Utils.toDefaultValue(defaults[key], this.sequelize.options.dialect), { raw: true });
delete values[key];
}
}
}
}
this.set(values, options);
}
// validateIncludedElements should have been called before this method
static _paranoidClause(model, options = {}) {
// Apply on each include
// This should be handled before handling where conditions because of logic with returns
// otherwise this code will never run on includes of a already conditionable where
if (options.include) {
for (const include of options.include) {
this._paranoidClause(include.model, include);
}
}
// apply paranoid when groupedLimit is used
if (_.get(options, 'groupedLimit.on.options.paranoid')) {
const throughModel = _.get(options, 'groupedLimit.on.through.model');
if (throughModel) {
options.groupedLimit.through = this._paranoidClause(throughModel, options.groupedLimit.through);
}
}
if (!model.options.timestamps || !model.options.paranoid || options.paranoid === false) {
// This model is not paranoid, nothing to do here;
return options;
}
const deletedAtCol = model._timestampAttributes.deletedAt;
const deletedAtAttribute = model.rawAttributes[deletedAtCol];
const deletedAtObject = {};
let deletedAtDefaultValue = deletedAtAttribute.hasOwnProperty('defaultValue') ? deletedAtAttribute.defaultValue : null;
deletedAtDefaultValue = deletedAtDefaultValue || {
[Op.eq]: null
};
deletedAtObject[deletedAtAttribute.field || deletedAtCol] = deletedAtDefaultValue;
if (Utils.isWhereEmpty(options.where)) {
options.where = deletedAtObject;
} else {
options.where = { [Op.and]: [deletedAtObject, options.where] };
}
return options;
}
static _addDefaultAttributes() {
const tail = {};
let head = {};
// Add id if no primary key was manually added to definition
// Can't use this.primaryKeys here, since this function is called before PKs are identified
if (!_.some(this.rawAttributes, 'primaryKey')) {
if ('id' in this.rawAttributes) {
// Something is fishy here!
throw new Error(`A column called 'id' was added to the attributes of '${this.tableName}' but not marked with 'primaryKey: true'`);
}
head = {
id: {
type: new DataTypes.INTEGER(),
allowNull: false,
primaryKey: true,
autoIncrement: true,
_autoGenerated: true
}
};
}
if (this._timestampAttributes.createdAt) {
tail[this._timestampAttributes.createdAt] = {
type: DataTypes.DATE,
allowNull: false,
_autoGenerated: true
};
}
if (this._timestampAttributes.updatedAt) {
tail[this._timestampAttributes.updatedAt] = {
type: DataTypes.DATE,
allowNull: false,
_autoGenerated: true
};
}
if (this._timestampAttributes.deletedAt) {
tail[this._timestampAttributes.deletedAt] = {
type: DataTypes.DATE,
_autoGenerated: true
};
}
if (this._versionAttribute) {
tail[this._versionAttribute] = {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
_autoGenerated: true
};
}
const existingAttributes = _.clone(this.rawAttributes);
this.rawAttributes = {};
_.each(head, (value, attr) => {
this.rawAttributes[attr] = value;
});
_.each(existingAttributes, (value, attr) => {
this.rawAttributes[attr] = value;
});
_.each(tail, (value, attr) => {
if (_.isUndefined(this.rawAttributes[attr])) {
this.rawAttributes[attr] = value;
}
});
if (!Object.keys(this.primaryKeys).length) {
this.primaryKeys.id = this.rawAttributes.id;
}
}
static _findAutoIncrementAttribute() {
this.autoIncrementAttribute = null;
for (const name in this.rawAttributes) {
if (this.rawAttributes.hasOwnProperty(name)) {
const definition = this.rawAttributes[name];
if (definition && definition.autoIncrement) {
if (this.autoIncrementAttribute) {
throw new Error('Invalid Instance definition. Only one autoincrement field allowed.');
} else {
this.autoIncrementAttribute = name;
}
}
}
}
}
static _conformOptions(options, self) {
if (self) {
self._expandAttributes(options);
}
if (!options.include) {
return;
}
// if include is not an array, wrap in an array
if (!Array.isArray(options.include)) {
options.include = [options.include];
} else if (!options.include.length) {
delete options.include;
return;
}
// convert all included elements to { model: Model } form
options.include = options.include.map(include => this._conformInclude(include, self));
}
static _transformStringAssociation(include, self) {
if (self && typeof include === 'string') {
if (!self.associations.hasOwnProperty(include)) {
throw new Error(`Association with alias "${include}" does not exists`);
}
return self.associations[include];
}
return include;
}
static _conformInclude(include, self) {
let model;
if (include._pseudo) return include;
include = this._transformStringAssociation(include, self);
if (include instanceof Association) {
if (self && include.target.name === self.name) {
model = include.source;
} else {
model = include.target;
}
include = { model, association: include, as: include.as };
} else if (include.prototype && include.prototype instanceof Model) {
include = { model: include };
} else if (_.isPlainObject(include)) {
if (include.association) {
include.association = this._transformStringAssociation(include.association, self);
if (self && include.association.target.name === self.name) {
model = include.association.source;
} else {
model = include.association.target;
}
if (!include.model) {
include.model = model;
}
if (!include.as) {
include.as = include.association.as;
}
} else {
model = include.model;
}
this._conformOptions(include, model);
} else {
throw new Error('Include unexpected. Element has to be either a Model, an Association or an object.');
}
return include;
}
static _expandIncludeAllElement(includes, include) {
// check 'all' attribute provided is valid
let all = include.all;
delete include.all;
if (all !== true) {
if (!Array.isArray(all)) {
all = [all];
}
const validTypes = {
BelongsTo: true,
HasOne: true,
HasMany: true,
One: ['BelongsTo', 'HasOne'],
Has: ['HasOne', 'HasMany'],
Many: ['HasMany']
};
for (let i = 0; i < all.length; i++) {
const type = all[i];
if (type === 'All') {
all = true;
break;
}
const types = validTypes[type];
if (!types) {
throw new sequelizeErrors.EagerLoadingError(`include all '${type}' is not valid - must be BelongsTo, HasOne, HasMany, One, Has, Many or All`);
}
if (types !== true) {
// replace type placeholder e.g. 'One' with its constituent types e.g. 'HasOne', 'BelongsTo'
all.splice(i, 1);
i--;
for (let j = 0; j < types.length; j++) {
if (!all.includes(types[j])) {
all.unshift(types[j]);
i++;
}
}
}
}
}
// add all associations of types specified to includes
const nested = include.nested;
if (nested) {
delete include.nested;
if (!include.include) {
include.include = [];
} else if (!Array.isArray(include.include)) {
include.include = [include.include];
}
}
const used = [];
(function addAllIncludes(parent, includes) {
_.forEach(parent.associations, association => {
if (all !== true && !all.includes(association.associationType)) {
return;
}
// check if model already included, and skip if so
const model = association.target;
const as = association.options.as;
const predicate = {model};
if (as) {
// We only add 'as' to the predicate if it actually exists
predicate.as = as;
}
if (_.find(includes, predicate)) {
return;
}
// skip if recursing over a model already nested
if (nested && used.includes(model)) {
return;
}
used.push(parent);
// include this model
const thisInclude = Utils.cloneDeep(include);
thisInclude.model = model;
if (as) {
thisInclude.as = as;
}
includes.push(thisInclude);
// run recursively if nested
if (nested) {
addAllIncludes(model, thisInclude.include);
if (thisInclude.include.length === 0) delete thisInclude.include;
}
});
used.pop();
})(this, includes);
}
static _validateIncludedElements(options, tableNames) {
if (!options.model) options.model = this;
tableNames = tableNames || {};
options.includeNames = [];
options.includeMap = {};
/* Legacy */
options.hasSingleAssociation = false;
options.hasMultiAssociation = false;
if (!options.parent) {
options.topModel = options.model;
options.topLimit = options.limit;
}
options.include = options.include.map(include => {
include = this._conformInclude(include);
include.parent = options;
include.topLimit = options.topLimit;
this._validateIncludedElement.call(options.model, include, tableNames, options);
if (include.duplicating === undefined) {
include.duplicating = include.association.isMultiAssociation;
}
include.hasDuplicating = include.hasDuplicating || include.duplicating;
include.hasRequired = include.hasRequired || include.required;
options.hasDuplicating = options.hasDuplicating || include.hasDuplicating;
options.hasRequired = options.hasRequired || include.required;
options.hasWhere = options.hasWhere || include.hasWhere || !!include.where;
return include;
});
for (const include of options.include) {
include.hasParentWhere = options.hasParentWhere || !!options.where;
include.hasParentRequired = options.hasParentRequired || !!options.required;
if (include.subQuery !== false && options.hasDuplicating && options.topLimit) {
if (include.duplicating) {
include.subQuery = false;
include.subQueryFilter = include.hasRequired;
} else {
include.subQuery = include.hasRequired;
include.subQueryFilter = false;
}
} else {
include.subQuery = include.subQuery || false;
if (include.duplicating) {
include.subQueryFilter = include.subQuery;
include.subQuery = false;
} else {
include.subQueryFilter = false;
include.subQuery = include.subQuery || include.hasParentRequired && include.hasRequired;
}
}
options.includeMap[include.as] = include;
options.includeNames.push(include.as);
// Set top level options
if (options.topModel === options.model && options.subQuery === undefined && options.topLimit) {
if (include.subQuery) {
options.subQuery = include.subQuery;
} else if (include.hasDuplicating) {
options.subQuery = true;
}
}
/* Legacy */
options.hasIncludeWhere = options.hasIncludeWhere || include.hasIncludeWhere || !!include.where;
options.hasIncludeRequired = options.hasIncludeRequired || include.hasIncludeRequired || !!include.required;
if (include.association.isMultiAssociation || include.hasMultiAssociation) {
options.hasMultiAssociation = true;
}
if (include.association.isSingleAssociation || include.hasSingleAssociation) {
options.hasSingleAssociation = true;
}
}
if (options.topModel === options.model && options.subQuery === undefined) {
options.subQuery = false;
}
return options;
}
static _validateIncludedElement(include, tableNames, options) {
tableNames[include.model.getTableName()] = true;
if (include.attributes && !options.raw) {
include.model._expandAttributes(include);
// Need to make sure virtuals are mapped before setting originalAttributes
include = Utils.mapFinderOptions(include, include.model);
include.originalAttributes = include.attributes.slice(0);
if (include.attributes.length) {
_.each(include.model.primaryKeys, (attr, key) => {
// Include the primary key if it's not already included - take into account that the pk might be aliased (due to a .field prop)
if (!_.some(include.attributes, includeAttr => {
if (attr.field !== key) {
return Array.isArray(includeAttr) && includeAttr[0] === attr.field && includeAttr[1] === key;
}
return includeAttr === key;
})) {
include.attributes.unshift(key);
}
});
}
} else {
include = Utils.mapFinderOptions(include, include.model);
}
// pseudo include just needed the attribute logic, return
if (include._pseudo) {
include.attributes = Object.keys(include.model.tableAttributes);
return Utils.mapFinderOptions(include, include.model);
}
// check if the current Model is actually associated with the passed Model - or it's a pseudo include
const association = include.association || this._getIncludedAssociation(include.model, include.as);
include.association = association;
include.as = association.as;
// If through, we create a pseudo child include, to ease our parsing later on
if (include.association.through && Object(include.association.through.model) === include.association.through.model) {
if (!include.include) include.include = [];
const through = include.association.through;
include.through = _.defaults(include.through || {}, {
model: through.model,
as: through.model.name,
association: {
isSingleAssociation: true
},
_pseudo: true,
parent: include
});
if (through.scope) {
include.through.where = include.through.where ? { [Op.and]: [include.through.where, through.scope]} : through.scope;
}
include.include.push(include.through);
tableNames[through.tableName] = true;
}
// include.model may be the main model, while the association target may be scoped - thus we need to look at association.target/source
let model;
if (include.model.scoped === true) {
// If the passed model is already scoped, keep that
model = include.model;
} else {
// Otherwise use the model that was originally passed to the association
model = include.association.target.name === include.model.name ? include.association.target : include.association.source;
}
model._injectScope(include);
// This check should happen after injecting the scope, since the scope may contain a .attributes
if (!include.attributes) {
include.attributes = Object.keys(include.model.tableAttributes);
}
include = Utils.mapFinderOptions(include, include.model);
if (include.required === undefined) {
include.required = !!include.where;
}
if (include.association.scope) {
include.where = include.where ? { [Op.and]: [include.where, include.association.scope] }: include.association.scope;
}
if (include.limit && include.separate === undefined) {
include.separate = true;
}
if (include.separate === true) {
if (!(include.association instanceof HasMany)) {
throw new Error('Only HasMany associations support include.separate');
}
include.duplicating = false;
if (
options.attributes
&& options.attributes.length
&& !_.flattenDepth(options.attributes, 2).includes(association.sourceKey)
) {
options.attributes.push(association.sourceKey);
}
if (
include.attributes
&& include.attributes.length
&& !_.flattenDepth(include.attributes, 2).includes(association.foreignKey)
) {
include.attributes.push(association.foreignKey);
}
}
// Validate child includes
if (include.hasOwnProperty('include')) {
this._validateIncludedElements.call(include.model, include, tableNames, options);
}
return include;
}
static _getIncludedAssociation(targetModel, targetAlias) {
const associations = this.getAssociations(targetModel);
let association = null;
if (associations.length === 0) {
throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is not associated to ${this.name}!`);
} else if (associations.length === 1) {
association = this.getAssociationForAlias(targetModel, targetAlias);
if (!association) {
if (targetAlias) {
const existingAliases = this.getAssociations(targetModel).map(association => association.as);
throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is associated to ${this.name} using an alias. ` +
`You've included an alias (${targetAlias}), but it does not match the alias(es) defined in your association (${existingAliases.join(', ')}).`);
} else {
throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is associated to ${this.name} using an alias. ` +
'You must use the \'as\' keyword to specify the alias within your include statement.');
}
}
} else {
association = this.getAssociationForAlias(targetModel, targetAlias);
if (!association) {
throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is associated to ${this.name} multiple times. ` +
'To identify the correct association, you must use the \'as\' keyword to specify the alias of the association you want to include.');
}
}
return association;
}
static _expandIncludeAll(options) {
const includes = options.include;
if (!includes) {
return;
}
for (let index = 0; index < includes.length; index++) {
const include = includes[index];
if (include.all) {
includes.splice(index, 1);
index--;
this._expandIncludeAllElement.call(this, includes, include);
}
}
includes.forEach(include => {
this._expandIncludeAll.call(include.model, include);
});
}
static _conformIndex(index) {
if (!index.fields) {
throw new Error('Missing "fields" property for index definition');
}
index = _.defaults(index, {
type: '',
parser: null
});
if (index.type && index.type.toLowerCase() === 'unique') {
index.unique = true;
delete index.type;
}
return index;
}
/**
* Initialize a model, representing a table in the DB, with attributes and options.
*
* The table columns are define by the hash that is given as the first argument.
* Each attribute of the hash represents a column.
*
* For more about <a href="/manual/tutorial/models-definition.html#validations"/>Validations</a>
*
* More examples, <a href="/manual/tutorial/models-definition.html"/>Model Definition</a>
*
* @example
* Project.init({
* columnA: {
* type: Sequelize.BOOLEAN,
* validate: {
* is: ['[a-z]','i'], // will only allow letters
* max: 23, // only allow values <= 23
* isIn: {
* args: [['en', 'zh']],
* msg: "Must be English or Chinese"
* }
* },
* field: 'column_a'
* // Other attributes here
* },
* columnB: Sequelize.STRING,
* columnC: 'MY VERY OWN COLUMN TYPE'
* }, {sequelize})
*
* sequelize.models.modelName // The model will now be available in models under the class name
*
* @see {@link DataTypes}
* @see {@link Hooks}
*
* @param {Object} attributes An object, where each attribute is a column of the table. Each column can be either a DataType, a string or a type-description object, with the properties described below:
* @param {string|DataTypes|Object} attributes.column The description of a database column
* @param {string|DataTypes} attributes.column.type A string or a data type
* @param {boolean} [attributes.column.allowNull=true] If false, the column will have a NOT NULL constraint, and a not null validation will be run before an instance is saved.
* @param {any} [attributes.column.defaultValue=null] A literal default value, a JavaScript function, or an SQL function (see `sequelize.fn`)
* @param {string|boolean} [attributes.column.unique=false] If true, the column will get a unique constraint. If a string is provided, the column will be part of a composite unique index. If multiple columns have the same string, they will be part of the same unique index
* @param {boolean} [attributes.column.primaryKey=false] If true, this attribute will be marked as primary key
* @param {string} [attributes.column.field=null] If set, sequelize will map the attribute name to a different name in the database
* @param {boolean} [attributes.column.autoIncrement=false] If true, this column will be set to auto increment
* @param {string} [attributes.column.comment=null] Comment for this column
* @param {string|Model} [attributes.column.references=null] An object with reference configurations
* @param {string|Model} [attributes.column.references.model] If this column references another table, provide it here as a Model, or a string
* @param {string} [attributes.column.references.key='id'] The column of the foreign table that this column references
* @param {string} [attributes.column.onUpdate] What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION
* @param {string} [attributes.column.onDelete] What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION
* @param {Function} [attributes.column.get] Provide a custom getter for this column. Use `this.getDataValue(String)` to manipulate the underlying values.
* @param {Function} [attributes.column.set] Provide a custom setter for this column. Use `this.setDataValue(String, Value)` to manipulate the underlying values.
* @param {Object} [attributes.validate] An object of validations to execute for this column every time the model is saved. Can be either the name of a validation provided by validator.js, a validation function provided by extending validator.js (see the `DAOValidator` property for more details), or a custom validation function. Custom validation functions are called with the value of the field, and can possibly take a second callback argument, to signal that they are asynchronous. If the validator is sync, it should throw in the case of a failed validation, it it is async, the callback should be called with the error text.
* @param {Object} options These options are merged with the default define options provided to the Sequelize constructor
* @param {Object} options.sequelize Define the sequelize instance to attach to the new Model. Throw error if none is provided.
* @param {string} [options.modelName] Set name of the model. By default its same as Class name.
* @param {Object} [options.defaultScope={}] Define the default search scope to use for this model. Scopes have the same form as the options passed to find / findAll
* @param {Object} [options.scopes] More scopes, defined in the same way as defaultScope above. See `Model.scope` for more information about how scopes are defined, and what you can do with them
* @param {boolean} [options.omitNull] Don't persist null values. This means that all columns with null values will not be saved
* @param {boolean} [options.timestamps=true] Adds createdAt and updatedAt timestamps to the model.
* @param {boolean} [options.paranoid=false] Calling `destroy` will not delete the model, but instead set a `deletedAt` timestamp if this is true. Needs `timestamps=true` to work
* @param {boolean} [options.underscored=false] Add underscored field to all attributes, this covers user defined attributes, timestamps and foreign keys. Will not affect attributes with explicitly set `field` option
* @param {boolean} [options.freezeTableName=false] If freezeTableName is true, sequelize will not try to alter the model name to get the table name. Otherwise, the model name will be pluralized
* @param {Object} [options.name] An object with two attributes, `singular` and `plural`, which are used when this model is associated to others.
* @param {string} [options.name.singular=Utils.singularize(modelName)] Singular name for model
* @param {string} [options.name.plural=Utils.pluralize(modelName)] Plural name for model
* @param {Array<Object>} [options.indexes] indexes definitions
* @param {string} [options.indexes[].name] The name of the index. Defaults to model name + _ + fields concatenated
* @param {string} [options.indexes[].type] Index type. Only used by mysql. One of `UNIQUE`, `FULLTEXT` and `SPATIAL`
* @param {string} [options.indexes[].using] The method to create the index by (`USING` statement in SQL). BTREE and HASH are supported by mysql and postgres, and postgres additionally supports GIST and GIN.
* @param {boolean} [options.indexes[].unique=false] Should the index by unique? Can also be triggered by setting type to `UNIQUE`
* @param {boolean} [options.indexes[].concurrently=false] PostgresSQL will build the index without taking any write locks. Postgres only
* @param {Array<string|Object>} [options.indexes[].fields] An array of the fields to index. Each field can either be a string containing the name of the field, a sequelize object (e.g `sequelize.fn`), or an object with the following attributes: `attribute` (field name), `length` (create a prefix index of length chars), `order` (the direction the column should be sorted in), `collate` (the collation (sort order) for the column)
* @param {string|boolean} [options.createdAt] Override the name of the createdAt attribute if a string is provided, or disable it if false. Timestamps must be true. Underscored field will be set with underscored setting.
* @param {string|boolean} [options.updatedAt] Override the name of the updatedAt attribute if a string is provided, or disable it if false. Timestamps must be true. Underscored field will be set with underscored setting.
* @param {string|boolean} [options.deletedAt] Override the name of the deletedAt attribute if a string is provided, or disable it if false. Timestamps must be true. Underscored field will be set with underscored setting.
* @param {string} [options.tableName] Defaults to pluralized model name, unless freezeTableName is true, in which case it uses model name verbatim
* @param {string} [options.schema='public'] schema
* @param {string} [options.engine] Specify engine for model's table
* @param {string} [options.charset] Specify charset for model's table
* @param {string} [options.comment] Specify comment for model's table
* @param {string} [options.collate] Specify collation for model's table
* @param {string} [options.initialAutoIncrement] Set the initial AUTO_INCREMENT value for the table in MySQL.
* @param {Object} [options.hooks] An object of hook function that are called before and after certain lifecycle events. The possible hooks are: beforeValidate, afterValidate, validationFailed, beforeBulkCreate, beforeBulkDestroy, beforeBulkUpdate, beforeCreate, beforeDestroy, beforeUpdate, afterCreate, afterDestroy, afterUpdate, afterBulkCreate, afterBulkDestroy and afterBulkUpdate. See Hooks for more information about hook functions and their signatures. Each property can either be a function, or an array of functions.
* @param {Object} [options.validate] An object of model wide validations. Validations have access to all model values via `this`. If the validator function takes an argument, it is assumed to be async, and is called with a callback that accepts an optional error.
*
* @returns {Model}
*/
static init(attributes, options = {}) { // testhint options:none
if (!options.sequelize) {
throw new Error('No Sequelize instance passed');
}
this.sequelize = options.sequelize;
const globalOptions = this.sequelize.options;
options = Utils.merge(_.cloneDeep(globalOptions.define), options);
if (!options.modelName) {
options.modelName = this.name;
}
options = Utils.merge({
name: {
plural: Utils.pluralize(options.modelName),
singular: Utils.singularize(options.modelName)
},
indexes: [],
omitNull: globalOptions.omitNull,
schema: globalOptions.schema
}, options);
this.sequelize.runHooks('beforeDefine', attributes, options);
if (options.modelName !== this.name) {
Object.defineProperty(this, 'name', {value: options.modelName});
}
delete options.modelName;
this.options = Object.assign({
timestamps: true,
validate: {},
freezeTableName: false,
underscored: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: {},
indexes: []
}, options);
// if you call "define" multiple times for the same modelName, do not clutter the factory
if (this.sequelize.isDefined(this.name)) {
this.sequelize.modelManager.removeModel(this.sequelize.modelManager.getModel(this.name));
}
this.associations = {};
this._setupHooks(options.hooks);
this.underscored = this.options.underscored;
if (!this.options.tableName) {
this.tableName = this.options.freezeTableName ? this.name : Utils.underscoredIf(Utils.pluralize(this.name), this.underscored);
} else {
this.tableName = this.options.tableName;
}
this._schema = this.options.schema;
this._schemaDelimiter = this.options.schemaDelimiter;
// error check options
_.each(options.validate, (validator, validatorType) => {
if (attributes.hasOwnProperty(validatorType)) {
throw new Error(`A model validator function must not have the same name as a field. Model: ${this.name}, field/validation name: ${validatorType}`);
}
if (!_.isFunction(validator)) {
throw new Error(`Members of the validate option must be functions. Model: ${this.name}, error with validate member ${validatorType}`);
}
});
this.rawAttributes = _.mapValues(attributes, (attribute, name) => {
attribute = this.sequelize.normalizeAttribute(attribute);
if (attribute.type === undefined) {
throw new Error(`Unrecognized datatype for attribute "${this.name}.${name}"`);
}
if (attribute.allowNull !== false && _.get(attribute, 'validate.notNull')) {
throw new Error(`Invalid definition for "${this.name}.${name}", "notNull" validator is only allowed with "allowNull:false"`);
}
if (_.get(attribute, 'references.model.prototype') instanceof Model) {
attribute.references.model = attribute.references.model.getTableName();
}
return attribute;
});
this._indexes = this.options.indexes
.map(index => this._conformIndex(index))
.map(index => Utils.nameIndex(index, this.getTableName()));
this.primaryKeys = {};
this._readOnlyAttributes = [];
this._timestampAttributes = {};
// setup names of timestamp attributes
if (this.options.timestamps) {
if (this.options.createdAt !== false) {
this._timestampAttributes.createdAt = this.options.createdAt || 'createdAt';
this._readOnlyAttributes.push(this._timestampAttributes.createdAt);
}
if (this.options.updatedAt !== false) {
this._timestampAttributes.updatedAt = this.options.updatedAt || 'updatedAt';
this._readOnlyAttributes.push(this._timestampAttributes.updatedAt);
}
if (this.options.paranoid && this.options.deletedAt !== false) {
this._timestampAttributes.deletedAt = this.options.deletedAt || 'deletedAt';
this._readOnlyAttributes.push(this._timestampAttributes.deletedAt);
}
}
// setup name for version attribute
if (this.options.version) {
this._versionAttribute = typeof this.options.version === 'string' ? this.options.version : 'version';
this._readOnlyAttributes.push(this._versionAttribute);
}
this._hasReadOnlyAttributes = this._readOnlyAttributes.length > 0;
this._isReadOnlyAttribute = _.memoize(key => this._readOnlyAttributes.includes(key));
// Add head and tail default attributes (id, timestamps)
this._addDefaultAttributes();
this.refreshAttributes();
this._findAutoIncrementAttribute();
this._scope = this.options.defaultScope;
this._scopeNames = ['defaultScope'];
if (_.isPlainObject(this._scope)) {
this._conformOptions(this._scope, this);
}
_.each(this.options.scopes, scope => {
if (_.isPlainObject(scope)) {
this._conformOptions(scope, this);
}
});
this.sequelize.modelManager.addModel(this);
this.sequelize.runHooks('afterDefine', this);
return this;
}
static refreshAttributes() {
const attributeManipulation = {};