/lib/model.js

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

Large files are truncated click here to view the full 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 individ…