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;
} }
+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');
} }
}
/** return $this->getLogger()->logCategory('Max retry exceeded for SQL: ' . $this->sql, 'mysql');
* @return int|bool }
* @throws
*/
private function _prepare(): int|bool /**
{ * @return bool
$client = $this->connection->getConnection(); * @throws
try { */
$startTime = microtime(true); public function flush(): bool
if (($prepare = $client->prepare($this->sql)) === false) { {
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]);
} /**
* 执行写入类 SQL 操作,内置断连重试机制
$prepare->closeCursor(); * 当数据库连接断开时自动重试,断开的连接不再归还池中防止污染连接池
* @return int|bool
$result = $client->lastInsertId(); * @throws
*/
$this->connection->println($startTime, microtime(true), $this->sql, $this->params); private function _prepare(): int|bool
if (str_starts_with($this->sql, 'DELETE')) { {
return $prepare->rowCount(); $retryCount = 0;
}
while ($retryCount <= self::MAX_RETRIES) {
return $result == 0 ? $prepare->rowCount() : (int)$result; $client = $this->connection->getConnection();
} catch (Throwable $throwable) { try {
$this->getLogger()->json_log($throwable); $startTime = microtime(true);
if (($prepare = $client->prepare($this->sql)) === false) {
if ($this->isRefresh($throwable)) { throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $prepare->errorInfo()[2]);
return $this->_prepare(); }
}
$errorMsg = $throwable->getMessage() . PHP_EOL . ' Sql: ' . $this->sql . '.' . json_encode($this->params, JSON_UNESCAPED_UNICODE); if ($prepare->execute($this->params) === false) {
throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $prepare->errorInfo()[2]);
return $this->getLogger()->logCategory($errorMsg . PHP_EOL, 'mysql'); }
} finally {
$this->connection->release($client); $prepare->closeCursor();
}
} $result = $client->lastInsertId();
$this->connection->println($startTime, microtime(true), $this->sql, $this->params);
/** if (str_starts_with($this->sql, 'DELETE')) {
* @param Throwable $throwable $this->connection->release($client);
* @return bool return $prepare->rowCount();
*/ }
protected function isRefresh(Throwable $throwable): bool
{ $this->connection->release($client);
$message = $throwable->getMessage(); return $result == 0 ? $prepare->rowCount() : (int)$result;
} catch (Throwable $throwable) {
// MySQL 错误处理 $this->getLogger()->json_log($throwable);
if (str_contains($message, 'MySQL server has gone away')) {
return true; if ($this->isRefresh($throwable) && $retryCount < self::MAX_RETRIES) {
} $retryCount++;
if (str_contains($message, 'Send of 14 bytes failed with errno=32 Broken pipe')) { $this->connection->connections->abandon($this->connection->getName());
return true; continue;
} }
if (str_contains($message, 'Lost connection to MySQL server during query')) {
return true; $this->connection->release($client);
}
$errorMsg = $throwable->getMessage() . PHP_EOL . ' Sql: ' . $this->sql . '.' . json_encode($this->params, JSON_UNESCAPED_UNICODE);
// PostgreSQL 错误处理
if (str_contains($message, 'server closed the connection unexpectedly')) { return $this->getLogger()->logCategory($errorMsg . PHP_EOL, 'mysql');
return true; }
} }
if (str_contains($message, 'Connection refused')) {
return true; return $this->getLogger()->logCategory('Max retry exceeded for SQL: ' . $this->sql, '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;
}
}
+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) {
+8 -7
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));
} }
} }
@@ -63,15 +63,16 @@ class DatabasesProviders extends Providers
} }
/** /**
* @param array $database * @param string $key
* @return array * @param array $database
*/ * @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'],
+473 -462
View File
@@ -1,462 +1,473 @@
<?php <?php
/** @noinspection ALL */ /** @noinspection ALL */
declare(strict_types=1); declare(strict_types=1);
namespace Database; 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;
/**
* Class SqlBuilder /**
* @package Database * Class SqlBuilder
*/ * @package Database
class SqlBuilder extends Component */
{ class SqlBuilder extends Component
{
/**
* @var ActiveQuery|Query|ISqlBuilder|null /**
*/ * @var ActiveQuery|Query|ISqlBuilder|null
public ActiveQuery|Query|ISqlBuilder|null $query; */
public ActiveQuery|Query|ISqlBuilder|null $query;
/**
* @param ActiveQuery|Query|ISqlBuilder|null $config /**
*/ * @param ActiveQuery|Query|ISqlBuilder|null $config
public function __construct(ActiveQuery|Query|null|ISqlBuilder $config) */
{ public function __construct(ActiveQuery|Query|null|ISqlBuilder $config)
parent::__construct(); {
parent::__construct();
$this->query = $config;
} $this->query = $config;
}
/**
* @param ISqlBuilder|null $query /**
* @return $this * @param ISqlBuilder|null $query
* @throws * @return $this
*/ * @throws
public static function builder(ISqlBuilder|null $query): static */
{ public static function builder(ISqlBuilder|null $query): static
return new static($query); {
} return new static($query);
}
/**
* @return string /**
* @throws * @return string
*/ * @throws
public function getCondition(): string */
{ public function getCondition(): string
return $this->where($this->query); {
} return $this->where($this->query->where);
}
/**
* @param array $compiler /**
* @return string * @param array $compiler
* @throws * @return string
*/ * @throws
public function hashCompiler(array $compiler): string */
{ public function hashCompiler(array $compiler): string
return $this->where($compiler); {
} return $this->where($compiler);
}
/**
* @param array $attributes /**
* @return bool|array * @param array $attributes
* @throws * @return bool|array
*/ * @throws
public function update(array $attributes): bool|string */
{ public function update(array $attributes): bool|string
$conditions = $this->query; {
$this->query = []; $params = $this->query->params;
$data = $this->__updateBuilder($this->makeParams($attributes)); $this->query->params = [];
foreach ($conditions as $condition) { $array = $this->makeParams($attributes);
$this->query->pushParam($condition); foreach ($params as $name => $value) {
} $this->query->pushParam($value);
return $data; }
} return $this->__updateBuilder($array);
}
/**
* @param array $attributes /**
* @param string $opera * @param array $attributes
* @return bool|array * @param string $opera
* @throws * @return bool|array
*/ * @throws
public function mathematics(array $attributes, string $opera = '+'): bool|string */
{ public function mathematics(array $attributes, string $opera = '+'): bool|string
$string = []; {
foreach ($attributes as $attribute => $value) { $string = [];
$string[] = $attribute . '=' . $attribute . $opera . $value; foreach ($attributes as $attribute => $value) {
} $string[] = $attribute . '=' . $attribute . $opera . $value;
return $this->__updateBuilder($string); }
} return $this->__updateBuilder($string);
}
/**
* @param array $string /**
* @return string|bool * @param array $string
* @throws * @return string|bool
*/ * @throws
private function __updateBuilder(array $string): string|bool */
{ private function __updateBuilder(array $string): string|bool
if (empty($string)) { {
return Kiri::getLogger()->logCategory('None data update.'); 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();
}
/**
* @param array $attributes
* @param false $isBatch /**
* @return array * @param array $attributes
* @throws * @param false $isBatch
*/ * @return array
public function insert(array $attributes, bool $isBatch = false): string * @throws
{ */
$update = 'INSERT INTO ' . $this->query; public function insert(array $attributes, bool $isBatch = false): string
if ($isBatch === false) { {
$attributes = [$attributes]; $update = 'INSERT INTO ' . $this->getFromAlias(true);
} if ($isBatch === false) {
$update .= '(' . implode(',', $this->getFields($attributes)) . ') VALUES '; $attributes = [$attributes];
}
$keys = []; $update .= '(' . implode(',', $this->getFields($attributes)) . ') VALUES ';
foreach ($attributes as $attribute) {
$_keys = $this->makeParams($attribute, true); $keys = [];
foreach ($attributes as $attribute) {
$keys[] = implode(',', $_keys); $_keys = $this->makeParams($attribute, true);
}
return $update . '(' . implode('),(', $keys) . ')'; $keys[] = implode(',', $_keys);
} }
return $update . '(' . implode('),(', $keys) . ')';
}
/**
* @return string
* @throws /**
*/ * @return string
public function delete(): string * @throws
{ */
return 'DELETE FROM ' . $this->query . $this->make(); public function delete(): string
} {
return 'DELETE FROM ' . $this->getFromAlias() . ' ' . $this->make();
}
/**
* @param $attributes
* @return array /**
*/ * @param $attributes
#[Pure] private function getFields(array $attributes): array * @return array
{ */
return array_keys(current($attributes)); #[Pure]
} private function getFields(array $attributes): array
{
return array_keys(current($attributes));
/** }
* @param array $attributes
* @param bool $isInsert
* @return array[] /**
* a=:b, * @param array $attributes
*/ * @param bool $isInsert
private function makeParams(array $attributes, bool $isInsert = false): array * @return array[]
{ * a=:b,
$keys = []; */
foreach ($attributes as $key => $value) { private function makeParams(array $attributes, bool $isInsert = false): array
if ($isInsert === true) { {
$keys[] = '?'; $keys = [];
$this->query->pushParam($value); foreach ($attributes as $key => $value) {
} else { if ($isInsert === true) {
$keys = $this->resolveParams($key, $value, $keys); $keys[] = '?';
} $this->query->pushParam($value);
} } else {
return $keys; $keys = $this->resolveParams($key, $value, $keys);
} }
}
return $keys;
/** }
* @param string $key
* @param mixed $value
* @param array $keys /**
* @return array * @param string $key
*/ * @param mixed $value
private function resolveParams(string $key, mixed $value, array $keys): array * @param array $keys
{ * @return array
if (is_null($value)) { */
return $keys; private function resolveParams(string $key, mixed $value, array $keys): array
} {
if (preg_match('/^[+|-]\s\d+$/', (string)$value)) { if (is_null($value)) {
$keys[] = $key . '=' . $key . ' ' . $value; return $keys;
} else { }
$this->query->pushParam($value); if (preg_match('/^[+|-]\s\d+$/', (string)$value)) {
$keys[] = $key . '= ?'; $keys[] = $key . '=' . $key . ' ' . $value;
} } else {
return $keys; $this->query->pushParam($value);
} $keys[] = $key . '= ?';
}
return $keys;
/** }
* @return string
* @throws
*/ /**
public function one(): string * @return string
{ * @throws
$this->query->offset(0)->limit(1); */
return $this->makeSelect($this->query) . $this->make() . $this->makeLimit(); public function one(): string
} {
$this->query->offset(0)->limit(1);
return $this->all();
/** }
* @return string
* @throws
*/ /**
public function all(): string * @return string
{ * @throws
return $this->makeSelect($this->query) . $this->make() . $this->makeLimit(); */
} public function all(): string
{
return $this->makeSelect($this->query->select) . ' ' . $this->make() . ' ' . $this->makeLimit();
/** }
* @return string
* @throws
*/ /**
public function count(): string * @return string
{ * @throws
return $this->makeSelect(['COUNT(*)']) . $this->make(); */
} public function count(): string
{
return $this->makeSelect(['COUNT(*)']) . ' ' . $this->make();
/** }
* @return string
* @throws
*/ /**
public function exists(): string * @return string
{ * @throws
return $this->makeSelect(['0']) . $this->make(); */
} public function exists(): string
{
return $this->makeSelect(['0']) . ' ' . $this->make();
/** }
* @param string $table
* @return string
* @throws /**
*/ * @param string $table
public function columns(string $table): string * @return string
{ * @throws
$driver = $this->getDriver(); */
if (in_array($driver, ['pgsql', 'postgresql'])) { public function columns(string $table): string
// PostgreSQL 使用 information_schema {
$tableName = trim($table, '"`'); $driver = $this->getDriver();
return "SELECT if (in_array($driver, ['pgsql', 'postgresql'])) {
column_name as Field, $tableName = trim($table, '"`');
data_type as Type, return "SELECT
is_nullable as Null, column_name as Field,
column_default as Default, data_type as Type,
'' as Extra, is_nullable as Null,
'' as Key column_default as Default,
FROM information_schema.columns '' as Extra,
WHERE table_name = '$tableName' '' as Key
ORDER BY ordinal_position"; FROM information_schema.columns
} WHERE table_name = '$tableName'
// MySQL 使用 SHOW FULL FIELDS ORDER BY ordinal_position";
return 'SHOW FULL FIELDS FROM ' . $table; }
} return 'SHOW FULL FIELDS FROM ' . $table;
}
/**
* @return string /**
* @throws * @return string
*/ * @throws
private function make(): string */
{ private function make(): string
$select = $this->makeCondition(); {
$select .= $this->makeGroup(); return $this->makeCondition() . ' ' . $this->makeGroup() . ' ' . $this->makeOrder();
$select .= $this->makeOrder(); }
return $select;
} /**
* @param mixed $select 列名数组或 QueryTrait 对象
/** * @return string
* @param array $select */
* @return string private function makeSelect(mixed $select = ['*']): string
*/ {
private function makeSelect(array $select = ['*']): string if (!is_array($select)) {
{ $select = ['*'];
$select = "SELECT " . implode(',', $select) . " FROM " . $this->query; }
if ($this->query != "") { $sql = 'SELECT ' . implode(',', $select) . ' FROM ' . $this->getFromAlias();
$select .= " AS " . $this->query; if ($this->query->join !== []) {
} $sql .= ' ' . implode(' ', $this->query->join);
if (count($this->query) > 0) { }
$select .= ' ' . implode(' ', $this->query); return $sql;
} }
return $select;
}
/**
* @return string
/** */
* @return string private function makeGroup(): string
*/ {
private function makeGroup(): string if ($this->query->group !== '' && $this->query->group !== '0') {
{ return 'GROUP BY ' . $this->query->group;
if ($this->query != "") { }
return ' GROUP BY ' . $this->query; return '';
} }
return '';
}
/**
* @return string
/** */
* @return string private function makeOrder(): string
*/ {
private function makeOrder(): string if (count($this->query->order) > 0) {
{ return 'ORDER BY ' . implode(',', $this->query->order);
if (count($this->query) > 0) { }
return ' ORDER BY ' . implode(',', $this->query); return '';
} }
return '';
}
/**
* @return string
/** */
* @return string private function makeCondition(): string
*/ {
private function makeCondition(): string $condition = $this->where($this->query->where);
{ if (empty($condition)) {
$condition = $this->where($this->query); return '';
if (empty($condition)) { }
return ''; return 'WHERE ' . $condition;
} }
return ' WHERE ' . $condition;
}
/**
* @return string
/** * @throws
* @return string */
* @throws private function makeLimit(): string
*/ {
private function makeLimit(): string if ($this->query->offset >= 0 && $this->query->limit >= 1) {
{ $driver = $this->getDriver();
if ($this->query >= 0 && $this->query >= 1) { if (in_array($driver, ['pgsql', 'postgresql'])) {
$driver = $this->getDriver(); return 'LIMIT ' . $this->query->limit . ' OFFSET ' . $this->query->offset;
if (in_array($driver, ['pgsql', 'postgresql'])) { }
// PostgreSQL 使用 LIMIT ... OFFSET ... 语法 return 'LIMIT ' . $this->query->offset . ',' . $this->query->limit;
return ' LIMIT ' . $this->query . ' OFFSET ' . $this->query; }
} return '';
// MySQL 使用 LIMIT offset,limit 语法 }
return ' LIMIT ' . $this->query . ',' . $this->query;
}
return ''; /**
} * @param false $isCount
* @return string
* @throws
/** */
* @param false $isCount public function get(bool $isCount = false): string
* @return string {
* @throws if ($isCount === false) {
*/ return $this->all();
public function get(bool $isCount = false): string }
{ return $this->count();
if ($isCount === false) { }
return $this->all();
}
return $this->count(); /**
} * @return string
* @throws
*/
/** public function truncate(): string
* @return string {
* @throws return sprintf('TRUNCATE %s', $this->getFromAlias());
*/ }
public function truncate(): string
{
return sprintf('TRUNCATE %s', $this->query); /**
} * @param array $where
* @return string
*/
/** private function where(array $where): string
* @param array $where {
* @return string if (count($where) < 1) {
*/ return '';
private function where(array $where): string }
{ $_tmp = [];
if (count($where) < 1) { foreach ($where as $key => $value) {
return ''; $_tmp[] = $this->resolveCondition($key, $value);
} }
$_tmp = []; return implode(' AND ', $_tmp);
foreach ($where as $key => $value) { }
$_tmp[] = $this->resolveCondition($key, $value);
}
return implode(' AND ', $_tmp); /**
} * @param string $field
* @param mixed $condition
* @return string
/** */
* @param string $field private function resolveCondition(string|int $field, mixed $condition): string
* @param mixed $condition {
* @return string if (is_string($field)) {
*/ $this->query->pushParam($condition);
private function resolveCondition(string|int $field, mixed $condition): string return $field . ' = ?';
{ } else if (is_string($condition)) {
if (is_string($field)) { return $condition;
$this->query->pushParam($condition); } else {
return $field . ' = ?'; return implode(' AND ', $this->_hashMap($condition));
} else if (is_string($condition)) { }
return $condition; }
} else {
return implode(' AND ', $this->_hashMap($condition));
} /**
} * @param $condition
* @return array
*/
/** private function _hashMap(array $condition): array
* @param $condition {
* @return array $_array = [];
*/ foreach ($condition as $key => $value) {
private function _hashMap(array $condition): array $this->query->pushParam($value);
{ $_array[] = $key . '= ?';
$_array = []; }
foreach ($condition as $key => $value) { return $_array;
$this->query->pushParam($value); }
$_array[] = $key . '= ?';
} /**
return $_array; * 获取数据库驱动类型
} * @return string
* @throws
/** */
* 获取数据库驱动类型 private function getDriver(): string
* @return string {
* @throws try {
*/ if ($this->query instanceof ActiveQuery && $this->query->modelClass !== null) {
private function getDriver(): string if ($this->query->modelClass instanceof Model) {
{ $connection = $this->query->modelClass->getConnection();
try { if ($connection instanceof Connection) {
// 尝试从 query 对象获取 connection return strtolower($connection->driver ?? 'mysql');
if ($this->query instanceof ActiveQuery && $this->query->modelClass !== null) { }
if ($this->query->modelClass instanceof Model) { }
$connection = $this->query->modelClass->getConnection(); }
if ($connection instanceof Connection) { if (method_exists($this->query, 'getConnection')) {
return strtolower($connection->driver ?? 'mysql'); $connection = $this->query->getConnection();
} if ($connection instanceof Connection) {
} return strtolower($connection->driver ?? 'mysql');
} }
// 如果是 Db 查询,尝试获取默认 connection }
if (method_exists($this->query, 'getConnection')) { } catch (\Throwable $e) {
$connection = $this->query->getConnection(); $this->getLogger()->json_log($e);
if ($connection instanceof Connection) { }
return strtolower($connection->driver ?? 'mysql'); return 'mysql';
} }
}
} catch (\Throwable $e) {
// 忽略错误,返回默认值 /**
$this->getLogger()->json_log($e); * 获取 FROM 子句(表名 + 别名)
} * QueryTrait 对象有 $from 和 $alias 属性
// 默认返回 mysql * @return string
return 'mysql'; */
} 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