Compare commits

..

3 Commits

Author SHA1 Message Date
as2252258 06074c38c1 eee 2026-06-24 22:00:50 +08:00
as2252258 404b511c5f eee 2026-06-24 21:53:42 +08:00
as2252258 bf4f8538ed eee 2026-06-24 20:11:10 +08:00
3 changed files with 817 additions and 777 deletions
+86 -58
View File
@@ -23,6 +23,9 @@ use Throwable;
class Command extends Component
{
/** @var int 数据库操作最大重试次数 */
private const MAX_RETRIES = 2;
public Connection $connection;
public ?string $sql = '';
public array $params = [];
@@ -101,40 +104,52 @@ class Command extends Component
/**
* @param string $method
* 执行查询类 SQL 操作,内置断连重试机制
* 当数据库连接断开时自动重试,断开的连接不再归还池中防止污染连接池
* @param string $method PDO 结果获取方法名
* @return mixed
* @throws
*/
protected function search(string $method): mixed
{
$client = $this->connection->getConnection();
try {
$startTime = microtime(true);
if (($prepare = $client->prepare($this->sql)) === false) {
throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $client->errorInfo()[2]);
$retryCount = 0;
while ($retryCount <= self::MAX_RETRIES) {
$client = $this->connection->getConnection();
try {
$startTime = microtime(true);
if (($prepare = $client->prepare($this->sql)) === false) {
throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $client->errorInfo()[2]);
}
$prepare->execute($this->params);
$result = $method == 'rowCount' ? $prepare->rowCount() : $prepare->{$method}(PDO::FETCH_ASSOC);
$prepare->closeCursor();
$this->connection->println($startTime, microtime(true), $this->sql, $this->params);
$this->connection->release($client);
return $result;
} catch (Throwable $throwable) {
$this->getLogger()->json_log($throwable);
if ($this->isRefresh($throwable) && $retryCount < self::MAX_RETRIES) {
$retryCount++;
$this->connection->connections->abandon($this->connection->getName());
continue;
}
$this->connection->release($client);
$errorMsg = $throwable->getMessage() . PHP_EOL . ' Sql: ' . $this->sql . '.' . json_encode($this->params);
return $this->getLogger()->logCategory($errorMsg . PHP_EOL, 'mysql');
}
$prepare->execute($this->params);
$result = $method == 'rowCount' ? $prepare->rowCount() : $prepare->{$method}(PDO::FETCH_ASSOC);
$prepare->closeCursor();
$this->connection->println($startTime, microtime(true), $this->sql, $this->params);
return $result;
} catch (Throwable $throwable) {
$this->getLogger()->json_log($throwable);
if ($this->isRefresh($throwable)) {
return $this->search($method);
}
$errorMsg = $throwable->getMessage() . PHP_EOL . ' Sql: ' . $this->sql . '.' . json_encode($this->params);
return $this->getLogger()->logCategory($errorMsg . PHP_EOL, 'mysql');
} finally {
$this->connection->release($client);
}
$errorMsg = 'Max retry exceeded for SQL: ' . $this->sql;
return $this->getLogger()->logCategory($errorMsg, 'mysql');
}
@@ -149,44 +164,57 @@ class Command extends Component
/**
* 执行写入类 SQL 操作,内置断连重试机制
* 当数据库连接断开时自动重试,断开的连接不再归还池中防止污染连接池
* @return int|bool
* @throws
*/
private function _prepare(): int|bool
{
$client = $this->connection->getConnection();
try {
$startTime = microtime(true);
if (($prepare = $client->prepare($this->sql)) === false) {
throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $prepare->errorInfo()[2]);
$retryCount = 0;
while ($retryCount <= self::MAX_RETRIES) {
$client = $this->connection->getConnection();
try {
$startTime = microtime(true);
if (($prepare = $client->prepare($this->sql)) === false) {
throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $prepare->errorInfo()[2]);
}
if ($prepare->execute($this->params) === false) {
throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $prepare->errorInfo()[2]);
}
$prepare->closeCursor();
$result = $client->lastInsertId();
$this->connection->println($startTime, microtime(true), $this->sql, $this->params);
if (str_starts_with($this->sql, 'DELETE')) {
$this->connection->release($client);
return $prepare->rowCount();
}
$this->connection->release($client);
return $result == 0 ? $prepare->rowCount() : (int)$result;
} catch (Throwable $throwable) {
$this->getLogger()->json_log($throwable);
if ($this->isRefresh($throwable) && $retryCount < self::MAX_RETRIES) {
$retryCount++;
$this->connection->connections->abandon($this->connection->getName());
continue;
}
$this->connection->release($client);
$errorMsg = $throwable->getMessage() . PHP_EOL . ' Sql: ' . $this->sql . '.' . json_encode($this->params, JSON_UNESCAPED_UNICODE);
return $this->getLogger()->logCategory($errorMsg . PHP_EOL, 'mysql');
}
if ($prepare->execute($this->params) === false) {
throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $prepare->errorInfo()[2]);
}
$prepare->closeCursor();
$result = $client->lastInsertId();
$this->connection->println($startTime, microtime(true), $this->sql, $this->params);
if (str_starts_with($this->sql, 'DELETE')) {
return $prepare->rowCount();
}
return $result == 0 ? $prepare->rowCount() : (int)$result;
} catch (Throwable $throwable) {
$this->getLogger()->json_log($throwable);
if ($this->isRefresh($throwable)) {
return $this->_prepare();
}
$errorMsg = $throwable->getMessage() . PHP_EOL . ' Sql: ' . $this->sql . '.' . json_encode($this->params, JSON_UNESCAPED_UNICODE);
return $this->getLogger()->logCategory($errorMsg . PHP_EOL, 'mysql');
} finally {
$this->connection->release($client);
}
$errorMsg = 'Max retry exceeded for SQL: ' . $this->sql;
return $this->getLogger()->logCategory($errorMsg, 'mysql');
}
+4
View File
@@ -264,6 +264,7 @@ class Connection extends Component
$pdo->rollback();
}
$this->release($pdo);
Context::remove($this->cds);
}
}
@@ -283,6 +284,7 @@ class Connection extends Component
$pdo->commit();
}
$this->release($pdo);
Context::remove($this->cds);
}
}
@@ -302,6 +304,8 @@ class Connection extends Component
$pdo->rollback();
}
$this->release($pdo);
Context::remove($this->cds);
$this->storey = 0;
}
+37 -29
View File
@@ -9,6 +9,7 @@ namespace Database;
use JetBrains\PhpStorm\Pure;
use Kiri;
use Kiri\Abstracts\Component;
use Database\Traits\QueryTrait;
/**
@@ -52,7 +53,7 @@ class SqlBuilder extends Component
*/
public function getCondition(): string
{
return $this->where($this->query);
return $this->where($this->query->where);
}
@@ -110,7 +111,7 @@ class SqlBuilder extends Component
if (empty($string)) {
return Kiri::getLogger()->logCategory('None data update.');
}
return 'UPDATE ' . $this->query . ' SET ' . implode(',', $string) . $this->make();
return 'UPDATE ' . $this->getFromAlias() . ' SET ' . implode(',', $string) . $this->make();
}
@@ -122,7 +123,7 @@ class SqlBuilder extends Component
*/
public function insert(array $attributes, bool $isBatch = false): string
{
$update = 'INSERT INTO ' . $this->query;
$update = 'INSERT INTO ' . $this->getFromAlias();
if ($isBatch === false) {
$attributes = [$attributes];
}
@@ -144,7 +145,7 @@ class SqlBuilder extends Component
*/
public function delete(): string
{
return 'DELETE FROM ' . $this->query . $this->make();
return 'DELETE FROM ' . $this->getFromAlias() . $this->make();
}
@@ -250,7 +251,6 @@ class SqlBuilder extends Component
{
$driver = $this->getDriver();
if (in_array($driver, ['pgsql', 'postgresql'])) {
// PostgreSQL 使用 information_schema
$tableName = trim($table, '"`');
return "SELECT
column_name as Field,
@@ -263,7 +263,6 @@ class SqlBuilder extends Component
WHERE table_name = '$tableName'
ORDER BY ordinal_position";
}
// MySQL 使用 SHOW FULL FIELDS
return 'SHOW FULL FIELDS FROM ' . $table;
}
@@ -281,19 +280,19 @@ class SqlBuilder extends Component
}
/**
* @param array $select
* @param mixed $select 列名数组或 QueryTrait 对象
* @return string
*/
private function makeSelect(array $select = ['*']): string
private function makeSelect(mixed $select = ['*']): string
{
$select = "SELECT " . implode(',', $select) . " FROM " . $this->query;
if ($this->query != "") {
$select .= " AS " . $this->query;
if (!is_array($select)) {
$select = ['*'];
}
if (count($this->query) > 0) {
$select .= ' ' . implode(' ', $this->query);
$sql = "SELECT " . implode(',', $select) . " FROM " . $this->getFromAlias();
if ($this->query->join !== []) {
$sql .= ' ' . implode(' ', $this->query->join);
}
return $select;
return $sql;
}
@@ -302,8 +301,8 @@ class SqlBuilder extends Component
*/
private function makeGroup(): string
{
if ($this->query != "") {
return ' GROUP BY ' . $this->query;
if ($this->query->group !== '' && $this->query->group !== '0') {
return ' GROUP BY ' . $this->query->group;
}
return '';
}
@@ -314,8 +313,8 @@ class SqlBuilder extends Component
*/
private function makeOrder(): string
{
if (count($this->query) > 0) {
return ' ORDER BY ' . implode(',', $this->query);
if (count($this->query->order) > 0) {
return ' ORDER BY ' . implode(',', $this->query->order);
}
return '';
}
@@ -326,7 +325,7 @@ class SqlBuilder extends Component
*/
private function makeCondition(): string
{
$condition = $this->where($this->query);
$condition = $this->where($this->query->where);
if (empty($condition)) {
return '';
}
@@ -340,14 +339,12 @@ class SqlBuilder extends Component
*/
private function makeLimit(): string
{
if ($this->query >= 0 && $this->query >= 1) {
if ($this->query->offset >= 0 && $this->query->limit >= 1) {
$driver = $this->getDriver();
if (in_array($driver, ['pgsql', 'postgresql'])) {
// PostgreSQL 使用 LIMIT ... OFFSET ... 语法
return ' LIMIT ' . $this->query . ' OFFSET ' . $this->query;
return ' LIMIT ' . $this->query->limit . ' OFFSET ' . $this->query->offset;
}
// MySQL 使用 LIMIT offset,limit 语法
return ' LIMIT ' . $this->query . ',' . $this->query;
return ' LIMIT ' . $this->query->offset . ',' . $this->query->limit;
}
return '';
}
@@ -373,7 +370,7 @@ class SqlBuilder extends Component
*/
public function truncate(): string
{
return sprintf('TRUNCATE %s', $this->query);
return sprintf('TRUNCATE %s', $this->getFromAlias());
}
@@ -434,7 +431,6 @@ class SqlBuilder extends Component
private function getDriver(): string
{
try {
// 尝试从 query 对象获取 connection
if ($this->query instanceof ActiveQuery && $this->query->modelClass !== null) {
if ($this->query->modelClass instanceof Model) {
$connection = $this->query->modelClass->getConnection();
@@ -443,7 +439,6 @@ class SqlBuilder extends Component
}
}
}
// 如果是 Db 查询,尝试获取默认 connection
if (method_exists($this->query, 'getConnection')) {
$connection = $this->query->getConnection();
if ($connection instanceof Connection) {
@@ -451,12 +446,25 @@ class SqlBuilder extends Component
}
}
} catch (\Throwable $e) {
// 忽略错误,返回默认值
$this->getLogger()->json_log($e);
}
// 默认返回 mysql
return 'mysql';
}
/**
* 获取 FROM 子句(表名 + 别名)
* QueryTrait 对象有 $from 和 $alias 属性
* @return string
*/
private function getFromAlias(): string
{
$from = $this->query->from;
if ($this->query->alias !== '' && $this->query->alias !== '0') {
$from .= ' AS ' . $this->query->alias;
}
return $from;
}
}