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

Commit ad9ff463 by Daniel Durante

Custom primary key (not keys, just singular) should no longer be a problem for m…

…odels when using any of the data retrievals with just a number or through associations. Closes #694
1 parent 93016a05
...@@ -37,15 +37,20 @@ module.exports = (function() { ...@@ -37,15 +37,20 @@ module.exports = (function() {
BelongsTo.prototype.injectGetter = function(obj) { BelongsTo.prototype.injectGetter = function(obj) {
var self = this var self = this
, accessor = Utils._.camelize('get_' + (this.options.as || Utils.singularize(this.target.tableName, this.target.options.language))) , accessor = Utils._.camelize('get_' + (this.options.as || Utils.singularize(this.target.tableName, this.target.options.language)))
, primaryKeys = Object.keys(self.target.primaryKeys)
, primaryKey = primaryKeys.length === 1 ? primaryKeys[0] : 'id'
obj[accessor] = function(params) { obj[accessor] = function(params) {
var id = this[self.identifier] var id = this[self.identifier]
, where = {}
where[primaryKey] = id
if (!Utils._.isUndefined(params)) { if (!Utils._.isUndefined(params)) {
if (!Utils._.isUndefined(params.where)) { if (!Utils._.isUndefined(params.where)) {
params.where = Utils._.extend({id:id}, params.where) params.where = Utils._.extend(where, params.where)
} else { } else {
params.where = {id: id} params.where = where
} }
} else { } else {
params = id params = id
...@@ -62,7 +67,10 @@ module.exports = (function() { ...@@ -62,7 +67,10 @@ module.exports = (function() {
, accessor = Utils._.camelize('set_' + (this.options.as || Utils.singularize(this.target.tableName, this.target.options.language))) , accessor = Utils._.camelize('set_' + (this.options.as || Utils.singularize(this.target.tableName, this.target.options.language)))
obj[accessor] = function(associatedObject) { obj[accessor] = function(associatedObject) {
this[self.identifier] = associatedObject ? associatedObject.id : null var primaryKeys = !!associatedObject && !!associatedObject.daoFactory ? Object.keys(associatedObject.daoFactory.primaryKeys) : []
, primaryKey = primaryKeys.length === 1 ? primaryKeys[0] : 'id'
this[self.identifier] = associatedObject ? associatedObject[primaryKey] : null
// passes the changed field to save, so only that field get updated. // passes the changed field to save, so only that field get updated.
return this.save([ self.identifier ]) return this.save([ self.identifier ])
......
...@@ -10,15 +10,21 @@ module.exports = (function() { ...@@ -10,15 +10,21 @@ module.exports = (function() {
var self = this, _options = options var self = this, _options = options
var customEventEmitter = new Utils.CustomEventEmitter(function() { var customEventEmitter = new Utils.CustomEventEmitter(function() {
var where = {}, options = _options || {}; var where = {}, options = _options || {}
//fully qualify //fully qualify
where[self.__factory.connectorDAO.tableName+"."+self.__factory.identifier] = self.instance.id var instancePrimaryKeys = Object.keys(self.instance.daoFactory.primaryKeys)
, instancePrimaryKey = instancePrimaryKeys.length > 0 ? instancePrimaryKeys[0] : 'id'
where[self.__factory.connectorDAO.tableName+"."+self.__factory.identifier] = self.instance[instancePrimaryKey]
var primaryKeys = Object.keys(self.__factory.connectorDAO.rawAttributes) var primaryKeys = Object.keys(self.__factory.connectorDAO.rawAttributes)
, foreignKey = primaryKeys.filter(function(pk) { return pk != self.__factory.identifier })[0] , foreignKey = primaryKeys.filter(function(pk) { return pk != self.__factory.identifier })[0]
, foreignPrimary = Object.keys(self.__factory.target.primaryKeys)
foreignPrimary = foreignPrimary.length === 1 ? foreignPrimary[0] : 'id'
where[self.__factory.connectorDAO.tableName+"."+foreignKey] = {join: self.__factory.target.tableName+".id"} where[self.__factory.connectorDAO.tableName+"."+foreignKey] = {join: self.__factory.target.tableName+"."+foreignPrimary}
if (options.where) { if (options.where) {
if (Array.isArray(options.where)) { if (Array.isArray(options.where)) {
...@@ -28,18 +34,11 @@ module.exports = (function() { ...@@ -28,18 +34,11 @@ module.exports = (function() {
options.where = smart options.where = smart
} }
} else { } else {
Utils._.each(options.where, function(value, index) { smart = Utils.smartWhere([where, options.where], self.__factory.target.daoFactoryManager.sequelize.options.dialect)
delete options.where[index]; smart = Utils.compileSmartWhere.call(self.__factory.target, smart, self.__factory.target.daoFactoryManager.sequelize.options.dialect)
smart = Utils.smartWhere(value, self.__factory.target.daoFactoryManager.sequelize.options.dialect) if (smart.length > 0) {
smart = Utils.compileSmartWhere.call(self.__factory.target, smart) options.where = smart
if (smart.length > 0) { }
value = smart
}
options.where[self.__factory.target.tableName+"."+index] = value;
});
options.where = Utils._.extend(options.where, where)
} }
} else { } else {
options.where = where; options.where = where;
...@@ -58,16 +57,17 @@ module.exports = (function() { ...@@ -58,16 +57,17 @@ module.exports = (function() {
var self = this var self = this
, chainer = new Utils.QueryChainer() , chainer = new Utils.QueryChainer()
, association = self.__factory.target.associations[self.__factory.associationAccessor] , association = self.__factory.target.associations[self.__factory.associationAccessor]
, foreignIdentifier = association.isSelfAssociation ? association.foreignIdentifier : association.identifier , foreignIdentifier = association.isSelfAssociation ? association.foreignIdentifier : association.identifier;
, obsoleteAssociations = oldAssociations.filter(function (old) {
var obsoleteAssociations = oldAssociations.filter(function (old) {
// Return only those old associations that are not found in new // Return only those old associations that are not found in new
return !Utils._.find(newAssociations, function (obj) { return !Utils._.find(newAssociations, function (obj) {
return obj.id === old.id return (!!obj[foreignIdentifier] && !!old[foreignIdentifier] ? obj[foreignIdentifier] === old[foreignIdentifier] : obj.id === old.id)
}) })
}) })
, unassociatedObjects = newAssociations.filter(function (obj) { , unassociatedObjects = newAssociations.filter(function (obj) {
return !Utils._.find(oldAssociations, function (old) { return !Utils._.find(oldAssociations, function (old) {
return obj.id === old.id return (!!obj[foreignIdentifier] && !!old[foreignIdentifier] ? obj[foreignIdentifier] === old[foreignIdentifier] : obj.id === old.id)
}) })
}) })
...@@ -79,7 +79,7 @@ module.exports = (function() { ...@@ -79,7 +79,7 @@ module.exports = (function() {
, foreignKey = primaryKeys.filter(function(pk) { return pk != self.__factory.identifier })[0] , foreignKey = primaryKeys.filter(function(pk) { return pk != self.__factory.identifier })[0]
var where = {} var where = {}
where[self.__factory.identifier] = self.instance.id where[self.__factory.identifier] = self.instance[self.__factory.identifier] || self.instance.id
where[foreignKey] = foreignIds where[foreignKey] = foreignIds
chainer.add(self.__factory.connectorDAO.destroy(where)) chainer.add(self.__factory.connectorDAO.destroy(where))
...@@ -88,8 +88,8 @@ module.exports = (function() { ...@@ -88,8 +88,8 @@ module.exports = (function() {
if (unassociatedObjects.length > 0) { if (unassociatedObjects.length > 0) {
var bulk = unassociatedObjects.map(function(unassociatedObject) { var bulk = unassociatedObjects.map(function(unassociatedObject) {
var attributes = {} var attributes = {}
attributes[self.__factory.identifier] = self.instance.id attributes[self.__factory.identifier] = self.instance[self.__factory.identifier] || self.instance.id
attributes[foreignIdentifier] = unassociatedObject.id attributes[foreignIdentifier] = unassociatedObject[foreignIdentifier] || unassociatedObject.id
return attributes return attributes
}) })
...@@ -109,8 +109,8 @@ module.exports = (function() { ...@@ -109,8 +109,8 @@ module.exports = (function() {
, association = this.__factory.target.associations[this.__factory.associationAccessor] , association = this.__factory.target.associations[this.__factory.associationAccessor]
, foreignIdentifier = association.isSelfAssociation ? association.foreignIdentifier : association.identifier; , foreignIdentifier = association.isSelfAssociation ? association.foreignIdentifier : association.identifier;
attributes[this.__factory.identifier] = this.instance.id attributes[this.__factory.identifier] = this.instance[this.__factory.identifier] || this.instance.id
attributes[foreignIdentifier] = newAssociation.id attributes[foreignIdentifier] = newAssociation[foreignIdentifier] || newAssociation.id
this.__factory.connectorDAO.create(attributes) this.__factory.connectorDAO.create(attributes)
.success(function() { emitterProxy.emit('success', newAssociation) }) .success(function() { emitterProxy.emit('success', newAssociation) })
......
...@@ -7,14 +7,17 @@ module.exports = (function() { ...@@ -7,14 +7,17 @@ module.exports = (function() {
} }
HasManySingleLinked.prototype.injectGetter = function(options) { HasManySingleLinked.prototype.injectGetter = function(options) {
var where = {} var self = this
, where = {}
options = options || {} options = options || {}
where[this.__factory.identifier] = this.instance.id var primaryKey = Object.keys(this.instance.rawAttributes).filter(function(k) { return self.instance.rawAttributes[k].primaryKey === true })
primaryKey = primaryKey.length === 1 ? primaryKey[0] : 'id'
where[this.__factory.identifier] = this.instance[primaryKey]
if (options.where) { if (options.where) {
smart = Utils.smartWhere([where, options.where], this.__factory.target.daoFactoryManager.sequelize.options.dialect) smart = Utils.smartWhere([where, options.where], this.__factory.target.daoFactoryManager.sequelize.options.dialect)
smart = Utils.compileSmartWhere.call(this.__factory.target, smart) smart = Utils.compileSmartWhere.call(this.__factory.target, smart, this.__factory.target.daoFactoryManager.sequelize.options.dialect)
if (smart.length > 0) { if (smart.length > 0) {
options.where = smart options.where = smart
} }
...@@ -27,15 +30,17 @@ module.exports = (function() { ...@@ -27,15 +30,17 @@ module.exports = (function() {
HasManySingleLinked.prototype.injectSetter = function(emitter, oldAssociations, newAssociations) { HasManySingleLinked.prototype.injectSetter = function(emitter, oldAssociations, newAssociations) {
var self = this var self = this
, associationKeys = Object.keys((oldAssociations[0] || newAssociations[0] || {}).daoFactory.primaryKeys || {})
, associationKey = associationKeys.length === 1 ? associationKeys[0] : 'id'
, chainer = new Utils.QueryChainer() , chainer = new Utils.QueryChainer()
, obsoleteAssociations = oldAssociations.filter(function (old) { , obsoleteAssociations = oldAssociations.filter(function (old) {
return !Utils._.find(newAssociations, function (obj) { return !Utils._.find(newAssociations, function (obj) {
return obj.id === old.id return obj[associationKey] === old[associationKey]
}) })
}) })
, unassociatedObjects = newAssociations.filter(function (obj) { , unassociatedObjects = newAssociations.filter(function (obj) {
return !Utils._.find(oldAssociations, function (old) { return !Utils._.find(oldAssociations, function (old) {
return obj.id === old.id return obj[associationKey] === old[associationKey]
}) })
}) })
, update , update
...@@ -44,24 +49,38 @@ module.exports = (function() { ...@@ -44,24 +49,38 @@ module.exports = (function() {
// clear the old associations // clear the old associations
var obsoleteIds = obsoleteAssociations.map(function(associatedObject) { var obsoleteIds = obsoleteAssociations.map(function(associatedObject) {
associatedObject[self.__factory.identifier] = null associatedObject[self.__factory.identifier] = null
return associatedObject.id return associatedObject[associationKey]
}) })
update = {} update = {}
update[self.__factory.identifier] = null update[self.__factory.identifier] = null
chainer.add(this.__factory.target.update(update, { id: obsoleteIds })) var primaryKeys = Object.keys(this.__factory.target.primaryKeys)
, primaryKey = primaryKeys.length === 1 ? primaryKeys[0] : 'id'
, updateWhere = {}
updateWhere[primaryKey] = obsoleteIds
chainer.add(this.__factory.target.update(update, updateWhere))
} }
if (unassociatedObjects.length > 0) { if (unassociatedObjects.length > 0) {
// For the self.instance
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'
, updateWhere = {}
// set the new associations // set the new associations
var unassociatedIds = unassociatedObjects.map(function(associatedObject) { var unassociatedIds = unassociatedObjects.map(function(associatedObject) {
associatedObject[self.__factory.identifier] = self.instance.id associatedObject[self.__factory.identifier] = self.instance[pkey] || self.instance.id
return associatedObject.id return associatedObject[associationKey]
}) })
update = {} update = {}
update[self.__factory.identifier] = self.instance.id update[self.__factory.identifier] = self.instance[pkey] || self.instance.id
chainer.add(this.__factory.target.update(update, { id: unassociatedIds })) updateWhere[primaryKey] = unassociatedIds
chainer.add(this.__factory.target.update(update, updateWhere))
} }
chainer chainer
...@@ -72,7 +91,10 @@ module.exports = (function() { ...@@ -72,7 +91,10 @@ module.exports = (function() {
} }
HasManySingleLinked.prototype.injectAdder = function(emitterProxy, newAssociation) { HasManySingleLinked.prototype.injectAdder = function(emitterProxy, newAssociation) {
newAssociation[this.__factory.identifier] = this.instance.id var primaryKeys = Object.keys(this.instance.daoFactory.primaryKeys)
, primaryKey = primaryKeys.length === 1 ? primaryKeys[0] : 'id'
newAssociation[this.__factory.identifier] = this.instance[primaryKey]
newAssociation.save() newAssociation.save()
.success(function() { emitterProxy.emit('success', newAssociation) }) .success(function() { emitterProxy.emit('success', newAssociation) })
......
...@@ -88,7 +88,7 @@ module.exports = (function() { ...@@ -88,7 +88,7 @@ module.exports = (function() {
} }
obj[this.accessors.hasAll] = function(objects) { obj[this.accessors.hasAll] = function(objects) {
var instance = this; var instance = this;
var customEventEmitter = new Utils.CustomEventEmitter(function() { var customEventEmitter = new Utils.CustomEventEmitter(function() {
instance[self.accessors.get]() instance[self.accessors.get]()
.error(function(err){ customEventEmitter.emit('error', err)}) .error(function(err){ customEventEmitter.emit('error', err)})
...@@ -108,7 +108,7 @@ module.exports = (function() { ...@@ -108,7 +108,7 @@ module.exports = (function() {
} }
obj[this.accessors.hasSingle] = function(o) { obj[this.accessors.hasSingle] = function(o) {
var instance = this; var instance = this;
var customEventEmitter = new Utils.CustomEventEmitter(function() { var customEventEmitter = new Utils.CustomEventEmitter(function() {
instance[self.accessors.get]() instance[self.accessors.get]()
.error(function(err){ customEventEmitter.emit('error', err)}) .error(function(err){ customEventEmitter.emit('error', err)})
...@@ -155,8 +155,13 @@ module.exports = (function() { ...@@ -155,8 +155,13 @@ module.exports = (function() {
obj[this.accessors.add] = function(newAssociatedObject) { obj[this.accessors.add] = function(newAssociatedObject) {
var instance = this var instance = this
, primaryKeys = Object.keys(newAssociatedObject.daoFactory.primaryKeys || {})
, primaryKey = primaryKeys.length === 1 ? primaryKeys[0] : 'id'
, where = {}
where[newAssociatedObject.daoFactory.tableName+'.'+primaryKey] = newAssociatedObject[primaryKey]
return new Utils.CustomEventEmitter(function(emitter) { return new Utils.CustomEventEmitter(function(emitter) {
instance[self.accessors.get]({ where: { id: newAssociatedObject.id }}) instance[self.accessors.get]({ where: where })
.error(function(err){ emitter.emit('error', err)}) .error(function(err){ emitter.emit('error', err)})
.success(function(currentAssociatedObjects) { .success(function(currentAssociatedObjects) {
if (currentAssociatedObjects.length === 0) { if (currentAssociatedObjects.length === 0) {
......
...@@ -43,8 +43,10 @@ module.exports = (function() { ...@@ -43,8 +43,10 @@ module.exports = (function() {
var self = this var self = this
obj[this.accessors.get] = function(params) { obj[this.accessors.get] = function(params) {
var id = this.id var primaryKeys = Object.keys(this.daoFactory.primaryKeys)
, primaryKey = primaryKeys.length === 1 ? primaryKeys[0] : 'id'
, where = {} , where = {}
, id = this[primaryKey] || this.id
where[self.identifier] = id where[self.identifier] = id
...@@ -56,8 +58,8 @@ module.exports = (function() { ...@@ -56,8 +58,8 @@ module.exports = (function() {
params = {where: where} params = {where: where}
} }
smart = Utils.smartWhere([where, params.where || []], self.target.daoFactoryManager.sequelize.options.dialect) smart = Utils.smartWhere(params.where || [], self.target.daoFactoryManager.sequelize.options.dialect)
smart = Utils.compileSmartWhere.call(self.target, smart) smart = Utils.compileSmartWhere.call(self.target, smart, self.target.daoFactoryManager.sequelize.options.dialect)
if (smart.length > 0) { if (smart.length > 0) {
params.where = smart params.where = smart
} }
...@@ -69,11 +71,13 @@ module.exports = (function() { ...@@ -69,11 +71,13 @@ module.exports = (function() {
} }
HasOne.prototype.injectSetter = function(obj) { HasOne.prototype.injectSetter = function(obj) {
var self = this var self = this
, options = self.options || {}
obj[this.accessors.set] = function(associatedObject) { obj[this.accessors.set] = function(associatedObject) {
var instance = this; var instance = this
, instanceKeys = Object.keys(instance.daoFactory.primaryKeys)
, instanceKey = instanceKeys.length === 1 ? instanceKeys[0] : 'id'
return new Utils.CustomEventEmitter(function(emitter) { return new Utils.CustomEventEmitter(function(emitter) {
instance[self.accessors.get]().success(function(oldObj) { instance[self.accessors.get]().success(function(oldObj) {
if (oldObj) { if (oldObj) {
...@@ -82,7 +86,7 @@ module.exports = (function() { ...@@ -82,7 +86,7 @@ module.exports = (function() {
} }
if (associatedObject) { if (associatedObject) {
associatedObject[self.identifier] = instance.id associatedObject[self.identifier] = instance[instanceKey]
associatedObject associatedObject
.save() .save()
.success(function() { emitter.emit('success', associatedObject) }) .success(function() { emitter.emit('success', associatedObject) })
......
...@@ -250,7 +250,6 @@ module.exports = (function() { ...@@ -250,7 +250,6 @@ module.exports = (function() {
} }
var primaryKeys = this.primaryKeys var primaryKeys = this.primaryKeys
// options is not a hash but an id // options is not a hash but an id
if (typeof options === 'number') { if (typeof options === 'number') {
options = { where: options } options = { where: options }
......
...@@ -163,7 +163,7 @@ module.exports = (function() { ...@@ -163,7 +163,7 @@ module.exports = (function() {
return Utils._.template(query)({ tableName: tableName, attributes: attrString.join(', ') }) return Utils._.template(query)({ tableName: tableName, attributes: attrString.join(', ') })
}, },
selectQuery: function(tableName, options) { selectQuery: function(tableName, options, factory) {
var table = null, var table = null,
joinQuery = "" joinQuery = ""
...@@ -205,7 +205,7 @@ module.exports = (function() { ...@@ -205,7 +205,7 @@ module.exports = (function() {
query += joinQuery query += joinQuery
if (options.hasOwnProperty('where')) { if (options.hasOwnProperty('where')) {
options.where = this.getWhereConditions(options.where, tableName) options.where = this.getWhereConditions(options.where, tableName, factory)
query += " WHERE " + options.where query += " WHERE " + options.where
} }
...@@ -403,14 +403,24 @@ module.exports = (function() { ...@@ -403,14 +403,24 @@ module.exports = (function() {
return Utils._.template(sql)({ tableName: tableName, indexName: indexName }) return Utils._.template(sql)({ tableName: tableName, indexName: indexName })
}, },
getWhereConditions: function(smth, tableName) { getWhereConditions: function(smth, tableName, factory) {
var result = null var result = null
, where = {}
if (Utils.isHash(smth)) { if (Utils.isHash(smth)) {
smth = Utils.prependTableNameToHash(tableName, smth) smth = Utils.prependTableNameToHash(tableName, smth)
result = this.hashToWhereConditions(smth) result = this.hashToWhereConditions(smth)
} else if (typeof smth === 'number') { } else if (typeof smth === 'number') {
smth = Utils.prependTableNameToHash(tableName, { id: smth }) var primaryKeys = !!factory ? Object.keys(factory.primaryKeys) : []
if (primaryKeys.length > 0) {
// Since we're just a number, assume only the first key
primaryKeys = primaryKeys[0]
} else {
primaryKeys = 'id'
}
where[primaryKeys] = smth
smth = Utils.prependTableNameToHash(tableName, where)
result = this.hashToWhereConditions(smth) result = this.hashToWhereConditions(smth)
} else if (typeof smth === "string") { } else if (typeof smth === "string") {
result = smth result = smth
......
...@@ -217,7 +217,7 @@ module.exports = (function() { ...@@ -217,7 +217,7 @@ module.exports = (function() {
}) })
}, },
selectQuery: function(tableName, options) { selectQuery: function(tableName, options, factory) {
var query = "SELECT <%= attributes %> FROM <%= table %>", var query = "SELECT <%= attributes %> FROM <%= table %>",
table = null table = null
...@@ -258,7 +258,7 @@ module.exports = (function() { ...@@ -258,7 +258,7 @@ module.exports = (function() {
} }
if(options.hasOwnProperty('where')) { if(options.hasOwnProperty('where')) {
options.where = this.getWhereConditions(options.where, tableName) options.where = this.getWhereConditions(options.where, tableName, factory)
query += " WHERE <%= where %>" query += " WHERE <%= where %>"
} }
......
...@@ -134,7 +134,7 @@ module.exports = (function() { ...@@ -134,7 +134,7 @@ module.exports = (function() {
return Utils._.template(query)(replacements) return Utils._.template(query)(replacements)
}, },
selectQuery: function(tableName, options) { selectQuery: function(tableName, options, factory) {
var table = null, var table = null,
joinQuery = "" joinQuery = ""
...@@ -176,7 +176,7 @@ module.exports = (function() { ...@@ -176,7 +176,7 @@ module.exports = (function() {
query += joinQuery query += joinQuery
if (options.hasOwnProperty('where')) { if (options.hasOwnProperty('where')) {
options.where = this.getWhereConditions(options.where, tableName) options.where = this.getWhereConditions(options.where, tableName, factory)
query += " WHERE " + options.where query += " WHERE " + options.where
} }
......
...@@ -288,7 +288,7 @@ module.exports = (function() { ...@@ -288,7 +288,7 @@ module.exports = (function() {
QueryInterface.prototype.select = function(factory, tableName, options, queryOptions) { QueryInterface.prototype.select = function(factory, tableName, options, queryOptions) {
options = options || {} options = options || {}
var sql = this.QueryGenerator.selectQuery(tableName, options) var sql = this.QueryGenerator.selectQuery(tableName, options, factory)
queryOptions = Utils._.extend({}, queryOptions, { include: options.include }) queryOptions = Utils._.extend({}, queryOptions, { include: options.include })
return queryAndEmit.call(this, [sql, factory, queryOptions], 'select') return queryAndEmit.call(this, [sql, factory, queryOptions], 'select')
} }
......
...@@ -188,7 +188,6 @@ var Utils = module.exports = { ...@@ -188,7 +188,6 @@ var Utils = module.exports = {
break break
default: // lazy default: // lazy
text = text.concat(obj[column].lazy.conditions.map(function(val){ return columnName + ' ' + val })) text = text.concat(obj[column].lazy.conditions.map(function(val){ return columnName + ' ' + val }))
obj[column].lazy.bindings = obj[column].lazy.bindings.map(function(v) { return SqlString.escape(v, false, null, dialect) })
whereArgs = whereArgs.concat(obj[column].lazy.bindings) whereArgs = whereArgs.concat(obj[column].lazy.bindings)
} }
}) })
......
/*jshint camelcase: false*/
if (typeof require === 'function') { if (typeof require === 'function') {
const buster = require("buster") const buster = require("buster")
, Helpers = require('../buster-helpers') , Helpers = require('../buster-helpers')
...@@ -20,6 +21,33 @@ describe(Helpers.getTestDialectTeaser("BelongsTo"), function() { ...@@ -20,6 +21,33 @@ describe(Helpers.getTestDialectTeaser("BelongsTo"), function() {
}) })
describe('setAssociation', function() { describe('setAssociation', function() {
it('can set the association with declared primary keys...', function(done) {
var User = this.sequelize.define('UserXYZ', { user_id: {type: Sequelize.INTEGER, primaryKey: true }, username: Sequelize.STRING })
, Task = this.sequelize.define('TaskXYZ', { task_id: {type: Sequelize.INTEGER, primaryKey: true }, title: Sequelize.STRING })
Task.belongsTo(User, { foreignKey: 'user_id' })
this.sequelize.sync({ force: true }).success(function() {
User.create({ user_id: 1, username: 'foo' }).success(function(user) {
Task.create({ task_id: 1, title: 'task' }).success(function(task) {
task.setUserXYZ(user).success(function() {
task.getUserXYZ().success(function(user) {
expect(user).not.toEqual(null)
task.setUserXYZ(null).success(function() {
task.getUserXYZ().success(function(user) {
expect(user).toEqual(null)
done()
})
})
})
})
})
})
})
})
it('clears the association if null is passed', function(done) { it('clears the association if null is passed', function(done) {
var User = this.sequelize.define('UserXYZ', { username: Sequelize.STRING }) var User = this.sequelize.define('UserXYZ', { username: Sequelize.STRING })
, Task = this.sequelize.define('TaskXYZ', { title: Sequelize.STRING }) , Task = this.sequelize.define('TaskXYZ', { title: Sequelize.STRING })
...@@ -49,7 +77,6 @@ describe(Helpers.getTestDialectTeaser("BelongsTo"), function() { ...@@ -49,7 +77,6 @@ describe(Helpers.getTestDialectTeaser("BelongsTo"), function() {
}) })
describe("Foreign key constraints", function() { describe("Foreign key constraints", function() {
it("are not enabled by default", function(done) { it("are not enabled by default", function(done) {
var Task = this.sequelize.define('Task', { title: Sequelize.STRING }) var Task = this.sequelize.define('Task', { title: Sequelize.STRING })
, User = this.sequelize.define('User', { username: Sequelize.STRING }) , User = this.sequelize.define('User', { username: Sequelize.STRING })
......
/*jshint camelcase: false */
if (typeof require === 'function') { if (typeof require === 'function') {
const buster = require("buster") const buster = require("buster")
, Helpers = require('../buster-helpers') , Helpers = require('../buster-helpers')
...@@ -415,6 +416,40 @@ describe(Helpers.getTestDialectTeaser("HasMany"), function() { ...@@ -415,6 +416,40 @@ describe(Helpers.getTestDialectTeaser("HasMany"), function() {
}) })
}) })
}) })
it("joins an association with custom primary keys", function(done) {
var Group = this.sequelize.define('group', {
group_id: {type: Sequelize.STRING(32), primaryKey: true},
name: Sequelize.STRING(64)
})
, Member = this.sequelize.define('member', {
member_id: {type: Sequelize.STRING(32), primaryKey: true},
email: Sequelize.STRING(64)
})
Group.hasMany(Member, {joinTableName: 'group_members', foreignKey: 'group_id'})
Member.hasMany(Group, {joinTableName: 'group_members', foreignKey: 'member_id'})
this.sequelize.sync({ force: true }).success(function() {
Group.create({group_id: 1, name: 'Group1'}).success(function(){
Member.create({member_id: 10, email: 'team@sequelizejs.com'}).success(function() {
Group.find(1).success(function(group) {
Member.find(10).success(function(member) {
group.addMember(member).success(function() {
group.getMembers().success(function(members) {
expect(members).toBeArray()
expect(members.length).toEqual(1)
expect(members[0].member_id).toEqual(10)
expect(members[0].email).toEqual('team@sequelizejs.com')
done()
})
})
})
})
})
})
})
})
}) })
describe('optimizations using bulk create, destroy and update', function () { describe('optimizations using bulk create, destroy and update', function () {
......
...@@ -41,6 +41,32 @@ describe(Helpers.getTestDialectTeaser("HasOne"), function() { ...@@ -41,6 +41,32 @@ describe(Helpers.getTestDialectTeaser("HasOne"), function() {
}) })
describe('setAssociation', function() { describe('setAssociation', function() {
it('can set an association with predefined primary keys', function(done) {
var User = this.sequelize.define('UserXYZ', { userCoolIdTag: { type: Sequelize.INTEGER, primaryKey: true }, username: Sequelize.STRING })
, Task = this.sequelize.define('TaskXYZ', { taskOrSomething: { type: Sequelize.INTEGER, primaryKey: true }, title: Sequelize.STRING })
User.hasOne(Task, {foreignKey: 'userCoolIdTag'})
this.sequelize.sync({ force: true }).success(function() {
User.create({userCoolIdTag: 1, username: 'foo'}).success(function(user) {
Task.create({taskOrSomething: 1, title: 'bar'}).success(function(task) {
user.setTaskXYZ(task).success(function() {
user.getTaskXYZ().success(function(task) {
expect(task).not.toEqual(null)
user.setTaskXYZ(null).success(function() {
user.getTaskXYZ().success(function(task) {
expect(task).toEqual(null)
done()
})
})
})
})
})
})
})
})
it('clears the association if null is passed', function(done) { it('clears the association if null is passed', function(done) {
var User = this.sequelize.define('UserXYZ', { username: Sequelize.STRING }) var User = this.sequelize.define('UserXYZ', { username: Sequelize.STRING })
, Task = this.sequelize.define('TaskXYZ', { title: Sequelize.STRING }) , Task = this.sequelize.define('TaskXYZ', { title: Sequelize.STRING })
...@@ -70,7 +96,6 @@ describe(Helpers.getTestDialectTeaser("HasOne"), function() { ...@@ -70,7 +96,6 @@ describe(Helpers.getTestDialectTeaser("HasOne"), function() {
}) })
describe("Foreign key constraints", function() { describe("Foreign key constraints", function() {
it("are not enabled by default", function(done) { it("are not enabled by default", function(done) {
var Task = this.sequelize.define('Task', { title: Sequelize.STRING }) var Task = this.sequelize.define('Task', { title: Sequelize.STRING })
, User = this.sequelize.define('User', { username: Sequelize.STRING }) , User = this.sequelize.define('User', { username: Sequelize.STRING })
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!