sequelize
Advanced tools
Comparing version 2.0.0-beta.1 to 2.0.0-beta.2
@@ -35,4 +35,4 @@ var Utils = require("./../utils") | ||
// Sync attributes to DAO proto each time a new assoc is added | ||
this.source.DAO.prototype.attributes = Object.keys(this.source.DAO.prototype.rawAttributes) | ||
// Sync attributes and setters/getters to DAO prototype | ||
this.source.refreshAttributes() | ||
@@ -49,4 +49,5 @@ return this | ||
obj[accessor] = function(params) { | ||
var id = this[self.identifier] | ||
, where = {} | ||
var id = this[self.identifier] | ||
, where = {} | ||
, options = Utils._.pick(params || {}, 'transaction') | ||
@@ -65,3 +66,3 @@ where[primaryKey] = id | ||
return self.target.find(params) | ||
return self.target.find(params, options) | ||
} | ||
@@ -76,3 +77,3 @@ | ||
obj[accessor] = function(associatedObject) { | ||
obj[accessor] = function(associatedObject, options) { | ||
var primaryKeys = !!associatedObject && !!associatedObject.daoFactory ? Object.keys(associatedObject.daoFactory.primaryKeys) : [] | ||
@@ -82,5 +83,6 @@ , primaryKey = primaryKeys.length === 1 ? primaryKeys[0] : 'id' | ||
this[self.identifier] = associatedObject ? associatedObject[primaryKey] : null | ||
options = Utils._.extend({ fields: [ self.identifier ], allowNull: [self.identifier] }, options) | ||
// passes the changed field to save, so only that field get updated. | ||
return this.save([ self.identifier ], {allowNull: [self.identifier]}) | ||
return this.save(options) | ||
} | ||
@@ -87,0 +89,0 @@ |
@@ -1,2 +0,3 @@ | ||
var Utils = require('./../utils') | ||
var Utils = require('./../utils') | ||
, Transaction = require('./../transaction') | ||
@@ -13,3 +14,5 @@ module.exports = (function() { | ||
HasManyDoubleLinked.prototype.injectGetter = function(options) { | ||
var self = this, _options = options | ||
var self = this | ||
, _options = options | ||
, smart | ||
@@ -50,3 +53,3 @@ var customEventEmitter = new Utils.CustomEventEmitter(function() { | ||
options.attributes.push( | ||
self.QueryInterface.quoteIdentifiers(connectorDAO.tableName + '.' + elem) + ' as ' + | ||
self.QueryInterface.quoteIdentifiers(connectorDAO.tableName + '.' + elem) + ' as ' + | ||
self.QueryInterface.quoteIdentifier(connectorDAO.name + '.' + elem, true) | ||
@@ -58,3 +61,3 @@ ) | ||
options.attributes.push( | ||
self.QueryInterface.quoteIdentifiers(connectorDAO.tableName + '.' + key) + ' as ' + | ||
self.QueryInterface.quoteIdentifiers(connectorDAO.tableName + '.' + key) + ' as ' + | ||
self.QueryInterface.quoteIdentifier(connectorDAO.name + '.' + key, true) | ||
@@ -94,12 +97,18 @@ ) | ||
HasManyDoubleLinked.prototype.injectSetter = function(emitterProxy, oldAssociations, newAssociations, defaultAttributes) { | ||
var self = this | ||
, chainer = new Utils.QueryChainer() | ||
, association = self.__factory.target.associations[self.__factory.associationAccessor] | ||
, foreignIdentifier = association.isSelfAssociation ? association.foreignIdentifier : association.identifier | ||
, sourceKeys = Object.keys(self.__factory.source.primaryKeys) | ||
, targetKeys = Object.keys(self.__factory.target.primaryKeys) | ||
var self = this | ||
, chainer = new Utils.QueryChainer() | ||
, association = self.__factory.target.associations[self.__factory.associationAccessor] | ||
, foreignIdentifier = association.isSelfAssociation ? association.foreignIdentifier : association.identifier | ||
, sourceKeys = Object.keys(self.__factory.source.primaryKeys) | ||
, targetKeys = Object.keys(self.__factory.target.primaryKeys) | ||
, obsoleteAssociations = [] | ||
, changedAssociations = [] | ||
, changedAssociations = [] | ||
, options = {} | ||
, unassociatedObjects; | ||
if ((defaultAttributes || {}).transaction instanceof Transaction) { | ||
options.transaction = defaultAttributes.transaction | ||
delete defaultAttributes.transaction | ||
} | ||
unassociatedObjects = newAssociations.filter(function (obj) { | ||
@@ -126,3 +135,3 @@ return !Utils._.find(oldAssociations, function (old) { | ||
changedAssociation.where[foreignIdentifier] = newObj[foreignIdentifier] || newObj.id | ||
changedAssociations.push(changedAssociation) | ||
@@ -138,6 +147,7 @@ } | ||
var where = {} | ||
where[self.__factory.identifier] = ((sourceKeys.length === 1) ? self.instance[sourceKeys[0]] : self.instance.id) | ||
where[foreignIdentifier] = foreignIds | ||
chainer.add(self.__factory.connectorDAO.destroy(where)) | ||
chainer.add(self.__factory.connectorDAO.destroy(where, options)) | ||
} | ||
@@ -148,2 +158,3 @@ | ||
var attributes = {} | ||
attributes[self.__factory.identifier] = ((sourceKeys.length === 1) ? self.instance[sourceKeys[0]] : self.instance.id) | ||
@@ -155,7 +166,7 @@ attributes[foreignIdentifier] = ((targetKeys.length === 1) ? unassociatedObject[targetKeys[0]] : unassociatedObject.id) | ||
} | ||
return attributes | ||
}) | ||
chainer.add(self.__factory.connectorDAO.bulkCreate(bulk)) | ||
chainer.add(self.__factory.connectorDAO.bulkCreate(bulk, options)) | ||
} | ||
@@ -165,3 +176,3 @@ | ||
changedAssociations.forEach(function (assoc) { | ||
chainer.add(self.__factory.connectorDAO.update(assoc.attributes, assoc.where)) | ||
chainer.add(self.__factory.connectorDAO.update(assoc.attributes, assoc.where, options)) | ||
}) | ||
@@ -201,3 +212,3 @@ } | ||
.error(function(err) { emitterProxy.emit('error', err) }) | ||
.on('sql', function(sql) { emitterProxy.emit('sql', sql) }) | ||
.on('sql', function(sql) { emitterProxy.emit('sql', sql) }) | ||
} | ||
@@ -204,0 +215,0 @@ } |
@@ -1,2 +0,3 @@ | ||
var Utils = require('./../utils') | ||
var Utils = require('./../utils') | ||
, Transaction = require('./../transaction') | ||
@@ -12,2 +13,3 @@ module.exports = (function() { | ||
, where = {} | ||
, smart | ||
options = options || {} | ||
@@ -32,7 +34,8 @@ | ||
HasManySingleLinked.prototype.injectSetter = function(emitter, oldAssociations, newAssociations) { | ||
var self = this | ||
, associationKeys = Object.keys((oldAssociations[0] || newAssociations[0] || {daoFactory: {primaryKeys: {}}}).daoFactory.primaryKeys || {}) | ||
, associationKey = associationKeys.length === 1 ? associationKeys[0] : 'id' | ||
, chainer = new Utils.QueryChainer() | ||
HasManySingleLinked.prototype.injectSetter = function(emitter, oldAssociations, newAssociations, defaultAttributes) { | ||
var self = this | ||
, associationKeys = Object.keys((oldAssociations[0] || newAssociations[0] || {daoFactory: {primaryKeys: {}}}).daoFactory.primaryKeys || {}) | ||
, associationKey = (associationKeys.length === 1) ? associationKeys[0] : 'id' | ||
, chainer = new Utils.QueryChainer() | ||
, options = {} | ||
, obsoleteAssociations = oldAssociations.filter(function (old) { | ||
@@ -43,3 +46,3 @@ return !Utils._.find(newAssociations, function (obj) { | ||
}) | ||
, unassociatedObjects = newAssociations.filter(function (obj) { | ||
, unassociatedObjects = newAssociations.filter(function (obj) { | ||
return !Utils._.find(oldAssociations, function (old) { | ||
@@ -51,2 +54,7 @@ return obj[associationKey] === old[associationKey] | ||
if ((defaultAttributes || {}).transaction instanceof Transaction) { | ||
options.transaction = defaultAttributes.transaction | ||
delete defaultAttributes.transaction | ||
} | ||
if (obsoleteAssociations.length > 0) { | ||
@@ -61,8 +69,13 @@ // clear the old associations | ||
update[self.__factory.identifier] = null | ||
var primaryKeys = Object.keys(this.__factory.target.primaryKeys) | ||
, primaryKey = primaryKeys.length === 1 ? primaryKeys[0] : 'id' | ||
, primaryKey = primaryKeys.length === 1 ? primaryKeys[0] : 'id' | ||
, updateWhere = {} | ||
updateWhere[primaryKey] = obsoleteIds | ||
chainer.add(this.__factory.target.update(update, updateWhere, {allowNull: [self.__factory.identifier]})) | ||
chainer.add(this.__factory.target.update( | ||
update, | ||
updateWhere, | ||
Utils._.extend(options, { allowNull: [self.__factory.identifier] }) | ||
)) | ||
} | ||
@@ -72,7 +85,7 @@ | ||
// For the self.instance | ||
var pkeys = Object.keys(self.instance.daoFactory.primaryKeys) | ||
, pkey = pkeys.length === 1 ? pkeys[0] : 'id' | ||
var pkeys = Object.keys(self.instance.daoFactory.primaryKeys) | ||
, pkey = pkeys.length === 1 ? pkeys[0] : 'id' | ||
// For chainer | ||
, primaryKeys = Object.keys(this.__factory.target.primaryKeys) | ||
, primaryKey = primaryKeys.length === 1 ? primaryKeys[0] : 'id' | ||
, primaryKey = primaryKeys.length === 1 ? primaryKeys[0] : 'id' | ||
, updateWhere = {} | ||
@@ -86,6 +99,11 @@ | ||
update = {} | ||
update = {} | ||
update[self.__factory.identifier] = (newAssociations.length < 1 ? null : self.instance[pkey] || self.instance.id) | ||
updateWhere[primaryKey] = unassociatedIds | ||
chainer.add(this.__factory.target.update(update, updateWhere, {allowNull: [self.__factory.identifier]})) | ||
updateWhere[primaryKey] = unassociatedIds | ||
chainer.add(this.__factory.target.update( | ||
update, | ||
updateWhere, | ||
Utils._.extend(options, { allowNull: [self.__factory.identifier] }) | ||
)) | ||
} | ||
@@ -92,0 +110,0 @@ |
@@ -112,5 +112,5 @@ var Utils = require("./../utils") | ||
// Sync attributes to DAO proto each time a new assoc is added | ||
this.target.DAO.prototype.attributes = Object.keys(this.target.DAO.prototype.rawAttributes); | ||
this.source.DAO.prototype.attributes = Object.keys(this.source.DAO.prototype.rawAttributes); | ||
// Sync attributes and setters/getters to DAO prototype | ||
this.target.refreshAttributes() | ||
this.source.refreshAttributes() | ||
@@ -128,18 +128,18 @@ return this | ||
obj[this.accessors.hasAll] = function(objects) { | ||
obj[this.accessors.hasAll] = function(objects, options) { | ||
var instance = this; | ||
var customEventEmitter = new Utils.CustomEventEmitter(function() { | ||
instance[self.accessors.get]() | ||
.error(function(err){ customEventEmitter.emit('error', err)}) | ||
.success(function(associatedObjects) { | ||
customEventEmitter.emit('success', | ||
Utils._.all(objects, function(o) { | ||
return Utils._.any(associatedObjects, function(associatedObject) { | ||
return Utils._.all(associatedObject.identifiers, function(key, identifier) { | ||
return o[identifier] == associatedObject[identifier]; | ||
}); | ||
instance[self.accessors.get](options) | ||
.error(function(err) { customEventEmitter.emit('error', err) }) | ||
.success(function(associatedObjects) { | ||
customEventEmitter.emit('success', | ||
Utils._.all(objects, function(o) { | ||
return Utils._.any(associatedObjects, function(associatedObject) { | ||
return Utils._.all(associatedObject.identifiers, function(key, identifier) { | ||
return o[identifier] == associatedObject[identifier]; | ||
}); | ||
}) | ||
}) | ||
}) | ||
) | ||
}) | ||
) | ||
}) | ||
}) | ||
@@ -149,6 +149,6 @@ return customEventEmitter.run() | ||
obj[this.accessors.hasSingle] = function(o) { | ||
var instance = this; | ||
obj[this.accessors.hasSingle] = function(o, options) { | ||
var instance = this | ||
var customEventEmitter = new Utils.CustomEventEmitter(function() { | ||
instance[self.accessors.get]() | ||
instance[self.accessors.get](options) | ||
.error(function(err){ customEventEmitter.emit('error', err)}) | ||
@@ -155,0 +155,0 @@ .success(function(associatedObjects) { |
@@ -40,5 +40,4 @@ var Utils = require("./../utils") | ||
// Sync attributes to DAO proto each time a new assoc is added | ||
this.target.DAO.prototype.attributes = Object.keys(this.target.DAO.prototype.rawAttributes); | ||
// Sync attributes and setters/getters to DAO prototype | ||
this.target.refreshAttributes() | ||
return this | ||
@@ -49,2 +48,3 @@ } | ||
var self = this | ||
, smart | ||
@@ -82,6 +82,6 @@ obj[this.accessors.get] = function(params) { | ||
obj[this.accessors.set] = function(associatedObject) { | ||
var instance = this | ||
obj[this.accessors.set] = function(associatedObject, options) { | ||
var instance = this | ||
, instanceKeys = Object.keys(instance.daoFactory.primaryKeys) | ||
, instanceKey = instanceKeys.length === 1 ? instanceKeys[0] : 'id' | ||
, instanceKey = instanceKeys.length === 1 ? instanceKeys[0] : 'id' | ||
@@ -92,13 +92,20 @@ return new Utils.CustomEventEmitter(function(emitter) { | ||
oldObj[self.identifier] = null | ||
oldObj.save([self.identifier], {allowNull: [self.identifier]}).success(function() { | ||
if (associatedObject) { | ||
associatedObject[self.identifier] = instance[instanceKey] | ||
associatedObject | ||
.save() | ||
.success(function() { emitter.emit('success', associatedObject) }) | ||
.error(function(err) { emitter.emit('error', err) }) | ||
} else { | ||
emitter.emit('success', null) | ||
} | ||
}) | ||
oldObj | ||
.save( | ||
Utils._.extend({}, options, { | ||
fields: [self.identifier], | ||
allowNull: [self.identifier] | ||
}) | ||
) | ||
.success(function() { | ||
if (associatedObject) { | ||
associatedObject[self.identifier] = instance[instanceKey] | ||
associatedObject | ||
.save(options) | ||
.success(function() { emitter.emit('success', associatedObject) }) | ||
.error(function(err) { emitter.emit('error', err) }) | ||
} else { | ||
emitter.emit('success', null) | ||
} | ||
}) | ||
} else { | ||
@@ -108,3 +115,3 @@ if (associatedObject) { | ||
associatedObject | ||
.save() | ||
.save(options) | ||
.success(function() { emitter.emit('success', associatedObject) }) | ||
@@ -111,0 +118,0 @@ .error(function(err) { emitter.emit('error', err) }) |
@@ -1,7 +0,8 @@ | ||
var Utils = require("./utils") | ||
, DAO = require("./dao") | ||
, DataTypes = require("./data-types") | ||
, Util = require('util') | ||
, sql = require('sql') | ||
, SqlString = require('./sql-string') | ||
var Utils = require("./utils") | ||
, DAO = require("./dao") | ||
, DataTypes = require("./data-types") | ||
, Util = require('util') | ||
, sql = require('sql') | ||
, SqlString = require('./sql-string') | ||
, Transaction = require('./transaction') | ||
@@ -95,4 +96,9 @@ module.exports = (function() { | ||
result.exec = function() { | ||
return self.QueryInterface.queryAndEmit([result.toSql(), self, { type: 'SELECT' }], 'snafu') | ||
result.exec = function(options) { | ||
options = Utils._.extend({ | ||
transaction: null, | ||
type: 'SELECT' | ||
}, options || {}) | ||
return self.QueryInterface.queryAndEmit([result.toSql(), self, options], 'snafu') | ||
} | ||
@@ -145,24 +151,4 @@ | ||
Utils._.each(['Get', 'Set'], function(type) { | ||
var prop = type.toLowerCase() | ||
, opt = prop + 'terMethods' | ||
, meth = '__define' + type + 'ter__' | ||
, funcs = Utils._.isObject(self.options[opt]) ? self.options[opt] : {} | ||
this.refreshAttributes(); | ||
Utils._.each(self.rawAttributes, function(attr, name) { | ||
if (attr.hasOwnProperty(prop)) { | ||
funcs[name] = attr[prop] | ||
} | ||
}) | ||
Utils._.each(funcs, function(fct, name) { | ||
if (!Utils._.isFunction(fct)) { | ||
throw new Error(type + 'ter for "' + name + '" is not a function.') | ||
} | ||
self.DAO.prototype[meth](name, fct) | ||
}) | ||
}) | ||
this.DAO.prototype.attributes = Object.keys(this.DAO.prototype.rawAttributes); | ||
this.DAO.prototype.booleanValues = [] | ||
@@ -192,2 +178,49 @@ this.DAO.prototype.defaultValues = {} | ||
DAOFactory.prototype.refreshAttributes = function() { | ||
var self = this | ||
, attributeManipulation = {}; | ||
Utils._.each(['get', 'set'], function(type) { | ||
var opt = type + 'terMethods' | ||
, funcs = Utils._.isObject(self.options[opt]) ? self.options[opt] : {} | ||
Utils._.each(self.rawAttributes, function(options, attribute) { | ||
if (options.hasOwnProperty(type)) { | ||
funcs[attribute] = options[type] | ||
} else if (typeof funcs[attribute] === "undefined") { | ||
if (type === 'get') { | ||
funcs[attribute] = function() { return this.dataValues[attribute]; } | ||
} | ||
if (type === 'set') { | ||
funcs[attribute] = function(value) { | ||
if (Utils.hasChanged(this.dataValues[attribute], value)) { | ||
//Only dirty the object if the change is not due to id, touchedAt, createdAt or updatedAt being initiated | ||
var updatedAtAttr = Utils._.underscoredIf(this.__options.updatedAt, this.__options.underscored) | ||
, createdAtAttr = Utils._.underscoredIf(this.__options.createdAt, this.__options.underscored) | ||
, touchedAtAttr = Utils._.underscoredIf(this.__options.touchedAt, this.__options.underscored) | ||
if (this.dataValues[attribute] || (attribute != 'id' && attribute != touchedAtAttr && attribute != createdAtAttr && attribute != updatedAtAttr)) { | ||
this.isDirty = true | ||
} | ||
} | ||
this.dataValues[attribute] = value | ||
} | ||
} | ||
} | ||
}) | ||
Utils._.each(funcs, function(fct, name) { | ||
if (!attributeManipulation[name]) { | ||
attributeManipulation[name] = { | ||
configurable: true | ||
} | ||
} | ||
attributeManipulation[name][type] = fct | ||
}) | ||
}) | ||
Object.defineProperties(this.DAO.prototype, attributeManipulation) | ||
this.DAO.prototype.attributes = Object.keys(this.DAO.prototype.rawAttributes) | ||
} | ||
DAOFactory.prototype.sync = function(options) { | ||
@@ -197,5 +230,7 @@ options = Utils._.extend({}, this.options, options || {}) | ||
var self = this | ||
return new Utils.CustomEventEmitter(function(emitter) { | ||
var doQuery = function() { | ||
self.QueryInterface | ||
self | ||
.QueryInterface | ||
.createTable(self.getTableName(), self.attributes, options) | ||
@@ -208,3 +243,6 @@ .success(function() { emitter.emit('success', self) }) | ||
if (options.force) { | ||
self.drop(options).success(doQuery).error(function(err) { emitter.emit('error', err) }) | ||
self | ||
.drop(options) | ||
.success(doQuery) | ||
.error(function(err) { emitter.emit('error', err) }) | ||
} else { | ||
@@ -220,2 +258,3 @@ doQuery() | ||
, tableName = isPostgres ? this.tableName : this.getTableName() | ||
return this.QueryInterface.dropTable(tableName, options) | ||
@@ -256,2 +295,3 @@ } | ||
, scopeName | ||
, scopeOptions | ||
, argLength = arguments.length | ||
@@ -357,3 +397,3 @@ , lastArg = arguments[argLength-1] | ||
hasJoin: hasJoin | ||
}, queryOptions)) | ||
}, queryOptions, { transaction: (options || {}).transaction })) | ||
} | ||
@@ -371,3 +411,3 @@ | ||
type: 'SELECT' | ||
}, queryOptions)) | ||
}, queryOptions, { transaction: (options || {}).transaction })) | ||
} | ||
@@ -538,15 +578,34 @@ | ||
DAOFactory.prototype.create = function(values, fields) { | ||
return this.build(values).save(fields) | ||
DAOFactory.prototype.create = function(values, fieldsOrOptions) { | ||
Utils.validateParameter(values, Object, { optional: true }) | ||
Utils.validateParameter(fieldsOrOptions, Object, { deprecated: Array, optional: true, index: 2, method: 'DAOFactory#create' }) | ||
if (fieldsOrOptions instanceof Array) { | ||
fieldsOrOptions = { fields: fieldsOrOptions } | ||
} | ||
fieldsOrOptions = Utils._.extend({ | ||
transaction: null | ||
}, fieldsOrOptions || {}) | ||
return this.build(values).save(fieldsOrOptions) | ||
} | ||
DAOFactory.prototype.findOrInitialize = DAOFactory.prototype.findOrBuild = function (params, defaults) { | ||
DAOFactory.prototype.findOrInitialize = DAOFactory.prototype.findOrBuild = function (params, defaults, options) { | ||
defaults = defaults || {} | ||
options = options || {} | ||
var self = this | ||
, defaultKeys = Object.keys(defaults || {}) | ||
, defaultKeys = Object.keys(defaults) | ||
, defaultLength = defaultKeys.length | ||
if (!options.transaction && defaults.transaction && (defaults.transaction instanceof Transaction)) { | ||
options.transaction = defaults.transaction | ||
delete defaults.transaction | ||
} | ||
return new Utils.CustomEventEmitter(function (emitter) { | ||
self.find({ | ||
where: params | ||
}).success(function (instance) { | ||
}, options).success(function (instance) { | ||
if (instance === null) { | ||
@@ -576,8 +635,19 @@ var i = 0 | ||
DAOFactory.prototype.findOrCreate = function (params, defaults) { | ||
var self = this; | ||
DAOFactory.prototype.findOrCreate = function (where, defaults, options) { | ||
var self = this | ||
, params = {} | ||
options = Utils._.extend({ | ||
transaction: null | ||
}, options || {}) | ||
for (var attrname in where) { | ||
params[attrname] = where[attrname] | ||
} | ||
return new Utils.CustomEventEmitter(function (emitter) { | ||
self.find({ | ||
where: params | ||
}, { | ||
transaction: options.transaction | ||
}).success(function (instance) { | ||
@@ -589,3 +659,4 @@ if (instance === null) { | ||
self.create(params) | ||
self | ||
.create(params, options) | ||
.success(function (instance) { | ||
@@ -620,9 +691,18 @@ emitter.emit('success', instance, true) | ||
DAOFactory.prototype.bulkCreate = function(records, fields, options) { | ||
options = options || {} | ||
options.validate = options.validate === undefined ? false : Boolean(options.validate) | ||
options.hooks = options.hooks === undefined ? false : Boolean(options.hooks) | ||
DAOFactory.prototype.bulkCreate = function(records, fieldsOrOptions, options) { | ||
Utils.validateParameter(fieldsOrOptions, Object, { deprecated: Array, optional: true, index: 2, method: 'DAOFactory#bulkCreate' }) | ||
Utils.validateParameter(options, 'undefined', { deprecated: Object, optional: true, index: 3, method: 'DAOFactory#bulkCreate' }) | ||
fields = fields || [] | ||
options = Utils._.extend({ | ||
validate: false, | ||
hooks: false | ||
}, options || {}) | ||
if (fieldsOrOptions instanceof Array) { | ||
options.fields = fieldsOrOptions | ||
} else { | ||
options.fields = options.fields || [] | ||
options = Utils._.extend(options, fieldsOrOptions) | ||
} | ||
var self = this | ||
@@ -632,9 +712,7 @@ , updatedAtAttr = Utils._.underscoredIf(self.options.updatedAt, self.options.underscored) | ||
, errors = [] | ||
, daos = records.map(function(v) { | ||
return self.build(v) | ||
}) | ||
, daos = records.map(function(v) { return self.build(v) }) | ||
return new Utils.CustomEventEmitter(function(emitter) { | ||
var done = function() { | ||
self.runHooks('afterBulkCreate', daos, fields, function(err, newRecords, newFields) { | ||
self.runHooks('afterBulkCreate', daos, options.fields, function(err, newRecords, newFields) { | ||
if (!!err) { | ||
@@ -644,6 +722,6 @@ return emitter.emit('error', err) | ||
daos = newRecords || daos | ||
fields = newFields || fields | ||
daos = newRecords || daos | ||
options.fields = newFields || options.fields | ||
emitter.emit('success', daos, fields) | ||
emitter.emit('success', daos, options.fields) | ||
}) | ||
@@ -669,3 +747,3 @@ } | ||
daos[i] = newValues || daos[i] | ||
daos[i].save().error(function(err) { | ||
daos[i].save({ transaction: options.transaction }).error(function(err) { | ||
emitter.emit('error', err) | ||
@@ -698,5 +776,5 @@ }).success(function() { | ||
daos.forEach(function(dao) { | ||
var values = fields.length > 0 ? {} : dao.dataValues | ||
var values = options.fields.length > 0 ? {} : dao.dataValues | ||
fields.forEach(function(field) { | ||
options.fields.forEach(function(field) { | ||
values[field] = dao.dataValues[field] | ||
@@ -718,3 +796,3 @@ }) | ||
self.QueryInterface.bulkInsert(self.tableName, records) | ||
self.QueryInterface.bulkInsert(self.tableName, records, options) | ||
.on('sql', function(sql) { | ||
@@ -730,3 +808,3 @@ emitter.emit('sql', sql) | ||
self.runHooks('beforeBulkCreate', daos, fields, function(err, newRecords, newFields) { | ||
self.runHooks('beforeBulkCreate', daos, options.fields, function(err, newRecords, newFields) { | ||
if (!!err) { | ||
@@ -736,4 +814,4 @@ return emitter.emit('error', err) | ||
daos = newRecords || daos | ||
fields = newFields || fields | ||
daos = newRecords || daos | ||
options.fields = newFields || options.fields | ||
@@ -743,3 +821,3 @@ if (options.validate === true) { | ||
var iterate = function(i) { | ||
daos[i].hookValidate({skip: fields}).complete(function (err) { | ||
daos[i].hookValidate({skip: options.fields}).complete(function (err) { | ||
if (!!err) { | ||
@@ -758,3 +836,3 @@ errors.push({record: v, errors: err}) | ||
} else { | ||
var afterDaos = Utils._.after(daos.length, function() { | ||
var afterDaos = Utils._.after(daos.length, function() { | ||
next(errors.length > 0 ? errors : null) | ||
@@ -764,3 +842,3 @@ }) | ||
daos.forEach(function(v) { | ||
v.validate({skip: fields}).success(function(err) { | ||
v.validate({skip: options.fields}).success(function(err) { | ||
if (!!err) { | ||
@@ -1055,3 +1133,3 @@ errors.push({record: v, errors: err}) | ||
DAOFactory.prototype.__setSqlDialect = function() { | ||
var dialect = this.daoFactoryManager.sequelize.options.dialect | ||
var dialect = this.daoFactoryManager.sequelize.options.dialect | ||
this.__sql = sql.setDialect(dialect === 'mariadb' ? 'mysql' : dialect) | ||
@@ -1058,0 +1136,0 @@ } |
@@ -76,2 +76,3 @@ var Validator = require("validator") | ||
var next = function(err) { | ||
if (err) { | ||
@@ -141,4 +142,29 @@ var error = {} | ||
isCustomValidator = true | ||
var callArgs = [] | ||
var validatorArity = details.length | ||
var omitValue = !!(options || {}).omitValue | ||
if (!omitValue) { | ||
callArgs.push(value) | ||
} | ||
// check if validator is async and requires a callback | ||
var isAsync = omitValue && validatorArity === 1 || | ||
!omitValue && validatorArity === 2 | ||
validatorFunction = function(next) { | ||
details.apply(this.model, ((options || {}).omitValue) ? [next] : [value, next]) | ||
if (isAsync) { | ||
callArgs.push(next) | ||
} | ||
try { | ||
details.apply(this.model, callArgs) | ||
} catch(ex) { | ||
return next(ex.message) | ||
} | ||
if (!isAsync) { | ||
next() | ||
} | ||
}.bind(this) | ||
@@ -145,0 +171,0 @@ } else { |
147
lib/dao.js
@@ -99,16 +99,22 @@ var Utils = require("./utils") | ||
// only those fields will be updated | ||
DAO.prototype.save = function(fields, options) { | ||
DAO.prototype.save = function(fieldsOrOptions, options) { | ||
if (fieldsOrOptions instanceof Array) { | ||
fieldsOrOptions = { fields: fieldsOrOptions } | ||
} | ||
options = Utils._.extend({}, options, fieldsOrOptions) | ||
var self = this | ||
, values = fields ? {} : this.dataValues | ||
, values = options.fields ? {} : this.dataValues | ||
, updatedAtAttr = Utils._.underscoredIf(this.__options.updatedAt, this.__options.underscored) | ||
, createdAtAttr = Utils._.underscoredIf(this.__options.createdAt, this.__options.underscored) | ||
if (fields) { | ||
if (options.fields) { | ||
if (self.__options.timestamps) { | ||
if (fields.indexOf(updatedAtAttr) === -1) { | ||
fields.push(updatedAtAttr) | ||
if (options.fields.indexOf(updatedAtAttr) === -1) { | ||
options.fields.push(updatedAtAttr) | ||
} | ||
if (fields.indexOf(createdAtAttr) === -1 && this.isNewRecord === true) { | ||
fields.push(createdAtAttr) | ||
if (options.fields.indexOf(createdAtAttr) === -1 && this.isNewRecord === true) { | ||
options.fields.push(createdAtAttr) | ||
} | ||
@@ -119,3 +125,3 @@ } | ||
fields.forEach(function(field) { | ||
options.fields.forEach(function(field) { | ||
if (tmpVals[field] !== undefined) { | ||
@@ -139,5 +145,6 @@ values[field] = tmpVals[field] | ||
, ciCollation = !!self.daoFactory.options.collate && self.daoFactory.options.collate.match(/_ci$/i) | ||
, valueOutOfScope | ||
// Unfortunately for MySQL CI collation we need to map/lowercase values again | ||
if (isEnum && isMySQL && ciCollation && (attrName in values)) { | ||
if (isEnum && isMySQL && ciCollation && (attrName in values) && values[attrName]) { | ||
var scopeIndex = (definition.values || []).map(function(d) { return d.toLowerCase() }).indexOf(values[attrName].toLowerCase()) | ||
@@ -178,3 +185,3 @@ valueOutOfScope = scopeIndex === -1 | ||
query = 'insert' | ||
args = [self, self.QueryInterface.QueryGenerator.addSchema(self.__factory), values] | ||
args = [self, self.QueryInterface.QueryGenerator.addSchema(self.__factory), values, options] | ||
hook = 'Create' | ||
@@ -231,3 +238,3 @@ } else { | ||
*/ | ||
DAO.prototype.reload = function() { | ||
DAO.prototype.reload = function(options) { | ||
var where = [ | ||
@@ -243,3 +250,3 @@ this.QueryInterface.quoteIdentifier(this.__factory.tableName) + '.' + this.QueryInterface.quoteIdentifier('id')+'=?', | ||
include: this.__eagerlyLoadedOptions || [] | ||
}) | ||
}, options) | ||
.on('sql', function(sql) { emitter.emit('sql', sql) }) | ||
@@ -279,5 +286,10 @@ .on('error', function(error) { emitter.emit('error', error) }) | ||
DAO.prototype.updateAttributes = function(updates, fields) { | ||
DAO.prototype.updateAttributes = function(updates, fieldsOrOptions) { | ||
if (fieldsOrOptions instanceof Array) { | ||
fieldsOrOptions = { fields: fieldsOrOptions } | ||
} | ||
this.setAttributes(updates) | ||
return this.save(fields) | ||
return this.save(fieldsOrOptions) | ||
} | ||
@@ -324,3 +336,3 @@ | ||
DAO.prototype.destroy = function() { | ||
DAO.prototype.destroy = function(options) { | ||
var self = this | ||
@@ -338,6 +350,6 @@ , query = null | ||
self.dataValues[attr] = new Date() | ||
query = self.save() | ||
query = self.save(options) | ||
} else { | ||
var identifier = self.__options.hasPrimaryKeys ? self.primaryKeyValues : { id: self.id }; | ||
query = self.QueryInterface.delete(self, self.QueryInterface.QueryGenerator.addSchema(self.__factory.tableName, self.__factory.options.schema), identifier) | ||
query = self.QueryInterface.delete(self, self.QueryInterface.QueryGenerator.addSchema(self.__factory.tableName, self.__factory.options.schema), identifier, options) | ||
} | ||
@@ -364,31 +376,69 @@ | ||
DAO.prototype.increment = function(fields, count) { | ||
var identifier = this.__options.hasPrimaryKeys ? this.primaryKeyValues : { id: this.id }, | ||
values = {} | ||
DAO.prototype.increment = function(fields, countOrOptions) { | ||
Utils.validateParameter(countOrOptions, Object, { | ||
optional: true, | ||
deprecated: 'number', | ||
deprecationWarning: "Increment expects an object as second parameter. Please pass the incrementor as option! ~> instance.increment(" + JSON.stringify(fields) + ", { by: " + countOrOptions + " })" | ||
}) | ||
if (count === undefined) { | ||
count = 1; | ||
var identifier = this.__options.hasPrimaryKeys ? this.primaryKeyValues : { id: this.id } | ||
, updatedAtAttr = Utils._.underscoredIf(this.__options.updatedAt, this.__options.underscored) | ||
, values = {} | ||
if (countOrOptions === undefined) { | ||
countOrOptions = { by: 1, transaction: null } | ||
} else if (typeof countOrOptions === 'number') { | ||
countOrOptions = { by: countOrOptions, transaction: null } | ||
} | ||
countOrOptions = Utils._.extend({ | ||
by: 1, | ||
attributes: {} | ||
}, countOrOptions) | ||
if (Utils._.isString(fields)) { | ||
values[fields] = count; | ||
values[fields] = countOrOptions.by | ||
} else if (Utils._.isArray(fields)) { | ||
Utils._.each(fields, function (field) { | ||
values[field] = count | ||
values[field] = countOrOptions.by | ||
}) | ||
} else { // Assume fields is key-value pairs | ||
values = fields; | ||
values = fields | ||
} | ||
return this.QueryInterface.increment(this, this.QueryInterface.QueryGenerator.addSchema(this.__factory.tableName, this.__factory.options.schema), values, identifier) | ||
if (this.__options.timestamps) { | ||
if (!values[updatedAtAttr]) { | ||
countOrOptions.attributes[updatedAtAttr] = Utils.now(this.daoFactory.daoFactoryManager.sequelize.options.dialect) | ||
} | ||
} | ||
return this.QueryInterface.increment(this, this.QueryInterface.QueryGenerator.addSchema(this.__factory.tableName, this.__factory.options.schema), values, identifier, countOrOptions) | ||
} | ||
DAO.prototype.decrement = function (fields, count) { | ||
DAO.prototype.decrement = function (fields, countOrOptions) { | ||
Utils.validateParameter(countOrOptions, Object, { | ||
optional: true, | ||
deprecated: 'number', | ||
deprecationWarning: "Decrement expects an object as second parameter. Please pass the decrementor as option! ~> instance.decrement(" + JSON.stringify(fields) + ", { by: " + countOrOptions + " })" | ||
}) | ||
if (countOrOptions === undefined) { | ||
countOrOptions = { by: 1, transaction: null } | ||
} else if (typeof countOrOptions === 'number') { | ||
countOrOptions = { by: countOrOptions, transaction: null } | ||
} | ||
if (countOrOptions.by === undefined) { | ||
countOrOptions.by = 1 | ||
} | ||
if (!Utils._.isString(fields) && !Utils._.isArray(fields)) { // Assume fields is key-value pairs | ||
Utils._.each(fields, function (value, field) { | ||
fields[field] = -value; | ||
}); | ||
fields[field] = -value | ||
}) | ||
} | ||
return this.increment(fields, 0 - count); | ||
countOrOptions.by = 0 - countOrOptions.by | ||
return this.increment(fields, countOrOptions) | ||
} | ||
@@ -424,39 +474,2 @@ | ||
var has = (function(o) { | ||
var predef = Object.getOwnPropertyDescriptor(o, attribute); | ||
if (predef && predef.hasOwnProperty('value')) { | ||
return true // true here means 'this property exist as a simple value property, do not place setters or getters at all' | ||
} | ||
return { | ||
get: (predef && predef.hasOwnProperty('get') ? predef.get : null) || o.__lookupGetter__(attribute), | ||
set: (predef && predef.hasOwnProperty('set') ? predef.set : null) || o.__lookupSetter__(attribute) | ||
}; | ||
})(this); | ||
// @ node-v0.8.19: | ||
// calling __defineGetter__ destroys any previously defined setters for the attribute in | ||
// question *if* that property setter was defined on the object's prototype (which is what | ||
// we do in dao-factory) ... therefore we need to [re]define both the setter and getter | ||
// here with either the function that already existed OR the default/automatic definition | ||
// | ||
// (the same is true for __defineSetter and 'prototype' getters) | ||
if (has !== true) { | ||
this.__defineGetter__(attribute, has.get || function() { return this.dataValues[attribute]; }); | ||
this.__defineSetter__(attribute, has.set || function(v) { | ||
if (Utils.hasChanged(this.dataValues[attribute], v)) { | ||
//Only dirty the object if the change is not due to id, touchedAt, createdAt or updatedAt being initiated | ||
var updatedAtAttr = Utils._.underscoredIf(this.__options.updatedAt, this.__options.underscored) | ||
, createdAtAttr = Utils._.underscoredIf(this.__options.createdAt, this.__options.underscored) | ||
, touchedAtAttr = Utils._.underscoredIf(this.__options.touchedAt, this.__options.underscored) | ||
if (this.dataValues[attribute] || (attribute != 'id' && attribute != touchedAtAttr && attribute != createdAtAttr && attribute != updatedAtAttr)) { | ||
this.isDirty = true | ||
} | ||
} | ||
this.dataValues[attribute] = v | ||
}); | ||
} | ||
this[attribute] = value; | ||
@@ -463,0 +476,0 @@ } |
@@ -191,2 +191,5 @@ var STRING = function(length, binary) { | ||
BLOB: BLOB, | ||
UUID: 'CHAR(36)', | ||
UUIDV1: 'UUIDV1', | ||
UUIDV4: 'UUIDV4', | ||
@@ -193,0 +196,0 @@ get ENUM() { |
@@ -457,2 +457,46 @@ var Utils = require("../../utils") | ||
/** | ||
* Returns a query that starts a transaction. | ||
* | ||
* @param {Boolean} value A boolean that states whether autocommit shall be done or not. | ||
* @return {String} The generated sql query. | ||
*/ | ||
setAutocommitQuery: function(value) { | ||
throwMethodUndefined('setAutocommitQuery') | ||
}, | ||
setIsolationLevelQuery: function(value) { | ||
throwMethodUndefined('setIsolationLevelQuery') | ||
}, | ||
/** | ||
* Returns a query that starts a transaction. | ||
* | ||
* @param {Object} options An object with options. | ||
* @return {String} The generated sql query. | ||
*/ | ||
startTransactionQuery: function(options) { | ||
throwMethodUndefined('startTransactionQuery') | ||
}, | ||
/** | ||
* Returns a query that commits a transaction. | ||
* | ||
* @param {Object} options An object with options. | ||
* @return {String} The generated sql query. | ||
*/ | ||
commitTransactionQuery: function(options) { | ||
throwMethodUndefined('commitTransactionQuery') | ||
}, | ||
/** | ||
* Returns a query that rollbacks a transaction. | ||
* | ||
* @param {Object} options An object with options. | ||
* @return {String} The generated sql query. | ||
*/ | ||
rollbackTransactionQuery: function(options) { | ||
throwMethodUndefined('rollbackTransactionQuery') | ||
}, | ||
addLimitAndOffset: function(options, query){ | ||
@@ -654,3 +698,3 @@ if (options.offset && !options.limit) { | ||
for (var logic in value) { | ||
var logicResult = Utils.getWhereLogic(logic) | ||
var logicResult = Utils.getWhereLogic(logic, hash[key][logic]); | ||
if (logic === "IN" || logic === "NOT IN") { | ||
@@ -657,0 +701,0 @@ var values = Array.isArray(where[i][ii]) ? where[i][ii] : [where[i][ii]] |
@@ -430,3 +430,8 @@ var Utils = require('../../utils') | ||
existingEntry[attrName] = existingEntry[attrName] || [] | ||
existingEntry[attrName].push(row[attrName]) | ||
var attrRowExists = existingEntry[attrName].some(function(attrRow) { | ||
return Utils._.isEqual(attrRow, row[attrName]) | ||
}) | ||
if (!attrRowExists) { | ||
existingEntry[attrName].push(row[attrName]) | ||
} | ||
} | ||
@@ -433,0 +438,0 @@ } |
@@ -10,2 +10,6 @@ module.exports = (function(){ | ||
ConnectorManager.prototype.afterTransactionSetup = function(callback) { | ||
callback() | ||
} | ||
ConnectorManager.prototype.connect = function() { | ||
@@ -12,0 +16,0 @@ throw new Error('Define the connect method!') |
@@ -23,3 +23,3 @@ var Utils = require("../../utils") | ||
if (this.options.logging !== false) { | ||
this.options.logging('Executing: ' + this.sql) | ||
this.options.logging('Executing (' + this.options.uuid + '): ' + this.sql) | ||
} | ||
@@ -36,2 +36,4 @@ | ||
.on('row', function(row, metadata) { | ||
var type | ||
for (var prop in row) { | ||
@@ -70,3 +72,3 @@ if (row.hasOwnProperty(prop)) { | ||
if (metadata.charsetNrs[prop] === 63) { // binary | ||
row[prop] = new Buffer(row[prop]) | ||
row[prop] = new Buffer(row[prop]) | ||
} | ||
@@ -108,3 +110,3 @@ break | ||
/^describe/.test(self.sql.toLowerCase())) { | ||
self.emit('success', self.formatResults(resultSet)) | ||
self.emit('success', self.formatResults(resultSet)) | ||
} else { | ||
@@ -111,0 +113,0 @@ self.emit('success', self.formatResults(info)) |
@@ -164,4 +164,5 @@ var mysql | ||
enqueue.call(this, queueItem, options); | ||
return queueItem.query; | ||
queueItem.query.options.uuid = this.config.uuid | ||
enqueue.call(this, queueItem, options) | ||
return queueItem.query | ||
} | ||
@@ -172,2 +173,3 @@ | ||
query.options.uuid = this.config.uuid | ||
query.done(function() { | ||
@@ -282,3 +284,3 @@ self.pendingQueries--; | ||
case 'ECONNREFUSED': | ||
case 'ER_ACCESS_DENIED_ERROR': | ||
case 'ER_ACCESS_D2ENIED_ERROR': | ||
emitter.emit('error', 'Failed to authenticate for MySQL. Please double check your settings.') | ||
@@ -285,0 +287,0 @@ break |
@@ -247,3 +247,3 @@ var Utils = require("../../utils") | ||
incrementQuery: function (tableName, attrValueHash, where) { | ||
incrementQuery: function (tableName, attrValueHash, where, options) { | ||
attrValueHash = Utils.removeNullValuesFromHash(attrValueHash, this.options.omitNull) | ||
@@ -260,2 +260,8 @@ | ||
options = options || {} | ||
for (var key in options) { | ||
var value = options[key]; | ||
values.push(this.quoteIdentifier(key) + "=" + this.escape(value)) | ||
} | ||
var table = this.quoteIdentifier(tableName) | ||
@@ -332,2 +338,34 @@ values = values.join(",") | ||
/** | ||
* Returns a query that starts a transaction. | ||
* | ||
* @param {Boolean} value A boolean that states whether autocommit shall be done or not. | ||
* @return {String} The generated sql query. | ||
*/ | ||
setAutocommitQuery: function(value) { | ||
return "SET autocommit = " + (!!value ? 1 : 0) + ";" | ||
}, | ||
setIsolationLevelQuery: function(value) { | ||
return "SET SESSION TRANSACTION ISOLATION LEVEL " + value + ";" | ||
}, | ||
/** | ||
* Returns a query that starts a transaction. | ||
* | ||
* @param {Object} options An object with options. | ||
* @return {String} The generated sql query. | ||
*/ | ||
startTransactionQuery: function(options) { | ||
return "START TRANSACTION;" | ||
}, | ||
commitTransactionQuery: function(options) { | ||
return "COMMIT;" | ||
}, | ||
rollbackTransactionQuery: function(options) { | ||
return "ROLLBACK;" | ||
}, | ||
attributesToSQL: function(attributes) { | ||
@@ -334,0 +372,0 @@ var result = {} |
@@ -23,3 +23,3 @@ var Utils = require("../../utils") | ||
if (this.options.logging !== false) { | ||
this.options.logging('Executing: ' + this.sql) | ||
this.options.logging('Executing (' + this.options.uuid + '): ' + this.sql) | ||
} | ||
@@ -26,0 +26,0 @@ |
@@ -0,1 +1,2 @@ | ||
var Query = require("./query") | ||
@@ -63,3 +64,5 @@ , Utils = require("../../utils") | ||
return query.run(sql) | ||
.complete(function(err) { done && done(err) }) | ||
.complete(function(err) { | ||
self.endQuery.call(self) | ||
done && done(err) }) | ||
.success(function(results) { self.endQuery.call(self) }) | ||
@@ -72,2 +75,6 @@ .error(function(err) { self.endQuery.call(self) }) | ||
ConnectorManager.prototype.afterTransactionSetup = function(callback) { | ||
this.setTimezone(this.client, 'UTC', callback) | ||
} | ||
ConnectorManager.prototype.connect = function(callback) { | ||
@@ -111,8 +118,21 @@ var self = this | ||
} | ||
} else { | ||
emitter.emit('error', new Error(err.message)) | ||
} | ||
} else if (client) { | ||
client.query("SET TIME ZONE 'UTC'").on('end', function() { | ||
var timezoneCallback = function() { | ||
self.isConnected = true | ||
self.client = client | ||
emitter.emit('success', done) | ||
} | ||
if (self.config.keepDefaultTimezone) { | ||
Utils.tick(timezoneCallback) | ||
} else { | ||
self.setTimezone(client, 'UTC', timezoneCallback) | ||
} | ||
} else if (self.config.native) { | ||
self.setTimezone(self.client, 'UTC', function() { | ||
self.isConnected = true | ||
emitter.emit('success', done) | ||
}) | ||
@@ -135,3 +155,5 @@ } else { | ||
this.client = new this.pg.Client(uri) | ||
this.client.connect(connectCallback) | ||
this.client.connect(function(err, client, done) { | ||
connectCallback(err, client || self.client, done) | ||
}) | ||
} | ||
@@ -143,2 +165,6 @@ } | ||
ConnectorManager.prototype.setTimezone = function(client, timezone, callback) { | ||
client.query("SET TIME ZONE '" + (timezone || "UTC") + "'").on('end', callback) | ||
} | ||
ConnectorManager.prototype.disconnect = function() { | ||
@@ -161,2 +187,2 @@ if (this.poolIdentifier) { | ||
return ConnectorManager | ||
})() | ||
})() |
@@ -148,6 +148,10 @@ var Utils = require("../../utils") | ||
arrayValue: function(value, key, _key, factory){ | ||
var col = null | ||
, coltype = null | ||
, _realKey = key.split('.').pop() | ||
, _value | ||
if (value.length === 0) { value = [null] } | ||
var col = null, coltype = null | ||
// Special conditions for searching within an array column type | ||
var _realKey = key.split('.').pop() | ||
if (!!factory && !!factory.rawAttributes[_realKey]) { | ||
@@ -370,3 +374,3 @@ col = factory.rawAttributes[_realKey] | ||
incrementQuery: function(tableName, attrValueHash, where) { | ||
incrementQuery: function(tableName, attrValueHash, where, options) { | ||
attrValueHash = Utils.removeNullValuesFromHash(attrValueHash, this.options.omitNull) | ||
@@ -382,2 +386,8 @@ | ||
options = options || {} | ||
for (var key in options) { | ||
var value = options[key]; | ||
values.push(this.quoteIdentifier(key) + "=" + this.escape(value)) | ||
} | ||
var replacements = { | ||
@@ -876,3 +886,35 @@ table: this.quoteIdentifiers(tableName), | ||
return 'ALTER TABLE ' + this.quoteIdentifier(tableName) + ' DROP CONSTRAINT ' + this.quoteIdentifier(foreignKey) + ';' | ||
} | ||
}, | ||
/** | ||
* Returns a query that starts a transaction. | ||
* | ||
* @param {Boolean} value A boolean that states whether autocommit shall be done or not. | ||
* @return {String} The generated sql query. | ||
*/ | ||
setAutocommitQuery: function(value) { | ||
return "SET autocommit = " + (!!value ? 1 : 0) + ";" | ||
}, | ||
setIsolationLevelQuery: function(value) { | ||
return "SET SESSION TRANSACTION ISOLATION LEVEL " + value + ";" | ||
}, | ||
/** | ||
* Returns a query that starts a transaction. | ||
* | ||
* @param {Object} options An object with options. | ||
* @return {String} The generated sql query. | ||
*/ | ||
startTransactionQuery: function(options) { | ||
return "START TRANSACTION;" | ||
}, | ||
commitTransactionQuery: function(options) { | ||
return "COMMIT;" | ||
}, | ||
rollbackTransactionQuery: function(options) { | ||
return "ROLLBACK;" | ||
}, | ||
} | ||
@@ -879,0 +921,0 @@ |
@@ -24,3 +24,3 @@ var Utils = require("../../utils") | ||
var self = this | ||
var self = this | ||
, receivedError = false | ||
@@ -31,3 +31,3 @@ , query = this.client.query(sql) | ||
if (this.options.logging !== false) { | ||
this.options.logging('Executing: ' + this.sql) | ||
this.options.logging('Executing (' + this.options.uuid + '): ' + this.sql) | ||
} | ||
@@ -62,3 +62,3 @@ | ||
var onSuccess = function(rows, sql) { | ||
var results = [] | ||
var results = rows | ||
, self = this | ||
@@ -168,2 +168,2 @@ , isTableNameQuery = (sql.indexOf('SELECT table_name FROM information_schema.tables') === 0) | ||
return Query | ||
})() | ||
})() |
@@ -1,4 +0,5 @@ | ||
var Utils = require("../../utils") | ||
, DataTypes = require("../../data-types") | ||
, SqlString = require("../../sql-string") | ||
var Utils = require("../../utils") | ||
, DataTypes = require("../../data-types") | ||
, SqlString = require("../../sql-string") | ||
, Transaction = require("../../transaction") | ||
@@ -84,4 +85,11 @@ var MySqlQueryGenerator = Utils._.extend( | ||
dataType = dataType.replace(length[0], '') | ||
dataType = Utils._.insert(dataType, modifierLastIndex, length[0]) | ||
// Since the legnth was placed before the modifier, removing the legnth has changed the index | ||
if (length.index < modifierLastIndex) { | ||
modifierLastIndex -= length[0].length | ||
} | ||
dataType = Utils._.insert(dataType, modifierLastIndex, length[0]).trim() | ||
} | ||
modifierLastIndex = -1 | ||
} | ||
@@ -218,3 +226,3 @@ | ||
incrementQuery: function(tableName, attrValueHash, where) { | ||
incrementQuery: function(tableName, attrValueHash, where, options) { | ||
attrValueHash = Utils.removeNullValuesFromHash(attrValueHash, this.options.omitNull) | ||
@@ -230,2 +238,8 @@ | ||
options = options || {} | ||
for (var key in options) { | ||
var value = options[key]; | ||
values.push(this.quoteIdentifier(key) + "=" + this.escape(value)) | ||
} | ||
var replacements = { | ||
@@ -402,2 +416,25 @@ table: this.quoteIdentifier(tableName), | ||
startTransactionQuery: function(options) { | ||
return "BEGIN TRANSACTION;" | ||
}, | ||
setAutocommitQuery: function(value) { | ||
return "-- SQLite does not support SET autocommit." | ||
}, | ||
setIsolationLevelQuery: function(value) { | ||
switch (value) { | ||
case Transaction.ISOLATION_LEVELS.REPEATABLE_READ: | ||
return "-- SQLite is not able to choose the isolation level REPEATABLE READ." | ||
case Transaction.ISOLATION_LEVELS.READ_UNCOMMITTED: | ||
return "PRAGMA read_uncommitted = ON;" | ||
case Transaction.ISOLATION_LEVELS.READ_COMMITTED: | ||
return "PRAGMA read_uncommitted = OFF;" | ||
case Transaction.ISOLATION_LEVELS.SERIALIZABLE: | ||
return "-- SQLite's default isolation level is SERIALIZABLE. Nothing to do." | ||
default: | ||
throw new Error('Unknown isolation level: ' + value) | ||
} | ||
}, | ||
replaceBooleanDefaults: function(sql) { | ||
@@ -404,0 +441,0 @@ return sql.replace(/DEFAULT '?false'?/g, "DEFAULT 0").replace(/DEFAULT '?true'?/g, "DEFAULT 1") |
@@ -29,3 +29,3 @@ var Utils = require("../../utils") | ||
if (this.options.logging !== false) { | ||
this.options.logging('Executing: ' + this.sql) | ||
this.options.logging('Executing (' + this.options.uuid + '): ' + this.sql) | ||
} | ||
@@ -36,10 +36,23 @@ | ||
var executeSql = function() { | ||
self.database[getDatabaseMethod.call(self)](self.sql, function(err, results) { | ||
// allow clients to listen to sql to do their own logging or whatnot | ||
self.emit('sql', self.sql) | ||
this.columnTypes = columnTypes; | ||
err ? onFailure.call(self, err) : onSuccess.call(self, results, this) | ||
}) | ||
}; | ||
if (self.sql.indexOf('-- ') === 0) { | ||
// the sql query starts with a comment. don't bother the server with that ... | ||
Utils.tick(function() { | ||
self.emit('sql', self.sql) | ||
self.emit('success', null) | ||
}) | ||
} else { | ||
self.database[getDatabaseMethod.call(self)](self.sql, function(err, results) { | ||
// allow clients to listen to sql to do their own logging or whatnot | ||
self.emit('sql', self.sql) | ||
if (err) { | ||
onFailure.call(self, err) | ||
} else { | ||
this.columnTypes = columnTypes | ||
onSuccess.call(self, results, this) | ||
} | ||
}) | ||
} | ||
} | ||
if ((getDatabaseMethod.call(self) === 'all') && /select\s.*?\sfrom\s+([^ ;]+)/i.test(self.sql)) { | ||
@@ -46,0 +59,0 @@ var tableName = RegExp.$1; |
var util = require("util") | ||
, EventEmitter = require("events").EventEmitter | ||
, Promise = require("promise") | ||
, Promise = require("bluebird") | ||
, proxyEventKeys = ['success', 'error', 'sql'] | ||
, tick = (typeof setImmediate !== "undefined" ? setImmediate : process.nextTick) | ||
, Utils = require('../utils') | ||
@@ -23,3 +22,3 @@ | ||
CustomEventEmitter.prototype.run = function() { | ||
tick(function() { | ||
Utils.tick(function() { | ||
if (this.fct) { | ||
@@ -26,0 +25,0 @@ this.fct.call(this, this) |
@@ -236,3 +236,3 @@ const fs = require("fs") | ||
var getLastMigrationFromDatabase = function() { | ||
var getLastMigrationFromDatabase = Migrator.prototype.getLastMigrationFromDatabase = function() { | ||
var self = this | ||
@@ -259,3 +259,3 @@ | ||
var getLastMigrationIdFromDatabase = function() { | ||
var getLastMigrationIdFromDatabase = Migrator.prototype.getLastMigrationIdFromDatabase = function() { | ||
var self = this | ||
@@ -275,3 +275,3 @@ | ||
var getFormattedDateString = function(s) { | ||
var getFormattedDateString = Migrator.prototype.getFormattedDateString = function(s) { | ||
var result = null | ||
@@ -288,7 +288,7 @@ | ||
var stringToDate = function(s) { | ||
var stringToDate = Migrator.prototype.stringToDate = function(s) { | ||
return moment(getFormattedDateString(s), "YYYYMMDDHHmmss") | ||
} | ||
var saveSuccessfulMigration = function(from, to, callback) { | ||
var saveSuccessfulMigration = Migrator.prototype.saveSuccessfulMigration = function(from, to, callback) { | ||
var self = this | ||
@@ -303,3 +303,3 @@ | ||
var deleteUndoneMigration = function(from, to, callback) { | ||
var deleteUndoneMigration = Migrator.prototype.deleteUndoneMigration = function(from, to, callback) { | ||
var self = this | ||
@@ -306,0 +306,0 @@ |
@@ -78,2 +78,6 @@ var Utils = require(__dirname + "/utils") | ||
} else { | ||
if (typeof serial.options === "object" && Object.keys(serial.options).length > 0 && serial.method === "queryAndEmit") { | ||
serial.params.push(serial.options) | ||
} | ||
var emitter = serial.klass[serial.method].apply(serial.klass, serial.params) | ||
@@ -80,0 +84,0 @@ |
var Utils = require(__dirname + '/utils') | ||
, DataTypes = require(__dirname + '/data-types') | ||
, SQLiteQueryInterface = require(__dirname + '/dialects/sqlite/query-interface') | ||
, Transaction = require(__dirname + '/transaction') | ||
@@ -82,2 +83,6 @@ module.exports = (function() { | ||
options = Utils._.extend({ | ||
logging: this.sequelize.options.logging | ||
}, options || {}) | ||
return new Utils.CustomEventEmitter(function(emitter) { | ||
@@ -94,3 +99,3 @@ // Postgres requires a special SQL command for enums | ||
sql = self.QueryGenerator.pgListEnums(getTableName, keys[i], options) | ||
chainer.add(self.sequelize.query(sql, null, { plain: true, raw: true, type: 'SELECT' })) | ||
chainer.add(self.sequelize.query(sql, null, { plain: true, raw: true, type: 'SELECT', logging: options.logging })) | ||
} | ||
@@ -112,5 +117,4 @@ } | ||
sql = self.QueryGenerator.pgEnum(getTableName, keys[i], attributes[keys[i]], options) | ||
chainer2.add(self.sequelize.query(sql, null, { raw: true })) | ||
} | ||
else if (!!results[enumIdx] && !!daoTable) { | ||
chainer2.add(self.sequelize.query(sql, null, { raw: true, logging: options.logging })) | ||
} else if (!!results[enumIdx] && !!daoTable) { | ||
var enumVals = self.QueryGenerator.fromArray(results[enumIdx].enum_value) | ||
@@ -143,12 +147,15 @@ , vals = daoTable.rawAttributes[keys[i]].values | ||
chainer2.run().success(function() { | ||
queryAndEmit.call(self, sql, 'createTable') | ||
.success(function(res) { | ||
self.emit('createTable', null) | ||
emitter.emit('success', res) | ||
}) | ||
.error(function(err) { | ||
self.emit('createTable', err) | ||
emitter.emit('error', err) | ||
}) | ||
.on('sql', function(sql) { emitter.emit('sql', sql) }) | ||
queryAndEmit | ||
.call(self, sql, 'createTable', options) | ||
.success(function(res) { | ||
self.emit('createTable', null) | ||
emitter.emit('success', res) | ||
}) | ||
.error(function(err) { | ||
self.emit('createTable', err) | ||
emitter.emit('error', err) | ||
}) | ||
.on('sql', function(sql) { | ||
emitter.emit('sql', sql) | ||
}) | ||
}).error(function(err) { | ||
@@ -164,3 +171,3 @@ emitter.emit('error', err) | ||
queryAndEmit.call(self, sql, 'createTable', emitter).success(function(results) { | ||
queryAndEmit.call(self, sql, 'createTable', options).success(function(results) { | ||
self.emit('createTable', null) | ||
@@ -189,3 +196,3 @@ emitter.emit('success', results) | ||
chainer.add(self, 'queryAndEmit', [sql]) | ||
chainer.add(self, 'queryAndEmit', [sql, 'dropTable'], options) | ||
@@ -211,3 +218,3 @@ // Since postgres has a special case for enums, we should drop the related | ||
if (daoTable.rawAttributes[keys[i]].type && daoTable.rawAttributes[keys[i]].type === "ENUM") { | ||
chainer.add(self.sequelize, 'query', [self.QueryGenerator.pgEnumDrop(getTableName, keys[i]), null, {raw: true}]) | ||
chainer.add(self.sequelize, 'query', [self.QueryGenerator.pgEnumDrop(getTableName, keys[i]), null, {logging: options.logging, raw: true}]) | ||
} | ||
@@ -453,5 +460,5 @@ } | ||
QueryInterface.prototype.insert = function(dao, tableName, values) { | ||
QueryInterface.prototype.insert = function(dao, tableName, values, options) { | ||
var sql = this.QueryGenerator.insertQuery(tableName, values, dao.daoFactory.rawAttributes) | ||
return queryAndEmit.call(this, [sql, dao], 'insert', { | ||
return queryAndEmit.call(this, [sql, dao, options], 'insert', { | ||
success: function(obj) { obj.isNewRecord = false } | ||
@@ -461,5 +468,5 @@ }) | ||
QueryInterface.prototype.bulkInsert = function(tableName, records) { | ||
QueryInterface.prototype.bulkInsert = function(tableName, records, options) { | ||
var sql = this.QueryGenerator.bulkInsertQuery(tableName, records) | ||
return queryAndEmit.call(this, sql, 'bulkInsert') | ||
return queryAndEmit.call(this, [sql, null, options], 'bulkInsert') | ||
} | ||
@@ -487,3 +494,3 @@ | ||
chainer.add(self, 'queryAndEmit', [[sql, dao], 'delete']) | ||
chainer.add(self, 'queryAndEmit', [[sql, dao, options], 'delete']) | ||
@@ -514,3 +521,3 @@ chainer.runSerially() | ||
chainer.add(self, 'queryAndEmit', [sql, 'bulkUpdate']) | ||
chainer.add(self, 'queryAndEmit', [[sql, null, options], 'bulkUpdate']) | ||
@@ -531,3 +538,3 @@ return chainer.runSerially() | ||
QueryInterface.prototype.delete = function(dao, tableName, identifier) { | ||
QueryInterface.prototype.delete = function(dao, tableName, identifier, options) { | ||
var self = this | ||
@@ -601,3 +608,3 @@ , restrict = false | ||
chainer.add(self, 'queryAndEmit', [[sql, dao], 'delete']) | ||
chainer.add(self, 'queryAndEmit', [[sql, dao, options], 'delete']) | ||
@@ -632,3 +639,3 @@ chainer.runSerially() | ||
chainer.add(self, 'queryAndEmit', [sql, 'bulkDelete', options]) | ||
chainer.add(self, 'queryAndEmit', [[sql, null, options], 'bulkDelete', options]) | ||
@@ -673,5 +680,5 @@ chainer.runSerially() | ||
QueryInterface.prototype.increment = function(dao, tableName, values, identifier) { | ||
var sql = this.QueryGenerator.incrementQuery(tableName, values, identifier); | ||
return queryAndEmit.call(this, [sql, dao], 'increment'); | ||
QueryInterface.prototype.increment = function(dao, tableName, values, identifier, options) { | ||
var sql = this.QueryGenerator.incrementQuery(tableName, values, identifier, options.attributes) | ||
return queryAndEmit.call(this, [sql, dao, options], 'increment') | ||
} | ||
@@ -687,6 +694,7 @@ | ||
return new Utils.CustomEventEmitter(function(emitter) { | ||
var sql = self.QueryGenerator.selectQuery(tableName, options) | ||
, qry = self.sequelize.query(sql, null, { plain: true, raw: true, type: 'SELECT' }) | ||
var sql = self.QueryGenerator.selectQuery(tableName, options) | ||
, queryOptions = Utils._.extend({ transaction: options.transaction }, { plain: true, raw: true, type: 'SELECT' }) | ||
, query = self.sequelize.query(sql, null, queryOptions) | ||
qry | ||
query | ||
.success(function(data) { | ||
@@ -817,2 +825,59 @@ var result = data ? data[attributeSelector] : null | ||
QueryInterface.prototype.setAutocommit = function(transaction, value) { | ||
if (!transaction || !(transaction instanceof Transaction)) { | ||
throw new Error('Unable to set autocommit for a transaction without transaction object!') | ||
} | ||
var sql = this.QueryGenerator.setAutocommitQuery(value) | ||
return this.queryAndEmit([sql, null, { transaction: transaction }], 'setAutocommit') | ||
} | ||
QueryInterface.prototype.setIsolationLevel = function(transaction, value) { | ||
if (!transaction || !(transaction instanceof Transaction)) { | ||
throw new Error('Unable to set isolation level for a transaction without transaction object!') | ||
} | ||
var sql = this.QueryGenerator.setIsolationLevelQuery(value) | ||
return this.queryAndEmit([sql, null, { transaction: transaction }], 'setIsolationLevel') | ||
} | ||
QueryInterface.prototype.startTransaction = function(transaction, options) { | ||
if (!transaction || !(transaction instanceof Transaction)) { | ||
throw new Error('Unable to start a transaction without transaction object!') | ||
} | ||
options = Utils._.extend({ | ||
transaction: transaction | ||
}, options || {}) | ||
var sql = this.QueryGenerator.startTransactionQuery(options) | ||
return this.queryAndEmit([sql, null, options], 'startTransaction') | ||
} | ||
QueryInterface.prototype.commitTransaction = function(transaction, options) { | ||
if (!transaction || !(transaction instanceof Transaction)) { | ||
throw new Error('Unable to commit a transaction without transaction object!') | ||
} | ||
options = Utils._.extend({ | ||
transaction: transaction | ||
}, options || {}) | ||
var sql = this.QueryGenerator.commitTransactionQuery(options) | ||
return this.queryAndEmit([sql, null, options], 'commitTransaction') | ||
} | ||
QueryInterface.prototype.rollbackTransaction = function(transaction, options) { | ||
if (!transaction || !(transaction instanceof Transaction)) { | ||
throw new Error('Unable to rollback a transaction without transaction object!') | ||
} | ||
options = Utils._.extend({ | ||
transaction: transaction | ||
}, options || {}) | ||
var sql = this.QueryGenerator.rollbackTransactionQuery(options) | ||
return this.queryAndEmit([sql, null, options], 'rollbackTransaction') | ||
} | ||
// private | ||
@@ -831,4 +896,6 @@ | ||
options = Utils._.extend({ | ||
success: function(){}, | ||
error: function(){} | ||
success: function(){}, | ||
error: function(){}, | ||
transaction: null, | ||
logging: this.sequelize.options.logging | ||
}, options || {}) | ||
@@ -845,26 +912,25 @@ | ||
if (sqlOrQueryParams.length === 2) { | ||
sqlOrQueryParams.push({}) | ||
sqlOrQueryParams.push(typeof options === "object" ? options : {}) | ||
} | ||
query = this.sequelize.query.apply(this.sequelize, sqlOrQueryParams) | ||
emitter.query = this.sequelize.query.apply(this.sequelize, sqlOrQueryParams) | ||
} else { | ||
query = this.sequelize.query(sqlOrQueryParams, null, {}) | ||
emitter.query = this.sequelize.query(sqlOrQueryParams, null, options) | ||
} | ||
// append the query for better testing | ||
emitter.query = query | ||
query.success(function(obj) { | ||
options.success && options.success(obj) | ||
this.emit(methodName, null) | ||
emitter.emit('success', obj) | ||
}.bind(this)).error(function(err) { | ||
options.error && options.error(err) | ||
this.emit(methodName, err) | ||
emitter.emit('error', err) | ||
}.bind(this)) | ||
query.on('sql', function(sql) { | ||
emitter.emit('sql', sql) | ||
}) | ||
emitter | ||
.query | ||
.success(function(obj) { | ||
options.success && options.success(obj) | ||
this.emit(methodName, null) | ||
emitter.emit('success', obj) | ||
}.bind(this)) | ||
.error(function(err) { | ||
options.error && options.error(err) | ||
this.emit(methodName, err) | ||
emitter.emit('error', err) | ||
}.bind(this)) | ||
.on('sql', function(sql) { | ||
emitter.emit('sql', sql) | ||
}) | ||
}.bind(this) | ||
@@ -871,0 +937,0 @@ |
@@ -1,8 +0,10 @@ | ||
var url = require("url") | ||
, Path = require("path") | ||
, Utils = require("./utils") | ||
, DAOFactory = require("./dao-factory") | ||
, DataTypes = require('./data-types') | ||
, DAOFactoryManager = require("./dao-factory-manager") | ||
, QueryInterface = require("./query-interface") | ||
var url = require("url") | ||
, Path = require("path") | ||
, Utils = require("./utils") | ||
, DAOFactory = require("./dao-factory") | ||
, DataTypes = require('./data-types') | ||
, DAOFactoryManager = require("./dao-factory-manager") | ||
, QueryInterface = require("./query-interface") | ||
, Transaction = require("./transaction") | ||
, TransactionManager = require('./transaction-manager') | ||
@@ -75,2 +77,3 @@ module.exports = (function() { | ||
host: 'localhost', | ||
port: 3306, | ||
protocol: 'tcp', | ||
@@ -112,11 +115,5 @@ define: {}, | ||
} | ||
try { | ||
var ConnectorManager = require("./dialects/" + this.options.dialect + "/connector-manager") | ||
} catch(err) { | ||
throw new Error("The dialect " + this.options.dialect + " is not supported.") | ||
} | ||
this.daoFactoryManager = new DAOFactoryManager(this) | ||
this.connectorManager = new ConnectorManager(this, this.config) | ||
this.daoFactoryManager = new DAOFactoryManager(this) | ||
this.transactionManager = new TransactionManager(this) | ||
@@ -136,2 +133,20 @@ this.importCache = {} | ||
/** | ||
* Polyfill for the default connector manager. | ||
*/ | ||
Object.defineProperty(Sequelize.prototype, 'connectorManager', { | ||
get: function() { | ||
return this.transactionManager.getConnectorManager() | ||
} | ||
}) | ||
/** | ||
* Returns the specified dialect. | ||
* | ||
* @return {String} The specified dialect. | ||
*/ | ||
Sequelize.prototype.getDialect = function() { | ||
return this.options.dialect | ||
} | ||
/** | ||
Returns an instance of QueryInterface. | ||
@@ -256,3 +271,3 @@ | ||
, callerPath = Path.dirname(callerFilename) | ||
path = Path.resolve(callerPath, path) | ||
@@ -295,3 +310,3 @@ } | ||
return this.connectorManager.query(sql, callee, options) | ||
return this.transactionManager.query(sql, callee, options) | ||
} | ||
@@ -338,2 +353,4 @@ | ||
options.logging = options.logging === undefined ? false : Boolean(options.logging) | ||
var chainer = new Utils.QueryChainer() | ||
@@ -366,2 +383,18 @@ | ||
Sequelize.prototype.authenticate = function() { | ||
var self = this | ||
return new Utils.CustomEventEmitter(function(emitter) { | ||
self | ||
.query('SELECT 1+1 AS result', null, { raw: true, plain: true }) | ||
.complete(function(err, result) { | ||
if (!!err) { | ||
emitter.emit('error', new Error('Invalid credentials.')) | ||
} else { | ||
emitter.emit('success') | ||
} | ||
}) | ||
}).run() | ||
} | ||
Sequelize.prototype.fn = function (fn) { | ||
@@ -383,3 +416,18 @@ return new Utils.fn(fn, Array.prototype.slice.call(arguments, 1)) | ||
Sequelize.prototype.transaction = function(_options, _callback) { | ||
var options = (typeof _options === 'function') ? {} : _options | ||
, callback = (typeof _options === 'function') ? _options : _callback | ||
, transaction = new Transaction(this, options) | ||
, self = this | ||
Utils.tick(function() { | ||
transaction.prepareEnvironment(function() { | ||
callback(transaction) | ||
}) | ||
}) | ||
return transaction | ||
} | ||
return Sequelize | ||
})() |
@@ -146,3 +146,3 @@ var moment = require("moment") | ||
SqlString.formatNamedParameters = function(sql, values, timeZone, dialect) { | ||
return sql.replace(/\:(\w+)/g, function (value, key) { | ||
return sql.replace(/\:(?!\d)(\w+)/g, function (value, key) { | ||
if (values.hasOwnProperty(key)) { | ||
@@ -149,0 +149,0 @@ return SqlString.escape(values[key], false, timeZone, dialect) |
@@ -1,6 +0,8 @@ | ||
var util = require("util") | ||
, DataTypes = require("./data-types") | ||
, SqlString = require("./sql-string") | ||
, lodash = require("lodash") | ||
, _string = require('underscore.string') | ||
var util = require("util") | ||
, DataTypes = require("./data-types") | ||
, SqlString = require("./sql-string") | ||
, lodash = require("lodash") | ||
, _string = require('underscore.string') | ||
, ParameterValidator = require('./utils/parameter-validator') | ||
, uuid = require('node-uuid') | ||
@@ -183,3 +185,3 @@ var Utils = module.exports = { | ||
Object.keys(where[i]).forEach(function(ii) { | ||
logic = self.getWhereLogic(ii) | ||
logic = self.getWhereLogic(ii, where[i][ii]); | ||
@@ -286,3 +288,3 @@ switch(logic) { | ||
}, | ||
getWhereLogic: function(logic) { | ||
getWhereLogic: function(logic, val) { | ||
switch (logic) { | ||
@@ -302,3 +304,3 @@ case 'join': | ||
case 'ne': | ||
return '!=' | ||
return val ? '!=' : 'IS NOT' | ||
case 'between': | ||
@@ -381,4 +383,10 @@ case '..': | ||
return value() | ||
} else if (value === DataTypes.UUIDV1) { | ||
return uuid.v1() | ||
} else if (value === DataTypes.UUIDV4) { | ||
return uuid.v4() | ||
} else if (value === DataTypes.NOW) { | ||
return Utils.now() | ||
} else { | ||
return (value === DataTypes.NOW) ? Utils.now() : value | ||
return value | ||
} | ||
@@ -401,2 +409,4 @@ }, | ||
if (value === DataTypes.UUIDV1 || value === DataTypes.UUIDV4) {return false} | ||
if (lodash.isFunction(value)) { | ||
@@ -496,3 +506,2 @@ return false | ||
now: function(dialect) { | ||
@@ -504,2 +513,7 @@ var now = new Date() | ||
tick: function(func) { | ||
var tick = (typeof setImmediate !== "undefined" ? setImmediate : process.nextTick) | ||
tick(func) | ||
}, | ||
// Note: Use the `quoteIdentifier()` and `escape()` methods on the | ||
@@ -534,2 +548,13 @@ // `QueryInterface` instead for more portable code. | ||
this.val = val | ||
}, | ||
generateUUID: function() { | ||
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { | ||
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8) | ||
return v.toString(16) | ||
}) | ||
}, | ||
validateParameter: function(value, expectation, options) { | ||
return ParameterValidator.check(value, expectation, options) | ||
} | ||
@@ -536,0 +561,0 @@ } |
{ | ||
"name": "sequelize", | ||
"description": "Multi dialect ORM for Node.JS", | ||
"version": "2.0.0-beta.1", | ||
"version": "2.0.0-beta.2", | ||
"author": "Sascha Depold <sascha@depold.com>", | ||
@@ -43,3 +43,3 @@ "contributors": [ | ||
"validator": "~1.5.0", | ||
"moment": "~2.2.1", | ||
"moment": "~2.4.0", | ||
"commander": "~2.0.0", | ||
@@ -49,4 +49,6 @@ "dottie": "0.0.8-0", | ||
"generic-pool": "2.0.4", | ||
"promise": "~3.2.0", | ||
"sql": "~0.28.0" | ||
"sql": "~0.31.0", | ||
"circular-json": "~0.1.5", | ||
"bluebird": "~0.11.5", | ||
"node-uuid": "~1.4.1" | ||
}, | ||
@@ -56,3 +58,3 @@ "devDependencies": { | ||
"mysql": "~2.0.0-alpha9", | ||
"pg": "~2.6.0", | ||
"pg": "~2.8.1", | ||
"watchr": "~2.4.3", | ||
@@ -64,3 +66,7 @@ "yuidocjs": "~0.3.36", | ||
"sinon": "~1.7.3", | ||
"mariasql": "git://github.com/sequelize/node-mariasql.git" | ||
"mariasql": "git://github.com/mscdex/node-mariasql.git", | ||
"chai-spies": "~0.5.1", | ||
"lcov-result-merger": "0.0.2", | ||
"istanbul": "~0.1.45", | ||
"coveralls": "~2.5.0" | ||
}, | ||
@@ -85,2 +91,2 @@ "keywords": [ | ||
"license": "MIT" | ||
} | ||
} |
@@ -61,3 +61,3 @@ # Sequelize [![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/sequelize/sequelize/trend.png)](https://bitdeli.com/free "Bitdeli Badge") [![Build Status](https://secure.travis-ci.org/sequelize/sequelize.png)](http://travis-ci.org/sequelize/sequelize) [![Dependency Status](https://david-dm.org/sequelize/sequelize.png)](https://david-dm.org/sequelize/sequelize) [![Flattr this](http://api.flattr.com/button/flattr-badge-large.png)](http://flattr.com/thing/1259407/Sequelize) # | ||
- ~~Check if lodash is a proper alternative to current underscore usage.~~ | ||
- Transactions | ||
- ~~Transactions~~ | ||
- Associations of not yet saved objects: [#864](https://github.com/sequelize/sequelize/issues/864) | ||
@@ -73,2 +73,3 @@ - Support for update of tables without primary key | ||
- ~~Support for foreign keys~~ Implemented in [#595](https://github.com/sequelize/sequelize/pull/595), thanks to @optilude | ||
- Support for socket paths. [#982](https://github.com/sequelize/sequelize/issues/982) | ||
@@ -75,0 +76,0 @@ ### 1.7.x |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
395271
51
9481
256
1
13
14
21
+ Addedbluebird@~0.11.5
+ Addedcircular-json@~0.1.5
+ Addednode-uuid@~1.4.1
+ Addedbluebird@0.11.6(transitive)
+ Addedcircular-json@0.1.6(transitive)
+ Addedmoment@2.4.0(transitive)
+ Addednode-uuid@1.4.8(transitive)
+ Addedsql@0.31.0(transitive)
+ Addedwru@0.3.0(transitive)
- Removedpromise@~3.2.0
- Removedmoment@2.2.1(transitive)
- Removedpromise@3.2.0(transitive)
- Removedsql@0.28.0(transitive)
Updatedmoment@~2.4.0
Updatedsql@~0.31.0