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

Commit a92fb9ce by Mick Hansen

Merge pull request #3837 from BridgeAR/fix-indentation

Remove unnecessary indentation
2 parents 073f1777 33ff3ad5
var Association = function() {
var Association = function () {};
};
module.exports = Association;
\ No newline at end of file
......@@ -7,8 +7,7 @@ var Utils = require('./../utils')
, CounterCache = require('../plugins/counter-cache')
, util = require('util');
module.exports = (function() {
var BelongsToMany = function(source, target, options) {
var BelongsToMany = function(source, target, options) {
Association.call(this);
this.associationType = 'BelongsToMany';
......@@ -176,13 +175,13 @@ module.exports = (function() {
if (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
// or in an extra table which connects two tables
BelongsToMany.prototype.injectAttributes = function() {
// the id is in the target table
// or in an extra table which connects two tables
BelongsToMany.prototype.injectAttributes = function() {
var self = this;
this.identifier = this.foreignKey;
......@@ -263,9 +262,9 @@ module.exports = (function() {
Helpers.checkNamingCollision(this);
return this;
};
};
BelongsToMany.prototype.injectGetter = function(obj) {
BelongsToMany.prototype.injectGetter = function(obj) {
var association = this;
obj[this.accessors.get] = function(options) {
......@@ -364,9 +363,9 @@ module.exports = (function() {
};
return this;
};
};
BelongsToMany.prototype.injectSetter = function(obj) {
BelongsToMany.prototype.injectSetter = function(obj) {
var association = this
, primaryKeyAttribute = association.target.primaryKeyAttribute;
......@@ -668,9 +667,9 @@ module.exports = (function() {
};
return this;
};
};
BelongsToMany.prototype.injectCreator = function(obj) {
BelongsToMany.prototype.injectCreator = function(obj) {
var association = this;
obj[this.accessors.create] = function(values, options) {
......@@ -701,7 +700,6 @@ module.exports = (function() {
};
return this;
};
};
return BelongsToMany;
})();
module.exports = BelongsToMany;
......@@ -6,8 +6,7 @@ var Utils = require('./../utils')
, Association = require('./base')
, util = require('util');
module.exports = (function() {
var BelongsTo = function(source, target, options) {
var BelongsTo = function(source, target, options) {
Association.call(this);
this.associationType = 'BelongsTo';
......@@ -67,12 +66,12 @@ module.exports = (function() {
set: 'set' + singular,
create: 'create' + singular
};
};
};
util.inherits(BelongsTo, Association);
util.inherits(BelongsTo, Association);
// the id is in the source table
BelongsTo.prototype.injectAttributes = function() {
// the id is in the source table
BelongsTo.prototype.injectAttributes = function() {
var newAttributes = {};
newAttributes[this.identifier] = Utils._.defaults(this.foreignKeyAttribute, { type: this.options.keyType || this.target.rawAttributes[this.targetIdentifier].type });
......@@ -90,10 +89,10 @@ module.exports = (function() {
Helpers.checkNamingCollision(this);
return this;
};
};
// Add getAssociation method to the prototype of the model instance
BelongsTo.prototype.injectGetter = function(instancePrototype) {
// Add getAssociation method to the prototype of the model instance
BelongsTo.prototype.injectGetter = function(instancePrototype) {
var association = this;
instancePrototype[this.accessors.get] = function(options) {
......@@ -124,10 +123,10 @@ module.exports = (function() {
};
return this;
};
};
// Add setAssociaton method to the prototype of the model instance
BelongsTo.prototype.injectSetter = function(instancePrototype) {
// Add setAssociaton method to the prototype of the model instance
BelongsTo.prototype.injectSetter = function(instancePrototype) {
var association = this;
instancePrototype[this.accessors.set] = function(associatedInstance, options) {
......@@ -154,10 +153,10 @@ module.exports = (function() {
};
return this;
};
};
// Add createAssociation method to the prototype of the model instance
BelongsTo.prototype.injectCreator = function(instancePrototype) {
// Add createAssociation method to the prototype of the model instance
BelongsTo.prototype.injectCreator = function(instancePrototype) {
var association = this;
instancePrototype[this.accessors.create] = function(values, fieldsOrOptions) {
......@@ -175,7 +174,6 @@ module.exports = (function() {
};
return this;
};
};
return BelongsTo;
})();
module.exports = BelongsTo;
......@@ -3,15 +3,14 @@
var Utils = require('./../utils')
, _ = require('lodash');
module.exports = (function() {
var HasManySingleLinked = function(association, instance) {
var HasManySingleLinked = function(association, instance) {
this.association = association;
this.instance = instance;
this.target = this.association.target;
this.source = this.association.source;
};
};
HasManySingleLinked.prototype.injectGetter = function(options) {
HasManySingleLinked.prototype.injectGetter = function(options) {
var scopeWhere = this.association.scope ? {} : null;
if (this.association.scope) {
Object.keys(this.association.scope).forEach(function (attribute) {
......@@ -40,9 +39,9 @@ module.exports = (function() {
}
return model.all(options);
};
};
HasManySingleLinked.prototype.injectSetter = function(oldAssociations, newAssociations, defaultAttributes) {
HasManySingleLinked.prototype.injectSetter = function(oldAssociations, newAssociations, defaultAttributes) {
var self = this
, primaryKeys
, primaryKey
......@@ -120,9 +119,9 @@ module.exports = (function() {
}
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));
if (this.association.scope) {
Object.keys(this.association.scope).forEach(function (attribute) {
......@@ -131,7 +130,6 @@ module.exports = (function() {
}
return newAssociation.save(options);
};
};
return HasManySingleLinked;
})();
module.exports = HasManySingleLinked;
......@@ -8,8 +8,7 @@ var Utils = require('./../utils')
, util = require('util')
, HasManySingleLinked = require('./has-many-single-linked');
module.exports = (function() {
var HasMany = function(source, target, options) {
var HasMany = function(source, target, options) {
Association.call(this);
this.associationType = 'HasMany';
......@@ -81,13 +80,13 @@ module.exports = (function() {
if (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
// or in an extra table which connects two tables
HasMany.prototype.injectAttributes = function() {
// the id is in the target table
// or in an extra table which connects two tables
HasMany.prototype.injectAttributes = function() {
this.identifier = this.foreignKey || Utils._.camelizeIf(
[
Utils._.underscoredIf(this.source.options.name.singular, this.source.options.underscored),
......@@ -115,9 +114,9 @@ module.exports = (function() {
Helpers.checkNamingCollision(this);
return this;
};
};
HasMany.prototype.injectGetter = function(obj) {
HasMany.prototype.injectGetter = function(obj) {
var association = this;
obj[this.accessors.get] = function(options) {
......@@ -188,9 +187,9 @@ module.exports = (function() {
};
return this;
};
};
HasMany.prototype.injectSetter = function(obj) {
HasMany.prototype.injectSetter = function(obj) {
var association = this
, primaryKeyAttribute = association.target.primaryKeyAttribute;
......@@ -340,9 +339,9 @@ module.exports = (function() {
};
return this;
};
};
HasMany.prototype.injectCreator = function(obj) {
HasMany.prototype.injectCreator = function(obj) {
var association = this;
obj[this.accessors.create] = function(values, options) {
......@@ -372,7 +371,6 @@ module.exports = (function() {
};
return this;
};
};
return HasMany;
})();
module.exports = HasMany;
......@@ -5,8 +5,7 @@ var Utils = require('./../utils')
, Association = require('./base')
, util = require('util');
module.exports = (function() {
var HasOne = function(srcModel, targetModel, options) {
var HasOne = function(srcModel, targetModel, options) {
Association.call(this);
this.associationType = 'HasOne';
......@@ -65,12 +64,12 @@ module.exports = (function() {
set: 'set' + singular,
create: 'create' + singular
};
};
};
util.inherits(HasOne, Association);
util.inherits(HasOne, Association);
// the id is in the target table
HasOne.prototype.injectAttributes = function() {
// the id is in the target table
HasOne.prototype.injectAttributes = function() {
var newAttributes = {}
, keyType = this.source.rawAttributes[this.sourceIdentifier].type;
......@@ -91,9 +90,9 @@ module.exports = (function() {
Helpers.checkNamingCollision(this);
return this;
};
};
HasOne.prototype.injectGetter = function(instancePrototype) {
HasOne.prototype.injectGetter = function(instancePrototype) {
var association = this;
instancePrototype[this.accessors.get] = function(options) {
......@@ -124,9 +123,9 @@ module.exports = (function() {
};
return this;
};
};
HasOne.prototype.injectSetter = function(instancePrototype) {
HasOne.prototype.injectSetter = function(instancePrototype) {
var association = this;
instancePrototype[this.accessors.set] = function(associatedInstance, options) {
......@@ -160,9 +159,9 @@ module.exports = (function() {
};
return this;
};
};
HasOne.prototype.injectCreator = function(instancePrototype) {
HasOne.prototype.injectCreator = function(instancePrototype) {
var association = this;
instancePrototype[this.accessors.create] = function(values, options) {
......@@ -176,7 +175,6 @@ module.exports = (function() {
};
return this;
};
};
return HasOne;
})();
module.exports = HasOne;
......@@ -2,8 +2,7 @@
var Utils = require('./../utils');
module.exports = {
checkNamingCollision: function (association) {
function checkNamingCollision (association) {
if (association.source.rawAttributes.hasOwnProperty(association.as)) {
throw new Error(
'Naming collision between attribute \'' + association.as +
......@@ -11,9 +10,9 @@ module.exports = {
'. 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`
// on the association, or request an `onDelete` or `onUpdate` behaviour
......@@ -44,6 +43,9 @@ module.exports = {
newAttribute.onUpdate = options.onUpdate;
}
}
}
}
module.exports = {
checkNamingCollision: checkNamingCollision,
addForeignKeyConstraints: addForeignKeyConstraints
};
......@@ -9,8 +9,12 @@ var Utils = require('../../utils')
, Dottie = require('dottie')
, uuid = require('node-uuid');
module.exports = (function() {
var QueryGenerator = {
/* istanbul ignore next */
var throwMethodUndefined = function(methodName) {
throw new Error('The method "' + methodName + '" is not defined! Please add it to your sql dialect.');
};
var QueryGenerator = {
options: {},
addSchema: function(param) {
......@@ -2061,12 +2065,6 @@ module.exports = (function() {
booleanValue: function(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')
, Dot = require('dottie')
, 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 associated data by the callee.
......@@ -266,8 +41,8 @@ module.exports = (function() {
]
}
]
*/
/*
*/
/*
* Assumptions
* 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)
......@@ -280,7 +55,7 @@ module.exports = (function() {
* 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) {
return [];
}
......@@ -569,9 +344,231 @@ module.exports = (function() {
}
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')
, Model = require('../../model')
, AbstractQueryGenerator = require('../abstract/query-generator');
module.exports = (function() {
var QueryGenerator = {
/* istanbul ignore next */
var throwMethodUndefined = function(methodName) {
throw new Error('The method "' + methodName + '" is not defined! Please add it to your sql dialect.');
};
var QueryGenerator = {
options: {},
dialect: 'mssql',
......@@ -595,17 +599,11 @@ module.exports = (function() {
booleanValue: function(value) {
return !!value ? 1 : 0;
}
};
};
// private methods
function wrapSingleQuote(identifier){
// private methods
function wrapSingleQuote(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')
, AbstractQuery = require('../abstract/query')
, sequelizeErrors = require('../../errors.js');
module.exports = (function() {
var Query = function(connection, sequelize, options) {
var Query = function(connection, sequelize, options) {
this.connection = connection;
this.instance = options.instance;
this.model = options.model;
......@@ -17,15 +16,15 @@ module.exports = (function() {
}, options || {});
this.checkLoggingOption();
};
};
Utils.inherit(Query, AbstractQuery);
Utils.inherit(Query, AbstractQuery);
Query.prototype.getInsertIdField = function() {
Query.prototype.getInsertIdField = function() {
return 'id';
};
};
Query.prototype.run = function(sql) {
Query.prototype.run = function(sql) {
var self = this;
this.sql = sql;
......@@ -84,9 +83,9 @@ module.exports = (function() {
});
return promise;
};
};
/**
/**
* High level function that handles the results of a query execution.
*
*
......@@ -102,7 +101,7 @@ module.exports = (function() {
*
* @param {Array} data - The result of the query execution.
*/
Query.prototype.formatResults = function(data) {
Query.prototype.formatResults = function(data) {
var result = this.instance;
if (this.isInsertQuery(data)) {
this.handleInsertQuery(data);
......@@ -155,18 +154,18 @@ module.exports = (function() {
}
return result;
};
};
Query.prototype.handleShowTablesQuery = function(results) {
Query.prototype.handleShowTablesQuery = function(results) {
return results.map(function(resultSet) {
return {
tableName: resultSet.TABLE_NAME,
schema: resultSet.TABLE_SCHEMA
};
});
};
};
Query.prototype.formatError = function (err) {
Query.prototype.formatError = function (err) {
var match;
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 '(.*)'/);
......@@ -210,9 +209,9 @@ module.exports = (function() {
}
return new sequelizeErrors.DatabaseError(err);
};
};
Query.prototype.isShowOrDescribeQuery = function() {
Query.prototype.isShowOrDescribeQuery = function() {
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 */
......@@ -220,13 +219,13 @@ module.exports = (function() {
result = result || (this.sql.toLowerCase().indexOf('exec sys.sp_helpindex @objname') === 0);
return result;
};
};
Query.prototype.isShowIndexesQuery = function () {
Query.prototype.isShowIndexesQuery = function () {
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
data = Utils._.foldl(data, function (acc, item) {
if (!(item.index_name in acc)) {
......@@ -261,9 +260,9 @@ module.exports = (function() {
type: undefined,
};
});
};
};
Query.prototype.handleInsertQuery = function(results, metaData) {
Query.prototype.handleInsertQuery = function(results, metaData) {
if (this.instance) {
// add the inserted row id to the instance
var autoIncrementField = this.model.autoIncrementField
......@@ -281,7 +280,6 @@ module.exports = (function() {
this.instance[autoIncrementField] = id;
}
};
};
return Query;
})();
module.exports = Query;
......@@ -3,8 +3,7 @@
var Utils = require('../../utils')
, DataTypes = require('../../data-types');
module.exports = (function() {
var QueryGenerator = {
var QueryGenerator = {
dialect: 'mysql',
createSchema: function() {
......@@ -372,7 +371,6 @@ module.exports = (function() {
dropForeignKeyQuery: function(tableName, 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')
, uuid = require('node-uuid')
, sequelizeErrors = require('../../errors.js');
module.exports = (function() {
var Query = function(connection, sequelize, options) {
var Query = function(connection, sequelize, options) {
this.connection = connection;
this.instance = options.instance;
this.model = options.model;
......@@ -19,10 +18,10 @@ module.exports = (function() {
}, options || {});
this.checkLoggingOption();
};
};
Utils.inherit(Query, AbstractQuery);
Query.prototype.run = function(sql) {
Utils.inherit(Query, AbstractQuery);
Query.prototype.run = function(sql) {
var self = this;
this.sql = sql;
......@@ -41,7 +40,7 @@ module.exports = (function() {
});
return promise;
};
};
/**
* High level function that handles the results of a query execution.
......@@ -59,7 +58,7 @@ module.exports = (function() {
*
* @param {Array} data - The result of the query execution.
*/
Query.prototype.formatResults = function(data) {
Query.prototype.formatResults = function(data) {
var result = this.instance;
if (this.isInsertQuery(data)) {
......@@ -101,10 +100,10 @@ module.exports = (function() {
}
return result;
};
};
Query.prototype.formatError = function (err) {
Query.prototype.formatError = function (err) {
var match;
switch (err.errno || err.code) {
......@@ -157,9 +156,9 @@ module.exports = (function() {
default:
return new sequelizeErrors.DatabaseError(err);
}
};
};
Query.prototype.handleShowIndexesQuery = function (data) {
Query.prototype.handleShowIndexesQuery = function (data) {
// Group by index name, and collect all fields
data = Utils._.foldl(data, function (acc, item) {
if (!(item.Key_name in acc)) {
......@@ -187,7 +186,6 @@ module.exports = (function() {
type: item.Index_type,
};
});
};
};
return Query;
})();
module.exports = Query;
......@@ -2,15 +2,17 @@
var hstore = require('pg-hstore')({sanitize : true});
module.exports = {
stringify: function(data) {
if(data === null) return null;
function stringify (data) {
if (data === null) return null;
return hstore.stringify(data);
},
parse: function(value) {
if(value === null) return null;
}
function parse (value) {
if (value === null) return null;
return hstore.parse(value);
}
}
module.exports = {
stringify: stringify,
parse: parse
};
......@@ -10,8 +10,7 @@ var Utils = require('../../utils')
, AbstractQueryGenerator = require('../abstract/query-generator')
, primaryKeys = {};
module.exports = (function() {
var QueryGenerator = {
var QueryGenerator = {
options: {},
dialect: 'postgres',
......@@ -938,7 +937,6 @@ module.exports = (function() {
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) {
return fields;
}
module.exports = (function() {
var Query = function(client, sequelize, options) {
var Query = function(client, sequelize, options) {
this.client = client;
this.sequelize = sequelize;
this.instance = options.instance;
......@@ -79,12 +78,12 @@ module.exports = (function() {
}, options || {});
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;
var self = this
......@@ -336,9 +335,9 @@ module.exports = (function() {
});
return promise;
};
};
Query.prototype.formatError = function (err) {
Query.prototype.formatError = function (err) {
var match
, table
, index
......@@ -420,15 +419,14 @@ module.exports = (function() {
default:
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);
};
};
Query.prototype.getInsertIdField = function() {
Query.prototype.getInsertIdField = function() {
return 'id';
};
};
return Query;
})();
module.exports = Query;
......@@ -3,8 +3,7 @@
var Utils = require('../../utils'),
moment = require('moment');
module.exports = {
stringify: function (data) {
function stringify (data) {
if (data === null) return null;
if (!Utils._.isArray(data) || data.length !== 2) return '';
......@@ -26,8 +25,9 @@ module.exports = {
});
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(typeof AttributeType === 'function') AttributeType = new AttributeType();
......@@ -58,5 +58,9 @@ module.exports = {
result.inclusive = [(value[0] === '['), (value[value.length - 1] === ']')];
return result;
}
}
module.exports = {
stringify: stringify,
parse: parse
};
......@@ -11,8 +11,7 @@ var MySqlQueryGenerator = Utils._.extend(
Utils._.clone(require('../mysql/query-generator'))
);
module.exports = (function() {
var QueryGenerator = {
var QueryGenerator = {
options: {},
dialect: 'sqlite',
......@@ -437,7 +436,6 @@ module.exports = (function() {
var sql = 'PRAGMA foreign_key_list(<%= 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')
@class QueryInterface
@static
*/
module.exports = {
/**
/**
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
new table with the same name but without the obsolete column.
......@@ -27,7 +27,7 @@ module.exports = {
@since 1.6.0
*/
removeColumn: function(tableName, attributeName, options) {
var removeColumn = function(tableName, attributeName, options) {
var self = this;
options = options || {};
......@@ -41,9 +41,9 @@ module.exports = {
return self.sequelize.query(subQuery + ';', { raw: true, logging: options.logging });
});
});
},
};
/**
/**
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
new table with the same name but with a modified version of the respective column.
......@@ -60,7 +60,7 @@ module.exports = {
@since 1.6.0
*/
changeColumn: function(tableName, attributes, options) {
var changeColumn = function(tableName, attributes, options) {
var attributeName = Utils._.keys(attributes)[0]
, self = this;
options = options || {};
......@@ -75,9 +75,9 @@ module.exports = {
return self.sequelize.query(subQuery + ';', { raw: true, logging: options.logging });
});
});
},
};
/**
/**
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
new table with the same name but with a renamed version of the respective column.
......@@ -95,7 +95,7 @@ module.exports = {
@since 1.6.0
*/
renameColumn: function(tableName, attrNameBefore, attrNameAfter, options) {
var renameColumn = function(tableName, attrNameBefore, attrNameAfter, options) {
var self = this;
options = options || {};
......@@ -110,5 +110,10 @@ module.exports = {
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')
, QueryTypes = require('../../query-types')
, sequelizeErrors = require('../../errors.js');
module.exports = (function() {
var Query = function(database, sequelize, options) {
var Query = function(database, sequelize, options) {
this.database = database;
this.sequelize = sequelize;
this.instance = options.instance;
......@@ -18,14 +17,14 @@ module.exports = (function() {
}, options || {});
this.checkLoggingOption();
};
Utils.inherit(Query, AbstractQuery);
};
Utils.inherit(Query, AbstractQuery);
Query.prototype.getInsertIdField = function() {
Query.prototype.getInsertIdField = function() {
return 'lastID';
};
};
Query.prototype.run = function(sql) {
Query.prototype.run = function(sql) {
var self = this
, promise;
......@@ -179,9 +178,9 @@ module.exports = (function() {
});
return promise;
};
};
Query.prototype.formatError = function (err) {
Query.prototype.formatError = function (err) {
var match;
switch (err.code) {
......@@ -241,9 +240,9 @@ module.exports = (function() {
default:
return new sequelizeErrors.DatabaseError(err);
}
};
};
Query.prototype.handleShowIndexesQuery = function (data) {
Query.prototype.handleShowIndexesQuery = function (data) {
var self = this;
// Sqlite returns indexes so the one that was defined last is returned first. Lets reverse that!
......@@ -264,9 +263,9 @@ module.exports = (function() {
return item;
});
});
};
};
Query.prototype.getDatabaseMethod = function() {
Query.prototype.getDatabaseMethod = function() {
if (this.isUpsertQuery()) {
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) {
......@@ -274,7 +273,6 @@ module.exports = (function() {
} else {
return 'all';
}
};
};
return Query;
})();
module.exports = Query;
......@@ -11,8 +11,59 @@ var Utils = require('./utils')
, primitives = ['string', 'number', 'boolean']
, 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
* 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() {
* @see {Sequelize#define} for more information about getters and setters
* @class Instance
*/
var Instance = function(values, options) {
var Instance = function(values, options) {
this.dataValues = {};
this._previousDataValues = {};
this._changed = {};
......@@ -54,25 +105,25 @@ module.exports = (function() {
*/
initValues.call(this, values, options);
};
};
/**
/**
* A reference to the sequelize instance
* @see {Sequelize}
* @property sequelize
* @return {Sequelize}
*/
Object.defineProperty(Instance.prototype, 'sequelize', {
Object.defineProperty(Instance.prototype, 'sequelize', {
get: function() { return this.Model.modelManager.sequelize; }
});
});
/**
/**
* Get an object representing the query for this instance, use with `options.where`
*
* @property where
* @return {Object}
*/
Instance.prototype.where = function() {
Instance.prototype.where = function() {
var where;
where = this.Model.primaryKeyAttributes.reduce(function (result, attribute) {
......@@ -84,38 +135,38 @@ module.exports = (function() {
return this.__options.whereCollection;
}
return where;
};
};
Instance.prototype.toString = function () {
Instance.prototype.toString = function () {
return '[object SequelizeInstance:'+this.Model.name+']';
};
};
/**
/**
* Get the value of the underlying data value
*
* @param {String} key
* @return {any}
*/
Instance.prototype.getDataValue = function(key) {
Instance.prototype.getDataValue = function(key) {
return this.dataValues[key];
};
};
/**
/**
* Update the underlying data value
*
* @param {String} key
* @param {any} value
*/
Instance.prototype.setDataValue = function(key, value) {
Instance.prototype.setDataValue = function(key, value) {
var originalValue = this._previousDataValues[key];
if (primitives.indexOf(typeof value) === -1 || value !== originalValue) {
this.changed(key, true);
}
this.dataValues[key] = value;
};
};
/**
/**
* 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.
......@@ -125,7 +176,7 @@ module.exports = (function() {
* @param {Boolean} [options.plain=false] If set to true, included instances will be returned as plain objects
* @return {Object|any}
*/
Instance.prototype.get = function(key, options) {
Instance.prototype.get = function(key, options) {
if (options === undefined && typeof key === 'object') {
options = key;
key = undefined;
......@@ -181,9 +232,9 @@ module.exports = (function() {
return values;
}
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`).
* 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.
......@@ -207,7 +258,7 @@ module.exports = (function() {
* @param {Boolean} [options.reset=false] Clear all previously set data values
* @alias setAttributes
*/
Instance.prototype.set = function(key, value, options) {
Instance.prototype.set = function(key, value, options) {
var values
, originalValue
, keys
......@@ -331,13 +382,13 @@ module.exports = (function() {
}
return this;
};
};
Instance.prototype.setAttributes = function(updates) {
Instance.prototype.setAttributes = function(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 without an argument, it will return an array of keys that have changed.
......@@ -347,7 +398,7 @@ module.exports = (function() {
* @param {String} [key]
* @return {Boolean|Array}
*/
Instance.prototype.changed = function(key, value) {
Instance.prototype.changed = function(key, value) {
if (key) {
if (value !== undefined) {
this._changed[key] = value;
......@@ -361,18 +412,18 @@ module.exports = (function() {
}.bind(this));
return changed.length ? changed : false;
};
};
/**
/**
* Returns the previous value for key from `_previousDataValues`.
* @param {String} key
* @return {any}
*/
Instance.prototype.previous = function(key) {
Instance.prototype.previous = function(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 (value[0] instanceof Instance) {
value = value.map(function(instance) {
......@@ -412,9 +463,9 @@ module.exports = (function() {
self[accessor] = self.dataValues[accessor] = isEmpty ? [] : include.model.bulkBuild(value, childOptions);
}
}
};
};
/**
/**
* 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`.
......@@ -429,7 +480,7 @@ module.exports = (function() {
*
* @return {Promise<this|Errors.ValidationError>}
*/
Instance.prototype.save = function(options) {
Instance.prototype.save = function(options) {
if (arguments.length > 1) {
throw new Error('The second argument was removed in favor of the options object.');
}
......@@ -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.
* This is different from doing a `find(Instance.id)`, because that would create and return a new instance. With this method,
* all references to the Instance are updated with the new data and no new objects are created.
*
* @see {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.
* @return {Promise<this>}
*/
Instance.prototype.reload = function(options) {
};
/*
* Refresh the current instance in-place, i.e. update the object with current data from the DB and return the same object.
* This is different from doing a `find(Instance.id)`, because that would create and return a new instance. With this method,
* all references to the Instance are updated with the new data and no new objects are created.
*
* @see {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.
* @return {Promise<this>}
*/
Instance.prototype.reload = function(options) {
var self = this
, where = [
this.sequelize.getQueryInterface().quoteTable(this.Model.name) + '.' + this.sequelize.getQueryInterface().quoteIdentifier(this.Model.primaryKeyField) + '=?',
......@@ -689,9 +740,9 @@ module.exports = (function() {
return this.Model.findOne(options).then(function(reload) {
self.set(reload.dataValues, {raw: true, reset: true});
}).return(self);
};
};
/*
/*
* 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.
......@@ -702,15 +753,15 @@ module.exports = (function() {
*
* @return {Promise<undefined|Errors.ValidationError>}
*/
Instance.prototype.validate = function(options) {
Instance.prototype.validate = function(options) {
return new InstanceValidator(this, options).validate();
};
};
Instance.prototype.hookValidate = function(options) {
Instance.prototype.hookValidate = function(options) {
return new InstanceValidator(this, options).hookValidate();
};
};
/**
/**
* This is the same as calling `set` and then calling `save`.
*
* @see {Instance#set}
......@@ -721,7 +772,7 @@ module.exports = (function() {
* @return {Promise<this>}
* @alias updateAttributes
*/
Instance.prototype.update = function(values, options) {
Instance.prototype.update = function(values, options) {
var changedBefore = this.changed() || []
, sideEffects
, fields;
......@@ -741,10 +792,10 @@ module.exports = (function() {
}
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.
*
* @param {Object} [options={}]
......@@ -754,7 +805,7 @@ module.exports = (function() {
*
* @return {Promise<undefined>}
*/
Instance.prototype.destroy = function(options) {
Instance.prototype.destroy = function(options) {
options = Utils._.extend({
hooks: true,
force: false
......@@ -787,9 +838,9 @@ module.exports = (function() {
}).then(function(result) {
return result;
});
};
};
/**
/**
* Restore the row corresponding to this instance. Only available for paranoid models.
*
* @param {Object} [options={}]
......@@ -798,7 +849,7 @@ module.exports = (function() {
*
* @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');
options = Utils._.extend({
......@@ -820,9 +871,9 @@ module.exports = (function() {
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
* ```sql
* SET column = column + X
......@@ -845,7 +896,7 @@ module.exports = (function() {
*
* @return {Promise<this>}
*/
Instance.prototype.increment = function(fields, options) {
Instance.prototype.increment = function(fields, options) {
var identifier = this.where()
, updatedAtAttr = this.Model._timestampAttributes.updatedAt
, values = {}
......@@ -893,9 +944,9 @@ module.exports = (function() {
}, 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
* ```sql
* SET column = column - X
......@@ -918,7 +969,7 @@ module.exports = (function() {
*
* @return {Promise}
*/
Instance.prototype.decrement = function(fields, options) {
Instance.prototype.decrement = function(fields, options) {
options = _.defaults(options || {}, {
by: 1
});
......@@ -932,15 +983,15 @@ module.exports = (function() {
options.by = 0 - options.by;
return this.increment(fields, options);
};
};
/**
/**
* Check whether all values of this and `other` Instance are the same
*
* @param {Instance} other
* @return {Boolean}
*/
Instance.prototype.equals = function(other) {
Instance.prototype.equals = function(other) {
var result = true;
Utils._.each(this.dataValues, function(value, key) {
......@@ -952,89 +1003,36 @@ module.exports = (function() {
});
return result;
};
};
/**
/**
* Check if this is eqaul to one of `others` by calling equals
*
* @param {Array} others
* @return {Boolean}
*/
Instance.prototype.equalsOneOf = function(others) {
Instance.prototype.equalsOneOf = function(others) {
var self = this;
return _.any(others, function(other) {
return self.equals(other);
});
};
};
Instance.prototype.setValidators = function(attribute, validators) {
Instance.prototype.setValidators = function(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.
*
* @see {Instance#get}
* @return {object}
*/
Instance.prototype.toJSON = function() {
Instance.prototype.toJSON = function() {
return this.get({
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')
, Utils = require('./utils')
, _ = require('lodash');
module.exports = (function() {
var ModelManager = function(sequelize) {
var ModelManager = function(sequelize) {
this.models = [];
this.sequelize = sequelize;
};
};
ModelManager.prototype.addModel = function(model) {
ModelManager.prototype.addModel = function(model) {
this.models.push(model);
this.sequelize.models[model.name] = model;
return model;
};
};
ModelManager.prototype.removeModel = function(model) {
ModelManager.prototype.removeModel = function(model) {
this.models = this.models.filter(function($model) {
return $model.name !== model.name;
});
delete this.sequelize.models[model.name];
};
};
ModelManager.prototype.getModel = function(against, options) {
ModelManager.prototype.getModel = function(against, options) {
options = _.defaults(options || {}, {
attribute: 'name'
});
......@@ -35,18 +34,18 @@ module.exports = (function() {
});
return !!model ? model[0] : null;
};
};
ModelManager.prototype.__defineGetter__('all', function() {
ModelManager.prototype.__defineGetter__('all', function() {
return this.models;
});
});
/**
/**
* Iterate over Models in an order suitable for e.g. creating tables. Will
* take foreign key constraints into account so that dependencies are visited
* before dependents.
*/
ModelManager.prototype.forEachModel = function(iterator, options) {
ModelManager.prototype.forEachModel = function(iterator, options) {
var models = {}
, sorter = new Toposort()
, sorted
......@@ -97,7 +96,6 @@ module.exports = (function() {
sorted.forEach(function(name) {
iterator(models[name], name);
});
};
};
return ModelManager;
})();
module.exports = ModelManager;
This diff could not be displayed because it is too large.
'use strict';
module.exports = (function() {
var Attribute = function(options) {
var Attribute = function(options) {
if (options.type === undefined) options = {type: options};
this.type = options.type;
};
};
return Attribute;
})();
module.exports = Attribute;
......@@ -5,8 +5,7 @@ var Utils = require('./../utils')
, DataTypes = require('../data-types')
, Promise = require('bluebird');
module.exports = (function() {
var CounterCache = function(association, options) {
var CounterCache = function(association, options) {
this.association = association;
this.source = association.source;
this.target = association.target;
......@@ -32,10 +31,10 @@ module.exports = (function() {
this.injectAttributes();
this.injectHooks();
};
};
// Add countAssociation attribute to source model
CounterCache.prototype.injectAttributes = function() {
// Add countAssociation attribute to source model
CounterCache.prototype.injectAttributes = function() {
// Do not try to use a column that's already taken
Helpers.checkNamingCollision(this);
......@@ -54,10 +53,10 @@ module.exports = (function() {
// Sync attributes and setters/getters to DAO prototype
this.source.refreshAttributes();
};
};
// Add setAssociaton method to the prototype of the model instance
CounterCache.prototype.injectHooks = function() {
// Add setAssociaton method to the prototype of the model instance
CounterCache.prototype.injectHooks = function() {
var association = this.association,
counterCacheInstance = this,
CounterUtil,
......@@ -173,7 +172,6 @@ module.exports = (function() {
association.target.addHook('afterUpdate', atomicHooks.update);
association.target.addHook('afterDestroy', atomicHooks.destroy);
}
};
};
return CounterCache;
})();
module.exports = CounterCache;
......@@ -8,29 +8,28 @@ var Utils = require('./utils')
, Promise = require('./promise')
, QueryTypes = require('./query-types');
module.exports = (function() {
/*
/*
* The interface that Sequelize uses to talk to all databases
* @class QueryInterface
**/
var QueryInterface = function(sequelize) {
**/
var QueryInterface = function(sequelize) {
this.sequelize = sequelize;
this.QueryGenerator = this.sequelize.dialect.QueryGenerator;
};
};
QueryInterface.prototype.createSchema = function(schema, options) {
QueryInterface.prototype.createSchema = function(schema, options) {
options = options || {};
var sql = this.QueryGenerator.createSchema(schema);
return this.sequelize.query(sql, {logging: options.logging});
};
};
QueryInterface.prototype.dropSchema = function(schema, options) {
QueryInterface.prototype.dropSchema = function(schema, options) {
options = options || {};
var sql = this.QueryGenerator.dropSchema(schema);
return this.sequelize.query(sql, {logging: options.logging});
};
};
QueryInterface.prototype.dropAllSchemas = function(options) {
QueryInterface.prototype.dropAllSchemas = function(options) {
options = options || {};
var self = this;
......@@ -41,9 +40,9 @@ module.exports = (function() {
return self.dropSchema(schemaName, { logging: options.logging });
});
}
};
};
QueryInterface.prototype.showAllSchemas = function(options) {
QueryInterface.prototype.showAllSchemas = function(options) {
var self = this;
options = Utils._.extend({
......@@ -61,18 +60,18 @@ module.exports = (function() {
})
);
});
};
};
QueryInterface.prototype.databaseVersion = function(options) {
QueryInterface.prototype.databaseVersion = function(options) {
options = options || {};
return this.sequelize.query(this.QueryGenerator.versionQuery(), {
raw: true,
type: QueryTypes.VERSION,
logging: options.logging
});
};
};
QueryInterface.prototype.createTable = function(tableName, attributes, options) {
QueryInterface.prototype.createTable = function(tableName, attributes, options) {
var keys = Object.keys(attributes)
, keyLen = keys.length
, self = this
......@@ -192,9 +191,9 @@ module.exports = (function() {
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
options = options || {};
options.cascade = options.cascade || options.force || false;
......@@ -227,9 +226,9 @@ module.exports = (function() {
return Promise.all(promises).get(0);
});
};
};
QueryInterface.prototype.dropAllTables = function(options) {
QueryInterface.prototype.dropAllTables = function(options) {
var self = this;
options = options || {};
......@@ -281,9 +280,9 @@ module.exports = (function() {
});
}
});
};
};
QueryInterface.prototype.dropAllEnums = function(options) {
QueryInterface.prototype.dropAllEnums = function(options) {
if (this.sequelize.getDialect() !== 'postgres') {
return Promise.resolve();
}
......@@ -299,15 +298,15 @@ module.exports = (function() {
{logging: options.logging, raw: true}
);
});
};
};
QueryInterface.prototype.renameTable = function(before, after, options) {
QueryInterface.prototype.renameTable = function(before, after, options) {
options = options || {};
var sql = this.QueryGenerator.renameTableQuery(before, after);
return this.sequelize.query(sql, { logging: options.logging });
};
};
QueryInterface.prototype.showAllTables = function(options) {
QueryInterface.prototype.showAllTables = function(options) {
var self = this;
options = Utils._.extend({
raw: true,
......@@ -318,9 +317,9 @@ module.exports = (function() {
return self.sequelize.query(showTablesSql, options).then(function(tableNames) {
return Utils._.flatten(tableNames);
});
};
};
QueryInterface.prototype.describeTable = function(tableName, options) {
QueryInterface.prototype.describeTable = function(tableName, options) {
var schema = null
, schemaDelimiter = null;
......@@ -348,15 +347,15 @@ module.exports = (function() {
return Promise.resolve(data);
}
});
};
};
QueryInterface.prototype.addColumn = function(table, key, attribute, options) {
QueryInterface.prototype.addColumn = function(table, key, attribute, options) {
options = options || {};
attribute = this.sequelize.normalizeAttribute(attribute);
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 || {};
if (this.sequelize.options.dialect === 'sqlite') {
// sqlite needs some special treatment as it cannot drop a column
......@@ -365,9 +364,9 @@ module.exports = (function() {
var sql = this.QueryGenerator.removeColumnQuery(tableName, attributeName);
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 = {};
options = options || {};
......@@ -388,9 +387,9 @@ module.exports = (function() {
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 || {};
return this.describeTable(tableName, options).then(function(data) {
data = data[attrNameBefore] || {};
......@@ -421,9 +420,9 @@ module.exports = (function() {
return this.sequelize.query(sql, {logging: options.logging});
}
}.bind(this));
};
};
QueryInterface.prototype.addIndex = function(tableName, _attributes, options, _rawTablename) {
QueryInterface.prototype.addIndex = function(tableName, _attributes, options, _rawTablename) {
var attributes, rawTablename;
// Support for passing tableName, attributes, options or tableName, options (with a fields param which is the attributes)
......@@ -448,9 +447,9 @@ module.exports = (function() {
options.fields = attributes;
var sql = this.QueryGenerator.addIndexQuery(tableName, options, rawTablename);
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);
options = options || {};
return this.sequelize.query(sql, {
......@@ -458,13 +457,13 @@ module.exports = (function() {
logging: options.logging,
type: QueryTypes.SHOWINDEXES
});
};
};
QueryInterface.prototype.nameIndexes = function(indexes, rawTablename) {
QueryInterface.prototype.nameIndexes = function(indexes, rawTablename) {
return this.QueryGenerator.nameIndexes(indexes, rawTablename);
};
};
QueryInterface.prototype.getForeignKeysForTables = function(tableNames, options) {
QueryInterface.prototype.getForeignKeysForTables = function(tableNames, options) {
var self = this;
options = options || {};
......@@ -489,15 +488,15 @@ module.exports = (function() {
return result;
});
};
};
QueryInterface.prototype.removeIndex = function(tableName, indexNameOrAttributes, options) {
QueryInterface.prototype.removeIndex = function(tableName, indexNameOrAttributes, options) {
options = options || {};
var sql = this.QueryGenerator.removeIndexQuery(tableName, indexNameOrAttributes);
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);
options.type = QueryTypes.INSERT;
......@@ -506,9 +505,9 @@ module.exports = (function() {
if (instance) result.isNewRecord = false;
return result;
});
};
};
QueryInterface.prototype.upsert = function(tableName, values, model, options) {
QueryInterface.prototype.upsert = function(tableName, values, model, options) {
var wheres = []
, where
, indexFields
......@@ -581,15 +580,15 @@ module.exports = (function() {
return rowCount === 1;
});
};
};
QueryInterface.prototype.bulkInsert = function(tableName, records, options, attributes) {
QueryInterface.prototype.bulkInsert = function(tableName, records, options, attributes) {
options.type = QueryTypes.INSERT;
var sql = this.QueryGenerator.bulkInsertQuery(tableName, records, options, attributes);
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
, restrict = false
, sql = self.QueryGenerator.updateQuery(tableName, values, identifier, options, instance.Model.rawAttributes);
......@@ -611,9 +610,9 @@ module.exports = (function() {
options.instance = instance;
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)
, table = Utils._.isObject(tableName) ? tableName : { tableName: tableName }
, model = Utils._.find(this.sequelize.modelManager.models, { tableName: table.tableName });
......@@ -621,9 +620,9 @@ module.exports = (function() {
options = options || {};
options.model = model;
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
, cascades = []
, sql = self.QueryGenerator.deleteQuery(tableName, identifier, null, instance.Model);
......@@ -662,14 +661,14 @@ module.exports = (function() {
options.instance = instance;
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);
return this.sequelize.query(sql, options);
};
};
QueryInterface.prototype.select = function(model, tableName, options) {
QueryInterface.prototype.select = function(model, tableName, options) {
options = options || {};
options.type = QueryTypes.SELECT;
options.model = model;
......@@ -677,9 +676,9 @@ module.exports = (function() {
this.QueryGenerator.selectQuery(tableName, options, model),
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);
options = options || {};
......@@ -687,9 +686,9 @@ module.exports = (function() {
options.type = QueryTypes.RAW;
options.instance = instance;
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) {
tableName = this.QueryGenerator.addSchema({
tableName: tableName,
......@@ -734,9 +733,9 @@ module.exports = (function() {
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);
options = options || {};
if (sql) {
......@@ -744,9 +743,9 @@ module.exports = (function() {
} else {
return Promise.resolve();
}
};
};
QueryInterface.prototype.dropTrigger = function(tableName, triggerName, options) {
QueryInterface.prototype.dropTrigger = function(tableName, triggerName, options) {
var sql = this.QueryGenerator.dropTrigger(tableName, triggerName);
options = options || {};
......@@ -755,9 +754,9 @@ module.exports = (function() {
} else {
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);
options = options || {};
......@@ -766,9 +765,9 @@ module.exports = (function() {
} else {
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);
options = options || {};
......@@ -777,9 +776,9 @@ module.exports = (function() {
} else {
return Promise.resolve();
}
};
};
QueryInterface.prototype.dropFunction = function(functionName, params, options) {
QueryInterface.prototype.dropFunction = function(functionName, params, options) {
var sql = this.QueryGenerator.dropFunction(functionName, params);
options = options || {};
......@@ -788,9 +787,9 @@ module.exports = (function() {
} else {
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);
options = options || {};
......@@ -799,40 +798,40 @@ module.exports = (function() {
} else {
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,
* the identifier will be quoted even if the `quoteIdentifiers` option is
* false.
*/
QueryInterface.prototype.quoteIdentifier = function(identifier, force) {
QueryInterface.prototype.quoteIdentifier = function(identifier, force) {
return this.QueryGenerator.quoteIdentifier(identifier, force);
};
};
QueryInterface.prototype.quoteTable = function(identifier) {
QueryInterface.prototype.quoteTable = function(identifier) {
return this.QueryGenerator.quoteTable(identifier);
};
};
/**
/**
* Split an identifier into .-separated tokens and quote each part.
* If force is true, the identifier will be quoted even if the
* `quoteIdentifiers` option is false.
*/
QueryInterface.prototype.quoteIdentifiers = function(identifiers, force) {
QueryInterface.prototype.quoteIdentifiers = function(identifiers, force) {
return this.QueryGenerator.quoteIdentifiers(identifiers, force);
};
};
/**
/**
* 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);
};
};
QueryInterface.prototype.setAutocommit = function(transaction, value, options) {
QueryInterface.prototype.setAutocommit = function(transaction, value, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to set autocommit for a transaction without transaction object!');
}
......@@ -847,9 +846,9 @@ module.exports = (function() {
} else {
return Promise.resolve();
}
};
};
QueryInterface.prototype.setIsolationLevel = function(transaction, value, options) {
QueryInterface.prototype.setIsolationLevel = function(transaction, value, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to set isolation level for a transaction without transaction object!');
}
......@@ -865,9 +864,9 @@ module.exports = (function() {
} else {
return Promise.resolve();
}
};
};
QueryInterface.prototype.startTransaction = function(transaction, options) {
QueryInterface.prototype.startTransaction = function(transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to start a transaction without transaction object!');
}
......@@ -879,9 +878,9 @@ module.exports = (function() {
var sql = this.QueryGenerator.startTransactionQuery(transaction, options);
return this.sequelize.query(sql, options);
};
};
QueryInterface.prototype.deferConstraints = function (transaction, options) {
QueryInterface.prototype.deferConstraints = function (transaction, options) {
options = Utils._.extend({
transaction: transaction,
parent: options.transaction
......@@ -894,9 +893,9 @@ module.exports = (function() {
}
return Promise.resolve();
};
};
QueryInterface.prototype.commitTransaction = function(transaction, options) {
QueryInterface.prototype.commitTransaction = function(transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to commit a transaction without transaction object!');
}
......@@ -913,9 +912,9 @@ module.exports = (function() {
} else {
return Promise.resolve();
}
};
};
QueryInterface.prototype.rollbackTransaction = function(transaction, options) {
QueryInterface.prototype.rollbackTransaction = function(transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to rollback a transaction without transaction object!');
}
......@@ -927,7 +926,6 @@ module.exports = (function() {
var sql = this.QueryGenerator.rollbackTransactionQuery(transaction, options);
return this.sequelize.query(sql, options);
};
};
return QueryInterface;
})();
module.exports = QueryInterface;
......@@ -26,7 +26,6 @@ var url = require('url')
*
* @class Sequelize
*/
module.exports = (function() {
/**
* Instantiate sequelize with name of database, username and password
......@@ -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 {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.
*/
*/
/**
/**
* Instantiate sequelize with an URI
* @name Sequelize
* @constructor
*
* @param {String} uri A full database URI
* @param {object} [options={}] See above for possible options
*/
var Sequelize = function(database, username, password, options) {
*/
var Sequelize = function(database, username, password, options) {
var urlParts;
options = options || {};
......@@ -205,203 +204,203 @@ module.exports = (function() {
};
Sequelize.runHooks('afterInit', this);
};
};
Sequelize.options = {hooks: {}};
Sequelize.options = {hooks: {}};
/**
/**
* A reference to Sequelize constructor from sequelize. Useful for accessing DataTypes, Errors etc.
* @property 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.
* @property 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
* @property Promise
* @see {Promise}
*/
Sequelize.prototype.Promise = Sequelize.Promise = Promise;
Sequelize.prototype.Promise = Sequelize.Promise = Promise;
/**
/**
* Available query types for use with `sequelize.query`
* @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.
* @property Validator
* @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];
}
}
Object.defineProperty(Sequelize.prototype, 'connectorManager', {
Object.defineProperty(Sequelize.prototype, 'connectorManager', {
get: function() {
return this.transactionManager.getConnectorManager();
}
});
});
/**
/**
* A reference to the sequelize transaction class. Use this to access isolationLevels when creating a transaction
* @property Transaction
* @see {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.
* @property Deferrable
* @see {Deferrable}
* @see {Sequelize#transaction}
*/
Sequelize.prototype.Deferrable = Sequelize.Deferrable = Deferrable;
Sequelize.prototype.Deferrable = Sequelize.Deferrable = Deferrable;
/**
/**
* A reference to the sequelize instance class.
* @property 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
* and on Sequelize/sequelize methods e.g. Sequelize(), Sequelize#define()
*/
Hooks.applyTo(Sequelize);
Hooks.applyTo(Sequelize);
/**
/**
* A general error class
* @property Error
* @see {Errors#BaseError}
*/
Sequelize.prototype.Error = Sequelize.Error =
Sequelize.prototype.Error = Sequelize.Error =
sequelizeErrors.BaseError;
/**
/**
* Emitted when a validation fails
* @property ValidationError
* @see {Errors#ValidationError}
*/
Sequelize.prototype.ValidationError = Sequelize.ValidationError =
Sequelize.prototype.ValidationError = Sequelize.ValidationError =
sequelizeErrors.ValidationError;
/**
/**
* Describes a validation error on an instance path
* @property ValidationErrorItem
* @see {Errors#ValidationErrorItem}
*/
Sequelize.prototype.ValidationErrorItem = Sequelize.ValidationErrorItem =
Sequelize.prototype.ValidationErrorItem = Sequelize.ValidationErrorItem =
sequelizeErrors.ValidationErrorItem;
/**
/**
* A base class for all database related errors.
* @see {Errors#DatabaseError}
*/
Sequelize.prototype.DatabaseError = Sequelize.DatabaseError =
Sequelize.prototype.DatabaseError = Sequelize.DatabaseError =
sequelizeErrors.DatabaseError;
/**
/**
* Thrown when a database query times out because of a deadlock
* @see {Errors#TimeoutError}
*/
Sequelize.prototype.TimeoutError = Sequelize.TimeoutError =
Sequelize.prototype.TimeoutError = Sequelize.TimeoutError =
sequelizeErrors.TimeoutError;
/**
/**
* Thrown when a unique constraint is violated in the database
* @see {Errors#UniqueConstraintError}
*/
Sequelize.prototype.UniqueConstraintError = Sequelize.UniqueConstraintError =
Sequelize.prototype.UniqueConstraintError = Sequelize.UniqueConstraintError =
sequelizeErrors.UniqueConstraintError;
/**
/**
* Thrown when an exclusion constraint is violated in the database
* @see {Errors#ExclusionConstraintError}
*/
Sequelize.prototype.ExclusionConstraintError = Sequelize.ExclusionConstraintError =
Sequelize.prototype.ExclusionConstraintError = Sequelize.ExclusionConstraintError =
sequelizeErrors.ExclusionConstraintError;
/**
/**
* Thrown when a foreign key constraint is violated in the database
* @see {Errors#ForeignKeyConstraintError}
*/
Sequelize.prototype.ForeignKeyConstraintError = Sequelize.ForeignKeyConstraintError =
Sequelize.prototype.ForeignKeyConstraintError = Sequelize.ForeignKeyConstraintError =
sequelizeErrors.ForeignKeyConstraintError;
/**
/**
* A base class for all connection related errors.
* @see {Errors#ConnectionError}
*/
Sequelize.prototype.ConnectionError = Sequelize.ConnectionError =
Sequelize.prototype.ConnectionError = Sequelize.ConnectionError =
sequelizeErrors.ConnectionError;
/**
/**
* Thrown when a connection to a database is refused
* @see {Errors#ConnectionRefusedError}
*/
Sequelize.prototype.ConnectionRefusedError = Sequelize.ConnectionRefusedError =
Sequelize.prototype.ConnectionRefusedError = Sequelize.ConnectionRefusedError =
sequelizeErrors.ConnectionRefusedError;
/**
/**
* Thrown when a connection to a database is refused due to insufficient access
* @see {Errors#AccessDeniedError}
*/
Sequelize.prototype.AccessDeniedError = Sequelize.AccessDeniedError =
Sequelize.prototype.AccessDeniedError = Sequelize.AccessDeniedError =
sequelizeErrors.AccessDeniedError;
/**
/**
* Thrown when a connection to a database has a hostname that was not found
* @see {Errors#HostNotFoundError}
*/
Sequelize.prototype.HostNotFoundError = Sequelize.HostNotFoundError =
Sequelize.prototype.HostNotFoundError = Sequelize.HostNotFoundError =
sequelizeErrors.HostNotFoundError;
/**
/**
* Thrown when a connection to a database has a hostname that was not reachable
* @see {Errors#HostNotReachableError}
*/
Sequelize.prototype.HostNotReachableError = Sequelize.HostNotReachableError =
Sequelize.prototype.HostNotReachableError = Sequelize.HostNotReachableError =
sequelizeErrors.HostNotReachableError;
/**
/**
* Thrown when a connection to a database has invalid values for any of the connection parameters
* @see {Errors#InvalidConnectionError}
*/
Sequelize.prototype.InvalidConnectionError = Sequelize.InvalidConnectionError =
Sequelize.prototype.InvalidConnectionError = Sequelize.InvalidConnectionError =
sequelizeErrors.InvalidConnectionError;
/**
/**
* Thrown when a connection to a database times out
* @see {Errors#ConnectionTimedOutError}
*/
Sequelize.prototype.ConnectionTimedOutError = Sequelize.ConnectionTimedOutError =
Sequelize.prototype.ConnectionTimedOutError = Sequelize.ConnectionTimedOutError =
sequelizeErrors.ConnectionTimedOutError;
/**
/**
* Returns the specified dialect.
*
* @return {String} The specified dialect.
*/
Sequelize.prototype.getDialect = function() {
Sequelize.prototype.getDialect = function() {
return this.options.dialect;
};
};
/**
/**
* Returns an instance of QueryInterface.
* @method getQueryInterface
......@@ -409,12 +408,12 @@ module.exports = (function() {
*
* @see {QueryInterface}
*/
Sequelize.prototype.getQueryInterface = function() {
Sequelize.prototype.getQueryInterface = function() {
this.queryInterface = this.queryInterface || new QueryInterface(this);
return this.queryInterface;
};
};
/**
/**
* 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:
......@@ -512,7 +511,7 @@ module.exports = (function() {
*
* @return {Model}
*/
Sequelize.prototype.define = function(modelName, attributes, options) {
Sequelize.prototype.define = function(modelName, attributes, options) {
options = options || {};
var globalOptions = this.options;
......@@ -549,35 +548,35 @@ module.exports = (function() {
this.runHooks('afterDefine', model);
return model;
};
};
/**
/**
* Fetch a Model which is already defined
*
* @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)
* @return {Model}
*/
Sequelize.prototype.model = function(modelName) {
Sequelize.prototype.model = function(modelName) {
if (!this.isDefined(modelName)) {
throw new Error(modelName + ' has not been defined');
}
return this.modelManager.getModel(modelName);
};
};
/**
/**
* Checks whether a model with the given name is defined
*
* @param {String} modelName The name of a model defined with Sequelize.define
* @return {Boolean}
*/
Sequelize.prototype.isDefined = function(modelName) {
Sequelize.prototype.isDefined = function(modelName) {
var models = this.modelManager.models;
return (models.filter(function(model) { return model.name === modelName; }).length !== 0);
};
};
/**
/**
* 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
......@@ -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
* @return {Model}
*/
Sequelize.prototype.import = function(path) {
Sequelize.prototype.import = function(path) {
// is it a relative path?
if(Path.normalize(path) !== Path.resolve(path)){
// make path relative to the caller
......@@ -602,13 +601,13 @@ module.exports = (function() {
}
return this.importCache[path];
};
};
Sequelize.prototype.migrate = function(options) {
Sequelize.prototype.migrate = function(options) {
return this.getMigrator().migrate(options);
};
};
/**
/**
* 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.
......@@ -643,7 +642,7 @@ module.exports = (function() {
*
* @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) {
// 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.');
......@@ -724,9 +723,9 @@ module.exports = (function() {
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.
* Only works for MySQL.
*
......@@ -737,7 +736,7 @@ module.exports = (function() {
*
* @return {Promise}
*/
Sequelize.prototype.set = function( variables, options ) {
Sequelize.prototype.set = function( variables, options ) {
var query;
// Prepare options
......@@ -763,19 +762,19 @@ module.exports = (function() {
}).join(', ');
return this.query(query, options);
};
};
/**
/**
* Escape value.
*
* @param {String} value
* @return {String}
*/
Sequelize.prototype.escape = function(value) {
Sequelize.prototype.escape = function(value) {
return this.getQueryInterface().escape(value);
};
};
/**
/**
* 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),
......@@ -787,11 +786,11 @@ module.exports = (function() {
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise}
*/
Sequelize.prototype.createSchema = function(schema, options) {
Sequelize.prototype.createSchema = function(schema, options) {
return this.getQueryInterface().createSchema(schema, options);
};
};
/**
/**
* 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),
......@@ -800,11 +799,11 @@ module.exports = (function() {
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise}
*/
Sequelize.prototype.showAllSchemas = function(options) {
Sequelize.prototype.showAllSchemas = function(options) {
return this.getQueryInterface().showAllSchemas(options);
};
};
/**
/**
* 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),
......@@ -814,11 +813,11 @@ module.exports = (function() {
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise}
*/
Sequelize.prototype.dropSchema = function(schema, options) {
Sequelize.prototype.dropSchema = function(schema, options) {
return this.getQueryInterface().dropSchema(schema, options);
};
};
/**
/**
* 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),
......@@ -827,11 +826,11 @@ module.exports = (function() {
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise}
*/
Sequelize.prototype.dropAllSchemas = function(options) {
Sequelize.prototype.dropAllSchemas = function(options) {
return this.getQueryInterface().dropAllSchemas(options);
};
};
/**
/**
* Sync all defined models to the DB.
*
* @param {Object} [options={}]
......@@ -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
* @return {Promise}
*/
Sequelize.prototype.sync = function(options) {
Sequelize.prototype.sync = function(options) {
var self = this;
options = Utils._.defaults(options || {}, this.options.sync, this.options);
......@@ -877,17 +876,20 @@ module.exports = (function() {
// return the sequelize instance
}).return(self);
});
};
};
/**
* Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model
* @see {Model#drop} for options
/**
* Truncate all tables defined through the sequelize models. This is done
* by calling Model.truncate() on each model.
*
* @param {object} options The options passed to each call to Model.drop
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @param {object} [options] The options passed to Model.destroy in addition to truncate
* @param {Boolean|function} [options.transaction]
* @param {Boolean|function} [options.logging] A function that logs sql queries, or false for no logging
* @return {Promise}
*
* @see {Model#truncate} for more information
*/
Sequelize.prototype.drop = function(options) {
Sequelize.prototype.truncate = function(options) {
var models = [];
this.modelManager.forEachModel(function(model) {
......@@ -896,23 +898,20 @@ module.exports = (function() {
}
}, { reverse: false });
return Promise.each(models, function(model) {
return model.drop(options);
return Promise.map(models, function(model) {
return model.truncate(options);
});
};
};
/**
* Truncate all tables defined through the sequelize models. This is done
* by calling Model.truncate() on each model.
/**
* Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model
* @see {Model#drop} for options
*
* @param {object} [options] The options passed to Model.destroy in addition to truncate
* @param {Boolean|function} [options.transaction]
* @param {Boolean|function} [options.logging] A function that logs sql queries, or false for no logging
* @param {object} options The options passed to each call to Model.drop
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise}
*
* @see {Model#truncate} for more information
*/
Sequelize.prototype.truncate = function(options) {
Sequelize.prototype.drop = function(options) {
var models = [];
this.modelManager.forEachModel(function(model) {
......@@ -921,12 +920,12 @@ module.exports = (function() {
}
}, { reverse: false });
return Promise.map(models, function(model) {
return model.truncate(options);
return Promise.each(models, function(model) {
return model.drop(options);
});
};
};
/**
/**
* Test the connection by trying to authenticate
*
* @fires success If authentication was successfull
......@@ -934,19 +933,19 @@ module.exports = (function() {
* @alias validate
* @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) {
throw new Error(err);
});
};
};
Sequelize.prototype.databaseVersion = function(options) {
Sequelize.prototype.databaseVersion = function(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.
* 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() {
* @since v2.0.0-dev3
* @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));
};
};
/**
/**
* 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}
*
......@@ -982,12 +981,12 @@ module.exports = (function() {
* @since v2.0.0-dev3
* @return {Sequelize.col}
*/
Sequelize.col = Sequelize.prototype.col = function(col) {
Sequelize.col = Sequelize.prototype.col = function(col) {
return new Utils.col(col);
};
};
/**
/**
* Creates a object representing a call to the cast function.
*
* @method cast
......@@ -996,11 +995,11 @@ module.exports = (function() {
* @since v2.0.0-dev3
* @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);
};
};
/**
/**
* Creates a object representing a literal, i.e. something that will not be escaped.
*
* @method literal
......@@ -1009,11 +1008,11 @@ module.exports = (function() {
* @since v2.0.0-dev3
* @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);
};
};
/**
/**
* An AND query
* @see {Model#find}
*
......@@ -1022,11 +1021,11 @@ module.exports = (function() {
* @since v2.0.0-dev3
* @return {Sequelize.and}
*/
Sequelize.and = Sequelize.prototype.and = function() {
Sequelize.and = Sequelize.prototype.and = function() {
return new Utils.and(Utils.sliceArgs(arguments));
};
};
/**
/**
* An OR query
* @see {Model#find}
*
......@@ -1035,11 +1034,11 @@ module.exports = (function() {
* @since v2.0.0-dev3
* @return {Sequelize.or}
*/
Sequelize.or = Sequelize.prototype.or = function() {
Sequelize.or = Sequelize.prototype.or = function() {
return new Utils.or(Utils.sliceArgs(arguments));
};
};
/**
/**
* Creates an object representing nested where conditions for postgres's json data-type.
* @see {Model#find}
*
......@@ -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>'".
* @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);
};
};
/*
/*
* 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
......@@ -1070,11 +1069,11 @@ module.exports = (function() {
* @since v2.0.0-dev3
* @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);
};
};
/**
/**
* 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
......@@ -1123,7 +1122,7 @@ module.exports = (function() {
* @fires error If there is an uncaught error during the transaction
* @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') {
autoCallback = options;
options = undefined;
......@@ -1167,9 +1166,9 @@ module.exports = (function() {
} else {
return transaction.prepareEnvironment().return(transaction);
}
};
};
Sequelize.prototype.log = function() {
Sequelize.prototype.log = function() {
var args = Utils.sliceArgs(arguments)
, last = Utils._.last(args)
, options;
......@@ -1191,19 +1190,19 @@ module.exports = (function() {
options.logging.apply(null, args);
}
};
};
/**
/**
* 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
* to garbage collect some of them.
*/
Sequelize.prototype.close = function () {
Sequelize.prototype.close = function () {
this.connectionManager.close();
};
};
Sequelize.prototype.normalizeDataType = function(Type) {
Sequelize.prototype.normalizeDataType = function(Type) {
var type = typeof Type === 'function' ? new Type() : Type
, dialectTypes = this.dialect.DataTypes || {};
......@@ -1215,8 +1214,8 @@ module.exports = (function() {
type.type = dialectTypes[type.type.key].extend(type.type);
}
return type;
};
Sequelize.prototype.normalizeAttribute = function(attribute) {
};
Sequelize.prototype.normalizeAttribute = function(attribute) {
if (!Utils._.isPlainObject(attribute)) {
attribute = { type: attribute };
}
......@@ -1231,9 +1230,7 @@ module.exports = (function() {
}
return attribute;
};
};
// Allows the promise to access cls namespaces
Promise.Sequelize = Sequelize;
return Sequelize;
})();
// Allows the promise to access cls namespaces
module.exports = Promise.Sequelize = Sequelize;
......@@ -3,7 +3,7 @@
var DataTypes = require('./data-types')
, SqlString = require('./sql-string')
, lodash = require('lodash')
, ParameterValidator = require('./utils/parameter-validator')
, parameterValidator = require('./utils/parameter-validator')
, inflection = require('inflection')
, dottie = require('dottie')
, uuid = require('node-uuid')
......@@ -398,9 +398,7 @@ var Utils = module.exports = {
this.logic = logic;
},
validateParameter: function(value, expectation, options) {
return ParameterValidator.check(value, expectation, options);
},
validateParameter: parameterValidator,
formatReferences: function (obj) {
if (!lodash.isPlainObject(obj.references)) {
......
......@@ -3,7 +3,7 @@
var _ = require('lodash');
var util = require('util');
var validateDeprecation = function(value, expectation, options) {
function validateDeprecation (value, expectation, options) {
if (!options.deprecated) {
return;
}
......@@ -17,9 +17,9 @@ var validateDeprecation = function(value, expectation, options) {
}
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
// 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())) {
......@@ -27,10 +27,9 @@ var validate = function(value, expectation) {
}
throw new Error(util.format('The parameter (value: %s) is no %s.', value, expectation.name));
};
}
module.exports = {
check: function(value, expectation, options) {
function check (value, expectation, options) {
options = _.extend({
deprecated: false,
index: null,
......@@ -53,5 +52,6 @@ module.exports = {
return false
|| validateDeprecation(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!