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

Commit 4478d74a by Simon Schick Committed by Sushant

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

1 parent f862e6bb
Showing with 371 additions and 310 deletions
{
"extends": "eslint:recommended",
"rules": {
"mocha/no-exclusive-tests": "error",
"mocha/no-skipped-tests": "warn",
// "jsdoc/check-param-names": "error",
// "jsdoc/check-tag-names": "error",
// "jsdoc/check-types": "error",
// "jsdoc/newline-after-description": "error",
// "jsdoc/no-undefined-types": "error",
// "jsdoc/require-description-complete-sentence": "off",
// "jsdoc/require-example": "off",
// "jsdoc/require-hyphen-before-param-description": "off",
// "jsdoc/require-param": "error",
// "jsdoc/require-param-description": "error",
// "jsdoc/require-param-name": "error",
// "jsdoc/require-param-type": "error",
// "jsdoc/require-returns-description": "off",
// "jsdoc/require-returns-type": "error",
// "jsdoc/valid-types": "off",
"jsdoc/check-param-names": "error",
"jsdoc/check-tag-names": "error",
"jsdoc/check-types": "error",
"jsdoc/newline-after-description": "error",
"jsdoc/no-undefined-types": "off",
"jsdoc/require-description-complete-sentence": "off",
"jsdoc/require-example": "off",
"jsdoc/require-hyphen-before-param-description": "off",
"jsdoc/require-param": "error",
"jsdoc/require-param-description": "off",
"jsdoc/require-param-name": "error",
"jsdoc/require-param-type": "error",
"jsdoc/require-returns-description": "off",
"jsdoc/require-returns-type": "error",
"jsdoc/valid-types": "error",
// style
"array-bracket-spacing": "error",
"comma-spacing": "error",
"key-spacing": "error",
"keyword-spacing": "error",
"object-curly-spacing": ["error", "always"],
"func-call-spacing": ["error", "never"],
"no-console": "off",
"no-extra-parens": "error",
"valid-jsdoc": "off",
"new-cap": [
"error",
{
......@@ -36,13 +34,6 @@
"properties": false
}
],
"no-extra-boolean-cast": "error",
"strict": [
"error",
"global"
],
"no-var": "error",
"prefer-const": "error",
"semi": [
"error",
"always"
......@@ -52,7 +43,6 @@
"never"
],
"space-before-blocks": "error",
"prefer-arrow-callback": "error",
"arrow-parens": [
"error",
"as-needed"
......@@ -61,18 +51,6 @@
"error",
"last"
],
"no-bitwise": "off",
"no-cond-assign": [
"error",
"except-parens"
],
"curly": "off",
"eqeqeq": "error",
"no-extend-native": "error",
"wrap-iife": [
"error",
"any"
],
"indent": [
"error",
2,
......@@ -80,15 +58,8 @@
"SwitchCase": 1
}
],
"no-use-before-define": "off",
"no-caller": "error",
"no-undef": "error",
"no-unused-vars": "error",
"no-irregular-whitespace": "error",
"max-depth": [
"error",
6
],
"no-extra-parens": "error",
"curly": "off",
"quotes": [
"error",
"single",
......@@ -97,16 +68,37 @@
}
],
"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",
"object-shorthand": "error",
"one-var-declaration-per-line": "error",
"comma-dangle": "error",
"no-shadow": "warn",
"camelcase": "error",
"prefer-template": "error",
"no-else-return": ["error", { "allowElseIf": false }],
"no-lonely-if": "error",
"no-this-before-super": "error",
"no-throw-literal": "error",
"prefer-promise-reject-errors": "error",
"no-invalid-this": "error",
......@@ -117,7 +109,8 @@
"no-useless-call": "error",
"no-unused-expressions": "error",
"no-sequences": "error",
"no-self-compare": "error"
"no-self-compare": "error",
"no-case-declarations": "off"
},
"parserOptions": {
"ecmaVersion": 6,
......@@ -132,17 +125,4 @@
"mocha": true,
"es6": true
}
// "globals": {
// "Association": true,
// "HasMany": true,
// "BelongsTo": true,
// "HasOne": true,
// "BelongsToMany": true,
// "DataTypes": true,
// "Sequelize": true,
// "Transaction": true,
// "Model": true,
// "QueryInterface": true,
// "QueryType": true
// },
}
......@@ -362,15 +362,16 @@ class BelongsToMany extends Association {
/**
* 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.where] An optional where clause to limit the associated models
* @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {string} [options.schema] Apply a schema on the related model
*
* @returns {Promise<Array<<Model>>>}
* @returns {Promise<Array<Model>>}
*/
get(instance, options) {
options = Utils.cloneDeep(options) || {};
......@@ -433,7 +434,7 @@ class BelongsToMany extends Association {
/**
* 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.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
......@@ -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
*
* @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} 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 {Object} [options] Options passed to getAssociations
*
* @returns {Promise<boolean>}
......@@ -502,8 +503,8 @@ class BelongsToMany extends Association {
* Set the associated models by passing an array of instances or their primary keys.
* Everything that it not in the passed array will be un-associated.
*
* @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} sourceInstance source instance to associate new instances with
* @param {Model|Model[]|string[]|string|number[]|number} [newAssociatedObjects] A single instance or primary key, or a mixed array of persisted instances or primary keys
* @param {Object} [options] Options passed to `through.findAll`, `bulkCreate`, `update` and `destroy`
* @param {Object} [options.validate] Run validation for the join model
* @param {Object} [options.through] Additional attributes for the join table.
......@@ -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
* that may be missing from `newInstances`.
*
* @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} sourceInstance source instance to associate new instances with
* @param {Model|Model[]|string[]|string|number[]|number} [newInstances] A single instance or primary key, or a mixed array of persisted instances or primary keys
* @param {Object} [options] Options passed to `through.findAll`, `bulkCreate` and `update`
* @param {Object} [options.validate] Run validation for the join model.
* @param {Object} [options.through] Additional attributes for the join table.
......@@ -706,8 +707,8 @@ class BelongsToMany extends Association {
/**
* Un-associate one or more instance(s).
*
* @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} sourceInstance instance to un associate instances with
* @param {Model|Model[]|string|string[]|number|number[]} [oldAssociatedObjects] Can be an Instance or its primary key, or a mixed array of instances and primary keys
* @param {Object} [options] Options passed to `through.destroy`
*
* @returns {Promise}
......@@ -730,7 +731,7 @@ class BelongsToMany extends Association {
/**
* 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} [options] Options passed to create and add
* @param {Object} [options.through] Additional attributes for the join table
......
......@@ -113,14 +113,15 @@ class BelongsTo extends Association {
/**
* Get the associated instance.
*
* @param {<Model>|Array<Model>} instances source instances
* @param {Model|Array<Model>} instances source instances
* @param {Object} [options] find options
* @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false.
* @param {string} [options.schema] Apply a schema on the related model
*
* @see {@link Model.findOne} for a full explanation of options
* @see
* {@link Model.findOne} for a full explanation of options
*
* @returns {Promise<<Model>>}
* @returns {Promise<Model>}
*/
get(instances, options) {
const where = {};
......@@ -183,7 +184,7 @@ class BelongsTo extends Association {
/**
* 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 {Object} [options={}] options passed to `this.save`
* @param {boolean} [options.save=true] Skip saving this after setting the foreign key if false.
......@@ -214,11 +215,12 @@ class BelongsTo extends Association {
/**
* 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} [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
*/
......
......@@ -157,15 +157,16 @@ class HasMany extends Association {
/**
* 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.where] An optional where clause to limit the associated models
* @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {string} [options.schema] Apply a schema on the related model
*
* @see {@link Model.findAll} for a full explanation of options
* @see
* {@link Model.findAll} for a full explanation of options
*
* @returns {Promise<Array<<Model>>>}
* @returns {Promise<Array<Model>>}
*/
get(instances, options = {}) {
const where = {};
......@@ -241,7 +242,7 @@ class HasMany extends Association {
/**
* 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.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
......@@ -269,8 +270,8 @@ class HasMany extends Association {
/**
* Check if one or more rows are associated with `this`.
*
* @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} sourceInstance the source instance
* @param {Model|Model[]|string[]|string|number[]|number} [targetInstances] Can be an array of instances or their primary keys
* @param {Object} [options] Options passed to getAssociations
*
* @returns {Promise}
......@@ -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
*
* @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} sourceInstance source instance to associate new instances with
* @param {Model|Model[]|string[]|string|number[]|number} [targetInstances] An array of persisted instances or primary key of instances to associate with this. Pass `null` or `undefined` to remove all associations.
* @param {Object} [options] Options passed to `target.findAll` and `update`.
* @param {Object} [options.validate] Run validation for the join model
*
......@@ -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,
* or a mixed array of Model / string / numbers to associate multiple rows.
*
* @param {<Model>} sourceInstance the source instance
* @param {<Model>|<Model>[]|string[]|string|number[]|number} [targetInstances] A single instance or primary key, or a mixed array of persisted instances or primary keys
* @param {Model} sourceInstance the source instance
* @param {Model|Model[]|string[]|string|number[]|number} [targetInstances] A single instance or primary key, or a mixed array of persisted instances or primary keys
* @param {Object} [options] Options passed to `target.update`.
*
* @returns {Promise}
......@@ -413,8 +414,8 @@ class HasMany extends Association {
/**
* Un-associate one or several target rows.
*
* @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} sourceInstance instance to un associate instances with
* @param {Model|Model[]|string|string[]|number|number[]} [targetInstances] Can be an Instance or its primary key, or a mixed array of instances and primary keys
* @param {Object} [options] Options passed to `target.update`
*
* @returns {Promise}
......@@ -439,7 +440,7 @@ class HasMany extends Association {
/**
* 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} [options] Options passed to `target.create`
*
......
......@@ -112,12 +112,13 @@ class HasOne extends Association {
/**
* Get the associated instance.
*
* @param {<Model>|Array<Model>} instances source instances
* @param {Model|Array<Model>} instances source instances
* @param {Object} [options] find options
* @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
* @param {string} [options.schema] Apply a schema on the related model
*
* @see {@link Model.findOne} for a full explanation of options
* @see
* {@link Model.findOne} for a full explanation of options
*
* @returns {Promise<Model>}
*/
......@@ -183,7 +184,7 @@ class HasOne extends Association {
/**
* 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 {Object} [options] Options passed to getAssociation and `target.save`
*
......@@ -233,11 +234,12 @@ class HasOne extends Association {
/**
* 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} [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
*/
......
......@@ -41,7 +41,7 @@ class ABSTRACT {
}
static extend(oldType) {
return new this(oldType.options);
};
}
}
ABSTRACT.prototype.dialectTypes = '';
......
......@@ -58,7 +58,7 @@ class ConnectionManager {
* Try to load dialect module from various configured options.
* 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
* @returns {Object}
......
......@@ -493,7 +493,7 @@ class QueryGenerator {
options.prefix = options.prefix || rawTablename || tableName;
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, '');
}
const fieldsSql = options.fields.map(field => {
......@@ -859,11 +859,8 @@ class QueryGenerator {
/**
* Split a list of identifiers by "." and quote each part
*
* @param {string} dialect Dialect name
* @param {string} identifiers
* @param {Object} [options]
* @param {boolean} [options.force=false]
* @param {boolean} [options.quoteIdentifiers=true]
* @param {string} identifier
* @param {boolean} force
*
* @returns {string}
*/
......@@ -897,8 +894,8 @@ class QueryGenerator {
/**
* Quote table name with optional alias and schema attribution
*
* @param {String|Object} param table string or object
* @param {String|Boolean} alias alias name
* @param {string|Object} param table string or object
* @param {string|boolean} alias alias name
*
* @returns {string}
*/
......@@ -1035,7 +1032,7 @@ class QueryGenerator {
* Generates an SQL query that extract JSON property of given path.
*
* @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
* @private
*/
......@@ -1830,7 +1827,7 @@ class QueryGenerator {
topLevelInfo.options.where[`__${includeAs.internalAs}`] = this.sequelize.literal([
'(',
query.replace(/\;$/, ''),
query.replace(/;$/, ''),
')',
'IS NOT NULL'
].join(' '));
......@@ -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 The model passed to the selectQuery.
* @returns {string} The generated sql query.
* @private
*/
......
......@@ -65,7 +65,7 @@ function quoteIdentifier(dialect, identifier, options) {
}
return Utils.addTicks(rawIdentifier, '"');
case 'mssql':
return `[${identifier.replace(/[\[\]']+/g, '')}]`;
return `[${identifier.replace(/[[\]']+/g, '')}]`;
default:
throw new Error(`Dialect "${dialect}" is not supported`);
......@@ -78,7 +78,7 @@ module.exports.quoteIdentifier = quoteIdentifier;
*
* @param {string} identifier
*
* @returns Boolean
* @returns {boolean}
* @private
*/
function isIdentifierQuoted(identifier) {
......
......@@ -27,7 +27,6 @@ const TransactionQueries = {
* Returns a query that starts a transaction.
*
* @param {Transaction} transaction
* @param {Object} options An object with options.
* @returns {string} The generated sql query.
* @private
*/
......@@ -40,14 +39,6 @@ const TransactionQueries = {
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() {},
setConstraintQuery() {},
......@@ -57,7 +48,7 @@ const TransactionQueries = {
/**
* 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.
* @private
*/
......@@ -73,7 +64,6 @@ const TransactionQueries = {
* Returns a query that rollbacks a transaction.
*
* @param {Transaction} transaction
* @param {Object} options An object with options.
* @returns {string} The generated sql query.
* @private
*/
......
......@@ -14,6 +14,7 @@ class AbstractQuery {
this.model = options.model;
this.sequelize = sequelize;
this.options = Object.assign({
// eslint-disable-next-line no-console
logging: console.log,
plain: false,
raw: false
......@@ -34,6 +35,12 @@ class AbstractQuery {
* Options
* skipUnescape: bool, skip unescaping $$
* 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
*/
static formatBindParameters(sql, values, dialect, replacementFunc, options) {
......@@ -105,7 +112,6 @@ class AbstractQuery {
*
* query.run('SELECT 1')
*
* @param {string} sql - The SQL query which should be executed.
* @private
*/
run() {
......@@ -115,12 +121,12 @@ class AbstractQuery {
/**
* Check the logging option of the instance and print deprecation warnings.
*
* @returns {void}
* @private
*/
checkLoggingOption() {
if (this.options.logging === true) {
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;
}
}
......@@ -349,6 +355,10 @@ class AbstractQuery {
* ]
* }
* ]
*
* @param {Array} rows
* @param {Object} includeOptions
* @param {Object} options
* @private
*/
static _groupJoinData(rows, includeOptions, options) {
......
......@@ -47,9 +47,10 @@ class ConnectionManager extends AbstractConnectionManager {
/**
* Connect with MariaDB database based on config, Handle any errors in connection
* 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
*/
connect(config) {
......
......@@ -73,7 +73,7 @@ module.exports = BaseTypes => {
class DATEONLY extends BaseTypes.DATEONLY {
static parse(value) {
return value.string();
};
}
}
class UUID extends BaseTypes.UUID {
......
......@@ -39,7 +39,7 @@ class MariaDBQueryGenerator extends MySQLQueryGenerator {
const conditions = this.parseConditionObject(smth.conditions).map(
condition =>
`json_unquote(json_extract(${this.quoteIdentifier(
condition.path[0])},'\$.${_.tail(condition.path).join(
condition.path[0])},'$.${_.tail(condition.path).join(
'.')}')) = '${condition.value}'`
);
......@@ -73,7 +73,7 @@ class MariaDBQueryGenerator extends MySQLQueryGenerator {
}
str = `json_unquote(json_extract(${this.quoteIdentifier(
columnName)},'\$${startWithDot ? '.' : ''}${path.join('.')}'))`;
columnName)},'$${startWithDot ? '.' : ''}${path.join('.')}'))`;
}
if (smth.value) {
......
......@@ -7,7 +7,8 @@ module.exports = BaseTypes => {
/**
* 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
*/
function removeUnsupportedIntegerOptions(dataType) {
......@@ -127,7 +128,7 @@ module.exports = BaseTypes => {
class DATEONLY extends BaseTypes.DATEONLY {
static parse(value) {
return moment(value).format('YYYY-MM-DD');
};
}
}
class INTEGER extends BaseTypes.INTEGER {
......
......@@ -252,10 +252,10 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator {
commentTemplate(comment, table, column) {
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\', ' +
`@level1type = N\'Table\', @level1name = ${this.quoteIdentifier(table)}, ` +
`@level2type = N\'Column\', @level2name = ${this.quoteIdentifier(column)};`;
`@level1type = N'Table', @level1name = ${this.quoteIdentifier(table)}, ` +
`@level2type = N'Column', @level2name = ${this.quoteIdentifier(column)};`;
}
removeColumnQuery(tableName, attributeName) {
......@@ -662,6 +662,8 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator {
/**
* Generate common SQL prefix for ForeignKeysQuery.
*
* @param {string} catalogName
* @returns {string}
*/
_getForeignKeysQueryPrefix(catalogName) {
......@@ -688,7 +690,8 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator {
/**
* 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
* @returns {string}
*/
......@@ -878,7 +881,7 @@ class MSSQLQueryGenerator extends AbstractQueryGenerator {
booleanValue(value) {
return value ? 1 : 0;
}
};
}
// private methods
function wrapSingleQuote(identifier) {
......
......@@ -12,10 +12,11 @@
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} attributeName The name of the attribute that we want to remove.
@param {Object} options
@param {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
@param {boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
@private
*/
......
......@@ -72,7 +72,6 @@ class Query extends AbstractQuery {
}
resolve(this.formatResults());
}, this.options.transaction.name);
return;
}
if (this.sql.startsWith('SAVE TRANSACTION')) {
return connection.saveTransaction(err => {
......@@ -148,7 +147,10 @@ class Query extends AbstractQuery {
/**
* 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:
* query.formatResults([
* {
......@@ -158,9 +160,6 @@ class Query extends AbstractQuery {
* Tasks.title: 'task' // this is from the associated table
* }
* ])
*
* @param {Array} data - The result of the query execution.
* @private
*/
formatResults(data, rowCount) {
let result = this.instance;
......
......@@ -47,9 +47,10 @@ class ConnectionManager extends AbstractConnectionManager {
/**
* Connect with MySQL database based on config, Handle any errors in connection
* 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
*/
connect(config) {
......
......@@ -209,7 +209,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
// Parse nested object
if (smth.conditions) {
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 ');
......@@ -241,7 +241,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
startWithDot = false;
}
str = `${this.quoteIdentifier(columnName)}->>'\$${startWithDot ? '.' : ''}${path.join('.')}'`;
str = `${this.quoteIdentifier(columnName)}->>'$${startWithDot ? '.' : ''}${path.join('.')}'`;
}
if (smth.value) {
......@@ -499,7 +499,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
/**
* Generates an SQL query that returns all foreign keys of a table.
*
* @param {string} tableName The name of the table.
* @param {Object} table The table.
* @param {string} schemaName The name of the schema.
* @returns {string} The generated sql query.
* @private
......@@ -512,7 +512,7 @@ class MySQLQueryGenerator extends AbstractQueryGenerator {
/**
* Generates an SQL query that returns the foreign key constraint of a given column.
*
* @param {string} tableName The name of the table.
* @param {Object} table The table.
* @param {string} columnName The name of the column.
* @returns {string} The generated sql query.
* @private
......
......@@ -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.
@param {QueryInterface} qi
@param {string} tableName The name of the table.
@param {string} columnName The name of the attribute that we want to remove.
@param {Object} options
......
......@@ -274,8 +274,8 @@ class ConnectionManager extends AbstractConnectionManager {
if (row.rngtypid) {
newNameOidMap[row.typname].rangeOid = row.rngtypid;
if (row.rngtyparray) newNameOidMap[row.typname].arrayRangeOid = row.rngtyparray;
};
};
}
}
// Replace all OID mappings. Avoids temporary empty OID mappings.
this.nameOidMap = newNameOidMap;
......
......@@ -8,7 +8,8 @@ module.exports = BaseTypes => {
/**
* 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
*/
function removeUnsupportedIntegerOptions(dataType) {
......@@ -494,7 +495,7 @@ module.exports = BaseTypes => {
class ENUM extends BaseTypes.ENUM {
static parse(value) {
return value;
};
}
}
BaseTypes.ENUM.types.postgres = [null];
......
......@@ -837,6 +837,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
/**
* Generate common SQL prefix for getForeignKeyReferencesQuery.
*
* @returns {string}
*/
_getForeignKeyReferencesQueryPrefix() {
......@@ -863,6 +864,7 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
* Generates an SQL query that returns all foreign keys details of a table.
*
* As for getForeignKeysQuery is not compatible with getForeignKeyReferencesQuery, so add a new function.
*
* @param {string} tableName
* @param {string} catalogName
* @param {string} schemaName
......@@ -893,6 +895,6 @@ class PostgresQueryGenerator extends AbstractQueryGenerator {
dropForeignKeyQuery(tableName, foreignKey) {
return `ALTER TABLE ${this.quoteTable(tableName)} DROP CONSTRAINT ${this.quoteIdentifier(foreignKey)};`;
}
};
}
module.exports = PostgresQueryGenerator;
......@@ -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 {Object} attributes Object representing a list of normalized table attributes
* @param {Object} [attributes]
* @param {Object} [options]
* @param {Model} [model]
*
* @returns {Promise}
......
......@@ -10,7 +10,11 @@ const _ = require('lodash');
class Query extends AbstractQuery {
/**
* rewrite query with parameters
* Rewrite query with parameters.
*
* @param {string} sql
* @param {Array|Object} values
* @param {string} dialect
* @private
*/
static formatBindParameters(sql, values, dialect) {
......@@ -283,9 +287,9 @@ class Query extends AbstractQuery {
switch (code) {
case '23503':
index = errMessage.match(/violates foreign key constraint \"(.+?)\"/);
index = errMessage.match(/violates foreign key constraint "(.+?)"/);
index = index ? index[1] : undefined;
table = errMessage.match(/on table \"(.+?)\"/);
table = errMessage.match(/on table "(.+?)"/);
table = table ? table[1] : undefined;
return new sequelizeErrors.ForeignKeyConstraintError({ message: errMessage, fields: null, index, table, parent: err });
......@@ -344,9 +348,9 @@ class Query extends AbstractQuery {
case '42704':
if (err.sql && /(CONSTRAINT|INDEX)/gi.test(err.sql)) {
message = 'Unknown constraint error';
index = errMessage.match(/(?:constraint|index) \"(.+?)\"/i);
index = errMessage.match(/(?:constraint|index) "(.+?)"/i);
index = index ? index[1] : undefined;
table = errMessage.match(/relation \"(.+?)\"/i);
table = errMessage.match(/relation "(.+?)"/i);
table = table ? table[1] : undefined;
throw new sequelizeErrors.UnknownConstraintError({
......@@ -357,7 +361,7 @@ class Query extends AbstractQuery {
parent: err
});
}
// falls through
default:
return new sequelizeErrors.DatabaseError(err);
}
......
......@@ -5,7 +5,8 @@ module.exports = BaseTypes => {
/**
* 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
*/
function removeUnsupportedIntegerOptions(dataType) {
......@@ -177,12 +178,12 @@ module.exports = BaseTypes => {
}
for (const floating of [FLOAT, DOUBLE, REAL]) {
floating.parse = parseFloating;
};
}
for (const num of [FLOAT, DOUBLE, REAL, TINYINT, SMALLINT, MEDIUMINT, INTEGER, BIGINT]) {
num.prototype.toSql = NUMBER.prototype.toSql;
};
}
class ENUM extends BaseTypes.ENUM {
toSql() {
......
......@@ -498,6 +498,6 @@ class SQLiteQueryGenerator extends MySqlQueryGenerator {
getForeignKeysQuery(tableName) {
return `PRAGMA foreign_key_list(${tableName})`;
}
};
}
module.exports = SQLiteQueryGenerator;
......@@ -22,7 +22,7 @@ const QueryTypes = require('../../query-types');
@param {string} tableName The name of the table.
@param {string} attributeName The name of the attribute that we want to remove.
@param {Object} options
@param {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
@param {boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
@since 1.6.0
@private
......@@ -50,7 +50,7 @@ exports.removeColumn = removeColumn;
@param {string} tableName The name of the table.
@param {Object} attributes An object with the attribute's name as key and its options as value object.
@param {Object} options
@param {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
@param {boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
@since 1.6.0
@private
......@@ -80,7 +80,7 @@ exports.changeColumn = changeColumn;
@param {string} attrNameBefore The name of the attribute before it was renamed.
@param {string} attrNameAfter The name of the attribute after it was renamed.
@param {Object} options
@param {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
@param {boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
@since 1.6.0
@private
......@@ -102,6 +102,10 @@ exports.renameColumn = renameColumn;
/**
* @param {QueryInterface} qi
* @param {string} tableName
* @param {string} constraintName
* @param {Object} options
*
* @private
*/
function removeConstraint(qi, tableName, constraintName, options) {
......@@ -147,6 +151,9 @@ exports.removeConstraint = removeConstraint;
/**
* @param {QueryInterface} qi
* @param {string} tableName
* @param {Object} options
*
* @private
*/
function addConstraint(qi, tableName, options) {
......
......@@ -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
*/
static formatBindParameters(sql, values, dialect) {
......@@ -346,7 +350,7 @@ class Query extends AbstractQuery {
constraintType: constraint[1],
updateAction,
deleteAction,
sql: sql.replace(/\"/g, '\`'), //Sqlite returns double quotes for table name
sql: sql.replace(/"/g, '`'), //Sqlite returns double quotes for table name
constraintCondition,
referenceTableName,
referenceTableKeys
......
......@@ -65,7 +65,7 @@ const getProxiedHooks = hookType =>
function getHooks(hooked, hookType) {
return (hooked.options.hooks || {})[hookType] || [];
};
}
const Hooks = {
/**
......
......@@ -34,8 +34,8 @@ const Op = require('./operators');
* However, if getters and/or setters are defined for `field` they will be invoked, instead of returning the value from `dataValues`.
* Accessing properties directly or using `get` is preferred for regular use, `getDataValue` should only be used for custom getters.
*
* @see {@link Sequelize#define} for more information about getters and setters
* @class Model
* @see
* {@link Sequelize#define} for more information about getters and setters
* @mixes Hooks
*/
class Model {
......@@ -50,7 +50,8 @@ class Model {
/**
* A reference to the sequelize instance
*
* @see {@link Sequelize}
* @see
* {@link Sequelize}
*
* @property sequelize
*
......@@ -848,8 +849,10 @@ class Model {
*
* sequelize.models.modelName // The model will now be available in models under the class name
*
* @see {@link DataTypes}
* @see {@link Hooks}
* @see
* {@link DataTypes}
* @see
* {@link Hooks}
*
* @param {Object} attributes An object, where each attribute is a column of the table. Each column can be either a DataType, a string or a type-description object, with the properties described below:
* @param {string|DataTypes|Object} attributes.column The description of a database column
......@@ -1251,7 +1254,8 @@ class Model {
*
* @param {Object} [options] sync options
*
* @see {@link Sequelize#sync} for options
* @see
* {@link Sequelize#sync} for options
*
* @returns {Promise<Model>}
*/
......@@ -1389,7 +1393,8 @@ class Model {
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @param {boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
*
* @see {@link Sequelize#define} for more information about setting a default schema.
* @see
* {@link Sequelize#define} for more information about setting a default schema.
*
* @returns {Model}
*/
......@@ -1611,7 +1616,8 @@ class Model {
*
* # WHERE `Model`.`name` = 'a project' AND (`Model`.`id` IN (1, 2, 3) OR (`Model`.`id` > 10 AND `Model`.`id` < 100));
*
* @see {@link Operators} for possible operators
* @see
* {@link Operators} for possible operators
* __Alias__: _all_
*
* The promise is resolved with an array of Model instances if the query succeeds._
......@@ -1648,7 +1654,8 @@ class Model {
* @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
* @param {boolean|Error} [options.rejectOnEmpty=false] Throws an error when no records found
*
* @see {@link Sequelize#query}
* @see
* {@link Sequelize#query}
*
* @returns {Promise<Array<Model>>}
*/
......@@ -1846,7 +1853,8 @@ class Model {
* @param {Transaction} [options.transaction] Transaction to run query under
* @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
*
* @see {@link Model.findAll} for a full explanation of options
* @see
* {@link Model.findAll} for a full explanation of options
*
* @returns {Promise<Model>}
*/
......@@ -1879,7 +1887,8 @@ class Model {
* @param {Transaction} [options.transaction] Transaction to run query under
* @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
*
* @see {@link Model.findAll} for an explanation of options
* @see
* {@link Model.findAll} for an explanation of options
*
* @returns {Promise<Model>}
*/
......@@ -1964,7 +1973,7 @@ class Model {
return 0;
}
return value;
});;
});
}
/**
......@@ -2042,8 +2051,10 @@ class Model {
*
* @param {Object} [options] See findAll options
*
* @see {@link Model.findAll} for a specification of find and query options
* @see {@link Model.count} for a specification of count options
* @see
* {@link Model.findAll} for a specification of find and query options
* @see
* {@link Model.count} for a specification of count options
*
* @returns {Promise<{count: number, rows: Model[]}>}
*/
......@@ -2074,7 +2085,8 @@ class Model {
* @param {string} field attribute / field name
* @param {Object} [options] See aggregate
*
* @see {@link Model.aggregate} for options
* @see
* {@link Model.aggregate} for options
*
* @returns {Promise<*>}
*/
......@@ -2088,7 +2100,8 @@ class Model {
* @param {string} field attribute / field name
* @param {Object} [options] See aggregate
*
* @see {@link Model.aggregate} for options
* @see
* {@link Model.aggregate} for options
*
* @returns {Promise<*>}
*/
......@@ -2102,7 +2115,8 @@ class Model {
* @param {string} field attribute / field name
* @param {Object} [options] See aggregate
*
* @see {@link Model.aggregate} for options
* @see
* {@link Model.aggregate} for options
*
* @returns {Promise<number>}
*/
......@@ -2152,8 +2166,10 @@ class Model {
/**
* Builds a new model instance and calls save on it.
* @see {@link Model.build}
* @see {@link Model.save}
* @see
* {@link Model.build}
* @see
* {@link Model.save}
*
* @param {Object} values hash of data values to create new record with
* @param {Object} [options] build and query options
......@@ -2231,7 +2247,8 @@ class Model {
* However, it is not always possible to handle this case in SQLite, specifically if one transaction inserts and another tries to select before the first one has committed. In this case, an instance of sequelize. TimeoutError will be thrown instead.
* If a transaction is created, a savepoint will be created instead, and any unique constraint violation will be handled internally.
*
* @see {@link Model.findAll} for a full specification of find and options
* @see
* {@link Model.findAll} for a full specification of find and options
*
* @param {Object} options find and create options
* @param {Object} options.where where A hash of search attributes.
......@@ -2340,7 +2357,8 @@ class Model {
* A more performant findOrCreate that will not work under a transaction (at least not in postgres)
* Will execute a find call, if empty then attempt to create, if unique constraint then attempt to find again
*
* @see {@link Model.findAll} for a full specification of find and options
* @see
* {@link Model.findAll} for a full specification of find and options
*
* @param {Object} options find options
* @param {Object} options.where A hash of search attributes.
......@@ -2655,7 +2673,8 @@ class Model {
*
* @returns {Promise}
*
* @see {@link Model.destroy} for more information
* @see
* {@link Model.destroy} for more information
*/
static truncate(options) {
options = Utils.cloneDeep(options) || {};
......@@ -3110,7 +3129,8 @@ class Model {
* // `by` is ignored, as each column has its own value
* Model.increment({ answer: 42, tries: -1}, { by: 2, where: { foo: 'bar' } });
*
* @see {@link Model#reload}
* @see
* {@link Model#reload}
*
* @param {string|Array|Object} fields If a string is provided, that column is incremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is incremented by the value given.
* @param {Object} options increment options
......@@ -3202,8 +3222,10 @@ class Model {
* @param {string|Array|Object} fields If a string is provided, that column is incremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is incremented by the value given.
* @param {Object} options decrement options, similar to increment
*
* @see {@link Model.increment}
* @see {@link Model#reload}
* @see
* {@link Model.increment}
* @see
* {@link Model#reload}
* @since 4.36.0
* @returns {Promise<Model[],?number>} returns an array of affected rows and affected count with `options.returning: true`, whenever supported by dialect
......@@ -3366,7 +3388,8 @@ class Model {
*
* If called with a dot.separated key on a JSON/JSONB attribute it will set the value nested and flag the entire object as changed.
*
* @see {@link Model.findAll} for more information about includes
* @see
* {@link Model.findAll} for more information about includes
*
* @param {string|Object} key key to set, it can be string or object. When string it will set that key, for object it will loop over all object properties nd set them.
* @param {any} value value to set
......@@ -3374,7 +3397,7 @@ class Model {
* @param {boolean} [options.raw=false] If set to true, field and virtual setters will be ignored
* @param {boolean} [options.reset=false] Clear all previously set data values
*
* @returns {<Model>}
* @returns {Model}
*/
set(key, value, options) {
let values;
......@@ -3607,7 +3630,7 @@ class Model {
* @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
* @param {boolean} [options.returning] Append RETURNING * to get back auto generated values (Postgres only)
*
* @returns {Promise<<Model>|Errors.ValidationError>}
* @returns {Promise<Model>}
*/
save(options) {
if (arguments.length > 1) {
......@@ -3876,12 +3899,13 @@ class Model {
* This is different from doing a `find(Instance.id)`, because that would create and return a new instance. With this method,
* all references to the Instance are updated with the new data and no new objects are created.
*
* @see {@link Model.findAll}
* @see
* {@link Model.findAll}
*
* @param {Object} [options] Options that are passed on to `Model.find`
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
*
* @returns {Promise<<Model>>}
* @returns {Promise<Model>}
*/
reload(options) {
options = Utils.defaults({}, options, {
......@@ -3929,13 +3953,15 @@ class Model {
* This is the same as calling `set` and then calling `save` but it only saves the
* exact values passed to it, making it more atomic and safer.
*
* @see {@link Model#set}
* @see {@link Model#save}
* @see
* {@link Model#set}
* @see
* {@link Model#save}
*
* @param {Object} values See `set`
* @param {Object} options See `save`
*
* @returns {Promise<<Model>>}
* @returns {Promise<Model>}
*/
update(values, options) {
// Clone values so it doesn't get modified for caller scope and ignore undefined values
......@@ -4093,7 +4119,8 @@ class Model {
* // `by` is ignored, since each column has its own value
* instance.increment({ answer: 42, tries: 1}, { by: 2 })
*
* @see {@link Model#reload}
* @see
* {@link Model#reload}
*
* @param {string|Array|Object} fields If a string is provided, that column is incremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is incremented by the value given.
* @param {Object} [options] options
......@@ -4104,7 +4131,7 @@ class Model {
* @param {string} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
* @param {boolean} [options.returning=true] Append RETURNING * to get back auto generated values (Postgres only)
*
* @returns {Promise<<Model>>}
* @returns {Promise<Model>}
* @since 4.0.0
*/
increment(fields, options) {
......@@ -4133,7 +4160,8 @@ class Model {
* // `by` is ignored, since each column has its own value
* instance.decrement({ answer: 42, tries: 1}, { by: 2 })
*
* @see {@link Model#reload}
* @see
* {@link Model#reload}
* @param {string|Array|Object} fields If a string is provided, that column is decremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is decremented by the value given
* @param {Object} [options] drecrement options
* @param {number} [options.by=1] The number to decrement by
......@@ -4156,7 +4184,7 @@ class Model {
/**
* Check whether this and `other` Instance refer to the same row
*
* @param {<Model>} other Other instance to compare against
* @param {Model} other Other instance to compare against
*
* @returns {boolean}
*/
......@@ -4192,7 +4220,8 @@ class Model {
* Proxies to calling `get` with no keys.
* This means get all values gotten from the DB, and apply all custom getters.
*
* @see {@link Model#get}
* @see
* {@link Model#get}
*
* @returns {Object}
*/
......
......@@ -25,8 +25,6 @@ const Op = require('./operators');
/**
* This is the main class, the entry point to sequelize.
*
* @class Sequelize
*/
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.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.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 {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:'
......@@ -158,6 +156,7 @@ class Sequelize {
sync: {},
timezone: '+00:00',
clientMinMessages: 'warning',
// eslint-disable-next-line no-console
logging: console.log,
omitNull: false,
native: false,
......@@ -193,6 +192,7 @@ class Sequelize {
if (this.options.logging === true) {
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;
}
......@@ -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} [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 {@link DataTypes} For a list of possible data types
* @see
* {@link DataTypes} For a list of possible data types
*
* @returns {Model} Newly defined model
*
......@@ -475,6 +477,7 @@ class Sequelize {
}
options = _.defaults(options, {
// eslint-disable-next-line no-console
logging: this.options.hasOwnProperty('logging') ? this.options.logging : console.log,
searchPath: this.options.hasOwnProperty('searchPath') ? this.options.searchPath : 'DEFAULT'
});
......@@ -557,7 +560,7 @@ class Sequelize {
}
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;
throw error;
}
......@@ -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),
* not a database table. In mysql and sqlite, this command will do nothing.
*
* @see {@link Model.schema}
* @see
* {@link Model.schema}
*
* @param {string} schema Name of the schema
* @param {Object} [options={}] query options
......@@ -759,7 +763,8 @@ class Sequelize {
* @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
* @returns {Promise}
*
* @see {@link Model.truncate} for more information
* @see
* {@link Model.truncate} for more information
*/
truncate(options) {
const models = [];
......@@ -782,7 +787,8 @@ class Sequelize {
* Drop all tables defined through this sequelize instance.
* This is done by calling Model.drop on each model.
*
* @see {@link Model.drop} for options
* @see
* {@link Model.drop} for options
*
* @param {Object} [options] The options passed to each call to Model.drop
* @param {boolean|Function} [options.logging] A function that logs sql queries, or false for no logging
......@@ -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.
* 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 {@link Sequelize.define}
* @see {@link Sequelize.col}
* @see
* {@link Model.findAll}
* @see
* {@link Sequelize.define}
* @see
* {@link Sequelize.col}
*
* @param {string} fn The function you want to call
* @param {any} args All further arguments will be passed as arguments to the function
......@@ -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.
*
* @see {@link Sequelize#fn}
* @see
* {@link Sequelize#fn}
*
* @param {string} col The name of the column
* @since v2.0.0-dev3
......@@ -904,7 +914,8 @@ class Sequelize {
/**
* An AND query
*
* @see {@link Model.findAll}
* @see
* {@link Model.findAll}
*
* @param {...string|Object} args Each argument will be joined by AND
* @since v2.0.0-dev3
......@@ -919,7 +930,8 @@ class Sequelize {
/**
* An OR query
*
* @see {@link Model.findAll}
* @see
* {@link Model.findAll}
*
* @param {...string|Object} args Each argument will be joined by OR
* @since v2.0.0-dev3
......@@ -934,7 +946,8 @@ class Sequelize {
/**
* 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|number|boolean} [value] An optional value to compare against. Produces a string of the form "<json path> = '<value>'".
......@@ -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`.
*
* @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 {Symbol} [comparator='Op.eq'] operator
......@@ -1080,6 +1094,7 @@ class Sequelize {
options = last;
// 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) {
args.splice(args.length-1, 1);
}
......@@ -1090,10 +1105,12 @@ class Sequelize {
if (options.logging) {
if (options.logging === true) {
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;
}
// 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) {
args = [`${args[0]} Elapsed time: ${args[1]}ms`];
}
......
......@@ -75,7 +75,8 @@ function escape(val, timeZone, dialect, format) {
val = val.replace(/\0/g, '\\0');
}
} 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) {
case '\0': return '\\0';
case '\n': return '\\n';
......@@ -109,7 +110,7 @@ function format(sql, values, timeZone, dialect) {
exports.format = format;
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)) {
return value;
}
......
......@@ -379,8 +379,8 @@ exports.removeTicks = removeTicks;
* address.coordinates.longitude: 12.5964313
* }
*
* @param value, an Object
* @returns Object, an flattened object
* @param {Object} value an Object
* @returns {Object} a flattened object
* @private
*/
function flattenObjectDeep(value) {
......@@ -486,6 +486,7 @@ exports.Where = Where;
/**
* getOperators
*
* @param {Object} obj
* @returns {Array<Symbol>} All operators properties of obj
* @private
......@@ -497,8 +498,9 @@ exports.getOperators = getOperators;
/**
* getComplexKeys
*
* @param {Object} obj
* @returns {Array<String|Symbol>} All keys including operators
* @returns {Array<string|Symbol>} All keys including operators
* @private
*/
function getComplexKeys(obj) {
......@@ -508,8 +510,9 @@ exports.getComplexKeys = getComplexKeys;
/**
* getComplexSize
*
* @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
*/
function getComplexSize(obj) {
......@@ -544,6 +547,7 @@ exports.generateEnumName = generateEnumName;
/**
* Returns an new Object which keys are camelized
*
* @param {Object} obj
* @returns {string}
* @private
......@@ -570,11 +574,9 @@ exports.camelizeObjectKeys = camelizeObjectKeys;
* @returns {Object} Returns `object`.
* @private
*/
function defaults(object) {
function defaults(object, ...sources) {
object = Object(object);
const sources = _.tail(arguments);
sources.forEach(source => {
if (source) {
source = Object(source);
......@@ -602,7 +604,7 @@ exports.defaults = defaults;
* @param {Object} index
* @param {Array} index.fields
* @param {string} [index.name]
* @param {String|Object} tableName
* @param {string|Object} tableName
*
* @returns {Object}
* @private
......
......@@ -3,8 +3,9 @@
/**
* Wraps a constructor to not need the `new` keyword using a proxy.
* 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) {
return new Proxy(Class, {
......
......@@ -34,6 +34,7 @@ class Logger {
}
warn(message) {
// eslint-disable-next-line no-console
console.warn(`(${this.config.context}) Warning: ${message}`);
}
......
......@@ -39,7 +39,7 @@ const extensions = {
return !this.regex(str, pattern, modifiers);
},
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) {
const number = parseFloat(str);
......
......@@ -2,6 +2,7 @@
"rules": {
"no-invalid-this": 0,
"no-unused-expressions": 0,
"camelcase": 0
"camelcase": 0,
"no-console": 0
}
}
......@@ -153,7 +153,7 @@ describe(Support.getTestDialectTeaser('HasOne'), () => {
return this.sequelize.showAllSchemas().then(schemas => {
if (dialect === 'postgres' || dialect === 'mssql' || dialect === 'mariadb') {
expect(schemas).to.not.have.property('admin');
};
}
});
});
});
......
......@@ -22,7 +22,7 @@ if (dialect.match(/^postgres/)) {
});
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', () => {
......@@ -49,11 +49,11 @@ if (dialect.match(/^postgres/)) {
});
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', () => {
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', () => {
......
......@@ -54,7 +54,7 @@ if (dialect.match(/^postgres/)) {
return this.queryInterface.databaseVersion()
.then(res => {
// 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'), () => {
/*
* shortcut for building simple {name: 'foo'} seed data
*/
function build() {
return Array.prototype.slice.call(arguments).map(arg => ({ name: arg }));
function build(...args) {
return args.map(arg => ({ name: arg }));
}
/*
......
......@@ -261,8 +261,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
return User.sync({ force: true, logging: _.after(2, _.once(sql => {
if (dialect === 'mssql') {
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*([`"[]?user_and_email[`"\]]?)?\s*UNIQUE\s*\([`"[]?username[`"\]]?, [`"[]?email[`"\]]?\)/);
expect(sql).to.match(/CONSTRAINT\s*([`"[]?a_and_b[`"\]]?)?\s*UNIQUE\s*\([`"[]?aCol[`"\]]?, [`"[]?bCol[`"\]]?\)/);
} else {
expect(sql).to.match(/UNIQUE\s*([`"]?user_and_email[`"]?)?\s*\([`"]?username[`"]?, [`"]?email[`"]?\)/);
expect(sql).to.match(/UNIQUE\s*([`"]?a_and_b[`"]?)?\s*\([`"]?aCol[`"]?, [`"]?bCol[`"]?\)/);
......@@ -2517,7 +2517,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
if (semver.gte(current.options.databaseVersion, '5.6.0')) {
expect(err.message).to.match(/Cannot add foreign key constraint/);
} else {
expect(err.message).to.match(/Can\'t create table/);
expect(err.message).to.match(/Can't create table/);
}
} else if (dialect === 'sqlite') {
// the parser should not end up here ... see above
......
......@@ -110,7 +110,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
where: { 'specialkey': 'awesome' },
logging(sql) {
test = true;
expect(sql).to.match(/WHERE ["|`|\[]UserPrimary["|`|\]]\.["|`|\[]specialkey["|`|\]] = N?'awesome'/);
expect(sql).to.match(/WHERE ["|`|[]UserPrimary["|`|\]]\.["|`|[]specialkey["|`|\]] = N?'awesome'/);
}
}).then(() => {
expect(test).to.be.true;
......
......@@ -25,7 +25,7 @@ function assertSameConnection(newConnection, oldConnection) {
default:
throw new Error('Unsupported dialect');
}
};
}
function assertNewConnection(newConnection, oldConnection) {
switch (dialect) {
......@@ -46,7 +46,7 @@ function assertNewConnection(newConnection, oldConnection) {
default:
throw new Error('Unsupported dialect');
}
};
}
function unwrapAndAttachMSSQLUniqueId(connection) {
if (dialect === 'mssql') {
......
......@@ -1021,7 +1021,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => {
} else if (dialect === 'mssql') {
expect(err.message).to.equal('Login failed for user \'bar\'.');
} else {
expect(err.message.toString()).to.match(/.*Access\ denied.*/);
expect(err.message.toString()).to.match(/.*Access denied.*/);
}
});
});
......
......@@ -218,7 +218,7 @@ if (dialect === 'mariadb') {
},
{
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' }],
......
......@@ -175,7 +175,7 @@ if (dialect === 'mysql') {
},
{
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' }],
......
......@@ -181,43 +181,43 @@ if (dialect.startsWith('postgres')) {
createTableQuery: [
{
arguments: ['myTable', { int: 'INTEGER', bigint: 'BIGINT', smallint: 'SMALLINT' }],
expectation: 'CREATE TABLE IF NOT EXISTS \"myTable\" (\"int\" INTEGER, \"bigint\" BIGINT, \"smallint\" SMALLINT);'
expectation: 'CREATE TABLE IF NOT EXISTS "myTable" ("int" INTEGER, "bigint" BIGINT, "smallint" SMALLINT);'
},
{
arguments: ['myTable', { serial: 'INTEGER SERIAL', bigserial: 'BIGINT SERIAL', smallserial: 'SMALLINT SERIAL' }],
expectation: 'CREATE TABLE IF NOT EXISTS \"myTable\" (\"serial\" SERIAL, \"bigserial\" BIGSERIAL, \"smallserial\" SMALLSERIAL);'
expectation: 'CREATE TABLE IF NOT EXISTS "myTable" ("serial" SERIAL, "bigserial" BIGSERIAL, "smallserial" SMALLSERIAL);'
},
{
arguments: ['myTable', { int: 'INTEGER COMMENT Test', foo: 'INTEGER COMMENT Foo Comment' }],
expectation: 'CREATE TABLE IF NOT EXISTS \"myTable\" (\"int\" INTEGER , \"foo\" INTEGER ); COMMENT ON COLUMN \"myTable\".\"int\" IS \'Test\'; COMMENT ON COLUMN \"myTable\".\"foo\" IS \'Foo Comment\';'
expectation: 'CREATE TABLE IF NOT EXISTS "myTable" ("int" INTEGER , "foo" INTEGER ); COMMENT ON COLUMN "myTable"."int" IS \'Test\'; COMMENT ON COLUMN "myTable"."foo" IS \'Foo Comment\';'
},
{
arguments: ['myTable', { title: 'VARCHAR(255)', name: 'VARCHAR(255)' }],
expectation: 'CREATE TABLE IF NOT EXISTS \"myTable\" (\"title\" VARCHAR(255), \"name\" VARCHAR(255));'
expectation: 'CREATE TABLE IF NOT EXISTS "myTable" ("title" VARCHAR(255), "name" VARCHAR(255));'
},
{
arguments: ['myTable', { data: current.normalizeDataType(DataTypes.BLOB).toSql() }],
expectation: 'CREATE TABLE IF NOT EXISTS \"myTable\" (\"data\" BYTEA);'
expectation: 'CREATE TABLE IF NOT EXISTS "myTable" ("data" BYTEA);'
},
{
arguments: ['myTable', { data: current.normalizeDataType(DataTypes.BLOB('long')).toSql() }],
expectation: 'CREATE TABLE IF NOT EXISTS \"myTable\" (\"data\" BYTEA);'
expectation: 'CREATE TABLE IF NOT EXISTS "myTable" ("data" BYTEA);'
},
{
arguments: [{ tableName: 'myTable', schema: 'mySchema' }, { title: 'VARCHAR(255)', name: 'VARCHAR(255)' }],
expectation: 'CREATE TABLE IF NOT EXISTS \"mySchema\".\"myTable\" (\"title\" VARCHAR(255), \"name\" VARCHAR(255));'
expectation: 'CREATE TABLE IF NOT EXISTS "mySchema"."myTable" ("title" VARCHAR(255), "name" VARCHAR(255));'
},
{
arguments: ['myTable', { title: 'ENUM("A", "B", "C")', name: 'VARCHAR(255)' }],
expectation: 'CREATE TABLE IF NOT EXISTS \"myTable\" (\"title\" \"public\".\"enum_myTable_title\", \"name\" VARCHAR(255));'
expectation: 'CREATE TABLE IF NOT EXISTS "myTable" ("title" "public"."enum_myTable_title", "name" VARCHAR(255));'
},
{
arguments: ['myTable', { title: 'VARCHAR(255)', name: 'VARCHAR(255)', id: 'INTEGER PRIMARY KEY' }],
expectation: 'CREATE TABLE IF NOT EXISTS \"myTable\" (\"title\" VARCHAR(255), \"name\" VARCHAR(255), \"id\" INTEGER , PRIMARY KEY (\"id\"));'
expectation: 'CREATE TABLE IF NOT EXISTS "myTable" ("title" VARCHAR(255), "name" VARCHAR(255), "id" INTEGER , PRIMARY KEY ("id"));'
},
{
arguments: ['myTable', { title: 'VARCHAR(255)', name: 'VARCHAR(255)', otherId: 'INTEGER REFERENCES "otherTable" ("id") ON DELETE CASCADE ON UPDATE NO ACTION' }],
expectation: 'CREATE TABLE IF NOT EXISTS \"myTable\" (\"title\" VARCHAR(255), \"name\" VARCHAR(255), \"otherId\" INTEGER REFERENCES \"otherTable\" (\"id\") ON DELETE CASCADE ON UPDATE NO ACTION);'
expectation: 'CREATE TABLE IF NOT EXISTS "myTable" ("title" VARCHAR(255), "name" VARCHAR(255), "otherId" INTEGER REFERENCES "otherTable" ("id") ON DELETE CASCADE ON UPDATE NO ACTION);'
},
// Variants when quoteIdentifiers is false
......@@ -251,19 +251,19 @@ if (dialect.startsWith('postgres')) {
dropTableQuery: [
{
arguments: ['myTable'],
expectation: 'DROP TABLE IF EXISTS \"myTable\";'
expectation: 'DROP TABLE IF EXISTS "myTable";'
},
{
arguments: [{ tableName: 'myTable', schema: 'mySchema' }],
expectation: 'DROP TABLE IF EXISTS \"mySchema\".\"myTable\";'
expectation: 'DROP TABLE IF EXISTS "mySchema"."myTable";'
},
{
arguments: ['myTable', { cascade: true }],
expectation: 'DROP TABLE IF EXISTS \"myTable\" CASCADE;'
expectation: 'DROP TABLE IF EXISTS "myTable" CASCADE;'
},
{
arguments: [{ tableName: 'myTable', schema: 'mySchema' }, { cascade: true }],
expectation: 'DROP TABLE IF EXISTS \"mySchema\".\"myTable\" CASCADE;'
expectation: 'DROP TABLE IF EXISTS "mySchema"."myTable" CASCADE;'
},
// Variants when quoteIdentifiers is false
......@@ -302,13 +302,13 @@ if (dialect.startsWith('postgres')) {
selectQuery: [
{
arguments: ['myTable'],
expectation: 'SELECT * FROM \"myTable\";'
expectation: 'SELECT * FROM "myTable";'
}, {
arguments: ['myTable', { attributes: ['id', 'name'] }],
expectation: 'SELECT \"id\", \"name\" FROM \"myTable\";'
expectation: 'SELECT "id", "name" FROM "myTable";'
}, {
arguments: ['myTable', { where: { id: 2 } }],
expectation: 'SELECT * FROM \"myTable\" WHERE \"myTable\".\"id\" = 2;'
expectation: 'SELECT * FROM "myTable" WHERE "myTable"."id" = 2;'
}, {
arguments: ['myTable', { where: { name: 'foo' } }],
expectation: "SELECT * FROM \"myTable\" WHERE \"myTable\".\"name\" = 'foo';"
......@@ -317,10 +317,10 @@ if (dialect.startsWith('postgres')) {
expectation: "SELECT * FROM \"myTable\" WHERE \"myTable\".\"name\" = 'foo'';DROP TABLE myTable;';"
}, {
arguments: ['myTable', { where: 2 }],
expectation: 'SELECT * FROM \"myTable\" WHERE \"myTable\".\"id\" = 2;'
expectation: 'SELECT * FROM "myTable" WHERE "myTable"."id" = 2;'
}, {
arguments: ['foo', { attributes: [['count(*)', 'count']] }],
expectation: 'SELECT count(*) AS \"count\" FROM \"foo\";'
expectation: 'SELECT count(*) AS "count" FROM "foo";'
}, {
arguments: ['myTable', { order: ['id'] }],
expectation: 'SELECT * FROM "myTable" ORDER BY "id";',
......@@ -422,10 +422,10 @@ if (dialect.startsWith('postgres')) {
}, {
title: 'single string argument should be quoted',
arguments: ['myTable', { group: 'name' }],
expectation: 'SELECT * FROM \"myTable\" GROUP BY \"name\";'
expectation: 'SELECT * FROM "myTable" GROUP BY "name";'
}, {
arguments: ['myTable', { group: ['name'] }],
expectation: 'SELECT * FROM \"myTable\" GROUP BY \"name\";'
expectation: 'SELECT * FROM "myTable" GROUP BY "name";'
}, {
title: 'functions work for group by',
arguments: ['myTable', function(sequelize) {
......@@ -433,7 +433,7 @@ if (dialect.startsWith('postgres')) {
group: [sequelize.fn('YEAR', sequelize.col('createdAt'))]
};
}],
expectation: 'SELECT * FROM \"myTable\" GROUP BY YEAR(\"createdAt\");',
expectation: 'SELECT * FROM "myTable" GROUP BY YEAR("createdAt");',
needsSequelize: true
}, {
title: 'It is possible to mix sequelize.fn and string arguments to group by',
......@@ -442,12 +442,12 @@ if (dialect.startsWith('postgres')) {
group: [sequelize.fn('YEAR', sequelize.col('createdAt')), 'title']
};
}],
expectation: 'SELECT * FROM \"myTable\" GROUP BY YEAR(\"createdAt\"), \"title\";',
expectation: 'SELECT * FROM "myTable" GROUP BY YEAR("createdAt"), "title";',
context: QueryGenerator,
needsSequelize: true
}, {
arguments: ['myTable', { group: ['name', 'title'] }],
expectation: 'SELECT * FROM \"myTable\" GROUP BY \"name\", \"title\";'
expectation: 'SELECT * FROM "myTable" GROUP BY "name", "title";'
}, {
title: 'HAVING clause works with where-like hash',
arguments: ['myTable', function(sequelize) {
......@@ -457,22 +457,22 @@ if (dialect.startsWith('postgres')) {
having: { creationYear: { [Op.gt]: 2002 } }
};
}],
expectation: 'SELECT *, YEAR(\"createdAt\") AS \"creationYear\" FROM \"myTable\" GROUP BY \"creationYear\", \"title\" HAVING \"creationYear\" > 2002;',
expectation: 'SELECT *, YEAR("createdAt") AS "creationYear" FROM "myTable" GROUP BY "creationYear", "title" HAVING "creationYear" > 2002;',
context: QueryGenerator,
needsSequelize: true
}, {
arguments: ['myTable', { limit: 10 }],
expectation: 'SELECT * FROM \"myTable\" LIMIT 10;'
expectation: 'SELECT * FROM "myTable" LIMIT 10;'
}, {
arguments: ['myTable', { limit: 10, offset: 2 }],
expectation: 'SELECT * FROM \"myTable\" LIMIT 10 OFFSET 2;'
expectation: 'SELECT * FROM "myTable" LIMIT 10 OFFSET 2;'
}, {
title: 'uses offset even if no limit was passed',
arguments: ['myTable', { offset: 2 }],
expectation: 'SELECT * FROM \"myTable\" OFFSET 2;'
expectation: 'SELECT * FROM "myTable" OFFSET 2;'
}, {
arguments: [{ tableName: 'myTable', schema: 'mySchema' }],
expectation: 'SELECT * FROM \"mySchema\".\"myTable\";'
expectation: 'SELECT * FROM "mySchema"."myTable";'
}, {
arguments: [{ tableName: 'myTable', schema: 'mySchema' }, { where: { name: "foo';DROP TABLE mySchema.myTable;" } }],
expectation: "SELECT * FROM \"mySchema\".\"myTable\" WHERE \"mySchema\".\"myTable\".\"name\" = 'foo'';DROP TABLE mySchema.myTable;';"
......@@ -600,7 +600,7 @@ if (dialect.startsWith('postgres')) {
{
arguments: ['myTable', {}],
expectation: {
query: 'INSERT INTO \"myTable\" DEFAULT VALUES;',
query: 'INSERT INTO "myTable" DEFAULT VALUES;',
bind: []
}
},
......@@ -710,7 +710,7 @@ if (dialect.startsWith('postgres')) {
};
}],
expectation: {
query: 'INSERT INTO \"myTable\" (\"foo\") VALUES (NOW());',
query: 'INSERT INTO "myTable" ("foo") VALUES (NOW());',
bind: []
},
needsSequelize: true
......@@ -1084,13 +1084,13 @@ if (dialect.startsWith('postgres')) {
removeIndexQuery: [
{
arguments: ['User', 'user_foo_bar'],
expectation: 'DROP INDEX IF EXISTS \"user_foo_bar\"'
expectation: 'DROP INDEX IF EXISTS "user_foo_bar"'
}, {
arguments: ['User', ['foo', 'bar']],
expectation: 'DROP INDEX IF EXISTS \"user_foo_bar\"'
expectation: 'DROP INDEX IF EXISTS "user_foo_bar"'
}, {
arguments: ['User', 'mySchema.user_foo_bar'],
expectation: 'DROP INDEX IF EXISTS \"mySchema\".\"user_foo_bar\"'
expectation: 'DROP INDEX IF EXISTS "mySchema"."user_foo_bar"'
},
// Variants when quoteIdentifiers is false
......@@ -1117,12 +1117,12 @@ if (dialect.startsWith('postgres')) {
},
{
arguments: [{ parent: 'MockTransaction', name: 'transaction-uid' }],
expectation: 'SAVEPOINT \"transaction-uid\";',
expectation: 'SAVEPOINT "transaction-uid";',
context: { options: { quoteIdentifiers: false } }
},
{
arguments: [{ parent: 'MockTransaction', name: 'transaction-uid' }],
expectation: 'SAVEPOINT \"transaction-uid\";',
expectation: 'SAVEPOINT "transaction-uid";',
context: { options: { quoteIdentifiers: true } }
}
],
......@@ -1135,12 +1135,12 @@ if (dialect.startsWith('postgres')) {
},
{
arguments: [{ parent: 'MockTransaction', name: 'transaction-uid' }],
expectation: 'ROLLBACK TO SAVEPOINT \"transaction-uid\";',
expectation: 'ROLLBACK TO SAVEPOINT "transaction-uid";',
context: { options: { quoteIdentifiers: false } }
},
{
arguments: [{ parent: 'MockTransaction', name: 'transaction-uid' }],
expectation: 'ROLLBACK TO SAVEPOINT \"transaction-uid\";',
expectation: 'ROLLBACK TO SAVEPOINT "transaction-uid";',
context: { options: { quoteIdentifiers: true } }
}
],
......
......@@ -127,7 +127,7 @@ if (dialect === 'sqlite') {
},
{
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' }],
......@@ -174,7 +174,7 @@ if (dialect === 'sqlite') {
context: QueryGenerator
}, {
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
}, {
arguments: ['myTable', { where: 2 }],
......
......@@ -24,7 +24,7 @@ describe('errors', () => {
const stackParts = err.stack.split('\n');
const fullErrorName = `Sequelize${errorName}`;
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', () => {
const fullErrorName = `Sequelize${errorName}`;
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'), () => {
}
if (typeof val === 'string') {
// Canonicalize phone number
val = val.replace(/^\+/, '00').replace(/\(0\)|[\s+\/.\-\(\)]/g, '');
val = val.replace(/^\+/, '00').replace(/\(0\)|[\s+/.\-()]/g, '');
}
this.setDataValue('phoneNumber', val);
}
......
......@@ -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)',
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;",
default: "DELETE FROM [public.test_users] WHERE `name` = 'foo\\';DROP TABLE mySchema.myTable;' LIMIT 10"
}
......
......@@ -462,7 +462,7 @@ describe(Support.getTestDialectTeaser('SQL'), () => {
expectsql(sql.selectQuery('User', {
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];'
});
});
......
......@@ -25,10 +25,10 @@ describe(Support.getTestDialectTeaser('Utils'), () => {
expect(Utils.toDefaultValue(DataTypes.UUIDV4)).to.equal('UUIDV4');
});
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', () => {
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', () => {
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!