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

You need to sign in or sign up before continuing.
Commit 33ff3ad5 by Ruben Bridgewater

Remove unnecessary indentation

1 parent 073f1777
var Association = function() { var Association = function () {};
};
module.exports = Association; module.exports = Association;
\ No newline at end of file
...@@ -7,8 +7,7 @@ var Utils = require('./../utils') ...@@ -7,8 +7,7 @@ var Utils = require('./../utils')
, CounterCache = require('../plugins/counter-cache') , CounterCache = require('../plugins/counter-cache')
, util = require('util'); , util = require('util');
module.exports = (function() { var BelongsToMany = function(source, target, options) {
var BelongsToMany = function(source, target, options) {
Association.call(this); Association.call(this);
this.associationType = 'BelongsToMany'; this.associationType = 'BelongsToMany';
...@@ -176,13 +175,13 @@ module.exports = (function() { ...@@ -176,13 +175,13 @@ module.exports = (function() {
if (this.options.counterCache) { if (this.options.counterCache) {
new CounterCache(this, this.options.counterCache !== true ? this.options.counterCache : {}); new CounterCache(this, this.options.counterCache !== true ? this.options.counterCache : {});
} }
}; };
util.inherits(BelongsToMany, Association); util.inherits(BelongsToMany, Association);
// the id is in the target table // the id is in the target table
// or in an extra table which connects two tables // or in an extra table which connects two tables
BelongsToMany.prototype.injectAttributes = function() { BelongsToMany.prototype.injectAttributes = function() {
var self = this; var self = this;
this.identifier = this.foreignKey; this.identifier = this.foreignKey;
...@@ -263,9 +262,9 @@ module.exports = (function() { ...@@ -263,9 +262,9 @@ module.exports = (function() {
Helpers.checkNamingCollision(this); Helpers.checkNamingCollision(this);
return this; return this;
}; };
BelongsToMany.prototype.injectGetter = function(obj) { BelongsToMany.prototype.injectGetter = function(obj) {
var association = this; var association = this;
obj[this.accessors.get] = function(options) { obj[this.accessors.get] = function(options) {
...@@ -364,9 +363,9 @@ module.exports = (function() { ...@@ -364,9 +363,9 @@ module.exports = (function() {
}; };
return this; return this;
}; };
BelongsToMany.prototype.injectSetter = function(obj) { BelongsToMany.prototype.injectSetter = function(obj) {
var association = this var association = this
, primaryKeyAttribute = association.target.primaryKeyAttribute; , primaryKeyAttribute = association.target.primaryKeyAttribute;
...@@ -668,9 +667,9 @@ module.exports = (function() { ...@@ -668,9 +667,9 @@ module.exports = (function() {
}; };
return this; return this;
}; };
BelongsToMany.prototype.injectCreator = function(obj) { BelongsToMany.prototype.injectCreator = function(obj) {
var association = this; var association = this;
obj[this.accessors.create] = function(values, options) { obj[this.accessors.create] = function(values, options) {
...@@ -701,7 +700,6 @@ module.exports = (function() { ...@@ -701,7 +700,6 @@ module.exports = (function() {
}; };
return this; return this;
}; };
return BelongsToMany; module.exports = BelongsToMany;
})();
...@@ -6,8 +6,7 @@ var Utils = require('./../utils') ...@@ -6,8 +6,7 @@ var Utils = require('./../utils')
, Association = require('./base') , Association = require('./base')
, util = require('util'); , util = require('util');
module.exports = (function() { var BelongsTo = function(source, target, options) {
var BelongsTo = function(source, target, options) {
Association.call(this); Association.call(this);
this.associationType = 'BelongsTo'; this.associationType = 'BelongsTo';
...@@ -67,12 +66,12 @@ module.exports = (function() { ...@@ -67,12 +66,12 @@ module.exports = (function() {
set: 'set' + singular, set: 'set' + singular,
create: 'create' + singular create: 'create' + singular
}; };
}; };
util.inherits(BelongsTo, Association); util.inherits(BelongsTo, Association);
// the id is in the source table // the id is in the source table
BelongsTo.prototype.injectAttributes = function() { BelongsTo.prototype.injectAttributes = function() {
var newAttributes = {}; var newAttributes = {};
newAttributes[this.identifier] = Utils._.defaults(this.foreignKeyAttribute, { type: this.options.keyType || this.target.rawAttributes[this.targetIdentifier].type }); newAttributes[this.identifier] = Utils._.defaults(this.foreignKeyAttribute, { type: this.options.keyType || this.target.rawAttributes[this.targetIdentifier].type });
...@@ -90,10 +89,10 @@ module.exports = (function() { ...@@ -90,10 +89,10 @@ module.exports = (function() {
Helpers.checkNamingCollision(this); Helpers.checkNamingCollision(this);
return this; return this;
}; };
// Add getAssociation method to the prototype of the model instance // Add getAssociation method to the prototype of the model instance
BelongsTo.prototype.injectGetter = function(instancePrototype) { BelongsTo.prototype.injectGetter = function(instancePrototype) {
var association = this; var association = this;
instancePrototype[this.accessors.get] = function(options) { instancePrototype[this.accessors.get] = function(options) {
...@@ -124,10 +123,10 @@ module.exports = (function() { ...@@ -124,10 +123,10 @@ module.exports = (function() {
}; };
return this; return this;
}; };
// Add setAssociaton method to the prototype of the model instance // Add setAssociaton method to the prototype of the model instance
BelongsTo.prototype.injectSetter = function(instancePrototype) { BelongsTo.prototype.injectSetter = function(instancePrototype) {
var association = this; var association = this;
instancePrototype[this.accessors.set] = function(associatedInstance, options) { instancePrototype[this.accessors.set] = function(associatedInstance, options) {
...@@ -154,10 +153,10 @@ module.exports = (function() { ...@@ -154,10 +153,10 @@ module.exports = (function() {
}; };
return this; return this;
}; };
// Add createAssociation method to the prototype of the model instance // Add createAssociation method to the prototype of the model instance
BelongsTo.prototype.injectCreator = function(instancePrototype) { BelongsTo.prototype.injectCreator = function(instancePrototype) {
var association = this; var association = this;
instancePrototype[this.accessors.create] = function(values, fieldsOrOptions) { instancePrototype[this.accessors.create] = function(values, fieldsOrOptions) {
...@@ -175,7 +174,6 @@ module.exports = (function() { ...@@ -175,7 +174,6 @@ module.exports = (function() {
}; };
return this; return this;
}; };
return BelongsTo; module.exports = BelongsTo;
})();
...@@ -3,15 +3,14 @@ ...@@ -3,15 +3,14 @@
var Utils = require('./../utils') var Utils = require('./../utils')
, _ = require('lodash'); , _ = require('lodash');
module.exports = (function() { var HasManySingleLinked = function(association, instance) {
var HasManySingleLinked = function(association, instance) {
this.association = association; this.association = association;
this.instance = instance; this.instance = instance;
this.target = this.association.target; this.target = this.association.target;
this.source = this.association.source; this.source = this.association.source;
}; };
HasManySingleLinked.prototype.injectGetter = function(options) { HasManySingleLinked.prototype.injectGetter = function(options) {
var scopeWhere = this.association.scope ? {} : null; var scopeWhere = this.association.scope ? {} : null;
if (this.association.scope) { if (this.association.scope) {
Object.keys(this.association.scope).forEach(function (attribute) { Object.keys(this.association.scope).forEach(function (attribute) {
...@@ -40,9 +39,9 @@ module.exports = (function() { ...@@ -40,9 +39,9 @@ module.exports = (function() {
} }
return model.all(options); return model.all(options);
}; };
HasManySingleLinked.prototype.injectSetter = function(oldAssociations, newAssociations, defaultAttributes) { HasManySingleLinked.prototype.injectSetter = function(oldAssociations, newAssociations, defaultAttributes) {
var self = this var self = this
, primaryKeys , primaryKeys
, primaryKey , primaryKey
...@@ -120,9 +119,9 @@ module.exports = (function() { ...@@ -120,9 +119,9 @@ module.exports = (function() {
} }
return Utils.Promise.all(promises); return Utils.Promise.all(promises);
}; };
HasManySingleLinked.prototype.injectAdder = function(newAssociation, options) { HasManySingleLinked.prototype.injectAdder = function(newAssociation, options) {
newAssociation.set(this.association.identifier, this.instance.get(this.instance.Model.primaryKeyAttribute)); newAssociation.set(this.association.identifier, this.instance.get(this.instance.Model.primaryKeyAttribute));
if (this.association.scope) { if (this.association.scope) {
Object.keys(this.association.scope).forEach(function (attribute) { Object.keys(this.association.scope).forEach(function (attribute) {
...@@ -131,7 +130,6 @@ module.exports = (function() { ...@@ -131,7 +130,6 @@ module.exports = (function() {
} }
return newAssociation.save(options); return newAssociation.save(options);
}; };
return HasManySingleLinked; module.exports = HasManySingleLinked;
})();
...@@ -8,8 +8,7 @@ var Utils = require('./../utils') ...@@ -8,8 +8,7 @@ var Utils = require('./../utils')
, util = require('util') , util = require('util')
, HasManySingleLinked = require('./has-many-single-linked'); , HasManySingleLinked = require('./has-many-single-linked');
module.exports = (function() { var HasMany = function(source, target, options) {
var HasMany = function(source, target, options) {
Association.call(this); Association.call(this);
this.associationType = 'HasMany'; this.associationType = 'HasMany';
...@@ -81,13 +80,13 @@ module.exports = (function() { ...@@ -81,13 +80,13 @@ module.exports = (function() {
if (this.options.counterCache) { if (this.options.counterCache) {
new CounterCache(this, this.options.counterCache !== true ? this.options.counterCache : {}); new CounterCache(this, this.options.counterCache !== true ? this.options.counterCache : {});
} }
}; };
util.inherits(HasMany, Association); util.inherits(HasMany, Association);
// the id is in the target table // the id is in the target table
// or in an extra table which connects two tables // or in an extra table which connects two tables
HasMany.prototype.injectAttributes = function() { HasMany.prototype.injectAttributes = function() {
this.identifier = this.foreignKey || Utils._.camelizeIf( this.identifier = this.foreignKey || Utils._.camelizeIf(
[ [
Utils._.underscoredIf(this.source.options.name.singular, this.source.options.underscored), Utils._.underscoredIf(this.source.options.name.singular, this.source.options.underscored),
...@@ -115,9 +114,9 @@ module.exports = (function() { ...@@ -115,9 +114,9 @@ module.exports = (function() {
Helpers.checkNamingCollision(this); Helpers.checkNamingCollision(this);
return this; return this;
}; };
HasMany.prototype.injectGetter = function(obj) { HasMany.prototype.injectGetter = function(obj) {
var association = this; var association = this;
obj[this.accessors.get] = function(options) { obj[this.accessors.get] = function(options) {
...@@ -188,9 +187,9 @@ module.exports = (function() { ...@@ -188,9 +187,9 @@ module.exports = (function() {
}; };
return this; return this;
}; };
HasMany.prototype.injectSetter = function(obj) { HasMany.prototype.injectSetter = function(obj) {
var association = this var association = this
, primaryKeyAttribute = association.target.primaryKeyAttribute; , primaryKeyAttribute = association.target.primaryKeyAttribute;
...@@ -340,9 +339,9 @@ module.exports = (function() { ...@@ -340,9 +339,9 @@ module.exports = (function() {
}; };
return this; return this;
}; };
HasMany.prototype.injectCreator = function(obj) { HasMany.prototype.injectCreator = function(obj) {
var association = this; var association = this;
obj[this.accessors.create] = function(values, options) { obj[this.accessors.create] = function(values, options) {
...@@ -372,7 +371,6 @@ module.exports = (function() { ...@@ -372,7 +371,6 @@ module.exports = (function() {
}; };
return this; return this;
}; };
return HasMany; module.exports = HasMany;
})();
...@@ -5,8 +5,7 @@ var Utils = require('./../utils') ...@@ -5,8 +5,7 @@ var Utils = require('./../utils')
, Association = require('./base') , Association = require('./base')
, util = require('util'); , util = require('util');
module.exports = (function() { var HasOne = function(srcModel, targetModel, options) {
var HasOne = function(srcModel, targetModel, options) {
Association.call(this); Association.call(this);
this.associationType = 'HasOne'; this.associationType = 'HasOne';
...@@ -65,12 +64,12 @@ module.exports = (function() { ...@@ -65,12 +64,12 @@ module.exports = (function() {
set: 'set' + singular, set: 'set' + singular,
create: 'create' + singular create: 'create' + singular
}; };
}; };
util.inherits(HasOne, Association); util.inherits(HasOne, Association);
// the id is in the target table // the id is in the target table
HasOne.prototype.injectAttributes = function() { HasOne.prototype.injectAttributes = function() {
var newAttributes = {} var newAttributes = {}
, keyType = this.source.rawAttributes[this.sourceIdentifier].type; , keyType = this.source.rawAttributes[this.sourceIdentifier].type;
...@@ -91,9 +90,9 @@ module.exports = (function() { ...@@ -91,9 +90,9 @@ module.exports = (function() {
Helpers.checkNamingCollision(this); Helpers.checkNamingCollision(this);
return this; return this;
}; };
HasOne.prototype.injectGetter = function(instancePrototype) { HasOne.prototype.injectGetter = function(instancePrototype) {
var association = this; var association = this;
instancePrototype[this.accessors.get] = function(options) { instancePrototype[this.accessors.get] = function(options) {
...@@ -124,9 +123,9 @@ module.exports = (function() { ...@@ -124,9 +123,9 @@ module.exports = (function() {
}; };
return this; return this;
}; };
HasOne.prototype.injectSetter = function(instancePrototype) { HasOne.prototype.injectSetter = function(instancePrototype) {
var association = this; var association = this;
instancePrototype[this.accessors.set] = function(associatedInstance, options) { instancePrototype[this.accessors.set] = function(associatedInstance, options) {
...@@ -160,9 +159,9 @@ module.exports = (function() { ...@@ -160,9 +159,9 @@ module.exports = (function() {
}; };
return this; return this;
}; };
HasOne.prototype.injectCreator = function(instancePrototype) { HasOne.prototype.injectCreator = function(instancePrototype) {
var association = this; var association = this;
instancePrototype[this.accessors.create] = function(values, options) { instancePrototype[this.accessors.create] = function(values, options) {
...@@ -176,7 +175,6 @@ module.exports = (function() { ...@@ -176,7 +175,6 @@ module.exports = (function() {
}; };
return this; return this;
}; };
return HasOne; module.exports = HasOne;
})();
...@@ -2,8 +2,7 @@ ...@@ -2,8 +2,7 @@
var Utils = require('./../utils'); var Utils = require('./../utils');
module.exports = { function checkNamingCollision (association) {
checkNamingCollision: function (association) {
if (association.source.rawAttributes.hasOwnProperty(association.as)) { if (association.source.rawAttributes.hasOwnProperty(association.as)) {
throw new Error( throw new Error(
'Naming collision between attribute \'' + association.as + 'Naming collision between attribute \'' + association.as +
...@@ -11,9 +10,9 @@ module.exports = { ...@@ -11,9 +10,9 @@ module.exports = {
'. To remedy this, change either foreignKey or as in your association definition' '. To remedy this, change either foreignKey or as in your association definition'
); );
} }
}, }
addForeignKeyConstraints: function(newAttribute, source, target, options) { function addForeignKeyConstraints (newAttribute, source, target, options) {
// FK constraints are opt-in: users must either set `foreignKeyConstraints` // FK constraints are opt-in: users must either set `foreignKeyConstraints`
// on the association, or request an `onDelete` or `onUpdate` behaviour // on the association, or request an `onDelete` or `onUpdate` behaviour
...@@ -44,6 +43,9 @@ module.exports = { ...@@ -44,6 +43,9 @@ module.exports = {
newAttribute.onUpdate = options.onUpdate; newAttribute.onUpdate = options.onUpdate;
} }
} }
} }
module.exports = {
checkNamingCollision: checkNamingCollision,
addForeignKeyConstraints: addForeignKeyConstraints
}; };
...@@ -9,8 +9,12 @@ var Utils = require('../../utils') ...@@ -9,8 +9,12 @@ var Utils = require('../../utils')
, Dottie = require('dottie') , Dottie = require('dottie')
, uuid = require('node-uuid'); , uuid = require('node-uuid');
module.exports = (function() { /* istanbul ignore next */
var QueryGenerator = { var throwMethodUndefined = function(methodName) {
throw new Error('The method "' + methodName + '" is not defined! Please add it to your sql dialect.');
};
var QueryGenerator = {
options: {}, options: {},
addSchema: function(param) { addSchema: function(param) {
...@@ -2061,12 +2065,6 @@ module.exports = (function() { ...@@ -2061,12 +2065,6 @@ module.exports = (function() {
booleanValue: function(value) { booleanValue: function(value) {
return value; return value;
} }
}; };
/* istanbul ignore next */
var throwMethodUndefined = function(methodName) {
throw new Error('The method "' + methodName + '" is not defined! Please add it to your sql dialect.');
};
return QueryGenerator; module.exports = QueryGenerator;
})();
...@@ -4,234 +4,9 @@ var Utils = require('../../utils') ...@@ -4,234 +4,9 @@ var Utils = require('../../utils')
, Dot = require('dottie') , Dot = require('dottie')
, QueryTypes = require('../../query-types'); , QueryTypes = require('../../query-types');
module.exports = (function() { var AbstractQuery = function(database, sequelize, options) {};
var AbstractQuery = function(database, sequelize, options) {};
/** /**
* Execute the passed sql query.
*
* Examples:
*
* query.run('SELECT 1')
*
* @param {String} sql - The SQL query which should be executed.
* @api public
*/
AbstractQuery.prototype.run = function() {
throw new Error('The run method wasn\'t overwritten!');
};
/**
* Check the logging option of the instance and print deprecation warnings.
*
* @return {void}
*/
AbstractQuery.prototype.checkLoggingOption = function() {
if (this.options.logging === true) {
console.log('DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log');
this.options.logging = console.log;
}
if (this.options.logging === console.log) {
// using just console.log will break in node < 0.6
this.options.logging = function(s) { console.log(s); };
}
};
/**
* Get the attributes of an insert query, which contains the just inserted id.
*
* @return {String} The field name.
*/
AbstractQuery.prototype.getInsertIdField = function() {
return 'insertId';
};
/**
* Iterate over all known tables and search their names inside the sql query.
* This method will also check association aliases ('as' option).
*
* @param {String} attribute An attribute of a SQL query. (?)
* @return {String} The found tableName / alias.
*/
AbstractQuery.prototype.findTableNameInAttribute = function(attribute) {
if (!this.options.include) {
return null;
}
if (!this.options.includeNames) {
this.options.includeNames = this.options.include.map(function(include) {
return include.as;
});
}
var tableNames = this.options.includeNames.filter(function(include) {
return attribute.indexOf(include + '.') === 0;
});
if (tableNames.length === 1) {
return tableNames[0];
} else {
return null;
}
};
AbstractQuery.prototype.isRawQuery = function () {
return this.options.type === QueryTypes.RAW;
};
AbstractQuery.prototype.isVersionQuery = function () {
return this.options.type === QueryTypes.VERSION;
};
AbstractQuery.prototype.isUpsertQuery = function () {
return this.options.type === QueryTypes.UPSERT;
};
AbstractQuery.prototype.isInsertQuery = function(results, metaData) {
var result = true;
if (this.options.type === QueryTypes.INSERT) {
return true;
}
// is insert query if sql contains insert into
result = result && (this.sql.toLowerCase().indexOf('insert into') === 0);
// is insert query if no results are passed or if the result has the inserted id
result = result && (!results || results.hasOwnProperty(this.getInsertIdField()));
// is insert query if no metadata are passed or if the metadata has the inserted id
result = result && (!metaData || metaData.hasOwnProperty(this.getInsertIdField()));
return result;
};
AbstractQuery.prototype.handleInsertQuery = function(results, metaData) {
if (this.instance) {
// add the inserted row id to the instance
var autoIncrementField = this.model.autoIncrementField
, id = null;
id = id || (results && results[this.getInsertIdField()]);
id = id || (metaData && metaData[this.getInsertIdField()]);
this.instance[autoIncrementField] = id;
}
};
AbstractQuery.prototype.isShowTablesQuery = function() {
return this.options.type === QueryTypes.SHOWTABLES;
};
AbstractQuery.prototype.handleShowTablesQuery = function(results) {
return Utils._.flatten(results.map(function(resultSet) {
return Utils._.values(resultSet);
}));
};
AbstractQuery.prototype.isShowIndexesQuery = function () {
return this.options.type === QueryTypes.SHOWINDEXES;
};
AbstractQuery.prototype.isDescribeQuery = function () {
return this.options.type === QueryTypes.DESCRIBE;
};
AbstractQuery.prototype.isSelectQuery = function() {
return this.options.type === QueryTypes.SELECT;
};
AbstractQuery.prototype.isBulkUpdateQuery = function() {
return this.options.type === QueryTypes.BULKUPDATE;
};
AbstractQuery.prototype.isBulkDeleteQuery = function() {
return this.options.type === QueryTypes.BULKDELETE;
};
AbstractQuery.prototype.isForeignKeysQuery = function() {
return this.options.type === QueryTypes.FOREIGNKEYS;
};
AbstractQuery.prototype.isUpdateQuery = function() {
return this.options.type === QueryTypes.UPDATE;
};
AbstractQuery.prototype.handleSelectQuery = function(results) {
var result = null;
// Raw queries
if (this.options.raw) {
result = results.map(function(result) {
var o = {};
for (var key in result) {
if (result.hasOwnProperty(key)) {
o[key] = result[key];
}
}
if (this.options.nest) {
o = Dot.transform(o);
}
return o;
}, this);
// Queries with include
} else if (this.options.hasJoin === true) {
results = groupJoinData(results, {
model: this.model,
includeMap: this.options.includeMap,
includeNames: this.options.includeNames
}, {
checkExisting: this.options.hasMultiAssociation
});
result = this.model.bulkBuild(results, {
isNewRecord: false,
include: this.options.include,
includeNames: this.options.includeNames,
includeMap: this.options.includeMap,
includeValidated: true,
attributes: this.options.originalAttributes || this.options.attributes,
raw: true
});
// Regular queries
} else {
result = this.model.bulkBuild(results, {
isNewRecord: false,
raw: true,
attributes: this.options.attributes
});
}
// return the first real model instance if options.plain is set (e.g. Model.find)
if (this.options.plain) {
result = (result.length === 0) ? null : result[0];
}
return result;
};
AbstractQuery.prototype.isShowOrDescribeQuery = function() {
var result = false;
result = result || (this.sql.toLowerCase().indexOf('show') === 0);
result = result || (this.sql.toLowerCase().indexOf('describe') === 0);
return result;
};
AbstractQuery.prototype.isCallQuery = function() {
var result = false;
result = result || (this.sql.toLowerCase().indexOf('call') === 0);
return result;
};
/**
The function takes the result of the query execution and groups The function takes the result of the query execution and groups
the associated data by the callee. the associated data by the callee.
...@@ -266,8 +41,8 @@ module.exports = (function() { ...@@ -266,8 +41,8 @@ module.exports = (function() {
] ]
} }
] ]
*/ */
/* /*
* Assumptions * Assumptions
* ID is not necessarily the first field * ID is not necessarily the first field
* All fields for a level is grouped in the same set (i.e. Panel.id, Task.id, Panel.title is not possible) * All fields for a level is grouped in the same set (i.e. Panel.id, Task.id, Panel.title is not possible)
...@@ -280,7 +55,7 @@ module.exports = (function() { ...@@ -280,7 +55,7 @@ module.exports = (function() {
* groupJoinData is a performance critical function so we prioritize perf over readability. * groupJoinData is a performance critical function so we prioritize perf over readability.
*/ */
var groupJoinData = function(rows, includeOptions, options) { var groupJoinData = function(rows, includeOptions, options) {
if (!rows.length) { if (!rows.length) {
return []; return [];
} }
...@@ -569,9 +344,231 @@ module.exports = (function() { ...@@ -569,9 +344,231 @@ module.exports = (function() {
} }
return results; return results;
}; };
/**
* Execute the passed sql query.
*
* Examples:
*
* query.run('SELECT 1')
*
* @param {String} sql - The SQL query which should be executed.
* @api public
*/
AbstractQuery.prototype.run = function() {
throw new Error('The run method wasn\'t overwritten!');
};
/**
* Check the logging option of the instance and print deprecation warnings.
*
* @return {void}
*/
AbstractQuery.prototype.checkLoggingOption = function() {
if (this.options.logging === true) {
console.log('DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log');
this.options.logging = console.log;
}
if (this.options.logging === console.log) {
// using just console.log will break in node < 0.6
this.options.logging = function(s) { console.log(s); };
}
};
/**
* Get the attributes of an insert query, which contains the just inserted id.
*
* @return {String} The field name.
*/
AbstractQuery.prototype.getInsertIdField = function() {
return 'insertId';
};
/**
* Iterate over all known tables and search their names inside the sql query.
* This method will also check association aliases ('as' option).
*
* @param {String} attribute An attribute of a SQL query. (?)
* @return {String} The found tableName / alias.
*/
AbstractQuery.prototype.findTableNameInAttribute = function(attribute) {
if (!this.options.include) {
return null;
}
if (!this.options.includeNames) {
this.options.includeNames = this.options.include.map(function(include) {
return include.as;
});
}
var tableNames = this.options.includeNames.filter(function(include) {
return attribute.indexOf(include + '.') === 0;
});
if (tableNames.length === 1) {
return tableNames[0];
} else {
return null;
}
};
AbstractQuery.prototype.isRawQuery = function () {
return this.options.type === QueryTypes.RAW;
};
AbstractQuery.prototype.isVersionQuery = function () {
return this.options.type === QueryTypes.VERSION;
};
AbstractQuery.prototype.isUpsertQuery = function () {
return this.options.type === QueryTypes.UPSERT;
};
AbstractQuery.prototype.isInsertQuery = function(results, metaData) {
var result = true;
if (this.options.type === QueryTypes.INSERT) {
return true;
}
// is insert query if sql contains insert into
result = result && (this.sql.toLowerCase().indexOf('insert into') === 0);
// is insert query if no results are passed or if the result has the inserted id
result = result && (!results || results.hasOwnProperty(this.getInsertIdField()));
// is insert query if no metadata are passed or if the metadata has the inserted id
result = result && (!metaData || metaData.hasOwnProperty(this.getInsertIdField()));
return result;
};
AbstractQuery.prototype.handleInsertQuery = function(results, metaData) {
if (this.instance) {
// add the inserted row id to the instance
var autoIncrementField = this.model.autoIncrementField
, id = null;
id = id || (results && results[this.getInsertIdField()]);
id = id || (metaData && metaData[this.getInsertIdField()]);
this.instance[autoIncrementField] = id;
}
};
AbstractQuery.prototype.isShowTablesQuery = function() {
return this.options.type === QueryTypes.SHOWTABLES;
};
AbstractQuery.prototype.handleShowTablesQuery = function(results) {
return Utils._.flatten(results.map(function(resultSet) {
return Utils._.values(resultSet);
}));
};
AbstractQuery.prototype.isShowIndexesQuery = function () {
return this.options.type === QueryTypes.SHOWINDEXES;
};
AbstractQuery.prototype.isDescribeQuery = function () {
return this.options.type === QueryTypes.DESCRIBE;
};
AbstractQuery.prototype.isSelectQuery = function() {
return this.options.type === QueryTypes.SELECT;
};
AbstractQuery.prototype.isBulkUpdateQuery = function() {
return this.options.type === QueryTypes.BULKUPDATE;
};
AbstractQuery.prototype.isBulkDeleteQuery = function() {
return this.options.type === QueryTypes.BULKDELETE;
};
AbstractQuery.prototype.isForeignKeysQuery = function() {
return this.options.type === QueryTypes.FOREIGNKEYS;
};
AbstractQuery.prototype.isUpdateQuery = function() {
return this.options.type === QueryTypes.UPDATE;
};
AbstractQuery.prototype.handleSelectQuery = function(results) {
var result = null;
// Raw queries
if (this.options.raw) {
result = results.map(function(result) {
var o = {};
for (var key in result) {
if (result.hasOwnProperty(key)) {
o[key] = result[key];
}
}
if (this.options.nest) {
o = Dot.transform(o);
}
return o;
}, this);
// Queries with include
} else if (this.options.hasJoin === true) {
results = groupJoinData(results, {
model: this.model,
includeMap: this.options.includeMap,
includeNames: this.options.includeNames
}, {
checkExisting: this.options.hasMultiAssociation
});
result = this.model.bulkBuild(results, {
isNewRecord: false,
include: this.options.include,
includeNames: this.options.includeNames,
includeMap: this.options.includeMap,
includeValidated: true,
attributes: this.options.originalAttributes || this.options.attributes,
raw: true
});
// Regular queries
} else {
result = this.model.bulkBuild(results, {
isNewRecord: false,
raw: true,
attributes: this.options.attributes
});
}
// return the first real model instance if options.plain is set (e.g. Model.find)
if (this.options.plain) {
result = (result.length === 0) ? null : result[0];
}
return result;
};
AbstractQuery.prototype.isShowOrDescribeQuery = function() {
var result = false;
result = result || (this.sql.toLowerCase().indexOf('show') === 0);
result = result || (this.sql.toLowerCase().indexOf('describe') === 0);
return result;
};
AbstractQuery.prototype.isCallQuery = function() {
var result = false;
result = result || (this.sql.toLowerCase().indexOf('call') === 0);
return result;
};
AbstractQuery.$groupJoinData = groupJoinData; AbstractQuery.$groupJoinData = groupJoinData;
return AbstractQuery; module.exports = AbstractQuery;
})();
...@@ -6,8 +6,12 @@ var Utils = require('../../utils') ...@@ -6,8 +6,12 @@ var Utils = require('../../utils')
, Model = require('../../model') , Model = require('../../model')
, AbstractQueryGenerator = require('../abstract/query-generator'); , AbstractQueryGenerator = require('../abstract/query-generator');
module.exports = (function() { /* istanbul ignore next */
var QueryGenerator = { var throwMethodUndefined = function(methodName) {
throw new Error('The method "' + methodName + '" is not defined! Please add it to your sql dialect.');
};
var QueryGenerator = {
options: {}, options: {},
dialect: 'mssql', dialect: 'mssql',
...@@ -595,17 +599,11 @@ module.exports = (function() { ...@@ -595,17 +599,11 @@ module.exports = (function() {
booleanValue: function(value) { booleanValue: function(value) {
return !!value ? 1 : 0; return !!value ? 1 : 0;
} }
}; };
// private methods // private methods
function wrapSingleQuote(identifier){ function wrapSingleQuote(identifier){
return Utils.addTicks(identifier, "'"); return Utils.addTicks(identifier, "'");
} }
/* istanbul ignore next */
var throwMethodUndefined = function(methodName) {
throw new Error('The method "' + methodName + '" is not defined! Please add it to your sql dialect.');
};
return Utils._.extend(Utils._.clone(AbstractQueryGenerator), QueryGenerator); module.exports = Utils._.extend(Utils._.clone(AbstractQueryGenerator), QueryGenerator);
})();
...@@ -4,8 +4,7 @@ var Utils = require('../../utils') ...@@ -4,8 +4,7 @@ var Utils = require('../../utils')
, AbstractQuery = require('../abstract/query') , AbstractQuery = require('../abstract/query')
, sequelizeErrors = require('../../errors.js'); , sequelizeErrors = require('../../errors.js');
module.exports = (function() { var Query = function(connection, sequelize, options) {
var Query = function(connection, sequelize, options) {
this.connection = connection; this.connection = connection;
this.instance = options.instance; this.instance = options.instance;
this.model = options.model; this.model = options.model;
...@@ -17,15 +16,15 @@ module.exports = (function() { ...@@ -17,15 +16,15 @@ module.exports = (function() {
}, options || {}); }, options || {});
this.checkLoggingOption(); this.checkLoggingOption();
}; };
Utils.inherit(Query, AbstractQuery); Utils.inherit(Query, AbstractQuery);
Query.prototype.getInsertIdField = function() { Query.prototype.getInsertIdField = function() {
return 'id'; return 'id';
}; };
Query.prototype.run = function(sql) { Query.prototype.run = function(sql) {
var self = this; var self = this;
this.sql = sql; this.sql = sql;
...@@ -84,9 +83,9 @@ module.exports = (function() { ...@@ -84,9 +83,9 @@ module.exports = (function() {
}); });
return promise; return promise;
}; };
/** /**
* High level function that handles the results of a query execution. * High level function that handles the results of a query execution.
* *
* *
...@@ -102,7 +101,7 @@ module.exports = (function() { ...@@ -102,7 +101,7 @@ module.exports = (function() {
* *
* @param {Array} data - The result of the query execution. * @param {Array} data - The result of the query execution.
*/ */
Query.prototype.formatResults = function(data) { Query.prototype.formatResults = function(data) {
var result = this.instance; var result = this.instance;
if (this.isInsertQuery(data)) { if (this.isInsertQuery(data)) {
this.handleInsertQuery(data); this.handleInsertQuery(data);
...@@ -155,18 +154,18 @@ module.exports = (function() { ...@@ -155,18 +154,18 @@ module.exports = (function() {
} }
return result; return result;
}; };
Query.prototype.handleShowTablesQuery = function(results) { Query.prototype.handleShowTablesQuery = function(results) {
return results.map(function(resultSet) { return results.map(function(resultSet) {
return { return {
tableName: resultSet.TABLE_NAME, tableName: resultSet.TABLE_NAME,
schema: resultSet.TABLE_SCHEMA schema: resultSet.TABLE_SCHEMA
}; };
}); });
}; };
Query.prototype.formatError = function (err) { Query.prototype.formatError = function (err) {
var match; var match;
match = err.message.match(/Violation of UNIQUE KEY constraint '((.|\s)*)'. Cannot insert duplicate key in object '.*'. The duplicate key value is \((.*)\)./); match = err.message.match(/Violation of UNIQUE KEY constraint '((.|\s)*)'. Cannot insert duplicate key in object '.*'. The duplicate key value is \((.*)\)./);
match = match || err.message.match(/Cannot insert duplicate key row in object .* with unique index '(.*)'/); match = match || err.message.match(/Cannot insert duplicate key row in object .* with unique index '(.*)'/);
...@@ -210,9 +209,9 @@ module.exports = (function() { ...@@ -210,9 +209,9 @@ module.exports = (function() {
} }
return new sequelizeErrors.DatabaseError(err); return new sequelizeErrors.DatabaseError(err);
}; };
Query.prototype.isShowOrDescribeQuery = function() { Query.prototype.isShowOrDescribeQuery = function() {
var result = false; var result = false;
result = result || (this.sql.toLowerCase().indexOf("select c.column_name as 'name', c.data_type as 'type', c.is_nullable as 'isnull'") === 0); /* jshint ignore: line */ result = result || (this.sql.toLowerCase().indexOf("select c.column_name as 'name', c.data_type as 'type', c.is_nullable as 'isnull'") === 0); /* jshint ignore: line */
...@@ -220,13 +219,13 @@ module.exports = (function() { ...@@ -220,13 +219,13 @@ module.exports = (function() {
result = result || (this.sql.toLowerCase().indexOf('exec sys.sp_helpindex @objname') === 0); result = result || (this.sql.toLowerCase().indexOf('exec sys.sp_helpindex @objname') === 0);
return result; return result;
}; };
Query.prototype.isShowIndexesQuery = function () { Query.prototype.isShowIndexesQuery = function () {
return this.sql.toLowerCase().indexOf('exec sys.sp_helpindex @objname') === 0; return this.sql.toLowerCase().indexOf('exec sys.sp_helpindex @objname') === 0;
}; };
Query.prototype.handleShowIndexesQuery = function (data) { Query.prototype.handleShowIndexesQuery = function (data) {
// Group by index name, and collect all fields // Group by index name, and collect all fields
data = Utils._.foldl(data, function (acc, item) { data = Utils._.foldl(data, function (acc, item) {
if (!(item.index_name in acc)) { if (!(item.index_name in acc)) {
...@@ -261,9 +260,9 @@ module.exports = (function() { ...@@ -261,9 +260,9 @@ module.exports = (function() {
type: undefined, type: undefined,
}; };
}); });
}; };
Query.prototype.handleInsertQuery = function(results, metaData) { Query.prototype.handleInsertQuery = function(results, metaData) {
if (this.instance) { if (this.instance) {
// add the inserted row id to the instance // add the inserted row id to the instance
var autoIncrementField = this.model.autoIncrementField var autoIncrementField = this.model.autoIncrementField
...@@ -281,7 +280,6 @@ module.exports = (function() { ...@@ -281,7 +280,6 @@ module.exports = (function() {
this.instance[autoIncrementField] = id; this.instance[autoIncrementField] = id;
} }
}; };
return Query; module.exports = Query;
})();
...@@ -3,8 +3,7 @@ ...@@ -3,8 +3,7 @@
var Utils = require('../../utils') var Utils = require('../../utils')
, DataTypes = require('../../data-types'); , DataTypes = require('../../data-types');
module.exports = (function() { var QueryGenerator = {
var QueryGenerator = {
dialect: 'mysql', dialect: 'mysql',
createSchema: function() { createSchema: function() {
...@@ -372,7 +371,6 @@ module.exports = (function() { ...@@ -372,7 +371,6 @@ module.exports = (function() {
dropForeignKeyQuery: function(tableName, foreignKey) { dropForeignKeyQuery: function(tableName, foreignKey) {
return 'ALTER TABLE ' + this.quoteTable(tableName) + ' DROP FOREIGN KEY ' + this.quoteIdentifier(foreignKey) + ';'; return 'ALTER TABLE ' + this.quoteTable(tableName) + ' DROP FOREIGN KEY ' + this.quoteIdentifier(foreignKey) + ';';
} }
}; };
return Utils._.extend(Utils._.clone(require('../abstract/query-generator')), QueryGenerator); module.exports = Utils._.extend(Utils._.clone(require('../abstract/query-generator')), QueryGenerator);
})();
...@@ -5,8 +5,7 @@ var Utils = require('../../utils') ...@@ -5,8 +5,7 @@ var Utils = require('../../utils')
, uuid = require('node-uuid') , uuid = require('node-uuid')
, sequelizeErrors = require('../../errors.js'); , sequelizeErrors = require('../../errors.js');
module.exports = (function() { var Query = function(connection, sequelize, options) {
var Query = function(connection, sequelize, options) {
this.connection = connection; this.connection = connection;
this.instance = options.instance; this.instance = options.instance;
this.model = options.model; this.model = options.model;
...@@ -19,10 +18,10 @@ module.exports = (function() { ...@@ -19,10 +18,10 @@ module.exports = (function() {
}, options || {}); }, options || {});
this.checkLoggingOption(); this.checkLoggingOption();
}; };
Utils.inherit(Query, AbstractQuery); Utils.inherit(Query, AbstractQuery);
Query.prototype.run = function(sql) { Query.prototype.run = function(sql) {
var self = this; var self = this;
this.sql = sql; this.sql = sql;
...@@ -41,7 +40,7 @@ module.exports = (function() { ...@@ -41,7 +40,7 @@ module.exports = (function() {
}); });
return promise; return promise;
}; };
/** /**
* High level function that handles the results of a query execution. * High level function that handles the results of a query execution.
...@@ -59,7 +58,7 @@ module.exports = (function() { ...@@ -59,7 +58,7 @@ module.exports = (function() {
* *
* @param {Array} data - The result of the query execution. * @param {Array} data - The result of the query execution.
*/ */
Query.prototype.formatResults = function(data) { Query.prototype.formatResults = function(data) {
var result = this.instance; var result = this.instance;
if (this.isInsertQuery(data)) { if (this.isInsertQuery(data)) {
...@@ -101,10 +100,10 @@ module.exports = (function() { ...@@ -101,10 +100,10 @@ module.exports = (function() {
} }
return result; return result;
}; };
Query.prototype.formatError = function (err) { Query.prototype.formatError = function (err) {
var match; var match;
switch (err.errno || err.code) { switch (err.errno || err.code) {
...@@ -157,9 +156,9 @@ module.exports = (function() { ...@@ -157,9 +156,9 @@ module.exports = (function() {
default: default:
return new sequelizeErrors.DatabaseError(err); return new sequelizeErrors.DatabaseError(err);
} }
}; };
Query.prototype.handleShowIndexesQuery = function (data) { Query.prototype.handleShowIndexesQuery = function (data) {
// Group by index name, and collect all fields // Group by index name, and collect all fields
data = Utils._.foldl(data, function (acc, item) { data = Utils._.foldl(data, function (acc, item) {
if (!(item.Key_name in acc)) { if (!(item.Key_name in acc)) {
...@@ -187,7 +186,6 @@ module.exports = (function() { ...@@ -187,7 +186,6 @@ module.exports = (function() {
type: item.Index_type, type: item.Index_type,
}; };
}); });
}; };
return Query; module.exports = Query;
})();
...@@ -2,15 +2,17 @@ ...@@ -2,15 +2,17 @@
var hstore = require('pg-hstore')({sanitize : true}); var hstore = require('pg-hstore')({sanitize : true});
module.exports = { function stringify (data) {
stringify: function(data) { if (data === null) return null;
if(data === null) return null;
return hstore.stringify(data); return hstore.stringify(data);
}, }
parse: function(value) {
if(value === null) return null;
function parse (value) {
if (value === null) return null;
return hstore.parse(value); return hstore.parse(value);
} }
module.exports = {
stringify: stringify,
parse: parse
}; };
...@@ -10,8 +10,7 @@ var Utils = require('../../utils') ...@@ -10,8 +10,7 @@ var Utils = require('../../utils')
, AbstractQueryGenerator = require('../abstract/query-generator') , AbstractQueryGenerator = require('../abstract/query-generator')
, primaryKeys = {}; , primaryKeys = {};
module.exports = (function() { var QueryGenerator = {
var QueryGenerator = {
options: {}, options: {},
dialect: 'postgres', dialect: 'postgres',
...@@ -938,7 +937,6 @@ module.exports = (function() { ...@@ -938,7 +937,6 @@ module.exports = (function() {
return AbstractQueryGenerator.setAutocommitQuery.call(this, value, options); return AbstractQueryGenerator.setAutocommitQuery.call(this, value, options);
} }
}; };
return Utils._.extend(Utils._.clone(AbstractQueryGenerator), QueryGenerator); module.exports = Utils._.extend(Utils._.clone(AbstractQueryGenerator), QueryGenerator);
})();
...@@ -66,8 +66,7 @@ function dialectSpecificFieldDatatypeMap (options, prefix) { ...@@ -66,8 +66,7 @@ function dialectSpecificFieldDatatypeMap (options, prefix) {
return fields; return fields;
} }
module.exports = (function() { var Query = function(client, sequelize, options) {
var Query = function(client, sequelize, options) {
this.client = client; this.client = client;
this.sequelize = sequelize; this.sequelize = sequelize;
this.instance = options.instance; this.instance = options.instance;
...@@ -79,12 +78,12 @@ module.exports = (function() { ...@@ -79,12 +78,12 @@ module.exports = (function() {
}, options || {}); }, options || {});
this.checkLoggingOption(); this.checkLoggingOption();
}; };
Utils.inherit(Query, AbstractQuery); Utils.inherit(Query, AbstractQuery);
Query.prototype.parseDialectSpecificFields = parseDialectSpecificFields; Query.prototype.parseDialectSpecificFields = parseDialectSpecificFields;
Query.prototype.run = function(sql) { Query.prototype.run = function(sql) {
this.sql = sql; this.sql = sql;
var self = this var self = this
...@@ -336,9 +335,9 @@ module.exports = (function() { ...@@ -336,9 +335,9 @@ module.exports = (function() {
}); });
return promise; return promise;
}; };
Query.prototype.formatError = function (err) { Query.prototype.formatError = function (err) {
var match var match
, table , table
, index , index
...@@ -420,15 +419,14 @@ module.exports = (function() { ...@@ -420,15 +419,14 @@ module.exports = (function() {
default: default:
return new sequelizeErrors.DatabaseError(err); return new sequelizeErrors.DatabaseError(err);
} }
}; };
Query.prototype.isForeignKeysQuery = function() { Query.prototype.isForeignKeysQuery = function() {
return /SELECT conname as constraint_name, pg_catalog\.pg_get_constraintdef\(r\.oid, true\) as condef FROM pg_catalog\.pg_constraint r WHERE r\.conrelid = \(SELECT oid FROM pg_class WHERE relname = '.*' LIMIT 1\) AND r\.contype = 'f' ORDER BY 1;/.test(this.sql); return /SELECT conname as constraint_name, pg_catalog\.pg_get_constraintdef\(r\.oid, true\) as condef FROM pg_catalog\.pg_constraint r WHERE r\.conrelid = \(SELECT oid FROM pg_class WHERE relname = '.*' LIMIT 1\) AND r\.contype = 'f' ORDER BY 1;/.test(this.sql);
}; };
Query.prototype.getInsertIdField = function() { Query.prototype.getInsertIdField = function() {
return 'id'; return 'id';
}; };
return Query; module.exports = Query;
})();
...@@ -3,8 +3,7 @@ ...@@ -3,8 +3,7 @@
var Utils = require('../../utils'), var Utils = require('../../utils'),
moment = require('moment'); moment = require('moment');
module.exports = { function stringify (data) {
stringify: function (data) {
if (data === null) return null; if (data === null) return null;
if (!Utils._.isArray(data) || data.length !== 2) return ''; if (!Utils._.isArray(data) || data.length !== 2) return '';
...@@ -26,8 +25,9 @@ module.exports = { ...@@ -26,8 +25,9 @@ module.exports = {
}); });
return (data.inclusive[0] ? '[' : '(') + JSON.stringify(data[0]) + ',' + JSON.stringify(data[1]) + (data.inclusive[1] ? ']' : ')'); return (data.inclusive[0] ? '[' : '(') + JSON.stringify(data[0]) + ',' + JSON.stringify(data[1]) + (data.inclusive[1] ? ']' : ')');
}, }
parse: function (value, AttributeType) {
function parse (value, AttributeType) {
if (value === null) return null; if (value === null) return null;
if(typeof AttributeType === 'function') AttributeType = new AttributeType(); if(typeof AttributeType === 'function') AttributeType = new AttributeType();
...@@ -58,5 +58,9 @@ module.exports = { ...@@ -58,5 +58,9 @@ module.exports = {
result.inclusive = [(value[0] === '['), (value[value.length - 1] === ']')]; result.inclusive = [(value[0] === '['), (value[value.length - 1] === ']')];
return result; return result;
} }
module.exports = {
stringify: stringify,
parse: parse
}; };
...@@ -11,8 +11,7 @@ var MySqlQueryGenerator = Utils._.extend( ...@@ -11,8 +11,7 @@ var MySqlQueryGenerator = Utils._.extend(
Utils._.clone(require('../mysql/query-generator')) Utils._.clone(require('../mysql/query-generator'))
); );
module.exports = (function() { var QueryGenerator = {
var QueryGenerator = {
options: {}, options: {},
dialect: 'sqlite', dialect: 'sqlite',
...@@ -437,7 +436,6 @@ module.exports = (function() { ...@@ -437,7 +436,6 @@ module.exports = (function() {
var sql = 'PRAGMA foreign_key_list(<%= tableName %>)'; var sql = 'PRAGMA foreign_key_list(<%= tableName %>)';
return Utils._.template(sql)({ tableName: tableName }); return Utils._.template(sql)({ tableName: tableName });
} }
}; };
return Utils._.extend({}, MySqlQueryGenerator, QueryGenerator); module.exports = Utils._.extend({}, MySqlQueryGenerator, QueryGenerator);
})();
...@@ -9,8 +9,8 @@ var Utils = require('../../utils') ...@@ -9,8 +9,8 @@ var Utils = require('../../utils')
@class QueryInterface @class QueryInterface
@static @static
*/ */
module.exports = {
/** /**
A wrapper that fixes SQLite's inability to remove columns from existing tables. A wrapper that fixes SQLite's inability to remove columns from existing tables.
It will create a backup of the table, drop the table afterwards and create a It will create a backup of the table, drop the table afterwards and create a
new table with the same name but without the obsolete column. new table with the same name but without the obsolete column.
...@@ -27,7 +27,7 @@ module.exports = { ...@@ -27,7 +27,7 @@ module.exports = {
@since 1.6.0 @since 1.6.0
*/ */
removeColumn: function(tableName, attributeName, options) { var removeColumn = function(tableName, attributeName, options) {
var self = this; var self = this;
options = options || {}; options = options || {};
...@@ -41,9 +41,9 @@ module.exports = { ...@@ -41,9 +41,9 @@ module.exports = {
return self.sequelize.query(subQuery + ';', { raw: true, logging: options.logging }); return self.sequelize.query(subQuery + ';', { raw: true, logging: options.logging });
}); });
}); });
}, };
/** /**
A wrapper that fixes SQLite's inability to change columns from existing tables. A wrapper that fixes SQLite's inability to change columns from existing tables.
It will create a backup of the table, drop the table afterwards and create a It will create a backup of the table, drop the table afterwards and create a
new table with the same name but with a modified version of the respective column. new table with the same name but with a modified version of the respective column.
...@@ -60,7 +60,7 @@ module.exports = { ...@@ -60,7 +60,7 @@ module.exports = {
@since 1.6.0 @since 1.6.0
*/ */
changeColumn: function(tableName, attributes, options) { var changeColumn = function(tableName, attributes, options) {
var attributeName = Utils._.keys(attributes)[0] var attributeName = Utils._.keys(attributes)[0]
, self = this; , self = this;
options = options || {}; options = options || {};
...@@ -75,9 +75,9 @@ module.exports = { ...@@ -75,9 +75,9 @@ module.exports = {
return self.sequelize.query(subQuery + ';', { raw: true, logging: options.logging }); return self.sequelize.query(subQuery + ';', { raw: true, logging: options.logging });
}); });
}); });
}, };
/** /**
A wrapper that fixes SQLite's inability to rename columns from existing tables. A wrapper that fixes SQLite's inability to rename columns from existing tables.
It will create a backup of the table, drop the table afterwards and create a It will create a backup of the table, drop the table afterwards and create a
new table with the same name but with a renamed version of the respective column. new table with the same name but with a renamed version of the respective column.
...@@ -95,7 +95,7 @@ module.exports = { ...@@ -95,7 +95,7 @@ module.exports = {
@since 1.6.0 @since 1.6.0
*/ */
renameColumn: function(tableName, attrNameBefore, attrNameAfter, options) { var renameColumn = function(tableName, attrNameBefore, attrNameAfter, options) {
var self = this; var self = this;
options = options || {}; options = options || {};
...@@ -110,5 +110,10 @@ module.exports = { ...@@ -110,5 +110,10 @@ module.exports = {
return self.sequelize.query(subQuery + ';', { raw: true, logging: options.logging }); return self.sequelize.query(subQuery + ';', { raw: true, logging: options.logging });
}); });
}); });
} };
module.exports = {
removeColumn: removeColumn,
changeColumn: changeColumn,
renameColumn: renameColumn
}; };
\ No newline at end of file
...@@ -5,8 +5,7 @@ var Utils = require('../../utils') ...@@ -5,8 +5,7 @@ var Utils = require('../../utils')
, QueryTypes = require('../../query-types') , QueryTypes = require('../../query-types')
, sequelizeErrors = require('../../errors.js'); , sequelizeErrors = require('../../errors.js');
module.exports = (function() { var Query = function(database, sequelize, options) {
var Query = function(database, sequelize, options) {
this.database = database; this.database = database;
this.sequelize = sequelize; this.sequelize = sequelize;
this.instance = options.instance; this.instance = options.instance;
...@@ -18,14 +17,14 @@ module.exports = (function() { ...@@ -18,14 +17,14 @@ module.exports = (function() {
}, options || {}); }, options || {});
this.checkLoggingOption(); this.checkLoggingOption();
}; };
Utils.inherit(Query, AbstractQuery); Utils.inherit(Query, AbstractQuery);
Query.prototype.getInsertIdField = function() { Query.prototype.getInsertIdField = function() {
return 'lastID'; return 'lastID';
}; };
Query.prototype.run = function(sql) { Query.prototype.run = function(sql) {
var self = this var self = this
, promise; , promise;
...@@ -179,9 +178,9 @@ module.exports = (function() { ...@@ -179,9 +178,9 @@ module.exports = (function() {
}); });
return promise; return promise;
}; };
Query.prototype.formatError = function (err) { Query.prototype.formatError = function (err) {
var match; var match;
switch (err.code) { switch (err.code) {
...@@ -241,9 +240,9 @@ module.exports = (function() { ...@@ -241,9 +240,9 @@ module.exports = (function() {
default: default:
return new sequelizeErrors.DatabaseError(err); return new sequelizeErrors.DatabaseError(err);
} }
}; };
Query.prototype.handleShowIndexesQuery = function (data) { Query.prototype.handleShowIndexesQuery = function (data) {
var self = this; var self = this;
// Sqlite returns indexes so the one that was defined last is returned first. Lets reverse that! // Sqlite returns indexes so the one that was defined last is returned first. Lets reverse that!
...@@ -264,9 +263,9 @@ module.exports = (function() { ...@@ -264,9 +263,9 @@ module.exports = (function() {
return item; return item;
}); });
}); });
}; };
Query.prototype.getDatabaseMethod = function() { Query.prototype.getDatabaseMethod = function() {
if (this.isUpsertQuery()) { if (this.isUpsertQuery()) {
return 'exec'; // Needed to run multiple queries in one return 'exec'; // Needed to run multiple queries in one
} else if (this.isInsertQuery() || this.isUpdateQuery() || this.isBulkUpdateQuery() || (this.sql.toLowerCase().indexOf('CREATE TEMPORARY TABLE'.toLowerCase()) !== -1) || this.options.type === QueryTypes.BULKDELETE) { } else if (this.isInsertQuery() || this.isUpdateQuery() || this.isBulkUpdateQuery() || (this.sql.toLowerCase().indexOf('CREATE TEMPORARY TABLE'.toLowerCase()) !== -1) || this.options.type === QueryTypes.BULKDELETE) {
...@@ -274,7 +273,6 @@ module.exports = (function() { ...@@ -274,7 +273,6 @@ module.exports = (function() {
} else { } else {
return 'all'; return 'all';
} }
}; };
return Query; module.exports = Query;
})();
...@@ -11,8 +11,59 @@ var Utils = require('./utils') ...@@ -11,8 +11,59 @@ var Utils = require('./utils')
, primitives = ['string', 'number', 'boolean'] , primitives = ['string', 'number', 'boolean']
, defaultsOptions = { raw: true }; , defaultsOptions = { raw: true };
module.exports = (function() { // private
/** var initValues = function(values, options) {
var defaults
, key;
values = values && _.clone(values) || {};
if (options.isNewRecord) {
defaults = {};
if (this.Model._hasDefaultValues) {
Utils._.each(this.Model._defaultValues, function(valueFn, key) {
if (defaults[key] === undefined) {
defaults[key] = valueFn();
}
});
}
// set id to null if not passed as value, a newly created dao has no id
// removing this breaks bulkCreate
// do after default values since it might have UUID as a default value
if (!defaults.hasOwnProperty(this.Model.primaryKeyAttribute)) {
defaults[this.Model.primaryKeyAttribute] = null;
}
if (this.Model._timestampAttributes.createdAt && defaults[this.Model._timestampAttributes.createdAt]) {
this.dataValues[this.Model._timestampAttributes.createdAt] = Utils.toDefaultValue(defaults[this.Model._timestampAttributes.createdAt]);
delete defaults[this.Model._timestampAttributes.createdAt];
}
if (this.Model._timestampAttributes.updatedAt && defaults[this.Model._timestampAttributes.updatedAt]) {
this.dataValues[this.Model._timestampAttributes.updatedAt] = Utils.toDefaultValue(defaults[this.Model._timestampAttributes.updatedAt]);
delete defaults[this.Model._timestampAttributes.updatedAt];
}
if (this.Model._timestampAttributes.deletedAt && defaults[this.Model._timestampAttributes.deletedAt]) {
this.dataValues[this.Model._timestampAttributes.deletedAt] = Utils.toDefaultValue(defaults[this.Model._timestampAttributes.deletedAt]);
delete defaults[this.Model._timestampAttributes.deletedAt];
}
if (Object.keys(defaults).length) {
for (key in defaults) {
if (values[key] === undefined) {
this.set(key, Utils.toDefaultValue(defaults[key]), defaultsOptions);
}
}
}
}
this.set(values, options);
};
/**
* This class represents an single instance, a database row. You might see it referred to as both Instance and instance. You should not * This class represents an single instance, a database row. You might see it referred to as both Instance and instance. You should not
* instantiate the Instance class directly, instead you access it using the finder and creation methods on the model. * instantiate the Instance class directly, instead you access it using the finder and creation methods on the model.
* *
...@@ -31,7 +82,7 @@ module.exports = (function() { ...@@ -31,7 +82,7 @@ module.exports = (function() {
* @see {Sequelize#define} for more information about getters and setters * @see {Sequelize#define} for more information about getters and setters
* @class Instance * @class Instance
*/ */
var Instance = function(values, options) { var Instance = function(values, options) {
this.dataValues = {}; this.dataValues = {};
this._previousDataValues = {}; this._previousDataValues = {};
this._changed = {}; this._changed = {};
...@@ -54,25 +105,25 @@ module.exports = (function() { ...@@ -54,25 +105,25 @@ module.exports = (function() {
*/ */
initValues.call(this, values, options); initValues.call(this, values, options);
}; };
/** /**
* A reference to the sequelize instance * A reference to the sequelize instance
* @see {Sequelize} * @see {Sequelize}
* @property sequelize * @property sequelize
* @return {Sequelize} * @return {Sequelize}
*/ */
Object.defineProperty(Instance.prototype, 'sequelize', { Object.defineProperty(Instance.prototype, 'sequelize', {
get: function() { return this.Model.modelManager.sequelize; } get: function() { return this.Model.modelManager.sequelize; }
}); });
/** /**
* Get an object representing the query for this instance, use with `options.where` * Get an object representing the query for this instance, use with `options.where`
* *
* @property where * @property where
* @return {Object} * @return {Object}
*/ */
Instance.prototype.where = function() { Instance.prototype.where = function() {
var where; var where;
where = this.Model.primaryKeyAttributes.reduce(function (result, attribute) { where = this.Model.primaryKeyAttributes.reduce(function (result, attribute) {
...@@ -84,38 +135,38 @@ module.exports = (function() { ...@@ -84,38 +135,38 @@ module.exports = (function() {
return this.__options.whereCollection; return this.__options.whereCollection;
} }
return where; return where;
}; };
Instance.prototype.toString = function () { Instance.prototype.toString = function () {
return '[object SequelizeInstance:'+this.Model.name+']'; return '[object SequelizeInstance:'+this.Model.name+']';
}; };
/** /**
* Get the value of the underlying data value * Get the value of the underlying data value
* *
* @param {String} key * @param {String} key
* @return {any} * @return {any}
*/ */
Instance.prototype.getDataValue = function(key) { Instance.prototype.getDataValue = function(key) {
return this.dataValues[key]; return this.dataValues[key];
}; };
/** /**
* Update the underlying data value * Update the underlying data value
* *
* @param {String} key * @param {String} key
* @param {any} value * @param {any} value
*/ */
Instance.prototype.setDataValue = function(key, value) { Instance.prototype.setDataValue = function(key, value) {
var originalValue = this._previousDataValues[key]; var originalValue = this._previousDataValues[key];
if (primitives.indexOf(typeof value) === -1 || value !== originalValue) { if (primitives.indexOf(typeof value) === -1 || value !== originalValue) {
this.changed(key, true); this.changed(key, true);
} }
this.dataValues[key] = value; this.dataValues[key] = value;
}; };
/** /**
* If no key is given, returns all values of the instance, also invoking virtual getters. * If no key is given, returns all values of the instance, also invoking virtual getters.
* *
* If key is given and a field or virtual getter is present for the key it will call that getter - else it will return the value for key. * If key is given and a field or virtual getter is present for the key it will call that getter - else it will return the value for key.
...@@ -125,7 +176,7 @@ module.exports = (function() { ...@@ -125,7 +176,7 @@ module.exports = (function() {
* @param {Boolean} [options.plain=false] If set to true, included instances will be returned as plain objects * @param {Boolean} [options.plain=false] If set to true, included instances will be returned as plain objects
* @return {Object|any} * @return {Object|any}
*/ */
Instance.prototype.get = function(key, options) { Instance.prototype.get = function(key, options) {
if (options === undefined && typeof key === 'object') { if (options === undefined && typeof key === 'object') {
options = key; options = key;
key = undefined; key = undefined;
...@@ -181,9 +232,9 @@ module.exports = (function() { ...@@ -181,9 +232,9 @@ module.exports = (function() {
return values; return values;
} }
return this.dataValues; return this.dataValues;
}; };
/** /**
* Set is used to update values on the instance (the sequelize representation of the instance that is, remember that nothing will be persisted before you actually call `save`). * Set is used to update values on the instance (the sequelize representation of the instance that is, remember that nothing will be persisted before you actually call `save`).
* In its most basic form `set` will update a value stored in the underlying `dataValues` object. However, if a custom setter function is defined for the key, that function * In its most basic form `set` will update a value stored in the underlying `dataValues` object. However, if a custom setter function is defined for the key, that function
* will be called instead. To bypass the setter, you can pass `raw: true` in the options object. * will be called instead. To bypass the setter, you can pass `raw: true` in the options object.
...@@ -207,7 +258,7 @@ module.exports = (function() { ...@@ -207,7 +258,7 @@ module.exports = (function() {
* @param {Boolean} [options.reset=false] Clear all previously set data values * @param {Boolean} [options.reset=false] Clear all previously set data values
* @alias setAttributes * @alias setAttributes
*/ */
Instance.prototype.set = function(key, value, options) { Instance.prototype.set = function(key, value, options) {
var values var values
, originalValue , originalValue
, keys , keys
...@@ -331,13 +382,13 @@ module.exports = (function() { ...@@ -331,13 +382,13 @@ module.exports = (function() {
} }
return this; return this;
}; };
Instance.prototype.setAttributes = function(updates) { Instance.prototype.setAttributes = function(updates) {
return this.set(updates); return this.set(updates);
}; };
/** /**
* If changed is called with a string it will return a boolean indicating whether the value of that key in `dataValues` is different from the value in `_previousDataValues`. * If changed is called with a string it will return a boolean indicating whether the value of that key in `dataValues` is different from the value in `_previousDataValues`.
* *
* If changed is called without an argument, it will return an array of keys that have changed. * If changed is called without an argument, it will return an array of keys that have changed.
...@@ -347,7 +398,7 @@ module.exports = (function() { ...@@ -347,7 +398,7 @@ module.exports = (function() {
* @param {String} [key] * @param {String} [key]
* @return {Boolean|Array} * @return {Boolean|Array}
*/ */
Instance.prototype.changed = function(key, value) { Instance.prototype.changed = function(key, value) {
if (key) { if (key) {
if (value !== undefined) { if (value !== undefined) {
this._changed[key] = value; this._changed[key] = value;
...@@ -361,18 +412,18 @@ module.exports = (function() { ...@@ -361,18 +412,18 @@ module.exports = (function() {
}.bind(this)); }.bind(this));
return changed.length ? changed : false; return changed.length ? changed : false;
}; };
/** /**
* Returns the previous value for key from `_previousDataValues`. * Returns the previous value for key from `_previousDataValues`.
* @param {String} key * @param {String} key
* @return {any} * @return {any}
*/ */
Instance.prototype.previous = function(key) { Instance.prototype.previous = function(key) {
return this._previousDataValues[key]; return this._previousDataValues[key];
}; };
Instance.prototype._setInclude = function(key, value, options) { Instance.prototype._setInclude = function(key, value, options) {
if (!Array.isArray(value)) value = [value]; if (!Array.isArray(value)) value = [value];
if (value[0] instanceof Instance) { if (value[0] instanceof Instance) {
value = value.map(function(instance) { value = value.map(function(instance) {
...@@ -412,9 +463,9 @@ module.exports = (function() { ...@@ -412,9 +463,9 @@ module.exports = (function() {
self[accessor] = self.dataValues[accessor] = isEmpty ? [] : include.model.bulkBuild(value, childOptions); self[accessor] = self.dataValues[accessor] = isEmpty ? [] : include.model.bulkBuild(value, childOptions);
} }
} }
}; };
/** /**
* Validate this instance, and if the validation passes, persist it to the database. * Validate this instance, and if the validation passes, persist it to the database.
* *
* On success, the callback will be called with this instance. On validation error, the callback will be called with an instance of `Sequelize.ValidationError`. * On success, the callback will be called with this instance. On validation error, the callback will be called with an instance of `Sequelize.ValidationError`.
...@@ -429,7 +480,7 @@ module.exports = (function() { ...@@ -429,7 +480,7 @@ module.exports = (function() {
* *
* @return {Promise<this|Errors.ValidationError>} * @return {Promise<this|Errors.ValidationError>}
*/ */
Instance.prototype.save = function(options) { Instance.prototype.save = function(options) {
if (arguments.length > 1) { if (arguments.length > 1) {
throw new Error('The second argument was removed in favor of the options object.'); throw new Error('The second argument was removed in favor of the options object.');
} }
...@@ -661,19 +712,19 @@ module.exports = (function() { ...@@ -661,19 +712,19 @@ module.exports = (function() {
}); });
}); });
}); });
}; };
/* /*
* Refresh the current instance in-place, i.e. update the object with current data from the DB and return the same object. * Refresh the current instance in-place, i.e. update the object with current data from the DB and return the same object.
* This is different from doing a `find(Instance.id)`, because that would create and return a new instance. With this method, * This is different from doing a `find(Instance.id)`, because that would create and return a new instance. With this method,
* all references to the Instance are updated with the new data and no new objects are created. * all references to the Instance are updated with the new data and no new objects are created.
* *
* @see {Model#find} * @see {Model#find}
* @param {Object} [options] Options that are passed on to `Model.find` * @param {Object} [options] Options that are passed on to `Model.find`
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql. * @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @return {Promise<this>} * @return {Promise<this>}
*/ */
Instance.prototype.reload = function(options) { Instance.prototype.reload = function(options) {
var self = this var self = this
, where = [ , where = [
this.sequelize.getQueryInterface().quoteTable(this.Model.name) + '.' + this.sequelize.getQueryInterface().quoteIdentifier(this.Model.primaryKeyField) + '=?', this.sequelize.getQueryInterface().quoteTable(this.Model.name) + '.' + this.sequelize.getQueryInterface().quoteIdentifier(this.Model.primaryKeyField) + '=?',
...@@ -689,9 +740,9 @@ module.exports = (function() { ...@@ -689,9 +740,9 @@ module.exports = (function() {
return this.Model.findOne(options).then(function(reload) { return this.Model.findOne(options).then(function(reload) {
self.set(reload.dataValues, {raw: true, reset: true}); self.set(reload.dataValues, {raw: true, reset: true});
}).return(self); }).return(self);
}; };
/* /*
* Validate the attribute of this instance according to validation rules set in the model definition. * Validate the attribute of this instance according to validation rules set in the model definition.
* *
* Emits null if and only if validation successful; otherwise an Error instance containing { field name : [error msgs] } entries. * Emits null if and only if validation successful; otherwise an Error instance containing { field name : [error msgs] } entries.
...@@ -702,15 +753,15 @@ module.exports = (function() { ...@@ -702,15 +753,15 @@ module.exports = (function() {
* *
* @return {Promise<undefined|Errors.ValidationError>} * @return {Promise<undefined|Errors.ValidationError>}
*/ */
Instance.prototype.validate = function(options) { Instance.prototype.validate = function(options) {
return new InstanceValidator(this, options).validate(); return new InstanceValidator(this, options).validate();
}; };
Instance.prototype.hookValidate = function(options) { Instance.prototype.hookValidate = function(options) {
return new InstanceValidator(this, options).hookValidate(); return new InstanceValidator(this, options).hookValidate();
}; };
/** /**
* This is the same as calling `set` and then calling `save`. * This is the same as calling `set` and then calling `save`.
* *
* @see {Instance#set} * @see {Instance#set}
...@@ -721,7 +772,7 @@ module.exports = (function() { ...@@ -721,7 +772,7 @@ module.exports = (function() {
* @return {Promise<this>} * @return {Promise<this>}
* @alias updateAttributes * @alias updateAttributes
*/ */
Instance.prototype.update = function(values, options) { Instance.prototype.update = function(values, options) {
var changedBefore = this.changed() || [] var changedBefore = this.changed() || []
, sideEffects , sideEffects
, fields; , fields;
...@@ -741,10 +792,10 @@ module.exports = (function() { ...@@ -741,10 +792,10 @@ module.exports = (function() {
} }
return this.save(options); return this.save(options);
}; };
Instance.prototype.updateAttributes = Instance.prototype.update; Instance.prototype.updateAttributes = Instance.prototype.update;
/** /**
* Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will either be completely deleted, or have its deletedAt timestamp set to the current time. * Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will either be completely deleted, or have its deletedAt timestamp set to the current time.
* *
* @param {Object} [options={}] * @param {Object} [options={}]
...@@ -754,7 +805,7 @@ module.exports = (function() { ...@@ -754,7 +805,7 @@ module.exports = (function() {
* *
* @return {Promise<undefined>} * @return {Promise<undefined>}
*/ */
Instance.prototype.destroy = function(options) { Instance.prototype.destroy = function(options) {
options = Utils._.extend({ options = Utils._.extend({
hooks: true, hooks: true,
force: false force: false
...@@ -787,9 +838,9 @@ module.exports = (function() { ...@@ -787,9 +838,9 @@ module.exports = (function() {
}).then(function(result) { }).then(function(result) {
return result; return result;
}); });
}; };
/** /**
* Restore the row corresponding to this instance. Only available for paranoid models. * Restore the row corresponding to this instance. Only available for paranoid models.
* *
* @param {Object} [options={}] * @param {Object} [options={}]
...@@ -798,7 +849,7 @@ module.exports = (function() { ...@@ -798,7 +849,7 @@ module.exports = (function() {
* *
* @return {Promise<undefined>} * @return {Promise<undefined>}
*/ */
Instance.prototype.restore = function(options) { Instance.prototype.restore = function(options) {
if (!this.Model._timestampAttributes.deletedAt) throw new Error('Model is not paranoid'); if (!this.Model._timestampAttributes.deletedAt) throw new Error('Model is not paranoid');
options = Utils._.extend({ options = Utils._.extend({
...@@ -820,9 +871,9 @@ module.exports = (function() { ...@@ -820,9 +871,9 @@ module.exports = (function() {
return this.Model.runHooks('afterRestore', this, options); return this.Model.runHooks('afterRestore', this, options);
} }
}); });
}; };
/** /**
* Increment the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The increment is done using a * Increment the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The increment is done using a
* ```sql * ```sql
* SET column = column + X * SET column = column + X
...@@ -845,7 +896,7 @@ module.exports = (function() { ...@@ -845,7 +896,7 @@ module.exports = (function() {
* *
* @return {Promise<this>} * @return {Promise<this>}
*/ */
Instance.prototype.increment = function(fields, options) { Instance.prototype.increment = function(fields, options) {
var identifier = this.where() var identifier = this.where()
, updatedAtAttr = this.Model._timestampAttributes.updatedAt , updatedAtAttr = this.Model._timestampAttributes.updatedAt
, values = {} , values = {}
...@@ -893,9 +944,9 @@ module.exports = (function() { ...@@ -893,9 +944,9 @@ module.exports = (function() {
}, this); }, this);
return this.sequelize.getQueryInterface().increment(this, this.Model.getTableName(options), values, where, options).return(this); return this.sequelize.getQueryInterface().increment(this, this.Model.getTableName(options), values, where, options).return(this);
}; };
/** /**
* Decrement the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The decrement is done using a * Decrement the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The decrement is done using a
* ```sql * ```sql
* SET column = column - X * SET column = column - X
...@@ -918,7 +969,7 @@ module.exports = (function() { ...@@ -918,7 +969,7 @@ module.exports = (function() {
* *
* @return {Promise} * @return {Promise}
*/ */
Instance.prototype.decrement = function(fields, options) { Instance.prototype.decrement = function(fields, options) {
options = _.defaults(options || {}, { options = _.defaults(options || {}, {
by: 1 by: 1
}); });
...@@ -932,15 +983,15 @@ module.exports = (function() { ...@@ -932,15 +983,15 @@ module.exports = (function() {
options.by = 0 - options.by; options.by = 0 - options.by;
return this.increment(fields, options); return this.increment(fields, options);
}; };
/** /**
* Check whether all values of this and `other` Instance are the same * Check whether all values of this and `other` Instance are the same
* *
* @param {Instance} other * @param {Instance} other
* @return {Boolean} * @return {Boolean}
*/ */
Instance.prototype.equals = function(other) { Instance.prototype.equals = function(other) {
var result = true; var result = true;
Utils._.each(this.dataValues, function(value, key) { Utils._.each(this.dataValues, function(value, key) {
...@@ -952,89 +1003,36 @@ module.exports = (function() { ...@@ -952,89 +1003,36 @@ module.exports = (function() {
}); });
return result; return result;
}; };
/** /**
* Check if this is eqaul to one of `others` by calling equals * Check if this is eqaul to one of `others` by calling equals
* *
* @param {Array} others * @param {Array} others
* @return {Boolean} * @return {Boolean}
*/ */
Instance.prototype.equalsOneOf = function(others) { Instance.prototype.equalsOneOf = function(others) {
var self = this; var self = this;
return _.any(others, function(other) { return _.any(others, function(other) {
return self.equals(other); return self.equals(other);
}); });
}; };
Instance.prototype.setValidators = function(attribute, validators) { Instance.prototype.setValidators = function(attribute, validators) {
this.validators[attribute] = validators; this.validators[attribute] = validators;
}; };
/** /**
* Convert the instance to a JSON representation. Proxies to calling `get` with no keys. This means get all values gotten from the DB, and apply all custom getters. * Convert the instance to a JSON representation. Proxies to calling `get` with no keys. This means get all values gotten from the DB, and apply all custom getters.
* *
* @see {Instance#get} * @see {Instance#get}
* @return {object} * @return {object}
*/ */
Instance.prototype.toJSON = function() { Instance.prototype.toJSON = function() {
return this.get({ return this.get({
plain: true plain: true
}); });
}; };
// private
var initValues = function(values, options) {
var defaults
, key;
values = values && _.clone(values) || {};
if (options.isNewRecord) {
defaults = {};
if (this.Model._hasDefaultValues) {
Utils._.each(this.Model._defaultValues, function(valueFn, key) {
if (defaults[key] === undefined) {
defaults[key] = valueFn();
}
});
}
// set id to null if not passed as value, a newly created dao has no id
// removing this breaks bulkCreate
// do after default values since it might have UUID as a default value
if (!defaults.hasOwnProperty(this.Model.primaryKeyAttribute)) {
defaults[this.Model.primaryKeyAttribute] = null;
}
if (this.Model._timestampAttributes.createdAt && defaults[this.Model._timestampAttributes.createdAt]) {
this.dataValues[this.Model._timestampAttributes.createdAt] = Utils.toDefaultValue(defaults[this.Model._timestampAttributes.createdAt]);
delete defaults[this.Model._timestampAttributes.createdAt];
}
if (this.Model._timestampAttributes.updatedAt && defaults[this.Model._timestampAttributes.updatedAt]) {
this.dataValues[this.Model._timestampAttributes.updatedAt] = Utils.toDefaultValue(defaults[this.Model._timestampAttributes.updatedAt]);
delete defaults[this.Model._timestampAttributes.updatedAt];
}
if (this.Model._timestampAttributes.deletedAt && defaults[this.Model._timestampAttributes.deletedAt]) {
this.dataValues[this.Model._timestampAttributes.deletedAt] = Utils.toDefaultValue(defaults[this.Model._timestampAttributes.deletedAt]);
delete defaults[this.Model._timestampAttributes.deletedAt];
}
if (Object.keys(defaults).length) {
for (key in defaults) {
if (values[key] === undefined) {
this.set(key, Utils.toDefaultValue(defaults[key]), defaultsOptions);
}
}
}
}
this.set(values, options);
};
return Instance; module.exports = Instance;
})();
...@@ -4,28 +4,27 @@ var Toposort = require('toposort-class') ...@@ -4,28 +4,27 @@ var Toposort = require('toposort-class')
, Utils = require('./utils') , Utils = require('./utils')
, _ = require('lodash'); , _ = require('lodash');
module.exports = (function() { var ModelManager = function(sequelize) {
var ModelManager = function(sequelize) {
this.models = []; this.models = [];
this.sequelize = sequelize; this.sequelize = sequelize;
}; };
ModelManager.prototype.addModel = function(model) { ModelManager.prototype.addModel = function(model) {
this.models.push(model); this.models.push(model);
this.sequelize.models[model.name] = model; this.sequelize.models[model.name] = model;
return model; return model;
}; };
ModelManager.prototype.removeModel = function(model) { ModelManager.prototype.removeModel = function(model) {
this.models = this.models.filter(function($model) { this.models = this.models.filter(function($model) {
return $model.name !== model.name; return $model.name !== model.name;
}); });
delete this.sequelize.models[model.name]; delete this.sequelize.models[model.name];
}; };
ModelManager.prototype.getModel = function(against, options) { ModelManager.prototype.getModel = function(against, options) {
options = _.defaults(options || {}, { options = _.defaults(options || {}, {
attribute: 'name' attribute: 'name'
}); });
...@@ -35,18 +34,18 @@ module.exports = (function() { ...@@ -35,18 +34,18 @@ module.exports = (function() {
}); });
return !!model ? model[0] : null; return !!model ? model[0] : null;
}; };
ModelManager.prototype.__defineGetter__('all', function() { ModelManager.prototype.__defineGetter__('all', function() {
return this.models; return this.models;
}); });
/** /**
* Iterate over Models in an order suitable for e.g. creating tables. Will * Iterate over Models in an order suitable for e.g. creating tables. Will
* take foreign key constraints into account so that dependencies are visited * take foreign key constraints into account so that dependencies are visited
* before dependents. * before dependents.
*/ */
ModelManager.prototype.forEachModel = function(iterator, options) { ModelManager.prototype.forEachModel = function(iterator, options) {
var models = {} var models = {}
, sorter = new Toposort() , sorter = new Toposort()
, sorted , sorted
...@@ -97,7 +96,6 @@ module.exports = (function() { ...@@ -97,7 +96,6 @@ module.exports = (function() {
sorted.forEach(function(name) { sorted.forEach(function(name) {
iterator(models[name], name); iterator(models[name], name);
}); });
}; };
return ModelManager; module.exports = ModelManager;
})();
This diff could not be displayed because it is too large.
'use strict'; 'use strict';
module.exports = (function() { var Attribute = function(options) {
var Attribute = function(options) {
if (options.type === undefined) options = {type: options}; if (options.type === undefined) options = {type: options};
this.type = options.type; this.type = options.type;
}; };
return Attribute; module.exports = Attribute;
})();
...@@ -5,8 +5,7 @@ var Utils = require('./../utils') ...@@ -5,8 +5,7 @@ var Utils = require('./../utils')
, DataTypes = require('../data-types') , DataTypes = require('../data-types')
, Promise = require('bluebird'); , Promise = require('bluebird');
module.exports = (function() { var CounterCache = function(association, options) {
var CounterCache = function(association, options) {
this.association = association; this.association = association;
this.source = association.source; this.source = association.source;
this.target = association.target; this.target = association.target;
...@@ -32,10 +31,10 @@ module.exports = (function() { ...@@ -32,10 +31,10 @@ module.exports = (function() {
this.injectAttributes(); this.injectAttributes();
this.injectHooks(); this.injectHooks();
}; };
// Add countAssociation attribute to source model // Add countAssociation attribute to source model
CounterCache.prototype.injectAttributes = function() { CounterCache.prototype.injectAttributes = function() {
// Do not try to use a column that's already taken // Do not try to use a column that's already taken
Helpers.checkNamingCollision(this); Helpers.checkNamingCollision(this);
...@@ -54,10 +53,10 @@ module.exports = (function() { ...@@ -54,10 +53,10 @@ module.exports = (function() {
// Sync attributes and setters/getters to DAO prototype // Sync attributes and setters/getters to DAO prototype
this.source.refreshAttributes(); this.source.refreshAttributes();
}; };
// Add setAssociaton method to the prototype of the model instance // Add setAssociaton method to the prototype of the model instance
CounterCache.prototype.injectHooks = function() { CounterCache.prototype.injectHooks = function() {
var association = this.association, var association = this.association,
counterCacheInstance = this, counterCacheInstance = this,
CounterUtil, CounterUtil,
...@@ -173,7 +172,6 @@ module.exports = (function() { ...@@ -173,7 +172,6 @@ module.exports = (function() {
association.target.addHook('afterUpdate', atomicHooks.update); association.target.addHook('afterUpdate', atomicHooks.update);
association.target.addHook('afterDestroy', atomicHooks.destroy); association.target.addHook('afterDestroy', atomicHooks.destroy);
} }
}; };
return CounterCache; module.exports = CounterCache;
})();
...@@ -8,29 +8,28 @@ var Utils = require('./utils') ...@@ -8,29 +8,28 @@ var Utils = require('./utils')
, Promise = require('./promise') , Promise = require('./promise')
, QueryTypes = require('./query-types'); , QueryTypes = require('./query-types');
module.exports = (function() { /*
/*
* The interface that Sequelize uses to talk to all databases * The interface that Sequelize uses to talk to all databases
* @class QueryInterface * @class QueryInterface
**/ **/
var QueryInterface = function(sequelize) { var QueryInterface = function(sequelize) {
this.sequelize = sequelize; this.sequelize = sequelize;
this.QueryGenerator = this.sequelize.dialect.QueryGenerator; this.QueryGenerator = this.sequelize.dialect.QueryGenerator;
}; };
QueryInterface.prototype.createSchema = function(schema, options) { QueryInterface.prototype.createSchema = function(schema, options) {
options = options || {}; options = options || {};
var sql = this.QueryGenerator.createSchema(schema); var sql = this.QueryGenerator.createSchema(schema);
return this.sequelize.query(sql, {logging: options.logging}); return this.sequelize.query(sql, {logging: options.logging});
}; };
QueryInterface.prototype.dropSchema = function(schema, options) { QueryInterface.prototype.dropSchema = function(schema, options) {
options = options || {}; options = options || {};
var sql = this.QueryGenerator.dropSchema(schema); var sql = this.QueryGenerator.dropSchema(schema);
return this.sequelize.query(sql, {logging: options.logging}); return this.sequelize.query(sql, {logging: options.logging});
}; };
QueryInterface.prototype.dropAllSchemas = function(options) { QueryInterface.prototype.dropAllSchemas = function(options) {
options = options || {}; options = options || {};
var self = this; var self = this;
...@@ -41,9 +40,9 @@ module.exports = (function() { ...@@ -41,9 +40,9 @@ module.exports = (function() {
return self.dropSchema(schemaName, { logging: options.logging }); return self.dropSchema(schemaName, { logging: options.logging });
}); });
} }
}; };
QueryInterface.prototype.showAllSchemas = function(options) { QueryInterface.prototype.showAllSchemas = function(options) {
var self = this; var self = this;
options = Utils._.extend({ options = Utils._.extend({
...@@ -61,18 +60,18 @@ module.exports = (function() { ...@@ -61,18 +60,18 @@ module.exports = (function() {
}) })
); );
}); });
}; };
QueryInterface.prototype.databaseVersion = function(options) { QueryInterface.prototype.databaseVersion = function(options) {
options = options || {}; options = options || {};
return this.sequelize.query(this.QueryGenerator.versionQuery(), { return this.sequelize.query(this.QueryGenerator.versionQuery(), {
raw: true, raw: true,
type: QueryTypes.VERSION, type: QueryTypes.VERSION,
logging: options.logging logging: options.logging
}); });
}; };
QueryInterface.prototype.createTable = function(tableName, attributes, options) { QueryInterface.prototype.createTable = function(tableName, attributes, options) {
var keys = Object.keys(attributes) var keys = Object.keys(attributes)
, keyLen = keys.length , keyLen = keys.length
, self = this , self = this
...@@ -192,9 +191,9 @@ module.exports = (function() { ...@@ -192,9 +191,9 @@ module.exports = (function() {
return self.sequelize.query(sql, options); return self.sequelize.query(sql, options);
} }
}; };
QueryInterface.prototype.dropTable = function(tableName, options) { QueryInterface.prototype.dropTable = function(tableName, options) {
// if we're forcing we should be cascading unless explicitly stated otherwise // if we're forcing we should be cascading unless explicitly stated otherwise
options = options || {}; options = options || {};
options.cascade = options.cascade || options.force || false; options.cascade = options.cascade || options.force || false;
...@@ -227,9 +226,9 @@ module.exports = (function() { ...@@ -227,9 +226,9 @@ module.exports = (function() {
return Promise.all(promises).get(0); return Promise.all(promises).get(0);
}); });
}; };
QueryInterface.prototype.dropAllTables = function(options) { QueryInterface.prototype.dropAllTables = function(options) {
var self = this; var self = this;
options = options || {}; options = options || {};
...@@ -281,9 +280,9 @@ module.exports = (function() { ...@@ -281,9 +280,9 @@ module.exports = (function() {
}); });
} }
}); });
}; };
QueryInterface.prototype.dropAllEnums = function(options) { QueryInterface.prototype.dropAllEnums = function(options) {
if (this.sequelize.getDialect() !== 'postgres') { if (this.sequelize.getDialect() !== 'postgres') {
return Promise.resolve(); return Promise.resolve();
} }
...@@ -299,15 +298,15 @@ module.exports = (function() { ...@@ -299,15 +298,15 @@ module.exports = (function() {
{logging: options.logging, raw: true} {logging: options.logging, raw: true}
); );
}); });
}; };
QueryInterface.prototype.renameTable = function(before, after, options) { QueryInterface.prototype.renameTable = function(before, after, options) {
options = options || {}; options = options || {};
var sql = this.QueryGenerator.renameTableQuery(before, after); var sql = this.QueryGenerator.renameTableQuery(before, after);
return this.sequelize.query(sql, { logging: options.logging }); return this.sequelize.query(sql, { logging: options.logging });
}; };
QueryInterface.prototype.showAllTables = function(options) { QueryInterface.prototype.showAllTables = function(options) {
var self = this; var self = this;
options = Utils._.extend({ options = Utils._.extend({
raw: true, raw: true,
...@@ -318,9 +317,9 @@ module.exports = (function() { ...@@ -318,9 +317,9 @@ module.exports = (function() {
return self.sequelize.query(showTablesSql, options).then(function(tableNames) { return self.sequelize.query(showTablesSql, options).then(function(tableNames) {
return Utils._.flatten(tableNames); return Utils._.flatten(tableNames);
}); });
}; };
QueryInterface.prototype.describeTable = function(tableName, options) { QueryInterface.prototype.describeTable = function(tableName, options) {
var schema = null var schema = null
, schemaDelimiter = null; , schemaDelimiter = null;
...@@ -348,15 +347,15 @@ module.exports = (function() { ...@@ -348,15 +347,15 @@ module.exports = (function() {
return Promise.resolve(data); return Promise.resolve(data);
} }
}); });
}; };
QueryInterface.prototype.addColumn = function(table, key, attribute, options) { QueryInterface.prototype.addColumn = function(table, key, attribute, options) {
options = options || {}; options = options || {};
attribute = this.sequelize.normalizeAttribute(attribute); attribute = this.sequelize.normalizeAttribute(attribute);
return this.sequelize.query(this.QueryGenerator.addColumnQuery(table, key, attribute), { logging: options.logging }); return this.sequelize.query(this.QueryGenerator.addColumnQuery(table, key, attribute), { logging: options.logging });
}; };
QueryInterface.prototype.removeColumn = function(tableName, attributeName, options) { QueryInterface.prototype.removeColumn = function(tableName, attributeName, options) {
options = options || {}; options = options || {};
if (this.sequelize.options.dialect === 'sqlite') { if (this.sequelize.options.dialect === 'sqlite') {
// sqlite needs some special treatment as it cannot drop a column // sqlite needs some special treatment as it cannot drop a column
...@@ -365,9 +364,9 @@ module.exports = (function() { ...@@ -365,9 +364,9 @@ module.exports = (function() {
var sql = this.QueryGenerator.removeColumnQuery(tableName, attributeName); var sql = this.QueryGenerator.removeColumnQuery(tableName, attributeName);
return this.sequelize.query(sql, {logging: options.logging}); return this.sequelize.query(sql, {logging: options.logging});
} }
}; };
QueryInterface.prototype.changeColumn = function(tableName, attributeName, dataTypeOrOptions, options) { QueryInterface.prototype.changeColumn = function(tableName, attributeName, dataTypeOrOptions, options) {
var attributes = {}; var attributes = {};
options = options || {}; options = options || {};
...@@ -388,9 +387,9 @@ module.exports = (function() { ...@@ -388,9 +387,9 @@ module.exports = (function() {
return this.sequelize.query(sql, {logging: options.logging}); return this.sequelize.query(sql, {logging: options.logging});
} }
}; };
QueryInterface.prototype.renameColumn = function(tableName, attrNameBefore, attrNameAfter, options) { QueryInterface.prototype.renameColumn = function(tableName, attrNameBefore, attrNameAfter, options) {
options = options || {}; options = options || {};
return this.describeTable(tableName, options).then(function(data) { return this.describeTable(tableName, options).then(function(data) {
data = data[attrNameBefore] || {}; data = data[attrNameBefore] || {};
...@@ -421,9 +420,9 @@ module.exports = (function() { ...@@ -421,9 +420,9 @@ module.exports = (function() {
return this.sequelize.query(sql, {logging: options.logging}); return this.sequelize.query(sql, {logging: options.logging});
} }
}.bind(this)); }.bind(this));
}; };
QueryInterface.prototype.addIndex = function(tableName, _attributes, options, _rawTablename) { QueryInterface.prototype.addIndex = function(tableName, _attributes, options, _rawTablename) {
var attributes, rawTablename; var attributes, rawTablename;
// Support for passing tableName, attributes, options or tableName, options (with a fields param which is the attributes) // Support for passing tableName, attributes, options or tableName, options (with a fields param which is the attributes)
...@@ -448,9 +447,9 @@ module.exports = (function() { ...@@ -448,9 +447,9 @@ module.exports = (function() {
options.fields = attributes; options.fields = attributes;
var sql = this.QueryGenerator.addIndexQuery(tableName, options, rawTablename); var sql = this.QueryGenerator.addIndexQuery(tableName, options, rawTablename);
return this.sequelize.query(sql, { logging: options.logging }); return this.sequelize.query(sql, { logging: options.logging });
}; };
QueryInterface.prototype.showIndex = function(tableName, options) { QueryInterface.prototype.showIndex = function(tableName, options) {
var sql = this.QueryGenerator.showIndexesQuery(tableName, options); var sql = this.QueryGenerator.showIndexesQuery(tableName, options);
options = options || {}; options = options || {};
return this.sequelize.query(sql, { return this.sequelize.query(sql, {
...@@ -458,13 +457,13 @@ module.exports = (function() { ...@@ -458,13 +457,13 @@ module.exports = (function() {
logging: options.logging, logging: options.logging,
type: QueryTypes.SHOWINDEXES type: QueryTypes.SHOWINDEXES
}); });
}; };
QueryInterface.prototype.nameIndexes = function(indexes, rawTablename) { QueryInterface.prototype.nameIndexes = function(indexes, rawTablename) {
return this.QueryGenerator.nameIndexes(indexes, rawTablename); return this.QueryGenerator.nameIndexes(indexes, rawTablename);
}; };
QueryInterface.prototype.getForeignKeysForTables = function(tableNames, options) { QueryInterface.prototype.getForeignKeysForTables = function(tableNames, options) {
var self = this; var self = this;
options = options || {}; options = options || {};
...@@ -489,15 +488,15 @@ module.exports = (function() { ...@@ -489,15 +488,15 @@ module.exports = (function() {
return result; return result;
}); });
}; };
QueryInterface.prototype.removeIndex = function(tableName, indexNameOrAttributes, options) { QueryInterface.prototype.removeIndex = function(tableName, indexNameOrAttributes, options) {
options = options || {}; options = options || {};
var sql = this.QueryGenerator.removeIndexQuery(tableName, indexNameOrAttributes); var sql = this.QueryGenerator.removeIndexQuery(tableName, indexNameOrAttributes);
return this.sequelize.query(sql, {logging: options.logging}); return this.sequelize.query(sql, {logging: options.logging});
}; };
QueryInterface.prototype.insert = function(instance, tableName, values, options) { QueryInterface.prototype.insert = function(instance, tableName, values, options) {
var sql = this.QueryGenerator.insertQuery(tableName, values, instance && instance.Model.rawAttributes, options); var sql = this.QueryGenerator.insertQuery(tableName, values, instance && instance.Model.rawAttributes, options);
options.type = QueryTypes.INSERT; options.type = QueryTypes.INSERT;
...@@ -506,9 +505,9 @@ module.exports = (function() { ...@@ -506,9 +505,9 @@ module.exports = (function() {
if (instance) result.isNewRecord = false; if (instance) result.isNewRecord = false;
return result; return result;
}); });
}; };
QueryInterface.prototype.upsert = function(tableName, values, model, options) { QueryInterface.prototype.upsert = function(tableName, values, model, options) {
var wheres = [] var wheres = []
, where , where
, indexFields , indexFields
...@@ -581,15 +580,15 @@ module.exports = (function() { ...@@ -581,15 +580,15 @@ module.exports = (function() {
return rowCount === 1; return rowCount === 1;
}); });
}; };
QueryInterface.prototype.bulkInsert = function(tableName, records, options, attributes) { QueryInterface.prototype.bulkInsert = function(tableName, records, options, attributes) {
options.type = QueryTypes.INSERT; options.type = QueryTypes.INSERT;
var sql = this.QueryGenerator.bulkInsertQuery(tableName, records, options, attributes); var sql = this.QueryGenerator.bulkInsertQuery(tableName, records, options, attributes);
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}; };
QueryInterface.prototype.update = function(instance, tableName, values, identifier, options) { QueryInterface.prototype.update = function(instance, tableName, values, identifier, options) {
var self = this var self = this
, restrict = false , restrict = false
, sql = self.QueryGenerator.updateQuery(tableName, values, identifier, options, instance.Model.rawAttributes); , sql = self.QueryGenerator.updateQuery(tableName, values, identifier, options, instance.Model.rawAttributes);
...@@ -611,9 +610,9 @@ module.exports = (function() { ...@@ -611,9 +610,9 @@ module.exports = (function() {
options.instance = instance; options.instance = instance;
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}; };
QueryInterface.prototype.bulkUpdate = function(tableName, values, identifier, options, attributes) { QueryInterface.prototype.bulkUpdate = function(tableName, values, identifier, options, attributes) {
var sql = this.QueryGenerator.updateQuery(tableName, values, identifier, options, attributes) var sql = this.QueryGenerator.updateQuery(tableName, values, identifier, options, attributes)
, table = Utils._.isObject(tableName) ? tableName : { tableName: tableName } , table = Utils._.isObject(tableName) ? tableName : { tableName: tableName }
, model = Utils._.find(this.sequelize.modelManager.models, { tableName: table.tableName }); , model = Utils._.find(this.sequelize.modelManager.models, { tableName: table.tableName });
...@@ -621,9 +620,9 @@ module.exports = (function() { ...@@ -621,9 +620,9 @@ module.exports = (function() {
options = options || {}; options = options || {};
options.model = model; options.model = model;
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}; };
QueryInterface.prototype.delete = function(instance, tableName, identifier, options) { QueryInterface.prototype.delete = function(instance, tableName, identifier, options) {
var self = this var self = this
, cascades = [] , cascades = []
, sql = self.QueryGenerator.deleteQuery(tableName, identifier, null, instance.Model); , sql = self.QueryGenerator.deleteQuery(tableName, identifier, null, instance.Model);
...@@ -662,14 +661,14 @@ module.exports = (function() { ...@@ -662,14 +661,14 @@ module.exports = (function() {
options.instance = instance; options.instance = instance;
return self.sequelize.query(sql, options); return self.sequelize.query(sql, options);
}); });
}; };
QueryInterface.prototype.bulkDelete = function(tableName, identifier, options, model) { QueryInterface.prototype.bulkDelete = function(tableName, identifier, options, model) {
var sql = this.QueryGenerator.deleteQuery(tableName, identifier, Utils._.defaults(options || {}, {limit: null}), model); var sql = this.QueryGenerator.deleteQuery(tableName, identifier, Utils._.defaults(options || {}, {limit: null}), model);
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}; };
QueryInterface.prototype.select = function(model, tableName, options) { QueryInterface.prototype.select = function(model, tableName, options) {
options = options || {}; options = options || {};
options.type = QueryTypes.SELECT; options.type = QueryTypes.SELECT;
options.model = model; options.model = model;
...@@ -677,9 +676,9 @@ module.exports = (function() { ...@@ -677,9 +676,9 @@ module.exports = (function() {
this.QueryGenerator.selectQuery(tableName, options, model), this.QueryGenerator.selectQuery(tableName, options, model),
options options
); );
}; };
QueryInterface.prototype.increment = function(instance, tableName, values, identifier, options) { QueryInterface.prototype.increment = function(instance, tableName, values, identifier, options) {
var sql = this.QueryGenerator.incrementQuery(tableName, values, identifier, options.attributes); var sql = this.QueryGenerator.incrementQuery(tableName, values, identifier, options.attributes);
options = options || {}; options = options || {};
...@@ -687,9 +686,9 @@ module.exports = (function() { ...@@ -687,9 +686,9 @@ module.exports = (function() {
options.type = QueryTypes.RAW; options.type = QueryTypes.RAW;
options.instance = instance; options.instance = instance;
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}; };
QueryInterface.prototype.rawSelect = function(tableName, options, attributeSelector, Model) { QueryInterface.prototype.rawSelect = function(tableName, options, attributeSelector, Model) {
if (options.schema) { if (options.schema) {
tableName = this.QueryGenerator.addSchema({ tableName = this.QueryGenerator.addSchema({
tableName: tableName, tableName: tableName,
...@@ -734,9 +733,9 @@ module.exports = (function() { ...@@ -734,9 +733,9 @@ module.exports = (function() {
return result; return result;
}); });
}; };
QueryInterface.prototype.createTrigger = function(tableName, triggerName, timingType, fireOnArray, functionName, functionParams, optionsArray, options) { QueryInterface.prototype.createTrigger = function(tableName, triggerName, timingType, fireOnArray, functionName, functionParams, optionsArray, options) {
var sql = this.QueryGenerator.createTrigger(tableName, triggerName, timingType, fireOnArray, functionName, functionParams, optionsArray); var sql = this.QueryGenerator.createTrigger(tableName, triggerName, timingType, fireOnArray, functionName, functionParams, optionsArray);
options = options || {}; options = options || {};
if (sql) { if (sql) {
...@@ -744,9 +743,9 @@ module.exports = (function() { ...@@ -744,9 +743,9 @@ module.exports = (function() {
} else { } else {
return Promise.resolve(); return Promise.resolve();
} }
}; };
QueryInterface.prototype.dropTrigger = function(tableName, triggerName, options) { QueryInterface.prototype.dropTrigger = function(tableName, triggerName, options) {
var sql = this.QueryGenerator.dropTrigger(tableName, triggerName); var sql = this.QueryGenerator.dropTrigger(tableName, triggerName);
options = options || {}; options = options || {};
...@@ -755,9 +754,9 @@ module.exports = (function() { ...@@ -755,9 +754,9 @@ module.exports = (function() {
} else { } else {
return Promise.resolve(); return Promise.resolve();
} }
}; };
QueryInterface.prototype.renameTrigger = function(tableName, oldTriggerName, newTriggerName, options) { QueryInterface.prototype.renameTrigger = function(tableName, oldTriggerName, newTriggerName, options) {
var sql = this.QueryGenerator.renameTrigger(tableName, oldTriggerName, newTriggerName); var sql = this.QueryGenerator.renameTrigger(tableName, oldTriggerName, newTriggerName);
options = options || {}; options = options || {};
...@@ -766,9 +765,9 @@ module.exports = (function() { ...@@ -766,9 +765,9 @@ module.exports = (function() {
} else { } else {
return Promise.resolve(); return Promise.resolve();
} }
}; };
QueryInterface.prototype.createFunction = function(functionName, params, returnType, language, body, options) { QueryInterface.prototype.createFunction = function(functionName, params, returnType, language, body, options) {
var sql = this.QueryGenerator.createFunction(functionName, params, returnType, language, body, options); var sql = this.QueryGenerator.createFunction(functionName, params, returnType, language, body, options);
options = options || {}; options = options || {};
...@@ -777,9 +776,9 @@ module.exports = (function() { ...@@ -777,9 +776,9 @@ module.exports = (function() {
} else { } else {
return Promise.resolve(); return Promise.resolve();
} }
}; };
QueryInterface.prototype.dropFunction = function(functionName, params, options) { QueryInterface.prototype.dropFunction = function(functionName, params, options) {
var sql = this.QueryGenerator.dropFunction(functionName, params); var sql = this.QueryGenerator.dropFunction(functionName, params);
options = options || {}; options = options || {};
...@@ -788,9 +787,9 @@ module.exports = (function() { ...@@ -788,9 +787,9 @@ module.exports = (function() {
} else { } else {
return Promise.resolve(); return Promise.resolve();
} }
}; };
QueryInterface.prototype.renameFunction = function(oldFunctionName, params, newFunctionName, options) { QueryInterface.prototype.renameFunction = function(oldFunctionName, params, newFunctionName, options) {
var sql = this.QueryGenerator.renameFunction(oldFunctionName, params, newFunctionName); var sql = this.QueryGenerator.renameFunction(oldFunctionName, params, newFunctionName);
options = options || {}; options = options || {};
...@@ -799,40 +798,40 @@ module.exports = (function() { ...@@ -799,40 +798,40 @@ module.exports = (function() {
} else { } else {
return Promise.resolve(); return Promise.resolve();
} }
}; };
// Helper methods useful for querying // Helper methods useful for querying
/** /**
* Escape an identifier (e.g. a table or attribute name). If force is true, * Escape an identifier (e.g. a table or attribute name). If force is true,
* the identifier will be quoted even if the `quoteIdentifiers` option is * the identifier will be quoted even if the `quoteIdentifiers` option is
* false. * false.
*/ */
QueryInterface.prototype.quoteIdentifier = function(identifier, force) { QueryInterface.prototype.quoteIdentifier = function(identifier, force) {
return this.QueryGenerator.quoteIdentifier(identifier, force); return this.QueryGenerator.quoteIdentifier(identifier, force);
}; };
QueryInterface.prototype.quoteTable = function(identifier) { QueryInterface.prototype.quoteTable = function(identifier) {
return this.QueryGenerator.quoteTable(identifier); return this.QueryGenerator.quoteTable(identifier);
}; };
/** /**
* Split an identifier into .-separated tokens and quote each part. * Split an identifier into .-separated tokens and quote each part.
* If force is true, the identifier will be quoted even if the * If force is true, the identifier will be quoted even if the
* `quoteIdentifiers` option is false. * `quoteIdentifiers` option is false.
*/ */
QueryInterface.prototype.quoteIdentifiers = function(identifiers, force) { QueryInterface.prototype.quoteIdentifiers = function(identifiers, force) {
return this.QueryGenerator.quoteIdentifiers(identifiers, force); return this.QueryGenerator.quoteIdentifiers(identifiers, force);
}; };
/** /**
* Escape a value (e.g. a string, number or date) * Escape a value (e.g. a string, number or date)
*/ */
QueryInterface.prototype.escape = function(value) { QueryInterface.prototype.escape = function(value) {
return this.QueryGenerator.escape(value); return this.QueryGenerator.escape(value);
}; };
QueryInterface.prototype.setAutocommit = function(transaction, value, options) { QueryInterface.prototype.setAutocommit = function(transaction, value, options) {
if (!transaction || !(transaction instanceof Transaction)) { if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to set autocommit for a transaction without transaction object!'); throw new Error('Unable to set autocommit for a transaction without transaction object!');
} }
...@@ -847,9 +846,9 @@ module.exports = (function() { ...@@ -847,9 +846,9 @@ module.exports = (function() {
} else { } else {
return Promise.resolve(); return Promise.resolve();
} }
}; };
QueryInterface.prototype.setIsolationLevel = function(transaction, value, options) { QueryInterface.prototype.setIsolationLevel = function(transaction, value, options) {
if (!transaction || !(transaction instanceof Transaction)) { if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to set isolation level for a transaction without transaction object!'); throw new Error('Unable to set isolation level for a transaction without transaction object!');
} }
...@@ -865,9 +864,9 @@ module.exports = (function() { ...@@ -865,9 +864,9 @@ module.exports = (function() {
} else { } else {
return Promise.resolve(); return Promise.resolve();
} }
}; };
QueryInterface.prototype.startTransaction = function(transaction, options) { QueryInterface.prototype.startTransaction = function(transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) { if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to start a transaction without transaction object!'); throw new Error('Unable to start a transaction without transaction object!');
} }
...@@ -879,9 +878,9 @@ module.exports = (function() { ...@@ -879,9 +878,9 @@ module.exports = (function() {
var sql = this.QueryGenerator.startTransactionQuery(transaction, options); var sql = this.QueryGenerator.startTransactionQuery(transaction, options);
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}; };
QueryInterface.prototype.deferConstraints = function (transaction, options) { QueryInterface.prototype.deferConstraints = function (transaction, options) {
options = Utils._.extend({ options = Utils._.extend({
transaction: transaction, transaction: transaction,
parent: options.transaction parent: options.transaction
...@@ -894,9 +893,9 @@ module.exports = (function() { ...@@ -894,9 +893,9 @@ module.exports = (function() {
} }
return Promise.resolve(); return Promise.resolve();
}; };
QueryInterface.prototype.commitTransaction = function(transaction, options) { QueryInterface.prototype.commitTransaction = function(transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) { if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to commit a transaction without transaction object!'); throw new Error('Unable to commit a transaction without transaction object!');
} }
...@@ -913,9 +912,9 @@ module.exports = (function() { ...@@ -913,9 +912,9 @@ module.exports = (function() {
} else { } else {
return Promise.resolve(); return Promise.resolve();
} }
}; };
QueryInterface.prototype.rollbackTransaction = function(transaction, options) { QueryInterface.prototype.rollbackTransaction = function(transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) { if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to rollback a transaction without transaction object!'); throw new Error('Unable to rollback a transaction without transaction object!');
} }
...@@ -927,7 +926,6 @@ module.exports = (function() { ...@@ -927,7 +926,6 @@ module.exports = (function() {
var sql = this.QueryGenerator.rollbackTransactionQuery(transaction, options); var sql = this.QueryGenerator.rollbackTransactionQuery(transaction, options);
return this.sequelize.query(sql, options); return this.sequelize.query(sql, options);
}; };
return QueryInterface; module.exports = QueryInterface;
})();
...@@ -26,7 +26,6 @@ var url = require('url') ...@@ -26,7 +26,6 @@ var url = require('url')
* *
* @class Sequelize * @class Sequelize
*/ */
module.exports = (function() {
/** /**
* Instantiate sequelize with name of database, username and password * Instantiate sequelize with name of database, username and password
...@@ -80,17 +79,17 @@ module.exports = (function() { ...@@ -80,17 +79,17 @@ module.exports = (function() {
* @param {Function} [options.pool.validateConnection] A function that validates a connection. Called with client. The default function checks that client is an object, and that its state is not disconnected * @param {Function} [options.pool.validateConnection] A function that validates a connection. Called with client. The default function checks that client is an object, and that its state is not disconnected
* @param {Boolean} [options.quoteIdentifiers=true] Set to `false` to make table names and attributes case-insensitive on Postgres and skip double quoting of them. * @param {Boolean} [options.quoteIdentifiers=true] Set to `false` to make table names and attributes case-insensitive on Postgres and skip double quoting of them.
* @param {String} [options.isolationLevel='REPEATABLE_READ'] Set the default transaction isolation level. See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options. * @param {String} [options.isolationLevel='REPEATABLE_READ'] Set the default transaction isolation level. See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options.
*/ */
/** /**
* Instantiate sequelize with an URI * Instantiate sequelize with an URI
* @name Sequelize * @name Sequelize
* @constructor * @constructor
* *
* @param {String} uri A full database URI * @param {String} uri A full database URI
* @param {object} [options={}] See above for possible options * @param {object} [options={}] See above for possible options
*/ */
var Sequelize = function(database, username, password, options) { var Sequelize = function(database, username, password, options) {
var urlParts; var urlParts;
options = options || {}; options = options || {};
...@@ -205,203 +204,203 @@ module.exports = (function() { ...@@ -205,203 +204,203 @@ module.exports = (function() {
}; };
Sequelize.runHooks('afterInit', this); Sequelize.runHooks('afterInit', this);
}; };
Sequelize.options = {hooks: {}}; Sequelize.options = {hooks: {}};
/** /**
* A reference to Sequelize constructor from sequelize. Useful for accessing DataTypes, Errors etc. * A reference to Sequelize constructor from sequelize. Useful for accessing DataTypes, Errors etc.
* @property Sequelize * @property Sequelize
* @see {Sequelize} * @see {Sequelize}
*/ */
Sequelize.prototype.Sequelize = Sequelize; Sequelize.prototype.Sequelize = Sequelize;
/** /**
* A reference to sequelize utilities. Most users will not need to use these utils directly. However, you might want to use `Sequelize.Utils._`, which is a reference to the lodash library, if you don't already have it imported in your project. * A reference to sequelize utilities. Most users will not need to use these utils directly. However, you might want to use `Sequelize.Utils._`, which is a reference to the lodash library, if you don't already have it imported in your project.
* @property Utils * @property Utils
* @see {Utils} * @see {Utils}
*/ */
Sequelize.prototype.Utils = Sequelize.Utils = Utils; Sequelize.prototype.Utils = Sequelize.Utils = Utils;
/** /**
* A modified version of bluebird promises, that allows listening for sql events * A modified version of bluebird promises, that allows listening for sql events
* @property Promise * @property Promise
* @see {Promise} * @see {Promise}
*/ */
Sequelize.prototype.Promise = Sequelize.Promise = Promise; Sequelize.prototype.Promise = Sequelize.Promise = Promise;
/** /**
* Available query types for use with `sequelize.query` * Available query types for use with `sequelize.query`
* @property QueryTypes * @property QueryTypes
*/ */
Sequelize.prototype.QueryTypes = Sequelize.QueryTypes = QueryTypes; Sequelize.prototype.QueryTypes = Sequelize.QueryTypes = QueryTypes;
/** /**
* Exposes the validator.js object, so you can extend it with custom validation functions. The validator is exposed both on the instance, and on the constructor. * Exposes the validator.js object, so you can extend it with custom validation functions. The validator is exposed both on the instance, and on the constructor.
* @property Validator * @property Validator
* @see https://github.com/chriso/validator.js * @see https://github.com/chriso/validator.js
*/ */
Sequelize.prototype.Validator = Sequelize.Validator = require('validator'); Sequelize.prototype.Validator = Sequelize.Validator = require('validator');
Sequelize.prototype.Model = Sequelize.Model = Model; Sequelize.prototype.Model = Sequelize.Model = Model;
for (var dataType in DataTypes) { for (var dataType in DataTypes) {
Sequelize[dataType] = DataTypes[dataType]; Sequelize[dataType] = DataTypes[dataType];
} }
Object.defineProperty(Sequelize.prototype, 'connectorManager', { Object.defineProperty(Sequelize.prototype, 'connectorManager', {
get: function() { get: function() {
return this.transactionManager.getConnectorManager(); return this.transactionManager.getConnectorManager();
} }
}); });
/** /**
* A reference to the sequelize transaction class. Use this to access isolationLevels when creating a transaction * A reference to the sequelize transaction class. Use this to access isolationLevels when creating a transaction
* @property Transaction * @property Transaction
* @see {Transaction} * @see {Transaction}
* @see {Sequelize#transaction} * @see {Sequelize#transaction}
*/ */
Sequelize.prototype.Transaction = Sequelize.Transaction = Transaction; Sequelize.prototype.Transaction = Sequelize.Transaction = Transaction;
/** /**
* A reference to the deferrable collection. Use this to access the different deferrable options. * A reference to the deferrable collection. Use this to access the different deferrable options.
* @property Deferrable * @property Deferrable
* @see {Deferrable} * @see {Deferrable}
* @see {Sequelize#transaction} * @see {Sequelize#transaction}
*/ */
Sequelize.prototype.Deferrable = Sequelize.Deferrable = Deferrable; Sequelize.prototype.Deferrable = Sequelize.Deferrable = Deferrable;
/** /**
* A reference to the sequelize instance class. * A reference to the sequelize instance class.
* @property Instance * @property Instance
* @see {Instance} * @see {Instance}
*/ */
Sequelize.prototype.Instance = Sequelize.Instance = Instance; Sequelize.prototype.Instance = Sequelize.Instance = Instance;
/** /**
* Allow hooks to be defined on Sequelize + on sequelize instance as universal hooks to run on all models * Allow hooks to be defined on Sequelize + on sequelize instance as universal hooks to run on all models
* and on Sequelize/sequelize methods e.g. Sequelize(), Sequelize#define() * and on Sequelize/sequelize methods e.g. Sequelize(), Sequelize#define()
*/ */
Hooks.applyTo(Sequelize); Hooks.applyTo(Sequelize);
/** /**
* A general error class * A general error class
* @property Error * @property Error
* @see {Errors#BaseError} * @see {Errors#BaseError}
*/ */
Sequelize.prototype.Error = Sequelize.Error = Sequelize.prototype.Error = Sequelize.Error =
sequelizeErrors.BaseError; sequelizeErrors.BaseError;
/** /**
* Emitted when a validation fails * Emitted when a validation fails
* @property ValidationError * @property ValidationError
* @see {Errors#ValidationError} * @see {Errors#ValidationError}
*/ */
Sequelize.prototype.ValidationError = Sequelize.ValidationError = Sequelize.prototype.ValidationError = Sequelize.ValidationError =
sequelizeErrors.ValidationError; sequelizeErrors.ValidationError;
/** /**
* Describes a validation error on an instance path * Describes a validation error on an instance path
* @property ValidationErrorItem * @property ValidationErrorItem
* @see {Errors#ValidationErrorItem} * @see {Errors#ValidationErrorItem}
*/ */
Sequelize.prototype.ValidationErrorItem = Sequelize.ValidationErrorItem = Sequelize.prototype.ValidationErrorItem = Sequelize.ValidationErrorItem =
sequelizeErrors.ValidationErrorItem; sequelizeErrors.ValidationErrorItem;
/** /**
* A base class for all database related errors. * A base class for all database related errors.
* @see {Errors#DatabaseError} * @see {Errors#DatabaseError}
*/ */
Sequelize.prototype.DatabaseError = Sequelize.DatabaseError = Sequelize.prototype.DatabaseError = Sequelize.DatabaseError =
sequelizeErrors.DatabaseError; sequelizeErrors.DatabaseError;
/** /**
* Thrown when a database query times out because of a deadlock * Thrown when a database query times out because of a deadlock
* @see {Errors#TimeoutError} * @see {Errors#TimeoutError}
*/ */
Sequelize.prototype.TimeoutError = Sequelize.TimeoutError = Sequelize.prototype.TimeoutError = Sequelize.TimeoutError =
sequelizeErrors.TimeoutError; sequelizeErrors.TimeoutError;
/** /**
* Thrown when a unique constraint is violated in the database * Thrown when a unique constraint is violated in the database
* @see {Errors#UniqueConstraintError} * @see {Errors#UniqueConstraintError}
*/ */
Sequelize.prototype.UniqueConstraintError = Sequelize.UniqueConstraintError = Sequelize.prototype.UniqueConstraintError = Sequelize.UniqueConstraintError =
sequelizeErrors.UniqueConstraintError; sequelizeErrors.UniqueConstraintError;
/** /**
* Thrown when an exclusion constraint is violated in the database * Thrown when an exclusion constraint is violated in the database
* @see {Errors#ExclusionConstraintError} * @see {Errors#ExclusionConstraintError}
*/ */
Sequelize.prototype.ExclusionConstraintError = Sequelize.ExclusionConstraintError = Sequelize.prototype.ExclusionConstraintError = Sequelize.ExclusionConstraintError =
sequelizeErrors.ExclusionConstraintError; sequelizeErrors.ExclusionConstraintError;
/** /**
* Thrown when a foreign key constraint is violated in the database * Thrown when a foreign key constraint is violated in the database
* @see {Errors#ForeignKeyConstraintError} * @see {Errors#ForeignKeyConstraintError}
*/ */
Sequelize.prototype.ForeignKeyConstraintError = Sequelize.ForeignKeyConstraintError = Sequelize.prototype.ForeignKeyConstraintError = Sequelize.ForeignKeyConstraintError =
sequelizeErrors.ForeignKeyConstraintError; sequelizeErrors.ForeignKeyConstraintError;
/** /**
* A base class for all connection related errors. * A base class for all connection related errors.
* @see {Errors#ConnectionError} * @see {Errors#ConnectionError}
*/ */
Sequelize.prototype.ConnectionError = Sequelize.ConnectionError = Sequelize.prototype.ConnectionError = Sequelize.ConnectionError =
sequelizeErrors.ConnectionError; sequelizeErrors.ConnectionError;
/** /**
* Thrown when a connection to a database is refused * Thrown when a connection to a database is refused
* @see {Errors#ConnectionRefusedError} * @see {Errors#ConnectionRefusedError}
*/ */
Sequelize.prototype.ConnectionRefusedError = Sequelize.ConnectionRefusedError = Sequelize.prototype.ConnectionRefusedError = Sequelize.ConnectionRefusedError =
sequelizeErrors.ConnectionRefusedError; sequelizeErrors.ConnectionRefusedError;
/** /**
* Thrown when a connection to a database is refused due to insufficient access * Thrown when a connection to a database is refused due to insufficient access
* @see {Errors#AccessDeniedError} * @see {Errors#AccessDeniedError}
*/ */
Sequelize.prototype.AccessDeniedError = Sequelize.AccessDeniedError = Sequelize.prototype.AccessDeniedError = Sequelize.AccessDeniedError =
sequelizeErrors.AccessDeniedError; sequelizeErrors.AccessDeniedError;
/** /**
* Thrown when a connection to a database has a hostname that was not found * Thrown when a connection to a database has a hostname that was not found
* @see {Errors#HostNotFoundError} * @see {Errors#HostNotFoundError}
*/ */
Sequelize.prototype.HostNotFoundError = Sequelize.HostNotFoundError = Sequelize.prototype.HostNotFoundError = Sequelize.HostNotFoundError =
sequelizeErrors.HostNotFoundError; sequelizeErrors.HostNotFoundError;
/** /**
* Thrown when a connection to a database has a hostname that was not reachable * Thrown when a connection to a database has a hostname that was not reachable
* @see {Errors#HostNotReachableError} * @see {Errors#HostNotReachableError}
*/ */
Sequelize.prototype.HostNotReachableError = Sequelize.HostNotReachableError = Sequelize.prototype.HostNotReachableError = Sequelize.HostNotReachableError =
sequelizeErrors.HostNotReachableError; sequelizeErrors.HostNotReachableError;
/** /**
* Thrown when a connection to a database has invalid values for any of the connection parameters * Thrown when a connection to a database has invalid values for any of the connection parameters
* @see {Errors#InvalidConnectionError} * @see {Errors#InvalidConnectionError}
*/ */
Sequelize.prototype.InvalidConnectionError = Sequelize.InvalidConnectionError = Sequelize.prototype.InvalidConnectionError = Sequelize.InvalidConnectionError =
sequelizeErrors.InvalidConnectionError; sequelizeErrors.InvalidConnectionError;
/** /**
* Thrown when a connection to a database times out * Thrown when a connection to a database times out
* @see {Errors#ConnectionTimedOutError} * @see {Errors#ConnectionTimedOutError}
*/ */
Sequelize.prototype.ConnectionTimedOutError = Sequelize.ConnectionTimedOutError = Sequelize.prototype.ConnectionTimedOutError = Sequelize.ConnectionTimedOutError =
sequelizeErrors.ConnectionTimedOutError; sequelizeErrors.ConnectionTimedOutError;
/** /**
* Returns the specified dialect. * Returns the specified dialect.
* *
* @return {String} The specified dialect. * @return {String} The specified dialect.
*/ */
Sequelize.prototype.getDialect = function() { Sequelize.prototype.getDialect = function() {
return this.options.dialect; return this.options.dialect;
}; };
/** /**
* Returns an instance of QueryInterface. * Returns an instance of QueryInterface.
* @method getQueryInterface * @method getQueryInterface
...@@ -409,12 +408,12 @@ module.exports = (function() { ...@@ -409,12 +408,12 @@ module.exports = (function() {
* *
* @see {QueryInterface} * @see {QueryInterface}
*/ */
Sequelize.prototype.getQueryInterface = function() { Sequelize.prototype.getQueryInterface = function() {
this.queryInterface = this.queryInterface || new QueryInterface(this); this.queryInterface = this.queryInterface || new QueryInterface(this);
return this.queryInterface; return this.queryInterface;
}; };
/** /**
* Define a new model, representing a table in the DB. * Define a new model, representing a table in the DB.
* *
* The table columns are define by the hash that is given as the second argument. Each attribute of the hash represents a column. A short table definition might look like this: * The table columns are define by the hash that is given as the second argument. Each attribute of the hash represents a column. A short table definition might look like this:
...@@ -512,7 +511,7 @@ module.exports = (function() { ...@@ -512,7 +511,7 @@ module.exports = (function() {
* *
* @return {Model} * @return {Model}
*/ */
Sequelize.prototype.define = function(modelName, attributes, options) { Sequelize.prototype.define = function(modelName, attributes, options) {
options = options || {}; options = options || {};
var globalOptions = this.options; var globalOptions = this.options;
...@@ -549,35 +548,35 @@ module.exports = (function() { ...@@ -549,35 +548,35 @@ module.exports = (function() {
this.runHooks('afterDefine', model); this.runHooks('afterDefine', model);
return model; return model;
}; };
/** /**
* Fetch a Model which is already defined * Fetch a Model which is already defined
* *
* @param {String} modelName The name of a model defined with Sequelize.define * @param {String} modelName The name of a model defined with Sequelize.define
* @throws Will throw an error if the model is not defined (that is, if sequelize#isDefined returns false) * @throws Will throw an error if the model is not defined (that is, if sequelize#isDefined returns false)
* @return {Model} * @return {Model}
*/ */
Sequelize.prototype.model = function(modelName) { Sequelize.prototype.model = function(modelName) {
if (!this.isDefined(modelName)) { if (!this.isDefined(modelName)) {
throw new Error(modelName + ' has not been defined'); throw new Error(modelName + ' has not been defined');
} }
return this.modelManager.getModel(modelName); return this.modelManager.getModel(modelName);
}; };
/** /**
* Checks whether a model with the given name is defined * Checks whether a model with the given name is defined
* *
* @param {String} modelName The name of a model defined with Sequelize.define * @param {String} modelName The name of a model defined with Sequelize.define
* @return {Boolean} * @return {Boolean}
*/ */
Sequelize.prototype.isDefined = function(modelName) { Sequelize.prototype.isDefined = function(modelName) {
var models = this.modelManager.models; var models = this.modelManager.models;
return (models.filter(function(model) { return model.name === modelName; }).length !== 0); return (models.filter(function(model) { return model.name === modelName; }).length !== 0);
}; };
/** /**
* Imports a model defined in another file * Imports a model defined in another file
* *
* Imported models are cached, so multiple calls to import with the same path will not load the file multiple times * Imported models are cached, so multiple calls to import with the same path will not load the file multiple times
...@@ -586,7 +585,7 @@ module.exports = (function() { ...@@ -586,7 +585,7 @@ module.exports = (function() {
* @param {String} path The path to the file that holds the model you want to import. If the part is relative, it will be resolved relatively to the calling file * @param {String} path The path to the file that holds the model you want to import. If the part is relative, it will be resolved relatively to the calling file
* @return {Model} * @return {Model}
*/ */
Sequelize.prototype.import = function(path) { Sequelize.prototype.import = function(path) {
// is it a relative path? // is it a relative path?
if(Path.normalize(path) !== Path.resolve(path)){ if(Path.normalize(path) !== Path.resolve(path)){
// make path relative to the caller // make path relative to the caller
...@@ -602,13 +601,13 @@ module.exports = (function() { ...@@ -602,13 +601,13 @@ module.exports = (function() {
} }
return this.importCache[path]; return this.importCache[path];
}; };
Sequelize.prototype.migrate = function(options) { Sequelize.prototype.migrate = function(options) {
return this.getMigrator().migrate(options); return this.getMigrator().migrate(options);
}; };
/** /**
* Execute a query on the DB, with the posibility to bypass all the sequelize goodness. * Execute a query on the DB, with the posibility to bypass all the sequelize goodness.
* *
* By default, the function will return two arguments: an array of results, and a metadata object, containing number of affected rows etc. Use `.spread` to access the results. * By default, the function will return two arguments: an array of results, and a metadata object, containing number of affected rows etc. Use `.spread` to access the results.
...@@ -643,7 +642,7 @@ module.exports = (function() { ...@@ -643,7 +642,7 @@ module.exports = (function() {
* *
* @see {Model#build} for more information about instance option. * @see {Model#build} for more information about instance option.
*/ */
Sequelize.prototype.query = function(sql, options) { Sequelize.prototype.query = function(sql, options) {
if (arguments.length > 2) { if (arguments.length > 2) {
// TODO: Remove this note in the next major version (4.0) // TODO: Remove this note in the next major version (4.0)
throw new Error('Sequelize.query was refactored to only use the parameters `sql` and `options`. Please read the changelog about BC.'); throw new Error('Sequelize.query was refactored to only use the parameters `sql` and `options`. Please read the changelog about BC.');
...@@ -724,9 +723,9 @@ module.exports = (function() { ...@@ -724,9 +723,9 @@ module.exports = (function() {
self.test.$runningQueries--; self.test.$runningQueries--;
} }
}); });
}; };
/** /**
* Execute a query which would set an environment or user variable. The variables are set per connection, so this function needs a transaction. * Execute a query which would set an environment or user variable. The variables are set per connection, so this function needs a transaction.
* Only works for MySQL. * Only works for MySQL.
* *
...@@ -737,7 +736,7 @@ module.exports = (function() { ...@@ -737,7 +736,7 @@ module.exports = (function() {
* *
* @return {Promise} * @return {Promise}
*/ */
Sequelize.prototype.set = function( variables, options ) { Sequelize.prototype.set = function( variables, options ) {
var query; var query;
// Prepare options // Prepare options
...@@ -763,19 +762,19 @@ module.exports = (function() { ...@@ -763,19 +762,19 @@ module.exports = (function() {
}).join(', '); }).join(', ');
return this.query(query, options); return this.query(query, options);
}; };
/** /**
* Escape value. * Escape value.
* *
* @param {String} value * @param {String} value
* @return {String} * @return {String}
*/ */
Sequelize.prototype.escape = function(value) { Sequelize.prototype.escape = function(value) {
return this.getQueryInterface().escape(value); return this.getQueryInterface().escape(value);
}; };
/** /**
* Create a new database schema. * Create a new database schema.
* *
* 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),
...@@ -787,11 +786,11 @@ module.exports = (function() { ...@@ -787,11 +786,11 @@ module.exports = (function() {
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging * @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise} * @return {Promise}
*/ */
Sequelize.prototype.createSchema = function(schema, options) { Sequelize.prototype.createSchema = function(schema, options) {
return this.getQueryInterface().createSchema(schema, options); return this.getQueryInterface().createSchema(schema, options);
}; };
/** /**
* Show all defined schemas * Show all defined schemas
* *
* 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),
...@@ -800,11 +799,11 @@ module.exports = (function() { ...@@ -800,11 +799,11 @@ module.exports = (function() {
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging * @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise} * @return {Promise}
*/ */
Sequelize.prototype.showAllSchemas = function(options) { Sequelize.prototype.showAllSchemas = function(options) {
return this.getQueryInterface().showAllSchemas(options); return this.getQueryInterface().showAllSchemas(options);
}; };
/** /**
* Drop a single schema * Drop a single schema
* *
* 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),
...@@ -814,11 +813,11 @@ module.exports = (function() { ...@@ -814,11 +813,11 @@ module.exports = (function() {
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging * @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise} * @return {Promise}
*/ */
Sequelize.prototype.dropSchema = function(schema, options) { Sequelize.prototype.dropSchema = function(schema, options) {
return this.getQueryInterface().dropSchema(schema, options); return this.getQueryInterface().dropSchema(schema, options);
}; };
/** /**
* Drop all schemas * Drop all schemas
* *
* 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),
...@@ -827,11 +826,11 @@ module.exports = (function() { ...@@ -827,11 +826,11 @@ module.exports = (function() {
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging * @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise} * @return {Promise}
*/ */
Sequelize.prototype.dropAllSchemas = function(options) { Sequelize.prototype.dropAllSchemas = function(options) {
return this.getQueryInterface().dropAllSchemas(options); return this.getQueryInterface().dropAllSchemas(options);
}; };
/** /**
* Sync all defined models to the DB. * Sync all defined models to the DB.
* *
* @param {Object} [options={}] * @param {Object} [options={}]
...@@ -841,7 +840,7 @@ module.exports = (function() { ...@@ -841,7 +840,7 @@ module.exports = (function() {
* @param {String} [options.schema='public'] The schema that the tables should be created in. This can be overriden for each table in sequelize.define * @param {String} [options.schema='public'] The schema that the tables should be created in. This can be overriden for each table in sequelize.define
* @return {Promise} * @return {Promise}
*/ */
Sequelize.prototype.sync = function(options) { Sequelize.prototype.sync = function(options) {
var self = this; var self = this;
options = Utils._.defaults(options || {}, this.options.sync, this.options); options = Utils._.defaults(options || {}, this.options.sync, this.options);
...@@ -877,17 +876,20 @@ module.exports = (function() { ...@@ -877,17 +876,20 @@ module.exports = (function() {
// return the sequelize instance // return the sequelize instance
}).return(self); }).return(self);
}); });
}; };
/** /**
* Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model * Truncate all tables defined through the sequelize models. This is done
* @see {Model#drop} for options * by calling Model.truncate() on each model.
* *
* @param {object} options The options passed to each call to Model.drop * @param {object} [options] The options passed to Model.destroy in addition to truncate
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging * @param {Boolean|function} [options.transaction]
* @param {Boolean|function} [options.logging] A function that logs sql queries, or false for no logging
* @return {Promise} * @return {Promise}
*
* @see {Model#truncate} for more information
*/ */
Sequelize.prototype.drop = function(options) { Sequelize.prototype.truncate = function(options) {
var models = []; var models = [];
this.modelManager.forEachModel(function(model) { this.modelManager.forEachModel(function(model) {
...@@ -896,23 +898,20 @@ module.exports = (function() { ...@@ -896,23 +898,20 @@ module.exports = (function() {
} }
}, { reverse: false }); }, { reverse: false });
return Promise.each(models, function(model) { return Promise.map(models, function(model) {
return model.drop(options); return model.truncate(options);
}); });
}; };
/** /**
* Truncate all tables defined through the sequelize models. This is done * Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model
* by calling Model.truncate() on each model. * @see {Model#drop} for options
* *
* @param {object} [options] The options passed to Model.destroy in addition to truncate * @param {object} options The options passed to each call to Model.drop
* @param {Boolean|function} [options.transaction] * @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @param {Boolean|function} [options.logging] A function that logs sql queries, or false for no logging
* @return {Promise} * @return {Promise}
*
* @see {Model#truncate} for more information
*/ */
Sequelize.prototype.truncate = function(options) { Sequelize.prototype.drop = function(options) {
var models = []; var models = [];
this.modelManager.forEachModel(function(model) { this.modelManager.forEachModel(function(model) {
...@@ -921,12 +920,12 @@ module.exports = (function() { ...@@ -921,12 +920,12 @@ module.exports = (function() {
} }
}, { reverse: false }); }, { reverse: false });
return Promise.map(models, function(model) { return Promise.each(models, function(model) {
return model.truncate(options); return model.drop(options);
}); });
}; };
/** /**
* Test the connection by trying to authenticate * Test the connection by trying to authenticate
* *
* @fires success If authentication was successfull * @fires success If authentication was successfull
...@@ -934,19 +933,19 @@ module.exports = (function() { ...@@ -934,19 +933,19 @@ module.exports = (function() {
* @alias validate * @alias validate
* @return {Promise} * @return {Promise}
*/ */
Sequelize.prototype.authenticate = function() { Sequelize.prototype.authenticate = function() {
return this.query('SELECT 1+1 AS result', { 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(options) { Sequelize.prototype.databaseVersion = function(options) {
return this.queryInterface.databaseVersion(options); return this.queryInterface.databaseVersion(options);
}; };
Sequelize.prototype.validate = Sequelize.prototype.authenticate; Sequelize.prototype.validate = Sequelize.prototype.authenticate;
/** /**
* Creates a object representing a database function. This can be used in search queries, both in where and order parts, and as default values in column definitions. * Creates a object representing a database function. This can be used in search queries, both in where and order parts, and as default values in column definitions.
* If you want to refer to columns in your function, you should use `sequelize.col`, so that the columns are properly interpreted as columns and not a strings. * If you want to refer to columns in your function, you should use `sequelize.col`, so that the columns are properly interpreted as columns and not a strings.
* *
...@@ -969,11 +968,11 @@ module.exports = (function() { ...@@ -969,11 +968,11 @@ module.exports = (function() {
* @since v2.0.0-dev3 * @since v2.0.0-dev3
* @return {Sequelize.fn} * @return {Sequelize.fn}
*/ */
Sequelize.fn = Sequelize.prototype.fn = function(fn) { Sequelize.fn = Sequelize.prototype.fn = function(fn) {
return new Utils.fn(fn, Utils.sliceArgs(arguments, 1)); return new Utils.fn(fn, Utils.sliceArgs(arguments, 1));
}; };
/** /**
* Creates a object representing a column in the DB. This is often useful in conjunction with `sequelize.fn`, since raw string arguments to fn will be escaped. * Creates a object representing a column in the DB. This is often useful in conjunction with `sequelize.fn`, since raw string arguments to fn will be escaped.
* @see {Sequelize#fn} * @see {Sequelize#fn}
* *
...@@ -982,12 +981,12 @@ module.exports = (function() { ...@@ -982,12 +981,12 @@ module.exports = (function() {
* @since v2.0.0-dev3 * @since v2.0.0-dev3
* @return {Sequelize.col} * @return {Sequelize.col}
*/ */
Sequelize.col = Sequelize.prototype.col = function(col) { Sequelize.col = Sequelize.prototype.col = function(col) {
return new Utils.col(col); return new Utils.col(col);
}; };
/** /**
* Creates a object representing a call to the cast function. * Creates a object representing a call to the cast function.
* *
* @method cast * @method cast
...@@ -996,11 +995,11 @@ module.exports = (function() { ...@@ -996,11 +995,11 @@ module.exports = (function() {
* @since v2.0.0-dev3 * @since v2.0.0-dev3
* @return {Sequelize.cast} * @return {Sequelize.cast}
*/ */
Sequelize.cast = Sequelize.prototype.cast = function(val, type) { Sequelize.cast = Sequelize.prototype.cast = function(val, type) {
return new Utils.cast(val, type); return new Utils.cast(val, type);
}; };
/** /**
* Creates a object representing a literal, i.e. something that will not be escaped. * Creates a object representing a literal, i.e. something that will not be escaped.
* *
* @method literal * @method literal
...@@ -1009,11 +1008,11 @@ module.exports = (function() { ...@@ -1009,11 +1008,11 @@ module.exports = (function() {
* @since v2.0.0-dev3 * @since v2.0.0-dev3
* @return {Sequelize.literal} * @return {Sequelize.literal}
*/ */
Sequelize.literal = Sequelize.asIs = Sequelize.prototype.asIs = Sequelize.prototype.literal = function(val) { Sequelize.literal = Sequelize.asIs = Sequelize.prototype.asIs = Sequelize.prototype.literal = function(val) {
return new Utils.literal(val); return new Utils.literal(val);
}; };
/** /**
* An AND query * An AND query
* @see {Model#find} * @see {Model#find}
* *
...@@ -1022,11 +1021,11 @@ module.exports = (function() { ...@@ -1022,11 +1021,11 @@ module.exports = (function() {
* @since v2.0.0-dev3 * @since v2.0.0-dev3
* @return {Sequelize.and} * @return {Sequelize.and}
*/ */
Sequelize.and = Sequelize.prototype.and = function() { Sequelize.and = Sequelize.prototype.and = function() {
return new Utils.and(Utils.sliceArgs(arguments)); return new Utils.and(Utils.sliceArgs(arguments));
}; };
/** /**
* An OR query * An OR query
* @see {Model#find} * @see {Model#find}
* *
...@@ -1035,11 +1034,11 @@ module.exports = (function() { ...@@ -1035,11 +1034,11 @@ module.exports = (function() {
* @since v2.0.0-dev3 * @since v2.0.0-dev3
* @return {Sequelize.or} * @return {Sequelize.or}
*/ */
Sequelize.or = Sequelize.prototype.or = function() { Sequelize.or = Sequelize.prototype.or = function() {
return new Utils.or(Utils.sliceArgs(arguments)); return new Utils.or(Utils.sliceArgs(arguments));
}; };
/** /**
* Creates an object representing nested where conditions for postgres's json data-type. * Creates an object representing nested where conditions for postgres's json data-type.
* @see {Model#find} * @see {Model#find}
* *
...@@ -1048,11 +1047,11 @@ module.exports = (function() { ...@@ -1048,11 +1047,11 @@ module.exports = (function() {
* @param {String|Number|Boolean} [value] An optional value to compare against. Produces a string of the form "<json path> = '<value>'". * @param {String|Number|Boolean} [value] An optional value to compare against. Produces a string of the form "<json path> = '<value>'".
* @return {Sequelize.json} * @return {Sequelize.json}
*/ */
Sequelize.json = Sequelize.prototype.json = function (conditionsOrPath, value) { Sequelize.json = Sequelize.prototype.json = function (conditionsOrPath, value) {
return new Utils.json(conditionsOrPath, value); return new Utils.json(conditionsOrPath, value);
}; };
/* /*
* A way of specifying attr = condition. * A way of specifying attr = condition.
* *
* The attr can either be an object taken from `Model.rawAttributes` (for example `Model.rawAttributes.id` or `Model.rawAttributes.name`). The * The attr can either be an object taken from `Model.rawAttributes` (for example `Model.rawAttributes.id` or `Model.rawAttributes.name`). The
...@@ -1070,11 +1069,11 @@ module.exports = (function() { ...@@ -1070,11 +1069,11 @@ module.exports = (function() {
* @since v2.0.0-dev3 * @since v2.0.0-dev3
* @return {Sequelize.where} * @return {Sequelize.where}
*/ */
Sequelize.where = Sequelize.condition = Sequelize.prototype.condition = Sequelize.prototype.where = function(attr, comparator, logic) { Sequelize.where = Sequelize.condition = Sequelize.prototype.condition = Sequelize.prototype.where = function(attr, comparator, logic) {
return new Utils.where(attr, comparator, logic); return new Utils.where(attr, comparator, logic);
}; };
/** /**
* Start a transaction. When using transactions, you should pass the transaction in the options argument in order for the query to happen under that transaction * Start a transaction. When using transactions, you should pass the transaction in the options argument in order for the query to happen under that transaction
* *
* ```js * ```js
...@@ -1123,7 +1122,7 @@ module.exports = (function() { ...@@ -1123,7 +1122,7 @@ module.exports = (function() {
* @fires error If there is an uncaught error during the transaction * @fires error If there is an uncaught error during the transaction
* @fires success When the transaction has ended (either comitted or rolled back) * @fires success When the transaction has ended (either comitted or rolled back)
*/ */
Sequelize.prototype.transaction = function(options, autoCallback) { Sequelize.prototype.transaction = function(options, autoCallback) {
if (typeof options === 'function') { if (typeof options === 'function') {
autoCallback = options; autoCallback = options;
options = undefined; options = undefined;
...@@ -1167,9 +1166,9 @@ module.exports = (function() { ...@@ -1167,9 +1166,9 @@ module.exports = (function() {
} else { } else {
return transaction.prepareEnvironment().return(transaction); return transaction.prepareEnvironment().return(transaction);
} }
}; };
Sequelize.prototype.log = function() { Sequelize.prototype.log = function() {
var args = Utils.sliceArgs(arguments) var args = Utils.sliceArgs(arguments)
, last = Utils._.last(args) , last = Utils._.last(args)
, options; , options;
...@@ -1191,19 +1190,19 @@ module.exports = (function() { ...@@ -1191,19 +1190,19 @@ module.exports = (function() {
options.logging.apply(null, args); options.logging.apply(null, args);
} }
}; };
/** /**
* Close all connections used by this sequelize instance, and free all references so the instance can be garbage collected. * Close all connections used by this sequelize instance, and free all references so the instance can be garbage collected.
* *
* Normally this is done on process exit, so you only need to call this method if you are creating multiple instances, and want * Normally this is done on process exit, so you only need to call this method if you are creating multiple instances, and want
* to garbage collect some of them. * to garbage collect some of them.
*/ */
Sequelize.prototype.close = function () { Sequelize.prototype.close = function () {
this.connectionManager.close(); this.connectionManager.close();
}; };
Sequelize.prototype.normalizeDataType = function(Type) { Sequelize.prototype.normalizeDataType = function(Type) {
var type = typeof Type === 'function' ? new Type() : Type var type = typeof Type === 'function' ? new Type() : Type
, dialectTypes = this.dialect.DataTypes || {}; , dialectTypes = this.dialect.DataTypes || {};
...@@ -1215,8 +1214,8 @@ module.exports = (function() { ...@@ -1215,8 +1214,8 @@ module.exports = (function() {
type.type = dialectTypes[type.type.key].extend(type.type); type.type = dialectTypes[type.type.key].extend(type.type);
} }
return type; return type;
}; };
Sequelize.prototype.normalizeAttribute = function(attribute) { Sequelize.prototype.normalizeAttribute = function(attribute) {
if (!Utils._.isPlainObject(attribute)) { if (!Utils._.isPlainObject(attribute)) {
attribute = { type: attribute }; attribute = { type: attribute };
} }
...@@ -1231,9 +1230,7 @@ module.exports = (function() { ...@@ -1231,9 +1230,7 @@ module.exports = (function() {
} }
return attribute; return attribute;
}; };
// Allows the promise to access cls namespaces // Allows the promise to access cls namespaces
Promise.Sequelize = Sequelize; module.exports = Promise.Sequelize = Sequelize;
return Sequelize;
})();
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
var DataTypes = require('./data-types') var DataTypes = require('./data-types')
, SqlString = require('./sql-string') , SqlString = require('./sql-string')
, lodash = require('lodash') , lodash = require('lodash')
, ParameterValidator = require('./utils/parameter-validator') , parameterValidator = require('./utils/parameter-validator')
, inflection = require('inflection') , inflection = require('inflection')
, dottie = require('dottie') , dottie = require('dottie')
, uuid = require('node-uuid') , uuid = require('node-uuid')
...@@ -398,9 +398,7 @@ var Utils = module.exports = { ...@@ -398,9 +398,7 @@ var Utils = module.exports = {
this.logic = logic; this.logic = logic;
}, },
validateParameter: function(value, expectation, options) { validateParameter: parameterValidator,
return ParameterValidator.check(value, expectation, options);
},
formatReferences: function (obj) { formatReferences: function (obj) {
if (!lodash.isPlainObject(obj.references)) { if (!lodash.isPlainObject(obj.references)) {
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
var _ = require('lodash'); var _ = require('lodash');
var util = require('util'); var util = require('util');
var validateDeprecation = function(value, expectation, options) { function validateDeprecation (value, expectation, options) {
if (!options.deprecated) { if (!options.deprecated) {
return; return;
} }
...@@ -17,9 +17,9 @@ var validateDeprecation = function(value, expectation, options) { ...@@ -17,9 +17,9 @@ var validateDeprecation = function(value, expectation, options) {
} }
return valid; return valid;
}; }
var validate = function(value, expectation) { function validate (value, expectation) {
// the second part of this check is a workaround to deal with an issue that occurs in node-webkit when // the second part of this check is a workaround to deal with an issue that occurs in node-webkit when
// using object literals. https://github.com/sequelize/sequelize/issues/2685 // using object literals. https://github.com/sequelize/sequelize/issues/2685
if (value instanceof expectation || Object.prototype.toString.call(value) === Object.prototype.toString.call(expectation.call())) { if (value instanceof expectation || Object.prototype.toString.call(value) === Object.prototype.toString.call(expectation.call())) {
...@@ -27,10 +27,9 @@ var validate = function(value, expectation) { ...@@ -27,10 +27,9 @@ var validate = function(value, expectation) {
} }
throw new Error(util.format('The parameter (value: %s) is no %s.', value, expectation.name)); throw new Error(util.format('The parameter (value: %s) is no %s.', value, expectation.name));
}; }
module.exports = { function check (value, expectation, options) {
check: function(value, expectation, options) {
options = _.extend({ options = _.extend({
deprecated: false, deprecated: false,
index: null, index: null,
...@@ -53,5 +52,6 @@ module.exports = { ...@@ -53,5 +52,6 @@ module.exports = {
return false return false
|| validateDeprecation(value, expectation, options) || validateDeprecation(value, expectation, options)
|| validate(value, expectation, options); || validate(value, expectation, options);
} }
};
module.exports = check;
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!