forked from sequelize/sequelize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.js
1934 lines (1664 loc) · 68 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";
var Utils = require('./utils')
, Instance = require('./instance')
, Attribute = require('./model/attribute')
, DataTypes = require('./data-types')
, Util = require('util')
, sql = require('sql')
, SqlString = require('./sql-string')
, Transaction = require('./transaction')
, Promise = require("./promise")
, QueryTypes = require('./query-types');
module.exports = (function() {
/**
* A Model represents a table in the database. Sometimes you might also see it refererred 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,
createdAt: 'createdAt',
updatedAt: 'updatedAt',
deletedAt: 'deletedAt',
instanceMethods: {},
classMethods: {},
validate: {},
freezeTableName: false,
underscored: false,
underscoredAll: false,
paranoid: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
language: 'en',
defaultScope: null,
scopes: null,
hooks: {
beforeCreate: [],
afterCreate: []
}
}, options || {});
this.sequelize = options.sequelize;
this.underscored = this.underscored || this.underscoredAll;
// error check options
Utils._.each(options.validate, function(validator, validatorType) {
if (Utils._.contains(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 (!Utils._.isFunction(validator)) {
throw new Error('Members of the validate option must be functions. Model: ' + name + ', error with validate member ' + validatorType);
}
});
this.name = name;
if (!this.options.tableName) {
this.tableName = this.options.freezeTableName ? name : Utils._.underscoredIf(Utils.pluralize(name, this.options.language), this.options.underscoredAll);
} else {
this.tableName = this.options.tableName;
}
// If you don't specify a valid data type lets help you debug it
Utils._.each(attributes, function(attribute, name) {
var dataType;
if (Utils._.isPlainObject(attribute)) {
// We have special cases where the type is an object containing
// the values (e.g. Sequelize.ENUM(value, value2) returns an object
// instead of a function)
// Copy these values to the dataType
attribute.values = (attribute.type && attribute.type.values) || attribute.values;
// We keep on working with the actual type object
dataType = attribute.type;
} else {
dataType = attribute;
}
if (dataType === undefined) {
throw new Error('Unrecognized data type for field ' + name);
}
if (dataType.toString() === 'ENUM') {
if (!(Array.isArray(attribute.values) && (attribute.values.length > 0))) {
throw new Error('Values for ENUM haven\'t been defined.');
}
attributes[name].validate = attributes[name].validate || {
_checkEnum: function(value, next) {
var hasValue = value !== undefined
, isMySQL = ['mysql', 'mariadb'].indexOf(options.sequelize.options.dialect) !== -1
, ciCollation = !!options.collate && options.collate.match(/_ci$/i) !== null
, valueOutOfScope;
if (isMySQL && ciCollation && hasValue) {
var scopeIndex = (attributes[name].values || []).map(function(d) { return d.toLowerCase(); }).indexOf(value.toLowerCase());
valueOutOfScope = scopeIndex === -1;
} else {
valueOutOfScope = ((attributes[name].values || []).indexOf(value) === -1);
}
if (hasValue && valueOutOfScope && attributes[name].allowNull !== true) {
return next('Value "' + value + '" for ENUM ' + name + ' is out of allowed scope. Allowed values: ' + attributes[name].values.join(', '));
}
next();
}
};
}
});
Object.keys(attributes).forEach(function(attrName) {
if (attributes[attrName].references instanceof Model) {
attributes[attrName].references = attributes[attrName].references.tableName;
}
});
this.options.hooks = this.replaceHookAliases(this.options.hooks);
this.attributes =
this.rawAttributes = attributes;
this.modelManager =
this.daoFactoryManager = null; // defined in init function
this.associations = {};
this.scopeObj = {};
};
Object.defineProperty(Model.prototype, 'QueryInterface', {
get: function() { return this.modelManager.sequelize.getQueryInterface(); }
});
Object.defineProperty(Model.prototype, 'QueryGenerator', {
get: function() { return this.QueryInterface.QueryGenerator; }
});
// inject the node-sql methods to the dao factory in order to
// receive the syntax sugar ...
(function() {
var instance = sql.define({ name: 'dummy', columns: [] });
for (var methodName in instance) {
;(function(methodName) {
Model.prototype[methodName] = function() {
var dataset = this.dataset()
, result = dataset[methodName].apply(dataset, arguments)
, dialect = this.modelManager.sequelize.options.dialect
, self = this;
result.toSql = function() {
var query = result.toQuery();
return SqlString.format(query.text.replace(/(\$\d)/g, '?'), query.values, null, dialect) + ';';
};
result.exec = function(options) {
options = Utils._.extend({
transaction: null,
type: QueryTypes.SELECT
}, options || {});
return self.sequelize.query(result.toSql(), self, options);
};
return result;
};
})(methodName);
}
})();
Model.prototype.init = function(modelManager) {
var self = this;
this.modelManager =
this.daoFactoryManager = modelManager;
this.primaryKeys = {};
self.options.uniqueKeys = {};
// Setup names of timestamp attributes
this._timestampAttributes = {};
if (this.options.timestamps) {
if (this.options.createdAt) {
this._timestampAttributes.createdAt = Utils._.underscoredIf(this.options.createdAt, this.options.underscored);
}
if (this.options.updatedAt) {
this._timestampAttributes.updatedAt = Utils._.underscoredIf(this.options.updatedAt, this.options.underscored);
}
if (this.options.paranoid && this.options.deletedAt) {
this._timestampAttributes.deletedAt = Utils._.underscoredIf(this.options.deletedAt, this.options.underscored);
}
}
// Identify primary and unique attributes
Utils._.each(this.rawAttributes, function(options, attribute) {
if (options.hasOwnProperty('unique') && options.unique !== true && options.unique !== false) {
var idxName = options.unique;
if (typeof options.unique === 'object') {
idxName = options.unique.name;
}
self.options.uniqueKeys[idxName] = self.options.uniqueKeys[idxName] || {fields: [], msg: null};
self.options.uniqueKeys[idxName].fields.push(attribute);
self.options.uniqueKeys[idxName].msg = self.options.uniqueKeys[idxName].msg || options.unique.msg || null;
self.options.uniqueKeys[idxName].name = idxName || false;
}
if (options.primaryKey === true) {
self.primaryKeys[attribute] = self.attributes[attribute];
}
});
// Add head and tail default attributes (id, timestamps)
addDefaultAttributes.call(this);
addOptionalClassMethods.call(this);
// Primary key convenience variables
this.primaryKeyAttributes = Object.keys(this.primaryKeys);
this.primaryKeyAttribute = this.primaryKeyAttributes[0];
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;
});
if (typeof this.options.defaultScope === 'object') {
Utils.injectScope.call(this, this.options.defaultScope);
}
// Instance prototype
this.Instance = this.DAO = 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;
});
}
this.refreshAttributes();
findAutoIncrementField.call(this);
this._booleanAttributes = [];
this._dateAttributes = [];
this._hstoreAttributes = [];
this._virtualAttributes = [];
this._defaultValues = {};
this.Instance.prototype.validators = {};
Utils._.each(this.rawAttributes, function(definition, name) {
var type = definition.originalType || definition.type || definition;
if (type === DataTypes.BOOLEAN) {
self._booleanAttributes.push(name);
} else if (type === DataTypes.DATE) {
self._dateAttributes.push(name);
} else if (type === DataTypes.HSTORE) {
self._hstoreAttributes.push(name);
} else if (type === DataTypes.VIRTUAL) {
self._virtualAttributes.push(name);
}
if (definition.hasOwnProperty('defaultValue')) {
self._defaultValues[name] = Utils._.partial(
Utils.toDefaultValue, definition.defaultValue);
}
if (definition.hasOwnProperty('validate')) {
self.Instance.prototype.validators[name] = definition.validate;
}
});
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._hasVirtualAttributes = !!this._virtualAttributes.length;
this._isVirtualAttribute = Utils._.memoize(function(key) {
return self._virtualAttributes.indexOf(key) !== -1;
});
this.Instance.prototype.Model = this;
this._hasDefaultValues = !Utils._.isEmpty(this._defaultValues);
this.tableAttributes = Utils._.omit(this.rawAttributes, this._virtualAttributes);
return this;
};
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) {
options.Model = self;
options.fieldName = attribute;
options._modelAttribute = true;
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.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.defineProperties(this.Instance.prototype, attributeManipulation);
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;
});
};
/**
* 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 = Utils._.extend({}, this.options, options || {});
var self = this
, attributes = this.tableAttributes;
return Promise.resolve().then(function () {
if (options.force) {
return self.drop(options);
}
}).then(function () {
return self.QueryInterface.createTable(self.getTableName(options), attributes, options);
}).return(this);
};
/**
* Drop the table represented by this Model
* @param {Object} [options]
* @param {Boolean} [options.cascade=false] Also drop all objects depending on this table, such as views. Only works in postgres
* @return {Promise}
*/
Model.prototype.drop = function(options) {
return this.QueryInterface.dropTable(this.getTableName(options), options);
};
Model.prototype.dropSchema = function(schema) {
return this.QueryInterface.dropSchema(schema);
};
/**
* Apply a schema to this model. For postgres, this will actually place the schema in front of the table name - `"schema"."tableName"`,
* while the schema will be prepended to the table name for mysql and sqlite - `'schema.tablename'`.
*
* @param {String} schema The name of the schema
* @param {Object} [options]
* @param {String} [options.schemaDelimiter='.'] The character(s) that separates the schema name from the table name
* @return this
*/
Model.prototype.schema = function(schema, options) {
this.options.schema = schema;
if (!!options) {
if (typeof options === 'string') {
this.options.schemaDelimiter = options;
} else {
if (!!options.schemaDelimiter) {
this.options.schemaDelimiter = options.schemaDelimiter;
}
}
}
return this;
};
/**
* Get the tablename of the model, taking schema into account. The method will return The name as a string if the model has no schema,
* or an object with `tableName`, `schema` and `delimiter` properties.
*
* @param {Object} options The hash of options from any query. You can use one model to access tables with matching schemas by overriding `getTableName` and using custom key/values to alter the name of the table. (eg. subscribers_1, subscribers_2)
* @return {String|Object}
*/
Model.prototype.getTableName = function(options) {
return this.QueryGenerator.addSchema(this);
};
/**
* Apply a scope created in `define` to the model. First let's look at how to create scopes:
* ```js
* var Model = sequelize.define('model', attributes, {
* defaultScope: {
* where: {
* username: 'dan'
* },
* limit: 12
* },
* scopes: {
* isALie: {
* where: {
* stuff: 'cake'
* }
* },
* complexFunction: function(email, accessLevel) {
* return {
* where: ['email like ? AND access_level >= ?', email + '%', accessLevel]
* }
* },
* }
* })
* ```
* Now, since you defined a default scope, every time you do Model.find, the default scope is appended to your query. Here's a couple of examples:
* ```js
* Model.findAll() // WHERE username = 'dan'
* Model.findAll({ where: { age: { gt: 12 } } }) // WHERE age > 12 AND username = 'dan'
* ```
*
* To invoke scope functions you can do:
* ```js
* Model.scope({ method: ['complexFunction' '[email protected]', 42]}).findAll()
* // WHERE email like '[email protected]%' AND access_level >= 42
* ```
*
* @param {Array|Object|String|null} options* The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of arguments. To apply simple scopes, pass them as strings. For scope function, pass an object, with a `method` property. The value can either be a string, if the method does not take any arguments, or an array, where the first element is the name of the method, and consecutive elements are arguments to that method. Pass null to remove all scopes, including the default.
* @return {Model} A reference to the model, with the scope(s) applied. Calling scope again on the returned model will clear the previous scope.
*/
Model.prototype.scope = function(option) {
var self = Object.create(this)
, type
, options
, merge
, i
, scope
, scopeName
, scopeOptions
, argLength = arguments.length
, lastArg = arguments[argLength - 1];
// Set defaults
scopeOptions = (typeof lastArg === 'object' && !Array.isArray(lastArg) ? lastArg : {}) || {}; // <-- for no arguments
scopeOptions.silent = (scopeOptions !== null && scopeOptions.hasOwnProperty('silent') ? scopeOptions.silent : true);
// Clear out any predefined scopes...
self.scopeObj = {};
// Possible formats for option:
// String of arguments: 'hello', 'world', 'etc'
// Array: ['hello', 'world', 'etc']
// Object: {merge: 'hello'}, {method: ['scopeName' [, args1, args2..]]}, {merge: true, method: ...}
if (argLength < 1 || !option) {
return self;
}
for (i = 0; i < argLength; i++) {
options = Array.isArray(arguments[i]) ? arguments[i] : [arguments[i]];
options.forEach(function(o) {
type = typeof o;
scope = null;
merge = false;
scopeName = null;
if (type === 'object') {
// Right now we only support a merge functionality for objects
if (!!o.merge) {
merge = true;
scopeName = o.merge[0];
if (Array.isArray(o.merge) && !!self.options.scopes[scopeName]) {
scope = self.options.scopes[scopeName].apply(self, o.merge.splice(1));
}
else if (typeof o.merge === 'string') {
scopeName = o.merge;
scope = self.options.scopes[scopeName];
}
}
if (!!o.method) {
if (Array.isArray(o.method) && !!self.options.scopes[o.method[0]]) {
scopeName = o.method[0];
scope = self.options.scopes[scopeName].apply(self, o.method.splice(1));
merge = !!o.merge;
}
else if (!!self.options.scopes[o.method]) {
scopeName = o.method;
scope = self.options.scopes[scopeName].apply(self);
}
} else {
scopeName = o;
scope = self.options.scopes[scopeName];
}
} else {
scopeName = o;
scope = self.options.scopes[scopeName];
}
if (!!scope) {
Utils.injectScope.call(self, scope, merge);
}
else if (scopeOptions.silent !== true && !!scopeName) {
throw new Error('Invalid scope ' + scopeName + ' called.');
}
});
}
return self;
};
Model.prototype.all = function(options, queryOptions) {
return this.findAll(options, queryOptions);
};
/**
* Search for multiple instances.
*
* __Simple search using AND and =__
* ```js
* Model.find({
* where: {
* attr1: 42,
* attr2: 'cake'
* }
* })
* ```
* ```sql
* WHERE attr1 = 42 AND attr2 = 'cake'
*```
*
* __Using greater than, less than etc.__
* ```js
*
* Model.find({
* where: {
* attr1: {
* gt: 50
* },
* attr2: {
* lte: 45
* },
* attr3: {
* in: [1,2,3]
* },
* attr4: {
* ne: 5
* }
* }
* })
* ```
* ```sql
* WHERE attr1 > 50 AND attr2 <= 45 AND attr3 IN (1,2,3) AND attr4 != 5
* ```
* Possible options are: `gt, gte, lt, lte, ne, between/.., nbetween/notbetween/!.., in, not, like, nlike/notlike`
*
* __Queries using OR__
* ```js
* Model.find({
* where: Sequelize.and(
* { name: 'a project' },
* Sequelize.or(
* { id: [1,2,3] },
* { id: { gt: 10 } }
* )
* )
* })
* ```
* ```sql
* WHERE name = 'a project' AND (id` IN (1,2,3) OR id > 10)
* ```
*
* The success listener is called with an array of instances if the query succeeds.
*
* @param {Object} [options] A hash of options to describe the scope of the search
* @param {Object} [options.where] A hash of attributes to describe your search. See above for examples.
* @param {Array<String>} [options.attributes] A list of the attributes that you want to select. To rename an attribute, you can pass an array, with two elements - the first is the name of the attribute in the DB (or some kind of expression such as `Sequelize.literal`, `Sequelize.fn` and so on), and the second is the name you want the attribute to have in the returned instance
* @param {Array<Object|Model>} [options.include] A list of associations to eagerly load using a left join. Supported is either `{ include: [ Model1, Model2, ...]}` or `{ include: [{ model: Model1, as: 'Alias' }]}`. If your association are set up with an `as` (eg. `X.hasMany(Y, { as: 'Z }`, you need to specify Z in the as attribute when eager loading Y).
* @param {Model} [options.include[].model] The model you want to eagerly load
* @param {String} [options.include[].as] The alias of the relation, in case the model you want to eagerly load is aliassed.
* @param {Object} [options.include[].where] Where clauses to apply to the child models. Note that this converts the eager load to an inner join, unless you explicitly set `required: true`
* @param {Array<String>} [options.include[].attributes] A list of attributes to select from the child model
* @param {Boolean} [options.include[].required] If true, converts to an inner join, which means that the parent model will only be loaded if it has any matching children. True if `include.where` is set, false otherwise.
* @param {Array<Object|Model>} [options.include[].include] Load further nested related models
* @param {String|Array|Sequelize.fn} [options.order] Specifies an ordering. If a string is provided, it will be esacped. Using an array, you can provide several columns / functions to order by. Each element can be further wrapped in a two-element array. The first element is the column / function to order by, the second is the direction. For example: `order: [['name', 'DESC']]`. In this way the column will be escaped, but the direction will not.
* @param {Number} [options.limit]
* @param {Number} [options.offset]
* @param {Object} [queryOptions] Set the query options, e.g. raw, specifying that you want raw data instead of built Instances. See sequelize.query for options
* @param {Transaction} [queryOptions.transaction]
* @param {String} [queryOptions.lock] Lock the selected rows in either share or update mode. Possible options are transaction.LOCK.UPDATE and transaction.LOCK.SHARE. See [transaction.LOCK for an example](https://github.com/sequelize/sequelize/wiki/API-Reference-Transaction#LOCK)
*
* @see {Sequelize#query}
* @return {Promise<Array<Instance>>}
* @alias all
*/
Model.prototype.findAll = function(options, queryOptions) {
var hasJoin = false
, tableNames = { };
tableNames[this.tableName] = true;
options = optClone(options || {});
if (typeof options === 'object') {
if (options.hasOwnProperty('include') && options.include) {
hasJoin = true;
validateIncludedElements.call(this, options, tableNames);
if (options.attributes) {
if (options.attributes.indexOf(this.primaryKeyAttribute) === -1) {
options.originalAttributes = options.attributes;
options.attributes = [this.primaryKeyAttribute].concat(options.attributes);
}
}
}
// whereCollection is used for non-primary key updates
this.options.whereCollection = options.where || null;
}
if (options.attributes === undefined) {
options.attributes = Object.keys(this.tableAttributes);
}
mapFieldNames.call(this, options, this);
options = paranoidClause.call(this, options);
return this.QueryInterface.select(this, this.getTableName(options), options, Utils._.defaults({
type: QueryTypes.SELECT,
hasJoin: hasJoin,
tableNames: Object.keys(tableNames)
}, queryOptions, { transaction: (options || {}).transaction }));
};
//right now, the caller (has-many-double-linked) is in charge of the where clause
Model.prototype.findAllJoin = function(joinTableName, options, queryOptions) {
var optcpy = Utils._.clone(options);
optcpy.attributes = optcpy.attributes || [this.QueryInterface.quoteTable(this.name) + '.*'];
// whereCollection is used for non-primary key updates
this.options.whereCollection = optcpy.where || null;
return this.QueryInterface.select(this, [[this.getTableName(options), this.name], joinTableName], optcpy, Utils._.defaults({
type: QueryTypes.SELECT
}, queryOptions, { transaction: (options || {}).transaction }));
};
/**
* Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single instance.
*
* @param {Object|Number} [options] A hash of options to describe the scope of the search, or a number to search by id.
* @param {Object} [queryOptions]
*
* @see {Model#findAll} for an explanation of options and queryOptions
* @return {Promise<Instance>}
*/
Model.prototype.find = function(options, queryOptions) {
var hasJoin = false;
// no options defined?
// return an emitter which emits null
if ([null, undefined].indexOf(options) !== -1) {
return Promise.resolve(null);
}
var primaryKeys = this.primaryKeys
, keys = Object.keys(primaryKeys)
, keysLength = keys.length
, tableNames = { };
tableNames[this.tableName] = true;
// options is not a hash but an id
if (typeof options === 'number') {
var oldOption = options;
options = { where: {} };
if (keysLength === 1) {
options.where[keys[0]] = oldOption;
} else {
options.where.id = oldOption;
}
} else if (Utils._.size(primaryKeys) && Utils.argsArePrimaryKeys(arguments, primaryKeys)) {
var where = {};
Utils._.each(arguments, function(arg, i) {
var key = keys[i];
where[key] = arg;
});
options = { where: where };
} else if (typeof options === 'string' && parseInt(options, 10).toString() === options) {
var parsedId = parseInt(options, 10);
if (!Utils._.isFinite(parsedId)) {
throw new Error('Invalid argument to find(). Must be an id or an options object.');
}
options = { where: parsedId };
} else if (typeof options === 'object') {
options = Utils._.clone(options, function(thing) {
if (Buffer.isBuffer(thing)) { return thing; }
return undefined;
});
if (options.hasOwnProperty('include') && options.include) {
hasJoin = true;
validateIncludedElements.call(this, options, tableNames);
}
// whereCollection is used for non-primary key updates
this.options.whereCollection = options.where || null;
} else if (typeof options === 'string') {
var where = {};
if (this.primaryKeyCount === 1) {
where[primaryKeys[keys[0]]] = options;
options = where;
} else if (this.primaryKeyCount < 1) {
// Revert to default behavior which is {where: [int]}
options = {where: parseInt(Number(options) || 0, 0)};
}
}
if (options.attributes === undefined) {
options.attributes = Object.keys(this.tableAttributes);
}
if (options.limit === undefined && !(options.where && options.where[this.primaryKeyAttribute])) {
options.limit = 1;
}
mapFieldNames.call(this, options, this);
options = paranoidClause.call(this, options);
return this.QueryInterface.select(this, this.getTableName(options), options, Utils._.defaults({
plain: true,
type: QueryTypes.SELECT,
hasJoin: hasJoin,
tableNames: Object.keys(tableNames)
}, queryOptions, { transaction: (options || {}).transaction }));
};
/**
* Run an aggregation method on the specified field
*
* @param {String} field The field to aggregate over. Can be a field name or *
* @param {String} aggregateFunction The function to use for aggregation, e.g. sum, max etc.
* @param {Object} [options] Query options. See sequelize.query for full options
* @param {DataType|String} [options.dataType] The type of the result. If `field` is a field in this Model, the default will be the type of that field, otherwise defaults to float.
*
* @return {Promise<options.dataType>}
*/
Model.prototype.aggregate = function(field, aggregateFunction, options) {
options = Utils._.extend({ attributes: [] }, options || {});
options.attributes.push([this.sequelize.fn(aggregateFunction, this.sequelize.col(field)), aggregateFunction]);
if (!options.dataType) {
if (this.rawAttributes[field]) {
options.dataType = this.rawAttributes[field];
} else {
// Use FLOAT as fallback
options.dataType = DataTypes.FLOAT;
}
}
options = paranoidClause.call(this, options);
return this.QueryInterface.rawSelect(this.getTableName(options), options, aggregateFunction, this);
};
/**
* Count the number of records matching the provided where clause.
*
* If you provide an `include` option, the number of matching associations will be counted instead.
*
* @param {Object} [options]
* @param {Object} [options.include] Include options. See `find` for details
*
* @return {Promise<Integer>}
*/
Model.prototype.count = function(options) {
options = Utils._.clone(options || {});
var col = '*';
if (options.include) {
col = this.name + '.' + this.primaryKeyAttribute;
validateIncludedElements.call(this, options);
}
options.dataType = DataTypes.INTEGER;
options.includeIgnoreAttributes = false;
options.limit = null;
return this.aggregate(col, 'COUNT', options);
};
/**
* Find all the rows matching your query, within a specified offset / limit, and get the total number of rows matching your query. This is very usefull for paging
*
* ```js
* Model.findAndCountAll({
* where: ...,
* limit: 12,
* offset: 12
* }).success(function (result) {
* })
* ```
* In the above example, `result.rows` will contain rows 13 through 24, while `result.count` will return the total number of rows that matched your query.
*
* @param {Object} [findOptions] See findAll
* @param {Object} [queryOptions] See Sequelize.query
*
* @see {Model#findAll} for a specification of find and query options
* @return {Promise<Object>}
*/
Model.prototype.findAndCountAll = function(findOptions, queryOptions) {
var self = this
// no limit, offset, order, attributes for the options given to count()
, countOptions = Utils._.omit(findOptions ? Utils._.merge({}, findOptions) : {}, ['offset', 'limit', 'order', 'attributes']);
return self.count(countOptions).then(function(count) {
if (count === 0) {
return {
count: count || 0,
rows: []
};
}
return self.findAll(findOptions, queryOptions).then(function(results) {
return {
count: count || 0,
rows: (results && Array.isArray(results) ? results : [])
};
});
});
};
/**
* Find the maximum value of field
*
* @param {String} field
* @param {Object} [options] See aggregate
* @see {Model#aggregate} for options
*
* @return {Promise<Any>}
*/
Model.prototype.max = function(field, options) {
return this.aggregate(field, 'max', options);
};
/**
* Find the minimum value of field
*
* @param {String} field
* @param {Object} [options] See aggregate
* @see {Model#aggregate} for options
*
* @return {Promise<Any>}
*/
Model.prototype.min = function(field, options) {
return this.aggregate(field, 'min', options);
};
/**
* Find the sum of field
*
* @param {String} field
* @param {Object} [options] See aggregate
* @see {Model#aggregate} for options
*
* @return {Promise<Number>}
*/
Model.prototype.sum = function(field, options) {
return this.aggregate(field, 'sum', options);
};
/**
* Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty.
* @param {Object} values
* @param {Object} [options]
* @param {Boolean} [options.raw=false] If set to true, values will ignore field and virtual setters.
* @param {Boolean} [options.isNewRecord=true]
* @param {Boolean} [options.isDirty=true]
* @param {Array} [options.include] an array of include options - Used to build prefetched/included model instances. See `set`
*
* @return {Instance}
*/
Model.prototype.build = function(values, options) {
if (Array.isArray(values)) {
return this.bulkBuild(values, options);
}
options = options || { isNewRecord: true, isDirty: true };
if (options.attributes) {
options.attributes = options.attributes.map(function(attribute) {
return Array.isArray(attribute) ? attribute[1] : attribute;
});
}
if (options.hasOwnProperty('include') && options.include && !options.includeValidated) {
validateIncludedElements.call(this, options);
}
return new this.Instance(values, options);
};
Model.prototype.bulkBuild = function(valueSets, options) {
options = options || { isNewRecord: true, isDirty: true };
if (options.hasOwnProperty('include') && options.include && !options.includeValidated) {
validateIncludedElements.call(this, options);
}
if (options.attributes) {
options.attributes = options.attributes.map(function(attribute) {
return Array.isArray(attribute) ? attribute[1] : attribute;
});
}
return valueSets.map(function(values) {
return this.build(values, options);
}.bind(this));
};
/**
* Builds a new model instance and calls save on it.
* @see {Instance#build}
* @see {Instance#save}
*