/lib/model.js

https://github.com/db6edr/library-sequelize · JavaScript · 2185 lines · 1413 code · 290 blank · 482 comment · 349 complexity · e330e719707f5dfcf5cf285c905aca34 MD5 · raw file

  1. "use strict";
  2. var Utils = require('./utils')
  3. , Instance = require('./instance')
  4. , Attribute = require('./model/attribute')
  5. , Association = require('./associations/base')
  6. , DataTypes = require('./data-types')
  7. , Util = require('util')
  8. , SqlString = require('./sql-string')
  9. , Transaction = require('./transaction')
  10. , Promise = require('./promise')
  11. , QueryTypes = require('./query-types')
  12. , Hooks = require('./hooks')
  13. , _ = require('lodash')
  14. , associationsMixin = require('./associations/mixin');
  15. module.exports = (function() {
  16. /**
  17. * 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`
  18. *
  19. * @class Model
  20. * @mixes Hooks
  21. * @mixes Associations
  22. */
  23. var Model = function(name, attributes, options) {
  24. this.options = Utils._.extend({
  25. timestamps: true,
  26. createdAt: 'createdAt',
  27. updatedAt: 'updatedAt',
  28. deletedAt: 'deletedAt',
  29. instanceMethods: {},
  30. classMethods: {},
  31. validate: {},
  32. freezeTableName: false,
  33. underscored: false,
  34. underscoredAll: false,
  35. paranoid: false,
  36. whereCollection: null,
  37. schema: null,
  38. schemaDelimiter: '',
  39. defaultScope: null,
  40. scopes: null,
  41. hooks: {}
  42. }, options || {});
  43. this.associations = {};
  44. this.modelManager = this.daoFactoryManager = null;
  45. this.name = name;
  46. this.options.hooks = _.mapValues(this.replaceHookAliases(this.options.hooks), function (hooks) {
  47. if (!Array.isArray(hooks)) hooks = [hooks];
  48. return hooks;
  49. });
  50. this.scopeObj = {};
  51. this.sequelize = options.sequelize;
  52. this.underscored = this.underscored || this.underscoredAll;
  53. if (!this.options.tableName) {
  54. this.tableName = this.options.freezeTableName ? name : Utils._.underscoredIf(Utils.pluralize(name), this.options.underscoredAll);
  55. } else {
  56. this.tableName = this.options.tableName;
  57. }
  58. // error check options
  59. Utils._.each(options.validate, function(validator, validatorType) {
  60. if (Utils._.contains(Utils._.keys(attributes), validatorType)) {
  61. throw new Error('A model validator function must not have the same name as a field. Model: ' + name + ', field/validation name: ' + validatorType);
  62. }
  63. if (!Utils._.isFunction(validator)) {
  64. throw new Error('Members of the validate option must be functions. Model: ' + name + ', error with validate member ' + validatorType);
  65. }
  66. });
  67. this.attributes = this.rawAttributes = Utils._.mapValues(attributes, function(attribute, name) {
  68. if (!Utils._.isPlainObject(attribute)) {
  69. attribute = { type: attribute };
  70. }
  71. attribute = this.sequelize.normalizeAttribute(attribute);
  72. if (attribute.references instanceof Model) {
  73. attribute.references = attribute.references.tableName;
  74. }
  75. if (attribute.type === undefined) {
  76. throw new Error('Unrecognized data type for field ' + name);
  77. }
  78. if (attribute.type instanceof DataTypes.ENUM) {
  79. if (!attribute.values.length) {
  80. throw new Error('Values for ENUM haven\'t been defined.');
  81. }
  82. attribute.validate = attribute.validate || {
  83. _checkEnum: function(value, next) {
  84. var hasValue = value !== undefined
  85. , isMySQL = ['mysql', 'mariadb'].indexOf(options.sequelize.options.dialect) !== -1
  86. , ciCollation = !!options.collate && options.collate.match(/_ci$/i) !== null
  87. , valueOutOfScope;
  88. if (isMySQL && ciCollation && hasValue) {
  89. var scopeIndex = (attributes[name].values || []).map(function(d) { return d.toLowerCase(); }).indexOf(value.toLowerCase());
  90. valueOutOfScope = scopeIndex === -1;
  91. } else {
  92. valueOutOfScope = ((attributes[name].values || []).indexOf(value) === -1);
  93. }
  94. if (hasValue && valueOutOfScope && attributes[name].allowNull !== true) {
  95. return next('Value "' + value + '" for ENUM ' + name + ' is out of allowed scope. Allowed values: ' + attributes[name].values.join(', '));
  96. }
  97. next();
  98. }
  99. };
  100. }
  101. return attribute;
  102. }, this);
  103. };
  104. Object.defineProperty(Model.prototype, 'QueryInterface', {
  105. get: function() { return this.modelManager.sequelize.getQueryInterface(); }
  106. });
  107. Object.defineProperty(Model.prototype, 'QueryGenerator', {
  108. get: function() { return this.QueryInterface.QueryGenerator; }
  109. });
  110. Model.prototype.toString = function () {
  111. return '[object SequelizeModel]';
  112. };
  113. Model.prototype.init = function(modelManager) {
  114. var self = this;
  115. this.modelManager =
  116. this.daoFactoryManager = modelManager;
  117. this.primaryKeys = {};
  118. self.options.uniqueKeys = {};
  119. // Setup names of timestamp attributes
  120. this._timestampAttributes = {};
  121. if (this.options.timestamps) {
  122. if (this.options.createdAt) {
  123. this._timestampAttributes.createdAt = Utils._.underscoredIf(this.options.createdAt, this.options.underscored);
  124. }
  125. if (this.options.updatedAt) {
  126. this._timestampAttributes.updatedAt = Utils._.underscoredIf(this.options.updatedAt, this.options.underscored);
  127. }
  128. if (this.options.paranoid && this.options.deletedAt) {
  129. this._timestampAttributes.deletedAt = Utils._.underscoredIf(this.options.deletedAt, this.options.underscored);
  130. }
  131. }
  132. // Identify primary and unique attributes
  133. Utils._.each(this.rawAttributes, function(options, attribute) {
  134. if (options.hasOwnProperty('unique')) {
  135. var idxName;
  136. if (options.unique === true) {
  137. idxName = self.tableName + '_' + attribute + '_unique';
  138. self.options.uniqueKeys[idxName] = {
  139. name: idxName,
  140. fields: [attribute],
  141. singleField: true
  142. };
  143. } else if (options.unique !== false) {
  144. idxName = options.unique;
  145. if (typeof options.unique === 'object') {
  146. idxName = options.unique.name;
  147. }
  148. self.options.uniqueKeys[idxName] = self.options.uniqueKeys[idxName] || {fields: [], msg: null};
  149. self.options.uniqueKeys[idxName].fields.push(options.field || attribute);
  150. self.options.uniqueKeys[idxName].msg = self.options.uniqueKeys[idxName].msg || options.unique.msg || null;
  151. self.options.uniqueKeys[idxName].name = idxName || false;
  152. }
  153. }
  154. if (options.primaryKey === true) {
  155. self.primaryKeys[attribute] = self.attributes[attribute];
  156. }
  157. });
  158. // Add head and tail default attributes (id, timestamps)
  159. addDefaultAttributes.call(this);
  160. addOptionalClassMethods.call(this);
  161. // Primary key convenience variables
  162. this.primaryKeyAttributes = Object.keys(this.primaryKeys);
  163. this.primaryKeyAttribute = this.primaryKeyAttributes[0];
  164. this.primaryKeyField = this.rawAttributes[this.primaryKeyAttribute].field || this.primaryKeyAttribute;
  165. this.primaryKeyCount = this.primaryKeyAttributes.length;
  166. this._hasPrimaryKeys = this.options.hasPrimaryKeys = this.hasPrimaryKeys = this.primaryKeyCount > 0;
  167. this._isPrimaryKey = Utils._.memoize(function(key) {
  168. return self.primaryKeyAttributes.indexOf(key) !== -1;
  169. });
  170. if (typeof this.options.defaultScope === 'object') {
  171. Utils.injectScope.call(this, this.options.defaultScope);
  172. }
  173. // Instance prototype
  174. this.Instance = this.DAO = function() {
  175. Instance.apply(this, arguments);
  176. };
  177. Util.inherits(this.Instance, Instance);
  178. this._readOnlyAttributes = Utils._.values(this._timestampAttributes);
  179. this._hasReadOnlyAttributes = this._readOnlyAttributes && this._readOnlyAttributes.length;
  180. this._isReadOnlyAttribute = Utils._.memoize(function(key) {
  181. return self._hasReadOnlyAttributes && self._readOnlyAttributes.indexOf(key) !== -1;
  182. });
  183. if (this.options.instanceMethods) {
  184. Utils._.each(this.options.instanceMethods, function(fct, name) {
  185. self.Instance.prototype[name] = fct;
  186. });
  187. }
  188. this.refreshAttributes();
  189. findAutoIncrementField.call(this);
  190. this.Instance.prototype.$Model =
  191. this.Instance.prototype.Model = this;
  192. return this;
  193. };
  194. Model.prototype.refreshAttributes = function() {
  195. var self = this
  196. , attributeManipulation = {};
  197. this.Instance.prototype._customGetters = {};
  198. this.Instance.prototype._customSetters = {};
  199. Utils._.each(['get', 'set'], function(type) {
  200. var opt = type + 'terMethods'
  201. , funcs = Utils._.clone(Utils._.isObject(self.options[opt]) ? self.options[opt] : {})
  202. , _custom = type === 'get' ? self.Instance.prototype._customGetters : self.Instance.prototype._customSetters;
  203. Utils._.each(funcs, function(method, attribute) {
  204. _custom[attribute] = method;
  205. if (type === 'get') {
  206. funcs[attribute] = function() {
  207. return this.get(attribute);
  208. };
  209. }
  210. if (type === 'set') {
  211. funcs[attribute] = function(value) {
  212. return this.set(attribute, value);
  213. };
  214. }
  215. });
  216. Utils._.each(self.rawAttributes, function(options, attribute) {
  217. if (options.hasOwnProperty(type)) {
  218. _custom[attribute] = options[type];
  219. }
  220. if (type === 'get') {
  221. funcs[attribute] = function() {
  222. return this.get(attribute);
  223. };
  224. }
  225. if (type === 'set') {
  226. funcs[attribute] = function(value) {
  227. return this.set(attribute, value);
  228. };
  229. }
  230. });
  231. Utils._.each(funcs, function(fct, name) {
  232. if (!attributeManipulation[name]) {
  233. attributeManipulation[name] = {
  234. configurable: true
  235. };
  236. }
  237. attributeManipulation[name][type] = fct;
  238. });
  239. });
  240. this._booleanAttributes = [];
  241. this._dateAttributes = [];
  242. this._hstoreAttributes = [];
  243. this._rangeAttributes = [];
  244. this._jsonAttributes = [];
  245. this._virtualAttributes = [];
  246. this._defaultValues = {};
  247. this.Instance.prototype.validators = {};
  248. Utils._.each(this.rawAttributes, function(definition, name) {
  249. definition.type = self.sequelize.normalizeDataType(definition.type);
  250. definition.Model = self;
  251. definition.fieldName = name;
  252. definition._modelAttribute = true;
  253. if (definition.field === undefined) {
  254. definition.field = name;
  255. }
  256. if (definition.type instanceof DataTypes.BOOLEAN) {
  257. self._booleanAttributes.push(name);
  258. } else if (definition.type instanceof DataTypes.DATE) {
  259. self._dateAttributes.push(name);
  260. } else if (definition.type instanceof DataTypes.HSTORE || DataTypes.ARRAY.is(definition.type, DataTypes.HSTORE)) {
  261. self._hstoreAttributes.push(name);
  262. } else if (definition.type instanceof DataTypes.RANGE || DataTypes.ARRAY.is(definition.type, DataTypes.RANGE)) {
  263. self._rangeAttributes.push(name);
  264. } else if (definition.type instanceof DataTypes.JSON) {
  265. self._jsonAttributes.push(name);
  266. } else if (definition.type instanceof DataTypes.VIRTUAL) {
  267. self._virtualAttributes.push(name);
  268. }
  269. if (definition.hasOwnProperty('defaultValue')) {
  270. if (typeof definition.defaultValue === "function" && (
  271. definition.defaultValue === DataTypes.NOW ||
  272. definition.defaultValue === DataTypes.UUIDV4 ||
  273. definition.defaultValue === DataTypes.UUIDV4
  274. )) {
  275. definition.defaultValue = new definition.defaultValue();
  276. }
  277. self._defaultValues[name] = Utils._.partial(Utils.toDefaultValue, definition.defaultValue);
  278. }
  279. if (definition.hasOwnProperty('validate')) {
  280. self.Instance.prototype.validators[name] = definition.validate;
  281. }
  282. });
  283. this._hasBooleanAttributes = !!this._booleanAttributes.length;
  284. this._isBooleanAttribute = Utils._.memoize(function(key) {
  285. return self._booleanAttributes.indexOf(key) !== -1;
  286. });
  287. this._hasDateAttributes = !!this._dateAttributes.length;
  288. this._isDateAttribute = Utils._.memoize(function(key) {
  289. return self._dateAttributes.indexOf(key) !== -1;
  290. });
  291. this._hasHstoreAttributes = !!this._hstoreAttributes.length;
  292. this._isHstoreAttribute = Utils._.memoize(function(key) {
  293. return self._hstoreAttributes.indexOf(key) !== -1;
  294. });
  295. this._hasRangeAttributes = !!this._rangeAttributes.length;
  296. this._isRangeAttribute = Utils._.memoize(function(key) {
  297. return self._rangeAttributes.indexOf(key) !== -1;
  298. });
  299. this._hasJsonAttributes = !!this._jsonAttributes.length;
  300. this._isJsonAttribute = Utils._.memoize(function(key) {
  301. return self._jsonAttributes.indexOf(key) !== -1;
  302. });
  303. this._hasVirtualAttributes = !!this._virtualAttributes.length;
  304. this._isVirtualAttribute = Utils._.memoize(function(key) {
  305. return self._virtualAttributes.indexOf(key) !== -1;
  306. });
  307. this._hasDefaultValues = !Utils._.isEmpty(this._defaultValues);
  308. this.attributes = this.rawAttributes;
  309. this.tableAttributes = Utils._.omit(this.rawAttributes, this._virtualAttributes);
  310. this.Instance.prototype._hasCustomGetters = Object.keys(this.Instance.prototype._customGetters).length;
  311. this.Instance.prototype._hasCustomSetters = Object.keys(this.Instance.prototype._customSetters).length;
  312. Object.defineProperties(this.Instance.prototype, attributeManipulation);
  313. this.Instance.prototype.rawAttributes = this.rawAttributes;
  314. this.Instance.prototype.attributes = Object.keys(this.Instance.prototype.rawAttributes);
  315. this.Instance.prototype._isAttribute = Utils._.memoize(function(key) {
  316. return self.Instance.prototype.attributes.indexOf(key) !== -1;
  317. });
  318. };
  319. /**
  320. * Remove attribute from model definition
  321. * @param {String} [attribute]
  322. */
  323. Model.prototype.removeAttribute = function(attribute) {
  324. delete this.rawAttributes[attribute];
  325. this.refreshAttributes();
  326. };
  327. /**
  328. * Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the model instance (this)
  329. * @see {Sequelize#sync} for options
  330. * @return {Promise<this>}
  331. */
  332. Model.prototype.sync = function(options) {
  333. options = Utils._.extend({}, this.options, options || {});
  334. var self = this
  335. , attributes = this.tableAttributes;
  336. return Promise.resolve().then(function () {
  337. if (options.force) {
  338. return self.drop(options);
  339. }
  340. }).then(function () {
  341. return self.QueryInterface.createTable(self.getTableName(options), attributes, options);
  342. }).then(function () {
  343. return self.QueryInterface.showIndex(self.getTableName(options), options);
  344. }).then(function (indexes) {
  345. // Assign an auto-generated name to indexes which are not named by the user
  346. self.options.indexes = self.QueryInterface.nameIndexes(self.options.indexes, self.tableName);
  347. indexes = Utils._.filter(self.options.indexes, function (item1) {
  348. return !Utils._.any(indexes, function (item2) {
  349. return item1.name === item2.name;
  350. });
  351. });
  352. return Promise.map(indexes, function (index) {
  353. return self.QueryInterface.addIndex(self.getTableName(options), index.fields, index, self.tableName);
  354. });
  355. }).return(this);
  356. };
  357. /**
  358. * Drop the table represented by this Model
  359. * @param {Object} [options]
  360. * @param {Boolean} [options.cascade=false] Also drop all objects depending on this table, such as views. Only works in postgres
  361. * @return {Promise}
  362. */
  363. Model.prototype.drop = function(options) {
  364. return this.QueryInterface.dropTable(this.getTableName(options), options);
  365. };
  366. Model.prototype.dropSchema = function(schema) {
  367. return this.QueryInterface.dropSchema(schema);
  368. };
  369. /**
  370. * Apply a schema to this model. For postgres, this will actually place the schema in front of the table name - `"schema"."tableName"`,
  371. * while the schema will be prepended to the table name for mysql and sqlite - `'schema.tablename'`.
  372. *
  373. * @param {String} schema The name of the schema
  374. * @param {Object} [options]
  375. * @param {String} [options.schemaDelimiter='.'] The character(s) that separates the schema name from the table name
  376. * @return this
  377. */
  378. Model.prototype.schema = function(schema, options) {
  379. this.options.schema = schema;
  380. if (!!options) {
  381. if (typeof options === 'string') {
  382. this.options.schemaDelimiter = options;
  383. } else {
  384. if (!!options.schemaDelimiter) {
  385. this.options.schemaDelimiter = options.schemaDelimiter;
  386. }
  387. }
  388. }
  389. return this;
  390. };
  391. /**
  392. * 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,
  393. * or an object with `tableName`, `schema` and `delimiter` properties.
  394. *
  395. * @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)
  396. * @return {String|Object}
  397. */
  398. Model.prototype.getTableName = function(options) {
  399. return this.QueryGenerator.addSchema(this);
  400. };
  401. /**
  402. * Apply a scope created in `define` to the model. First let's look at how to create scopes:
  403. * ```js
  404. * var Model = sequelize.define('model', attributes, {
  405. * defaultScope: {
  406. * where: {
  407. * username: 'dan'
  408. * },
  409. * limit: 12
  410. * },
  411. * scopes: {
  412. * isALie: {
  413. * where: {
  414. * stuff: 'cake'
  415. * }
  416. * },
  417. * complexFunction: function(email, accessLevel) {
  418. * return {
  419. * where: ['email like ? AND access_level >= ?', email + '%', accessLevel]
  420. * }
  421. * },
  422. * }
  423. * })
  424. * ```
  425. * 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:
  426. * ```js
  427. * Model.findAll() // WHERE username = 'dan'
  428. * Model.findAll({ where: { age: { gt: 12 } } }) // WHERE age > 12 AND username = 'dan'
  429. * ```
  430. *
  431. * To invoke scope functions you can do:
  432. * ```js
  433. * Model.scope({ method: ['complexFunction' 'dan@sequelize.com', 42]}).findAll()
  434. * // WHERE email like 'dan@sequelize.com%' AND access_level >= 42
  435. * ```
  436. *
  437. * @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.
  438. * @return {Model} A reference to the model, with the scope(s) applied. Calling scope again on the returned model will clear the previous scope.
  439. */
  440. Model.prototype.scope = function(option) {
  441. var self = Object.create(this)
  442. , type
  443. , options
  444. , merge
  445. , i
  446. , scope
  447. , scopeName
  448. , scopeOptions
  449. , argLength = arguments.length
  450. , lastArg = arguments[argLength - 1];
  451. self.scoped = true;
  452. // Set defaults
  453. scopeOptions = (typeof lastArg === 'object' && !Array.isArray(lastArg) ? lastArg : {}) || {}; // <-- for no arguments
  454. scopeOptions.silent = (scopeOptions !== null && scopeOptions.hasOwnProperty('silent') ? scopeOptions.silent : true);
  455. // Clear out any predefined scopes...
  456. self.scopeObj = {};
  457. // Possible formats for option:
  458. // String of arguments: 'hello', 'world', 'etc'
  459. // Array: ['hello', 'world', 'etc']
  460. // Object: {merge: 'hello'}, {method: ['scopeName' [, args1, args2..]]}, {merge: true, method: ...}
  461. if (argLength < 1 || !option) {
  462. return self;
  463. }
  464. for (i = 0; i < argLength; i++) {
  465. options = Array.isArray(arguments[i]) ? arguments[i] : [arguments[i]];
  466. options.forEach(function(o) {
  467. type = typeof o;
  468. scope = null;
  469. merge = false;
  470. scopeName = null;
  471. if (type === 'object') {
  472. // Right now we only support a merge functionality for objects
  473. if (!!o.merge) {
  474. merge = true;
  475. scopeName = o.merge[0];
  476. if (Array.isArray(o.merge) && !!self.options.scopes[scopeName]) {
  477. scope = self.options.scopes[scopeName].apply(self, o.merge.splice(1));
  478. }
  479. else if (typeof o.merge === 'string') {
  480. scopeName = o.merge;
  481. scope = self.options.scopes[scopeName];
  482. }
  483. }
  484. if (!!o.method) {
  485. if (Array.isArray(o.method) && !!self.options.scopes[o.method[0]]) {
  486. scopeName = o.method[0];
  487. scope = self.options.scopes[scopeName].apply(self, o.method.splice(1));
  488. merge = !!o.merge;
  489. }
  490. else if (!!self.options.scopes[o.method]) {
  491. scopeName = o.method;
  492. scope = self.options.scopes[scopeName].apply(self);
  493. }
  494. } else {
  495. scopeName = o;
  496. scope = self.options.scopes[scopeName];
  497. }
  498. if (o.where) {
  499. scope = o;
  500. merge = true;
  501. }
  502. } else {
  503. scopeName = o;
  504. scope = self.options.scopes[scopeName];
  505. }
  506. if (!!scope) {
  507. Utils.injectScope.call(self, scope, merge);
  508. }
  509. else if (scopeOptions.silent !== true && !!scopeName) {
  510. throw new Error('Invalid scope ' + scopeName + ' called.');
  511. }
  512. });
  513. }
  514. return self;
  515. };
  516. Model.prototype.all = function(options, queryOptions) {
  517. return this.findAll(options, queryOptions);
  518. };
  519. /**
  520. * Search for multiple instances.
  521. *
  522. * __Simple search using AND and =__
  523. * ```js
  524. * Model.findAll({
  525. * where: {
  526. * attr1: 42,
  527. * attr2: 'cake'
  528. * }
  529. * })
  530. * ```
  531. * ```sql
  532. * WHERE attr1 = 42 AND attr2 = 'cake'
  533. *```
  534. *
  535. * __Using greater than, less than etc.__
  536. * ```js
  537. *
  538. * Model.findAll({
  539. * where: {
  540. * attr1: {
  541. * gt: 50
  542. * },
  543. * attr2: {
  544. * lte: 45
  545. * },
  546. * attr3: {
  547. * in: [1,2,3]
  548. * },
  549. * attr4: {
  550. * ne: 5
  551. * }
  552. * }
  553. * })
  554. * ```
  555. * ```sql
  556. * WHERE attr1 > 50 AND attr2 <= 45 AND attr3 IN (1,2,3) AND attr4 != 5
  557. * ```
  558. * Possible options are: `gt, gte, lt, lte, ne, between/.., nbetween/notbetween/!.., in, not, like, nlike/notlike`
  559. *
  560. * __Queries using OR__
  561. * ```js
  562. * Model.findAll({
  563. * where: Sequelize.and(
  564. * { name: 'a project' },
  565. * Sequelize.or(
  566. * { id: [1,2,3] },
  567. * { id: { gt: 10 } }
  568. * )
  569. * )
  570. * })
  571. * ```
  572. * ```sql
  573. * WHERE name = 'a project' AND (id` IN (1,2,3) OR id > 10)
  574. * ```
  575. *
  576. * The success listener is called with an array of instances if the query succeeds.
  577. *
  578. * @param {Object} [options] A hash of options to describe the scope of the search
  579. * @param {Object} [options.where] A hash of attributes to describe your search. See above for examples.
  580. * @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
  581. * @param {Boolean} [options.paranoid=true] If true, only non-deleted records will be returned. If false, both deleted and non-deleted records will be returned. Only applies if `options.paranoid` is true for the model.
  582. * @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).
  583. * @param {Model} [options.include[].model] The model you want to eagerly load
  584. * @param {String} [options.include[].as] The alias of the relation, in case the model you want to eagerly load is aliassed. For `hasOne` / `belongsTo`, this should be the singular name, and for `hasMany`, it should be the plural
  585. * @param {Association} [options.include[].association] The association you want to eagerly load. (This can be used instead of providing a model/as pair)
  586. * @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: false`
  587. * @param {Array<String>} [options.include[].attributes] A list of attributes to select from the child model
  588. * @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.
  589. * @param {Array<Object|Model>} [options.include[].include] Load further nested related models
  590. * @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.
  591. * @param {Number} [options.limit]
  592. * @param {Number} [options.offset]
  593. * @param {Transaction} [options.transaction]
  594. * @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
  595. * @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)
  596. *
  597. * @see {Sequelize#query}
  598. * @return {Promise<Array<Instance>>}
  599. * @alias all
  600. */
  601. Model.prototype.findAll = function(options, queryOptions) {
  602. var hasJoin = false
  603. , tableNames = { };
  604. tableNames[this.getTableName(options)] = true;
  605. options = optClone(options || {});
  606. options = Utils._.defaults(options, {
  607. hooks: true
  608. });
  609. return Promise.bind(this).then(function() {
  610. conformOptions(options);
  611. if (options.hooks) {
  612. return this.runHooks('beforeFind', options);
  613. }
  614. }).then(function() {
  615. expandIncludeAll.call(this, options);
  616. if (options.hooks) {
  617. return this.runHooks('beforeFindAfterExpandIncludeAll', options);
  618. }
  619. }).then(function() {
  620. if (typeof options === 'object') {
  621. if (options.include) {
  622. hasJoin = true;
  623. validateIncludedElements.call(this, options, tableNames);
  624. if (options.attributes) {
  625. if (options.attributes.indexOf(this.primaryKeyAttribute) === -1) {
  626. options.originalAttributes = options.attributes;
  627. options.attributes = [this.primaryKeyAttribute].concat(options.attributes);
  628. }
  629. }
  630. }
  631. // whereCollection is used for non-primary key updates
  632. this.options.whereCollection = options.where || null;
  633. }
  634. if (options.attributes === undefined) {
  635. options.attributes = Object.keys(this.tableAttributes);
  636. }
  637. Utils.mapOptionFieldNames(options, this);
  638. options = paranoidClause(this, options);
  639. if (options.hooks) {
  640. return this.runHooks('beforeFindAfterOptions', options);
  641. }
  642. }).then(function() {
  643. return this.QueryInterface.select(this, this.getTableName(options), options, Utils._.defaults({
  644. hasJoin: hasJoin,
  645. tableNames: Object.keys(tableNames)
  646. }, queryOptions, { transaction: options.transaction, logging: options.logging }));
  647. }).tap(function(results) {
  648. if (options.hooks) {
  649. return this.runHooks('afterFind', results, options);
  650. }
  651. });
  652. };
  653. //right now, the caller (has-many-double-linked) is in charge of the where clause
  654. Model.prototype.findAllJoin = function(joinTableName, options, queryOptions) {
  655. options = optClone(options || {});
  656. options.attributes = options.attributes || [this.QueryInterface.quoteTable(this.name) + '.*'];
  657. // whereCollection is used for non-primary key updates
  658. this.options.whereCollection = options.where || null;
  659. return this.QueryInterface.select(this, [[this.getTableName(options), this.name], joinTableName], options, Utils._.defaults(queryOptions, { transaction: (options || {}).transaction }));
  660. };
  661. /**
  662. * Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single instance.
  663. *
  664. * @param {Object|Number} [options] A hash of options to describe the scope of the search, or a number to search by id.
  665. * @param {Transaction} [options.transaction]
  666. * @param {Object} [queryOptions]
  667. *
  668. * @see {Model#findAll} for an explanation of options and queryOptions
  669. * @return {Promise<Instance>}
  670. * @alias find
  671. */
  672. Model.prototype.findOne = function(param, queryOptions) {
  673. // For sanity findOne will never return if no options are passed
  674. if ([null, undefined].indexOf(param) !== -1) {
  675. return Promise.resolve(null);
  676. }
  677. var options = {};
  678. if (typeof param === 'number' || typeof param === 'string' || Buffer.isBuffer(param)) {
  679. options.where = {};
  680. options.where[this.primaryKeyAttribute] = param;
  681. } else {
  682. options = optClone(param);
  683. }
  684. if (options.limit === undefined && !(options.where && options.where[this.primaryKeyAttribute])) {
  685. options.limit = 1;
  686. }
  687. // Bypass a possible overloaded findAll.
  688. return Model.prototype.findAll.call(this, options, Utils._.defaults({
  689. plain: true
  690. }, queryOptions || {}));
  691. };
  692. Model.prototype.find = Model.prototype.findOne;
  693. /**
  694. * Run an aggregation method on the specified field
  695. *
  696. * @param {String} field The field to aggregate over. Can be a field name or *
  697. * @param {String} aggregateFunction The function to use for aggregation, e.g. sum, max etc.
  698. * @param {Object} [options] Query options. See sequelize.query for full options
  699. * @param {Object} [options.where] A hash of search attributes.
  700. * @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.
  701. * @param {boolean} [options.distinct] Applies DISTINCT to the field being aggregated over
  702. * @param {Transaction} [options.transaction]
  703. * @param {boolean} [options.plain] When `true`, the first returned value of `aggregateFunction` is cast to `dataType` and returned. If additional attributes are specified, along with `group` clauses, set `plain` to `false` to return all values of all returned rows. Defaults to `true`
  704. *
  705. * @return {Promise<options.dataType|object>} Returns the aggregate result cast to `options.dataType`, unless `options.plain` is false, in which case the complete data result is returned.
  706. */
  707. Model.prototype.aggregate = function(field, aggregateFunction, options) {
  708. options = Utils._.extend({ attributes: [] }, options || {});
  709. var aggregateColumn = this.sequelize.col(field);
  710. if (options.distinct) {
  711. aggregateColumn = this.sequelize.fn('DISTINCT', aggregateColumn);
  712. }
  713. options.attributes.push([this.sequelize.fn(aggregateFunction, aggregateColumn), aggregateFunction]);
  714. if (!options.dataType) {
  715. if (this.rawAttributes[field]) {
  716. options.dataType = this.rawAttributes[field].type;
  717. } else {
  718. // Use FLOAT as fallback
  719. options.dataType = new DataTypes.FLOAT();
  720. }
  721. } else {
  722. options.dataType = this.sequelize.normalizeDataType(options.dataType);
  723. }
  724. options = paranoidClause(this, options);
  725. return this.QueryInterface.rawSelect(this.getTableName(options), options, aggregateFunction, this);
  726. };
  727. /**
  728. * Count the number of records matching the provided where clause.
  729. *
  730. * If you provide an `include` option, the number of matching associations will be counted instead.
  731. *
  732. * @param {Object} [options]
  733. * @param {Object} [options.where] A hash of search attributes.
  734. * @param {Object} [options.include] Include options. See `find` for details
  735. * @param {boolean} [options.distinct] Apply COUNT(DISTINCT(col))
  736. * @param {Object} [options.attributes] Used in conjustion with `group`
  737. * @param {Object} [options.group] For creating complex counts. Will return multiple rows as needed.
  738. *
  739. * @return {Promise<Integer>}
  740. */
  741. Model.prototype.count = function(options) {
  742. options = Utils._.clone(options || {});
  743. conformOptions(options);
  744. var col = '*';
  745. if (options.include) {
  746. col = this.name + '.' + this.primaryKeyAttribute;
  747. expandIncludeAll.call(this, options);
  748. validateIncludedElements.call(this, options);
  749. }
  750. Utils.mapOptionFieldNames(options, this);
  751. options.plain = options.group ? false : true;
  752. options.dataType = new DataTypes.INTEGER();
  753. options.includeIgnoreAttributes = false;
  754. options.limit = null;
  755. return this.aggregate(col, 'count', options);
  756. };
  757. /**
  758. * 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
  759. *
  760. * ```js
  761. * Model.findAndCountAll({
  762. * where: ...,
  763. * limit: 12,
  764. * offset: 12
  765. * }).success(function (result) {
  766. * })
  767. * ```
  768. * 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.
  769. *
  770. * @param {Object} [findOptions] See findAll
  771. * @param {Object} [queryOptions] See Sequelize.query
  772. *
  773. * @see {Model#findAll} for a specification of find and query options
  774. * @return {Promise<Object>}
  775. * @alias findAndCountAll
  776. */
  777. Model.prototype.findAndCount = function(findOptions, queryOptions) {
  778. findOptions = findOptions || {};
  779. var self = this
  780. // no limit, offset, order, attributes for the options given to count()
  781. , countOptions = _.omit(_.clone(findOptions), ['offset', 'limit', 'order', 'attributes']);
  782. conformOptions(countOptions);
  783. if (countOptions.include) {
  784. countOptions.include = _.cloneDeep(countOptions.include, function (element) {
  785. if (element instanceof Model) return element;
  786. if (element instanceof Association) return element;
  787. return undefined;
  788. });
  789. expandIncludeAll.call(this, countOptions);
  790. validateIncludedElements.call(this, countOptions);
  791. var keepNeeded = function(includes) {
  792. return includes.filter(function (include) {
  793. if (include.include) include.include = keepNeeded(include.include);
  794. return include.required || include.hasIncludeRequired;
  795. });
  796. };
  797. countOptions.include = keepNeeded(countOptions.include);
  798. }
  799. return self.count(countOptions).then(function(count) {
  800. if (count === 0) {
  801. return {
  802. count: count || 0,
  803. rows: []
  804. };
  805. }
  806. return self.findAll(findOptions, queryOptions).then(function(results) {
  807. return {
  808. count: count || 0,
  809. rows: (results && Array.isArray(results) ? results : [])
  810. };
  811. });
  812. });
  813. };
  814. Model.prototype.findAndCountAll = Model.prototype.findAndCount;
  815. /**
  816. * Find the maximum value of field
  817. *
  818. * @param {String} field
  819. * @param {Object} [options] See aggregate
  820. * @see {Model#aggregate} for options
  821. *
  822. * @return {Promise<Any>}
  823. */
  824. Model.prototype.max = function(field, options) {
  825. return this.aggregate(field, 'max', options);
  826. };
  827. /**
  828. * Find the minimum value of field
  829. *
  830. * @param {String} field
  831. * @param {Object} [options] See aggregate
  832. * @see {Model#aggregate} for options
  833. *
  834. * @return {Promise<Any>}
  835. */
  836. Model.prototype.min = function(field, options) {
  837. return this.aggregate(field, 'min', options);
  838. };
  839. /**
  840. * Find the sum of field
  841. *
  842. * @param {String} field
  843. * @param {Object} [options] See aggregate
  844. * @see {Model#aggregate} for options
  845. *
  846. * @return {Promise<Number>}
  847. */
  848. Model.prototype.sum = function(field, options) {
  849. return this.aggregate(field, 'sum', options);
  850. };
  851. /**
  852. * Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty.
  853. * @param {Object} values
  854. * @param {Object} [options]
  855. * @param {Boolean} [options.raw=false] If set to true, values will ignore field and virtual setters.
  856. * @param {Boolean} [options.isNewRecord=true]
  857. * @param {Boolean} [options.isDirty=true]
  858. * @param {Array} [options.include] an array of include options - Used to build prefetched/included model instances. See `set`
  859. *
  860. * @return {Instance}
  861. */
  862. Model.prototype.build = function(values, options) {
  863. if (Array.isArray(values)) {
  864. return this.bulkBuild(values, options);
  865. }
  866. options = Utils._.extend({
  867. isNewRecord: true,
  868. isDirty: true
  869. }, options || {});
  870. if (options.attributes) {
  871. options.attributes = options.attributes.map(function(attribute) {
  872. return Array.isArray(attribute) ? attribute[1] : attribute;
  873. });
  874. }
  875. if (!options.includeValidated) {
  876. conformOptions(options);
  877. if (options.include) {
  878. expandIncludeAll.call(this, options);
  879. validateIncludedElements.call(this, options);
  880. }
  881. }
  882. return new this.Instance(values, options);
  883. };
  884. Model.prototype.bulkBuild = function(valueSets, options) {
  885. options = Utils._.extend({
  886. isNewRecord: true,
  887. isDirty: true
  888. }, options || {});
  889. if (!options.includeValidated) {
  890. conformOptions(options);
  891. if (options.include) {
  892. expandIncludeAll.call(this, options);
  893. validateIncludedElements.call(this, options);
  894. }
  895. }
  896. if (options.attributes) {
  897. options.attributes = options.attributes.map(function(attribute) {
  898. return Array.isArray(attribute) ? attribute[1] : attribute;
  899. });
  900. }
  901. return valueSets.map(function(values) {
  902. return this.build(values, options);
  903. }.bind(this));
  904. };
  905. /**
  906. * Builds a new model instance and calls save on it.
  907. * @see {Instance#build}
  908. * @see {Instance#save}
  909. *
  910. * @param {Object} values
  911. * @param {Object} [options]
  912. * @param {Boolean} [options.raw=false] If set to true, values will ignore field and virtual setters.
  913. * @param {Boolean} [options.isNewRecord=true]
  914. * @param {Boolean} [options.isDirty=true]
  915. * @param {Array} [options.fields] If set, only columns matching those in fields will be saved
  916. * @param {Array} [options.include] an array of include options - Used to build prefetched/included model instances
  917. * @param {String} [options.onDuplicate]
  918. * @param {Transaction} [options.transaction]
  919. *
  920. * @return {Promise<Instance>}
  921. */
  922. Model.prototype.create = function(values, options) {
  923. Utils.validateParameter(values, Object, { optional: true });
  924. Utils.validateParameter(options, Object, { deprecated: Array, optional: true, index: 2, method: 'Model#create' });
  925. if (options instanceof Array) {
  926. options = { fields: options };
  927. }
  928. options = options || {};
  929. return this.build(values, {
  930. isNewRecord: true,
  931. attributes: options.fields,
  932. include: options.include,
  933. raw: options.raw,
  934. silent: options.silent
  935. }).save(options);
  936. };
  937. /**
  938. * Find a row that matches the query, or build (but don't save) the row if none is found.
  939. * The successfull result of the promise will be (instance, initialized) - Make sure to use .spread()
  940. *
  941. * @param {Object} options
  942. * @param {Object} options.where A hash of search attributes.
  943. * @param {Object} [options.defaults] Default values to use if building a new instance
  944. * @param {Object} [options.transaction] Transaction to run query under
  945. *
  946. * @return {Promise<Instance>}
  947. * @alias findOrBuild
  948. */
  949. Model.prototype.findOrInitialize = Model.prototype.findOrBuild = function(options) {
  950. if (!options || !options.where) {
  951. throw new Error('Missing where attribute in the options parameter passed to findOrCreate. Please note that the API has changed, and is now options (an object with where and defaults keys), queryOptions (transaction etc.)');
  952. }
  953. var self = this
  954. , values;
  955. return self.find({
  956. where: options.where
  957. }, options).then(function(instance) {
  958. if (instance === null) {
  959. values = Utils._.clone(options.defaults) || {};
  960. if (Utils._.isPlainObject(options.where)) {
  961. values = Utils._.defaults(values, options.where);
  962. }
  963. instance = self.build(values);
  964. return Promise.resolve([instance, true]);
  965. }
  966. return Promise.resolve([instance, false]);
  967. });
  968. };
  969. /**
  970. * Find a row that matches the query, or build and save the row if none is found
  971. * The successfull result of the promise will be (instance, created) - Make sure to use .spread()
  972. *
  973. * If no transaction is passed in the `queryOptions` object, a new transaction will be created internally, to prevent the race condition where a matching row is created by another connection after the find but before the insert call.
  974. * However, it is not always possible to handle this case in SQLite, specifically if one transaction inserts and another tries to select before the first one has comitted. In this case, an instance of sequelize.TimeoutError will be thrown instead.
  975. * If a transaction is created, a savepoint will be created instead, and any unique constraint violation will be handled internally.
  976. *
  977. * @param {Object} options
  978. * @param {Object} options.where where A hash of search attributes.
  979. * @param {Object} [options.defaults] Default values to use if creating a new instance
  980. * @param {Object} [queryOptions] Options passed to the find and create calls
  981. *
  982. * @return {Promise<Instance,created>}
  983. */
  984. Model.prototype.findOrCreate = function(options, queryOptions) {
  985. var self = this
  986. , internalTransaction = !(queryOptions && queryOptions.transaction)
  987. , values
  988. , whereFields
  989. , defaultFields;
  990. if (!options || !options.where) {
  991. throw new Error('Missing where attribute in the options parameter passed to findOrCreate. Please note that the API has changed, and is now options (an object with where and defaults keys), queryOptions (transaction etc.)');
  992. }
  993. queryOptions = queryOptions ? Utils._.clone(queryOptions) : {};
  994. if (options.logging) queryOptions.logging = options.logging;
  995. whereFields = Object.keys(options.where);
  996. if (options.defaults) defaultFields = Object.keys(options.defaults);
  997. // Create a transaction or a savepoint, depending on whether a transaction was passed in
  998. return self.sequelize.transaction(queryOptions).bind({}).then(function (transaction) {
  999. this.transaction = transaction;
  1000. queryOptions.transaction = transaction;
  1001. return self.find(options, {
  1002. transaction: transaction
  1003. });
  1004. }).then(function(instance) {
  1005. if (instance !== null) {
  1006. return [instance, false];
  1007. }
  1008. values = Utils._.clone(options.defaults) || {};
  1009. if (Utils._.isPlainObject(options.where)) {
  1010. values = Utils._.defaults(values, options.where);
  1011. }
  1012. queryOptions.exception = true;
  1013. return self.create(values, queryOptions).bind(this).then(function(instance) {
  1014. if (instance.get(self.primaryKeyAttribute, { raw: true }) === null) {
  1015. // If the query returned an empty result for the primary key, we know that this was actually a unique constraint violation
  1016. throw new self.sequelize.UniqueConstraintError();
  1017. }
  1018. return [instance, true];
  1019. }).catch(self.sequelize.UniqueConstraintError, function (err) {
  1020. if (defaultFields) {
  1021. if (!_.intersection(err.fields, whereFields).length && _.intersection(err.fields, defaultFields).length) {
  1022. throw err;
  1023. }
  1024. }
  1025. // Someone must have created a matching instance inside the same transaction since we last did a find. Let's find it!
  1026. return self.find(options, {
  1027. transaction: internalTransaction ? null : this.transaction
  1028. }).then(function(instance) {
  1029. // Sanity check, ideally we caught this at the defaultFeilds/err.fields check
  1030. // But if we didn't and instance is null, we will throw
  1031. if (instance === null) throw err;
  1032. return [instance, false];
  1033. });
  1034. });
  1035. }).finally(function () {
  1036. if (internalTransaction && this.transaction) {
  1037. // If we created a transaction internally, we should clean it up
  1038. return this.transaction.commit();
  1039. }
  1040. });
  1041. };
  1042. /**
  1043. * Insert or update a single row. An update will be executed if a row which matches the supplied values on either the primary key or a unique key is found. Note that the unique index must be defined in your sequelize model and not just in the table. Otherwise you may experience a unique constraint violation, because sequelize fails to identify the row that should be updated.
  1044. *
  1045. * **Implementation details:**
  1046. *
  1047. * * MySQL - Implemented as a single query `INSERT values ON DUPLICATE KEY UPDATE values`
  1048. * * PostgreSQL - Implemented as a temporary function with exception handling: INSERT EXCEPTION WHEN unique_constraint UPDATE
  1049. * * SQLite - Implemented as two queries `INSERT; UPDATE`. This means that the update is executed regardless of whether the row already existed or not
  1050. *
  1051. * **Note** that SQLite returns undefined for created, no matter if the row was created or updated. This is because SQLite always runs INSERT OR IGNORE + UPDATE, in a single query, so there is no way to know whether the row was inserted or not.
  1052. *
  1053. * @param {Object} values
  1054. * @param {Object} [options]
  1055. * @param {Boolean} [options.validate=true] Run validations before the row is inserted
  1056. * @param {Array} [options.fields=Object.keys(this.attributes)] The fields to insert / update. Defaults to all fields
  1057. *
  1058. * @alias insertOrUpdate
  1059. * @return {Promise<created>} Returns a boolean indicating whether the row was created or updated.
  1060. */
  1061. Model.prototype.upsert = function (values, options) {
  1062. options = options || {};
  1063. if (!options.fields) {
  1064. options.fields = Object.keys(this.attributes);
  1065. }
  1066. var createdAtAttr = this._timestampAttributes.createdAt
  1067. , updatedAtAttr = this._timestampAttributes.updatedAt
  1068. , hadPrimary = this.primaryKeyField in values
  1069. , instance = this.build(values);
  1070. return instance.hookValidate(options).bind(this).then(function () {
  1071. // Map field names
  1072. values = Utils.mapValueFieldNames(instance.dataValues, options.fields, this);
  1073. if (createdAtAttr && !values[createdAtAttr]) {
  1074. values[createdAtAttr] = this.__getTimestamp(createdAtAttr);
  1075. }
  1076. if (updatedAtAttr && !values[updatedAtAttr]) {
  1077. values[updatedAtAttr] = this.__getTimestamp(updatedAtAttr);
  1078. }
  1079. // Build adds a null value for the primary key, if none was given by the user.
  1080. // We need to remove that because of some Postgres technicalities.
  1081. if (!hadPrimary) {
  1082. delete values[this.primaryKeyField];
  1083. }
  1084. return this.QueryInterface.upsert(this.getTableName(options), values, this, options);
  1085. });
  1086. };
  1087. Model.prototype.insertOrUpdate = Model.prototype.upsert;
  1088. /**
  1089. * Create and insert multiple instances in bulk.
  1090. *
  1091. * The success handler is passed an array of instances, but please notice that these may not completely represent the state of the rows in the DB. This is because MySQL
  1092. * and SQLite do not make it easy to obtain back automatically generated IDs and other default values in a way that can be mapped to multiple records.
  1093. * To obtain Instances for the newly created values, you will need to query for them again.
  1094. *
  1095. * @param {Array} records List of objects (key/value pairs) to create instances from
  1096. * @param {Object} [options]
  1097. * @param {Array} [options.fields] Fields to insert (defaults to all fields)
  1098. * @param {Boolean} [options.validate=false] Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails validation
  1099. * @param {Boolean} [options.hooks=true] Run before / after bulk create hooks?
  1100. * @param {Boolean} [options.individualHooks=false] Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run if options.hooks is true.
  1101. * @param {Boolean} [options.ignoreDuplicates=false] Ignore duplicate values for primary keys? (not supported by postgres)
  1102. * @param {Array} [options.updateOnDuplicate] Fields to update if row key already exists (on duplicate key update)? (only supported by mysql & mariadb). By default, all fields are updated.
  1103. * @param {Transaction} [options.transaction]
  1104. *
  1105. * @return {Promise<Array<Instance>>}
  1106. */
  1107. Model.prototype.bulkCreate = function(records, fieldsOrOptions, options) {
  1108. Utils.validateParameter(fieldsOrOptions, Object, { deprecated: Array, optional: true, index: 2, method: 'Model#bulkCreate' });
  1109. Utils.validateParameter(options, undefined, { deprecated: Object, optional: true, index: 3, method: 'Model#bulkCreate' });
  1110. if (!records.length) {
  1111. return Promise.resolve([]);
  1112. }
  1113. options = Utils._.extend({
  1114. validate: false,
  1115. hooks: true,
  1116. individualHooks: false,
  1117. ignoreDuplicates: false
  1118. }, options || {});
  1119. if (fieldsOrOptions instanceof Array) {
  1120. options.fields = fieldsOrOptions;
  1121. } else {
  1122. options.fields = options.fields || Object.keys(this.tableAttributes);
  1123. options = Utils._.extend(options, fieldsOrOptions);
  1124. }
  1125. var dialect = this.sequelize.options.dialect;
  1126. if (options.ignoreDuplicates && ['postgres', 'mssql'].indexOf(dialect) !== -1) {
  1127. return Promise.reject(new Error(dialect + ' does not support the \'ignoreDuplicates\' option.'));
  1128. }
  1129. if (options.updateOnDuplicate && ['mysql', 'mariadb'].indexOf(dialect) === -1) {
  1130. return Promise.reject(new Error(dialect + ' does not support the \'updateOnDuplicate\' option.'));
  1131. }
  1132. if (options.updateOnDuplicate) {
  1133. // By default, all attributes except 'createdAt' can be updated
  1134. var updatableFields = Utils._.pull(Object.keys(this.tableAttributes), 'createdAt');
  1135. if (Utils._.isArray(options.updateOnDuplicate) && !Utils._.isEmpty(options.updateOnDuplicate)) {
  1136. updatableFields = Utils._.intersection(updatableFields, options.updateOnDuplicate);
  1137. }
  1138. options.updateOnDuplicate = updatableFields;
  1139. }
  1140. var self = this
  1141. , createdAtAttr = this._timestampAttributes.createdAt
  1142. , updatedAtAttr = this._timestampAttributes.updatedAt
  1143. , now = Utils.now(self.modelManager.sequelize.options.dialect);
  1144. // build DAOs
  1145. var instances = records.map(function(values) {
  1146. return self.build(values, {isNewRecord: true});
  1147. });
  1148. return Promise.try(function() {
  1149. // Run before hook
  1150. if (options.hooks) {
  1151. return self.runHooks('beforeBulkCreate', instances, options);
  1152. }
  1153. }).then(function() {
  1154. instances.forEach(function(instance) {
  1155. // Filter dataValues by options.fields
  1156. var values = {};
  1157. options.fields.forEach(function(field) {
  1158. values[field] = instance.dataValues[field];
  1159. });
  1160. // set createdAt/updatedAt attributes
  1161. if (createdAtAttr && !values[createdAtAttr]) {
  1162. values[createdAtAttr] = now;
  1163. }
  1164. if (updatedAtAttr && !values[updatedAtAttr]) {
  1165. values[updatedAtAttr] = now;
  1166. }
  1167. instance.dataValues = values;
  1168. });
  1169. // Validate
  1170. if (options.validate) {
  1171. var errors = [];
  1172. return Promise.map(instances, function(instance) {
  1173. // hookValidate rejects with errors, validate returns with errors
  1174. if (options.individualHooks) {
  1175. return instance.hookValidate(options);
  1176. } else {
  1177. return instance.validate(options).then(function (err) {
  1178. if (err) {
  1179. errors.push({record: instance, errors: err});
  1180. }
  1181. });
  1182. }
  1183. }).then(function() {
  1184. delete options.skip;
  1185. if (errors.length) {
  1186. return Promise.reject(errors);
  1187. }
  1188. });
  1189. }
  1190. }).then(function() {
  1191. if (options.individualHooks) {
  1192. // Create each instance individually
  1193. return Promise.map(instances, function(instance) {
  1194. var individualOptions = Utils._.clone(options);
  1195. delete individualOptions.fields;
  1196. delete individualOptions.individualHooks;
  1197. delete individualOptions.ignoreDuplicates;
  1198. individualOptions.validate = false;
  1199. individualOptions.hooks = true;
  1200. return instance.save(individualOptions);
  1201. }).then(function(_instances) {
  1202. instances = _instances;
  1203. });
  1204. } else {
  1205. // Create all in one query
  1206. // Recreate records from instances to represent any changes made in hooks or validation
  1207. records = instances.map(function(instance) {
  1208. return Utils._.omit(instance.dataValues, self._virtualAttributes);
  1209. });
  1210. var rawAttribute;
  1211. // Map field names
  1212. records.forEach(function(values) {
  1213. for (var attr in values) {
  1214. if (values.hasOwnProperty(attr)) {
  1215. rawAttribute = self.rawAttributes[attr];
  1216. if (rawAttribute.field && rawAttribute.field !== rawAttribute.fieldName) {
  1217. values[self.rawAttributes[attr].field] = values[attr];
  1218. delete values[attr];
  1219. }
  1220. }
  1221. }
  1222. });
  1223. // Map attributes for serial identification
  1224. var attributes = {};
  1225. for (var attr in self.tableAttributes) {
  1226. attributes[attr] = self.rawAttributes[attr];
  1227. if (self.rawAttributes[attr].field) {
  1228. attributes[self.rawAttributes[attr].field] = self.rawAttributes[attr];
  1229. }
  1230. }
  1231. // Insert all records at once
  1232. return self.QueryInterface.bulkInsert(self.getTableName(options), records, options, attributes).then(function (results) {
  1233. if (Array.isArray(results)) {
  1234. results.forEach(function (result, i) {
  1235. instances[i].set(self.primaryKeyAttribute, result[self.rawAttributes[self.primaryKeyAttribute].field], {raw: true});
  1236. });
  1237. }
  1238. return results;
  1239. });
  1240. }
  1241. }).then(function() {
  1242. // Run after hook
  1243. if (options.hooks) {
  1244. return self.runHooks('afterBulkCreate', instances, options);
  1245. }
  1246. }).then(function() {
  1247. return instances;
  1248. });
  1249. };
  1250. /**
  1251. * Delete multiple instances, or set their deletedAt timestamp to the current time if `paranoid` is enabled.
  1252. *
  1253. * @param {Object} options
  1254. * @param {Object} [options.where] Filter the destroy
  1255. * @param {Boolean} [options.hooks=true] Run before / after bulk destroy hooks?
  1256. * @param {Boolean} [options.individualHooks=false] If set to true, destroy will SELECT all records matching the where parameter and will execute before / after destroy hooks on each row
  1257. * @param {Number} [options.limit] How many rows to delete
  1258. * @param {Boolean} [options.force=false] Delete instead of setting deletedAt to current timestamp (only applicable if `paranoid` is enabled)
  1259. * @param {Boolean} [options.truncate=false] If set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is truncated the where and limit options are ignored
  1260. * @param {Boolean} [options.cascade=false] Only used in conjuction with TRUNCATE. Truncates all tables that have foreign-key references to the named table, or to any tables added to the group due to CASCADE.
  1261. * @param {Transaction} [options.transaction]
  1262. * @return {Promise<undefined>}
  1263. */
  1264. Model.prototype.destroy = function(options) {
  1265. var self = this
  1266. , instances;
  1267. if (!options || !(options.where || options.truncate)) {
  1268. throw new Error('Missing where or truncate attribute in the options parameter passed to destroy.');
  1269. }
  1270. options = Utils._.extend({
  1271. hooks: true,
  1272. individualHooks: false,
  1273. force: false,
  1274. cascade: false
  1275. }, options || {});
  1276. options.type = QueryTypes.BULKDELETE;
  1277. Utils.mapOptionFieldNames(options, this);
  1278. return Promise.try(function() {
  1279. // Run before hook
  1280. if (options.hooks) {
  1281. return self.runHooks('beforeBulkDestroy', options);
  1282. }
  1283. }).then(function() {
  1284. // Get daos and run beforeDestroy hook on each record individually
  1285. if (options.individualHooks) {
  1286. return self.findAll({where: options.where}, {transaction: options.transaction}).map(function(instance) {
  1287. return self.runHooks('beforeDestroy', instance, options).then(function() {
  1288. return instance;
  1289. });
  1290. }).then(function(_instances) {
  1291. instances = _instances;
  1292. });
  1293. }
  1294. }).then(function() {
  1295. // Run delete query (or update if paranoid)
  1296. if (self._timestampAttributes.deletedAt && !options.force) {
  1297. var attrValueHash = {}
  1298. , field = self.rawAttributes[self._timestampAttributes.deletedAt].field || self._timestampAttributes.deletedAt;
  1299. attrValueHash[field] = Utils.now(self.modelManager.sequelize.options.dialect);
  1300. return self.QueryInterface.bulkUpdate(self.getTableName(options), attrValueHash, options.where, options, self.rawAttributes);
  1301. } else {
  1302. return self.QueryInterface.bulkDelete(self.getTableName(options), options.where, options, self);
  1303. }
  1304. }).tap(function() {
  1305. // Run afterDestroy hook on each record individually
  1306. if (options.individualHooks) {
  1307. return Promise.map(instances, function(instance) {
  1308. return self.runHooks('afterDestroy', instance, options);
  1309. });
  1310. }
  1311. }).tap(function() {
  1312. // Run after hook
  1313. if (options.hooks) {
  1314. return self.runHooks('afterBulkDestroy', options);
  1315. }
  1316. }).then(function(affectedRows) {
  1317. return affectedRows;
  1318. });
  1319. };
  1320. /**
  1321. * Restore multiple instances if `paranoid` is enabled.
  1322. *
  1323. * @param {Object} options
  1324. * @param {Object} [options.where] Filter the restore
  1325. * @param {Boolean} [options.hooks=true] Run before / after bulk restore hooks?
  1326. * @param {Boolean} [options.individualHooks=false] If set to true, restore will find all records within the where parameter and will execute before / after bulkRestore hooks on each row
  1327. * @param {Number} [options.limit] How many rows to undelete
  1328. * @param {Transaction} [options.transaction]
  1329. *
  1330. * @return {Promise<undefined>}
  1331. */
  1332. Model.prototype.restore = function(options) {
  1333. if (!this._timestampAttributes.deletedAt) throw new Error("Model is not paranoid");
  1334. options = Utils._.extend({
  1335. hooks: true,
  1336. individualHooks: false
  1337. }, options || {});
  1338. options.type = QueryTypes.BULKUNDELETE;
  1339. var self = this
  1340. , instances;
  1341. Utils.mapOptionFieldNames(options, this);
  1342. return Promise.try(function() {
  1343. // Run before hook
  1344. if (options.hooks) {
  1345. return self.runHooks('beforeBulkRestore', options);
  1346. }
  1347. }).then(function() {
  1348. // Get daos and run beforeDestroy hook on each record individually
  1349. if (options.individualHooks) {
  1350. return self.findAll({where: options.where}, {transaction: options.transaction}).map(function(instance) {
  1351. return self.runHooks('beforeRestore', instance, options).then(function() {
  1352. return instance;
  1353. });
  1354. }).then(function(_instances) {
  1355. instances = _instances;
  1356. });
  1357. }
  1358. }).then(function() {
  1359. // Run undelete query
  1360. var attrValueHash = {};
  1361. attrValueHash[self._timestampAttributes.deletedAt] = null;
  1362. options.omitNull = false;
  1363. return self.QueryInterface.bulkUpdate(self.getTableName(options), attrValueHash, options.where, options, self._timestampAttributes.deletedAt);
  1364. }).tap(function() {
  1365. // Run afterDestroy hook on each record individually
  1366. if (options.individualHooks) {
  1367. return Promise.map(instances, function(instance) {
  1368. return self.runHooks('afterRestore', instance, options);
  1369. });
  1370. }
  1371. }).tap(function() {
  1372. // Run after hook
  1373. if (options.hooks) {
  1374. return self.runHooks('afterBulkRestore', options);
  1375. }
  1376. }).then(function(affectedRows) {
  1377. return affectedRows;
  1378. });
  1379. };
  1380. /**
  1381. * Update multiple instances that match the where options. The promise returns an array with one or two elements. The first element is always the number
  1382. * of affected rows, while the second element is the actual affected rows (only supported in postgres with `options.returning` true.)
  1383. *
  1384. * @param {Object} values
  1385. * @param {Object} options
  1386. * @param {Object options.where Options to describe the scope of the search.
  1387. * @param {Boolean} [options.validate=true] Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails validation
  1388. * @param {Boolean} [options.hooks=true] Run before / after bulk update hooks?
  1389. * @param {Boolean} [options.individualHooks=false] Run before / after update hooks?. If true, this will execute a SELECT followed by individual UPDATEs. A select is needed, because the row data needs to be passed to the hooks
  1390. * @param {Boolean} [options.returning=false] Return the affected rows (only for postgres)
  1391. * @param {Number} [options.limit] How many rows to update (only for mysql and mariadb)
  1392. * @param {Transaction} [options.transaction]
  1393. *
  1394. * @return {Promise<Array<affectedCount,affectedRows>>}
  1395. */
  1396. Model.prototype.update = function(values, options) {
  1397. var self = this;
  1398. if (!options || !options.where) {
  1399. throw new Error('Missing where attribute in the options parameter passed to update.');
  1400. }
  1401. options = Utils._.extend({
  1402. validate: true,
  1403. hooks: true,
  1404. individualHooks: false,
  1405. returning: false,
  1406. force: false
  1407. }, options || {});
  1408. options.type = QueryTypes.BULKUPDATE;
  1409. if (this._timestampAttributes.updatedAt) {
  1410. values[this._timestampAttributes.updatedAt] = this.__getTimestamp(this._timestampAttributes.updatedAt);
  1411. }
  1412. var daos
  1413. , valuesUse;
  1414. return Promise.try(function() {
  1415. // Validate
  1416. if (options.validate) {
  1417. var build = self.build(values);
  1418. build.set(self._timestampAttributes.updatedAt, values[self._timestampAttributes.updatedAt], { raw: true });
  1419. // We want to skip validations for all other fields
  1420. options.skip = Utils._.difference(Object.keys(self.attributes), Object.keys(values));
  1421. return build.hookValidate(options).then(function(attributes) {
  1422. delete options.skip;
  1423. if (attributes && attributes.dataValues) {
  1424. values = Utils._.pick(attributes.dataValues, Object.keys(values));
  1425. }
  1426. });
  1427. }
  1428. }).then(function() {
  1429. // Run before hook
  1430. if (options.hooks) {
  1431. options.attributes = values;
  1432. return self.runHooks('beforeBulkUpdate', options).then(function() {
  1433. values = options.attributes;
  1434. delete options.attributes;
  1435. });
  1436. }
  1437. }).then(function() {
  1438. valuesUse = values;
  1439. // Get daos and run beforeUpdate hook on each record individually
  1440. if (options.individualHooks) {
  1441. return self.findAll({where: options.where}, {transaction: options.transaction}).then(function(_daos) {
  1442. daos = _daos;
  1443. if (!daos.length) {
  1444. return [];
  1445. }
  1446. // Run beforeUpdate hooks on each record and check whether beforeUpdate hook changes values uniformly
  1447. // i.e. whether they change values for each record in the same way
  1448. var changedValues
  1449. , different = false;
  1450. return Promise.map(daos, function(dao) {
  1451. // Record updates in dao's dataValues
  1452. Utils._.extend(dao.dataValues, values);
  1453. // Run beforeUpdate hook
  1454. return self.runHooks('beforeUpdate', dao, options).then(function() {
  1455. if (!different) {
  1456. var thisChangedValues = {};
  1457. Utils._.forIn(dao.dataValues, function(newValue, attr) {
  1458. if (newValue !== dao._previousDataValues[attr]) {
  1459. thisChangedValues[attr] = newValue;
  1460. }
  1461. });
  1462. if (!changedValues) {
  1463. changedValues = thisChangedValues;
  1464. } else {
  1465. different = !Utils._.isEqual(changedValues, thisChangedValues);
  1466. }
  1467. }
  1468. return dao;
  1469. });
  1470. }).then(function(_daos) {
  1471. daos = _daos;
  1472. if (!different) {
  1473. // Hooks do not change values or change them uniformly
  1474. if (Object.keys(changedValues).length) {
  1475. // Hooks change values - record changes in valuesUse so they are executed
  1476. valuesUse = changedValues;
  1477. }
  1478. return;
  1479. } else {
  1480. // Hooks change values in a different way for each record
  1481. // Do not run original query but save each record individually
  1482. return Promise.map(daos, function(dao) {
  1483. var individualOptions = Utils._.clone(options);
  1484. delete individualOptions.individualHooks;
  1485. individualOptions.hooks = false;
  1486. individualOptions.validate = false;
  1487. return dao.save(individualOptions);
  1488. }).tap(function(_daos) {
  1489. daos = _daos;
  1490. });
  1491. }
  1492. });
  1493. });
  1494. }
  1495. }).then(function(results) {
  1496. if (results) {
  1497. // Update already done row-by-row - exit
  1498. return [results.length, results];
  1499. }
  1500. Object.keys(valuesUse).forEach(function (attr) {
  1501. if (self.rawAttributes[attr].field && self.rawAttributes[attr].field !== attr) {
  1502. valuesUse[self.rawAttributes[attr].field] = valuesUse[attr];
  1503. delete valuesUse[attr];
  1504. }
  1505. });
  1506. Utils.mapOptionFieldNames(options, self);
  1507. // Run query to update all rows
  1508. return self.QueryInterface.bulkUpdate(self.getTableName(options), valuesUse, options.where, options, self.tableAttributes).then(function(affectedRows) {
  1509. if (options.returning) {
  1510. daos = affectedRows;
  1511. return [affectedRows.length, affectedRows];
  1512. }
  1513. return [affectedRows];
  1514. });
  1515. }).tap(function(result) {
  1516. if (options.individualHooks) {
  1517. return Promise.map(daos, function(dao) {
  1518. return self.runHooks('afterUpdate', dao, options);
  1519. }).then(function() {
  1520. result[1] = daos;
  1521. });
  1522. }
  1523. }).tap(function() {
  1524. // Run after hook
  1525. if (options.hooks) {
  1526. options.attributes = values;
  1527. return self.runHooks('afterBulkUpdate', options).then(function() {
  1528. delete options.attributes;
  1529. });
  1530. }
  1531. }).then(function(result) {
  1532. // Return result in form [affectedRows, daos] (daos missed off if options.individualHooks != true)
  1533. return result;
  1534. });
  1535. };
  1536. /**
  1537. * Run a describe query on the table. The result will be return to the listener as a hash of attributes and their types.
  1538. *
  1539. * @return {Promise}
  1540. */
  1541. Model.prototype.describe = function(schema) {
  1542. return this.QueryInterface.describeTable(this.tableName, schema || this.options.schema || undefined);
  1543. };
  1544. Model.prototype.__getTimestamp = function(attr) {
  1545. if (!!this.rawAttributes[attr] && !!this.rawAttributes[attr].defaultValue) {
  1546. return this.rawAttributes[attr].defaultValue;
  1547. } else {
  1548. return Utils.now(this.sequelize.options.dialect);
  1549. }
  1550. };
  1551. // private
  1552. // validateIncludedElements should have been called before this method
  1553. var paranoidClause = function(model, options) {
  1554. options = options || {};
  1555. // Apply on each include
  1556. // This should be handled before handling where conditions because of logic with returns
  1557. // otherwise this code will never run on includes of a already conditionable where
  1558. if (options.include) {
  1559. options.include.forEach(function(include) {
  1560. paranoidClause(include.model, include);
  1561. });
  1562. }
  1563. if (!model.options.timestamps || !model.options.paranoid || options.paranoid === false) {
  1564. // This model is not paranoid, nothing to do here;
  1565. return options;
  1566. }
  1567. var deletedAtCol = model._timestampAttributes.deletedAt
  1568. , deletedAtObject = {};
  1569. deletedAtObject[model.rawAttributes[deletedAtCol].field || deletedAtCol] = null;
  1570. if (Utils._.isEmpty(options.where)) {
  1571. options.where = deletedAtObject;
  1572. } else {
  1573. options.where = model.sequelize.and(deletedAtObject, options.where);
  1574. }
  1575. return options;
  1576. };
  1577. var addOptionalClassMethods = function() {
  1578. var self = this;
  1579. Utils._.each(this.options.classMethods || {}, function(fct, name) { self[name] = fct; });
  1580. };
  1581. var addDefaultAttributes = function() {
  1582. var self = this
  1583. , tail = {}
  1584. , head = {};
  1585. // Add id if no primary key was manually added to definition
  1586. if (!Object.keys(this.primaryKeys).length) {
  1587. head = {
  1588. id: {
  1589. type: new DataTypes.INTEGER(),
  1590. allowNull: false,
  1591. primaryKey: true,
  1592. autoIncrement: true,
  1593. _autoGenerated: true
  1594. }
  1595. };
  1596. }
  1597. if (this._timestampAttributes.createdAt) {
  1598. tail[this._timestampAttributes.createdAt] = {
  1599. type: DataTypes.DATE,
  1600. allowNull: false,
  1601. _autoGenerated: true
  1602. };
  1603. }
  1604. if (this._timestampAttributes.updatedAt) {
  1605. tail[this._timestampAttributes.updatedAt] = {
  1606. type: DataTypes.DATE,
  1607. allowNull: false,
  1608. _autoGenerated: true
  1609. };
  1610. }
  1611. if (this._timestampAttributes.deletedAt) {
  1612. tail[this._timestampAttributes.deletedAt] = {
  1613. type: DataTypes.DATE,
  1614. _autoGenerated: true
  1615. };
  1616. }
  1617. var existingAttributes = Utils._.clone(self.rawAttributes);
  1618. self.rawAttributes = {};
  1619. Utils._.each(head, function(value, attr) {
  1620. self.rawAttributes[attr] = value;
  1621. });
  1622. Utils._.each(existingAttributes, function(value, attr) {
  1623. self.rawAttributes[attr] = value;
  1624. });
  1625. Utils._.each(tail, function(value, attr) {
  1626. if (Utils._.isUndefined(self.rawAttributes[attr])) {
  1627. self.rawAttributes[attr] = value;
  1628. }
  1629. });
  1630. if (!Object.keys(this.primaryKeys).length) {
  1631. self.primaryKeys.id = self.rawAttributes.id;
  1632. }
  1633. };
  1634. var findAutoIncrementField = function() {
  1635. var fields = this.QueryGenerator.findAutoIncrementField(this);
  1636. this.autoIncrementField = null;
  1637. fields.forEach(function(field) {
  1638. if (this.autoIncrementField) {
  1639. throw new Error('Invalid Instance definition. Only one autoincrement field allowed.');
  1640. } else {
  1641. this.autoIncrementField = field;
  1642. }
  1643. }.bind(this));
  1644. };
  1645. var conformOptions = function(options) {
  1646. if (!options.include) {
  1647. return;
  1648. }
  1649. // if include is not an array, wrap in an array
  1650. if (!Array.isArray(options.include)) {
  1651. options.include = [options.include];
  1652. } else if (!options.include.length) {
  1653. delete options.include;
  1654. return;
  1655. }
  1656. // convert all included elements to { model: Model } form
  1657. options.include = options.include.map(function(include) {
  1658. if (include instanceof Association) {
  1659. include = { association: include };
  1660. } else if (include instanceof Model) {
  1661. include = { model: include };
  1662. } else if (typeof include !== 'object') {
  1663. throw new Error('Include unexpected. Element has to be either a Model, an Association or an object.');
  1664. } else {
  1665. // convert daoFactory to model (for backwards compatibility)
  1666. if (include.hasOwnProperty('daoFactory')) {
  1667. include.model = include.daoFactory;
  1668. delete include.daoFactory;
  1669. }
  1670. conformOptions(include);
  1671. }
  1672. return include;
  1673. });
  1674. };
  1675. var validateIncludedElements = function(options, tableNames) {
  1676. tableNames = tableNames || {};
  1677. options.includeNames = [];
  1678. options.includeMap = {};
  1679. options.hasSingleAssociation = false;
  1680. options.hasMultiAssociation = false;
  1681. if (!options.model) options.model = this;
  1682. // validate all included elements
  1683. var includes = options.include;
  1684. for (var index = 0; index < includes.length; index++) {
  1685. var include = includes[index] = validateIncludedElement.call(this, includes[index], tableNames);
  1686. include.parent = options;
  1687. // associations that are required or have a required child as is not a ?:M association are candidates for the subquery
  1688. include.subQuery = !include.association.isMultiAssociation && (include.hasIncludeRequired || include.required);
  1689. include.hasParentWhere = options.hasParentWhere || !!options.where;
  1690. include.hasParentRequired = options.hasParentRequired || !!options.required;
  1691. options.includeMap[include.as] = include;
  1692. options.includeNames.push(include.as);
  1693. if (include.association.isMultiAssociation || include.hasMultiAssociation) {
  1694. options.hasMultiAssociation = true;
  1695. }
  1696. if (include.association.isSingleAssociation || include.hasSingleAssociation) {
  1697. options.hasSingleAssociation = true;
  1698. }
  1699. options.hasIncludeWhere = options.hasIncludeWhere || include.hasIncludeWhere || !!include.where;
  1700. options.hasIncludeRequired = options.hasIncludeRequired || include.hasIncludeRequired || !!include.required;
  1701. }
  1702. };
  1703. Model.$validateIncludedElements = validateIncludedElements;
  1704. var validateIncludedElement = function(include, tableNames) {
  1705. if (!include.hasOwnProperty('model') && !include.hasOwnProperty('association')) {
  1706. throw new Error('Include malformed. Expected attributes: model or association');
  1707. }
  1708. if (include.association && !include._pseudo && !include.model) {
  1709. if (include.association.source === this) {
  1710. include.model = include.association.target;
  1711. } else {
  1712. include.model = include.association.source;
  1713. }
  1714. }
  1715. tableNames[include.model.getTableName()] = true;
  1716. if (include.attributes) {
  1717. include.originalAttributes = include.attributes.slice(0);
  1718. include.model.primaryKeyAttributes.forEach(function(attr) {
  1719. if (include.attributes.indexOf(attr) === -1) {
  1720. include.attributes.unshift(attr);
  1721. }
  1722. });
  1723. } else {
  1724. include.attributes = Object.keys(include.model.tableAttributes);
  1725. }
  1726. include = Utils.mapOptionFieldNames(include, include.model);
  1727. // pseudo include just needed the attribute logic, return
  1728. if (include._pseudo) {
  1729. return include;
  1730. }
  1731. // check if the current Model is actually associated with the passed Model - or it's a pseudo include
  1732. var association = include.association || this.getAssociation(include.model, include.as);
  1733. if (association) {
  1734. include.association = association;
  1735. include.as = association.as;
  1736. // If through, we create a pseudo child include, to ease our parsing later on
  1737. if (include.association.through && Object(include.association.through.model) === include.association.through.model) {
  1738. if (!include.include) include.include = [];
  1739. var through = include.association.through;
  1740. include.through = Utils._.defaults(include.through || {}, {
  1741. model: through.model,
  1742. as: through.model.name,
  1743. association: {
  1744. isSingleAssociation: true
  1745. },
  1746. _pseudo: true
  1747. });
  1748. if (through.scope) {
  1749. include.through.where = include.through.where ? new Utils.and([include.through.where, through.scope]) : through.scope;
  1750. }
  1751. include.include.push(include.through);
  1752. tableNames[through.tableName] = true;
  1753. }
  1754. if (include.required === undefined) {
  1755. include.required = !!include.where;
  1756. }
  1757. if (include.association.scope) {
  1758. include.where = include.where ? new Utils.and([include.where, include.association.scope]) : include.association.scope;
  1759. }
  1760. // Validate child includes
  1761. if (include.hasOwnProperty('include')) {
  1762. validateIncludedElements.call(include.model, include, tableNames);
  1763. }
  1764. return include;
  1765. } else {
  1766. var msg = include.model.name;
  1767. if (include.as) {
  1768. msg += ' (' + include.as + ')';
  1769. }
  1770. msg += ' is not associated to ' + this.name + '!';
  1771. throw new Error(msg);
  1772. }
  1773. };
  1774. var expandIncludeAll = function(options) {
  1775. var includes = options.include;
  1776. if (!includes) {
  1777. return;
  1778. }
  1779. for (var index = 0; index < includes.length; index++) {
  1780. var include = includes[index];
  1781. if (include.all) {
  1782. includes.splice(index, 1);
  1783. index--;
  1784. expandIncludeAllElement.call(this, includes, include);
  1785. }
  1786. }
  1787. Utils._.forEach(includes, function(include) {
  1788. expandIncludeAll.call(include.model, include);
  1789. });
  1790. };
  1791. var expandIncludeAllElement = function(includes, include) {
  1792. // check 'all' attribute provided is valid
  1793. var all = include.all;
  1794. delete include.all;
  1795. if (all !== true) {
  1796. if (!Array.isArray(all)) {
  1797. all = [all];
  1798. }
  1799. var validTypes = {
  1800. BelongsTo: true,
  1801. HasOne: true,
  1802. HasMany: true,
  1803. One: ['BelongsTo', 'HasOne'],
  1804. Has: ['HasOne', 'HasMany'],
  1805. Many: ['HasMany']
  1806. };
  1807. for (var i = 0; i < all.length; i++) {
  1808. var type = all[i];
  1809. if (type === 'All') {
  1810. all = true;
  1811. break;
  1812. }
  1813. var types = validTypes[type];
  1814. if (!types) {
  1815. throw new Error('include all \'' + type + '\' is not valid - must be BelongsTo, HasOne, HasMany, One, Has, Many or All');
  1816. }
  1817. if (types !== true) {
  1818. // replace type placeholder e.g. 'One' with it's constituent types e.g. 'HasOne', 'BelongsTo'
  1819. all.splice(i, 1);
  1820. i--;
  1821. for (var j = 0; j < types.length; j++) {
  1822. if (all.indexOf(types[j]) === -1) {
  1823. all.unshift(types[j]);
  1824. i++;
  1825. }
  1826. }
  1827. }
  1828. }
  1829. }
  1830. // add all associations of types specified to includes
  1831. var nested = include.nested;
  1832. if (nested) {
  1833. delete include.nested;
  1834. if (!include.include) {
  1835. include.include = [];
  1836. } else if (!Array.isArray(include.include)) {
  1837. include.include = [include.include];
  1838. }
  1839. }
  1840. var used = [];
  1841. (function addAllIncludes(parent, includes) {
  1842. used.push(parent);
  1843. Utils._.forEach(parent.associations, function(association) {
  1844. if (all !== true && all.indexOf(association.associationType) === -1) {
  1845. return;
  1846. }
  1847. // check if model already included, and skip if so
  1848. var model = association.target;
  1849. var as = association.options.as;
  1850. if (Utils._.find(includes, {model: model, as: as})) {
  1851. return;
  1852. }
  1853. // skip if recursing over a model already nested
  1854. if (nested && used.indexOf(model) !== -1) {
  1855. return;
  1856. }
  1857. // include this model
  1858. var thisInclude = optClone(include);
  1859. thisInclude.model = model;
  1860. if (as) {
  1861. thisInclude.as = as;
  1862. }
  1863. includes.push(thisInclude);
  1864. // run recursively if nested
  1865. if (nested) {
  1866. addAllIncludes(model, thisInclude.include);
  1867. if (thisInclude.include.length === 0) delete thisInclude.include;
  1868. }
  1869. });
  1870. used.pop();
  1871. })(this, includes);
  1872. };
  1873. var optClone = Model.prototype.__optClone = function(options) {
  1874. return Utils.cloneDeep(options, function(elem) {
  1875. // The InstanceFactories used for include are pass by ref, so don't clone them.
  1876. if (elem &&
  1877. (
  1878. elem._isSequelizeMethod ||
  1879. elem instanceof Model ||
  1880. elem instanceof Transaction ||
  1881. elem instanceof Association
  1882. )
  1883. ) {
  1884. return elem;
  1885. }
  1886. // Otherwise return undefined, meaning, 'handle this lodash'
  1887. return undefined;
  1888. });
  1889. };
  1890. Utils._.extend(Model.prototype, associationsMixin);
  1891. Hooks.applyTo(Model);
  1892. return Model;
  1893. })();