不要怂,就是干,撸起袖子干!

Commit 14d14468 by Sushant Committed by GitHub

docs: cleanup / correct jsdocs (#9702)

1 parent 84f80481
...@@ -3,6 +3,22 @@ ...@@ -3,6 +3,22 @@
"mocha/no-exclusive-tests": "error", "mocha/no-exclusive-tests": "error",
"mocha/no-skipped-tests": "warn", "mocha/no-skipped-tests": "warn",
// "jsdoc/check-param-names": "error",
// "jsdoc/check-tag-names": "error",
// "jsdoc/check-types": "error",
// "jsdoc/newline-after-description": "error",
// "jsdoc/no-undefined-types": "error",
// "jsdoc/require-description-complete-sentence": "off",
// "jsdoc/require-example": "off",
// "jsdoc/require-hyphen-before-param-description": "off",
// "jsdoc/require-param": "error",
// "jsdoc/require-param-description": "error",
// "jsdoc/require-param-name": "error",
// "jsdoc/require-param-type": "error",
// "jsdoc/require-returns-description": "off",
// "jsdoc/require-returns-type": "error",
// "jsdoc/valid-types": "off",
"array-bracket-spacing": "error", "array-bracket-spacing": "error",
"comma-spacing": "error", "comma-spacing": "error",
"key-spacing": "error", "key-spacing": "error",
...@@ -90,11 +106,25 @@ ...@@ -90,11 +106,25 @@
"sourceType": "script" "sourceType": "script"
}, },
"plugins": [ "plugins": [
"mocha" "mocha",
"jsdoc"
], ],
"env": { "env": {
"node": true, "node": true,
"mocha": true, "mocha": true,
"es6": true "es6": true
},
"globals": {
"Association": true,
"HasMany": true,
"BelongsTo": true,
"HasOne": true,
"BelongsToMany": true,
"DataTypes": true,
"Sequelize": true,
"Transaction": true,
"Model": true,
"QueryInterface": true,
"QueryType": true
} }
} }
\ No newline at end of file
...@@ -2,21 +2,22 @@ test*.js ...@@ -2,21 +2,22 @@ test*.js
*.swp *.swp
.idea .idea
.DS_STORE .DS_STORE
node_modules
npm-debug.log npm-debug.log
*~ *~
test/binary/tmp/*
test/tmp/*
test/dialects/sqlite/test.sqlite test/dialects/sqlite/test.sqlite
test/sqlite/test.sqlite test/sqlite/test.sqlite
coverage-*
site
docs/api/tmp.md docs/api/tmp.md
ssce.js ssce.js
sscce.js sscce.js
coverage
.vscode/
*.sublime* *.sublime*
esdoc
package-lock.json package-lock.json
yarn.lock yarn.lock
coverage-*
coverage
test/tmp/*
test/binary/tmp/*
site
.vscode/
esdoc
node_modules
\ No newline at end of file
{
"plugins": [
"plugins/markdown"
],
"markdown": {
"parser": "gfm"
},
"tags": {
"allowUnknownTags": false
},
"source": {
"include": [
"lib/",
"docs/index.md"
],
"excludePattern": "(node_modules)"
},
"opts": {
"template": "node_modules/docdash",
"encoding": "utf8",
"destination": "newdocs/",
"recurse": true,
"tutorials": "docs/"
},
"templates": {
"outputSourcePath": false,
"outputSourceFiles": false,
"includeDate": false,
"sort": false
}
}
\ No newline at end of file
...@@ -112,9 +112,10 @@ class Association { ...@@ -112,9 +112,10 @@ class Association {
/** /**
* Normalize input * Normalize input
* *
* @param input {Any}, it may be array or single obj, instance or primary key * @param {Array|string} input it may be array or single obj, instance or primary key
* *
* @returns <Array>, built objects * @private
* @returns {Array} built objects
*/ */
toInstanceArray(input) { toInstanceArray(input) {
if (!Array.isArray(input)) { if (!Array.isArray(input)) {
......
...@@ -357,12 +357,15 @@ class BelongsToMany extends Association { ...@@ -357,12 +357,15 @@ class BelongsToMany extends Association {
/** /**
* Get everything currently associated with this, using an optional where clause. * 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 * @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) { get(instance, options) {
options = Utils.cloneDeep(options) || {}; options = Utils.cloneDeep(options) || {};
...@@ -426,10 +429,12 @@ class BelongsToMany extends Association { ...@@ -426,10 +429,12 @@ class BelongsToMany extends Association {
/** /**
* Count everything currently associated with this, using an optional where clause. * 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 {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|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @return {Promise<Integer>} *
* @returns {Promise<number>}
*/ */
count(instance, options) { count(instance, options) {
const association = this; const association = this;
...@@ -450,9 +455,11 @@ class BelongsToMany extends Association { ...@@ -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 * 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 * @param {Object} [options] Options passed to getAssociations
* @return {Promise<boolean>} *
* @returns {Promise<boolean>}
*/ */
has(sourceInstance, instances, options) { has(sourceInstance, instances, options) {
const association = this; const association = this;
...@@ -489,13 +496,16 @@ class BelongsToMany extends Association { ...@@ -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] Options passed to `through.findAll`, `bulkCreate`, `update` and `destroy`
* @param {Object} [options.validate] Run validation for the join model * @param {Object} [options.validate] Run validation for the join model
* @param {Object} [options.through] Additional attributes for the join table. * @param {Object} [options.through] Additional attributes for the join table.
* @return {Promise} *
* @returns {Promise}
*/ */
set(sourceInstance, newAssociatedObjects, options) { set(sourceInstance, newAssociatedObjects, options) {
options = options || {}; options = options || {};
...@@ -590,13 +600,16 @@ class BelongsToMany extends Association { ...@@ -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] Options passed to `through.findAll`, `bulkCreate` and `update`
* @param {Object} [options.validate] Run validation for the join model. * @param {Object} [options.validate] Run validation for the join model.
* @param {Object} [options.through] Additional attributes for the join table. * @param {Object} [options.through] Additional attributes for the join table.
* @return {Promise} *
* @returns {Promise}
*/ */
add(sourceInstance, newInstances, options) { add(sourceInstance, newInstances, options) {
// If newInstances is null or undefined, no-op // If newInstances is null or undefined, no-op
...@@ -684,9 +697,11 @@ class BelongsToMany extends Association { ...@@ -684,9 +697,11 @@ class BelongsToMany extends Association {
/** /**
* Un-associate one or more instance(s). * 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 {Object} [options] Options passed to `through.destroy`
* @return {Promise} *
* @returns {Promise}
*/ */
remove(sourceInstance, oldAssociatedObjects, options) { remove(sourceInstance, oldAssociatedObjects, options) {
const association = this; const association = this;
...@@ -705,10 +720,12 @@ class BelongsToMany extends Association { ...@@ -705,10 +720,12 @@ class BelongsToMany extends Association {
/** /**
* Create a new instance of the associated model and associate it with this. * Create a new instance of the associated model and associate it with this.
* *
* @param {Object} [values] * @param {<Model>} sourceInstance source instance
* @param {Object} [values] values for target model
* @param {Object} [options] Options passed to create and add * @param {Object} [options] Options passed to create and add
* @param {Object} [options.through] Additional attributes for the join table * @param {Object} [options.through] Additional attributes for the join table
* @return {Promise} *
* @returns {Promise}
*/ */
create(sourceInstance, values, options) { create(sourceInstance, values, options) {
const association = this; const association = this;
......
...@@ -113,13 +113,14 @@ class BelongsTo extends Association { ...@@ -113,13 +113,14 @@ class BelongsTo extends Association {
/** /**
* Get the associated instance. * Get the associated instance.
* *
* @param {Object} [options] * @param {<Model>|Array<Model>} instances source instances
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false. * @param {Object} [options] find options
* @param {String} [options.schema] Apply a schema on the related model * @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 * @see {@link Model.findOne} for a full explanation of options
* *
* @return {Promise<Model>} * @returns {Promise<<Model>>}
*/ */
get(instances, options) { get(instances, options) {
const where = {}; const where = {};
...@@ -183,11 +184,12 @@ class BelongsTo extends Association { ...@@ -183,11 +184,12 @@ class BelongsTo extends Association {
/** /**
* Set the associated model. * 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 {<Model>} sourceInstance the source instance
* @param {Object} [options] Options passed to `this.save` * @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 {Boolean} [options.save=true] Skip saving this after setting the foreign key if false. * @param {Object} [options={}] options passed to `this.save`
* @param {boolean} [options.save=true] Skip saving this after setting the foreign key if false.
* *
* @return {Promise} * @returns {Promise}
*/ */
set(sourceInstance, associatedInstance, options = {}) { set(sourceInstance, associatedInstance, options = {}) {
let value = associatedInstance; let value = associatedInstance;
...@@ -213,12 +215,13 @@ class BelongsTo extends Association { ...@@ -213,12 +215,13 @@ class BelongsTo extends Association {
/** /**
* Create a new instance of the associated model and associate it with this. * Create a new instance of the associated model and associate it with this.
* *
* @param {Object} [values] * @param {<Model>} sourceInstance the source instance
* @param {Object} [options] Options passed to `target.create` and setAssociation. * @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 * @see {@link Model#create} for a full explanation of options
* *
* @return {Promise} * @returns {Promise}
*/ */
create(sourceInstance, values, options) { create(sourceInstance, values, options) {
values = values || {}; values = values || {};
......
...@@ -157,12 +157,15 @@ class HasMany extends Association { ...@@ -157,12 +157,15 @@ class HasMany extends Association {
/** /**
* Get everything currently associated with this, using an optional where clause. * Get everything currently associated with this, using an optional where clause.
* *
* @param {Object} [options] * @param {<Model>|Array<Model>} instances source instances
* @param {Object} [options] find options
* @param {Object} [options.where] An optional where clause to limit the associated models * @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|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 * @param {string} [options.schema] Apply a schema on the related model
*
* @see {@link Model.findAll} for a full explanation of options * @see {@link Model.findAll} for a full explanation of options
* @return {Promise<Array<Model>>} *
* @returns {Promise<Array<<Model>>>}
*/ */
get(instances, options = {}) { get(instances, options = {}) {
const where = {}; const where = {};
...@@ -238,11 +241,12 @@ class HasMany extends Association { ...@@ -238,11 +241,12 @@ class HasMany extends Association {
/** /**
* Count everything currently associated with this, using an optional where clause. * Count everything currently associated with this, using an optional where clause.
* *
* @param {Object} [options] * @param {<Model>} instance the source instance
* @param {Object} [options] find & count options
* @param {Object} [options.where] An optional where clause to limit the associated models * @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|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* *
* @return {Promise<Integer>} * @returns {Promise<number>}
*/ */
count(instance, options) { count(instance, options) {
options = Utils.cloneDeep(options); options = Utils.cloneDeep(options);
...@@ -265,10 +269,11 @@ class HasMany extends Association { ...@@ -265,10 +269,11 @@ class HasMany extends Association {
/** /**
* Check if one or more rows are associated with `this`. * Check if one or more rows are associated with `this`.
* *
* @param {Model[]|Model|string[]|String|number[]|Number} [instance(s)] * @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 * @param {Object} [options] Options passed to getAssociations
* *
* @return {Promise} * @returns {Promise}
*/ */
has(sourceInstance, targetInstances, options) { has(sourceInstance, targetInstances, options) {
const where = {}; const where = {};
...@@ -305,10 +310,12 @@ class HasMany extends Association { ...@@ -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 * 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] Options passed to `target.findAll` and `update`.
* @param {Object} [options.validate] Run validation for the join model * @param {Object} [options.validate] Run validation for the join model
* @return {Promise} *
* @returns {Promise}
*/ */
set(sourceInstance, targetInstances, options) { set(sourceInstance, targetInstances, options) {
if (targetInstances === null) { if (targetInstances === null) {
...@@ -377,9 +384,11 @@ class HasMany extends Association { ...@@ -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, * 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. * or a mixed array of Model / string / numbers to associate multiple rows.
* *
* @param {Model[]|Model|string[]|string|number[]|number} [newAssociation(s)] * @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 {Object} [options] Options passed to `target.update`.
* @return {Promise} *
* @returns {Promise}
*/ */
add(sourceInstance, targetInstances, options = {}) { add(sourceInstance, targetInstances, options = {}) {
if (!targetInstances) return Utils.Promise.resolve(); if (!targetInstances) return Utils.Promise.resolve();
...@@ -402,9 +411,11 @@ class HasMany extends Association { ...@@ -402,9 +411,11 @@ class HasMany extends Association {
/** /**
* Un-associate one or several target rows. * Un-associate one or several target rows.
* *
* @param {Model[]|Model|String[]|string|Number[]|number} [oldAssociatedInstance(s)] * @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 {Object} [options] Options passed to `target.update`
* @return {Promise} *
* @returns {Promise}
*/ */
remove(sourceInstance, targetInstances, options = {}) { remove(sourceInstance, targetInstances, options = {}) {
const update = {}; const update = {};
...@@ -425,9 +436,11 @@ class HasMany extends Association { ...@@ -425,9 +436,11 @@ class HasMany extends Association {
/** /**
* Create a new instance of the associated model and associate it with this. * Create a new instance of the associated model and associate it with this.
* *
* @param {Object} [values] * @param {<Model>} sourceInstance source instance
* @param {Object} [options] Options passed to `target.create`. * @param {Object} [values] values for target model instance
* @return {Promise} * @param {Object} [options] Options passed to `target.create`
*
* @returns {Promise}
*/ */
create(sourceInstance, values, options = {}) { create(sourceInstance, values, options = {}) {
if (Array.isArray(options)) { if (Array.isArray(options)) {
......
...@@ -112,11 +112,14 @@ class HasOne extends Association { ...@@ -112,11 +112,14 @@ class HasOne extends Association {
/** /**
* Get the associated instance. * Get the associated instance.
* *
* @param {Object} [options] * @param {<Model>|Array<Model>} instances source instances
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false * @param {Object} [options] find options
* @param {String} [options.schema] Apply a schema on the related model * @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 * @see {@link Model.findOne} for a full explanation of options
* @return {Promise<Model>} *
* @returns {Promise<Model>}
*/ */
get(instances, options) { get(instances, options) {
const where = {}; const where = {};
...@@ -180,10 +183,11 @@ class HasOne extends Association { ...@@ -180,10 +183,11 @@ class HasOne extends Association {
/** /**
* Set the associated model. * 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` * @param {Object} [options] Options passed to getAssociation and `target.save`
* *
* @return {Promise} * @returns {Promise}
*/ */
set(sourceInstance, associatedInstance, options) { set(sourceInstance, associatedInstance, options) {
let alreadyAssociated; let alreadyAssociated;
...@@ -229,12 +233,13 @@ class HasOne extends Association { ...@@ -229,12 +233,13 @@ class HasOne extends Association {
/** /**
* Create a new instance of the associated model and associate it with this. * 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. * @param {Object} [options] Options passed to `target.create` and setAssociation.
* *
* @see {@link Model#create} for a full explanation of options * @see {@link Model#create} for a full explanation of options
* *
* @return {Promise} * @returns {Promise}
*/ */
create(sourceInstance, values, options) { create(sourceInstance, values, options) {
values = values || {}; values = values || {};
......
...@@ -45,10 +45,12 @@ exports.addForeignKeyConstraints = addForeignKeyConstraints; ...@@ -45,10 +45,12 @@ exports.addForeignKeyConstraints = addForeignKeyConstraints;
* Mixin (inject) association methods to model prototype * Mixin (inject) association methods to model prototype
* *
* @private * @private
* @param {Object} Association instance *
* @param {Object} Model prototype * @param {Object} association instance
* @param {Array} Method names to inject * @param {Object} obj Model prototype
* @param {Object} Mapping between model and association method names * @param {Array} methods Method names to inject
* @param {Object} aliases Mapping between model and association method names
*
*/ */
function mixinMethods(association, obj, methods, aliases) { function mixinMethods(association, obj, methods, aliases) {
aliases = aliases || {}; aliases = aliases || {};
......
...@@ -40,6 +40,15 @@ ABSTRACT.prototype.bindParam = function bindParam(value, options) { ...@@ -40,6 +40,15 @@ ABSTRACT.prototype.bindParam = function bindParam(value, options) {
return options.bindParam(this.stringify(value, options)); return options.bindParam(this.stringify(value, options));
}; };
/**
* STRING A variable length string
*
* @param {number} [length=255] length of string
* @param {boolean} [binary=false] Is this binary?
*
* @namespace DataTypes.STRING
*
*/
function STRING(length, binary) { function STRING(length, binary) {
const options = typeof length === 'object' && length || {length, binary}; const options = typeof length === 'object' && length || {length, binary};
...@@ -73,6 +82,14 @@ Object.defineProperty(STRING.prototype, 'BINARY', { ...@@ -73,6 +82,14 @@ Object.defineProperty(STRING.prototype, 'BINARY', {
} }
}); });
/**
* CHAR A fixed length string
*
* @param {number} [length=255] length of string
* @param {boolean} [binary=false] Is this binary?
*
* @namespace DataTypes.CHAR
*/
function CHAR(length, binary) { function CHAR(length, binary) {
const options = typeof length === 'object' && length || {length, binary}; const options = typeof length === 'object' && length || {length, binary};
...@@ -86,6 +103,13 @@ CHAR.prototype.toSql = function toSql() { ...@@ -86,6 +103,13 @@ CHAR.prototype.toSql = function toSql() {
return 'CHAR(' + this._length + ')' + (this._binary ? ' BINARY' : ''); return 'CHAR(' + this._length + ')' + (this._binary ? ' BINARY' : '');
}; };
/**
* Unlimited length TEXT column
*
* @param {string} [length=''] could be tiny, medium, long.
*
* @namespace DataTypes.TEXT
*/
function TEXT(length) { function TEXT(length) {
const options = typeof length === 'object' && length || {length}; const options = typeof length === 'object' && length || {length};
if (!(this instanceof TEXT)) return new TEXT(options); if (!(this instanceof TEXT)) return new TEXT(options);
...@@ -115,6 +139,19 @@ TEXT.prototype.validate = function validate(value) { ...@@ -115,6 +139,19 @@ TEXT.prototype.validate = function validate(value) {
return true; return true;
}; };
/**
* Base number type which is used to build other types
*
* @param {Object} options type options
* @param {string|number} [options.length] length of type, like `INT(4)`
* @param {boolean} [options.zerofill] Is zero filled?
* @param {boolean} [options.unsigned] Is unsigned?
* @param {string|number} [options.decimals] number of decimal points, used with length `FLOAT(5, 4)`
* @param {string|number} [options.precision] defines precision for decimal type
* @param {string|number} [options.scale] defines scale for decimal type
*
* @namespace DataTypes.NUMBER
*/
function NUMBER(options) { function NUMBER(options) {
this.options = options; this.options = options;
this._length = options.length; this._length = options.length;
...@@ -144,7 +181,6 @@ NUMBER.prototype.toSql = function toSql() { ...@@ -144,7 +181,6 @@ NUMBER.prototype.toSql = function toSql() {
} }
return result; return result;
}; };
NUMBER.prototype.validate = function(value) { NUMBER.prototype.validate = function(value) {
if (!Validator.isFloat(String(value))) { if (!Validator.isFloat(String(value))) {
throw new sequelizeErrors.ValidationError(util.format('%j is not a valid ' + _.toLower(this.key), value)); throw new sequelizeErrors.ValidationError(util.format('%j is not a valid ' + _.toLower(this.key), value));
...@@ -152,7 +188,6 @@ NUMBER.prototype.validate = function(value) { ...@@ -152,7 +188,6 @@ NUMBER.prototype.validate = function(value) {
return true; return true;
}; };
Object.defineProperty(NUMBER.prototype, 'UNSIGNED', { Object.defineProperty(NUMBER.prototype, 'UNSIGNED', {
get() { get() {
this._unsigned = true; this._unsigned = true;
...@@ -168,6 +203,13 @@ Object.defineProperty(NUMBER.prototype, 'ZEROFILL', { ...@@ -168,6 +203,13 @@ Object.defineProperty(NUMBER.prototype, 'ZEROFILL', {
} }
}); });
/**
* A 32 bit integer
*
* @param {string|number} [length] Integer length, INT(12)
*
* @namespace DataTypes.INTEGER
*/
function INTEGER(length) { function INTEGER(length) {
const options = typeof length === 'object' && length || {length}; const options = typeof length === 'object' && length || {length};
if (!(this instanceof INTEGER)) return new INTEGER(options); if (!(this instanceof INTEGER)) return new INTEGER(options);
...@@ -184,6 +226,13 @@ INTEGER.prototype.validate = function validate(value) { ...@@ -184,6 +226,13 @@ INTEGER.prototype.validate = function validate(value) {
return true; return true;
}; };
/**
* A 8 bit integer
*
* @param {string|number} [length] Integer length
*
* @namespace DataTypes.TINYINT
*/
function TINYINT(length) { function TINYINT(length) {
const options = typeof length === 'object' && length || {length}; const options = typeof length === 'object' && length || {length};
if (!(this instanceof TINYINT)) return new TINYINT(options); if (!(this instanceof TINYINT)) return new TINYINT(options);
...@@ -193,6 +242,13 @@ inherits(TINYINT, INTEGER); ...@@ -193,6 +242,13 @@ inherits(TINYINT, INTEGER);
TINYINT.prototype.key = TINYINT.key = 'TINYINT'; TINYINT.prototype.key = TINYINT.key = 'TINYINT';
/**
* A 16 bit integer
*
* @param {string|number} [length] Integer length
*
* @namespace DataTypes.SMALLINT
*/
function SMALLINT(length) { function SMALLINT(length) {
const options = typeof length === 'object' && length || {length}; const options = typeof length === 'object' && length || {length};
if (!(this instanceof SMALLINT)) return new SMALLINT(options); if (!(this instanceof SMALLINT)) return new SMALLINT(options);
...@@ -202,6 +258,13 @@ inherits(SMALLINT, INTEGER); ...@@ -202,6 +258,13 @@ inherits(SMALLINT, INTEGER);
SMALLINT.prototype.key = SMALLINT.key = 'SMALLINT'; SMALLINT.prototype.key = SMALLINT.key = 'SMALLINT';
/**
* A 24 bit integer
*
* @param {string|number} [length] Integer length
*
* @namespace DataTypes.MEDIUMINT
*/
function MEDIUMINT(length) { function MEDIUMINT(length) {
const options = typeof length === 'object' && length || {length}; const options = typeof length === 'object' && length || {length};
if (!(this instanceof MEDIUMINT)) return new MEDIUMINT(options); if (!(this instanceof MEDIUMINT)) return new MEDIUMINT(options);
...@@ -211,6 +274,13 @@ inherits(MEDIUMINT, INTEGER); ...@@ -211,6 +274,13 @@ inherits(MEDIUMINT, INTEGER);
MEDIUMINT.prototype.key = MEDIUMINT.key = 'MEDIUMINT'; MEDIUMINT.prototype.key = MEDIUMINT.key = 'MEDIUMINT';
/**
* A 64 bit integer
*
* @param {string|number} [length] Integer length
*
* @namespace DataTypes.BIGINT
*/
function BIGINT(length) { function BIGINT(length) {
const options = typeof length === 'object' && length || {length}; const options = typeof length === 'object' && length || {length};
if (!(this instanceof BIGINT)) return new BIGINT(options); if (!(this instanceof BIGINT)) return new BIGINT(options);
...@@ -220,6 +290,14 @@ inherits(BIGINT, INTEGER); ...@@ -220,6 +290,14 @@ inherits(BIGINT, INTEGER);
BIGINT.prototype.key = BIGINT.key = 'BIGINT'; BIGINT.prototype.key = BIGINT.key = 'BIGINT';
/**
* Floating point number (4-byte precision).
*
* @param {string|number} [length] length of type, like `FLOAT(4)`
* @param {string|number} [decimals] number of decimal points, used with length `FLOAT(5, 4)`
*
* @namespace DataTypes.FLOAT
*/
function FLOAT(length, decimals) { function FLOAT(length, decimals) {
const options = typeof length === 'object' && length || {length, decimals}; const options = typeof length === 'object' && length || {length, decimals};
if (!(this instanceof FLOAT)) return new FLOAT(options); if (!(this instanceof FLOAT)) return new FLOAT(options);
...@@ -236,6 +314,14 @@ FLOAT.prototype.validate = function validate(value) { ...@@ -236,6 +314,14 @@ FLOAT.prototype.validate = function validate(value) {
return true; return true;
}; };
/**
* Floating point number (4-byte precision).
*
* @param {string|number} [length] length of type, like `REAL(4)`
* @param {string|number} [decimals] number of decimal points, used with length `REAL(5, 4)`
*
* @namespace DataTypes.REAL
*/
function REAL(length, decimals) { function REAL(length, decimals) {
const options = typeof length === 'object' && length || {length, decimals}; const options = typeof length === 'object' && length || {length, decimals};
if (!(this instanceof REAL)) return new REAL(options); if (!(this instanceof REAL)) return new REAL(options);
...@@ -245,6 +331,14 @@ inherits(REAL, NUMBER); ...@@ -245,6 +331,14 @@ inherits(REAL, NUMBER);
REAL.prototype.key = REAL.key = 'REAL'; REAL.prototype.key = REAL.key = 'REAL';
/**
* Floating point number (8-byte precision).
*
* @param {string|number} [length] length of type, like `DOUBLE PRECISION(25)`
* @param {string|number} [decimals] number of decimal points, used with length `DOUBLE PRECISION(25, 10)`
*
* @namespace DataTypes.DOUBLE
*/
function DOUBLE(length, decimals) { function DOUBLE(length, decimals) {
const options = typeof length === 'object' && length || {length, decimals}; const options = typeof length === 'object' && length || {length, decimals};
if (!(this instanceof DOUBLE)) return new DOUBLE(options); if (!(this instanceof DOUBLE)) return new DOUBLE(options);
...@@ -254,6 +348,14 @@ inherits(DOUBLE, NUMBER); ...@@ -254,6 +348,14 @@ inherits(DOUBLE, NUMBER);
DOUBLE.prototype.key = DOUBLE.key = 'DOUBLE PRECISION'; DOUBLE.prototype.key = DOUBLE.key = 'DOUBLE PRECISION';
/**
* Decimal type, variable precision, take length as specified by user
*
* @param {string|number} [precision] defines precision
* @param {string|number} [scale] defines scale
*
* @namespace DataTypes.DECIMAL
*/
function DECIMAL(precision, scale) { function DECIMAL(precision, scale) {
const options = typeof precision === 'object' && precision || {precision, scale}; const options = typeof precision === 'object' && precision || {precision, scale};
if (!(this instanceof DECIMAL)) return new DECIMAL(options); if (!(this instanceof DECIMAL)) return new DECIMAL(options);
...@@ -298,6 +400,11 @@ for (const floating of [FLOAT, DOUBLE, REAL]) { ...@@ -298,6 +400,11 @@ for (const floating of [FLOAT, DOUBLE, REAL]) {
}; };
} }
/**
* A boolean / tinyint column, depending on dialect
*
* @namespace DataTypes.BOOLEAN
*/
function BOOLEAN() { function BOOLEAN() {
if (!(this instanceof BOOLEAN)) return new BOOLEAN(); if (!(this instanceof BOOLEAN)) return new BOOLEAN();
} }
...@@ -336,6 +443,11 @@ BOOLEAN.prototype._sanitize = function _sanitize(value) { ...@@ -336,6 +443,11 @@ BOOLEAN.prototype._sanitize = function _sanitize(value) {
}; };
BOOLEAN.parse = BOOLEAN.prototype._sanitize; BOOLEAN.parse = BOOLEAN.prototype._sanitize;
/**
* A time column
*
* @namespace DataTypes.TIME
*/
function TIME() { function TIME() {
if (!(this instanceof TIME)) return new TIME(); if (!(this instanceof TIME)) return new TIME();
} }
...@@ -346,6 +458,13 @@ TIME.prototype.toSql = function toSql() { ...@@ -346,6 +458,13 @@ TIME.prototype.toSql = function toSql() {
return 'TIME'; return 'TIME';
}; };
/**
* Date column with timezone, default is UTC
*
* @param {string|number} [length] precision to allow storing milliseconds
*
* @namespace DataTypes.DATE
*/
function DATE(length) { function DATE(length) {
const options = typeof length === 'object' && length || {length}; const options = typeof length === 'object' && length || {length};
...@@ -416,6 +535,11 @@ DATE.prototype._stringify = function _stringify(date, options) { ...@@ -416,6 +535,11 @@ DATE.prototype._stringify = function _stringify(date, options) {
return date.format('YYYY-MM-DD HH:mm:ss.SSS Z'); return date.format('YYYY-MM-DD HH:mm:ss.SSS Z');
}; };
/**
* A date only column (no timestamp)
*
* @namespace DataTypes.DATEONLY
*/
function DATEONLY() { function DATEONLY() {
if (!(this instanceof DATEONLY)) return new DATEONLY(); if (!(this instanceof DATEONLY)) return new DATEONLY();
} }
...@@ -451,6 +575,11 @@ DATEONLY.prototype._isChanged = function _isChanged(value, originalValue) { ...@@ -451,6 +575,11 @@ DATEONLY.prototype._isChanged = function _isChanged(value, originalValue) {
return true; return true;
}; };
/**
* A key / value store column. Only available in Postgres.
*
* @namespace DataTypes.HSTORE
*/
function HSTORE() { function HSTORE() {
if (!(this instanceof HSTORE)) return new HSTORE(); if (!(this instanceof HSTORE)) return new HSTORE();
} }
...@@ -465,6 +594,11 @@ HSTORE.prototype.validate = function validate(value) { ...@@ -465,6 +594,11 @@ HSTORE.prototype.validate = function validate(value) {
return true; return true;
}; };
/**
* A JSON string column. Available in MySQL, Postgres and SQLite
*
* @namespace DataTypes.JSON
*/
function JSONTYPE() { function JSONTYPE() {
if (!(this instanceof JSONTYPE)) return new JSONTYPE(); if (!(this instanceof JSONTYPE)) return new JSONTYPE();
} }
...@@ -479,6 +613,11 @@ JSONTYPE.prototype._stringify = function _stringify(value) { ...@@ -479,6 +613,11 @@ JSONTYPE.prototype._stringify = function _stringify(value) {
return JSON.stringify(value); return JSON.stringify(value);
}; };
/**
* A binary storage JSON column. Only available in Postgres.
*
* @namespace DataTypes.JSONB
*/
function JSONB() { function JSONB() {
if (!(this instanceof JSONB)) return new JSONB(); if (!(this instanceof JSONB)) return new JSONB();
JSONTYPE.call(this); JSONTYPE.call(this);
...@@ -487,6 +626,11 @@ inherits(JSONB, JSONTYPE); ...@@ -487,6 +626,11 @@ inherits(JSONB, JSONTYPE);
JSONB.prototype.key = JSONB.key = 'JSONB'; JSONB.prototype.key = JSONB.key = 'JSONB';
/**
* A default value of the current timestamp
*
* @namespace DataTypes.NOW
*/
function NOW() { function NOW() {
if (!(this instanceof NOW)) return new NOW(); if (!(this instanceof NOW)) return new NOW();
} }
...@@ -494,6 +638,14 @@ inherits(NOW, ABSTRACT); ...@@ -494,6 +638,14 @@ inherits(NOW, ABSTRACT);
NOW.prototype.key = NOW.key = 'NOW'; NOW.prototype.key = NOW.key = 'NOW';
/**
* Binary storage
*
* @param {string} [length=''] could be tiny, medium, long.
*
* @namespace DataTypes.BLOB
*
*/
function BLOB(length) { function BLOB(length) {
const options = typeof length === 'object' && length || {length}; const options = typeof length === 'object' && length || {length};
if (!(this instanceof BLOB)) return new BLOB(options); if (!(this instanceof BLOB)) return new BLOB(options);
...@@ -552,6 +704,14 @@ BLOB.prototype._bindParam = function _bindParam(value, options) { ...@@ -552,6 +704,14 @@ BLOB.prototype._bindParam = function _bindParam(value, options) {
return options.bindParam(value); return options.bindParam(value);
}; };
/**
* 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
*
* @param {<DataTypes>} subtype A subtype for range, like RANGE(DATE)
*
* @namespace DataTypes.RANGE
*/
function RANGE(subtype) { function RANGE(subtype) {
const options = _.isPlainObject(subtype) ? subtype : {subtype}; const options = _.isPlainObject(subtype) ? subtype : {subtype};
...@@ -605,6 +765,12 @@ RANGE.prototype.validate = function validate(value) { ...@@ -605,6 +765,12 @@ RANGE.prototype.validate = function validate(value) {
return true; return true;
}; };
/**
* A column storing a unique universal identifier.
* Use with `UUIDV1` or `UUIDV4` for default values.
*
* @namespace DataTypes.UUID
*/
function UUID() { function UUID() {
if (!(this instanceof UUID)) return new UUID(); if (!(this instanceof UUID)) return new UUID();
} }
...@@ -619,6 +785,11 @@ UUID.prototype.validate = function validate(value, options) { ...@@ -619,6 +785,11 @@ UUID.prototype.validate = function validate(value, options) {
return true; return true;
}; };
/**
* A default unique universal identifier generated following the UUID v1 standard
*
* @namespace DataTypes.UUIDV1
*/
function UUIDV1() { function UUIDV1() {
if (!(this instanceof UUIDV1)) return new UUIDV1(); if (!(this instanceof UUIDV1)) return new UUIDV1();
} }
...@@ -633,6 +804,11 @@ UUIDV1.prototype.validate = function validate(value, options) { ...@@ -633,6 +804,11 @@ UUIDV1.prototype.validate = function validate(value, options) {
return true; return true;
}; };
/**
* A default unique universal identifier generated following the UUID v4 standard
*
* @namespace DataTypes.UUIDV4
*/
function UUIDV4() { function UUIDV4() {
if (!(this instanceof UUIDV4)) return new UUIDV4(); if (!(this instanceof UUIDV4)) return new UUIDV4();
} }
...@@ -647,6 +823,51 @@ UUIDV4.prototype.validate = function validate(value, options) { ...@@ -647,6 +823,51 @@ UUIDV4.prototype.validate = function validate(value, options) {
return true; return true;
}; };
/**
* 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
* this.setDataValue('password', val);
* this.setDataValue('password_hash', this.salt + val);
* },
* validate: {
* isLongEnough: function (val) {
* if (val.length < 7) {
* throw new Error("Please choose a longer password")
* }
* }
* }
* }
* })
*
* # In the above code the password is stored plainly in the password field so it can be validated, but is never stored in the DB.
*
* @example <caption>Virtual with dependency fields</caption>
* {
* active: {
* type: new DataTypes.VIRTUAL(DataTypes.BOOLEAN, ['createdAt']),
* get: function() {
* return this.get('createdAt') > Date.now() - (7 * 24 * 60 * 60 * 1000)
* }
* }
* }
*
* @param {<DataTypes>} [ReturnType] return type for virtual type
* @param {Array} [fields] array of fields this virtual type is dependent on
*
* @namespace DataTypes.VIRTUAL
*
*/
function VIRTUAL(ReturnType, fields) { function VIRTUAL(ReturnType, fields) {
if (!(this instanceof VIRTUAL)) return new VIRTUAL(ReturnType, fields); if (!(this instanceof VIRTUAL)) return new VIRTUAL(ReturnType, fields);
if (typeof ReturnType === 'function') ReturnType = new ReturnType(); if (typeof ReturnType === 'function') ReturnType = new ReturnType();
...@@ -658,6 +879,21 @@ inherits(VIRTUAL, ABSTRACT); ...@@ -658,6 +879,21 @@ inherits(VIRTUAL, ABSTRACT);
VIRTUAL.prototype.key = VIRTUAL.key = 'VIRTUAL'; VIRTUAL.prototype.key = VIRTUAL.key = 'VIRTUAL';
/**
* An enumeration, Postgres Only
*
* @example
* DataTypes.ENUM('value', 'another value')
* DataTypes.ENUM(['value', 'another value'])
* DataTypes.ENUM({
* values: ['value', 'another value']
* })
*
* @param {Array|Object} value either array of values or options object with values array. It also supports variadic values
*
* @namespace DataTypes.ENUM
*
*/
function ENUM(value) { function ENUM(value) {
const options = typeof value === 'object' && !Array.isArray(value) && value || { const options = typeof value === 'object' && !Array.isArray(value) && value || {
values: Array.prototype.slice.call(arguments).reduce((result, element) => { values: Array.prototype.slice.call(arguments).reduce((result, element) => {
...@@ -679,6 +915,16 @@ ENUM.prototype.validate = function validate(value) { ...@@ -679,6 +915,16 @@ ENUM.prototype.validate = function validate(value) {
return true; return true;
}; };
/**
* An array of `type`. Only available in Postgres.
*
* @example
* DataTypes.ARRAY(DataTypes.DECIMAL)`.
*
* @param {<DataTypes>} type type of array values
*
* @namespace DataTypes.ARRAY
*/
function ARRAY(type) { function ARRAY(type) {
const options = _.isPlainObject(type) ? type : {type}; const options = _.isPlainObject(type) ? type : {type};
if (!(this instanceof ARRAY)) return new ARRAY(options); if (!(this instanceof ARRAY)) return new ARRAY(options);
...@@ -701,6 +947,56 @@ ARRAY.is = function is(obj, type) { ...@@ -701,6 +947,56 @@ ARRAY.is = function is(obj, type) {
return obj instanceof ARRAY && obj.type instanceof type; return obj instanceof ARRAY && obj.type instanceof type;
}; };
/**
* 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:
*
* @example <caption>Defining a Geometry type attribute</caption>
* DataTypes.GEOMETRY
* DataTypes.GEOMETRY('POINT')
* DataTypes.GEOMETRY('POINT', 4326)
*
* @example <caption>Create a new point</caption>
* const point = { type: 'Point', coordinates: [39.807222,-76.984722]};
*
* User.create({username: 'username', geometry: point });
*
* @example <caption>Create a new linestring</caption>
* const line = { type: 'LineString', 'coordinates': [ [100.0, 0.0], [101.0, 1.0] ] };
*
* User.create({username: 'username', geometry: line });
*
* @example <caption>Create a new polygon</caption>
* const polygon = { type: 'Polygon', coordinates: [
* [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],
* [100.0, 1.0], [100.0, 0.0] ]
* ]};
*
* User.create({username: 'username', geometry: polygon });
* @example <caption>Create a new point with a custom SRID</caption>
* const point = {
* type: 'Point',
* coordinates: [39.807222,-76.984722],
* crs: { type: 'name', properties: { name: 'EPSG:4326'} }
* };
*
* User.create({username: 'username', geometry: point })
*
* @param {string} [type] Type of geometry data
* @param {string} [srid] SRID of type
*
* @see {@link DataTypes.GEOGRAPHY}
* @namespace DataTypes.GEOMETRY
*/
function GEOMETRY(type, srid) { function GEOMETRY(type, srid) {
const options = _.isPlainObject(type) ? type : {type, srid}; const options = _.isPlainObject(type) ? type : {type, srid};
...@@ -722,6 +1018,32 @@ GEOMETRY.prototype._bindParam = function _bindParam(value, options) { ...@@ -722,6 +1018,32 @@ GEOMETRY.prototype._bindParam = function _bindParam(value, options) {
return 'GeomFromText(' + options.bindParam(wkx.Geometry.parseGeoJSON(value).toWkt()) + ')'; return 'GeomFromText(' + options.bindParam(wkx.Geometry.parseGeoJSON(value).toWkt()) + ')';
}; };
/**
* 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>
* DataTypes.GEOGRAPHY
* DataTypes.GEOGRAPHY('POINT')
* DataTypes.GEOGRAPHY('POINT', 4326)
*
* @param {string} [type] Type of geography data
* @param {string} [srid] SRID of type
*
* @namespace DataTypes.GEOGRAPHY
*/
function GEOGRAPHY(type, srid) { function GEOGRAPHY(type, srid) {
const options = _.isPlainObject(type) ? type : {type, srid}; const options = _.isPlainObject(type) ? type : {type, srid};
...@@ -743,6 +1065,13 @@ GEOGRAPHY.prototype._bindParam = function _bindParam(value, options) { ...@@ -743,6 +1065,13 @@ GEOGRAPHY.prototype._bindParam = function _bindParam(value, options) {
return 'GeomFromText(' + options.bindParam(wkx.Geometry.parseGeoJSON(value).toWkt()) + ')'; return 'GeomFromText(' + options.bindParam(wkx.Geometry.parseGeoJSON(value).toWkt()) + ')';
}; };
/**
* The cidr type holds an IPv4 or IPv6 network specification. Takes 7 or 19 bytes.
*
* Only available for Postgres
*
* @namespace DataTypes.CIDR
*/
function CIDR() { function CIDR() {
if (!(this instanceof CIDR)) return new CIDR(); if (!(this instanceof CIDR)) return new CIDR();
} }
...@@ -758,6 +1087,13 @@ CIDR.prototype.validate = function validate(value) { ...@@ -758,6 +1087,13 @@ CIDR.prototype.validate = function validate(value) {
return true; return true;
}; };
/**
* 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
*/
function INET() { function INET() {
if (!(this instanceof INET)) return new INET(); if (!(this instanceof INET)) return new INET();
} }
...@@ -773,6 +1109,13 @@ INET.prototype.validate = function validate(value) { ...@@ -773,6 +1109,13 @@ INET.prototype.validate = function validate(value) {
return true; return true;
}; };
/**
* The MACADDR type stores MAC addresses. Takes 6 bytes
*
* Only available for Postgres
*
* @namespace DataTypes.MACADDR
*/
function MACADDR() { function MACADDR() {
if (!(this instanceof MACADDR)) return new MACADDR(); if (!(this instanceof MACADDR)) return new MACADDR();
} }
...@@ -813,7 +1156,7 @@ for (const helper of Object.keys(helpers)) { ...@@ -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 data types are used when defining a new model using `Sequelize.define`, like this:
* ```js * ```js
* sequelize.define('model', { * sequelize.define('model', {
* column: DataTypes.INTEGER * column: DataTypes.INTEGER
...@@ -831,7 +1174,6 @@ for (const helper of Object.keys(helpers)) { ...@@ -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` * * All number types (`INTEGER`, `BIGINT`, `FLOAT`, `DOUBLE`, `REAL`, `DECIMAL`) expose the properties `UNSIGNED` and `ZEROFILL`
* * The `CHAR` and `STRING` types expose the `BINARY` property * * 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 * 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: * defining default values. For example, to get a uuid field with a default value generated following v1 of the UUID standard:
* ```js` * ```js`
...@@ -858,109 +1200,7 @@ for (const helper of Object.keys(helpers)) { ...@@ -858,109 +1200,7 @@ for (const helper of Object.keys(helpers)) {
* }) * })
* ``` * ```
* *
* @property {function(length=255: integer)} STRING A variable length string * @namespace DataTypes
* @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(precision: integer, scale: integer)} DECIMAL Decimal number.
* @property {function(length: integer, decimals: integer)} REAL Floating point number (4-byte precision).
* @property {function} BOOLEAN A boolean / tinyint column, depending on dialect
* @property {function(length: string)} BLOB Binary storage. Available lengths: `tiny`, `medium`, `long`
* @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 });
*
* // Create a new linestring:
* const line = { type: 'LineString', 'coordinates': [ [100.0, 0.0], [101.0, 1.0] ] };
*
* User.create({username: 'username', geometry: line });
*
* // Create a new polygon:
* const polygon = { type: 'Polygon', coordinates: [
* [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],
* [100.0, 1.0], [100.0, 0.0] ]
* ]};
*
* User.create({username: 'username', geometry: polygon });
* // Create a new point with a custom SRID:
* const point = {
* type: 'Point',
* coordinates: [39.807222,-76.984722],
* crs: { type: 'name', properties: { name: 'EPSG:4326'} }
* };
*
* 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
* this.setDataValue('password', val);
* this.setDataValue('password_hash', this.salt + val);
* },
* validate: {
* isLongEnough: function (val) {
* if (val.length < 7) {
* throw new Error("Please choose a longer password")
* }
* }
* }
* }
* })
* ```
* In the above code the password is stored plainly in the password field so it can be validated, but is never stored in the DB.
*
* 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.
* ```js
* {
* active: {
* type: new DataTypes.VIRTUAL(DataTypes.BOOLEAN, ['createdAt']),
* get: function() {
* return this.get('createdAt') > Date.now() - (7 * 24 * 60 * 60 * 1000)
* }
* }
* }
* ```
*/ */
const DataTypes = module.exports = { const DataTypes = module.exports = {
ABSTRACT, ABSTRACT,
......
...@@ -62,7 +62,7 @@ class ConnectionManager { ...@@ -62,7 +62,7 @@ class ConnectionManager {
* Handler which executes on process exit or connection manager shutdown * Handler which executes on process exit or connection manager shutdown
* *
* @private * @private
* @return {Promise} * @returns {Promise}
*/ */
_onProcessExit() { _onProcessExit() {
if (!this.pool) { if (!this.pool) {
...@@ -78,7 +78,7 @@ class ConnectionManager { ...@@ -78,7 +78,7 @@ class ConnectionManager {
/** /**
* Drain the pool and close it permanently * Drain the pool and close it permanently
* *
* @return {Promise} * @returns {Promise}
*/ */
close() { close() {
// Mark close of pool // Mark close of pool
...@@ -234,10 +234,10 @@ class ConnectionManager { ...@@ -234,10 +234,10 @@ class ConnectionManager {
* *
* @param {Object} [options] Pool options * @param {Object} [options] Pool options
* @param {Integer} [options.priority] Set priority for this call. Read more at https://github.com/coopernurse/node-pool#priority-queueing * @param {Integer} [options.priority] Set priority for this call. Read more at https://github.com/coopernurse/node-pool#priority-queueing
* @param {String} [options.type] Set which replica to use. Available options are `read` and `write` * @param {string} [options.type] Set which replica to use. Available options are `read` and `write`
* @param {Boolean} [options.useMaster=false] Force master or write replica to get connection from * @param {boolean} [options.useMaster=false] Force master or write replica to get connection from
* *
* @return {Promise<Connection>} * @returns {Promise<Connection>}
*/ */
getConnection(options) { getConnection(options) {
options = options || {}; options = options || {};
...@@ -282,7 +282,7 @@ class ConnectionManager { ...@@ -282,7 +282,7 @@ class ConnectionManager {
* *
* @param {Connection} connection * @param {Connection} connection
* *
* @return {Promise} * @returns {Promise}
*/ */
releaseConnection(connection) { releaseConnection(connection) {
return this.pool.release(connection) return this.pool.release(connection)
...@@ -296,7 +296,7 @@ class ConnectionManager { ...@@ -296,7 +296,7 @@ class ConnectionManager {
* *
* @param {Object|Error} mayBeConnection Object which can be either connection or error * @param {Object|Error} mayBeConnection Object which can be either connection or error
* *
* @return {Promise<Connection>} * @returns {Promise<Connection>}
*/ */
_determineConnection(mayBeConnection) { _determineConnection(mayBeConnection) {
if (mayBeConnection instanceof Error) { if (mayBeConnection instanceof Error) {
...@@ -313,7 +313,7 @@ class ConnectionManager { ...@@ -313,7 +313,7 @@ class ConnectionManager {
* *
* @param {*} config Connection config * @param {*} config Connection config
* @private * @private
* @return {Promise<Connection>} * @returns {Promise<Connection>}
*/ */
_connect(config) { _connect(config) {
return this.sequelize.runHooks('beforeConnect', config) return this.sequelize.runHooks('beforeConnect', config)
...@@ -326,7 +326,7 @@ class ConnectionManager { ...@@ -326,7 +326,7 @@ class ConnectionManager {
* *
* @param {Connection} connection * @param {Connection} connection
* @private * @private
* @return {Promise} * @returns {Promise}
*/ */
_disconnect(connection) { _disconnect(connection) {
return this.dialect.connectionManager.disconnect(connection); return this.dialect.connectionManager.disconnect(connection);
...@@ -337,7 +337,7 @@ class ConnectionManager { ...@@ -337,7 +337,7 @@ class ConnectionManager {
* *
* @param {Connection} connection * @param {Connection} connection
* *
* @return {Boolean} * @returns {boolean}
*/ */
_validate(connection) { _validate(connection) {
if (!this.dialect.connectionManager.validate) { if (!this.dialect.connectionManager.validate) {
......
...@@ -95,7 +95,7 @@ class QueryGenerator { ...@@ -95,7 +95,7 @@ class QueryGenerator {
/** /**
* Returns an insert into command * Returns an insert into command
* *
* @param {String} table * @param {string} table
* @param {Object} valueHash attribute value pairs * @param {Object} valueHash attribute value pairs
* @param {Object} modelAttributes * @param {Object} modelAttributes
* @param {Object} [options] * @param {Object} [options]
...@@ -262,7 +262,7 @@ class QueryGenerator { ...@@ -262,7 +262,7 @@ class QueryGenerator {
/** /**
* Returns an insert into command for multiple values. * Returns an insert into command for multiple values.
* *
* @param {String} tableName * @param {string} tableName
* @param {Object} fieldValueHashes * @param {Object} fieldValueHashes
* @param {Object} options * @param {Object} options
* @param {Object} fieldMappedAttributes * @param {Object} fieldMappedAttributes
...@@ -330,7 +330,7 @@ class QueryGenerator { ...@@ -330,7 +330,7 @@ class QueryGenerator {
/** /**
* Returns an update query * Returns an update query
* *
* @param {String} tableName * @param {string} tableName
* @param {Object} attrValueHash * @param {Object} attrValueHash
* @param {Object} where A hash with conditions (e.g. {name: 'foo'}) OR an ID as integer * @param {Object} where A hash with conditions (e.g. {name: 'foo'}) OR an ID as integer
OR a string with conditions (e.g. 'name="foo"'). If you use a string, you have to escape it on your own. OR a string with conditions (e.g. 'name="foo"'). If you use a string, you have to escape it on your own.
...@@ -452,8 +452,8 @@ class QueryGenerator { ...@@ -452,8 +452,8 @@ class QueryGenerator {
/** /**
* Returns an update query using arithmetic operator * Returns an update query using arithmetic operator
* *
* @param {String} operator String with the arithmetic operator (e.g. '+' or '-') * @param {string} operator String with the arithmetic operator (e.g. '+' or '-')
* @param {String} tableName Name of the table * @param {string} tableName Name of the table
* @param {Object} attrValueHash A hash with attribute-value-pairs * @param {Object} attrValueHash A hash with attribute-value-pairs
* @param {Object} where A hash with conditions (e.g. {name: 'foo'}) OR an ID as integer * @param {Object} where A hash with conditions (e.g. {name: 'foo'}) OR an ID as integer
OR a string with conditions (e.g. 'name="foo"'). If you use a string, you have to escape it on your own. OR a string with conditions (e.g. 'name="foo"'). If you use a string, you have to escape it on your own.
...@@ -895,13 +895,13 @@ class QueryGenerator { ...@@ -895,13 +895,13 @@ class QueryGenerator {
/** /**
* Split a list of identifiers by "." and quote each part * Split a list of identifiers by "." and quote each part
* *
* @param {String} dialect Dialect name * @param {string} dialect Dialect name
* @param {String} identifiers * @param {string} identifiers
* @param {Object} [options] * @param {Object} [options]
* @param {Boolean} [options.force=false] * @param {boolean} [options.force=false]
* @param {Boolean} [options.quoteIdentifiers=true] * @param {boolean} [options.quoteIdentifiers=true]
* *
* @returns {String} * @returns {string}
*/ */
quoteIdentifier(identifier, force) { quoteIdentifier(identifier, force) {
return QuoteHelper.quoteIdentifier(this.dialect, identifier, { return QuoteHelper.quoteIdentifier(this.dialect, identifier, {
...@@ -929,7 +929,7 @@ class QueryGenerator { ...@@ -929,7 +929,7 @@ class QueryGenerator {
* @param {String|Object} param table string or object * @param {String|Object} param table string or object
* @param {String|Boolean} alias alias name * @param {String|Boolean} alias alias name
* *
* @returns {String} * @returns {string}
*/ */
quoteTable(param, alias) { quoteTable(param, alias) {
let table = ''; let table = '';
...@@ -1065,9 +1065,9 @@ class QueryGenerator { ...@@ -1065,9 +1065,9 @@ class QueryGenerator {
/** /**
* Generates an SQL query that extract JSON property of given path. * Generates an SQL query that extract JSON property of given path.
* *
* @param {String} column The JSON column * @param {string} column The JSON column
* @param {String|Array<String>} [path] The path to extract (optional) * @param {String|Array<String>} [path] The path to extract (optional)
* @returns {String} The generated sql query * @returns {string} The generated sql query
* @private * @private
*/ */
jsonPathExtractionQuery(column, path) { jsonPathExtractionQuery(column, path) {
...@@ -1946,7 +1946,7 @@ class QueryGenerator { ...@@ -1946,7 +1946,7 @@ class QueryGenerator {
* *
* @param {Object} options An object with selectQuery options. * @param {Object} options An object with selectQuery options.
* @param {Object} options The model passed to the selectQuery. * @param {Object} options The model passed to the selectQuery.
* @return {String} The generated sql query. * @returns {string} The generated sql query.
* @private * @private
*/ */
addLimitAndOffset(options) { addLimitAndOffset(options) {
......
...@@ -23,13 +23,13 @@ const postgresReservedWords = 'all,analyse,analyze,and,any,array,as,asc,asymmetr ...@@ -23,13 +23,13 @@ const postgresReservedWords = 'all,analyse,analyze,and,any,array,as,asc,asymmetr
/** /**
* *
* @param {String} dialect Dialect name * @param {string} dialect Dialect name
* @param {String} identifier Identifier to quote * @param {string} identifier Identifier to quote
* @param {Object} [options] * @param {Object} [options]
* @param {Boolean} [options.force=false] * @param {boolean} [options.force=false]
* @param {Boolean} [options.quoteIdentifiers=true] * @param {boolean} [options.quoteIdentifiers=true]
* *
* @returns {String} * @returns {string}
* @private * @private
*/ */
function quoteIdentifier(dialect, identifier, options) { function quoteIdentifier(dialect, identifier, options) {
...@@ -79,9 +79,9 @@ module.exports.quoteIdentifier = quoteIdentifier; ...@@ -79,9 +79,9 @@ module.exports.quoteIdentifier = quoteIdentifier;
/** /**
* Test if a give string is already quoted * Test if a give string is already quoted
* *
* @param {String} identifier * @param {string} identifier
* *
* @return Boolean * @returns Boolean
* @private * @private
*/ */
function isIdentifierQuoted(identifier) { function isIdentifierQuoted(identifier) {
......
...@@ -6,9 +6,9 @@ const TransactionQueries = { ...@@ -6,9 +6,9 @@ const TransactionQueries = {
/** /**
* Returns a query that starts a transaction. * Returns a query that starts a transaction.
* *
* @param {Boolean} value A boolean that states whether autocommit shall be done or not. * @param {boolean} value A boolean that states whether autocommit shall be done or not.
* @param {Object} options An object with options. * @param {Object} options An object with options.
* @return {String} The generated sql query. * @returns {string} The generated sql query.
* @private * @private
*/ */
setAutocommitQuery(value, options) { setAutocommitQuery(value, options) {
...@@ -27,9 +27,9 @@ const TransactionQueries = { ...@@ -27,9 +27,9 @@ const TransactionQueries = {
/** /**
* Returns a query that sets the transaction isolation level. * Returns a query that sets the transaction isolation level.
* *
* @param {String} value The isolation level. * @param {string} value The isolation level.
* @param {Object} options An object with options. * @param {Object} options An object with options.
* @return {String} The generated sql query. * @returns {string} The generated sql query.
* @private * @private
*/ */
setIsolationLevelQuery(value, options) { setIsolationLevelQuery(value, options) {
...@@ -49,7 +49,7 @@ const TransactionQueries = { ...@@ -49,7 +49,7 @@ const TransactionQueries = {
* *
* @param {Transaction} transaction * @param {Transaction} transaction
* @param {Object} options An object with options. * @param {Object} options An object with options.
* @return {String} The generated sql query. * @returns {string} The generated sql query.
* @private * @private
*/ */
startTransactionQuery(transaction) { startTransactionQuery(transaction) {
...@@ -66,7 +66,7 @@ const TransactionQueries = { ...@@ -66,7 +66,7 @@ const TransactionQueries = {
* *
* @param {Transaction} transaction * @param {Transaction} transaction
* @param {Object} options An object with options. * @param {Object} options An object with options.
* @return {String} The generated sql query. * @returns {string} The generated sql query.
* @private * @private
*/ */
deferConstraintsQuery() {}, deferConstraintsQuery() {},
...@@ -79,7 +79,7 @@ const TransactionQueries = { ...@@ -79,7 +79,7 @@ const TransactionQueries = {
* Returns a query that commits a transaction. * Returns a query that commits a transaction.
* *
* @param {Object} options An object with options. * @param {Object} options An object with options.
* @return {String} The generated sql query. * @returns {string} The generated sql query.
* @private * @private
*/ */
commitTransactionQuery(transaction) { commitTransactionQuery(transaction) {
...@@ -95,7 +95,7 @@ const TransactionQueries = { ...@@ -95,7 +95,7 @@ const TransactionQueries = {
* *
* @param {Transaction} transaction * @param {Transaction} transaction
* @param {Object} options An object with options. * @param {Object} options An object with options.
* @return {String} The generated sql query. * @returns {string} The generated sql query.
* @private * @private
*/ */
rollbackTransactionQuery(transaction) { rollbackTransactionQuery(transaction) {
......
...@@ -95,7 +95,7 @@ class AbstractQuery { ...@@ -95,7 +95,7 @@ class AbstractQuery {
* *
* query.run('SELECT 1') * query.run('SELECT 1')
* *
* @param {String} sql - The SQL query which should be executed. * @param {string} sql - The SQL query which should be executed.
* @private * @private
*/ */
run() { run() {
...@@ -105,7 +105,7 @@ class AbstractQuery { ...@@ -105,7 +105,7 @@ class AbstractQuery {
/** /**
* Check the logging option of the instance and print deprecation warnings. * Check the logging option of the instance and print deprecation warnings.
* *
* @return {void} * @returns {void}
* @private * @private
*/ */
checkLoggingOption() { checkLoggingOption() {
...@@ -118,7 +118,7 @@ class AbstractQuery { ...@@ -118,7 +118,7 @@ class AbstractQuery {
/** /**
* Get the attributes of an insert query, which contains the just inserted id. * Get the attributes of an insert query, which contains the just inserted id.
* *
* @return {String} The field name. * @returns {string} The field name.
* @private * @private
*/ */
getInsertIdField() { getInsertIdField() {
......
...@@ -698,7 +698,7 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator { ...@@ -698,7 +698,7 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator {
/** /**
* Generate common SQL prefix for ForeignKeysQuery. * Generate common SQL prefix for ForeignKeysQuery.
* @returns {String} * @returns {string}
*/ */
_getForeignKeysQueryPrefix(catalogName) { _getForeignKeysQueryPrefix(catalogName) {
return 'SELECT ' + return 'SELECT ' +
...@@ -725,8 +725,8 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator { ...@@ -725,8 +725,8 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator {
/** /**
* Generates an SQL query that returns all foreign keys details of a table. * Generates an SQL query that returns all foreign keys details of a table.
* @param {Stirng|Object} table * @param {Stirng|Object} table
* @param {String} catalogName database name * @param {string} catalogName database name
* @returns {String} * @returns {string}
*/ */
getForeignKeysQuery(table, catalogName) { getForeignKeysQuery(table, catalogName) {
const tableName = table.tableName || table; const tableName = table.tableName || table;
......
...@@ -11,13 +11,12 @@ ...@@ -11,13 +11,12 @@
/** /**
A wrapper that fixes MSSQL's inability to cleanly remove columns from existing tables if they have a default constraint. A wrapper that fixes MSSQL's inability to cleanly remove columns from existing tables if they have a default constraint.
@method removeColumn
@for QueryInterface
@param {String} tableName The name of the table. @param {string} tableName The name of the table.
@param {String} attributeName The name of the attribute that we want to remove. @param {string} attributeName The name of the attribute that we want to remove.
@param {Object} options @param {Object} options
@param {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries @param {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
@private @private
*/ */
const removeColumn = function(tableName, attributeName, options) { const removeColumn = function(tableName, attributeName, options) {
......
...@@ -17,7 +17,7 @@ const parserStore = require('../parserStore')('mysql'); ...@@ -17,7 +17,7 @@ const parserStore = require('../parserStore')('mysql');
* Use https://github.com/sidorares/node-mysql2 to connect with MySQL server * Use https://github.com/sidorares/node-mysql2 to connect with MySQL server
* *
* @extends AbstractConnectionManager * @extends AbstractConnectionManager
* @return Class<ConnectionManager> * @returns Class<ConnectionManager>
* @private * @private
*/ */
...@@ -63,7 +63,7 @@ class ConnectionManager extends AbstractConnectionManager { ...@@ -63,7 +63,7 @@ class ConnectionManager extends AbstractConnectionManager {
* Set the pool handlers on connection.error * Set the pool handlers on connection.error
* Also set proper timezone once conection is connected * Also set proper timezone once conection is connected
* *
* @return Promise<Connection> * @returns Promise<Connection>
* @private * @private
*/ */
connect(config) { connect(config) {
......
...@@ -403,8 +403,8 @@ class MySQLQueryGenerator extends AbstractQueryGenerator { ...@@ -403,8 +403,8 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
/** /**
* Check whether the statmement is json function or simple path * Check whether the statmement is json function or simple path
* *
* @param {String} stmt The statement to validate * @param {string} stmt The statement to validate
* @returns {Boolean} true if the given statement is json function * @returns {boolean} true if the given statement is json function
* @throws {Error} throw if the statement looks like json function but has invalid token * @throws {Error} throw if the statement looks like json function but has invalid token
* @private * @private
*/ */
...@@ -469,7 +469,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator { ...@@ -469,7 +469,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
/** /**
* Generates fields for getForeignKeysQuery * Generates fields for getForeignKeysQuery
* @returns {String} fields * @returns {string} fields
* @private * @private
*/ */
_getForeignKeysQueryFields() { _getForeignKeysQueryFields() {
...@@ -492,9 +492,9 @@ class MySQLQueryGenerator extends AbstractQueryGenerator { ...@@ -492,9 +492,9 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
/** /**
* Generates an SQL query that returns all foreign keys of a table. * Generates an SQL query that returns all foreign keys of a table.
* *
* @param {String} tableName The name of the table. * @param {string} tableName The name of the table.
* @param {String} schemaName The name of the schema. * @param {string} schemaName The name of the schema.
* @return {String} The generated sql query. * @returns {string} The generated sql query.
* @private * @private
*/ */
getForeignKeysQuery(tableName, schemaName) { getForeignKeysQuery(tableName, schemaName) {
...@@ -505,9 +505,9 @@ class MySQLQueryGenerator extends AbstractQueryGenerator { ...@@ -505,9 +505,9 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
/** /**
* Generates an SQL query that returns the foreign key constraint of a given column. * Generates an SQL query that returns the foreign key constraint of a given column.
* *
* @param {String} tableName The name of the table. * @param {string} tableName The name of the table.
* @param {String} columnName The name of the column. * @param {string} columnName The name of the column.
* @return {String} The generated sql query. * @returns {string} The generated sql query.
* @private * @private
*/ */
getForeignKeyQuery(table, columnName) { getForeignKeyQuery(table, columnName) {
...@@ -529,9 +529,9 @@ class MySQLQueryGenerator extends AbstractQueryGenerator { ...@@ -529,9 +529,9 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
/** /**
* Generates an SQL query that removes a foreign key from a table. * Generates an SQL query that removes a foreign key from a table.
* *
* @param {String} tableName The name of the table. * @param {string} tableName The name of the table.
* @param {String} foreignKey The name of the foreign key constraint. * @param {string} foreignKey The name of the foreign key constraint.
* @return {String} The generated sql query. * @returns {string} The generated sql query.
* @private * @private
*/ */
dropForeignKeyQuery(tableName, foreignKey) { dropForeignKeyQuery(tableName, foreignKey) {
......
...@@ -14,12 +14,10 @@ const sequelizeErrors = require('../../errors'); ...@@ -14,12 +14,10 @@ const sequelizeErrors = require('../../errors');
/** /**
A wrapper that fixes MySQL's inability to cleanly remove columns from existing tables if they have a foreign key constraint. A wrapper that fixes MySQL's inability to cleanly remove columns from existing tables if they have a foreign key constraint.
@method removeColumn @param {string} tableName The name of the table.
@for QueryInterface @param {string} columnName The name of the attribute that we want to remove.
@param {String} tableName The name of the table.
@param {String} columnName The name of the attribute that we want to remove.
@param {Object} options @param {Object} options
@private @private
*/ */
function removeColumn(tableName, columnName, options) { function removeColumn(tableName, columnName, options) {
......
...@@ -129,8 +129,8 @@ class PostgresQueryGenerator extends AbstractQueryGenerator { ...@@ -129,8 +129,8 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
/** /**
* Check whether the statmement is json function or simple path * Check whether the statmement is json function or simple path
* *
* @param {String} stmt The statement to validate * @param {string} stmt The statement to validate
* @returns {Boolean} true if the given statement is json function * @returns {boolean} true if the given statement is json function
* @throws {Error} throw if the statement looks like json function but has invalid token * @throws {Error} throw if the statement looks like json function but has invalid token
*/ */
_checkValidJsonStatement(stmt) { _checkValidJsonStatement(stmt) {
...@@ -841,8 +841,8 @@ class PostgresQueryGenerator extends AbstractQueryGenerator { ...@@ -841,8 +841,8 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
/** /**
* Generates an SQL query that returns all foreign keys of a table. * Generates an SQL query that returns all foreign keys of a table.
* *
* @param {String} tableName The name of the table. * @param {string} tableName The name of the table.
* @return {String} The generated sql query. * @returns {string} The generated sql query.
* @private * @private
*/ */
getForeignKeysQuery(tableName) { getForeignKeysQuery(tableName) {
...@@ -852,7 +852,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator { ...@@ -852,7 +852,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
/** /**
* Generate common SQL prefix for getForeignKeyReferencesQuery. * Generate common SQL prefix for getForeignKeyReferencesQuery.
* @returns {String} * @returns {string}
*/ */
_getForeignKeyReferencesQueryPrefix() { _getForeignKeyReferencesQueryPrefix() {
return 'SELECT ' + return 'SELECT ' +
...@@ -878,9 +878,9 @@ class PostgresQueryGenerator extends AbstractQueryGenerator { ...@@ -878,9 +878,9 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
* Generates an SQL query that returns all foreign keys details of a table. * Generates an SQL query that returns all foreign keys details of a table.
* *
* As for getForeignKeysQuery is not compatible with getForeignKeyReferencesQuery, so add a new function. * As for getForeignKeysQuery is not compatible with getForeignKeyReferencesQuery, so add a new function.
* @param {String} tableName * @param {string} tableName
* @param {String} catalogName * @param {string} catalogName
* @param {String} schemaName * @param {string} schemaName
*/ */
getForeignKeyReferencesQuery(tableName, catalogName, schemaName) { getForeignKeyReferencesQuery(tableName, catalogName, schemaName) {
return this._getForeignKeyReferencesQueryPrefix() + return this._getForeignKeyReferencesQueryPrefix() +
...@@ -900,9 +900,9 @@ class PostgresQueryGenerator extends AbstractQueryGenerator { ...@@ -900,9 +900,9 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
/** /**
* Generates an SQL query that removes a foreign key from a table. * Generates an SQL query that removes a foreign key from a table.
* *
* @param {String} tableName The name of the table. * @param {string} tableName The name of the table.
* @param {String} foreignKey The name of the foreign key constraint. * @param {string} foreignKey The name of the foreign key constraint.
* @return {String} The generated sql query. * @returns {string} The generated sql query.
* @private * @private
*/ */
dropForeignKeyQuery(tableName, foreignKey) { dropForeignKeyQuery(tableName, foreignKey) {
......
...@@ -17,12 +17,12 @@ const _ = require('lodash'); ...@@ -17,12 +17,12 @@ const _ = require('lodash');
/** /**
* Ensure enum and their values * Ensure enum and their values
* *
* @param {String} tableName Name of table to create * @param {string} tableName Name of table to create
* @param {Object} attributes Object representing a list of normalized table attributes * @param {Object} attributes Object representing a list of normalized table attributes
* @param {Object} [attributes] * @param {Object} [attributes]
* @param {Model} [model] * @param {Model} [model]
* *
* @return {Promise} * @returns {Promise}
* @private * @private
*/ */
function ensureEnums(tableName, attributes, options, model) { function ensureEnums(tableName, attributes, options, model) {
......
...@@ -78,8 +78,8 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator { ...@@ -78,8 +78,8 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator {
/** /**
* Check whether the statmement is json function or simple path * Check whether the statmement is json function or simple path
* *
* @param {String} stmt The statement to validate * @param {string} stmt The statement to validate
* @returns {Boolean} true if the given statement is json function * @returns {boolean} true if the given statement is json function
* @throws {Error} throw if the statement looks like json function but has invalid token * @throws {Error} throw if the statement looks like json function but has invalid token
*/ */
_checkValidJsonStatement(stmt) { _checkValidJsonStatement(stmt) {
...@@ -490,8 +490,8 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator { ...@@ -490,8 +490,8 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator {
/** /**
* Generates an SQL query that returns all foreign keys of a table. * Generates an SQL query that returns all foreign keys of a table.
* *
* @param {String} tableName The name of the table. * @param {string} tableName The name of the table.
* @return {String} The generated sql query. * @returns {string} The generated sql query.
* @private * @private
*/ */
getForeignKeysQuery(tableName) { getForeignKeysQuery(tableName) {
......
...@@ -18,11 +18,8 @@ const QueryTypes = require('../../query-types'); ...@@ -18,11 +18,8 @@ const QueryTypes = require('../../query-types');
It will create a backup of the table, drop the table afterwards and create a It will create a backup of the table, drop the table afterwards and create a
new table with the same name but without the obsolete column. new table with the same name but without the obsolete column.
@method removeColumn @param {string} tableName The name of the table.
@for QueryInterface @param {string} attributeName The name of the attribute that we want to remove.
@param {String} tableName The name of the table.
@param {String} attributeName The name of the attribute that we want to remove.
@param {Object} options @param {Object} options
@param {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries @param {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
...@@ -48,10 +45,7 @@ exports.removeColumn = removeColumn; ...@@ -48,10 +45,7 @@ exports.removeColumn = removeColumn;
It will create a backup of the table, drop the table afterwards and create a It will create a backup of the table, drop the table afterwards and create a
new table with the same name but with a modified version of the respective column. new table with the same name but with a modified version of the respective column.
@method changeColumn @param {string} tableName The name of the table.
@for QueryInterface
@param {String} tableName The name of the table.
@param {Object} attributes An object with the attribute's name as key and its options as value object. @param {Object} attributes An object with the attribute's name as key and its options as value object.
@param {Object} options @param {Object} options
@param {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries @param {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
...@@ -79,12 +73,9 @@ exports.changeColumn = changeColumn; ...@@ -79,12 +73,9 @@ exports.changeColumn = changeColumn;
It will create a backup of the table, drop the table afterwards and create a It will create a backup of the table, drop the table afterwards and create a
new table with the same name but with a renamed version of the respective column. new table with the same name but with a renamed version of the respective column.
@method renameColumn @param {string} tableName The name of the table.
@for QueryInterface @param {string} attrNameBefore The name of the attribute before it was renamed.
@param {string} attrNameAfter The name of the attribute after it was renamed.
@param {String} tableName The name of the table.
@param {String} attrNameBefore The name of the attribute before it was renamed.
@param {String} attrNameAfter The name of the attribute after it was renamed.
@param {Object} options @param {Object} options
@param {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries @param {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
...@@ -174,7 +165,7 @@ exports.addConstraint = addConstraint; ...@@ -174,7 +165,7 @@ exports.addConstraint = addConstraint;
/** /**
* *
* @param {String} tableName * @param {string} tableName
* @param {Object} options Query Options * @param {Object} options Query Options
* *
* @private * @private
......
...@@ -6,6 +6,8 @@ ...@@ -6,6 +6,8 @@
* *
* This means that errors can be accessed using `Sequelize.ValidationError` or `sequelize.ValidationError` * This means that errors can be accessed using `Sequelize.ValidationError` or `sequelize.ValidationError`
* The Base Error all Sequelize Errors inherit from. * The Base Error all Sequelize Errors inherit from.
*
* @extends Error
*/ */
class BaseError extends Error { class BaseError extends Error {
constructor(message) { constructor(message) {
...@@ -18,6 +20,8 @@ exports.BaseError = BaseError; ...@@ -18,6 +20,8 @@ exports.BaseError = BaseError;
/** /**
* Scope Error. Thrown when the sequelize cannot query the specified scope. * Scope Error. Thrown when the sequelize cannot query the specified scope.
*
* @extends BaseError
*/ */
class SequelizeScopeError extends BaseError { class SequelizeScopeError extends BaseError {
constructor(parent) { constructor(parent) {
...@@ -36,6 +40,8 @@ exports.SequelizeScopeError = SequelizeScopeError; ...@@ -36,6 +40,8 @@ exports.SequelizeScopeError = SequelizeScopeError;
* @param {Array} [errors] Array of ValidationErrorItem objects describing the validation errors * @param {Array} [errors] Array of ValidationErrorItem objects describing the validation errors
* *
* @property errors {ValidationErrorItems[]} * @property errors {ValidationErrorItems[]}
*
* @extends BaseError
*/ */
class ValidationError extends BaseError { class ValidationError extends BaseError {
constructor(message, errors) { constructor(message, errors) {
...@@ -63,7 +69,8 @@ class ValidationError extends BaseError { ...@@ -63,7 +69,8 @@ class ValidationError extends BaseError {
* Gets all validation error items for the path / field specified. * Gets all validation error items for the path / field specified.
* *
* @param {string} path The path to be checked for error items * @param {string} path The path to be checked for error items
* @returns {ValidationErrorItem[]} Validation error items for the specified path *
* @returns {Array<ValidationErrorItem>} Validation error items for the specified path
*/ */
get(path) { get(path) {
return this.errors.reduce((reduced, error) => { return this.errors.reduce((reduced, error) => {
...@@ -78,6 +85,8 @@ exports.ValidationError = ValidationError; ...@@ -78,6 +85,8 @@ exports.ValidationError = ValidationError;
/** /**
* Thrown when attempting to update a stale model instance * Thrown when attempting to update a stale model instance
*
* @extends BaseError
*/ */
class OptimisticLockError extends BaseError { class OptimisticLockError extends BaseError {
constructor(options) { constructor(options) {
...@@ -107,6 +116,8 @@ exports.OptimisticLockError = OptimisticLockError; ...@@ -107,6 +116,8 @@ exports.OptimisticLockError = OptimisticLockError;
/** /**
* A base class for all database related errors. * A base class for all database related errors.
*
* @extends BaseError
*/ */
class DatabaseError extends BaseError { class DatabaseError extends BaseError {
constructor(parent) { constructor(parent) {
...@@ -132,6 +143,8 @@ exports.DatabaseError = DatabaseError; ...@@ -132,6 +143,8 @@ exports.DatabaseError = DatabaseError;
/** /**
* Thrown when a database query times out because of a deadlock * Thrown when a database query times out because of a deadlock
*
* @extends DatabaseError
*/ */
class TimeoutError extends DatabaseError { class TimeoutError extends DatabaseError {
constructor(parent) { constructor(parent) {
...@@ -144,6 +157,8 @@ exports.TimeoutError = TimeoutError; ...@@ -144,6 +157,8 @@ exports.TimeoutError = TimeoutError;
/** /**
* Thrown when a unique constraint is violated in the database * Thrown when a unique constraint is violated in the database
*
* @extends ValidationError
*/ */
class UniqueConstraintError extends ValidationError { class UniqueConstraintError extends ValidationError {
constructor(options) { constructor(options) {
...@@ -166,6 +181,8 @@ exports.UniqueConstraintError = UniqueConstraintError; ...@@ -166,6 +181,8 @@ exports.UniqueConstraintError = UniqueConstraintError;
/** /**
* Thrown when a foreign key constraint is violated in the database * Thrown when a foreign key constraint is violated in the database
*
* @extends DatabaseError
*/ */
class ForeignKeyConstraintError extends DatabaseError { class ForeignKeyConstraintError extends DatabaseError {
constructor(options) { constructor(options) {
...@@ -188,6 +205,8 @@ exports.ForeignKeyConstraintError = ForeignKeyConstraintError; ...@@ -188,6 +205,8 @@ exports.ForeignKeyConstraintError = ForeignKeyConstraintError;
/** /**
* Thrown when an exclusion constraint is violated in the database * Thrown when an exclusion constraint is violated in the database
*
* @extends DatabaseError
*/ */
class ExclusionConstraintError extends DatabaseError { class ExclusionConstraintError extends DatabaseError {
constructor(options) { constructor(options) {
...@@ -208,6 +227,8 @@ exports.ExclusionConstraintError = ExclusionConstraintError; ...@@ -208,6 +227,8 @@ exports.ExclusionConstraintError = ExclusionConstraintError;
/** /**
* Thrown when constraint name is not found in the database * Thrown when constraint name is not found in the database
*
* @extends DatabaseError
*/ */
class UnknownConstraintError extends DatabaseError { class UnknownConstraintError extends DatabaseError {
constructor(options) { constructor(options) {
...@@ -229,43 +250,46 @@ exports.UnknownConstraintError = UnknownConstraintError; ...@@ -229,43 +250,46 @@ exports.UnknownConstraintError = UnknownConstraintError;
/** /**
* Validation Error Item * Validation Error Item
* Instances of this class are included in the `ValidationError.errors` property. * Instances of this class are included in the `ValidationError.errors` property.
*/
class ValidationErrorItem {
/**
* Creates new validation error item
* *
* @param {String} message An error message * @param {string} message An error message
* @param {String} type The type/origin of the validation error * @param {string} type The type/origin of the validation error
* @param {String} path The field that triggered the validation error * @param {string} path The field that triggered the validation error
* @param {String} value The value that generated the error * @param {string} value The value that generated the error
* @param {Object} [inst] the DAO instance that caused the validation error * @param {Object} [inst] the DAO instance that caused the validation error
* @param {Object} [validatorKey] a validation "key", used for identification * @param {Object} [validatorKey] a validation "key", used for identification
* @param {String} [fnName] property name of the BUILT-IN validator function that caused the validation error (e.g. "in" or "len"), if applicable * @param {string} [fnName] property name of the BUILT-IN validator function that caused the validation error (e.g. "in" or "len"), if applicable
* @param {String} [fnArgs] parameters used with the BUILT-IN validator function, if applicable * @param {string} [fnArgs] parameters used with the BUILT-IN validator function, if applicable
*/ */
class ValidationErrorItem {
constructor(message, type, path, value, inst, validatorKey, fnName, fnArgs) { constructor(message, type, path, value, inst, validatorKey, fnName, fnArgs) {
/** /**
* An error message * An error message
* *
* @type {String} message * @type {string} message
*/ */
this.message = message || ''; this.message = message || '';
/** /**
* The type/origin of the validation error * The type/origin of the validation error
* *
* @type {String} * @type {string}
*/ */
this.type = null; this.type = null;
/** /**
* The field that triggered the validation error * The field that triggered the validation error
* *
* @type {String} * @type {string}
*/ */
this.path = path || null; this.path = path || null;
/** /**
* The value that generated the error * The value that generated the error
* *
* @type {String} * @type {string}
*/ */
this.value = value !== undefined ? value : null; this.value = value !== undefined ? value : null;
...@@ -281,21 +305,21 @@ class ValidationErrorItem { ...@@ -281,21 +305,21 @@ class ValidationErrorItem {
/** /**
* A validation "key", used for identification * A validation "key", used for identification
* *
* @type {String} * @type {string}
*/ */
this.validatorKey = validatorKey || null; this.validatorKey = validatorKey || null;
/** /**
* Property name of the BUILT-IN validator function that caused the validation error (e.g. "in" or "len"), if applicable * Property name of the BUILT-IN validator function that caused the validation error (e.g. "in" or "len"), if applicable
* *
* @type {String} * @type {string}
*/ */
this.validatorName = fnName || null; this.validatorName = fnName || null;
/** /**
* Parameters used with the BUILT-IN validator function, if applicable * Parameters used with the BUILT-IN validator function, if applicable
* *
* @type {String} * @type {string}
*/ */
this.validatorArgs = fnArgs || []; this.validatorArgs = fnArgs || [];
...@@ -321,12 +345,12 @@ class ValidationErrorItem { ...@@ -321,12 +345,12 @@ class ValidationErrorItem {
* *
* Note: the string will be empty if the instance has neither a valid `validatorKey` property nor a valid `validatorName` property * Note: the string will be empty if the instance has neither a valid `validatorKey` property nor a valid `validatorName` property
* *
* @param {Boolean} [useTypeAsNS=true] controls whether the returned value is "namespace", * @param {boolean} [useTypeAsNS=true] controls whether the returned value is "namespace",
* this parameter is ignored if the validator's `type` is not one of ValidationErrorItem.Origins * this parameter is ignored if the validator's `type` is not one of ValidationErrorItem.Origins
* @param {String} [NSSeparator='.'] a separator string for concatenating the namespace, must be not be empty, * @param {string} [NSSeparator='.'] a separator string for concatenating the namespace, must be not be empty,
* defaults to "." (fullstop). only used and validated if useTypeAsNS is TRUE. * defaults to "." (fullstop). only used and validated if useTypeAsNS is TRUE.
* @throws {Error} thrown if NSSeparator is found to be invalid. * @throws {Error} thrown if NSSeparator is found to be invalid.
* @return {String} * @returns {string}
* *
* @private * @private
*/ */
...@@ -356,9 +380,9 @@ exports.ValidationErrorItem = ValidationErrorItem; ...@@ -356,9 +380,9 @@ exports.ValidationErrorItem = ValidationErrorItem;
* An enum that defines valid ValidationErrorItem `origin` values * An enum that defines valid ValidationErrorItem `origin` values
* *
* @type {Object} * @type {Object}
* @property CORE {String} specifies errors that originate from the sequelize "core" * @property CORE {string} specifies errors that originate from the sequelize "core"
* @property DB {String} specifies validation errors that originate from the storage engine * @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 FUNCTION {string} specifies validation errors that originate from validator functions (both built-in and custom) defined for a given attribute
*/ */
ValidationErrorItem.Origins = { ValidationErrorItem.Origins = {
CORE: 'CORE', CORE: 'CORE',
...@@ -382,6 +406,8 @@ ValidationErrorItem.TypeStringMap = { ...@@ -382,6 +406,8 @@ ValidationErrorItem.TypeStringMap = {
/** /**
* A base class for all connection related errors. * A base class for all connection related errors.
*
* @extends BaseError
*/ */
class ConnectionError extends BaseError { class ConnectionError extends BaseError {
constructor(parent) { constructor(parent) {
...@@ -400,6 +426,8 @@ exports.ConnectionError = ConnectionError; ...@@ -400,6 +426,8 @@ exports.ConnectionError = ConnectionError;
/** /**
* Thrown when a connection to a database is refused * Thrown when a connection to a database is refused
*
* @extends ConnectionError
*/ */
class ConnectionRefusedError extends ConnectionError { class ConnectionRefusedError extends ConnectionError {
constructor(parent) { constructor(parent) {
...@@ -412,6 +440,8 @@ exports.ConnectionRefusedError = ConnectionRefusedError; ...@@ -412,6 +440,8 @@ exports.ConnectionRefusedError = ConnectionRefusedError;
/** /**
* Thrown when a connection to a database is refused due to insufficient privileges * Thrown when a connection to a database is refused due to insufficient privileges
*
* @extends ConnectionError
*/ */
class AccessDeniedError extends ConnectionError { class AccessDeniedError extends ConnectionError {
constructor(parent) { constructor(parent) {
...@@ -424,6 +454,8 @@ exports.AccessDeniedError = AccessDeniedError; ...@@ -424,6 +454,8 @@ exports.AccessDeniedError = AccessDeniedError;
/** /**
* Thrown when a connection to a database has a hostname that was not found * Thrown when a connection to a database has a hostname that was not found
*
* @extends ConnectionError
*/ */
class HostNotFoundError extends ConnectionError { class HostNotFoundError extends ConnectionError {
constructor(parent) { constructor(parent) {
...@@ -436,6 +468,8 @@ exports.HostNotFoundError = HostNotFoundError; ...@@ -436,6 +468,8 @@ exports.HostNotFoundError = HostNotFoundError;
/** /**
* Thrown when a connection to a database has a hostname that was not reachable * Thrown when a connection to a database has a hostname that was not reachable
*
* @extends ConnectionError
*/ */
class HostNotReachableError extends ConnectionError { class HostNotReachableError extends ConnectionError {
constructor(parent) { constructor(parent) {
...@@ -448,6 +482,8 @@ exports.HostNotReachableError = HostNotReachableError; ...@@ -448,6 +482,8 @@ exports.HostNotReachableError = HostNotReachableError;
/** /**
* Thrown when a connection to a database has invalid values for any of the connection parameters * Thrown when a connection to a database has invalid values for any of the connection parameters
*
* @extends ConnectionError
*/ */
class InvalidConnectionError extends ConnectionError { class InvalidConnectionError extends ConnectionError {
constructor(parent) { constructor(parent) {
...@@ -460,6 +496,8 @@ exports.InvalidConnectionError = InvalidConnectionError; ...@@ -460,6 +496,8 @@ exports.InvalidConnectionError = InvalidConnectionError;
/** /**
* Thrown when a connection to a database times out * Thrown when a connection to a database times out
*
* @extends ConnectionError
*/ */
class ConnectionTimedOutError extends ConnectionError { class ConnectionTimedOutError extends ConnectionError {
constructor(parent) { constructor(parent) {
...@@ -472,6 +510,8 @@ exports.ConnectionTimedOutError = ConnectionTimedOutError; ...@@ -472,6 +510,8 @@ exports.ConnectionTimedOutError = ConnectionTimedOutError;
/** /**
* Thrown when a some problem occurred with Instance methods (see message for details) * Thrown when a some problem occurred with Instance methods (see message for details)
*
* @extends BaseError
*/ */
class InstanceError extends BaseError { class InstanceError extends BaseError {
constructor(message) { constructor(message) {
...@@ -484,6 +524,8 @@ exports.InstanceError = InstanceError; ...@@ -484,6 +524,8 @@ exports.InstanceError = InstanceError;
/** /**
* Thrown when a record was not found, Usually used with rejectOnEmpty mode (see message for details) * Thrown when a record was not found, Usually used with rejectOnEmpty mode (see message for details)
*
* @extends BaseError
*/ */
class EmptyResultError extends BaseError { class EmptyResultError extends BaseError {
constructor(message) { constructor(message) {
...@@ -496,6 +538,8 @@ exports.EmptyResultError = EmptyResultError; ...@@ -496,6 +538,8 @@ exports.EmptyResultError = EmptyResultError;
/** /**
* Thrown when an include statement is improperly constructed (see message for details) * Thrown when an include statement is improperly constructed (see message for details)
*
* @extends BaseError
*/ */
class EagerLoadingError extends BaseError { class EagerLoadingError extends BaseError {
constructor(message) { constructor(message) {
...@@ -508,6 +552,8 @@ exports.EagerLoadingError = EagerLoadingError; ...@@ -508,6 +552,8 @@ exports.EagerLoadingError = EagerLoadingError;
/** /**
* Thrown when an association is improperly constructed (see message for details) * Thrown when an association is improperly constructed (see message for details)
*
* @extends BaseError
*/ */
class AssociationError extends BaseError { class AssociationError extends BaseError {
constructor(message) { constructor(message) {
...@@ -519,6 +565,8 @@ class AssociationError extends BaseError { ...@@ -519,6 +565,8 @@ class AssociationError extends BaseError {
exports.AssociationError = AssociationError; exports.AssociationError = AssociationError;
/** /**
* Thrown when a query is passed invalid options (see message for details) * Thrown when a query is passed invalid options (see message for details)
*
* @extends BaseError
*/ */
class QueryError extends BaseError { class QueryError extends BaseError {
constructor(message) { constructor(message) {
...@@ -535,6 +583,8 @@ exports.QueryError = QueryError; ...@@ -535,6 +583,8 @@ exports.QueryError = QueryError;
* *
* @param {Error} error Error for a given record/instance * @param {Error} error Error for a given record/instance
* @param {Object} record DAO instance that error belongs to * @param {Object} record DAO instance that error belongs to
*
* @extends BaseError
*/ */
class BulkRecordError extends BaseError { class BulkRecordError extends BaseError {
constructor(error, record) { constructor(error, record) {
......
...@@ -60,7 +60,10 @@ const hookAliases = { ...@@ -60,7 +60,10 @@ const hookAliases = {
exports.hookAliases = hookAliases; exports.hookAliases = hookAliases;
/** /**
* 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 * @private
*/ */
const getProxiedHooks = hookType => const getProxiedHooks = hookType =>
...@@ -77,11 +80,11 @@ const Hooks = { ...@@ -77,11 +80,11 @@ const Hooks = {
/** /**
* Process user supplied hooks definition * Process user supplied hooks definition
* *
* @param {Object} hooks * @param {Object} hooks hooks definition
* *
* @private * @private
* @memberOf Sequelize * @memberof Sequelize
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
_setupHooks(hooks) { _setupHooks(hooks) {
this.options.hooks = {}; this.options.hooks = {};
...@@ -141,12 +144,12 @@ const Hooks = { ...@@ -141,12 +144,12 @@ const Hooks = {
/** /**
* Add a hook to the model * Add a hook to the model
* *
* @param {String} hookType * @param {string} hookType hook name @see {@link hookTypes}
* @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|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 * @param {Function} fn The hook function
* *
* @memberOf Sequelize * @memberof Sequelize
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
addHook(hookType, name, fn) { addHook(hookType, name, fn) {
if (typeof name === 'function') { if (typeof name === 'function') {
...@@ -171,11 +174,11 @@ const Hooks = { ...@@ -171,11 +174,11 @@ const Hooks = {
/** /**
* Remove hook from the model * Remove hook from the model
* *
* @param {String} hookType * @param {string} hookType @see {@link hookTypes}
* @param {String|Function} name * @param {string|Function} name name of hook or function reference which was attached
* *
* @memberOf Sequelize * @memberof Sequelize
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
removeHook(hookType, name) { removeHook(hookType, name) {
hookType = hookAliases[hookType] || hookType; hookType = hookAliases[hookType] || hookType;
...@@ -207,11 +210,12 @@ const Hooks = { ...@@ -207,11 +210,12 @@ const Hooks = {
/** /**
* Check whether the mode has any hooks of this type * Check whether the mode has any hooks of this type
* *
* @param {String} hookType * @param {string} hookType @see {@link hookTypes}
* *
* @alias hasHooks * @alias hasHooks
* @memberOf Sequelize *
* @memberOf Sequelize.Model * @memberof Sequelize
* @memberof Sequelize.Model
*/ */
hasHook(hookType) { hasHook(hookType) {
return this.options.hooks[hookType] && !!this.options.hooks[hookType].length; return this.options.hooks[hookType] && !!this.options.hooks[hookType].length;
...@@ -234,317 +238,317 @@ exports.applyTo = applyTo; ...@@ -234,317 +238,317 @@ exports.applyTo = applyTo;
/** /**
* A hook that is run before validation * A hook that is run before validation
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with instance, options * @param {Function} fn A callback function that is called with instance, options
* @name beforeValidate * @name beforeValidate
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run after validation * A hook that is run after validation
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with instance, options * @param {Function} fn A callback function that is called with instance, options
* @name afterValidate * @name afterValidate
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run when validation fails * A hook that is run when validation fails
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with instance, options, error. Error is the * @param {Function} fn A callback function that is called with instance, options, error. Error is the
* SequelizeValidationError. If the callback throws an error, it will replace the original validation error. * SequelizeValidationError. If the callback throws an error, it will replace the original validation error.
* @name validationFailed * @name validationFailed
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run before creating a single instance * A hook that is run before creating a single instance
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with attributes, options * @param {Function} fn A callback function that is called with attributes, options
* @name beforeCreate * @name beforeCreate
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run after creating a single instance * A hook that is run after creating a single instance
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with attributes, options * @param {Function} fn A callback function that is called with attributes, options
* @name afterCreate * @name afterCreate
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run before creating or updating a single instance, It proxies `beforeCreate` and `beforeUpdate` * A hook that is run before creating or updating a single instance, It proxies `beforeCreate` and `beforeUpdate`
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with attributes, options * @param {Function} fn A callback function that is called with attributes, options
* @name beforeSave * @name beforeSave
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run before upserting * A hook that is run before upserting
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with attributes, options * @param {Function} fn A callback function that is called with attributes, options
* @name beforeUpsert * @name beforeUpsert
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run after upserting * A hook that is run after upserting
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with the result of upsert(), options * @param {Function} fn A callback function that is called with the result of upsert(), options
* @name afterUpsert * @name afterUpsert
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run after creating or updating a single instance, It proxies `afterCreate` and `afterUpdate` * A hook that is run after creating or updating a single instance, It proxies `afterCreate` and `afterUpdate`
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with attributes, options * @param {Function} fn A callback function that is called with attributes, options
* @name afterSave * @name afterSave
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run before destroying a single instance * A hook that is run before destroying a single instance
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with instance, options * @param {Function} fn A callback function that is called with instance, options
* *
* @name beforeDestroy * @name beforeDestroy
* @alias beforeDelete * @alias beforeDelete
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run after destroying a single instance * A hook that is run after destroying a single instance
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with instance, options * @param {Function} fn A callback function that is called with instance, options
* *
* @name afterDestroy * @name afterDestroy
* @alias afterDelete * @alias afterDelete
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run before restoring a single instance * A hook that is run before restoring a single instance
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with instance, options * @param {Function} fn A callback function that is called with instance, options
* *
* @name beforeRestore * @name beforeRestore
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run after restoring a single instance * A hook that is run after restoring a single instance
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with instance, options * @param {Function} fn A callback function that is called with instance, options
* *
* @name afterRestore * @name afterRestore
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run before updating a single instance * A hook that is run before updating a single instance
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with instance, options * @param {Function} fn A callback function that is called with instance, options
* @name beforeUpdate * @name beforeUpdate
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run after updating a single instance * A hook that is run after updating a single instance
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with instance, options * @param {Function} fn A callback function that is called with instance, options
* @name afterUpdate * @name afterUpdate
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run before creating instances in bulk * A hook that is run before creating instances in bulk
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with instances, options * @param {Function} fn A callback function that is called with instances, options
* @name beforeBulkCreate * @name beforeBulkCreate
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run after creating instances in bulk * A hook that is run after creating instances in bulk
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with instances, options * @param {Function} fn A callback function that is called with instances, options
* @name afterBulkCreate * @name afterBulkCreate
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run before destroying instances in bulk * A hook that is run before destroying instances in bulk
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with options * @param {Function} fn A callback function that is called with options
* *
* @name beforeBulkDestroy * @name beforeBulkDestroy
* @alias beforeBulkDelete * @alias beforeBulkDelete
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run after destroying instances in bulk * A hook that is run after destroying instances in bulk
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with options * @param {Function} fn A callback function that is called with options
* *
* @name afterBulkDestroy * @name afterBulkDestroy
* @alias afterBulkDelete * @alias afterBulkDelete
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run before restoring instances in bulk * A hook that is run before restoring instances in bulk
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with options * @param {Function} fn A callback function that is called with options
* *
* @name beforeBulkRestore * @name beforeBulkRestore
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run after restoring instances in bulk * A hook that is run after restoring instances in bulk
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with options * @param {Function} fn A callback function that is called with options
* *
* @name afterBulkRestore * @name afterBulkRestore
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run before updating instances in bulk * A hook that is run before updating instances in bulk
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with options * @param {Function} fn A callback function that is called with options
* @name beforeBulkUpdate * @name beforeBulkUpdate
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run after updating instances in bulk * A hook that is run after updating instances in bulk
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with options * @param {Function} fn A callback function that is called with options
* @name afterBulkUpdate * @name afterBulkUpdate
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run before a find (select) query * A hook that is run before a find (select) query
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with options * @param {Function} fn A callback function that is called with options
* @name beforeFind * @name beforeFind
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded * A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with options * @param {Function} fn A callback function that is called with options
* @name beforeFindAfterExpandIncludeAll * @name beforeFindAfterExpandIncludeAll
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run before a find (select) query, after all option parsing is complete * A hook that is run before a find (select) query, after all option parsing is complete
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with options * @param {Function} fn A callback function that is called with options
* @name beforeFindAfterOptions * @name beforeFindAfterOptions
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run after a find (select) query * A hook that is run after a find (select) query
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with instance(s), options * @param {Function} fn A callback function that is called with instance(s), options
* @name afterFind * @name afterFind
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run before a count query * A hook that is run before a count query
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with options * @param {Function} fn A callback function that is called with options
* @name beforeCount * @name beforeCount
* @memberOf Sequelize.Model * @memberof Sequelize.Model
*/ */
/** /**
* A hook that is run before a define call * A hook that is run before a define call
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with attributes, options * @param {Function} fn A callback function that is called with attributes, options
* @name beforeDefine * @name beforeDefine
* @memberOf Sequelize * @memberof Sequelize
*/ */
/** /**
* A hook that is run after a define call * A hook that is run after a define call
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with factory * @param {Function} fn A callback function that is called with factory
* @name afterDefine * @name afterDefine
* @memberOf Sequelize * @memberof Sequelize
*/ */
/** /**
* A hook that is run before Sequelize() call * A hook that is run before Sequelize() call
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with config, options * @param {Function} fn A callback function that is called with config, options
* @name beforeInit * @name beforeInit
* @memberOf Sequelize * @memberof Sequelize
*/ */
/** /**
* A hook that is run after Sequelize() call * A hook that is run after Sequelize() call
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with sequelize * @param {Function} fn A callback function that is called with sequelize
* @name afterInit * @name afterInit
* @memberOf Sequelize * @memberof Sequelize
*/ */
/** /**
* A hook that is run before a connection is created * A hook that is run before a connection is created
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with config passed to connection * @param {Function} fn A callback function that is called with config passed to connection
* @name beforeConnect * @name beforeConnect
* @memberOf Sequelize * @memberof Sequelize
*/ */
/** /**
* A hook that is run after a connection is created * A hook that is run after a connection is created
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with the connection object and thye config passed to connection * @param {Function} fn A callback function that is called with the connection object and thye config passed to connection
* @name afterConnect * @name afterConnect
* @memberOf Sequelize * @memberof Sequelize
*/ */
/** /**
* A hook that is run before Model.sync call * A hook that is run before Model.sync call
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with options passed to Model.sync * @param {Function} fn A callback function that is called with options passed to Model.sync
* @name beforeSync * @name beforeSync
* @memberOf Sequelize * @memberof Sequelize
*/ */
/** /**
* A hook that is run after Model.sync call * A hook that is run after Model.sync call
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with options passed to Model.sync * @param {Function} fn A callback function that is called with options passed to Model.sync
* @name afterSync * @name afterSync
* @memberOf Sequelize * @memberof Sequelize
*/ */
/** /**
* A hook that is run before sequelize.sync call * A hook that is run before sequelize.sync call
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with options passed to sequelize.sync * @param {Function} fn A callback function that is called with options passed to sequelize.sync
* @name beforeBulkSync * @name beforeBulkSync
* @memberOf Sequelize * @memberof Sequelize
*/ */
/** /**
* A hook that is run after sequelize.sync call * A hook that is run after sequelize.sync call
* @param {String} name * @param {string} name
* @param {Function} fn A callback function that is called with options passed to sequelize.sync * @param {Function} fn A callback function that is called with options passed to sequelize.sync
* @name afterBulkSync * @name afterBulkSync
* @memberOf Sequelize * @memberof Sequelize
*/ */
'use strict'; 'use strict';
const validator = require('./utils/validator-extras').validator; const _ = require('lodash');
const extendModelValidations = require('./utils/validator-extras').extendModelValidations;
const Utils = require('./utils'); const Utils = require('./utils');
const sequelizeError = require('./errors'); const sequelizeError = require('./errors');
const Promise = require('./promise'); const Promise = require('./promise');
const DataTypes = require('./data-types'); const DataTypes = require('./data-types');
const BelongsTo = require('./associations/belongs-to'); const BelongsTo = require('./associations/belongs-to');
const _ = require('lodash'); const validator = require('./utils/validator-extras').validator;
const extendModelValidations = require('./utils/validator-extras').extendModelValidations;
/** /**
* The Main Instance Validator. * Instance Validator.
* *
* @param {Instance} modelInstance The model instance. * @param {Instance} modelInstance The model instance.
* @param {Object} options A dictionary with options. * @param {Object} options A dictionary with options.
* @constructor *
* @private * @private
*/ */
class InstanceValidator { class InstanceValidator {
...@@ -61,7 +61,7 @@ class InstanceValidator { ...@@ -61,7 +61,7 @@ class InstanceValidator {
/** /**
* The main entry point for the Validation module, invoke to start the dance. * The main entry point for the Validation module, invoke to start the dance.
* *
* @return {Promise} * @returns {Promise}
* @private * @private
*/ */
_validate() { _validate() {
...@@ -86,7 +86,7 @@ class InstanceValidator { ...@@ -86,7 +86,7 @@ class InstanceValidator {
* - On validation success: After Validation Model Hooks * - On validation success: After Validation Model Hooks
* - On validation failure: Validation Failed Model Hooks * - On validation failure: Validation Failed Model Hooks
* *
* @return {Promise} * @returns {Promise}
* @private * @private
*/ */
validate() { validate() {
...@@ -100,7 +100,7 @@ class InstanceValidator { ...@@ -100,7 +100,7 @@ class InstanceValidator {
* - On validation success: After Validation Model Hooks * - On validation success: After Validation Model Hooks
* - On validation failure: Validation Failed Model Hooks * - On validation failure: Validation Failed Model Hooks
* *
* @return {Promise} * @returns {Promise}
* @private * @private
*/ */
_validateAndRunHooks() { _validateAndRunHooks() {
...@@ -118,7 +118,7 @@ class InstanceValidator { ...@@ -118,7 +118,7 @@ class InstanceValidator {
/** /**
* Will run all the built-in validators. * Will run all the built-in validators.
* *
* @return {Promise(Array.<Promise.PromiseInspection>)} A promise from .reflect(). * @returns {Promise<Array.<Promise.PromiseInspection>>} A promise from .reflect().
* @private * @private
*/ */
_builtinValidators() { _builtinValidators() {
...@@ -152,7 +152,7 @@ class InstanceValidator { ...@@ -152,7 +152,7 @@ class InstanceValidator {
/** /**
* Will run all the custom validators. * Will run all the custom validators.
* *
* @return {Promise(Array.<Promise.PromiseInspection>)} A promise from .reflect(). * @returns {Promise<Array.<Promise.PromiseInspection>>} A promise from .reflect().
* @private * @private
*/ */
_customValidators() { _customValidators() {
...@@ -176,11 +176,12 @@ class InstanceValidator { ...@@ -176,11 +176,12 @@ class InstanceValidator {
/** /**
* Validate a single attribute with all the defined built-in validators. * Validate a single attribute with all the defined built-in validators.
* *
* @private
*
* @param {*} value Anything. * @param {*} value Anything.
* @param {string} field The field name. * @param {string} field The field name.
* @return {Promise} A promise, will always resolve, *
* auto populates error on this.error local object. * @returns {Promise} A promise, will always resolve, auto populates error on this.error local object.
* @private
*/ */
_builtinAttrValidate(value, field) { _builtinAttrValidate(value, field) {
// check if value is null (if null not allowed the Schema pass will capture it) // check if value is null (if null not allowed the Schema pass will capture it)
...@@ -222,12 +223,15 @@ class InstanceValidator { ...@@ -222,12 +223,15 @@ class InstanceValidator {
/** /**
* Prepare and invoke a custom validator. * Prepare and invoke a custom validator.
* *
* @private
*
* @param {Function} validator The custom validator. * @param {Function} validator The custom validator.
* @param {string} validatorType the custom validator type (name). * @param {string} validatorType the custom validator type (name).
* @param {boolean=} optAttrDefined Set to true if custom validator was defined * @param {boolean} optAttrDefined Set to true if custom validator was defined from the attribute
* from the Attribute * @param {*} optValue value for attribute
* @return {Promise} A promise. * @param {string} optField field for attribute
* @private *
* @returns {Promise} A promise.
*/ */
_invokeCustomValidator(validator, validatorType, optAttrDefined, optValue, optField) { _invokeCustomValidator(validator, validatorType, optAttrDefined, optValue, optField) {
let validatorFunction = null; // the validation function to call let validatorFunction = null; // the validation function to call
...@@ -265,12 +269,14 @@ class InstanceValidator { ...@@ -265,12 +269,14 @@ class InstanceValidator {
/** /**
* Prepare and invoke a build-in validator. * Prepare and invoke a build-in validator.
* *
* @private
*
* @param {*} value Anything. * @param {*} value Anything.
* @param {*} test The test case. * @param {*} test The test case.
* @param {string} validatorType One of known to Sequelize validators. * @param {string} validatorType One of known to Sequelize validators.
* @param {string} field The field that is being validated * @param {string} field The field that is being validated
* @return {Object} An object with specific keys to invoke the validator. *
* @private * @returns {Object} An object with specific keys to invoke the validator.
*/ */
_invokeBuiltinValidator(value, test, validatorType, field) { _invokeBuiltinValidator(value, test, validatorType, field) {
return Promise.try(() => { return Promise.try(() => {
...@@ -295,6 +301,7 @@ class InstanceValidator { ...@@ -295,6 +301,7 @@ class InstanceValidator {
* @param {*} test The test case. * @param {*} test The test case.
* @param {string} validatorType One of known to Sequelize validators. * @param {string} validatorType One of known to Sequelize validators.
* @param {string} field The field that is being validated. * @param {string} field The field that is being validated.
*
* @private * @private
*/ */
_extractValidatorArgs(test, validatorType, field) { _extractValidatorArgs(test, validatorType, field) {
...@@ -321,6 +328,7 @@ class InstanceValidator { ...@@ -321,6 +328,7 @@ class InstanceValidator {
* @param {Object} rawAttribute As defined in the Schema. * @param {Object} rawAttribute As defined in the Schema.
* @param {string} field The field name. * @param {string} field The field name.
* @param {*} value anything. * @param {*} value anything.
*
* @private * @private
*/ */
_validateSchema(rawAttribute, field, value) { _validateSchema(rawAttribute, field, value) {
...@@ -363,7 +371,8 @@ class InstanceValidator { ...@@ -363,7 +371,8 @@ class InstanceValidator {
* *
* @param {string} field The attribute name. * @param {string} field The attribute name.
* @param {string|number} value The data value. * @param {string|number} value The data value.
* @param {Array.<Promise.PromiseInspection>} Promise inspection objects. * @param {Array<Promise.PromiseInspection>} promiseInspections objects.
*
* @private * @private
*/ */
_handleReflectedResult(field, value, promiseInspections) { _handleReflectedResult(field, value, promiseInspections) {
...@@ -380,11 +389,11 @@ class InstanceValidator { ...@@ -380,11 +389,11 @@ class InstanceValidator {
/** /**
* Signs all errors retaining the original. * Signs all errors retaining the original.
* *
* @param {Boolean} isBuiltin - Determines if error is from builtin validator. * @param {boolean} isBuiltin - Determines if error is from builtin validator.
* @param {String} errorKey - name of invalid attribute. * @param {string} errorKey - name of invalid attribute.
* @param {Error|String} rawError - The original error. * @param {Error|string} rawError - The original error.
* @param {String|Number} value - The data that triggered the error. * @param {string|number} value - The data that triggered the error.
* @param {String} fnName - Name of the validator, if any * @param {string} fnName - Name of the validator, if any
* @param {Array} fnArgs - Arguments for the validator [function], if any * @param {Array} fnArgs - Arguments for the validator [function], if any
* *
* @private * @private
......
...@@ -37,9 +37,11 @@ class ModelManager { ...@@ -37,9 +37,11 @@ class ModelManager {
} }
/** /**
* Iterate over Models in an order suitable for e.g. creating tables. Will * Iterate over Models in an order suitable for e.g. creating tables.
* take foreign key constraints into account so that dependencies are visited * Will take foreign key constraints into account so that dependencies are visited before dependents.
* before dependents. *
* @param {Function} iterator method to execute on each model
* @param {Object} [options] iterator options
* @private * @private
*/ */
forEachModel(iterator, options) { forEachModel(iterator, options) {
......
This diff could not be displayed because it is too large.
'use strict'; 'use strict';
const Utils = require('./utils');
const _ = require('lodash'); const _ = require('lodash');
const Utils = require('./utils');
const DataTypes = require('./data-types'); const DataTypes = require('./data-types');
const SQLiteQueryInterface = require('./dialects/sqlite/query-interface'); const SQLiteQueryInterface = require('./dialects/sqlite/query-interface');
const MSSSQLQueryInterface = require('./dialects/mssql/query-interface'); const MSSSQLQueryInterface = require('./dialects/mssql/query-interface');
...@@ -26,10 +27,10 @@ class QueryInterface { ...@@ -26,10 +27,10 @@ class QueryInterface {
/** /**
* Creates a schema * Creates a schema
* *
* @param {String} schema Schema name to create * @param {string} schema Schema name to create
* @param {Object} [options] Query options * @param {Object} [options] Query options
* *
* @return {Promise} * @returns {Promise}
*/ */
createSchema(schema, options) { createSchema(schema, options) {
options = options || {}; options = options || {};
...@@ -40,10 +41,10 @@ class QueryInterface { ...@@ -40,10 +41,10 @@ class QueryInterface {
/** /**
* Drops a schema * Drops a schema
* *
* @param {String} schema Schema name to drop * @param {string} schema Schema name to drop
* @param {Object} [options] Query options * @param {Object} [options] Query options
* *
* @return {Promise} * @returns {Promise}
*/ */
dropSchema(schema, options) { dropSchema(schema, options) {
options = options || {}; options = options || {};
...@@ -56,7 +57,7 @@ class QueryInterface { ...@@ -56,7 +57,7 @@ class QueryInterface {
* *
* @param {Object} [options] Query options * @param {Object} [options] Query options
* *
* @return {Promise} * @returns {Promise}
*/ */
dropAllSchemas(options) { dropAllSchemas(options) {
options = options || {}; options = options || {};
...@@ -73,7 +74,7 @@ class QueryInterface { ...@@ -73,7 +74,7 @@ class QueryInterface {
* *
* @param {Object} [options] Query options * @param {Object} [options] Query options
* *
* @return {Promise<Array>} * @returns {Promise<Array>}
*/ */
showAllSchemas(options) { showAllSchemas(options) {
options = _.assign({}, options, { options = _.assign({}, options, {
...@@ -150,12 +151,12 @@ class QueryInterface { ...@@ -150,12 +151,12 @@ class QueryInterface {
* ) * )
* ``` * ```
* *
* @param {String} tableName Name of table to create * @param {string} tableName Name of table to create
* @param {Object} attributes Object representing a list of table attributes to create * @param {Object} attributes Object representing a list of table attributes to create
* @param {Object} [options] * @param {Object} [options] create table and query options
* @param {Model} [model] * @param {Model} [model] model class
* *
* @return {Promise} * @returns {Promise}
*/ */
createTable(tableName, attributes, options, model) { createTable(tableName, attributes, options, model) {
let sql = ''; let sql = '';
...@@ -198,10 +199,10 @@ class QueryInterface { ...@@ -198,10 +199,10 @@ class QueryInterface {
/** /**
* Drops a table from database * Drops a table from database
* *
* @param {String} tableName Table name to drop * @param {string} tableName Table name to drop
* @param {Object} options Query options * @param {Object} options Query options
* *
* @return {Promise} * @returns {Promise}
*/ */
dropTable(tableName, options) { dropTable(tableName, options) {
// if we're forcing we should be cascading unless explicitly stated otherwise // if we're forcing we should be cascading unless explicitly stated otherwise
...@@ -241,10 +242,10 @@ class QueryInterface { ...@@ -241,10 +242,10 @@ class QueryInterface {
/** /**
* Drop all tables from database * Drop all tables from database
* *
* @param {Object} [options] * @param {Object} [options] query options
* @param {Array} [options.skip] List of table to skip * @param {Array} [options.skip] List of table to skip
* *
* @return {Promise} * @returns {Promise}
*/ */
dropAllTables(options) { dropAllTables(options) {
options = options || {}; options = options || {};
...@@ -294,10 +295,11 @@ class QueryInterface { ...@@ -294,10 +295,11 @@ class QueryInterface {
/** /**
* Drop specified enum from database, Postgres Only * Drop specified enum from database, Postgres Only
* @param {String} [enumName] Enum name to drop *
* @param {string} [enumName] Enum name to drop
* @param {Object} options Query options * @param {Object} options Query options
* *
* @return {Promise} * @returns {Promise}
* @private * @private
*/ */
dropEnum(enumName, options) { dropEnum(enumName, options) {
...@@ -318,7 +320,7 @@ class QueryInterface { ...@@ -318,7 +320,7 @@ class QueryInterface {
* *
* @param {Object} options Query options * @param {Object} options Query options
* *
* @return {Promise} * @returns {Promise}
* @private * @private
*/ */
dropAllEnums(options) { dropAllEnums(options) {
...@@ -337,10 +339,10 @@ class QueryInterface { ...@@ -337,10 +339,10 @@ class QueryInterface {
/** /**
* List all enums, Postgres Only * List all enums, Postgres Only
* *
* @param {String} [tableName] Table whose enum to list * @param {string} [tableName] Table whose enum to list
* @param {Object} [options] Query options * @param {Object} [options] Query options
* *
* @return {Promise} * @returns {Promise}
* @private * @private
*/ */
pgListEnums(tableName, options) { pgListEnums(tableName, options) {
...@@ -352,11 +354,11 @@ class QueryInterface { ...@@ -352,11 +354,11 @@ class QueryInterface {
/** /**
* Renames a table * Renames a table
* *
* @param {String} before Current name of table * @param {string} before Current name of table
* @param {String} after New name from table * @param {string} after New name from table
* @param {Object} [options] Query options * @param {Object} [options] Query options
* *
* @return {Promise} * @returns {Promise}
*/ */
renameTable(before, after, options) { renameTable(before, after, options) {
options = options || {}; options = options || {};
...@@ -368,10 +370,10 @@ class QueryInterface { ...@@ -368,10 +370,10 @@ class QueryInterface {
* Get all tables in current database * Get all tables in current database
* *
* @param {Object} [options] Query options * @param {Object} [options] Query options
* @param {Boolean} [options.raw=true] Run query in raw mode * @param {boolean} [options.raw=true] Run query in raw mode
* @param {QueryType} [options.type=QueryType.SHOWTABLE] * @param {QueryType} [options.type=QueryType.SHOWTABLE] query type
* *
* @return {Promise<Array>} * @returns {Promise<Array>}
* @private * @private
*/ */
showAllTables(options) { showAllTables(options) {
...@@ -403,10 +405,11 @@ class QueryInterface { ...@@ -403,10 +405,11 @@ class QueryInterface {
* } * }
* } * }
* ``` * ```
* @param {String} tableName *
* @param {string} tableName table name
* @param {Object} [options] Query options * @param {Object} [options] Query options
* *
* @return {Promise<Object>} * @returns {Promise<Object>}
*/ */
describeTable(tableName, options) { describeTable(tableName, options) {
let schema = null; let schema = null;
...@@ -449,12 +452,13 @@ class QueryInterface { ...@@ -449,12 +452,13 @@ class QueryInterface {
* after: 'columnB' // after option is only supported by MySQL * after: 'columnB' // after option is only supported by MySQL
* }); * });
* ``` * ```
* @param {String} table Table to add column to *
* @param {String} key Column name * @param {string} table Table to add column to
* @param {string} key Column name
* @param {Object} attribute Attribute definition * @param {Object} attribute Attribute definition
* @param {Object} [options] Query options * @param {Object} [options] Query options
* *
* @return {Promise} * @returns {Promise}
*/ */
addColumn(table, key, attribute, options) { addColumn(table, key, attribute, options) {
if (!table || !key || !attribute) { if (!table || !key || !attribute) {
...@@ -469,11 +473,11 @@ class QueryInterface { ...@@ -469,11 +473,11 @@ class QueryInterface {
/** /**
* Remove a column from table * Remove a column from table
* *
* @param {String} tableName Table to remove column from * @param {string} tableName Table to remove column from
* @param {String} attributeName Columns name to remove * @param {string} attributeName Columns name to remove
* @param {Object} [options] Query options * @param {Object} [options] Query options
* *
* @return {Promise} * @returns {Promise}
*/ */
removeColumn(tableName, attributeName, options) { removeColumn(tableName, attributeName, options) {
options = options || {}; options = options || {};
...@@ -495,12 +499,12 @@ class QueryInterface { ...@@ -495,12 +499,12 @@ class QueryInterface {
/** /**
* Change a column definition * Change a column definition
* *
* @param {String} tableName Table name to change from * @param {string} tableName Table name to change from
* @param {String} attributeName Column name * @param {string} attributeName Column name
* @param {Object} dataTypeOrOptions Attribute definition for new column * @param {Object} dataTypeOrOptions Attribute definition for new column
* @param {Object} [options] Query options * @param {Object} [options] Query options
* *
* @return {Promise} * @returns {Promise}
*/ */
changeColumn(tableName, attributeName, dataTypeOrOptions, options) { changeColumn(tableName, attributeName, dataTypeOrOptions, options) {
const attributes = {}; const attributes = {};
...@@ -528,12 +532,12 @@ class QueryInterface { ...@@ -528,12 +532,12 @@ class QueryInterface {
/** /**
* Rename a column * Rename a column
* *
* @param {String} tableName Table name whose column to rename * @param {string} tableName Table name whose column to rename
* @param {String} attrNameBefore Current column name * @param {string} attrNameBefore Current column name
* @param {String} attrNameAfter New column name * @param {string} attrNameAfter New column name
* @param {Object} [options] Query option * @param {Object} [options] Query option
* *
* @return {Promise} * @returns {Promise}
*/ */
renameColumn(tableName, attrNameBefore, attrNameAfter, options) { renameColumn(tableName, attrNameBefore, attrNameAfter, options) {
options = options || {}; options = options || {};
...@@ -575,16 +579,18 @@ class QueryInterface { ...@@ -575,16 +579,18 @@ class QueryInterface {
/** /**
* Add index to a column * Add index to a column
* *
* @param {String} tableName Table name to add index on * @param {string|Object} tableName Table name to add index on, can be a object with schema
* @param {Object} options * @param {Array} [attributes] Use options.fields instead, List of attributes to add index on
* @param {Object} options indexes options
* @param {Array} options.fields List of attributes to add index on * @param {Array} options.fields List of attributes to add index on
* @param {Boolean} [options.unique] Create a unique index * @param {boolean} [options.unique] Create a unique index
* @param {String} [options.using] Useful for GIN indexes * @param {string} [options.using] Useful for GIN indexes
* @param {String} [options.type] Type of index, available options are UNIQUE|FULLTEXT|SPATIAL * @param {string} [options.type] Type of index, available options are UNIQUE|FULLTEXT|SPATIAL
* @param {String} [options.name] Name of the index. Default is <table>_<attr1>_<attr2> * @param {string} [options.name] Name of the index. Default is <table>_<attr1>_<attr2>
* @param {Object} [options.where] Where condition on index, for partial indexes * @param {Object} [options.where] Where condition on index, for partial indexes
* @param {string} [rawTablename] table name, this is just for backward compatibiity
* *
* @return {Promise} * @returns {Promise}
*/ */
addIndex(tableName, attributes, options, rawTablename) { addIndex(tableName, attributes, options, rawTablename) {
// Support for passing tableName, attributes, options or tableName, options (with a fields param which is the attributes) // Support for passing tableName, attributes, options or tableName, options (with a fields param which is the attributes)
...@@ -609,10 +615,10 @@ class QueryInterface { ...@@ -609,10 +615,10 @@ class QueryInterface {
/** /**
* Show indexes on a table * Show indexes on a table
* *
* @param {String} tableName * @param {string} tableName table name
* @param {Object} [options] Query options * @param {Object} [options] Query options
* *
* @return {Promise<Array>} * @returns {Promise<Array>}
* @private * @private
*/ */
showIndex(tableName, options) { showIndex(tableName, options) {
...@@ -656,8 +662,9 @@ class QueryInterface { ...@@ -656,8 +662,9 @@ class QueryInterface {
* referencedTableCatalog, referencedTableCatalog, referencedTableSchema, referencedTableName, referencedColumnName. * referencedTableCatalog, referencedTableCatalog, referencedTableSchema, referencedTableName, referencedColumnName.
* Remind: constraint informations won't return if it's sqlite. * Remind: constraint informations won't return if it's sqlite.
* *
* @param {String} tableName * @param {string} tableName table name
* @param {Object} [options] Query options * @param {Object} [options] Query options
*
* @returns {Promise} * @returns {Promise}
*/ */
getForeignKeyReferencesForTable(tableName, options) { getForeignKeyReferencesForTable(tableName, options) {
...@@ -690,11 +697,11 @@ class QueryInterface { ...@@ -690,11 +697,11 @@ class QueryInterface {
/** /**
* Remove an already existing index from a table * Remove an already existing index from a table
* *
* @param {String} tableName Table name to drop index from * @param {string} tableName Table name to drop index from
* @param {String} indexNameOrAttributes Index name * @param {string} indexNameOrAttributes Index name
* @param {Object} [options] Query options * @param {Object} [options] Query options
* *
* @return {Promise} * @returns {Promise}
*/ */
removeIndex(tableName, indexNameOrAttributes, options) { removeIndex(tableName, indexNameOrAttributes, options) {
options = options || {}; options = options || {};
...@@ -712,41 +719,33 @@ class QueryInterface { ...@@ -712,41 +719,33 @@ class QueryInterface {
* - FOREIGN KEY * - FOREIGN KEY
* - PRIMARY KEY * - PRIMARY KEY
* *
* UNIQUE * @example <caption>UNIQUE</caption>
* ```js
* queryInterface.addConstraint('Users', ['email'], { * queryInterface.addConstraint('Users', ['email'], {
* type: 'unique', * type: 'unique',
* name: 'custom_unique_constraint_name' * name: 'custom_unique_constraint_name'
* }); * });
* ```
* *
* CHECK * @example <caption>CHECK</caption>
* ```js
* queryInterface.addConstraint('Users', ['roles'], { * queryInterface.addConstraint('Users', ['roles'], {
* type: 'check', * type: 'check',
* where: { * where: {
* roles: ['user', 'admin', 'moderator', 'guest'] * roles: ['user', 'admin', 'moderator', 'guest']
* } * }
* }); * });
* ``` *
* Default - MSSQL only * @example <caption>Default - MSSQL only</caption>
* ```js
* queryInterface.addConstraint('Users', ['roles'], { * queryInterface.addConstraint('Users', ['roles'], {
* type: 'default', * type: 'default',
* defaultValue: 'guest' * defaultValue: 'guest'
* }); * });
* ```
* *
* Primary Key * @example <caption>Primary Key</caption>
* ```js
* queryInterface.addConstraint('Users', ['username'], { * queryInterface.addConstraint('Users', ['username'], {
* type: 'primary key', * type: 'primary key',
* name: 'custom_primary_constraint_name' * name: 'custom_primary_constraint_name'
* }); * });
* ```
* *
* Foreign Key * @example <caption>Foreign Key</caption>
* ```js
* queryInterface.addConstraint('Posts', ['username'], { * queryInterface.addConstraint('Posts', ['username'], {
* type: 'foreign key', * type: 'foreign key',
* name: 'custom_fkey_constraint_name', * name: 'custom_fkey_constraint_name',
...@@ -757,20 +756,20 @@ class QueryInterface { ...@@ -757,20 +756,20 @@ class QueryInterface {
* onDelete: 'cascade', * onDelete: 'cascade',
* onUpdate: 'cascade' * onUpdate: 'cascade'
* }); * });
* ```
* *
* @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 {Array} attributes Array of column names to apply the constraint over
* @param {Object} options An object to define the constraint name, type etc * @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.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.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.defaultValue] The value for the default constraint
* @param {Object} [options.where] Where clause/expression for the CHECK 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 {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.table] Target table name
* @param {String} [options.references.field] Target column name * @param {string} [options.references.field] Target column name
* @param {string} [rawTablename] Table name, for backward compatibility
* *
* @return {Promise} * @returns {Promise}
*/ */
addConstraint(tableName, attributes, options, rawTablename) { addConstraint(tableName, attributes, options, rawTablename) {
if (!Array.isArray(attributes)) { if (!Array.isArray(attributes)) {
...@@ -806,11 +805,11 @@ class QueryInterface { ...@@ -806,11 +805,11 @@ class QueryInterface {
/** /**
* *
* @param {String} tableName Table name to drop constraint from * @param {string} tableName Table name to drop constraint from
* @param {String} constraintName Constraint name * @param {string} constraintName Constraint name
* @param {Object} options Query options * @param {Object} options Query options
* *
* @return {Promise} * @returns {Promise}
*/ */
removeConstraint(tableName, constraintName, options) { removeConstraint(tableName, constraintName, options) {
options = options || {}; options = options || {};
...@@ -844,14 +843,14 @@ class QueryInterface { ...@@ -844,14 +843,14 @@ class QueryInterface {
/** /**
* Upsert * Upsert
* *
* @param {String} tableName * @param {string} tableName table to upsert on
* @param {Object} insertValues values to be inserted, mapped to field name * @param {Object} insertValues values to be inserted, mapped to field name
* @param {Object} updateValues values to be updated, mapped to field name * @param {Object} updateValues values to be updated, mapped to field name
* @param {Object} where various conditions * @param {Object} where various conditions
* @param {Model} model * @param {Model} model Model to upsert on
* @param {Object} options * @param {Object} options query options
* *
* @returns {Promise<created, primaryKey>} * @returns {Promise<boolean,?number>} Resolves an array with <created, primaryKey>
*/ */
upsert(tableName, insertValues, updateValues, where, model, options) { upsert(tableName, insertValues, updateValues, where, model, options) {
const wheres = []; const wheres = [];
...@@ -924,7 +923,7 @@ class QueryInterface { ...@@ -924,7 +923,7 @@ class QueryInterface {
/** /**
* Insert records into a table * Insert records into a table
* *
* ```js * @example
* queryInterface.bulkInsert('roles', [{ * queryInterface.bulkInsert('roles', [{
* label: 'user', * label: 'user',
* createdAt: new Date(), * createdAt: new Date(),
...@@ -934,14 +933,13 @@ class QueryInterface { ...@@ -934,14 +933,13 @@ class QueryInterface {
* createdAt: new Date(), * createdAt: new Date(),
* updatedAt: new Date() * updatedAt: new Date()
* }]); * }]);
* ```
* *
* @param {String} tableName Table name to insert record to * @param {string} tableName Table name to insert record to
* @param {Array} records List of records to insert * @param {Array} records List of records to insert
* @param {Object} options Various options, please see Model.bulkCreate options * @param {Object} options Various options, please see Model.bulkCreate options
* @param {Object} fieldMappedAttributes Various attributes mapped by field name * @param {Object} attributes Various attributes mapped by field name
* *
* @return {Promise} * @returns {Promise}
*/ */
bulkInsert(tableName, records, options, attributes) { bulkInsert(tableName, records, options, attributes) {
options = _.clone(options) || {}; options = _.clone(options) || {};
...@@ -1019,12 +1017,13 @@ class QueryInterface { ...@@ -1019,12 +1017,13 @@ class QueryInterface {
/** /**
* Delete records from a table * Delete records from a table
* *
* @param {String} tableName table name from where to delete records * @param {string} tableName table name from where to delete records
* @param {Object} where where conditions to find records to delete * @param {Object} where where conditions to find records to delete
* @param {Object} [options] options * @param {Object} [options] options
* @param {Boolean} [options.truncate] * @param {boolean} [options.truncate] Use truncate table command
* @param {Model} [model] Model
* *
* @return {Promise} * @returns {Promise}
*/ */
bulkDelete(tableName, where, options, model) { bulkDelete(tableName, where, options, model) {
options = Utils.cloneDeep(options); options = Utils.cloneDeep(options);
...@@ -1161,7 +1160,7 @@ class QueryInterface { ...@@ -1161,7 +1160,7 @@ class QueryInterface {
/** /**
* Create SQL function * Create SQL function
* *
* ```js * @example
* queryInterface.createFunction( * queryInterface.createFunction(
* 'someFunction', * 'someFunction',
* [ * [
...@@ -1175,17 +1174,16 @@ class QueryInterface { ...@@ -1175,17 +1174,16 @@ class QueryInterface {
* 'LEAKPROOF' * 'LEAKPROOF'
* ] * ]
* ); * );
* ```
* *
* @param {String} functionName Name of SQL function to create * @param {string} functionName Name of SQL function to create
* @param {Array} params List of parameters declared for SQL function * @param {Array} params List of parameters declared for SQL function
* @param {String} returnType SQL type of function returned value * @param {string} returnType SQL type of function returned value
* @param {String} language The name of the language that the function is implemented in * @param {string} language The name of the language that the function is implemented in
* @param {String} body Source code of function * @param {string} body Source code of function
* @param {Array} optionsArray Extra-options for creation * @param {Array} optionsArray Extra-options for creation
* @param {Object} [options] * @param {Object} [options] query options
* *
* @return {Promise} * @returns {Promise}
*/ */
createFunction(functionName, params, returnType, language, body, optionsArray, options) { createFunction(functionName, params, returnType, language, body, optionsArray, options) {
const sql = this.QueryGenerator.createFunction(functionName, params, returnType, language, body, optionsArray); const sql = this.QueryGenerator.createFunction(functionName, params, returnType, language, body, optionsArray);
...@@ -1201,7 +1199,7 @@ class QueryInterface { ...@@ -1201,7 +1199,7 @@ class QueryInterface {
/** /**
* Drop SQL function * Drop SQL function
* *
* ```js * @example
* queryInterface.dropFunction( * queryInterface.dropFunction(
* 'someFunction', * 'someFunction',
* [ * [
...@@ -1209,13 +1207,12 @@ class QueryInterface { ...@@ -1209,13 +1207,12 @@ class QueryInterface {
* {type: 'integer', name: 'param2', direction: 'INOUT'} * {type: 'integer', name: 'param2', direction: 'INOUT'}
* ] * ]
* ); * );
* ```
* *
* @param {String} functionName Name of SQL function to drop * @param {string} functionName Name of SQL function to drop
* @param {Array} params List of parameters declared for SQL function * @param {Array} params List of parameters declared for SQL function
* @param {Object} [options] * @param {Object} [options] query options
* *
* @return {Promise} * @returns {Promise}
*/ */
dropFunction(functionName, params, options) { dropFunction(functionName, params, options) {
const sql = this.QueryGenerator.dropFunction(functionName, params); const sql = this.QueryGenerator.dropFunction(functionName, params);
...@@ -1231,7 +1228,7 @@ class QueryInterface { ...@@ -1231,7 +1228,7 @@ class QueryInterface {
/** /**
* Rename SQL function * Rename SQL function
* *
* ```js * @example
* queryInterface.renameFunction( * queryInterface.renameFunction(
* 'fooFunction', * 'fooFunction',
* [ * [
...@@ -1240,14 +1237,13 @@ class QueryInterface { ...@@ -1240,14 +1237,13 @@ class QueryInterface {
* ], * ],
* 'barFunction' * 'barFunction'
* ); * );
* ```
* *
* @param {String} oldFunctionName * @param {string} oldFunctionName Current name of function
* @param {Array} params List of parameters declared for SQL function * @param {Array} params List of parameters declared for SQL function
* @param {String} newFunctionName * @param {string} newFunctionName New name of function
* @param {Object} [options] * @param {Object} [options] query options
* *
* @return {Promise} * @returns {Promise}
*/ */
renameFunction(oldFunctionName, params, newFunctionName, options) { renameFunction(oldFunctionName, params, newFunctionName, options) {
const sql = this.QueryGenerator.renameFunction(oldFunctionName, params, newFunctionName); const sql = this.QueryGenerator.renameFunction(oldFunctionName, params, newFunctionName);
...@@ -1263,9 +1259,11 @@ class QueryInterface { ...@@ -1263,9 +1259,11 @@ class QueryInterface {
// Helper methods useful for querying // Helper methods useful for querying
/** /**
* Escape an identifier (e.g. a table or attribute name). If force is true, * Escape an identifier (e.g. a table or attribute name)
* the identifier will be quoted even if the `quoteIdentifiers` option is *
* false. * @param {string} identifier identifier to quote
* @param {boolean} [force] If force is true,the identifier will be quoted even if the `quoteIdentifiers` option is false.
*
* @private * @private
*/ */
quoteIdentifier(identifier, force) { quoteIdentifier(identifier, force) {
...@@ -1277,9 +1275,11 @@ class QueryInterface { ...@@ -1277,9 +1275,11 @@ class QueryInterface {
} }
/** /**
* Split an identifier into .-separated tokens and quote each part. * Quote array of identifiers at once
* If force is true, the identifier will be quoted even if the *
* `quoteIdentifiers` option is false. * @param {string[]} identifiers array of identifiers to quote
* @param {boolean} [force] If force is true,the identifier will be quoted even if the `quoteIdentifiers` option is false.
*
* @private * @private
*/ */
quoteIdentifiers(identifiers, force) { quoteIdentifiers(identifiers, force) {
...@@ -1288,6 +1288,9 @@ class QueryInterface { ...@@ -1288,6 +1288,9 @@ class QueryInterface {
/** /**
* Escape a value (e.g. a string, number or date) * Escape a value (e.g. a string, number or date)
*
* @param {string} value string to escape
*
* @private * @private
*/ */
escape(value) { escape(value) {
......
...@@ -24,81 +24,71 @@ const Validator = require('./utils/validator-extras').validator; ...@@ -24,81 +24,71 @@ const Validator = require('./utils/validator-extras').validator;
const Op = require('./operators'); const Op = require('./operators');
/** /**
* 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 * @class Sequelize
* 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 { class Sequelize {
/** /**
* Instantiate sequelize with name of database, username and password * 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')
* *
* @example
* // without password / with blank password * // 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 * // 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 * // with database, username, and password in the options object
* const sequelize = new Sequelize({ database, username, password }); * const sequelize = new Sequelize({ database, username, password, dialect: 'mssql' });
* *
* // with uri * // with uri
* const sequelize = new Sequelize('mysql://localhost:3306/database', {}) * const sequelize = new Sequelize('mysql://localhost:3306/database', {})
* ```
* *
* @param {String} [database] The name of the 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} [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} [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 {Object} [options={}] An object with options.
* @param {String} [options.host='localhost'] The host of the relational database. * @param {string} [options.host='localhost'] The host of the relational database.
* @param {Integer} [options.port=] The port 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.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.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.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.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.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 {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.storage] Only used by sqlite. Defaults to ':memory:'
* @param {String} [options.protocol='tcp'] The protocol of the relational database. * @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.define={}] Default options for model definitions. See sequelize.define for options
* @param {Object} [options.query={}] Default options for sequelize.query * @param {Object} [options.query={}] Default options for sequelize.query
* @param {Object} [options.set={}] Default options for sequelize.set * @param {Object} [options.set={}] Default options for sequelize.set
* @param {Object} [options.sync={}] Default options for sequelize.sync * @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 {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.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.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.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.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 {Object} [options.pool] sequelize connection pool configuration
* @param {Integer} [options.pool.max=5] Maximum number of connection in pool * @param {number} [options.pool.max=5] Maximum number of connection in pool
* @param {Integer} [options.pool.min=0] Minimum number of connection in pool * @param {number} [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 {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 {Integer} [options.pool.acquire=10000] The maximum time, in milliseconds, that pool will try to get connection before throwing error * @param {number} [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 {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 {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 {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 {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.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 {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 {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 {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 {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 {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. * @param {Object} [options.operatorsAliases] String based operator alias. Pass object to limit set of aliased operators.
*
*/ */
constructor(database, username, password, options) { constructor(database, username, password, options) {
let config; let config;
...@@ -267,6 +257,11 @@ class Sequelize { ...@@ -267,6 +257,11 @@ class Sequelize {
Sequelize.runHooks('afterInit', this); Sequelize.runHooks('afterInit', this);
} }
/**
* Refresh data types and parsers.
*
* @private
*/
refreshTypes() { refreshTypes() {
this.connectionManager.refreshTypeParser(DataTypes); this.connectionManager.refreshTypeParser(DataTypes);
} }
...@@ -274,7 +269,7 @@ class Sequelize { ...@@ -274,7 +269,7 @@ class Sequelize {
/** /**
* Returns the specified dialect. * Returns the specified dialect.
* *
* @return {String} The specified dialect. * @returns {string} The specified dialect.
*/ */
getDialect() { getDialect() {
return this.options.dialect; return this.options.dialect;
...@@ -282,10 +277,8 @@ class Sequelize { ...@@ -282,10 +277,8 @@ class Sequelize {
/** /**
* Returns an instance of QueryInterface. * Returns an instance of QueryInterface.
*
* @method getQueryInterface * @returns {QueryInterface} An instance (singleton) of QueryInterface.
* @memberOf Sequelize
* @return {QueryInterface} An instance (singleton) of QueryInterface.
*/ */
getQueryInterface() { getQueryInterface() {
this.queryInterface = this.queryInterface || new QueryInterface(this); this.queryInterface = this.queryInterface || new QueryInterface(this);
...@@ -293,19 +286,19 @@ class Sequelize { ...@@ -293,19 +286,19 @@ class Sequelize {
} }
/** /**
* Define a new model, representing a table in the DB. * Define a new model, representing a table in the database.
* *
* The table columns are defined by the object that is given as the second argument. Each key of the object represents a column * The table columns are defined by the object that is given as the second argument. Each key of the object represents a column
* *
* @param {String} modelName The name of the model. The model will be stored in `sequelize.models` under this name * @param {string} modelName The name of the model. The model will be stored in `sequelize.models` under this name
* @param {Object} attributes An object, where each attribute is a column of the table. See {@link Model.init} * @param {Object} attributes An object, where each attribute is a column of the table. See {@link Model.init}
* @param {Object} [options] These options are merged with the default define options provided to the Sequelize constructor and passed to Model.init() * @param {Object} [options] These options are merged with the default define options provided to the Sequelize constructor and passed to Model.init()
* *
* @see {@link Model.init} for a more comprehensive specification of the `options` and `attributes` objects. * @see {@link Model.init} for a more comprehensive specification of the `options` and `attributes` objects.
* @see <a href="../manual/tutorial/models-definition.html">The manual section about defining models</a> * @see <a href="/manual/tutorial/models-definition.html">Model definition</a> Manual related to model definition
* @see {@link DataTypes} For a list of possible data types * @see {@link DataTypes} For a list of possible data types
* *
* @return {Model} * @returns {Model} Newly defined model
* *
* @example * @example
* sequelize.define('modelName', { * sequelize.define('modelName', {
...@@ -320,11 +313,10 @@ class Sequelize { ...@@ -320,11 +313,10 @@ class Sequelize {
* } * }
* }, * },
* field: 'column_a' * field: 'column_a'
* // Other attributes here
* }, * },
* columnB: Sequelize.STRING, * columnB: Sequelize.STRING,
* columnC: 'MY VERY OWN COLUMN TYPE' * columnC: 'MY VERY OWN COLUMN TYPE'
* }) * });
* *
* sequelize.models.modelName // The model will now be available in models under the name given to define * sequelize.models.modelName // The model will now be available in models under the name given to define
*/ */
...@@ -342,9 +334,10 @@ class Sequelize { ...@@ -342,9 +334,10 @@ class Sequelize {
/** /**
* Fetch a Model which is already defined * Fetch a Model which is already defined
* *
* @param {String} modelName The name of a model defined with Sequelize.define * @param {string} modelName The name of a model defined with Sequelize.define
*
* @throws Will throw an error if the model is not defined (that is, if sequelize#isDefined returns false) * @throws Will throw an error if the model is not defined (that is, if sequelize#isDefined returns false)
* @return {Model} * @returns {Model} Specified model
*/ */
model(modelName) { model(modelName) {
if (!this.isDefined(modelName)) { if (!this.isDefined(modelName)) {
...@@ -357,21 +350,23 @@ class Sequelize { ...@@ -357,21 +350,23 @@ class Sequelize {
/** /**
* Checks whether a model with the given name is defined * Checks whether a model with the given name is defined
* *
* @param {String} modelName The name of a model defined with Sequelize.define * @param {string} modelName The name of a model defined with Sequelize.define
* @return {Boolean} *
* @returns {boolean} Returns true if model is already defined, otherwise false
*/ */
isDefined(modelName) { isDefined(modelName) {
return !!this.modelManager.models.find(model => model.name === modelName); return !!this.modelManager.models.find(model => model.name === modelName);
} }
/** /**
* Imports a model defined in another file * Imports a model defined in another file. Imported models are cached, so multiple
* calls to import with the same path will not load the file multiple times.
* *
* Imported models are cached, so multiple calls to import with the same path will not load the file multiple times * @tutorial https://github.com/sequelize/express-example
* *
* 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
* @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} * @returns {Model} Imported model, returned from cache if was already imported
*/ */
import(path) { import(path) {
// is it a relative path? // is it a relative path?
...@@ -412,29 +407,28 @@ class Sequelize { ...@@ -412,29 +407,28 @@ class Sequelize {
* }) * })
* ``` * ```
* *
* @method query * @param {string} sql
* @param {String} sql
* @param {Object} [options={}] Query options. * @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 {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 {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.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.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.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 {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 {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 {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 {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 {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 {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 {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 {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.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 {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. * @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. * @see {@link Model.build} for more information about instance option.
*/ */
...@@ -566,13 +560,13 @@ class Sequelize { ...@@ -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. * 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. * Only works for MySQL.
* *
* @method set
* @param {Object} variables Object with multiple variables. * @param {Object} variables Object with multiple variables.
* @param {Object} options Query options. * @param {Object} [options] query options.
* @param {Transaction} options.transaction The transaction that the query should be executed under * @param {Transaction} [options.transaction] The transaction that the query should be executed under
* *
* @memberof Sequelize * @memberof Sequelize
* @return {Promise} *
* @returns {Promise}
*/ */
set(variables, options) { set(variables, options) {
...@@ -602,8 +596,9 @@ class Sequelize { ...@@ -602,8 +596,9 @@ class Sequelize {
/** /**
* Escape value. * Escape value.
* *
* @param {String} value * @param {string} value string value to escape
* @return {String} *
* @returns {string}
*/ */
escape(value) { escape(value) {
return this.getQueryInterface().escape(value); return this.getQueryInterface().escape(value);
...@@ -612,14 +607,16 @@ class Sequelize { ...@@ -612,14 +607,16 @@ class Sequelize {
/** /**
* Create a new database schema. * 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. * not a database table. In mysql and sqlite, this command will do nothing.
* *
* @see {@link Model.schema} * @see {@link Model.schema}
* @param {String} schema Name of the schema *
* @param {Object} options={} * @param {string} schema Name of the schema
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging * @param {Object} [options={}] query options
* @return {Promise} * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
*
* @returns {Promise}
*/ */
createSchema(schema, options) { createSchema(schema, options) {
return this.getQueryInterface().createSchema(schema, options); return this.getQueryInterface().createSchema(schema, options);
...@@ -628,11 +625,13 @@ class Sequelize { ...@@ -628,11 +625,13 @@ class Sequelize {
/** /**
* Show all defined schemas * Show all defined schemas
* *
* 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 will show all tables. * not a database table. In mysql and sqlite, this will show all tables.
* @param {Object} options={} *
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging * @param {Object} [options={}] query options
* @return {Promise} * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
*
* @returns {Promise}
*/ */
showAllSchemas(options) { showAllSchemas(options) {
return this.getQueryInterface().showAllSchemas(options); return this.getQueryInterface().showAllSchemas(options);
...@@ -641,25 +640,29 @@ class Sequelize { ...@@ -641,25 +640,29 @@ class Sequelize {
/** /**
* Drop a single schema * Drop a single 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 drop a table matching the schema name * not a database table. In mysql and sqlite, this drop a table matching the schema name
* @param {String} schema Name of the schema *
* @param {Object} options={} * @param {string} schema Name of the schema
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging * @param {Object} [options={}] query options
* @return {Promise} * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
*
* @returns {Promise}
*/ */
dropSchema(schema, options) { dropSchema(schema, options) {
return this.getQueryInterface().dropSchema(schema, options); return this.getQueryInterface().dropSchema(schema, options);
} }
/** /**
* Drop all schemas * Drop all schemas.
* *
* 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 is the equivalent of drop all tables. * not a database table. In mysql and sqlite, this is the equivalent of drop all tables.
* @param {Object} options={} *
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging * @param {Object} [options={}] query options
* @return {Promise} * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
*
* @returns {Promise}
*/ */
dropAllSchemas(options) { dropAllSchemas(options) {
return this.getQueryInterface().dropAllSchemas(options); return this.getQueryInterface().dropAllSchemas(options);
...@@ -668,15 +671,16 @@ class Sequelize { ...@@ -668,15 +671,16 @@ class Sequelize {
/** /**
* Sync all defined models to the DB. * Sync all defined models to the DB.
* *
* @param {Object} [options={}] * @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 {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 {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 {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.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 {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.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. * @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} *
* @returns {Promise}
*/ */
sync(options) { sync(options) {
options = _.clone(options) || {}; options = _.clone(options) || {};
...@@ -719,13 +723,12 @@ class Sequelize { ...@@ -719,13 +723,12 @@ class Sequelize {
} }
/** /**
* Truncate all tables defined through the sequelize models. This is done * Truncate all tables defined through the sequelize models.
* by calling Model.truncate() on each model. * This is done by calling `Model.truncate()` on each model.
* *
* @param {object} [options] The options passed to Model.destroy in addition to truncate * @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
* @param {Boolean|function} [options.logging] A function that logs sql queries, or false for no logging * @returns {Promise}
* @return {Promise}
* *
* @see {@link Model.truncate} for more information * @see {@link Model.truncate} for more information
*/ */
...@@ -748,12 +751,15 @@ class Sequelize { ...@@ -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 * @see {@link Model.drop} for options
* *
* @param {object} options The options passed to each call to Model.drop * @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 * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
* @return {Promise} *
* @returns {Promise}
*/ */
drop(options) { drop(options) {
const models = []; const models = [];
...@@ -768,10 +774,11 @@ class Sequelize { ...@@ -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...) * @returns {Promise}
* @return {Promise}
*/ */
authenticate(options) { authenticate(options) {
options = _.assign({ options = _.assign({
...@@ -790,7 +797,7 @@ class Sequelize { ...@@ -790,7 +797,7 @@ class Sequelize {
/** /**
* Get the fn for random based on the dialect * Get the fn for random based on the dialect
* *
* @return {Sequelize.fn} * @returns {Sequelize.fn}
*/ */
random() { random() {
if (['postgres', 'sqlite'].includes(this.getDialect())) { if (['postgres', 'sqlite'].includes(this.getDialect())) {
...@@ -804,42 +811,36 @@ class Sequelize { ...@@ -804,42 +811,36 @@ class Sequelize {
* 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. * 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. * 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.
* *
* Convert a user's username to upper case
* ```js
* instance.updateAttributes({
* username: self.sequelize.fn('upper', self.sequelize.col('username'))
* })
* ```
*
* @see {@link Model.findAll} * @see {@link Model.findAll}
* @see {@link Sequelize.define} * @see {@link Sequelize.define}
* @see {@link Sequelize.col} * @see {@link Sequelize.col}
* @method fn
* *
* @param {String} fn The function you want to call * @param {string} fn The function you want to call
* @param {any} args All further arguments will be passed as arguments to the function * @param {any} args All further arguments will be passed as arguments to the function
* *
* @since v2.0.0-dev3 * @since v2.0.0-dev3
* @memberof Sequelize * @memberof Sequelize
* @return {Sequelize.fn} * @returns {Sequelize.fn}
*
* @example <caption>Convert a user's username to upper case</caption> * @example <caption>Convert a user's username to upper case</caption>
* instance.updateAttributes({ * instance.update({
* username: self.sequelize.fn('upper', self.sequelize.col('username')) * username: sequelize.fn('upper', sequelize.col('username'))
* }) * });
*/ */
static fn(fn) { static fn(fn, ...args) {
return new Utils.Fn(fn, Utils.sliceArgs(arguments, 1)); return new Utils.Fn(fn, Utils.sliceArgs(args));
} }
/** /**
* 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. * 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} * @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 * @since v2.0.0-dev3
* @memberof Sequelize * @memberof Sequelize
* @return {Sequelize.col} *
* @returns {Sequelize.col}
*/ */
static col(col) { static col(col) {
return new Utils.Col(col); return new Utils.Col(col);
...@@ -848,12 +849,12 @@ class Sequelize { ...@@ -848,12 +849,12 @@ class Sequelize {
/** /**
* Creates an object representing a call to the cast function. * Creates an object representing a call to the cast function.
* *
* @method cast
* @param {any} val The value to 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 * @since v2.0.0-dev3
* @memberof Sequelize * @memberof Sequelize
* @return {Sequelize.cast} *
* @returns {Sequelize.cast}
*/ */
static cast(val, type) { static cast(val, type) {
return new Utils.Cast(val, type); return new Utils.Cast(val, type);
...@@ -862,12 +863,11 @@ class Sequelize { ...@@ -862,12 +863,11 @@ class Sequelize {
/** /**
* Creates an object representing a literal, i.e. something that will not be escaped. * Creates an object representing a literal, i.e. something that will not be escaped.
* *
* @method literal * @param {any} val literal value
* @param {any} val
* @alias asIs
* @since v2.0.0-dev3 * @since v2.0.0-dev3
* @memberof Sequelize * @memberof Sequelize
* @return {Sequelize.literal} *
* @returns {Sequelize.literal}
*/ */
static literal(val) { static literal(val) {
return new Utils.Literal(val); return new Utils.Literal(val);
...@@ -875,41 +875,44 @@ class Sequelize { ...@@ -875,41 +875,44 @@ class Sequelize {
/** /**
* An AND query * An AND query
*
* @see {@link Model.findAll} * @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 * @since v2.0.0-dev3
* @memberof Sequelize * @memberof Sequelize
* @return {Sequelize.and} *
* @returns {Sequelize.and}
*/ */
static and() { static and(...args) {
return { [Op.and]: Utils.sliceArgs(arguments) }; return { [Op.and]: Utils.sliceArgs(args) };
} }
/** /**
* An OR query * An OR query
*
* @see {@link Model.findAll} * @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 * @since v2.0.0-dev3
* @memberof Sequelize * @memberof Sequelize
* @return {Sequelize.or} *
* @returns {Sequelize.or}
*/ */
static or() { static or(...args) {
return { [Op.or]: Utils.sliceArgs(arguments) }; return { [Op.or]: Utils.sliceArgs(args) };
} }
/** /**
* Creates an object representing nested where conditions for postgres/sqlite/mysql json data-type. * Creates an object representing nested where conditions for postgres/sqlite/mysql json data-type.
* @see {@link Model#findAll}
* *
* @method json * @see {@link Model.findAll}
* @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>'". * @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 * @memberof Sequelize
* @return {Sequelize.json} *
* @returns {Sequelize.json}
*/ */
static json(conditionsOrPath, value) { static json(conditionsOrPath, value) {
return new Utils.Json(conditionsOrPath, value); return new Utils.Json(conditionsOrPath, value);
...@@ -926,9 +929,8 @@ class Sequelize { ...@@ -926,9 +929,8 @@ class Sequelize {
* @see {@link Model.findAll} * @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 {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='&#61;'] * @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.) * @param {string|Object} logic The condition. Can be both a simply type, or a further condition (`or`, `and`, `.literal` etc.)
* @alias condition
* @since v2.0.0-dev3 * @since v2.0.0-dev3
*/ */
static where(attr, comparator, logic) { static where(attr, comparator, logic) {
...@@ -936,20 +938,20 @@ class Sequelize { ...@@ -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
*
* @example
* sequelize.transaction().then(transaction => { * sequelize.transaction().then(transaction => {
* return User.find(..., {transaction}) * return User.find(..., {transaction})
* .then(user => user.updateAttributes(..., {transaction})) * .then(user => user.updateAttributes(..., {transaction}))
* .then(() => transaction.commit()) * .then(() => transaction.commit())
* .catch(() => transaction.rollback()); * .catch(() => transaction.rollback());
* }) * })
* ```
* *
* A syntax for automatically committing or rolling back based on the promise chain resolution is also supported: * @example <caption>A syntax for automatically committing or rolling back based on the promise chain resolution is also supported</caption>
* *
* ```js
* sequelize.transaction(transaction => { // Note that we use a callback rather than a promise.then() * sequelize.transaction(transaction => { // Note that we use a callback rather than a promise.then()
* return User.find(..., {transaction}) * return User.find(..., {transaction})
* .then(user => user.updateAttributes(..., {transaction})) * .then(user => user.updateAttributes(..., {transaction}))
...@@ -959,27 +961,24 @@ class Sequelize { ...@@ -959,27 +961,24 @@ class Sequelize {
* // Rolled back * // Rolled back
* console.error(err); * console.error(err);
* }); * });
* ```
* *
* 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. * @example <caption>To enable CLS, add it do your project, create a namespace and set it on the sequelize constructor:</caption>
* To enable CLS, add it do your project, create a namespace and set it on the sequelize constructor:
* *
* ```js
* const cls = require('continuation-local-storage'); * const cls = require('continuation-local-storage');
* const ns = cls.createNamespace('....'); * const ns = cls.createNamespace('....');
* const Sequelize = require('sequelize'); * const Sequelize = require('sequelize');
* Sequelize.useCLS(ns); * Sequelize.useCLS(ns);
* ```
* Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace
* *
* @see {@link Transaction} * // Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace
* @param {Object} [options={}] *
* @param {Boolean} [options.autocommit] * @param {Object} [options] Transaction options
* @param {String} [options.type='DEFERRED'] See `Sequelize.Transaction.TYPES` for possible options. Sqlite only. * @param {boolean} [options.autocommit] Auto commit this transaction
* @param {String} [options.isolationLevel] See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options * @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} [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 * @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
* @return {Promise} *
* @returns {Promise}
*/ */
transaction(options, autoCallback) { transaction(options, autoCallback) {
if (typeof options === 'function') { if (typeof options === 'function') {
...@@ -1048,6 +1047,7 @@ class Sequelize { ...@@ -1048,6 +1047,7 @@ class Sequelize {
log() { log() {
let options; let options;
let args = Utils.sliceArgs(arguments); let args = Utils.sliceArgs(arguments);
const last = _.last(args); const last = _.last(args);
if (last && _.isPlainObject(last) && last.hasOwnProperty('logging')) { if (last && _.isPlainObject(last) && last.hasOwnProperty('logging')) {
...@@ -1082,7 +1082,7 @@ class Sequelize { ...@@ -1082,7 +1082,7 @@ class Sequelize {
* Normally this is done on process exit, so you only need to call this method if you are creating multiple instances, and want * Normally this is done on process exit, so you only need to call this method if you are creating multiple instances, and want
* to garbage collect some of them. * to garbage collect some of them.
* *
* @return {Promise} * @returns {Promise}
*/ */
close() { close() {
return this.connectionManager.close(); return this.connectionManager.close();
......
...@@ -4,20 +4,23 @@ const _ = require('lodash'); ...@@ -4,20 +4,23 @@ const _ = require('lodash');
const Promise = require('./promise'); const Promise = require('./promise');
/** /**
* The transaction object is used to identify a running transaction. It is created by calling `Sequelize.transaction()`. * The transaction object is used to identify a running transaction.
* * It is created by calling `Sequelize.transaction()`.
* To run a query under a transaction, you should pass the transaction in the options object. * To run a query under a transaction, you should pass the transaction in the options object.
* *
* @class Transaction
* @see {@link Sequelize.transaction} * @see {@link Sequelize.transaction}
*/ */
class Transaction { class Transaction {
/** /**
* Creates a new transaction instance
*
* @param {Sequelize} sequelize A configured sequelize Instance * @param {Sequelize} sequelize A configured sequelize Instance
* @param {Object} options An object with options * @param {Object} options An object with options
* @param {Boolean} options.autocommit Sets the autocommit property of the transaction. * @param {boolean} options.autocommit Sets the autocommit property of the transaction.
* @param {String} options.type=true Sets the type of the transaction. * @param {string} options.type=true Sets the type of the transaction.
* @param {String} options.isolationLevel=true Sets the isolation level of the transaction. * @param {string} options.isolationLevel=true Sets the isolation level of the transaction.
* @param {String} options.deferrable Sets the constraints to be deferred or immediately checked. * @param {string} options.deferrable Sets the constraints to be deferred or immediately checked.
*/ */
constructor(sequelize, options) { constructor(sequelize, options) {
this.sequelize = sequelize; this.sequelize = sequelize;
...@@ -52,10 +55,9 @@ class Transaction { ...@@ -52,10 +55,9 @@ class Transaction {
/** /**
* Commit the transaction * Commit the transaction
* *
* @return {Promise} * @returns {Promise}
*/ */
commit() { commit() {
if (this.finished) { if (this.finished) {
return Promise.reject(new Error('Transaction cannot be committed because it has been finished with state: ' + this.finished)); return Promise.reject(new Error('Transaction cannot be committed because it has been finished with state: ' + this.finished));
} }
...@@ -82,10 +84,9 @@ class Transaction { ...@@ -82,10 +84,9 @@ class Transaction {
/** /**
* Rollback (abort) the transaction * Rollback (abort) the transaction
* *
* @return {Promise} * @returns {Promise}
*/ */
rollback() { rollback() {
if (this.finished) { if (this.finished) {
return Promise.reject(new Error('Transaction cannot be rolled back because it has been finished with state: ' + this.finished)); return Promise.reject(new Error('Transaction cannot be rolled back because it has been finished with state: ' + this.finished));
} }
...@@ -191,9 +192,10 @@ class Transaction { ...@@ -191,9 +192,10 @@ class Transaction {
/** /**
* A hook that is run after a transaction is committed * A hook that is run after a transaction is committed
*
* @param {Function} fn A callback function that is called with the committed transaction * @param {Function} fn A callback function that is called with the committed transaction
* @name afterCommit * @name afterCommit
* @memberOf Sequelize.Transaction * @memberof Sequelize.Transaction
*/ */
afterCommit(fn) { afterCommit(fn) {
if (!fn || typeof fn !== 'function') { if (!fn || typeof fn !== 'function') {
...@@ -209,17 +211,15 @@ class Transaction { ...@@ -209,17 +211,15 @@ class Transaction {
* *
* Pass in the desired level as the first argument: * Pass in the desired level as the first argument:
* *
* ```js * @example
* return sequelize.transaction({type: Sequelize.Transaction.TYPES.EXCLUSIVE}, transaction => { * return sequelize.transaction({type: Sequelize.Transaction.TYPES.EXCLUSIVE}, transaction => {
*
* // your transactions * // your transactions
*
* }).then(result => { * }).then(result => {
* // transaction has been committed. Do something after the commit if required. * // transaction has been committed. Do something after the commit if required.
* }).catch(err => { * }).catch(err => {
* // do something with the err. * // do something with the err.
* }); * });
* ``` *
* @property DEFERRED * @property DEFERRED
* @property IMMEDIATE * @property IMMEDIATE
* @property EXCLUSIVE * @property EXCLUSIVE
...@@ -233,22 +233,20 @@ class Transaction { ...@@ -233,22 +233,20 @@ class Transaction {
} }
/** /**
* Isolations levels can be set per-transaction by passing `options.isolationLevel` to `sequelize.transaction`. * Isolation levels can be set per-transaction by passing `options.isolationLevel` to `sequelize.transaction`.
* Default to `REPEATABLE_READ` but you can override the default isolation level by passing `options.isolationLevel` in `new Sequelize`. * Default to `REPEATABLE_READ` but you can override the default isolation level by passing `options.isolationLevel` in `new Sequelize`.
* *
* Pass in the desired level as the first argument: * Pass in the desired level as the first argument:
* *
* ```js * @example
* return sequelize.transaction({isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE}, transaction => { * return sequelize.transaction({isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE}, transaction => {
*
* // your transactions * // your transactions
*
* }).then(result => { * }).then(result => {
* // transaction has been committed. Do something after the commit if required. * // transaction has been committed. Do something after the commit if required.
* }).catch(err => { * }).catch(err => {
* // do something with the err. * // do something with the err.
* }); * });
* ``` *
* @property READ_UNCOMMITTED * @property READ_UNCOMMITTED
* @property READ_COMMITTED * @property READ_COMMITTED
* @property REPEATABLE_READ * @property REPEATABLE_READ
...@@ -267,17 +265,15 @@ class Transaction { ...@@ -267,17 +265,15 @@ class Transaction {
/** /**
* Possible options for row locking. Used in conjunction with `find` calls: * Possible options for row locking. Used in conjunction with `find` calls:
* *
* ```js * @example
* t1 // is a transaction * // t1 is a transaction
* Model.findAll({ * Model.findAll({
* where: ..., * where: ...,
* transaction: t1, * transaction: t1,
* lock: t1.LOCK... * lock: t1.LOCK...
* }); * });
* ```
* *
* Postgres also supports specific locks while eager loading by using OF: * @example <caption>Postgres also supports specific locks while eager loading by using OF:</caption>
* ```js
* UserModel.findAll({ * UserModel.findAll({
* where: ..., * where: ...,
* include: [TaskModel, ...], * include: [TaskModel, ...],
...@@ -287,23 +283,20 @@ class Transaction { ...@@ -287,23 +283,20 @@ class Transaction {
* of: UserModel * of: UserModel
* } * }
* }); * });
* ```
* UserModel will be locked but TaskModel won't!
* *
* You can also skip locked rows: * # UserModel will be locked but TaskModel won't!
* *
*```js * @example <caption>You can also skip locked rows:</caption>
* t1 // is a transaction * // t1 is a transaction
* Model.findAll({ * Model.findAll({
* where: ..., * where: ...,
* transaction: t1, * transaction: t1,
* lock: true, * lock: true,
* skipLocked: true * skipLocked: true
* }); * });
* ``` * # The query will now return any rows that aren't locked by another transaction
* The query will now return any rows that aren't locked by another transaction
* *
* @return {Object} * @returns {Object}
* @property UPDATE * @property UPDATE
* @property SHARE * @property SHARE
* @property KEY_SHARE Postgres 9.3+ only * @property KEY_SHARE Postgres 9.3+ only
...@@ -319,7 +312,7 @@ class Transaction { ...@@ -319,7 +312,7 @@ class Transaction {
} }
/** /**
* @see {@link Transaction.LOCK} * Please {@link Transaction.LOCK}
*/ */
get LOCK() { get LOCK() {
return Transaction.LOCK; return Transaction.LOCK;
......
...@@ -278,7 +278,7 @@ exports.toDefaultValue = toDefaultValue; ...@@ -278,7 +278,7 @@ exports.toDefaultValue = toDefaultValue;
* in a db schema using the DEFAULT directive. * in a db schema using the DEFAULT directive.
* *
* @param {*} value Any default value. * @param {*} value Any default value.
* @return {boolean} yes / no. * @returns {boolean} yes / no.
* @private * @private
*/ */
function defaultValueSchemable(value) { function defaultValueSchemable(value) {
...@@ -394,7 +394,7 @@ exports.removeTicks = removeTicks; ...@@ -394,7 +394,7 @@ exports.removeTicks = removeTicks;
* } * }
* *
* @param value, an Object * @param value, an Object
* @return Object, an flattened object * @returns Object, an flattened object
* @private * @private
*/ */
function flattenObjectDeep(value) { function flattenObjectDeep(value) {
...@@ -501,7 +501,7 @@ exports.Where = Where; ...@@ -501,7 +501,7 @@ exports.Where = Where;
/** /**
* getOperators * getOperators
* @param {Object} obj * @param {Object} obj
* @return {Array<Symbol>} All operators properties of obj * @returns {Array<Symbol>} All operators properties of obj
* @private * @private
*/ */
function getOperators(obj) { function getOperators(obj) {
...@@ -512,7 +512,7 @@ exports.getOperators = getOperators; ...@@ -512,7 +512,7 @@ exports.getOperators = getOperators;
/** /**
* getComplexKeys * getComplexKeys
* @param {Object} obj * @param {Object} obj
* @return {Array<String|Symbol>} All keys including operators * @returns {Array<String|Symbol>} All keys including operators
* @private * @private
*/ */
function getComplexKeys(obj) { function getComplexKeys(obj) {
...@@ -523,7 +523,7 @@ exports.getComplexKeys = getComplexKeys; ...@@ -523,7 +523,7 @@ exports.getComplexKeys = getComplexKeys;
/** /**
* getComplexSize * getComplexSize
* @param {Object|Array} obj * @param {Object|Array} obj
* @return {Integer} Length of object properties including operators if obj is array returns its length * @returns {Integer} Length of object properties including operators if obj is array returns its length
* @private * @private
*/ */
function getComplexSize(obj) { function getComplexSize(obj) {
...@@ -535,7 +535,7 @@ exports.getComplexSize = getComplexSize; ...@@ -535,7 +535,7 @@ exports.getComplexSize = getComplexSize;
* Returns true if a where clause is empty, even with Symbols * Returns true if a where clause is empty, even with Symbols
* *
* @param {Object} obj * @param {Object} obj
* @return {Boolean} * @returns {boolean}
* @private * @private
*/ */
function isWhereEmpty(obj) { function isWhereEmpty(obj) {
...@@ -546,9 +546,9 @@ exports.isWhereEmpty = isWhereEmpty; ...@@ -546,9 +546,9 @@ exports.isWhereEmpty = isWhereEmpty;
/** /**
* Returns ENUM name by joining table and column name * Returns ENUM name by joining table and column name
* *
* @param {String} tableName * @param {string} tableName
* @param {String} columnName * @param {string} columnName
* @return {String} * @returns {string}
* @private * @private
*/ */
function generateEnumName(tableName, columnName) { function generateEnumName(tableName, columnName) {
...@@ -559,7 +559,7 @@ exports.generateEnumName = generateEnumName; ...@@ -559,7 +559,7 @@ exports.generateEnumName = generateEnumName;
/** /**
* Returns an new Object which keys are camelized * Returns an new Object which keys are camelized
* @param {Object} obj * @param {Object} obj
* @return {String} * @returns {string}
* @private * @private
*/ */
function camelizeObjectKeys(obj) { function camelizeObjectKeys(obj) {
...@@ -624,7 +624,7 @@ exports.classToInvokable = classToInvokable; ...@@ -624,7 +624,7 @@ exports.classToInvokable = classToInvokable;
* *
* @param {Object} index * @param {Object} index
* @param {Array} index.fields * @param {Array} index.fields
* @param {String} [index.name] * @param {string} [index.name]
* @param {String|Object} tableName * @param {String|Object} tableName
* *
* @returns {Object} * @returns {Object}
......
...@@ -4,7 +4,12 @@ const util = require('util'); ...@@ -4,7 +4,12 @@ const util = require('util');
const _ = require('lodash'); const _ = require('lodash');
/** /**
* like util.inherits, but also copies over static properties * like util.inherits, but also copies over static properties. Inherit child constructor
* to have properties from super constructor
*
* @param {Function} constructor the child constructor
* @param {Function} superConstructor the super constructor
*
* @private * @private
*/ */
function inherits(constructor, superConstructor) { function inherits(constructor, superConstructor) {
......
...@@ -47,13 +47,16 @@ ...@@ -47,13 +47,16 @@
"continuation-local-storage": "^3.x", "continuation-local-storage": "^3.x",
"cross-env": "^5.2.0", "cross-env": "^5.2.0",
"cz-conventional-changelog": "^2.x", "cz-conventional-changelog": "^2.x",
"docdash": "^0.4.0",
"env-cmd": "^8.0.0", "env-cmd": "^8.0.0",
"esdoc": "^0.5.2", "esdoc": "^0.5.2",
"eslint": "^5.0.0", "eslint": "^5.0.0",
"eslint-plugin-jsdoc": "^3.7.1",
"eslint-plugin-mocha": "^5.0.0", "eslint-plugin-mocha": "^5.0.0",
"hints": "^1.x", "hints": "^1.x",
"husky": "^0.x", "husky": "^0.x",
"istanbul": "^0.x", "istanbul": "^0.x",
"jsdoc": "^3.5.5",
"lcov-result-merger": "^3.0.0", "lcov-result-merger": "^3.0.0",
"mocha": "^5.x", "mocha": "^5.x",
"mysql2": "^1.x", "mysql2": "^1.x",
...@@ -91,6 +94,7 @@ ...@@ -91,6 +94,7 @@
"test-docker-unit": "npm run test-unit", "test-docker-unit": "npm run test-unit",
"test-docker-integration": "env-cmd $npm_package_options_env_cmd npm run test-integration", "test-docker-integration": "env-cmd $npm_package_options_env_cmd npm run test-integration",
"docs": "esdoc && cp docs/ROUTER esdoc/ROUTER", "docs": "esdoc && cp docs/ROUTER esdoc/ROUTER",
"generate-jsdocs": "node_modules/.bin/jsdoc -c jsdoc.json",
"teaser": "node -e \"console.log('#'.repeat(process.env.DIALECT.length + 22) + '\\n# Running tests for ' + process.env.DIALECT + ' #\\n' + '#'.repeat(process.env.DIALECT.length + 22))\"", "teaser": "node -e \"console.log('#'.repeat(process.env.DIALECT.length + 22) + '\\n# Running tests for ' + process.env.DIALECT + ' #\\n' + '#'.repeat(process.env.DIALECT.length + 22))\"",
"test-unit": "mocha --require scripts/mocha-bootload --globals setImmediate,clearImmediate --ui tdd --exit --check-leaks --colors -t 30000 --reporter spec \"test/unit/**/*.js\"", "test-unit": "mocha --require scripts/mocha-bootload --globals setImmediate,clearImmediate --ui tdd --exit --check-leaks --colors -t 30000 --reporter spec \"test/unit/**/*.js\"",
"test-unit-mysql": "cross-env DIALECT=mysql npm run test-unit", "test-unit-mysql": "cross-env DIALECT=mysql npm run test-unit",
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!