From eac2800561ccd1bc69073d8db259c16be5c69eb1 Mon Sep 17 00:00:00 2001 From: "as2252258@163.com" Date: Sat, 1 Apr 2023 20:57:07 +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 | 64 +++++++++++++++++++++++++++++++++++------------------ 1 file changed, 43 insertions(+), 21 deletions(-) diff --git a/Command.php b/Command.php index 40a13d6..070e039 100644 --- a/Command.php +++ b/Command.php @@ -13,6 +13,7 @@ namespace Database; use Exception; use Kiri\Abstracts\Component; use Kiri\Di\Context; +use PDO; use PDOStatement; /** @@ -56,24 +57,36 @@ class Command extends Component { return $this->_execute(); } - - + + /** - * @return mixed + * @return array|null * @throws Exception */ - public function all(): mixed + public function all(): ?array { - return $this->search(static::FETCH_ALL); + [$pdo, $statement] = $this->search(); + + $data = $statement->fetchAll(PDO::FETCH_ASSOC); + + $this->db->release($pdo); + + return $data; } - + /** - * @return mixed + * @return array|null * @throws Exception */ - public function one(): mixed + public function one(): ?array { - return $this->search(static::FETCH); + [$pdo, $statement] = $this->search(); + + $data = $statement->fetch(PDO::FETCH_ASSOC); + + $this->db->release($pdo); + + return $data; } /** @@ -82,16 +95,28 @@ class Command extends Component */ public function fetchColumn(): mixed { - return $this->search(static::FETCH_COLUMN); + [$pdo, $statement] = $this->search(); + + $data = $statement->fetchColumn(PDO::FETCH_ASSOC); + + $this->db->release($pdo); + + return $data; } /** - * @return mixed + * @return ?int * @throws Exception */ - public function rowCount(): mixed + public function rowCount(): ?int { - return $this->search(static::ROW_COUNT); + [$pdo, $statement] = $this->search(); + + $data = $statement->rowCount(); + + $this->db->release($pdo); + + return $data; } /** @@ -136,13 +161,12 @@ class Command extends Component return $this->logger->addError($this->sql . '. error: ' . $throwable->getMessage(), 'mysql'); } } - + /** - * @param string $type - * @return array|int|bool|null + * @return array|bool * @throws Exception */ - private function search(string $type): mixed + private function search(): bool|array { $pdo = $this->db->getSlaveClient(); try { @@ -152,14 +176,12 @@ class Command extends Component foreach ($this->params as $key => $param) { $statement->bindValue($key, $param); } - $data = $statement->{$type}(\PDO::FETCH_ASSOC); - $this->db->release($pdo); - return $data; + return [$pdo, $statement]; } catch (\Throwable $throwable) { if (str_contains($throwable->getMessage(), 'MySQL server has gone away')) { $this->db->restore(); - return $this->search($type); + return $this->search(); } $this->db->release($pdo);