@@ -357,12 +357,15 @@ class BelongsToMany extends Association {
/**
* Get everything currently associated with this, using an optional where clause.
*
* @param {Object} [options]
* @param {Object} [options.where] An optional where clause to limit the associated models
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {String} [options.schema] Apply a schema on the related model
* @see {@link Model.findAll} for a full explanation of options
* @return {Promise<Array<Model>>}
*
* @param {<Model>} instance instance
* @param {Object} [options] find options
* @param {Object} [options.where] An optional where clause to limit the associated models
* @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {string} [options.schema] Apply a schema on the related model
*
* @returns {Promise<Array<<Model>>>}
*/
get(instance,options){
options=Utils.cloneDeep(options)||{};
...
...
@@ -426,10 +429,12 @@ class BelongsToMany extends Association {
/**
* Count everything currently associated with this, using an optional where clause.
*
* @param {Object} [options]
* @param {<Model>} instance instance
* @param {Object} [options] find options
* @param {Object} [options.where] An optional where clause to limit the associated models
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @return {Promise<Integer>}
* @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
*
* @returns {Promise<number>}
*/
count(instance,options){
constassociation=this;
...
...
@@ -450,9 +455,11 @@ class BelongsToMany extends Association {
/**
* Check if one or more instance(s) are associated with this. If a list of instances is passed, the function returns true if _all_ instances are associated
*
* @param {Model[]|Model|string[]|String|number[]|Number} [instance(s)] Can be an array of instances or their primary keys
* @param {<Model>} sourceInstance source instance to associate new instances with
* @param {<Model>|<Model>[]|string[]|string|number[]|number} [instances] Can be an array of instances or their primary keys
* @param {Object} [options] Options passed to getAssociations
* @return {Promise<boolean>}
*
* @returns {Promise<boolean>}
*/
has(sourceInstance,instances,options){
constassociation=this;
...
...
@@ -489,13 +496,16 @@ class BelongsToMany extends Association {
}
/**
* Set the associated models by passing an array of instances or their primary keys. Everything that it not in the passed array will be un-associated.
* Set the associated models by passing an array of instances or their primary keys.
* Everything that it not in the passed array will be un-associated.
*
* @param {Array<Model|String|Number>} [newAssociations] An array of persisted instances or primary key of instances to associate with this. Pass `null` or `undefined` to remove all associations.
* @param {<Model>} sourceInstance source instance to associate new instances with
* @param {<Model>|<Model>[]|string[]|string|number[]|number} [newAssociatedObjects] A single instance or primary key, or a mixed array of persisted instances or primary keys
* @param {Object} [options] Options passed to `through.findAll`, `bulkCreate`, `update` and `destroy`
* @param {Object} [options.validate] Run validation for the join model
* @param {Object} [options.through] Additional attributes for the join table.
* @return {Promise}
*
* @returns {Promise}
*/
set(sourceInstance,newAssociatedObjects,options){
options=options||{};
...
...
@@ -590,13 +600,16 @@ class BelongsToMany extends Association {
}
/**
* Associate one ore several rows with `this`.
* Associate one ore several rows with source instance. It will not un-associate any already assoicated instance
* that may be missing from `newInstances`.
*
* @param {Model[]|Model|string[]|string|number[]|Number} [newAssociation(s)] A single instance or primary key, or a mixed array of persisted instances or primary keys
* @param {<Model>} sourceInstance source instance to associate new instances with
* @param {<Model>|<Model>[]|string[]|string|number[]|number} [newInstances] A single instance or primary key, or a mixed array of persisted instances or primary keys
* @param {Object} [options] Options passed to `through.findAll`, `bulkCreate` and `update`
* @param {Object} [options.validate] Run validation for the join model.
* @param {Object} [options.through] Additional attributes for the join table.
* @return {Promise}
*
* @returns {Promise}
*/
add(sourceInstance,newInstances,options){
// If newInstances is null or undefined, no-op
...
...
@@ -684,9 +697,11 @@ class BelongsToMany extends Association {
/**
* Un-associate one or more instance(s).
*
* @param {Model|String|Number} [oldAssociated] Can be an Instance or its primary key, or a mixed array of instances and primary keys
* @param {<Model>} sourceInstance instance to un associate instances with
* @param {<Model>|<Model>[]|string|string[]|number|number[]} [oldAssociatedObjects] Can be an Instance or its primary key, or a mixed array of instances and primary keys
* @param {Object} [options] Options passed to `through.destroy`
* @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false.
* @param {string} [options.schema] Apply a schema on the related model
*
* @see {@link Model.findOne} for a full explanation of options
*
* @return {Promise<Model>}
* @returns {Promise<<Model>>}
*/
get(instances,options){
constwhere={};
...
...
@@ -183,11 +184,12 @@ class BelongsTo extends Association {
/**
* Set the associated model.
*
* @param {Model|String|Number} [newAssociation] An persisted instance or the primary key of an instance to associate with this. Pass `null` or `undefined` to remove the association.
* @param {Object} [options] Options passed to `this.save`
* @param {Boolean} [options.save=true] Skip saving this after setting the foreign key if false.
* @param {<Model>} sourceInstance the source instance
* @param {?<Model>|string|number} [associatedInstance] An persisted instance or the primary key of an instance to associate with this. Pass `null` or `undefined` to remove the association.
* @param {Object} [options={}] options passed to `this.save`
* @param {boolean} [options.save=true] Skip saving this after setting the foreign key if false.
* @param {<Model>} sourceInstance the source instance
* @param {<Model>|<Model>[]|string[]|string|number[]|number} [targetInstances] Can be an array of instances or their primary keys
* @param {Object} [options] Options passed to getAssociations
*
* @return {Promise}
* @returns {Promise}
*/
has(sourceInstance,targetInstances,options){
constwhere={};
...
...
@@ -305,10 +310,12 @@ class HasMany extends Association {
/**
* Set the associated models by passing an array of persisted instances or their primary keys. Everything that is not in the passed array will be un-associated
*
* @param {Array<Model|String|Number>} [newAssociations] An array of persisted instances or primary key of instances to associate with this. Pass `null` or `undefined` to remove all associations.
* @param {<Model>} sourceInstance source instance to associate new instances with
* @param {<Model>|<Model>[]|string[]|string|number[]|number} [targetInstances] An array of persisted instances or primary key of instances to associate with this. Pass `null` or `undefined` to remove all associations.
* @param {Object} [options] Options passed to `target.findAll` and `update`.
* @param {Object} [options.validate] Run validation for the join model
* @return {Promise}
*
* @returns {Promise}
*/
set(sourceInstance,targetInstances,options){
if(targetInstances===null){
...
...
@@ -377,9 +384,11 @@ class HasMany extends Association {
* Associate one or more target rows with `this`. This method accepts a Model / string / number to associate a single row,
* or a mixed array of Model / string / numbers to associate multiple rows.
* @param {<Model>} sourceInstance the source instance
* @param {<Model>|<Model>[]|string[]|string|number[]|number} [targetInstances] A single instance or primary key, or a mixed array of persisted instances or primary keys
* @param {Object} [options] Options passed to `target.update`.
* @param {<Model>} sourceInstance instance to un associate instances with
* @param {<Model>|<Model>[]|string|string[]|number|number[]} [targetInstances] Can be an Instance or its primary key, or a mixed array of instances and primary keys
* @param {Object} [options] Options passed to `target.update`
* @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {string} [options.schema] Apply a schema on the related model
*
* @see {@link Model.findOne} for a full explanation of options
* @return {Promise<Model>}
*
* @returns {Promise<Model>}
*/
get(instances,options){
constwhere={};
...
...
@@ -180,10 +183,11 @@ class HasOne extends Association {
/**
* Set the associated model.
*
* @param {Model|String|Number} [associatedInstance] An persisted instance or the primary key of a persisted instance to associate with this. Pass `null` or `undefined` to remove the association.
* @param {<Model>} sourceInstance the source instance
* @param {?<Model>|string|number} [associatedInstance] An persisted instance or the primary key of an instance to associate with this. Pass `null` or `undefined` to remove the association.
* @param {Object} [options] Options passed to getAssociation and `target.save`
*
* @return {Promise}
* @returns {Promise}
*/
set(sourceInstance,associatedInstance,options){
letalreadyAssociated;
...
...
@@ -229,12 +233,13 @@ class HasOne extends Association {
/**
* Create a new instance of the associated model and associate it with this.
*
* @param {Object} [values]
* @param {<Model>} sourceInstance the source instance
* @param {Object} [values={}] values to create associated model instance with
* @param {Object} [options] Options passed to `target.create` and setAssociation.
*
* @see {@link Model#create} for a full explanation of options
@@ -605,6 +765,12 @@ RANGE.prototype.validate = function validate(value) {
returntrue;
};
/**
* A column storing a unique universal identifier.
* Use with `UUIDV1` or `UUIDV4` for default values.
*
* @namespace DataTypes.UUID
*/
functionUUID(){
if(!(thisinstanceofUUID))returnnewUUID();
}
...
...
@@ -619,6 +785,11 @@ UUID.prototype.validate = function validate(value, options) {
returntrue;
};
/**
* A default unique universal identifier generated following the UUID v1 standard
*
* @namespace DataTypes.UUIDV1
*/
functionUUIDV1(){
if(!(thisinstanceofUUIDV1))returnnewUUIDV1();
}
...
...
@@ -633,6 +804,11 @@ UUIDV1.prototype.validate = function validate(value, options) {
returntrue;
};
/**
* A default unique universal identifier generated following the UUID v4 standard
*
* @namespace DataTypes.UUIDV4
*/
functionUUIDV4(){
if(!(thisinstanceofUUIDV4))returnnewUUIDV4();
}
...
...
@@ -647,6 +823,51 @@ UUIDV4.prototype.validate = function validate(value, options) {
returntrue;
};
/**
* A virtual value that is not stored in the DB. This could for example be useful if you want to provide a default value in your model that is returned to the user but not stored in the DB.
*
* You could also use it to validate a value before permuting and storing it. VIRTUAL also takes a return type and dependency fields as arguments
* If a virtual attribute is present in `attributes` it will automatically pull in the extra fields as well.
* Return type is mostly useful for setups that rely on types like GraphQL.
*
* @example <caption>Checking password length before hashing it</caption>
* sequelize.define('user', {
* password_hash: DataTypes.STRING,
* password: {
* type: DataTypes.VIRTUAL,
* set: function (val) {
* // Remember to set the data value, otherwise it won't be validated
* A geography datatype represents two dimensional spacial objects in an elliptic coord system.
*
* __The difference from geometry and geography type:__
*
* PostGIS 1.5 introduced a new spatial type called geography, which uses geodetic measurement instead of Cartesian measurement.
* Coordinate points in the geography type are always represented in WGS 84 lon lat degrees (SRID 4326),
* but measurement functions and relationships ST_Distance, ST_DWithin, ST_Length, and ST_Area always return answers in meters or assume inputs in meters.
*
* __What is best to use? It depends:__
*
* When choosing between the geometry and geography type for data storage, you should consider what you’ll be using it for.
* If all you do are simple measurements and relationship checks on your data, and your data covers a fairly large area, then most likely you’ll be better off storing your data using the new geography type.
* Although the new geography data type can cover the globe, the geometry type is far from obsolete.
* The geometry type has a much richer set of functions than geography, relationship checks are generally faster, and it has wider support currently across desktop and web-mapping tools
*
* @example <caption>Defining a Geography type attribute</caption>
* The cidr type holds an IPv4 or IPv6 network specification. Takes 7 or 19 bytes.
*
* Only available for Postgres
*
* @namespace DataTypes.CIDR
*/
functionCIDR(){
if(!(thisinstanceofCIDR))returnnewCIDR();
}
...
...
@@ -758,6 +1087,13 @@ CIDR.prototype.validate = function validate(value) {
returntrue;
};
/**
* The INET type holds an IPv4 or IPv6 host address, and optionally its subnet. Takes 7 or 19 bytes
*
* Only available for Postgres
*
* @namespace DataTypes.INET
*/
functionINET(){
if(!(thisinstanceofINET))returnnewINET();
}
...
...
@@ -773,6 +1109,13 @@ INET.prototype.validate = function validate(value) {
returntrue;
};
/**
* The MACADDR type stores MAC addresses. Takes 6 bytes
*
* Only available for Postgres
*
* @namespace DataTypes.MACADDR
*/
functionMACADDR(){
if(!(thisinstanceofMACADDR))returnnewMACADDR();
}
...
...
@@ -813,7 +1156,7 @@ for (const helper of Object.keys(helpers)) {
}
/**
* A convenience class holding commonly used data types. The datatypes are used when defining a new model using `Sequelize.define`, like this:
* A convenience class holding commonly used data types. The datatypes are used when defining a new model using `Sequelize.define`, like this:
* ```js
* sequelize.define('model', {
* column: DataTypes.INTEGER
...
...
@@ -831,7 +1174,6 @@ for (const helper of Object.keys(helpers)) {
* * All number types (`INTEGER`, `BIGINT`, `FLOAT`, `DOUBLE`, `REAL`, `DECIMAL`) expose the properties `UNSIGNED` and `ZEROFILL`
* * The `CHAR` and `STRING` types expose the `BINARY` property
*
*
* Three of the values provided here (`NOW`, `UUIDV1` and `UUIDV4`) are special default values, that should not be used to define types. Instead they are used as shorthands for
* defining default values. For example, to get a uuid field with a default value generated following v1 of the UUID standard:
* ```js`
...
...
@@ -858,109 +1200,7 @@ for (const helper of Object.keys(helpers)) {
* })
* ```
*
* @property {function(length=255: integer)} STRING A variable length string
* @property {function(length=255: integer)} CHAR A fixed length string.
* @property {function(length: string)} TEXT An unlimited length text column. Available lengths: `tiny`, `medium`, `long`
* @property {function(length: integer)} TINYINT A 8 bit integer.
* @property {function(length: integer)} SMALLINT A 16 bit integer.
* @property {function(length: integer)} MEDIUMINT A 24 bit integer.
* @property {function(length=255: integer)} INTEGER A 32 bit integer.
* @property {function(length: integer)} BIGINT A 64 bit integer. Note: an attribute defined as `BIGINT` will be treated like a `string` due this [feature from node-postgres](https://github.com/brianc/node-postgres/pull/353) to prevent precision loss. To have this attribute as a `number`, this is a possible [workaround](https://github.com/sequelize/sequelize/issues/2383#issuecomment-58006083).
* @property {function(length: integer, decimals: integer)} FLOAT Floating point number (4-byte precision).
* @property {function(length: integer, decimals: integer)} DOUBLE Floating point number (8-byte precision).
* @property {function(values: string[])} ENUM An enumeration. `DataTypes.ENUM('value', 'another value')`.
* @property {function(length: integer)} DATE A datetime column
* @property {function} DATEONLY A date only column (no timestamp)
* @property {function} TIME A time column
* @property {function} NOW A default value of the current timestamp
* @property {function} UUID A column storing a unique universal identifier. Use with `UUIDV1` or `UUIDV4` for default values.
* @property {function} UUIDV1 A default unique universal identifier generated following the UUID v1 standard
* @property {function} UUIDV4 A default unique universal identifier generated following the UUID v4 standard
* @property {function} HSTORE A key / value store column. Only available in Postgres.
* @property {function} JSON A JSON string column. Available in MySQL, Postgres and SQLite
* @property {function} JSONB A binary storage JSON column. Only available in Postgres.
* @property {function(type: DataTypes)} ARRAY An array of `type`, e.g. `DataTypes.ARRAY(DataTypes.DECIMAL)`. Only available in Postgres.
* @property {function(type: DataTypes)} RANGE Range types are data types representing a range of values of some element type (called the range's subtype).
* Only available in Postgres. See [the Postgres documentation](http://www.postgresql.org/docs/9.4/static/rangetypes.html) for more details
* @property {function(type: string, srid: string)} GEOMETRY A column storing Geometry information. It is only available in PostgreSQL (with PostGIS) or MySQL.
* In MySQL, allowable Geometry types are `POINT`, `LINESTRING`, `POLYGON`.
*
* GeoJSON is accepted as input and returned as output.
* In PostGIS, the GeoJSON is parsed using the PostGIS function `ST_GeomFromGeoJSON`.
* In MySQL it is parsed using the function `GeomFromText`.
* Therefore, one can just follow the [GeoJSON spec](http://geojson.org/geojson-spec.html) for handling geometry objects. See the following examples:
*
* ```js
* // Create a new point:
* const point = { type: 'Point', coordinates: [39.807222,-76.984722]};
*
* User.create({username: 'username', geometry: point });
* User.create({username: 'username', geometry: point })
* ```
* @property {function(type: string, srid: string)} GEOGRAPHY A geography datatype represents two dimensional spacial objects in an elliptic coord system.
* @property {function(returnType: DataTypes, fields: string[])} VIRTUAL A virtual value that is not stored in the DB. This could for example be useful if you want to provide a default value in your model that is returned to the user but not stored in the DB.
*
* You could also use it to validate a value before permuting and storing it. Checking password length before hashing it for example:
* ```js
* sequelize.define('user', {
* password_hash: DataTypes.STRING,
* password: {
* type: DataTypes.VIRTUAL,
* set: function (val) {
* // Remember to set the data value, otherwise it won't be validated
* An enum that defines valid ValidationErrorItem `origin` values
*
* @type {Object}
* @property CORE {String} specifies errors that originate from the sequelize "core"
* @property DB {String} specifies validation errors that originate from the storage engine
* @property FUNCTION {String} specifies validation errors that originate from validator functions (both built-in and custom) defined for a given attribute
* @property CORE {string} specifies errors that originate from the sequelize "core"
* @property DB {string} specifies validation errors that originate from the storage engine
* @property FUNCTION {string} specifies validation errors that originate from validator functions (both built-in and custom) defined for a given attribute
* get array of current hook and its proxied hooks combined
* get array of current hook and its proxies combined
*
* @param {string} hookType any hook type @see {@link hookTypes}
*
* @private
*/
constgetProxiedHooks=hookType=>
...
...
@@ -77,11 +80,11 @@ const Hooks = {
/**
* Process user supplied hooks definition
*
* @param {Object} hooks
* @param {Object} hooks hooks definition
*
* @private
* @memberOf Sequelize
* @memberOf Sequelize.Model
* @memberof Sequelize
* @memberof Sequelize.Model
*/
_setupHooks(hooks){
this.options.hooks={};
...
...
@@ -141,12 +144,12 @@ const Hooks = {
/**
* Add a hook to the model
*
* @param {String} hookType
* @param {String} [name] Provide a name for the hook function. It can be used to remove the hook later or to order hooks based on some sort of priority system in the future.
* @param {string} hookType hook name @see {@link hookTypes}
* @param {string|Function} [name] Provide a name for the hook function. It can be used to remove the hook later or to order hooks based on some sort of priority system in the future.
* @param {Function} fn The hook function
*
* @memberOf Sequelize
* @memberOf Sequelize.Model
* @memberof Sequelize
* @memberof Sequelize.Model
*/
addHook(hookType,name,fn){
if(typeofname==='function'){
...
...
@@ -171,11 +174,11 @@ const Hooks = {
/**
* Remove hook from the model
*
* @param {String} hookType
* @param {String|Function} name
* @param {string} hookType @see {@link hookTypes}
* @param {string|Function} name name of hook or function reference which was attached
*
* @memberOf Sequelize
* @memberOf Sequelize.Model
* @memberof Sequelize
* @memberof Sequelize.Model
*/
removeHook(hookType,name){
hookType=hookAliases[hookType]||hookType;
...
...
@@ -207,11 +210,12 @@ const Hooks = {
/**
* Check whether the mode has any hooks of this type
* @param {String} tableName Table name where you want to add a constraint
* @param {string} tableName Table name where you want to add a constraint
* @param {Array} attributes Array of column names to apply the constraint over
* @param {Object} options An object to define the constraint name, type etc
* @param {String} options.type Type of constraint. One of the values in available constraints(case insensitive)
* @param {String} [options.name] Name of the constraint. If not specified, sequelize automatically creates a named constraint based on constraint type, table & column names
* @param {String} [options.defaultValue] The value for the default constraint
* @param {string} options.type Type of constraint. One of the values in available constraints(case insensitive)
* @param {string} [options.name] Name of the constraint. If not specified, sequelize automatically creates a named constraint based on constraint type, table & column names
* @param {string} [options.defaultValue] The value for the default constraint
* @param {Object} [options.where] Where clause/expression for the CHECK constraint
* @param {Object} [options.references] Object specifying target table, column name to create foreign key constraint
* @param {String} [options.references.table] Target table name
* @param {String} [options.references.field] Target column name
* @param {string} [options.references.table] Target table name
* @param {string} [options.references.field] Target column name
* @param {string} [rawTablename] Table name, for backward compatibility
* This is the main class, the entry point to sequelize. To use it, you just need to import sequelize:
* This is the main class, the entry point to sequelize.
*
* ```js
* const Sequelize = require('sequelize');
* ```
*
* In addition to sequelize, the connection library for the dialect you want to use should also be installed in your project. You don't need to import it however, as sequelize will take care of that.
* @class Sequelize
*/
classSequelize{
/**
* Instantiate sequelize with name of database, username and password
*
* #### Example usage
*
* ```javascript
* // without password and options
* const sequelize = new Sequelize('database', 'username')
*
* // without options
* const sequelize = new Sequelize('database', 'username', 'password')
* Instantiate sequelize with name of database, username and password.
*
* @example
* // without password / with blank password
* const sequelize = new Sequelize('database', 'username', null, {})
* const sequelize = new Sequelize('database', 'username', null, {
* dialect: 'mysql'
* })
*
* // with password and options
* const sequelize = new Sequelize('my_database', 'john', 'doe', {})
* const sequelize = new Sequelize('my_database', 'john', 'doe', {
* dialect: 'postgres'
* })
*
* // with database, username, and password in the options object
* const sequelize = new Sequelize({ database, username, password });
* const sequelize = new Sequelize('mysql://localhost:3306/database', {})
* ```
*
* @param {String} [database] The name of the database
* @param {String} [username=null] The username which is used to authenticate against the database.
* @param {String} [password=null] The password which is used to authenticate against the database. Supports SQLCipher encryption for SQLite.
* @param {string} [database] The name of the database
* @param {string} [username=null] The username which is used to authenticate against the database.
* @param {string} [password=null] The password which is used to authenticate against the database. Supports SQLCipher encryption for SQLite.
* @param {Object} [options={}] An object with options.
* @param {String} [options.host='localhost'] The host of the relational database.
* @param {Integer} [options.port=] The port of the relational database.
* @param {String} [options.username=null] The username which is used to authenticate against the database.
* @param {String} [options.password=null] The password which is used to authenticate against the database.
* @param {String} [options.database=null] The name of the database
* @param {String} [options.dialect] The dialect of the database you are connecting to. One of mysql, postgres, sqlite and mssql.
* @param {String} [options.dialectModulePath=null] If specified, load the dialect library from this path. For example, if you want to use pg.js instead of pg when connecting to a pg database, you should specify 'pg.js' here
* @param {string} [options.host='localhost'] The host of the relational database.
* @param {number} [options.port=] The port of the relational database.
* @param {string} [options.username=null] The username which is used to authenticate against the database.
* @param {string} [options.password=null] The password which is used to authenticate against the database.
* @param {string} [options.database=null] The name of the database
* @param {string} [options.dialect] The dialect of the database you are connecting to. One of mysql, postgres, sqlite and mssql.
* @param {string} [options.dialectModulePath=null] If specified, load the dialect library from this path. For example, if you want to use pg.js instead of pg when connecting to a pg database, you should specify 'pg.js' here
* @param {Object} [options.dialectOptions] An object of additional options, which are passed directly to the connection library
* @param {String} [options.storage] Only used by sqlite. Defaults to ':memory:'
* @param {String} [options.protocol='tcp'] The protocol of the relational database.
* @param {string} [options.storage] Only used by sqlite. Defaults to ':memory:'
* @param {string} [options.protocol='tcp'] The protocol of the relational database.
* @param {Object} [options.define={}] Default options for model definitions. See sequelize.define for options
* @param {Object} [options.query={}] Default options for sequelize.query
* @param {Object} [options.set={}] Default options for sequelize.set
* @param {Object} [options.sync={}] Default options for sequelize.sync
* @param {String} [options.timezone='+00:00'] The timezone used when converting a date from the database into a JavaScript date. The timezone is also used to SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP and other time related functions have in the right timezone. For best cross platform performance use the format +/-HH:MM. Will also accept string versions of timezones used by moment.js (e.g. 'America/Los_Angeles'); this is useful to capture daylight savings time changes.
* @param {string} [options.timezone='+00:00'] The timezone used when converting a date from the database into a JavaScript date. The timezone is also used to SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP and other time related functions have in the right timezone. For best cross platform performance use the format +/-HH:MM. Will also accept string versions of timezones used by moment.js (e.g. 'America/Los_Angeles'); this is useful to capture daylight savings time changes.
* @param {Function} [options.logging=console.log] A function that gets executed every time Sequelize would log something.
* @param {Boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
* @param {Boolean} [options.omitNull=false] A flag that defines if null values should be passed to SQL queries or not.
* @param {Boolean} [options.native=false] A flag that defines if native library shall be used or not. Currently only has an effect for postgres
* @param {Boolean} [options.replication=false] Use read / write replication. To enable replication, pass an object, with two properties, read and write. Write should be an object (a single server for handling writes), and read an array of object (several servers to handle reads). Each read/write server can have the following properties: `host`, `port`, `username`, `password`, `database`
* @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
* @param {boolean} [options.omitNull=false] A flag that defines if null values should be passed to SQL queries or not.
* @param {boolean} [options.native=false] A flag that defines if native library shall be used or not. Currently only has an effect for postgres
* @param {boolean} [options.replication=false] Use read / write replication. To enable replication, pass an object, with two properties, read and write. Write should be an object (a single server for handling writes), and read an array of object (several servers to handle reads). Each read/write server can have the following properties: `host`, `port`, `username`, `password`, `database`
* @param {Object} [options.pool] sequelize connection pool configuration
* @param {Integer} [options.pool.max=5] Maximum number of connection in pool
* @param {Integer} [options.pool.min=0] Minimum number of connection in pool
* @param {Integer} [options.pool.idle=10000] The maximum time, in milliseconds, that a connection can be idle before being released. Use with combination of evict for proper working, for more details read https://github.com/coopernurse/node-pool/issues/178#issuecomment-327110870
* @param {Integer} [options.pool.acquire=10000] The maximum time, in milliseconds, that pool will try to get connection before throwing error
* @param {Integer} [options.pool.evict=10000] The time interval, in milliseconds, for evicting stale connections. Set it to 0 to disable this feature.
* @param {Boolean} [options.pool.handleDisconnects=true] Controls if pool should handle connection disconnect automatically without throwing errors
* @param {number} [options.pool.max=5] Maximum number of connection in pool
* @param {number} [options.pool.min=0] Minimum number of connection in pool
* @param {number} [options.pool.idle=10000] The maximum time, in milliseconds, that a connection can be idle before being released. Use with combination of evict for proper working, for more details read https://github.com/coopernurse/node-pool/issues/178#issuecomment-327110870
* @param {number} [options.pool.acquire=10000] The maximum time, in milliseconds, that pool will try to get connection before throwing error
* @param {number} [options.pool.evict=10000] The time interval, in milliseconds, for evicting stale connections. Set it to 0 to disable this feature.
* @param {boolean} [options.pool.handleDisconnects=true] Controls if pool should handle connection disconnect automatically without throwing errors
* @param {Function} [options.pool.validate] A function that validates a connection. Called with client. The default function checks that client is an object, and that its state is not disconnected
* @param {Boolean} [options.quoteIdentifiers=true] Set to `false` to make table names and attributes case-insensitive on Postgres and skip double quoting of them. WARNING: Setting this to false may expose vulnerabilities and is not recommended!
* @param {String} [options.transactionType='DEFERRED'] Set the default transaction type. See `Sequelize.Transaction.TYPES` for possible options. Sqlite only.
* @param {String} [options.isolationLevel] Set the default transaction isolation level. See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options.
* @param {boolean} [options.quoteIdentifiers=true] Set to `false` to make table names and attributes case-insensitive on Postgres and skip double quoting of them. WARNING: Setting this to false may expose vulnerabilities and is not recommended!
* @param {string} [options.transactionType='DEFERRED'] Set the default transaction type. See `Sequelize.Transaction.TYPES` for possible options. Sqlite only.
* @param {string} [options.isolationLevel] Set the default transaction isolation level. See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options.
* @param {Object} [options.retry] Set of flags that control when a query is automatically retried.
* @param {Array} [options.retry.match] Only retry a query if the error matches one of these strings.
* @param {Integer} [options.retry.max] How many times a failing query is automatically retried. Set to 0 to disable retrying on SQL_BUSY error.
* @param {Boolean} [options.typeValidation=false] Run built in type validators on insert and update, e.g. validate that arguments passed to integer fields are integer-like.
* @param {number} [options.retry.max] How many times a failing query is automatically retried. Set to 0 to disable retrying on SQL_BUSY error.
* @param {boolean} [options.typeValidation=false] Run built in type validators on insert and update, e.g. validate that arguments passed to integer fields are integer-like.
* @param {Object} [options.operatorsAliases] String based operator alias. Pass object to limit set of aliased operators.
* See https://github.com/sequelize/express-example for a short example of how to define your models in separate files so that they can be imported by sequelize.import
* @param {String} path The path to the file that holds the model you want to import. If the part is relative, it will be resolved relatively to the calling file
* @return {Model}
* @param {string} path The path to the file that holds the model you want to import. If the part is relative, it will be resolved relatively to the calling file
*
* @returns {Model} Imported model, returned from cache if was already imported
*/
import(path){
// is it a relative path?
...
...
@@ -412,29 +407,28 @@ class Sequelize {
* })
* ```
*
* @method query
* @param {String} sql
* @param {string} sql
* @param {Object} [options={}] Query options.
* @param {Boolean} [options.raw] If true, sequelize will not try to format the results of the query, or build an instance of a model from the result
* @param {boolean} [options.raw] If true, sequelize will not try to format the results of the query, or build an instance of a model from the result
* @param {Transaction} [options.transaction=null] The transaction that the query should be executed under
* @param {QueryTypes} [options.type='RAW'] The type of query you are executing. The query type affects how results are formatted before they are passed back. The type is a string, but `Sequelize.QueryTypes` is provided as convenience shortcuts.
* @param {Boolean} [options.nest=false] If true, transforms objects with `.` separated property names into nested objects using [dottie.js](https://github.com/mickhansen/dottie.js). For example { 'user.username': 'john' } becomes { user: { username: 'john' }}. When `nest` is true, the query type is assumed to be `'SELECT'`, unless otherwise specified
* @param {Boolean} [options.plain=false] Sets the query type to `SELECT` and return a single row
* @param {boolean} [options.nest=false] If true, transforms objects with `.` separated property names into nested objects using [dottie.js](https://github.com/mickhansen/dottie.js). For example { 'user.username': 'john' } becomes { user: { username: 'john' }}. When `nest` is true, the query type is assumed to be `'SELECT'`, unless otherwise specified
* @param {boolean} [options.plain=false] Sets the query type to `SELECT` and return a single row
* @param {Object|Array} [options.replacements] Either an object of named parameter replacements in the format `:param` or an array of unnamed replacements to replace `?` in your SQL.
* @param {Object|Array} [options.bind] Either an object of named bind parameter in the format `_param` or an array of unnamed bind parameter to replace `$1, $2, ...` in your SQL.
* @param {Boolean} [options.useMaster=false] Force the query to use the write pool, regardless of the query type.
* @param {boolean} [options.useMaster=false] Force the query to use the write pool, regardless of the query type.
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @param {new Model()} [options.instance] A sequelize instance used to build the return instance
* @param {Model} [options.model] A sequelize model used to build the returned model instances (used to be called callee)
* @param {Object} [options.retry] Set of flags that control when a query is automatically retried.
* @param {Array} [options.retry.match] Only retry a query if the error matches one of these strings.
* @param {Integer} [options.retry.max] How many times a failing query is automatically retried.
* @param {String} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
* @param {Boolean} [options.supportsSearchPath] If false do not prepend the query with the search_path (Postgres only)
* @param {Boolean} [options.mapToModel=false] Map returned fields to model's fields if `options.model` or `options.instance` is present. Mapping will occur before building the model instance.
* @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
* @param {boolean} [options.supportsSearchPath] If false do not prepend the query with the search_path (Postgres only)
* @param {boolean} [options.mapToModel=false] Map returned fields to model's fields if `options.model` or `options.instance` is present. Mapping will occur before building the model instance.
* @param {Object} [options.fieldMap] Map returned fields to arbitrary names for `SELECT` query type.
*
* @return {Promise}
* @returns {Promise}
*
* @see {@link Model.build} for more information about instance option.
*/
...
...
@@ -566,13 +560,13 @@ class Sequelize {
* Execute a query which would set an environment or user variable. The variables are set per connection, so this function needs a transaction.
* Only works for MySQL.
*
* @method set
* @param {Object} variables Object with multiple variables.
* @param {Object} options Query options.
* @param {Transaction} options.transaction The transaction that the query should be executed under
* @param {Object} [options] query options.
* @param {Transaction} [options.transaction] The transaction that the query should be executed under
*
* @memberof Sequelize
* @return {Promise}
*
* @returns {Promise}
*/
set(variables,options){
...
...
@@ -602,8 +596,9 @@ class Sequelize {
/**
* Escape value.
*
* @param {String} value
* @return {String}
* @param {string} value string value to escape
*
* @returns {string}
*/
escape(value){
returnthis.getQueryInterface().escape(value);
...
...
@@ -612,14 +607,16 @@ class Sequelize {
/**
* Create a new database schema.
*
* Note, that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
* **Note:** this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
* not a database table. In mysql and sqlite, this command will do nothing.
*
* @see {@link Model.schema}
* @param {String} schema Name of the schema
* @param {Object} options={}
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise}
*
* @param {string} schema Name of the schema
* @param {Object} [options={}] query options
* @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
* @param {Boolean} [options.force=false] If force is true, each Model will run `DROP TABLE IF EXISTS`, before it tries to create its own table
* @param {Object} [options={}] sync options
* @param {boolean} [options.force=false] If force is true, each Model will run `DROP TABLE IF EXISTS`, before it tries to create its own table
* @param {RegExp} [options.match] Match a regex against the database name before syncing, a safety check for cases where force: true is used in tests but not live code
* @param {Boolean|function} [options.logging=console.log] A function that logs sql queries, or false for no logging
* @param {String} [options.schema='public'] The schema that the tables should be created in. This can be overriden for each table in sequelize.define
* @param {String} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
* @param {Boolean} [options.hooks=true] If hooks is true then beforeSync, afterSync, beforeBulkSync, afterBulkSync hooks will be called
* @param {Boolean} [options.alter=false] Alters tables to fit models. Not recommended for production use. Deletes data in columns that were removed or had their type changed in the model.
* @return {Promise}
* @param {boolean|Function} [options.logging=console.log] A function that logs sql queries, or false for no logging
* @param {string} [options.schema='public'] The schema that the tables should be created in. This can be overriden for each table in sequelize.define
* @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
* @param {boolean} [options.hooks=true] If hooks is true then beforeSync, afterSync, beforeBulkSync, afterBulkSync hooks will be called
* @param {boolean} [options.alter=false] Alters tables to fit models. Not recommended for production use. Deletes data in columns that were removed or had their type changed in the model.
*
* @returns {Promise}
*/
sync(options){
options=_.clone(options)||{};
...
...
@@ -719,13 +723,12 @@ class Sequelize {
}
/**
* Truncate all tables defined through the sequelize models. This is done
* by calling Model.truncate() on each model.
* Truncate all tables defined through the sequelize models.
* This is done by calling `Model.truncate()` on each model.
*
* @param {object} [options] The options passed to Model.destroy in addition to truncate
* @param {Boolean|function} [options.transaction]
* @param {Boolean|function} [options.logging] A function that logs sql queries, or false for no logging
* @return {Promise}
* @param {Object} [options] The options passed to Model.destroy in addition to truncate
* @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
* @returns {Promise}
*
* @see {@link Model.truncate} for more information
*/
...
...
@@ -748,12 +751,15 @@ class Sequelize {
}
/**
* Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model
* Drop all tables defined through this sequelize instance.
* This is done by calling Model.drop on each model.
*
* @see {@link Model.drop} for options
*
* @param {object} options The options passed to each call to Model.drop
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise}
* @param {Object} [options] The options passed to each call to Model.drop
* @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
*
* @returns {Promise}
*/
drop(options){
constmodels=[];
...
...
@@ -768,10 +774,11 @@ class Sequelize {
}
/**
* Test the connection by trying to authenticate
* Test the connection by trying to authenticate. It runs `SELECT 1+1 AS result` query.
*
* @param {Object} options query options
*
* @error 'Invalid credentials' if the authentication failed (even if the database did not respond at all...)
* Creates an object representing a database function. This can be used in search queries, both in where and order parts, and as default values in column definitions.
* If you want to refer to columns in your function, you should use `sequelize.col`, so that the columns are properly interpreted as columns and not a strings.
* Creates an object which represents a column in the DB, this allows referencing another column in your query. This is often useful in conjunction with `sequelize.fn`, since raw string arguments to fn will be escaped.
*
* @see {@link Sequelize#fn}
*
* @method col
* @param {String} col The name of the column
* @param {string} col The name of the column
* @since v2.0.0-dev3
* @memberof Sequelize
* @return {Sequelize.col}
*
* @returns {Sequelize.col}
*/
staticcol(col){
returnnewUtils.Col(col);
...
...
@@ -848,12 +849,12 @@ class Sequelize {
/**
* Creates an object representing a call to the cast function.
*
* @method cast
* @param {any} val The value to cast
* @param {String} type The type to cast it to
* @param {string} type The type to cast it to
* @since v2.0.0-dev3
* @memberof Sequelize
* @return {Sequelize.cast}
*
* @returns {Sequelize.cast}
*/
staticcast(val,type){
returnnewUtils.Cast(val,type);
...
...
@@ -862,12 +863,11 @@ class Sequelize {
/**
* Creates an object representing a literal, i.e. something that will not be escaped.
*
* @method literal
* @param {any} val
* @alias asIs
* @param {any} val literal value
* @since v2.0.0-dev3
* @memberof Sequelize
* @return {Sequelize.literal}
*
* @returns {Sequelize.literal}
*/
staticliteral(val){
returnnewUtils.Literal(val);
...
...
@@ -875,41 +875,44 @@ class Sequelize {
/**
* An AND query
*
* @see {@link Model.findAll}
*
* @method and
* @param {String|Object} args Each argument will be joined by AND
* @param {...string|Object} args Each argument will be joined by AND
* @since v2.0.0-dev3
* @memberof Sequelize
* @return {Sequelize.and}
*
* @returns {Sequelize.and}
*/
staticand(){
return{[Op.and]:Utils.sliceArgs(arguments)};
staticand(...args){
return{[Op.and]:Utils.sliceArgs(args)};
}
/**
* An OR query
*
* @see {@link Model.findAll}
*
* @method or
* @param {String|Object} args Each argument will be joined by OR
* @param {...string|Object} args Each argument will be joined by OR
* @since v2.0.0-dev3
* @memberof Sequelize
* @return {Sequelize.or}
*
* @returns {Sequelize.or}
*/
staticor(){
return{[Op.or]:Utils.sliceArgs(arguments)};
staticor(...args){
return{[Op.or]:Utils.sliceArgs(args)};
}
/**
* Creates an object representing nested where conditions for postgres/sqlite/mysql json data-type.
* @see {@link Model#findAll}
*
* @method json
* @param {String|Object} conditions A hash containing strings/numbers or other nested hash, a string using dot notation or a string using postgres/sqlite/mysql json syntax.
* @param {String|Number|Boolean} [value] An optional value to compare against. Produces a string of the form "<json path> = '<value>'".
* @see {@link Model.findAll}
*
* @param {string|Object} conditionsOrPath A hash containing strings/numbers or other nested hash, a string using dot notation or a string using postgres/sqlite/mysql json syntax.
* @param {string|number|boolean} [value] An optional value to compare against. Produces a string of the form "<json path> = '<value>'".
* @memberof Sequelize
* @return {Sequelize.json}
*
* @returns {Sequelize.json}
*/
staticjson(conditionsOrPath,value){
returnnewUtils.Json(conditionsOrPath,value);
...
...
@@ -926,9 +929,8 @@ class Sequelize {
* @see {@link Model.findAll}
*
* @param {Object} attr The attribute, which can be either an attribute object from `Model.rawAttributes` or a sequelize object, for example an instance of `sequelize.fn`. For simple string attributes, use the POJO syntax
* @param {String|Op} [comparator='=']
* @param {String|Object} logic The condition. Can be both a simply type, or a further condition (`or`, `and`, `.literal` etc.)
* @alias condition
* @param {Symbol} [comparator='Op.eq'] operator
* @param {string|Object} logic The condition. Can be both a simply type, or a further condition (`or`, `and`, `.literal` etc.)
* @since v2.0.0-dev3
*/
staticwhere(attr,comparator,logic){
...
...
@@ -936,20 +938,20 @@ class Sequelize {
}
/**
* Start a transaction. When using transactions, you should pass the transaction in the options argument in order for the query to happen under that transaction
* Start a transaction. When using transactions, you should pass the transaction in the options argument in order for the query to happen under that transaction @see {@link Transaction}
*
* ```js
* If you have [CLS](https://github.com/othiym23/node-continuation-local-storage) enabled, the transaction will automatically be passed to any query that runs within the callback
* If you have [CLS](https://github.com/othiym23/node-continuation-local-storage) enabled, the transaction will automatically be passed to any query that runs within the callback.
* To enable CLS, add it do your project, create a namespace and set it on the sequelize constructor:
* @example <caption>To enable CLS, add it do your project, create a namespace and set it on the sequelize constructor:</caption>
* Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace
*
* @see {@link Transaction}
* @param {Object} [options={}]
* @param {Boolean} [options.autocommit]
* @param {String} [options.type='DEFERRED'] See `Sequelize.Transaction.TYPES` for possible options. Sqlite only.
* @param {String} [options.isolationLevel] See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options
* // Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace
*
* @param {Object} [options] Transaction options
* @param {boolean} [options.autocommit] Auto commit this transaction
* @param {string} [options.type='DEFERRED'] See `Sequelize.Transaction.TYPES` for possible options. Sqlite only.
* @param {string} [options.isolationLevel] See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @param {Function} [autoCallback] The callback is called with the transaction object, and should return a promise. If the promise is resolved, the transaction commits; if the promise rejects, the transaction rolls back