This commit is contained in:
2023-04-02 19:53:43 +08:00
parent 685a0d72b2
commit f554b4c81e
+58 -13
View File
@@ -65,6 +65,7 @@ class Command extends Component
*/
public function all(): ?array
{
try {
[$pdo, $statement] = $this->search();
$statement->execute($this->params);
@@ -73,6 +74,17 @@ class Command extends Component
$this->db->release($pdo);
return $data;
} catch (\Throwable $throwable) {
if (str_contains($throwable->getMessage(), 'MySQL server has gone away')) {
$this->db->restore();
return $this->one();
}
if (isset($pdo)) {
$this->db->release($pdo);
}
return $this->printErrorMessage($throwable);
}
}
/**
@@ -81,6 +93,7 @@ class Command extends Component
*/
public function one(): ?array
{
try {
[$pdo, $statement] = $this->search();
$statement->execute($this->params);
@@ -89,6 +102,17 @@ class Command extends Component
$this->db->release($pdo);
return $data;
} catch (\Throwable $throwable) {
if (str_contains($throwable->getMessage(), 'MySQL server has gone away')) {
$this->db->restore();
return $this->one();
}
if (isset($pdo)) {
$this->db->release($pdo);
}
return $this->printErrorMessage($throwable);
}
}
/**
@@ -97,6 +121,7 @@ class Command extends Component
*/
public function fetchColumn(): mixed
{
try {
[$pdo, $statement] = $this->search();
$statement->execute($this->params);
@@ -105,14 +130,26 @@ class Command extends Component
$this->db->release($pdo);
return $data;
} catch (\Throwable $throwable) {
if (str_contains($throwable->getMessage(), 'MySQL server has gone away')) {
$this->db->restore();
return $this->fetchColumn();
}
if (isset($pdo)) {
$this->db->release($pdo);
}
return $this->printErrorMessage($throwable);
}
}
/**
* @return ?int
* @return int|null
* @throws Exception
*/
public function rowCount(): ?int
{
try {
[$pdo, $statement] = $this->search();
$statement->execute($this->params);
@@ -121,6 +158,25 @@ class Command extends Component
$this->db->release($pdo);
return $data;
} catch (\Throwable $throwable) {
if (str_contains($throwable->getMessage(), 'MySQL server has gone away')) {
$this->db->restore();
return $this->rowCount();
}
if (isset($pdo)) {
$this->db->release($pdo);
}
return $this->printErrorMessage($throwable);
}
}
private function printErrorMessage(\Throwable $throwable): mixed
{
$this->logger->addError($this->sql . '. error: ' . $throwable->getMessage(), 'mysql');
return null;
}
/**
@@ -173,22 +229,11 @@ class Command extends Component
private function search(): bool|array
{
$pdo = $this->db->getSlaveClient();
try {
if (($statement = $pdo->prepare($this->sql)) === false) {
throw new Exception($pdo->errorInfo()[1]);
}
return [$pdo, $statement];
} catch (\Throwable $throwable) {
if (str_contains($throwable->getMessage(), 'MySQL server has gone away')) {
$this->db->restore();
return $this->search();
}
$this->db->release($pdo);
return $this->logger->addError($this->sql . '. error: ' . $throwable->getMessage(), 'mysql');
}
}