数据库添加对事务的支持,需要数据库本身支持才能使用。

This commit is contained in:
welefen 2014-07-28 11:14:22 +08:00
parent 1e18d27281
commit e446c9db26
3 changed files with 69 additions and 7 deletions

View File

@ -37,6 +37,8 @@ var Db = module.exports = Class(function(){
linkId: null,
// 数据库连接参数配置
config: '',
// 事务次数
transTimes: 0,
/**
* 初始化
* @return {[type]} [description]

View File

@ -955,6 +955,30 @@ var Model = module.exports = Class(function(){
this.initDb().setModel(self.getModelName());
return promise;
},
/**
* 启动事务
* @return {[type]} [description]
*/
startTrans: function(){
var self = this;
return this.initDb().commit().then(function(){
return self.db.startTrans();
});
},
/**
* 提交事务
* @return {[type]} [description]
*/
commit: function(){
return this.initDb().commit();
},
/**
* 回滚事务
* @return {[type]} [description]
*/
rollback: function(){
return this.initDb().rollback();
},
/**
* 设置数据对象值
* @return {[type]} [description]

View File

@ -82,7 +82,9 @@ module.exports = Db(function(){
this.setSql(str);
var self = this;
return this.connect().query(str).then(function(data){
self.lastInsertId = data.insertId;
if (data.insertId) {
self.lastInsertId = data.insertId;
}
return data.affectedRows || 0;
});
},
@ -128,14 +130,38 @@ module.exports = Db(function(){
});
},
/**
* 关闭连接
* 启动事务
* @return {[type]} [description]
*/
close: function(){
if (this.linkId) {
this.linkId.close();
this.linkId = null;
startTrans: function(){
if (this.transTimes === 0) {
this.transTimes++;
return this.execute('START TRANSACTION');
}
this.transTimes++;
return getPromise();
},
/**
* 提交事务
* @return {[type]} [description]
*/
commit: function(){
if (this.transTimes > 0) {
this.transTimes = 0;
return this.execute('COMMIT');
}
return getPromise();
},
/**
* 回滚事务
* @return {[type]} [description]
*/
rollback: function(){
if (this.transTimes > 0) {
this.transTimes = 0;
return this.execute('ROLLBACK');
}
return getPromise();
},
/**
* 解析key
@ -155,6 +181,16 @@ module.exports = Db(function(){
*/
getLastInsertId: function(){
return this.lastInsertId;
}
},
/**
* 关闭连接
* @return {[type]} [description]
*/
close: function(){
if (this.linkId) {
this.linkId.close();
this.linkId = null;
}
},
};
});