This commit is contained in:
2026-06-24 22:00:50 +08:00
parent 404b511c5f
commit 06074c38c1
+465 -460
View File
@@ -1,465 +1,470 @@
<?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 = []; $conditions = $this->query;
$data = $this->__updateBuilder($this->makeParams($attributes)); $this->query = [];
foreach ($conditions as $condition) { $data = $this->__updateBuilder($this->makeParams($attributes));
$this->query->pushParam($condition); foreach ($conditions as $condition) {
} $this->query->pushParam($condition);
return $data; }
} return $data;
}
/**
* @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 * @param array $attributes
* @return array * @param false $isBatch
* @throws * @return array
*/ * @throws
public function insert(array $attributes, bool $isBatch = false): string */
{ public function insert(array $attributes, bool $isBatch = false): string
$update = 'INSERT INTO ' . $this->query; {
if ($isBatch === false) { $update = 'INSERT INTO ' . $this->getFromAlias();
$attributes = [$attributes]; if ($isBatch === false) {
} $attributes = [$attributes];
$update .= '(' . implode(',', $this->getFields($attributes)) . ') VALUES '; }
$update .= '(' . implode(',', $this->getFields($attributes)) . ') VALUES ';
$keys = [];
foreach ($attributes as $attribute) { $keys = [];
$_keys = $this->makeParams($attribute, true); foreach ($attributes as $attribute) {
$_keys = $this->makeParams($attribute, true);
$keys[] = implode(',', $_keys);
} $keys[] = implode(',', $_keys);
return $update . '(' . implode('),(', $keys) . ')'; }
} return $update . '(' . implode('),(', $keys) . ')';
}
/**
* @return string /**
* @throws * @return string
*/ * @throws
public function delete(): string */
{ public function delete(): string
return 'DELETE FROM ' . $this->query . $this->make(); {
} return 'DELETE FROM ' . $this->getFromAlias() . $this->make();
}
/**
* @param $attributes /**
* @return array * @param $attributes
*/ * @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));
}
/**
* @param array $attributes /**
* @param bool $isInsert * @param array $attributes
* @return array[] * @param bool $isInsert
* a=:b, * @return array[]
*/ * a=:b,
private function makeParams(array $attributes, bool $isInsert = false): array */
{ private function makeParams(array $attributes, bool $isInsert = false): array
$keys = []; {
foreach ($attributes as $key => $value) { $keys = [];
if ($isInsert === true) { foreach ($attributes as $key => $value) {
$keys[] = '?'; if ($isInsert === true) {
$this->query->pushParam($value); $keys[] = '?';
} else { $this->query->pushParam($value);
$keys = $this->resolveParams($key, $value, $keys); } else {
} $keys = $this->resolveParams($key, $value, $keys);
} }
return $keys; }
} return $keys;
}
/**
* @param string $key /**
* @param mixed $value * @param string $key
* @param array $keys * @param mixed $value
* @return array * @param array $keys
*/ * @return array
private function resolveParams(string $key, mixed $value, array $keys): array */
{ private function resolveParams(string $key, mixed $value, array $keys): array
if (is_null($value)) { {
return $keys; if (is_null($value)) {
} return $keys;
if (preg_match('/^[+|-]\s\d+$/', (string)$value)) { }
$keys[] = $key . '=' . $key . ' ' . $value; if (preg_match('/^[+|-]\s\d+$/', (string)$value)) {
} else { $keys[] = $key . '=' . $key . ' ' . $value;
$this->query->pushParam($value); } else {
$keys[] = $key . '= ?'; $this->query->pushParam($value);
} $keys[] = $key . '= ?';
return $keys; }
} return $keys;
}
/**
* @return string /**
* @throws * @return string
*/ * @throws
public function one(): string */
{ public function one(): string
$this->query->offset(0)->limit(1); {
return $this->makeSelect($this->query) . $this->make() . $this->makeLimit(); $this->query->offset(0)->limit(1);
} return $this->makeSelect($this->query) . $this->make() . $this->makeLimit();
}
/**
* @return string /**
* @throws * @return string
*/ * @throws
public function all(): string */
{ public function all(): string
return $this->makeSelect($this->query) . $this->make() . $this->makeLimit(); {
} return $this->makeSelect($this->query) . $this->make() . $this->makeLimit();
}
/**
* @return string /**
* @throws * @return string
*/ * @throws
public function count(): string */
{ public function count(): string
return $this->makeSelect(['COUNT(*)']) . $this->make(); {
} return $this->makeSelect(['COUNT(*)']) . $this->make();
}
/**
* @return string /**
* @throws * @return string
*/ * @throws
public function exists(): string */
{ public function exists(): string
return $this->makeSelect(['0']) . $this->make(); {
} return $this->makeSelect(['0']) . $this->make();
}
/**
* @param string $table /**
* @return string * @param string $table
* @throws * @return string
*/ * @throws
public function columns(string $table): string */
{ public function columns(string $table): string
$driver = $this->getDriver(); {
if (in_array($driver, ['pgsql', 'postgresql'])) { $driver = $this->getDriver();
// PostgreSQL 使用 information_schema if (in_array($driver, ['pgsql', 'postgresql'])) {
$tableName = trim($table, '"`'); $tableName = trim($table, '"`');
return "SELECT return "SELECT
column_name as Field, column_name as Field,
data_type as Type, data_type as Type,
is_nullable as Null, is_nullable as Null,
column_default as Default, column_default as Default,
'' as Extra, '' as Extra,
'' as Key '' as Key
FROM information_schema.columns FROM information_schema.columns
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; }
}
/**
/** * @return string
* @return string * @throws
* @throws */
*/ private function make(): string
private function make(): string {
{ $select = $this->makeCondition();
$select = $this->makeCondition(); $select .= $this->makeGroup();
$select .= $this->makeGroup(); $select .= $this->makeOrder();
$select .= $this->makeOrder(); return $select;
return $select; }
}
/**
/** * @param mixed $select 列名数组或 QueryTrait 对象
* @param array $select * @return string
* @return string */
*/
private function makeSelect(mixed $select = ['*']): string private function makeSelect(mixed $select = ['*']): string
{ {
if (!is_array($select)) { if (!is_array($select)) {
$select = ['*']; $select = ['*'];
} }
$select = "SELECT " . implode(',', $select) . " FROM " . $this->query; $sql = "SELECT " . implode(',', $select) . " FROM " . $this->getFromAlias();
if ($this->query != "") { if ($this->query->join !== []) {
$select .= " AS " . $this->query; $sql .= ' ' . implode(' ', $this->query->join);
} }
if (count($this->query) > 0) { return $sql;
$select .= ' ' . implode(' ', $this->query); }
}
return $select;
} /**
* @return string
*/
/** private function makeGroup(): string
* @return string {
*/ if ($this->query->group !== '' && $this->query->group !== '0') {
private function makeGroup(): string return ' GROUP BY ' . $this->query->group;
{ }
if ($this->query != "") { return '';
return ' GROUP BY ' . $this->query; }
}
return '';
} /**
* @return string
*/
/** private function makeOrder(): string
* @return string {
*/ if (count($this->query->order) > 0) {
private function makeOrder(): string return ' ORDER BY ' . implode(',', $this->query->order);
{ }
if (count($this->query) > 0) { return '';
return ' ORDER BY ' . implode(',', $this->query); }
}
return '';
} /**
* @return string
*/
/** private function makeCondition(): string
* @return string {
*/ $condition = $this->where($this->query->where);
private function makeCondition(): string if (empty($condition)) {
{ return '';
$condition = $this->where($this->query); }
if (empty($condition)) { return ' WHERE ' . $condition;
return ''; }
}
return ' WHERE ' . $condition;
} /**
* @return string
* @throws
/** */
* @return string private function makeLimit(): string
* @throws {
*/ if ($this->query->offset >= 0 && $this->query->limit >= 1) {
private function makeLimit(): string $driver = $this->getDriver();
{ if (in_array($driver, ['pgsql', 'postgresql'])) {
if ($this->query >= 0 && $this->query >= 1) { return ' LIMIT ' . $this->query->limit . ' OFFSET ' . $this->query->offset;
$driver = $this->getDriver(); }
if (in_array($driver, ['pgsql', 'postgresql'])) { return ' LIMIT ' . $this->query->offset . ',' . $this->query->limit;
// PostgreSQL 使用 LIMIT ... OFFSET ... 语法 }
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
*/
/** public function get(bool $isCount = false): string
* @param false $isCount {
* @return string if ($isCount === false) {
* @throws 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 return sprintf('TRUNCATE %s', $this->getFromAlias());
* @throws }
*/
public function truncate(): string
{ /**
return sprintf('TRUNCATE %s', $this->query); * @param array $where
} * @return string
*/
private function where(array $where): string
/** {
* @param array $where if (count($where) < 1) {
* @return string return '';
*/ }
private function where(array $where): string $_tmp = [];
{ foreach ($where as $key => $value) {
if (count($where) < 1) { $_tmp[] = $this->resolveCondition($key, $value);
return ''; }
} return implode(' AND ', $_tmp);
$_tmp = []; }
foreach ($where as $key => $value) {
$_tmp[] = $this->resolveCondition($key, $value);
} /**
return implode(' AND ', $_tmp); * @param string $field
} * @param mixed $condition
* @return string
*/
/** private function resolveCondition(string|int $field, mixed $condition): string
* @param string $field {
* @param mixed $condition if (is_string($field)) {
* @return string $this->query->pushParam($condition);
*/ return $field . ' = ?';
private function resolveCondition(string|int $field, mixed $condition): string } else if (is_string($condition)) {
{ return $condition;
if (is_string($field)) { } else {
$this->query->pushParam($condition); return implode(' AND ', $this->_hashMap($condition));
return $field . ' = ?'; }
} 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 $_array = [];
* @return array foreach ($condition as $key => $value) {
*/ $this->query->pushParam($value);
private function _hashMap(array $condition): array $_array[] = $key . '= ?';
{ }
$_array = []; return $_array;
foreach ($condition as $key => $value) { }
$this->query->pushParam($value);
$_array[] = $key . '= ?'; /**
} * 获取数据库驱动类型
return $_array; * @return string
} * @throws
*/
/** private function getDriver(): string
* 获取数据库驱动类型 {
* @return string try {
* @throws if ($this->query instanceof ActiveQuery && $this->query->modelClass !== null) {
*/ if ($this->query->modelClass instanceof Model) {
private function getDriver(): string $connection = $this->query->modelClass->getConnection();
{ if ($connection instanceof Connection) {
try { return strtolower($connection->driver ?? 'mysql');
// 尝试从 query 对象获取 connection }
if ($this->query instanceof ActiveQuery && $this->query->modelClass !== null) { }
if ($this->query->modelClass instanceof Model) { }
$connection = $this->query->modelClass->getConnection(); if (method_exists($this->query, 'getConnection')) {
if ($connection instanceof Connection) { $connection = $this->query->getConnection();
return strtolower($connection->driver ?? 'mysql'); if ($connection instanceof Connection) {
} return strtolower($connection->driver ?? 'mysql');
} }
} }
// 如果是 Db 查询,尝试获取默认 connection } catch (\Throwable $e) {
if (method_exists($this->query, 'getConnection')) { $this->getLogger()->json_log($e);
$connection = $this->query->getConnection(); }
if ($connection instanceof Connection) { return 'mysql';
return strtolower($connection->driver ?? 'mysql'); }
}
}
} catch (\Throwable $e) { /**
// 忽略错误,返回默认值 * 获取 FROM 子句(表名 + 别名)
$this->getLogger()->json_log($e); * QueryTrait 对象有 $from 和 $alias 属性
} * @return string
// 默认返回 mysql */
return 'mysql'; private function getFromAlias(): string
} {
$from = $this->query->from;
if ($this->query->alias !== '' && $this->query->alias !== '0') {
} $from .= ' AS ' . $this->query->alias;
}
return $from;
}
}