Files
kiri-databases/SqlBuilder.php
T

463 lines
11 KiB
PHP
Raw Normal View History

2025-02-17 16:26:32 +08:00
<?php
/** @noinspection ALL */
2022-01-09 03:49:51 +08:00
2023-04-16 01:45:33 +08:00
declare(strict_types=1);
2022-01-09 03:49:51 +08:00
namespace Database;
use JetBrains\PhpStorm\Pure;
2023-12-13 14:47:23 +08:00
use Kiri;
2022-01-09 03:49:51 +08:00
use Kiri\Abstracts\Component;
/**
* Class SqlBuilder
* @package Database
*/
class SqlBuilder extends Component
{
2023-04-07 21:47:15 +08:00
2023-07-26 11:00:08 +08:00
/**
* @var ActiveQuery|Query|ISqlBuilder|null
*/
public ActiveQuery|Query|ISqlBuilder|null $query;
/**
* @param ActiveQuery|Query|ISqlBuilder|null $config
*/
public function __construct(ActiveQuery|Query|null|ISqlBuilder $config)
{
parent::__construct();
$this->query = $config;
}
/**
* @param ISqlBuilder|null $query
* @return $this
2023-12-12 15:35:35 +08:00
* @throws
2023-07-26 11:00:08 +08:00
*/
public static function builder(ISqlBuilder|null $query): static
{
return new static($query);
}
/**
* @return string
2023-12-12 15:35:35 +08:00
* @throws
2023-07-26 11:00:08 +08:00
*/
public function getCondition(): string
{
2024-07-10 16:18:27 +08:00
return $this->where($this->query->getWhere());
2023-07-26 11:00:08 +08:00
}
/**
* @param array $compiler
* @return string
2023-12-12 15:35:35 +08:00
* @throws
2023-07-26 11:00:08 +08:00
*/
public function hashCompiler(array $compiler): string
{
return $this->where($compiler);
}
/**
* @param array $attributes
* @return bool|array
2023-12-12 15:35:35 +08:00
* @throws
2023-07-26 11:00:08 +08:00
*/
public function update(array $attributes): bool|string
{
2024-07-10 16:18:27 +08:00
$conditions = $this->query->getParams();
$this->query->setParams([]);
$data = $this->__updateBuilder($this->makeParams($attributes));
2023-08-17 17:41:26 +08:00
foreach ($conditions as $condition) {
$this->query->pushParam($condition);
}
return $data;
2023-07-26 11:00:08 +08:00
}
/**
* @param array $attributes
* @param string $opera
* @return bool|array
2023-12-12 15:35:35 +08:00
* @throws
2023-07-26 11:00:08 +08:00
*/
public function mathematics(array $attributes, string $opera = '+'): bool|string
{
$string = [];
foreach ($attributes as $attribute => $value) {
$string[] = $attribute . '=' . $attribute . $opera . $value;
}
return $this->__updateBuilder($string);
}
/**
* @param array $string
* @return string|bool
2023-12-12 15:35:35 +08:00
* @throws
2023-07-26 11:00:08 +08:00
*/
private function __updateBuilder(array $string): string|bool
{
if (empty($string)) {
2025-12-31 00:19:29 +08:00
return Kiri::getLogger()->logCategory('None data update.');
2023-07-26 11:00:08 +08:00
}
2024-07-10 16:18:27 +08:00
return 'UPDATE ' . $this->query->getFrom() . ' SET ' . implode(',', $string) . $this->make();
2023-07-26 11:00:08 +08:00
}
/**
* @param array $attributes
* @param false $isBatch
* @return array
2023-12-12 15:35:35 +08:00
* @throws
2023-07-26 11:00:08 +08:00
*/
2023-12-13 18:07:39 +08:00
public function insert(array $attributes, bool $isBatch = false): string
2023-07-26 11:00:08 +08:00
{
2024-07-10 16:18:27 +08:00
$update = 'INSERT INTO ' . $this->query->getFrom();
2023-07-26 11:00:08 +08:00
if ($isBatch === false) {
$attributes = [$attributes];
}
$update .= '(' . implode(',', $this->getFields($attributes)) . ') VALUES ';
2023-12-13 14:47:23 +08:00
$keys = [];
2023-07-26 11:00:08 +08:00
foreach ($attributes as $attribute) {
2023-12-13 14:47:23 +08:00
$_keys = $this->makeParams($attribute, true);
2023-07-26 11:00:08 +08:00
$keys[] = implode(',', $_keys);
}
2023-12-13 18:07:39 +08:00
return $update . '(' . implode('),(', $keys) . ')';
2023-07-26 11:00:08 +08:00
}
/**
* @return string
2023-12-12 15:35:35 +08:00
* @throws
2023-07-26 11:00:08 +08:00
*/
public function delete(): string
{
2024-07-10 16:18:27 +08:00
return 'DELETE FROM ' . $this->query->getFrom() . $this->make();
2023-07-26 11:00:08 +08:00
}
/**
* @param $attributes
* @return array
*/
2023-12-18 18:11:58 +08:00
#[Pure] private function getFields(array $attributes): array
2023-07-26 11:00:08 +08:00
{
return array_keys(current($attributes));
}
/**
* @param array $attributes
* @param bool $isInsert
* @return array[]
* a=:b,
*/
2023-12-13 14:47:23 +08:00
private function makeParams(array $attributes, bool $isInsert = false): array
2023-07-26 11:00:08 +08:00
{
$keys = [];
foreach ($attributes as $key => $value) {
2023-12-13 17:50:42 +08:00
if ($isInsert === true) {
2023-08-14 14:02:16 +08:00
$keys[] = '?';
$this->query->pushParam($value);
2023-07-26 11:00:08 +08:00
} else {
2023-12-13 14:47:23 +08:00
$keys = $this->resolveParams($key, $value, $keys);
2023-07-26 11:00:08 +08:00
}
}
return $keys;
}
/**
* @param string $key
* @param mixed $value
* @param array $keys
* @return array
*/
2023-12-13 14:47:23 +08:00
private function resolveParams(string $key, mixed $value, array $keys): array
2023-07-26 11:00:08 +08:00
{
if (is_null($value)) {
return $keys;
}
2025-02-17 16:29:10 +08:00
if (preg_match('/^[+|-]\s\d+$/', (string)$value)) {
2023-07-26 11:00:08 +08:00
$keys[] = $key . '=' . $key . ' ' . $value;
} else {
2023-08-14 14:02:16 +08:00
$this->query->pushParam($value);
$keys[] = $key . '= ?';
2023-07-26 11:00:08 +08:00
}
return $keys;
}
/**
* @return string
2023-12-12 15:35:35 +08:00
* @throws
2023-07-26 11:00:08 +08:00
*/
public function one(): string
{
2025-05-19 11:19:20 +08:00
$this->query->offset(0)->limit(1);
return $this->makeSelect($this->query->getSelect()) . $this->make() . $this->makeLimit();
2023-07-26 11:00:08 +08:00
}
/**
* @return string
2023-12-12 15:35:35 +08:00
* @throws
2023-07-26 11:00:08 +08:00
*/
public function all(): string
{
2025-05-19 11:19:20 +08:00
return $this->makeSelect($this->query->getSelect()) . $this->make() . $this->makeLimit();
2023-07-26 11:00:08 +08:00
}
/**
* @return string
2023-12-12 15:35:35 +08:00
* @throws
2023-07-26 11:00:08 +08:00
*/
public function count(): string
{
2024-04-26 15:28:40 +08:00
return $this->makeSelect(['COUNT(*)']) . $this->make();
2023-07-26 11:00:08 +08:00
}
2024-04-26 15:36:55 +08:00
/**
* @return string
* @throws
*/
public function exists(): string
{
return $this->makeSelect(['0']) . $this->make();
}
2023-07-26 11:00:08 +08:00
/**
2023-12-18 18:11:58 +08:00
* @param string $table
2023-07-26 11:00:08 +08:00
* @return string
2025-12-16 20:20:08 +08:00
* @throws
2023-07-26 11:00:08 +08:00
*/
2023-12-18 18:11:58 +08:00
public function columns(string $table): string
2023-07-26 11:00:08 +08:00
{
2025-12-16 20:20:08 +08:00
$driver = $this->getDriver();
if (in_array($driver, ['pgsql', 'postgresql'])) {
// PostgreSQL 使用 information_schema
$tableName = trim($table, '"`');
return "SELECT
column_name as Field,
data_type as Type,
is_nullable as Null,
column_default as Default,
'' as Extra,
'' as Key
FROM information_schema.columns
WHERE table_name = '$tableName'
ORDER BY ordinal_position";
}
// MySQL 使用 SHOW FULL FIELDS
2023-07-26 11:00:08 +08:00
return 'SHOW FULL FIELDS FROM ' . $table;
}
/**
* @return string
2023-12-12 15:35:35 +08:00
* @throws
2023-07-26 11:00:08 +08:00
*/
2023-12-13 14:47:23 +08:00
private function make(): string
2023-07-26 11:00:08 +08:00
{
2023-12-13 14:47:23 +08:00
$select = $this->makeCondition();
$select .= $this->makeGroup();
$select .= $this->makeOrder();
2023-07-26 11:00:08 +08:00
return $select;
}
2023-04-07 21:47:15 +08:00
2023-05-20 23:05:38 +08:00
/**
* @param array $select
* @return string
*/
2023-12-13 14:47:23 +08:00
private function makeSelect(array $select = ['*']): string
2023-07-26 11:00:08 +08:00
{
2024-07-10 16:18:27 +08:00
$select = "SELECT " . implode(',', $select) . " FROM " . $this->query->getFrom();
if ($this->query->getAlias() != "") {
$select .= " AS " . $this->query->getAlias();
2023-07-26 11:00:08 +08:00
}
2024-07-10 16:18:27 +08:00
if (count($this->query->getJoin()) > 0) {
$select .= ' ' . implode(' ', $this->query->getJoin());
2023-07-26 11:00:08 +08:00
}
return $select;
}
2023-12-13 14:47:23 +08:00
/**
* @return string
*/
private function makeGroup(): string
{
2024-07-10 16:18:27 +08:00
if ($this->query->getGroup() != "") {
return ' GROUP BY ' . $this->query->getGroup();
2023-12-13 14:47:23 +08:00
}
return '';
}
/**
* @return string
*/
private function makeOrder(): string
{
2024-07-10 16:18:27 +08:00
if (count($this->query->getOrder()) > 0) {
return ' ORDER BY ' . implode(',', $this->query->getOrder());
2023-12-13 14:47:23 +08:00
}
return '';
}
/**
* @return string
*/
private function makeCondition(): string
{
2024-07-10 16:18:27 +08:00
$condition = $this->where($this->query->getWhere());
2023-12-13 14:47:23 +08:00
if (empty($condition)) {
return '';
}
return ' WHERE ' . $condition;
}
2025-12-16 20:20:08 +08:00
/**
* @return string
* @throws
*/
2023-12-13 16:18:12 +08:00
private function makeLimit(): string
{
2024-07-10 16:18:27 +08:00
if ($this->query->getOffset() >= 0 && $this->query->getLimit() >= 1) {
2025-12-16 20:20:08 +08:00
$driver = $this->getDriver();
if (in_array($driver, ['pgsql', 'postgresql'])) {
// PostgreSQL 使用 LIMIT ... OFFSET ... 语法
return ' LIMIT ' . $this->query->getLimit() . ' OFFSET ' . $this->query->getOffset();
}
// MySQL 使用 LIMIT offset,limit 语法
2024-07-10 16:18:27 +08:00
return ' LIMIT ' . $this->query->getOffset() . ',' . $this->query->getLimit();
2023-12-13 16:19:16 +08:00
}
return '';
2023-12-13 16:18:12 +08:00
}
2023-07-26 11:00:08 +08:00
/**
* @param false $isCount
* @return string
2023-12-12 15:35:35 +08:00
* @throws
2023-07-26 11:00:08 +08:00
*/
public function get(bool $isCount = false): string
{
if ($isCount === false) {
return $this->all();
}
return $this->count();
}
/**
* @return string
2023-12-12 15:35:35 +08:00
* @throws
2023-07-26 11:00:08 +08:00
*/
public function truncate(): string
{
2024-07-10 16:18:27 +08:00
return sprintf('TRUNCATE %s', $this->query->getFrom());
2023-07-26 11:00:08 +08:00
}
/**
2023-12-13 14:47:23 +08:00
* @param array $where
2023-07-26 11:00:08 +08:00
* @return string
*/
2023-12-13 14:47:23 +08:00
private function where(array $where): string
2023-07-26 11:00:08 +08:00
{
2023-12-13 14:47:23 +08:00
if (count($where) < 1) {
return '';
}
$_tmp = [];
foreach ($where as $key => $value) {
$_tmp[] = $this->resolveCondition($key, $value);
}
return implode(' AND ', $_tmp);
2023-07-26 11:00:08 +08:00
}
2023-04-07 21:47:15 +08:00
2023-12-13 14:47:23 +08:00
/**
2023-12-18 18:11:58 +08:00
* @param string $field
* @param mixed $condition
2023-12-13 14:47:23 +08:00
* @return string
*/
2023-12-18 23:14:52 +08:00
private function resolveCondition(string|int $field, mixed $condition): string
2023-12-13 14:47:23 +08:00
{
if (is_string($field)) {
$this->query->pushParam($condition);
return $field . ' = ?';
} else if (is_string($condition)) {
return $condition;
} else {
return implode(' AND ', $this->_hashMap($condition));
}
}
/**
* @param $condition
* @return array
*/
2023-12-18 18:11:58 +08:00
private function _hashMap(array $condition): array
2023-12-13 14:47:23 +08:00
{
$_array = [];
foreach ($condition as $key => $value) {
$this->query->pushParam($value);
$_array[] = $key . '= ?';
}
return $_array;
}
2025-12-16 20:20:08 +08:00
/**
* 获取数据库驱动类型
* @return string
* @throws
*/
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();
if ($connection instanceof Connection) {
return strtolower($connection->driver ?? 'mysql');
}
}
}
// 如果是 Db 查询,尝试获取默认 connection
if (method_exists($this->query, 'getConnection')) {
$connection = $this->query->getConnection();
if ($connection instanceof Connection) {
return strtolower($connection->driver ?? 'mysql');
}
}
} catch (\Throwable $e) {
// 忽略错误,返回默认值
2025-12-31 00:19:29 +08:00
$this->getLogger()->json_log($e);
}
2025-12-16 20:20:08 +08:00
// 默认返回 mysql
return 'mysql';
}
2023-12-13 14:47:23 +08:00
2022-01-09 03:49:51 +08:00
}