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

Commit bb096ffb by Ruben Bridgewater

Add logging options to all querys and insert options into functions where it's missing

Reduce arguments.length lookup when not necessary

Refactor all internal .query calls to use .query(sql, options); instead of .query(sql, callee, options)

The callee is now passed to .query by using `options.instance = callee;`
1 parent e4bd7b5d
...@@ -126,7 +126,7 @@ migration.createTable( ...@@ -126,7 +126,7 @@ migration.createTable(
) )
``` ```
### dropTable(tableName) ### dropTable(tableName, options)
This method allows deletion of an existing table. This method allows deletion of an existing table.
...@@ -134,7 +134,7 @@ This method allows deletion of an existing table. ...@@ -134,7 +134,7 @@ This method allows deletion of an existing table.
migration.dropTable('nameOfTheExistingTable') migration.dropTable('nameOfTheExistingTable')
``` ```
### dropAllTables() ### dropAllTables(options)
This method allows deletion of all existing tables in the database. This method allows deletion of all existing tables in the database.
...@@ -142,7 +142,7 @@ This method allows deletion of all existing tables in the database. ...@@ -142,7 +142,7 @@ This method allows deletion of all existing tables in the database.
migration.dropAllTables() migration.dropAllTables()
``` ```
### renameTable(before, after) ### renameTable(before, after, options)
This method allows renaming of an existing table. This method allows renaming of an existing table.
...@@ -150,7 +150,7 @@ This method allows renaming of an existing table. ...@@ -150,7 +150,7 @@ This method allows renaming of an existing table.
migration.renameTable('Person', 'User') migration.renameTable('Person', 'User')
``` ```
### showAllTables() ### showAllTables(options)
This method returns the name of all existing tables in the database. This method returns the name of all existing tables in the database.
...@@ -158,7 +158,7 @@ This method returns the name of all existing tables in the database. ...@@ -158,7 +158,7 @@ This method returns the name of all existing tables in the database.
migration.showAllTables().success(function(tableNames) {}) migration.showAllTables().success(function(tableNames) {})
``` ```
### describeTable(tableName) ### describeTable(tableName, options)
This method returns an array of hashes containing information about all attributes in the table. This method returns an array of hashes containing information about all attributes in the table.
...@@ -183,7 +183,7 @@ migration.describeTable('Person').success(function(attributes) { ...@@ -183,7 +183,7 @@ migration.describeTable('Person').success(function(attributes) {
}) })
``` ```
### addColumn(tableName, attributeName, dataTypeOrOptions) ### addColumn(tableName, attributeName, dataTypeOrOptions, options)
This method allows adding columns to an existing table. The data type can be simple or complex. This method allows adding columns to an existing table. The data type can be simple or complex.
...@@ -206,7 +206,7 @@ migration.addColumn( ...@@ -206,7 +206,7 @@ migration.addColumn(
) )
``` ```
### removeColumn(tableName, attributeName) ### removeColumn(tableName, attributeName, options)
This method allows deletion of a specific column of an existing table. This method allows deletion of a specific column of an existing table.
...@@ -214,7 +214,7 @@ This method allows deletion of a specific column of an existing table. ...@@ -214,7 +214,7 @@ This method allows deletion of a specific column of an existing table.
migration.removeColumn('Person', 'signature') migration.removeColumn('Person', 'signature')
``` ```
### changeColumn(tableName, attributeName, dataTypeOrOptions) ### changeColumn(tableName, attributeName, dataTypeOrOptions, options)
This method changes the meta data of an attribute. It is possible to change the default value, allowance of null or the data type. Please make sure, that you are completely describing the new data type. Missing information are expected to be defaults. This method changes the meta data of an attribute. It is possible to change the default value, allowance of null or the data type. Please make sure, that you are completely describing the new data type. Missing information are expected to be defaults.
...@@ -238,7 +238,7 @@ migration.changeColumn( ...@@ -238,7 +238,7 @@ migration.changeColumn(
) )
``` ```
### renameColumn(tableName, attrNameBefore, attrNameAfter) ### renameColumn(tableName, attrNameBefore, attrNameAfter, options)
This methods allows renaming attributes. This methods allows renaming attributes.
...@@ -260,6 +260,7 @@ migration.addIndex('Person', ['firstname', 'lastname']) ...@@ -260,6 +260,7 @@ migration.addIndex('Person', ['firstname', 'lastname'])
// - indexName: The name of the index. Default is __ // - indexName: The name of the index. Default is __
// - parser: For FULLTEXT columns set your parser // - parser: For FULLTEXT columns set your parser
// - indexType: Set a type for the index, e.g. BTREE. See the documentation of the used dialect // - indexType: Set a type for the index, e.g. BTREE. See the documentation of the used dialect
// - logging: A function that receives the sql query, e.g. console.log
migration.addIndex( migration.addIndex(
'Person', 'Person',
['firstname', 'lastname'], ['firstname', 'lastname'],
...@@ -270,7 +271,7 @@ migration.addIndex( ...@@ -270,7 +271,7 @@ migration.addIndex(
) )
``` ```
### removeIndex(tableName, indexNameOrAttributes) ### removeIndex(tableName, indexNameOrAttributes, options)
This method deletes an existing index of a table. This method deletes an existing index of a table.
......
...@@ -415,8 +415,8 @@ module.exports = (function() { ...@@ -415,8 +415,8 @@ module.exports = (function() {
var association = this var association = this
, primaryKeyAttribute = association.target.primaryKeyAttribute; , primaryKeyAttribute = association.target.primaryKeyAttribute;
obj[this.accessors.set] = function(newAssociatedObjects, additionalAttributes) { obj[this.accessors.set] = function(newAssociatedObjects, options) {
additionalAttributes = additionalAttributes || {}; options = options || {};
if (newAssociatedObjects === null) { if (newAssociatedObjects === null) {
newAssociatedObjects = []; newAssociatedObjects = [];
...@@ -436,20 +436,20 @@ module.exports = (function() { ...@@ -436,20 +436,20 @@ module.exports = (function() {
var instance = this; var instance = this;
return instance[association.accessors.get]({}, { return instance[association.accessors.get]({}, {
transaction: additionalAttributes.transaction transaction: options.transaction,
logging: options.logging
}).then(function(oldAssociatedObjects) { }).then(function(oldAssociatedObjects) {
var foreignIdentifier = association.foreignIdentifier var foreignIdentifier = association.foreignIdentifier
, sourceKeys = Object.keys(association.source.primaryKeys) , sourceKeys = Object.keys(association.source.primaryKeys)
, targetKeys = Object.keys(association.target.primaryKeys) , targetKeys = Object.keys(association.target.primaryKeys)
, obsoleteAssociations = [] , obsoleteAssociations = []
, changedAssociations = [] , changedAssociations = []
, defaultAttributes = additionalAttributes , defaultAttributes = options
, options = additionalAttributes
, promises = [] , promises = []
, unassociatedObjects; , unassociatedObjects;
// Don't try to insert the transaction as an attribute in the through table // Don't try to insert the transaction as an attribute in the through table
defaultAttributes = Utils._.omit(defaultAttributes, ['transaction', 'hooks', 'individualHooks', 'ignoreDuplicates', 'validate', 'fields']); defaultAttributes = Utils._.omit(defaultAttributes, ['transaction', 'hooks', 'individualHooks', 'ignoreDuplicates', 'validate', 'fields', 'logging']);
unassociatedObjects = newAssociatedObjects.filter(function(obj) { unassociatedObjects = newAssociatedObjects.filter(function(obj) {
return !Utils._.find(oldAssociatedObjects, function(old) { return !Utils._.find(oldAssociatedObjects, function(old) {
...@@ -536,16 +536,16 @@ module.exports = (function() { ...@@ -536,16 +536,16 @@ module.exports = (function() {
// If newInstance is null or undefined, no-op // If newInstance is null or undefined, no-op
if (!newInstance) return Utils.Promise.resolve(); if (!newInstance) return Utils.Promise.resolve();
var instance = this
, primaryKeyAttribute = association.target.primaryKeyAttribute;
additionalAttributes = additionalAttributes || {};
if (association.through && association.through.scope) { if (association.through && association.through.scope) {
Object.keys(association.through.scope).forEach(function (attribute) { Object.keys(association.through.scope).forEach(function (attribute) {
additionalAttributes[attribute] = association.through.scope[attribute]; additionalAttributes[attribute] = association.through.scope[attribute];
}); });
} }
var instance = this
, primaryKeyAttribute = association.target.primaryKeyAttribute
, options = additionalAttributes = additionalAttributes || {};
if (Array.isArray(newInstance)) { if (Array.isArray(newInstance)) {
var newInstances = newInstance.map(function(newInstance) { var newInstances = newInstance.map(function(newInstance) {
if (!(newInstance instanceof association.target.Instance)) { if (!(newInstance instanceof association.target.Instance)) {
...@@ -563,14 +563,13 @@ module.exports = (function() { ...@@ -563,14 +563,13 @@ module.exports = (function() {
, targetKeys = Object.keys(association.target.primaryKeys) , targetKeys = Object.keys(association.target.primaryKeys)
, obsoleteAssociations = [] , obsoleteAssociations = []
, changedAssociations = [] , changedAssociations = []
, defaultAttributes = additionalAttributes || {} , defaultAttributes = additionalAttributes
, options = defaultAttributes
, promises = [] , promises = []
, oldAssociations = [] , oldAssociations = []
, unassociatedObjects; , unassociatedObjects;
// Don't try to insert the transaction as an attribute in the through table // Don't try to insert the transaction as an attribute in the through table
defaultAttributes = Utils._.omit(defaultAttributes, ['transaction', 'hooks', 'individualHooks', 'ignoreDuplicates', 'validate', 'fields']); defaultAttributes = Utils._.omit(defaultAttributes, ['transaction', 'hooks', 'individualHooks', 'ignoreDuplicates', 'validate', 'fields', 'logging']);
unassociatedObjects = newInstances.filter(function(obj) { unassociatedObjects = newInstances.filter(function(obj) {
return !Utils._.find(oldAssociations, function(old) { return !Utils._.find(oldAssociations, function(old) {
...@@ -664,19 +663,18 @@ module.exports = (function() { ...@@ -664,19 +663,18 @@ module.exports = (function() {
return instance[association.accessors.get]({ return instance[association.accessors.get]({
where: newInstance.primaryKeyValues where: newInstance.primaryKeyValues
}, { }, {
transaction: (additionalAttributes || {}).transaction transaction: (additionalAttributes || {}).transaction,
logging: options.logging
}).then(function(currentAssociatedObjects) { }).then(function(currentAssociatedObjects) {
additionalAttributes = additionalAttributes || {};
var attributes = {} var attributes = {}
, foreignIdentifier = association.foreignIdentifier , foreignIdentifier = association.foreignIdentifier;
, options = additionalAttributes;
var sourceKeys = Object.keys(association.source.primaryKeys); var sourceKeys = Object.keys(association.source.primaryKeys);
var targetKeys = Object.keys(association.target.primaryKeys); var targetKeys = Object.keys(association.target.primaryKeys);
// Don't try to insert the transaction as an attribute in the through table // Don't try to insert the transaction as an attribute in the through table
additionalAttributes = Utils._.omit(additionalAttributes, ['transaction', 'hooks', 'individualHooks', 'ignoreDuplicates', 'validate', 'fields']); additionalAttributes = Utils._.omit(additionalAttributes, ['transaction', 'hooks', 'individualHooks', 'ignoreDuplicates', 'validate', 'fields', 'logging']);
attributes[association.identifier] = ((sourceKeys.length === 1) ? instance[sourceKeys[0]] : instance.id); attributes[association.identifier] = ((sourceKeys.length === 1) ? instance[sourceKeys[0]] : instance.id);
attributes[foreignIdentifier] = ((targetKeys.length === 1) ? newInstance[targetKeys[0]] : newInstance.id); attributes[foreignIdentifier] = ((targetKeys.length === 1) ? newInstance[targetKeys[0]] : newInstance.id);
......
...@@ -20,13 +20,17 @@ module.exports = { ...@@ -20,13 +20,17 @@ module.exports = {
@param {String} tableName The name of the table. @param {String} tableName The name of the table.
@param {String} attributeName The name of the attribute that we want to remove. @param {String} attributeName The name of the attribute that we want to remove.
@param {Object} options
@param {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
@param {CustomEventEmitter} emitter The EventEmitter from outside. @param {CustomEventEmitter} emitter The EventEmitter from outside.
@param {Function} queryAndEmit The function from outside that triggers some events to get triggered. @param {Function} queryAndEmit The function from outside that triggers some events to get triggered.
@since 1.6.0 @since 1.6.0
*/ */
removeColumn: function(tableName, attributeName) { removeColumn: function(tableName, attributeName, options) {
var self = this; var self = this;
options = options || {};
return this.describeTable(tableName).then(function(fields) { return this.describeTable(tableName).then(function(fields) {
delete fields[attributeName]; delete fields[attributeName];
...@@ -34,7 +38,7 @@ module.exports = { ...@@ -34,7 +38,7 @@ module.exports = {
, subQueries = sql.split(';').filter(function(q) { return q !== ''; }); , subQueries = sql.split(';').filter(function(q) { return q !== ''; });
return Promise.each(subQueries, function(subQuery) { return Promise.each(subQueries, function(subQuery) {
return self.sequelize.query(subQuery + ';', null, { raw: true}); return self.sequelize.query(subQuery + ';', { raw: true, logging: options.logging });
}); });
}); });
}, },
...@@ -49,14 +53,17 @@ module.exports = { ...@@ -49,14 +53,17 @@ module.exports = {
@param {String} tableName The name of the table. @param {String} tableName The name of the table.
@param {Object} attributes An object with the attribute's name as key and it's options as value object. @param {Object} attributes An object with the attribute's name as key and it's 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 {CustomEventEmitter} emitter The EventEmitter from outside. @param {CustomEventEmitter} emitter The EventEmitter from outside.
@param {Function} queryAndEmit The function from outside that triggers some events to get triggered. @param {Function} queryAndEmit The function from outside that triggers some events to get triggered.
@since 1.6.0 @since 1.6.0
*/ */
changeColumn: function(tableName, attributes) { changeColumn: function(tableName, attributes, options) {
var attributeName = Utils._.keys(attributes)[0] var attributeName = Utils._.keys(attributes)[0]
, self = this; , self = this;
options = options || {};
return this.describeTable(tableName).then(function(fields) { return this.describeTable(tableName).then(function(fields) {
fields[attributeName] = attributes[attributeName]; fields[attributeName] = attributes[attributeName];
...@@ -65,7 +72,7 @@ module.exports = { ...@@ -65,7 +72,7 @@ module.exports = {
, subQueries = sql.split(';').filter(function(q) { return q !== ''; }); , subQueries = sql.split(';').filter(function(q) { return q !== ''; });
return Promise.each(subQueries, function(subQuery) { return Promise.each(subQueries, function(subQuery) {
return self.sequelize.query(subQuery + ';', null, { raw: true}); return self.sequelize.query(subQuery + ';', { raw: true, logging: options.logging });
}); });
}); });
}, },
...@@ -81,13 +88,17 @@ module.exports = { ...@@ -81,13 +88,17 @@ module.exports = {
@param {String} tableName The name of the table. @param {String} tableName The name of the table.
@param {String} attrNameBefore The name of the attribute before it was renamed. @param {String} attrNameBefore The name of the attribute before it was renamed.
@param {String} attrNameAfter The name of the attribute after it was renamed. @param {String} attrNameAfter The name of the attribute after it was renamed.
@param {Object} options
@param {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
@param {CustomEventEmitter} emitter The EventEmitter from outside. @param {CustomEventEmitter} emitter The EventEmitter from outside.
@param {Function} queryAndEmit The function from outside that triggers some events to get triggered. @param {Function} queryAndEmit The function from outside that triggers some events to get triggered.
@since 1.6.0 @since 1.6.0
*/ */
renameColumn: function(tableName, attrNameBefore, attrNameAfter) { renameColumn: function(tableName, attrNameBefore, attrNameAfter, options) {
var self = this; var self = this;
options = options || {};
return this.describeTable(tableName).then(function(fields) { return this.describeTable(tableName).then(function(fields) {
fields[attrNameAfter] = Utils._.clone(fields[attrNameBefore]); fields[attrNameAfter] = Utils._.clone(fields[attrNameBefore]);
delete fields[attrNameBefore]; delete fields[attrNameBefore];
...@@ -96,7 +107,7 @@ module.exports = { ...@@ -96,7 +107,7 @@ module.exports = {
, subQueries = sql.split(';').filter(function(q) { return q !== ''; }); , subQueries = sql.split(';').filter(function(q) { return q !== ''; });
return Promise.each(subQueries, function(subQuery) { return Promise.each(subQueries, function(subQuery) {
return self.sequelize.query(subQuery + ';', null, { raw: true}); return self.sequelize.query(subQuery + ';', { raw: true, logging: options.logging });
}); });
}); });
} }
......
...@@ -537,7 +537,7 @@ module.exports = (function() { ...@@ -537,7 +537,7 @@ module.exports = (function() {
self.scoped = true; self.scoped = true;
// Set defaults // Set defaults
scopeOptions = (typeof lastArg === 'object' && !Array.isArray(lastArg) && lastArg !== null ? lastArg : {}) || {}; // <-- for no arguments scopeOptions = typeof lastArg === 'object' && !Array.isArray(lastArg) && lastArg || {};
scopeOptions.silent = (scopeOptions !== null && scopeOptions.hasOwnProperty('silent') ? scopeOptions.silent : true); scopeOptions.silent = (scopeOptions !== null && scopeOptions.hasOwnProperty('silent') ? scopeOptions.silent : true);
// Clear out any predefined scopes... // Clear out any predefined scopes...
......
...@@ -667,19 +667,17 @@ module.exports = (function() { ...@@ -667,19 +667,17 @@ module.exports = (function() {
*/ */
Sequelize.prototype.query = function(sql, callee, options, replacements) { Sequelize.prototype.query = function(sql, callee, options, replacements) {
var self = this; var self = this;
if (arguments.length === 4) { if (arguments.length === 2) {
deprecated('passing raw query replacements as the 4th argument to sequelize.query is deprecated. Please use options.replacements instead');
options.replacements = replacements;
} else if (arguments.length === 3) {
options = options;
} else if (arguments.length === 2) {
if (callee instanceof Sequelize.Model) { if (callee instanceof Sequelize.Model) {
options = {}; options = {};
} else { } else {
options = callee; options = callee;
callee = undefined; callee = options.instance || undefined;
} }
} else { } else if (arguments.length === 4) {
deprecated('passing raw query replacements as the 4th argument to sequelize.query is deprecated. Please use options.replacements instead');
options.replacements = replacements;
} else if (arguments.length !== 3) {
options = { raw: true }; options = { raw: true };
} }
...@@ -789,7 +787,7 @@ module.exports = (function() { ...@@ -789,7 +787,7 @@ module.exports = (function() {
return '@'+k +' := '+ ( typeof v === 'string' ? '"'+v+'"' : v ); return '@'+k +' := '+ ( typeof v === 'string' ? '"'+v+'"' : v );
}).join(', '); }).join(', ');
return this.query(query, null, options); return this.query(query, options);
}; };
/** /**
...@@ -810,10 +808,12 @@ module.exports = (function() { ...@@ -810,10 +808,12 @@ module.exports = (function() {
* *
* @see {Model#schema} * @see {Model#schema}
* @param {String} schema Name of the schema * @param {String} schema Name of the schema
* @param {Object} options={}
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise} * @return {Promise}
*/ */
Sequelize.prototype.createSchema = function(schema) { Sequelize.prototype.createSchema = function(schema, options) {
return this.getQueryInterface().createSchema(schema); return this.getQueryInterface().createSchema(schema, options);
}; };
/** /**
...@@ -821,10 +821,12 @@ module.exports = (function() { ...@@ -821,10 +821,12 @@ module.exports = (function() {
* *
* Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), * Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
* not a database table. In mysql and sqlite, this will show all tables. * not a database table. In mysql and sqlite, this will show all tables.
* @param {Object} options={}
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise} * @return {Promise}
*/ */
Sequelize.prototype.showAllSchemas = function() { Sequelize.prototype.showAllSchemas = function(options) {
return this.getQueryInterface().showAllSchemas(); return this.getQueryInterface().showAllSchemas(options);
}; };
/** /**
...@@ -833,10 +835,12 @@ module.exports = (function() { ...@@ -833,10 +835,12 @@ module.exports = (function() {
* Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), * Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
* not a database table. In mysql and sqlite, this drop a table matching the schema name * not a database table. In mysql and sqlite, this drop a table matching the schema name
* @param {String} schema Name of the schema * @param {String} schema Name of the schema
* @param {Object} options={}
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise} * @return {Promise}
*/ */
Sequelize.prototype.dropSchema = function(schema) { Sequelize.prototype.dropSchema = function(schema, options) {
return this.getQueryInterface().dropSchema(schema); return this.getQueryInterface().dropSchema(schema, options);
}; };
/** /**
...@@ -844,10 +848,12 @@ module.exports = (function() { ...@@ -844,10 +848,12 @@ module.exports = (function() {
* *
* Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), * Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
* not a database table. In mysql and sqlite, this is the equivalent of drop all tables. * not a database table. In mysql and sqlite, this is the equivalent of drop all tables.
* @param {Object} options={}
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise} * @return {Promise}
*/ */
Sequelize.prototype.dropAllSchemas = function() { Sequelize.prototype.dropAllSchemas = function(options) {
return this.getQueryInterface().dropAllSchemas(); return this.getQueryInterface().dropAllSchemas(options);
}; };
/** /**
...@@ -903,6 +909,7 @@ module.exports = (function() { ...@@ -903,6 +909,7 @@ module.exports = (function() {
* @see {Model#drop} for options * @see {Model#drop} for options
* *
* @param {object} options The options passed to each call to Model.drop * @param {object} options The options passed to each call to Model.drop
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise} * @return {Promise}
*/ */
Sequelize.prototype.drop = function(options) { Sequelize.prototype.drop = function(options) {
...@@ -928,13 +935,13 @@ module.exports = (function() { ...@@ -928,13 +935,13 @@ module.exports = (function() {
* @return {Promise} * @return {Promise}
*/ */
Sequelize.prototype.authenticate = function() { Sequelize.prototype.authenticate = function() {
return this.query('SELECT 1+1 AS result', null, { raw: true, plain: true }).return().catch(function(err) { return this.query('SELECT 1+1 AS result', { raw: true, plain: true }).return().catch(function(err) {
throw new Error(err); throw new Error(err);
}); });
}; };
Sequelize.prototype.databaseVersion = function() { Sequelize.prototype.databaseVersion = function(options) {
return this.queryInterface.databaseVersion(); return this.queryInterface.databaseVersion(options);
}; };
Sequelize.prototype.validate = Sequelize.prototype.authenticate; Sequelize.prototype.validate = Sequelize.prototype.authenticate;
......
...@@ -874,7 +874,7 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), function() { ...@@ -874,7 +874,7 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), function() {
logging: spy logging: spy
}); });
}).then(function() { }).then(function() {
expect(spy.calledOnce).to.be.ok; expect(spy.calledTwice).to.be.ok;
}); });
}); });
...@@ -892,7 +892,7 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), function() { ...@@ -892,7 +892,7 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), function() {
logging: spy logging: spy
}); });
}).then(function() { }).then(function() {
expect(spy.calledOnce).to.be.ok; expect(spy.calledTwice).to.be.ok;
}); });
}); });
}); // end optimization using bulk create, destroy and update }); // end optimization using bulk create, destroy and update
...@@ -1070,6 +1070,7 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), function() { ...@@ -1070,6 +1070,7 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), function() {
it('should correctly get associations even after a child instance is deleted', function() { it('should correctly get associations even after a child instance is deleted', function() {
var self = this; var self = this;
var spy = sinon.spy();
return this.sequelize.sync({force: true}).then(function() { return this.sequelize.sync({force: true}).then(function() {
return Promise.join( return Promise.join(
...@@ -1078,13 +1079,20 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), function() { ...@@ -1078,13 +1079,20 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), function() {
self.Project.create({name: 'The Departed'}) self.Project.create({name: 'The Departed'})
); );
}).spread(function(user, project1, project2) { }).spread(function(user, project1, project2) {
return user.addProjects([project1, project2]).return (user); return user.addProjects([project1, project2], {
logging: spy
}).return (user);
}).then(function(user) { }).then(function(user) {
expect(spy.calledOnce).to.be.ok;
spy.reset();
return Promise.join( return Promise.join(
user, user,
user.getProjects() user.getProjects({
logging: spy
})
); );
}).spread(function(user, projects) { }).spread(function(user, projects) {
expect(spy.calledOnce).to.be.ok;
var project = projects[0]; var project = projects[0];
expect(project).to.be.ok; expect(project).to.be.ok;
return project.destroy().return (user); return project.destroy().return (user);
...@@ -1112,15 +1120,24 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), function() { ...@@ -1112,15 +1120,24 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), function() {
}).spread(function(user, project) { }).spread(function(user, project) {
self.user = user; self.user = user;
self.project = project; self.project = project;
return user.addProject(project).return (user); return user.addProject(project, { logging: spy }).return (user);
}).then(function(user) { }).then(function(user) {
return user.getProjects(); expect(spy.calledTwice).to.be.ok; // Once for SELECT, once for INSERT
spy.reset();
return user.getProjects({
logging: spy
});
}).then(function(projects) { }).then(function(projects) {
var project = projects[0]; var project = projects[0];
expect(spy.calledOnce).to.be.ok;
spy.reset();
expect(project).to.be.ok; expect(project).to.be.ok;
return self.user.removeProject(project, { return self.user.removeProject(project, {
logging: spy logging: function(sql) {
console.error(sql);
spy();
}
}).return (project); }).return (project);
}).then(function(project) { }).then(function(project) {
expect(spy.calledTwice).to.be.ok; // Once for SELECT, once for REMOVE expect(spy.calledTwice).to.be.ok; // Once for SELECT, once for REMOVE
......
...@@ -6,7 +6,14 @@ var chai = require('chai') ...@@ -6,7 +6,14 @@ var chai = require('chai')
, Support = require(__dirname + '/support') , Support = require(__dirname + '/support')
, DataTypes = require(__dirname + '/../../lib/data-types') , DataTypes = require(__dirname + '/../../lib/data-types')
, dialect = Support.getTestDialect() , dialect = Support.getTestDialect()
, _ = require('lodash'); , _ = require('lodash')
, count = 0
, log = function (sql) {
// sqlite fires a lot more querys than the other dbs. this is just a simple hack, since i'm lazy
if (dialect !== 'sqlite' || count === 0) {
count++;
}
};
chai.config.includeStack = true; chai.config.includeStack = true;
...@@ -20,12 +27,22 @@ describe(Support.getTestDialectTeaser('QueryInterface'), function() { ...@@ -20,12 +27,22 @@ describe(Support.getTestDialectTeaser('QueryInterface'), function() {
it('should drop all tables', function() { it('should drop all tables', function() {
var self = this; var self = this;
return this.queryInterface.dropAllTables().then(function() { return this.queryInterface.dropAllTables().then(function() {
return self.queryInterface.showAllTables().then(function(tableNames) { return self.queryInterface.showAllTables({logging: log}).then(function(tableNames) {
expect(count).to.be.equal(1);
count = 0;
expect(tableNames).to.be.empty; expect(tableNames).to.be.empty;
return self.queryInterface.createTable('table', { name: DataTypes.STRING }).then(function() { return self.queryInterface.createTable('table', { name: DataTypes.STRING }, {
return self.queryInterface.showAllTables().then(function(tableNames) { logging: log
}).then(function() {
expect(count).to.be.equal(1);
count = 0;
return self.queryInterface.showAllTables({logging: log}).then(function(tableNames) {
expect(count).to.be.equal(1);
count = 0;
expect(tableNames).to.have.length(1); expect(tableNames).to.have.length(1);
return self.queryInterface.dropAllTables().then(function() { return self.queryInterface.dropAllTables({logging: log}).then(function() {
expect(count).to.be.equal(1);
count = 0;
return self.queryInterface.showAllTables().then(function(tableNames) { return self.queryInterface.showAllTables().then(function(tableNames) {
expect(tableNames).to.be.empty; expect(tableNames).to.be.empty;
}); });
...@@ -56,7 +73,9 @@ describe(Support.getTestDialectTeaser('QueryInterface'), function() { ...@@ -56,7 +73,9 @@ describe(Support.getTestDialectTeaser('QueryInterface'), function() {
describe('indexes', function() { describe('indexes', function() {
beforeEach(function() { beforeEach(function() {
var self = this; var self = this;
return this.queryInterface.dropTable('Group').then(function() { return this.queryInterface.dropTable('Group', {logging: log}).then(function() {
expect(count).to.be.equal(1);
count = 0;
return self.queryInterface.createTable('Group', { return self.queryInterface.createTable('Group', {
username: DataTypes.STRING, username: DataTypes.STRING,
isAdmin: DataTypes.BOOLEAN, isAdmin: DataTypes.BOOLEAN,
...@@ -67,11 +86,20 @@ describe(Support.getTestDialectTeaser('QueryInterface'), function() { ...@@ -67,11 +86,20 @@ describe(Support.getTestDialectTeaser('QueryInterface'), function() {
it('adds, reads and removes an index to the table', function() { it('adds, reads and removes an index to the table', function() {
var self = this; var self = this;
return this.queryInterface.addIndex('Group', ['username', 'isAdmin']).then(function() { return this.queryInterface.addIndex('Group', ['username', 'isAdmin'], {
return self.queryInterface.showIndex('Group').then(function(indexes) { logging: log
}).then(function() {
expect(count).to.be.equal(1);
count = 0;
return self.queryInterface.showIndex('Group', {logging: log}).then(function(indexes) {
expect(count).to.be.equal(1);
count = 0;
var indexColumns = _.uniq(indexes.map(function(index) { return index.name; })); var indexColumns = _.uniq(indexes.map(function(index) { return index.name; }));
expect(indexColumns).to.include('group_username_is_admin'); expect(indexColumns).to.include('group_username_is_admin');
return self.queryInterface.removeIndex('Group', ['username', 'isAdmin']).then(function() { return self.queryInterface.removeIndex('Group', ['username', 'isAdmin'], {logging: log}).then(function() {
expect(count).to.be.equal(1);
count = 0;
return self.queryInterface.showIndex('Group').then(function(indexes) { return self.queryInterface.showIndex('Group').then(function(indexes) {
indexColumns = _.uniq(indexes.map(function(index) { return index.name; })); indexColumns = _.uniq(indexes.map(function(index) { return index.name; }));
expect(indexColumns).to.be.empty; expect(indexColumns).to.be.empty;
...@@ -96,7 +124,10 @@ describe(Support.getTestDialectTeaser('QueryInterface'), function() { ...@@ -96,7 +124,10 @@ describe(Support.getTestDialectTeaser('QueryInterface'), function() {
}, { freezeTableName: true }); }, { freezeTableName: true });
return Users.sync({ force: true }).then(function() { return Users.sync({ force: true }).then(function() {
return self.queryInterface.describeTable('_Users').then(function(metadata) { return self.queryInterface.describeTable('_Users', {logging: log}).then(function(metadata) {
expect(count).to.be.equal(1);
count = 0;
var username = metadata.username; var username = metadata.username;
var isAdmin = metadata.isAdmin; var isAdmin = metadata.isAdmin;
var enumVals = metadata.enumVals; var enumVals = metadata.enumVals;
...@@ -179,9 +210,16 @@ describe(Support.getTestDialectTeaser('QueryInterface'), function() { ...@@ -179,9 +210,16 @@ describe(Support.getTestDialectTeaser('QueryInterface'), function() {
it('should work with schemas', function() { it('should work with schemas', function() {
var self = this; var self = this;
return self.sequelize.dropAllSchemas().then(function() { return self.sequelize.dropAllSchemas({logging: log}).then(function() {
return self.sequelize.createSchema('hero'); // TODO: FIXME: somehow these do not fire the logging function
if (dialect !== 'mysql' && dialect !== 'sqlite' && dialect !== 'mariadb') {
expect(count).to.be.above(0);
}
count = 0;
return self.sequelize.createSchema('hero', {logging: log});
}).then(function() { }).then(function() {
expect(count).to.be.equal(1);
count = 0;
return self.queryInterface.createTable('User', { return self.queryInterface.createTable('User', {
name: { name: {
type: DataTypes.STRING type: DataTypes.STRING
...@@ -191,8 +229,12 @@ describe(Support.getTestDialectTeaser('QueryInterface'), function() { ...@@ -191,8 +229,12 @@ describe(Support.getTestDialectTeaser('QueryInterface'), function() {
}); });
}).then(function() { }).then(function() {
return self.queryInterface.rawSelect('User', { return self.queryInterface.rawSelect('User', {
schema: 'hero' schema: 'hero',
logging: log
}, 'name'); }, 'name');
}).then(function() {
expect(count).to.be.equal(1);
count = 0;
}); });
}); });
}); });
...@@ -205,7 +247,12 @@ describe(Support.getTestDialectTeaser('QueryInterface'), function() { ...@@ -205,7 +247,12 @@ describe(Support.getTestDialectTeaser('QueryInterface'), function() {
}, { freezeTableName: true }); }, { freezeTableName: true });
return Users.sync({ force: true }).then(function() { return Users.sync({ force: true }).then(function() {
return self.queryInterface.renameColumn('_Users', 'username', 'pseudo'); return self.queryInterface.renameColumn('_Users', 'username', 'pseudo', {logging: log}).then(function() {
if (dialect === 'sqlite')
count++;
expect(count).to.be.equal(2);
count = 0;
});
}); });
}); });
...@@ -297,6 +344,11 @@ describe(Support.getTestDialectTeaser('QueryInterface'), function() { ...@@ -297,6 +344,11 @@ describe(Support.getTestDialectTeaser('QueryInterface'), function() {
schema: 'archive' schema: 'archive'
}, 'currency', { }, 'currency', {
type: DataTypes.FLOAT type: DataTypes.FLOAT
}, {
logging: log
}).then(function() {
expect(count).to.be.equal(1);
count = 0;
}); });
}); });
}); });
...@@ -328,7 +380,10 @@ describe(Support.getTestDialectTeaser('QueryInterface'), function() { ...@@ -328,7 +380,10 @@ describe(Support.getTestDialectTeaser('QueryInterface'), function() {
referenceKey: 'id', referenceKey: 'id',
onUpdate: 'cascade', onUpdate: 'cascade',
onDelete: 'set null' onDelete: 'set null'
}); }, {logging: log});
}).then(function() {
expect(count).to.be.equal(1);
count = 0;
}); });
}); });
...@@ -404,8 +459,10 @@ describe(Support.getTestDialectTeaser('QueryInterface'), function() { ...@@ -404,8 +459,10 @@ describe(Support.getTestDialectTeaser('QueryInterface'), function() {
it('should get a list of foreign keys for the table', function() { it('should get a list of foreign keys for the table', function() {
var sql = this.queryInterface.QueryGenerator.getForeignKeysQuery('hosts', this.sequelize.config.database); var sql = this.queryInterface.QueryGenerator.getForeignKeysQuery('hosts', this.sequelize.config.database);
return this.sequelize.query(sql, {type: this.sequelize.QueryTypes.FOREIGNKEYS}).then(function(fks) { return this.sequelize.query(sql, {type: this.sequelize.QueryTypes.FOREIGNKEYS, logging: log}).then(function(fks) {
expect(count).to.be.equal(1);
expect(fks).to.have.length(3); expect(fks).to.have.length(3);
count = 0;
var keys = Object.keys(fks[0]), var keys = Object.keys(fks[0]),
keys2 = Object.keys(fks[1]), keys2 = Object.keys(fks[1]),
keys3 = Object.keys(fks[2]); keys3 = Object.keys(fks[2]);
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!