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

Commit 905114b1 by Jan Aagaard Meier

Removed synconassocation, added ondelete and onupdate to n:m and made cascade th…

…e default, made cascade / set null the default for hasone and belongsto
1 parent 7032288e
...@@ -2,7 +2,12 @@ Notice: All 1.7.x changes are present in 2.0.x aswell ...@@ -2,7 +2,12 @@ Notice: All 1.7.x changes are present in 2.0.x aswell
# v2.0.0-dev11 # v2.0.0-dev11
- [PERFORMANCE] increased build performance when using include, which speeds up findAll etc. - [PERFORMANCE] increased build performance when using include, which speeds up findAll etc.
<<<<<<< HEAD
- [BUG] Made it possible to use HSTORE both in attribute: HSTORE and attribute: { type: HSTORE } form. Thanks to @tomchentw [#1458](https://github.com/sequelize/sequelize/pull/1458) - [BUG] Made it possible to use HSTORE both in attribute: HSTORE and attribute: { type: HSTORE } form. Thanks to @tomchentw [#1458](https://github.com/sequelize/sequelize/pull/1458)
=======
- [FEATURE] n:m now marks the columns of the through table as foreign keys and cascades them on delete and update by default.
- [FEATURE] 1:1 and 1:m marks columns as foreign keys, and sets them to cascade on update and set null on delete. If you are working with an existing DB which does not allow null values, be sure to override those options, or disable them completely by passing useConstrations: false to your assocation call (`M1.belongsTo(M2, { useConstraints: false})`).
>>>>>>> Removed synconassocation, added ondelete and onupdate to n:m and made cascade the default, made cascade / set null the default for hasone and belongsto
#### Backwards compatability changes #### Backwards compatability changes
- selectedValues has been removed for performance reasons, if you depend on this, please open an issue and we will help you work around it. - selectedValues has been removed for performance reasons, if you depend on this, please open an issue and we will help you work around it.
...@@ -10,6 +15,8 @@ Notice: All 1.7.x changes are present in 2.0.x aswell ...@@ -10,6 +15,8 @@ Notice: All 1.7.x changes are present in 2.0.x aswell
- if you have any 1:1 relations where both sides use an alias, you'll need to set the foreign key, or they'll each use a different foreign key based on their alias. - if you have any 1:1 relations where both sides use an alias, you'll need to set the foreign key, or they'll each use a different foreign key based on their alias.
- foreign keys for non-id primary keys will now be named for the foreign key, i.e. pub_name rather than pub_id - foreign keys for non-id primary keys will now be named for the foreign key, i.e. pub_name rather than pub_id
- if you have non-id primary keys you should go through your associations and set the foreignKey option if relying on a incorrect _id foreign key - if you have non-id primary keys you should go through your associations and set the foreignKey option if relying on a incorrect _id foreign key
- syncOnAssocation has been removed. It only worked for n:m, and having a synchronous function (hasMany) that invokes an asynchronous function (sync) without returning an emitter does not make a lot of sense. If you (implicitly) depended on this feature, sequelize.sync is your friend. If you do not want to do a full sync, use custom through models for n:m (`M1.hasMany(M2, { through: M3})`) and sync the through model explicitly.
- Join tables will be no longer be paranoid (have a deletedAt timestamp added), even though other models are.
# v1.7.0 # v1.7.0
- [FEATURE] covers more advanced include cases with limiting and filtering (specifically cases where a include would be in the subquery but its child include wouldnt be, for cases where a 1:1 association had a 1:M association as a nested include) - [FEATURE] covers more advanced include cases with limiting and filtering (specifically cases where a include would be in the subquery but its child include wouldnt be, for cases where a 1:1 association had a 1:M association as a nested include)
......
...@@ -47,6 +47,10 @@ module.exports = (function() { ...@@ -47,6 +47,10 @@ module.exports = (function() {
var newAttributes = {} var newAttributes = {}
newAttributes[this.identifier] = { type: this.options.keyType || this.target.rawAttributes[this.targetIdentifier].type } newAttributes[this.identifier] = { type: this.options.keyType || this.target.rawAttributes[this.targetIdentifier].type }
if (this.options.useConstraints !== false) {
this.options.onDelete = this.options.onDelete || 'SET NULL'
this.options.onUpdate = this.options.onUpdate || 'CASCADE'
}
Helpers.addForeignKeyConstraints(newAttributes[this.identifier], this.target, this.source, this.options) Helpers.addForeignKeyConstraints(newAttributes[this.identifier], this.target, this.source, this.options)
Utils._.defaults(this.source.rawAttributes, newAttributes) Utils._.defaults(this.source.rawAttributes, newAttributes)
......
...@@ -103,7 +103,8 @@ module.exports = (function() { ...@@ -103,7 +103,8 @@ module.exports = (function() {
if (typeof this.through === "string") { if (typeof this.through === "string") {
this.through = this.sequelize.define(this.through, {}, _.extend(this.options, { this.through = this.sequelize.define(this.through, {}, _.extend(this.options, {
tableName: this.through tableName: this.through,
paranoid: false // A paranoid join table does not make sense
})) }))
if (this.targetAssociation) { if (this.targetAssociation) {
...@@ -174,24 +175,46 @@ module.exports = (function() { ...@@ -174,24 +175,46 @@ module.exports = (function() {
// define a new model, which connects the models // define a new model, which connects the models
var combinedTableAttributes = {} var combinedTableAttributes = {}
var sourceKeyType = this.source.rawAttributes[this.source.primaryKeyAttribute].type , sourceKeyType = this.source.rawAttributes[this.source.primaryKeyAttribute].type
var targetKeyType = this.target.rawAttributes[this.target.primaryKeyAttribute].type , targetKeyType = this.target.rawAttributes[this.target.primaryKeyAttribute].type
, sourceAttribute = { type: sourceKeyType }
, targetAttribute = { type: targetKeyType }
if (this.options.useConstraints !== false) {
sourceAttribute.references = this.source.getTableName()
sourceAttribute.referencesKey = this.source.primaryKeyAttribute
sourceAttribute.onDelete = this.options.onDelete || 'CASCADE'
sourceAttribute.onUpdate = this.options.onUpdate || 'CASCADE'
}
if (this.targetAssociation.options.useConstraints !== false) {
targetAttribute.references = this.target.getTableName()
targetAttribute.referencesKey = this.target.primaryKeyAttribute
targetAttribute.onDelete = this.targetAssociation.options.onDelete || 'CASCADE'
targetAttribute.onUpdate = this.targetAssociation.options.onUpdate || 'CASCADE'
}
if (primaryKeyDeleted) { if (primaryKeyDeleted) {
combinedTableAttributes[this.identifier] = {type: sourceKeyType, primaryKey: true} targetAttribute.primaryKey = sourceAttribute.primaryKey = true
combinedTableAttributes[this.foreignIdentifier] = {type: targetKeyType, primaryKey: true}
} else { } else {
var uniqueKey = [this.through.tableName, this.identifier, this.foreignIdentifier, 'unique'].join('_') var uniqueKey = [this.through.tableName, this.identifier, this.foreignIdentifier, 'unique'].join('_')
combinedTableAttributes[this.identifier] = {type: sourceKeyType, unique: uniqueKey} targetAttribute.unique = sourceAttribute.unique = uniqueKey
combinedTableAttributes[this.foreignIdentifier] = {type: targetKeyType, unique: uniqueKey}
} }
combinedTableAttributes[this.identifier] = sourceAttribute
combinedTableAttributes[this.foreignIdentifier] = targetAttribute
this.through.rawAttributes = Utils._.merge(this.through.rawAttributes, combinedTableAttributes) this.through.rawAttributes = Utils._.merge(this.through.rawAttributes, combinedTableAttributes)
this.through.init(this.through.daoFactoryManager) this.through.init(this.through.daoFactoryManager)
} else { } else {
var newAttributes = {} var newAttributes = {}
var constraintOptions = _.clone(this.options) // Create a new options object for use with addForeignKeyConstraints, to avoid polluting this.options in case it is later used for a n:m
newAttributes[this.identifier] = { type: this.options.keyType || this.target.rawAttributes[this.target.primaryKeyAttribute].type } newAttributes[this.identifier] = { type: this.options.keyType || this.target.rawAttributes[this.target.primaryKeyAttribute].type }
Helpers.addForeignKeyConstraints(newAttributes[this.identifier], this.source, this.target, this.options)
if (this.options.useConstraints !== false) {
constraintOptions.onDelete = constraintOptions.onDelete || 'SET NULL'
constraintOptions.onUpdate = constraintOptions.onUpdate || 'CASCADE'
}
Helpers.addForeignKeyConstraints(newAttributes[this.identifier], this.source, this.target, constraintOptions)
Utils._.defaults(this.target.rawAttributes, newAttributes) Utils._.defaults(this.target.rawAttributes, newAttributes)
} }
......
...@@ -48,6 +48,11 @@ module.exports = (function() { ...@@ -48,6 +48,11 @@ module.exports = (function() {
newAttributes[this.identifier] = { type: this.options.keyType || keyType } newAttributes[this.identifier] = { type: this.options.keyType || keyType }
Utils._.defaults(this.target.rawAttributes, newAttributes) Utils._.defaults(this.target.rawAttributes, newAttributes)
if (this.options.useConstraints !== false) {
this.options.onDelete = this.options.onDelete || 'SET NULL'
this.options.onUpdate = this.options.onUpdate || 'CASCADE'
}
Helpers.addForeignKeyConstraints(this.target.rawAttributes[this.identifier], this.source, this.target, this.options) Helpers.addForeignKeyConstraints(this.target.rawAttributes[this.identifier], this.source, this.target, this.options)
// Sync attributes and setters/getters to DAO prototype // Sync attributes and setters/getters to DAO prototype
......
var Toposort = require('toposort-class') var Toposort = require('toposort-class')
, DaoFactory = require('./dao-factory') , DaoFactory = require('./dao-factory')
, _ = require('lodash')
module.exports = (function() { module.exports = (function() {
var DAOFactoryManager = function(sequelize) { var DAOFactoryManager = function(sequelize) {
...@@ -39,9 +40,14 @@ module.exports = (function() { ...@@ -39,9 +40,14 @@ module.exports = (function() {
* take foreign key constraints into account so that dependencies are visited * take foreign key constraints into account so that dependencies are visited
* before dependents. * before dependents.
*/ */
DAOFactoryManager.prototype.forEachDAO = function(iterator) { DAOFactoryManager.prototype.forEachDAO = function(iterator, options) {
var daos = {} var daos = {}
, sorter = new Toposort() , sorter = new Toposort()
, sorted
options = _.defaults(options || {}, {
reverse: true
})
this.daos.forEach(function(dao) { this.daos.forEach(function(dao) {
var deps = [] var deps = []
...@@ -62,7 +68,11 @@ module.exports = (function() { ...@@ -62,7 +68,11 @@ module.exports = (function() {
sorter.add(dao.tableName, deps) sorter.add(dao.tableName, deps)
}) })
sorter.sort().reverse().forEach(function(name) { sorted = sorter.sort()
if (options.reverse) {
sorted = sorted.reverse()
}
sorted.forEach(function(name) {
iterator(daos[name], name) iterator(daos[name], name)
}) })
} }
......
...@@ -19,7 +19,6 @@ module.exports = (function() { ...@@ -19,7 +19,6 @@ module.exports = (function() {
validate: {}, validate: {},
freezeTableName: false, freezeTableName: false,
underscored: false, underscored: false,
syncOnAssociation: true,
paranoid: false, paranoid: false,
whereCollection: null, whereCollection: null,
schema: null, schema: null,
...@@ -1612,7 +1611,15 @@ module.exports = (function() { ...@@ -1612,7 +1611,15 @@ module.exports = (function() {
var optClone = function (options) { var optClone = function (options) {
return Utils._.cloneDeep(options, function (elem) { return Utils._.cloneDeep(options, function (elem) {
// The DAOFactories used for include are pass by ref, so don't clone them. // The DAOFactories used for include are pass by ref, so don't clone them.
if (elem instanceof DAOFactory || elem instanceof Utils.col || elem instanceof Utils.literal || elem instanceof Utils.cast || elem instanceof Utils.fn || elem instanceof Utils.and || elem instanceof Utils.or) { if (elem instanceof DAOFactory ||
elem instanceof Utils.col ||
elem instanceof Utils.literal ||
elem instanceof Utils.cast ||
elem instanceof Utils.fn ||
elem instanceof Utils.and ||
elem instanceof Utils.or ||
elem instanceof Transaction
) {
return elem return elem
} }
// Unfortunately, lodash.cloneDeep doesn't preserve Buffer.isBuffer, which we have to rely on for binary data // Unfortunately, lodash.cloneDeep doesn't preserve Buffer.isBuffer, which we have to rely on for binary data
......
...@@ -54,7 +54,15 @@ module.exports = (function() { ...@@ -54,7 +54,15 @@ module.exports = (function() {
if (Utils._.includes(dataType, 'PRIMARY KEY')) { if (Utils._.includes(dataType, 'PRIMARY KEY')) {
primaryKeys.push(attr) primaryKeys.push(attr)
attrStr.push(this.quoteIdentifier(attr) + " " + dataType.replace(/PRIMARY KEY/, ''))
if (Utils._.includes(dataType, 'REFERENCES')) {
// MySQL doesn't support inline REFERENCES declarations: move to the end
var m = dataType.match(/^(.+) (REFERENCES.*)$/)
attrStr.push(this.quoteIdentifier(attr) + " " + m[1].replace(/PRIMARY KEY/, ''))
foreignKeys[attr] = m[2]
} else {
attrStr.push(this.quoteIdentifier(attr) + " " + dataType.replace(/PRIMARY KEY/, ''))
}
} else if (Utils._.includes(dataType, 'REFERENCES')) { } else if (Utils._.includes(dataType, 'REFERENCES')) {
// MySQL doesn't support inline REFERENCES declarations: move to the end // MySQL doesn't support inline REFERENCES declarations: move to the end
var m = dataType.match(/^(.+) (REFERENCES.*)$/) var m = dataType.match(/^(.+) (REFERENCES.*)$/)
......
...@@ -80,7 +80,7 @@ module.exports = (function() { ...@@ -80,7 +80,7 @@ module.exports = (function() {
} }
var emitter = serial.klass[serial.method].apply(serial.klass, serial.params) var emitter = serial.klass[serial.method].apply(serial.klass, serial.params)
emitter.success(function(result) { emitter.success(function(result) {
self.serialResults[serialCopy.indexOf(serial)] = result self.serialResults[serialCopy.indexOf(serial)] = result
......
...@@ -387,7 +387,7 @@ module.exports = (function() { ...@@ -387,7 +387,7 @@ module.exports = (function() {
// Topologically sort by foreign key constraints to give us an appropriate // Topologically sort by foreign key constraints to give us an appropriate
// creation order // creation order
this.daoFactoryManager.forEachDAO(function(dao, daoName) { this.daoFactoryManager.forEachDAO(function(dao) {
if (dao) { if (dao) {
chainer.add(dao, 'sync', [options]) chainer.add(dao, 'sync', [options])
} else { } else {
...@@ -402,12 +402,12 @@ module.exports = (function() { ...@@ -402,12 +402,12 @@ module.exports = (function() {
var self = this var self = this
return new Utils.CustomEventEmitter(function(emitter) { return new Utils.CustomEventEmitter(function(emitter) {
var chainer = new Utils.QueryChainer var chainer = new Utils.QueryChainer()
self.daoFactoryManager.daos.forEach(function(dao) { chainer.add(dao.drop()) }) self.daoFactoryManager.forEachDAO(function(dao) { chainer.add(dao, 'drop', []) }, { reverse: false})
chainer chainer
.run() .runSerially()
.success(function() { emitter.emit('success', null) }) .success(function() { emitter.emit('success', null) })
.error(function(err) { emitter.emit('error', err) }) .error(function(err) { emitter.emit('error', err) })
}).run() }).run()
......
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
...@@ -283,19 +283,41 @@ describe(Support.getTestDialectTeaser("BelongsTo"), function() { ...@@ -283,19 +283,41 @@ describe(Support.getTestDialectTeaser("BelongsTo"), function() {
}); });
describe("foreign key constraints", function() { describe("foreign key constraints", function() {
it("are not enabled by default", function(done) { it("are enabled by default", function(done) {
var Task = this.sequelize.define('Task', { title: DataTypes.STRING }) var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
, User = this.sequelize.define('User', { username: DataTypes.STRING }) , User = this.sequelize.define('User', { username: DataTypes.STRING })
Task.belongsTo(User) Task.belongsTo(User) // defaults to SET NULL
this.sequelize.sync({ force: true }).success(function() { this.sequelize.sync({ force: true }).success(function() {
User.create({ username: 'foo' }).success(function(user) { User.create({ username: 'foo' }).success(function(user) {
Task.create({ title: 'task' }).success(function(task) { Task.create({ title: 'task' }).success(function(task) {
task.setUser(user).success(function() { task.setUser(user).success(function() {
user.destroy().success(function() { user.destroy().success(function() {
Task.findAll().success(function(tasks) { task.reload().success(function() {
expect(tasks).to.have.length(1) expect(task.UserId).to.equal(null)
done()
})
})
})
})
})
})
})
it("should be possible to disable them", function(done) {
var Task = this.sequelize.define('Task', { title: Sequelize.STRING })
, User = this.sequelize.define('User', { username: Sequelize.STRING })
Task.belongsTo(User, { useConstraints: false })
this.sequelize.sync({ force: true }).success(function() {
User.create({ username: 'foo' }).success(function(user) {
Task.create({ title: 'task' }).success(function(task) {
task.setUser(user).success(function() {
user.destroy().success(function() {
task.reload().success(function() {
expect(task.UserId).to.equal(user.id)
done() done()
}) })
}) })
...@@ -447,7 +469,7 @@ describe(Support.getTestDialectTeaser("BelongsTo"), function() { ...@@ -447,7 +469,7 @@ describe(Support.getTestDialectTeaser("BelongsTo"), function() {
var tableName = 'TaskXYZ_' + dataType.toString() var tableName = 'TaskXYZ_' + dataType.toString()
Tasks[dataType] = self.sequelize.define(tableName, { title: DataTypes.STRING }) Tasks[dataType] = self.sequelize.define(tableName, { title: DataTypes.STRING })
Tasks[dataType].belongsTo(User, { foreignKey: 'userId', keyType: dataType }) Tasks[dataType].belongsTo(User, { foreignKey: 'userId', keyType: dataType, useConstraints: false })
}) })
self.sequelize.sync({ force: true }) self.sequelize.sync({ force: true })
......
...@@ -211,7 +211,8 @@ describe(Support.getTestDialectTeaser("HasOne"), function() { ...@@ -211,7 +211,8 @@ describe(Support.getTestDialectTeaser("HasOne"), function() {
}) })
}) })
describe("foreign key", function () {
describe("Foreign key constraints", function() {
it('should lowercase foreign keys when using underscored', function () { it('should lowercase foreign keys when using underscored', function () {
var User = this.sequelize.define('User', { username: Sequelize.STRING }, { underscored: true }) var User = this.sequelize.define('User', { username: Sequelize.STRING }, { underscored: true })
, Account = this.sequelize.define('Account', { name: Sequelize.STRING }, { underscored: true }) , Account = this.sequelize.define('Account', { name: Sequelize.STRING }, { underscored: true })
...@@ -228,14 +229,12 @@ describe(Support.getTestDialectTeaser("HasOne"), function() { ...@@ -228,14 +229,12 @@ describe(Support.getTestDialectTeaser("HasOne"), function() {
expect(User.rawAttributes.AccountId).to.exist expect(User.rawAttributes.AccountId).to.exist
}) })
})
describe("foreign key constraints", function() { it("are 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 })
User.hasOne(Task) User.hasOne(Task) // defaults to set NULL
User.sync({ force: true }).success(function() { User.sync({ force: true }).success(function() {
Task.sync({ force: true }).success(function() { Task.sync({ force: true }).success(function() {
...@@ -243,8 +242,32 @@ describe(Support.getTestDialectTeaser("HasOne"), function() { ...@@ -243,8 +242,32 @@ describe(Support.getTestDialectTeaser("HasOne"), function() {
Task.create({ title: 'task' }).success(function(task) { Task.create({ title: 'task' }).success(function(task) {
user.setTask(task).success(function() { user.setTask(task).success(function() {
user.destroy().success(function() { user.destroy().success(function() {
Task.findAll().success(function(tasks) { task.reload().success(function() {
expect(tasks).to.have.length(1) expect(task.UserId).to.equal(null)
done()
})
})
})
})
})
})
})
})
it("should be possible to disable them", function(done) {
var Task = this.sequelize.define('Task', { title: Sequelize.STRING })
, User = this.sequelize.define('User', { username: Sequelize.STRING })
User.hasOne(Task, { useConstraints: false })
User.sync({ force: true }).success(function() {
Task.sync({ force: true }).success(function() {
User.create({ username: 'foo' }).success(function(user) {
Task.create({ title: 'task' }).success(function(task) {
user.setTask(task).success(function() {
user.destroy().success(function() {
task.reload().success(function() {
expect(task.UserId).to.equal(user.id)
done() done()
}) })
}) })
...@@ -406,7 +429,7 @@ describe(Support.getTestDialectTeaser("HasOne"), function() { ...@@ -406,7 +429,7 @@ describe(Support.getTestDialectTeaser("HasOne"), function() {
var tableName = 'TaskXYZ_' + dataType.toString() var tableName = 'TaskXYZ_' + dataType.toString()
Tasks[dataType] = self.sequelize.define(tableName, { title: Sequelize.STRING }) Tasks[dataType] = self.sequelize.define(tableName, { title: Sequelize.STRING })
User.hasOne(Tasks[dataType], { foreignKey: 'userId', keyType: dataType }) User.hasOne(Tasks[dataType], { foreignKey: 'userId', keyType: dataType, useConstraints: false })
Tasks[dataType].sync({ force: true }).success(function() { Tasks[dataType].sync({ force: true }).success(function() {
expect(Tasks[dataType].rawAttributes.userId.type.toString()) expect(Tasks[dataType].rawAttributes.userId.type.toString())
......
...@@ -313,18 +313,16 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () { ...@@ -313,18 +313,16 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
User.hasMany(Session, { as: 'Sessions' }) User.hasMany(Session, { as: 'Sessions' })
Session.belongsTo(User) Session.belongsTo(User)
Session.sync({ force: true }).success(function() { this.sequelize.sync({ force: true }).success(function() {
User.sync({ force: true }).success(function() { User.create({name: 'Name1', password: '123', isAdmin: false}).success(function(user) {
User.create({name: 'Name1', password: '123', isAdmin: false}).success(function(user) { var sess = Session.build({
var sess = Session.build({ lastUpdate: new Date(),
lastUpdate: new Date(), token: '123'
token: '123' })
})
user.addSession(sess).success(function(u) { user.addSession(sess).success(function(u) {
expect(u.token).to.equal('123') expect(u.token).to.equal('123')
done() done()
})
}) })
}) })
}) })
...@@ -849,9 +847,7 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () { ...@@ -849,9 +847,7 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
self.Country.hasMany(self.Person, { as: 'Residents', foreignKey: 'CountryResidentId' }) self.Country.hasMany(self.Person, { as: 'Residents', foreignKey: 'CountryResidentId' })
self.Person.belongsTo(self.Country, { as: 'CountryResident', foreignKey: 'CountryResidentId' }) self.Person.belongsTo(self.Country, { as: 'CountryResident', foreignKey: 'CountryResidentId' })
async.forEach([ self.Continent, self.Country, self.Industry, self.Person ], function(model, callback) { this.sequelize.sync({ force: true }).success(function () {
model.sync({ force: true }).done(callback)
}, function () {
async.parallel({ async.parallel({
europe: function(callback) {self.Continent.create({ name: 'Europe' }).done(callback)}, europe: function(callback) {self.Continent.create({ name: 'Europe' }).done(callback)},
england: function(callback) {self.Country.create({ name: 'England' }).done(callback)}, england: function(callback) {self.Country.create({ name: 'England' }).done(callback)},
...@@ -874,7 +870,7 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () { ...@@ -874,7 +870,7 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
done() done()
}) })
}) })
}) })
}) })
it('includes all associations', function(done) { it('includes all associations', function(done) {
...@@ -965,9 +961,7 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () { ...@@ -965,9 +961,7 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
self.Country.hasMany(self.Person, { as: 'Residents', foreignKey: 'CountryResidentId' }) self.Country.hasMany(self.Person, { as: 'Residents', foreignKey: 'CountryResidentId' })
self.Person.belongsTo(self.Country, { as: 'CountryResident', foreignKey: 'CountryResidentId' }) self.Person.belongsTo(self.Country, { as: 'CountryResident', foreignKey: 'CountryResidentId' })
async.forEach([ self.Continent, self.Country, self.Person ], function(model, callback) { this.sequelize.sync({ force: true }).success(function () {
model.sync({ force: true }).done(callback)
}, function () {
async.parallel({ async.parallel({
europe: function(callback) {self.Continent.create({ name: 'Europe' }).done(callback)}, europe: function(callback) {self.Continent.create({ name: 'Europe' }).done(callback)},
asia: function(callback) {self.Continent.create({ name: 'Asia' }).done(callback)}, asia: function(callback) {self.Continent.create({ name: 'Asia' }).done(callback)},
...@@ -1120,9 +1114,7 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () { ...@@ -1120,9 +1114,7 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
self.Country.hasMany(self.Industry, {through: self.IndustryCountry}) self.Country.hasMany(self.Industry, {through: self.IndustryCountry})
self.Industry.hasMany(self.Country, {through: self.IndustryCountry}) self.Industry.hasMany(self.Country, {through: self.IndustryCountry})
async.forEach([ self.Country, self.Industry ], function(model, callback) { this.sequelize.sync({ force: true }).success(function () {
model.sync({ force: true }).done(callback)
}, function () {
async.parallel({ async.parallel({
england: function(callback) {self.Country.create({ name: 'England' }).done(callback)}, england: function(callback) {self.Country.create({ name: 'England' }).done(callback)},
france: function(callback) {self.Country.create({ name: 'France' }).done(callback)}, france: function(callback) {self.Country.create({ name: 'France' }).done(callback)},
......
...@@ -353,14 +353,12 @@ describe(Support.getTestDialectTeaser("DaoValidator"), function() { ...@@ -353,14 +353,12 @@ describe(Support.getTestDialectTeaser("DaoValidator"), function() {
}) })
Project.hasOne(Task) Project.hasOne(Task)
Task.hasOne(Project) Task.belongsTo(Project)
Project.sync({ force: true }).success(function() { this.sequelize.sync({ force: true }).success(function() {
Task.sync({ force: true }).success(function() { self.Project = Project
self.Project = Project self.Task = Task
self.Task = Task done()
done()
})
}) })
}) })
......
...@@ -6334,10 +6334,8 @@ describe(Support.getTestDialectTeaser("Hooks"), function () { ...@@ -6334,10 +6334,8 @@ describe(Support.getTestDialectTeaser("Hooks"), function () {
this.Projects.hasOne(this.Tasks, {onDelete: 'cascade', hooks: true}) this.Projects.hasOne(this.Tasks, {onDelete: 'cascade', hooks: true})
this.Tasks.belongsTo(this.Projects) this.Tasks.belongsTo(this.Projects)
this.Projects.sync({ force: true }).success(function() { this.sequelize.sync({ force: true }).success(function() {
self.Tasks.sync({ force: true }).success(function() { done()
done()
})
}) })
}) })
...@@ -6733,10 +6731,8 @@ describe(Support.getTestDialectTeaser("Hooks"), function () { ...@@ -6733,10 +6731,8 @@ describe(Support.getTestDialectTeaser("Hooks"), function () {
this.Projects.hasMany(this.Tasks) this.Projects.hasMany(this.Tasks)
this.Tasks.belongsTo(this.Projects) this.Tasks.belongsTo(this.Projects)
this.Projects.sync({ force: true }).success(function() { this.sequelize.sync({ force: true }).success(function() {
self.Tasks.sync({ force: true }).success(function() { done()
done()
})
}) })
}) })
...@@ -6842,10 +6838,8 @@ describe(Support.getTestDialectTeaser("Hooks"), function () { ...@@ -6842,10 +6838,8 @@ describe(Support.getTestDialectTeaser("Hooks"), function () {
this.Projects.hasMany(this.Tasks, {cascade: 'onDelete', joinTableName: 'projects_and_tasks', hooks: true}) this.Projects.hasMany(this.Tasks, {cascade: 'onDelete', joinTableName: 'projects_and_tasks', hooks: true})
this.Tasks.hasMany(this.Projects, {cascade: 'onDelete', joinTableName: 'projects_and_tasks', hooks: true}) this.Tasks.hasMany(this.Projects, {cascade: 'onDelete', joinTableName: 'projects_and_tasks', hooks: true})
this.Projects.sync({ force: true }).success(function() { this.sequelize.sync({ force: true }).success(function() {
self.Tasks.sync({ force: true }).success(function() { done()
done()
})
}) })
}) })
...@@ -6952,10 +6946,8 @@ describe(Support.getTestDialectTeaser("Hooks"), function () { ...@@ -6952,10 +6946,8 @@ describe(Support.getTestDialectTeaser("Hooks"), function () {
this.Projects.hasMany(this.Tasks, {hooks: true}) this.Projects.hasMany(this.Tasks, {hooks: true})
this.Tasks.hasMany(this.Projects, {hooks: true}) this.Tasks.hasMany(this.Projects, {hooks: true})
this.Projects.sync({ force: true }).success(function() { this.sequelize.sync({ force: true }).success(function() {
self.Tasks.sync({ force: true }).success(function() { done()
done()
})
}) })
}) })
......
...@@ -57,8 +57,8 @@ if (Support.dialectIsMySQL()) { ...@@ -57,8 +57,8 @@ if (Support.dialectIsMySQL()) {
this.users = null this.users = null
this.tasks = null this.tasks = null
this.User.hasMany(this.Task, {as:'Tasks'}) this.User.hasMany(this.Task, {as:'Tasks', through: 'UserTasks'})
this.Task.hasMany(this.User, {as:'Users'}) this.Task.hasMany(this.User, {as:'Users', through: 'UserTasks'})
var self = this var self = this
, users = [] , users = []
...@@ -72,12 +72,10 @@ if (Support.dialectIsMySQL()) { ...@@ -72,12 +72,10 @@ if (Support.dialectIsMySQL()) {
tasks[tasks.length] = {name: 'Task' + Math.random()} tasks[tasks.length] = {name: 'Task' + Math.random()}
} }
this.User.sync({ force: true }).success(function() { this.sequelize.sync({ force: true }).success(function() {
self.Task.sync({ force: true }).success(function() { self.User.bulkCreate(users).success(function() {
self.User.bulkCreate(users).success(function() { self.Task.bulkCreate(tasks).success(function() {
self.Task.bulkCreate(tasks).success(function() { done()
done()
})
}) })
}) })
}) })
......
...@@ -63,8 +63,8 @@ if (dialect.match(/^postgres/)) { ...@@ -63,8 +63,8 @@ if (dialect.match(/^postgres/)) {
this.users = null this.users = null
this.tasks = null this.tasks = null
this.User.hasMany(this.Task, {as:'Tasks'}) this.User.hasMany(this.Task, {as:'Tasks', through: 'usertasks'})
this.Task.hasMany(this.User, {as:'Users'}) this.Task.hasMany(this.User, {as:'Users', through: 'usertasks'})
var self = this var self = this
, users = [] , users = []
...@@ -78,16 +78,14 @@ if (dialect.match(/^postgres/)) { ...@@ -78,16 +78,14 @@ if (dialect.match(/^postgres/)) {
tasks[tasks.length] = {name: 'Task' + Math.random()} tasks[tasks.length] = {name: 'Task' + Math.random()}
} }
self.User.sync({ force: true }).success(function() { this.sequelize.sync({ force: true }).success(function() {
self.Task.sync({ force: true }).success(function() { self.User.bulkCreate(users).success(function() {
self.User.bulkCreate(users).success(function() { self.Task.bulkCreate(tasks).success(function() {
self.Task.bulkCreate(tasks).success(function() { self.User.all().success(function(_users) {
self.User.all().success(function(_users) { self.Task.all().success(function(_tasks) {
self.Task.all().success(function(_tasks) { self.user = _users[0]
self.user = _users[0] self.task = _tasks[0]
self.task = _tasks[0] done()
done()
})
}) })
}) })
}) })
...@@ -122,8 +120,8 @@ if (dialect.match(/^postgres/)) { ...@@ -122,8 +120,8 @@ if (dialect.match(/^postgres/)) {
this.users = null this.users = null
this.tasks = null this.tasks = null
this.User.hasMany(this.Task, {as:'Tasks'}) this.User.hasMany(this.Task, {as:'Tasks', through: 'usertasks'})
this.Task.hasMany(this.User, {as:'Users'}) this.Task.hasMany(this.User, {as:'Users', through: 'usertasks'})
for (var i = 0; i < 5; ++i) { for (var i = 0; i < 5; ++i) {
users[users.length] = {id: i+1, name: 'User' + Math.random()} users[users.length] = {id: i+1, name: 'User' + Math.random()}
...@@ -133,29 +131,27 @@ if (dialect.match(/^postgres/)) { ...@@ -133,29 +131,27 @@ if (dialect.match(/^postgres/)) {
tasks[tasks.length] = {id: x+1, name: 'Task' + Math.random()} tasks[tasks.length] = {id: x+1, name: 'Task' + Math.random()}
} }
self.User.sync({ force: true }).success(function() { this.sequelize.sync({ force: true }).success(function() {
self.Task.sync({ force: true }).success(function() { self.User.bulkCreate(users).done(function(err) {
self.User.bulkCreate(users).done(function(err) { expect(err).not.to.be.ok
self.Task.bulkCreate(tasks).done(function(err) {
expect(err).not.to.be.ok expect(err).not.to.be.ok
self.Task.bulkCreate(tasks).done(function(err) { self.User.all().success(function(_users) {
expect(err).not.to.be.ok self.Task.all().success(function(_tasks) {
self.User.all().success(function(_users) { self.user = _users[0]
self.Task.all().success(function(_tasks) { self.task = _tasks[0]
self.user = _users[0] self.users = _users
self.task = _tasks[0] self.tasks = _tasks
self.users = _users
self.tasks = _tasks self.user.getTasks().on('success', function(__tasks) {
expect(__tasks).to.have.length(0)
self.user.getTasks().on('success', function(__tasks) { self.user.setTasks(self.tasks).on('success', function() {
expect(__tasks).to.have.length(0) self.user.getTasks().on('success', function(_tasks) {
self.user.setTasks(self.tasks).on('success', function() { expect(_tasks).to.have.length(self.tasks.length)
self.user.getTasks().on('success', function(_tasks) { self.user.removeTask(self.tasks[0]).on('success', function() {
expect(_tasks).to.have.length(self.tasks.length) self.user.getTasks().on('success', function(_tasks) {
self.user.removeTask(self.tasks[0]).on('success', function() { expect(_tasks).to.have.length(self.tasks.length - 1)
self.user.getTasks().on('success', function(_tasks) { done()
expect(_tasks).to.have.length(self.tasks.length - 1)
done()
})
}) })
}) })
}) })
......
var fs = require('fs') var fs = require('fs')
, path = require('path') , path = require('path')
, _ = require('lodash')
, Sequelize = require(__dirname + "/../index") , Sequelize = require(__dirname + "/../index")
, DataTypes = require(__dirname + "/../lib/data-types") , DataTypes = require(__dirname + "/../lib/data-types")
, Config = require(__dirname + "/config/config") , Config = require(__dirname + "/config/config")
...@@ -44,25 +45,14 @@ var Support = { ...@@ -44,25 +45,14 @@ var Support = {
var config = Config[options.dialect] var config = Config[options.dialect]
options.logging = (options.hasOwnProperty('logging') ? options.logging : false) var sequelizeOptions = _.defaults(options, {
options.pool = options.pool !== undefined ? options.pool : config.pool
var sequelizeOptions = {
host: options.host || config.host, host: options.host || config.host,
logging: options.logging, logging: false,
dialect: options.dialect, dialect: options.dialect,
port: options.port || process.env.SEQ_PORT || config.port, port: options.port || process.env.SEQ_PORT || config.port,
pool: options.pool, pool: config.pool,
dialectOptions: options.dialectOptions || {} dialectOptions: options.dialectOptions || {}
} })
if (!!options.define) {
sequelizeOptions.define = options.define
}
if (!!config.storage) {
sequelizeOptions.storage = config.storage
}
if (process.env.DIALECT === 'postgres-native') { if (process.env.DIALECT === 'postgres-native') {
sequelizeOptions.native = true sequelizeOptions.native = true
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!