From 9fc4c815089fe7f2f71274e9a2524d03830f06b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zo=C3=A9?= Date: Tue, 25 Jan 2022 11:43:42 +0100 Subject: [PATCH] fix: rollback PR #13951 in v6 (#14004) --- src/model.js | 2021 ++++++++++++++-------------- test/unit/model/find-by-pk.test.js | 42 - test/unit/model/find-one.test.js | 34 - 3 files changed, 985 insertions(+), 1112 deletions(-) delete mode 100644 test/unit/model/find-by-pk.test.js diff --git a/src/model.js b/src/model.js index 16d10e5d6884..971929411849 100644 --- a/src/model.js +++ b/src/model.js @@ -1,22 +1,24 @@ 'use strict'; -import { isModelStatic } from './utils/model-utils'; - const assert = require('assert'); const _ = require('lodash'); const Dottie = require('dottie'); const Utils = require('./utils'); const { logger } = require('./utils/logger'); -const { BelongsTo, BelongsToMany, Association, HasMany } = require('./associations'); -const { InstanceValidator } = require('./instance-validator'); -const { QueryTypes } = require('./query-types'); +const BelongsTo = require('./associations/belongs-to'); +const BelongsToMany = require('./associations/belongs-to-many'); +const InstanceValidator = require('./instance-validator'); +const QueryTypes = require('./query-types'); const sequelizeErrors = require('./errors'); +const Association = require('./associations/base'); +const HasMany = require('./associations/has-many'); const DataTypes = require('./data-types'); const Hooks = require('./hooks'); -const { Mixin: associationsMixin } = require('./associations/mixin'); -const { Op } = require('./operators'); -const { noDoubleNestedGroup, scopeRenamedToWithScope, schemaRenamedToWithSchema, noModelDropSchema, useModelSet } = require('./utils/deprecations'); +const associationsMixin = require('./associations/mixin'); +const Op = require('./operators'); +const { noDoubleNestedGroup } = require('./utils/deprecations'); + // This list will quickly become dated, but failing to maintain this list just means // we won't throw a warning when we should. At least most common cases will forever be covered @@ -32,8 +34,8 @@ const nonCascadingOptions = ['include', 'attributes', 'originalAttributes', 'ord /** * A Model represents a table in the database. Instances of this class represent a database row. * - * Model instances operate with the concept of a `dataValues` property, which stores the actual values represented by the - * instance. By default, the values from dataValues can also be accessed directly from the Instance, that is: + * Model instances operate with the concept of a `dataValues` property, which stores the actual values represented by the instance. + * By default, the values from dataValues can also be accessed directly from the Instance, that is: * ```js * instance.field * // is the same as @@ -41,14 +43,14 @@ const nonCascadingOptions = ['include', 'attributes', 'originalAttributes', 'ord * // is the same as * instance.getDataValue('field') * ``` - * However, if getters and/or setters are defined for `field` they will be invoked, instead of returning the value from - * `dataValues`. Accessing properties directly or using `get` is preferred for regular use, `getDataValue` should only be - * used for custom getters. + * However, if getters and/or setters are defined for `field` they will be invoked, instead of returning the value from `dataValues`. + * Accessing properties directly or using `get` is preferred for regular use, `getDataValue` should only be used for custom getters. * - * @see {Sequelize#define} for more information about getters and setters + * @see + * {@link Sequelize#define} for more information about getters and setters * @mixes Hooks */ -export class Model { +class Model { static get queryInterface() { return this.sequelize.getQueryInterface(); } @@ -60,6 +62,9 @@ export class Model { /** * A reference to the sequelize instance * + * @see + * {@link Sequelize} + * * @property sequelize * * @returns {Sequelize} @@ -75,8 +80,7 @@ export class Model { * @param {object} [options] instance construction options * @param {boolean} [options.raw=false] If set to true, values will ignore field and virtual setters. * @param {boolean} [options.isNewRecord=true] Is this a new record - * @param {Array} [options.include] an array of include options - Used to build prefetched/included model instances. See - * `set` + * @param {Array} [options.include] an array of include options - Used to build prefetched/included model instances. See `set` */ constructor(values = {}, options = {}) { if (!this.constructor._overwrittenAttributesChecked) { @@ -95,9 +99,9 @@ export class Model { } if (overwrittenAttributes.length > 0) { - logger.warn(`Model ${JSON.stringify(this.constructor.name)} is declaring public class fields for attribute(s): ${overwrittenAttributes.map(attr => JSON.stringify(attr)).join(', ')}.` - + '\nThese class fields are shadowing Sequelize\'s attribute getters & setters.' - + '\nSee https://sequelize.org/docs/v7/core-concepts/model-basics/#caveat-with-public-class-fields'); + logger.warn(`Model ${JSON.stringify(this.constructor.name)} is declaring public class fields for attribute(s): ${overwrittenAttributes.map(attr => JSON.stringify(attr)).join(', ')}.` + + '\nThese class fields are shadowing Sequelize\'s attribute getters & setters.' + + '\nSee https://sequelize.org/main/manual/model-basics.html#caveat-with-public-class-fields'); } }, 0); } @@ -106,11 +110,11 @@ export class Model { isNewRecord: true, _schema: this.constructor._schema, _schemaDelimiter: this.constructor._schemaDelimiter, - ...options, + ...options }; if (options.attributes) { - options.attributes = options.attributes.map(attribute => (Array.isArray(attribute) ? attribute[1] : attribute)); + options.attributes = options.attributes.map(attribute => Array.isArray(attribute) ? attribute[1] : attribute); } if (!options.includeValidated) { @@ -150,7 +154,6 @@ export class Model { if (this.constructor._hasDefaultValues) { defaults = _.mapValues(this.constructor._defaultValues, valueFn => { const value = valueFn(); - return value && value instanceof Utils.SequelizeMethod ? value : _.cloneDeep(value); }); } @@ -158,12 +161,12 @@ export class Model { // set id to null if not passed as value, a newly created dao has no id // removing this breaks bulkCreate // do after default values since it might have UUID as a default value - if (this.constructor.primaryKeyAttributes.length > 0) { - for (const primaryKeyAttribute of this.constructor.primaryKeyAttributes) { + if (this.constructor.primaryKeyAttributes.length) { + this.constructor.primaryKeyAttributes.forEach(primaryKeyAttribute => { if (!Object.prototype.hasOwnProperty.call(defaults, primaryKeyAttribute)) { defaults[primaryKeyAttribute] = null; } - } + }); } if (this.constructor._timestampAttributes.createdAt && defaults[this.constructor._timestampAttributes.createdAt]) { @@ -223,7 +226,7 @@ export class Model { let deletedAtDefaultValue = Object.prototype.hasOwnProperty.call(deletedAtAttribute, 'defaultValue') ? deletedAtAttribute.defaultValue : null; deletedAtDefaultValue = deletedAtDefaultValue || { - [Op.eq]: null, + [Op.eq]: null }; deletedAtObject[deletedAtAttribute.field || deletedAtCol] = deletedAtDefaultValue; @@ -242,9 +245,11 @@ export class Model { let head = {}; // Add id if no primary key was manually added to definition - if (!this.options.noPrimaryKey && !_.some(this.rawAttributes, 'primaryKey')) { - if ('id' in this.rawAttributes && this.rawAttributes.id.primaryKey === undefined) { - throw new Error(`An attribute called 'id' was defined in model '${this.tableName}' but primaryKey is not set. This is likely to be an error, which can be fixed by setting its 'primaryKey' option to true. If this is intended, explicitly set its 'primaryKey' option to false`); + // Can't use this.primaryKeys here, since this function is called before PKs are identified + if (!_.some(this.rawAttributes, 'primaryKey')) { + if ('id' in this.rawAttributes) { + // Something is fishy here! + throw new Error(`A column called 'id' was added to the attributes of '${this.tableName}' but not marked with 'primaryKey: true'`); } head = { @@ -253,8 +258,8 @@ export class Model { allowNull: false, primaryKey: true, autoIncrement: true, - _autoGenerated: true, - }, + _autoGenerated: true + } }; } @@ -262,7 +267,7 @@ export class Model { tail[this._timestampAttributes.createdAt] = { type: DataTypes.DATE, allowNull: false, - _autoGenerated: true, + _autoGenerated: true }; } @@ -270,14 +275,14 @@ export class Model { tail[this._timestampAttributes.updatedAt] = { type: DataTypes.DATE, allowNull: false, - _autoGenerated: true, + _autoGenerated: true }; } if (this._timestampAttributes.deletedAt) { tail[this._timestampAttributes.deletedAt] = { type: DataTypes.DATE, - _autoGenerated: true, + _autoGenerated: true }; } @@ -286,13 +291,13 @@ export class Model { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0, - _autoGenerated: true, + _autoGenerated: true }; } const newRawAttributes = { ...head, - ...this.rawAttributes, + ...this.rawAttributes }; _.each(tail, (value, attr) => { if (newRawAttributes[attr] === undefined) { @@ -301,6 +306,10 @@ export class Model { }); this.rawAttributes = newRawAttributes; + + if (!Object.keys(this.primaryKeys).length) { + this.primaryKeys.id = this.rawAttributes.id; + } } /** @@ -322,7 +331,6 @@ export class Model { if (this.autoIncrementAttribute) { throw new Error('Invalid Instance definition. Only one autoincrement field allowed.'); } - this.autoIncrementAttribute = name; } } @@ -330,16 +338,13 @@ export class Model { } static _conformIncludes(options, self) { - if (!options.include) { - return; - } + if (!options.include) return; // if include is not an array, wrap in an array if (!Array.isArray(options.include)) { options.include = [options.include]; - } else if (options.include.length === 0) { + } else if (!options.include.length) { delete options.include; - return; } @@ -352,10 +357,8 @@ export class Model { if (!Object.prototype.hasOwnProperty.call(self.associations, include)) { throw new Error(`Association with alias "${include}" does not exist on ${self.name}`); } - return self.associations[include]; } - return include; } @@ -363,9 +366,7 @@ export class Model { if (include) { let model; - if (include._pseudo) { - return include; - } + if (include._pseudo) return include; include = this._transformStringAssociation(include, self); @@ -379,7 +380,7 @@ export class Model { return { model, association: include, as: include.as }; } - if (isModelStatic(include)) { + if (include.prototype && include.prototype instanceof Model) { return { model: include }; } @@ -393,28 +394,20 @@ export class Model { model = include.association.target; } - if (!include.model) { - include.model = model; - } - - if (!include.as) { - include.as = include.association.as; - } + if (!include.model) include.model = model; + if (!include.as) include.as = include.association.as; this._conformIncludes(include, model); - return include; } if (include.model) { this._conformIncludes(include, include.model); - return include; } if (include.all) { this._conformIncludes(include); - return include; } } @@ -439,7 +432,7 @@ export class Model { HasMany: true, One: ['BelongsTo', 'HasOne'], Has: ['HasOne', 'HasMany'], - Many: ['HasMany'], + Many: ['HasMany'] }; for (let i = 0; i < all.length; i++) { @@ -458,9 +451,9 @@ export class Model { // replace type placeholder e.g. 'One' with its constituent types e.g. 'HasOne', 'BelongsTo' all.splice(i, 1); i--; - for (const type_ of types) { - if (!all.includes(type_)) { - all.unshift(type_); + for (let j = 0; j < types.length; j++) { + if (!all.includes(types[j])) { + all.unshift(types[j]); i++; } } @@ -505,7 +498,6 @@ export class Model { if (nested && used.includes(model)) { return; } - used.push(parent); // include this model @@ -514,25 +506,20 @@ export class Model { if (as) { thisInclude.as = as; } - includes.push(thisInclude); // run recursively if nested if (nested) { addAllIncludes(model, thisInclude.include); - if (thisInclude.include.length === 0) { - delete thisInclude.include; - } + if (thisInclude.include.length === 0) delete thisInclude.include; } }); used.pop(); - }(this, includes)); + })(this, includes); } static _validateIncludedElements(options, tableNames) { - if (!options.model) { - options.model = this; - } + if (!options.model) options.model = this; tableNames = tableNames || {}; options.includeNames = []; @@ -564,14 +551,13 @@ export class Model { options.hasDuplicating = options.hasDuplicating || include.hasDuplicating; options.hasRequired = options.hasRequired || include.required; - options.hasWhere = options.hasWhere || include.hasWhere || Boolean(include.where); - + options.hasWhere = options.hasWhere || include.hasWhere || !!include.where; return include; }); for (const include of options.include) { - include.hasParentWhere = options.hasParentWhere || Boolean(options.where); - include.hasParentRequired = options.hasParentRequired || Boolean(options.required); + include.hasParentWhere = options.hasParentWhere || !!options.where; + include.hasParentRequired = options.hasParentRequired || !!options.required; if (include.subQuery !== false && options.hasDuplicating && options.topLimit) { if (include.duplicating) { @@ -604,13 +590,12 @@ export class Model { } /* Legacy */ - options.hasIncludeWhere = options.hasIncludeWhere || include.hasIncludeWhere || Boolean(include.where); - options.hasIncludeRequired = options.hasIncludeRequired || include.hasIncludeRequired || Boolean(include.required); + options.hasIncludeWhere = options.hasIncludeWhere || include.hasIncludeWhere || !!include.where; + options.hasIncludeRequired = options.hasIncludeRequired || include.hasIncludeRequired || !!include.required; if (include.association.isMultiAssociation || include.hasMultiAssociation) { options.hasMultiAssociation = true; } - if (include.association.isSingleAssociation || include.hasSingleAssociation) { options.hasSingleAssociation = true; } @@ -619,7 +604,6 @@ export class Model { if (options.topModel === options.model && options.subQuery === undefined) { options.subQuery = false; } - return options; } @@ -633,14 +617,13 @@ export class Model { include = Utils.mapFinderOptions(include, include.model); - if (include.attributes.length > 0) { + if (include.attributes.length) { _.each(include.model.primaryKeys, (attr, key) => { // Include the primary key if it's not already included - take into account that the pk might be aliased (due to a .field prop) if (!include.attributes.some(includeAttr => { if (attr.field !== key) { return Array.isArray(includeAttr) && includeAttr[0] === attr.field && includeAttr[1] === key; } - return includeAttr === key; })) { include.attributes.unshift(key); @@ -656,7 +639,6 @@ export class Model { if (!include.attributes) { include.attributes = Object.keys(include.model.tableAttributes); } - return Utils.mapFinderOptions(include, include.model); } @@ -668,22 +650,20 @@ export class Model { // If through, we create a pseudo child include, to ease our parsing later on if (include.association.through && Object(include.association.through.model) === include.association.through.model) { - if (!include.include) { - include.include = []; - } - + if (!include.include) include.include = []; const through = include.association.through; include.through = _.defaults(include.through || {}, { model: through.model, as: through.model.name, association: { - isSingleAssociation: true, + isSingleAssociation: true }, _pseudo: true, - parent: include, + parent: include }); + if (through.scope) { include.through.where = include.through.where ? { [Op.and]: [include.through.where, through.scope] } : through.scope; } @@ -712,7 +692,7 @@ export class Model { include = Utils.mapFinderOptions(include, include.model); if (include.required === undefined) { - include.required = Boolean(include.where); + include.required = !!include.where; } if (include.association.scope) { @@ -725,14 +705,14 @@ export class Model { if (include.separate === true) { if (!(include.association instanceof HasMany)) { - throw new TypeError('Only HasMany associations support include.separate'); + throw new Error('Only HasMany associations support include.separate'); } include.duplicating = false; if ( options.attributes - && options.attributes.length > 0 + && options.attributes.length && !_.flattenDepth(options.attributes, 2).includes(association.sourceKey) ) { options.attributes.push(association.sourceKey); @@ -740,7 +720,7 @@ export class Model { if ( include.attributes - && include.attributes.length > 0 + && include.attributes.length && !_.flattenDepth(include.attributes, 2).includes(association.foreignKey) ) { include.attributes.push(association.foreignKey); @@ -761,32 +741,28 @@ export class Model { if (associations.length === 0) { throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is not associated to ${this.name}!`); } - if (associations.length === 1) { association = this.getAssociationForAlias(targetModel, targetAlias); if (association) { return association; } - if (targetAlias) { const existingAliases = this.getAssociations(targetModel).map(association => association.as); - throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is associated to ${this.name} using an alias. ` - + `You've included an alias (${targetAlias}), but it does not match the alias(es) defined in your association (${existingAliases.join(', ')}).`); + throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is associated to ${this.name} using an alias. ` + + `You've included an alias (${targetAlias}), but it does not match the alias(es) defined in your association (${existingAliases.join(', ')}).`); } - - throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is associated to ${this.name} using an alias. ` - + 'You must use the \'as\' keyword to specify the alias within your include statement.'); + throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is associated to ${this.name} using an alias. ` + + 'You must use the \'as\' keyword to specify the alias within your include statement.'); } - association = this.getAssociationForAlias(targetModel, targetAlias); if (!association) { - throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is associated to ${this.name} multiple times. ` - + 'To identify the correct association, you must use the \'as\' keyword to specify the alias of the association you want to include.'); + throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is associated to ${this.name} multiple times. ` + + 'To identify the correct association, you must use the \'as\' keyword to specify the alias of the association you want to include.'); } - return association; } + static _expandIncludeAll(options) { const includes = options.include; if (!includes) { @@ -804,9 +780,9 @@ export class Model { } } - for (const include of includes) { + includes.forEach(include => { this._expandIncludeAll.call(include.model, include); - } + }); } static _conformIndex(index) { @@ -816,7 +792,7 @@ export class Model { index = _.defaults(index, { type: '', - parser: null, + parser: null }); if (index.type && index.type.toLowerCase() === 'unique') { @@ -827,10 +803,9 @@ export class Model { return index; } + static _uniqIncludes(options) { - if (!options.include) { - return; - } + if (!options.include) return; options.include = _(options.include) .groupBy(include => `${include.model && include.model.name}-${include.as}`) @@ -842,7 +817,6 @@ export class Model { _.assignWith(...args); this._conformIncludes(args[0], this); this._uniqIncludes(args[0]); - return args[0]; } @@ -850,9 +824,13 @@ export class Model { if (Array.isArray(objValue) && Array.isArray(srcValue)) { return _.union(objValue, srcValue); } - if (['where', 'having'].includes(key)) { - return combineWheresWithAnd(objValue, srcValue); + if (srcValue instanceof Utils.SequelizeMethod) { + srcValue = { [Op.and]: srcValue }; + } + if (_.isPlainObject(objValue) && _.isPlainObject(srcValue)) { + return Object.assign(objValue, srcValue); + } } else if (key === 'attributes' && _.isPlainObject(objValue) && _.isPlainObject(srcValue)) { return _.assignWith(objValue, srcValue, (objValue, srcValue) => { if (Array.isArray(objValue) && Array.isArray(srcValue)) { @@ -860,14 +838,12 @@ export class Model { } }); } - // If we have a possible object/array to clone, we try it. // Otherwise, we return the original value when it's not undefined, // or the resulting object in that case. if (srcValue) { return Utils.cloneDeep(srcValue, true); } - return srcValue === undefined ? objValue : srcValue; } @@ -888,7 +864,6 @@ export class Model { * Each attribute of the hash represents a column. * * @example - * ```javascript * Project.init({ * columnA: { * type: Sequelize.BOOLEAN, @@ -906,16 +881,71 @@ export class Model { * columnB: Sequelize.STRING, * columnC: 'MY VERY OWN COLUMN TYPE' * }, {sequelize}) - * ``` * * sequelize.models.modelName // The model will now be available in models under the class name * - * @see https://sequelize.org/docs/v7/core-concepts/model-basics/ - * @see https://sequelize.org/docs/v7/core-concepts/validations-and-constraints/ + * @see + * Model Basics guide + * + * @see + * Hooks guide + * + * @see + * Validations & Constraints guide + * + * @param {object} attributes An object, where each attribute is a column of the table. Each column can be either a DataType, a string or a type-description object, with the properties described below: + * @param {string|DataTypes|object} attributes.column The description of a database column + * @param {string|DataTypes} attributes.column.type A string or a data type + * @param {boolean} [attributes.column.allowNull=true] If false, the column will have a NOT NULL constraint, and a not null validation will be run before an instance is saved. + * @param {any} [attributes.column.defaultValue=null] A literal default value, a JavaScript function, or an SQL function (see `sequelize.fn`) + * @param {string|boolean} [attributes.column.unique=false] If true, the column will get a unique constraint. If a string is provided, the column will be part of a composite unique index. If multiple columns have the same string, they will be part of the same unique index + * @param {boolean} [attributes.column.primaryKey=false] If true, this attribute will be marked as primary key + * @param {string} [attributes.column.field=null] If set, sequelize will map the attribute name to a different name in the database + * @param {boolean} [attributes.column.autoIncrement=false] If true, this column will be set to auto increment + * @param {boolean} [attributes.column.autoIncrementIdentity=false] If true, combined with autoIncrement=true, will use Postgres `GENERATED BY DEFAULT AS IDENTITY` instead of `SERIAL`. Postgres 10+ only. + * @param {string} [attributes.column.comment=null] Comment for this column + * @param {string|Model} [attributes.column.references=null] An object with reference configurations + * @param {string|Model} [attributes.column.references.model] If this column references another table, provide it here as a Model, or a string + * @param {string} [attributes.column.references.key='id'] The column of the foreign table that this column references + * @param {string} [attributes.column.onUpdate] What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION + * @param {string} [attributes.column.onDelete] What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION + * @param {Function} [attributes.column.get] Provide a custom getter for this column. Use `this.getDataValue(String)` to manipulate the underlying values. + * @param {Function} [attributes.column.set] Provide a custom setter for this column. Use `this.setDataValue(String, Value)` to manipulate the underlying values. + * @param {object} [attributes.column.validate] An object of validations to execute for this column every time the model is saved. Can be either the name of a validation provided by validator.js, a validation function provided by extending validator.js (see the `DAOValidator` property for more details), or a custom validation function. Custom validation functions are called with the value of the field and the instance itself as the `this` binding, and can possibly take a second callback argument, to signal that they are asynchronous. If the validator is sync, it should throw in the case of a failed validation; if it is async, the callback should be called with the error text. + * @param {object} options These options are merged with the default define options provided to the Sequelize constructor + * @param {object} options.sequelize Define the sequelize instance to attach to the new Model. Throw error if none is provided. + * @param {string} [options.modelName] Set name of the model. By default its same as Class name. + * @param {object} [options.defaultScope={}] Define the default search scope to use for this model. Scopes have the same form as the options passed to find / findAll + * @param {object} [options.scopes] More scopes, defined in the same way as defaultScope above. See `Model.scope` for more information about how scopes are defined, and what you can do with them + * @param {boolean} [options.omitNull] Don't persist null values. This means that all columns with null values will not be saved + * @param {boolean} [options.timestamps=true] Adds createdAt and updatedAt timestamps to the model. + * @param {boolean} [options.paranoid=false] Calling `destroy` will not delete the model, but instead set a `deletedAt` timestamp if this is true. Needs `timestamps=true` to work + * @param {boolean} [options.underscored=false] Add underscored field to all attributes, this covers user defined attributes, timestamps and foreign keys. Will not affect attributes with explicitly set `field` option + * @param {boolean} [options.freezeTableName=false] If freezeTableName is true, sequelize will not try to alter the model name to get the table name. Otherwise, the model name will be pluralized + * @param {object} [options.name] An object with two attributes, `singular` and `plural`, which are used when this model is associated to others. + * @param {string} [options.name.singular=Utils.singularize(modelName)] Singular name for model + * @param {string} [options.name.plural=Utils.pluralize(modelName)] Plural name for model + * @param {Array} [options.indexes] indexes definitions + * @param {string} [options.indexes[].name] The name of the index. Defaults to model name + _ + fields concatenated + * @param {string} [options.indexes[].type] Index type. Only used by mysql. One of `UNIQUE`, `FULLTEXT` and `SPATIAL` + * @param {string} [options.indexes[].using] The method to create the index by (`USING` statement in SQL). BTREE and HASH are supported by mysql and postgres, and postgres additionally supports GIST and GIN. + * @param {string} [options.indexes[].operator] Specify index operator. + * @param {boolean} [options.indexes[].unique=false] Should the index by unique? Can also be triggered by setting type to `UNIQUE` + * @param {boolean} [options.indexes[].concurrently=false] PostgresSQL will build the index without taking any write locks. Postgres only + * @param {Array} [options.indexes[].fields] An array of the fields to index. Each field can either be a string containing the name of the field, a sequelize object (e.g `sequelize.fn`), or an object with the following attributes: `attribute` (field name), `length` (create a prefix index of length chars), `order` (the direction the column should be sorted in), `collate` (the collation (sort order) for the column) + * @param {string|boolean} [options.createdAt] Override the name of the createdAt attribute if a string is provided, or disable it if false. Timestamps must be true. Underscored field will be set with underscored setting. + * @param {string|boolean} [options.updatedAt] Override the name of the updatedAt attribute if a string is provided, or disable it if false. Timestamps must be true. Underscored field will be set with underscored setting. + * @param {string|boolean} [options.deletedAt] Override the name of the deletedAt attribute if a string is provided, or disable it if false. Timestamps must be true. Underscored field will be set with underscored setting. + * @param {string} [options.tableName] Defaults to pluralized model name, unless freezeTableName is true, in which case it uses model name verbatim + * @param {string} [options.schema='public'] schema + * @param {string} [options.engine] Specify engine for model's table + * @param {string} [options.charset] Specify charset for model's table + * @param {string} [options.comment] Specify comment for model's table + * @param {string} [options.collate] Specify collation for model's table + * @param {string} [options.initialAutoIncrement] Set the initial AUTO_INCREMENT value for the table in MySQL. + * @param {object} [options.hooks] An object of hook function that are called before and after certain lifecycle events. The possible hooks are: beforeValidate, afterValidate, validationFailed, beforeBulkCreate, beforeBulkDestroy, beforeBulkUpdate, beforeCreate, beforeDestroy, beforeUpdate, afterCreate, beforeSave, afterDestroy, afterUpdate, afterBulkCreate, afterSave, afterBulkDestroy and afterBulkUpdate. See Hooks for more information about hook functions and their signatures. Each property can either be a function, or an array of functions. + * @param {object} [options.validate] An object of model wide validations. Validations have access to all model values via `this`. If the validator function takes an argument, it is assumed to be async, and is called with a callback that accepts an optional error. * - * @param {object} attributes An object, where each attribute is a column of the table. Each column can be either a - * DataType, a string or a type-description object. - * @param {object} options These options are merged with the default define options provided to the Sequelize constructor * @returns {Model} */ static init(attributes, options = {}) { @@ -936,11 +966,11 @@ export class Model { options = Utils.merge({ name: { plural: Utils.pluralize(options.modelName), - singular: Utils.singularize(options.modelName), + singular: Utils.singularize(options.modelName) }, indexes: [], omitNull: globalOptions.omitNull, - schema: globalOptions.schema, + schema: globalOptions.schema }, options); this.sequelize.runHooks('beforeDefine', attributes, options); @@ -948,11 +978,9 @@ export class Model { if (options.modelName !== this.name) { Object.defineProperty(this, 'name', { value: options.modelName }); } - delete options.modelName; this.options = { - noPrimaryKey: false, timestamps: true, validate: {}, freezeTableName: false, @@ -960,12 +988,12 @@ export class Model { paranoid: false, rejectOnEmpty: false, whereCollection: null, - schema: '', + schema: null, schemaDelimiter: '', defaultScope: {}, scopes: {}, indexes: [], - ...options, + ...options }; // if you call "define" multiple times for the same modelName, do not clutter the factory @@ -973,10 +1001,9 @@ export class Model { this.sequelize.modelManager.removeModel(this.sequelize.modelManager.getModel(this.name)); } - this.associations = Object.create(null); + this.associations = {}; this._setupHooks(options.hooks); - // TODO: use private field this.underscored = this.options.underscored; if (!this.options.tableName) { @@ -985,8 +1012,8 @@ export class Model { this.tableName = this.options.tableName; } - this._schema = this.options.schema || ''; - this._schemaDelimiter = this.options.schemaDelimiter || ''; + this._schema = this.options.schema; + this._schemaDelimiter = this.options.schemaDelimiter; // error check options _.each(options.validate, (validator, validatorType) => { @@ -995,36 +1022,13 @@ export class Model { } if (typeof validator !== 'function') { - throw new TypeError(`Members of the validate option must be functions. Model: ${this.name}, error with validate member ${validatorType}`); + throw new Error(`Members of the validate option must be functions. Model: ${this.name}, error with validate member ${validatorType}`); } }); this.rawAttributes = _.mapValues(attributes, (attribute, name) => { attribute = this.sequelize.normalizeAttribute(attribute); - // Checks whether the name is ambiguous with Utils.isColString - // we check whether the attribute starts *or* ends because the following query: - // { '$json.key$' } - // could be interpreted as both - // "json"."key" (accessible attribute 'key' on model 'json') - // or - // "$json" #>> {key$} (accessing key 'key$' on attribute '$json') - if (name.startsWith('$') || name.endsWith('$')) { - throw new Error(`Name of attribute "${name}" in model "${this.name}" cannot start or end with "$" as "$attribute$" is reserved syntax used to reference nested columns in queries.`); - } - - if (name.includes('.')) { - throw new Error(`Name of attribute "${name}" in model "${this.name}" cannot include the character "." as it would be ambiguous with the syntax used to reference nested columns, and nested json keys, in queries.`); - } - - if (name.includes('::')) { - throw new Error(`Name of attribute "${name}" in model "${this.name}" cannot include the character sequence "::" as it is reserved syntax used to cast attributes in queries.`); - } - - if (name.includes('->')) { - throw new Error(`Name of attribute "${name}" in model "${this.name}" cannot include the character sequence "->" as it is reserved syntax used in SQL generated by Sequelize to target nested associations.`); - } - if (attribute.type === undefined) { throw new Error(`Unrecognized datatype for attribute "${this.name}.${name}"`); } @@ -1054,27 +1058,24 @@ export class Model { if (!['undefined', 'string', 'boolean'].includes(typeof this.options[key])) { throw new Error(`Value for "${key}" option must be a string or a boolean, got ${typeof this.options[key]}`); } - if (this.options[key] === '') { throw new Error(`Value for "${key}" option cannot be an empty string`); } } if (this.options.createdAt !== false) { - this._timestampAttributes.createdAt - = typeof this.options.createdAt === 'string' ? this.options.createdAt : 'createdAt'; + this._timestampAttributes.createdAt = + typeof this.options.createdAt === 'string' ? this.options.createdAt : 'createdAt'; this._readOnlyAttributes.add(this._timestampAttributes.createdAt); } - if (this.options.updatedAt !== false) { - this._timestampAttributes.updatedAt - = typeof this.options.updatedAt === 'string' ? this.options.updatedAt : 'updatedAt'; + this._timestampAttributes.updatedAt = + typeof this.options.updatedAt === 'string' ? this.options.updatedAt : 'updatedAt'; this._readOnlyAttributes.add(this._timestampAttributes.updatedAt); } - if (this.options.paranoid && this.options.deletedAt !== false) { - this._timestampAttributes.deletedAt - = typeof this.options.deletedAt === 'string' ? this.options.deletedAt : 'deletedAt'; + this._timestampAttributes.deletedAt = + typeof this.options.deletedAt === 'string' ? this.options.deletedAt : 'deletedAt'; this._readOnlyAttributes.add(this._timestampAttributes.deletedAt); } } @@ -1107,7 +1108,7 @@ export class Model { this.prototype._customGetters = {}; this.prototype._customSetters = {}; - for (const type of ['get', 'set']) { + ['get', 'set'].forEach(type => { const opt = `${type}terMethods`; const funcs = { ...this.options[opt] }; const _custom = type === 'get' ? this.prototype._customGetters : this.prototype._customSetters; @@ -1116,13 +1117,12 @@ export class Model { _custom[attribute] = method; if (type === 'get') { - funcs[attribute] = function () { + funcs[attribute] = function() { return this.get(attribute); }; } - if (type === 'set') { - funcs[attribute] = function (value) { + funcs[attribute] = function(value) { return this.set(attribute, value); }; } @@ -1134,13 +1134,12 @@ export class Model { } if (type === 'get') { - funcs[attribute] = function () { + funcs[attribute] = function() { return this.get(attribute); }; } - if (type === 'set') { - funcs[attribute] = function (value) { + funcs[attribute] = function(value) { return this.set(attribute, value); }; } @@ -1149,13 +1148,12 @@ export class Model { _.each(funcs, (fct, name) => { if (!attributeManipulation[name]) { attributeManipulation[name] = { - configurable: true, + configurable: true }; } - attributeManipulation[name][type] = fct; }); - } + }); this._dataTypeChanges = {}; this._dataTypeSanitizers = {}; @@ -1167,10 +1165,10 @@ export class Model { this._defaultValues = {}; this.prototype.validators = {}; - this.fieldRawAttributesMap = Object.create(null); + this.fieldRawAttributesMap = {}; - this.primaryKeys = Object.create(null); - this.uniqueKeys = Object.create(null); + this.primaryKeys = {}; + this.uniqueKeys = {}; _.each(this.rawAttributes, (definition, name) => { definition.type = this.sequelize.normalizeDataType(definition.type); @@ -1214,8 +1212,8 @@ export class Model { if (Object.prototype.hasOwnProperty.call(definition, 'unique') && definition.unique) { let idxName; if ( - typeof definition.unique === 'object' - && Object.prototype.hasOwnProperty.call(definition.unique, 'name') + typeof definition.unique === 'object' && + Object.prototype.hasOwnProperty.call(definition.unique, 'name') ) { idxName = definition.unique.name; } else if (typeof definition.unique === 'string') { @@ -1244,10 +1242,10 @@ export class Model { Utils.nameIndex( this._conformIndex({ fields: [definition.field || name], - using: 'gin', + using: 'gin' }), - this.getTableName(), - ), + this.getTableName() + ) ); delete definition.index; @@ -1259,13 +1257,12 @@ export class Model { if (key !== value.fieldName) { map[key] = value.fieldName; } - return map; }, {}); - this._hasJsonAttributes = this._jsonAttributes.size > 0; + this._hasJsonAttributes = !!this._jsonAttributes.size; - this._hasVirtualAttributes = this._virtualAttributes.size > 0; + this._hasVirtualAttributes = !!this._virtualAttributes.size; this._hasDefaultValues = !_.isEmpty(this._defaultValues); @@ -1279,7 +1276,6 @@ export class Model { this.sequelize.log(`Not overriding built-in method from model attribute: ${key}`); continue; } - Object.defineProperty(this.prototype, key, attributeManipulation[key]); } @@ -1311,15 +1307,17 @@ export class Model { /** * Sync this Model to the DB, that is create the table. - * See {@link Sequelize#sync} for options * * @param {object} [options] sync options * + * @see + * {@link Sequelize#sync} for options + * * @returns {Promise} */ static async sync(options) { options = { ...this.options, ...options }; - options.hooks = options.hooks === undefined ? true : Boolean(options.hooks); + options.hooks = options.hooks === undefined ? true : !!options.hooks; const attributes = this.tableAttributes; const rawAttributes = this.fieldRawAttributesMap; @@ -1327,7 +1325,6 @@ export class Model { if (options.hooks) { await this.runHooks('beforeSync', options); } - if (options.force) { await this.drop(options); } @@ -1339,7 +1336,7 @@ export class Model { if (options.alter) { const tableInfos = await Promise.all([ this.queryInterface.describeTable(tableName, options), - this.queryInterface.getForeignKeyReferencesForTable(tableName, options), + this.queryInterface.getForeignKeyReferencesForTable(tableName, options) ]); const columns = tableInfos[0]; // Use for alter foreign keys @@ -1347,10 +1344,7 @@ export class Model { const removedConstraints = {}; for (const columnName in attributes) { - if (!Object.prototype.hasOwnProperty.call(attributes, columnName)) { - continue; - } - + if (!Object.prototype.hasOwnProperty.call(attributes, columnName)) continue; if (!columns[columnName] && !columns[attributes[columnName].field]) { await this.queryInterface.addColumn(tableName, attributes[columnName].field || columnName, attributes[columnName], options); } @@ -1358,20 +1352,13 @@ export class Model { if (options.alter === true || typeof options.alter === 'object' && options.alter.drop !== false) { for (const columnName in columns) { - if (!Object.prototype.hasOwnProperty.call(columns, columnName)) { - continue; - } - + if (!Object.prototype.hasOwnProperty.call(columns, columnName)) continue; const currentAttribute = rawAttributes[columnName]; if (!currentAttribute) { await this.queryInterface.removeColumn(tableName, columnName, options); continue; } - - if (currentAttribute.primaryKey) { - continue; - } - + if (currentAttribute.primaryKey) continue; // Check foreign keys. If it's a foreign key, it should remove constraint first. const references = currentAttribute.references; if (currentAttribute.references) { @@ -1380,37 +1367,31 @@ export class Model { // Find existed foreign keys for (const foreignKeyReference of foreignKeyReferences) { const constraintName = foreignKeyReference.constraintName; - if ((Boolean(constraintName) + if (!!constraintName && foreignKeyReference.tableCatalog === database && (schema ? foreignKeyReference.tableSchema === schema : true) && foreignKeyReference.referencedTableName === references.model && foreignKeyReference.referencedColumnName === references.key && (schema ? foreignKeyReference.referencedTableSchema === schema : true) - && !removedConstraints[constraintName]) - || this.sequelize.options.dialect === 'ibmi') { + && !removedConstraints[constraintName]) { // Remove constraint on foreign keys. await this.queryInterface.removeConstraint(tableName, constraintName, options); removedConstraints[constraintName] = true; } } } - await this.queryInterface.changeColumn(tableName, columnName, currentAttribute, options); } } } - let indexes = await this.queryInterface.showIndex(tableName, options); - indexes = this._indexes.filter(item1 => !indexes.some(item2 => item1.name === item2.name)).sort((index1, index2) => { + indexes = this._indexes.filter(item1 => + !indexes.some(item2 => item1.name === item2.name) + ).sort((index1, index2) => { if (this.sequelize.options.dialect === 'postgres') { // move concurrent indexes to the bottom to avoid weird deadlocks - if (index1.concurrently === true) { - return 1; - } - - if (index2.concurrently === true) { - return -1; - } + if (index1.concurrently === true) return 1; + if (index2.concurrently === true) return -1; } return 0; @@ -1430,73 +1411,63 @@ export class Model { /** * Drop the table represented by this Model * - * @param {object} [options] drop options + * @param {object} [options] drop options + * @param {boolean} [options.cascade=false] Also drop all objects depending on this table, such as views. Only works in postgres + * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql. + * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging). + * * @returns {Promise} */ static async drop(options) { return await this.queryInterface.dropTable(this.getTableName(options), options); } - /** - * @param {object | string} schema - * @deprecated use {@link Sequelize#dropSchema} or {@link QueryInterface#dropSchema} - */ - // TODO [>=2023-01-01]: remove me in Sequelize >= 8 static async dropSchema(schema) { - noModelDropSchema(); - return await this.queryInterface.dropSchema(schema); } /** - * Returns a copy of this model with the corresponding table located in the specified schema. + * Apply a schema to this model. For postgres, this will actually place the schema in front of the table name - `"schema"."tableName"`, + * while the schema will be prepended to the table name for mysql and sqlite - `'schema.tablename'`. * - * For postgres, this will actually place the schema in front of the table name (`"schema"."tableName"`), - * while the schema will be prepended to the table name for mysql and sqlite (`'schema.tablename'`). + * This method is intended for use cases where the same model is needed in multiple schemas. In such a use case it is important + * to call `model.schema(schema, [options]).sync()` for each model to ensure the models are created in the correct schema. * - * This method is intended for use cases where the same model is needed in multiple schemas. - * In such a use case it is important to call {@link Model.sync} (or use migrations!) for each model created by this method - * to ensure the models are created in the correct schema. + * If a single default schema per model is needed, set the `options.schema='schema'` parameter during the `define()` call + * for the model. * - * If a single default schema per model is needed, set the {@link ModelOptions.schema} option instead. + * @param {string} schema The name of the schema + * @param {object} [options] schema options + * @param {string} [options.schemaDelimiter='.'] The character(s) that separates the schema name from the table name + * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql. + * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging). * - * @param {string|object} schema The name of the schema + * @see + * {@link Sequelize#define} for more information about setting a default schema. * * @returns {Model} */ - static withSchema(schema) { - if (arguments.length > 1) { - throw new TypeError('Unlike Model.schema, Model.withSchema only accepts 1 argument which may be either a string or an option bag.'); - } + static schema(schema, options) { - const schemaOptions = typeof schema === 'string' ? { schema } : schema; + const clone = class extends this {}; + Object.defineProperty(clone, 'name', { value: this.name }); - return this.getInitialModel() - ._withScopeAndSchema(schemaOptions, this._scope, this._scopeNames); - } + clone._schema = schema; - // TODO [>=2023-01-01]: remove in Sequelize 8 - static schema(schema, options) { - schemaRenamedToWithSchema(); - - return this.withSchema({ - schema, - schemaDelimiter: typeof options === 'string' ? options : options?.schemaDelimiter, - }); - } + if (options) { + if (typeof options === 'string') { + clone._schemaDelimiter = options; + } else if (options.schemaDelimiter) { + clone._schemaDelimiter = options.schemaDelimiter; + } + } - /** - * Returns the initial model, the one returned by {@link Model.init} or {@link Sequelize#define}, - * before any scope or schema was applied. - */ - static getInitialModel() { - // '_initialModel' is set on model variants (withScope, withSchema, etc) - return this._initialModel ?? this; + return clone; } /** - * Get the table name of the model, taking schema into account. The method will return The name as a string if the model - * has no schema, or an object with `tableName`, `schema` and `delimiter` properties. + * Get the table name of the model, taking schema into account. The method will return The name as a string if the model has no schema, + * or an object with `tableName`, `schema` and `delimiter` properties. * * @returns {string|object} */ @@ -1505,25 +1476,25 @@ export class Model { } /** - * Add a new scope to the model - * - * This is especially useful for adding scopes with includes, when the model you want to - * include is not available at the time this model is defined. + * Get un-scoped model * - * By default, this will throw an error if a scope with that name already exists. - * Use {@link AddScopeOptions.override} in the options object to silence this error. + * @returns {Model} + */ + static unscoped() { + return this.scope(); + } + + /** + * Add a new scope to the model. This is especially useful for adding scopes with includes, when the model you want to include is not available at the time this model is defined. * - * See {@link https://sequelize.org/docs/v7/other-topics/scopes/} to learn more about scopes. + * By default this will throw an error if a scope with that name already exists. Pass `override: true` in the options object to silence this error. * * @param {string} name The name of the scope. Use `defaultScope` to override the default scope * @param {object|Function} scope scope or options * @param {object} [options] scope options + * @param {boolean} [options.override=false] override old scope if already defined */ static addScope(name, scope, options) { - if (this !== this.getInitialModel()) { - throw new Error(`Model.addScope can only be called on the initial model. Use "${this.name}.getInitialModel()" to access the initial model.`); - } - options = { override: false, ...options }; if ((name === 'defaultScope' && Object.keys(this.options.defaultScope).length > 0 || name in this.options.scopes) && options.override === false) { @@ -1537,204 +1508,224 @@ export class Model { } } - // TODO [>=2023-01-01]: remove in Sequelize 8 - static scope(...options) { - scopeRenamedToWithScope(); - - return this.withScope(...options); - } - /** - * Creates a copy of this model, with one or more scopes applied. + * Apply a scope created in `define` to the model. + * + * @example how to create scopes + * const Model = sequelize.define('model', attributes, { + * defaultScope: { + * where: { + * username: 'dan' + * }, + * limit: 12 + * }, + * scopes: { + * isALie: { + * where: { + * stuff: 'cake' + * } + * }, + * complexFunction: function(email, accessLevel) { + * return { + * where: { + * email: { + * [Op.like]: email + * }, + * access_level { + * [Op.gte]: accessLevel + * } + * } + * } + * } + * } + * }) * - * See {@link https://sequelize.org/docs/v7/other-topics/scopes/} to learn more about scopes. + * # As you have defined a default scope, every time you do Model.find, the default scope is appended to your query. Here's a couple of examples: * - * @param {?Array|object|string} [scopes] The scope(s) to apply. Scopes can either be passed as consecutive arguments, or - * as an array of arguments. To apply simple scopes and scope functions with no arguments, 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. + * Model.findAll() // WHERE username = 'dan' + * Model.findAll({ where: { age: { [Op.gt]: 12 } } }) // WHERE age > 12 AND username = 'dan' * - * @returns {Model} A reference to the model, with the scope(s) applied. Calling scope again on the returned model will - * clear the previous scope. + * @example To invoke scope functions you can do + * Model.scope({ method: ['complexFunction', 'dan@sequelize.com', 42]}).findAll() + * // WHERE email like 'dan@sequelize.com%' AND access_level >= 42 + * + * @param {?Array|object|string} [option] The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of arguments. To apply simple scopes and scope functions with no arguments, 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. + * + * @returns {Model} A reference to the model, with the scope(s) applied. Calling scope again on the returned model will clear the previous scope. */ - static withScope(...scopes) { - scopes = scopes.flat().filter(Boolean); + static scope(option) { + const self = class extends this {}; + let scope; + let scopeName; - const initialModel = this.getInitialModel(); + Object.defineProperty(self, 'name', { value: this.name }); - const mergedScope = {}; - const scopeNames = []; + self._scope = {}; + self._scopeNames = []; + self.scoped = true; + + if (!option) { + return self; + } - for (const option of scopes) { - let scope = null; - let scopeName = null; + const options = _.flatten(arguments); + + for (const option of options) { + scope = null; + scopeName = null; if (_.isPlainObject(option)) { if (option.method) { - if (Array.isArray(option.method) && Boolean(initialModel.options.scopes[option.method[0]])) { + if (Array.isArray(option.method) && !!self.options.scopes[option.method[0]]) { scopeName = option.method[0]; - scope = initialModel.options.scopes[scopeName].apply(initialModel, option.method.slice(1)); - } else if (initialModel.options.scopes[option.method]) { + scope = self.options.scopes[scopeName].apply(self, option.method.slice(1)); + } + else if (self.options.scopes[option.method]) { scopeName = option.method; - scope = initialModel.options.scopes[scopeName].apply(initialModel); + scope = self.options.scopes[scopeName].apply(self); } } else { scope = option; } - } else if (option === 'defaultScope' && _.isPlainObject(initialModel.options.defaultScope)) { - scope = initialModel.options.defaultScope; + } else if (option === 'defaultScope' && _.isPlainObject(self.options.defaultScope)) { + scope = self.options.defaultScope; } else { scopeName = option; - scope = initialModel.options.scopes[scopeName]; + scope = self.options.scopes[scopeName]; if (typeof scope === 'function') { scope = scope(); } } - if (!scope) { - throw new sequelizeErrors.SequelizeScopeError(`"${this.name}.withScope()" has been called with an invalid scope: "${scopeName}" does not exist.`); - } - - this._conformIncludes(scope, this); - // clone scope so it doesn't get modified - this._assignOptions(mergedScope, Utils.cloneDeep(scope)); - scopeNames.push(scopeName ? scopeName : 'defaultScope'); - } - - return initialModel._withScopeAndSchema({ - schema: this._schema || '', - schemaDelimiter: this._schemaDelimiter || '', - }, mergedScope, scopeNames); - } - - // TODO [>=2023-01-01]: remove in Sequelize 8 - /** - * Returns a model without scope. The default scope is also omitted. - * - * See {@link https://sequelize.org/docs/v7/other-topics/scopes/} to learn more about scopes. - */ - static unscoped() { - scopeRenamedToWithScope(); - - return this.withoutScope(); - } - - /** - * Returns a model without scope. The default scope is also omitted. - * - * See {@link https://sequelize.org/docs/v7/other-topics/scopes/} to learn more about scopes. - */ - static withoutScope() { - return this.withScope(null); - } - - /** - * Returns the base model, with its initial scope. - */ - static withInitialScope() { - const initialModel = this.getInitialModel(); - - if (this._schema !== initialModel._schema || this._schemaDelimiter !== initialModel._schemaDelimiter) { - return initialModel.withSchema({ - schema: this._schema, - schemaDelimiter: this._schemaDelimiter, - }); - } - - return initialModel; - } - - static _withScopeAndSchema(schemaOptions, mergedScope, scopeNames) { - if (!this._modelVariantRefs) { - // technically this weakref is unnecessary because we're referencing ourselves but it simplifies the code - // eslint-disable-next-line no-undef -- eslint doesn't know about WeakRef, this will be resolved once we migrate to TS. - this._modelVariantRefs = new Set([new WeakRef(this)]); - } - - for (const modelVariantRef of this._modelVariantRefs) { - const modelVariant = modelVariantRef.deref(); - - if (!modelVariant) { - this._modelVariantRefs.delete(modelVariantRef); - continue; - } - - if (modelVariant._schema !== (schemaOptions.schema || '')) { - continue; - } - - if (modelVariant._schemaDelimiter !== (schemaOptions.schemaDelimiter || '')) { - continue; - } - - // the item order of these arrays is important! scope('a', 'b') is not equal to scope('b', 'a') - if (!_.isEqual(modelVariant._scopeNames, scopeNames)) { - continue; - } - - if (!_.isEqual(modelVariant._scope, mergedScope)) { - continue; + if (scope) { + this._conformIncludes(scope, this); + // clone scope so it doesn't get modified + this._assignOptions(self._scope, Utils.cloneDeep(scope)); + self._scopeNames.push(scopeName ? scopeName : 'defaultScope'); + } else { + throw new sequelizeErrors.SequelizeScopeError(`Invalid scope ${scopeName} called.`); } - - return modelVariant; } - const clone = this._createModelVariant(); - // eslint-disable-next-line no-undef -- eslint doesn't know about WeakRef, this will be resolved once we migrate to TS. - this._modelVariantRefs.add(new WeakRef(clone)); - - clone._schema = schemaOptions.schema || ''; - clone._schemaDelimiter = schemaOptions.schemaDelimiter || ''; - clone._scope = mergedScope; - clone._scopeNames = scopeNames; - - if (scopeNames.length !== 1 || scopeNames[0] !== 'defaultScope') { - clone.scoped = true; - } - - return clone; - } - - static _createModelVariant() { - const model = class extends this {}; - model._initialModel = this; - Object.defineProperty(model, 'name', { value: this.name }); - - return model; + return self; } /** * Search for multiple instances. - * See {@link https://sequelize.org/docs/v7/core-concepts/model-querying-basics/} for more information about querying. * - * __Example of a simple search:__ - * ```js + * @example Simple search using AND and = * Model.findAll({ * where: { * attr1: 42, * attr2: 'cake' * } * }) - * ``` * - * See also: - * - {@link Model.findOne} - * - {@link Sequelize#query} + * # WHERE attr1 = 42 AND attr2 = 'cake' + * + * @example Using greater than, less than etc. + * const {gt, lte, ne, in: opIn} = Sequelize.Op; * - * @param {object} options - * @returns {Promise} A promise that will resolve with the array containing the results of the SELECT query. + * Model.findAll({ + * where: { + * attr1: { + * [gt]: 50 + * }, + * attr2: { + * [lte]: 45 + * }, + * attr3: { + * [opIn]: [1,2,3] + * }, + * attr4: { + * [ne]: 5 + * } + * } + * }) + * + * # WHERE attr1 > 50 AND attr2 <= 45 AND attr3 IN (1,2,3) AND attr4 != 5 + * + * @example Queries using OR + * const {or, and, gt, lt} = Sequelize.Op; + * + * Model.findAll({ + * where: { + * name: 'a project', + * [or]: [ + * {id: [1, 2, 3]}, + * { + * [and]: [ + * {id: {[gt]: 10}}, + * {id: {[lt]: 100}} + * ] + * } + * ] + * } + * }); + * + * # WHERE `Model`.`name` = 'a project' AND (`Model`.`id` IN (1, 2, 3) OR (`Model`.`id` > 10 AND `Model`.`id` < 100)); + * + * @see + * {@link Operators} for possible operators + * __Alias__: _all_ + * + * The promise is resolved with an array of Model instances if the query succeeds._ + * + * @param {object} [options] A hash of options to describe the scope of the search + * @param {object} [options.where] A hash of attributes to describe your search. See above for examples. + * @param {Array|object} [options.attributes] A list of the attributes that you want to select, or an object with `include` and `exclude` keys. To rename an attribute, you can pass an array, with two elements - the first is the name of the attribute in the DB (or some kind of expression such as `Sequelize.literal`, `Sequelize.fn` and so on), and the second is the name you want the attribute to have in the returned instance + * @param {Array} [options.attributes.include] Select all the attributes of the model, plus some additional ones. Useful for aggregations, e.g. `{ attributes: { include: [[sequelize.fn('COUNT', sequelize.col('id')), 'total']] }` + * @param {Array} [options.attributes.exclude] Select all the attributes of the model, except some few. Useful for security purposes e.g. `{ attributes: { exclude: ['password'] } }` + * @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. + * @param {Array} [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' }]}` or `{ include: ['Alias']}`. If your association are set up with an `as` (eg. `X.hasMany(Y, { as: 'Z }`, you need to specify Z in the as attribute when eager loading Y). + * @param {Model} [options.include[].model] The model you want to eagerly load + * @param {string} [options.include[].as] The alias of the relation, in case the model you want to eagerly load is aliased. For `hasOne` / `belongsTo`, this should be the singular name, and for `hasMany`, it should be the plural + * @param {Association} [options.include[].association] The association you want to eagerly load. (This can be used instead of providing a model/as pair) + * @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` + * @param {boolean} [options.include[].or=false] Whether to bind the ON and WHERE clause together by OR instead of AND. + * @param {object} [options.include[].on] Supply your own ON condition for the join. + * @param {Array} [options.include[].attributes] A list of attributes to select from the child model + * @param {boolean} [options.include[].required] If true, converts to an inner join, which means that the parent model will only be loaded if it has any matching children. True if `include.where` is set, false otherwise. + * @param {boolean} [options.include[].right] If true, converts to a right join if dialect support it. Ignored if `include.required` is true. + * @param {boolean} [options.include[].separate] If true, runs a separate query to fetch the associated instances, only supported for hasMany associations + * @param {number} [options.include[].limit] Limit the joined rows, only supported with include.separate=true + * @param {string} [options.include[].through.as] The alias for the join model, in case you want to give it a different name than the default one. + * @param {boolean} [options.include[].through.paranoid] If true, only non-deleted records will be returned from the join table. If false, both deleted and non-deleted records will be returned. Only applies if through model is paranoid. + * @param {object} [options.include[].through.where] Filter on the join model for belongsToMany relations + * @param {Array} [options.include[].through.attributes] A list of attributes to select from the join model for belongsToMany relations + * @param {Array} [options.include[].include] Load further nested related models + * @param {boolean} [options.include[].duplicating] Mark the include as duplicating, will prevent a subquery from being used. + * @param {Array|Sequelize.fn|Sequelize.col|Sequelize.literal} [options.order] Specifies an ordering. Using an array, you can provide several columns / functions to order by. Each element can be further wrapped in a two-element array. The first element is the column / function to order by, the second is the direction. For example: `order: [['name', 'DESC']]`. In this way the column will be escaped, but the direction will not. + * @param {number} [options.limit] Limit for result + * @param {number} [options.offset] Offset for result + * @param {Transaction} [options.transaction] Transaction to run query under + * @param {string|object} [options.lock] Lock the selected rows. Possible options are transaction.LOCK.UPDATE and transaction.LOCK.SHARE. Postgres also supports transaction.LOCK.KEY_SHARE, transaction.LOCK.NO_KEY_UPDATE and specific model locks with joins. + * @param {boolean} [options.skipLocked] Skip locked rows. Only supported in Postgres. + * @param {boolean} [options.raw] Return raw result. See sequelize.query for more information. + * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql. + * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging). + * @param {object} [options.having] Having options + * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only) + * @param {boolean|Error} [options.rejectOnEmpty=false] Throws an error when no records found + * @param {boolean} [options.dotNotation] Allows including tables having the same attribute/column names - which have a dot in them. + * + * @see + * {@link Sequelize#query} + * + * @returns {Promise>} */ static async findAll(options) { if (options !== undefined && !_.isPlainObject(options)) { throw new sequelizeErrors.QueryError('The argument passed to findAll must be an options object, use findByPk if you wish to pass a single primary key value'); } - if (options !== undefined && options.attributes && !Array.isArray(options.attributes) && !_.isPlainObject(options.attributes)) { - throw new sequelizeErrors.QueryError('The attributes option must be an array of column names or an object'); + if (options !== undefined && options.attributes) { + if (!Array.isArray(options.attributes) && !_.isPlainObject(options.attributes)) { + throw new sequelizeErrors.QueryError('The attributes option must be an array of column names or an object'); + } } - this._warnOnInvalidOptions(options, Object.keys(this.rawAttributes)); + this.warnOnInvalidOptions(options, Object.keys(this.rawAttributes)); const tableNames = {}; @@ -1753,7 +1744,6 @@ export class Model { if (options.hooks) { await this.runHooks('beforeFind', options); } - this._conformIncludes(options, this); this._expandAttributes(options); this._expandIncludeAll(options); @@ -1761,7 +1751,6 @@ export class Model { if (options.hooks) { await this.runHooks('beforeFindAfterExpandIncludeAll', options); } - options.originalAttributes = this._injectDependentVirtualAttributes(options.attributes); if (options.include) { @@ -1796,30 +1785,27 @@ export class Model { if (options.hooks) { await this.runHooks('beforeFindAfterOptions', options); } - const selectOptions = { ...options, tableNames: Object.keys(tableNames) }; const results = await this.queryInterface.select(this, this.getTableName(selectOptions), selectOptions); if (options.hooks) { await this.runHooks('afterFind', results, options); } - // rejectOnEmpty mode + //rejectOnEmpty mode if (_.isEmpty(results) && options.rejectOnEmpty) { if (typeof options.rejectOnEmpty === 'function') { throw new options.rejectOnEmpty(); } - if (typeof options.rejectOnEmpty === 'object') { throw options.rejectOnEmpty; } - throw new sequelizeErrors.EmptyResultError(); } return await Model._findSeparate(results, options); } - static _warnOnInvalidOptions(options, validColumnNames) { + static warnOnInvalidOptions(options, validColumnNames) { if (!_.isPlainObject(options)) { return; } @@ -1832,13 +1818,8 @@ export class Model { } static _injectDependentVirtualAttributes(attributes) { - if (!this._hasVirtualAttributes) { - return attributes; - } - - if (!attributes || !Array.isArray(attributes)) { - return attributes; - } + if (!this._hasVirtualAttributes) return attributes; + if (!attributes || !Array.isArray(attributes)) return attributes; for (const attribute of attributes) { if ( @@ -1855,18 +1836,12 @@ export class Model { } static async _findSeparate(results, options) { - if (!options.include || options.raw || !results) { - return results; - } + if (!options.include || options.raw || !results) return results; const original = results; - if (options.plain) { - results = [results]; - } + if (options.plain) results = [results]; - if (!Array.isArray(results) || results.length === 0) { - return original; - } + if (!results.length) return original; await Promise.all(options.include.map(async include => { if (!include.separate) { @@ -1875,40 +1850,35 @@ export class Model { let associations = result.get(include.association.as); // Might be an empty belongsTo relation - if (!associations) { - return memo; - } + if (!associations) return memo; // Force array so we can concat no matter if it's 1:1 or :M - if (!Array.isArray(associations)) { - associations = [associations]; - } + if (!Array.isArray(associations)) associations = [associations]; for (let i = 0, len = associations.length; i !== len; ++i) { memo.push(associations[i]); } - return memo; }, []), { ..._.omit(options, 'include', 'attributes', 'order', 'where', 'limit', 'offset', 'plain', 'scope'), - include: include.include || [], - }, + include: include.include || [] + } ); } const map = await include.association.get(results, { ..._.omit(options, nonCascadingOptions), - ..._.omit(include, ['parent', 'association', 'as', 'originalAttributes']), + ..._.omit(include, ['parent', 'association', 'as', 'originalAttributes']) }); for (const result of results) { result.set( include.association.as, map[result.get(include.association.sourceKey)], - { raw: true }, + { raw: true } ); } })); @@ -1917,16 +1887,17 @@ export class Model { } /** - * Search for a single instance by its primary key. + * Search for a single instance by its primary key._ * - * This applies LIMIT 1, only a single instance will be returned. + * @param {number|string|Buffer} param The value of the desired instance's primary key. + * @param {object} [options] find options + * @param {Transaction} [options.transaction] Transaction to run query under + * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only) * - * Returns the model with the matching primary key. - * If not found, returns null or throws an error if {@link FindOptions.rejectOnEmpty} is set. + * @see + * {@link Model.findAll} for a full explanation of options, Note that options.where is not supported. * - * @param {number|bigint|string|Buffer} param The value of the desired instance's primary key. - * @param {object} [options] find options - * @returns {Promise} + * @returns {Promise} */ static async findByPk(param, options) { // return Promise resolved with null if no arguments are passed @@ -1936,63 +1907,71 @@ export class Model { options = Utils.cloneDeep(options) || {}; - if (typeof param === 'number' || typeof param === 'bigint' || typeof param === 'string' || Buffer.isBuffer(param)) { + if (typeof param === 'number' || typeof param === 'string' || Buffer.isBuffer(param)) { options.where = { - [this.primaryKeyAttribute]: param, + [this.primaryKeyAttribute]: param }; } else { - throw new TypeError(`Argument passed to findByPk is invalid: ${param}`); + throw new Error(`Argument passed to findByPk is invalid: ${param}`); } // Bypass a possible overloaded findOne - return await Model.findOne.call(this, options); + // note: in v6, we don't bypass overload https://github.com/sequelize/sequelize/issues/14003 + return await this.findOne(options); } /** - * Search for a single instance. - * - * Returns the first instance corresponding matching the query. - * If not found, returns null or throws an error if {@link FindOptions.rejectOnEmpty} is set. + * Search for a single instance. Returns the first instance found, or null if none can be found. * * @param {object} [options] A hash of options to describe the scope of the search + * @param {Transaction} [options.transaction] Transaction to run query under + * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only) + * + * @see + * {@link Model.findAll} for an explanation of options + * * @returns {Promise} */ static async findOne(options) { if (options !== undefined && !_.isPlainObject(options)) { throw new Error('The argument passed to findOne must be an options object, use findByPk if you wish to pass a single primary key value'); } - options = Utils.cloneDeep(options); if (options.limit === undefined) { - const uniqueSingleColumns = _.chain(this.uniqueKeys).values().filter(c => c.fields.length === 1) - .map('column') - .value(); + const uniqueSingleColumns = _.chain(this.uniqueKeys).values().filter(c => c.fields.length === 1).map('column').value(); // Don't add limit if querying directly on the pk or a unique column - if (!options.where || !_.some(options.where, (value, key) => (key === this.primaryKeyAttribute || uniqueSingleColumns.includes(key)) - && (Utils.isPrimitive(value) || Buffer.isBuffer(value)))) { + if (!options.where || !_.some(options.where, (value, key) => + (key === this.primaryKeyAttribute || uniqueSingleColumns.includes(key)) && + (Utils.isPrimitive(value) || Buffer.isBuffer(value)) + )) { options.limit = 1; } } // Bypass a possible overloaded findAll. - return await Model.findAll.call(this, (_.defaults(options, { - plain: true, - }))); + // note: in v6, we don't bypass overload https://github.com/sequelize/sequelize/issues/14003 + return await this.findAll(_.defaults(options, { + plain: true + })); } /** - * Run an aggregation method on the specified field. - * - * Returns the aggregate result cast to {@link AggregateOptions.dataType}, - * unless `options.plain` is false, in which case the complete data result is returned. + * Run an aggregation method on the specified field * * @param {string} attribute The attribute to aggregate over. Can be a field name or * * @param {string} aggregateFunction The function to use for aggregation, e.g. sum, max etc. * @param {object} [options] Query options. See sequelize.query for full options - * - * @returns {Promise} + * @param {object} [options.where] A hash of search attributes. + * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql. + * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging). + * @param {DataTypes|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. + * @param {boolean} [options.distinct] Applies DISTINCT to the field being aggregated over + * @param {Transaction} [options.transaction] Transaction to run query under + * @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` + * + * @returns {Promise} Returns the aggregate result cast to `options.dataType`, unless `options.plain` is false, in which case the complete data result is returned. */ static async aggregate(attribute, aggregateFunction, options) { options = Utils.cloneDeep(options); @@ -2019,14 +1998,13 @@ export class Model { let { group } = options; if (Array.isArray(group) && Array.isArray(group[0])) { noDoubleNestedGroup(); - group = group.flat(); + group = _.flatten(group); } - options.attributes = _.unionBy( options.attributes, group, [[this.sequelize.fn(aggregateFunction, aggregateColumn), aggregateFunction]], - a => (Array.isArray(a) ? a[1] : a), + a => Array.isArray(a) ? a[1] : a ); if (!options.dataType) { @@ -2044,7 +2022,6 @@ export class Model { options = this._paranoidClause(this, options); const value = await this.queryInterface.rawSelect(this.getTableName(options), options, aggregateFunction, this); - return value; } @@ -2054,6 +2031,18 @@ export class Model { * If you provide an `include` option, the number of matching associations will be counted instead. * * @param {object} [options] options + * @param {object} [options.where] A hash of search attributes. + * @param {object} [options.include] Include options. See `find` for details + * @param {boolean} [options.paranoid=true] Set `true` to count only non-deleted records. Can be used on models with `paranoid` enabled + * @param {boolean} [options.distinct] Apply COUNT(DISTINCT(col)) on primary key or on options.col. + * @param {string} [options.col] Column on which COUNT() should be applied + * @param {Array} [options.attributes] Used in conjunction with `group` + * @param {Array} [options.group] For creating complex counts. Will return multiple rows as needed. + * @param {Transaction} [options.transaction] Transaction to run query under + * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql. + * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging). + * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only) + * * @returns {Promise} */ static async count(options) { @@ -2063,16 +2052,13 @@ export class Model { if (options.hooks) { await this.runHooks('beforeCount', options); } - let col = options.col || '*'; if (options.include) { col = `${this.name}.${options.col || this.primaryKeyField}`; } - if (options.distinct && col === '*') { col = this.primaryKeyField; } - options.plain = !options.group; options.dataType = new DataTypes.INTEGER(); options.includeIgnoreAttributes = false; @@ -2090,7 +2076,7 @@ export class Model { if (Array.isArray(result)) { return result.map(item => ({ ...item, - count: Number(item.count), + count: Number(item.count) })); } @@ -2098,46 +2084,37 @@ export class Model { } /** - * Finds all the rows matching your query, within a specified offset / limit, and get the total number of - * rows matching your query. This is very useful for pagination. + * 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 useful for paging * - * ```js - * Model.findAndCountAll({ + * @example + * const result = await Model.findAndCountAll({ * where: ..., * limit: 12, * offset: 12 - * }).then(result => { - * ... - * }) - * ``` - * In the above example, `result.rows` will contain rows 13 through 24, while `result.count` will return - * the total number of rows that matched your query. + * }); * - * When you add includes, only those which are required (either because they have a where clause, or - * because required` is explicitly set to true on the include) will be added to the count part. + * # 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. + * + * # When you add includes, only those which are required (either because they have a where clause, or because `required` is explicitly set to true on the include) will be added to the count part. + * + * # Suppose you want to find all users who have a profile attached: * - * Suppose you want to find all users who have a profile attached: - * ```js * User.findAndCountAll({ * include: [ * { model: Profile, required: true} * ], * limit: 3 * }); - * ``` - * Because the include for `Profile` has `required` set it will result in an inner join, and only the users - * who have a profile will be counted. If we remove `required` from the include, both users with and - * without profiles will be counted * - * This function also support grouping, when `group` is provided, the count will be an array of objects - * containing the count for each group and the projected attributes. - * ```js - * User.findAndCountAll({ - * group: 'type' - * }); - * ``` + * # Because the include for `Profile` has `required` set it will result in an inner join, and only the users who have a profile will be counted. If we remove `required` from the include, both users with and without profiles will be counted * * @param {object} [options] See findAll options + * + * @see + * {@link Model.findAll} for a specification of find and query options + * @see + * {@link Model.count} for a specification of count options + * * @returns {Promise<{count: number | number[], rows: Model[]}>} */ static async findAndCountAll(options) { @@ -2153,20 +2130,24 @@ export class Model { const [count, rows] = await Promise.all([ this.count(countOptions), - this.findAll(options), + this.findAll(options) ]); return { count, - rows: count === 0 ? [] : rows, + rows: count === 0 ? [] : rows }; } /** - * Finds the maximum value of field + * Find the maximum value of field * * @param {string} field attribute / field name * @param {object} [options] See aggregate + * + * @see + * {@link Model.aggregate} for options + * * @returns {Promise<*>} */ static async max(field, options) { @@ -2174,10 +2155,14 @@ export class Model { } /** - * Finds the minimum value of field + * Find the minimum value of field * * @param {string} field attribute / field name * @param {object} [options] See aggregate + * + * @see + * {@link Model.aggregate} for options + * * @returns {Promise<*>} */ static async min(field, options) { @@ -2185,10 +2170,14 @@ export class Model { } /** - * Retrieves the sum of field + * Find the sum of field * * @param {string} field attribute / field name * @param {object} [options] See aggregate + * + * @see + * {@link Model.aggregate} for options + * * @returns {Promise} */ static async sum(field, options) { @@ -2197,11 +2186,12 @@ export class Model { /** * Builds a new model instance. - * Unlike {@link Model.create}, the instance is not persisted, you need to call {@link Model#save} yourself. * - * @param {object|Array} values An object of key value pairs or an array of such. If an array, the function will return an - * array of instances. + * @param {object|Array} values An object of key value pairs or an array of such. If an array, the function will return an array of instances. * @param {object} [options] Instance build options + * @param {boolean} [options.raw=false] If set to true, values will ignore field and virtual setters. + * @param {boolean} [options.isNewRecord=true] Is this new record + * @param {Array} [options.include] an array of include options - Used to build prefetched/included model instances. See `set` * * @returns {Model|Array} */ @@ -2213,13 +2203,6 @@ export class Model { return new this(values, options); } - /** - * Builds multiple new model instances. - * Unlike {@link Model.create}, the instances are not persisted, you need to call {@link Model#save} yourself. - * - * @param {Array} valueSets An array of objects with key value pairs. - * @param {object} [options] Instance build options - */ static bulkBuild(valueSets, options) { options = { isNewRecord: true, ...options }; @@ -2232,18 +2215,35 @@ export class Model { } if (options.attributes) { - options.attributes = options.attributes.map(attribute => (Array.isArray(attribute) ? attribute[1] : attribute)); + options.attributes = options.attributes.map(attribute => Array.isArray(attribute) ? attribute[1] : attribute); } return valueSets.map(values => this.build(values, options)); } /** - * Builds a new model instance and persists it. - * Equivalent to calling {@link Model.build} then {@link Model.save}. + * Builds a new model instance and calls save on it. + * + * @see + * {@link Model.build} + * @see + * {@link Model.save} + * + * @param {object} values Hash of data values to create new record with + * @param {object} [options] Build and query options + * @param {boolean} [options.raw=false] If set to true, values will ignore field and virtual setters. + * @param {boolean} [options.isNewRecord=true] Is this new record + * @param {Array} [options.include] An array of include options - Used to build prefetched/included model instances. See `set` + * @param {string[]} [options.fields] An optional array of strings, representing database columns. If fields is provided, only those columns will be validated and saved. + * @param {boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated. + * @param {boolean} [options.validate=true] If false, validations won't be run. + * @param {boolean} [options.hooks=true] Run before and after create / update + validate hooks + * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql. + * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging). + * @param {Transaction} [options.transaction] Transaction to run query under + * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only) + * @param {boolean|Array} [options.returning=true] Appends RETURNING to get back all defined values; if an array of column names, append RETURNING to get back specific columns (Postgres only) * - * @param {object} values - * @param {object} options * @returns {Promise} * */ @@ -2255,22 +2255,26 @@ export class Model { attributes: options.fields, include: options.include, raw: options.raw, - silent: options.silent, + silent: options.silent }).save(options); } /** - * Find an entity that matches the query, or build (but don't save) the entity if none is found. - * The successful result of the promise will be the tuple [instance, initialized]. + * Find a row that matches the query, or build (but don't save) the row if none is found. + * The successful result of the promise will be (instance, built) + * + * @param {object} options find options + * @param {object} options.where A hash of search attributes. If `where` is a plain object it will be appended with defaults to build a new instance. + * @param {object} [options.defaults] Default values to use if building a new instance + * @param {object} [options.transaction] Transaction to run query under * - * @param {object} options find options * @returns {Promise} */ static async findOrBuild(options) { if (!options || !options.where || arguments.length > 1) { throw new Error( - 'Missing where attribute in the options parameter passed to findOrBuild. ' - + 'Please note that the API has changed, and is now options only (an object with where, defaults keys, transaction etc.)', + 'Missing where attribute in the options parameter passed to findOrBuild. ' + + 'Please note that the API has changed, and is now options only (an object with where, defaults keys, transaction etc.)' ); } @@ -2292,27 +2296,28 @@ export class Model { } /** - * Find an entity that matches the query, or {@link Model.create} the entity if none is found - * The successful result of the promise will be the tuple [instance, initialized]. + * Find a row that matches the query, or build and save the row if none is found + * The successful result of the promise will be (instance, created) + * + * If no transaction is passed in the `options` 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. + * 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 committed. In this case, an instance of sequelize. TimeoutError will be thrown instead. + * If a transaction is created, a savepoint will be created instead, and any unique constraint violation will be handled internally. * - * If no transaction is passed in the `options` 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. - * 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 committed. - * In this case, an instance of {@link TimeoutError} will be thrown instead. + * @see + * {@link Model.findAll} for a full specification of find and options * - * If a transaction is passed, a savepoint will be created instead, - * and any unique constraint violation will be handled internally. + * @param {object} options find and create options + * @param {object} options.where where A hash of search attributes. If `where` is a plain object it will be appended with defaults to build a new instance. + * @param {object} [options.defaults] Default values to use if creating a new instance + * @param {Transaction} [options.transaction] Transaction to run query under * - * @param {object} options find and create options * @returns {Promise} */ static async findOrCreate(options) { if (!options || !options.where || arguments.length > 1) { throw new Error( - 'Missing where attribute in the options parameter passed to findOrCreate. ' - + 'Please note that the API has changed, and is now options only (an object with where, defaults keys, transaction etc.)', + 'Missing where attribute in the options parameter passed to findOrCreate. ' + + 'Please note that the API has changed, and is now options only (an object with where, defaults keys, transaction etc.)' ); } @@ -2322,7 +2327,7 @@ export class Model { const defaults = Object.keys(options.defaults); const unknownDefaults = defaults.filter(name => !this.rawAttributes[name]); - if (unknownDefaults.length > 0) { + if (unknownDefaults.length) { logger.warn(`Unknown attributes (${unknownDefaults}) passed to defaults option of findOrCreate`); } } @@ -2364,11 +2369,8 @@ export class Model { } return [created, true]; - } catch (error) { - if (!(error instanceof sequelizeErrors.UniqueConstraintError)) { - throw error; - } - + } catch (err) { + if (!(err instanceof sequelizeErrors.UniqueConstraintError)) throw err; const flattenedWhere = Utils.flattenObjectDeep(options.where); const flattenedWhereKeys = Object.keys(flattenedWhere).map(name => _.last(name.split('.'))); const whereFields = flattenedWhereKeys.map(name => _.get(this.rawAttributes, `${name}.field`, name)); @@ -2376,14 +2378,14 @@ export class Model { .filter(name => this.rawAttributes[name]) .map(name => this.rawAttributes[name].field || name); - const errFieldKeys = Object.keys(error.fields); + const errFieldKeys = Object.keys(err.fields); const errFieldsWhereIntersects = Utils.intersects(errFieldKeys, whereFields); if (defaultFields && !errFieldsWhereIntersects && Utils.intersects(errFieldKeys, defaultFields)) { - throw error; + throw err; } if (errFieldsWhereIntersects) { - _.each(error.fields, (value, key) => { + _.each(err.fields, (value, key) => { const name = this.fieldRawAttributesMap[key].fieldName; if (value.toString() !== options.where[name].toString()) { throw new Error(`${this.name}#findOrCreate: value used for ${name} was not equal for both the find and the create calls, '${options.where[name]}' vs '${value}'`); @@ -2393,14 +2395,12 @@ export class Model { // Someone must have created a matching instance inside the same transaction since we last did a find. Let's find it! const otherCreated = await this.findOne(Utils.defaults({ - transaction: internalTransaction ? null : transaction, + transaction: internalTransaction ? null : transaction }, options)); // Sanity check, ideally we caught this at the defaultFeilds/err.fields check // But if we didn't and instance is null, we will throw - if (otherCreated === null) { - throw error; - } + if (otherCreated === null) throw err; return [otherCreated, false]; } @@ -2412,20 +2412,22 @@ export class Model { } /** - * A more performant {@link Model.findOrCreate} that will not start its own transaction or savepoint (at least not in - * postgres) + * A more performant findOrCreate that may not work under a transaction (working in postgres) + * Will execute a find call, if empty then attempt to create, if unique constraint then attempt to find again * - * It will execute a find call, attempt to create if empty, then attempt to find again if a unique constraint fails. - * - * The successful result of the promise will be the tuple [instance, initialized]. + * @see + * {@link Model.findAll} for a full specification of find and options * * @param {object} options find options + * @param {object} options.where A hash of search attributes. If `where` is a plain object it will be appended with defaults to build a new instance. + * @param {object} [options.defaults] Default values to use if creating a new instance + * * @returns {Promise} */ static async findCreateFind(options) { if (!options || !options.where) { throw new Error( - 'Missing where attribute in the options parameter passed to findCreateFind.', + 'Missing where attribute in the options parameter passed to findCreateFind.' ); } @@ -2434,10 +2436,9 @@ export class Model { values = Utils.defaults(values, options.where); } + const found = await this.findOne(options); - if (found) { - return [found, false]; - } + if (found) return [found, false]; try { const createOptions = { ...options }; @@ -2448,49 +2449,49 @@ export class Model { } const created = await this.create(values, createOptions); - return [created, true]; - } catch (error) { - if (!(error instanceof sequelizeErrors.UniqueConstraintError || error instanceof sequelizeErrors.EmptyResultError)) { - throw error; + } catch (err) { + if (!(err instanceof sequelizeErrors.UniqueConstraintError || err instanceof sequelizeErrors.EmptyResultError)) { + throw err; } const foundAgain = await this.findOne(options); - return [foundAgain, false]; } } /** - * Inserts or updates a single entity. 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. + * 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. * * **Implementation details:** * - * * MySQL - Implemented as a single query `INSERT values ON DUPLICATE KEY UPDATE values` - * * PostgreSQL - Implemented as a temporary function with exception handling: INSERT EXCEPTION WHEN - * unique_constraint UPDATE - * * SQLite - Implemented as two queries `INSERT; UPDATE`. This means that the update is executed regardless - * of whether the row already existed or not - * - * **Note:** SQLite returns null 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. - * - * @param {object} values hash of values to upsert - * @param {object} [options] upsert options - * @returns {Promise>} an array with two elements, the first being the new record and - * the second being `true` if it was just created or `false` if it already existed (except on Postgres and SQLite, which - * can't detect this and will always return `null` instead of a boolean). + * * MySQL - Implemented with ON DUPLICATE KEY UPDATE` + * * PostgreSQL - Implemented with ON CONFLICT DO UPDATE. If update data contains PK field, then PK is selected as the default conflict key. Otherwise first unique constraint/index will be selected, which can satisfy conflict key requirements. + * * SQLite - Implemented with ON CONFLICT DO UPDATE + * * MSSQL - Implemented as a single query using `MERGE` and `WHEN (NOT) MATCHED THEN` + * + * **Note** that Postgres/SQLite returns null for created, no matter if the row was created or updated + * + * @param {object} values hash of values to upsert + * @param {object} [options] upsert options + * @param {boolean} [options.validate=true] Run validations before the row is inserted + * @param {Array} [options.fields=Object.keys(this.attributes)] The fields to update if the record already exists. Defaults to all changed fields. If none of the specified fields are present on the provided `values` object, an insert will still be attempted, but duplicate key conflicts will be ignored. + * @param {boolean} [options.hooks=true] Run before / after upsert hooks? + * @param {boolean} [options.returning=true] If true, fetches back auto generated values + * @param {Transaction} [options.transaction] Transaction to run query under + * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql. + * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging). + * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only) + * @param {Array} [options.conflictFields] Optional override for the conflict fields in the ON CONFLICT part of the query. Only supported in Postgres >= 9.5 and SQLite >= 3.24.0 + * + * @returns {Promise>} returns an array with two elements, the first being the new record and the second being `true` if it was just created or `false` if it already existed (except on Postgres and SQLite, which can't detect this and will always return `null` instead of a boolean). */ static async upsert(values, options) { options = { hooks: true, returning: true, validate: true, - ...Utils.cloneDeep(options), + ...Utils.cloneDeep(options) }; const createdAtAttr = this._timestampAttributes.createdAt; @@ -2501,7 +2502,7 @@ export class Model { options.model = this; options.instance = instance; - const changed = [...instance._changed]; + const changed = Array.from(instance._changed); if (!options.fields) { options.fields = changed; } @@ -2509,7 +2510,6 @@ export class Model { if (options.validate) { await instance.validate(options); } - // Map field names const updatedDataValues = _.pick(instance.dataValues, changed); const insertValues = Utils.mapValueFieldNames(instance.dataValues, Object.keys(instance.rawAttributes), this); @@ -2521,7 +2521,6 @@ export class Model { const field = this.rawAttributes[createdAtAttr].field || createdAtAttr; insertValues[field] = this._getDefaultTimestamp(createdAtAttr) || now; } - if (updatedAtAttr && !insertValues[updatedAtAttr]) { const field = this.rawAttributes[updatedAtAttr].field || updatedAtAttr; insertValues[field] = updateValues[field] = this._getDefaultTimestamp(updatedAtAttr) || now; @@ -2531,8 +2530,7 @@ export class Model { // Add dummy values if not provided by test case or user. if (this.sequelize.options.dialect === 'db2') { this.uniqno = this.sequelize.dialect.queryGenerator.addUniqueFields( - insertValues, this.rawAttributes, this.uniqno, - ); + insertValues, this.rawAttributes, this.uniqno); } // Build adds a null value for the primary key, if none was given by the user. @@ -2545,7 +2543,6 @@ export class Model { if (options.hooks) { await this.runHooks('beforeUpsert', values, options); } - const result = await this.queryInterface.upsert(this.getTableName(options), insertValues, updateValues, instance.where(), options); const [record] = result; @@ -2553,32 +2550,38 @@ export class Model { if (options.hooks) { await this.runHooks('afterUpsert', result, options); - return result; } - return result; } /** - * Creates and inserts multiple instances in bulk. + * Create and insert multiple instances in bulk. * - * The promise resolves with an array of instances. + * 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 + * 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. + * To obtain Instances for the newly created values, you will need to query for them again. * - * Please note that, depending on your dialect, the resulting instances may not accurately - * represent the state of their rows in the database. - * This is because MySQL 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. - * To obtain the correct data for the newly created instance, you will need to query for them again. - * - * If validation fails, the promise is rejected with {@link AggregateError} + * If validation fails, the promise is rejected with an array-like AggregateError * * @param {Array} records List of objects (key/value pairs) to create instances from * @param {object} [options] Bulk create options + * @param {Array} [options.fields] Fields to insert (defaults to all fields) + * @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 + * @param {boolean} [options.hooks=true] Run before / after bulk create hooks? + * @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. + * @param {boolean} [options.ignoreDuplicates=false] Ignore duplicate values for primary keys? (not supported by MSSQL or Postgres < 9.5) + * @param {Array} [options.updateOnDuplicate] Fields to update if row key already exists (on duplicate key update)? (only supported by MySQL, MariaDB, SQLite >= 3.24.0 & Postgres >= 9.5). + * @param {Transaction} [options.transaction] Transaction to run query under + * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql. + * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging). + * @param {boolean|Array} [options.returning=false] If true, append RETURNING to get back all defined values; if an array of column names, append RETURNING to get back specific columns (Postgres only) + * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only) + * * @returns {Promise>} */ static async bulkCreate(records, options = {}) { - if (records.length === 0) { + if (!records.length) { return []; } @@ -2604,7 +2607,7 @@ export class Model { hooks: true, individualHooks: false, ignoreDuplicates: false, - ...options, + ...options }; if (options.returning === undefined) { @@ -2615,11 +2618,10 @@ export class Model { } } - if (options.ignoreDuplicates && ['mssql', 'db2', 'ibmi'].includes(dialect)) { + if (options.ignoreDuplicates && ['mssql', 'db2'].includes(dialect)) { throw new Error(`${dialect} does not support the ignoreDuplicates option.`); } - - if (options.updateOnDuplicate && !['mysql', 'mariadb', 'sqlite', 'postgres', 'ibmi'].includes(dialect)) { + if (options.updateOnDuplicate && (dialect !== 'mysql' && dialect !== 'mariadb' && dialect !== 'sqlite' && dialect !== 'postgres')) { throw new Error(`${dialect} does not support the updateOnDuplicate option.`); } @@ -2630,10 +2632,10 @@ export class Model { const updatedAtAttr = model._timestampAttributes.updatedAt; if (options.updateOnDuplicate !== undefined) { - if (Array.isArray(options.updateOnDuplicate) && options.updateOnDuplicate.length > 0) { + if (Array.isArray(options.updateOnDuplicate) && options.updateOnDuplicate.length) { options.updateOnDuplicate = _.intersection( _.without(Object.keys(model.tableAttributes), createdAtAttr), - options.updateOnDuplicate, + options.updateOnDuplicate ); } else { throw new Error('updateOnDuplicate option only supports non-empty array.'); @@ -2644,7 +2646,6 @@ export class Model { if (options.hooks) { await model.runHooks('beforeBulkCreate', instances, options); } - // Validate if (options.validate) { const errors = []; @@ -2654,23 +2655,22 @@ export class Model { await Promise.all(instances.map(async instance => { try { await instance.validate(validateOptions); - } catch (error) { - errors.push(new sequelizeErrors.BulkRecordError(error, instance)); + } catch (err) { + errors.push(new sequelizeErrors.BulkRecordError(err, instance)); } })); delete options.skip; - if (errors.length > 0) { + if (errors.length) { throw new sequelizeErrors.AggregateError(errors); } } - if (options.individualHooks) { await Promise.all(instances.map(async instance => { const individualOptions = { ...options, validate: false, - hooks: true, + hooks: true }; delete individualOptions.fields; delete individualOptions.individualHooks; @@ -2679,7 +2679,7 @@ export class Model { await instance.save(individualOptions); })); } else { - if (options.include && options.include.length > 0) { + if (options.include && options.include.length) { await Promise.all(options.include.filter(include => include.association instanceof BelongsTo).map(async include => { const associationInstances = []; const associationInstanceIndexToInstanceMap = []; @@ -2692,7 +2692,7 @@ export class Model { } } - if (associationInstances.length === 0) { + if (!associationInstances.length) { return; } @@ -2700,9 +2700,8 @@ export class Model { .omit(['association']) .defaults({ transaction: options.transaction, - logging: options.logging, - }) - .value(); + logging: options.logging + }).value(); const createdAssociationInstances = await recursiveBulkCreate(associationInstances, includeOptions); for (const idx in createdAssociationInstances) { @@ -2726,7 +2725,6 @@ export class Model { options.fields.push(createdAtAttr); } } - if (updatedAtAttr && !values[updatedAtAttr]) { values[updatedAtAttr] = now; if (!options.fields.includes(updatedAtAttr)) { @@ -2738,7 +2736,6 @@ export class Model { for (const key of model._virtualAttributes) { delete out[key]; } - return out; }); @@ -2778,19 +2775,18 @@ export class Model { const results = await model.queryInterface.bulkInsert(model.getTableName(options), records, options, fieldMappedAttributes); if (Array.isArray(results)) { - for (const [i, result] of results.entries()) { + results.forEach((result, i) => { const instance = instances[i]; for (const key in result) { - if (!instance || key === model.primaryKeyAttribute - && instance.get(model.primaryKeyAttribute) - && ['mysql', 'mariadb', 'sqlite'].includes(dialect)) { + if (!instance || key === model.primaryKeyAttribute && + instance.get(model.primaryKeyAttribute) && + ['mysql', 'mariadb', 'sqlite'].includes(dialect)) { // The query.js for these DBs is blind, it autoincrements the // primarykey value, even if it was set manually. Also, it can // return more results than instances, bug?. continue; } - if (Object.prototype.hasOwnProperty.call(result, key)) { const record = result[key]; @@ -2799,21 +2795,19 @@ export class Model { instance.dataValues[attr && attr.fieldName || key] = record; } } - } + }); } } - if (options.include && options.include.length > 0) { - await Promise.all(options.include.filter(include => !(include.association instanceof BelongsTo - || include.parent && include.parent.association instanceof BelongsToMany)).map(async include => { + if (options.include && options.include.length) { + await Promise.all(options.include.filter(include => !(include.association instanceof BelongsTo || + include.parent && include.parent.association instanceof BelongsToMany)).map(async include => { const associationInstances = []; const associationInstanceIndexToInstanceMap = []; for (const instance of instances) { let associated = instance.get(include.as); - if (!Array.isArray(associated)) { - associated = [associated]; - } + if (!Array.isArray(associated)) associated = [associated]; for (const associationInstance of associated) { if (associationInstance) { @@ -2821,14 +2815,13 @@ export class Model { associationInstance.set(include.association.foreignKey, instance.get(include.association.sourceKey || instance.constructor.primaryKeyAttribute, { raw: true }), { raw: true }); Object.assign(associationInstance, include.association.scope); } - associationInstances.push(associationInstance); associationInstanceIndexToInstanceMap.push(instance); } } } - if (associationInstances.length === 0) { + if (!associationInstances.length) { return; } @@ -2836,9 +2829,8 @@ export class Model { .omit(['association']) .defaults({ transaction: options.transaction, - logging: options.logging, - }) - .value(); + logging: options.logging + }).value(); const createdAssociationInstances = await recursiveBulkCreate(associationInstances, includeOptions); if (include.association instanceof BelongsToMany) { @@ -2852,17 +2844,16 @@ export class Model { [include.association.foreignKey]: instance.get(instance.constructor.primaryKeyAttribute, { raw: true }), [include.association.otherKey]: associationInstance.get(associationInstance.constructor.primaryKeyAttribute, { raw: true }), // Include values defined in the association - ...include.association.through.scope, + ...include.association.through.scope }; if (associationInstance[include.association.through.model.name]) { for (const attr of Object.keys(include.association.through.model.rawAttributes)) { - if (include.association.through.model.rawAttributes[attr]._autoGenerated - || attr === include.association.foreignKey - || attr === include.association.otherKey - || typeof associationInstance[include.association.through.model.name][attr] === 'undefined') { + if (include.association.through.model.rawAttributes[attr]._autoGenerated || + attr === include.association.foreignKey || + attr === include.association.otherKey || + typeof associationInstance[include.association.through.model.name][attr] === undefined) { continue; } - values[attr] = associationInstance[include.association.through.model.name][attr]; } } @@ -2874,9 +2865,8 @@ export class Model { .omit(['association', 'attributes']) .defaults({ transaction: options.transaction, - logging: options.logging, - }) - .value(); + logging: options.logging + }).value(); throughOptions.model = include.association.throughModel; const throughInstances = include.association.throughModel.bulkBuild(valueSets, throughOptions); @@ -2886,22 +2876,20 @@ export class Model { } // map fields back to attributes - for (const instance of instances) { + instances.forEach(instance => { for (const attr in model.rawAttributes) { - if (model.rawAttributes[attr].field - && instance.dataValues[model.rawAttributes[attr].field] !== undefined - && model.rawAttributes[attr].field !== attr + if (model.rawAttributes[attr].field && + instance.dataValues[model.rawAttributes[attr].field] !== undefined && + model.rawAttributes[attr].field !== attr ) { instance.dataValues[attr] = instance.dataValues[model.rawAttributes[attr].field]; delete instance.dataValues[model.rawAttributes[attr].field]; } - instance._previousDataValues[attr] = instance.dataValues[attr]; instance.changed(attr, false); } - instance.isNewRecord = false; - } + }); // Run after hook if (options.hooks) { @@ -2915,25 +2903,43 @@ export class Model { } /** - * Destroys all instances of the model. - * This is a convenient method for `MyModel.destroy({ truncate: true })`. + * Truncate all instances of the model. This is a convenient method for Model.destroy({ truncate: true }). * - * __Danger__: This will completely empty your table! + * @param {object} [options] The options passed to Model.destroy in addition to truncate + * @param {boolean|Function} [options.cascade = false] Truncates all tables that have foreign-key references to the named table, or to any tables added to the group due to CASCADE. + * @param {boolean} [options.restartIdentity=false] Automatically restart sequences owned by columns of the truncated table. + * @param {Transaction} [options.transaction] Transaction to run query under + * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging + * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging). + * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only) * - * @param {object} [options] truncate options * @returns {Promise} + * + * @see + * {@link Model.destroy} for more information */ static async truncate(options) { options = Utils.cloneDeep(options) || {}; options.truncate = true; - return await this.destroy(options); } /** - * Deletes multiple instances, or set their deletedAt timestamp to the current time if `paranoid` is enabled. + * Delete multiple instances, or set their deletedAt timestamp to the current time if `paranoid` is enabled. + * + * @param {object} options destroy options + * @param {object} [options.where] Filter the destroy + * @param {boolean} [options.hooks=true] Run before / after bulk destroy hooks? + * @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 + * @param {number} [options.limit] How many rows to delete + * @param {boolean} [options.force=false] Delete instead of setting deletedAt to current timestamp (only applicable if `paranoid` is enabled) + * @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 + * @param {boolean} [options.cascade=false] Only used in conjunction 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. + * @param {boolean} [options.restartIdentity=false] Only used in conjunction with TRUNCATE. Automatically restart sequences owned by columns of the truncated table. + * @param {Transaction} [options.transaction] Transaction to run query under + * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql. + * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging). * - * @param {object} options destroy options * @returns {Promise} The number of destroyed rows */ static async destroy(options) { @@ -2954,7 +2960,7 @@ export class Model { individualHooks: false, force: false, cascade: false, - restartIdentity: false, + restartIdentity: false }); options.type = QueryTypes.BULKDELETE; @@ -2962,11 +2968,11 @@ export class Model { Utils.mapOptionFieldNames(options, this); options.model = this; + // Run before hook if (options.hooks) { await this.runHooks('beforeBulkDestroy', options); } - let instances; // Get daos and run beforeDestroy hook on each record individually if (options.individualHooks) { @@ -2974,7 +2980,6 @@ export class Model { await Promise.all(instances.map(instance => this.runHooks('beforeDestroy', instance, options))); } - let result; // Run delete query (or update if paranoid) if (this._timestampAttributes.deletedAt && !options.force) { @@ -2985,46 +2990,49 @@ export class Model { const deletedAtAttribute = this.rawAttributes[this._timestampAttributes.deletedAt]; const field = this.rawAttributes[this._timestampAttributes.deletedAt].field; const where = { - [field]: Object.prototype.hasOwnProperty.call(deletedAtAttribute, 'defaultValue') ? deletedAtAttribute.defaultValue : null, + [field]: Object.prototype.hasOwnProperty.call(deletedAtAttribute, 'defaultValue') ? deletedAtAttribute.defaultValue : null }; + attrValueHash[field] = Utils.now(this.sequelize.options.dialect); result = await this.queryInterface.bulkUpdate(this.getTableName(options), attrValueHash, Object.assign(where, options.where), options, this.rawAttributes); } else { result = await this.queryInterface.bulkDelete(this.getTableName(options), options.where, options, this); } - // Run afterDestroy hook on each record individually if (options.individualHooks) { await Promise.all( - instances.map(instance => this.runHooks('afterDestroy', instance, options)), + instances.map(instance => this.runHooks('afterDestroy', instance, options)) ); } - // Run after hook if (options.hooks) { await this.runHooks('afterBulkDestroy', options); } - return result; } /** - * Restores multiple paranoid instances. - * Only usable if {@link ModelOptions.paranoid} is true. + * Restore multiple instances if `paranoid` is enabled. + * + * @param {object} options restore options + * @param {object} [options.where] Filter the restore + * @param {boolean} [options.hooks=true] Run before / after bulk restore hooks? + * @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 + * @param {number} [options.limit] How many rows to undelete (only for mysql) + * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql. + * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging). + * @param {Transaction} [options.transaction] Transaction to run query under * - * @param {object} options restore options * @returns {Promise} */ static async restore(options) { - if (!this._timestampAttributes.deletedAt) { - throw new Error('Model is not paranoid'); - } + if (!this._timestampAttributes.deletedAt) throw new Error('Model is not paranoid'); options = { hooks: true, individualHooks: false, - ...options, + ...options }; options.type = QueryTypes.RAW; @@ -3044,7 +3052,6 @@ export class Model { await Promise.all(instances.map(instance => this.runHooks('beforeRestore', instance, options))); } - // Run undelete query const attrValueHash = {}; const deletedAtCol = this._timestampAttributes.deletedAt; @@ -3057,29 +3064,38 @@ export class Model { // Run afterDestroy hook on each record individually if (options.individualHooks) { await Promise.all( - instances.map(instance => this.runHooks('afterRestore', instance, options)), + instances.map(instance => this.runHooks('afterRestore', instance, options)) ); } - // Run after hook if (options.hooks) { await this.runHooks('afterBulkRestore', options); } - return result; } /** - * Updates multiple instances that match the where options. - * - * The promise resolves with an array of one or two elements: - * - The first element is always the number of affected rows, - * - the second element is the list of affected entities (only supported in postgres and mssql with - * {@link UpdateOptions.returning} true.) + * Update multiple instances that match the where options. + * + * @param {object} values hash of values to update + * @param {object} options update options + * @param {object} options.where Options to describe the scope of the search. + * @param {boolean} [options.paranoid=true] If true, only non-deleted records will be updated. If false, both deleted and non-deleted records will be updated. Only applies if `options.paranoid` is true for the model. + * @param {Array} [options.fields] Fields to update (defaults to all fields) + * @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 + * @param {boolean} [options.hooks=true] Run before / after bulk update hooks? + * @param {boolean} [options.sideEffects=true] Whether or not to update the side effects of any virtual setters. + * @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 + * @param {boolean|Array} [options.returning=false] If true, append RETURNING to get back all defined values; if an array of column names, append RETURNING to get back specific columns (Postgres only) + * @param {number} [options.limit] How many rows to update (only for mysql and mariadb, implemented as TOP(n) for MSSQL; for sqlite it is supported only when rowid is present) + * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql. + * @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging). + * @param {Transaction} [options.transaction] Transaction to run query under + * @param {boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated. + * + * @returns {Promise>} The promise returns an array with one or two elements. The first element is always the number + * of affected rows, while the second element is the actual affected rows (only supported in postgres with `options.returning` true). * - * @param {object} values hash of values to update - * @param {object} options update options - * @returns {Promise>} */ static async update(values, options) { options = Utils.cloneDeep(options); @@ -3093,7 +3109,7 @@ export class Model { individualHooks: false, returning: false, force: false, - sideEffects: true, + sideEffects: true })); options.type = QueryTypes.BULKUPDATE; @@ -3102,7 +3118,7 @@ export class Model { values = _.omitBy(values, value => value === undefined); // Remove values that are not in the options.fields - if (options.fields && Array.isArray(options.fields)) { + if (options.fields && options.fields instanceof Array) { for (const key of Object.keys(values)) { if (!options.fields.includes(key)) { delete values[key]; @@ -3141,7 +3157,6 @@ export class Model { values = _.pick(attributes.dataValues, Object.keys(values)); } } - // Run before hook if (options.hooks) { options.attributes = values; @@ -3161,10 +3176,10 @@ export class Model { transaction: options.transaction, logging: options.logging, benchmark: options.benchmark, - paranoid: options.paranoid, + paranoid: options.paranoid }); - if (instances.length > 0) { + if (instances.length) { // Run beforeUpdate hooks on each record and check whether beforeUpdate hook changes values uniformly // i.e. whether they change values for each record in the same way let changedValues; @@ -3203,7 +3218,7 @@ export class Model { if (!different) { const keys = Object.keys(changedValues); // Hooks do not change values or change them uniformly - if (keys.length > 0) { + if (keys.length) { // Hooks change values - record changes in valuesUse so they are executed valuesUse = changedValues; options.fields = _.union(options.fields, keys); @@ -3213,7 +3228,7 @@ export class Model { const individualOptions = { ...options, hooks: false, - validate: false, + validate: false }; delete individualOptions.individualHooks; @@ -3223,7 +3238,6 @@ export class Model { } } } - let result; if (updateDoneRowByRow) { result = [instances.length, instances]; @@ -3249,19 +3263,17 @@ export class Model { await Promise.all(instances.map(instance => this.runHooks('afterUpdate', instance, options))); result[1] = instances; } - // Run after hook if (options.hooks) { options.attributes = values; await this.runHooks('afterBulkUpdate', options); delete options.attributes; } - return result; } /** - * Runs a describe query on the table. + * Run a describe query on the table. * * @param {string} [schema] schema name to search table in * @param {object} [options] query options @@ -3269,21 +3281,20 @@ export class Model { * @returns {Promise} hash of attributes and their types */ static async describe(schema, options) { - return await this.queryInterface.describeTable(this.tableName, { schema: schema || this._schema || '', ...options }); + return await this.queryInterface.describeTable(this.tableName, { schema: schema || this._schema || undefined, ...options }); } static _getDefaultTimestamp(attr) { - if (Boolean(this.rawAttributes[attr]) && Boolean(this.rawAttributes[attr].defaultValue)) { + if (!!this.rawAttributes[attr] && !!this.rawAttributes[attr].defaultValue) { return Utils.toDefaultValue(this.rawAttributes[attr].defaultValue, this.sequelize.options.dialect); } - + return undefined; } static _expandAttributes(options) { if (!_.isPlainObject(options.attributes)) { return; } - let attributes = Object.keys(this.rawAttributes); if (options.attributes.exclude) { @@ -3312,9 +3323,8 @@ export class Model { } /** - * Increments the value of one or more attributes. - * - * The increment is done using a `SET column = column + X WHERE foo = 'bar'` query. + * Increment the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The increment is done using a + * ``` SET column = column + X WHERE foo = 'bar' ``` query. To get the correct value after an increment into the Instance you should do a reload. * * @example increment number by 1 * Model.increment('number', { where: { foo: 'bar' }); @@ -3323,29 +3333,31 @@ export class Model { * Model.increment(['number', 'count'], { by: 2, where: { foo: 'bar' } }); * * @example increment answer by 42, and decrement tries by 1 - * // `by` cannot be used, as each attribute specifies its own value - * Model.increment({ answer: 42, tries: -1}, { where: { foo: 'bar' } }); + * // `by` is ignored, as each column has its own value + * Model.increment({ answer: 42, tries: -1}, { by: 2, where: { foo: 'bar' } }); * - * @param {string|Array|object} fields If a string is provided, that column is incremented by the - * value of `by` given in options. If an array is provided, the same is true for each column. - * If an object is provided, each key is incremented by the corresponding value, `by` is ignored. - * @param {object} options increment options - * @param {object} options.where conditions hash - * - * @returns {Promise} an array of affected rows and affected count with `options.returning` true, whenever supported by dialect + * @see + * {@link Model#reload} + * + * @param {string|Array|object} fields If a string is provided, that column is incremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is incremented by the value given. + * @param {object} options increment options + * @param {object} options.where conditions hash + * @param {number} [options.by=1] The number to increment by + * @param {boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated. + * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql. + * @param {Transaction} [options.transaction] Transaction to run query under + * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only) + * + * @returns {Promise} returns an array of affected rows and affected count with `options.returning` true, whenever supported by dialect */ static async increment(fields, options) { options = options || {}; - if (typeof fields === 'string') { - fields = [fields]; - } - + if (typeof fields === 'string') fields = [fields]; if (Array.isArray(fields)) { fields = fields.map(f => { if (this.rawAttributes[f] && this.rawAttributes[f].field && this.rawAttributes[f].field !== f) { return this.rawAttributes[f].field; } - return f; }); } else if (fields && typeof fields === 'object') { @@ -3355,7 +3367,6 @@ export class Model { } else { rawFields[f] = fields[f]; } - return rawFields; }, {}); } @@ -3366,7 +3377,7 @@ export class Model { options = Utils.defaults({}, options, { by: 1, where: {}, - increment: true, + increment: true }); const isSubtraction = !options.increment; @@ -3407,11 +3418,11 @@ export class Model { let affectedRows; if (isSubtraction) { affectedRows = await this.queryInterface.decrement( - this, tableName, where, incrementAmountsByField, extraAttributesToBeUpdated, options, + this, tableName, where, incrementAmountsByField, extraAttributesToBeUpdated, options ); } else { affectedRows = await this.queryInterface.increment( - this, tableName, where, incrementAmountsByField, extraAttributesToBeUpdated, options, + this, tableName, where, incrementAmountsByField, extraAttributesToBeUpdated, options ); } @@ -3423,10 +3434,8 @@ export class Model { } /** - * Decrement the value of one or more columns. This is done in the database, which means it does not use the values - * currently stored on the Instance. The decrement is done using a - * ```sql SET column = column - X WHERE foo = 'bar'``` query. To get the correct value after a decrement into the Instance - * you should do a reload. + * Decrement the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The decrement is done using a + * ```sql SET column = column - X WHERE foo = 'bar'``` query. To get the correct value after a decrement into the Instance you should do a reload. * * @example decrement number by 1 * Model.decrement('number', { where: { foo: 'bar' }); @@ -3438,21 +3447,22 @@ export class Model { * // `by` is ignored, since each column has its own value * Model.decrement({ answer: 42, tries: -1}, { by: 2, where: { foo: 'bar' } }); * - * @param {string|Array|object} fields If a string is provided, that column is incremented by the value of `by` given in - * options. If an array is provided, the same is true for each column. If and object is provided, each column is - * incremented by the value given. + * @param {string|Array|object} fields If a string is provided, that column is incremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is incremented by the value given. * @param {object} options decrement options, similar to increment * + * @see + * {@link Model.increment} + * @see + * {@link Model#reload} * @since 4.36.0 * - * @returns {Promise} returns an array of affected rows and affected count with `options.returning` true, - * whenever supported by dialect + * @returns {Promise} returns an array of affected rows and affected count with `options.returning` true, whenever supported by dialect */ static async decrement(fields, options) { return this.increment(fields, { by: 1, ...options, - increment: false, + increment: false }); } @@ -3463,7 +3473,7 @@ export class Model { } /** - * Returns an object representing the query for this instance, use with `options.where` + * Get an object representing the query for this instance, use with `options.where` * * @param {boolean} [checkVersion=false] include version attribute in where hash * @@ -3472,19 +3482,16 @@ export class Model { where(checkVersion) { const where = this.constructor.primaryKeyAttributes.reduce((result, attribute) => { result[attribute] = this.get(attribute, { raw: true }); - return result; }, {}); if (_.size(where) === 0) { return this.constructor.options.whereCollection; } - const versionAttr = this.constructor._versionAttribute; if (checkVersion && versionAttr) { where[versionAttr] = this.get(versionAttr, { raw: true }); } - return Utils.mapWhereFieldNames(where, this.constructor); } @@ -3493,12 +3500,10 @@ export class Model { } /** - * Returns the underlying data value + * Get the value of the underlying data value * - * Unlike {@link Model#get}, this method returns the value as it was retrieved, bypassing - * getters, cloning, virtual attributes. + * @param {string} key key to look in instance data store * - * @param {string} key The name of the attribute to return. * @returns {any} */ getDataValue(key) { @@ -3506,12 +3511,11 @@ export class Model { } /** - * Updates the underlying data value + * Update the underlying data value * - * Unlike {@link Model#set}, this method skips any special behavior and directly replaces the raw value. + * @param {string} key key to set in instance data store + * @param {any} value new value for given key * - * @param {string} key The name of the attribute to update. - * @param {any} value The new value for that attribute. */ setDataValue(key, value) { const originalValue = this._previousDataValues[key]; @@ -3526,11 +3530,12 @@ export class Model { /** * If no key is given, returns all values of the instance, also invoking virtual getters. * - * If key is given and a field or virtual getter is present for the key it will call that getter - else it will return the - * value for key. + * If key is given and a field or virtual getter is present for the key it will call that getter - else it will return the value for key. * * @param {string} [key] key to get value of * @param {object} [options] get options + * @param {boolean} [options.plain=false] If set to true, included instances will be returned as plain objects + * @param {boolean} [options.raw=false] If set to true, field and virtual setters will be ignored * * @returns {object|any} */ @@ -3551,11 +3556,9 @@ export class Model { if (Array.isArray(this.dataValues[key])) { return this.dataValues[key].map(instance => instance.get(options)); } - if (this.dataValues[key] instanceof Model) { return this.dataValues[key].get(options); } - return this.dataValues[key]; } @@ -3601,14 +3604,12 @@ export class Model { } /** - * Set is used to update values on the instance (the Sequelize representation of the instance that is, remember that - * nothing will be persisted before you actually call `save`). In its most basic form `set` will update a value stored in - * the underlying `dataValues` object. However, if a custom setter function is defined for the key, that function will be - * called instead. To bypass the setter, you can pass `raw: true` in the options object. + * Set is used to update values on the instance (the sequelize representation of the instance that is, remember that nothing will be persisted before you actually call `save`). + * In its most basic form `set` will update a value stored in the underlying `dataValues` object. However, if a custom setter function is defined for the key, that function + * will be called instead. To bypass the setter, you can pass `raw: true` in the options object. * - * If set is called with an object, it will loop over the object, and call set recursively for each key, value pair. If - * you set raw to true, the underlying dataValues will either be set directly to the object passed, or used to extend - * dataValues, if dataValues already contain values. + * If set is called with an object, it will loop over the object, and call set recursively for each key, value pair. If you set raw to true, the underlying dataValues will either be + * set directly to the object passed, or used to extend dataValues, if dataValues already contain values. * * When set is called, the previous value of the field is stored and sets a changed flag(see `changed`). * @@ -3616,13 +3617,16 @@ export class Model { * When using set with associations you need to make sure the property key matches the alias of the association * while also making sure that the proper include options have been set (from .build() or .findOne()) * - * If called with a dot.separated key on a JSON/JSONB attribute it will set the value nested and flag the entire object as - * changed. + * If called with a dot.separated key on a JSON/JSONB attribute it will set the value nested and flag the entire object as changed. + * + * @see + * {@link Model.findAll} for more information about includes * - * @param {string|object} key key to set, it can be string or object. When string it will set that key, for object it will - * loop over all object properties nd set them. + * @param {string|object} key key to set, it can be string or object. When string it will set that key, for object it will loop over all object properties nd set them. * @param {any} value value to set * @param {object} [options] set options + * @param {boolean} [options.raw=false] If set to true, field and virtual setters will be ignored + * @param {boolean} [options.reset=false] Clear all previously set data values * * @returns {Model} */ @@ -3643,12 +3647,11 @@ export class Model { // If raw, and we're not dealing with includes or special attributes, just set it straight on the dataValues object if (options.raw && !(this._options && this._options.include) && !(options && options.attributes) && !this.constructor._hasDateAttributes && !this.constructor._hasBooleanAttributes) { - if (Object.keys(this.dataValues).length > 0) { + if (Object.keys(this.dataValues).length) { Object.assign(this.dataValues, values); } else { this.dataValues = values; } - // If raw, .changed() shouldn't be true this._previousDataValues = { ...this.dataValues }; } else { @@ -3659,16 +3662,13 @@ export class Model { if (values[k] === undefined) { continue; } - this.set(k, values[k], options); } }; - setKeys(options.attributes); if (this.constructor._hasVirtualAttributes) { setKeys(this.constructor._virtualAttributes); } - if (this._options.includeNames) { setKeys(this._options.includeNames); } @@ -3683,14 +3683,10 @@ export class Model { this._previousDataValues = { ...this.dataValues }; } } - return this; } - - if (!options) { + if (!options) options = {}; - } - if (!options.raw) { originalValue = this.dataValues[key]; } @@ -3710,10 +3706,8 @@ export class Model { if (this._options && this._options.include && this._options.includeNames.includes(key)) { // Pass it on to the include handler this._setInclude(key, value, options); - return this; } - // Bunch of stuff we won't do when it's raw if (!options.raw) { // If attribute is not in model definition, return @@ -3725,7 +3719,6 @@ export class Model { this.changed(key.split('.')[0], true); } } - return this; } @@ -3750,13 +3743,13 @@ export class Model { // Set when the value has changed and not raw if ( - !options.raw - && ( + !options.raw && + ( // True when sequelize method - value instanceof Utils.SequelizeMethod + value instanceof Utils.SequelizeMethod || // Check for data type type comparators - || !(value instanceof Utils.SequelizeMethod) && this.constructor._dataTypeChanges[key] && this.constructor._dataTypeChanges[key].call(this, value, originalValue, options) // Check default - || !this.constructor._dataTypeChanges[key] && !_.isEqual(value, originalValue) + !(value instanceof Utils.SequelizeMethod) && this.constructor._dataTypeChanges[key] && this.constructor._dataTypeChanges[key].call(this, value, originalValue, options) || // Check default + !this.constructor._dataTypeChanges[key] && !_.isEqual(value, originalValue) ) ) { this._previousDataValues[key] = originalValue; @@ -3766,7 +3759,6 @@ export class Model { // set data value this.dataValues[key] = value; } - return this; } @@ -3775,8 +3767,7 @@ export class Model { } /** - * If changed is called with a string it will return a boolean indicating whether the value of that key in `dataValues` is - * different from the value in `_previousDataValues`. + * If changed is called with a string it will return a boolean indicating whether the value of that key in `dataValues` is different from the value in `_previousDataValues`. * * If changed is called without an argument, it will return an array of keys that have changed. * @@ -3805,24 +3796,18 @@ export class Model { changed(key, value) { if (key === undefined) { if (this._changed.size > 0) { - return [...this._changed]; + return Array.from(this._changed); } - return false; } - if (value === true) { this._changed.add(key); - return this; } - if (value === false) { this._changed.delete(key); - return this; } - return this._changed.has(key); } @@ -3844,10 +3829,7 @@ export class Model { } _setInclude(key, value, options) { - if (!Array.isArray(value)) { - value = [value]; - } - + if (!Array.isArray(value)) value = [value]; if (value[0] instanceof Model) { value = value.map(instance => instance.dataValues); } @@ -3863,16 +3845,15 @@ export class Model { includeMap: include.includeMap, includeValidated: true, raw: options.raw, - attributes: include.originalAttributes, + attributes: include.originalAttributes }; let isEmpty; - if (include.originalAttributes === undefined || include.originalAttributes.length > 0) { + if (include.originalAttributes === undefined || include.originalAttributes.length) { if (association.isSingleAssociation) { if (Array.isArray(value)) { value = value[0]; } - isEmpty = value && value[primaryKeyAttribute] === null || value === null; this[accessor] = this.dataValues[accessor] = isEmpty ? null : include.model.build(value, childOptions); } else { @@ -3885,17 +3866,22 @@ export class Model { /** * Validates this instance, and if the validation passes, persists it to the database. * - * Returns a Promise that resolves to the saved instance (or rejects with a {@link ValidationError}, - * which will have a property for each of the fields for which the validation failed, with the error message for that field). + * Returns a Promise that resolves to the saved instance (or rejects with a `Sequelize.ValidationError`, which will have a property for each of the fields for which the validation failed, with the error message for that field). + * + * This method is optimized to perform an UPDATE only into the fields that changed. If nothing has changed, no SQL query will be performed. * - * This method is optimized to perform an UPDATE only into the fields that changed. - * If nothing has changed, no SQL query will be performed. + * This method is not aware of eager loaded associations. In other words, if some other model instance (child) was eager loaded with this instance (parent), and you change something in the child, calling `save()` will simply ignore the change that happened on the child. * - * This method is not aware of eager loaded associations. - * In other words, if some other model instance (child) was eager loaded with this instance (parent), - * and you change something in the child, calling `save()` will simply ignore the change that happened on the child. + * @param {object} [options] save options + * @param {string[]} [options.fields] An optional array of strings, representing database columns. If fields is provided, only those columns will be validated and saved. + * @param {boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated. + * @param {boolean} [options.validate=true] If false, validations won't be run. + * @param {boolean} [options.hooks=true] Run before and after create / update + validate hooks + * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql. + * @param {Transaction} [options.transaction] Transaction to run query under + * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only) + * @param {boolean} [options.returning] Append RETURNING * to get back auto generated values (Postgres only) * - * @param {object} [options] save options * @returns {Promise} */ async save(options) { @@ -3906,7 +3892,7 @@ export class Model { options = Utils.cloneDeep(options); options = _.defaults(options, { hooks: true, - validate: true, + validate: true }); if (!options.fields) { @@ -3939,7 +3925,6 @@ export class Model { if (updatedAtAttr && options.fields.length > 0 && !options.fields.includes(updatedAtAttr)) { options.fields.push(updatedAtAttr); } - if (versionAttr && options.fields.length > 0 && !options.fields.includes(versionAttr)) { options.fields.push(versionAttr); } @@ -3960,8 +3945,10 @@ export class Model { } } - if (this.isNewRecord === false && primaryKeyName && this.get(primaryKeyName, { raw: true }) === undefined) { - throw new Error('You attempted to save an instance with no primary key, this is not allowed since it would result in a global update'); + if (this.isNewRecord === false) { + if (primaryKeyName && this.get(primaryKeyName, { raw: true }) === undefined) { + throw new Error('You attempted to save an instance with no primary key, this is not allowed since it would result in a global update'); + } } if (updatedAtAttr && !options.silent && options.fields.includes(updatedAtAttr)) { @@ -3971,20 +3958,16 @@ export class Model { if (this.isNewRecord && createdAtAttr && !this.dataValues[createdAtAttr]) { this.dataValues[createdAtAttr] = this.constructor._getDefaultTimestamp(createdAtAttr) || now; } - // Db2 does not allow NULL values for unique columns. // Add dummy values if not provided by test case or user. if (this.sequelize.options.dialect === 'db2' && this.isNewRecord) { this.uniqno = this.sequelize.dialect.queryGenerator.addUniqueFields( - this.dataValues, this.constructor.rawAttributes, this.uniqno, - ); + this.dataValues, this.constructor.rawAttributes, this.uniqno); } - // Validate if (options.validate) { await this.validate(options); } - // Run before hook if (options.hooks) { const beforeHookValues = _.pick(this.dataValues, options.fields); @@ -4010,45 +3993,37 @@ export class Model { options.fields = _.uniq(options.fields.concat(hookChanged)); } - if (hookChanged && options.validate) { - // Validate again + if (hookChanged) { + if (options.validate) { + // Validate again - options.skip = _.difference(Object.keys(this.constructor.rawAttributes), hookChanged); - await this.validate(options); - delete options.skip; + options.skip = _.difference(Object.keys(this.constructor.rawAttributes), hookChanged); + await this.validate(options); + delete options.skip; + } } } - - if (options.fields.length > 0 && this.isNewRecord && this._options.include && this._options.include.length > 0) { + if (options.fields.length && this.isNewRecord && this._options.include && this._options.include.length) { await Promise.all(this._options.include.filter(include => include.association instanceof BelongsTo).map(async include => { const instance = this.get(include.as); - if (!instance) { - return; - } + if (!instance) return; const includeOptions = _(Utils.cloneDeep(include)) .omit(['association']) .defaults({ transaction: options.transaction, logging: options.logging, - parentRecord: this, - }) - .value(); + parentRecord: this + }).value(); await instance.save(includeOptions); await this[include.association.accessors.set](instance, { save: false, logging: options.logging }); })); } - const realFields = options.fields.filter(field => !this.constructor._virtualAttributes.has(field)); - if (realFields.length === 0) { - return this; - } - - if (!this.changed() && !this.isNewRecord) { - return this; - } + if (!realFields.length) return this; + if (!this.changed() && !this.isNewRecord) return this; const versionFieldName = _.get(this.constructor.rawAttributes[versionAttr], 'field') || versionAttr; const values = Utils.mapValueFieldNames(this.dataValues, options.fields, this.constructor); @@ -4062,9 +4037,8 @@ export class Model { } else { where = this.where(true); if (versionAttr) { - values[versionFieldName] = Number.parseInt(values[versionFieldName], 10) + 1; + values[versionFieldName] = parseInt(values[versionFieldName], 10) + 1; } - query = 'update'; args = [this, this.constructor.getTableName(options), values, where, options]; } @@ -4076,7 +4050,7 @@ export class Model { throw new sequelizeErrors.OptimisticLockError({ modelName: this.constructor.name, values, - where, + where }); } else { result.dataValues[versionAttr] = values[versionFieldName]; @@ -4085,40 +4059,33 @@ export class Model { // Transfer database generated values (defaults, autoincrement, etc) for (const attr of Object.keys(this.constructor.rawAttributes)) { - if (this.constructor.rawAttributes[attr].field - && values[this.constructor.rawAttributes[attr].field] !== undefined - && this.constructor.rawAttributes[attr].field !== attr + if (this.constructor.rawAttributes[attr].field && + values[this.constructor.rawAttributes[attr].field] !== undefined && + this.constructor.rawAttributes[attr].field !== attr ) { values[attr] = values[this.constructor.rawAttributes[attr].field]; delete values[this.constructor.rawAttributes[attr].field]; } } - Object.assign(values, result.dataValues); Object.assign(result.dataValues, values); - if (wasNewRecord && this._options.include && this._options.include.length > 0) { + if (wasNewRecord && this._options.include && this._options.include.length) { await Promise.all( - this._options.include.filter(include => !(include.association instanceof BelongsTo - || include.parent && include.parent.association instanceof BelongsToMany)).map(async include => { + this._options.include.filter(include => !(include.association instanceof BelongsTo || + include.parent && include.parent.association instanceof BelongsToMany)).map(async include => { let instances = this.get(include.as); - if (!instances) { - return; - } - - if (!Array.isArray(instances)) { - instances = [instances]; - } + if (!instances) return; + if (!Array.isArray(instances)) instances = [instances]; const includeOptions = _(Utils.cloneDeep(include)) .omit(['association']) .defaults({ transaction: options.transaction, logging: options.logging, - parentRecord: this, - }) - .value(); + parentRecord: this + }).value(); // Instances will be updated in place so we can safely treat HasOne like a HasMany await Promise.all(instances.map(async instance => { @@ -4128,18 +4095,17 @@ export class Model { [include.association.foreignKey]: this.get(this.constructor.primaryKeyAttribute, { raw: true }), [include.association.otherKey]: instance.get(instance.constructor.primaryKeyAttribute, { raw: true }), // Include values defined in the association - ...include.association.through.scope, + ...include.association.through.scope }; if (instance[include.association.through.model.name]) { for (const attr of Object.keys(include.association.through.model.rawAttributes)) { - if (include.association.through.model.rawAttributes[attr]._autoGenerated - || attr === include.association.foreignKey - || attr === include.association.otherKey - || typeof instance[include.association.through.model.name][attr] === 'undefined') { + if (include.association.through.model.rawAttributes[attr]._autoGenerated || + attr === include.association.foreignKey || + attr === include.association.otherKey || + typeof instance[include.association.through.model.name][attr] === undefined) { continue; } - values0[attr] = instance[include.association.through.model.name][attr]; } } @@ -4151,67 +4117,69 @@ export class Model { await instance.save(includeOptions); } })); - }), + }) ); } - // Run after hook if (options.hooks) { await this.constructor.runHooks(`after${hook}`, result, options); } - for (const field of options.fields) { result._previousDataValues[field] = result.dataValues[field]; this.changed(field, false); } - this.isNewRecord = false; return result; } /** - * Refreshes the current instance in-place, i.e. update the object with current data from the DB and return - * the same object. This is different from doing a `find(Instance.id)`, because that would create and - * return a new instance. With this method, all references to the Instance are updated with the new data - * and no new objects are created. + * Refresh the current instance in-place, i.e. update the object with current data from the DB and return the same object. + * This is different from doing a `find(Instance.id)`, because that would create and return a new instance. With this method, + * all references to the Instance are updated with the new data and no new objects are created. + * + * @see + * {@link Model.findAll} * * @param {object} [options] Options that are passed on to `Model.find` + * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql. * * @returns {Promise} */ async reload(options) { options = Utils.defaults({ - where: this.where(), + where: this.where() }, options, { - include: this._options.include || undefined, + include: this._options.include || undefined }); const reloaded = await this.constructor.findOne(options); if (!reloaded) { throw new sequelizeErrors.InstanceError( - 'Instance could not be reloaded because it does not exist anymore (find call returned null)', + 'Instance could not be reloaded because it does not exist anymore (find call returned null)' ); } - // update the internal options of the instance this._options = reloaded._options; // re-set instance values this.set(reloaded.dataValues, { raw: true, - reset: true && !options.attributes, + reset: true && !options.attributes }); return this; } /** - * Validate the attribute of this instance according to validation rules set in the model definition. - * - * Emits null if and only if validation successful; otherwise an Error instance containing - * { field name : [error msgs] } entries. + * Validate the attributes of this instance according to validation rules set in the model definition. + * + * The promise fulfills if and only if validation successful; otherwise it rejects an Error instance containing { field name : [error msgs] } entries. * * @param {object} [options] Options that are passed to the validator + * @param {Array} [options.skip] An array of strings. All properties that are in this array will not be validated + * @param {Array} [options.fields] An array of strings. Only the properties that are in this array will be validated + * @param {boolean} [options.hooks=true] Run before and after validate hooks + * * @returns {Promise} */ async validate(options) { @@ -4219,8 +4187,13 @@ export class Model { } /** - * This is the same as calling {@link Model#set} followed by calling {@link Model#save}, - * but it only saves attributes values passed to it, making it safer. + * This is the same as calling `set` and then calling `save` but it only saves the + * exact values passed to it, making it more atomic and safer. + * + * @see + * {@link Model#set} + * @see + * {@link Model#save} * * @param {object} values See `set` * @param {object} options See `save` @@ -4234,9 +4207,7 @@ export class Model { const changedBefore = this.changed() || []; options = options || {}; - if (Array.isArray(options)) { - options = { fields: options }; - } + if (Array.isArray(options)) options = { fields: options }; options = Utils.cloneDeep(options); const setOptions = Utils.cloneDeep(options); @@ -4256,24 +4227,27 @@ export class Model { } /** - * Destroys the row corresponding to this instance. Depending on your setting for paranoid, the row will either be - * completely deleted, or have its deletedAt timestamp set to the current time. + * Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will either be completely deleted, or have its deletedAt timestamp set to the current time. + * + * @param {object} [options={}] destroy options + * @param {boolean} [options.force=false] If set to true, paranoid models will actually be deleted + * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql. + * @param {Transaction} [options.transaction] Transaction to run query under + * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only) * - * @param {object} [options={}] destroy options * @returns {Promise} */ async destroy(options) { options = { hooks: true, force: false, - ...options, + ...options }; // Run before hook if (options.hooks) { await this.constructor.runHooks('beforeDestroy', this, options); } - const where = this.where(true); let result; @@ -4294,20 +4268,17 @@ export class Model { } else { result = await this.constructor.queryInterface.delete(this, this.constructor.getTableName(options), where, { type: QueryTypes.DELETE, limit: null, ...options }); } - // Run after hook if (options.hooks) { await this.constructor.runHooks('afterDestroy', this, options); } - return result; } /** - * Returns true if this instance is "soft deleted". - * Throws an error if {@link ModelOptions.paranoid} is not enabled. - * - * See {@link https://sequelize.org/docs/v7/core-concepts/paranoid/} to learn more about soft deletion / paranoid models. + * Helper method to determine if a instance is "soft deleted". This is + * particularly useful if the implementer renamed the `deletedAt` attribute + * to something different. This method requires `paranoid` to be enabled. * * @returns {boolean} */ @@ -4325,30 +4296,27 @@ export class Model { } /** - * Restores the row corresponding to this instance. - * Only available for paranoid models. - * - * See {@link https://sequelize.org/docs/v7/core-concepts/paranoid/} to learn more about soft deletion / paranoid models. + * Restore the row corresponding to this instance. Only available for paranoid models. * * @param {object} [options={}] restore options + * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql. + * @param {Transaction} [options.transaction] Transaction to run query under + * * @returns {Promise} */ async restore(options) { - if (!this.constructor._timestampAttributes.deletedAt) { - throw new Error('Model is not paranoid'); - } + if (!this.constructor._timestampAttributes.deletedAt) throw new Error('Model is not paranoid'); options = { hooks: true, force: false, - ...options, + ...options }; // Run before hook if (options.hooks) { await this.constructor.runHooks('beforeRestore', this, options); } - const deletedAtCol = this.constructor._timestampAttributes.deletedAt; const deletedAtAttribute = this.constructor.rawAttributes[deletedAtCol]; const deletedAtDefaultValue = Object.prototype.hasOwnProperty.call(deletedAtAttribute, 'defaultValue') ? deletedAtAttribute.defaultValue : null; @@ -4358,21 +4326,17 @@ export class Model { // Run after hook if (options.hooks) { await this.constructor.runHooks('afterRestore', this, options); - return result; } - return result; } /** - * Increment the value of one or more columns. This is done in the database, which means it does not use the values - * currently stored on the Instance. The increment is done using a + * Increment the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The increment is done using a * ```sql * SET column = column + X * ``` - * query. The updated instance will be returned by default in Postgres. However, in other dialects, you will need to do a - * reload to get the new values. + * query. The updated instance will be returned by default in Postgres. However, in other dialects, you will need to do a reload to get the new values. * * @example * instance.increment('number') // increment number by 1 @@ -4383,10 +4347,17 @@ export class Model { * // `by` is ignored, since each column has its own value * instance.increment({ answer: 42, tries: 1}, { by: 2 }) * - * @param {string|Array|object} fields If a string is provided, that column is incremented by the value of `by` given in - * options. If an array is provided, the same is true for each column. If and object is provided, each column is - * incremented by the value given. + * @see + * {@link Model#reload} + * + * @param {string|Array|object} fields If a string is provided, that column is incremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is incremented by the value given. * @param {object} [options] options + * @param {number} [options.by=1] The number to increment by + * @param {boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated. + * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql. + * @param {Transaction} [options.transaction] Transaction to run query under + * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only) + * @param {boolean} [options.returning=true] Append RETURNING * to get back auto generated values (Postgres only) * * @returns {Promise} * @since 4.0.0 @@ -4404,13 +4375,11 @@ export class Model { } /** - * Decrement the value of one or more columns. This is done in the database, which means it does not use the values - * currently stored on the Instance. The decrement is done using a + * Decrement the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The decrement is done using a * ```sql * SET column = column - X * ``` - * query. The updated instance will be returned by default in Postgres. However, in other dialects, you will need to do a - * reload to get the new values. + * query. The updated instance will be returned by default in Postgres. However, in other dialects, you will need to do a reload to get the new values. * * @example * instance.decrement('number') // decrement number by 1 @@ -4421,17 +4390,24 @@ export class Model { * // `by` is ignored, since each column has its own value * instance.decrement({ answer: 42, tries: 1}, { by: 2 }) * - * @param {string|Array|object} fields If a string is provided, that column is decremented by the value of `by` given in - * options. If an array is provided, the same is true for each column. If and object is provided, each column is - * decremented by the value given + * @see + * {@link Model#reload} + * @param {string|Array|object} fields If a string is provided, that column is decremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is decremented by the value given * @param {object} [options] decrement options + * @param {number} [options.by=1] The number to decrement by + * @param {boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated. + * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql. + * @param {Transaction} [options.transaction] Transaction to run query under + * @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only) + * @param {boolean} [options.returning=true] Append RETURNING * to get back auto generated values (Postgres only) + * * @returns {Promise} */ async decrement(fields, options) { return this.increment(fields, { by: 1, ...options, - increment: false, + increment: false }); } @@ -4482,138 +4458,111 @@ export class Model { toJSON() { return _.cloneDeep( this.get({ - plain: true, - }), + plain: true + }) ); } /** - * Defines a 1:n association between two models. - * The foreign key is added on the target model. - * - * See {@link https://sequelize.org/docs/v7/core-concepts/assocs/} to learn more about associations. + * Creates a 1:m association between this (the source) and the provided target. + * The foreign key is added on the target. + * + * @param {Model} target Target model + * @param {object} [options] hasMany association options + * @param {boolean} [options.hooks=false] Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks + * @param {string|object} [options.as] The alias of this model. If you provide a string, it should be plural, and will be singularized using node.inflection. If you want to control the singular version yourself, provide an object with `plural` and `singular` keys. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the pluralized name of target + * @param {string|object} [options.foreignKey] The name of the foreign key in the target table or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of source + primary key of source + * @param {string} [options.sourceKey] The name of the field to use as the key for the association in the source table. Defaults to the primary key of the source table + * @param {object} [options.scope] A key/value set that will be used for association create and find defaults on the target. (sqlite not supported for N:M) + * @param {string} [options.onDelete='SET NULL|CASCADE'] SET NULL if foreignKey allows nulls, CASCADE if otherwise + * @param {string} [options.onUpdate='CASCADE'] Set `ON UPDATE` + * @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key. + * + * @returns {HasMany} * * @example - * ```javascript - * Profile.hasMany(User) - * ``` - * - * @param {Model} target The model that will be associated with a hasMany relationship - * @param {object} options Options for the association - * @returns {HasMany} The newly defined association (also available in {@link Model.associations}). + * User.hasMany(Profile) // This will add userId to the profile table */ - static hasMany(target, options) {} + static hasMany(target, options) {} // eslint-disable-line /** * Create an N:M association with a join table. Defining `through` is required. - * The foreign keys are added on the through model. * - * See {@link https://sequelize.org/docs/v7/core-concepts/assocs/} to learn more about associations. + * @param {Model} target Target model + * @param {object} options belongsToMany association options + * @param {boolean} [options.hooks=false] Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks + * @param {Model|string|object} options.through The name of the table that is used to join source and target in n:m associations. Can also be a sequelize model if you want to define the junction table yourself and add extra attributes to it. + * @param {Model} [options.through.model] The model used to join both sides of the N:M association. + * @param {object} [options.through.scope] A key/value set that will be used for association create and find defaults on the through model. (Remember to add the attributes to the through model) + * @param {boolean} [options.through.unique=true] If true a unique key will be generated from the foreign keys used (might want to turn this off and create specific unique keys when using scopes) + * @param {string|object} [options.as] The alias of this association. If you provide a string, it should be plural, and will be singularized using node.inflection. If you want to control the singular version yourself, provide an object with `plural` and `singular` keys. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the pluralized name of target + * @param {string|object} [options.foreignKey] The name of the foreign key in the join table (representing the source model) or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of source + primary key of source + * @param {string|object} [options.otherKey] The name of the foreign key in the join table (representing the target model) or an object representing the type definition for the other column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of target + primary key of target + * @param {object} [options.scope] A key/value set that will be used for association create and find defaults on the target. (sqlite not supported for N:M) + * @param {boolean} [options.timestamps=sequelize.options.timestamps] Should the join model have timestamps + * @param {string} [options.onDelete='SET NULL|CASCADE'] Cascade if this is a n:m, and set null if it is a 1:m + * @param {string} [options.onUpdate='CASCADE'] Sets `ON UPDATE` + * @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key. + * + * @returns {BelongsToMany} * * @example - * ```javascript * // Automagically generated join model * User.belongsToMany(Project, { through: 'UserProjects' }) + * Project.belongsToMany(User, { through: 'UserProjects' }) * * // Join model with additional attributes * const UserProjects = sequelize.define('UserProjects', { * started: Sequelize.BOOLEAN * }) * User.belongsToMany(Project, { through: UserProjects }) - * ``` - * - * @param {Model} target Target model - * @param {object} options belongsToMany association options - * @returns {BelongsToMany} The newly defined association (also available in {@link Model.associations}). + * Project.belongsToMany(User, { through: UserProjects }) */ - static belongsToMany(target, options) {} + static belongsToMany(target, options) {} // eslint-disable-line /** - * Creates a 1:1 association between this model (the source) and the provided target. - * The foreign key is added on the target model. + * Creates an association between this (the source) and the provided target. The foreign key is added on the target. * - * See {@link https://sequelize.org/docs/v7/core-concepts/assocs/} to learn more about associations. + * @param {Model} target Target model + * @param {object} [options] hasOne association options + * @param {boolean} [options.hooks=false] Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks + * @param {string} [options.as] The alias of this model, in singular form. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the singularized name of target + * @param {string|object} [options.foreignKey] The name of the foreign key attribute in the target model or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of source + primary key of source + * @param {string} [options.sourceKey] The name of the attribute to use as the key for the association in the source table. Defaults to the primary key of the source table + * @param {string} [options.onDelete='SET NULL|CASCADE'] SET NULL if foreignKey allows nulls, CASCADE if otherwise + * @param {string} [options.onUpdate='CASCADE'] Sets 'ON UPDATE' + * @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key. + * @param {string} [options.uniqueKey] The custom name for unique constraint. * - * @example - * ```javascript - * User.hasOne(Profile) - * ``` + * @returns {HasOne} * - * @param {Model} target The model that will be associated with hasOne relationship - * @param {object} [options] hasOne association options - * @returns {HasOne} The newly defined association (also available in {@link Model.associations}). + * @example + * User.hasOne(Profile) // This will add userId to the profile table */ - static hasOne(target, options) {} + static hasOne(target, options) {} // eslint-disable-line /** - * Creates an association between this (the source) and the provided target. - * The foreign key is added on the source Model. + * Creates an association between this (the source) and the provided target. The foreign key is added on the source. * - * See {@link https://sequelize.org/docs/v7/core-concepts/assocs/} to learn more about associations. + * @param {Model} target The target model + * @param {object} [options] belongsTo association options + * @param {boolean} [options.hooks=false] Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks + * @param {string} [options.as] The alias of this model, in singular form. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the association, you should provide the same alias when eager loading and when getting associated models. Defaults to the singularized name of target + * @param {string|object} [options.foreignKey] The name of the foreign key attribute in the source table or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of target + primary key of target + * @param {string} [options.targetKey] The name of the attribute to use as the key for the association in the target table. Defaults to the primary key of the target table + * @param {string} [options.onDelete='SET NULL|NO ACTION'] SET NULL if foreignKey allows nulls, NO ACTION if otherwise + * @param {string} [options.onUpdate='CASCADE'] Sets 'ON UPDATE' + * @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key. * - * @example - * ```javascript - * Profile.belongsTo(User) - * ``` + * @returns {BelongsTo} * - * @param {Model} target The target model - * @param {object} [options] belongsTo association options - * @returns {BelongsTo} The newly defined association (also available in {@link Model.associations}). + * @example + * Profile.belongsTo(User) // This will add userId to the profile table */ - static belongsTo(target, options) {} -} - -/** - * Unpacks an object that only contains a single Op.and key to the value of Op.and - * - * Internal method used by {@link combineWheresWithAnd} - * - * @param {WhereOptions} where The object to unpack - * @example `{ [Op.and]: [a, b] }` becomes `[a, b]` - * @example `{ [Op.and]: { key: val } }` becomes `{ key: val }` - * @example `{ [Op.or]: [a, b] }` remains as `{ [Op.or]: [a, b] }` - * @example `{ [Op.and]: [a, b], key: c }` remains as `{ [Op.and]: [a, b], key: c }` - * @private - */ -function unpackAnd(where) { - if (!_.isObject(where)) { - return where; - } - - const keys = Utils.getComplexKeys(where); - - // object is empty, remove it. - if (keys.length === 0) { - return; - } - - // we have more than just Op.and, keep as-is - if (keys.length !== 1 || keys[0] !== Op.and) { - return where; - } - - const andParts = where[Op.and]; - - return andParts; -} - -function combineWheresWithAnd(whereA, whereB) { - const unpackedA = unpackAnd(whereA); - - if (unpackedA === undefined) { - return whereB; - } - - const unpackedB = unpackAnd(whereB); - - if (unpackedB === undefined) { - return whereA; - } - - return { - [Op.and]: [unpackedA, unpackedB].flat(), - }; + static belongsTo(target, options) {} // eslint-disable-line } Object.assign(Model, associationsMixin); Hooks.applyTo(Model, true); + +module.exports = Model; diff --git a/test/unit/model/find-by-pk.test.js b/test/unit/model/find-by-pk.test.js deleted file mode 100644 index d87dfa0399e7..000000000000 --- a/test/unit/model/find-by-pk.test.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -const chai = require('chai'); - -const expect = chai.expect; -const Support = require('../support'); - -const Sequelize = Support.Sequelize; -const Op = Sequelize.Op; -const current = Support.sequelize; -const sinon = require('sinon'); -const DataTypes = require('../../../lib/data-types'); - -describe(Support.getTestDialectTeaser('Model'), () => { - describe('method findByPk', () => { - beforeEach(function () { - this.stub = sinon.stub(Sequelize.Model, 'findAll').resolves(); - }); - afterEach(() => { - sinon.restore(); - }); - - it('should call internal findOne() method if findOne() is overridden', async () => { - const Model = current.define('model', { - unique1: { - type: DataTypes.INTEGER, - unique: 'unique', - }, - unique2: { - type: DataTypes.INTEGER, - unique: 'unique', - }, - }); - Model.findOne = sinon.stub(); - sinon.spy(Sequelize.Model, 'findOne'); - - await Model.findByPk(1); - Model.findOne.should.not.have.been.called; - Sequelize.Model.findOne.should.have.been.called; - }); - }); -}); diff --git a/test/unit/model/find-one.test.js b/test/unit/model/find-one.test.js index 2daa22f50793..26b10b90b694 100644 --- a/test/unit/model/find-one.test.js +++ b/test/unit/model/find-one.test.js @@ -105,39 +105,5 @@ describe(Support.getTestDialectTeaser('Model'), () => { await Model.findOne({ where: { unique1: 42 } }); expect(this.stub.getCall(0).args[0]).to.be.an('object').to.have.property('limit'); }); - it('should call internal findAll() method if findOne() is overridden', async () => { - const Model = current.define('model', { - unique1: { - type: DataTypes.INTEGER, - unique: 'unique', - }, - unique2: { - type: DataTypes.INTEGER, - unique: 'unique', - }, - }); - Model.findAll = sinon.stub(); - - await Model.findOne(); - Model.findAll.should.not.have.been.called; - Sequelize.Model.findAll.should.have.been.called; - }); - it('should call internal findAll() method if findOne() is overridden', async () => { - const Model = current.define('model', { - unique1: { - type: DataTypes.INTEGER, - unique: 'unique', - }, - unique2: { - type: DataTypes.INTEGER, - unique: 'unique', - }, - }); - Model.findAll = sinon.stub(); - - await Model.findOne(); - Model.findAll.should.not.have.been.called; - Sequelize.Model.findAll.should.have.been.called; - }); }); });