instance.js
39.6 KB
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
'use strict';
var Utils = require('./utils')
, BelongsTo = require('./associations/belongs-to')
, BelongsToMany = require('./associations/belongs-to-many')
, InstanceValidator = require('./instance-validator')
, QueryTypes = require('./query-types')
, sequelizeErrors = require('./errors')
, Dottie = require('dottie')
, Promise = require('./promise')
, _ = require('lodash')
, defaultsOptions = { raw: true };
// private
var initValues = function(values, options) {
var defaults
, key;
values = values && _.clone(values) || {};
if (options.isNewRecord) {
defaults = {};
if (this.Model._hasDefaultValues) {
defaults = _.mapValues(this.Model._defaultValues, function(valueFn) {
var value = valueFn();
return (value && value._isSequelizeMethod) ? 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 (!defaults.hasOwnProperty(this.Model.primaryKeyAttribute)) {
defaults[this.Model.primaryKeyAttribute] = null;
}
if (this.Model._timestampAttributes.createdAt && defaults[this.Model._timestampAttributes.createdAt]) {
this.dataValues[this.Model._timestampAttributes.createdAt] = Utils.toDefaultValue(defaults[this.Model._timestampAttributes.createdAt]);
delete defaults[this.Model._timestampAttributes.createdAt];
}
if (this.Model._timestampAttributes.updatedAt && defaults[this.Model._timestampAttributes.updatedAt]) {
this.dataValues[this.Model._timestampAttributes.updatedAt] = Utils.toDefaultValue(defaults[this.Model._timestampAttributes.updatedAt]);
delete defaults[this.Model._timestampAttributes.updatedAt];
}
if (this.Model._timestampAttributes.deletedAt && defaults[this.Model._timestampAttributes.deletedAt]) {
this.dataValues[this.Model._timestampAttributes.deletedAt] = Utils.toDefaultValue(defaults[this.Model._timestampAttributes.deletedAt]);
delete defaults[this.Model._timestampAttributes.deletedAt];
}
if (Object.keys(defaults).length) {
for (key in defaults) {
if (values[key] === undefined) {
this.set(key, Utils.toDefaultValue(defaults[key]), defaultsOptions);
delete values[key];
}
}
}
}
this.set(values, options);
};
/**
* This class represents an single instance, a database row. You might see it referred to as both Instance and instance. You should not
* instantiate the Instance class directly, instead you access it using the finder and creation methods on the model.
*
* Instance 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 {Sequelize#define} for more information about getters and setters
* @class Instance
*/
var Instance = function(values, options) {
this.dataValues = {};
this._previousDataValues = {};
this._changed = {};
this.$modelOptions = this.Model.options;
this.$options = options || {};
this.hasPrimaryKeys = this.Model.options.hasPrimaryKeys;
this.__eagerlyLoadedAssociations = [];
/**
* Returns true if this instance has not yet been persisted to the database
* @property isNewRecord
* @return {Boolean}
*/
this.isNewRecord = options.isNewRecord;
/**
* Returns the Model the instance was created from.
* @see {Model}
* @property Model
* @return {Model}
*/
initValues.call(this, values, options);
};
/**
* A reference to the sequelize instance
* @see {Sequelize}
* @property sequelize
* @return {Sequelize}
*/
Object.defineProperty(Instance.prototype, 'sequelize', {
get: function() { return this.Model.modelManager.sequelize; }
});
/**
* Get an object representing the query for this instance, use with `options.where`
*
* @property where
* @return {Object}
*/
Instance.prototype.where = function() {
var where;
where = this.Model.primaryKeyAttributes.reduce(function (result, attribute) {
result[attribute] = this.get(attribute, {raw: true});
return result;
}.bind(this), {});
if (_.size(where) === 0) {
return this.$modelOptions.whereCollection;
}
return Utils.mapWhereFieldNames(where, this.$Model);
};
Instance.prototype.toString = function () {
return '[object SequelizeInstance:'+this.Model.name+']';
};
/**
* Get the value of the underlying data value
*
* @param {String} key
* @return {any}
*/
Instance.prototype.getDataValue = function(key) {
return this.dataValues[key];
};
/**
* Update the underlying data value
*
* @param {String} key
* @param {any} value
*/
Instance.prototype.setDataValue = function(key, value) {
var originalValue = this._previousDataValues[key];
if ((!Utils.isPrimitive(value) && value !== null) || value !== originalValue) {
this.changed(key, true);
}
this.dataValues[key] = value;
};
/**
* If no key is given, returns all values of the instance, also invoking virtual getters.
*
* If key is given and a field or virtual getter is present for the key it will call that getter - else it will return the value for key.
*
* @param {String} [key]
* @param {Object} [options]
* @param {Boolean} [options.plain=false] If set to true, included instances will be returned as plain objects
* @return {Object|any}
*/
Instance.prototype.get = function(key, options) { // testhint options:none
if (options === undefined && typeof key === 'object') {
options = key;
key = undefined;
}
options = options || {};
if (key) {
if (this._customGetters[key]) {
return this._customGetters[key].call(this, key, options);
}
if (options && options.plain && this.$options.include && this.$options.includeNames.indexOf(key) !== -1) {
if (Array.isArray(this.dataValues[key])) {
return this.dataValues[key].map(function (instance) {
return instance.get(options);
});
} else if (this.dataValues[key] instanceof Instance) {
return this.dataValues[key].get(options);
} else {
return this.dataValues[key];
}
}
return this.dataValues[key];
}
if (this._hasCustomGetters || (options && options.plain && this.$options.include) || (options && options.clone)) {
var values = {}
, _key;
if (this._hasCustomGetters) {
for (_key in this._customGetters) {
if (this._customGetters.hasOwnProperty(_key)) {
values[_key] = this.get(_key, options);
}
}
}
for (_key in this.dataValues) {
if (!values.hasOwnProperty(_key) && this.dataValues.hasOwnProperty(_key)) {
values[_key] = this.get(_key, options);
}
}
return values;
}
return this.dataValues;
};
/**
* Set is used to update values on the instance (the sequelize representation of the instance that is, remember that nothing will be persisted before you actually call `save`).
* In its most basic form `set` will update a value stored in the underlying `dataValues` object. However, if a custom setter function is defined for the key, that function
* will be called instead. To bypass the setter, you can pass `raw: true` in the options object.
*
* If set is called with an object, it will loop over the object, and call set recursively for each key, value pair. If you set raw to true, the underlying dataValues will either be
* set directly to the object passed, or used to extend dataValues, if dataValues already contain values.
*
* When set is called, the previous value of the field is stored and sets a changed flag(see `changed`).
*
* Set can also be used to build instances for associations, if you have values for those.
* When using set with associations you need to make sure the property key matches the alias of the association
* while also making sure that the proper include options have been set (from .build() or .find())
*
* If called with a dot.separated key on a JSON/JSONB attribute it will set the value nested and flag the entire object as changed.
*
* @see {Model#find} for more information about includes
* @param {String|Object} key
* @param {any} value
* @param {Object} [options]
* @param {Boolean} [options.raw=false] If set to true, field and virtual setters will be ignored
* @param {Boolean} [options.reset=false] Clear all previously set data values
* @alias setAttributes
*/
Instance.prototype.set = function(key, value, options) { // testhint options:none
var values
, originalValue
, keys
, i
, length;
if (typeof key === 'object' && key !== null) {
values = key;
options = value || {};
if (options.reset) {
this.dataValues = {};
}
// If raw, and we're not dealing with includes or special attributes, just set it straight on the dataValues object
if (options.raw && !(this.$options && this.$options.include) && !(options && options.attributes) && !this.Model._hasBooleanAttributes && !this.Model._hasDateAttributes) {
if (Object.keys(this.dataValues).length) {
this.dataValues = _.extend(this.dataValues, values);
} else {
this.dataValues = values;
}
// If raw, .changed() shouldn't be true
this._previousDataValues = _.clone(this.dataValues);
} else {
// Loop and call set
if (options.attributes) {
keys = options.attributes;
if (this.Model._hasVirtualAttributes) {
keys = keys.concat(this.Model._virtualAttributes);
}
if (this.$options.includeNames) {
keys = keys.concat(this.$options.includeNames);
}
for (i = 0, length = keys.length; i < length; i++) {
if (values[keys[i]] !== undefined) {
this.set(keys[i], values[keys[i]], options);
}
}
} else {
for (key in values) {
this.set(key, values[key], options);
}
}
if (options.raw) {
// If raw, .changed() shouldn't be true
this._previousDataValues = _.clone(this.dataValues);
}
}
} else {
if (!options)
options = {};
if (!options.raw) {
originalValue = this.dataValues[key];
}
// If not raw, and there's a customer setter
if (!options.raw && this._customSetters[key]) {
this._customSetters[key].call(this, value, key);
// custom setter should have changed value, get that changed value
var newValue = this.dataValues[key];
if (!Utils.isPrimitive(newValue) && newValue !== null || newValue !== originalValue) {
this._previousDataValues[key] = originalValue;
this.changed(key, true);
}
} else {
// Check if we have included models, and if this key matches the include model names/aliases
if (this.$options && this.$options.include && this.$options.includeNames.indexOf(key) !== -1) {
// Pass it on to the include handler
this._setInclude(key, value, options);
return this;
} else {
// Bunch of stuff we won't do when its raw
if (!options.raw) {
// If attribute is not in model definition, return
if (!this._isAttribute(key)) {
if (key.indexOf('.') > -1 && this.Model._isJsonAttribute(key.split('.')[0])) {
var previousDottieValue = Dottie.get(this.dataValues, key);
if (!_.isEqual(previousDottieValue, value)) {
Dottie.set(this.dataValues, key, value);
this.changed(key.split('.')[0], true);
}
}
return this;
}
// If attempting to set primary key and primary key is already defined, return
if (this.Model._hasPrimaryKeys && originalValue && this.Model._isPrimaryKey(key)) {
return this;
}
// If attempting to set read only attributes, return
if (!this.isNewRecord && this.Model._hasReadOnlyAttributes && this.Model._isReadOnlyAttribute(key)) {
return this;
}
// Convert date fields to real date objects
if (this.Model._hasDateAttributes && this.Model._isDateAttribute(key) && !!value && !value._isSequelizeMethod) {
if (!(value instanceof Date)) {
value = new Date(value);
}
if (originalValue) {
if (!(originalValue instanceof Date)) {
originalValue = new Date(originalValue);
}
if (value.getTime() === originalValue.getTime()) {
return this;
}
}
}
}
// Convert boolean-ish values to booleans
if (this.Model._hasBooleanAttributes && this.Model._isBooleanAttribute(key) && value !== null && value !== undefined && !value._isSequelizeMethod) {
if (Buffer.isBuffer(value) && value.length === 1) {
// Bit fields are returned as buffers
value = value[0];
}
if (_.isString(value)) {
// Only take action on valid boolean strings.
value = (value === 'true') ? true : (value === 'false') ? false : value;
} else if (_.isNumber(value)) {
// Only take action on valid boolean integers.
value = (value === 1) ? true : (value === 0) ? false : value;
}
}
if (!options.raw && ((!Utils.isPrimitive(value) && value !== null) || value !== originalValue)) {
this._previousDataValues[key] = originalValue;
this.changed(key, true);
}
this.dataValues[key] = value;
}
}
}
return this;
};
Instance.prototype.setAttributes = function(updates) {
return this.set(updates);
};
/**
* If changed is called with a string it will return a boolean indicating whether the value of that key in `dataValues` is different from the value in `_previousDataValues`.
*
* If changed is called without an argument, it will return an array of keys that have changed.
*
* If changed is called without an argument and no keys have changed, it will return `false`.
*
* @param {String} [key]
* @return {Boolean|Array}
*/
Instance.prototype.changed = function(key, value) {
if (key) {
if (value !== undefined) {
this._changed[key] = value;
return this;
}
return this._changed[key] || false;
}
var changed = Object.keys(this.dataValues).filter(function(key) {
return this.changed(key);
}.bind(this));
return changed.length ? changed : false;
};
/**
* Returns the previous value for key from `_previousDataValues`.
*
* If called without a key, returns the previous values for all values which have changed
*
* @param {String} [key]
* @return {any|Array<any>}
*/
Instance.prototype.previous = function(key) {
if (key) {
return this._previousDataValues[key];
}
return _.pickBy(this._previousDataValues, function(value, key) {
return this.changed(key);
}.bind(this));
};
Instance.prototype._setInclude = function(key, value, options) {
if (!Array.isArray(value)) value = [value];
if (value[0] instanceof Instance) {
value = value.map(function(instance) {
return instance.dataValues;
});
}
var include = this.$options.includeMap[key]
, association = include.association
, self = this
, accessor = key
, childOptions
, primaryKeyAttribute = include.model.primaryKeyAttribute
, isEmpty;
if (!isEmpty) {
childOptions = {
isNewRecord: this.isNewRecord,
include: include.include,
includeNames: include.includeNames,
includeMap: include.includeMap,
includeValidated: true,
raw: options.raw,
attributes: include.originalAttributes
};
}
if (include.originalAttributes === undefined || include.originalAttributes.length) {
if (association.isSingleAssociation) {
if (Array.isArray(value)) {
value = value[0];
}
isEmpty = (value && value[primaryKeyAttribute] === null) || (value === null);
self[accessor] = self.dataValues[accessor] = isEmpty ? null : include.model.build(value, childOptions);
} else {
isEmpty = value[0] && value[0][primaryKeyAttribute] === null;
self[accessor] = self.dataValues[accessor] = isEmpty ? [] : include.model.bulkBuild(value, childOptions);
}
}
};
/**
* Validate this instance, and if the validation passes, persist it to the database. It will only save changed fields, and do nothing if no fields have changed.
*
* On success, the callback will be called with this instance. On validation error, the callback will be called with an instance of `Sequelize.ValidationError`.
* This error will have a property for each of the fields for which validation failed, with the error message for that field.
*
* @param {Object} [options]
* @param {string[]} [options.fields] An optional array of strings, representing database columns. If fields is provided, only those columns will be validated and saved.
* @param {Boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated.
* @param {Boolean} [options.validate=true] If false, validations won't be run.
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @param {Transaction} [options.transaction]
* @param {String} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
*
* @return {Promise<this|Errors.ValidationError>}
*/
Instance.prototype.save = function(options) {
if (arguments.length > 1) {
throw new Error('The second argument was removed in favor of the options object.');
}
options = Utils.cloneDeep(options);
options = _.defaults(options, {
hooks: true,
validate: true
});
if (!options.fields) {
if (this.isNewRecord) {
options.fields = Object.keys(this.Model.attributes);
} else {
options.fields = _.intersection(this.changed(), Object.keys(this.Model.attributes));
}
options.defaultFields = options.fields;
}
if (options.returning === undefined) {
if (options.association) {
options.returning = false;
} else if (this.isNewRecord) {
options.returning = true;
}
}
var self = this
, primaryKeyName = this.Model.primaryKeyAttribute
, primaryKeyAttribute = primaryKeyName && this.Model.rawAttributes[primaryKeyName]
, updatedAtAttr = this.Model._timestampAttributes.updatedAt
, createdAtAttr = this.Model._timestampAttributes.createdAt
, hook = self.isNewRecord ? 'Create' : 'Update'
, wasNewRecord = this.isNewRecord
, now = Utils.now(this.sequelize.options.dialect);
if (updatedAtAttr && options.fields.length >= 1 && options.fields.indexOf(updatedAtAttr) === -1) {
options.fields.push(updatedAtAttr);
}
if (options.silent === true && !(this.isNewRecord && this.get(updatedAtAttr, {raw: true}))) {
// UpdateAtAttr might have been added as a result of Object.keys(Model.attributes). In that case we have to remove it again
Utils._.remove(options.fields, function(val) {
return val === updatedAtAttr;
});
updatedAtAttr = false;
}
if (this.isNewRecord === true) {
if (createdAtAttr && options.fields.indexOf(createdAtAttr) === -1) {
options.fields.push(createdAtAttr);
}
if (primaryKeyAttribute && primaryKeyAttribute.defaultValue && options.fields.indexOf(primaryKeyName) < 0) {
options.fields.unshift(primaryKeyName);
}
}
if (this.isNewRecord === false) {
if (primaryKeyName && this.get(primaryKeyName, {raw: true}) === undefined) {
throw new Error('You attempted to save an instance with no primary key, this is not allowed since it would result in a global update');
}
}
if (updatedAtAttr && !options.silent && options.fields.indexOf(updatedAtAttr) !== -1) {
this.dataValues[updatedAtAttr] = this.Model.$getDefaultTimestamp(updatedAtAttr) || now;
}
if (this.isNewRecord && createdAtAttr && !this.dataValues[createdAtAttr]) {
this.dataValues[createdAtAttr] = this.Model.$getDefaultTimestamp(createdAtAttr) || now;
}
return Promise.bind(this).then(function() {
// Validate
if (options.validate) {
return Promise.bind(this).then(function () {
// hookValidate rejects with errors, validate returns with errors
if (options.hooks) return this.hookValidate(options);
return this.validate(options).then(function (err) {
if (err) throw err;
});
});
}
}).then(function() {
return Promise.bind(this).then(function() {
// Run before hook
if (options.hooks) {
var beforeHookValues = _.pick(this.dataValues, options.fields)
, afterHookValues
, hookChanged
, ignoreChanged = _.difference(this.changed(), options.fields); // In case of update where it's only supposed to update the passed values and the hook values
if (updatedAtAttr && options.fields.indexOf(updatedAtAttr) !== -1) {
ignoreChanged = _.without(ignoreChanged, updatedAtAttr);
}
return this.Model.runHooks('before' + hook, this, options).bind(this).then(function() {
if (options.defaultFields && !this.isNewRecord) {
afterHookValues = _.pick(this.dataValues, _.difference(this.changed(), ignoreChanged));
hookChanged = [];
Object.keys(afterHookValues).forEach(function (key) {
if (afterHookValues[key] !== beforeHookValues[key]) {
hookChanged.push(key);
}
});
options.fields = _.uniq(options.fields.concat(hookChanged));
}
if (hookChanged) {
if (options.validate) {
// Validate again
options.skip = _.difference(Object.keys(this.Model.rawAttributes), hookChanged);
return Promise.bind(this).then(function () {
// hookValidate rejects with errors, validate returns with errors
if (options.hooks) return this.hookValidate(options);
return this.validate(options).then(function (err) {
if (err) throw err;
});
}).then(function() {
delete options.skip;
});
}
}
});
}
}).then(function() {
if (!options.fields.length) return this;
if (!this.isNewRecord) return this;
if (!this.$options.include || !this.$options.include.length) return this;
// Nested creation for BelongsTo relations
return Promise.map(this.$options.include.filter(function (include) {
return include.association instanceof BelongsTo;
}), function (include) {
var instance = self.get(include.as);
if (!instance) return Promise.resolve();
var includeOptions = _(Utils.cloneDeep(include))
.omit(['association'])
.defaults({
transaction: options.transaction,
logging: options.logging,
parentRecord: self
}).value();
return instance.save(includeOptions).then(function () {
return self[include.association.accessors.set](instance, {save: false, logging: options.logging});
});
});
})
.then(function() {
var realFields = [];
options.fields.forEach(function(field) {
if (!self.Model._isVirtualAttribute(field)) {
realFields.push(field);
}
});
if (!realFields.length) return this;
if (!this.changed() && !this.isNewRecord) return this;
var values = Utils.mapValueFieldNames(this.dataValues, options.fields, this.Model)
, query = null
, args = [];
if (self.isNewRecord) {
query = 'insert';
args = [self, self.$Model.getTableName(options), values, options];
} else {
var where = this.where();
where = Utils.mapValueFieldNames(where, Object.keys(where), this.Model);
query = 'update';
args = [self, self.$Model.getTableName(options), values, where, options];
}
return self.sequelize.getQueryInterface()[query].apply(self.sequelize.getQueryInterface(), args)
.then(function(result) {
// Transfer database generated values (defaults, autoincrement, etc)
Object.keys(self.Model.rawAttributes).forEach(function (attr) {
if (self.Model.rawAttributes[attr].field &&
values[self.Model.rawAttributes[attr].field] !== undefined &&
self.Model.rawAttributes[attr].field !== attr
) {
values[attr] = values[self.Model.rawAttributes[attr].field];
delete values[self.Model.rawAttributes[attr].field];
}
});
values = _.extend(values, result.dataValues);
result.dataValues = _.extend(result.dataValues, values);
return result;
})
.tap(function(result) {
// Run after hook
if (options.hooks) {
return self.Model.runHooks('after' + hook, result, options);
}
})
.then(function(result) {
options.fields.forEach(function (field) {
result._previousDataValues[field] = result.dataValues[field];
self.changed(field, false);
});
self.isNewRecord = false;
return result;
})
.tap(function() {
if (!wasNewRecord) return self;
if (!self.$options.include || !self.$options.include.length) return self;
// Nested creation for HasOne/HasMany/BelongsToMany relations
return Promise.map(self.$options.include.filter(function (include) {
return !(include.association instanceof BelongsTo);
}), function (include) {
var instances = self.get(include.as);
if (!instances) return Promise.resolve();
if (!Array.isArray(instances)) instances = [instances];
if (!instances.length) return Promise.resolve();
var includeOptions = _(Utils.cloneDeep(include))
.omit(['association'])
.defaults({
transaction: options.transaction,
logging: options.logging,
parentRecord: self
}).value();
// Instances will be updated in place so we can safely treat HasOne like a HasMany
return Promise.map(instances, function (instance) {
if (include.association instanceof BelongsToMany) {
return instance.save(includeOptions).then(function () {
var values = {};
values[include.association.foreignKey] = self.get(self.Model.primaryKeyAttribute, {raw: true});
values[include.association.otherKey] = instance.get(instance.Model.primaryKeyAttribute, {raw: true});
// Include values defined in the scope of the association
_.assign(values, include.association.through.scope);
return include.association.throughModel.create(values, includeOptions);
});
} else {
instance.set(include.association.foreignKey, self.get(self.Model.primaryKeyAttribute, {raw: true}));
return instance.save(includeOptions);
}
});
});
});
});
});
};
/*
* Refresh the current instance in-place, i.e. update the object with current data from the DB and return the same object.
* This is different from doing a `find(Instance.id)`, because that would create and return a new instance. With this method,
* all references to the Instance are updated with the new data and no new objects are created.
*
* @see {Model#find}
* @param {Object} [options] Options that are passed on to `Model.find`
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @return {Promise<this>}
*/
Instance.prototype.reload = function(options) {
options = _.defaults({}, options, {
where: this.where(),
include: this.$options.include || null
});
return this.Model.findOne(options).bind(this)
.tap(function (reload) {
if (!reload) {
throw new sequelizeErrors.InstanceError(
'Instance could not be reloaded because it does not exist anymore (find call returned null)'
);
}
})
.then(function(reload) {
// update the internal options of the instance
this.$options = reload.$options;
// re-set instance values
this.set(reload.dataValues, {
raw: true,
reset: true && !options.attributes
});
}).return(this);
};
/*
* Validate the attribute of this instance according to validation rules set in the model definition.
*
* Emits null if and only if validation successful; otherwise an Error instance containing { field name : [error msgs] } entries.
*
* @param {Object} [options] Options that are passed to the validator
* @param {Array} [options.skip] An array of strings. All properties that are in this array will not be validated
* @param {Array} [options.fields] An array of strings. Only the properties that are in this array will be validated.
* @see {InstanceValidator}
*
* @return {Promise<undefined|Errors.ValidationError>}
*/
Instance.prototype.validate = function(options) {
return new InstanceValidator(this, options).validate();
};
Instance.prototype.hookValidate = function(options) {
return new InstanceValidator(this, options).hookValidate();
};
/**
* This is the same as calling `set` and then calling `save` but it only saves the
* exact values passed to it, making it more atomic and safer.
*
* @see {Instance#set}
* @see {Instance#save}
* @param {Object} updates See `set`
* @param {Object} options See `save`
*
* @return {Promise<this>}
* @alias updateAttributes
*/
Instance.prototype.update = function(values, options) {
var changedBefore = this.changed() || []
, sideEffects
, fields
, setOptions;
options = options || {};
if (Array.isArray(options)) options = {fields: options};
options = Utils.cloneDeep(options);
setOptions = Utils.cloneDeep(options);
setOptions.attributes = options.fields;
this.set(values, setOptions);
// Now we need to figure out which fields were actually affected by the setter.
sideEffects = _.without.apply(this, [this.changed() || []].concat(changedBefore));
fields = _.union(Object.keys(values), sideEffects);
if (!options.fields) {
options.fields = _.intersection(fields, this.changed());
options.defaultFields = options.fields;
}
return this.save(options);
};
Instance.prototype.updateAttributes = Instance.prototype.update;
/**
* Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will either be completely deleted, or have its deletedAt timestamp set to the current time.
*
* @param {Object} [options={}]
* @param {Boolean} [options.force=false] If set to true, paranoid models will actually be deleted
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @param {Transaction} [options.transaction]
* @param {String} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
*
* @return {Promise<undefined>}
*/
Instance.prototype.destroy = function(options) {
options = Utils._.extend({
hooks: true,
force: false
}, options);
return Promise.bind(this).then(function() {
// Run before hook
if (options.hooks) {
return this.Model.runHooks('beforeDestroy', this, options);
}
}).then(function() {
var where = this.where();
if (this.Model._timestampAttributes.deletedAt && options.force === false) {
var attribute = this.Model.rawAttributes[this.Model._timestampAttributes.deletedAt]
, field = attribute.field || this.Model._timestampAttributes.deletedAt
, values = {};
values[field] = new Date();
where[field] = attribute.hasOwnProperty('defaultValue') ? attribute.defaultValue : null;
this.setDataValue(field, values[field]);
return this.sequelize.getQueryInterface().update(this, this.$Model.getTableName(options), values, where, _.defaults({ hooks: false }, options));
} else {
return this.sequelize.getQueryInterface().delete(this, this.$Model.getTableName(options), where, _.assign({ type: QueryTypes.DELETE, limit: null }, options));
}
}).tap(function() {
// Run after hook
if (options.hooks) {
return this.Model.runHooks('afterDestroy', this, options);
}
}).then(function(result) {
return result;
});
};
/**
* Restore the row corresponding to this instance. Only available for paranoid models.
*
* @param {Object} [options={}]
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @param {Transaction} [options.transaction]
*
* @return {Promise<undefined>}
*/
Instance.prototype.restore = function(options) {
if (!this.Model._timestampAttributes.deletedAt) throw new Error('Model is not paranoid');
options = Utils._.extend({
hooks: true,
force: false
}, options);
return Promise.bind(this).then(function() {
// Run before hook
if (options.hooks) {
return this.Model.runHooks('beforeRestore', this, options);
}
}).then(function() {
var deletedAtCol = this.Model._timestampAttributes.deletedAt
, deletedAtAttribute = this.Model.rawAttributes[deletedAtCol]
, deletedAtDefaultValue = deletedAtAttribute.hasOwnProperty('defaultValue') ? deletedAtAttribute.defaultValue : null;
this.setDataValue(deletedAtCol, deletedAtDefaultValue);
return this.save(_.extend({}, options, {hooks : false, omitNull : false}));
}).tap(function() {
// Run after hook
if (options.hooks) {
return this.Model.runHooks('afterRestore', this, options);
}
});
};
/**
* Increment the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The increment is done using a
* ```sql
* SET column = column + X
* ```
* query. To get the correct value after an increment into the Instance you should do a reload.
*
*```js
* instance.increment('number') // increment number by 1
* instance.increment(['number', 'count'], { by: 2 }) // increment number and count by 2
* instance.increment({ answer: 42, tries: 1}, { by: 2 }) // increment answer by 42, and tries by 1.
* // `by` is ignored, since each column has its own value
* ```
*
* @see {Instance#reload}
* @param {String|Array|Object} fields If a string is provided, that column is incremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is incremented by the value given.
* @param {Object} [options]
* @param {Integer} [options.by=1] The number to increment by
* @param {Boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated.
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @param {Transaction} [options.transaction]
* @param {String} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
*
* @return {Promise<this>}
*/
Instance.prototype.increment = function(fields, options) {
var identifier = this.where()
, updatedAtAttr = this.Model._timestampAttributes.updatedAt
, values = {}
, where;
options = _.defaults({}, options, {
by: 1,
attributes: {},
where: {}
});
where = _.extend({}, options.where, identifier);
if (Utils._.isString(fields)) {
values[fields] = options.by;
} else if (Utils._.isArray(fields)) {
Utils._.each(fields, function(field) {
values[field] = options.by;
});
} else { // Assume fields is key-value pairs
values = fields;
}
if (!options.silent && updatedAtAttr && !values[updatedAtAttr]) {
options.attributes[updatedAtAttr] = this.Model.$getDefaultTimestamp(updatedAtAttr) || Utils.now(this.sequelize.options.dialect);
}
Object.keys(values).forEach(function(attr) {
// Field name mapping
if (this.Model.rawAttributes[attr] && this.Model.rawAttributes[attr].field && this.Model.rawAttributes[attr].field !== attr) {
values[this.Model.rawAttributes[attr].field] = values[attr];
delete values[attr];
}
}, this);
return this.sequelize.getQueryInterface().increment(this, this.$Model.getTableName(options), values, where, options).return(this);
};
/**
* Decrement the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The decrement is done using a
* ```sql
* SET column = column - X
* ```
* query. To get the correct value after an decrement into the Instance you should do a reload.
*
* ```js
* instance.decrement('number') // decrement number by 1
* instance.decrement(['number', 'count'], { by: 2 }) // decrement number and count by 2
* instance.decrement({ answer: 42, tries: 1}, { by: 2 }) // decrement answer by 42, and tries by 1.
* // `by` is ignored, since each column has its own value
* ```
*
* @see {Instance#reload}
* @param {String|Array|Object} fields If a string is provided, that column is decremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is decremented by the value given
* @param {Object} [options]
* @param {Integer} [options.by=1] The number to decrement by
* @param {Boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated.
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @param {Transaction} [options.transaction]
* @param {String} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
*
* @return {Promise}
*/
Instance.prototype.decrement = function(fields, options) {
options = _.defaults({}, options, {
by: 1
});
if (!Utils._.isString(fields) && !Utils._.isArray(fields)) { // Assume fields is key-value pairs
Utils._.each(fields, function(value, field) {
fields[field] = -value;
});
}
options.by = 0 - options.by;
return this.increment(fields, options);
};
/**
* Check whether all values of this and `other` Instance are the same
*
* @param {Instance} other
* @return {Boolean}
*/
Instance.prototype.equals = function(other) {
var result = true;
if (!other || !other.dataValues) {
return false;
}
Utils._.each(this.dataValues, function(value, key) {
if (Utils._.isDate(value) && Utils._.isDate(other.dataValues[key])) {
result = result && (value.getTime() === other.dataValues[key].getTime());
} else {
result = result && (value === other.dataValues[key]);
}
});
return result;
};
/**
* Check if this is equal to one of `others` by calling equals
*
* @param {Array} others
* @return {Boolean}
*/
Instance.prototype.equalsOneOf = function(others) {
var self = this;
return _.some(others, function(other) {
return self.equals(other);
});
};
Instance.prototype.setValidators = function(attribute, validators) {
this.validators[attribute] = validators;
};
/**
* Convert the instance to a JSON representation. Proxies to calling `get` with no keys. This means get all values gotten from the DB, and apply all custom getters.
*
* @see {Instance#get}
* @return {object}
*/
Instance.prototype.toJSON = function() {
return this.get({
plain: true
});
};
module.exports = Instance;
module.exports.Instance = Instance;
module.exports.default = Instance;