yii 嵌套事务的回滚总数

rggaifut  于 2022-11-09  发布在  其他
关注(0)|答案(3)|浏览(171)

我真的很喜欢这个**NestedPDO**Yii解决方案,但我需要一些不同的事务处理。
我希望仅在所有嵌套事务都可以提交时才提交嵌套事务,并且如果一个事务执行了回滚,则所有事务都应回滚。
我怎么能那样做呢?
我尝试更改回滚功能,但没有成功:

public function rollBack() {
    $this->transLevel--;

    if($this->transLevel == 0 || !$this->nestable()) {
        parent::rollBack();
    } else {

        $level = $this->transLevel;
        for($level; $level>1; $level--){
            $this->exec("ROLLBACK TO SAVEPOINT LEVEL{$this->constantlevel}");
        }
        //parent::rollBack();
    }
}

我在考虑修改NestedPDO:在函数commit()中只对最外层的事务进行提交,而在函数rollBack()中则回滚到最外层的事务,不管是哪个子事务导致了回滚。但是我无法完成...
我正在使用MySQL和InnoDB表,我不确定自动提交是否有效,但在事务中回显自动提交的值时,我总是得到值1,这意味着自动提交已启用,但在事务中,自动提交应设置为0。我不确定这是否是整个回滚不起作用的原因?

i34xakig

i34xakig1#

If you want the whole transaction be rolled back automatically as soon as an error occurs, you could just re-throw the exception from B 's exception handler when called from some specific locations (eg. from A() ):

function A(){
   ...
   $this->B(true);
   ...
}

/*

* @param B boolean Throw an exception if the transaction is rolled back
* /

function B($rethrow) {
    $transaction=Yii::app()->db->beginTransaction();
    try {
        //do something
        $transaction->commit();
    } catch(Exception $e) {
        $transaction->rollBack();
        if ($rethrow) throw $e;
    }
}

Now I understand you actually just want your wrapper to detect if a transaction is already in progress, and in this case not start the transaction.
Therefore you do not really need the NestedPDO class. You could create a class like this instead:

class SingleTransactionManager extends PDO {
    private $nestingDepth = 0;

    public function beginTransaction() {
        if(!$this->nestingDepth++ == 0) {
            parent::beginTransaction();
        } // else do nothing
    }
    public function commit() {
        $this->nestingDepth--;
        if (--$this->nestingDepth == 0) {
            parent::commit();
        } // else do nothing
    }

    public function rollback() {
        parent::rollback();
        if (--$this->nestingDepth > 0) {
            $this->nestingDepth = 0;
            throw new Exception(); // so as to interrupt outer the transaction ASAP, which has become pointless
        }

    }
}
vwoqyblh

vwoqyblh2#

根据@RandomSeed的回答,我创建了一个默认Yii交易处理的'drop in':

$connection = Yii::app()->db;
$transaction=$connection->beginTransaction();
try
{
   $connection->createCommand($sql1)->execute();
   $connection->createCommand($sql2)->execute();
   //.... other SQL executions
   $transaction->commit();
}
catch(Exception $e)
{
   $transaction->rollback();
}

这是我的SingleTransactionManager类:

class SingleTransactionManager extends CComponent 
{
    // The current transaction level.
    private $transLevel = 0;

    // The CDbConnection object that should be wrapped
    public $dbConnection;

    public function init()
    {
        if($this->dbConnection===null)
            throw new Exception('Property `dbConnection` must be set.');

        $this->dbConnection=$this->evaluateExpression($this->dbConnection);
    }
    // We only start a transaction if we're the first doing so
    public function beginTransaction() {
        if($this->transLevel == 0) {
            $transaction = parent::beginTransaction();
        } else {
            $transaction = new SingleTransactionManager_Transaction($this->dbConnection, false);
        }
        // always increase transaction level:
        $this->transLevel++;

        return $transaction;
    }

    public function __call($name, $parameters)
    {
        return call_user_func_array(array($this->dbConnection, $name), $parameters);
    }
}

class SingleTransactionManager_Transaction extends CDbTransaction
{
    // boolean, whether this instance 'really' started the transaction
    private $_startedTransaction;

    public function __construct(CDbConnection $connection, $startedTransaction = false)
    {
        $this->_startedTransaction = $startedTransaction;
        parent::__construct($connection);
        $this->setActive($startedTransaction);
    }

    // We only commit a transaction if we've started the transaction
    public function commit() {
        if($this->_startedTransaction)
            parent::commit();
    }

    // We only rollback a transaction if we've started the transaction
    // else throw an Exception to revert parent transactions/take adquate action
    public function rollback() {
        if($this->_startedTransaction)
            parent::rollback();
        else
            throw new Exception('Child transaction rolled back!');
    }
}

此类“ Package ”主数据库连接,应在配置中将其声明为组件,如下所示:

'components'=>array(

    // database
    'db'=>array(
        'class' => 'CDbConnection',
        // using mysql
        'connectionString'=>'....',
        'username'=>'...',
        'password'=>'....',
    ),

    // database
    'singleTransaction'=>array(
        'class' => 'pathToComponents.db.SingleTransactionManager',
        'dbConnection' => 'Yii::app()->db'
    )

请注意,dbConnection属性应该是master数据库联机的表示式。现在,当巢状Try catch区块中的巢状交易时,您可以在例如巢状交易3中建立错误,而1和2上的巢状交易也会回复。
测试代码:

$connection = Yii::app()->singleTransaction;

$connection->createCommand('CREATE TABLE IF NOT EXISTS `test_transactions` (
  `number` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;')->execute();

$connection->createCommand('TRUNCATE TABLE `test_transactions`;')->execute();

testNesting(4, 3, 1);

echo '<br>';
echo 'Rows:';
echo '<br>';
$rows = $connection->createCommand('SELECT * FROM `test_transactions`')->queryAll();
if($rows)
{
    foreach($rows as $row)
    {
        print_r($row);
    }
}
else
    echo 'Table is empty!';

function testNesting(int $total, int $createErrorIn = null, int $current = 1)
{
    if($current>=$total)
        return;

    $connection = Yii::app()->singleTransaction;
    $indent = str_repeat('&nbsp;', ($current*4));

    echo $indent.'Transaction '.$current;
    echo '<br>';
    $transaction=$connection->beginTransaction();
    try
    {
        // create nonexisting columnname when we need to create an error in this nested transaction
        $columnname = 'number'.($createErrorIn===$current ? 'rr' : '');
        $connection->createCommand('INSERT INTO `test_transactions` (`'.$columnname.'`) VALUES ('.$current.')')->execute();

        testNesting($total, $createErrorIn, ($current+1));

        $transaction->commit();
    }
    catch(Exception $e)
    {
        echo $indent.'Exception';
        echo '<br>';
        echo $indent.$e->getMessage();
        echo '<br>';
        $transaction->rollback();
    }
}

产生以下输出:

Transaction 1
        Transaction 2
            Transaction 3
            Exception
            CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'numberrr' in 'field list'. The SQL statement executed was: INSERT INTO `test_transactions` (`numberrr`) VALUES (3)
        Exception
        Child transaction rolled back!
    Exception
    Child transaction rolled back!

Rows:
Table is empty!
ryevplcw

ryevplcw3#

恕我直言,在应用程序代码中模拟“嵌套事务”的想法是一种反模式。在应用程序中有许多不可能解决的异常情况(请参阅我对https://stackoverflow.com/a/319939/20860的回答)。
在PHP中,最好保持简单。工作被自然地组织成请求,所以使用请求作为事务作用域。

  • 在调用任何模型类之前,在控制器级别启动一个事务。
  • 让模型在发生任何错误时抛出异常。
  • 在控制器级别捕获异常,并在必要时回滚。
  • 如果未捕获到异常,则提交。

忘记所有关于事务级别的废话,模型不应该启动、提交或回滚任何事务。

相关问题