forked from sequelize/sequelize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.js
2739 lines (2353 loc) · 100 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';
/* jshint -W110 */
var Utils = require('./utils')
, Instance = require('./instance')
, Association = require('./associations/base')
, HasMany = require('./associations/has-many')
, DataTypes = require('./data-types')
, Util = require('util')
, Transaction = require('./transaction')
, Promise = require('./promise')
, QueryTypes = require('./query-types')
, Hooks = require('./hooks')
, sequelizeErrors = require('./errors')
, _ = require('lodash')
, associationsMixin = require('./associations/mixin');
/**
* A Model represents a table in the database. Sometimes you might also see it referred to as model, or simply as factory.
* This class should _not_ be instantiated directly, it is created using `sequelize.define`, and already created models can be loaded using `sequelize.import`
*
* @class Model
* @mixes Hooks
* @mixes Associations
*/
var Model = function(name, attributes, options) {
this.options = Utils._.extend({
timestamps: true,
instanceMethods: {},
classMethods: {},
validate: {},
freezeTableName: false,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: [],
hooks: {},
indexes: []
}, options || {});
this.associations = {};
this.modelManager = null;
this.name = name;
this.options.hooks = _.mapValues(this.replaceHookAliases(this.options.hooks), function (hooks) {
if (!Array.isArray(hooks)) hooks = [hooks];
return hooks;
});
this.sequelize = options.sequelize;
this.underscored = this.underscored || this.underscoredAll;
if (!this.options.tableName) {
this.tableName = this.options.freezeTableName ? name : Utils.underscoredIf(Utils.pluralize(name), this.options.underscoredAll);
} else {
this.tableName = this.options.tableName;
}
this.$schema = this.options.schema;
this.$schemaDelimiter = this.options.schemaDelimiter;
// error check options
_.each(options.validate, function(validator, validatorType) {
if (_.includes(Utils._.keys(attributes), validatorType)) {
throw new Error('A model validator function must not have the same name as a field. Model: ' + name + ', field/validation name: ' + validatorType);
}
if (!_.isFunction(validator)) {
throw new Error('Members of the validate option must be functions. Model: ' + name + ', error with validate member ' + validatorType);
}
});
this.attributes = this.rawAttributes = _.mapValues(attributes, function(attribute, name) {
if (!Utils._.isPlainObject(attribute)) {
attribute = { type: attribute };
}
attribute = this.sequelize.normalizeAttribute(attribute);
if (attribute.references) {
attribute = Utils.formatReferences(attribute);
if (attribute.references.model instanceof Model) {
attribute.references.model = attribute.references.model.tableName;
}
}
if (attribute.type === undefined) {
throw new Error('Unrecognized data type for field ' + name);
}
return attribute;
}.bind(this));
};
Object.defineProperty(Model.prototype, 'QueryInterface', {
get: function() {
return this.modelManager.sequelize.getQueryInterface();
}
});
Object.defineProperty(Model.prototype, 'QueryGenerator', {
get: function() {
return this.QueryInterface.QueryGenerator;
}
});
Model.prototype.toString = function () {
return '[object SequelizeModel:'+this.name+']';
};
// private
// validateIncludedElements should have been called before this method
var paranoidClause = function(model, options) {
options = 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) {
options.include.forEach(function(include) {
paranoidClause(include.model, include);
});
}
if (!model.options.timestamps || !model.options.paranoid || options.paranoid === false) {
// This model is not paranoid, nothing to do here;
return options;
}
var deletedAtCol = model._timestampAttributes.deletedAt
, deletedAtAttribute = model.rawAttributes[deletedAtCol]
, deletedAtObject = {}
, deletedAtDefaultValue = deletedAtAttribute.hasOwnProperty('defaultValue') ? deletedAtAttribute.defaultValue : null;
deletedAtObject[deletedAtAttribute.field || deletedAtCol] = deletedAtDefaultValue;
if (Utils._.isEmpty(options.where)) {
options.where = deletedAtObject;
} else {
options.where = { $and: [deletedAtObject, options.where] };
}
return options;
};
var addOptionalClassMethods = function() {
var self = this;
Utils._.each(this.options.classMethods || {}, function(fct, name) { self[name] = fct; });
};
var addDefaultAttributes = function() {
var self = this
, tail = {}
, 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
};
}
var existingAttributes = Utils._.clone(self.rawAttributes);
self.rawAttributes = {};
Utils._.each(head, function(value, attr) {
self.rawAttributes[attr] = value;
});
Utils._.each(existingAttributes, function(value, attr) {
self.rawAttributes[attr] = value;
});
Utils._.each(tail, function(value, attr) {
if (Utils._.isUndefined(self.rawAttributes[attr])) {
self.rawAttributes[attr] = value;
}
});
if (!Object.keys(this.primaryKeys).length) {
self.primaryKeys.id = self.rawAttributes.id;
}
};
var findAutoIncrementField = function() {
var fields = this.QueryGenerator.findAutoIncrementField(this);
this.autoIncrementField = null;
fields.forEach(function(field) {
if (this.autoIncrementField) {
throw new Error('Invalid Instance definition. Only one autoincrement field allowed.');
} else {
this.autoIncrementField = field;
}
}.bind(this));
};
function 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(function(include) {
include = conformInclude(include, self);
return include;
});
}
Model.$conformOptions = conformOptions;
function conformInclude(include, self) {
var model;
if (include._pseudo) return include;
if (include instanceof Association) {
if (self && include.target.name === self.name) {
model = include.source;
} else {
model = include.target;
}
include = { model: model, association: include, as: include.as };
} else if (include instanceof Model) {
include = { model: include };
} else if (_.isPlainObject(include)) {
if (include.association) {
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;
}
conformOptions(include, model);
} else {
throw new Error('Include unexpected. Element has to be either a Model, an Association or an object.');
}
return include;
}
Model.$conformInclude = conformInclude;
var optClone = Model.prototype.__optClone = Model.prototype.$optClone = function(options) {
options = options || {};
return Utils.cloneDeep(options, function(elem) {
// The InstanceFactories used for include are pass by ref, so don't clone them.
if (elem && typeof elem === 'object' &&
(
elem._isSequelizeMethod ||
elem instanceof Model ||
elem instanceof Instance ||
elem instanceof Transaction ||
elem instanceof Association
)
) {
return elem;
}
// Otherwise return undefined, meaning, 'handle this lodash'
return undefined;
});
};
var expandIncludeAllElement = function(includes, include) {
// check 'all' attribute provided is valid
var all = include.all;
delete include.all;
if (all !== true) {
if (!Array.isArray(all)) {
all = [all];
}
var validTypes = {
BelongsTo: true,
HasOne: true,
HasMany: true,
One: ['BelongsTo', 'HasOne'],
Has: ['HasOne', 'HasMany'],
Many: ['HasMany']
};
for (var i = 0; i < all.length; i++) {
var type = all[i];
if (type === 'All') {
all = true;
break;
}
var types = validTypes[type];
if (!types) {
throw new Error('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 it's constituent types e.g. 'HasOne', 'BelongsTo'
all.splice(i, 1);
i--;
for (var j = 0; j < types.length; j++) {
if (all.indexOf(types[j]) === -1) {
all.unshift(types[j]);
i++;
}
}
}
}
}
// add all associations of types specified to includes
var nested = include.nested;
if (nested) {
delete include.nested;
if (!include.include) {
include.include = [];
} else if (!Array.isArray(include.include)) {
include.include = [include.include];
}
}
var used = [];
(function addAllIncludes(parent, includes) {
Utils._.forEach(parent.associations, function(association) {
if (all !== true && all.indexOf(association.associationType) === -1) {
return;
}
// check if model already included, and skip if so
var model = association.target;
var as = association.options.as;
var predicate = {model: model};
if (as) {
// We only add 'as' to the predicate if it actually exists
predicate.as = as;
}
if (Utils._.find(includes, predicate)) {
return;
}
// skip if recursing over a model already nested
if (nested && used.indexOf(model) !== -1) {
return;
}
used.push(parent);
// include this model
var thisInclude = optClone(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);
};
var validateIncludedElement;
var validateIncludedElements = function(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(function (include) {
include = conformInclude(include);
include.parent = options;
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;
});
options.include.forEach(function (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;
}
return include;
});
if (options.topModel === options.model && options.subQuery === undefined) {
options.subQuery = false;
}
return options;
};
Model.$validateIncludedElements = validateIncludedElements;
validateIncludedElement = function(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, function (attr, key) {
// Include the primary key if its not already take - take into account that the pk might be aliassed (due to a .field prop)
if (!_.some(include.attributes, function (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
var association = include.association || this.getAssociation(include.model, include.as);
if (!association) {
var msg = include.model.name;
if (include.as) {
msg += ' (' + include.as + ')';
}
msg += ' is not associated to ' + this.name + '!';
throw new Error(msg);
}
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 = [];
var through = include.association.through;
include.through = Utils._.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 ? { $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
var 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 ? { $and: [include.where, include.association.scope] }: include.association.scope;
}
if (include.limit && include.separate === undefined) {
include.separate = true;
}
if (include.separate === true && !(include.association instanceof HasMany)) {
throw new Error('Only HasMany associations support include.separate');
}
if (include.separate === true) {
include.duplicating = false;
}
if (include.separate === true && options.attributes && options.attributes.length && !_.includes(options.attributes, association.source.primaryKeyAttribute)) {
options.attributes.push(association.source.primaryKeyAttribute);
}
// Validate child includes
if (include.hasOwnProperty('include')) {
validateIncludedElements.call(include.model, include, tableNames, options);
}
return include;
};
var expandIncludeAll = Model.$expandIncludeAll = function(options) {
var includes = options.include;
if (!includes) {
return;
}
for (var index = 0; index < includes.length; index++) {
var include = includes[index];
if (include.all) {
includes.splice(index, 1);
index--;
expandIncludeAllElement.call(this, includes, include);
}
}
Utils._.forEach(includes, function(include) {
expandIncludeAll.call(include.model, include);
});
};
Model.prototype.init = function(modelManager) {
var self = this;
this.modelManager = modelManager;
this.primaryKeys = {};
// Setup names of timestamp attributes
this._timestampAttributes = {};
if (this.options.timestamps) {
if (this.options.createdAt !== false) {
this._timestampAttributes.createdAt = this.options.createdAt || Utils.underscoredIf('createdAt', this.options.underscored);
}
if (this.options.updatedAt !== false) {
this._timestampAttributes.updatedAt = this.options.updatedAt || Utils.underscoredIf('updatedAt', this.options.underscored);
}
if (this.options.paranoid && this.options.deletedAt !== false) {
this._timestampAttributes.deletedAt = this.options.deletedAt || Utils.underscoredIf('deletedAt', this.options.underscored);
}
}
// Add head and tail default attributes (id, timestamps)
addOptionalClassMethods.call(this);
// Instance prototype
this.Instance = function() {
Instance.apply(this, arguments);
};
Util.inherits(this.Instance, Instance);
this._readOnlyAttributes = Utils._.values(this._timestampAttributes);
this._hasReadOnlyAttributes = this._readOnlyAttributes && this._readOnlyAttributes.length;
this._isReadOnlyAttribute = Utils._.memoize(function(key) {
return self._hasReadOnlyAttributes && self._readOnlyAttributes.indexOf(key) !== -1;
});
if (this.options.instanceMethods) {
Utils._.each(this.options.instanceMethods, function(fct, name) {
self.Instance.prototype[name] = fct;
});
}
addDefaultAttributes.call(this);
this.refreshAttributes();
findAutoIncrementField.call(this);
this.$scope = this.options.defaultScope;
if (_.isPlainObject(this.$scope)) {
conformOptions(this.$scope, this);
}
_.each(this.options.scopes, function (scope) {
if (_.isPlainObject(scope)) {
conformOptions(scope, this);
}
}.bind(this));
this.options.indexes = this.options.indexes.map(this.$conformIndex);
this.Instance.prototype.$Model =
this.Instance.prototype.Model = this;
return this;
};
Model.prototype.$conformIndex = function (index) {
index = _.defaults(index, {
type: '',
parser: null
});
if (index.type && index.type.toLowerCase() === 'unique') {
index.unique = true;
delete index.type;
}
return index;
};
Model.prototype.refreshAttributes = function() {
var self = this
, attributeManipulation = {};
this.Instance.prototype._customGetters = {};
this.Instance.prototype._customSetters = {};
Utils._.each(['get', 'set'], function(type) {
var opt = type + 'terMethods'
, funcs = Utils._.clone(Utils._.isObject(self.options[opt]) ? self.options[opt] : {})
, _custom = type === 'get' ? self.Instance.prototype._customGetters : self.Instance.prototype._customSetters;
Utils._.each(funcs, function(method, attribute) {
_custom[attribute] = method;
if (type === 'get') {
funcs[attribute] = function() {
return this.get(attribute);
};
}
if (type === 'set') {
funcs[attribute] = function(value) {
return this.set(attribute, value);
};
}
});
Utils._.each(self.rawAttributes, function(options, attribute) {
if (options.hasOwnProperty(type)) {
_custom[attribute] = options[type];
}
if (type === 'get') {
funcs[attribute] = function() {
return this.get(attribute);
};
}
if (type === 'set') {
funcs[attribute] = function(value) {
return this.set(attribute, value);
};
}
});
Utils._.each(funcs, function(fct, name) {
if (!attributeManipulation[name]) {
attributeManipulation[name] = {
configurable: true
};
}
attributeManipulation[name][type] = fct;
});
});
this._booleanAttributes = [];
this._dateAttributes = [];
this._hstoreAttributes = [];
this._rangeAttributes = [];
this._jsonAttributes = [];
this._geometryAttributes = [];
this._virtualAttributes = [];
this._defaultValues = {};
this.Instance.prototype.validators = {};
this.fieldRawAttributesMap = {};
this.primaryKeys = {};
self.options.uniqueKeys = {};
_.each(this.rawAttributes, function(definition, name) {
definition.type = self.sequelize.normalizeDataType(definition.type);
definition.Model = self;
definition.fieldName = name;
definition._modelAttribute = true;
if (definition.field === undefined) {
definition.field = name;
}
if (definition.primaryKey === true) {
self.primaryKeys[name] = definition;
}
self.fieldRawAttributesMap[definition.field] = definition;
if (definition.type instanceof DataTypes.BOOLEAN) {
self._booleanAttributes.push(name);
} else if (definition.type instanceof DataTypes.DATE) {
self._dateAttributes.push(name);
} else if (definition.type instanceof DataTypes.HSTORE || DataTypes.ARRAY.is(definition.type, DataTypes.HSTORE)) {
self._hstoreAttributes.push(name);
} else if (definition.type instanceof DataTypes.RANGE || DataTypes.ARRAY.is(definition.type, DataTypes.RANGE)) {
self._rangeAttributes.push(name);
} else if (definition.type instanceof DataTypes.JSON) {
self._jsonAttributes.push(name);
} else if (definition.type instanceof DataTypes.VIRTUAL) {
self._virtualAttributes.push(name);
} else if (definition.type instanceof DataTypes.GEOMETRY) {
self._geometryAttributes.push(name);
}
if (definition.hasOwnProperty('defaultValue')) {
self._defaultValues[name] = Utils._.partial(Utils.toDefaultValue, definition.defaultValue);
}
if (definition.hasOwnProperty('unique') && definition.unique !== false) {
var idxName;
if (typeof definition.unique === 'object' && definition.unique.hasOwnProperty('name')) {
idxName = definition.unique.name;
} else if (typeof definition.unique === 'string') {
idxName = definition.unique;
} else {
idxName = self.tableName + '_' + name + '_unique';
}
var idx = self.options.uniqueKeys[idxName] || { fields: [] };
idx = idx || {fields: [], msg: null};
idx.fields.push(definition.field);
idx.msg = idx.msg || definition.unique.msg || null;
idx.name = idxName || false;
idx.column = name;
self.options.uniqueKeys[idxName] = idx;
}
if (definition.hasOwnProperty('validate')) {
self.Instance.prototype.validators[name] = definition.validate;
}
if (definition.index === true && definition.type instanceof DataTypes.JSONB) {
self.options.indexes.push({
fields: [definition.field || name],
using: 'gin'
});
delete definition.index;
}
});
// Create a map of field to attribute names
this.fieldAttributeMap = Utils._.reduce(this.fieldRawAttributesMap, function(map, value, key) {
if (key !== value.fieldName) {
map[key] = value.fieldName;
}
return map;
}, {});
this.uniqueKeys = this.options.uniqueKeys;
this._hasBooleanAttributes = !!this._booleanAttributes.length;
this._isBooleanAttribute = Utils._.memoize(function(key) {
return self._booleanAttributes.indexOf(key) !== -1;
});
this._hasDateAttributes = !!this._dateAttributes.length;
this._isDateAttribute = Utils._.memoize(function(key) {
return self._dateAttributes.indexOf(key) !== -1;
});
this._hasHstoreAttributes = !!this._hstoreAttributes.length;
this._isHstoreAttribute = Utils._.memoize(function(key) {
return self._hstoreAttributes.indexOf(key) !== -1;
});
this._hasRangeAttributes = !!this._rangeAttributes.length;
this._isRangeAttribute = Utils._.memoize(function(key) {
return self._rangeAttributes.indexOf(key) !== -1;
});
this._hasJsonAttributes = !!this._jsonAttributes.length;
this._isJsonAttribute = Utils._.memoize(function(key) {
return self._jsonAttributes.indexOf(key) !== -1;
});
this._hasVirtualAttributes = !!this._virtualAttributes.length;
this._isVirtualAttribute = Utils._.memoize(function(key) {
return self._virtualAttributes.indexOf(key) !== -1;
});
this._hasGeometryAttributes = !!this._geometryAttributes.length;
this._isGeometryAttribute = Utils._.memoize(function(key) {
return self._geometryAttributes.indexOf(key) !== -1;
});
this._hasDefaultValues = !Utils._.isEmpty(this._defaultValues);
this.attributes = this.rawAttributes;
this.tableAttributes = Utils._.omit(this.rawAttributes, this._virtualAttributes);
this.Instance.prototype._hasCustomGetters = Object.keys(this.Instance.prototype._customGetters).length;
this.Instance.prototype._hasCustomSetters = Object.keys(this.Instance.prototype._customSetters).length;
Object.keys(attributeManipulation).forEach((function(key){
if (Instance.prototype.hasOwnProperty(key)) {
this.sequelize.log("Not overriding built-in method from model attribute: " + key);
return;
}
Object.defineProperty(this.Instance.prototype, key, attributeManipulation[key]);
}).bind(this));
this.Instance.prototype.rawAttributes = this.rawAttributes;
this.Instance.prototype.attributes = Object.keys(this.Instance.prototype.rawAttributes);
this.Instance.prototype._isAttribute = Utils._.memoize(function(key) {
return self.Instance.prototype.attributes.indexOf(key) !== -1;
});
// Primary key convenience variables
this.primaryKeyAttributes = Object.keys(this.primaryKeys);
this.primaryKeyAttribute = this.primaryKeyAttributes[0];
if (this.primaryKeyAttribute) {
this.primaryKeyField = this.rawAttributes[this.primaryKeyAttribute].field || this.primaryKeyAttribute;
}
this.primaryKeyCount = this.primaryKeyAttributes.length;
this._hasPrimaryKeys = this.options.hasPrimaryKeys = this.hasPrimaryKeys = this.primaryKeyCount > 0;
this._isPrimaryKey = Utils._.memoize(function(key) {
return self.primaryKeyAttributes.indexOf(key) !== -1;
});
};
/**
* Remove attribute from model definition
* @param {String} [attribute]
*/
Model.prototype.removeAttribute = function(attribute) {
delete this.rawAttributes[attribute];
this.refreshAttributes();
};
/**
* Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the model instance (this)
* @see {Sequelize#sync} for options
* @return {Promise<this>}
*/
Model.prototype.sync = function(options) {
options = options || {};
options.hooks = options.hooks === undefined ? true : !!options.hooks;
options = Utils._.extend({}, this.options, options);
var self = this
, attributes = this.tableAttributes;
return Promise.try(function () {