laravel之嵌套事务transactions实现

写在之前

关于mysql 的事务嵌套可以查看这个地址:
https://dev.mysql.com/doc/refman/5.5/en/implicit-commit.html

里面有这么一句话。

Transactions cannot be nested. This is a consequence of the implicit commit performed for any current transaction when you issue a START TRANSACTION statement or one of its synonyms.

大体意思是db不支持事务嵌套,如果你嵌套执行START TRANSACTION时会隐式执行commit

我们做个测试:

mysql>  BEGIN;
Query OK, 0 rows affected (0.16 sec)

mysql> INSERT INTO T2 VALUES(300);
Query OK, 1 row affected (0.29 sec)

mysql>  BEGIN;
Query OK, 0 rows affected (0.04 sec)

mysql> rollback;
Query OK, 0 rows affected (0.04 sec)

mysql> SELECT * FROM T2;
+------+
| ID   |
+------+
|  300 |
+------+
2 rows in set (0.04 sec)

果然,我们直接rollback上面的语句,但是还是执行了查询操作。

laravel之嵌套事务transactions实现

为啥官网不支持,但是 laravel 框架却优雅的实现了事务嵌套,我们来看看它的实现原理。

调用示例:

\DB::beginTransaction();    //主事务
try{
    \DB::beginTransaction(); //子事务
    \DB::insert('insert into T2 set ID=100');
    \DB::rollBack();         //子事务回滚
    \DB::insert('insert into T2 set ID=200');
    \DB::commit();
}catch (\Exception $e) {
    \DB::rollBack();
    echo $e->getMessage();exit;
}

查看执行结果:

mysql> SELECT * FROM T2;
+------+
| ID   |
+------+
|  100 |
+------+
1 row in set (0.05 sec)

说明子事务成功回滚了,下面看下子事务的实现。

代码分析:

laravel/framework/src/Illuminate/Database/Concerns/ManagesTransactions.php 90行

public function beginTransaction()
    {
        $this->createTransaction();

        $this->transactions++;

        $this->fireConnectionEvent('beganTransaction');
    }

每调一次beginTransaction会使 t h i s − > t r a n s a c t i o n s 加 1 接 着 看 一 下 this->transactions加1 接着看一下 this>transactions1this->createTransaction();的实现

/**
     * Create a transaction within the database.
     *
     * @return void
     */
    protected function createTransaction()
    {
        if ($this->transactions == 0) {
            try {
                $this->getPdo()->beginTransaction();
            } catch (Exception $e) {
                $this->handleBeginTransactionException($e);
            }
        } elseif ($this->transactions >= 1 && $this->queryGrammar->supportsSavepoints()) {
            $this->createSavepoint();
        }
    }

if ($this->transactions == 0) 首先判断是否在事务中。

没有在事务中则执行 $this->getPdo()->beginTransaction()
相当于执行 BEGIN;

在事务中执行 $this->createSavepoint(); 下面是createSavepoint方法的实现。

/**
     * Create a save point within the database.
     *
     * @return void
     */
    protected function createSavepoint()
    {
        $this->getPdo()->exec(
            $this->queryGrammar->compileSavepoint('trans'.($this->transactions + 1))
        );
    }

这里相当于在mysql里执行 SAVEPOINT trans1;

下面看下rollback方法实现:

public function rollBack($toLevel = null)
{
    $toLevel = is_null($toLevel)
                ? $this->transactions - 1
                : $toLevel;

    if ($toLevel < 0 || $toLevel >= $this->transactions) {
        return;
    }
    $this->performRollBack($toLevel);
    $this->transactions = $toLevel;
    $this->fireConnectionEvent('rollingBack');
}

首先rollback会使 t h i s − &gt; t r a n s a c t i o n s 减 一 。 然 后 调 用 this-&gt;transactions减一。 然后调用 this>transactionsthis->performRollBack

protected function performRollBack($toLevel)
{
    if ($toLevel == 0) {
        $this->getPdo()->rollBack();
    } elseif ($this->queryGrammar->supportsSavepoints()) {
        $this->getPdo()->exec(
            $this->queryGrammar->compileSavepointRollBack('trans'.($toLevel + 1))
        );
    }
}

performRollBack方式实际就是在重新设定savepoint值。

下面看下commit的实现:

/**
 * Commit the active database transaction.
 *
 * @return void
 */
public function commit()
{
    if ($this->transactions == 1) {
        $this->getPdo()->commit();
    }

    $this->transactions = max(0, $this->transactions - 1);

    $this->fireConnectionEvent('committed');
}

commit方法,只有在最外层时才会真正的提交。

总结:

  1. 基本实现原理是 savepoint
  2. 通过$this->transactions对应的数值设定 不同的savepoint实现不同层次嵌套
  3. 只有在最后一个commit时才会真正提交请求。

SAVEPOINT 使用demo如下:

mysql> CREATE TABLE T2(ID INT);
Query OK, 0 rows affected (0.05 sec)

mysql> select * from T2;
Empty set (0.17 sec)

mysql> BEGIN;
Query OK, 0 rows affected (0.04 sec)

mysql> INSERT INTO T2 VALUES(100);
Query OK, 1 row affected (0.04 sec)

mysql> SAVEPOINT trans1;
Query OK, 0 rows affected (0.04 sec)

mysql> INSERT INTO T2 VALUES(200);
Query OK, 1 row affected (0.04 sec)

mysql> ROLLBACK TO SAVEPOINT trans1;
Query OK, 0 rows affected (0.04 sec)

mysql> RELEASE SAVEPOINT trans1;
Query OK, 0 rows affected (0.03 sec)

mysql> commit;
Query OK, 0 rows affected (0.04 sec)

mysql> SELECT * FROM T2;
+------+
| ID   |
+------+
|  100 |
+------+
1 row in set (0.05 sec)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

e421083458

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值