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

Commit 4478d74a by Simon Schick Committed by Sushant

chore: strict linting for code and jsdocs (#10535)

1 parent f862e6bb
Showing with 269 additions and 238 deletions
{ {
"extends": "eslint:recommended",
"rules": { "rules": {
"mocha/no-exclusive-tests": "error", "mocha/no-exclusive-tests": "error",
"mocha/no-skipped-tests": "warn", "mocha/no-skipped-tests": "warn",
// "jsdoc/check-param-names": "error", "jsdoc/check-param-names": "error",
// "jsdoc/check-tag-names": "error", "jsdoc/check-tag-names": "error",
// "jsdoc/check-types": "error", "jsdoc/check-types": "error",
// "jsdoc/newline-after-description": "error", "jsdoc/newline-after-description": "error",
// "jsdoc/no-undefined-types": "error", "jsdoc/no-undefined-types": "off",
// "jsdoc/require-description-complete-sentence": "off", "jsdoc/require-description-complete-sentence": "off",
// "jsdoc/require-example": "off", "jsdoc/require-example": "off",
// "jsdoc/require-hyphen-before-param-description": "off", "jsdoc/require-hyphen-before-param-description": "off",
// "jsdoc/require-param": "error", "jsdoc/require-param": "error",
// "jsdoc/require-param-description": "error", "jsdoc/require-param-description": "off",
// "jsdoc/require-param-name": "error", "jsdoc/require-param-name": "error",
// "jsdoc/require-param-type": "error", "jsdoc/require-param-type": "error",
// "jsdoc/require-returns-description": "off", "jsdoc/require-returns-description": "off",
// "jsdoc/require-returns-type": "error", "jsdoc/require-returns-type": "error",
// "jsdoc/valid-types": "off", "jsdoc/valid-types": "error",
// style
"array-bracket-spacing": "error", "array-bracket-spacing": "error",
"comma-spacing": "error", "comma-spacing": "error",
"key-spacing": "error", "key-spacing": "error",
"keyword-spacing": "error", "keyword-spacing": "error",
"object-curly-spacing": ["error", "always"], "object-curly-spacing": ["error", "always"],
"func-call-spacing": ["error", "never"], "func-call-spacing": ["error", "never"],
"no-console": "off",
"no-extra-parens": "error",
"valid-jsdoc": "off",
"new-cap": [ "new-cap": [
"error", "error",
{ {
...@@ -36,13 +34,6 @@ ...@@ -36,13 +34,6 @@
"properties": false "properties": false
} }
], ],
"no-extra-boolean-cast": "error",
"strict": [
"error",
"global"
],
"no-var": "error",
"prefer-const": "error",
"semi": [ "semi": [
"error", "error",
"always" "always"
...@@ -52,7 +43,6 @@ ...@@ -52,7 +43,6 @@
"never" "never"
], ],
"space-before-blocks": "error", "space-before-blocks": "error",
"prefer-arrow-callback": "error",
"arrow-parens": [ "arrow-parens": [
"error", "error",
"as-needed" "as-needed"
...@@ -61,18 +51,6 @@ ...@@ -61,18 +51,6 @@
"error", "error",
"last" "last"
], ],
"no-bitwise": "off",
"no-cond-assign": [
"error",
"except-parens"
],
"curly": "off",
"eqeqeq": "error",
"no-extend-native": "error",
"wrap-iife": [
"error",
"any"
],
"indent": [ "indent": [
"error", "error",
2, 2,
...@@ -80,15 +58,8 @@ ...@@ -80,15 +58,8 @@
"SwitchCase": 1 "SwitchCase": 1
} }
], ],
"no-use-before-define": "off", "no-extra-parens": "error",
"no-caller": "error", "curly": "off",
"no-undef": "error",
"no-unused-vars": "error",
"no-irregular-whitespace": "error",
"max-depth": [
"error",
6
],
"quotes": [ "quotes": [
"error", "error",
"single", "single",
...@@ -97,16 +68,37 @@ ...@@ -97,16 +68,37 @@
} }
], ],
"linebreak-style": "error", "linebreak-style": "error",
"camelcase": "error",
"comma-dangle": "error",
// functional
"valid-jsdoc": "off",
"strict": [
"error",
"global"
],
"no-var": "error",
"prefer-const": "error",
"prefer-arrow-callback": "error",
"no-extend-native": "error",
"wrap-iife": [
"error",
"any"
],
"no-use-before-define": "off",
"no-caller": "error",
"no-irregular-whitespace": "error",
"max-depth": [
"error",
6
],
"no-loop-func": "warn", "no-loop-func": "warn",
"object-shorthand": "error", "object-shorthand": "error",
"one-var-declaration-per-line": "error", "one-var-declaration-per-line": "error",
"comma-dangle": "error",
"no-shadow": "warn", "no-shadow": "warn",
"camelcase": "error",
"prefer-template": "error", "prefer-template": "error",
"no-else-return": ["error", { "allowElseIf": false }], "no-else-return": ["error", { "allowElseIf": false }],
"no-lonely-if": "error", "no-lonely-if": "error",
"no-this-before-super": "error",
"no-throw-literal": "error", "no-throw-literal": "error",
"prefer-promise-reject-errors": "error", "prefer-promise-reject-errors": "error",
"no-invalid-this": "error", "no-invalid-this": "error",
...@@ -117,7 +109,8 @@ ...@@ -117,7 +109,8 @@
"no-useless-call": "error", "no-useless-call": "error",
"no-unused-expressions": "error", "no-unused-expressions": "error",
"no-sequences": "error", "no-sequences": "error",
"no-self-compare": "error" "no-self-compare": "error",
"no-case-declarations": "off"
}, },
"parserOptions": { "parserOptions": {
"ecmaVersion": 6, "ecmaVersion": 6,
...@@ -132,17 +125,4 @@ ...@@ -132,17 +125,4 @@
"mocha": true, "mocha": true,
"es6": true "es6": true
} }
// "globals": {
// "Association": true,
// "HasMany": true,
// "BelongsTo": true,
// "HasOne": true,
// "BelongsToMany": true,
// "DataTypes": true,
// "Sequelize": true,
// "Transaction": true,
// "Model": true,
// "QueryInterface": true,
// "QueryType": true
// },
} }
...@@ -362,15 +362,16 @@ class BelongsToMany extends Association { ...@@ -362,15 +362,16 @@ class BelongsToMany extends Association {
/** /**
* Get everything currently associated with this, using an optional where clause. * Get everything currently associated with this, using an optional where clause.
* *
* @see {@link Model.findAll} for a full explanation of options * @see
* {@link Model} for a full explanation of options
* *
* @param {<Model>} instance instance * @param {Model} instance instance
* @param {Object} [options] find options * @param {Object} [options] find options
* @param {Object} [options.where] An optional where clause to limit the associated models * @param {Object} [options.where] An optional where clause to limit the associated models
* @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false * @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {string} [options.schema] Apply a schema on the related model * @param {string} [options.schema] Apply a schema on the related model
* *
* @returns {Promise<Array<<Model>>>} * @returns {Promise<Array<Model>>}
*/ */
get(instance, options) { get(instance, options) {
options = Utils.cloneDeep(options) || {}; options = Utils.cloneDeep(options) || {};
...@@ -433,7 +434,7 @@ class BelongsToMany extends Association { ...@@ -433,7 +434,7 @@ class BelongsToMany extends Association {
/** /**
* Count everything currently associated with this, using an optional where clause. * Count everything currently associated with this, using an optional where clause.
* *
* @param {<Model>} instance instance * @param {Model} instance instance
* @param {Object} [options] find options * @param {Object} [options] find options
* @param {Object} [options.where] An optional where clause to limit the associated models * @param {Object} [options.where] An optional where clause to limit the associated models
* @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false * @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
...@@ -458,8 +459,8 @@ class BelongsToMany extends Association { ...@@ -458,8 +459,8 @@ class BelongsToMany extends Association {
/** /**
* Check if one or more instance(s) are associated with this. If a list of instances is passed, the function returns true if _all_ instances are associated * Check if one or more instance(s) are associated with this. If a list of instances is passed, the function returns true if _all_ instances are associated
* *
* @param {<Model>} sourceInstance source instance to check for an association with * @param {Model} sourceInstance source instance to check for an association with
* @param {<Model>|<Model>[]|string[]|string|number[]|number} [instances] Can be an array of instances or their primary keys * @param {Model|Model[]|string[]|string|number[]|number} [instances] Can be an array of instances or their primary keys
* @param {Object} [options] Options passed to getAssociations * @param {Object} [options] Options passed to getAssociations
* *
* @returns {Promise<boolean>} * @returns {Promise<boolean>}
...@@ -502,8 +503,8 @@ class BelongsToMany extends Association { ...@@ -502,8 +503,8 @@ class BelongsToMany extends Association {
* Set the associated models by passing an array of instances or their primary keys. * 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. * Everything that it not in the passed array will be un-associated.
* *
* @param {<Model>} sourceInstance source instance to associate new instances with * @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 {Model|Model[]|string[]|string|number[]|number} [newAssociatedObjects] A single instance or primary key, or a mixed array of persisted instances or primary keys
* @param {Object} [options] Options passed to `through.findAll`, `bulkCreate`, `update` and `destroy` * @param {Object} [options] Options passed to `through.findAll`, `bulkCreate`, `update` and `destroy`
* @param {Object} [options.validate] Run validation for the join model * @param {Object} [options.validate] Run validation for the join model
* @param {Object} [options.through] Additional attributes for the join table. * @param {Object} [options.through] Additional attributes for the join table.
...@@ -610,8 +611,8 @@ class BelongsToMany extends Association { ...@@ -610,8 +611,8 @@ class BelongsToMany extends Association {
* Associate one ore several rows with source instance. It will not un-associate any already assoicated instance * Associate one ore several rows with source instance. It will not un-associate any already assoicated instance
* that may be missing from `newInstances`. * that may be missing from `newInstances`.
* *
* @param {<Model>} sourceInstance source instance to associate new instances with * @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 {Model|Model[]|string[]|string|number[]|number} [newInstances] A single instance or primary key, or a mixed array of persisted instances or primary keys
* @param {Object} [options] Options passed to `through.findAll`, `bulkCreate` and `update` * @param {Object} [options] Options passed to `through.findAll`, `bulkCreate` and `update`
* @param {Object} [options.validate] Run validation for the join model. * @param {Object} [options.validate] Run validation for the join model.
* @param {Object} [options.through] Additional attributes for the join table. * @param {Object} [options.through] Additional attributes for the join table.
...@@ -706,8 +707,8 @@ class BelongsToMany extends Association { ...@@ -706,8 +707,8 @@ class BelongsToMany extends Association {
/** /**
* Un-associate one or more instance(s). * Un-associate one or more instance(s).
* *
* @param {<Model>} sourceInstance instance to un associate instances with * @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 {Model|Model[]|string|string[]|number|number[]} [oldAssociatedObjects] Can be an Instance or its primary key, or a mixed array of instances and primary keys
* @param {Object} [options] Options passed to `through.destroy` * @param {Object} [options] Options passed to `through.destroy`
* *
* @returns {Promise} * @returns {Promise}
...@@ -730,7 +731,7 @@ class BelongsToMany extends Association { ...@@ -730,7 +731,7 @@ class BelongsToMany extends Association {
/** /**
* Create a new instance of the associated model and associate it with this. * Create a new instance of the associated model and associate it with this.
* *
* @param {<Model>} sourceInstance source instance * @param {Model} sourceInstance source instance
* @param {Object} [values] values for target model * @param {Object} [values] values for target model
* @param {Object} [options] Options passed to create and add * @param {Object} [options] Options passed to create and add
* @param {Object} [options.through] Additional attributes for the join table * @param {Object} [options.through] Additional attributes for the join table
......
...@@ -113,14 +113,15 @@ class BelongsTo extends Association { ...@@ -113,14 +113,15 @@ class BelongsTo extends Association {
/** /**
* Get the associated instance. * Get the associated instance.
* *
* @param {<Model>|Array<Model>} instances source instances * @param {Model|Array<Model>} instances source instances
* @param {Object} [options] find options * @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|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false.
* @param {string} [options.schema] Apply a schema on the related model * @param {string} [options.schema] Apply a schema on the related model
* *
* @see {@link Model.findOne} for a full explanation of options * @see
* {@link Model.findOne} for a full explanation of options
* *
* @returns {Promise<<Model>>} * @returns {Promise<Model>}
*/ */
get(instances, options) { get(instances, options) {
const where = {}; const where = {};
...@@ -183,7 +184,7 @@ class BelongsTo extends Association { ...@@ -183,7 +184,7 @@ class BelongsTo extends Association {
/** /**
* Set the associated model. * Set the associated model.
* *
* @param {<Model>} sourceInstance the source instance * @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 {?<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 {Object} [options={}] options passed to `this.save`
* @param {boolean} [options.save=true] Skip saving this after setting the foreign key if false. * @param {boolean} [options.save=true] Skip saving this after setting the foreign key if false.
...@@ -214,11 +215,12 @@ class BelongsTo extends Association { ...@@ -214,11 +215,12 @@ class BelongsTo extends Association {
/** /**
* Create a new instance of the associated model and associate it with this. * Create a new instance of the associated model and associate it with this.
* *
* @param {<Model>} sourceInstance the source instance * @param {Model} sourceInstance the source instance
* @param {Object} [values={}] values to create associated model instance with * @param {Object} [values={}] values to create associated model instance with
* @param {Object} [options={}] Options passed to `target.create` and setAssociation. * @param {Object} [options={}] Options passed to `target.create` and setAssociation.
* *
* @see {@link Model#create} for a full explanation of options * @see
* {@link Model#create} for a full explanation of options
* *
* @returns {Promise<Model>} The created target model * @returns {Promise<Model>} The created target model
*/ */
......
...@@ -157,15 +157,16 @@ class HasMany extends Association { ...@@ -157,15 +157,16 @@ class HasMany extends Association {
/** /**
* Get everything currently associated with this, using an optional where clause. * Get everything currently associated with this, using an optional where clause.
* *
* @param {<Model>|Array<Model>} instances source instances * @param {Model|Array<Model>} instances source instances
* @param {Object} [options] find options * @param {Object} [options] find options
* @param {Object} [options.where] An optional where clause to limit the associated models * @param {Object} [options.where] An optional where clause to limit the associated models
* @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false * @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {string} [options.schema] Apply a schema on the related model * @param {string} [options.schema] Apply a schema on the related model
* *
* @see {@link Model.findAll} for a full explanation of options * @see
* {@link Model.findAll} for a full explanation of options
* *
* @returns {Promise<Array<<Model>>>} * @returns {Promise<Array<Model>>}
*/ */
get(instances, options = {}) { get(instances, options = {}) {
const where = {}; const where = {};
...@@ -241,7 +242,7 @@ class HasMany extends Association { ...@@ -241,7 +242,7 @@ class HasMany extends Association {
/** /**
* Count everything currently associated with this, using an optional where clause. * Count everything currently associated with this, using an optional where clause.
* *
* @param {<Model>} instance the source instance * @param {Model} instance the source instance
* @param {Object} [options] find & count options * @param {Object} [options] find & count options
* @param {Object} [options.where] An optional where clause to limit the associated models * @param {Object} [options.where] An optional where clause to limit the associated models
* @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false * @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
...@@ -269,8 +270,8 @@ class HasMany extends Association { ...@@ -269,8 +270,8 @@ class HasMany extends Association {
/** /**
* Check if one or more rows are associated with `this`. * Check if one or more rows are associated with `this`.
* *
* @param {<Model>} sourceInstance the source instance * @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 {Model|Model[]|string[]|string|number[]|number} [targetInstances] Can be an array of instances or their primary keys
* @param {Object} [options] Options passed to getAssociations * @param {Object} [options] Options passed to getAssociations
* *
* @returns {Promise} * @returns {Promise}
...@@ -310,8 +311,8 @@ class HasMany extends Association { ...@@ -310,8 +311,8 @@ class HasMany extends Association {
/** /**
* Set the associated models by passing an array of persisted instances or their primary keys. Everything that is not in the passed array will be un-associated * Set the associated models by passing an array of persisted instances or their primary keys. Everything that is not in the passed array will be un-associated
* *
* @param {<Model>} sourceInstance source instance to associate new instances with * @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 {Model|Model[]|string[]|string|number[]|number} [targetInstances] An array of persisted instances or primary key of instances to associate with this. Pass `null` or `undefined` to remove all associations.
* @param {Object} [options] Options passed to `target.findAll` and `update`. * @param {Object} [options] Options passed to `target.findAll` and `update`.
* @param {Object} [options.validate] Run validation for the join model * @param {Object} [options.validate] Run validation for the join model
* *
...@@ -385,8 +386,8 @@ class HasMany extends Association { ...@@ -385,8 +386,8 @@ class HasMany extends Association {
* Associate one or more target rows with `this`. This method accepts a Model / string / number to associate a single row, * Associate one or more target rows with `this`. This method accepts a Model / string / number to associate a single row,
* or a mixed array of Model / string / numbers to associate multiple rows. * or a mixed array of Model / string / numbers to associate multiple rows.
* *
* @param {<Model>} sourceInstance the source instance * @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 {Model|Model[]|string[]|string|number[]|number} [targetInstances] A single instance or primary key, or a mixed array of persisted instances or primary keys
* @param {Object} [options] Options passed to `target.update`. * @param {Object} [options] Options passed to `target.update`.
* *
* @returns {Promise} * @returns {Promise}
...@@ -413,8 +414,8 @@ class HasMany extends Association { ...@@ -413,8 +414,8 @@ class HasMany extends Association {
/** /**
* Un-associate one or several target rows. * Un-associate one or several target rows.
* *
* @param {<Model>} sourceInstance instance to un associate instances with * @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 {Model|Model[]|string|string[]|number|number[]} [targetInstances] Can be an Instance or its primary key, or a mixed array of instances and primary keys
* @param {Object} [options] Options passed to `target.update` * @param {Object} [options] Options passed to `target.update`
* *
* @returns {Promise} * @returns {Promise}
...@@ -439,7 +440,7 @@ class HasMany extends Association { ...@@ -439,7 +440,7 @@ class HasMany extends Association {
/** /**
* Create a new instance of the associated model and associate it with this. * Create a new instance of the associated model and associate it with this.
* *
* @param {<Model>} sourceInstance source instance * @param {Model} sourceInstance source instance
* @param {Object} [values] values for target model instance * @param {Object} [values] values for target model instance
* @param {Object} [options] Options passed to `target.create` * @param {Object} [options] Options passed to `target.create`
* *
......
...@@ -112,12 +112,13 @@ class HasOne extends Association { ...@@ -112,12 +112,13 @@ class HasOne extends Association {
/** /**
* Get the associated instance. * Get the associated instance.
* *
* @param {<Model>|Array<Model>} instances source instances * @param {Model|Array<Model>} instances source instances
* @param {Object} [options] find options * @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|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {string} [options.schema] Apply a schema on the related model * @param {string} [options.schema] Apply a schema on the related model
* *
* @see {@link Model.findOne} for a full explanation of options * @see
* {@link Model.findOne} for a full explanation of options
* *
* @returns {Promise<Model>} * @returns {Promise<Model>}
*/ */
...@@ -183,7 +184,7 @@ class HasOne extends Association { ...@@ -183,7 +184,7 @@ class HasOne extends Association {
/** /**
* Set the associated model. * Set the associated model.
* *
* @param {<Model>} sourceInstance the source instance * @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 {?<Model>|string|number} [associatedInstance] An persisted instance or the primary key of an instance to associate with this. Pass `null` or `undefined` to remove the association.
* @param {Object} [options] Options passed to getAssociation and `target.save` * @param {Object} [options] Options passed to getAssociation and `target.save`
* *
...@@ -233,11 +234,12 @@ class HasOne extends Association { ...@@ -233,11 +234,12 @@ class HasOne extends Association {
/** /**
* Create a new instance of the associated model and associate it with this. * Create a new instance of the associated model and associate it with this.
* *
* @param {<Model>} sourceInstance the source instance * @param {Model} sourceInstance the source instance
* @param {Object} [values={}] values to create associated model instance with * @param {Object} [values={}] values to create associated model instance with
* @param {Object} [options] Options passed to `target.create` and setAssociation. * @param {Object} [options] Options passed to `target.create` and setAssociation.
* *
* @see {@link Model#create} for a full explanation of options * @see
* {@link Model#create} for a full explanation of options
* *
* @returns {Promise<Model>} The created target model * @returns {Promise<Model>} The created target model
*/ */
......
...@@ -41,7 +41,7 @@ class ABSTRACT { ...@@ -41,7 +41,7 @@ class ABSTRACT {
} }
static extend(oldType) { static extend(oldType) {
return new this(oldType.options); return new this(oldType.options);
}; }
} }
ABSTRACT.prototype.dialectTypes = ''; ABSTRACT.prototype.dialectTypes = '';
......
...@@ -58,7 +58,7 @@ class ConnectionManager { ...@@ -58,7 +58,7 @@ class ConnectionManager {
* Try to load dialect module from various configured options. * Try to load dialect module from various configured options.
* Priority goes like dialectModulePath > dialectModule > require(default) * Priority goes like dialectModulePath > dialectModule > require(default)
* *
* @param {String} moduleName Name of dialect module to lookup * @param {string} moduleName Name of dialect module to lookup
* *
* @private * @private
* @returns {Object} * @returns {Object}
......
...@@ -493,7 +493,7 @@ class QueryGenerator { ...@@ -493,7 +493,7 @@ class QueryGenerator {
options.prefix = options.prefix || rawTablename || tableName; options.prefix = options.prefix || rawTablename || tableName;
if (options.prefix && typeof options.prefix === 'string') { if (options.prefix && typeof options.prefix === 'string') {
options.prefix = options.prefix.replace(/\./g, '_'); options.prefix = options.prefix.replace(/\./g, '_');
options.prefix = options.prefix.replace(/(\"|\')/g, ''); options.prefix = options.prefix.replace(/("|')/g, '');
} }
const fieldsSql = options.fields.map(field => { const fieldsSql = options.fields.map(field => {
...@@ -859,11 +859,8 @@ class QueryGenerator { ...@@ -859,11 +859,8 @@ class QueryGenerator {
/** /**
* Split a list of identifiers by "." and quote each part * Split a list of identifiers by "." and quote each part
* *
* @param {string} dialect Dialect name * @param {string} identifier
* @param {string} identifiers * @param {boolean} force
* @param {Object} [options]
* @param {boolean} [options.force=false]
* @param {boolean} [options.quoteIdentifiers=true]
* *
* @returns {string} * @returns {string}
*/ */
...@@ -897,8 +894,8 @@ class QueryGenerator { ...@@ -897,8 +894,8 @@ class QueryGenerator {
/** /**
* Quote table name with optional alias and schema attribution * Quote table name with optional alias and schema attribution
* *
* @param {String|Object} param table string or object * @param {string|Object} param table string or object
* @param {String|Boolean} alias alias name * @param {string|boolean} alias alias name
* *
* @returns {string} * @returns {string}
*/ */
...@@ -1035,7 +1032,7 @@ class QueryGenerator { ...@@ -1035,7 +1032,7 @@ class QueryGenerator {
* Generates an SQL query that extract JSON property of given path. * Generates an SQL query that extract JSON property of given path.
* *
* @param {string} column The JSON column * @param {string} column The JSON column
* @param {String|Array<String>} [path] The path to extract (optional) * @param {string|Array<string>} [path] The path to extract (optional)
* @returns {string} The generated sql query * @returns {string} The generated sql query
* @private * @private
*/ */
...@@ -1830,7 +1827,7 @@ class QueryGenerator { ...@@ -1830,7 +1827,7 @@ class QueryGenerator {
topLevelInfo.options.where[`__${includeAs.internalAs}`] = this.sequelize.literal([ topLevelInfo.options.where[`__${includeAs.internalAs}`] = this.sequelize.literal([
'(', '(',
query.replace(/\;$/, ''), query.replace(/;$/, ''),
')', ')',
'IS NOT NULL' 'IS NOT NULL'
].join(' ')); ].join(' '));
...@@ -1910,10 +1907,9 @@ class QueryGenerator { ...@@ -1910,10 +1907,9 @@ class QueryGenerator {
} }
/** /**
* Returns an SQL fragment for adding result constraints * Returns an SQL fragment for adding result constraints.
* *
* @param {Object} options An object with selectQuery options. * @param {Object} options An object with selectQuery options.
* @param {Object} options The model passed to the selectQuery.
* @returns {string} The generated sql query. * @returns {string} The generated sql query.
* @private * @private
*/ */
......
...@@ -65,7 +65,7 @@ function quoteIdentifier(dialect, identifier, options) { ...@@ -65,7 +65,7 @@ function quoteIdentifier(dialect, identifier, options) {
} }
return Utils.addTicks(rawIdentifier, '"'); return Utils.addTicks(rawIdentifier, '"');
case 'mssql': case 'mssql':
return `[${identifier.replace(/[\[\]']+/g, '')}]`; return `[${identifier.replace(/[[\]']+/g, '')}]`;
default: default:
throw new Error(`Dialect "${dialect}" is not supported`); throw new Error(`Dialect "${dialect}" is not supported`);
...@@ -78,7 +78,7 @@ module.exports.quoteIdentifier = quoteIdentifier; ...@@ -78,7 +78,7 @@ module.exports.quoteIdentifier = quoteIdentifier;
* *
* @param {string} identifier * @param {string} identifier
* *
* @returns Boolean * @returns {boolean}
* @private * @private
*/ */
function isIdentifierQuoted(identifier) { function isIdentifierQuoted(identifier) {
......
...@@ -27,7 +27,6 @@ const TransactionQueries = { ...@@ -27,7 +27,6 @@ const TransactionQueries = {
* Returns a query that starts a transaction. * Returns a query that starts a transaction.
* *
* @param {Transaction} transaction * @param {Transaction} transaction
* @param {Object} options An object with options.
* @returns {string} The generated sql query. * @returns {string} The generated sql query.
* @private * @private
*/ */
...@@ -40,14 +39,6 @@ const TransactionQueries = { ...@@ -40,14 +39,6 @@ const TransactionQueries = {
return 'START TRANSACTION;'; return 'START TRANSACTION;';
}, },
/**
* Returns a query that defers the constraints. Only works for postgres.
*
* @param {Transaction} transaction
* @param {Object} options An object with options.
* @returns {string} The generated sql query.
* @private
*/
deferConstraintsQuery() {}, deferConstraintsQuery() {},
setConstraintQuery() {}, setConstraintQuery() {},
...@@ -57,7 +48,7 @@ const TransactionQueries = { ...@@ -57,7 +48,7 @@ const TransactionQueries = {
/** /**
* Returns a query that commits a transaction. * Returns a query that commits a transaction.
* *
* @param {Object} options An object with options. * @param {Transaction} transaction An object with options.
* @returns {string} The generated sql query. * @returns {string} The generated sql query.
* @private * @private
*/ */
...@@ -73,7 +64,6 @@ const TransactionQueries = { ...@@ -73,7 +64,6 @@ const TransactionQueries = {
* Returns a query that rollbacks a transaction. * Returns a query that rollbacks a transaction.
* *
* @param {Transaction} transaction * @param {Transaction} transaction
* @param {Object} options An object with options.
* @returns {string} The generated sql query. * @returns {string} The generated sql query.
* @private * @private
*/ */
...@@ -87,4 +77,4 @@ const TransactionQueries = { ...@@ -87,4 +77,4 @@ const TransactionQueries = {
} }
}; };
module.exports = TransactionQueries; module.exports = TransactionQueries;
\ No newline at end of file
...@@ -14,6 +14,7 @@ class AbstractQuery { ...@@ -14,6 +14,7 @@ class AbstractQuery {
this.model = options.model; this.model = options.model;
this.sequelize = sequelize; this.sequelize = sequelize;
this.options = Object.assign({ this.options = Object.assign({
// eslint-disable-next-line no-console
logging: console.log, logging: console.log,
plain: false, plain: false,
raw: false raw: false
...@@ -34,6 +35,12 @@ class AbstractQuery { ...@@ -34,6 +35,12 @@ class AbstractQuery {
* Options * Options
* skipUnescape: bool, skip unescaping $$ * skipUnescape: bool, skip unescaping $$
* skipValueReplace: bool, do not replace (but do unescape $$). Check correct syntax and if all values are available * skipValueReplace: bool, do not replace (but do unescape $$). Check correct syntax and if all values are available
*
* @param {string} sql
* @param {Object|Array} values
* @param {string} dialect
* @param {Function} [replacementFunc]
* @param {Object} [options]
* @private * @private
*/ */
static formatBindParameters(sql, values, dialect, replacementFunc, options) { static formatBindParameters(sql, values, dialect, replacementFunc, options) {
...@@ -105,7 +112,6 @@ class AbstractQuery { ...@@ -105,7 +112,6 @@ class AbstractQuery {
* *
* query.run('SELECT 1') * query.run('SELECT 1')
* *
* @param {string} sql - The SQL query which should be executed.
* @private * @private
*/ */
run() { run() {
...@@ -115,12 +121,12 @@ class AbstractQuery { ...@@ -115,12 +121,12 @@ class AbstractQuery {
/** /**
* Check the logging option of the instance and print deprecation warnings. * Check the logging option of the instance and print deprecation warnings.
* *
* @returns {void}
* @private * @private
*/ */
checkLoggingOption() { checkLoggingOption() {
if (this.options.logging === true) { if (this.options.logging === true) {
logger.deprecate('The logging-option should be either a function or false. Default: console.log'); logger.deprecate('The logging-option should be either a function or false. Default: console.log');
// eslint-disable-next-line no-console
this.options.logging = console.log; this.options.logging = console.log;
} }
} }
...@@ -349,6 +355,10 @@ class AbstractQuery { ...@@ -349,6 +355,10 @@ class AbstractQuery {
* ] * ]
* } * }
* ] * ]
*
* @param {Array} rows
* @param {Object} includeOptions
* @param {Object} options
* @private * @private
*/ */
static _groupJoinData(rows, includeOptions, options) { static _groupJoinData(rows, includeOptions, options) {
......
...@@ -47,9 +47,10 @@ class ConnectionManager extends AbstractConnectionManager { ...@@ -47,9 +47,10 @@ class ConnectionManager extends AbstractConnectionManager {
/** /**
* Connect with MariaDB database based on config, Handle any errors in connection * Connect with MariaDB database based on config, Handle any errors in connection
* Set the pool handlers on connection.error * Set the pool handlers on connection.error
* Also set proper timezone once connection is connected * Also set proper timezone once connection is connected.
* *
* @returns Promise<Connection> * @param {Object} config
* @returns {Promise<Connection>}
* @private * @private
*/ */
connect(config) { connect(config) {
......
...@@ -73,7 +73,7 @@ module.exports = BaseTypes => { ...@@ -73,7 +73,7 @@ module.exports = BaseTypes => {
class DATEONLY extends BaseTypes.DATEONLY { class DATEONLY extends BaseTypes.DATEONLY {
static parse(value) { static parse(value) {
return value.string(); return value.string();
}; }
} }
class UUID extends BaseTypes.UUID { class UUID extends BaseTypes.UUID {
......
...@@ -39,7 +39,7 @@ class MariaDBQueryGenerator extends MySQLQueryGenerator { ...@@ -39,7 +39,7 @@ class MariaDBQueryGenerator extends MySQLQueryGenerator {
const conditions = this.parseConditionObject(smth.conditions).map( const conditions = this.parseConditionObject(smth.conditions).map(
condition => condition =>
`json_unquote(json_extract(${this.quoteIdentifier( `json_unquote(json_extract(${this.quoteIdentifier(
condition.path[0])},'\$.${_.tail(condition.path).join( condition.path[0])},'$.${_.tail(condition.path).join(
'.')}')) = '${condition.value}'` '.')}')) = '${condition.value}'`
); );
...@@ -73,7 +73,7 @@ class MariaDBQueryGenerator extends MySQLQueryGenerator { ...@@ -73,7 +73,7 @@ class MariaDBQueryGenerator extends MySQLQueryGenerator {
} }
str = `json_unquote(json_extract(${this.quoteIdentifier( str = `json_unquote(json_extract(${this.quoteIdentifier(
columnName)},'\$${startWithDot ? '.' : ''}${path.join('.')}'))`; columnName)},'$${startWithDot ? '.' : ''}${path.join('.')}'))`;
} }
if (smth.value) { if (smth.value) {
......
...@@ -7,7 +7,8 @@ module.exports = BaseTypes => { ...@@ -7,7 +7,8 @@ module.exports = BaseTypes => {
/** /**
* Removes unsupported MSSQL options, i.e., LENGTH, UNSIGNED and ZEROFILL, for the integer data types. * Removes unsupported MSSQL options, i.e., LENGTH, UNSIGNED and ZEROFILL, for the integer data types.
* @param dataType The base integer data type. *
* @param {Object} dataType The base integer data type.
* @private * @private
*/ */
function removeUnsupportedIntegerOptions(dataType) { function removeUnsupportedIntegerOptions(dataType) {
...@@ -127,7 +128,7 @@ module.exports = BaseTypes => { ...@@ -127,7 +128,7 @@ module.exports = BaseTypes => {
class DATEONLY extends BaseTypes.DATEONLY { class DATEONLY extends BaseTypes.DATEONLY {
static parse(value) { static parse(value) {
return moment(value).format('YYYY-MM-DD'); return moment(value).format('YYYY-MM-DD');
}; }
} }
class INTEGER extends BaseTypes.INTEGER { class INTEGER extends BaseTypes.INTEGER {
......
...@@ -252,10 +252,10 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator { ...@@ -252,10 +252,10 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator {
commentTemplate(comment, table, column) { commentTemplate(comment, table, column) {
return ' EXEC sp_addextendedproperty ' + return ' EXEC sp_addextendedproperty ' +
`@name = N\'MS_Description\', @value = ${this.escape(comment)}, ` + `@name = N'MS_Description', @value = ${this.escape(comment)}, ` +
'@level0type = N\'Schema\', @level0name = \'dbo\', ' + '@level0type = N\'Schema\', @level0name = \'dbo\', ' +
`@level1type = N\'Table\', @level1name = ${this.quoteIdentifier(table)}, ` + `@level1type = N'Table', @level1name = ${this.quoteIdentifier(table)}, ` +
`@level2type = N\'Column\', @level2name = ${this.quoteIdentifier(column)};`; `@level2type = N'Column', @level2name = ${this.quoteIdentifier(column)};`;
} }
removeColumnQuery(tableName, attributeName) { removeColumnQuery(tableName, attributeName) {
...@@ -662,6 +662,8 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator { ...@@ -662,6 +662,8 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator {
/** /**
* Generate common SQL prefix for ForeignKeysQuery. * Generate common SQL prefix for ForeignKeysQuery.
*
* @param {string} catalogName
* @returns {string} * @returns {string}
*/ */
_getForeignKeysQueryPrefix(catalogName) { _getForeignKeysQueryPrefix(catalogName) {
...@@ -688,7 +690,8 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator { ...@@ -688,7 +690,8 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator {
/** /**
* Generates an SQL query that returns all foreign keys details of a table. * Generates an SQL query that returns all foreign keys details of a table.
* @param {Stirng|Object} table *
* @param {string|Object} table
* @param {string} catalogName database name * @param {string} catalogName database name
* @returns {string} * @returns {string}
*/ */
...@@ -878,7 +881,7 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator { ...@@ -878,7 +881,7 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator {
booleanValue(value) { booleanValue(value) {
return value ? 1 : 0; return value ? 1 : 0;
} }
}; }
// private methods // private methods
function wrapSingleQuote(identifier) { function wrapSingleQuote(identifier) {
......
...@@ -12,10 +12,11 @@ ...@@ -12,10 +12,11 @@
A wrapper that fixes MSSQL's inability to cleanly remove columns from existing tables if they have a default constraint. A wrapper that fixes MSSQL's inability to cleanly remove columns from existing tables if they have a default constraint.
@param {QueryInterface} qi
@param {string} tableName The name of the table. @param {string} tableName The name of the table.
@param {string} attributeName The name of the attribute that we want to remove. @param {string} attributeName The name of the attribute that we want to remove.
@param {Object} options @param {Object} options
@param {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries @param {boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
@private @private
*/ */
......
...@@ -72,7 +72,6 @@ class Query extends AbstractQuery { ...@@ -72,7 +72,6 @@ class Query extends AbstractQuery {
} }
resolve(this.formatResults()); resolve(this.formatResults());
}, this.options.transaction.name); }, this.options.transaction.name);
return;
} }
if (this.sql.startsWith('SAVE TRANSACTION')) { if (this.sql.startsWith('SAVE TRANSACTION')) {
return connection.saveTransaction(err => { return connection.saveTransaction(err => {
...@@ -148,7 +147,10 @@ class Query extends AbstractQuery { ...@@ -148,7 +147,10 @@ class Query extends AbstractQuery {
/** /**
* High level function that handles the results of a query execution. * High level function that handles the results of a query execution.
* *
* * @param {Array} data - The result of the query execution.
* @param {number} rowCount
* @private
* @example
* Example: * Example:
* query.formatResults([ * query.formatResults([
* { * {
...@@ -158,9 +160,6 @@ class Query extends AbstractQuery { ...@@ -158,9 +160,6 @@ class Query extends AbstractQuery {
* Tasks.title: 'task' // this is from the associated table * Tasks.title: 'task' // this is from the associated table
* } * }
* ]) * ])
*
* @param {Array} data - The result of the query execution.
* @private
*/ */
formatResults(data, rowCount) { formatResults(data, rowCount) {
let result = this.instance; let result = this.instance;
......
...@@ -47,9 +47,10 @@ class ConnectionManager extends AbstractConnectionManager { ...@@ -47,9 +47,10 @@ class ConnectionManager extends AbstractConnectionManager {
/** /**
* Connect with MySQL database based on config, Handle any errors in connection * Connect with MySQL database based on config, Handle any errors in connection
* Set the pool handlers on connection.error * Set the pool handlers on connection.error
* Also set proper timezone once connection is connected * Also set proper timezone once connection is connected.
* *
* @returns Promise<Connection> * @param {Object} config
* @returns {Promise<Connection>}
* @private * @private
*/ */
connect(config) { connect(config) {
......
...@@ -209,7 +209,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator { ...@@ -209,7 +209,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
// Parse nested object // Parse nested object
if (smth.conditions) { if (smth.conditions) {
const conditions = this.parseConditionObject(smth.conditions).map(condition => const conditions = this.parseConditionObject(smth.conditions).map(condition =>
`${this.quoteIdentifier(condition.path[0])}->>'\$.${_.tail(condition.path).join('.')}' = '${condition.value}'` `${this.quoteIdentifier(condition.path[0])}->>'$.${_.tail(condition.path).join('.')}' = '${condition.value}'`
); );
return conditions.join(' and '); return conditions.join(' and ');
...@@ -241,7 +241,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator { ...@@ -241,7 +241,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
startWithDot = false; startWithDot = false;
} }
str = `${this.quoteIdentifier(columnName)}->>'\$${startWithDot ? '.' : ''}${path.join('.')}'`; str = `${this.quoteIdentifier(columnName)}->>'$${startWithDot ? '.' : ''}${path.join('.')}'`;
} }
if (smth.value) { if (smth.value) {
...@@ -499,7 +499,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator { ...@@ -499,7 +499,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
/** /**
* Generates an SQL query that returns all foreign keys of a table. * Generates an SQL query that returns all foreign keys of a table.
* *
* @param {string} tableName The name of the table. * @param {Object} table The table.
* @param {string} schemaName The name of the schema. * @param {string} schemaName The name of the schema.
* @returns {string} The generated sql query. * @returns {string} The generated sql query.
* @private * @private
...@@ -512,7 +512,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator { ...@@ -512,7 +512,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
/** /**
* Generates an SQL query that returns the foreign key constraint of a given column. * Generates an SQL query that returns the foreign key constraint of a given column.
* *
* @param {string} tableName The name of the table. * @param {Object} table The table.
* @param {string} columnName The name of the column. * @param {string} columnName The name of the column.
* @returns {string} The generated sql query. * @returns {string} The generated sql query.
* @private * @private
...@@ -526,7 +526,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator { ...@@ -526,7 +526,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
+ ` WHERE (REFERENCED_TABLE_NAME = ${quotedTableName}${table.schema + ` WHERE (REFERENCED_TABLE_NAME = ${quotedTableName}${table.schema
? ` AND REFERENCED_TABLE_SCHEMA = ${quotedSchemaName}` ? ` AND REFERENCED_TABLE_SCHEMA = ${quotedSchemaName}`
: ''} AND REFERENCED_COLUMN_NAME = ${quotedColumnName})` : ''} AND REFERENCED_COLUMN_NAME = ${quotedColumnName})`
+ ` OR (TABLE_NAME = ${quotedTableName}${table.schema ? + ` OR (TABLE_NAME = ${quotedTableName}${table.schema ?
` AND TABLE_SCHEMA = ${quotedSchemaName}` : ''} AND COLUMN_NAME = ${quotedColumnName} AND REFERENCED_TABLE_NAME IS NOT NULL)`; ` AND TABLE_SCHEMA = ${quotedSchemaName}` : ''} AND COLUMN_NAME = ${quotedColumnName} AND REFERENCED_TABLE_NAME IS NOT NULL)`;
} }
...@@ -539,7 +539,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator { ...@@ -539,7 +539,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
* @private * @private
*/ */
dropForeignKeyQuery(tableName, foreignKey) { dropForeignKeyQuery(tableName, foreignKey) {
return `ALTER TABLE ${this.quoteTable(tableName)} return `ALTER TABLE ${this.quoteTable(tableName)}
DROP FOREIGN KEY ${this.quoteIdentifier(foreignKey)};`; DROP FOREIGN KEY ${this.quoteIdentifier(foreignKey)};`;
} }
} }
......
...@@ -14,6 +14,7 @@ const sequelizeErrors = require('../../errors'); ...@@ -14,6 +14,7 @@ const sequelizeErrors = require('../../errors');
/** /**
A wrapper that fixes MySQL's inability to cleanly remove columns from existing tables if they have a foreign key constraint. A wrapper that fixes MySQL's inability to cleanly remove columns from existing tables if they have a foreign key constraint.
@param {QueryInterface} qi
@param {string} tableName The name of the table. @param {string} tableName The name of the table.
@param {string} columnName The name of the attribute that we want to remove. @param {string} columnName The name of the attribute that we want to remove.
@param {Object} options @param {Object} options
......
...@@ -274,8 +274,8 @@ class ConnectionManager extends AbstractConnectionManager { ...@@ -274,8 +274,8 @@ class ConnectionManager extends AbstractConnectionManager {
if (row.rngtypid) { if (row.rngtypid) {
newNameOidMap[row.typname].rangeOid = row.rngtypid; newNameOidMap[row.typname].rangeOid = row.rngtypid;
if (row.rngtyparray) newNameOidMap[row.typname].arrayRangeOid = row.rngtyparray; if (row.rngtyparray) newNameOidMap[row.typname].arrayRangeOid = row.rngtyparray;
}; }
}; }
// Replace all OID mappings. Avoids temporary empty OID mappings. // Replace all OID mappings. Avoids temporary empty OID mappings.
this.nameOidMap = newNameOidMap; this.nameOidMap = newNameOidMap;
......
...@@ -8,7 +8,8 @@ module.exports = BaseTypes => { ...@@ -8,7 +8,8 @@ module.exports = BaseTypes => {
/** /**
* Removes unsupported Postgres options, i.e., LENGTH, UNSIGNED and ZEROFILL, for the integer data types. * Removes unsupported Postgres options, i.e., LENGTH, UNSIGNED and ZEROFILL, for the integer data types.
* @param dataType The base integer data type. *
* @param {Object} dataType The base integer data type.
* @private * @private
*/ */
function removeUnsupportedIntegerOptions(dataType) { function removeUnsupportedIntegerOptions(dataType) {
...@@ -494,7 +495,7 @@ module.exports = BaseTypes => { ...@@ -494,7 +495,7 @@ module.exports = BaseTypes => {
class ENUM extends BaseTypes.ENUM { class ENUM extends BaseTypes.ENUM {
static parse(value) { static parse(value) {
return value; return value;
}; }
} }
BaseTypes.ENUM.types.postgres = [null]; BaseTypes.ENUM.types.postgres = [null];
......
...@@ -837,6 +837,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator { ...@@ -837,6 +837,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
/** /**
* Generate common SQL prefix for getForeignKeyReferencesQuery. * Generate common SQL prefix for getForeignKeyReferencesQuery.
*
* @returns {string} * @returns {string}
*/ */
_getForeignKeyReferencesQueryPrefix() { _getForeignKeyReferencesQueryPrefix() {
...@@ -863,6 +864,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator { ...@@ -863,6 +864,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
* Generates an SQL query that returns all foreign keys details of a table. * Generates an SQL query that returns all foreign keys details of a table.
* *
* As for getForeignKeysQuery is not compatible with getForeignKeyReferencesQuery, so add a new function. * As for getForeignKeysQuery is not compatible with getForeignKeyReferencesQuery, so add a new function.
*
* @param {string} tableName * @param {string} tableName
* @param {string} catalogName * @param {string} catalogName
* @param {string} schemaName * @param {string} schemaName
...@@ -893,6 +895,6 @@ class PostgresQueryGenerator extends AbstractQueryGenerator { ...@@ -893,6 +895,6 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
dropForeignKeyQuery(tableName, foreignKey) { dropForeignKeyQuery(tableName, foreignKey) {
return `ALTER TABLE ${this.quoteTable(tableName)} DROP CONSTRAINT ${this.quoteIdentifier(foreignKey)};`; return `ALTER TABLE ${this.quoteTable(tableName)} DROP CONSTRAINT ${this.quoteIdentifier(foreignKey)};`;
} }
}; }
module.exports = PostgresQueryGenerator; module.exports = PostgresQueryGenerator;
...@@ -15,11 +15,12 @@ const _ = require('lodash'); ...@@ -15,11 +15,12 @@ const _ = require('lodash');
*/ */
/** /**
* Ensure enum and their values * Ensure enum and their values.
* *
* @param {QueryInterface} qi
* @param {string} tableName Name of table to create * @param {string} tableName Name of table to create
* @param {Object} attributes Object representing a list of normalized table attributes * @param {Object} attributes Object representing a list of normalized table attributes
* @param {Object} [attributes] * @param {Object} [options]
* @param {Model} [model] * @param {Model} [model]
* *
* @returns {Promise} * @returns {Promise}
......
...@@ -10,7 +10,11 @@ const _ = require('lodash'); ...@@ -10,7 +10,11 @@ const _ = require('lodash');
class Query extends AbstractQuery { class Query extends AbstractQuery {
/** /**
* rewrite query with parameters * Rewrite query with parameters.
*
* @param {string} sql
* @param {Array|Object} values
* @param {string} dialect
* @private * @private
*/ */
static formatBindParameters(sql, values, dialect) { static formatBindParameters(sql, values, dialect) {
...@@ -283,9 +287,9 @@ class Query extends AbstractQuery { ...@@ -283,9 +287,9 @@ class Query extends AbstractQuery {
switch (code) { switch (code) {
case '23503': case '23503':
index = errMessage.match(/violates foreign key constraint \"(.+?)\"/); index = errMessage.match(/violates foreign key constraint "(.+?)"/);
index = index ? index[1] : undefined; index = index ? index[1] : undefined;
table = errMessage.match(/on table \"(.+?)\"/); table = errMessage.match(/on table "(.+?)"/);
table = table ? table[1] : undefined; table = table ? table[1] : undefined;
return new sequelizeErrors.ForeignKeyConstraintError({ message: errMessage, fields: null, index, table, parent: err }); return new sequelizeErrors.ForeignKeyConstraintError({ message: errMessage, fields: null, index, table, parent: err });
...@@ -344,9 +348,9 @@ class Query extends AbstractQuery { ...@@ -344,9 +348,9 @@ class Query extends AbstractQuery {
case '42704': case '42704':
if (err.sql && /(CONSTRAINT|INDEX)/gi.test(err.sql)) { if (err.sql && /(CONSTRAINT|INDEX)/gi.test(err.sql)) {
message = 'Unknown constraint error'; message = 'Unknown constraint error';
index = errMessage.match(/(?:constraint|index) \"(.+?)\"/i); index = errMessage.match(/(?:constraint|index) "(.+?)"/i);
index = index ? index[1] : undefined; index = index ? index[1] : undefined;
table = errMessage.match(/relation \"(.+?)\"/i); table = errMessage.match(/relation "(.+?)"/i);
table = table ? table[1] : undefined; table = table ? table[1] : undefined;
throw new sequelizeErrors.UnknownConstraintError({ throw new sequelizeErrors.UnknownConstraintError({
...@@ -357,7 +361,7 @@ class Query extends AbstractQuery { ...@@ -357,7 +361,7 @@ class Query extends AbstractQuery {
parent: err parent: err
}); });
} }
// falls through
default: default:
return new sequelizeErrors.DatabaseError(err); return new sequelizeErrors.DatabaseError(err);
} }
......
...@@ -5,7 +5,8 @@ module.exports = BaseTypes => { ...@@ -5,7 +5,8 @@ module.exports = BaseTypes => {
/** /**
* Removes unsupported SQLite options, i.e., UNSIGNED and ZEROFILL, for the integer data types. * Removes unsupported SQLite options, i.e., UNSIGNED and ZEROFILL, for the integer data types.
* @param dataType The base integer data type. *
* @param {Object} dataType The base integer data type.
* @private * @private
*/ */
function removeUnsupportedIntegerOptions(dataType) { function removeUnsupportedIntegerOptions(dataType) {
...@@ -177,12 +178,12 @@ module.exports = BaseTypes => { ...@@ -177,12 +178,12 @@ module.exports = BaseTypes => {
} }
for (const floating of [FLOAT, DOUBLE, REAL]) { for (const floating of [FLOAT, DOUBLE, REAL]) {
floating.parse = parseFloating; floating.parse = parseFloating;
}; }
for (const num of [FLOAT, DOUBLE, REAL, TINYINT, SMALLINT, MEDIUMINT, INTEGER, BIGINT]) { for (const num of [FLOAT, DOUBLE, REAL, TINYINT, SMALLINT, MEDIUMINT, INTEGER, BIGINT]) {
num.prototype.toSql = NUMBER.prototype.toSql; num.prototype.toSql = NUMBER.prototype.toSql;
}; }
class ENUM extends BaseTypes.ENUM { class ENUM extends BaseTypes.ENUM {
toSql() { toSql() {
......
...@@ -498,6 +498,6 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator { ...@@ -498,6 +498,6 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator {
getForeignKeysQuery(tableName) { getForeignKeysQuery(tableName) {
return `PRAGMA foreign_key_list(${tableName})`; return `PRAGMA foreign_key_list(${tableName})`;
} }
}; }
module.exports = SQLiteQueryGenerator; module.exports = SQLiteQueryGenerator;
...@@ -22,7 +22,7 @@ const QueryTypes = require('../../query-types'); ...@@ -22,7 +22,7 @@ const QueryTypes = require('../../query-types');
@param {string} tableName The name of the table. @param {string} tableName The name of the table.
@param {string} attributeName The name of the attribute that we want to remove. @param {string} attributeName The name of the attribute that we want to remove.
@param {Object} options @param {Object} options
@param {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries @param {boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
@since 1.6.0 @since 1.6.0
@private @private
...@@ -50,7 +50,7 @@ exports.removeColumn = removeColumn; ...@@ -50,7 +50,7 @@ exports.removeColumn = removeColumn;
@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} attributes An object with the attribute's name as key and its options as value object.
@param {Object} options @param {Object} options
@param {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries @param {boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
@since 1.6.0 @since 1.6.0
@private @private
...@@ -80,7 +80,7 @@ exports.changeColumn = changeColumn; ...@@ -80,7 +80,7 @@ exports.changeColumn = changeColumn;
@param {string} attrNameBefore The name of the attribute before it was renamed. @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} attrNameAfter The name of the attribute after it was renamed.
@param {Object} options @param {Object} options
@param {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries @param {boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
@since 1.6.0 @since 1.6.0
@private @private
...@@ -102,6 +102,10 @@ exports.renameColumn = renameColumn; ...@@ -102,6 +102,10 @@ exports.renameColumn = renameColumn;
/** /**
* @param {QueryInterface} qi * @param {QueryInterface} qi
* @param {string} tableName
* @param {string} constraintName
* @param {Object} options
*
* @private * @private
*/ */
function removeConstraint(qi, tableName, constraintName, options) { function removeConstraint(qi, tableName, constraintName, options) {
...@@ -147,6 +151,9 @@ exports.removeConstraint = removeConstraint; ...@@ -147,6 +151,9 @@ exports.removeConstraint = removeConstraint;
/** /**
* @param {QueryInterface} qi * @param {QueryInterface} qi
* @param {string} tableName
* @param {Object} options
*
* @private * @private
*/ */
function addConstraint(qi, tableName, options) { function addConstraint(qi, tableName, options) {
......
...@@ -16,7 +16,11 @@ class Query extends AbstractQuery { ...@@ -16,7 +16,11 @@ class Query extends AbstractQuery {
} }
/** /**
* rewrite query with parameters * rewrite query with parameters.
*
* @param {string} sql
* @param {Array|Object} values
* @param {string} dialect
* @private * @private
*/ */
static formatBindParameters(sql, values, dialect) { static formatBindParameters(sql, values, dialect) {
...@@ -346,7 +350,7 @@ class Query extends AbstractQuery { ...@@ -346,7 +350,7 @@ class Query extends AbstractQuery {
constraintType: constraint[1], constraintType: constraint[1],
updateAction, updateAction,
deleteAction, deleteAction,
sql: sql.replace(/\"/g, '\`'), //Sqlite returns double quotes for table name sql: sql.replace(/"/g, '`'), //Sqlite returns double quotes for table name
constraintCondition, constraintCondition,
referenceTableName, referenceTableName,
referenceTableKeys referenceTableKeys
......
...@@ -65,7 +65,7 @@ const getProxiedHooks = hookType => ...@@ -65,7 +65,7 @@ const getProxiedHooks = hookType =>
function getHooks(hooked, hookType) { function getHooks(hooked, hookType) {
return (hooked.options.hooks || {})[hookType] || []; return (hooked.options.hooks || {})[hookType] || [];
}; }
const Hooks = { const Hooks = {
/** /**
......
...@@ -25,8 +25,6 @@ const Op = require('./operators'); ...@@ -25,8 +25,6 @@ const Op = require('./operators');
/** /**
* This is the main class, the entry point to sequelize. * This is the main class, the entry point to sequelize.
*
* @class Sequelize
*/ */
class Sequelize { class Sequelize {
/** /**
...@@ -59,7 +57,7 @@ class Sequelize { ...@@ -59,7 +57,7 @@ class Sequelize {
* @param {string} [options.password=null] The password which is used to authenticate against the database. * @param {string} [options.password=null] The password which is used to authenticate against the database.
* @param {string} [options.database=null] The name of the database * @param {string} [options.database=null] The name of the database
* @param {string} [options.dialect] The dialect of the database you are connecting to. One of mysql, postgres, sqlite and mssql. * @param {string} [options.dialect] The dialect of the database you are connecting to. One of mysql, postgres, sqlite and mssql.
* @param {String} [options.dialectModule=null] If specified, use this dialect library. For example, if you want to use pg.js instead of pg when connecting to a pg database, you should specify 'require("pg.js")' here * @param {string} [options.dialectModule=null] If specified, use this dialect library. For example, if you want to use pg.js instead of pg when connecting to a pg database, you should specify 'require("pg.js")' here
* @param {string} [options.dialectModulePath=null] If specified, load the dialect library from this path. For example, if you want to use pg.js instead of pg when connecting to a pg database, you should specify '/path/to/pg.js' here * @param {string} [options.dialectModulePath=null] If specified, load the dialect library from this path. For example, if you want to use pg.js instead of pg when connecting to a pg database, you should specify '/path/to/pg.js' here
* @param {Object} [options.dialectOptions] An object of additional options, which are passed directly to the connection library * @param {Object} [options.dialectOptions] An object of additional options, which are passed directly to the connection library
* @param {string} [options.storage] Only used by sqlite. Defaults to ':memory:' * @param {string} [options.storage] Only used by sqlite. Defaults to ':memory:'
...@@ -158,6 +156,7 @@ class Sequelize { ...@@ -158,6 +156,7 @@ class Sequelize {
sync: {}, sync: {},
timezone: '+00:00', timezone: '+00:00',
clientMinMessages: 'warning', clientMinMessages: 'warning',
// eslint-disable-next-line no-console
logging: console.log, logging: console.log,
omitNull: false, omitNull: false,
native: false, native: false,
...@@ -193,6 +192,7 @@ class Sequelize { ...@@ -193,6 +192,7 @@ class Sequelize {
if (this.options.logging === true) { if (this.options.logging === true) {
logger.deprecate('The logging-option should be either a function or false. Default: console.log'); logger.deprecate('The logging-option should be either a function or false. Default: console.log');
// eslint-disable-next-line no-console
this.options.logging = console.log; this.options.logging = console.log;
} }
...@@ -319,9 +319,11 @@ class Sequelize { ...@@ -319,9 +319,11 @@ class Sequelize {
* @param {Object} attributes An object, where each attribute is a column of the table. See {@link Model.init} * @param {Object} attributes An object, where each attribute is a column of the table. See {@link Model.init}
* @param {Object} [options] These options are merged with the default define options provided to the Sequelize constructor and passed to Model.init() * @param {Object} [options] These options are merged with the default define options provided to the Sequelize constructor and passed to Model.init()
* *
* @see {@link Model.init} for a more comprehensive specification of the `options` and `attributes` objects. * @see
* {@link Model.init} for a more comprehensive specification of the `options` and `attributes` objects.
* @see <a href="/manual/tutorial/models-definition.html">Model definition</a> Manual related to model definition * @see <a href="/manual/tutorial/models-definition.html">Model definition</a> Manual related to model definition
* @see {@link DataTypes} For a list of possible data types * @see
* {@link DataTypes} For a list of possible data types
* *
* @returns {Model} Newly defined model * @returns {Model} Newly defined model
* *
...@@ -475,6 +477,7 @@ class Sequelize { ...@@ -475,6 +477,7 @@ class Sequelize {
} }
options = _.defaults(options, { options = _.defaults(options, {
// eslint-disable-next-line no-console
logging: this.options.hasOwnProperty('logging') ? this.options.logging : console.log, logging: this.options.hasOwnProperty('logging') ? this.options.logging : console.log,
searchPath: this.options.hasOwnProperty('searchPath') ? this.options.searchPath : 'DEFAULT' searchPath: this.options.hasOwnProperty('searchPath') ? this.options.searchPath : 'DEFAULT'
}); });
...@@ -557,7 +560,7 @@ class Sequelize { ...@@ -557,7 +560,7 @@ class Sequelize {
} }
if (options.transaction && options.transaction.finished) { if (options.transaction && options.transaction.finished) {
const error = new Error(`${options.transaction.finished} has been called on this transaction(${options.transaction.id}), you can no longer use it. (The rejected query is attached as the \'sql\' property of this error)`); const error = new Error(`${options.transaction.finished} has been called on this transaction(${options.transaction.id}), you can no longer use it. (The rejected query is attached as the 'sql' property of this error)`);
error.sql = sql; error.sql = sql;
throw error; throw error;
} }
...@@ -636,7 +639,8 @@ class Sequelize { ...@@ -636,7 +639,8 @@ class Sequelize {
* **Note:** this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), * **Note:** this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
* not a database table. In mysql and sqlite, this command will do nothing. * not a database table. In mysql and sqlite, this command will do nothing.
* *
* @see {@link Model.schema} * @see
* {@link Model.schema}
* *
* @param {string} schema Name of the schema * @param {string} schema Name of the schema
* @param {Object} [options={}] query options * @param {Object} [options={}] query options
...@@ -759,7 +763,8 @@ class Sequelize { ...@@ -759,7 +763,8 @@ class Sequelize {
* @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
* @returns {Promise} * @returns {Promise}
* *
* @see {@link Model.truncate} for more information * @see
* {@link Model.truncate} for more information
*/ */
truncate(options) { truncate(options) {
const models = []; const models = [];
...@@ -782,7 +787,8 @@ class Sequelize { ...@@ -782,7 +787,8 @@ class Sequelize {
* Drop all tables defined through this sequelize instance. * Drop all tables defined through this sequelize instance.
* This is done by calling Model.drop on each model. * This is done by calling Model.drop on each model.
* *
* @see {@link Model.drop} for options * @see
* {@link Model.drop} for options
* *
* @param {Object} [options] The options passed to each call to Model.drop * @param {Object} [options] The options passed to each call to Model.drop
* @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging * @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
...@@ -839,9 +845,12 @@ class Sequelize { ...@@ -839,9 +845,12 @@ class Sequelize {
* Creates an object representing a database function. This can be used in search queries, both in where and order parts, and as default values in column definitions. * Creates an object representing a database function. This can be used in search queries, both in where and order parts, and as default values in column definitions.
* If you want to refer to columns in your function, you should use `sequelize.col`, so that the columns are properly interpreted as columns and not a strings. * If you want to refer to columns in your function, you should use `sequelize.col`, so that the columns are properly interpreted as columns and not a strings.
* *
* @see {@link Model.findAll} * @see
* @see {@link Sequelize.define} * {@link Model.findAll}
* @see {@link Sequelize.col} * @see
* {@link Sequelize.define}
* @see
* {@link Sequelize.col}
* *
* @param {string} fn The function you want to call * @param {string} fn The function you want to call
* @param {any} args All further arguments will be passed as arguments to the function * @param {any} args All further arguments will be passed as arguments to the function
...@@ -862,7 +871,8 @@ class Sequelize { ...@@ -862,7 +871,8 @@ class Sequelize {
/** /**
* Creates an object which represents a column in the DB, this allows referencing another column in your query. This is often useful in conjunction with `sequelize.fn`, since raw string arguments to fn will be escaped. * Creates an object which represents a column in the DB, this allows referencing another column in your query. This is often useful in conjunction with `sequelize.fn`, since raw string arguments to fn will be escaped.
* *
* @see {@link Sequelize#fn} * @see
* {@link Sequelize#fn}
* *
* @param {string} col The name of the column * @param {string} col The name of the column
* @since v2.0.0-dev3 * @since v2.0.0-dev3
...@@ -904,7 +914,8 @@ class Sequelize { ...@@ -904,7 +914,8 @@ class Sequelize {
/** /**
* An AND query * An AND query
* *
* @see {@link Model.findAll} * @see
* {@link Model.findAll}
* *
* @param {...string|Object} args Each argument will be joined by AND * @param {...string|Object} args Each argument will be joined by AND
* @since v2.0.0-dev3 * @since v2.0.0-dev3
...@@ -919,7 +930,8 @@ class Sequelize { ...@@ -919,7 +930,8 @@ class Sequelize {
/** /**
* An OR query * An OR query
* *
* @see {@link Model.findAll} * @see
* {@link Model.findAll}
* *
* @param {...string|Object} args Each argument will be joined by OR * @param {...string|Object} args Each argument will be joined by OR
* @since v2.0.0-dev3 * @since v2.0.0-dev3
...@@ -934,7 +946,8 @@ class Sequelize { ...@@ -934,7 +946,8 @@ class Sequelize {
/** /**
* Creates an object representing nested where conditions for postgres/sqlite/mysql json data-type. * Creates an object representing nested where conditions for postgres/sqlite/mysql json data-type.
* *
* @see {@link Model.findAll} * @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|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>'". * @param {string|number|boolean} [value] An optional value to compare against. Produces a string of the form "<json path> = '<value>'".
...@@ -954,7 +967,8 @@ class Sequelize { ...@@ -954,7 +967,8 @@ class Sequelize {
* *
* For string attributes, use the regular `{ where: { attr: something }}` syntax. If you don't want your string to be escaped, use `sequelize.literal`. * For string attributes, use the regular `{ where: { attr: something }}` syntax. If you don't want your string to be escaped, use `sequelize.literal`.
* *
* @see {@link Model.findAll} * @see
* {@link Model.findAll}
* *
* @param {Object} attr The attribute, which can be either an attribute object from `Model.rawAttributes` or a sequelize object, for example an instance of `sequelize.fn`. For simple string attributes, use the POJO syntax * @param {Object} attr The attribute, which can be either an attribute object from `Model.rawAttributes` or a sequelize object, for example an instance of `sequelize.fn`. For simple string attributes, use the POJO syntax
* @param {Symbol} [comparator='Op.eq'] operator * @param {Symbol} [comparator='Op.eq'] operator
...@@ -1080,6 +1094,7 @@ class Sequelize { ...@@ -1080,6 +1094,7 @@ class Sequelize {
options = last; options = last;
// remove options from set of logged arguments if options.logging is equal to console.log // remove options from set of logged arguments if options.logging is equal to console.log
// eslint-disable-next-line no-console
if (options.logging === console.log) { if (options.logging === console.log) {
args.splice(args.length-1, 1); args.splice(args.length-1, 1);
} }
...@@ -1090,10 +1105,12 @@ class Sequelize { ...@@ -1090,10 +1105,12 @@ class Sequelize {
if (options.logging) { if (options.logging) {
if (options.logging === true) { if (options.logging === true) {
logger.deprecate('The logging-option should be either a function or false. Default: console.log'); logger.deprecate('The logging-option should be either a function or false. Default: console.log');
// eslint-disable-next-line no-console
options.logging = console.log; options.logging = console.log;
} }
// second argument is sql-timings, when benchmarking option enabled // second argument is sql-timings, when benchmarking option enabled
// eslint-disable-next-line no-console
if ((this.options.benchmark || options.benchmark) && options.logging === console.log) { if ((this.options.benchmark || options.benchmark) && options.logging === console.log) {
args = [`${args[0]} Elapsed time: ${args[1]}ms`]; args = [`${args[0]} Elapsed time: ${args[1]}ms`];
} }
......
...@@ -75,7 +75,8 @@ function escape(val, timeZone, dialect, format) { ...@@ -75,7 +75,8 @@ function escape(val, timeZone, dialect, format) {
val = val.replace(/\0/g, '\\0'); val = val.replace(/\0/g, '\\0');
} }
} else { } else {
val = val.replace(/[\0\n\r\b\t\\\'\"\x1a]/g, s => { // eslint-disable-next-line no-control-regex
val = val.replace(/[\0\n\r\b\t\\'"\x1a]/g, s => {
switch (s) { switch (s) {
case '\0': return '\\0'; case '\0': return '\\0';
case '\n': return '\\n'; case '\n': return '\\n';
...@@ -109,7 +110,7 @@ function format(sql, values, timeZone, dialect) { ...@@ -109,7 +110,7 @@ function format(sql, values, timeZone, dialect) {
exports.format = format; exports.format = format;
function formatNamedParameters(sql, values, timeZone, dialect) { function formatNamedParameters(sql, values, timeZone, dialect) {
return sql.replace(/\:+(?!\d)(\w+)/g, (value, key) => { return sql.replace(/:+(?!\d)(\w+)/g, (value, key) => {
if ('postgres' === dialect && '::' === value.slice(0, 2)) { if ('postgres' === dialect && '::' === value.slice(0, 2)) {
return value; return value;
} }
......
...@@ -379,8 +379,8 @@ exports.removeTicks = removeTicks; ...@@ -379,8 +379,8 @@ exports.removeTicks = removeTicks;
* address.coordinates.longitude: 12.5964313 * address.coordinates.longitude: 12.5964313
* } * }
* *
* @param value, an Object * @param {Object} value an Object
* @returns Object, an flattened object * @returns {Object} a flattened object
* @private * @private
*/ */
function flattenObjectDeep(value) { function flattenObjectDeep(value) {
...@@ -486,6 +486,7 @@ exports.Where = Where; ...@@ -486,6 +486,7 @@ exports.Where = Where;
/** /**
* getOperators * getOperators
*
* @param {Object} obj * @param {Object} obj
* @returns {Array<Symbol>} All operators properties of obj * @returns {Array<Symbol>} All operators properties of obj
* @private * @private
...@@ -497,8 +498,9 @@ exports.getOperators = getOperators; ...@@ -497,8 +498,9 @@ exports.getOperators = getOperators;
/** /**
* getComplexKeys * getComplexKeys
*
* @param {Object} obj * @param {Object} obj
* @returns {Array<String|Symbol>} All keys including operators * @returns {Array<string|Symbol>} All keys including operators
* @private * @private
*/ */
function getComplexKeys(obj) { function getComplexKeys(obj) {
...@@ -508,8 +510,9 @@ exports.getComplexKeys = getComplexKeys; ...@@ -508,8 +510,9 @@ exports.getComplexKeys = getComplexKeys;
/** /**
* getComplexSize * getComplexSize
*
* @param {Object|Array} obj * @param {Object|Array} obj
* @returns {Integer} Length of object properties including operators if obj is array returns its length * @returns {number} Length of object properties including operators if obj is array returns its length
* @private * @private
*/ */
function getComplexSize(obj) { function getComplexSize(obj) {
...@@ -544,6 +547,7 @@ exports.generateEnumName = generateEnumName; ...@@ -544,6 +547,7 @@ exports.generateEnumName = generateEnumName;
/** /**
* Returns an new Object which keys are camelized * Returns an new Object which keys are camelized
*
* @param {Object} obj * @param {Object} obj
* @returns {string} * @returns {string}
* @private * @private
...@@ -570,11 +574,9 @@ exports.camelizeObjectKeys = camelizeObjectKeys; ...@@ -570,11 +574,9 @@ exports.camelizeObjectKeys = camelizeObjectKeys;
* @returns {Object} Returns `object`. * @returns {Object} Returns `object`.
* @private * @private
*/ */
function defaults(object) { function defaults(object, ...sources) {
object = Object(object); object = Object(object);
const sources = _.tail(arguments);
sources.forEach(source => { sources.forEach(source => {
if (source) { if (source) {
source = Object(source); source = Object(source);
...@@ -602,7 +604,7 @@ exports.defaults = defaults; ...@@ -602,7 +604,7 @@ exports.defaults = defaults;
* @param {Object} index * @param {Object} index
* @param {Array} index.fields * @param {Array} index.fields
* @param {string} [index.name] * @param {string} [index.name]
* @param {String|Object} tableName * @param {string|Object} tableName
* *
* @returns {Object} * @returns {Object}
* @private * @private
......
...@@ -3,8 +3,9 @@ ...@@ -3,8 +3,9 @@
/** /**
* Wraps a constructor to not need the `new` keyword using a proxy. * Wraps a constructor to not need the `new` keyword using a proxy.
* Only used for data types. * Only used for data types.
* @param {Function} ctor *
* @return {Proxy} * @param {Function} Class The class instance to wrap as invocable.
* @returns {Proxy} Wrapped class instance.
*/ */
function classToInvokable(Class) { function classToInvokable(Class) {
return new Proxy(Class, { return new Proxy(Class, {
......
...@@ -34,6 +34,7 @@ class Logger { ...@@ -34,6 +34,7 @@ class Logger {
} }
warn(message) { warn(message) {
// eslint-disable-next-line no-console
console.warn(`(${this.config.context}) Warning: ${message}`); console.warn(`(${this.config.context}) Warning: ${message}`);
} }
......
...@@ -39,7 +39,7 @@ const extensions = { ...@@ -39,7 +39,7 @@ const extensions = {
return !this.regex(str, pattern, modifiers); return !this.regex(str, pattern, modifiers);
}, },
isDecimal(str) { isDecimal(str) {
return str !== '' && !!str.match(/^(?:-?(?:[0-9]+))?(?:\.[0-9]*)?(?:[eE][\+\-]?(?:[0-9]+))?$/); return str !== '' && !!str.match(/^(?:-?(?:[0-9]+))?(?:\.[0-9]*)?(?:[eE][+-]?(?:[0-9]+))?$/);
}, },
min(str, val) { min(str, val) {
const number = parseFloat(str); const number = parseFloat(str);
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
"rules": { "rules": {
"no-invalid-this": 0, "no-invalid-this": 0,
"no-unused-expressions": 0, "no-unused-expressions": 0,
"camelcase": 0 "camelcase": 0,
"no-console": 0
} }
} }
...@@ -153,7 +153,7 @@ describe(Support.getTestDialectTeaser('HasOne'), () => { ...@@ -153,7 +153,7 @@ describe(Support.getTestDialectTeaser('HasOne'), () => {
return this.sequelize.showAllSchemas().then(schemas => { return this.sequelize.showAllSchemas().then(schemas => {
if (dialect === 'postgres' || dialect === 'mssql' || dialect === 'mariadb') { if (dialect === 'postgres' || dialect === 'mssql' || dialect === 'mariadb') {
expect(schemas).to.not.have.property('admin'); expect(schemas).to.not.have.property('admin');
}; }
}); });
}); });
}); });
......
...@@ -22,7 +22,7 @@ if (dialect.match(/^postgres/)) { ...@@ -22,7 +22,7 @@ if (dialect.match(/^postgres/)) {
}); });
it('should handle empty string correctly', () => { it('should handle empty string correctly', () => {
expect(hstore.stringify({ foo: '' })).to.equal('"foo"=>\"\"'); expect(hstore.stringify({ foo: '' })).to.equal('"foo"=>""');
}); });
it('should handle a string with backslashes correctly', () => { it('should handle a string with backslashes correctly', () => {
...@@ -49,11 +49,11 @@ if (dialect.match(/^postgres/)) { ...@@ -49,11 +49,11 @@ if (dialect.match(/^postgres/)) {
}); });
it('should handle empty string correctly', () => { it('should handle empty string correctly', () => {
expect(hstore.parse('"foo"=>\"\"')).to.deep.equal({ foo: '' }); expect(hstore.parse('"foo"=>""')).to.deep.equal({ foo: '' });
}); });
it('should handle a string with double quotes correctly', () => { it('should handle a string with double quotes correctly', () => {
expect(hstore.parse('"foo"=>"\\\"\\\"a\\\""')).to.deep.equal({ foo: '\"\"a\"' }); expect(hstore.parse('"foo"=>"\\"\\"a\\""')).to.deep.equal({ foo: '""a"' });
}); });
it('should handle a string with single quotes correctly', () => { it('should handle a string with single quotes correctly', () => {
......
...@@ -54,7 +54,7 @@ if (dialect.match(/^postgres/)) { ...@@ -54,7 +54,7 @@ if (dialect.match(/^postgres/)) {
return this.queryInterface.databaseVersion() return this.queryInterface.databaseVersion()
.then(res => { .then(res => {
// check that result matches expected version number format. example 9.5.4 // check that result matches expected version number format. example 9.5.4
expect(res).to.match(/[0-9\.[0-9]\.[0-9]/); expect(res).to.match(/\d\.\d/);
}); });
}); });
}); });
......
...@@ -14,8 +14,8 @@ describe(Support.getTestDialectTeaser('Include'), () => { ...@@ -14,8 +14,8 @@ describe(Support.getTestDialectTeaser('Include'), () => {
/* /*
* shortcut for building simple {name: 'foo'} seed data * shortcut for building simple {name: 'foo'} seed data
*/ */
function build() { function build(...args) {
return Array.prototype.slice.call(arguments).map(arg => ({ name: arg })); return args.map(arg => ({ name: arg }));
} }
/* /*
......
...@@ -261,8 +261,8 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -261,8 +261,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
return User.sync({ force: true, logging: _.after(2, _.once(sql => { return User.sync({ force: true, logging: _.after(2, _.once(sql => {
if (dialect === 'mssql') { if (dialect === 'mssql') {
expect(sql).to.match(/CONSTRAINT\s*([`"\[]?user_and_email[`"\]]?)?\s*UNIQUE\s*\([`"\[]?username[`"\]]?, [`"\[]?email[`"\]]?\)/); expect(sql).to.match(/CONSTRAINT\s*([`"[]?user_and_email[`"\]]?)?\s*UNIQUE\s*\([`"[]?username[`"\]]?, [`"[]?email[`"\]]?\)/);
expect(sql).to.match(/CONSTRAINT\s*([`"\[]?a_and_b[`"\]]?)?\s*UNIQUE\s*\([`"\[]?aCol[`"\]]?, [`"\[]?bCol[`"\]]?\)/); expect(sql).to.match(/CONSTRAINT\s*([`"[]?a_and_b[`"\]]?)?\s*UNIQUE\s*\([`"[]?aCol[`"\]]?, [`"[]?bCol[`"\]]?\)/);
} else { } else {
expect(sql).to.match(/UNIQUE\s*([`"]?user_and_email[`"]?)?\s*\([`"]?username[`"]?, [`"]?email[`"]?\)/); expect(sql).to.match(/UNIQUE\s*([`"]?user_and_email[`"]?)?\s*\([`"]?username[`"]?, [`"]?email[`"]?\)/);
expect(sql).to.match(/UNIQUE\s*([`"]?a_and_b[`"]?)?\s*\([`"]?aCol[`"]?, [`"]?bCol[`"]?\)/); expect(sql).to.match(/UNIQUE\s*([`"]?a_and_b[`"]?)?\s*\([`"]?aCol[`"]?, [`"]?bCol[`"]?\)/);
...@@ -2517,7 +2517,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -2517,7 +2517,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
if (semver.gte(current.options.databaseVersion, '5.6.0')) { if (semver.gte(current.options.databaseVersion, '5.6.0')) {
expect(err.message).to.match(/Cannot add foreign key constraint/); expect(err.message).to.match(/Cannot add foreign key constraint/);
} else { } else {
expect(err.message).to.match(/Can\'t create table/); expect(err.message).to.match(/Can't create table/);
} }
} else if (dialect === 'sqlite') { } else if (dialect === 'sqlite') {
// the parser should not end up here ... see above // the parser should not end up here ... see above
......
...@@ -110,7 +110,7 @@ describe(Support.getTestDialectTeaser('Model'), () => { ...@@ -110,7 +110,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
where: { 'specialkey': 'awesome' }, where: { 'specialkey': 'awesome' },
logging(sql) { logging(sql) {
test = true; test = true;
expect(sql).to.match(/WHERE ["|`|\[]UserPrimary["|`|\]]\.["|`|\[]specialkey["|`|\]] = N?'awesome'/); expect(sql).to.match(/WHERE ["|`|[]UserPrimary["|`|\]]\.["|`|[]specialkey["|`|\]] = N?'awesome'/);
} }
}).then(() => { }).then(() => {
expect(test).to.be.true; expect(test).to.be.true;
......
...@@ -25,7 +25,7 @@ function assertSameConnection(newConnection, oldConnection) { ...@@ -25,7 +25,7 @@ function assertSameConnection(newConnection, oldConnection) {
default: default:
throw new Error('Unsupported dialect'); throw new Error('Unsupported dialect');
} }
}; }
function assertNewConnection(newConnection, oldConnection) { function assertNewConnection(newConnection, oldConnection) {
switch (dialect) { switch (dialect) {
...@@ -46,7 +46,7 @@ function assertNewConnection(newConnection, oldConnection) { ...@@ -46,7 +46,7 @@ function assertNewConnection(newConnection, oldConnection) {
default: default:
throw new Error('Unsupported dialect'); throw new Error('Unsupported dialect');
} }
}; }
function unwrapAndAttachMSSQLUniqueId(connection) { function unwrapAndAttachMSSQLUniqueId(connection) {
if (dialect === 'mssql') { if (dialect === 'mssql') {
......
...@@ -1021,7 +1021,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => { ...@@ -1021,7 +1021,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => {
} else if (dialect === 'mssql') { } else if (dialect === 'mssql') {
expect(err.message).to.equal('Login failed for user \'bar\'.'); expect(err.message).to.equal('Login failed for user \'bar\'.');
} else { } else {
expect(err.message.toString()).to.match(/.*Access\ denied.*/); expect(err.message.toString()).to.match(/.*Access denied.*/);
} }
}); });
}); });
......
...@@ -218,7 +218,7 @@ if (dialect === 'mariadb') { ...@@ -218,7 +218,7 @@ if (dialect === 'mariadb') {
}, },
{ {
arguments: ['myTable', { title: 'ENUM("A", "B", "C")', name: 'VARCHAR(255)' }, { charset: 'latin1' }], arguments: ['myTable', { title: 'ENUM("A", "B", "C")', name: 'VARCHAR(255)' }, { charset: 'latin1' }],
expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` ENUM(\"A\", \"B\", \"C\"), `name` VARCHAR(255)) ENGINE=InnoDB DEFAULT CHARSET=latin1;' expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` ENUM("A", "B", "C"), `name` VARCHAR(255)) ENGINE=InnoDB DEFAULT CHARSET=latin1;'
}, },
{ {
arguments: ['myTable', { title: 'VARCHAR(255)', name: 'VARCHAR(255)' }, { rowFormat: 'default' }], arguments: ['myTable', { title: 'VARCHAR(255)', name: 'VARCHAR(255)' }, { rowFormat: 'default' }],
......
...@@ -175,7 +175,7 @@ if (dialect === 'mysql') { ...@@ -175,7 +175,7 @@ if (dialect === 'mysql') {
}, },
{ {
arguments: ['myTable', { title: 'ENUM("A", "B", "C")', name: 'VARCHAR(255)' }, { charset: 'latin1' }], arguments: ['myTable', { title: 'ENUM("A", "B", "C")', name: 'VARCHAR(255)' }, { charset: 'latin1' }],
expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` ENUM(\"A\", \"B\", \"C\"), `name` VARCHAR(255)) ENGINE=InnoDB DEFAULT CHARSET=latin1;' expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` ENUM("A", "B", "C"), `name` VARCHAR(255)) ENGINE=InnoDB DEFAULT CHARSET=latin1;'
}, },
{ {
arguments: ['myTable', { title: 'VARCHAR(255)', name: 'VARCHAR(255)' }, { rowFormat: 'default' }], arguments: ['myTable', { title: 'VARCHAR(255)', name: 'VARCHAR(255)' }, { rowFormat: 'default' }],
......
...@@ -127,7 +127,7 @@ if (dialect === 'sqlite') { ...@@ -127,7 +127,7 @@ if (dialect === 'sqlite') {
}, },
{ {
arguments: ['myTable', { title: 'ENUM("A", "B", "C")', name: 'VARCHAR(255)' }], arguments: ['myTable', { title: 'ENUM("A", "B", "C")', name: 'VARCHAR(255)' }],
expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` ENUM(\"A\", \"B\", \"C\"), `name` VARCHAR(255));' expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` ENUM("A", "B", "C"), `name` VARCHAR(255));'
}, },
{ {
arguments: ['myTable', { title: 'VARCHAR(255)', name: 'VARCHAR(255)', id: 'INTEGER PRIMARY KEY' }], arguments: ['myTable', { title: 'VARCHAR(255)', name: 'VARCHAR(255)', id: 'INTEGER PRIMARY KEY' }],
...@@ -174,7 +174,7 @@ if (dialect === 'sqlite') { ...@@ -174,7 +174,7 @@ if (dialect === 'sqlite') {
context: QueryGenerator context: QueryGenerator
}, { }, {
arguments: ['myTable', { where: { name: "foo';DROP TABLE myTable;" } }], arguments: ['myTable', { where: { name: "foo';DROP TABLE myTable;" } }],
expectation: "SELECT * FROM `myTable` WHERE `myTable`.`name` = 'foo\'\';DROP TABLE myTable;';", expectation: "SELECT * FROM `myTable` WHERE `myTable`.`name` = 'foo'';DROP TABLE myTable;';",
context: QueryGenerator context: QueryGenerator
}, { }, {
arguments: ['myTable', { where: 2 }], arguments: ['myTable', { where: 2 }],
......
...@@ -24,7 +24,7 @@ describe('errors', () => { ...@@ -24,7 +24,7 @@ describe('errors', () => {
const stackParts = err.stack.split('\n'); const stackParts = err.stack.split('\n');
const fullErrorName = `Sequelize${errorName}`; const fullErrorName = `Sequelize${errorName}`;
expect(stackParts[0]).to.equal(`${fullErrorName}: this is a message`); expect(stackParts[0]).to.equal(`${fullErrorName}: this is a message`);
expect(stackParts[1]).to.match(/^ at throwError \(.*errors.test.js:\d+:\d+\)$/); expect(stackParts[1]).to.match(/^ {4}at throwError \(.*errors.test.js:\d+:\d+\)$/);
}); });
}); });
...@@ -49,7 +49,7 @@ describe('errors', () => { ...@@ -49,7 +49,7 @@ describe('errors', () => {
const fullErrorName = `Sequelize${errorName}`; const fullErrorName = `Sequelize${errorName}`;
expect(stackParts[0]).to.equal(fullErrorName); expect(stackParts[0]).to.equal(fullErrorName);
expect(stackParts[1]).to.match(/^ at throwError \(.*errors.test.js:\d+:\d+\)$/); expect(stackParts[1]).to.match(/^ {4}at throwError \(.*errors.test.js:\d+:\d+\)$/);
}); });
}); });
}); });
...@@ -98,7 +98,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => { ...@@ -98,7 +98,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
} }
if (typeof val === 'string') { if (typeof val === 'string') {
// Canonicalize phone number // Canonicalize phone number
val = val.replace(/^\+/, '00').replace(/\(0\)|[\s+\/.\-\(\)]/g, ''); val = val.replace(/^\+/, '00').replace(/\(0\)|[\s+/.\-()]/g, '');
} }
this.setDataValue('phoneNumber', val); this.setDataValue('phoneNumber', val);
} }
......
...@@ -115,7 +115,7 @@ describe(Support.getTestDialectTeaser('SQL'), () => { ...@@ -115,7 +115,7 @@ describe(Support.getTestDialectTeaser('SQL'), () => {
), { ), {
postgres: 'DELETE FROM "public"."test_users" WHERE "id" IN (SELECT "id" FROM "public"."test_users" WHERE "name" = \'foo\'\';DROP TABLE mySchema.myTable;\' LIMIT 10)', postgres: 'DELETE FROM "public"."test_users" WHERE "id" IN (SELECT "id" FROM "public"."test_users" WHERE "name" = \'foo\'\';DROP TABLE mySchema.myTable;\' LIMIT 10)',
mariadb: "DELETE FROM `public`.`test_users` WHERE `name` = 'foo\\';DROP TABLE mySchema.myTable;' LIMIT 10", mariadb: "DELETE FROM `public`.`test_users` WHERE `name` = 'foo\\';DROP TABLE mySchema.myTable;' LIMIT 10",
sqlite: "DELETE FROM `public.test_users` WHERE rowid IN (SELECT rowid FROM `public.test_users` WHERE `name` = \'foo\'\';DROP TABLE mySchema.myTable;\' LIMIT 10)", sqlite: "DELETE FROM `public.test_users` WHERE rowid IN (SELECT rowid FROM `public.test_users` WHERE `name` = 'foo'';DROP TABLE mySchema.myTable;' LIMIT 10)",
mssql: "DELETE TOP(10) FROM [public].[test_users] WHERE [name] = N'foo'';DROP TABLE mySchema.myTable;'; SELECT @@ROWCOUNT AS AFFECTEDROWS;", mssql: "DELETE TOP(10) FROM [public].[test_users] WHERE [name] = N'foo'';DROP TABLE mySchema.myTable;'; SELECT @@ROWCOUNT AS AFFECTEDROWS;",
default: "DELETE FROM [public.test_users] WHERE `name` = 'foo\\';DROP TABLE mySchema.myTable;' LIMIT 10" default: "DELETE FROM [public.test_users] WHERE `name` = 'foo\\';DROP TABLE mySchema.myTable;' LIMIT 10"
} }
......
...@@ -462,7 +462,7 @@ describe(Support.getTestDialectTeaser('SQL'), () => { ...@@ -462,7 +462,7 @@ describe(Support.getTestDialectTeaser('SQL'), () => {
expectsql(sql.selectQuery('User', { expectsql(sql.selectQuery('User', {
attributes: ['a\', * FROM User; DELETE FROM User;SELECT id'] attributes: ['a\', * FROM User; DELETE FROM User;SELECT id']
}), { }), {
default: "SELECT [a\', * FROM User; DELETE FROM User;SELECT id] FROM [User];", default: "SELECT [a', * FROM User; DELETE FROM User;SELECT id] FROM [User];",
mssql: 'SELECT [a, * FROM User; DELETE FROM User;SELECT id] FROM [User];' mssql: 'SELECT [a, * FROM User; DELETE FROM User;SELECT id] FROM [User];'
}); });
}); });
......
...@@ -25,10 +25,10 @@ describe(Support.getTestDialectTeaser('Utils'), () => { ...@@ -25,10 +25,10 @@ describe(Support.getTestDialectTeaser('Utils'), () => {
expect(Utils.toDefaultValue(DataTypes.UUIDV4)).to.equal('UUIDV4'); expect(Utils.toDefaultValue(DataTypes.UUIDV4)).to.equal('UUIDV4');
}); });
it('return uuid v1', () => { it('return uuid v1', () => {
expect(/^[a-z0-9\-]{36}$/.test(Utils.toDefaultValue(DataTypes.UUIDV1()))).to.be.equal(true); expect(/^[a-z0-9-]{36}$/.test(Utils.toDefaultValue(DataTypes.UUIDV1()))).to.be.equal(true);
}); });
it('return uuid v4', () => { it('return uuid v4', () => {
expect(/^[a-z0-9\-]{36}/.test(Utils.toDefaultValue(DataTypes.UUIDV4()))).to.be.equal(true); expect(/^[a-z0-9-]{36}/.test(Utils.toDefaultValue(DataTypes.UUIDV4()))).to.be.equal(true);
}); });
it('return now', () => { it('return now', () => {
expect(Object.prototype.toString.call(Utils.toDefaultValue(DataTypes.NOW()))).to.be.equal('[object Date]'); expect(Object.prototype.toString.call(Utils.toDefaultValue(DataTypes.NOW()))).to.be.equal('[object Date]');
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!