Merge pull request #301 from dweinand/schema-transactions

allow schema methods to use transactions
This commit is contained in:
Tim Griesser 2014-06-05 21:30:05 -04:00
commit cffd434a0f
2 changed files with 84 additions and 0 deletions

View File

@ -153,6 +153,8 @@ Knex.initialize = function(config) {
if (!client.SchemaBuilder) client.initSchema();
var builder = new client.SchemaBuilder();
if (config.__transactor__) builder.transacting(config.__transactor__);
// Passthrough all "query" events to the knex object.
builder.on('query', function(data) {
knex.emit('query', data);

View File

@ -147,6 +147,88 @@ module.exports = function(knex) {
});
});
if (knex.client.dialect === 'postgresql') {
it('should be able to run schema methods', function() {
var err = new Error('error message');
var __cid, count = 0;
return knex.transaction(function(trx) {
return trx.schema
.createTable('test_schema_transactions', function(table) {
table.increments();
table.string('name');
table.timestamps();
}).then(function() {
return trx('test_schema_transactions')
.insert({name: 'bob'});
}).then(function() {
return trx('test_schema_transactions')
.count('*');
}).then(function(resp) {
var _count = parseInt(resp[0].count);
expect(_count).to.equal(1);
throw err;
});
})
.on('query', function(obj) {
count++;
if (!__cid) __cid = obj.__cid;
expect(__cid).to.equal(obj.__cid);
})
.catch(function(msg) {
expect(msg).to.equal(err);
expect(count).to.equal(5);
return knex('test_schema_migrations')
.count('*');
})
.catch(function(e) {
expect(e.message).to.equal('relation "test_schema_migrations" does not exist');
});
});
} else {
it('should be able to run schema methods', function() {
var id = null;
var __cid, count = 0;
return knex.transaction(function(trx) {
return trx('accounts')
.returning('id')
.insert({
first_name: 'Transacting',
last_name: 'User3',
email:'transaction-test5@example.com',
logins: 1,
about: 'Lorem ipsum Dolore labore incididunt enim.',
created_at: new Date(),
updated_at: new Date()
}).then(function(resp) {
return trx('test_table_two').insert({
account_id: (id = resp[0]),
details: '',
status: 1
});
}).then(function() {
return trx.schema
.createTable('test_schema_transactions', function(table) {
table.increments();
table.string('name');
table.timestamps();
});
});
})
.on('query', function(obj) {
count++;
if (!__cid) __cid = obj.__cid;
expect(__cid).to.equal(obj.__cid);
}).then(function() {
expect(count).to.equal(5);
return knex('accounts').where('id', id).select('first_name');
}).then(function(resp) {
expect(resp).to.have.length(1);
}).finally(function() {
return knex.schema.dropTableIfExists('test_schema_transactions');
});
});
}
});
};