diff --git a/framework/yii/db/Command.php b/framework/yii/db/Command.php index a754e342328..3e66180714d 100644 --- a/framework/yii/db/Command.php +++ b/framework/yii/db/Command.php @@ -765,4 +765,34 @@ public function checkIntegrity($check = true, $schema = '') $sql = $this->db->getQueryBuilder()->checkIntegrity($check, $schema); return $this->setSql($sql); } + + /** + * @param \Closure $callable + * @return boolean|null + * @throws \Exception + */ + public function atomic($callable) + { + static $activeTransaction; + if ($activeTransaction !== null) { + $result = call_user_func($callable); + } else { + $transaction = $this->db->beginTransaction(); + $activeTransaction = $transaction; + try { + $result = call_user_func($callable); + if ($result === null || $result) { + $transaction->commit(); + } else { + $transaction->rollback(); + } + $activeTransaction = null; // emulate finally + } catch (Exception $e) { + $transaction->rollback(); + $activeTransaction = null; // emulate finally + throw $e; + } + } + return $result === null || $result; + } }