From 5a96ca96cce0c8e2f8dda808c361a0b3f8835c7a Mon Sep 17 00:00:00 2001 From: "as2252258@163.com" Date: Thu, 6 Apr 2023 22:54:50 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8F=98=E6=9B=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Command.php | 4 +--- Connection.php | 39 +++++++++++++++++++++++++++------------ 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/Command.php b/Command.php index 077a573..86e0186 100644 --- a/Command.php +++ b/Command.php @@ -170,7 +170,7 @@ class Command extends Component private function _execute(): bool|int { try { - $client = $this->connection->getConnection(); + $client = $this->connection->getTransactionClient(); if (($prepare = $client->prepare($this->sql)) === false) { throw new Exception($client->errorInfo()[1]); } @@ -185,8 +185,6 @@ class Command extends Component return $this->_execute(); } return $this->error($throwable); - } finally { - $this->connection->release($client ?? null); } } diff --git a/Connection.php b/Connection.php index ff45732..676f996 100644 --- a/Connection.php +++ b/Connection.php @@ -206,21 +206,36 @@ class Connection extends Component */ public function beginTransaction(): static { - $pdo = Context::get($this->cds); - if ($pdo === null) { - $pdo = $this->getConnection(); - } + $pdo = $this->getTransactionClient(); $pdo->beginTransaction(); return $this; } + + /** + * @return PDO + * @throws Exception + */ + public function getTransactionClient(): PDO + { + if (!Db::inTransactionsActive()) { + return $this->getConnection(); + } + $pdo = Context::get($this->cds); + if ($pdo === null) { + $pdo = Context::set($this->cds, $this->getConnection()); + } + return $pdo; + } + /** * @return $this|bool * @throws Exception */ public function inTransaction(): bool|static { - return Context::get($this->cds)->inTransaction(); + $pdo = $this->getTransactionClient(); + return $pdo->inTransaction(); } /** @@ -229,11 +244,12 @@ class Connection extends Component */ public function rollback() { - $pdo = Context::get($this->cds); + $pdo = $this->getTransactionClient(); if ($pdo->inTransaction()) { $pdo->rollback(); } - $this->release($pdo); + $this->connections->push($this->cds, $pdo); + Context::remove($this->cds); } /** @@ -242,11 +258,12 @@ class Connection extends Component */ public function commit() { - $pdo = Context::get($this->cds); + $pdo = $this->getTransactionClient(); if ($pdo->inTransaction()) { $pdo->commit(); } - $this->release($pdo); + $this->connections->push($this->cds, $pdo); + Context::remove($this->cds); } @@ -270,9 +287,7 @@ class Connection extends Component */ public function release(PDO $PDO) { - if ($PDO->inTransaction() === false) { - $this->connections->push($this->cds, $PDO); - } + $this->connections->push($this->cds, $PDO); }