This commit is contained in:
2023-04-01 20:57:07 +08:00
parent 6493bf91bf
commit eac2800561
+39 -17
View File
@@ -13,6 +13,7 @@ namespace Database;
use Exception; use Exception;
use Kiri\Abstracts\Component; use Kiri\Abstracts\Component;
use Kiri\Di\Context; use Kiri\Di\Context;
use PDO;
use PDOStatement; use PDOStatement;
/** /**
@@ -59,21 +60,33 @@ class Command extends Component
/** /**
* @return mixed * @return array|null
* @throws Exception * @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 * @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 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 * @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;
} }
/** /**
@@ -138,11 +163,10 @@ class Command extends Component
} }
/** /**
* @param string $type * @return array<PDO, PDOStatement>|bool
* @return array|int|bool|null
* @throws Exception * @throws Exception
*/ */
private function search(string $type): mixed private function search(): bool|array
{ {
$pdo = $this->db->getSlaveClient(); $pdo = $this->db->getSlaveClient();
try { try {
@@ -152,14 +176,12 @@ class Command extends Component
foreach ($this->params as $key => $param) { foreach ($this->params as $key => $param) {
$statement->bindValue($key, $param); $statement->bindValue($key, $param);
} }
$data = $statement->{$type}(\PDO::FETCH_ASSOC); return [$pdo, $statement];
$this->db->release($pdo);
return $data;
} catch (\Throwable $throwable) { } catch (\Throwable $throwable) {
if (str_contains($throwable->getMessage(), 'MySQL server has gone away')) { if (str_contains($throwable->getMessage(), 'MySQL server has gone away')) {
$this->db->restore(); $this->db->restore();
return $this->search($type); return $this->search();
} }
$this->db->release($pdo); $this->db->release($pdo);