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

Commit 5913a8fb by Mick Hansen

Merge pull request #1477 from janmeier/contraintWork

Enabled onDelete and onUpdate constraints for n:m
2 parents 259d6b36 e573e740
......@@ -3,6 +3,8 @@ Notice: All 1.7.x changes are present in 2.0.x aswell
# v2.0.0-dev11
- [PERFORMANCE] increased build performance when using include, which speeds up findAll etc.
- [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})`).
#### 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.
......@@ -10,6 +12,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.
- 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
- 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
- [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() {
var newAttributes = {}
newAttributes[this.identifier] = { type: this.options.keyType || this.target.rawAttributes[this.targetIdentifier].type }
if (this.options.constraints !== 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)
Utils._.defaults(this.source.rawAttributes, newAttributes)
......
......@@ -103,7 +103,8 @@ module.exports = (function() {
if (typeof this.through === "string") {
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) {
......@@ -174,24 +175,46 @@ module.exports = (function() {
// define a new model, which connects the models
var combinedTableAttributes = {}
var sourceKeyType = this.source.rawAttributes[this.source.primaryKeyAttribute].type
var targetKeyType = this.target.rawAttributes[this.target.primaryKeyAttribute].type
, sourceKeyType = this.source.rawAttributes[this.source.primaryKeyAttribute].type
, targetKeyType = this.target.rawAttributes[this.target.primaryKeyAttribute].type
, sourceAttribute = { type: sourceKeyType }
, targetAttribute = { type: targetKeyType }
if (this.options.constraints !== 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.constraints !== 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) {
combinedTableAttributes[this.identifier] = {type: sourceKeyType, primaryKey: true}
combinedTableAttributes[this.foreignIdentifier] = {type: targetKeyType, primaryKey: true}
targetAttribute.primaryKey = sourceAttribute.primaryKey = true
} else {
var uniqueKey = [this.through.tableName, this.identifier, this.foreignIdentifier, 'unique'].join('_')
combinedTableAttributes[this.identifier] = {type: sourceKeyType, unique: uniqueKey}
combinedTableAttributes[this.foreignIdentifier] = {type: targetKeyType, unique: uniqueKey}
targetAttribute.unique = sourceAttribute.unique = uniqueKey
}
combinedTableAttributes[this.identifier] = sourceAttribute
combinedTableAttributes[this.foreignIdentifier] = targetAttribute
this.through.rawAttributes = Utils._.merge(this.through.rawAttributes, combinedTableAttributes)
this.through.init(this.through.daoFactoryManager)
} else {
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 }
Helpers.addForeignKeyConstraints(newAttributes[this.identifier], this.source, this.target, this.options)
if (this.options.constraints !== 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)
}
......
......@@ -48,6 +48,11 @@ module.exports = (function() {
newAttributes[this.identifier] = { type: this.options.keyType || keyType }
Utils._.defaults(this.target.rawAttributes, newAttributes)
if (this.options.constraints !== 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)
// Sync attributes and setters/getters to DAO prototype
......
var Toposort = require('toposort-class')
, DaoFactory = require('./dao-factory')
, _ = require('lodash')
module.exports = (function() {
var DAOFactoryManager = function(sequelize) {
......@@ -39,9 +40,14 @@ module.exports = (function() {
* take foreign key constraints into account so that dependencies are visited
* before dependents.
*/
DAOFactoryManager.prototype.forEachDAO = function(iterator) {
DAOFactoryManager.prototype.forEachDAO = function(iterator, options) {
var daos = {}
, sorter = new Toposort()
, sorted
options = _.defaults(options || {}, {
reverse: true
})
this.daos.forEach(function(dao) {
var deps = []
......@@ -62,7 +68,11 @@ module.exports = (function() {
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)
})
}
......
......@@ -19,7 +19,6 @@ module.exports = (function() {
validate: {},
freezeTableName: false,
underscored: false,
syncOnAssociation: true,
paranoid: false,
whereCollection: null,
schema: null,
......@@ -1613,7 +1612,15 @@ module.exports = (function() {
var optClone = function (options) {
return Utils._.cloneDeep(options, function (elem) {
// 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
}
// Unfortunately, lodash.cloneDeep doesn't preserve Buffer.isBuffer, which we have to rely on for binary data
......
......@@ -54,7 +54,15 @@ module.exports = (function() {
if (Utils._.includes(dataType, 'PRIMARY KEY')) {
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')) {
// MySQL doesn't support inline REFERENCES declarations: move to the end
var m = dataType.match(/^(.+) (REFERENCES.*)$/)
......
......@@ -93,17 +93,18 @@ module.exports = (function() {
modifierLastIndex = -1
}
var dataTypeString = dataType
if (Utils._.includes(dataType, 'PRIMARY KEY')) {
if (Utils._.includes(dataType, 'INTEGER')) {
dataType = 'INTEGER PRIMARY KEY' // Only INTEGER is allowed for primary key, see https://github.com/sequelize/sequelize/issues/969 (no lenght, unsigned etc)
dataTypeString = 'INTEGER PRIMARY KEY' // Only INTEGER is allowed for primary key, see https://github.com/sequelize/sequelize/issues/969 (no lenght, unsigned etc)
}
if (needsMultiplePrimaryKeys) {
primaryKeys.push(attr)
dataType = dataType.replace(/PRIMARY KEY/, 'NOT NULL')
dataTypeString = dataType.replace(/PRIMARY KEY/, 'NOT NULL')
}
}
attrStr.push(this.quoteIdentifier(attr) + " " + dataType)
attrStr.push(this.quoteIdentifier(attr) + " " + dataTypeString)
}
}
......
......@@ -80,7 +80,7 @@ module.exports = (function() {
}
var emitter = serial.klass[serial.method].apply(serial.klass, serial.params)
emitter.success(function(result) {
self.serialResults[serialCopy.indexOf(serial)] = result
......
......@@ -532,26 +532,7 @@ module.exports = (function() {
}
}
return new Utils.CustomEventEmitter(function(emitter) {
var chainer = new Utils.QueryChainer()
chainer.add(self, 'queryAndEmit', [[sql, dao, options], 'delete'])
chainer.runSerially()
.success(function(results){
emitter.query = { sql: sql }
emitter.emit('success', results[0])
emitter.emit('sql', sql)
})
.error(function(err) {
emitter.query = { sql: sql }
emitter.emit('error', err)
emitter.emit('sql', sql)
})
.on('sql', function(sql) {
emitter.emit('sql', sql)
})
}).run()
return this.queryAndEmit([sql, dao, options], 'update')
}
QueryInterface.prototype.bulkUpdate = function(tableName, values, identifier, options) {
......
......@@ -387,7 +387,11 @@ module.exports = (function() {
// Topologically sort by foreign key constraints to give us an appropriate
// creation order
this.daoFactoryManager.forEachDAO(function(dao, daoName) {
if (options.force) {
chainer.add(this, 'drop')
}
this.daoFactoryManager.forEachDAO(function(dao) {
if (dao) {
chainer.add(dao, 'sync', [options])
} else {
......@@ -402,12 +406,16 @@ module.exports = (function() {
var self = this
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) {
if (dao) {
chainer.add(dao, 'drop', [])
}
}, { reverse: false})
chainer
.run()
.runSerially()
.success(function() { emitter.emit('success', null) })
.error(function(err) { emitter.emit('error', err) })
}).run()
......
......@@ -85,7 +85,7 @@ describe(Support.getTestDialectTeaser("BelongsTo"), function() {
self.sequelize.dropAllSchemas().done(function() {
self.sequelize.createSchema('archive').done(function () {
self.sequelize.sync({force: true}).done(function () {
self.sequelize.sync({force: true }).done(function () {
User.create({ username: 'foo', gender: 'male' }).success(function(user) {
Task.create({ title: 'task', status: 'inactive' }).success(function(task) {
task.setUserXYZ(user).success(function() {
......@@ -283,19 +283,41 @@ describe(Support.getTestDialectTeaser("BelongsTo"), 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 })
, 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() {
User.create({ username: 'foo' }).success(function(user) {
Task.create({ title: 'task' }).success(function(task) {
task.setUser(user).success(function() {
user.destroy().success(function() {
Task.findAll().success(function(tasks) {
expect(tasks).to.have.length(1)
task.reload().success(function() {
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, { constraints: 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()
})
})
......@@ -447,7 +469,7 @@ describe(Support.getTestDialectTeaser("BelongsTo"), function() {
var tableName = 'TaskXYZ_' + dataType.toString()
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, constraints: false })
})
self.sequelize.sync({ force: true })
......
......@@ -27,17 +27,13 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
describe('(1:N)', function() {
describe('hasSingle', function() {
beforeEach(function(done) {
var self = this
this.Article = this.sequelize.define('Article', { 'title': DataTypes.STRING })
this.Label = this.sequelize.define('Label', { 'text': DataTypes.STRING })
this.Article.hasMany(this.Label)
this.Label.sync({ force: true }).success(function() {
self.Article.sync({ force: true }).success(function() {
done()
})
this.sequelize.sync({ force: true }).success(function() {
done()
})
})
......@@ -74,7 +70,6 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
it('does not have any labels assigned to it initially', function(done) {
var chainer = new Sequelize.Utils.QueryChainer([
this.Article.create({ title: 'Articl2e' }),
this.Article.create({ title: 'Article' }),
this.Label.create({ text: 'Awesomeness' }),
this.Label.create({ text: 'Epicness' })
......@@ -130,10 +125,8 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
this.Article.hasMany(this.Label)
this.Label.sync({ force: true }).success(function() {
self.Article.sync({ force: true }).success(function() {
done()
})
this.sequelize.sync({ force: true }).success(function() {
done()
})
})
......@@ -242,19 +235,17 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
Task.hasMany(User)
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) {
task.setUsers([ user ]).success(function() {
task.getUsers().success(function(_users) {
expect(_users).to.have.length(1)
this.sequelize.sync({ force: true }).success(function() {
User.create({ username: 'foo' }).success(function(user) {
Task.create({ title: 'task' }).success(function(task) {
task.setUsers([ user ]).success(function() {
task.getUsers().success(function(_users) {
expect(_users).to.have.length(1)
task.setUsers(null).success(function() {
task.getUsers().success(function(_users) {
expect(_users).to.have.length(0)
done()
})
task.setUsers(null).success(function() {
task.getUsers().success(function(_users) {
expect(_users).to.have.length(0)
done()
})
})
})
......@@ -307,19 +298,17 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
Task.hasMany(User)
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) {
task.setUsers([ user ]).success(function() {
task.getUsers().success(function(_users) {
expect(_users).to.have.length(1)
this.sequelize.sync({ force: true }).success(function() {
User.create({ username: 'foo' }).success(function(user) {
Task.create({ title: 'task' }).success(function(task) {
task.setUsers([ user ]).success(function() {
task.getUsers().success(function(_users) {
expect(_users).to.have.length(1)
task.setUsers(null).success(function() {
task.getUsers().success(function(_users) {
expect(_users).to.have.length(0)
done()
})
task.setUsers(null).success(function() {
task.getUsers().success(function(_users) {
expect(_users).to.have.length(0)
done()
})
})
})
......@@ -391,18 +380,16 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
this.User.hasMany(self.Task)
this.User.sync({ force: true }).success(function() {
self.Task.sync({ force: true }).success(function() {
var chainer = new Sequelize.Utils.QueryChainer([
self.User.create({ username: 'John'}),
self.Task.create({ title: 'Get rich', active: true}),
self.Task.create({ title: 'Die trying', active: false})
])
chainer.run().success(function (results, john, task1, task2) {
john.setTasks([task1, task2]).success(function() {
done()
})
this.sequelize.sync({ force: true }).success(function() {
var chainer = new Sequelize.Utils.QueryChainer([
self.User.create({ username: 'John'}),
self.Task.create({ title: 'Get rich', active: true}),
self.Task.create({ title: 'Die trying', active: false})
])
chainer.run().success(function (results, john, task1, task2) {
john.setTasks([task1, task2]).success(function() {
done()
})
})
})
......@@ -420,22 +407,20 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
this.Article.hasMany(this.Label)
this.Label.sync({ force: true }).success(function() {
self.Article.sync({ force: true }).success(function() {
var chainer = new Sequelize.Utils.QueryChainer([
self.Article.create({ title: 'Article' }),
self.Label.create({ text: 'Awesomeness', until: '2014-01-01 01:00:00' }),
self.Label.create({ text: 'Epicness', until: '2014-01-03 01:00:00' })
])
chainer.run().success(function(results, article, label1, label2) {
article.setLabels([label1, label2]).success(function() {
article.getLabels({where: ['until > ?', moment('2014-01-02').toDate()]}).success(function(labels) {
expect(labels).to.be.instanceof(Array)
expect(labels).to.have.length(1)
expect(labels[0].text).to.equal('Epicness')
done()
})
self.sequelize.sync({ force: true }).success(function() {
var chainer = new Sequelize.Utils.QueryChainer([
self.Article.create({ title: 'Article' }),
self.Label.create({ text: 'Awesomeness', until: '2014-01-01 01:00:00' }),
self.Label.create({ text: 'Epicness', until: '2014-01-03 01:00:00' })
])
chainer.run().success(function(results, article, label1, label2) {
article.setLabels([label1, label2]).success(function() {
article.getLabels({where: ['until > ?', moment('2014-01-02').toDate()]}).success(function(labels) {
expect(labels).to.be.instanceof(Array)
expect(labels).to.have.length(1)
expect(labels[0].text).to.equal('Epicness')
done()
})
})
})
......@@ -549,10 +534,10 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
this.User = this.sequelize.define('User', { username: DataTypes.STRING })
this.Task = this.sequelize.define('Task', { title: DataTypes.STRING, active: DataTypes.BOOLEAN })
self.User.hasMany(self.Task)
self.Task.hasMany(self.User)
this.User.hasMany(this.Task)
this.Task.hasMany(this.User)
this.sequelize.sync({force: true}).done(function(err) {
this.sequelize.sync({ force: true }).success(function() {
var chainer = new Sequelize.Utils.QueryChainer([
self.User.create({ username: 'John'}),
self.Task.create({ title: 'Get rich', active: true}),
......@@ -702,19 +687,17 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
User.hasMany(Task)
Task.hasMany(User)
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) {
task.setUsers([ user ]).success(function() {
task.getUsers().success(function(_users) {
expect(_users).to.have.length(1)
this.sequelize.sync({ force: true }).success(function() {
User.create({ username: 'foo' }).success(function(user) {
Task.create({ title: 'task' }).success(function(task) {
task.setUsers([ user ]).success(function() {
task.getUsers().success(function(_users) {
expect(_users).to.have.length(1)
task.setUsers(null).success(function() {
task.getUsers().success(function(_users) {
expect(_users).to.have.length(0)
done()
})
task.setUsers(null).success(function() {
task.getUsers().success(function(_users) {
expect(_users).to.have.length(0)
done()
})
})
})
......@@ -737,20 +720,18 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
Group.hasMany(Member, {joinTableName: 'group_members', foreignKey: 'group_id'})
Member.hasMany(Group, {joinTableName: 'group_members', foreignKey: 'member_id'})
Group.sync({ force: true }).success(function() {
Member.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).to.be.instanceof(Array)
expect(members).to.have.length(1)
expect(members[0].member_id).to.equal(10)
expect(members[0].email).to.equal('team@sequelizejs.com')
done()
})
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).to.be.instanceof(Array)
expect(members).to.have.length(1)
expect(members[0].member_id).to.equal(10)
expect(members[0].email).to.equal('team@sequelizejs.com')
done()
})
})
})
......@@ -769,15 +750,13 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
User.hasMany(Task)
Task.hasMany(User)
User.sync({ force: true }).success(function() {
Task.sync({ force: true }).success(function() {
Task.create({ title: 'task' }).success(function(task) {
task.createUser({ username: 'foo' }).success(function() {
task.getUsers().success(function(_users) {
expect(_users).to.have.length(1)
this.sequelize.sync({ force: true }).success(function() {
Task.create({ title: 'task' }).success(function(task) {
task.createUser({ username: 'foo' }).success(function() {
task.getUsers().success(function(_users) {
expect(_users).to.have.length(1)
done()
})
done()
})
})
})
......@@ -793,18 +772,16 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
User.hasMany(Task)
Task.hasMany(User)
User.sync({ force: true }).success(function() {
Task.sync({ force: true }).success(function() {
Task.create({ title: 'task' }).success(function(task) {
sequelize.transaction(function (t) {
task.createUser({ username: 'foo' }, { transaction: t }).success(function() {
task.getUsers().success(function(users) {
expect(users).to.have.length(0)
task.getUsers({ transaction: t }).success(function(users) {
expect(users).to.have.length(1)
t.rollback().success(function() { done() })
})
sequelize.sync({ force: true }).success(function() {
Task.create({ title: 'task' }).success(function(task) {
sequelize.transaction(function (t) {
task.createUser({ username: 'foo' }, { transaction: t }).success(function() {
task.getUsers().success(function(users) {
expect(users).to.have.length(0)
task.getUsers({ transaction: t }).success(function(users) {
expect(users).to.have.length(1)
t.rollback().success(function() { done() })
})
})
})
......@@ -854,10 +831,8 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
this.User.hasMany(this.Task)
this.Task.hasMany(this.User)
this.User.sync({ force: true }).success(function() {
self.Task.sync({force: true}).success(function() {
done()
})
this.sequelize.sync({force: true}).success(function() {
done()
})
})
......@@ -924,7 +899,7 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
})
})
it('uses the specified joinTableName or a reasonable default', function(done) {
it('uses the specified joinTableName or a reasonable default', function() {
for (var associationName in this.User.associations) {
expect(associationName).not.to.equal(this.User.tableName)
expect(associationName).not.to.equal(this.Task.tableName)
......@@ -938,9 +913,26 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
expect(tableName).to.equal(associationName)
}
}
setTimeout(function () {
done()
}, 50)
})
it('makes join table non-paranoid by default', function () {
var paranoidSequelize = new Sequelize('','','', {
define: {
paranoid: true
}
})
, ParanoidUser = paranoidSequelize.define('ParanoidUser', {})
, ParanoidTask = paranoidSequelize.define('ParanoidTask', {})
ParanoidUser.hasMany(ParanoidTask)
ParanoidTask.hasMany(ParanoidUser)
expect(ParanoidUser.options.paranoid).to.be.ok
expect(ParanoidTask.options.paranoid).to.be.ok
_.forEach(ParanoidUser.associations, function (association) {
expect(association.through.options.paranoid).not.to.be.ok
})
})
})
......@@ -1404,20 +1396,20 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
})
describe("Foreign key constraints", function() {
it("are not enabled by default", function(done) {
var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
, User = this.sequelize.define('User', { username: DataTypes.STRING })
describe('1:m', function () {
it("sets null by default", function(done) {
var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
, User = this.sequelize.define('User', { username: DataTypes.STRING })
User.hasMany(Task)
User.hasMany(Task)
User.sync({ force: true }).success(function() {
Task.sync({ force: true }).success(function() {
this.sequelize.sync({ force: true }).success(function() {
User.create({ username: 'foo' }).success(function(user) {
Task.create({ title: 'task' }).success(function(task) {
user.setTasks([task]).success(function() {
user.destroy().success(function() {
Task.findAll().success(function(tasks) {
expect(tasks).to.have.length(1)
task.reload().success(function() {
expect(task.UserId).to.equal(null)
done()
})
})
......@@ -1426,22 +1418,20 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
})
})
})
})
it("can cascade deletes", function(done) {
var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
, User = this.sequelize.define('User', { username: DataTypes.STRING })
it("should be possible to remove all constraints", function(done) {
var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
, User = this.sequelize.define('User', { username: DataTypes.STRING })
User.hasMany(Task, {onDelete: 'cascade'})
User.hasMany(Task, { constraints: false })
User.sync({ force: true }).success(function() {
Task.sync({ force: true }).success(function() {
this.sequelize.sync({ force: true }).success(function() {
User.create({ username: 'foo' }).success(function(user) {
Task.create({ title: 'task' }).success(function(task) {
user.setTasks([task]).success(function() {
user.destroy().success(function() {
Task.findAll().success(function(tasks) {
expect(tasks).to.have.length(0)
task.reload().success(function() {
expect(task.UserId).to.equal(user.id)
done()
})
})
......@@ -1450,24 +1440,156 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
})
})
})
it("can cascade deletes", function(done) {
var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
, User = this.sequelize.define('User', { username: DataTypes.STRING })
User.hasMany(Task, {onDelete: 'cascade'})
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.setTasks([task]).success(function() {
user.destroy().success(function() {
Task.findAll().success(function(tasks) {
expect(tasks).to.have.length(0)
done()
})
})
})
})
})
})
})
})
it("can restrict deletes", function(done) {
var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
, User = this.sequelize.define('User', { username: DataTypes.STRING })
User.hasMany(Task, {onDelete: 'restrict'})
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.setTasks([task]).success(function() {
user.destroy().error(function() {
// Should fail due to FK restriction
Task.findAll().success(function(tasks) {
expect(tasks).to.have.length(1)
done()
})
})
})
})
})
})
})
})
it("can cascade updates", function(done) {
var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
, User = this.sequelize.define('User', { username: DataTypes.STRING })
User.hasMany(Task, {onUpdate: 'cascade'})
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.setTasks([task]).success(function() {
// Changing the id of a DAO requires a little dance since
// the `UPDATE` query generated by `save()` uses `id` in the
// `WHERE` clause
var tableName = user.QueryInterface.QueryGenerator.addSchema(user.Model)
user.QueryInterface.update(user, tableName, {id: 999}, user.id)
.success(function() {
Task.findAll().success(function(tasks) {
expect(tasks).to.have.length(1)
expect(tasks[0].UserId).to.equal(999)
done()
})
})
})
})
})
})
})
})
it("can restrict updates", function(done) {
var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
, User = this.sequelize.define('User', { username: DataTypes.STRING })
User.hasMany(Task, {onUpdate: 'restrict'})
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.setTasks([task]).success(function() {
// Changing the id of a DAO requires a little dance since
// the `UPDATE` query generated by `save()` uses `id` in the
// `WHERE` clause
var tableName = user.QueryInterface.QueryGenerator.addSchema(user.Model)
user.QueryInterface.update(user, tableName, {id: 999}, user.id)
.error(function() {
// Should fail due to FK restriction
Task.findAll().success(function(tasks) {
expect(tasks).to.have.length(1)
done()
})
})
})
})
})
})
})
})
})
it("can restrict deletes", function(done) {
var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
, User = this.sequelize.define('User', { username: DataTypes.STRING })
describe('n:m', function () {
beforeEach(function () {
this.Task = this.sequelize.define('task', { title: DataTypes.STRING })
this.User = this.sequelize.define('user', { username: DataTypes.STRING })
this.UserTasks = this.sequelize.define('tasksusers', { userId: DataTypes.INTEGER, taskId: DataTypes.INTEGER })
})
it("can cascade deletes both ways by default", function (done) {
var _done = _.after(2, done)
, self = this
User.hasMany(Task, {onDelete: 'restrict'})
self.User.hasMany(self.Task)
self.Task.hasMany(self.User)
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) {
this.sequelize.sync({ force: true }).success(function() {
self.User.create({ id: 67, username: 'foo' }).success(function(user) {
self.Task.create({ id: 52, title: 'task' }).success(function(task) {
user.setTasks([task]).success(function() {
user.destroy().error(function() {
// Should fail due to FK restriction
Task.findAll().success(function(tasks) {
expect(tasks).to.have.length(1)
done()
user.destroy().success(function() {
self.UserTasks.findAll({ where: { userId: user.id }}).success(function(usertasks) {
expect(usertasks).to.have.length(0)
_done()
})
})
})
})
})
self.User.create({ id: 89, username: 'bar' }).success(function(user) {
self.Task.create({ id: 42, title: 'kast' }).success(function(task) {
task.setUsers([user]).success(function() {
task.destroy().success(function() {
self.UserTasks.findAll({ where: { taskId: task.id }}).success(function(usertasks) {
expect(usertasks).to.have.length(0)
_done()
})
})
})
......@@ -1475,31 +1597,66 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
})
})
})
})
it("can cascade updates", function(done) {
var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
, User = this.sequelize.define('User', { username: DataTypes.STRING })
it("can restrict deletes both ways", function (done) {
var _done = _.after(2, done)
, self = this
User.hasMany(Task, {onUpdate: 'cascade'})
self.User.hasMany(self.Task, { onDelete: 'RESTRICT'})
self.Task.hasMany(self.User, { onDelete: 'RESTRICT'})
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) {
this.sequelize.sync({ force: true }).success(function() {
self.User.create({ id: 67, username: 'foo' }).success(function(user) {
self.Task.create({ id: 52, title: 'task' }).success(function(task) {
user.setTasks([task]).success(function() {
user.destroy().error(function() {
// This should error, because updates are restricted
_done()
})
})
})
})
self.User.create({ id: 89, username: 'bar' }).success(function(user) {
self.Task.create({ id: 42, title: 'kast' }).success(function(task) {
task.setUsers([user]).success(function() {
task.destroy().error(function () {
// This should error, because updates are restricted
_done()
})
})
})
})
})
})
// Changing the id of a DAO requires a little dance since
// the `UPDATE` query generated by `save()` uses `id` in the
// `WHERE` clause
it("can cascade and restrict deletes", function (done) {
var _done = _.after(2, done)
, self = this
var tableName = user.QueryInterface.QueryGenerator.addSchema(user.Model)
user.QueryInterface.update(user, tableName, {id: 999}, user.id)
.success(function() {
Task.findAll().success(function(tasks) {
expect(tasks).to.have.length(1)
expect(tasks[0].UserId).to.equal(999)
done()
self.User.hasMany(self.Task, { onDelete: 'RESTRICT'})
self.Task.hasMany(self.User) // Implicit CASCADE
this.sequelize.sync({ force: true }).success(function() {
self.User.create({ id: 67, username: 'foo' }).success(function(user) {
self.Task.create({ id: 52, title: 'task' }).success(function(task) {
user.setTasks([task]).success(function() {
user.destroy().error(function() {
// This should error, because deletes are restricted
_done()
})
})
})
})
self.User.create({ id: 89, username: 'bar' }).success(function(user) {
self.Task.create({ id: 42, title: 'kast' }).success(function(task) {
task.setUsers([user]).success(function() {
task.destroy().success(function () {
self.UserTasks.findAll({ where: { taskId: task.id }}).success(function(usertasks) {
// This should not exist because deletes cascade
expect(usertasks).to.have.length(0)
_done()
})
})
})
......@@ -1507,31 +1664,37 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
})
})
})
})
it("can restrict updates", function(done) {
var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
, User = this.sequelize.define('User', { username: DataTypes.STRING })
it("should be possible to remove all constraints", function (done) {
var _done = _.after(2, done)
, self = this
User.hasMany(Task, {onUpdate: 'restrict'})
self.User.hasMany(self.Task, { constraints: false })
self.Task.hasMany(self.User, { constraints: 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) {
this.sequelize.sync({ force: true }).success(function() {
self.User.create({ id: 67, username: 'foo' }).success(function(user) {
self.Task.create({ id: 52, title: 'task' }).success(function(task) {
user.setTasks([task]).success(function() {
user.destroy().success(function () {
self.UserTasks.findAll({ where: { userId: user.id }}).success(function(usertasks) {
// When we're not using foreign keys, join table rows will be orphaned
expect(usertasks).to.have.length(1)
_done()
})
})
})
})
})
// Changing the id of a DAO requires a little dance since
// the `UPDATE` query generated by `save()` uses `id` in the
// `WHERE` clause
var tableName = user.QueryInterface.QueryGenerator.addSchema(user.Model)
user.QueryInterface.update(user, tableName, {id: 999}, user.id)
.error(function() {
// Should fail due to FK restriction
Task.findAll().success(function(tasks) {
expect(tasks).to.have.length(1)
done()
self.User.create({ id: 89, username: 'bar' }).success(function(user) {
self.Task.create({ id: 42, title: 'kast' }).success(function(task) {
task.setUsers([user]).success(function() {
task.destroy().success(function () {
self.UserTasks.findAll({ where: { taskId: task.id }}).success(function(usertasks) {
// When we're not using foreign keys, join table rows will be orphaned
expect(usertasks).to.have.length(1)
_done()
})
})
})
......@@ -1553,7 +1716,7 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
var tableName = 'TaskXYZ_' + dataType.toString()
Tasks[dataType] = self.sequelize.define(tableName, { title: DataTypes.STRING })
User.hasMany(Tasks[dataType], { foreignKey: 'userId', keyType: dataType })
User.hasMany(Tasks[dataType], { foreignKey: 'userId', keyType: dataType, constraints: false })
Tasks[dataType].sync({ force: true }).success(function() {
expect(Tasks[dataType].rawAttributes.userId.type.toString())
......
......@@ -211,7 +211,7 @@ describe(Support.getTestDialectTeaser("HasOne"), function() {
})
})
describe("foreign key", function () {
describe('foreign key', function () {
it('should lowercase foreign keys when using underscored', function () {
var User = this.sequelize.define('User', { username: Sequelize.STRING }, { underscored: true })
, Account = this.sequelize.define('Account', { name: Sequelize.STRING }, { underscored: true })
......@@ -231,11 +231,11 @@ describe(Support.getTestDialectTeaser("HasOne"), 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: 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() {
Task.sync({ force: true }).success(function() {
......@@ -243,8 +243,32 @@ describe(Support.getTestDialectTeaser("HasOne"), function() {
Task.create({ title: 'task' }).success(function(task) {
user.setTask(task).success(function() {
user.destroy().success(function() {
Task.findAll().success(function(tasks) {
expect(tasks).to.have.length(1)
task.reload().success(function() {
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, { constraints: 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()
})
})
......@@ -406,7 +430,7 @@ describe(Support.getTestDialectTeaser("HasOne"), function() {
var tableName = 'TaskXYZ_' + dataType.toString()
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, constraints: false })
Tasks[dataType].sync({ force: true }).success(function() {
expect(Tasks[dataType].rawAttributes.userId.type.toString())
......
......@@ -279,11 +279,11 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
bCol: { type: Sequelize.STRING, unique: 'a_and_b' }
})
User.sync({ force: true }).on('sql', function(sql) {
User.sync({ force: true }).on('sql', _.after(2, function(sql) {
expect(sql).to.match(/UNIQUE\s*(uniq_UserWithUniqueUsernames_username_email)?\s*\([`"]?username[`"]?, [`"]?email[`"]?\)/)
expect(sql).to.match(/UNIQUE\s*(uniq_UserWithUniqueUsernames_aCol_bCol)?\s*\([`"]?aCol[`"]?, [`"]?bCol[`"]?\)/)
done()
})
}))
})
it('allows us to customize the error message for unique constraint', function(done) {
......@@ -1447,7 +1447,6 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
it('should be able to reference a table with a schema set', function(done) {
var self = this
var sequelize = this.sequelize
var UserPub = this.sequelize.define('UserPub', {
username: Sequelize.STRING
......@@ -1463,14 +1462,14 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
var run = function() {
UserPub.sync({ force: true }).success(function() {
ItemPub.sync({ force: true }).on('sql', function(sql) {
ItemPub.sync({ force: true }).on('sql', _.after(2, function(sql) {
if (dialect === "postgres") {
expect(sql).to.match(/REFERENCES\s+"prefix"\."UserPubs" \("id"\)/)
} else {
expect(sql).to.match(/REFERENCES\s+`prefix\.UserPubs` \(`id`\)/)
}
done()
})
}))
})
}
......@@ -1969,10 +1968,10 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
str: { type: Sequelize.STRING, unique: true }
})
uniqueTrue.sync({force: true}).on('sql', function(s) {
uniqueTrue.sync({force: true}).on('sql', _.after(2, function(s) {
expect(s).to.match(/UNIQUE/)
done()
})
}))
})
it("should not set unique when unique is false", function(done) {
......@@ -1981,10 +1980,10 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
str: { type: Sequelize.STRING, unique: false }
})
uniqueFalse.sync({force: true}).on('sql', function(s) {
uniqueFalse.sync({force: true}).on('sql', _.after(2, function(s) {
expect(s).not.to.match(/UNIQUE/)
done()
})
}))
})
it("should not set unique when unique is unset", function(done) {
......@@ -1993,10 +1992,10 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
str: { type: Sequelize.STRING }
})
uniqueUnset.sync({force: true}).on('sql', function(s) {
uniqueUnset.sync({force: true}).on('sql', _.after(2, function(s) {
expect(s).not.to.match(/UNIQUE/)
done()
})
}))
})
})
......
......@@ -277,14 +277,12 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
self.Worker = self.sequelize.define('Worker', { name: Sequelize.STRING })
this.init = function(callback) {
self.Task.sync({ force: true }).success(function() {
self.Worker.sync({ force: true }).success(function() {
self.Worker.create({ name: 'worker' }).success(function(worker) {
self.Task.create({ title: 'homework' }).success(function(task) {
self.worker = worker
self.task = task
callback()
})
self.sequelize.sync({ force: true }).success(function() {
self.Worker.create({ name: 'worker' }).success(function(worker) {
self.Task.create({ title: 'homework' }).success(function(task) {
self.worker = worker
self.task = task
callback()
})
})
})
......@@ -386,35 +384,32 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
self.User.belongsTo(self.Group)
self.sequelize.sync({ force: true }).success(function() {
self.User.create({ username: 'someone', GroupPKeagerbelongName: 'people' }).success(function() {
self.Group.create({ name: 'people' }).success(function() {
self.Group.create({ name: 'people' }).success(function() {
self.User.create({ username: 'someone', GroupPKeagerbelongName: 'people' }).success(function() {
self.User.find({
where: {
where: {
username: 'someone'
},
include: [self.Group]
}).complete(function (err, someUser) {
expect(err).to.be.null
expect(someUser).to.exist
expect(someUser.username).to.equal('someone')
expect(someUser.groupPKeagerbelong.name).to.equal('people')
done()
})
include: [self.Group]
}).complete(function (err, someUser) {
expect(err).to.be.null
expect(someUser).to.exist
expect(someUser.username).to.equal('someone')
expect(someUser.groupPKeagerbelong.name).to.equal('people')
done()
})
})
})
})
})
it('getting parent data in many to one relationship', function(done) {
var self = this;
var User = self.sequelize.define('User', {
var User = this.sequelize.define('User', {
id: {type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true},
username: {type: Sequelize.STRING}
})
var Message = self.sequelize.define('Message', {
var Message = this.sequelize.define('Message', {
id: {type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true},
user_id: {type: Sequelize.INTEGER},
message: {type: Sequelize.STRING}
......@@ -423,41 +418,35 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
User.hasMany(Message)
Message.belongsTo(User, { foreignKey: 'user_id' })
Message.sync({ force: true }).success(function() {
User.sync({ force: true }).success(function() {
User.create({username: 'test_testerson'}).success(function(user) {
Message.create({user_id: user.id, message: 'hi there!'}).success(function(message) {
Message.create({user_id: user.id, message: 'a second message'}).success(function(message) {
Message.findAll({
where: {user_id: user.id},
attributes: [
'user_id',
'message'
],
include: [{ model: User, attributes: ['username'] }]
this.sequelize.sync({ force: true }).success(function() {
User.create({username: 'test_testerson'}).success(function(user) {
Message.create({user_id: user.id, message: 'hi there!'}).success(function(message) {
Message.create({user_id: user.id, message: 'a second message'}).success(function(message) {
Message.findAll({
}).success(function(messages) {
where: {user_id: user.id},
attributes: [
'user_id',
'message'
],
include: [{ model: User, attributes: ['username'] }]
expect(messages.length).to.equal(2);
}).success(function(messages) {
expect(messages.length).to.equal(2);
expect(messages[0].message).to.equal('hi there!');
expect(messages[0].user.username).to.equal('test_testerson');
expect(messages[0].message).to.equal('hi there!');
expect(messages[0].user.username).to.equal('test_testerson');
expect(messages[1].message).to.equal('a second message');
expect(messages[1].user.username).to.equal('test_testerson');
expect(messages[1].message).to.equal('a second message');
expect(messages[1].user.username).to.equal('test_testerson');
done()
})
done()
})
})
})
})
})
})
it('allows mulitple assocations of the same model with different alias', function (done) {
......@@ -528,20 +517,20 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
self.Group.hasOne(self.User)
self.sequelize.sync({ force: true }).success(function() {
self.User.create({ username: 'someone', GroupPKeageroneName: 'people' }).success(function() {
self.Group.create({ name: 'people' }).success(function() {
self.Group.create({ name: 'people' }).success(function() {
self.User.create({ username: 'someone', GroupPKeageroneName: 'people' }).success(function() {
self.Group.find({
where: {
where: {
name: 'people'
},
include: [self.User]
}).complete(function (err, someGroup) {
expect(err).to.be.null
expect(someGroup).to.exist
expect(someGroup.name).to.equal('people')
expect(someGroup.userPKeagerone.username).to.equal('someone')
done()
})
include: [self.User]
}).complete(function (err, someGroup) {
expect(err).to.be.null
expect(someGroup).to.exist
expect(someGroup.name).to.equal('people')
expect(someGroup.userPKeagerone.username).to.equal('someone')
done()
})
})
})
})
......
......@@ -313,18 +313,16 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
User.hasMany(Session, { as: 'Sessions' })
Session.belongsTo(User)
Session.sync({ force: true }).success(function() {
User.sync({ force: true }).success(function() {
User.create({name: 'Name1', password: '123', isAdmin: false}).success(function(user) {
var sess = Session.build({
lastUpdate: new Date(),
token: '123'
})
this.sequelize.sync({ force: true }).success(function() {
User.create({name: 'Name1', password: '123', isAdmin: false}).success(function(user) {
var sess = Session.build({
lastUpdate: new Date(),
token: '123'
})
user.addSession(sess).success(function(u) {
expect(u.token).to.equal('123')
done()
})
user.addSession(sess).success(function(u) {
expect(u.token).to.equal('123')
done()
})
})
})
......@@ -849,9 +847,7 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
self.Country.hasMany(self.Person, { as: 'Residents', foreignKey: 'CountryResidentId' })
self.Person.belongsTo(self.Country, { as: 'CountryResident', foreignKey: 'CountryResidentId' })
async.forEach([ self.Continent, self.Country, self.Industry, self.Person ], function(model, callback) {
model.sync({ force: true }).done(callback)
}, function () {
this.sequelize.sync({ force: true }).success(function () {
async.parallel({
europe: function(callback) {self.Continent.create({ name: 'Europe' }).done(callback)},
england: function(callback) {self.Country.create({ name: 'England' }).done(callback)},
......@@ -874,7 +870,7 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
done()
})
})
})
})
})
it('includes all associations', function(done) {
......@@ -965,9 +961,7 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
self.Country.hasMany(self.Person, { as: 'Residents', foreignKey: 'CountryResidentId' })
self.Person.belongsTo(self.Country, { as: 'CountryResident', foreignKey: 'CountryResidentId' })
async.forEach([ self.Continent, self.Country, self.Person ], function(model, callback) {
model.sync({ force: true }).done(callback)
}, function () {
this.sequelize.sync({ force: true }).success(function () {
async.parallel({
europe: function(callback) {self.Continent.create({ name: 'Europe' }).done(callback)},
asia: function(callback) {self.Continent.create({ name: 'Asia' }).done(callback)},
......@@ -1120,9 +1114,7 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
self.Country.hasMany(self.Industry, {through: self.IndustryCountry})
self.Industry.hasMany(self.Country, {through: self.IndustryCountry})
async.forEach([ self.Country, self.Industry ], function(model, callback) {
model.sync({ force: true }).done(callback)
}, function () {
this.sequelize.sync({ force: true }).success(function () {
async.parallel({
england: function(callback) {self.Country.create({ name: 'England' }).done(callback)},
france: function(callback) {self.Country.create({ name: 'France' }).done(callback)},
......
......@@ -353,14 +353,12 @@ describe(Support.getTestDialectTeaser("DaoValidator"), function() {
})
Project.hasOne(Task)
Task.hasOne(Project)
Task.belongsTo(Project)
Project.sync({ force: true }).success(function() {
Task.sync({ force: true }).success(function() {
self.Project = Project
self.Task = Task
done()
})
this.sequelize.sync({ force: true }).success(function() {
self.Project = Project
self.Task = Task
done()
})
})
......
......@@ -6334,10 +6334,8 @@ describe(Support.getTestDialectTeaser("Hooks"), function () {
this.Projects.hasOne(this.Tasks, {onDelete: 'cascade', hooks: true})
this.Tasks.belongsTo(this.Projects)
this.Projects.sync({ force: true }).success(function() {
self.Tasks.sync({ force: true }).success(function() {
done()
})
this.sequelize.sync({ force: true }).success(function() {
done()
})
})
......@@ -6733,10 +6731,8 @@ describe(Support.getTestDialectTeaser("Hooks"), function () {
this.Projects.hasMany(this.Tasks)
this.Tasks.belongsTo(this.Projects)
this.Projects.sync({ force: true }).success(function() {
self.Tasks.sync({ force: true }).success(function() {
done()
})
this.sequelize.sync({ force: true }).success(function() {
done()
})
})
......@@ -6842,10 +6838,8 @@ describe(Support.getTestDialectTeaser("Hooks"), function () {
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.Projects.sync({ force: true }).success(function() {
self.Tasks.sync({ force: true }).success(function() {
done()
})
this.sequelize.sync({ force: true }).success(function() {
done()
})
})
......@@ -6952,10 +6946,8 @@ describe(Support.getTestDialectTeaser("Hooks"), function () {
this.Projects.hasMany(this.Tasks, {hooks: true})
this.Tasks.hasMany(this.Projects, {hooks: true})
this.Projects.sync({ force: true }).success(function() {
self.Tasks.sync({ force: true }).success(function() {
done()
})
this.sequelize.sync({ force: true }).success(function() {
done()
})
})
......
......@@ -57,8 +57,8 @@ if (Support.dialectIsMySQL()) {
this.users = null
this.tasks = null
this.User.hasMany(this.Task, {as:'Tasks'})
this.Task.hasMany(this.User, {as:'Users'})
this.User.hasMany(this.Task, {as:'Tasks', through: 'UserTasks'})
this.Task.hasMany(this.User, {as:'Users', through: 'UserTasks'})
var self = this
, users = []
......@@ -72,12 +72,10 @@ if (Support.dialectIsMySQL()) {
tasks[tasks.length] = {name: 'Task' + Math.random()}
}
this.User.sync({ force: true }).success(function() {
self.Task.sync({ force: true }).success(function() {
self.User.bulkCreate(users).success(function() {
self.Task.bulkCreate(tasks).success(function() {
done()
})
this.sequelize.sync({ force: true }).success(function() {
self.User.bulkCreate(users).success(function() {
self.Task.bulkCreate(tasks).success(function() {
done()
})
})
})
......
......@@ -63,8 +63,8 @@ if (dialect.match(/^postgres/)) {
this.users = null
this.tasks = null
this.User.hasMany(this.Task, {as:'Tasks'})
this.Task.hasMany(this.User, {as:'Users'})
this.User.hasMany(this.Task, {as:'Tasks', through: 'usertasks'})
this.Task.hasMany(this.User, {as:'Users', through: 'usertasks'})
var self = this
, users = []
......@@ -78,16 +78,14 @@ if (dialect.match(/^postgres/)) {
tasks[tasks.length] = {name: 'Task' + Math.random()}
}
self.User.sync({ force: true }).success(function() {
self.Task.sync({ force: true }).success(function() {
self.User.bulkCreate(users).success(function() {
self.Task.bulkCreate(tasks).success(function() {
self.User.all().success(function(_users) {
self.Task.all().success(function(_tasks) {
self.user = _users[0]
self.task = _tasks[0]
done()
})
this.sequelize.sync({ force: true }).success(function() {
self.User.bulkCreate(users).success(function() {
self.Task.bulkCreate(tasks).success(function() {
self.User.all().success(function(_users) {
self.Task.all().success(function(_tasks) {
self.user = _users[0]
self.task = _tasks[0]
done()
})
})
})
......@@ -122,8 +120,8 @@ if (dialect.match(/^postgres/)) {
this.users = null
this.tasks = null
this.User.hasMany(this.Task, {as:'Tasks'})
this.Task.hasMany(this.User, {as:'Users'})
this.User.hasMany(this.Task, {as:'Tasks', through: 'usertasks'})
this.Task.hasMany(this.User, {as:'Users', through: 'usertasks'})
for (var i = 0; i < 5; ++i) {
users[users.length] = {id: i+1, name: 'User' + Math.random()}
......@@ -133,29 +131,27 @@ if (dialect.match(/^postgres/)) {
tasks[tasks.length] = {id: x+1, name: 'Task' + Math.random()}
}
self.User.sync({ force: true }).success(function() {
self.Task.sync({ force: true }).success(function() {
self.User.bulkCreate(users).done(function(err) {
this.sequelize.sync({ force: true }).success(function() {
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
self.Task.bulkCreate(tasks).done(function(err) {
expect(err).not.to.be.ok
self.User.all().success(function(_users) {
self.Task.all().success(function(_tasks) {
self.user = _users[0]
self.task = _tasks[0]
self.users = _users
self.tasks = _tasks
self.user.getTasks().on('success', function(__tasks) {
expect(__tasks).to.have.length(0)
self.user.setTasks(self.tasks).on('success', function() {
self.user.getTasks().on('success', function(_tasks) {
expect(_tasks).to.have.length(self.tasks.length)
self.user.removeTask(self.tasks[0]).on('success', function() {
self.user.getTasks().on('success', function(_tasks) {
expect(_tasks).to.have.length(self.tasks.length - 1)
done()
})
self.User.all().success(function(_users) {
self.Task.all().success(function(_tasks) {
self.user = _users[0]
self.task = _tasks[0]
self.users = _users
self.tasks = _tasks
self.user.getTasks().on('success', function(__tasks) {
expect(__tasks).to.have.length(0)
self.user.setTasks(self.tasks).on('success', function() {
self.user.getTasks().on('success', function(_tasks) {
expect(_tasks).to.have.length(self.tasks.length)
self.user.removeTask(self.tasks[0]).on('success', function() {
self.user.getTasks().on('success', function(_tasks) {
expect(_tasks).to.have.length(self.tasks.length - 1)
done()
})
})
})
......
......@@ -7,84 +7,87 @@ var chai = require('chai')
, exec = require('child_process').exec
, version = (require(__dirname + '/../package.json')).version
, path = require('path')
, os = require('os')
chai.Assertion.includeStack = true
describe(Support.getTestDialectTeaser("Executable"), function() {
describe('call without arguments', function() {
it("prints usage instructions", function(done) {
exec('bin/sequelize', function(err, stdout, stderr) {
expect(stdout).to.include("No action specified. Try \"sequelize --help\" for usage information.")
done()
if (os.type().toLowerCase().indexOf('windows') === -1) {
describe(Support.getTestDialectTeaser("Executable"), function() {
describe('call without arguments', function() {
it("prints usage instructions", function(done) {
exec('bin/sequelize', function(err, stdout, stderr) {
expect(stdout).to.include("No action specified. Try \"sequelize --help\" for usage information.")
done()
})
})
})
})
;(function(flags) {
flags.forEach(function(flag) {
describe(flag, function() {
it("prints the help", function(done) {
exec("bin/sequelize " + flag, function(err, stdout, stderr) {
expect(stdout).to.include("Usage: sequelize [options]")
done()
;(function(flags) {
flags.forEach(function(flag) {
describe(flag, function() {
it("prints the help", function(done) {
exec("bin/sequelize " + flag, function(err, stdout, stderr) {
expect(stdout).to.include("Usage: sequelize [options]")
done()
})
})
})
})
})
})(["--help", "-h"])
;(function(flags) {
flags.forEach(function(flag) {
describe(flag, function() {
it("prints the help", function(done) {
exec("bin/sequelize " + flag, function(err, stdout, stderr) {
expect(version).to.not.be.empty
expect(stdout).to.include(version)
done()
})(["--help", "-h"])
;(function(flags) {
flags.forEach(function(flag) {
describe(flag, function() {
it("prints the help", function(done) {
exec("bin/sequelize " + flag, function(err, stdout, stderr) {
expect(version).to.not.be.empty
expect(stdout).to.include(version)
done()
})
})
})
})
})
})(['--version', '-V'])
;(function(flags) {
flags.forEach(function(flag) {
describe(flag, function() {
;(function(folders) {
folders.forEach(function(folder) {
it("creates a '" + folder + "' folder", function(done) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function() {
exec("ls -ila", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.include(folder)
done()
})(['--version', '-V'])
;(function(flags) {
flags.forEach(function(flag) {
describe(flag, function() {
;(function(folders) {
folders.forEach(function(folder) {
it("creates a '" + folder + "' folder", function(done) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function() {
exec("ls -ila", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.include(folder)
done()
})
})
})
})
})
})
})(['config', 'migrations'])
})(['config', 'migrations'])
it("creates a config.json file", function(done) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function() {
exec("ls -ila config", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.include('config.json')
done()
it("creates a config.json file", function(done) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function() {
exec("ls -ila config", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.include('config.json')
done()
})
})
})
})
})
it("does not overwrite an existing config.json file", function(done) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function() {
exec("echo 'foo' > config/config.json", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function(err) {
expect(err.code).to.equal(1)
exec("cat config/config.json", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.equal("foo\n")
done()
it("does not overwrite an existing config.json file", function(done) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function() {
exec("echo 'foo' > config/config.json", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function(err) {
expect(err.code).to.equal(1)
exec("cat config/config.json", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.equal("foo\n")
done()
})
})
})
})
......@@ -92,345 +95,346 @@ describe(Support.getTestDialectTeaser("Executable"), function() {
})
})
})
})
})(['--init', '-i'])
;(function(flags) {
flags.forEach(function(flag) {
var prepare = function(callback) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize " + flag + " 'foo'", { cwd: __dirname + '/tmp' }, callback)
})(['--init', '-i'])
;(function(flags) {
flags.forEach(function(flag) {
var prepare = function(callback) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize " + flag + " 'foo'", { cwd: __dirname + '/tmp' }, callback)
})
})
})
}
}
describe(flag, function() {
it("creates a new file with the current timestamp", function(done) {
prepare(function() {
exec("ls -1 migrations", { cwd: __dirname + '/tmp' }, function(err, stdout) {
var date = new Date()
, format = function(i) { return (parseInt(i, 10) < 10 ? '0' + i : i) }
, sDate = [date.getFullYear(), format(date.getMonth() + 1), format(date.getDate()), format(date.getHours()), format(date.getMinutes())].join('')
describe(flag, function() {
it("creates a new file with the current timestamp", function(done) {
prepare(function() {
exec("ls -1 migrations", { cwd: __dirname + '/tmp' }, function(err, stdout) {
var date = new Date()
, format = function(i) { return (parseInt(i, 10) < 10 ? '0' + i : i) }
, sDate = [date.getFullYear(), format(date.getMonth() + 1), format(date.getDate()), format(date.getHours()), format(date.getMinutes())].join('')
expect(stdout).to.match(new RegExp(sDate + "..-foo.js"))
done()
expect(stdout).to.match(new RegExp(sDate + "..-foo.js"))
done()
})
})
})
})
it("adds a skeleton with an up and a down method", function(done) {
prepare(function() {
exec("cat migrations/*-foo.js", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.include('up: function(migration, DataTypes, done) {')
expect(stdout).to.include('down: function(migration, DataTypes, done) {')
done()
it("adds a skeleton with an up and a down method", function(done) {
prepare(function() {
exec("cat migrations/*-foo.js", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.include('up: function(migration, DataTypes, done) {')
expect(stdout).to.include('down: function(migration, DataTypes, done) {')
done()
})
})
})
})
it("calls the done callback", function(done) {
prepare(function() {
exec("cat migrations/*-foo.js", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.include('done()')
expect(stdout.match(/(done\(\))/)).to.have.length(2)
done()
it("calls the done callback", function(done) {
prepare(function() {
exec("cat migrations/*-foo.js", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.include('done()')
expect(stdout.match(/(done\(\))/)).to.have.length(2)
done()
})
})
})
})
})
})
})(['--create-migration', '-c'])
})(['--create-migration', '-c'])
;(function(flags) {
flags.forEach(function(flag) {
var prepare = function(callback) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize " + flag + " 'foo'", { cwd: __dirname + '/tmp' }, callback)
;(function(flags) {
flags.forEach(function(flag) {
var prepare = function(callback) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize " + flag + " 'foo'", { cwd: __dirname + '/tmp' }, callback)
})
})
})
}
}
describe(flag, function() {
it("creates a new file with the current timestamp", function(done) {
prepare(function() {
exec("ls -1 migrations", { cwd: __dirname + '/tmp' }, function(err, stdout) {
var date = new Date()
, format = function(i) { return (parseInt(i, 10) < 10 ? '0' + i : i) }
, sDate = [date.getFullYear(), format(date.getMonth() + 1), format(date.getDate()), format(date.getHours()), format(date.getMinutes())].join('')
describe(flag, function() {
it("creates a new file with the current timestamp", function(done) {
prepare(function() {
exec("ls -1 migrations", { cwd: __dirname + '/tmp' }, function(err, stdout) {
var date = new Date()
, format = function(i) { return (parseInt(i, 10) < 10 ? '0' + i : i) }
, sDate = [date.getFullYear(), format(date.getMonth() + 1), format(date.getDate()), format(date.getHours()), format(date.getMinutes())].join('')
expect(stdout).to.match(new RegExp(sDate + "..-foo.coffee"))
done()
expect(stdout).to.match(new RegExp(sDate + "..-foo.coffee"))
done()
})
})
})
})
it("adds a skeleton with an up and a down method", function(done) {
prepare(function() {
exec("cat migrations/*-foo.coffee", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.include('up: (migration, DataTypes, done) ->')
expect(stdout).to.include('down: (migration, DataTypes, done) ->')
done()
it("adds a skeleton with an up and a down method", function(done) {
prepare(function() {
exec("cat migrations/*-foo.coffee", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.include('up: (migration, DataTypes, done) ->')
expect(stdout).to.include('down: (migration, DataTypes, done) ->')
done()
})
})
})
})
it("calls the done callback", function(done) {
prepare(function() {
exec("cat migrations/*-foo.coffee", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.include('done()')
expect(stdout.match(/(done\(\))/)).to.have.length(2)
done()
it("calls the done callback", function(done) {
prepare(function() {
exec("cat migrations/*-foo.coffee", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.include('done()')
expect(stdout.match(/(done\(\))/)).to.have.length(2)
done()
})
})
})
})
})
})
})(['--coffee --create-migration', '--coffee -c'])
;(function(flags) {
flags.forEach(function(flag) {
var prepare = function(callback) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function(error, stdout) {
var source = (flag.indexOf('coffee') === -1)
? "../assets/migrations/*-createPerson.js"
: "../assets/migrations/*-createPerson.coffee"
exec("cp " + source + " ./migrations/", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("cat ../support.js|sed s,/../,/../../, > ./support.js", { cwd: __dirname + '/tmp' }, function(error, stdout) {
var dialect = Support.getTestDialect()
, config = require(__dirname + '/config/config.js')
config.sqlite.storage = __dirname + "/tmp/test.sqlite"
config = _.extend(config, config[dialect], { dialect: dialect })
exec("echo '" + JSON.stringify(config) + "' > config/config.json", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("../../bin/sequelize " + flag, { cwd: __dirname + "/tmp" }, callback)
})(['--coffee --create-migration', '--coffee -c'])
;(function(flags) {
flags.forEach(function(flag) {
var prepare = function(callback) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function(error, stdout) {
var source = (flag.indexOf('coffee') === -1)
? "../assets/migrations/*-createPerson.js"
: "../assets/migrations/*-createPerson.coffee"
exec("cp " + source + " ./migrations/", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("cat ../support.js|sed s,/../,/../../, > ./support.js", { cwd: __dirname + '/tmp' }, function(error, stdout) {
var dialect = Support.getTestDialect()
, config = require(__dirname + '/config/config.js')
config.sqlite.storage = __dirname + "/tmp/test.sqlite"
config = _.extend(config, config[dialect], { dialect: dialect })
exec("echo '" + JSON.stringify(config) + "' > config/config.json", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("../../bin/sequelize " + flag, { cwd: __dirname + "/tmp" }, callback)
})
})
})
})
})
})
}
}
describe(flag, function() {
it("creates a SequelizeMeta table", function(done) {
var sequelize = this.sequelize
describe(flag, function() {
it("creates a SequelizeMeta table", function(done) {
var sequelize = this.sequelize
if (this.sequelize.options.dialect === 'sqlite') {
var options = this.sequelize.options
options.storage = __dirname + "/tmp/test.sqlite"
sequelize = new Support.Sequelize("", "", "", options)
}
if (this.sequelize.options.dialect === 'sqlite') {
var options = this.sequelize.options
options.storage = __dirname + "/tmp/test.sqlite"
sequelize = new Support.Sequelize("", "", "", options)
}
prepare(function() {
sequelize.getQueryInterface().showAllTables().success(function(tables) {
tables = tables.sort()
prepare(function() {
sequelize.getQueryInterface().showAllTables().success(function(tables) {
tables = tables.sort()
expect(tables).to.have.length(2)
expect(tables[1]).to.equal("SequelizeMeta")
done()
})
}.bind(this))
})
expect(tables).to.have.length(2)
expect(tables[1]).to.equal("SequelizeMeta")
done()
})
}.bind(this))
})
it("creates the respective table", function(done) {
var sequelize = this.sequelize
it("creates the respective table", function(done) {
var sequelize = this.sequelize
if (this.sequelize.options.dialect === 'sqlite') {
var options = this.sequelize.options
options.storage = __dirname + "/tmp/test.sqlite"
sequelize = new Support.Sequelize("", "", "", options)
}
if (this.sequelize.options.dialect === 'sqlite') {
var options = this.sequelize.options
options.storage = __dirname + "/tmp/test.sqlite"
sequelize = new Support.Sequelize("", "", "", options)
}
prepare(function() {
sequelize.getQueryInterface().showAllTables().success(function(tables) {
tables = tables.sort()
prepare(function() {
sequelize.getQueryInterface().showAllTables().success(function(tables) {
tables = tables.sort()
expect(tables).to.have.length(2)
expect(tables[0]).to.equal("Person")
done()
})
}.bind(this))
expect(tables).to.have.length(2)
expect(tables[0]).to.equal("Person")
done()
})
}.bind(this))
})
})
})
})
})([
'--migrate',
'--migrate --coffee',
'--migrate --config ../tmp/config/config.json',
'--migrate --config ' + path.join(__dirname, 'tmp', 'config', 'config.json'),
'-m',
'-m --coffee',
'-m --config ../tmp/config/config.json',
'-m --config ' + path.join(__dirname, 'tmp', 'config', 'config.json')
])
;(function(flags) {
flags.forEach(function(flag) {
var execBinary = function(callback, _flag) {
_flag = _flag || flag
var dialect = Support.getTestDialect()
, config = require(__dirname + '/config/config.js')
config.sqlite.storage = __dirname + "/tmp/test.sqlite"
config = _.extend(config, config[dialect], { dialect: dialect })
exec("echo '" + JSON.stringify(config) + "' > config/config.json", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("../../bin/sequelize " + _flag, { cwd: __dirname + "/tmp" }, callback)
})
}
var prepare = function(callback, options) {
options = options || {}
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("cp ../assets/migrations/*-createPerson.js ./migrations/", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("cat ../support.js|sed s,/../,/../../, > ./support.js", { cwd: __dirname + '/tmp' }, function(error, stdout) {
if (!options.skipExecBinary) {
execBinary(callback, options.flag)
}
})([
'--migrate',
'--migrate --coffee',
'--migrate --config ../tmp/config/config.json',
'--migrate --config ' + path.join(__dirname, 'tmp', 'config', 'config.json'),
'-m',
'-m --coffee',
'-m --config ../tmp/config/config.json',
'-m --config ' + path.join(__dirname, 'tmp', 'config', 'config.json')
])
;(function(flags) {
flags.forEach(function(flag) {
var execBinary = function(callback, _flag) {
_flag = _flag || flag
var dialect = Support.getTestDialect()
, config = require(__dirname + '/config/config.js')
config.sqlite.storage = __dirname + "/tmp/test.sqlite"
config = _.extend(config, config[dialect], { dialect: dialect })
exec("echo '" + JSON.stringify(config) + "' > config/config.json", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("../../bin/sequelize " + _flag, { cwd: __dirname + "/tmp" }, callback)
})
}
var prepare = function(callback, options) {
options = options || {}
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("cp ../assets/migrations/*-createPerson.js ./migrations/", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("cat ../support.js|sed s,/../,/../../, > ./support.js", { cwd: __dirname + '/tmp' }, function(error, stdout) {
if (!options.skipExecBinary) {
execBinary(callback, options.flag)
}
})
})
})
})
})
}
}
describe(flag, function() {
it("creates a SequelizeMeta table", function(done) {
var sequelize = this.sequelize
describe(flag, function() {
it("creates a SequelizeMeta table", function(done) {
var sequelize = this.sequelize
if (this.sequelize.options.dialect === 'sqlite') {
var options = this.sequelize.options
options.storage = __dirname + "/tmp/test.sqlite"
sequelize = new Support.Sequelize("", "", "", options)
}
if (this.sequelize.options.dialect === 'sqlite') {
var options = this.sequelize.options
options.storage = __dirname + "/tmp/test.sqlite"
sequelize = new Support.Sequelize("", "", "", options)
}
prepare(function() {
sequelize.getQueryInterface().showAllTables().success(function(tables) {
tables = tables.sort()
prepare(function() {
sequelize.getQueryInterface().showAllTables().success(function(tables) {
tables = tables.sort()
expect(tables).to.have.length(1)
expect(tables[0]).to.equal("SequelizeMeta")
done()
})
}.bind(this))
})
expect(tables).to.have.length(1)
expect(tables[0]).to.equal("SequelizeMeta")
done()
})
}.bind(this))
})
it("stops execution if no migrations have been done yet", function(done) {
var sequelize = this.sequelize
it("stops execution if no migrations have been done yet", function(done) {
var sequelize = this.sequelize
if (this.sequelize.options.dialect === 'sqlite') {
var options = this.sequelize.options
options.storage = __dirname + "/tmp/test.sqlite"
sequelize = new Support.Sequelize("", "", "", options)
}
if (this.sequelize.options.dialect === 'sqlite') {
var options = this.sequelize.options
options.storage = __dirname + "/tmp/test.sqlite"
sequelize = new Support.Sequelize("", "", "", options)
}
prepare(function(err, output) {
expect(err).to.be.null
expect(output).to.include("There are no pending migrations.")
done()
}.bind(this))
})
prepare(function(err, output) {
expect(err).to.be.null
expect(output).to.include("There are no pending migrations.")
done()
}.bind(this))
})
it("is correctly undoing a migration if they have been done yet", function(done) {
var sequelize = this.sequelize
it("is correctly undoing a migration if they have been done yet", function(done) {
var sequelize = this.sequelize
if (this.sequelize.options.dialect === 'sqlite') {
var options = this.sequelize.options
options.storage = __dirname + "/tmp/test.sqlite"
sequelize = new Support.Sequelize("", "", "", options)
}
if (this.sequelize.options.dialect === 'sqlite') {
var options = this.sequelize.options
options.storage = __dirname + "/tmp/test.sqlite"
sequelize = new Support.Sequelize("", "", "", options)
}
prepare(function() {
sequelize.getQueryInterface().showAllTables().success(function(tables) {
tables = tables.sort()
prepare(function() {
sequelize.getQueryInterface().showAllTables().success(function(tables) {
tables = tables.sort()
expect(tables).to.have.length(2)
expect(tables[0]).to.equal("Person")
expect(tables).to.have.length(2)
expect(tables[0]).to.equal("Person")
execBinary(function(err, output) {
sequelize.getQueryInterface().showAllTables().success(function(tables) {
expect(tables).to.have.length(1)
expect(tables[0]).to.equal("SequelizeMeta")
execBinary(function(err, output) {
sequelize.getQueryInterface().showAllTables().success(function(tables) {
expect(tables).to.have.length(1)
expect(tables[0]).to.equal("SequelizeMeta")
done()
done()
})
})
})
})
}.bind(this), { flag: '-m' })
}.bind(this), { flag: '-m' })
})
})
})
})
})(['--migrate --undo', '-mu', '--undo', '-u'])
;(function(flags) {
flags.forEach(function(flag) {
var prepare = function(callback) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("cp ../assets/migrations/*-createPerson.js ./migrations/", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("cat ../support.js|sed s,/../,/../../, > ./support.js", { cwd: __dirname + '/tmp' }, function(error, stdout) {
var dialect = Support.getTestDialect()
, config = require(__dirname + '/config/config.js')
config.sqlite.storage = __dirname + "/tmp/test.sqlite"
config = _.extend(config, config[dialect], { dialect: dialect })
var url = Support.getTestUrl(config);
exec("echo '" + JSON.stringify(config) + "' > config/config.json", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("../../bin/sequelize -m " + flag + " " + url, { cwd: __dirname + "/tmp" }, callback)
})(['--migrate --undo', '-mu', '--undo', '-u'])
;(function(flags) {
flags.forEach(function(flag) {
var prepare = function(callback) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("cp ../assets/migrations/*-createPerson.js ./migrations/", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("cat ../support.js|sed s,/../,/../../, > ./support.js", { cwd: __dirname + '/tmp' }, function(error, stdout) {
var dialect = Support.getTestDialect()
, config = require(__dirname + '/config/config.js')
config.sqlite.storage = __dirname + "/tmp/test.sqlite"
config = _.extend(config, config[dialect], { dialect: dialect })
var url = Support.getTestUrl(config);
exec("echo '" + JSON.stringify(config) + "' > config/config.json", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("../../bin/sequelize -m " + flag + " " + url, { cwd: __dirname + "/tmp" }, callback)
})
})
})
})
})
})
}
}
describe(flag, function() {
it("creates a SequelizeMeta table", function(done) {
var sequelize = this.sequelize
describe(flag, function() {
it("creates a SequelizeMeta table", function(done) {
var sequelize = this.sequelize
if (this.sequelize.options.dialect === 'sqlite') {
var options = this.sequelize.options
options.storage = __dirname + "/tmp/test.sqlite"
sequelize = new Support.Sequelize("", "", "", options)
}
if (this.sequelize.options.dialect === 'sqlite') {
var options = this.sequelize.options
options.storage = __dirname + "/tmp/test.sqlite"
sequelize = new Support.Sequelize("", "", "", options)
}
prepare(function() {
sequelize.getQueryInterface().showAllTables().success(function(tables) {
tables = tables.sort()
prepare(function() {
sequelize.getQueryInterface().showAllTables().success(function(tables) {
tables = tables.sort()
expect(tables).to.have.length(2)
expect(tables[1]).to.equal("SequelizeMeta")
done()
})
}.bind(this))
})
expect(tables).to.have.length(2)
expect(tables[1]).to.equal("SequelizeMeta")
done()
})
}.bind(this))
})
it("creates the respective table via url", function(done) {
var sequelize = this.sequelize
it("creates the respective table via url", function(done) {
var sequelize = this.sequelize
if (this.sequelize.options.dialect === 'sqlite') {
var options = this.sequelize.options
options.storage = __dirname + "/tmp/test.sqlite"
sequelize = new Support.Sequelize("", "", "", options)
}
if (this.sequelize.options.dialect === 'sqlite') {
var options = this.sequelize.options
options.storage = __dirname + "/tmp/test.sqlite"
sequelize = new Support.Sequelize("", "", "", options)
}
prepare(function() {
sequelize.getQueryInterface().showAllTables().success(function(tables) {
tables = tables.sort()
prepare(function() {
sequelize.getQueryInterface().showAllTables().success(function(tables) {
tables = tables.sort()
expect(tables).to.have.length(2)
expect(tables[0]).to.equal("Person")
done()
})
}.bind(this))
expect(tables).to.have.length(2)
expect(tables[0]).to.equal("Person")
done()
})
}.bind(this))
})
})
})
})
})(['--url', '-U'])
})
})(['--url', '-U'])
})
}
var fs = require('fs')
, path = require('path')
, _ = require('lodash')
, Sequelize = require(__dirname + "/../index")
, DataTypes = require(__dirname + "/../lib/data-types")
, Config = require(__dirname + "/config/config")
......@@ -44,30 +45,23 @@ var Support = {
var config = Config[options.dialect]
options.logging = (options.hasOwnProperty('logging') ? options.logging : false)
options.pool = options.pool !== undefined ? options.pool : config.pool
var sequelizeOptions = {
var sequelizeOptions = _.defaults(options, {
host: options.host || config.host,
logging: options.logging,
logging: false,
dialect: options.dialect,
port: options.port || process.env.SEQ_PORT || config.port,
pool: options.pool,
pool: config.pool,
dialectOptions: options.dialectOptions || {}
}
})
if (!!options.define) {
sequelizeOptions.define = options.define
if (process.env.DIALECT === 'postgres-native') {
sequelizeOptions.native = true
}
if (!!config.storage) {
sequelizeOptions.storage = config.storage
}
if (process.env.DIALECT === 'postgres-native') {
sequelizeOptions.native = true
}
return this.getSequelizeInstance(config.database, config.username, config.password, sequelizeOptions)
},
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!