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

Commit 46887666 by Mick Hansen

Merge pull request #3549 from BridgeAR/propper-sql-logging

Proper sql logging
2 parents cc439041 ee7099a6
# Next # Next
- [BUG] Enable standards conforming strings on connection in postgres. Adresses [#3545](https://github.com/sequelize/sequelize/issues/3545) - [BUG] Enable standards conforming strings on connection in postgres. Adresses [#3545](https://github.com/sequelize/sequelize/issues/3545)
- [BUG] instance.removeAssociation(s) do not fire the select query twice anymore
- [BUG] Error messages thrown by the db in languages other than english do not crash the app anymore (mysql, mariadb and postgres only) [#3567](https://github.com/sequelize/sequelize/pull/3567)
- [FEATURE] All querys can be logged individually by inserting `logging: fn` in the query option.
- The query-chainer is deprecated and will be removed in version 2.2. Please use promises instead.
# 2.0.6 # 2.0.6
- [BUG] Don't update virtual attributes in Model.update. Fixes [#2860](https://github.com/sequelize/sequelize/issues/2860) - [BUG] Don't update virtual attributes in Model.update. Fixes [#2860](https://github.com/sequelize/sequelize/issues/2860)
...@@ -12,6 +17,11 @@ ...@@ -12,6 +17,11 @@
+ inflection@1.6.0 + inflection@1.6.0
+ lodash@3.5.0 + lodash@3.5.0
+ validator@3.34 + validator@3.34
+ generic-pool@2.2.0
- [INTERNALS] Updated devDependencies.
+ coffee-script@1.9.1
+ dox@0.7.1
+ mysql@2.6.2
# 2.0.5 # 2.0.5
- [FEATURE] Highly experimental support for nested creation [#3386](https://github.com/sequelize/sequelize/pull/3386) - [FEATURE] Highly experimental support for nested creation [#3386](https://github.com/sequelize/sequelize/pull/3386)
......
...@@ -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,41 +415,48 @@ module.exports = (function() { ...@@ -415,41 +415,48 @@ 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) {
newAssociatedObjects = [];
} else {
newAssociatedObjects = newAssociatedObjects.map(function(newAssociatedObject) {
if (!(newAssociatedObject instanceof association.target.Instance)) {
var tmpInstance = {};
tmpInstance[primaryKeyAttribute] = newAssociatedObject;
return association.target.build(tmpInstance, {
isNewRecord: false
});
}
return newAssociatedObject;
});
}
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;
if (newAssociatedObjects === null) {
newAssociatedObjects = [];
} else {
if (!Array.isArray(newAssociatedObjects)) {
newAssociatedObjects = [newAssociatedObjects];
}
newAssociatedObjects = newAssociatedObjects.map(function(newAssociatedObject) {
if (!(newAssociatedObject instanceof association.target.Instance)) {
var tmpInstance = {};
tmpInstance[primaryKeyAttribute] = newAssociatedObject;
return association.target.build(tmpInstance, {
isNewRecord: false
});
}
return newAssociatedObject;
});
}
if (options.remove) {
oldAssociatedObjects = newAssociatedObjects;
newAssociatedObjects = [];
}
// 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 +543,16 @@ module.exports = (function() { ...@@ -536,16 +543,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 +570,13 @@ module.exports = (function() { ...@@ -563,14 +570,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 +670,18 @@ module.exports = (function() { ...@@ -664,19 +670,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);
...@@ -706,62 +711,10 @@ module.exports = (function() { ...@@ -706,62 +711,10 @@ module.exports = (function() {
} }
}; };
obj[this.accessors.remove] = function(oldAssociatedObject, options) { obj[this.accessors.removeMultiple] = obj[this.accessors.remove] = function(oldAssociatedObject, options) {
var instance = this; options = options || {};
return instance[association.accessors.get]({}, options).then(function(currentAssociatedObjects) { options.remove = true;
var newAssociations = []; return this[association.accessors.set](oldAssociatedObject, options);
if (!(oldAssociatedObject instanceof association.target.Instance)) {
var tmpInstance = {};
tmpInstance[primaryKeyAttribute] = oldAssociatedObject;
oldAssociatedObject = association.target.build(tmpInstance, {
isNewRecord: false
});
}
currentAssociatedObjects.forEach(function(association) {
if (!Utils._.isEqual(oldAssociatedObject.identifiers, association.identifiers)) {
newAssociations.push(association);
}
});
return instance[association.accessors.set](newAssociations, options);
});
};
obj[this.accessors.removeMultiple] = function(oldAssociatedObjects, options) {
var instance = this;
return instance[association.accessors.get]({}, options).then(function(currentAssociatedObjects) {
var newAssociations = [];
// Ensure the oldAssociatedObjects array is an array of target instances
oldAssociatedObjects = oldAssociatedObjects.map(function(oldAssociatedObject) {
if (!(oldAssociatedObject instanceof association.target.Instance)) {
var tmpInstance = {};
tmpInstance[primaryKeyAttribute] = oldAssociatedObject;
oldAssociatedObject = association.target.build(tmpInstance, {
isNewRecord: false
});
}
return oldAssociatedObject;
});
currentAssociatedObjects.forEach(function(association) {
// Determine is this is an association we want to remove
var obj = Utils._.find(oldAssociatedObjects, function(oldAssociatedObject) {
return Utils._.isEqual(oldAssociatedObject.identifiers, association.identifiers);
});
// This is not an association we want to remove. Add it back
// to the set of associations we will associate our instance with
if (!obj) {
newAssociations.push(association);
}
});
return instance[association.accessors.set](newAssociations, options);
});
}; };
return this; return this;
......
...@@ -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 });
}); });
}); });
} }
......
...@@ -265,7 +265,7 @@ module.exports = (function() { ...@@ -265,7 +265,7 @@ module.exports = (function() {
, i , i
, length; , length;
if (typeof key === 'object') { if (typeof key === 'object' && key !== null) {
values = key; values = key;
options = value || {}; options = value || {};
......
...@@ -409,7 +409,7 @@ module.exports = (function() { ...@@ -409,7 +409,7 @@ module.exports = (function() {
var self = this var self = this
, attributes = this.tableAttributes; , attributes = this.tableAttributes;
return Promise.resolve().then(function () { return Promise.try(function () {
if (options.force) { if (options.force) {
return self.drop(options); return self.drop(options);
} }
...@@ -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 : {}) || {}; // <-- 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...
......
'use strict'; 'use strict';
var Utils = require(__dirname + '/utils'); var Utils = require(__dirname + '/utils')
, deprecatedSeen = {}
, deprecated = function(message) {
if (deprecatedSeen[message]) return;
console.warn(message);
deprecatedSeen[message] = true;
};
module.exports = (function() { module.exports = (function() {
/** /**
...@@ -12,6 +18,8 @@ module.exports = (function() { ...@@ -12,6 +18,8 @@ module.exports = (function() {
var QueryChainer = function(emitters) { var QueryChainer = function(emitters) {
var self = this; var self = this;
deprecated('The query chainer is deprecated, and due for removal in v. 2.2. Please use promises (http://sequelize.readthedocs.org/en/latest/api/promise/) instead!');
this.finishedEmits = 0; this.finishedEmits = 0;
this.emitters = []; this.emitters = [];
this.serials = []; this.serials = [];
......
...@@ -184,7 +184,6 @@ module.exports = (function() { ...@@ -184,7 +184,6 @@ module.exports = (function() {
var Dialect = require('./dialects/' + this.getDialect()); var Dialect = require('./dialects/' + this.getDialect());
this.dialect = new Dialect(this); this.dialect = new Dialect(this);
} catch (err) { } catch (err) {
console.log(err.stack);
throw new Error('The dialect ' + this.getDialect() + ' is not supported. ('+err+')'); throw new Error('The dialect ' + this.getDialect() + ' is not supported. ('+err+')');
} }
...@@ -668,19 +667,17 @@ module.exports = (function() { ...@@ -668,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 };
} }
...@@ -790,7 +787,7 @@ module.exports = (function() { ...@@ -790,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);
}; };
/** /**
...@@ -811,10 +808,12 @@ module.exports = (function() { ...@@ -811,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);
}; };
/** /**
...@@ -822,10 +821,12 @@ module.exports = (function() { ...@@ -822,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);
}; };
/** /**
...@@ -834,10 +835,12 @@ module.exports = (function() { ...@@ -834,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);
}; };
/** /**
...@@ -845,10 +848,12 @@ module.exports = (function() { ...@@ -845,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);
}; };
/** /**
...@@ -904,6 +909,7 @@ module.exports = (function() { ...@@ -904,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) {
...@@ -929,13 +935,13 @@ module.exports = (function() { ...@@ -929,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;
......
...@@ -31,14 +31,14 @@ SqlString.escapeId = function(val, forbidQualified) { ...@@ -31,14 +31,14 @@ SqlString.escapeId = function(val, forbidQualified) {
}; };
SqlString.escape = function(val, stringifyObjects, timeZone, dialect, field) { SqlString.escape = function(val, stringifyObjects, timeZone, dialect, field) {
if (arguments.length === 1 && typeof arguments[0] === 'object') { if (arguments.length === 1 && typeof val === 'object' && val !== null) {
val = val.val || val.value || null; val = val.val || val.value || null;
stringifyObjects = val.stringifyObjects || val.objects || undefined; stringifyObjects = val.stringifyObjects || val.objects || undefined;
timeZone = val.timeZone || val.zone || null; timeZone = val.timeZone || val.zone || null;
dialect = val.dialect || null; dialect = val.dialect || null;
field = val.field || null; field = val.field || null;
} }
else if (arguments.length < 3 && typeof arguments[1] === 'object') { else if (arguments.length === 2 && typeof stringifyObjects === 'object' && stringifyObjects !== null) {
timeZone = stringifyObjects.timeZone || stringifyObjects.zone || null; timeZone = stringifyObjects.timeZone || stringifyObjects.zone || null;
dialect = stringifyObjects.dialect || null; dialect = stringifyObjects.dialect || null;
field = stringifyObjects.field || null; field = stringifyObjects.field || null;
...@@ -73,7 +73,7 @@ SqlString.escape = function(val, stringifyObjects, timeZone, dialect, field) { ...@@ -73,7 +73,7 @@ SqlString.escape = function(val, stringifyObjects, timeZone, dialect, field) {
return SqlString.arrayToList(val, timeZone, dialect, field); return SqlString.arrayToList(val, timeZone, dialect, field);
} }
if (typeof val === 'object') { if (typeof val === 'object' && val !== null) {
if (stringifyObjects) { if (stringifyObjects) {
val = val.toString(); val = val.toString();
} else { } else {
......
...@@ -130,7 +130,7 @@ var Utils = module.exports = { ...@@ -130,7 +130,7 @@ var Utils = module.exports = {
if (merge === true && !!scope.where && !!self.scopeObj.where) { if (merge === true && !!scope.where && !!self.scopeObj.where) {
var scopeKeys = Object.keys(scope.where); var scopeKeys = Object.keys(scope.where);
self.scopeObj.where = self.scopeObj.where.map(function(scopeObj) { self.scopeObj.where = self.scopeObj.where.map(function(scopeObj) {
if (!Array.isArray(scopeObj) && typeof scopeObj === 'object') { if (!Array.isArray(scopeObj) && typeof scopeObj === 'object' && scopeObj !== null) {
return lodash.omit.apply(undefined, [scopeObj].concat(scopeKeys)); return lodash.omit.apply(undefined, [scopeObj].concat(scopeKeys));
} else { } else {
return scopeObj; return scopeObj;
...@@ -270,7 +270,7 @@ var Utils = module.exports = { ...@@ -270,7 +270,7 @@ var Utils = module.exports = {
_where._.bindings = _where._.bindings.concat(values); _where._.bindings = _where._.bindings.concat(values);
} }
} }
else if (typeof where === 'object') { else if (typeof where === 'object' && where !== null) {
// First iteration is trying to compress IN and NOT IN as much as possible... // First iteration is trying to compress IN and NOT IN as much as possible...
// .. reason being is that WHERE username IN (?) AND username IN (?) != WHERE username IN (?,?) // .. reason being is that WHERE username IN (?) AND username IN (?) != WHERE username IN (?,?)
Object.keys(where).forEach(function(i) { Object.keys(where).forEach(function(i) {
......
...@@ -108,6 +108,7 @@ describe(Support.getTestDialectTeaser('Self'), function() { ...@@ -108,6 +108,7 @@ describe(Support.getTestDialectTeaser('Self'), function() {
expect(foreignIdentifiers).to.have.members(['preexisting_parent', 'preexisting_child']); expect(foreignIdentifiers).to.have.members(['preexisting_parent', 'preexisting_child']);
expect(rawAttributes).to.have.members(['preexisting_parent', 'preexisting_child']); expect(rawAttributes).to.have.members(['preexisting_parent', 'preexisting_child']);
var count = 0;
return this.sequelize.sync({ force: true }).bind(this).then(function() { return this.sequelize.sync({ force: true }).bind(this).then(function() {
return Promise.all([ return Promise.all([
Person.create({ name: 'Mary' }), Person.create({ name: 'Mary' }),
...@@ -118,26 +119,36 @@ describe(Support.getTestDialectTeaser('Self'), function() { ...@@ -118,26 +119,36 @@ describe(Support.getTestDialectTeaser('Self'), function() {
this.mary = mary; this.mary = mary;
this.chris = chris; this.chris = chris;
this.john = john; this.john = john;
return mary.setParents([john]).on('sql', function(sql) { return mary.setParents([john], {
if (sql.match(/INSERT/)) { logging: function(sql) {
expect(sql).to.have.string('preexisting_child'); if (sql.match(/INSERT/)) {
expect(sql).to.have.string('preexisting_parent'); count++;
expect(sql).to.have.string('preexisting_child');
expect(sql).to.have.string('preexisting_parent');
}
} }
}); });
}).then(function() { }).then(function() {
return this.mary.addParent(this.chris).on('sql', function(sql) { return this.mary.addParent(this.chris, {
if (sql.match(/INSERT/)) { logging: function(sql) {
expect(sql).to.have.string('preexisting_child'); if (sql.match(/INSERT/)) {
expect(sql).to.have.string('preexisting_parent'); count++;
expect(sql).to.have.string('preexisting_child');
expect(sql).to.have.string('preexisting_parent');
}
} }
}); });
}).then(function() { }).then(function() {
return this.john.getChildren().on('sql', function(sql) { return this.john.getChildren(undefined, {
var whereClause = sql.split('FROM')[1]; // look only in the whereClause logging: function(sql) {
expect(whereClause).to.have.string('preexisting_child'); count++;
expect(whereClause).to.have.string('preexisting_parent'); var whereClause = sql.split('FROM')[1]; // look only in the whereClause
expect(whereClause).to.have.string('preexisting_child');
expect(whereClause).to.have.string('preexisting_parent');
}
}); });
}).then(function(children) { }).then(function(children) {
expect(count).to.be.equal(3);
expect(_.map(children, 'id')).to.have.members([this.mary.id]); expect(_.map(children, 'id')).to.have.members([this.mary.id]);
}); });
}); });
......
...@@ -55,8 +55,8 @@ if (dialect.match(/^postgres/)) { ...@@ -55,8 +55,8 @@ if (dialect.match(/^postgres/)) {
this.users = null; this.users = null;
this.tasks = null; this.tasks = null;
this.User.hasMany(this.Task, {as: 'Tasks', through: 'usertasks'}); this.User.belongsToMany(this.Task, {as: 'Tasks', through: 'usertasks'});
this.Task.hasMany(this.User, {as: 'Users', through: 'usertasks'}); this.Task.belongsToMany(this.User, {as: 'Users', through: 'usertasks'});
var users = [] var users = []
, tasks = []; , tasks = [];
......
...@@ -39,8 +39,10 @@ if (dialect.match(/^postgres/)) { ...@@ -39,8 +39,10 @@ if (dialect.match(/^postgres/)) {
}); });
it('should be able to search within an array', function() { it('should be able to search within an array', function() {
return this.User.findAll({where: {email: ['hello', 'world']}, attributes: ['id','username','email','settings','document','phones','emergency_contact','friends']}).on('sql', function(sql) { return this.User.findAll({where: {email: ['hello', 'world']}, attributes: ['id','username','email','settings','document','phones','emergency_contact','friends']}, {
expect(sql).to.equal('SELECT "id", "username", "email", "settings", "document", "phones", "emergency_contact", "friends" FROM "Users" AS "User" WHERE "User"."email" = ARRAY[\'hello\',\'world\']::TEXT[];'); logging: function (sql) {
expect(sql).to.equal('Executing (default): SELECT "id", "username", "email", "settings", "document", "phones", "emergency_contact", "friends" FROM "Users" AS "User" WHERE "User"."email" = ARRAY[\'hello\',\'world\']::TEXT[];');
}
}); });
}); });
...@@ -95,10 +97,11 @@ if (dialect.match(/^postgres/)) { ...@@ -95,10 +97,11 @@ if (dialect.match(/^postgres/)) {
username: 'bob', username: 'bob',
emergency_contact: { name: 'joe', phones: [1337, 42] } emergency_contact: { name: 'joe', phones: [1337, 42] }
}, { }, {
fields: ['id', 'username', 'document', 'emergency_contact'] fields: ['id', 'username', 'document', 'emergency_contact'],
}).on('sql', function(sql) { logging: function(sql) {
var expected = '\'{"name":"joe","phones":[1337,42]}\''; var expected = '\'{"name":"joe","phones":[1337,42]}\'';
expect(sql.indexOf(expected)).not.to.equal(-1); expect(sql.indexOf(expected)).not.to.equal(-1);
}
}); });
}); });
...@@ -294,9 +297,11 @@ if (dialect.match(/^postgres/)) { ...@@ -294,9 +297,11 @@ if (dialect.match(/^postgres/)) {
username: 'bob', username: 'bob',
email: ['myemail@email.com'], email: ['myemail@email.com'],
settings: {mailing: false, push: 'facebook', frequency: 3} settings: {mailing: false, push: 'facebook', frequency: 3}
}).on('sql', function(sql) { }, {
var expected = '\'"mailing"=>"false","push"=>"facebook","frequency"=>"3"\',\'"default"=>"\'\'value\'\'"\''; logging: function (sql) {
expect(sql.indexOf(expected)).not.to.equal(-1); var expected = '\'"mailing"=>"false","push"=>"facebook","frequency"=>"3"\',\'"default"=>"\'\'value\'\'"\'';
expect(sql.indexOf(expected)).not.to.equal(-1);
}
}); });
}); });
...@@ -375,25 +380,25 @@ if (dialect.match(/^postgres/)) { ...@@ -375,25 +380,25 @@ if (dialect.match(/^postgres/)) {
mood: DataTypes.ENUM('neutral', 'happy', 'sad', 'ecstatic', 'meh', 'joyful') mood: DataTypes.ENUM('neutral', 'happy', 'sad', 'ecstatic', 'meh', 'joyful')
}); });
return User.sync().then(function() { return User.sync({
expect(User.rawAttributes.mood.values).to.deep.equal(['neutral', 'happy', 'sad', 'ecstatic', 'meh', 'joyful']); logging: function (sql) {
count++; if (sql.indexOf('neutral') > -1) {
}).on('sql', function(sql) { expect(sql.indexOf("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'neutral' BEFORE 'happy'")).to.not.be.equal(-1);
if (sql.indexOf('neutral') > -1) { count++;
expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'neutral' BEFORE 'happy'"); }
count++; else if (sql.indexOf('ecstatic') > -1) {
} expect(sql.indexOf("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'ecstatic' BEFORE 'meh'")).to.not.be.equal(-1);
else if (sql.indexOf('ecstatic') > -1) { count++;
expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'ecstatic' BEFORE 'meh'"); }
count++; else if (sql.indexOf('joyful') > -1) {
} expect(sql.indexOf("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'joyful' AFTER 'meh'")).to.not.be.equal(-1);
else if (sql.indexOf('joyful') > -1) { count++;
expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'joyful' AFTER 'meh'"); }
count++;
} }
}).then(function() {
expect(User.rawAttributes.mood.values).to.deep.equal(['neutral', 'happy', 'sad', 'ecstatic', 'meh', 'joyful']);
expect(count).to.equal(3);
}); });
}).then(function() {
expect(count).to.equal(4);
}); });
}); });
}); });
...@@ -475,8 +480,10 @@ if (dialect.match(/^postgres/)) { ...@@ -475,8 +480,10 @@ if (dialect.match(/^postgres/)) {
it('should use postgres "TIMESTAMP WITH TIME ZONE" instead of "DATETIME"', function() { it('should use postgres "TIMESTAMP WITH TIME ZONE" instead of "DATETIME"', function() {
return this.User.create({ return this.User.create({
dates: [] dates: []
}).on('sql', function(sql) { }, {
expect(sql.indexOf('TIMESTAMP WITH TIME ZONE')).to.be.greaterThan(0); logging: function(sql) {
expect(sql.indexOf('TIMESTAMP WITH TIME ZONE')).to.be.greaterThan(0);
}
}); });
}); });
}); });
......
...@@ -1707,7 +1707,7 @@ describe(Support.getTestDialectTeaser('Instance'), function() { ...@@ -1707,7 +1707,7 @@ describe(Support.getTestDialectTeaser('Instance'), function() {
return User.sync().then(function() { return User.sync().then(function() {
var user = User.build({ username: 'foo' }); var user = User.build({ username: 'foo' });
expect(user.values).to.deep.equal({ username: 'foo', id: null }); expect(user.get({ plain: true })).to.deep.equal({ username: 'foo', id: null });
}); });
}); });
}); });
...@@ -1767,9 +1767,11 @@ describe(Support.getTestDialectTeaser('Instance'), function() { ...@@ -1767,9 +1767,11 @@ describe(Support.getTestDialectTeaser('Instance'), function() {
return UserDelete.create({name: 'hallo', bio: 'welt'}).then(function(u) { return UserDelete.create({name: 'hallo', bio: 'welt'}).then(function(u) {
return UserDelete.findAll().then(function(users) { return UserDelete.findAll().then(function(users) {
expect(users.length).to.equal(1); expect(users.length).to.equal(1);
return u.destroy().on('sql', function(sql) { return u.destroy({
expect(sql).to.exist; logging: function (sql) {
expect(sql.toUpperCase().indexOf('DELETE')).to.be.above(-1); expect(sql).to.exist;
expect(sql.toUpperCase().indexOf('DELETE')).to.be.above(-1);
}
}); });
}); });
}); });
......
...@@ -71,18 +71,26 @@ describe(Support.getTestDialectTeaser('Model'), function() { ...@@ -71,18 +71,26 @@ describe(Support.getTestDialectTeaser('Model'), function() {
it('should be ignored in find, findAll and includes', function() { it('should be ignored in find, findAll and includes', function() {
return Promise.all([ return Promise.all([
this.User.find().on('sql', this.sqlAssert), this.User.find(null, {
this.User.findAll().on('sql', this.sqlAssert), logging: this.sqlAssert
}),
this.User.findAll(null, {
logging: this.sqlAssert
}),
this.Task.findAll({ this.Task.findAll({
include: [ include: [
this.User this.User
] ]
}).on('sql', this.sqlAssert), }, {
logging: this.sqlAssert
}),
this.Project.findAll({ this.Project.findAll({
include: [ include: [
this.User this.User
] ]
}).on('sql', this.sqlAssert) }, {
logging: this.sqlAssert
})
]); ]);
}); });
...@@ -132,7 +140,9 @@ describe(Support.getTestDialectTeaser('Model'), function() { ...@@ -132,7 +140,9 @@ describe(Support.getTestDialectTeaser('Model'), function() {
var self = this; var self = this;
return this.User.bulkCreate([{ return this.User.bulkCreate([{
field1: 'something' field1: 'something'
}]).on('sql', this.sqlAssert).then(function() { }], {
logging: this.sqlAssert
}).then(function() {
return self.User.findAll(); return self.User.findAll();
}).then(function(users) { }).then(function(users) {
expect(users[0].storage).to.equal('something'); expect(users[0].storage).to.equal('something');
......
...@@ -675,11 +675,12 @@ describe(Support.getTestDialectTeaser('Model'), function() { ...@@ -675,11 +675,12 @@ describe(Support.getTestDialectTeaser('Model'), function() {
return this.User.create({ return this.User.create({
intVal: this.sequelize.cast('1', type) intVal: this.sequelize.cast('1', type)
}).on('sql', function(sql) { }, {
expect(sql).to.match(new RegExp("CAST\\('1' AS " + type.toUpperCase() + '\\)')); logging: function(sql) {
match = true; expect(sql).to.match(new RegExp("CAST\\('1' AS " + type.toUpperCase() + '\\)'));
}) match = true;
.then(function(user) { }
}).then(function(user) {
return self.User.find(user.id).then(function(user) { return self.User.find(user.id).then(function(user) {
expect(user.intVal).to.equal(1); expect(user.intVal).to.equal(1);
expect(match).to.equal(true); expect(match).to.equal(true);
...@@ -698,14 +699,15 @@ describe(Support.getTestDialectTeaser('Model'), function() { ...@@ -698,14 +699,15 @@ describe(Support.getTestDialectTeaser('Model'), function() {
return this.User.create({ return this.User.create({
intVal: type intVal: type
}).on('sql', function(sql) { }, {
if (Support.dialectIsMySQL()) { logging: function(sql) {
expect(sql).to.contain('CAST(CAST(1-2 AS UNSIGNED) AS SIGNED)'); if (Support.dialectIsMySQL()) {
} else { expect(sql).to.contain('CAST(CAST(1-2 AS UNSIGNED) AS SIGNED)');
expect(sql).to.contain('CAST(CAST(1-2 AS INTEGER) AS INTEGER)'); } else {
expect(sql).to.contain('CAST(CAST(1-2 AS INTEGER) AS INTEGER)');
}
match = true;
} }
match = true;
}).then(function(user) { }).then(function(user) {
return self.User.find(user.id).then(function(user) { return self.User.find(user.id).then(function(user) {
expect(user.intVal).to.equal(-1); expect(user.intVal).to.equal(-1);
...@@ -811,11 +813,17 @@ describe(Support.getTestDialectTeaser('Model'), function() { ...@@ -811,11 +813,17 @@ describe(Support.getTestDialectTeaser('Model'), function() {
mystr: { type: Sequelize.ARRAY(Sequelize.STRING) } mystr: { type: Sequelize.ARRAY(Sequelize.STRING) }
}); });
var test = false;
return User.sync({force: true}).then(function() { return User.sync({force: true}).then(function() {
return User.create({myvals: [], mystr: []}).on('sql', function(sql) { return User.create({myvals: [], mystr: []}, {
expect(sql.indexOf('ARRAY[]::INTEGER[]')).to.be.above(-1); logging: function(sql) {
expect(sql.indexOf('ARRAY[]::VARCHAR[]')).to.be.above(-1); test = true;
expect(sql.indexOf('ARRAY[]::INTEGER[]')).to.be.above(-1);
expect(sql.indexOf('ARRAY[]::VARCHAR[]')).to.be.above(-1);
}
}); });
}).then(function() {
expect(test).to.be.true;
}); });
}); });
...@@ -829,16 +837,22 @@ describe(Support.getTestDialectTeaser('Model'), function() { ...@@ -829,16 +837,22 @@ describe(Support.getTestDialectTeaser('Model'), function() {
myvals: { type: Sequelize.ARRAY(Sequelize.INTEGER) }, myvals: { type: Sequelize.ARRAY(Sequelize.INTEGER) },
mystr: { type: Sequelize.ARRAY(Sequelize.STRING) } mystr: { type: Sequelize.ARRAY(Sequelize.STRING) }
}); });
var test = false;
return User.sync({force: true}).then(function() { return User.sync({force: true}).then(function() {
return User.create({myvals: [1, 2, 3, 4], mystr: ['One', 'Two', 'Three', 'Four']}).then(function(user) { return User.create({myvals: [1, 2, 3, 4], mystr: ['One', 'Two', 'Three', 'Four']}).then(function(user) {
user.myvals = []; user.myvals = [];
user.mystr = []; user.mystr = [];
return user.save().on('sql', function(sql) { return user.save(undefined, {
expect(sql.indexOf('ARRAY[]::INTEGER[]')).to.be.above(-1); logging: function(sql) {
expect(sql.indexOf('ARRAY[]::VARCHAR[]')).to.be.above(-1); test = true;
expect(sql.indexOf('ARRAY[]::INTEGER[]')).to.be.above(-1);
expect(sql.indexOf('ARRAY[]::VARCHAR[]')).to.be.above(-1);
}
}); });
}); });
}).then(function() {
expect(test).to.be.true;
}); });
}); });
...@@ -986,13 +1000,18 @@ describe(Support.getTestDialectTeaser('Model'), function() { ...@@ -986,13 +1000,18 @@ describe(Support.getTestDialectTeaser('Model'), function() {
smth: {type: Sequelize.STRING, allowNull: false} smth: {type: Sequelize.STRING, allowNull: false}
}); });
var test = false;
return User.sync({ force: true }).then(function() { return User.sync({ force: true }).then(function() {
return User return User
.create({ name: 'Fluffy Bunny', smth: 'else' }) .create({ name: 'Fluffy Bunny', smth: 'else' }, {
.on('sql', function(sql) { logging: function(sql) {
expect(sql).to.exist; expect(sql).to.exist;
expect(sql.toUpperCase().indexOf('INSERT')).to.be.above(-1); test = true;
expect(sql.toUpperCase().indexOf('INSERT')).to.be.above(-1);
}
}); });
}).then(function() {
expect(test).to.be.true;
}); });
}); });
...@@ -1601,9 +1620,7 @@ describe(Support.getTestDialectTeaser('Model'), function() { ...@@ -1601,9 +1620,7 @@ describe(Support.getTestDialectTeaser('Model'), function() {
data.push({ uniqueName: 'Michael', secretValue: '26' }); data.push({ uniqueName: 'Michael', secretValue: '26' });
return self.User.bulkCreate(data, { fields: ['uniqueName', 'secretValue'], ignoreDuplicates: true }).catch(function(err) { return self.User.bulkCreate(data, { fields: ['uniqueName', 'secretValue'], ignoreDuplicates: true }).catch(function(err) {
expect(err).to.exist;
if (dialect === 'mssql') { if (dialect === 'mssql') {
console.log(err.message);
expect(err.message).to.match(/mssql does not support the \'ignoreDuplicates\' option./); expect(err.message).to.match(/mssql does not support the \'ignoreDuplicates\' option./);
} else { } else {
expect(err.message).to.match(/postgres does not support the \'ignoreDuplicates\' option./); expect(err.message).to.match(/postgres does not support the \'ignoreDuplicates\' option./);
......
...@@ -117,10 +117,16 @@ describe(Support.getTestDialectTeaser('Model'), function() { ...@@ -117,10 +117,16 @@ describe(Support.getTestDialectTeaser('Model'), function() {
}); });
it('treats questionmarks in an array', function() { it('treats questionmarks in an array', function() {
var test = false;
return this.UserPrimary.find({ return this.UserPrimary.find({
where: ['specialkey = ?', 'awesome'] where: ['specialkey = ?', 'awesome']
}).on('sql', function(sql) { }, {
expect(sql).to.contain("WHERE specialkey = 'awesome'"); logging: function(sql) {
test = true;
expect(sql).to.contain("WHERE specialkey = 'awesome'");
}
}).then(function() {
expect(test).to.be.true;
}); });
}); });
...@@ -190,9 +196,15 @@ describe(Support.getTestDialectTeaser('Model'), function() { ...@@ -190,9 +196,15 @@ describe(Support.getTestDialectTeaser('Model'), function() {
}); });
it('allows sql logging', function() { it('allows sql logging', function() {
return this.User.find({ where: { username: 'foo' } }).on('sql', function(sql) { var test = false;
expect(sql).to.exist; return this.User.find({ where: { username: 'foo' } }, {
expect(sql.toUpperCase().indexOf('SELECT')).to.be.above(-1); logging: function(sql) {
test = true;
expect(sql).to.exist;
expect(sql.toUpperCase().indexOf('SELECT')).to.be.above(-1);
}
}).then(function() {
expect(test).to.be.true;
}); });
}); });
...@@ -257,16 +269,17 @@ describe(Support.getTestDialectTeaser('Model'), function() { ...@@ -257,16 +269,17 @@ describe(Support.getTestDialectTeaser('Model'), function() {
return this.User.bulkCreate([{username: 'jack'}, {username: 'jack'}]).then(function() { return this.User.bulkCreate([{username: 'jack'}, {username: 'jack'}]).then(function() {
return self.sequelize.Promise.map(permutations, function(perm) { return self.sequelize.Promise.map(permutations, function(perm) {
return self.User.find(perm).then(function(user) { return self.User.find(perm, {
logging: function(s) {
expect(s.indexOf(0)).not.to.equal(-1);
count++;
}
}).then(function(user) {
expect(user).to.be.null; expect(user).to.be.null;
count++;
}).on('sql', function(s) {
expect(s.indexOf(0)).not.to.equal(-1);
count++;
}); });
}); });
}).then(function() { }).then(function() {
expect(count).to.be.equal(2 * permutations.length); expect(count).to.be.equal(permutations.length);
}); });
}); });
......
...@@ -397,22 +397,6 @@ describe(Support.getTestDialectTeaser('Promise'), function() { ...@@ -397,22 +397,6 @@ describe(Support.getTestDialectTeaser('Promise'), function() {
}); });
}); });
it('should still work with .success() when emitting', function(done) {
var spy = sinon.spy()
, promise = new SequelizePromise(function(resolve, reject) {
// no-op
});
promise.success(spy);
promise.then(function() {
expect(spy.calledOnce).to.be.true;
expect(spy.firstCall.args).to.deep.equal(['yay']);
done();
});
promise.emit('success', 'yay');
});
it('should still work with .done() when rejecting', function(done) { it('should still work with .done() when rejecting', function(done) {
var spy = sinon.spy() var spy = sinon.spy()
, promise = new SequelizePromise(function(resolve, reject) { , promise = new SequelizePromise(function(resolve, reject) {
...@@ -440,110 +424,5 @@ describe(Support.getTestDialectTeaser('Promise'), function() { ...@@ -440,110 +424,5 @@ describe(Support.getTestDialectTeaser('Promise'), function() {
done(); done();
}); });
}); });
it('should still work with .on(\'error\') when throwing', function(done) {
var spy = sinon.spy()
, promise = new SequelizePromise(function(resolve, reject) {
throw new Error('noway');
});
promise.on('error', spy);
promise.catch(function() {
expect(spy.calledOnce).to.be.true;
expect(spy.firstCall.args[0]).to.be.an.instanceof(Error);
done();
});
});
it('should still work with .error() when emitting', function(done) {
var spy = sinon.spy()
, promise = new SequelizePromise(function(resolve, reject) {
// no-op
});
promise.on('error', spy);
promise.catch(function() {
expect(spy.calledOnce).to.be.true;
expect(spy.firstCall.args[0]).to.be.an.instanceof(Error);
done();
});
promise.emit('error', new Error('noway'));
});
it('should still support sql events', function() {
var spy = sinon.spy()
, promise = new SequelizePromise(function(resolve, reject) {
resolve('yay');
});
promise.on('sql', spy);
promise.emit('sql', 'SQL STATEMENT 1');
promise.emit('sql', 'SQL STATEMENT 2');
return promise.then(function() {
expect(spy.calledTwice).to.be.true;
});
});
describe('proxy', function() {
it('should correctly work with success listeners', function(done) {
var emitter = new SequelizePromise(function() {})
, proxy = new SequelizePromise(function() {})
, success = sinon.spy();
emitter.success(success);
proxy.success(function() {
process.nextTick(function() {
expect(success.called).to.be.true;
done();
});
});
proxy.proxy(emitter);
proxy.emit('success');
});
it('should correctly work with complete/done listeners', function(done) {
var promise = new SequelizePromise(function() {})
, proxy = new SequelizePromise(function() {})
, complete = sinon.spy();
promise.complete(complete);
proxy.complete(function() {
process.nextTick(function() {
expect(complete.called).to.be.true;
done();
});
});
proxy.proxy(promise);
proxy.emit('success');
});
});
describe('when emitting an error event with an array of errors', function() {
describe('if an error handler is given', function() {
it('should return the whole array', function(done) {
var emitter = new SequelizePromise(function() {});
var errors = [
[
new Error('First error'),
new Error('Second error')
], [
new Error('Third error')
]
];
emitter.error(function(err) {
expect(err).to.equal(errors);
done();
});
emitter.emit('error', errors);
});
});
});
}); });
}); });
...@@ -5,11 +5,16 @@ var chai = require('chai') ...@@ -5,11 +5,16 @@ var chai = require('chai')
, expect = chai.expect , expect = chai.expect
, Support = require(__dirname + '/support') , Support = require(__dirname + '/support')
, QueryChainer = require('../../lib/query-chainer') , QueryChainer = require('../../lib/query-chainer')
, CustomEventEmitter = require('../../lib/emitters/custom-event-emitter'); , CustomEventEmitter;
chai.config.includeStack = true; chai.config.includeStack = true;
describe(Support.getTestDialectTeaser('QueryChainer'), function() { describe(Support.getTestDialectTeaser('QueryChainer'), function() {
before(function() {
CustomEventEmitter = require('../../lib/emitters/custom-event-emitter');
});
beforeEach(function() { beforeEach(function() {
this.queryChainer = new QueryChainer(); this.queryChainer = new QueryChainer();
}); });
...@@ -40,7 +45,7 @@ describe(Support.getTestDialectTeaser('QueryChainer'), function() { ...@@ -40,7 +45,7 @@ describe(Support.getTestDialectTeaser('QueryChainer'), function() {
expect(true).to.be.true; expect(true).to.be.true;
done(); done();
}).error(function(err) { }).error(function(err) {
console.log(err); done(err);
}); });
emitter1.run(); emitter1.run();
......
...@@ -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]);
......
...@@ -113,7 +113,6 @@ describe(Support.getTestDialectTeaser('Sequelize'), function() { ...@@ -113,7 +113,6 @@ describe(Support.getTestDialectTeaser('Sequelize'), function() {
.sequelizeWithInvalidConnection .sequelizeWithInvalidConnection
.authenticate() .authenticate()
.catch(function(err) { .catch(function(err) {
console.log(err.message);
expect( expect(
err.message.match(/connect ECONNREFUSED/) || err.message.match(/connect ECONNREFUSED/) ||
err.message.match(/invalid port number/) || err.message.match(/invalid port number/) ||
...@@ -397,7 +396,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), function() { ...@@ -397,7 +396,7 @@ describe(Support.getTestDialectTeaser('Sequelize'), function() {
if (Support.getTestDialect() === 'postgres') { if (Support.getTestDialect() === 'postgres') {
it('replaces named parameters with the passed object and ignores casts', function() { it('replaces named parameters with the passed object and ignores casts', function() {
return expect(this.sequelize.query('select :one as foo, :two as bar, \'1000\'::integer as baz', null, { raw: true }, { one: 1, two: 2 }).get(0)) return expect(this.sequelize.query('select :one as foo, :two as bar, \'1000\'::integer as baz', null, { raw: true, replacements: { one: 1, two: 2 } }).get(0))
.to.eventually.deep.equal([{ foo: 1, bar: 2, baz: 1000 }]); .to.eventually.deep.equal([{ foo: 1, bar: 2, baz: 1000 }]);
}); });
......
...@@ -20,8 +20,6 @@ describe(Support.getTestDialectTeaser('Vectors'), function() { ...@@ -20,8 +20,6 @@ describe(Support.getTestDialectTeaser('Vectors'), function() {
return Student.sync({force: true}).then(function () { return Student.sync({force: true}).then(function () {
return Student.create({ return Student.create({
name: 'Robert\\\'); DROP TABLE "students"; --' name: 'Robert\\\'); DROP TABLE "students"; --'
}, {
logging: console.log
}).then(function(result) { }).then(function(result) {
expect(result.get('name')).to.equal('Robert\\\'); DROP TABLE "students"; --'); expect(result.get('name')).to.equal('Robert\\\'); DROP TABLE "students"; --');
return Student.findAll(); return Student.findAll();
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!