Skip to content
This repository has been archived by the owner on Jan 4, 2020. It is now read-only.

改进事务方法,支持嵌套事务提交 #490

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

keepeye
Copy link
Contributor

@keepeye keepeye commented Jan 3, 2017

原事务方法不支持如下写法

M()->startTrans();
M()->startTrans();//这里会提交事务
M()->rollback();//这行以下的事务全部无效
M()->commit();
M()->commit();

原因是 Model::startTrans() 方法会自动执行一次 commit ,这样会导致上面嵌套写法的事务在中间被强制提交 ,而之后的 commit 以及 rollback 全部无效,主要是rollback的失效会导致严重的问题。

改进想法:
M()->startTrans(); 不自动提交,这样只会 transTimes+1 ,然后 commit 和 rollback 都检测 transTimes == 1 如果是的话就执行 提交或回滚,否则只将 transTimes -1 ,唯一的要求外层需要检测内层返回值或异常,如果不成功外层也要执行 rollback 确保正常回滚。

例子:

function foo()
{
        //内层事务
        M()->startTrans();//transTimes: 2
        try {
               //....
               M()->commit(); // transTimes : 1
        } catch(\Exception $e)
               M()->rollback();// transTimes: 1
               throw $e;
        }
}

//外层
M()->startTrans();//transTimes : 1
try {
      foo();
      M()->commit(); // transTimes==1 提交事务
} catch(\Exception $e)
      M()->rollback();// transTimes==1 回滚操作
}

@keepeye keepeye closed this Jan 3, 2017
@keepeye keepeye deleted the transaction-improvement branch January 3, 2017 03:09
@keepeye keepeye restored the transaction-improvement branch January 3, 2017 03:16
@keepeye keepeye reopened this Jan 3, 2017
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant