Compare commits

...

39 Commits

Author SHA1 Message Date
as2252258 dce38ad64e eee 2026-07-07 11:28:53 +08:00
as2252258 fe9d054be0 eee 2026-07-07 02:08:19 +08:00
as2252258 abec2ffbff eee 2026-07-07 02:06:57 +08:00
as2252258 bcd75c84ac eee 2026-07-06 21:26:40 +08:00
as2252258 06de50699a eee 2026-07-06 21:25:47 +08:00
as2252258 efb3077bec eee 2026-07-06 21:21:08 +08:00
as2252258 008e6ababa eee 2026-07-06 21:20:58 +08:00
as2252258 99f458f81e eee 2026-07-06 21:18:48 +08:00
as2252258 3e72503b6a eee 2026-07-06 21:15:25 +08:00
as2252258 26395d7d29 eee 2026-07-06 21:13:07 +08:00
as2252258 98c4a9cf0f eee 2026-07-06 21:10:56 +08:00
as2252258 395d31e045 eee 2026-07-06 21:09:37 +08:00
as2252258 efea04878f eee 2026-07-06 21:08:18 +08:00
as2252258 703ca7bb76 eee 2026-07-06 21:06:09 +08:00
as2252258 ade6e48f0b eee 2026-07-06 21:04:28 +08:00
as2252258 39905b77e3 eee 2026-07-03 14:35:45 +08:00
as2252258 fce82ec56c eee 2026-06-30 23:27:42 +08:00
as2252258 2970c3bc6b eee 2026-06-30 23:16:18 +08:00
as2252258 a35d0bb921 eee 2026-06-30 23:15:59 +08:00
as2252258 fce2b8bcdb eee 2026-06-30 23:15:06 +08:00
as2252258 ce92f310a5 eee 2026-06-30 23:14:22 +08:00
as2252258 28fa17ecfb eee 2026-06-30 23:12:17 +08:00
as2252258 9fc910f10f eee 2026-06-30 23:11:55 +08:00
as2252258 0a95e722d6 eee 2026-06-30 23:09:52 +08:00
as2252258 9f2611972f eee 2026-06-30 23:08:13 +08:00
as2252258 b7e59d1c96 eee 2026-06-30 23:06:55 +08:00
as2252258 9b0ee54608 eee 2026-06-30 23:03:51 +08:00
as2252258 763a4baa57 eee 2026-06-30 23:01:40 +08:00
as2252258 fe639bbd1f eee 2026-06-30 23:01:11 +08:00
as2252258 e40de4ee4a eee 2026-06-30 23:00:25 +08:00
as2252258 ffc2af69da eee 2026-06-30 22:54:04 +08:00
as2252258 218a38da48 eee 2026-06-30 22:46:19 +08:00
as2252258 5acb2f4600 eee 2026-06-30 22:43:20 +08:00
as2252258 d6a07446bb eee 2026-06-30 22:35:02 +08:00
as2252258 6c936c3896 eee 2026-06-30 22:31:47 +08:00
as2252258 14448d824a eee 2026-06-30 22:07:04 +08:00
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
6 changed files with 790 additions and 733 deletions
+1
View File
@@ -487,6 +487,7 @@ abstract class Model extends Component implements ModelInterface, ArrayAccess, \
return TRUE; return TRUE;
} }
$generate = SqlBuilder::builder($query)->update($change); $generate = SqlBuilder::builder($query)->update($change);
var_dump($generate, $query->params);
if ($generate === FALSE) { if ($generate === FALSE) {
return FALSE; return FALSE;
} }
+37 -9
View File
@@ -23,6 +23,9 @@ use Throwable;
class Command extends Component class Command extends Component
{ {
/** @var int 数据库操作最大重试次数 */
private const MAX_RETRIES = 2;
public Connection $connection; public Connection $connection;
public ?string $sql = ''; public ?string $sql = '';
public array $params = []; public array $params = [];
@@ -101,12 +104,17 @@ class Command extends Component
/** /**
* @param string $method * 执行查询类 SQL 操作,内置断连重试机制
* 当数据库连接断开时自动重试,断开的连接不再归还池中防止污染连接池
* @param string $method PDO 结果获取方法名
* @return mixed * @return mixed
* @throws * @throws
*/ */
protected function search(string $method): mixed protected function search(string $method): mixed
{ {
$retryCount = 0;
while ($retryCount <= self::MAX_RETRIES) {
$client = $this->connection->getConnection(); $client = $this->connection->getConnection();
try { try {
$startTime = microtime(true); $startTime = microtime(true);
@@ -121,22 +129,28 @@ class Command extends Component
$this->connection->println($startTime, microtime(true), $this->sql, $this->params); $this->connection->println($startTime, microtime(true), $this->sql, $this->params);
$this->connection->release($client);
return $result; return $result;
} catch (Throwable $throwable) { } catch (Throwable $throwable) {
$this->getLogger()->json_log($throwable); $this->getLogger()->json_log($throwable);
if ($this->isRefresh($throwable)) { if ($this->isRefresh($throwable) && $retryCount < self::MAX_RETRIES) {
return $this->search($method); $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); $errorMsg = $throwable->getMessage() . PHP_EOL . ' Sql: ' . $this->sql . '.' . json_encode($this->params);
return $this->getLogger()->logCategory($errorMsg . PHP_EOL, 'mysql'); return $this->getLogger()->logCategory($errorMsg . PHP_EOL, 'mysql');
} finally {
$this->connection->release($client);
} }
} }
return $this->getLogger()->logCategory('Max retry exceeded for SQL: ' . $this->sql, 'mysql');
}
/** /**
* @return bool * @return bool
@@ -149,17 +163,24 @@ class Command extends Component
/** /**
* 执行写入类 SQL 操作,内置断连重试机制
* 当数据库连接断开时自动重试,断开的连接不再归还池中防止污染连接池
* @return int|bool * @return int|bool
* @throws * @throws
*/ */
private function _prepare(): int|bool private function _prepare(): int|bool
{ {
$retryCount = 0;
while ($retryCount <= self::MAX_RETRIES) {
$client = $this->connection->getConnection(); $client = $this->connection->getConnection();
try { try {
$startTime = microtime(true); $startTime = microtime(true);
if (($prepare = $client->prepare($this->sql)) === false) { if (($prepare = $client->prepare($this->sql)) === false) {
throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $prepare->errorInfo()[2]); throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $prepare->errorInfo()[2]);
} }
if ($prepare->execute($this->params) === false) { if ($prepare->execute($this->params) === false) {
throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $prepare->errorInfo()[2]); throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $prepare->errorInfo()[2]);
} }
@@ -170,25 +191,32 @@ class Command extends Component
$this->connection->println($startTime, microtime(true), $this->sql, $this->params); $this->connection->println($startTime, microtime(true), $this->sql, $this->params);
if (str_starts_with($this->sql, 'DELETE')) { if (str_starts_with($this->sql, 'DELETE')) {
$this->connection->release($client);
return $prepare->rowCount(); return $prepare->rowCount();
} }
$this->connection->release($client);
return $result == 0 ? $prepare->rowCount() : (int)$result; return $result == 0 ? $prepare->rowCount() : (int)$result;
} catch (Throwable $throwable) { } catch (Throwable $throwable) {
$this->getLogger()->json_log($throwable); $this->getLogger()->json_log($throwable);
if ($this->isRefresh($throwable)) { if ($this->isRefresh($throwable) && $retryCount < self::MAX_RETRIES) {
return $this->_prepare(); $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); $errorMsg = $throwable->getMessage() . PHP_EOL . ' Sql: ' . $this->sql . '.' . json_encode($this->params, JSON_UNESCAPED_UNICODE);
return $this->getLogger()->logCategory($errorMsg . PHP_EOL, 'mysql'); return $this->getLogger()->logCategory($errorMsg . PHP_EOL, 'mysql');
} finally {
$this->connection->release($client);
} }
} }
return $this->getLogger()->logCategory('Max retry exceeded for SQL: ' . $this->sql, 'mysql');
}
/** /**
* @param Throwable $throwable * @param Throwable $throwable
+8 -4
View File
@@ -154,7 +154,7 @@ class Connection extends Component
/** /**
* @return string * @return string
*/ */
private function getName(): string public function getName(): string
{ {
return strtolower($this->driver) . '.' . $this->cds; return strtolower($this->driver) . '.' . $this->cds;
} }
@@ -264,6 +264,7 @@ class Connection extends Component
$pdo->rollback(); $pdo->rollback();
} }
$this->release($pdo); $this->release($pdo);
Context::remove($this->cds);
} }
} }
@@ -283,6 +284,7 @@ class Connection extends Component
$pdo->commit(); $pdo->commit();
} }
$this->release($pdo); $this->release($pdo);
Context::remove($this->cds);
} }
} }
@@ -302,6 +304,8 @@ class Connection extends Component
$pdo->rollback(); $pdo->rollback();
} }
$this->release($pdo); $this->release($pdo);
Context::remove($this->cds);
$this->storey = 0;
} }
@@ -368,9 +372,9 @@ class Connection extends Component
]; ];
// MySQL 特定的选项 // MySQL 特定的选项
if ($driver === 'mysql') { // if ($driver === 'mysql') {
$options[\PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . $this->charset; // $options[\PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . $this->charset;
} // }
$pdo = new PDO($this->database, $this->cds, $this->username, $this->password, $options, $driver); $pdo = new PDO($this->database, $this->cds, $this->username, $this->password, $options, $driver);
foreach ($this->attributes as $key => $attribute) { foreach ($this->attributes as $key => $attribute) {
+4 -3
View File
@@ -35,7 +35,7 @@ class DatabasesProviders extends Providers
return; return;
} }
foreach ($databases as $key => $database) { foreach ($databases as $key => $database) {
$this->set($key, $this->_settings($database)); $this->set($key, $this->_settings($key, $database));
} }
} }
@@ -64,14 +64,15 @@ class DatabasesProviders extends Providers
/** /**
* @param string $key
* @param array $database * @param array $database
* @return array * @return array
*/ */
private function _settings(array $database): array private function _settings(string $key, array $database): array
{ {
$clientPool = $database['pool'] ?? ['min' => 1, 'max' => 5, 'tick' => 60]; $clientPool = $database['pool'] ?? ['min' => 1, 'max' => 5, 'tick' => 60];
return [ return [
'id' => $database['id'], 'id' => $key,
'cds' => $database['cds'], 'cds' => $database['cds'],
'class' => Connection::class, 'class' => Connection::class,
'username' => $database['username'], 'username' => $database['username'],
+55 -44
View File
@@ -9,6 +9,7 @@ namespace Database;
use JetBrains\PhpStorm\Pure; use JetBrains\PhpStorm\Pure;
use Kiri; use Kiri;
use Kiri\Abstracts\Component; use Kiri\Abstracts\Component;
use Database\Traits\QueryTrait;
/** /**
@@ -52,7 +53,7 @@ class SqlBuilder extends Component
*/ */
public function getCondition(): string public function getCondition(): string
{ {
return $this->where($this->query); return $this->where($this->query->where);
} }
@@ -74,13 +75,13 @@ class SqlBuilder extends Component
*/ */
public function update(array $attributes): bool|string public function update(array $attributes): bool|string
{ {
$conditions = $this->query; $params = $this->query->params;
$this->query = []; $this->query->params = [];
$data = $this->__updateBuilder($this->makeParams($attributes)); $array = $this->makeParams($attributes);
foreach ($conditions as $condition) { foreach ($params as $name => $value) {
$this->query->pushParam($condition); $this->query->pushParam($value);
} }
return $data; return $this->__updateBuilder($array);
} }
@@ -110,7 +111,8 @@ class SqlBuilder extends Component
if (empty($string)) { if (empty($string)) {
return Kiri::getLogger()->logCategory('None data update.'); 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 +124,7 @@ class SqlBuilder extends Component
*/ */
public function insert(array $attributes, bool $isBatch = false): string public function insert(array $attributes, bool $isBatch = false): string
{ {
$update = 'INSERT INTO ' . $this->query; $update = 'INSERT INTO ' . $this->getFromAlias(true);
if ($isBatch === false) { if ($isBatch === false) {
$attributes = [$attributes]; $attributes = [$attributes];
} }
@@ -144,7 +146,7 @@ class SqlBuilder extends Component
*/ */
public function delete(): string public function delete(): string
{ {
return 'DELETE FROM ' . $this->query . $this->make(); return 'DELETE FROM ' . $this->getFromAlias() . ' ' . $this->make();
} }
@@ -152,7 +154,8 @@ class SqlBuilder extends Component
* @param $attributes * @param $attributes
* @return array * @return array
*/ */
#[Pure] private function getFields(array $attributes): array #[Pure]
private function getFields(array $attributes): array
{ {
return array_keys(current($attributes)); return array_keys(current($attributes));
} }
@@ -207,7 +210,7 @@ class SqlBuilder extends Component
public function one(): string public function one(): string
{ {
$this->query->offset(0)->limit(1); $this->query->offset(0)->limit(1);
return $this->makeSelect($this->query) . $this->make() . $this->makeLimit(); return $this->all();
} }
@@ -217,7 +220,7 @@ class SqlBuilder extends Component
*/ */
public function all(): string public function all(): string
{ {
return $this->makeSelect($this->query) . $this->make() . $this->makeLimit(); return $this->makeSelect($this->query->select) . ' ' . $this->make() . ' ' . $this->makeLimit();
} }
@@ -227,7 +230,7 @@ class SqlBuilder extends Component
*/ */
public function count(): string public function count(): string
{ {
return $this->makeSelect(['COUNT(*)']) . $this->make(); return $this->makeSelect(['COUNT(*)']) . ' ' . $this->make();
} }
@@ -237,7 +240,7 @@ class SqlBuilder extends Component
*/ */
public function exists(): string public function exists(): string
{ {
return $this->makeSelect(['0']) . $this->make(); return $this->makeSelect(['0']) . ' ' . $this->make();
} }
@@ -250,7 +253,6 @@ class SqlBuilder extends Component
{ {
$driver = $this->getDriver(); $driver = $this->getDriver();
if (in_array($driver, ['pgsql', 'postgresql'])) { if (in_array($driver, ['pgsql', 'postgresql'])) {
// PostgreSQL 使用 information_schema
$tableName = trim($table, '"`'); $tableName = trim($table, '"`');
return "SELECT return "SELECT
column_name as Field, column_name as Field,
@@ -263,7 +265,6 @@ class SqlBuilder extends Component
WHERE table_name = '$tableName' WHERE table_name = '$tableName'
ORDER BY ordinal_position"; ORDER BY ordinal_position";
} }
// MySQL 使用 SHOW FULL FIELDS
return 'SHOW FULL FIELDS FROM ' . $table; return 'SHOW FULL FIELDS FROM ' . $table;
} }
@@ -274,26 +275,23 @@ class SqlBuilder extends Component
*/ */
private function make(): string private function make(): string
{ {
$select = $this->makeCondition(); return $this->makeCondition() . ' ' . $this->makeGroup() . ' ' . $this->makeOrder();
$select .= $this->makeGroup();
$select .= $this->makeOrder();
return $select;
} }
/** /**
* @param array $select * @param mixed $select 列名数组或 QueryTrait 对象
* @return string * @return string
*/ */
private function makeSelect(array $select = ['*']): string private function makeSelect(mixed $select = ['*']): string
{ {
$select = "SELECT " . implode(',', $select) . " FROM " . $this->query; if (!is_array($select)) {
if ($this->query != "") { $select = ['*'];
$select .= " AS " . $this->query;
} }
if (count($this->query) > 0) { $sql = 'SELECT ' . implode(',', $select) . ' FROM ' . $this->getFromAlias();
$select .= ' ' . implode(' ', $this->query); if ($this->query->join !== []) {
$sql .= ' ' . implode(' ', $this->query->join);
} }
return $select; return $sql;
} }
@@ -302,8 +300,8 @@ class SqlBuilder extends Component
*/ */
private function makeGroup(): string private function makeGroup(): string
{ {
if ($this->query != "") { if ($this->query->group !== '' && $this->query->group !== '0') {
return ' GROUP BY ' . $this->query; return 'GROUP BY ' . $this->query->group;
} }
return ''; return '';
} }
@@ -314,8 +312,8 @@ class SqlBuilder extends Component
*/ */
private function makeOrder(): string private function makeOrder(): string
{ {
if (count($this->query) > 0) { if (count($this->query->order) > 0) {
return ' ORDER BY ' . implode(',', $this->query); return 'ORDER BY ' . implode(',', $this->query->order);
} }
return ''; return '';
} }
@@ -326,7 +324,7 @@ class SqlBuilder extends Component
*/ */
private function makeCondition(): string private function makeCondition(): string
{ {
$condition = $this->where($this->query); $condition = $this->where($this->query->where);
if (empty($condition)) { if (empty($condition)) {
return ''; return '';
} }
@@ -340,14 +338,12 @@ class SqlBuilder extends Component
*/ */
private function makeLimit(): string private function makeLimit(): string
{ {
if ($this->query >= 0 && $this->query >= 1) { if ($this->query->offset >= 0 && $this->query->limit >= 1) {
$driver = $this->getDriver(); $driver = $this->getDriver();
if (in_array($driver, ['pgsql', 'postgresql'])) { if (in_array($driver, ['pgsql', 'postgresql'])) {
// PostgreSQL 使用 LIMIT ... OFFSET ... 语法 return 'LIMIT ' . $this->query->limit . ' OFFSET ' . $this->query->offset;
return ' LIMIT ' . $this->query . ' OFFSET ' . $this->query;
} }
// MySQL 使用 LIMIT offset,limit 语法 return 'LIMIT ' . $this->query->offset . ',' . $this->query->limit;
return ' LIMIT ' . $this->query . ',' . $this->query;
} }
return ''; return '';
} }
@@ -373,7 +369,7 @@ class SqlBuilder extends Component
*/ */
public function truncate(): string public function truncate(): string
{ {
return sprintf('TRUNCATE %s', $this->query); return sprintf('TRUNCATE %s', $this->getFromAlias());
} }
@@ -434,7 +430,6 @@ class SqlBuilder extends Component
private function getDriver(): string private function getDriver(): string
{ {
try { try {
// 尝试从 query 对象获取 connection
if ($this->query instanceof ActiveQuery && $this->query->modelClass !== null) { if ($this->query instanceof ActiveQuery && $this->query->modelClass !== null) {
if ($this->query->modelClass instanceof Model) { if ($this->query->modelClass instanceof Model) {
$connection = $this->query->modelClass->getConnection(); $connection = $this->query->modelClass->getConnection();
@@ -443,7 +438,6 @@ class SqlBuilder extends Component
} }
} }
} }
// 如果是 Db 查询,尝试获取默认 connection
if (method_exists($this->query, 'getConnection')) { if (method_exists($this->query, 'getConnection')) {
$connection = $this->query->getConnection(); $connection = $this->query->getConnection();
if ($connection instanceof Connection) { if ($connection instanceof Connection) {
@@ -451,12 +445,29 @@ class SqlBuilder extends Component
} }
} }
} catch (\Throwable $e) { } catch (\Throwable $e) {
// 忽略错误,返回默认值
$this->getLogger()->json_log($e); $this->getLogger()->json_log($e);
} }
// 默认返回 mysql
return 'mysql'; return 'mysql';
} }
/**
* 获取 FROM 子句(表名 + 别名)
* QueryTrait 对象有 $from 和 $alias 属性
* @return string
*/
private function getFromAlias(bool $insert = false): string
{
$from = $this->query->from;
if ($insert) {
return $from;
}
if ($this->query->alias !== '' && $this->query->alias !== '0') {
$from .= ' AS ' . $this->query->alias;
}
return $from;
}
} }
+12
View File
@@ -116,6 +116,18 @@ abstract class QueryTrait extends Component implements ActiveQueryInterface, ISq
} }
public function __get(string $name)
{
if (property_exists($this, $name)) {
return $this->$name;
}
if (method_exists($this, $name)) {
return $this->$name();
}
return parent::__get($name); // TODO: Change the autogenerated stub
}
/** /**
* Comply constructor. * Comply constructor.
* @throws * @throws