This commit is contained in:
2026-06-24 20:11:10 +08:00
parent 8a985a65df
commit bf4f8538ed
2 changed files with 347 additions and 315 deletions
+288 -260
View File
@@ -1,260 +1,288 @@
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: whwyy * User: whwyy
* Date: 2018/3/30 0030 * Date: 2018/3/30 0030
* Time: 15:23 * Time: 15:23
*/ */
declare(strict_types=1); declare(strict_types=1);
namespace Database; namespace Database;
use Exception; use Exception;
use Kiri\Abstracts\Component; use Kiri\Abstracts\Component;
use Kiri\Di\Container; use Kiri\Di\Container;
use PDO; use PDO;
use Throwable; use Throwable;
/** /**
* Class Command * Class Command
* @package Database * @package Database
*/ */
class Command extends Component class Command extends Component
{ {
public Connection $connection; /** @var int 数据库操作最大重试次数 */
public ?string $sql = ''; private const MAX_RETRIES = 2;
public array $params = [];
public Connection $connection;
/** public ?string $sql = '';
* @param array $params public array $params = [];
* @throws
*/ /**
public function __construct(array $params = []) * @param array $params
{ * @throws
parent::__construct(); */
Container::configure($this, $params); public function __construct(array $params = [])
} {
parent::__construct();
Container::configure($this, $params);
/** }
* @return bool
* @throws
*/ /**
public function incrOrDecr(): bool * @return bool
{ * @throws
return (bool)$this->_prepare(); */
} public function incrOrDecr(): bool
{
return (bool)$this->_prepare();
/** }
* @return bool|array
* @throws
*/ /**
public function all(): bool|array * @return bool|array
{ * @throws
return $this->search('fetchAll'); */
} public function all(): bool|array
{
/** return $this->search('fetchAll');
* @return array|bool|null }
* @throws
*/ /**
public function one(): array|null|bool * @return array|bool|null
{ * @throws
return $this->search('fetch'); */
} public function one(): array|null|bool
{
/** return $this->search('fetch');
* @return bool }
* @throws Exception
*/ /**
public function exists(): bool * @return bool
{ * @throws Exception
$data = $this->search('fetch'); */
if (!$data) { public function exists(): bool
return false; {
} $data = $this->search('fetch');
return true; if (!$data) {
} return false;
}
/** return true;
* @return mixed }
* @throws
*/ /**
public function fetchColumn(): mixed * @return mixed
{ * @throws
return $this->search('fetchColumn'); */
} public function fetchColumn(): mixed
{
/** return $this->search('fetchColumn');
* @return mixed }
* @throws
*/ /**
public function rowCount(): int * @return mixed
{ * @throws
$data = $this->search('fetch'); */
public function rowCount(): int
return !$data ? 0 : +current($data); {
} $data = $this->search('fetch');
return !$data ? 0 : +current($data);
/** }
* @param string $method
* @return mixed
* @throws /**
*/ * 执行查询类 SQL 操作,内置断连重试机制
protected function search(string $method): mixed * 当数据库连接断开时自动重试,断开的连接不再归还池中防止污染连接池
{ * @param string $method PDO 结果获取方法名
$client = $this->connection->getConnection(); * @return mixed
try { * @throws
$startTime = microtime(true); */
if (($prepare = $client->prepare($this->sql)) === false) { protected function search(string $method): mixed
throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $client->errorInfo()[2]); {
} $retryCount = 0;
$prepare->execute($this->params); while ($retryCount <= self::MAX_RETRIES) {
$client = $this->connection->getConnection();
$result = $method == 'rowCount' ? $prepare->rowCount() : $prepare->{$method}(PDO::FETCH_ASSOC); try {
$prepare->closeCursor(); $startTime = microtime(true);
if (($prepare = $client->prepare($this->sql)) === false) {
$this->connection->println($startTime, microtime(true), $this->sql, $this->params); throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $client->errorInfo()[2]);
}
return $result;
} catch (Throwable $throwable) { $prepare->execute($this->params);
$this->getLogger()->json_log($throwable);
$result = $method == 'rowCount' ? $prepare->rowCount() : $prepare->{$method}(PDO::FETCH_ASSOC);
if ($this->isRefresh($throwable)) { $prepare->closeCursor();
return $this->search($method);
} $this->connection->println($startTime, microtime(true), $this->sql, $this->params);
$errorMsg = $throwable->getMessage() . PHP_EOL . ' Sql: ' . $this->sql . '.' . json_encode($this->params); $this->connection->release($client);
return $result;
return $this->getLogger()->logCategory($errorMsg . PHP_EOL, 'mysql'); } catch (Throwable $throwable) {
} finally { $this->getLogger()->json_log($throwable);
$this->connection->release($client);
} if ($this->isRefresh($throwable) && $retryCount < self::MAX_RETRIES) {
} $retryCount++;
$this->connection->connections->abandon($this->connection->getName());
continue;
/** }
* @return bool
* @throws $this->connection->release($client);
*/
public function flush(): bool $errorMsg = $throwable->getMessage() . PHP_EOL . ' Sql: ' . $this->sql . '.' . json_encode($this->params);
{
return (bool)$this->_prepare(); return $this->getLogger()->logCategory($errorMsg . PHP_EOL, 'mysql');
} }
}
/** $errorMsg = 'Max retry exceeded for SQL: ' . $this->sql;
* @return int|bool return $this->getLogger()->logCategory($errorMsg, 'mysql');
* @throws }
*/
private function _prepare(): int|bool
{ /**
$client = $this->connection->getConnection(); * @return bool
try { * @throws
$startTime = microtime(true); */
if (($prepare = $client->prepare($this->sql)) === false) { public function flush(): bool
throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $prepare->errorInfo()[2]); {
} return (bool)$this->_prepare();
if ($prepare->execute($this->params) === false) { }
throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $prepare->errorInfo()[2]);
}
/**
$prepare->closeCursor(); * 执行写入类 SQL 操作,内置断连重试机制
* 当数据库连接断开时自动重试,断开的连接不再归还池中防止污染连接池
$result = $client->lastInsertId(); * @return int|bool
* @throws
$this->connection->println($startTime, microtime(true), $this->sql, $this->params); */
if (str_starts_with($this->sql, 'DELETE')) { private function _prepare(): int|bool
return $prepare->rowCount(); {
} $retryCount = 0;
return $result == 0 ? $prepare->rowCount() : (int)$result; while ($retryCount <= self::MAX_RETRIES) {
} catch (Throwable $throwable) { $client = $this->connection->getConnection();
$this->getLogger()->json_log($throwable); try {
$startTime = microtime(true);
if ($this->isRefresh($throwable)) { if (($prepare = $client->prepare($this->sql)) === false) {
return $this->_prepare(); throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $prepare->errorInfo()[2]);
} }
if ($prepare->execute($this->params) === false) {
$errorMsg = $throwable->getMessage() . PHP_EOL . ' Sql: ' . $this->sql . '.' . json_encode($this->params, JSON_UNESCAPED_UNICODE); throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $prepare->errorInfo()[2]);
}
return $this->getLogger()->logCategory($errorMsg . PHP_EOL, 'mysql');
} finally { $prepare->closeCursor();
$this->connection->release($client);
} $result = $client->lastInsertId();
}
$this->connection->println($startTime, microtime(true), $this->sql, $this->params);
if (str_starts_with($this->sql, 'DELETE')) {
/** $this->connection->release($client);
* @param Throwable $throwable return $prepare->rowCount();
* @return bool }
*/
protected function isRefresh(Throwable $throwable): bool $this->connection->release($client);
{ return $result == 0 ? $prepare->rowCount() : (int)$result;
$message = $throwable->getMessage(); } catch (Throwable $throwable) {
$this->getLogger()->json_log($throwable);
// MySQL 错误处理
if (str_contains($message, 'MySQL server has gone away')) { if ($this->isRefresh($throwable) && $retryCount < self::MAX_RETRIES) {
return true; $retryCount++;
} $this->connection->connections->abandon($this->connection->getName());
if (str_contains($message, 'Send of 14 bytes failed with errno=32 Broken pipe')) { continue;
return true; }
}
if (str_contains($message, 'Lost connection to MySQL server during query')) { $this->connection->release($client);
return true;
} $errorMsg = $throwable->getMessage() . PHP_EOL . ' Sql: ' . $this->sql . '.' . json_encode($this->params, JSON_UNESCAPED_UNICODE);
// PostgreSQL 错误处理 return $this->getLogger()->logCategory($errorMsg . PHP_EOL, 'mysql');
if (str_contains($message, 'server closed the connection unexpectedly')) { }
return true; }
}
if (str_contains($message, 'Connection refused')) { $errorMsg = 'Max retry exceeded for SQL: ' . $this->sql;
return true; return $this->getLogger()->logCategory($errorMsg, 'mysql');
} }
if (str_contains($message, 'Broken pipe')) {
return true;
} /**
if (str_contains($message, 'connection to server was lost')) { * @param Throwable $throwable
return true; * @return bool
} */
protected function isRefresh(Throwable $throwable): bool
return false; {
} $message = $throwable->getMessage();
// MySQL 错误处理
/** if (str_contains($message, 'MySQL server has gone away')) {
* @return bool return true;
* @throws }
*/ if (str_contains($message, 'Send of 14 bytes failed with errno=32 Broken pipe')) {
public function delete(): bool return true;
{ }
return $this->_prepare(); if (str_contains($message, 'Lost connection to MySQL server during query')) {
} return true;
}
/** // PostgreSQL 错误处理
* @return int|bool if (str_contains($message, 'server closed the connection unexpectedly')) {
*/ return true;
public function exec(): int|bool }
{ if (str_contains($message, 'Connection refused')) {
return $this->_prepare(); return true;
} }
if (str_contains($message, 'Broken pipe')) {
/** return true;
* @param array $data }
* @return $this if (str_contains($message, 'connection to server was lost')) {
*/ return true;
public function bindValues(array $data = []): static }
{
if (count($data) > 0) { return false;
$this->params = array_merge($this->params, $data); }
}
return $this;
} /**
* @return bool
} * @throws
*/
public function delete(): bool
{
return $this->_prepare();
}
/**
* @return int|bool
*/
public function exec(): int|bool
{
return $this->_prepare();
}
/**
* @param array $data
* @return $this
*/
public function bindValues(array $data = []): static
{
if (count($data) > 0) {
$this->params = array_merge($this->params, $data);
}
return $this;
}
}
+59 -55
View File
@@ -248,61 +248,65 @@ class Connection extends Component
} }
/** /**
* @throws * @throws
* 事务回滚 * 事务回滚
*/ */
public function rollback(): void public function rollback(): void
{ {
$this->storey--; $this->storey--;
if ($this->storey == 0) { if ($this->storey == 0) {
if (!Context::exists($this->cds)) { if (!Context::exists($this->cds)) {
return; return;
} }
$pdo = $this->getTransactionClient(); $pdo = $this->getTransactionClient();
if ($pdo->inTransaction()) { if ($pdo->inTransaction()) {
$pdo->rollback(); $pdo->rollback();
} }
$this->release($pdo); $this->release($pdo);
} Context::remove($this->cds);
} }
}
/**
* @throws /**
* 事务提交 * @throws
*/ * 事务提交
public function commit(): void */
{ public function commit(): void
$this->storey--; {
if ($this->storey == 0) { $this->storey--;
if (!Context::exists($this->cds)) { if ($this->storey == 0) {
return; if (!Context::exists($this->cds)) {
} return;
$pdo = $this->getTransactionClient(); }
if ($pdo->inTransaction()) { $pdo = $this->getTransactionClient();
$pdo->commit(); if ($pdo->inTransaction()) {
} $pdo->commit();
$this->release($pdo); }
} $this->release($pdo);
} Context::remove($this->cds);
}
}
/**
* @return void
* @throws /**
*/ * @return void
public function clear(): void * @throws
{ */
/** @var PDO $pdo */ public function clear(): void
$pdo = Context::get($this->cds); {
if ($pdo === null) { /** @var PDO $pdo */
return; $pdo = Context::get($this->cds);
} if ($pdo === null) {
if ($this->inTransaction()) { return;
$pdo->rollback(); }
} if ($this->inTransaction()) {
$this->release($pdo); $pdo->rollback();
} }
$this->release($pdo);
Context::remove($this->cds);
$this->storey = 0;
}
/** /**