diff --git a/lib/Lib/Core/Db.js b/lib/Lib/Core/Db.js index 6e4261f7..75056314 100644 --- a/lib/Lib/Core/Db.js +++ b/lib/Lib/Core/Db.js @@ -37,6 +37,8 @@ var Db = module.exports = Class(function(){ linkId: null, // 数据库连接参数配置 config: '', + // 事务次数 + transTimes: 0, /** * 初始化 * @return {[type]} [description] diff --git a/lib/Lib/Core/Model.js b/lib/Lib/Core/Model.js index b11f27c7..94f3e27c 100644 --- a/lib/Lib/Core/Model.js +++ b/lib/Lib/Core/Model.js @@ -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] diff --git a/lib/Lib/Driver/Db/MysqlDb.js b/lib/Lib/Driver/Db/MysqlDb.js index 6a7292a1..64bb6e98 100644 --- a/lib/Lib/Driver/Db/MysqlDb.js +++ b/lib/Lib/Driver/Db/MysqlDb.js @@ -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; + } + }, }; }); \ No newline at end of file