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

Commit 2fc43c4c by greenkeeper[bot] Committed by Felix Becker

chore(package): update eslint to version 4.2.0 (#7908)

1 parent 8d4700fb
Showing with 814 additions and 814 deletions
......@@ -153,8 +153,8 @@ class BelongsTo extends Association {
}
options.where = options.where ?
{$and: [where, options.where]} :
where;
{$and: [where, options.where]} :
where;
if (instances) {
return Target.findAll(options).then(results => {
......
......@@ -202,8 +202,8 @@ class HasMany extends Association {
options.where = options.where ?
{$and: [where, options.where]} :
where;
{$and: [where, options.where]} :
where;
if (options.hasOwnProperty('scope')) {
if (!options.scope) {
......
......@@ -151,8 +151,8 @@ class HasOne extends Association {
}
options.where = options.where ?
{$and: [where, options.where]} :
where;
{$and: [where, options.where]} :
where;
if (instances) {
return Target.findAll(options).then(results => {
......
......@@ -269,18 +269,18 @@ class ConnectionManager {
return Promise.race([
this.pool.acquire(options.priority, options.type, options.useMaster),
new Promise((resolve, reject) =>
timers.setTimeout(() => {
if (this.poolError) {
reject(this.poolError);
}
}, 0))
timers.setTimeout(() => {
if (this.poolError) {
reject(this.poolError);
}
}, 0))
])
.tap(() => { debug('connection acquired'); })
.catch(e => {
e = this.poolError || e;
this.poolError = null;
throw e;
});
.tap(() => { debug('connection acquired'); })
.catch(e => {
e = this.poolError || e;
this.poolError = null;
throw e;
});
});
}
......
......@@ -1109,7 +1109,7 @@ const QueryGenerator = {
return Utils.spliceStr(baseQuery, splicePos, placeHolder.length, this.getWhereConditions(groupWhere, groupedTableName));
}).join(
this._dialect.supports['UNION ALL'] ? ' UNION ALL ' : ' UNION '
)
)
+ ')', mainTable.as));
} else {
mainQueryItems.push(this.selectFromTableFragment(options, mainTable.model, attributes.main, mainTable.quotedName, mainTable.as));
......
......@@ -63,7 +63,7 @@ const QueryGenerator = {
primaryKeys.push(attr);
if (Utils._.includes(dataType, 'REFERENCES')) {
// MSSQL doesn't support inline REFERENCES declarations: move to the end
// MSSQL doesn't support inline REFERENCES declarations: move to the end
match = dataType.match(/^(.+) (REFERENCES.*)$/);
attrStr.push(this.quoteIdentifier(attr) + ' ' + match[1].replace(/PRIMARY KEY/, ''));
foreignKeys[attr] = match[2];
......@@ -294,7 +294,7 @@ const QueryGenerator = {
const replacements = {
table: this.quoteTable(tableName),
attributes: allAttributes.map(attr =>
this.quoteIdentifier(attr)).join(','),
this.quoteIdentifier(attr)).join(','),
tuples: tuples.slice(offset, Math.min(tuples.length, offset + batch)),
output: outputFragment
};
......@@ -425,11 +425,11 @@ const QueryGenerator = {
return false;
}
})
.map(key => {
const value = this.escape(updateValues[key]);
key = this.quoteIdentifier(key);
return `${targetTableAlias}.${key} = ${value}`;
}).join(', ');
.map(key => {
const value = this.escape(updateValues[key]);
key = this.quoteIdentifier(key);
return `${targetTableAlias}.${key} = ${value}`;
}).join(', ');
const insertSnippet = `(${insertKeysQuoted}) VALUES(${insertValuesEscaped})`;
let query = `MERGE INTO ${tableNameQuoted} WITH(HOLDLOCK) AS ${targetTableAlias} USING (${sourceTableQuery}) AS ${sourceTableAlias}(${insertKeysQuoted}) ON ${joinCondition}`;
......
......@@ -118,34 +118,34 @@ class ConnectionManager extends AbstractConnectionManager {
connection.on('error', errorHandler);
connection.once('connect', connectHandler);
})
.tap (() => { debug('connection acquired'); })
.then(connection => {
return new Utils.Promise((resolve, reject) => {
.tap (() => { debug('connection acquired'); })
.then(connection => {
return new Utils.Promise((resolve, reject) => {
// set timezone for this connection
// but named timezone are not directly supported in mysql, so get its offset first
let tzOffset = this.sequelize.options.timezone;
tzOffset = /\//.test(tzOffset) ? momentTz.tz(tzOffset).format('Z') : tzOffset;
connection.query(`SET time_zone = '${tzOffset}'`, err => {
if (err) { reject(err); } else { resolve(connection); }
let tzOffset = this.sequelize.options.timezone;
tzOffset = /\//.test(tzOffset) ? momentTz.tz(tzOffset).format('Z') : tzOffset;
connection.query(`SET time_zone = '${tzOffset}'`, err => {
if (err) { reject(err); } else { resolve(connection); }
});
});
})
.catch(err => {
switch (err.code) {
case 'ECONNREFUSED':
throw new SequelizeErrors.ConnectionRefusedError(err);
case 'ER_ACCESS_DENIED_ERROR':
throw new SequelizeErrors.AccessDeniedError(err);
case 'ENOTFOUND':
throw new SequelizeErrors.HostNotFoundError(err);
case 'EHOSTUNREACH':
throw new SequelizeErrors.HostNotReachableError(err);
case 'EINVAL':
throw new SequelizeErrors.InvalidConnectionError(err);
default:
throw new SequelizeErrors.ConnectionError(err);
}
});
})
.catch(err => {
switch (err.code) {
case 'ECONNREFUSED':
throw new SequelizeErrors.ConnectionRefusedError(err);
case 'ER_ACCESS_DENIED_ERROR':
throw new SequelizeErrors.AccessDeniedError(err);
case 'ENOTFOUND':
throw new SequelizeErrors.HostNotFoundError(err);
case 'EHOSTUNREACH':
throw new SequelizeErrors.HostNotReachableError(err);
case 'EINVAL':
throw new SequelizeErrors.InvalidConnectionError(err);
default:
throw new SequelizeErrors.ConnectionError(err);
}
});
}
disconnect(connection) {
......
......@@ -40,7 +40,7 @@ const QueryGenerator = {
primaryKeys.push(attr);
if (Utils._.includes(dataType, 'REFERENCES')) {
// MySQL doesn't support inline REFERENCES declarations: move to the end
// MySQL doesn't support inline REFERENCES declarations: move to the end
match = dataType.match(/^(.+) (REFERENCES.*)$/);
attrStr.push(this.quoteIdentifier(attr) + ' ' + match[1].replace(/PRIMARY KEY/, ''));
foreignKeys[attr] = match[2];
......
......@@ -26,9 +26,9 @@ function removeColumn(tableName, columnName, options) {
options = options || {};
return this.sequelize.query(
this.QueryGenerator.getForeignKeyQuery(tableName, columnName),
_.assign({ raw: true }, options)
)
this.QueryGenerator.getForeignKeyQuery(tableName, columnName),
_.assign({ raw: true }, options)
)
.spread(results => {
//Exclude primary key constraint
if (!results.length || results[0].constraint_name === 'PRIMARY') {
......
......@@ -59,17 +59,17 @@ class Query extends AbstractQuery {
}).setMaxListeners(100);
})
// Log warnings if we've got them.
.then(results => {
if (showWarnings && results && results.warningStatus > 0) {
return this.logWarnings(results);
}
return results;
})
.then(results => {
if (showWarnings && results && results.warningStatus > 0) {
return this.logWarnings(results);
}
return results;
})
// Return formatted results...
.then(results => this.formatResults(results));
.then(results => this.formatResults(results));
}
/**
/**
* High level function that handles the results of a query execution.
*
*
......
......@@ -62,22 +62,22 @@ class ConnectionManager extends AbstractConnectionManager {
if (config.dialectOptions) {
Utils._.merge(connectionConfig,
Utils._.pick(config.dialectOptions, [
Utils._.pick(config.dialectOptions, [
// see [http://www.postgresql.org/docs/9.3/static/runtime-config-logging.html#GUC-APPLICATION-NAME]
'application_name',
// choose the SSL mode with the PGSSLMODE environment variable
// object format: [https://github.com/brianc/node-postgres/blob/master/lib/connection.js#L79]
// see also [http://www.postgresql.org/docs/9.3/static/libpq-ssl.html]
'ssl',
// In addition to the values accepted by the corresponding server,
// you can use "auto" to determine the right encoding from the
// current locale in the client (LC_CTYPE environment variable on Unix systems)
'client_encoding',
// !! DONT SET THIS TO TRUE !!
// (unless you know what you're doing)
// see [http://www.postgresql.org/message-id/flat/bc9549a50706040852u27633f41ib1e6b09f8339d845@mail.gmail.com#bc9549a50706040852u27633f41ib1e6b09f8339d845@mail.gmail.com]
'binary'
]));
'application_name',
// choose the SSL mode with the PGSSLMODE environment variable
// object format: [https://github.com/brianc/node-postgres/blob/master/lib/connection.js#L79]
// see also [http://www.postgresql.org/docs/9.3/static/libpq-ssl.html]
'ssl',
// In addition to the values accepted by the corresponding server,
// you can use "auto" to determine the right encoding from the
// current locale in the client (LC_CTYPE environment variable on Unix systems)
'client_encoding',
// !! DONT SET THIS TO TRUE !!
// (unless you know what you're doing)
// see [http://www.postgresql.org/message-id/flat/bc9549a50706040852u27633f41ib1e6b09f8339d845@mail.gmail.com#bc9549a50706040852u27633f41ib1e6b09f8339d845@mail.gmail.com]
'binary'
]));
}
return new Promise((resolve, reject) => {
......
......@@ -185,8 +185,8 @@ class Query extends AbstractQuery {
}
return tableTypes[name]
? query.applyParsers(tableTypes[name], value)
: value;
? query.applyParsers(tableTypes[name], value)
: value;
});
});
}
......
......@@ -284,7 +284,7 @@ exports.applyTo = applyTo;
* @memberOf Sequelize.Model
*/
/**
/**
* A hook that is run after creating or updating a single instance, It proxies `afterCreate` and `afterUpdate`
* @param {String} name
* @param {Function} fn A callback function that is called with attributes, options
......@@ -520,7 +520,7 @@ exports.applyTo = applyTo;
* @memberOf Sequelize
*/
/**
/**
* A hook that is run before sequelize.sync call
* @param {String} name
* @param {Function} fn A callback function that is called with options passed to sequelize.sync
......@@ -528,7 +528,7 @@ exports.applyTo = applyTo;
* @memberOf Sequelize
*/
/**
/**
* A hook that is run after sequelize.sync call
* @param {String} name
* @param {Function} fn A callback function that is called with options passed to sequelize.sync
......
......@@ -108,8 +108,8 @@ class InstanceValidator {
return runHooks('beforeValidate', this.modelInstance, this.options)
.then(() =>
this._validate()
.catch(error => runHooks('validationFailed', this.modelInstance, this.options, error)
.then(newError => { throw newError || error; }))
.catch(error => runHooks('validationFailed', this.modelInstance, this.options, error)
.then(newError => { throw newError || error; }))
)
.then(() => runHooks('afterValidate', this.modelInstance, this.options))
.return(this.modelInstance);
......@@ -210,8 +210,8 @@ class InstanceValidator {
});
return Promise
.all(validators)
.then(results => this._handleReflectedResult(field, value, results));
.all(validators)
.then(results => this._handleReflectedResult(field, value, results));
}
/**
......@@ -249,11 +249,11 @@ class InstanceValidator {
validatorFunction = Promise.promisify(validator.bind(this.modelInstance));
}
return validatorFunction()
.catch(e => this._pushError(false, errorKey, e, optValue));
.catch(e => this._pushError(false, errorKey, e, optValue));
} else {
return Promise
.try(() => validator.call(this.modelInstance, invokeArgs))
.catch(e => this._pushError(false, errorKey, e, optValue));
.try(() => validator.call(this.modelInstance, invokeArgs))
.catch(e => this._pushError(false, errorKey, e, optValue));
}
}
......@@ -323,8 +323,8 @@ class InstanceValidator {
if (rawAttribute.allowNull === false && (value === null || value === undefined)) {
const validators = this.modelInstance.validators[field];
const errMsg = validators
? (validators.notNull || {}).msg
: `${field} cannot be null`;
? (validators.notNull || {}).msg
: `${field} cannot be null`;
error = new sequelizeError.ValidationErrorItem(errMsg, 'notNull Violation', field, value);
this.errors.push(error);
}
......
......@@ -1098,59 +1098,59 @@ class Model {
return this.drop(options);
}
})
.then(() => this.QueryInterface.createTable(this.getTableName(options), attributes, options, this))
.then(() => {
if (options.alter) {
return this.QueryInterface.describeTable(this.getTableName(options))
.then(columns => {
const changes = []; // array of promises to run
_.each(attributes, (columnDesc, columnName) => {
if (!columns[columnName]) {
changes.push(() => this.QueryInterface.addColumn(this.getTableName(options), columnName, attributes[columnName]));
}
});
_.each(columns, (columnDesc, columnName) => {
if (!attributes[columnName]) {
changes.push(() => this.QueryInterface.removeColumn(this.getTableName(options), columnName, options));
} else if (!attributes[columnName].primaryKey) {
changes.push(() => this.QueryInterface.changeColumn(this.getTableName(options), columnName, attributes[columnName]));
}
.then(() => this.QueryInterface.createTable(this.getTableName(options), attributes, options, this))
.then(() => {
if (options.alter) {
return this.QueryInterface.describeTable(this.getTableName(options))
.then(columns => {
const changes = []; // array of promises to run
_.each(attributes, (columnDesc, columnName) => {
if (!columns[columnName]) {
changes.push(() => this.QueryInterface.addColumn(this.getTableName(options), columnName, attributes[columnName]));
}
});
_.each(columns, (columnDesc, columnName) => {
if (!attributes[columnName]) {
changes.push(() => this.QueryInterface.removeColumn(this.getTableName(options), columnName, options));
} else if (!attributes[columnName].primaryKey) {
changes.push(() => this.QueryInterface.changeColumn(this.getTableName(options), columnName, attributes[columnName]));
}
});
return changes.reduce((p, fn) => p.then(fn), Promise.resolve());
});
return changes.reduce((p, fn) => p.then(fn), Promise.resolve());
});
}
})
.then(() => this.QueryInterface.showIndex(this.getTableName(options), options))
.then(indexes => {
}
})
.then(() => this.QueryInterface.showIndex(this.getTableName(options), options))
.then(indexes => {
// Assign an auto-generated name to indexes which are not named by the user
this.options.indexes = this.QueryInterface.nameIndexes(this.options.indexes, this.tableName);
this.options.indexes = this.QueryInterface.nameIndexes(this.options.indexes, this.tableName);
indexes = _.filter(this.options.indexes, item1 =>
!_.some(indexes, item2 => item1.name === item2.name)
).sort((index1, index2) => {
if (this.sequelize.options.dialect === 'postgres') {
indexes = _.filter(this.options.indexes, item1 =>
!_.some(indexes, item2 => item1.name === item2.name)
).sort((index1, index2) => {
if (this.sequelize.options.dialect === 'postgres') {
// move concurrent indexes to the bottom to avoid weird deadlocks
if (index1.concurrently === true) return 1;
if (index2.concurrently === true) return -1;
}
if (index1.concurrently === true) return 1;
if (index2.concurrently === true) return -1;
}
return 0;
});
return 0;
});
return Promise.map(indexes, index => this.QueryInterface.addIndex(
this.getTableName(options),
_.assign({
logging: options.logging,
benchmark: options.benchmark,
transaction: options.transaction
}, index),
this.tableName
));
}).then(() => {
if (options.hooks) {
return this.runHooks('afterSync', options);
}
}).return(this);
return Promise.map(indexes, index => this.QueryInterface.addIndex(
this.getTableName(options),
_.assign({
logging: options.logging,
benchmark: options.benchmark,
transaction: options.transaction
}, index),
this.tableName
));
}).then(() => {
if (options.hooks) {
return this.runHooks('afterSync', options);
}
}).return(this);
}
/**
......@@ -2835,7 +2835,7 @@ class Model {
return this.associations.hasOwnProperty(alias);
}
/**
/**
* Increment the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The increment is done using a
* ```sql
* SET column = column + X WHERE foo = 'bar'
......@@ -3511,31 +3511,31 @@ class Model {
}
return this.constructor.runHooks('before' + hook, this, options)
.then(() => {
if (options.defaultFields && !this.isNewRecord) {
afterHookValues = _.pick(this.dataValues, _.difference(this.changed(), ignoreChanged));
hookChanged = [];
for (const key of Object.keys(afterHookValues)) {
if (afterHookValues[key] !== beforeHookValues[key]) {
hookChanged.push(key);
.then(() => {
if (options.defaultFields && !this.isNewRecord) {
afterHookValues = _.pick(this.dataValues, _.difference(this.changed(), ignoreChanged));
hookChanged = [];
for (const key of Object.keys(afterHookValues)) {
if (afterHookValues[key] !== beforeHookValues[key]) {
hookChanged.push(key);
}
}
}
options.fields = _.uniq(options.fields.concat(hookChanged));
}
options.fields = _.uniq(options.fields.concat(hookChanged));
}
if (hookChanged) {
if (options.validate) {
if (hookChanged) {
if (options.validate) {
// Validate again
options.skip = _.difference(Object.keys(this.constructor.rawAttributes), hookChanged);
return this.validate(options).then(() => {
delete options.skip;
});
options.skip = _.difference(Object.keys(this.constructor.rawAttributes), hookChanged);
return this.validate(options).then(() => {
delete options.skip;
});
}
}
}
});
});
}
}).then(() => {
if (!options.fields.length) return this;
......@@ -3669,7 +3669,7 @@ class Model {
});
}
/**
/**
* Refresh the current instance in-place, i.e. update the object with current data from the DB and return the same object.
* 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.
......@@ -3687,23 +3687,23 @@ class Model {
});
return this.constructor.findOne(options)
.tap(reload => {
if (!reload) {
throw new sequelizeErrors.InstanceError(
'Instance could not be reloaded because it does not exist anymore (find call returned null)'
);
}
})
.then(reload => {
.tap(reload => {
if (!reload) {
throw new sequelizeErrors.InstanceError(
'Instance could not be reloaded because it does not exist anymore (find call returned null)'
);
}
})
.then(reload => {
// update the internal options of the instance
this._options = reload._options;
// re-set instance values
this.set(reload.dataValues, {
raw: true,
reset: true && !options.attributes
this._options = reload._options;
// re-set instance values
this.set(reload.dataValues, {
raw: true,
reset: true && !options.attributes
});
return this;
});
return this;
});
}
/**
......
......@@ -53,7 +53,7 @@ class QueryInterface {
const showSchemasSql = this.QueryGenerator.showSchemasQuery();
return this.sequelize.query(showSchemasSql, options).then(schemaNames => Utils._.flatten(
Utils._.map(schemaNames, value => value.schema_name ? value.schema_name : value)
Utils._.map(schemaNames, value => value.schema_name ? value.schema_name : value)
));
}
......
......@@ -1084,7 +1084,7 @@ class Sequelize {
if (attribute.hasOwnProperty('defaultValue')) {
if (typeof attribute.defaultValue === 'function' && (
attribute.defaultValue === DataTypes.NOW ||
attribute.defaultValue === DataTypes.NOW ||
attribute.defaultValue === DataTypes.UUIDV1 ||
attribute.defaultValue === DataTypes.UUIDV4
)) {
......
......@@ -66,7 +66,7 @@
"cross-env": "^3.0.0",
"cz-conventional-changelog": "^2.0.0",
"esdoc": "^0.5.2",
"eslint": "^3.6.0",
"eslint": "^4.2.0",
"hints": "^1.1.0",
"husky": "^0.13.4",
"istanbul": "^0.4.5",
......
......@@ -2130,20 +2130,20 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), () => {
User.belongsToMany(User, { through: Follow, as: 'Fan' });
return this.sequelize.sync({ force: true })
.then(() => {
return self.sequelize.Promise.all([
User.create({ name: 'Khsama' }),
User.create({ name: 'Vivek' }),
User.create({ name: 'Satya' })
]);
})
.then(users => {
return self.sequelize.Promise.all([
users[0].addFan(users[1]),
users[1].addUser(users[2]),
users[2].addFan(users[0])
]);
});
.then(() => {
return self.sequelize.Promise.all([
User.create({ name: 'Khsama' }),
User.create({ name: 'Vivek' }),
User.create({ name: 'Satya' })
]);
})
.then(users => {
return self.sequelize.Promise.all([
users[0].addFan(users[1]),
users[1].addUser(users[2]),
users[2].addFan(users[0])
]);
});
});
it('should work with custom self reference', function() {
......@@ -2171,20 +2171,20 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), () => {
});
return this.sequelize.sync({ force: true })
.then(() => {
return self.sequelize.Promise.all([
User.create({ name: 'Jalrangi' }),
User.create({ name: 'Sargrahi' })
]);
})
.then(users => {
return self.sequelize.Promise.all([
users[0].addFollower(users[1]),
users[1].addFollower(users[0]),
users[0].addInvitee(users[1]),
users[1].addInvitee(users[0])
]);
});
.then(() => {
return self.sequelize.Promise.all([
User.create({ name: 'Jalrangi' }),
User.create({ name: 'Sargrahi' })
]);
})
.then(users => {
return self.sequelize.Promise.all([
users[0].addFollower(users[1]),
users[1].addFollower(users[0]),
users[0].addInvitee(users[1]),
users[1].addInvitee(users[0])
]);
});
});
it('should setup correct foreign keys', function() {
......
......@@ -621,12 +621,12 @@ describe(Support.getTestDialectTeaser('BelongsTo'), () => {
const tableName = user.sequelize.getQueryInterface().QueryGenerator.addSchema(user.constructor);
return user.sequelize.getQueryInterface().update(user, tableName, {id: 999}, {id: user.id})
.then(() => {
return Task.findAll().then(tasks => {
expect(tasks).to.have.length(1);
expect(tasks[0].UserId).to.equal(999);
.then(() => {
return Task.findAll().then(tasks => {
expect(tasks).to.have.length(1);
expect(tasks[0].UserId).to.equal(999);
});
});
});
});
});
});
......
......@@ -1130,10 +1130,10 @@ describe(Support.getTestDialectTeaser('HasMany'), () => {
const tableName = user.sequelize.getQueryInterface().QueryGenerator.addSchema(user.constructor);
return user.sequelize.getQueryInterface().update(user, tableName, {id: 999}, {id: user.id})
.catch (self.sequelize.ForeignKeyConstraintError, () => {
.catch (self.sequelize.ForeignKeyConstraintError, () => {
// Should fail due to FK violation
return Task.findAll();
});
return Task.findAll();
});
}).then(tasks => {
expect(tasks).to.have.length(1);
});
......
......@@ -250,24 +250,24 @@ describe(Support.getTestDialectTeaser('HasOne'), () => {
Task.create({id: 20, title: 'bar'})
]);
})
.spread((user, task) => {
return user.setTaskXYZ(task.id)
.then(() => user.getTaskXYZ())
.then(task => {
expect(task).not.to.be.null;
return Promise.all([
user,
Task.create({id: 2, title: 'bar2'})
]);
});
})
.spread((user, task2) => {
return user.setTaskXYZ(task2.id)
.then(() => user.getTaskXYZ())
.then(task => {
expect(task).not.to.be.null;
});
});
.spread((user, task) => {
return user.setTaskXYZ(task.id)
.then(() => user.getTaskXYZ())
.then(task => {
expect(task).not.to.be.null;
return Promise.all([
user,
Task.create({id: 2, title: 'bar2'})
]);
});
})
.spread((user, task2) => {
return user.setTaskXYZ(task2.id)
.then(() => user.getTaskXYZ())
.then(task => {
expect(task).not.to.be.null;
});
});
});
it('supports setting same association twice', function() {
......
......@@ -61,71 +61,71 @@ describe(Support.getTestDialectTeaser('Configuration'), () => {
return Sequelize.Promise.promisify(fs.access)(p, fs.R_OK | fs.W_OK);
} else { // Node v0.10 and older don't have fs.access
return Sequelize.Promise.promisify(fs.open)(p, 'r+')
.then(fd => {
return Sequelize.Promise.promisify(fs.close)(fd);
});
.then(fd => {
return Sequelize.Promise.promisify(fs.close)(fd);
});
}
});
return Sequelize.Promise.promisify(fs.unlink)(p)
.catch(err => {
expect(err.code).to.equal('ENOENT');
})
.then(() => {
const sequelizeReadOnly = new Sequelize('sqlite://foo', {
storage: p,
dialectOptions: {
mode: sqlite3.OPEN_READONLY
}
});
const sequelizeReadWrite = new Sequelize('sqlite://foo', {
storage: p,
dialectOptions: {
mode: sqlite3.OPEN_READWRITE
}
});
.catch(err => {
expect(err.code).to.equal('ENOENT');
})
.then(() => {
const sequelizeReadOnly = new Sequelize('sqlite://foo', {
storage: p,
dialectOptions: {
mode: sqlite3.OPEN_READONLY
}
});
const sequelizeReadWrite = new Sequelize('sqlite://foo', {
storage: p,
dialectOptions: {
mode: sqlite3.OPEN_READWRITE
}
});
expect(sequelizeReadOnly.config.dialectOptions.mode).to.equal(sqlite3.OPEN_READONLY);
expect(sequelizeReadWrite.config.dialectOptions.mode).to.equal(sqlite3.OPEN_READWRITE);
expect(sequelizeReadOnly.config.dialectOptions.mode).to.equal(sqlite3.OPEN_READONLY);
expect(sequelizeReadWrite.config.dialectOptions.mode).to.equal(sqlite3.OPEN_READWRITE);
return Sequelize.Promise.join(
sequelizeReadOnly.query(createTableFoo)
.should.be.rejectedWith(Error, 'SQLITE_CANTOPEN: unable to open database file'),
sequelizeReadWrite.query(createTableFoo)
.should.be.rejectedWith(Error, 'SQLITE_CANTOPEN: unable to open database file')
);
})
.then(() => {
return Sequelize.Promise.join(
sequelizeReadOnly.query(createTableFoo)
.should.be.rejectedWith(Error, 'SQLITE_CANTOPEN: unable to open database file'),
sequelizeReadWrite.query(createTableFoo)
.should.be.rejectedWith(Error, 'SQLITE_CANTOPEN: unable to open database file')
);
})
.then(() => {
// By default, sqlite creates a connection that's READWRITE | CREATE
const sequelize = new Sequelize('sqlite://foo', {
storage: p
});
return sequelize.query(createTableFoo);
})
.then(testAccess)
.then(() => {
const sequelizeReadOnly = new Sequelize('sqlite://foo', {
storage: p,
dialectOptions: {
mode: sqlite3.OPEN_READONLY
}
});
const sequelizeReadWrite = new Sequelize('sqlite://foo', {
storage: p,
dialectOptions: {
mode: sqlite3.OPEN_READWRITE
}
});
const sequelize = new Sequelize('sqlite://foo', {
storage: p
});
return sequelize.query(createTableFoo);
})
.then(testAccess)
.then(() => {
const sequelizeReadOnly = new Sequelize('sqlite://foo', {
storage: p,
dialectOptions: {
mode: sqlite3.OPEN_READONLY
}
});
const sequelizeReadWrite = new Sequelize('sqlite://foo', {
storage: p,
dialectOptions: {
mode: sqlite3.OPEN_READWRITE
}
});
return Sequelize.Promise.join(
sequelizeReadOnly.query(createTableBar)
.should.be.rejectedWith(Error, 'SQLITE_READONLY: attempt to write a readonly database'),
sequelizeReadWrite.query(createTableBar)
);
})
.finally(() => {
return Sequelize.Promise.promisify(fs.unlink)(p);
});
return Sequelize.Promise.join(
sequelizeReadOnly.query(createTableBar)
.should.be.rejectedWith(Error, 'SQLITE_READONLY: attempt to write a readonly database'),
sequelizeReadWrite.query(createTableBar)
);
})
.finally(() => {
return Sequelize.Promise.promisify(fs.unlink)(p);
});
});
}
});
......
......@@ -266,7 +266,7 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => {
it('calls parse and stringify for ENUM', () => {
const Type = new Sequelize.ENUM('hat', 'cat');
// No dialects actually allow us to identify that we get an enum back..
// No dialects actually allow us to identify that we get an enum back..
testFailure(Type);
});
......@@ -428,12 +428,12 @@ describe(Support.getTestDialectTeaser('DataTypes'), () => {
});
return Model.sync({ force: true })
.then(() => Model.create({ interval: [1, 4] }) )
.then(() => Model.findAll() )
.spread(m => {
expect(m.interval[0]).to.be.eql(1);
expect(m.interval[1]).to.be.eql(4);
});
.then(() => Model.create({ interval: [1, 4] }) )
.then(() => Model.findAll() )
.spread(m => {
expect(m.interval[0]).to.be.eql(1);
expect(m.interval[1]).to.be.eql(4);
});
});
}
......
......@@ -38,16 +38,16 @@ if (dialect === 'mysql') {
const User = sequelize.define('User', { username: DataTypes.STRING });
return User
.sync({force: true})
.then(() => User.create({username: 'user1'}))
.then(() => sequelize.Promise.delay(100))
.then(() => {
.sync({force: true})
.then(() => User.create({username: 'user1'}))
.then(() => sequelize.Promise.delay(100))
.then(() => {
// This query will be queued just after the `client.end` is executed and before its callback is called
return sequelize.query('SELECT COUNT(*) AS count FROM Users', { type: sequelize.QueryTypes.SELECT });
})
.then(count => {
expect(count[0].count).to.equal(1);
});
return sequelize.query('SELECT COUNT(*) AS count FROM Users', { type: sequelize.QueryTypes.SELECT });
})
.then(count => {
expect(count[0].count).to.equal(1);
});
});
it('should maintain connection', () => {
......
......@@ -47,8 +47,8 @@ describe(Support.getTestDialectTeaser('Hooks'), () => {
this.User.afterValidate(user => {
//if username is defined and has more than 5 char
user.username = user.username
? user.username.length < 5 ? null : user.username
: null;
? user.username.length < 5 ? null : user.username
: null;
user.username = user.username || 'Samorost 3';
});
......
......@@ -885,7 +885,7 @@ describe(Support.getTestDialectTeaser('Include'), () => {
}).then(results => {
return Promise.join(
results.users[0].setGroup(results.groups[1]),
results.users[1].setGroup(results.groups[0])
results.users[1].setGroup(results.groups[0])
);
}).then(() => {
return User.findAll({
......
......@@ -268,26 +268,26 @@ describe(Support.getTestDialectTeaser('Include'), () => {
{ ProjectId: 2, name: 'proposes' }
]);
})
.then(() => {
.then(() => {
// Find All Tasks with Project(m=a) and User(name=user-name-2)
return Task.findAndCountAll({
limit: 1,
offset: 0,
order: [[ 'id', 'DESC' ]],
include: [
{
model: Project,
where: { '$and': [ { m: 'A' } ] },
include: [ {
model: User,
where: { '$and': [ { name: 'user-name-2' } ] }
}
]
},
{ model : Tag }
]
return Task.findAndCountAll({
limit: 1,
offset: 0,
order: [[ 'id', 'DESC' ]],
include: [
{
model: Project,
where: { '$and': [ { m: 'A' } ] },
include: [ {
model: User,
where: { '$and': [ { name: 'user-name-2' } ] }
}
]
},
{ model : Tag }
]
});
});
});
}).then(result => {
expect(result.count).to.equal(2);
expect(result.rows.length).to.equal(1);
......@@ -326,8 +326,8 @@ describe(Support.getTestDialectTeaser('Include'), () => {
limit: 1,
offset: 1,
where: sequelize.or(
{ first_name : { like: '%user-fname%' } },
{ last_name : { like: '%user-lname%' } }
{ first_name : { like: '%user-fname%' } },
{ last_name : { like: '%user-lname%' } }
),
include: [
{
......
......@@ -77,9 +77,9 @@ if (current.dialect.supports.groupedLimit) {
return User.create({
id: 1,
tasks: [
{},
{},
{}
{},
{},
{}
]
}, {
include: [User.Tasks]
......@@ -87,10 +87,10 @@ if (current.dialect.supports.groupedLimit) {
return User.findAll({
attributes: ['name'],
include: [
{association: User.Tasks, separate: true}
{association: User.Tasks, separate: true}
],
order: [
['id', 'ASC']
['id', 'ASC']
],
logging: sqlSpy
});
......
......@@ -770,9 +770,9 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
username: 'a user'
}
})
.then(user => {
expect(user.isSuperUser).to.be.false;
});
.then(user => {
expect(user.isSuperUser).to.be.false;
});
});
});
......@@ -789,9 +789,9 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
username: 'a user'
}
})
.then(user => {
expect(user.isSuperUser).to.be.true;
});
.then(user => {
expect(user.isSuperUser).to.be.true;
});
});
});
......@@ -808,9 +808,9 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
username: 'a user'
}
})
.then(user => {
expect(user.isSuperUser).to.be.true;
});
.then(user => {
expect(user.isSuperUser).to.be.true;
});
});
});
......@@ -819,18 +819,18 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
username: 'a user',
isSuperUser: 1
})
.save()
.bind(this)
.then(function() {
return this.User.findOne({
where: {
username: 'a user'
}
})
.then(user => {
expect(user.isSuperUser).to.be.true;
});
});
.save()
.bind(this)
.then(function() {
return this.User.findOne({
where: {
username: 'a user'
}
})
.then(user => {
expect(user.isSuperUser).to.be.true;
});
});
});
it('should throw error when given value of incorrect type', function() {
......@@ -840,15 +840,15 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
username: 'a user',
isSuperUser: 'INCORRECT_VALUE_TYPE'
})
.save()
.then(() => {
callCount += 1;
})
.catch(err => {
expect(callCount).to.equal(0);
expect(err).to.exist;
expect(err.message).to.exist;
});
.save()
.then(() => {
callCount += 1;
})
.catch(err => {
expect(callCount).to.equal(0);
expect(err).to.exist;
expect(err.message).to.exist;
});
});
});
});
......@@ -1171,18 +1171,18 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
updatedAtPaul = users[0].updatedAt;
updatedAtPeter = users[1].updatedAt;
})
.then(function() {
this.clock.tick(150);
return this.User.update(
{ aNumber: 1 },
{ where: {}, silent: true }
);
}).then(() => {
return self.User.findAll();
}).then(users => {
expect(users[0].updatedAt).to.equalTime(updatedAtPeter);
expect(users[1].updatedAt).to.equalTime(updatedAtPaul);
});
.then(function() {
this.clock.tick(150);
return this.User.update(
{ aNumber: 1 },
{ where: {}, silent: true }
);
}).then(() => {
return self.User.findAll();
}).then(users => {
expect(users[0].updatedAt).to.equalTime(updatedAtPeter);
expect(users[1].updatedAt).to.equalTime(updatedAtPaul);
});
});
describe('when nothing changed', () => {
......@@ -1337,14 +1337,14 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
it('should fail a validation upon building', function() {
return this.User.build({aNumber: 0, validateCustom: 'aaaaaaaaaaaaaaaaaaaaaaaaaa'}).save()
.catch(err => {
expect(err).to.exist;
expect(err).to.be.instanceof(Object);
expect(err.get('validateCustom')).to.exist;
expect(err.get('validateCustom')).to.be.instanceof(Array);
expect(err.get('validateCustom')[0]).to.exist;
expect(err.get('validateCustom')[0].message).to.equal('Length failed.');
});
.catch(err => {
expect(err).to.exist;
expect(err).to.be.instanceof(Object);
expect(err.get('validateCustom')).to.exist;
expect(err.get('validateCustom')).to.be.instanceof(Array);
expect(err.get('validateCustom')[0]).to.exist;
expect(err.get('validateCustom')[0].message).to.equal('Length failed.');
});
});
it('should fail a validation when updating', function() {
......@@ -2154,8 +2154,8 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
paranoid: true
}),
data = [{ username: 'Peter', secretValue: '42' },
{ username: 'Paul', secretValue: '43' },
{ username: 'Bob', secretValue: '44' }];
{ username: 'Paul', secretValue: '43' },
{ username: 'Bob', secretValue: '44' }];
return ParanoidUser.sync({ force: true }).then(() => {
return ParanoidUser.bulkCreate(data);
......
......@@ -891,8 +891,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('updates only values that match filter', function() {
const self = this,
data = [{ username: 'Peter', secretValue: '42' },
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }];
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }];
return this.User.bulkCreate(data).then(() => {
return self.User.update({username: 'Bill'}, {where: {secretValue: '42'}}).then(() => {
......@@ -1069,8 +1069,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('sets updatedAt to the current timestamp', function() {
const data = [{ username: 'Peter', secretValue: '42' },
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }];
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }];
return this.User.bulkCreate(data).bind(this).then(function() {
return this.User.findAll({order: ['id']});
......@@ -1098,8 +1098,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('returns the number of affected rows', function() {
const self = this,
data = [{ username: 'Peter', secretValue: '42' },
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }];
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }];
return this.User.bulkCreate(data).then(() => {
return self.User.update({username: 'Bill'}, {where: {secretValue: '42'}}).spread(affectedRows => {
......@@ -1116,8 +1116,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('returns the affected rows if `options.returning` is true', function() {
const self = this,
data = [{ username: 'Peter', secretValue: '42' },
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }];
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }];
return this.User.bulkCreate(data).then(() => {
return self.User.update({ username: 'Bill' }, { where: {secretValue: '42' }, returning: true }).spread((count, rows) => {
......@@ -1137,8 +1137,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('supports limit clause', function() {
const self = this,
data = [{ username: 'Peter', secretValue: '42' },
{ username: 'Peter', secretValue: '42' },
{ username: 'Peter', secretValue: '42' }];
{ username: 'Peter', secretValue: '42' },
{ username: 'Peter', secretValue: '42' }];
return this.User.bulkCreate(data).then(() => {
return self.User.update({secretValue: '43'}, {where: {username: 'Peter'}, limit: 1}).spread(affectedRows => {
......@@ -1154,8 +1154,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('convenient method `truncate` should clear the table', function() {
const User = this.sequelize.define('User', { username: DataTypes.STRING }),
data = [
{ username: 'user1' },
{ username: 'user2' }
{ username: 'user1' },
{ username: 'user2' }
];
return this.sequelize.sync({ force: true }).then(() => {
......@@ -1170,8 +1170,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('truncate should clear the table', function() {
const User = this.sequelize.define('User', { username: DataTypes.STRING }),
data = [
{ username: 'user1' },
{ username: 'user2' }
{ username: 'user1' },
{ username: 'user2' }
];
return this.sequelize.sync({ force: true }).then(() => {
......@@ -1199,8 +1199,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('deletes all instances when given an empty where object', function() {
const User = this.sequelize.define('User', { username: DataTypes.STRING }),
data = [
{ username: 'user1' },
{ username: 'user2' }
{ username: 'user1' },
{ username: 'user2' }
];
return this.sequelize.sync({ force: true }).then(() => {
......@@ -1245,8 +1245,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('deletes values that match filter', function() {
const self = this,
data = [{ username: 'Peter', secretValue: '42' },
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }];
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }];
return this.User.bulkCreate(data).then(() => {
return self.User.destroy({where: {secretValue: '42'}})
......@@ -1323,8 +1323,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
paranoid: true
}),
data = [{ username: 'Peter', secretValue: '42' },
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }];
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }];
return ParanoidUser.sync({ force: true }).then(() => {
return ParanoidUser.bulkCreate(data);
......@@ -1453,32 +1453,32 @@ describe(Support.getTestDialectTeaser('Model'), () => {
let user;
return User.sync({ force: true })
.then(() => { return Pet.sync({ force: true }); })
.then(() => { return User.create({ username: 'Joe' }); })
.then(_user => {
user = _user;
return Pet.bulkCreate([
{ name: 'Fido', UserId: user.id },
{ name: 'Fifi', UserId: user.id }
]);
})
.then(() => { return Pet.findById(1); })
.then(pet => { return pet.destroy(); })
.then(() => {
return [
User.find({ where: {id: user.id}, include: Pet }),
User.find({
where: {id: user.id},
include: [{ model: Pet, paranoid: false }]
})
];
})
.spread((user, userWithDeletedPets) => {
expect(user).to.exist;
expect(user.Pets).to.have.length(1);
expect(userWithDeletedPets).to.exist;
expect(userWithDeletedPets.Pets).to.have.length(2);
});
.then(() => { return Pet.sync({ force: true }); })
.then(() => { return User.create({ username: 'Joe' }); })
.then(_user => {
user = _user;
return Pet.bulkCreate([
{ name: 'Fido', UserId: user.id },
{ name: 'Fifi', UserId: user.id }
]);
})
.then(() => { return Pet.findById(1); })
.then(pet => { return pet.destroy(); })
.then(() => {
return [
User.find({ where: {id: user.id}, include: Pet }),
User.find({
where: {id: user.id},
include: [{ model: Pet, paranoid: false }]
})
];
})
.spread((user, userWithDeletedPets) => {
expect(user).to.exist;
expect(user.Pets).to.have.length(1);
expect(userWithDeletedPets).to.exist;
expect(userWithDeletedPets.Pets).to.have.length(2);
});
});
it('should delete a paranoid record if I set force to true', function() {
......@@ -1525,8 +1525,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('returns the number of affected rows', function() {
const self = this,
data = [{ username: 'Peter', secretValue: '42' },
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }];
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }];
return this.User.bulkCreate(data).then(() => {
return self.User.destroy({where: {secretValue: '42'}}).then(affectedRows => {
......@@ -1542,8 +1542,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('supports table schema/prefix', function() {
const self = this,
data = [{ username: 'Peter', secretValue: '42' },
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }],
{ username: 'Paul', secretValue: '42' },
{ username: 'Bob', secretValue: '43' }],
prefixUser = self.User.schema('prefix');
const run = function() {
......@@ -1572,9 +1572,9 @@ describe(Support.getTestDialectTeaser('Model'), () => {
const self = this;
return this.User.create({username: 'Peter', secretValue: '42'})
.then(() => {
expect(() => {self.User.restore({where: {secretValue: '42'}});}).to.throw(Error, 'Model is not paranoid');
});
.then(() => {
expect(() => {self.User.restore({where: {secretValue: '42'}});}).to.throw(Error, 'Model is not paranoid');
});
});
it('restores a previously deleted model', function() {
......@@ -1588,8 +1588,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
paranoid: true
}),
data = [{ username: 'Peter', secretValue: '42' },
{ username: 'Paul', secretValue: '43' },
{ username: 'Bob', secretValue: '44' }];
{ username: 'Paul', secretValue: '43' },
{ username: 'Bob', secretValue: '44' }];
return ParanoidUser.sync({ force: true }).then(() => {
return ParanoidUser.bulkCreate(data);
......@@ -1789,8 +1789,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
.then(() => Post.create({}))
.then(post => PostComment.bulkCreate([{ PostId: post.id }, { PostId: post.id }]))
.then(() => Promise.join(
Post.count({ distinct: false, include: [{ model: PostComment, required: false }] }),
Post.count({ distinct: true, include: [{ model: PostComment, required: false }] }),
Post.count({ distinct: false, include: [{ model: PostComment, required: false }] }),
Post.count({ distinct: true, include: [{ model: PostComment, required: false }] }),
(count1, count2) => {
expect(count1).to.equal(2);
expect(count2).to.equal(1);
......@@ -2716,8 +2716,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
describe('bulkCreate errors', () => {
it('should return array of errors if validate and individualHooks are true', function() {
const data = [{ username: null },
{ username: null },
{ username: null }];
{ username: null },
{ username: null }];
const user = this.sequelize.define('Users', {
username: {
......
......@@ -58,17 +58,17 @@ describe(Support.getTestDialectTeaser('Model'), () => {
expect(score.test_value).to.equal(1001);
});
})
.then(() => {
return Promise.join(
self.Student.build({no: 1}).getCourses({where: {no: 100}}),
self.Score.find({ where: { StudentId: 1, CourseId: 100 } })
);
})
.spread((courses, score) => {
expect(score.test_value).to.equal(1001);
expect(courses[0].score.toJSON().test_value).to.equal(1001);
expect(self.callCount).to.equal(1);
});
.then(() => {
return Promise.join(
self.Student.build({no: 1}).getCourses({where: {no: 100}}),
self.Score.find({ where: { StudentId: 1, CourseId: 100 } })
);
})
.spread((courses, score) => {
expect(score.test_value).to.equal(1001);
expect(courses[0].score.toJSON().test_value).to.equal(1001);
expect(self.callCount).to.equal(1);
});
});
});
});
......
......@@ -499,21 +499,21 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('should sync foreign keys with custom field names', function() {
return this.sequelize.sync({ force: true })
.then(() => {
const attrs = this.Task.tableAttributes;
expect(attrs.user_id.references.model).to.equal('users');
expect(attrs.user_id.references.key).to.equal('userId');
});
.then(() => {
const attrs = this.Task.tableAttributes;
expect(attrs.user_id.references.model).to.equal('users');
expect(attrs.user_id.references.key).to.equal('userId');
});
});
it('should find the value of an attribute with a custom field name', function() {
return this.User.create({ name: 'test user' })
.then(() => {
return this.User.find({ where: { name: 'test user' } });
})
.then(user => {
expect(user.name).to.equal('test user');
});
.then(() => {
return this.User.find({ where: { name: 'test user' } });
})
.then(user => {
expect(user.name).to.equal('test user');
});
});
it('field names that are the same as property names should create, update, and read correctly', function() {
......
......@@ -56,79 +56,79 @@ describe(Support.getTestDialectTeaser('Model'), () => {
username: 'valak',
createdAt: (new Date()).setFullYear(2015)
})
.then(() =>
this.User.count({
attributes: ['createdAt'],
group: ['createdAt']
})
)
.then(users => {
expect(users.length).to.be.eql(2);
.then(() =>
this.User.count({
attributes: ['createdAt'],
group: ['createdAt']
})
)
.then(users => {
expect(users.length).to.be.eql(2);
// have attributes
expect(users[0].createdAt).to.exist;
expect(users[1].createdAt).to.exist;
});
// have attributes
expect(users[0].createdAt).to.exist;
expect(users[1].createdAt).to.exist;
});
});
it('should not return NaN', function() {
return this.sequelize.sync({ force: true })
.then(() =>
this.User.bulkCreate([
{ username: 'valak', age: 10},
{ username: 'conjuring', age: 20},
{ username: 'scary', age: 10}
])
)
.then(() =>
this.User.count({
where: { age: 10 },
group: ['age'],
order: ['age']
.then(() =>
this.User.bulkCreate([
{ username: 'valak', age: 10},
{ username: 'conjuring', age: 20},
{ username: 'scary', age: 10}
])
)
.then(() =>
this.User.count({
where: { age: 10 },
group: ['age'],
order: ['age']
})
)
.then(result => {
expect(parseInt(result[0].count)).to.be.eql(2);
return this.User.count({
where: { username: 'fire' }
});
})
)
.then(result => {
expect(parseInt(result[0].count)).to.be.eql(2);
return this.User.count({
where: { username: 'fire' }
});
})
.then(count => {
expect(count).to.be.eql(0);
return this.User.count({
where: { username: 'fire' },
group: 'age'
.then(count => {
expect(count).to.be.eql(0);
return this.User.count({
where: { username: 'fire' },
group: 'age'
});
})
.then(count => {
expect(count).to.be.eql([]);
});
})
.then(count => {
expect(count).to.be.eql([]);
});
});
it('should be able to specify column for COUNT()', function() {
return this.sequelize.sync({ force: true })
.then(() =>
this.User.bulkCreate([
{ username: 'ember', age: 10},
{ username: 'angular', age: 20},
{ username: 'mithril', age: 10}
])
)
.then(() =>
this.User.count({
col: 'username'
.then(() =>
this.User.bulkCreate([
{ username: 'ember', age: 10},
{ username: 'angular', age: 20},
{ username: 'mithril', age: 10}
])
)
.then(() =>
this.User.count({
col: 'username'
})
)
.then(count => {
expect(parseInt(count)).to.be.eql(3);
return this.User.count({
col: 'age',
distinct: true
});
})
)
.then(count => {
expect(parseInt(count)).to.be.eql(3);
return this.User.count({
col: 'age',
distinct: true
.then(count => {
expect(parseInt(count)).to.be.eql(2);
});
})
.then(count => {
expect(parseInt(count)).to.be.eql(2);
});
});
it('should be able to use where clause on included models', function() {
......
......@@ -351,13 +351,13 @@ describe(Support.getTestDialectTeaser('Model'), () => {
no: 1
}
})
.timeout(1000)
.catch (Promise.TimeoutError, e => {
throw new Error(e);
})
.catch (Sequelize.ValidationError, () => {
return test(times + 1);
});
.timeout(1000)
.catch (Promise.TimeoutError, e => {
throw new Error(e);
})
.catch (Sequelize.ValidationError, () => {
return test(times + 1);
});
};
return test(0);
......@@ -1481,8 +1481,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('properly handles disparate field lists', function() {
const self = this,
data = [{username: 'Peter', secretValue: '42', uniqueName: '1' },
{username: 'Paul', uniqueName: '2'},
{username: 'Steve', uniqueName: '3'}];
{username: 'Paul', uniqueName: '2'},
{username: 'Steve', uniqueName: '3'}];
return this.User.bulkCreate(data).then(() => {
return self.User.findAll({where: {username: 'Paul'}}).then(users => {
......@@ -1496,7 +1496,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('inserts multiple values respecting the white list', function() {
const self = this,
data = [{ username: 'Peter', secretValue: '42', uniqueName: '1' },
{ username: 'Paul', secretValue: '23', uniqueName: '2'}];
{ username: 'Paul', secretValue: '23', uniqueName: '2'}];
return this.User.bulkCreate(data, { fields: ['username', 'uniqueName'] }).then(() => {
return self.User.findAll({order: ['id']}).then(users => {
......@@ -1512,7 +1512,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('should store all values if no whitelist is specified', function() {
const self = this,
data = [{ username: 'Peter', secretValue: '42', uniqueName: '1' },
{ username: 'Paul', secretValue: '23', uniqueName: '2'}];
{ username: 'Paul', secretValue: '23', uniqueName: '2'}];
return this.User.bulkCreate(data).then(() => {
return self.User.findAll({order: ['id']}).then(users => {
......@@ -1528,7 +1528,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('should set isNewRecord = false', function() {
const self = this,
data = [{ username: 'Peter', secretValue: '42', uniqueName: '1' },
{ username: 'Paul', secretValue: '23', uniqueName: '2'}];
{ username: 'Paul', secretValue: '23', uniqueName: '2'}];
return this.User.bulkCreate(data).then(() => {
return self.User.findAll({order: ['id']}).then(users => {
......@@ -1544,7 +1544,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
const self = this,
quote = "Single'Quote",
data = [{ username: 'Peter', data: quote, uniqueName: '1'},
{ username: 'Paul', data: quote, uniqueName: '2'}];
{ username: 'Paul', data: quote, uniqueName: '2'}];
return this.User.bulkCreate(data).then(() => {
return self.User.findAll({order: ['id']}).then(users => {
......@@ -1561,7 +1561,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
const self = this,
quote = 'Double"Quote',
data = [{ username: 'Peter', data: quote, uniqueName: '1'},
{ username: 'Paul', data: quote, uniqueName: '2'}];
{ username: 'Paul', data: quote, uniqueName: '2'}];
return this.User.bulkCreate(data).then(() => {
return self.User.findAll({order: ['id']}).then(users => {
......@@ -1578,7 +1578,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
const self = this,
json = JSON.stringify({ key: 'value' }),
data = [{ username: 'Peter', data: json, uniqueName: '1'},
{ username: 'Paul', data: json, uniqueName: '2'}];
{ username: 'Paul', data: json, uniqueName: '2'}];
return this.User.bulkCreate(data).then(() => {
return self.User.findAll({order: ['id']}).then(users => {
......@@ -1604,7 +1604,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('stores the current date in createdAt', function() {
const self = this,
data = [{ username: 'Peter', uniqueName: '1'},
{ username: 'Paul', uniqueName: '2'}];
{ username: 'Paul', uniqueName: '2'}];
return this.User.bulkCreate(data).then(() => {
return self.User.findAll({order: ['id']}).then(users => {
......@@ -1731,7 +1731,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('should support the ignoreDuplicates option', function() {
const self = this,
data = [{ uniqueName: 'Peter', secretValue: '42' },
{ uniqueName: 'Paul', secretValue: '23' }];
{ uniqueName: 'Paul', secretValue: '23' }];
return this.User.bulkCreate(data, { fields: ['uniqueName', 'secretValue'] }).then(() => {
data.push({ uniqueName: 'Michael', secretValue: '26' });
......@@ -1752,7 +1752,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('should throw an error when the ignoreDuplicates option is passed', function() {
const self = this,
data = [{ uniqueName: 'Peter', secretValue: '42' },
{ uniqueName: 'Paul', secretValue: '23' }];
{ uniqueName: 'Paul', secretValue: '23' }];
return this.User.bulkCreate(data, { fields: ['uniqueName', 'secretValue'] }).then(() => {
data.push({ uniqueName: 'Michael', secretValue: '26' });
......@@ -1854,27 +1854,27 @@ describe(Support.getTestDialectTeaser('Model'), () => {
const M2 = { id: 2, name: 'Dwitiya Maya', secret: 'You are on list #2'};
return Maya.sync({ force: true }).then(() => Maya.create(M1))
.then(m => {
expect(m.createdAt).to.be.ok;
expect(m.id).to.be.eql(M1.id);
expect(m.name).to.be.eql(M1.name);
expect(m.secret).to.be.eql(M1.secret);
.then(m => {
expect(m.createdAt).to.be.ok;
expect(m.id).to.be.eql(M1.id);
expect(m.name).to.be.eql(M1.name);
expect(m.secret).to.be.eql(M1.secret);
return Maya.bulkCreate([M2]);
}).spread(m => {
return Maya.bulkCreate([M2]);
}).spread(m => {
// only attributes are returned, no fields are mixed
expect(m.createdAt).to.be.ok;
expect(m.created_at).to.not.exist;
expect(m.secret_given).to.not.exist;
expect(m.get('secret_given')).not.to.be.defined;
expect(m.get('created_at')).not.to.be.defined;
expect(m.createdAt).to.be.ok;
expect(m.created_at).to.not.exist;
expect(m.secret_given).to.not.exist;
expect(m.get('secret_given')).not.to.be.defined;
expect(m.get('created_at')).not.to.be.defined;
// values look fine
expect(m.id).to.be.eql(M2.id);
expect(m.name).to.be.eql(M2.name);
expect(m.secret).to.be.eql(M2.secret);
});
// values look fine
expect(m.id).to.be.eql(M2.id);
expect(m.name).to.be.eql(M2.name);
expect(m.secret).to.be.eql(M2.secret);
});
});
it('should return autoIncrement primary key (create)', function() {
......@@ -1883,9 +1883,9 @@ describe(Support.getTestDialectTeaser('Model'), () => {
const M1 = {};
return Maya.sync({ force: true }).then(() => Maya.create(M1, {returning: true}))
.then(m => {
expect(m.id).to.be.eql(1);
});
.then(m => {
expect(m.id).to.be.eql(1);
});
});
it('should return autoIncrement primary key (bulkCreate)', function() {
......@@ -1895,10 +1895,10 @@ describe(Support.getTestDialectTeaser('Model'), () => {
const M2 = {};
return Maya.sync({ force: true }).then(() => Maya.bulkCreate([M1, M2], {returning: true}))
.then(ms => {
expect(ms[0].id).to.be.eql(1);
expect(ms[1].id).to.be.eql(2);
});
.then(ms => {
expect(ms[0].id).to.be.eql(1);
expect(ms[1].id).to.be.eql(2);
});
});
});
......
......@@ -551,11 +551,11 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it(`throws an error indicating an incorrect alias was entered if an association
and alias exist but the alias doesn't match`, function() {
const self = this;
return self.Worker.findOne({ include: [{ model: self.Task, as: 'Work' }] }).catch (err => {
expect(err.message).to.equal('Task is associated to Worker using an alias. You\'ve included an alias (Work), but it does not match the alias defined in your association.');
const self = this;
return self.Worker.findOne({ include: [{ model: self.Task, as: 'Work' }] }).catch (err => {
expect(err.message).to.equal('Task is associated to Worker using an alias. You\'ve included an alias (Work), but it does not match the alias defined in your association.');
});
});
});
it('returns the associated task via worker.task', function() {
return this.Worker.findOne({
......@@ -713,11 +713,11 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it(`throws an error indicating an incorrect alias was entered if an association
and alias exist but the alias doesn't match`, function() {
const self = this;
return self.Worker.findOne({ include: [{ model: self.Task, as: 'Work' }] }).catch (err => {
expect(err.message).to.equal('Task is associated to Worker using an alias. You\'ve included an alias (Work), but it does not match the alias defined in your association.');
const self = this;
return self.Worker.findOne({ include: [{ model: self.Task, as: 'Work' }] }).catch (err => {
expect(err.message).to.equal('Task is associated to Worker using an alias. You\'ve included an alias (Work), but it does not match the alias defined in your association.');
});
});
});
it('returns the associated task via worker.task', function() {
return this.Worker.findOne({
......
......@@ -889,11 +889,11 @@ describe(Support.getTestDialectTeaser('Model'), () => {
this.Kingdom.create({ name: 'Water' }),
this.Kingdom.create({ name: 'Wind' })
]).spread((k1, k2, k3) =>
Sequelize.Promise.all([
k1.addAnimals([a1, a2]),
k2.addAnimals([a4]),
k3.addAnimals([a3])
])
Sequelize.Promise.all([
k1.addAnimals([a1, a2]),
k2.addAnimals([a4]),
k3.addAnimals([a3])
])
));
});
......
......@@ -145,7 +145,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
const User = this.User;
const point = { type: 'Polygon', coordinates: [
[ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],
[100.0, 1.0], [100.0, 0.0] ]
[100.0, 1.0], [100.0, 0.0] ]
]};
return User.create({username: 'username', geography: point }).then(newUser => {
......@@ -157,12 +157,12 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('should update a geography object', function() {
const User = this.User;
const polygon1 = { type: 'Polygon', coordinates: [
[ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],
[100.0, 1.0], [100.0, 0.0] ]
[ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],
[100.0, 1.0], [100.0, 0.0] ]
]},
polygon2 = { type: 'Polygon', coordinates: [
[ [100.0, 0.0], [102.0, 0.0], [102.0, 1.0],
[100.0, 1.0], [100.0, 0.0] ]
[100.0, 1.0], [100.0, 0.0] ]
]};
const props = {username: 'username', geography: polygon1};
......
......@@ -147,7 +147,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
const User = this.User;
const point = { type: 'Polygon', coordinates: [
[ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],
[100.0, 1.0], [100.0, 0.0] ]
[100.0, 1.0], [100.0, 0.0] ]
]};
return User.create({username: 'username', geometry: point }).then(newUser => {
......@@ -159,12 +159,12 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('should update a geometry object', function() {
const User = this.User;
const polygon1 = { type: 'Polygon', coordinates: [
[ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],
[100.0, 1.0], [100.0, 0.0] ]
[ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],
[100.0, 1.0], [100.0, 0.0] ]
]},
polygon2 = { type: 'Polygon', coordinates: [
[ [100.0, 0.0], [102.0, 0.0], [102.0, 1.0],
[100.0, 1.0], [100.0, 0.0] ]
[100.0, 1.0], [100.0, 0.0] ]
]};
const props = {username: 'username', geometry: polygon1};
......
......@@ -38,9 +38,9 @@ describe(Support.getTestDialectTeaser('Model'), () => {
.then(count => {
expect(count).to.be.equal(1);
return Account.destroy({ where: { ownerId: 12 }})
.then(result => {
expect(result).to.be.equal(1);
});
.then(result => {
expect(result).to.be.equal(1);
});
})
.then(() => Account.count())
.then(count => {
......
......@@ -20,16 +20,16 @@ describe(Support.getTestDialectTeaser('Model'), () => {
foo: DataTypes.STRING,
bar: DataTypes.STRING
},
{tableName: 'restaurants'});
{tableName: 'restaurants'});
this.Location = current.define('location', {
name: DataTypes.STRING
},
{tableName: 'locations'});
{tableName: 'locations'});
this.Employee = current.define('employee', {
first_name: DataTypes.STRING,
last_name: DataTypes.STRING
},
{tableName: 'employees'});
{tableName: 'employees'});
this.EmployeeOne = this.Employee.schema(SCHEMA_ONE);
this.Restaurant.belongsTo(this.Location,
{
......
......@@ -42,11 +42,11 @@ describe(Support.getTestDialectTeaser('Model'), () => {
it('should be able to merge attributes as array', function() {
return this.ScopeMe.scope('lowAccess', 'withName').findOne()
.then(record => {
expect(record.other_value).to.exist;
expect(record.username).to.exist;
expect(record.access_level).to.exist;
});
.then(record => {
expect(record.other_value).to.exist;
expect(record.username).to.exist;
expect(record.access_level).to.exist;
});
});
});
});
......@@ -24,16 +24,16 @@ describe(Support.getTestDialectTeaser('Model'), () => {
foo: DataTypes.STRING,
bar: DataTypes.STRING
},
{tableName: 'restaurants'});
{tableName: 'restaurants'});
this.Location = current.define('location', {
name: DataTypes.STRING
},
{tableName: 'locations'});
{tableName: 'locations'});
this.Employee = current.define('employee', {
first_name: DataTypes.STRING,
last_name: DataTypes.STRING
},
{tableName: 'employees'});
{tableName: 'employees'});
this.Restaurant.belongsTo(this.Location,
{
foreignKey: 'location_id',
......
......@@ -59,30 +59,30 @@ describe(Support.getTestDialectTeaser('Model'), () => {
ownerId: 2,
name: 'Account Name 1'
})
.then(() => {
return this.Account.create({
ownerId: 2,
name: 'Account Name 2'
.then(() => {
return this.Account.create({
ownerId: 2,
name: 'Account Name 2'
});
})
.then(() => {
return this.Account.create({
ownerId: 2,
name: 'Account Name 3'
});
})
.then(() => {
const options = {
where: {
ownerId: 2
},
limit: 1
};
return this.Account.update({ name: 'New Name' }, options);
})
.then(account => {
expect(account[0]).to.equal(1);
});
})
.then(() => {
return this.Account.create({
ownerId: 2,
name: 'Account Name 3'
});
})
.then(() => {
const options = {
where: {
ownerId: 2
},
limit: 1
};
return this.Account.update({ name: 'New Name' }, options);
})
.then(account => {
expect(account[0]).to.equal(1);
});
});
}
});
......
......@@ -141,7 +141,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
return User.sync({ force: true }).bind(this).then(() => {
return Promise.all([
// Create two users
// Create two users
User.upsert({ a: 'a', b: 'b', username: 'john' }),
User.upsert({ a: 'a', b: 'a', username: 'curt' })
]);
......
......@@ -547,7 +547,7 @@ describe(Support.getTestDialectTeaser('QueryInterface'), () => {
}
});
//SQlite navitely doesnt support ALTER Foreign key
//SQlite navitely doesnt support ALTER Foreign key
if (dialect !== 'sqlite') {
describe('should support foreign keys', () => {
beforeEach(function() {
......@@ -868,9 +868,9 @@ describe(Support.getTestDialectTeaser('QueryInterface'), () => {
}).then(fks => {
if (dialect === 'mysql') {
return self.sequelize.query(
self.queryInterface.QueryGenerator.getForeignKeyQuery('hosts', 'admin'),
{}
)
self.queryInterface.QueryGenerator.getForeignKeyQuery('hosts', 'admin'),
{}
)
.spread(fk => {
expect(fks[0]).to.deep.eql(fk[0]);
});
......@@ -900,17 +900,17 @@ describe(Support.getTestDialectTeaser('QueryInterface'), () => {
return this.queryInterface.addConstraint('users', ['email'], {
type: 'unique'
})
.then(() => this.queryInterface.showConstraint('users'))
.then(constraints => {
constraints = constraints.map(constraint => constraint.constraintName);
expect(constraints).to.include('users_email_uk');
return this.queryInterface.removeConstraint('users', 'users_email_uk');
})
.then(() => this.queryInterface.showConstraint('users'))
.then(constraints => {
constraints = constraints.map(constraint => constraint.constraintName);
expect(constraints).to.not.include('users_email_uk');
});
.then(() => this.queryInterface.showConstraint('users'))
.then(constraints => {
constraints = constraints.map(constraint => constraint.constraintName);
expect(constraints).to.include('users_email_uk');
return this.queryInterface.removeConstraint('users', 'users_email_uk');
})
.then(() => this.queryInterface.showConstraint('users'))
.then(constraints => {
constraints = constraints.map(constraint => constraint.constraintName);
expect(constraints).to.not.include('users_email_uk');
});
});
});
......@@ -924,17 +924,17 @@ describe(Support.getTestDialectTeaser('QueryInterface'), () => {
},
name: 'check_user_roles'
})
.then(() => this.queryInterface.showConstraint('users'))
.then(constraints => {
constraints = constraints.map(constraint => constraint.constraintName);
expect(constraints).to.include('check_user_roles');
return this.queryInterface.removeConstraint('users', 'check_user_roles');
})
.then(() => this.queryInterface.showConstraint('users'))
.then(constraints => {
constraints = constraints.map(constraint => constraint.constraintName);
expect(constraints).to.not.include('check_user_roles');
});
.then(() => this.queryInterface.showConstraint('users'))
.then(constraints => {
constraints = constraints.map(constraint => constraint.constraintName);
expect(constraints).to.include('check_user_roles');
return this.queryInterface.removeConstraint('users', 'check_user_roles');
})
.then(() => this.queryInterface.showConstraint('users'))
.then(constraints => {
constraints = constraints.map(constraint => constraint.constraintName);
expect(constraints).to.not.include('check_user_roles');
});
});
});
}
......@@ -946,17 +946,17 @@ describe(Support.getTestDialectTeaser('QueryInterface'), () => {
type: 'default',
defaultValue: 'guest'
})
.then(() => this.queryInterface.showConstraint('users'))
.then(constraints => {
constraints = constraints.map(constraint => constraint.constraintName);
expect(constraints).to.include('users_roles_df');
return this.queryInterface.removeConstraint('users', 'users_roles_df');
})
.then(() => this.queryInterface.showConstraint('users'))
.then(constraints => {
constraints = constraints.map(constraint => constraint.constraintName);
expect(constraints).to.not.include('users_roles_df');
});
.then(() => this.queryInterface.showConstraint('users'))
.then(constraints => {
constraints = constraints.map(constraint => constraint.constraintName);
expect(constraints).to.include('users_roles_df');
return this.queryInterface.removeConstraint('users', 'users_roles_df');
})
.then(() => this.queryInterface.showConstraint('users'))
.then(constraints => {
constraints = constraints.map(constraint => constraint.constraintName);
expect(constraints).to.not.include('users_roles_df');
});
});
});
}
......@@ -965,74 +965,74 @@ describe(Support.getTestDialectTeaser('QueryInterface'), () => {
describe('primary key', () => {
it('should add, read & remove primary key constraint', function() {
return this.queryInterface.removeColumn('users', 'id')
.then(() => {
return this.queryInterface.changeColumn('users', 'username', {
type: DataTypes.STRING,
allowNull: false
});
})
.then(() => {
return this.queryInterface.addConstraint('users', ['username'], {
type: 'PRIMARY KEY'
.then(() => {
return this.queryInterface.changeColumn('users', 'username', {
type: DataTypes.STRING,
allowNull: false
});
})
.then(() => {
return this.queryInterface.addConstraint('users', ['username'], {
type: 'PRIMARY KEY'
});
})
.then(() => this.queryInterface.showConstraint('users'))
.then(constraints => {
constraints = constraints.map(constraint => constraint.constraintName);
//The name of primaryKey constraint is always PRIMARY in case of mysql
if (dialect === 'mysql') {
expect(constraints).to.include('PRIMARY');
return this.queryInterface.removeConstraint('users', 'PRIMARY');
} else {
expect(constraints).to.include('users_username_pk');
return this.queryInterface.removeConstraint('users', 'users_username_pk');
}
})
.then(() => this.queryInterface.showConstraint('users'))
.then(constraints => {
constraints = constraints.map(constraint => constraint.constraintName);
expect(constraints).to.not.include('users_username_pk');
});
})
.then(() => this.queryInterface.showConstraint('users'))
.then(constraints => {
constraints = constraints.map(constraint => constraint.constraintName);
//The name of primaryKey constraint is always PRIMARY in case of mysql
if (dialect === 'mysql') {
expect(constraints).to.include('PRIMARY');
return this.queryInterface.removeConstraint('users', 'PRIMARY');
} else {
expect(constraints).to.include('users_username_pk');
return this.queryInterface.removeConstraint('users', 'users_username_pk');
}
})
.then(() => this.queryInterface.showConstraint('users'))
.then(constraints => {
constraints = constraints.map(constraint => constraint.constraintName);
expect(constraints).to.not.include('users_username_pk');
});
});
});
describe('foreign key', () => {
it('should add, read & remove foreign key constraint', function() {
return this.queryInterface.removeColumn('users', 'id')
.then(() => {
return this.queryInterface.changeColumn('users', 'username', {
type: DataTypes.STRING,
allowNull: false
});
})
.then(() => {
return this.queryInterface.addConstraint('users', {
type: 'PRIMARY KEY',
fields: ['username']
});
})
.then(() => {
return this.queryInterface.addConstraint('posts', ['username'], {
references: {
table: 'users',
field: 'username'
},
onDelete: 'cascade',
onUpdate: 'cascade',
type: 'foreign key'
.then(() => {
return this.queryInterface.changeColumn('users', 'username', {
type: DataTypes.STRING,
allowNull: false
});
})
.then(() => {
return this.queryInterface.addConstraint('users', {
type: 'PRIMARY KEY',
fields: ['username']
});
})
.then(() => {
return this.queryInterface.addConstraint('posts', ['username'], {
references: {
table: 'users',
field: 'username'
},
onDelete: 'cascade',
onUpdate: 'cascade',
type: 'foreign key'
});
})
.then(() => this.queryInterface.showConstraint('posts'))
.then(constraints => {
constraints = constraints.map(constraint => constraint.constraintName);
expect(constraints).to.include('posts_username_users_fk');
return this.queryInterface.removeConstraint('posts', 'posts_username_users_fk');
})
.then(() => this.queryInterface.showConstraint('posts'))
.then(constraints => {
constraints = constraints.map(constraint => constraint.constraintName);
expect(constraints).to.not.include('posts_username_users_fk');
});
})
.then(() => this.queryInterface.showConstraint('posts'))
.then(constraints => {
constraints = constraints.map(constraint => constraint.constraintName);
expect(constraints).to.include('posts_username_users_fk');
return this.queryInterface.removeConstraint('posts', 'posts_username_users_fk');
})
.then(() => this.queryInterface.showConstraint('posts'))
.then(constraints => {
constraints = constraints.map(constraint => constraint.constraintName);
expect(constraints).to.not.include('posts_username_users_fk');
});
});
});
......
......@@ -34,10 +34,10 @@ describe(Support.getTestDialectTeaser('Replication'), function() {
});
return this.User.sync({force: true})
.then(() => {
readSpy = sandbox.spy(this.sequelize.connectionManager.pool.read, 'acquire');
writeSpy = sandbox.spy(this.sequelize.connectionManager.pool.write, 'acquire');
});
.then(() => {
readSpy = sandbox.spy(this.sequelize.connectionManager.pool.read, 'acquire');
writeSpy = sandbox.spy(this.sequelize.connectionManager.pool.write, 'acquire');
});
});
afterEach(() => {
......@@ -58,25 +58,25 @@ describe(Support.getTestDialectTeaser('Replication'), function() {
return this.User.create({
firstName: Math.random().toString()
})
.then(expectWriteCalls);
.then(expectWriteCalls);
});
it('should be able to make a read', () => {
return this.User.findAll()
.then(expectReadCalls);
.then(expectReadCalls);
});
it('should run read-only transactions on the replica', () => {
return this.sequelize.transaction({readOnly: true}, transaction => {
return this.User.findAll({transaction});
})
.then(expectReadCalls);
.then(expectReadCalls);
});
it('should run non-read-only transactions on the primary', () => {
return this.sequelize.transaction(transaction => {
return this.User.findAll({transaction});
})
.then(expectWriteCalls);
.then(expectWriteCalls);
});
});
......@@ -282,10 +282,10 @@ describe(Support.getTestDialectTeaser('Sequelize'), () => {
") VALUES ('john', 'john@gmail.com', 'HORSE', '2012-01-01 10:10:10')";
return sequelize.query(insertWarningQuery)
.then(() => {
expect(logger.callCount).to.equal(3);
expect(logger.args[2][0]).to.be.match(/^MySQL Warnings \(default\):.*?'createdAt'/m);
});
.then(() => {
expect(logger.callCount).to.equal(3);
expect(logger.args[2][0]).to.be.match(/^MySQL Warnings \(default\):.*?'createdAt'/m);
});
});
}
......
......@@ -23,29 +23,29 @@ if (current.dialect.supports.transactions) {
it('gets triggered once a transaction has been successfully committed', function() {
let called = false;
return this
.sequelize
.transaction().then(t => {
return t.commit().then(() => {
called = 1;
.sequelize
.transaction().then(t => {
return t.commit().then(() => {
called = 1;
});
})
.then(() => {
expect(called).to.be.ok;
});
})
.then(() => {
expect(called).to.be.ok;
});
});
it('gets triggered once a transaction has been successfully rolled back', function() {
let called = false;
return this
.sequelize
.transaction().then(t => {
return t.rollback().then(() => {
called = 1;
.sequelize
.transaction().then(t => {
return t.rollback().then(() => {
called = 1;
});
})
.then(() => {
expect(called).to.be.ok;
});
})
.then(() => {
expect(called).to.be.ok;
});
});
if (Support.getTestDialect() !== 'sqlite') {
......@@ -107,17 +107,17 @@ if (current.dialect.supports.transactions) {
expect(transaction).to.be.instanceOf(Transaction);
return Test
.create({ name: 'Peter' }, { transaction })
.then(() => {
return Promise.delay(1000).then(() => {
return transaction
.commit()
.then(() => { return Test.count(); })
.then(count => {
expect(count).to.equal(1);
});
.create({ name: 'Peter' }, { transaction })
.then(() => {
return Promise.delay(1000).then(() => {
return transaction
.commit()
.then(() => { return Test.count(); })
.then(count => {
expect(count).to.equal(1);
});
});
});
});
});
});
});
......
......@@ -52,9 +52,9 @@ if (current.dialect.supports.tmpTableTrigger) {
user.username = 'usernamechanged';
return user.save();
})
.then(() => {
return expect(User.find({username: 'usernamechanged'})).to.eventually.have.property('username').which.equals('usernamechanged');
});
.then(() => {
return expect(User.find({username: 'usernamechanged'})).to.eventually.have.property('username').which.equals('usernamechanged');
});
});
it('should return output rows after Model update', () => {
......@@ -69,9 +69,9 @@ if (current.dialect.supports.tmpTableTrigger) {
}
});
})
.then(() => {
return expect(User.find({username: 'usernamechanged'})).to.eventually.have.property('username').which.equals('usernamechanged');
});
.then(() => {
return expect(User.find({username: 'usernamechanged'})).to.eventually.have.property('username').which.equals('usernamechanged');
});
});
it('should successfully delete with a trigger on the table', () => {
......
......@@ -283,7 +283,7 @@ describe(Support.getTestDialectTeaser('Utils'), () => {
it('accepts condition object (auto casting)', function() {
return Airplane.findAll({
attributes: [
[this.sequelize.fn('COUNT', '*'), 'count'],
[this.sequelize.fn('COUNT', '*'), 'count'],
[Sequelize.fn('SUM', {
engines: 1
}), 'count-engines'],
......
......@@ -202,8 +202,8 @@ const Support = {
if (!expectation) {
if (expectations['default'] !== undefined) {
expectation = expectations['default']
.replace(/\[/g, Support.sequelize.dialect.TICK_CHAR_LEFT)
.replace(/\]/g, Support.sequelize.dialect.TICK_CHAR_RIGHT);
.replace(/\[/g, Support.sequelize.dialect.TICK_CHAR_LEFT)
.replace(/\]/g, Support.sequelize.dialect.TICK_CHAR_RIGHT);
} else {
throw new Error('Undefined expectation for "' + Support.sequelize.dialect.name + '"!');
}
......
......@@ -26,15 +26,15 @@ describe('[MSSQL] Connection Manager', () => {
}
};
instance = new Sequelize(config.database
, config.username
, config.password
, config);
, config.username
, config.password
, config);
});
it('connectionManager._connect() Does not delete `domain` from config.dialectOptions',
() => {
expect(config.dialectOptions.domain).to.equal('TEST.COM');
instance.dialect.connectionManager._connect(config);
expect(config.dialectOptions.domain).to.equal('TEST.COM');
});
() => {
expect(config.dialectOptions.domain).to.equal('TEST.COM');
instance.dialect.connectionManager._connect(config);
expect(config.dialectOptions.domain).to.equal('TEST.COM');
});
});
......@@ -209,9 +209,9 @@ suite(Support.getTestDialectTeaser('SQL'), () => {
field: 'last_name'
}
},
{
tableName: 'users'
});
{
tableName: 'users'
});
const Post = Support.sequelize.define('Post', {
title: DataTypes.STRING,
userId: {
......@@ -219,9 +219,9 @@ suite(Support.getTestDialectTeaser('SQL'), () => {
field: 'user_id'
}
},
{
tableName: 'post'
});
{
tableName: 'post'
});
User.Posts = User.hasMany(Post, {foreignKey: 'userId', as: 'POSTS'});
......@@ -232,9 +232,9 @@ suite(Support.getTestDialectTeaser('SQL'), () => {
field: 'post_id'
}
},
{
tableName: 'comment'
});
{
tableName: 'comment'
});
Post.Comments = Post.hasMany(Comment, {foreignKey: 'postId', as: 'COMMENTS'});
......@@ -346,15 +346,15 @@ suite(Support.getTestDialectTeaser('SQL'), () => {
name: DataTypes.STRING,
age: DataTypes.INTEGER
},
{
freezeTableName: true
});
{
freezeTableName: true
});
const Post = Support.sequelize.define('Post', {
title: DataTypes.STRING
},
{
freezeTableName: true
});
{
freezeTableName: true
});
User.Posts = User.hasMany(Post, {foreignKey: 'user_id'});
......@@ -403,15 +403,15 @@ suite(Support.getTestDialectTeaser('SQL'), () => {
name: DataTypes.STRING,
age: DataTypes.INTEGER
},
{
freezeTableName: true
});
{
freezeTableName: true
});
const Post = Support.sequelize.define('Post', {
title: DataTypes.STRING
},
{
freezeTableName: true
});
{
freezeTableName: true
});
User.Posts = User.hasMany(Post, {foreignKey: 'user_id'});
......@@ -437,21 +437,21 @@ suite(Support.getTestDialectTeaser('SQL'), () => {
name: DataTypes.STRING,
age: DataTypes.INTEGER
},
{
freezeTableName: true
});
{
freezeTableName: true
});
const Post = Support.sequelize.define('Post', {
title: DataTypes.STRING
},
{
freezeTableName: true
});
{
freezeTableName: true
});
const Comment = Support.sequelize.define('Comment', {
title: DataTypes.STRING
},
{
freezeTableName: true
});
{
freezeTableName: true
});
User.Posts = User.hasMany(Post, {foreignKey: 'user_id'});
Post.Comments = Post.hasMany(Comment, {foreignKey: 'post_id'});
......
......@@ -303,8 +303,8 @@ suite(Support.getTestDialectTeaser('SQL'), () => {
testsql('name', {
$and: [
{like : '%someValue1%'},
{like : '%someValue2%'}
{like : '%someValue1%'},
{like : '%someValue2%'}
]
}, {
default: "([name] LIKE '%someValue1%' AND [name] LIKE '%someValue2%')",
......
......@@ -13,13 +13,13 @@ describe('Transaction', function() {
this.stub = sinon.stub(current, 'query').returns(Sequelize.Promise.resolve({}));
this.stubConnection = sinon.stub(current.connectionManager, 'getConnection')
.returns(Sequelize.Promise.resolve({
uuid: 'ssfdjd-434fd-43dfg23-2d',
close() {}
}));
.returns(Sequelize.Promise.resolve({
uuid: 'ssfdjd-434fd-43dfg23-2d',
close() {}
}));
this.stubRelease = sinon.stub(current.connectionManager, 'releaseConnection')
.returns(Sequelize.Promise.resolve());
.returns(Sequelize.Promise.resolve());
});
beforeEach(() => {
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!