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

Commit 14d14468 by Sushant Committed by GitHub

docs: cleanup / correct jsdocs (#9702)

1 parent 84f80481
......@@ -3,6 +3,22 @@
"mocha/no-exclusive-tests": "error",
"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",
"comma-spacing": "error",
"key-spacing": "error",
......@@ -90,11 +106,25 @@
"sourceType": "script"
},
"plugins": [
"mocha"
"mocha",
"jsdoc"
],
"env": {
"node": true,
"mocha": 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
*.swp
.idea
.DS_STORE
node_modules
npm-debug.log
*~
test/binary/tmp/*
test/tmp/*
test/dialects/sqlite/test.sqlite
test/sqlite/test.sqlite
coverage-*
site
docs/api/tmp.md
ssce.js
sscce.js
coverage
.vscode/
*.sublime*
esdoc
package-lock.json
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 {
/**
* 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) {
if (!Array.isArray(input)) {
......
......@@ -357,12 +357,15 @@ class BelongsToMany extends Association {
/**
* Get everything currently associated with this, using an optional where clause.
*
* @param {Object} [options]
* @param {Object} [options.where] An optional where clause to limit the associated models
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {String} [options.schema] Apply a schema on the related model
* @see {@link Model.findAll} for a full explanation of options
* @return {Promise<Array<Model>>}
*
* @param {<Model>} instance instance
* @param {Object} [options] find options
* @param {Object} [options.where] An optional where clause to limit the associated models
* @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {string} [options.schema] Apply a schema on the related model
*
* @returns {Promise<Array<<Model>>>}
*/
get(instance, options) {
options = Utils.cloneDeep(options) || {};
......@@ -426,10 +429,12 @@ class BelongsToMany extends Association {
/**
* Count everything currently associated with this, using an optional where clause.
*
* @param {Object} [options]
* @param {<Model>} instance instance
* @param {Object} [options] find options
* @param {Object} [options.where] An optional where clause to limit the associated models
* @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @return {Promise<Integer>}
* @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
*
* @returns {Promise<number>}
*/
count(instance, options) {
const association = this;
......@@ -450,9 +455,11 @@ class BelongsToMany extends Association {
/**
* Check if one or more instance(s) are associated with this. If a list of instances is passed, the function returns true if _all_ instances are associated
*
* @param {Model[]|Model|string[]|String|number[]|Number} [instance(s)] Can be an array of instances or their primary keys
* @param {<Model>} sourceInstance source instance to associate new instances with
* @param {<Model>|<Model>[]|string[]|string|number[]|number} [instances] Can be an array of instances or their primary keys
* @param {Object} [options] Options passed to getAssociations
* @return {Promise<boolean>}
*
* @returns {Promise<boolean>}
*/
has(sourceInstance, instances, options) {
const association = this;
......@@ -489,13 +496,16 @@ class BelongsToMany extends Association {
}
/**
* Set the associated models by passing an array of instances or their primary keys. Everything that it not in the passed array will be un-associated.
* Set the associated models by passing an array of instances or their primary keys.
* Everything that it not in the passed array will be un-associated.
*
* @param {Array<Model|String|Number>} [newAssociations] An array of persisted instances or primary key of instances to associate with this. Pass `null` or `undefined` to remove all associations.
* @param {<Model>} sourceInstance source instance to associate new instances with
* @param {<Model>|<Model>[]|string[]|string|number[]|number} [newAssociatedObjects] A single instance or primary key, or a mixed array of persisted instances or primary keys
* @param {Object} [options] Options passed to `through.findAll`, `bulkCreate`, `update` and `destroy`
* @param {Object} [options.validate] Run validation for the join model
* @param {Object} [options.through] Additional attributes for the join table.
* @return {Promise}
*
* @returns {Promise}
*/
set(sourceInstance, newAssociatedObjects, options) {
options = options || {};
......@@ -590,13 +600,16 @@ class BelongsToMany extends Association {
}
/**
* Associate one ore several rows with `this`.
* Associate one ore several rows with source instance. It will not un-associate any already assoicated instance
* that may be missing from `newInstances`.
*
* @param {Model[]|Model|string[]|string|number[]|Number} [newAssociation(s)] A single instance or primary key, or a mixed array of persisted instances or primary keys
* @param {<Model>} sourceInstance source instance to associate new instances with
* @param {<Model>|<Model>[]|string[]|string|number[]|number} [newInstances] A single instance or primary key, or a mixed array of persisted instances or primary keys
* @param {Object} [options] Options passed to `through.findAll`, `bulkCreate` and `update`
* @param {Object} [options.validate] Run validation for the join model.
* @param {Object} [options.through] Additional attributes for the join table.
* @return {Promise}
*
* @returns {Promise}
*/
add(sourceInstance, newInstances, options) {
// If newInstances is null or undefined, no-op
......@@ -684,9 +697,11 @@ class BelongsToMany extends Association {
/**
* Un-associate one or more instance(s).
*
* @param {Model|String|Number} [oldAssociated] Can be an Instance or its primary key, or a mixed array of instances and primary keys
* @param {<Model>} sourceInstance instance to un associate instances with
* @param {<Model>|<Model>[]|string|string[]|number|number[]} [oldAssociatedObjects] Can be an Instance or its primary key, or a mixed array of instances and primary keys
* @param {Object} [options] Options passed to `through.destroy`
* @return {Promise}
*
* @returns {Promise}
*/
remove(sourceInstance, oldAssociatedObjects, options) {
const association = this;
......@@ -705,10 +720,12 @@ class BelongsToMany extends Association {
/**
* 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.through] Additional attributes for the join table
* @return {Promise}
*
* @returns {Promise}
*/
create(sourceInstance, values, options) {
const association = this;
......
......@@ -113,13 +113,14 @@ class BelongsTo extends Association {
/**
* Get the associated instance.
*
* @param {Object} [options]
* @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 {<Model>|Array<Model>} instances source instances
* @param {Object} [options] find options
* @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false.
* @param {string} [options.schema] Apply a schema on the related model
*
* @see {@link Model.findOne} for a full explanation of options
*
* @return {Promise<Model>}
* @returns {Promise<<Model>>}
*/
get(instances, options) {
const where = {};
......@@ -183,11 +184,12 @@ class BelongsTo extends Association {
/**
* Set the associated model.
*
* @param {Model|String|Number} [newAssociation] An persisted instance or the primary key of an instance to associate with this. Pass `null` or `undefined` to remove the association.
* @param {Object} [options] Options passed to `this.save`
* @param {Boolean} [options.save=true] Skip saving this after setting the foreign key if false.
* @param {<Model>} sourceInstance the source instance
* @param {?<Model>|string|number} [associatedInstance] An persisted instance or the primary key of an instance to associate with this. Pass `null` or `undefined` to remove the association.
* @param {Object} [options={}] options passed to `this.save`
* @param {boolean} [options.save=true] Skip saving this after setting the foreign key if false.
*
* @return {Promise}
* @returns {Promise}
*/
set(sourceInstance, associatedInstance, options = {}) {
let value = associatedInstance;
......@@ -213,12 +215,13 @@ class BelongsTo extends Association {
/**
* Create a new instance of the associated model and associate it with this.
*
* @param {Object} [values]
* @param {Object} [options] Options passed to `target.create` and setAssociation.
* @param {<Model>} sourceInstance the source instance
* @param {Object} [values={}] values to create associated model instance with
* @param {Object} [options={}] Options passed to `target.create` and setAssociation.
*
* @see {@link Model#create} for a full explanation of options
*
* @return {Promise}
* @returns {Promise}
*/
create(sourceInstance, values, options) {
values = values || {};
......
......@@ -157,12 +157,15 @@ class HasMany extends Association {
/**
* 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 {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|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {string} [options.schema] Apply a schema on the related model
*
* @see {@link Model.findAll} for a full explanation of options
* @return {Promise<Array<Model>>}
*
* @returns {Promise<Array<<Model>>>}
*/
get(instances, options = {}) {
const where = {};
......@@ -238,11 +241,12 @@ class HasMany extends Association {
/**
* 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 {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) {
options = Utils.cloneDeep(options);
......@@ -265,10 +269,11 @@ class HasMany extends Association {
/**
* 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
*
* @return {Promise}
* @returns {Promise}
*/
has(sourceInstance, targetInstances, options) {
const where = {};
......@@ -305,10 +310,12 @@ class HasMany extends Association {
/**
* Set the associated models by passing an array of persisted instances or their primary keys. Everything that is not in the passed array will be un-associated
*
* @param {Array<Model|String|Number>} [newAssociations] An array of persisted instances or primary key of instances to associate with this. Pass `null` or `undefined` to remove all associations.
* @param {<Model>} sourceInstance source instance to associate new instances with
* @param {<Model>|<Model>[]|string[]|string|number[]|number} [targetInstances] An array of persisted instances or primary key of instances to associate with this. Pass `null` or `undefined` to remove all associations.
* @param {Object} [options] Options passed to `target.findAll` and `update`.
* @param {Object} [options.validate] Run validation for the join model
* @return {Promise}
*
* @returns {Promise}
*/
set(sourceInstance, targetInstances, options) {
if (targetInstances === null) {
......@@ -377,9 +384,11 @@ class HasMany extends Association {
* Associate one or more target rows with `this`. This method accepts a Model / string / number to associate a single row,
* or a mixed array of Model / string / numbers to associate multiple rows.
*
* @param {Model[]|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`.
* @return {Promise}
*
* @returns {Promise}
*/
add(sourceInstance, targetInstances, options = {}) {
if (!targetInstances) return Utils.Promise.resolve();
......@@ -402,9 +411,11 @@ class HasMany extends Association {
/**
* 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`
* @return {Promise}
*
* @returns {Promise}
*/
remove(sourceInstance, targetInstances, options = {}) {
const update = {};
......@@ -425,9 +436,11 @@ class HasMany extends Association {
/**
* Create a new instance of the associated model and associate it with this.
*
* @param {Object} [values]
* @param {Object} [options] Options passed to `target.create`.
* @return {Promise}
* @param {<Model>} sourceInstance source instance
* @param {Object} [values] values for target model instance
* @param {Object} [options] Options passed to `target.create`
*
* @returns {Promise}
*/
create(sourceInstance, values, options = {}) {
if (Array.isArray(options)) {
......
......@@ -112,11 +112,14 @@ class HasOne extends Association {
/**
* Get the associated instance.
*
* @param {Object} [options]
* @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 {<Model>|Array<Model>} instances source instances
* @param {Object} [options] find options
* @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {string} [options.schema] Apply a schema on the related model
*
* @see {@link Model.findOne} for a full explanation of options
* @return {Promise<Model>}
*
* @returns {Promise<Model>}
*/
get(instances, options) {
const where = {};
......@@ -180,10 +183,11 @@ class HasOne extends Association {
/**
* Set the associated model.
*
* @param {Model|String|Number} [associatedInstance] An persisted instance or the primary key of a persisted instance to associate with this. Pass `null` or `undefined` to remove the association.
* @param {<Model>} sourceInstance the source instance
* @param {?<Model>|string|number} [associatedInstance] An persisted instance or the primary key of an instance to associate with this. Pass `null` or `undefined` to remove the association.
* @param {Object} [options] Options passed to getAssociation and `target.save`
*
* @return {Promise}
* @returns {Promise}
*/
set(sourceInstance, associatedInstance, options) {
let alreadyAssociated;
......@@ -229,12 +233,13 @@ class HasOne extends Association {
/**
* Create a new instance of the associated model and associate it with this.
*
* @param {Object} [values]
* @param {<Model>} sourceInstance the source instance
* @param {Object} [values={}] values to create associated model instance with
* @param {Object} [options] Options passed to `target.create` and setAssociation.
*
* @see {@link Model#create} for a full explanation of options
*
* @return {Promise}
* @returns {Promise}
*/
create(sourceInstance, values, options) {
values = values || {};
......
......@@ -45,10 +45,12 @@ exports.addForeignKeyConstraints = addForeignKeyConstraints;
* Mixin (inject) association methods to model prototype
*
* @private
* @param {Object} Association instance
* @param {Object} Model prototype
* @param {Array} Method names to inject
* @param {Object} Mapping between model and association method names
*
* @param {Object} association instance
* @param {Object} obj Model prototype
* @param {Array} methods Method names to inject
* @param {Object} aliases Mapping between model and association method names
*
*/
function mixinMethods(association, obj, methods, aliases) {
aliases = aliases || {};
......
......@@ -40,6 +40,15 @@ ABSTRACT.prototype.bindParam = function bindParam(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) {
const options = typeof length === 'object' && length || {length, 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) {
const options = typeof length === 'object' && length || {length, binary};
......@@ -86,6 +103,13 @@ CHAR.prototype.toSql = function toSql() {
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) {
const options = typeof length === 'object' && length || {length};
if (!(this instanceof TEXT)) return new TEXT(options);
......@@ -115,6 +139,19 @@ TEXT.prototype.validate = function validate(value) {
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) {
this.options = options;
this._length = options.length;
......@@ -144,7 +181,6 @@ NUMBER.prototype.toSql = function toSql() {
}
return result;
};
NUMBER.prototype.validate = function(value) {
if (!Validator.isFloat(String(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) {
return true;
};
Object.defineProperty(NUMBER.prototype, 'UNSIGNED', {
get() {
this._unsigned = true;
......@@ -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) {
const options = typeof length === 'object' && length || {length};
if (!(this instanceof INTEGER)) return new INTEGER(options);
......@@ -184,6 +226,13 @@ INTEGER.prototype.validate = function validate(value) {
return true;
};
/**
* A 8 bit integer
*
* @param {string|number} [length] Integer length
*
* @namespace DataTypes.TINYINT
*/
function TINYINT(length) {
const options = typeof length === 'object' && length || {length};
if (!(this instanceof TINYINT)) return new TINYINT(options);
......@@ -193,6 +242,13 @@ inherits(TINYINT, INTEGER);
TINYINT.prototype.key = TINYINT.key = 'TINYINT';
/**
* A 16 bit integer
*
* @param {string|number} [length] Integer length
*
* @namespace DataTypes.SMALLINT
*/
function SMALLINT(length) {
const options = typeof length === 'object' && length || {length};
if (!(this instanceof SMALLINT)) return new SMALLINT(options);
......@@ -202,6 +258,13 @@ inherits(SMALLINT, INTEGER);
SMALLINT.prototype.key = SMALLINT.key = 'SMALLINT';
/**
* A 24 bit integer
*
* @param {string|number} [length] Integer length
*
* @namespace DataTypes.MEDIUMINT
*/
function MEDIUMINT(length) {
const options = typeof length === 'object' && length || {length};
if (!(this instanceof MEDIUMINT)) return new MEDIUMINT(options);
......@@ -211,6 +274,13 @@ inherits(MEDIUMINT, INTEGER);
MEDIUMINT.prototype.key = MEDIUMINT.key = 'MEDIUMINT';
/**
* A 64 bit integer
*
* @param {string|number} [length] Integer length
*
* @namespace DataTypes.BIGINT
*/
function BIGINT(length) {
const options = typeof length === 'object' && length || {length};
if (!(this instanceof BIGINT)) return new BIGINT(options);
......@@ -220,6 +290,14 @@ inherits(BIGINT, INTEGER);
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) {
const options = typeof length === 'object' && length || {length, decimals};
if (!(this instanceof FLOAT)) return new FLOAT(options);
......@@ -236,6 +314,14 @@ FLOAT.prototype.validate = function validate(value) {
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) {
const options = typeof length === 'object' && length || {length, decimals};
if (!(this instanceof REAL)) return new REAL(options);
......@@ -245,6 +331,14 @@ inherits(REAL, NUMBER);
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) {
const options = typeof length === 'object' && length || {length, decimals};
if (!(this instanceof DOUBLE)) return new DOUBLE(options);
......@@ -254,6 +348,14 @@ inherits(DOUBLE, NUMBER);
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) {
const options = typeof precision === 'object' && precision || {precision, scale};
if (!(this instanceof DECIMAL)) return new DECIMAL(options);
......@@ -298,6 +400,11 @@ for (const floating of [FLOAT, DOUBLE, REAL]) {
};
}
/**
* A boolean / tinyint column, depending on dialect
*
* @namespace DataTypes.BOOLEAN
*/
function BOOLEAN() {
if (!(this instanceof BOOLEAN)) return new BOOLEAN();
}
......@@ -336,6 +443,11 @@ BOOLEAN.prototype._sanitize = function _sanitize(value) {
};
BOOLEAN.parse = BOOLEAN.prototype._sanitize;
/**
* A time column
*
* @namespace DataTypes.TIME
*/
function TIME() {
if (!(this instanceof TIME)) return new TIME();
}
......@@ -346,6 +458,13 @@ TIME.prototype.toSql = function toSql() {
return 'TIME';
};
/**
* Date column with timezone, default is UTC
*
* @param {string|number} [length] precision to allow storing milliseconds
*
* @namespace DataTypes.DATE
*/
function DATE(length) {
const options = typeof length === 'object' && length || {length};
......@@ -416,6 +535,11 @@ DATE.prototype._stringify = function _stringify(date, options) {
return date.format('YYYY-MM-DD HH:mm:ss.SSS Z');
};
/**
* A date only column (no timestamp)
*
* @namespace DataTypes.DATEONLY
*/
function DATEONLY() {
if (!(this instanceof DATEONLY)) return new DATEONLY();
}
......@@ -451,6 +575,11 @@ DATEONLY.prototype._isChanged = function _isChanged(value, originalValue) {
return true;
};
/**
* A key / value store column. Only available in Postgres.
*
* @namespace DataTypes.HSTORE
*/
function HSTORE() {
if (!(this instanceof HSTORE)) return new HSTORE();
}
......@@ -465,6 +594,11 @@ HSTORE.prototype.validate = function validate(value) {
return true;
};
/**
* A JSON string column. Available in MySQL, Postgres and SQLite
*
* @namespace DataTypes.JSON
*/
function JSONTYPE() {
if (!(this instanceof JSONTYPE)) return new JSONTYPE();
}
......@@ -479,6 +613,11 @@ JSONTYPE.prototype._stringify = function _stringify(value) {
return JSON.stringify(value);
};
/**
* A binary storage JSON column. Only available in Postgres.
*
* @namespace DataTypes.JSONB
*/
function JSONB() {
if (!(this instanceof JSONB)) return new JSONB();
JSONTYPE.call(this);
......@@ -487,6 +626,11 @@ inherits(JSONB, JSONTYPE);
JSONB.prototype.key = JSONB.key = 'JSONB';
/**
* A default value of the current timestamp
*
* @namespace DataTypes.NOW
*/
function NOW() {
if (!(this instanceof NOW)) return new NOW();
}
......@@ -494,6 +638,14 @@ inherits(NOW, ABSTRACT);
NOW.prototype.key = NOW.key = 'NOW';
/**
* Binary storage
*
* @param {string} [length=''] could be tiny, medium, long.
*
* @namespace DataTypes.BLOB
*
*/
function BLOB(length) {
const options = typeof length === 'object' && length || {length};
if (!(this instanceof BLOB)) return new BLOB(options);
......@@ -552,6 +704,14 @@ BLOB.prototype._bindParam = function _bindParam(value, options) {
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) {
const options = _.isPlainObject(subtype) ? subtype : {subtype};
......@@ -605,6 +765,12 @@ RANGE.prototype.validate = function validate(value) {
return true;
};
/**
* A column storing a unique universal identifier.
* Use with `UUIDV1` or `UUIDV4` for default values.
*
* @namespace DataTypes.UUID
*/
function UUID() {
if (!(this instanceof UUID)) return new UUID();
}
......@@ -619,6 +785,11 @@ UUID.prototype.validate = function validate(value, options) {
return true;
};
/**
* A default unique universal identifier generated following the UUID v1 standard
*
* @namespace DataTypes.UUIDV1
*/
function UUIDV1() {
if (!(this instanceof UUIDV1)) return new UUIDV1();
}
......@@ -633,6 +804,11 @@ UUIDV1.prototype.validate = function validate(value, options) {
return true;
};
/**
* A default unique universal identifier generated following the UUID v4 standard
*
* @namespace DataTypes.UUIDV4
*/
function UUIDV4() {
if (!(this instanceof UUIDV4)) return new UUIDV4();
}
......@@ -647,6 +823,51 @@ UUIDV4.prototype.validate = function validate(value, options) {
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) {
if (!(this instanceof VIRTUAL)) return new VIRTUAL(ReturnType, fields);
if (typeof ReturnType === 'function') ReturnType = new ReturnType();
......@@ -658,6 +879,21 @@ inherits(VIRTUAL, ABSTRACT);
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) {
const options = typeof value === 'object' && !Array.isArray(value) && value || {
values: Array.prototype.slice.call(arguments).reduce((result, element) => {
......@@ -679,6 +915,16 @@ ENUM.prototype.validate = function validate(value) {
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) {
const options = _.isPlainObject(type) ? type : {type};
if (!(this instanceof ARRAY)) return new ARRAY(options);
......@@ -701,6 +947,56 @@ ARRAY.is = function is(obj, 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) {
const options = _.isPlainObject(type) ? type : {type, srid};
......@@ -722,6 +1018,32 @@ GEOMETRY.prototype._bindParam = function _bindParam(value, options) {
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) {
const options = _.isPlainObject(type) ? type : {type, srid};
......@@ -743,6 +1065,13 @@ GEOGRAPHY.prototype._bindParam = function _bindParam(value, options) {
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() {
if (!(this instanceof CIDR)) return new CIDR();
}
......@@ -758,6 +1087,13 @@ CIDR.prototype.validate = function validate(value) {
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() {
if (!(this instanceof INET)) return new INET();
}
......@@ -773,6 +1109,13 @@ INET.prototype.validate = function validate(value) {
return true;
};
/**
* The MACADDR type stores MAC addresses. Takes 6 bytes
*
* Only available for Postgres
*
* @namespace DataTypes.MACADDR
*/
function MACADDR() {
if (!(this instanceof MACADDR)) return new MACADDR();
}
......@@ -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
* sequelize.define('model', {
* column: DataTypes.INTEGER
......@@ -831,7 +1174,6 @@ for (const helper of Object.keys(helpers)) {
* * All number types (`INTEGER`, `BIGINT`, `FLOAT`, `DOUBLE`, `REAL`, `DECIMAL`) expose the properties `UNSIGNED` and `ZEROFILL`
* * The `CHAR` and `STRING` types expose the `BINARY` property
*
*
* Three of the values provided here (`NOW`, `UUIDV1` and `UUIDV4`) are special default values, that should not be used to define types. Instead they are used as shorthands for
* defining default values. For example, to get a uuid field with a default value generated following v1 of the UUID standard:
* ```js`
......@@ -858,109 +1200,7 @@ for (const helper of Object.keys(helpers)) {
* })
* ```
*
* @property {function(length=255: integer)} STRING A variable length string
* @property {function(length=255: integer)} CHAR A fixed length string.
* @property {function(length: string)} TEXT An unlimited length text column. Available lengths: `tiny`, `medium`, `long`
* @property {function(length: integer)} TINYINT A 8 bit integer.
* @property {function(length: integer)} SMALLINT A 16 bit integer.
* @property {function(length: integer)} MEDIUMINT A 24 bit integer.
* @property {function(length=255: integer)} INTEGER A 32 bit integer.
* @property {function(length: integer)} BIGINT A 64 bit integer. Note: an attribute defined as `BIGINT` will be treated like a `string` due this [feature from node-postgres](https://github.com/brianc/node-postgres/pull/353) to prevent precision loss. To have this attribute as a `number`, this is a possible [workaround](https://github.com/sequelize/sequelize/issues/2383#issuecomment-58006083).
* @property {function(length: integer, decimals: integer)} FLOAT Floating point number (4-byte precision).
* @property {function(length: integer, decimals: integer)} DOUBLE Floating point number (8-byte precision).
* @property {function(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)
* }
* }
* }
* ```
* @namespace DataTypes
*/
const DataTypes = module.exports = {
ABSTRACT,
......
......@@ -62,7 +62,7 @@ class ConnectionManager {
* Handler which executes on process exit or connection manager shutdown
*
* @private
* @return {Promise}
* @returns {Promise}
*/
_onProcessExit() {
if (!this.pool) {
......@@ -78,7 +78,7 @@ class ConnectionManager {
/**
* Drain the pool and close it permanently
*
* @return {Promise}
* @returns {Promise}
*/
close() {
// Mark close of pool
......@@ -234,10 +234,10 @@ class ConnectionManager {
*
* @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 {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 {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
*
* @return {Promise<Connection>}
* @returns {Promise<Connection>}
*/
getConnection(options) {
options = options || {};
......@@ -282,7 +282,7 @@ class ConnectionManager {
*
* @param {Connection} connection
*
* @return {Promise}
* @returns {Promise}
*/
releaseConnection(connection) {
return this.pool.release(connection)
......@@ -296,7 +296,7 @@ class ConnectionManager {
*
* @param {Object|Error} mayBeConnection Object which can be either connection or error
*
* @return {Promise<Connection>}
* @returns {Promise<Connection>}
*/
_determineConnection(mayBeConnection) {
if (mayBeConnection instanceof Error) {
......@@ -313,7 +313,7 @@ class ConnectionManager {
*
* @param {*} config Connection config
* @private
* @return {Promise<Connection>}
* @returns {Promise<Connection>}
*/
_connect(config) {
return this.sequelize.runHooks('beforeConnect', config)
......@@ -326,7 +326,7 @@ class ConnectionManager {
*
* @param {Connection} connection
* @private
* @return {Promise}
* @returns {Promise}
*/
_disconnect(connection) {
return this.dialect.connectionManager.disconnect(connection);
......@@ -337,7 +337,7 @@ class ConnectionManager {
*
* @param {Connection} connection
*
* @return {Boolean}
* @returns {boolean}
*/
_validate(connection) {
if (!this.dialect.connectionManager.validate) {
......
......@@ -95,7 +95,7 @@ class QueryGenerator {
/**
* Returns an insert into command
*
* @param {String} table
* @param {string} table
* @param {Object} valueHash attribute value pairs
* @param {Object} modelAttributes
* @param {Object} [options]
......@@ -262,7 +262,7 @@ class QueryGenerator {
/**
* Returns an insert into command for multiple values.
*
* @param {String} tableName
* @param {string} tableName
* @param {Object} fieldValueHashes
* @param {Object} options
* @param {Object} fieldMappedAttributes
......@@ -330,7 +330,7 @@ class QueryGenerator {
/**
* Returns an update query
*
* @param {String} tableName
* @param {string} tableName
* @param {Object} attrValueHash
* @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.
......@@ -452,8 +452,8 @@ class QueryGenerator {
/**
* Returns an update query using arithmetic operator
*
* @param {String} operator String with the arithmetic operator (e.g. '+' or '-')
* @param {String} tableName Name of the table
* @param {string} operator String with the arithmetic operator (e.g. '+' or '-')
* @param {string} tableName Name of the table
* @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
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 {
/**
* Split a list of identifiers by "." and quote each part
*
* @param {String} dialect Dialect name
* @param {String} identifiers
* @param {string} dialect Dialect name
* @param {string} identifiers
* @param {Object} [options]
* @param {Boolean} [options.force=false]
* @param {Boolean} [options.quoteIdentifiers=true]
* @param {boolean} [options.force=false]
* @param {boolean} [options.quoteIdentifiers=true]
*
* @returns {String}
* @returns {string}
*/
quoteIdentifier(identifier, force) {
return QuoteHelper.quoteIdentifier(this.dialect, identifier, {
......@@ -929,7 +929,7 @@ class QueryGenerator {
* @param {String|Object} param table string or object
* @param {String|Boolean} alias alias name
*
* @returns {String}
* @returns {string}
*/
quoteTable(param, alias) {
let table = '';
......@@ -1065,9 +1065,9 @@ class QueryGenerator {
/**
* 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)
* @returns {String} The generated sql query
* @returns {string} The generated sql query
* @private
*/
jsonPathExtractionQuery(column, path) {
......@@ -1946,7 +1946,7 @@ class QueryGenerator {
*
* @param {Object} options An object with selectQuery options.
* @param {Object} options The model passed to the selectQuery.
* @return {String} The generated sql query.
* @returns {string} The generated sql query.
* @private
*/
addLimitAndOffset(options) {
......
......@@ -23,13 +23,13 @@ const postgresReservedWords = 'all,analyse,analyze,and,any,array,as,asc,asymmetr
/**
*
* @param {String} dialect Dialect name
* @param {String} identifier Identifier to quote
* @param {string} dialect Dialect name
* @param {string} identifier Identifier to quote
* @param {Object} [options]
* @param {Boolean} [options.force=false]
* @param {Boolean} [options.quoteIdentifiers=true]
* @param {boolean} [options.force=false]
* @param {boolean} [options.quoteIdentifiers=true]
*
* @returns {String}
* @returns {string}
* @private
*/
function quoteIdentifier(dialect, identifier, options) {
......@@ -79,9 +79,9 @@ module.exports.quoteIdentifier = quoteIdentifier;
/**
* Test if a give string is already quoted
*
* @param {String} identifier
* @param {string} identifier
*
* @return Boolean
* @returns Boolean
* @private
*/
function isIdentifierQuoted(identifier) {
......
......@@ -6,9 +6,9 @@ const TransactionQueries = {
/**
* 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.
* @return {String} The generated sql query.
* @returns {string} The generated sql query.
* @private
*/
setAutocommitQuery(value, options) {
......@@ -27,9 +27,9 @@ const TransactionQueries = {
/**
* 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.
* @return {String} The generated sql query.
* @returns {string} The generated sql query.
* @private
*/
setIsolationLevelQuery(value, options) {
......@@ -49,7 +49,7 @@ const TransactionQueries = {
*
* @param {Transaction} transaction
* @param {Object} options An object with options.
* @return {String} The generated sql query.
* @returns {string} The generated sql query.
* @private
*/
startTransactionQuery(transaction) {
......@@ -66,7 +66,7 @@ const TransactionQueries = {
*
* @param {Transaction} transaction
* @param {Object} options An object with options.
* @return {String} The generated sql query.
* @returns {string} The generated sql query.
* @private
*/
deferConstraintsQuery() {},
......@@ -79,7 +79,7 @@ const TransactionQueries = {
* Returns a query that commits a transaction.
*
* @param {Object} options An object with options.
* @return {String} The generated sql query.
* @returns {string} The generated sql query.
* @private
*/
commitTransactionQuery(transaction) {
......@@ -95,7 +95,7 @@ const TransactionQueries = {
*
* @param {Transaction} transaction
* @param {Object} options An object with options.
* @return {String} The generated sql query.
* @returns {string} The generated sql query.
* @private
*/
rollbackTransactionQuery(transaction) {
......
......@@ -95,7 +95,7 @@ class AbstractQuery {
*
* 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
*/
run() {
......@@ -105,7 +105,7 @@ class AbstractQuery {
/**
* Check the logging option of the instance and print deprecation warnings.
*
* @return {void}
* @returns {void}
* @private
*/
checkLoggingOption() {
......@@ -118,7 +118,7 @@ class AbstractQuery {
/**
* Get the attributes of an insert query, which contains the just inserted id.
*
* @return {String} The field name.
* @returns {string} The field name.
* @private
*/
getInsertIdField() {
......
......@@ -698,7 +698,7 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator {
/**
* Generate common SQL prefix for ForeignKeysQuery.
* @returns {String}
* @returns {string}
*/
_getForeignKeysQueryPrefix(catalogName) {
return 'SELECT ' +
......@@ -725,8 +725,8 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator {
/**
* Generates an SQL query that returns all foreign keys details of a table.
* @param {Stirng|Object} table
* @param {String} catalogName database name
* @returns {String}
* @param {string} catalogName database name
* @returns {string}
*/
getForeignKeysQuery(table, catalogName) {
const tableName = table.tableName || table;
......
......@@ -11,13 +11,12 @@
/**
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} 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 {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
@private
*/
const removeColumn = function(tableName, attributeName, options) {
......
......@@ -17,7 +17,7 @@ const parserStore = require('../parserStore')('mysql');
* Use https://github.com/sidorares/node-mysql2 to connect with MySQL server
*
* @extends AbstractConnectionManager
* @return Class<ConnectionManager>
* @returns Class<ConnectionManager>
* @private
*/
......@@ -63,7 +63,7 @@ class ConnectionManager extends AbstractConnectionManager {
* Set the pool handlers on connection.error
* Also set proper timezone once conection is connected
*
* @return Promise<Connection>
* @returns Promise<Connection>
* @private
*/
connect(config) {
......
......@@ -403,8 +403,8 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
/**
* Check whether the statmement is json function or simple path
*
* @param {String} stmt The statement to validate
* @returns {Boolean} true if the given statement is json function
* @param {string} stmt The statement to validate
* @returns {boolean} true if the given statement is json function
* @throws {Error} throw if the statement looks like json function but has invalid token
* @private
*/
......@@ -469,7 +469,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
/**
* Generates fields for getForeignKeysQuery
* @returns {String} fields
* @returns {string} fields
* @private
*/
_getForeignKeysQueryFields() {
......@@ -492,9 +492,9 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
/**
* Generates an SQL query that returns all foreign keys of a table.
*
* @param {String} tableName The name of the table.
* @param {String} schemaName The name of the schema.
* @return {String} The generated sql query.
* @param {string} tableName The name of the table.
* @param {string} schemaName The name of the schema.
* @returns {string} The generated sql query.
* @private
*/
getForeignKeysQuery(tableName, schemaName) {
......@@ -505,9 +505,9 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
/**
* Generates an SQL query that returns the foreign key constraint of a given column.
*
* @param {String} tableName The name of the table.
* @param {String} columnName The name of the column.
* @return {String} The generated sql query.
* @param {string} tableName The name of the table.
* @param {string} columnName The name of the column.
* @returns {string} The generated sql query.
* @private
*/
getForeignKeyQuery(table, columnName) {
......@@ -529,9 +529,9 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
/**
* Generates an SQL query that removes a foreign key from a table.
*
* @param {String} tableName The name of the table.
* @param {String} foreignKey The name of the foreign key constraint.
* @return {String} The generated sql query.
* @param {string} tableName The name of the table.
* @param {string} foreignKey The name of the foreign key constraint.
* @returns {string} The generated sql query.
* @private
*/
dropForeignKeyQuery(tableName, foreignKey) {
......
......@@ -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.
@method removeColumn
@for QueryInterface
@param {String} tableName The name of the table.
@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
@private
*/
function removeColumn(tableName, columnName, options) {
......
......@@ -129,8 +129,8 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
/**
* Check whether the statmement is json function or simple path
*
* @param {String} stmt The statement to validate
* @returns {Boolean} true if the given statement is json function
* @param {string} stmt The statement to validate
* @returns {boolean} true if the given statement is json function
* @throws {Error} throw if the statement looks like json function but has invalid token
*/
_checkValidJsonStatement(stmt) {
......@@ -841,8 +841,8 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
/**
* Generates an SQL query that returns all foreign keys of a table.
*
* @param {String} tableName The name of the table.
* @return {String} The generated sql query.
* @param {string} tableName The name of the table.
* @returns {string} The generated sql query.
* @private
*/
getForeignKeysQuery(tableName) {
......@@ -852,7 +852,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
/**
* Generate common SQL prefix for getForeignKeyReferencesQuery.
* @returns {String}
* @returns {string}
*/
_getForeignKeyReferencesQueryPrefix() {
return 'SELECT ' +
......@@ -878,9 +878,9 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
* 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.
* @param {String} tableName
* @param {String} catalogName
* @param {String} schemaName
* @param {string} tableName
* @param {string} catalogName
* @param {string} schemaName
*/
getForeignKeyReferencesQuery(tableName, catalogName, schemaName) {
return this._getForeignKeyReferencesQueryPrefix() +
......@@ -900,9 +900,9 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
/**
* Generates an SQL query that removes a foreign key from a table.
*
* @param {String} tableName The name of the table.
* @param {String} foreignKey The name of the foreign key constraint.
* @return {String} The generated sql query.
* @param {string} tableName The name of the table.
* @param {string} foreignKey The name of the foreign key constraint.
* @returns {string} The generated sql query.
* @private
*/
dropForeignKeyQuery(tableName, foreignKey) {
......
......@@ -17,12 +17,12 @@ const _ = require('lodash');
/**
* 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]
* @param {Model} [model]
*
* @return {Promise}
* @returns {Promise}
* @private
*/
function ensureEnums(tableName, attributes, options, model) {
......
......@@ -78,8 +78,8 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator {
/**
* Check whether the statmement is json function or simple path
*
* @param {String} stmt The statement to validate
* @returns {Boolean} true if the given statement is json function
* @param {string} stmt The statement to validate
* @returns {boolean} true if the given statement is json function
* @throws {Error} throw if the statement looks like json function but has invalid token
*/
_checkValidJsonStatement(stmt) {
......@@ -490,8 +490,8 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator {
/**
* Generates an SQL query that returns all foreign keys of a table.
*
* @param {String} tableName The name of the table.
* @return {String} The generated sql query.
* @param {string} tableName The name of the table.
* @returns {string} The generated sql query.
* @private
*/
getForeignKeysQuery(tableName) {
......
......@@ -18,11 +18,8 @@ const QueryTypes = require('../../query-types');
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.
@method removeColumn
@for QueryInterface
@param {String} tableName The name of the table.
@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 {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;
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.
@method changeColumn
@for QueryInterface
@param {String} tableName The name of the table.
@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} options
@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;
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.
@method renameColumn
@for QueryInterface
@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 {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 {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;
/**
*
* @param {String} tableName
* @param {string} tableName
* @param {Object} options Query Options
*
* @private
......
......@@ -6,6 +6,8 @@
*
* This means that errors can be accessed using `Sequelize.ValidationError` or `sequelize.ValidationError`
* The Base Error all Sequelize Errors inherit from.
*
* @extends Error
*/
class BaseError extends Error {
constructor(message) {
......@@ -18,6 +20,8 @@ exports.BaseError = BaseError;
/**
* Scope Error. Thrown when the sequelize cannot query the specified scope.
*
* @extends BaseError
*/
class SequelizeScopeError extends BaseError {
constructor(parent) {
......@@ -36,6 +40,8 @@ exports.SequelizeScopeError = SequelizeScopeError;
* @param {Array} [errors] Array of ValidationErrorItem objects describing the validation errors
*
* @property errors {ValidationErrorItems[]}
*
* @extends BaseError
*/
class ValidationError extends BaseError {
constructor(message, errors) {
......@@ -63,7 +69,8 @@ class ValidationError extends BaseError {
* Gets all validation error items for the path / field specified.
*
* @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) {
return this.errors.reduce((reduced, error) => {
......@@ -78,6 +85,8 @@ exports.ValidationError = ValidationError;
/**
* Thrown when attempting to update a stale model instance
*
* @extends BaseError
*/
class OptimisticLockError extends BaseError {
constructor(options) {
......@@ -107,6 +116,8 @@ exports.OptimisticLockError = OptimisticLockError;
/**
* A base class for all database related errors.
*
* @extends BaseError
*/
class DatabaseError extends BaseError {
constructor(parent) {
......@@ -132,6 +143,8 @@ exports.DatabaseError = DatabaseError;
/**
* Thrown when a database query times out because of a deadlock
*
* @extends DatabaseError
*/
class TimeoutError extends DatabaseError {
constructor(parent) {
......@@ -144,6 +157,8 @@ exports.TimeoutError = TimeoutError;
/**
* Thrown when a unique constraint is violated in the database
*
* @extends ValidationError
*/
class UniqueConstraintError extends ValidationError {
constructor(options) {
......@@ -166,6 +181,8 @@ exports.UniqueConstraintError = UniqueConstraintError;
/**
* Thrown when a foreign key constraint is violated in the database
*
* @extends DatabaseError
*/
class ForeignKeyConstraintError extends DatabaseError {
constructor(options) {
......@@ -188,6 +205,8 @@ exports.ForeignKeyConstraintError = ForeignKeyConstraintError;
/**
* Thrown when an exclusion constraint is violated in the database
*
* @extends DatabaseError
*/
class ExclusionConstraintError extends DatabaseError {
constructor(options) {
......@@ -208,6 +227,8 @@ exports.ExclusionConstraintError = ExclusionConstraintError;
/**
* Thrown when constraint name is not found in the database
*
* @extends DatabaseError
*/
class UnknownConstraintError extends DatabaseError {
constructor(options) {
......@@ -229,43 +250,46 @@ exports.UnknownConstraintError = UnknownConstraintError;
/**
* Validation Error Item
* 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} type The type/origin of the validation error
* @param {String} path The field that triggered the validation error
* @param {String} value The value that generated the error
* @param {string} message An error message
* @param {string} type The type/origin of the validation error
* @param {string} path The field that triggered the validation error
* @param {string} value The value that generated the error
* @param {Object} [inst] the DAO instance that caused the validation error
* @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} [fnArgs] parameters used with the BUILT-IN validator function, 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
*/
class ValidationErrorItem {
constructor(message, type, path, value, inst, validatorKey, fnName, fnArgs) {
/**
* An error message
*
* @type {String} message
* @type {string} message
*/
this.message = message || '';
/**
* The type/origin of the validation error
*
* @type {String}
* @type {string}
*/
this.type = null;
/**
* The field that triggered the validation error
*
* @type {String}
* @type {string}
*/
this.path = path || null;
/**
* The value that generated the error
*
* @type {String}
* @type {string}
*/
this.value = value !== undefined ? value : null;
......@@ -281,21 +305,21 @@ class ValidationErrorItem {
/**
* A validation "key", used for identification
*
* @type {String}
* @type {string}
*/
this.validatorKey = validatorKey || null;
/**
* 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;
/**
* Parameters used with the BUILT-IN validator function, if applicable
*
* @type {String}
* @type {string}
*/
this.validatorArgs = fnArgs || [];
......@@ -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
*
* @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
* @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.
* @throws {Error} thrown if NSSeparator is found to be invalid.
* @return {String}
* @returns {string}
*
* @private
*/
......@@ -356,9 +380,9 @@ exports.ValidationErrorItem = ValidationErrorItem;
* An enum that defines valid ValidationErrorItem `origin` values
*
* @type {Object}
* @property CORE {String} specifies errors that originate from the sequelize "core"
* @property DB {String} specifies validation errors that originate from the storage engine
* @property FUNCTION {String} specifies validation errors that originate from validator functions (both built-in and custom) defined for a given attribute
* @property CORE {string} specifies errors that originate from the sequelize "core"
* @property DB {string} specifies validation errors that originate from the storage engine
* @property FUNCTION {string} specifies validation errors that originate from validator functions (both built-in and custom) defined for a given attribute
*/
ValidationErrorItem.Origins = {
CORE: 'CORE',
......@@ -382,6 +406,8 @@ ValidationErrorItem.TypeStringMap = {
/**
* A base class for all connection related errors.
*
* @extends BaseError
*/
class ConnectionError extends BaseError {
constructor(parent) {
......@@ -400,6 +426,8 @@ exports.ConnectionError = ConnectionError;
/**
* Thrown when a connection to a database is refused
*
* @extends ConnectionError
*/
class ConnectionRefusedError extends ConnectionError {
constructor(parent) {
......@@ -412,6 +440,8 @@ exports.ConnectionRefusedError = ConnectionRefusedError;
/**
* Thrown when a connection to a database is refused due to insufficient privileges
*
* @extends ConnectionError
*/
class AccessDeniedError extends ConnectionError {
constructor(parent) {
......@@ -424,6 +454,8 @@ exports.AccessDeniedError = AccessDeniedError;
/**
* Thrown when a connection to a database has a hostname that was not found
*
* @extends ConnectionError
*/
class HostNotFoundError extends ConnectionError {
constructor(parent) {
......@@ -436,6 +468,8 @@ exports.HostNotFoundError = HostNotFoundError;
/**
* Thrown when a connection to a database has a hostname that was not reachable
*
* @extends ConnectionError
*/
class HostNotReachableError extends ConnectionError {
constructor(parent) {
......@@ -448,6 +482,8 @@ exports.HostNotReachableError = HostNotReachableError;
/**
* Thrown when a connection to a database has invalid values for any of the connection parameters
*
* @extends ConnectionError
*/
class InvalidConnectionError extends ConnectionError {
constructor(parent) {
......@@ -460,6 +496,8 @@ exports.InvalidConnectionError = InvalidConnectionError;
/**
* Thrown when a connection to a database times out
*
* @extends ConnectionError
*/
class ConnectionTimedOutError extends ConnectionError {
constructor(parent) {
......@@ -472,6 +510,8 @@ exports.ConnectionTimedOutError = ConnectionTimedOutError;
/**
* Thrown when a some problem occurred with Instance methods (see message for details)
*
* @extends BaseError
*/
class InstanceError extends BaseError {
constructor(message) {
......@@ -484,6 +524,8 @@ exports.InstanceError = InstanceError;
/**
* Thrown when a record was not found, Usually used with rejectOnEmpty mode (see message for details)
*
* @extends BaseError
*/
class EmptyResultError extends BaseError {
constructor(message) {
......@@ -496,6 +538,8 @@ exports.EmptyResultError = EmptyResultError;
/**
* Thrown when an include statement is improperly constructed (see message for details)
*
* @extends BaseError
*/
class EagerLoadingError extends BaseError {
constructor(message) {
......@@ -508,6 +552,8 @@ exports.EagerLoadingError = EagerLoadingError;
/**
* Thrown when an association is improperly constructed (see message for details)
*
* @extends BaseError
*/
class AssociationError extends BaseError {
constructor(message) {
......@@ -519,6 +565,8 @@ class AssociationError extends BaseError {
exports.AssociationError = AssociationError;
/**
* Thrown when a query is passed invalid options (see message for details)
*
* @extends BaseError
*/
class QueryError extends BaseError {
constructor(message) {
......@@ -535,6 +583,8 @@ exports.QueryError = QueryError;
*
* @param {Error} error Error for a given record/instance
* @param {Object} record DAO instance that error belongs to
*
* @extends BaseError
*/
class BulkRecordError extends BaseError {
constructor(error, record) {
......
......@@ -60,7 +60,10 @@ const 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
*/
const getProxiedHooks = hookType =>
......@@ -77,11 +80,11 @@ const Hooks = {
/**
* Process user supplied hooks definition
*
* @param {Object} hooks
* @param {Object} hooks hooks definition
*
* @private
* @memberOf Sequelize
* @memberOf Sequelize.Model
* @memberof Sequelize
* @memberof Sequelize.Model
*/
_setupHooks(hooks) {
this.options.hooks = {};
......@@ -141,12 +144,12 @@ const Hooks = {
/**
* Add a hook to the model
*
* @param {String} hookType
* @param {String} [name] Provide a name for the hook function. It can be used to remove the hook later or to order hooks based on some sort of priority system in the future.
* @param {string} hookType hook name @see {@link hookTypes}
* @param {string|Function} [name] Provide a name for the hook function. It can be used to remove the hook later or to order hooks based on some sort of priority system in the future.
* @param {Function} fn The hook function
*
* @memberOf Sequelize
* @memberOf Sequelize.Model
* @memberof Sequelize
* @memberof Sequelize.Model
*/
addHook(hookType, name, fn) {
if (typeof name === 'function') {
......@@ -171,11 +174,11 @@ const Hooks = {
/**
* Remove hook from the model
*
* @param {String} hookType
* @param {String|Function} name
* @param {string} hookType @see {@link hookTypes}
* @param {string|Function} name name of hook or function reference which was attached
*
* @memberOf Sequelize
* @memberOf Sequelize.Model
* @memberof Sequelize
* @memberof Sequelize.Model
*/
removeHook(hookType, name) {
hookType = hookAliases[hookType] || hookType;
......@@ -207,11 +210,12 @@ const Hooks = {
/**
* Check whether the mode has any hooks of this type
*
* @param {String} hookType
* @param {string} hookType @see {@link hookTypes}
*
* @alias hasHooks
* @memberOf Sequelize
* @memberOf Sequelize.Model
*
* @memberof Sequelize
* @memberof Sequelize.Model
*/
hasHook(hookType) {
return this.options.hooks[hookType] && !!this.options.hooks[hookType].length;
......@@ -234,317 +238,317 @@ exports.applyTo = applyTo;
/**
* 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
* @name beforeValidate
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
* @name afterValidate
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
* SequelizeValidationError. If the callback throws an error, it will replace the original validation error.
* @name validationFailed
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
* @name beforeCreate
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
* @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`
* @param {String} name
* @param {string} name
* @param {Function} fn A callback function that is called with attributes, options
* @name beforeSave
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
* @name beforeUpsert
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
* @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`
* @param {String} name
* @param {string} name
* @param {Function} fn A callback function that is called with attributes, options
* @name afterSave
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
*
* @name beforeDestroy
* @alias beforeDelete
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
*
* @name afterDestroy
* @alias afterDelete
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
*
* @name beforeRestore
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
*
* @name afterRestore
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
* @name beforeUpdate
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
* @name afterUpdate
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
* @name beforeBulkCreate
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
* @name afterBulkCreate
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
*
* @name beforeBulkDestroy
* @alias beforeBulkDelete
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
*
* @name afterBulkDestroy
* @alias afterBulkDelete
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
*
* @name beforeBulkRestore
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
*
* @name afterBulkRestore
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
* @name beforeBulkUpdate
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
* @name afterBulkUpdate
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
* @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
* @param {String} name
* @param {string} name
* @param {Function} fn A callback function that is called with options
* @name beforeFindAfterExpandIncludeAll
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
* @name beforeFindAfterOptions
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
* @name afterFind
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
* @name beforeCount
* @memberOf Sequelize.Model
* @memberof Sequelize.Model
*/
/**
* 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
* @name beforeDefine
* @memberOf Sequelize
* @memberof Sequelize
*/
/**
* 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
* @name afterDefine
* @memberOf Sequelize
* @memberof Sequelize
*/
/**
* 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
* @name beforeInit
* @memberOf Sequelize
* @memberof Sequelize
*/
/**
* 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
* @name afterInit
* @memberOf Sequelize
* @memberof Sequelize
*/
/**
* 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
* @name beforeConnect
* @memberOf Sequelize
* @memberof Sequelize
*/
/**
* 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
* @name afterConnect
* @memberOf Sequelize
* @memberof Sequelize
*/
/**
* 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
* @name beforeSync
* @memberOf Sequelize
* @memberof Sequelize
*/
/**
* 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
* @name afterSync
* @memberOf Sequelize
* @memberof Sequelize
*/
/**
* 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
* @name beforeBulkSync
* @memberOf Sequelize
* @memberof Sequelize
*/
/**
* 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
* @name afterBulkSync
* @memberOf Sequelize
* @memberof Sequelize
*/
'use strict';
const validator = require('./utils/validator-extras').validator;
const extendModelValidations = require('./utils/validator-extras').extendModelValidations;
const _ = require('lodash');
const Utils = require('./utils');
const sequelizeError = require('./errors');
const Promise = require('./promise');
const DataTypes = require('./data-types');
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 {Object} options A dictionary with options.
* @constructor
*
* @private
*/
class InstanceValidator {
......@@ -61,7 +61,7 @@ class InstanceValidator {
/**
* The main entry point for the Validation module, invoke to start the dance.
*
* @return {Promise}
* @returns {Promise}
* @private
*/
_validate() {
......@@ -86,7 +86,7 @@ class InstanceValidator {
* - On validation success: After Validation Model Hooks
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
* @returns {Promise}
* @private
*/
validate() {
......@@ -100,7 +100,7 @@ class InstanceValidator {
* - On validation success: After Validation Model Hooks
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
* @returns {Promise}
* @private
*/
_validateAndRunHooks() {
......@@ -118,7 +118,7 @@ class InstanceValidator {
/**
* 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
*/
_builtinValidators() {
......@@ -152,7 +152,7 @@ class InstanceValidator {
/**
* 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
*/
_customValidators() {
......@@ -176,11 +176,12 @@ class InstanceValidator {
/**
* Validate a single attribute with all the defined built-in validators.
*
* @private
*
* @param {*} value Anything.
* @param {string} field The field name.
* @return {Promise} A promise, will always resolve,
* auto populates error on this.error local object.
* @private
*
* @returns {Promise} A promise, will always resolve, auto populates error on this.error local object.
*/
_builtinAttrValidate(value, field) {
// check if value is null (if null not allowed the Schema pass will capture it)
......@@ -222,12 +223,15 @@ class InstanceValidator {
/**
* Prepare and invoke a custom validator.
*
* @private
*
* @param {Function} validator The custom validator.
* @param {string} validatorType the custom validator type (name).
* @param {boolean=} optAttrDefined Set to true if custom validator was defined
* from the Attribute
* @return {Promise} A promise.
* @private
* @param {boolean} optAttrDefined Set to true if custom validator was defined from the attribute
* @param {*} optValue value for attribute
* @param {string} optField field for attribute
*
* @returns {Promise} A promise.
*/
_invokeCustomValidator(validator, validatorType, optAttrDefined, optValue, optField) {
let validatorFunction = null; // the validation function to call
......@@ -265,12 +269,14 @@ class InstanceValidator {
/**
* Prepare and invoke a build-in validator.
*
* @private
*
* @param {*} value Anything.
* @param {*} test The test case.
* @param {string} validatorType One of known to Sequelize validators.
* @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) {
return Promise.try(() => {
......@@ -295,6 +301,7 @@ class InstanceValidator {
* @param {*} test The test case.
* @param {string} validatorType One of known to Sequelize validators.
* @param {string} field The field that is being validated.
*
* @private
*/
_extractValidatorArgs(test, validatorType, field) {
......@@ -321,6 +328,7 @@ class InstanceValidator {
* @param {Object} rawAttribute As defined in the Schema.
* @param {string} field The field name.
* @param {*} value anything.
*
* @private
*/
_validateSchema(rawAttribute, field, value) {
......@@ -363,7 +371,8 @@ class InstanceValidator {
*
* @param {string} field The attribute name.
* @param {string|number} value The data value.
* @param {Array.<Promise.PromiseInspection>} Promise inspection objects.
* @param {Array<Promise.PromiseInspection>} promiseInspections objects.
*
* @private
*/
_handleReflectedResult(field, value, promiseInspections) {
......@@ -380,11 +389,11 @@ class InstanceValidator {
/**
* Signs all errors retaining the original.
*
* @param {Boolean} isBuiltin - Determines if error is from builtin validator.
* @param {String} errorKey - name of invalid attribute.
* @param {Error|String} rawError - The original error.
* @param {String|Number} value - The data that triggered the error.
* @param {String} fnName - Name of the validator, if any
* @param {boolean} isBuiltin - Determines if error is from builtin validator.
* @param {string} errorKey - name of invalid attribute.
* @param {Error|string} rawError - The original error.
* @param {string|number} value - The data that triggered the error.
* @param {string} fnName - Name of the validator, if any
* @param {Array} fnArgs - Arguments for the validator [function], if any
*
* @private
......
......@@ -37,9 +37,11 @@ class ModelManager {
}
/**
* Iterate over Models in an order suitable for e.g. creating tables. Will
* take foreign key constraints into account so that dependencies are visited
* before dependents.
* Iterate over Models in an order suitable for e.g. creating tables.
* Will take foreign key constraints into account so that dependencies are visited before dependents.
*
* @param {Function} iterator method to execute on each model
* @param {Object} [options] iterator options
* @private
*/
forEachModel(iterator, options) {
......
This diff could not be displayed because it is too large.
'use strict';
const Utils = require('./utils');
const _ = require('lodash');
const Utils = require('./utils');
const DataTypes = require('./data-types');
const SQLiteQueryInterface = require('./dialects/sqlite/query-interface');
const MSSSQLQueryInterface = require('./dialects/mssql/query-interface');
......@@ -26,10 +27,10 @@ class QueryInterface {
/**
* Creates a schema
*
* @param {String} schema Schema name to create
* @param {string} schema Schema name to create
* @param {Object} [options] Query options
*
* @return {Promise}
* @returns {Promise}
*/
createSchema(schema, options) {
options = options || {};
......@@ -40,10 +41,10 @@ class QueryInterface {
/**
* Drops a schema
*
* @param {String} schema Schema name to drop
* @param {string} schema Schema name to drop
* @param {Object} [options] Query options
*
* @return {Promise}
* @returns {Promise}
*/
dropSchema(schema, options) {
options = options || {};
......@@ -56,7 +57,7 @@ class QueryInterface {
*
* @param {Object} [options] Query options
*
* @return {Promise}
* @returns {Promise}
*/
dropAllSchemas(options) {
options = options || {};
......@@ -73,7 +74,7 @@ class QueryInterface {
*
* @param {Object} [options] Query options
*
* @return {Promise<Array>}
* @returns {Promise<Array>}
*/
showAllSchemas(options) {
options = _.assign({}, options, {
......@@ -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} [options]
* @param {Model} [model]
* @param {Object} [options] create table and query options
* @param {Model} [model] model class
*
* @return {Promise}
* @returns {Promise}
*/
createTable(tableName, attributes, options, model) {
let sql = '';
......@@ -198,10 +199,10 @@ class QueryInterface {
/**
* Drops a table from database
*
* @param {String} tableName Table name to drop
* @param {string} tableName Table name to drop
* @param {Object} options Query options
*
* @return {Promise}
* @returns {Promise}
*/
dropTable(tableName, options) {
// if we're forcing we should be cascading unless explicitly stated otherwise
......@@ -241,10 +242,10 @@ class QueryInterface {
/**
* Drop all tables from database
*
* @param {Object} [options]
* @param {Object} [options] query options
* @param {Array} [options.skip] List of table to skip
*
* @return {Promise}
* @returns {Promise}
*/
dropAllTables(options) {
options = options || {};
......@@ -294,10 +295,11 @@ class QueryInterface {
/**
* 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
*
* @return {Promise}
* @returns {Promise}
* @private
*/
dropEnum(enumName, options) {
......@@ -318,7 +320,7 @@ class QueryInterface {
*
* @param {Object} options Query options
*
* @return {Promise}
* @returns {Promise}
* @private
*/
dropAllEnums(options) {
......@@ -337,10 +339,10 @@ class QueryInterface {
/**
* 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
*
* @return {Promise}
* @returns {Promise}
* @private
*/
pgListEnums(tableName, options) {
......@@ -352,11 +354,11 @@ class QueryInterface {
/**
* Renames a table
*
* @param {String} before Current name of table
* @param {String} after New name from table
* @param {string} before Current name of table
* @param {string} after New name from table
* @param {Object} [options] Query options
*
* @return {Promise}
* @returns {Promise}
*/
renameTable(before, after, options) {
options = options || {};
......@@ -368,10 +370,10 @@ class QueryInterface {
* Get all tables in current database
*
* @param {Object} [options] Query options
* @param {Boolean} [options.raw=true] Run query in raw mode
* @param {QueryType} [options.type=QueryType.SHOWTABLE]
* @param {boolean} [options.raw=true] Run query in raw mode
* @param {QueryType} [options.type=QueryType.SHOWTABLE] query type
*
* @return {Promise<Array>}
* @returns {Promise<Array>}
* @private
*/
showAllTables(options) {
......@@ -403,10 +405,11 @@ class QueryInterface {
* }
* }
* ```
* @param {String} tableName
*
* @param {string} tableName table name
* @param {Object} [options] Query options
*
* @return {Promise<Object>}
* @returns {Promise<Object>}
*/
describeTable(tableName, options) {
let schema = null;
......@@ -449,12 +452,13 @@ class QueryInterface {
* 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} [options] Query options
*
* @return {Promise}
* @returns {Promise}
*/
addColumn(table, key, attribute, options) {
if (!table || !key || !attribute) {
......@@ -469,11 +473,11 @@ class QueryInterface {
/**
* Remove a column from table
*
* @param {String} tableName Table to remove column from
* @param {String} attributeName Columns name to remove
* @param {string} tableName Table to remove column from
* @param {string} attributeName Columns name to remove
* @param {Object} [options] Query options
*
* @return {Promise}
* @returns {Promise}
*/
removeColumn(tableName, attributeName, options) {
options = options || {};
......@@ -495,12 +499,12 @@ class QueryInterface {
/**
* Change a column definition
*
* @param {String} tableName Table name to change from
* @param {String} attributeName Column name
* @param {string} tableName Table name to change from
* @param {string} attributeName Column name
* @param {Object} dataTypeOrOptions Attribute definition for new column
* @param {Object} [options] Query options
*
* @return {Promise}
* @returns {Promise}
*/
changeColumn(tableName, attributeName, dataTypeOrOptions, options) {
const attributes = {};
......@@ -528,12 +532,12 @@ class QueryInterface {
/**
* Rename a column
*
* @param {String} tableName Table name whose column to rename
* @param {String} attrNameBefore Current column name
* @param {String} attrNameAfter New column name
* @param {string} tableName Table name whose column to rename
* @param {string} attrNameBefore Current column name
* @param {string} attrNameAfter New column name
* @param {Object} [options] Query option
*
* @return {Promise}
* @returns {Promise}
*/
renameColumn(tableName, attrNameBefore, attrNameAfter, options) {
options = options || {};
......@@ -575,16 +579,18 @@ class QueryInterface {
/**
* Add index to a column
*
* @param {String} tableName Table name to add index on
* @param {Object} options
* @param {string|Object} tableName Table name to add index on, can be a object with schema
* @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 {Boolean} [options.unique] Create a unique index
* @param {String} [options.using] Useful for GIN indexes
* @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 {boolean} [options.unique] Create a unique index
* @param {string} [options.using] Useful for GIN indexes
* @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 {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) {
// Support for passing tableName, attributes, options or tableName, options (with a fields param which is the attributes)
......@@ -609,10 +615,10 @@ class QueryInterface {
/**
* Show indexes on a table
*
* @param {String} tableName
* @param {string} tableName table name
* @param {Object} [options] Query options
*
* @return {Promise<Array>}
* @returns {Promise<Array>}
* @private
*/
showIndex(tableName, options) {
......@@ -656,8 +662,9 @@ class QueryInterface {
* referencedTableCatalog, referencedTableCatalog, referencedTableSchema, referencedTableName, referencedColumnName.
* Remind: constraint informations won't return if it's sqlite.
*
* @param {String} tableName
* @param {string} tableName table name
* @param {Object} [options] Query options
*
* @returns {Promise}
*/
getForeignKeyReferencesForTable(tableName, options) {
......@@ -690,11 +697,11 @@ class QueryInterface {
/**
* Remove an already existing index from a table
*
* @param {String} tableName Table name to drop index from
* @param {String} indexNameOrAttributes Index name
* @param {string} tableName Table name to drop index from
* @param {string} indexNameOrAttributes Index name
* @param {Object} [options] Query options
*
* @return {Promise}
* @returns {Promise}
*/
removeIndex(tableName, indexNameOrAttributes, options) {
options = options || {};
......@@ -712,41 +719,33 @@ class QueryInterface {
* - FOREIGN KEY
* - PRIMARY KEY
*
* UNIQUE
* ```js
* @example <caption>UNIQUE</caption>
* queryInterface.addConstraint('Users', ['email'], {
* type: 'unique',
* name: 'custom_unique_constraint_name'
* });
* ```
*
* CHECK
* ```js
* @example <caption>CHECK</caption>
* queryInterface.addConstraint('Users', ['roles'], {
* type: 'check',
* where: {
* roles: ['user', 'admin', 'moderator', 'guest']
* }
* });
* ```
* Default - MSSQL only
* ```js
*
* @example <caption>Default - MSSQL only</caption>
* queryInterface.addConstraint('Users', ['roles'], {
* type: 'default',
* defaultValue: 'guest'
* });
* ```
*
* Primary Key
* ```js
* @example <caption>Primary Key</caption>
* queryInterface.addConstraint('Users', ['username'], {
* type: 'primary key',
* name: 'custom_primary_constraint_name'
* });
* ```
*
* Foreign Key
* ```js
* @example <caption>Foreign Key</caption>
* queryInterface.addConstraint('Posts', ['username'], {
* type: 'foreign key',
* name: 'custom_fkey_constraint_name',
......@@ -757,20 +756,20 @@ class QueryInterface {
* onDelete: '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 {Object} options An object to define the constraint name, type etc
* @param {String} options.type Type of constraint. One of the values in available constraints(case insensitive)
* @param {String} [options.name] Name of the constraint. If not specified, sequelize automatically creates a named constraint based on constraint type, table & column names
* @param {String} [options.defaultValue] The value for the default constraint
* @param {string} options.type Type of constraint. One of the values in available constraints(case insensitive)
* @param {string} [options.name] Name of the constraint. If not specified, sequelize automatically creates a named constraint based on constraint type, table & column names
* @param {string} [options.defaultValue] The value for the default constraint
* @param {Object} [options.where] Where clause/expression for the CHECK constraint
* @param {Object} [options.references] Object specifying target table, column name to create foreign key constraint
* @param {String} [options.references.table] Target table name
* @param {String} [options.references.field] Target column name
* @param {string} [options.references.table] Target table name
* @param {string} [options.references.field] Target column name
* @param {string} [rawTablename] Table name, for backward compatibility
*
* @return {Promise}
* @returns {Promise}
*/
addConstraint(tableName, attributes, options, rawTablename) {
if (!Array.isArray(attributes)) {
......@@ -806,11 +805,11 @@ class QueryInterface {
/**
*
* @param {String} tableName Table name to drop constraint from
* @param {String} constraintName Constraint name
* @param {string} tableName Table name to drop constraint from
* @param {string} constraintName Constraint name
* @param {Object} options Query options
*
* @return {Promise}
* @returns {Promise}
*/
removeConstraint(tableName, constraintName, options) {
options = options || {};
......@@ -844,14 +843,14 @@ class QueryInterface {
/**
* Upsert
*
* @param {String} tableName
* @param {string} tableName table to upsert on
* @param {Object} insertValues values to be inserted, mapped to field name
* @param {Object} updateValues values to be updated, mapped to field name
* @param {Object} where various conditions
* @param {Model} model
* @param {Object} options
* @param {Model} model Model to upsert on
* @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) {
const wheres = [];
......@@ -924,7 +923,7 @@ class QueryInterface {
/**
* Insert records into a table
*
* ```js
* @example
* queryInterface.bulkInsert('roles', [{
* label: 'user',
* createdAt: new Date(),
......@@ -934,14 +933,13 @@ class QueryInterface {
* createdAt: 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 {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) {
options = _.clone(options) || {};
......@@ -1019,12 +1017,13 @@ class QueryInterface {
/**
* 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} [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) {
options = Utils.cloneDeep(options);
......@@ -1161,7 +1160,7 @@ class QueryInterface {
/**
* Create SQL function
*
* ```js
* @example
* queryInterface.createFunction(
* 'someFunction',
* [
......@@ -1175,17 +1174,16 @@ class QueryInterface {
* '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 {String} returnType SQL type of function returned value
* @param {String} language The name of the language that the function is implemented in
* @param {String} body Source code of function
* @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} body Source code of function
* @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) {
const sql = this.QueryGenerator.createFunction(functionName, params, returnType, language, body, optionsArray);
......@@ -1201,7 +1199,7 @@ class QueryInterface {
/**
* Drop SQL function
*
* ```js
* @example
* queryInterface.dropFunction(
* 'someFunction',
* [
......@@ -1209,13 +1207,12 @@ class QueryInterface {
* {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 {Object} [options]
* @param {Object} [options] query options
*
* @return {Promise}
* @returns {Promise}
*/
dropFunction(functionName, params, options) {
const sql = this.QueryGenerator.dropFunction(functionName, params);
......@@ -1231,7 +1228,7 @@ class QueryInterface {
/**
* Rename SQL function
*
* ```js
* @example
* queryInterface.renameFunction(
* 'fooFunction',
* [
......@@ -1240,14 +1237,13 @@ class QueryInterface {
* ],
* 'barFunction'
* );
* ```
*
* @param {String} oldFunctionName
* @param {string} oldFunctionName Current name of function
* @param {Array} params List of parameters declared for SQL function
* @param {String} newFunctionName
* @param {Object} [options]
* @param {string} newFunctionName New name of function
* @param {Object} [options] query options
*
* @return {Promise}
* @returns {Promise}
*/
renameFunction(oldFunctionName, params, newFunctionName, options) {
const sql = this.QueryGenerator.renameFunction(oldFunctionName, params, newFunctionName);
......@@ -1263,9 +1259,11 @@ class QueryInterface {
// Helper methods useful for querying
/**
* Escape an identifier (e.g. a table or attribute name). If force is true,
* the identifier will be quoted even if the `quoteIdentifiers` option is
* false.
* Escape an identifier (e.g. a table or attribute name)
*
* @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
*/
quoteIdentifier(identifier, force) {
......@@ -1277,9 +1275,11 @@ class QueryInterface {
}
/**
* Split an identifier into .-separated tokens and quote each part.
* If force is true, the identifier will be quoted even if the
* `quoteIdentifiers` option is false.
* Quote array of identifiers at once
*
* @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
*/
quoteIdentifiers(identifiers, force) {
......@@ -1288,6 +1288,9 @@ class QueryInterface {
/**
* Escape a value (e.g. a string, number or date)
*
* @param {string} value string to escape
*
* @private
*/
escape(value) {
......
......@@ -24,81 +24,71 @@ const Validator = require('./utils/validator-extras').validator;
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
* 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
*
* #### Example usage
*
* ```javascript
* // without password and options
* const sequelize = new Sequelize('database', 'username')
*
* // without options
* const sequelize = new Sequelize('database', 'username', 'password')
* Instantiate sequelize with name of database, username and password.
*
* @example
* // without password / with blank password
* const sequelize = new Sequelize('database', 'username', null, {})
* const sequelize = new Sequelize('database', 'username', null, {
* dialect: 'mysql'
* })
*
* // with password and options
* const sequelize = new Sequelize('my_database', 'john', 'doe', {})
* const sequelize = new Sequelize('my_database', 'john', 'doe', {
* dialect: 'postgres'
* })
*
* // with database, username, and password in the options object
* const sequelize = new Sequelize({ database, username, password });
* const sequelize = new Sequelize({ database, username, password, dialect: 'mssql' });
*
* // with uri
* const sequelize = new Sequelize('mysql://localhost:3306/database', {})
* ```
*
* @param {String} [database] The name of the database
* @param {String} [username=null] The username which is used to authenticate against the database.
* @param {String} [password=null] The password which is used to authenticate against the database. Supports SQLCipher encryption for SQLite.
* @param {string} [database] The name of the database
* @param {string} [username=null] The username which is used to authenticate against the database.
* @param {string} [password=null] The password which is used to authenticate against the database. Supports SQLCipher encryption for SQLite.
* @param {Object} [options={}] An object with options.
* @param {String} [options.host='localhost'] The host of the relational database.
* @param {Integer} [options.port=] The port of the relational database.
* @param {String} [options.username=null] The username which is used to authenticate against the database.
* @param {String} [options.password=null] The password which is used to authenticate against the database.
* @param {String} [options.database=null] The name of the database
* @param {String} [options.dialect] The dialect of the database you are connecting to. One of mysql, postgres, sqlite and mssql.
* @param {String} [options.dialectModulePath=null] If specified, load the dialect library from this path. For example, if you want to use pg.js instead of pg when connecting to a pg database, you should specify 'pg.js' here
* @param {string} [options.host='localhost'] The host of the relational database.
* @param {number} [options.port=] The port of the relational database.
* @param {string} [options.username=null] The username which is used to authenticate against the database.
* @param {string} [options.password=null] The password which is used to authenticate against the database.
* @param {string} [options.database=null] The name of the database
* @param {string} [options.dialect] The dialect of the database you are connecting to. One of mysql, postgres, sqlite and mssql.
* @param {string} [options.dialectModulePath=null] If specified, load the dialect library from this path. For example, if you want to use pg.js instead of pg when connecting to a pg database, you should specify 'pg.js' here
* @param {Object} [options.dialectOptions] An object of additional options, which are passed directly to the connection library
* @param {String} [options.storage] Only used by sqlite. Defaults to ':memory:'
* @param {String} [options.protocol='tcp'] The protocol of the relational database.
* @param {string} [options.storage] Only used by sqlite. Defaults to ':memory:'
* @param {string} [options.protocol='tcp'] The protocol of the relational database.
* @param {Object} [options.define={}] Default options for model definitions. See sequelize.define for options
* @param {Object} [options.query={}] Default options for sequelize.query
* @param {Object} [options.set={}] Default options for sequelize.set
* @param {Object} [options.sync={}] Default options for sequelize.sync
* @param {String} [options.timezone='+00:00'] The timezone used when converting a date from the database into a JavaScript date. The timezone is also used to SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP and other time related functions have in the right timezone. For best cross platform performance use the format +/-HH:MM. Will also accept string versions of timezones used by moment.js (e.g. 'America/Los_Angeles'); this is useful to capture daylight savings time changes.
* @param {string} [options.timezone='+00:00'] The timezone used when converting a date from the database into a JavaScript date. The timezone is also used to SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP and other time related functions have in the right timezone. For best cross platform performance use the format +/-HH:MM. Will also accept string versions of timezones used by moment.js (e.g. 'America/Los_Angeles'); this is useful to capture daylight savings time changes.
* @param {Function} [options.logging=console.log] A function that gets executed every time Sequelize would log something.
* @param {Boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
* @param {Boolean} [options.omitNull=false] A flag that defines if null values should be passed to SQL queries or not.
* @param {Boolean} [options.native=false] A flag that defines if native library shall be used or not. Currently only has an effect for postgres
* @param {Boolean} [options.replication=false] Use read / write replication. To enable replication, pass an object, with two properties, read and write. Write should be an object (a single server for handling writes), and read an array of object (several servers to handle reads). Each read/write server can have the following properties: `host`, `port`, `username`, `password`, `database`
* @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
* @param {boolean} [options.omitNull=false] A flag that defines if null values should be passed to SQL queries or not.
* @param {boolean} [options.native=false] A flag that defines if native library shall be used or not. Currently only has an effect for postgres
* @param {boolean} [options.replication=false] Use read / write replication. To enable replication, pass an object, with two properties, read and write. Write should be an object (a single server for handling writes), and read an array of object (several servers to handle reads). Each read/write server can have the following properties: `host`, `port`, `username`, `password`, `database`
* @param {Object} [options.pool] sequelize connection pool configuration
* @param {Integer} [options.pool.max=5] Maximum number of connection in pool
* @param {Integer} [options.pool.min=0] Minimum number of connection in pool
* @param {Integer} [options.pool.idle=10000] The maximum time, in milliseconds, that a connection can be idle before being released. Use with combination of evict for proper working, for more details read https://github.com/coopernurse/node-pool/issues/178#issuecomment-327110870
* @param {Integer} [options.pool.acquire=10000] The maximum time, in milliseconds, that pool will try to get connection before throwing error
* @param {Integer} [options.pool.evict=10000] The time interval, in milliseconds, for evicting stale connections. Set it to 0 to disable this feature.
* @param {Boolean} [options.pool.handleDisconnects=true] Controls if pool should handle connection disconnect automatically without throwing errors
* @param {number} [options.pool.max=5] Maximum number of connection in pool
* @param {number} [options.pool.min=0] Minimum number of connection in pool
* @param {number} [options.pool.idle=10000] The maximum time, in milliseconds, that a connection can be idle before being released. Use with combination of evict for proper working, for more details read https://github.com/coopernurse/node-pool/issues/178#issuecomment-327110870
* @param {number} [options.pool.acquire=10000] The maximum time, in milliseconds, that pool will try to get connection before throwing error
* @param {number} [options.pool.evict=10000] The time interval, in milliseconds, for evicting stale connections. Set it to 0 to disable this feature.
* @param {boolean} [options.pool.handleDisconnects=true] Controls if pool should handle connection disconnect automatically without throwing errors
* @param {Function} [options.pool.validate] A function that validates a connection. Called with client. The default function checks that client is an object, and that its state is not disconnected
* @param {Boolean} [options.quoteIdentifiers=true] Set to `false` to make table names and attributes case-insensitive on Postgres and skip double quoting of them. WARNING: Setting this to false may expose vulnerabilities and is not recommended!
* @param {String} [options.transactionType='DEFERRED'] Set the default transaction type. See `Sequelize.Transaction.TYPES` for possible options. Sqlite only.
* @param {String} [options.isolationLevel] Set the default transaction isolation level. See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options.
* @param {boolean} [options.quoteIdentifiers=true] Set to `false` to make table names and attributes case-insensitive on Postgres and skip double quoting of them. WARNING: Setting this to false may expose vulnerabilities and is not recommended!
* @param {string} [options.transactionType='DEFERRED'] Set the default transaction type. See `Sequelize.Transaction.TYPES` for possible options. Sqlite only.
* @param {string} [options.isolationLevel] Set the default transaction isolation level. See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options.
* @param {Object} [options.retry] Set of flags that control when a query is automatically retried.
* @param {Array} [options.retry.match] Only retry a query if the error matches one of these strings.
* @param {Integer} [options.retry.max] How many times a failing query is automatically retried. Set to 0 to disable retrying on SQL_BUSY error.
* @param {Boolean} [options.typeValidation=false] Run built in type validators on insert and update, e.g. validate that arguments passed to integer fields are integer-like.
* @param {number} [options.retry.max] How many times a failing query is automatically retried. Set to 0 to disable retrying on SQL_BUSY error.
* @param {boolean} [options.typeValidation=false] Run built in type validators on insert and update, e.g. validate that arguments passed to integer fields are integer-like.
* @param {Object} [options.operatorsAliases] String based operator alias. Pass object to limit set of aliased operators.
*
*/
constructor(database, username, password, options) {
let config;
......@@ -267,6 +257,11 @@ class Sequelize {
Sequelize.runHooks('afterInit', this);
}
/**
* Refresh data types and parsers.
*
* @private
*/
refreshTypes() {
this.connectionManager.refreshTypeParser(DataTypes);
}
......@@ -274,7 +269,7 @@ class Sequelize {
/**
* Returns the specified dialect.
*
* @return {String} The specified dialect.
* @returns {string} The specified dialect.
*/
getDialect() {
return this.options.dialect;
......@@ -282,10 +277,8 @@ class Sequelize {
/**
* Returns an instance of QueryInterface.
* @method getQueryInterface
* @memberOf Sequelize
* @return {QueryInterface} An instance (singleton) of QueryInterface.
*
* @returns {QueryInterface} An instance (singleton) of QueryInterface.
*/
getQueryInterface() {
this.queryInterface = this.queryInterface || new QueryInterface(this);
......@@ -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
*
* @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} [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 <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
*
* @return {Model}
* @returns {Model} Newly defined model
*
* @example
* sequelize.define('modelName', {
......@@ -320,11 +313,10 @@ class Sequelize {
* }
* },
* field: 'column_a'
* // Other attributes here
* },
* columnB: Sequelize.STRING,
* columnC: 'MY VERY OWN COLUMN TYPE'
* })
* });
*
* sequelize.models.modelName // The model will now be available in models under the name given to define
*/
......@@ -342,9 +334,10 @@ class Sequelize {
/**
* 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)
* @return {Model}
* @returns {Model} Specified model
*/
model(modelName) {
if (!this.isDefined(modelName)) {
......@@ -357,21 +350,23 @@ class Sequelize {
/**
* Checks whether a model with the given name is defined
*
* @param {String} modelName The name of a model defined with Sequelize.define
* @return {Boolean}
* @param {string} modelName The name of a model defined with Sequelize.define
*
* @returns {boolean} Returns true if model is already defined, otherwise false
*/
isDefined(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
* @return {Model}
* @param {string} path The path to the file that holds the model you want to import. If the part is relative, it will be resolved relatively to the calling file
*
* @returns {Model} Imported model, returned from cache if was already imported
*/
import(path) {
// is it a relative path?
......@@ -412,29 +407,28 @@ class Sequelize {
* })
* ```
*
* @method query
* @param {String} sql
* @param {string} sql
* @param {Object} [options={}] Query options.
* @param {Boolean} [options.raw] If true, sequelize will not try to format the results of the query, or build an instance of a model from the result
* @param {boolean} [options.raw] If true, sequelize will not try to format the results of the query, or build an instance of a model from the result
* @param {Transaction} [options.transaction=null] The transaction that the query should be executed under
* @param {QueryTypes} [options.type='RAW'] The type of query you are executing. The query type affects how results are formatted before they are passed back. The type is a string, but `Sequelize.QueryTypes` is provided as convenience shortcuts.
* @param {Boolean} [options.nest=false] If true, transforms objects with `.` separated property names into nested objects using [dottie.js](https://github.com/mickhansen/dottie.js). For example { 'user.username': 'john' } becomes { user: { username: 'john' }}. When `nest` is true, the query type is assumed to be `'SELECT'`, unless otherwise specified
* @param {Boolean} [options.plain=false] Sets the query type to `SELECT` and return a single row
* @param {boolean} [options.nest=false] If true, transforms objects with `.` separated property names into nested objects using [dottie.js](https://github.com/mickhansen/dottie.js). For example { 'user.username': 'john' } becomes { user: { username: 'john' }}. When `nest` is true, the query type is assumed to be `'SELECT'`, unless otherwise specified
* @param {boolean} [options.plain=false] Sets the query type to `SELECT` and return a single row
* @param {Object|Array} [options.replacements] Either an object of named parameter replacements in the format `:param` or an array of unnamed replacements to replace `?` in your SQL.
* @param {Object|Array} [options.bind] Either an object of named bind parameter in the format `_param` or an array of unnamed bind parameter to replace `$1, $2, ...` in your SQL.
* @param {Boolean} [options.useMaster=false] Force the query to use the write pool, regardless of the query type.
* @param {boolean} [options.useMaster=false] Force the query to use the write pool, regardless of the query type.
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @param {new Model()} [options.instance] A sequelize instance used to build the return instance
* @param {Model} [options.model] A sequelize model used to build the returned model instances (used to be called callee)
* @param {Object} [options.retry] Set of flags that control when a query is automatically retried.
* @param {Array} [options.retry.match] Only retry a query if the error matches one of these strings.
* @param {Integer} [options.retry.max] How many times a failing query is automatically retried.
* @param {String} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
* @param {Boolean} [options.supportsSearchPath] If false do not prepend the query with the search_path (Postgres only)
* @param {Boolean} [options.mapToModel=false] Map returned fields to model's fields if `options.model` or `options.instance` is present. Mapping will occur before building the model instance.
* @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
* @param {boolean} [options.supportsSearchPath] If false do not prepend the query with the search_path (Postgres only)
* @param {boolean} [options.mapToModel=false] Map returned fields to model's fields if `options.model` or `options.instance` is present. Mapping will occur before building the model instance.
* @param {Object} [options.fieldMap] Map returned fields to arbitrary names for `SELECT` query type.
*
* @return {Promise}
* @returns {Promise}
*
* @see {@link Model.build} for more information about instance option.
*/
......@@ -566,13 +560,13 @@ class Sequelize {
* Execute a query which would set an environment or user variable. The variables are set per connection, so this function needs a transaction.
* Only works for MySQL.
*
* @method set
* @param {Object} variables Object with multiple variables.
* @param {Object} options Query options.
* @param {Transaction} options.transaction The transaction that the query should be executed under
* @param {Object} [options] query options.
* @param {Transaction} [options.transaction] The transaction that the query should be executed under
*
* @memberof Sequelize
* @return {Promise}
*
* @returns {Promise}
*/
set(variables, options) {
......@@ -602,8 +596,9 @@ class Sequelize {
/**
* Escape value.
*
* @param {String} value
* @return {String}
* @param {string} value string value to escape
*
* @returns {string}
*/
escape(value) {
return this.getQueryInterface().escape(value);
......@@ -612,14 +607,16 @@ class Sequelize {
/**
* Create a new database schema.
*
* Note, that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
* **Note:** this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
* not a database table. In mysql and sqlite, this command will do nothing.
*
* @see {@link Model.schema}
* @param {String} schema Name of the schema
* @param {Object} options={}
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise}
*
* @param {string} schema Name of the schema
* @param {Object} [options={}] query options
* @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
*
* @returns {Promise}
*/
createSchema(schema, options) {
return this.getQueryInterface().createSchema(schema, options);
......@@ -628,11 +625,13 @@ class Sequelize {
/**
* 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.
* @param {Object} options={}
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise}
*
* @param {Object} [options={}] query options
* @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
*
* @returns {Promise}
*/
showAllSchemas(options) {
return this.getQueryInterface().showAllSchemas(options);
......@@ -641,25 +640,29 @@ class Sequelize {
/**
* 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
* @param {String} schema Name of the schema
* @param {Object} options={}
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise}
*
* @param {string} schema Name of the schema
* @param {Object} [options={}] query options
* @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
*
* @returns {Promise}
*/
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.
* @param {Object} options={}
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise}
*
* @param {Object} [options={}] query options
* @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
*
* @returns {Promise}
*/
dropAllSchemas(options) {
return this.getQueryInterface().dropAllSchemas(options);
......@@ -668,15 +671,16 @@ class Sequelize {
/**
* Sync all defined models to the DB.
*
* @param {Object} [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 {Object} [options={}] sync options
* @param {boolean} [options.force=false] If force is true, each Model will run `DROP TABLE IF EXISTS`, before it tries to create its own table
* @param {RegExp} [options.match] Match a regex against the database name before syncing, a safety check for cases where force: true is used in tests but not live code
* @param {Boolean|function} [options.logging=console.log] A function that logs sql queries, or false for no logging
* @param {String} [options.schema='public'] The schema that the tables should be created in. This can be overriden for each table in sequelize.define
* @param {String} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
* @param {Boolean} [options.hooks=true] If hooks is true then beforeSync, afterSync, beforeBulkSync, afterBulkSync hooks will be called
* @param {Boolean} [options.alter=false] Alters tables to fit models. Not recommended for production use. Deletes data in columns that were removed or had their type changed in the model.
* @return {Promise}
* @param {boolean|Function} [options.logging=console.log] A function that logs sql queries, or false for no logging
* @param {string} [options.schema='public'] The schema that the tables should be created in. This can be overriden for each table in sequelize.define
* @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
* @param {boolean} [options.hooks=true] If hooks is true then beforeSync, afterSync, beforeBulkSync, afterBulkSync hooks will be called
* @param {boolean} [options.alter=false] Alters tables to fit models. Not recommended for production use. Deletes data in columns that were removed or had their type changed in the model.
*
* @returns {Promise}
*/
sync(options) {
options = _.clone(options) || {};
......@@ -719,13 +723,12 @@ class Sequelize {
}
/**
* Truncate all tables defined through the sequelize models. This is done
* by calling Model.truncate() on each model.
* Truncate all tables defined through the sequelize models.
* This is done by calling `Model.truncate()` on each model.
*
* @param {object} [options] The options passed to Model.destroy in addition to truncate
* @param {Boolean|function} [options.transaction]
* @param {Boolean|function} [options.logging] A function that logs sql queries, or false for no logging
* @return {Promise}
* @param {Object} [options] The options passed to Model.destroy in addition to truncate
* @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
* @returns {Promise}
*
* @see {@link Model.truncate} for more information
*/
......@@ -748,12 +751,15 @@ class Sequelize {
}
/**
* Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model
* Drop all tables defined through this sequelize instance.
* This is done by calling Model.drop on each model.
*
* @see {@link Model.drop} for options
*
* @param {object} options The options passed to each call to Model.drop
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise}
* @param {Object} [options] The options passed to each call to Model.drop
* @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
*
* @returns {Promise}
*/
drop(options) {
const models = [];
......@@ -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...)
* @return {Promise}
* @returns {Promise}
*/
authenticate(options) {
options = _.assign({
......@@ -790,7 +797,7 @@ class Sequelize {
/**
* Get the fn for random based on the dialect
*
* @return {Sequelize.fn}
* @returns {Sequelize.fn}
*/
random() {
if (['postgres', 'sqlite'].includes(this.getDialect())) {
......@@ -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.
* 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 Sequelize.define}
* @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
*
* @since v2.0.0-dev3
* @memberof Sequelize
* @return {Sequelize.fn}
* @returns {Sequelize.fn}
*
* @example <caption>Convert a user's username to upper case</caption>
* instance.updateAttributes({
* username: self.sequelize.fn('upper', self.sequelize.col('username'))
* })
* instance.update({
* username: sequelize.fn('upper', sequelize.col('username'))
* });
*/
static fn(fn) {
return new Utils.Fn(fn, Utils.sliceArgs(arguments, 1));
static fn(fn, ...args) {
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.
*
* @see {@link Sequelize#fn}
*
* @method col
* @param {String} col The name of the column
* @param {string} col The name of the column
* @since v2.0.0-dev3
* @memberof Sequelize
* @return {Sequelize.col}
*
* @returns {Sequelize.col}
*/
static col(col) {
return new Utils.Col(col);
......@@ -848,12 +849,12 @@ class Sequelize {
/**
* Creates an object representing a call to the cast function.
*
* @method cast
* @param {any} val The value to cast
* @param {String} type The type to cast it to
* @param {string} type The type to cast it to
* @since v2.0.0-dev3
* @memberof Sequelize
* @return {Sequelize.cast}
*
* @returns {Sequelize.cast}
*/
static cast(val, type) {
return new Utils.Cast(val, type);
......@@ -862,12 +863,11 @@ class Sequelize {
/**
* Creates an object representing a literal, i.e. something that will not be escaped.
*
* @method literal
* @param {any} val
* @alias asIs
* @param {any} val literal value
* @since v2.0.0-dev3
* @memberof Sequelize
* @return {Sequelize.literal}
*
* @returns {Sequelize.literal}
*/
static literal(val) {
return new Utils.Literal(val);
......@@ -875,41 +875,44 @@ class Sequelize {
/**
* An AND query
*
* @see {@link Model.findAll}
*
* @method and
* @param {String|Object} args Each argument will be joined by AND
* @param {...string|Object} args Each argument will be joined by AND
* @since v2.0.0-dev3
* @memberof Sequelize
* @return {Sequelize.and}
*
* @returns {Sequelize.and}
*/
static and() {
return { [Op.and]: Utils.sliceArgs(arguments) };
static and(...args) {
return { [Op.and]: Utils.sliceArgs(args) };
}
/**
* An OR query
*
* @see {@link Model.findAll}
*
* @method or
* @param {String|Object} args Each argument will be joined by OR
* @param {...string|Object} args Each argument will be joined by OR
* @since v2.0.0-dev3
* @memberof Sequelize
* @return {Sequelize.or}
*
* @returns {Sequelize.or}
*/
static or() {
return { [Op.or]: Utils.sliceArgs(arguments) };
static or(...args) {
return { [Op.or]: Utils.sliceArgs(args) };
}
/**
* Creates an object representing nested where conditions for postgres/sqlite/mysql json data-type.
* @see {@link Model#findAll}
*
* @method json
* @param {String|Object} conditions A hash containing strings/numbers or other nested hash, a string using dot notation or a string using postgres/sqlite/mysql json syntax.
* @param {String|Number|Boolean} [value] An optional value to compare against. Produces a string of the form "<json path> = '<value>'".
* @see {@link Model.findAll}
*
* @param {string|Object} conditionsOrPath A hash containing strings/numbers or other nested hash, a string using dot notation or a string using postgres/sqlite/mysql json syntax.
* @param {string|number|boolean} [value] An optional value to compare against. Produces a string of the form "<json path> = '<value>'".
* @memberof Sequelize
* @return {Sequelize.json}
*
* @returns {Sequelize.json}
*/
static json(conditionsOrPath, value) {
return new Utils.Json(conditionsOrPath, value);
......@@ -926,9 +929,8 @@ class Sequelize {
* @see {@link Model.findAll}
*
* @param {Object} attr The attribute, which can be either an attribute object from `Model.rawAttributes` or a sequelize object, for example an instance of `sequelize.fn`. For simple string attributes, use the POJO syntax
* @param {String|Op} [comparator='&#61;']
* @param {String|Object} logic The condition. Can be both a simply type, or a further condition (`or`, `and`, `.literal` etc.)
* @alias condition
* @param {Symbol} [comparator='Op.eq'] operator
* @param {string|Object} logic The condition. Can be both a simply type, or a further condition (`or`, `and`, `.literal` etc.)
* @since v2.0.0-dev3
*/
static where(attr, comparator, logic) {
......@@ -936,20 +938,20 @@ class Sequelize {
}
/**
* Start a transaction. When using transactions, you should pass the transaction in the options argument in order for the query to happen under that transaction
* Start a transaction. When using transactions, you should pass the transaction in the options argument in order for the query to happen under that transaction @see {@link Transaction}
*
* ```js
* If you have [CLS](https://github.com/othiym23/node-continuation-local-storage) enabled, the transaction will automatically be passed to any query that runs within the callback
*
* @example
* sequelize.transaction().then(transaction => {
* return User.find(..., {transaction})
* .then(user => user.updateAttributes(..., {transaction}))
* .then(() => transaction.commit())
* .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()
* return User.find(..., {transaction})
* .then(user => user.updateAttributes(..., {transaction}))
......@@ -959,27 +961,24 @@ class Sequelize {
* // Rolled back
* 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.
* To enable CLS, add it do your project, create a namespace and set it on the sequelize constructor:
* @example <caption>To enable CLS, add it do your project, create a namespace and set it on the sequelize constructor:</caption>
*
* ```js
* const cls = require('continuation-local-storage');
* const ns = cls.createNamespace('....');
* const Sequelize = require('sequelize');
* Sequelize.useCLS(ns);
* ```
* Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace
*
* @see {@link Transaction}
* @param {Object} [options={}]
* @param {Boolean} [options.autocommit]
* @param {String} [options.type='DEFERRED'] See `Sequelize.Transaction.TYPES` for possible options. Sqlite only.
* @param {String} [options.isolationLevel] See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options
* // Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace
*
* @param {Object} [options] Transaction options
* @param {boolean} [options.autocommit] Auto commit this transaction
* @param {string} [options.type='DEFERRED'] See `Sequelize.Transaction.TYPES` for possible options. Sqlite only.
* @param {string} [options.isolationLevel] See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @param {Function} [autoCallback] The callback is called with the transaction object, and should return a promise. If the promise is resolved, the transaction commits; if the promise rejects, the transaction rolls back
* @return {Promise}
*
* @returns {Promise}
*/
transaction(options, autoCallback) {
if (typeof options === 'function') {
......@@ -1048,6 +1047,7 @@ class Sequelize {
log() {
let options;
let args = Utils.sliceArgs(arguments);
const last = _.last(args);
if (last && _.isPlainObject(last) && last.hasOwnProperty('logging')) {
......@@ -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
* to garbage collect some of them.
*
* @return {Promise}
* @returns {Promise}
*/
close() {
return this.connectionManager.close();
......
......@@ -4,20 +4,23 @@ const _ = require('lodash');
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.
*
* @class Transaction
* @see {@link Sequelize.transaction}
*/
class Transaction {
/**
* Creates a new transaction instance
*
* @param {Sequelize} sequelize A configured sequelize Instance
* @param {Object} options An object with options
* @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.isolationLevel=true Sets the isolation level of the transaction.
* @param {String} options.deferrable Sets the constraints to be deferred or immediately checked.
* @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.isolationLevel=true Sets the isolation level of the transaction.
* @param {string} options.deferrable Sets the constraints to be deferred or immediately checked.
*/
constructor(sequelize, options) {
this.sequelize = sequelize;
......@@ -52,10 +55,9 @@ class Transaction {
/**
* Commit the transaction
*
* @return {Promise}
* @returns {Promise}
*/
commit() {
if (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 {
/**
* Rollback (abort) the transaction
*
* @return {Promise}
* @returns {Promise}
*/
rollback() {
if (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 {
/**
* A hook that is run after a transaction is committed
*
* @param {Function} fn A callback function that is called with the committed transaction
* @name afterCommit
* @memberOf Sequelize.Transaction
* @memberof Sequelize.Transaction
*/
afterCommit(fn) {
if (!fn || typeof fn !== 'function') {
......@@ -209,17 +211,15 @@ class Transaction {
*
* Pass in the desired level as the first argument:
*
* ```js
* @example
* return sequelize.transaction({type: Sequelize.Transaction.TYPES.EXCLUSIVE}, transaction => {
*
* // your transactions
*
* }).then(result => {
* // transaction has been committed. Do something after the commit if required.
* }).catch(err => {
* // do something with the err.
* });
* ```
*
* @property DEFERRED
* @property IMMEDIATE
* @property EXCLUSIVE
......@@ -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`.
*
* Pass in the desired level as the first argument:
*
* ```js
* @example
* return sequelize.transaction({isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE}, transaction => {
*
* // your transactions
*
* }).then(result => {
* // transaction has been committed. Do something after the commit if required.
* }).catch(err => {
* // do something with the err.
* });
* ```
*
* @property READ_UNCOMMITTED
* @property READ_COMMITTED
* @property REPEATABLE_READ
......@@ -267,17 +265,15 @@ class Transaction {
/**
* Possible options for row locking. Used in conjunction with `find` calls:
*
* ```js
* t1 // is a transaction
* @example
* // t1 is a transaction
* Model.findAll({
* where: ...,
* transaction: t1,
* lock: t1.LOCK...
* });
* ```
*
* Postgres also supports specific locks while eager loading by using OF:
* ```js
* @example <caption>Postgres also supports specific locks while eager loading by using OF:</caption>
* UserModel.findAll({
* where: ...,
* include: [TaskModel, ...],
......@@ -287,23 +283,20 @@ class Transaction {
* 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
* t1 // is a transaction
* @example <caption>You can also skip locked rows:</caption>
* // t1 is a transaction
* Model.findAll({
* where: ...,
* transaction: t1,
* lock: 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 SHARE
* @property KEY_SHARE Postgres 9.3+ only
......@@ -319,7 +312,7 @@ class Transaction {
}
/**
* @see {@link Transaction.LOCK}
* Please {@link Transaction.LOCK}
*/
get LOCK() {
return Transaction.LOCK;
......
......@@ -278,7 +278,7 @@ exports.toDefaultValue = toDefaultValue;
* in a db schema using the DEFAULT directive.
*
* @param {*} value Any default value.
* @return {boolean} yes / no.
* @returns {boolean} yes / no.
* @private
*/
function defaultValueSchemable(value) {
......@@ -394,7 +394,7 @@ exports.removeTicks = removeTicks;
* }
*
* @param value, an Object
* @return Object, an flattened object
* @returns Object, an flattened object
* @private
*/
function flattenObjectDeep(value) {
......@@ -501,7 +501,7 @@ exports.Where = Where;
/**
* getOperators
* @param {Object} obj
* @return {Array<Symbol>} All operators properties of obj
* @returns {Array<Symbol>} All operators properties of obj
* @private
*/
function getOperators(obj) {
......@@ -512,7 +512,7 @@ exports.getOperators = getOperators;
/**
* getComplexKeys
* @param {Object} obj
* @return {Array<String|Symbol>} All keys including operators
* @returns {Array<String|Symbol>} All keys including operators
* @private
*/
function getComplexKeys(obj) {
......@@ -523,7 +523,7 @@ exports.getComplexKeys = getComplexKeys;
/**
* getComplexSize
* @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
*/
function getComplexSize(obj) {
......@@ -535,7 +535,7 @@ exports.getComplexSize = getComplexSize;
* Returns true if a where clause is empty, even with Symbols
*
* @param {Object} obj
* @return {Boolean}
* @returns {boolean}
* @private
*/
function isWhereEmpty(obj) {
......@@ -546,9 +546,9 @@ exports.isWhereEmpty = isWhereEmpty;
/**
* Returns ENUM name by joining table and column name
*
* @param {String} tableName
* @param {String} columnName
* @return {String}
* @param {string} tableName
* @param {string} columnName
* @returns {string}
* @private
*/
function generateEnumName(tableName, columnName) {
......@@ -559,7 +559,7 @@ exports.generateEnumName = generateEnumName;
/**
* Returns an new Object which keys are camelized
* @param {Object} obj
* @return {String}
* @returns {string}
* @private
*/
function camelizeObjectKeys(obj) {
......@@ -624,7 +624,7 @@ exports.classToInvokable = classToInvokable;
*
* @param {Object} index
* @param {Array} index.fields
* @param {String} [index.name]
* @param {string} [index.name]
* @param {String|Object} tableName
*
* @returns {Object}
......
......@@ -4,7 +4,12 @@ const util = require('util');
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
*/
function inherits(constructor, superConstructor) {
......
......@@ -47,13 +47,16 @@
"continuation-local-storage": "^3.x",
"cross-env": "^5.2.0",
"cz-conventional-changelog": "^2.x",
"docdash": "^0.4.0",
"env-cmd": "^8.0.0",
"esdoc": "^0.5.2",
"eslint": "^5.0.0",
"eslint-plugin-jsdoc": "^3.7.1",
"eslint-plugin-mocha": "^5.0.0",
"hints": "^1.x",
"husky": "^0.x",
"istanbul": "^0.x",
"jsdoc": "^3.5.5",
"lcov-result-merger": "^3.0.0",
"mocha": "^5.x",
"mysql2": "^1.x",
......@@ -91,6 +94,7 @@
"test-docker-unit": "npm run test-unit",
"test-docker-integration": "env-cmd $npm_package_options_env_cmd npm run test-integration",
"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))\"",
"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",
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!