Skip to content

Commit

Permalink
Fix error on transaction
Browse files Browse the repository at this point in the history
  • Loading branch information
welefen committed Aug 3, 2016
1 parent 3989c5e commit 8d7e89d
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 12 deletions.
13 changes: 10 additions & 3 deletions src/model/_base.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
'use strict';

import Validator from '../core/think_validate.js';

let forceNewNum = 1;

/**
* base model class
*/
Expand Down Expand Up @@ -120,12 +123,16 @@ export default class extends think.base {
* get db instance
* @return {Object} []
*/
db(){
if (this._db) {
db(forceNew = false){
if (this._db && !forceNew) {
return this._db;
}
let DB = think.adapter('db', this.config.type || 'mysql');
this._db = new DB(this.config);
let config = this.config;
if(forceNew){
config = think.extend({}, config, {forceNewNum: forceNewNum++});
}
this._db = new DB(config);
return this._db;
}
/**
Expand Down
16 changes: 11 additions & 5 deletions src/model/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -597,21 +597,27 @@ export default class extends Base {
* @return {Promise} []
*/
startTrans(){
return this.db().startTrans();
return this.db(true).startTrans();
}
/**
* commit transcation
* @return {Promise} []
*/
commit(){
return this.db().commit();
async commit(){
let data = await this.db().commit();
this.close();
this._db = null;
return data;
}
/**
* rollback transaction
* @return {Promise} []
*/
rollback(){
return this.db().rollback();
async rollback(){
let data = await this.db().rollback();
this.close();
this._db = null;
return data;
}
/**
* transaction exec functions
Expand Down
10 changes: 6 additions & 4 deletions test/model/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -1104,16 +1104,18 @@ describe('model/base.js', function(){
return instance.commit();
}).then(function(data){
var sql = instance.getLastSql();
assert.equal(sql, 'COMMIT');
assert.equal(sql, '');
done();
}).catch(function(err){
console.log(err)
})
})
it('rollback', function(done){
instance.startTrans().then(function(){
return instance.rollback();
}).then(function(data){
var sql = instance.getLastSql();
assert.equal(sql, 'ROLLBACK');
assert.equal(sql, '');
done();
})
})
Expand All @@ -1125,7 +1127,7 @@ describe('model/base.js', function(){
})
}).then(function(){
var sql = instance.getLastSql();
assert.equal(sql, 'COMMIT');
assert.equal(sql, '');
done();
})
})
Expand All @@ -1134,7 +1136,7 @@ describe('model/base.js', function(){
return Promise.reject(new Error('error'))
}).then(function(){
var sql = instance.getLastSql();
assert.equal(sql, 'ROLLBACK');
assert.equal(sql, '');
done();
})
})
Expand Down

0 comments on commit 8d7e89d

Please sign in to comment.