This commit is contained in:
2023-04-01 00:25:22 +08:00
parent c165f5f205
commit 79db796ba3
3 changed files with 123 additions and 178 deletions
+78 -118
View File
@@ -16,13 +16,13 @@ use Kiri\Abstracts\Component;
*/ */
class SqlBuilder extends Component class SqlBuilder extends Component
{ {
use Builder; use Builder;
public ActiveQuery|Query|null $query; public ActiveQuery|Query|null $query;
/** /**
* @param ISqlBuilder|null $query * @param ISqlBuilder|null $query
* @return $this * @return $this
@@ -32,8 +32,8 @@ class SqlBuilder extends Component
{ {
return new static(['query' => $query]); return new static(['query' => $query]);
} }
/** /**
* @return string * @return string
* @throws Exception * @throws Exception
@@ -42,8 +42,8 @@ class SqlBuilder extends Component
{ {
return $this->conditionToString(); return $this->conditionToString();
} }
/** /**
* @param array $compiler * @param array $compiler
* @return string * @return string
@@ -53,8 +53,8 @@ class SqlBuilder extends Component
{ {
return $this->where($compiler); return $this->where($compiler);
} }
/** /**
* @param array $attributes * @param array $attributes
* @return bool|array * @return bool|array
@@ -63,11 +63,11 @@ class SqlBuilder extends Component
public function update(array $attributes): bool|array public function update(array $attributes): bool|array
{ {
[$string, $array] = $this->builderParams($attributes); [$string, $array] = $this->builderParams($attributes);
return $this->__updateBuilder($string, $array); return $this->__updateBuilder($string, $array);
} }
/** /**
* @param array $attributes * @param array $attributes
* @param string $opera * @param string $opera
@@ -82,8 +82,8 @@ class SqlBuilder extends Component
} }
return $this->__updateBuilder($string, []); return $this->__updateBuilder($string, []);
} }
/** /**
* @param array $string * @param array $string
* @param array $params * @param array $params
@@ -95,19 +95,14 @@ class SqlBuilder extends Component
if (empty($string)) { if (empty($string)) {
return $this->logger->addError('None data update.'); return $this->logger->addError('None data update.');
} }
$condition = $this->conditionToString(); $update = 'UPDATE ' . $this->tableName() . ' SET ' . implode(',', $string) . $this->_prefix();
if (!empty($condition)) {
$condition = ' WHERE ' . $condition;
}
$update = 'UPDATE ' . $this->tableName() . ' SET ' . implode(',', $string) . $condition;
$update .= $this->builderLimit($this->query, false); $update .= $this->builderLimit($this->query, false);
return [$update, $params]; return [$update, $params];
} }
/** /**
* @param array $attributes * @param array $attributes
* @param false $isBatch * @param false $isBatch
@@ -121,33 +116,29 @@ class SqlBuilder extends Component
$attributes = [$attributes]; $attributes = [$attributes];
} }
$update .= '(' . implode(',', $this->getFields($attributes)) . ') VALUES '; $update .= '(' . implode(',', $this->getFields($attributes)) . ') VALUES ';
$order = 0; $order = 0;
$keys = $params = []; $keys = $params = [];
foreach ($attributes as $attribute) { foreach ($attributes as $attribute) {
[$_keys, $params] = $this->builderParams($attribute, true, $params, $order); [$_keys, $params] = $this->builderParams($attribute, true, $params, $order);
$keys[] = implode(',', $_keys); $keys[] = implode(',', $_keys);
$order++; $order++;
} }
return [$update . '(' . implode('),(', $keys) . ')', $params]; return [$update . '(' . implode('),(', $keys) . ')', $params];
} }
/** /**
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public function delete(): string public function delete(): string
{ {
$delete = sprintf('DELETE FROM %s ', $this->query->modelClass->getTable()); return 'DELETE FROM ' . $this->tableName() . ' WHERE ' . $this->_prefix();
$this->query->from = null;
return $delete . ' WHERE ' . $this->_prefix(true);
} }
/** /**
* @param $attributes * @param $attributes
* @return array * @return array
@@ -156,8 +147,8 @@ class SqlBuilder extends Component
{ {
return array_keys(current($attributes)); return array_keys(current($attributes));
} }
/** /**
* @param array $attributes * @param array $attributes
* @param bool $isInsert * @param bool $isInsert
@@ -179,8 +170,8 @@ class SqlBuilder extends Component
} }
return [$keys, $params]; return [$keys, $params];
} }
/** /**
* @param string $key * @param string $key
* @param mixed $value * @param mixed $value
@@ -205,8 +196,8 @@ class SqlBuilder extends Component
} }
return [$keys, $params]; return [$keys, $params];
} }
/** /**
* @return string * @return string
* @throws Exception * @throws Exception
@@ -214,39 +205,31 @@ class SqlBuilder extends Component
public function one(): string public function one(): string
{ {
$this->query->limit(0, 1); $this->query->limit(0, 1);
if (empty($this->query->from) && !empty($this->query->modelClass)) { return $this->_selectPrefix() . $this->_prefix();
$this->query->from($this->query->getTable());
}
return $this->_prefix(true);
} }
/** /**
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public function all(): string public function all(): string
{ {
if (empty($this->query->from) && !empty($this->query->modelClass)) { return $this->_selectPrefix() . $this->_prefix();
$this->query->from($this->query->getTable());
}
return $this->_prefix(true);
} }
/** /**
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public function count(): string public function count(): string
{ {
if (empty($this->query->from) && !empty($this->query->modelClass)) { $this->query->select('COUNT(*)');
$this->query->from($this->query->getTable()); return $this->_selectPrefix() . $this->_prefix();
}
return $this->_prefix(false, true);
} }
/** /**
* @param $table * @param $table
* @return string * @return string
@@ -255,74 +238,50 @@ class SqlBuilder extends Component
{ {
return 'SHOW FULL FIELDS FROM ' . $table; return 'SHOW FULL FIELDS FROM ' . $table;
} }
/** /**
* @param bool $hasOrder
* @param bool $isCount
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
private function _prefix(bool $hasOrder = false, bool $isCount = false): string private function _prefix(): string
{ {
$select = ''; $select = '';
if (!empty($this->query->from)) { if (($condition = $this->conditionToString()) != '') {
$select = $this->_selectPrefix($isCount); $select .= " WHERE ${$condition}";
} }
$select = $this->_wherePrefix($select); if (count($this->query->attributes) > 0) {
if (!empty($this->query->attributes) && is_array($this->query->attributes)) {
$select = strtr($select, $this->query->attributes); $select = strtr($select, $this->query->attributes);
} }
if ($this->query->group != "") {
if (!empty($this->query->group)) { $select .= ' GROUP BY ' . $this->query->group;
$select .= $this->builderGroup($this->query->group);
} }
if ($hasOrder === true && !empty($this->query->order)) { if ($this->query->order != "") {
$select .= $this->builderOrder($this->query->order); $select .= ' ORDER BY ' . implode(',', $this->query->order);
} }
$sql = $select . $this->builderLimit($this->query); return $select . $this->builderLimit($this->query);
if ($this->query->lock) {
$sql .= ' FOR UPDATE';
}
return $sql;
} }
/** /**
* @param $select
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
private function _wherePrefix($select): string private function _selectPrefix(): string
{ {
$condition = $this->conditionToString(); if (count($this->query->select) < 1) {
if (empty($condition)) { $this->query->select = ['*'];
return $select;
} else if (empty($select)) {
return $condition;
} }
return sprintf('%s WHERE %s', $select, $condition); $select = "SELECT " . implode(',', $this->query->select) . " FROM " . $this->tableName();
} if ($this->query->alias != "") {
$select .= " AS " . $this->query->alias;
/**
* @param bool $isCount
* @return string
* @throws Exception
*/
private function _selectPrefix(bool $isCount): string
{
$select = $this->builderSelect($this->query->select, $isCount) . ' FROM ' . $this->tableName();
if (!empty($this->query->alias)) {
$select .= $this->builderAlias($this->query->alias);
} }
if (!empty($this->query->join)) { if (count($this->query->join) > 0) {
$select .= $this->builderJoin($this->query->join); $select .= ' ' . implode(' ', $this->query->join);
} }
return $select; return $select;
} }
/** /**
* @param false $isCount * @param false $isCount
* @return string * @return string
@@ -335,8 +294,8 @@ class SqlBuilder extends Component
} }
return $this->count(); return $this->count();
} }
/** /**
* @return string * @return string
* @throws Exception * @throws Exception
@@ -345,8 +304,8 @@ class SqlBuilder extends Component
{ {
return sprintf('TRUNCATE %s', $this->tableName()); return sprintf('TRUNCATE %s', $this->tableName());
} }
/** /**
* @return string * @return string
* @throws Exception * @throws Exception
@@ -355,8 +314,8 @@ class SqlBuilder extends Component
{ {
return $this->where($this->query->where); return $this->where($this->query->where);
} }
/** /**
* @return string * @return string
* @throws Exception * @throws Exception
@@ -364,15 +323,16 @@ class SqlBuilder extends Component
public function tableName(): string public function tableName(): string
{ {
if ($this->query->from instanceof \Closure) { if ($this->query->from instanceof \Closure) {
$this->query->from = sprintf('(%s)', $this->query->makeClosureFunction($this->query->from)); $this->query->from = '(' . $this->query->makeClosureFunction($this->query->from) . ')';
} }
if ($this->query->from instanceof ActiveQuery) { if ($this->query->from instanceof ActiveQuery) {
$this->query->from = sprintf('%s', SqlBuilder::builder($this->query->from)->get($this->query->from)); $this->query->from = '(' . SqlBuilder::builder($this->query->from)->get($this->query->from) . ')';
} }
if (empty($this->query->from)) { if ($this->query->from == "") {
return $this->query->modelClass->getTable(); return $this->query->modelClass->getTable();
} else {
return $this->query->from;
} }
return $this->query->from;
} }
} }
+39 -54
View File
@@ -22,8 +22,8 @@ use ReflectionException;
*/ */
trait Builder trait Builder
{ {
/** /**
* @param $alias * @param $alias
* @return string * @return string
@@ -32,7 +32,7 @@ trait Builder
{ {
return " AS " . $alias; return " AS " . $alias;
} }
/** /**
* @param $table * @param $table
* @return string * @return string
@@ -45,7 +45,7 @@ trait Builder
} }
return " FROM " . $table; return " FROM " . $table;
} }
/** /**
* @param $join * @param $join
* @return string * @return string
@@ -57,29 +57,18 @@ trait Builder
} }
return ''; return '';
} }
/** /**
* @param null $select * @param string $select
* @param bool $isCount
* @return string * @return string
*/ */
#[Pure] private function builderSelect($select = NULL, bool $isCount = false): string #[Pure] private function builderSelect(string $select = "*"): string
{ {
if ($isCount) { return "SELECT " . $select;
return "SELECT COUNT(*)";
}
if (empty($select)) {
return "SELECT *";
}
if (is_array($select)) {
return "SELECT " . implode(',', $select);
} else {
return "SELECT " . $select;
}
} }
/** /**
* @param $group * @param $group
* @return string * @return string
@@ -91,7 +80,7 @@ trait Builder
} }
return ' GROUP BY ' . $group; return ' GROUP BY ' . $group;
} }
/** /**
* @param $order * @param $order
* @return string * @return string
@@ -104,7 +93,7 @@ trait Builder
return ''; return '';
} }
} }
/** /**
* @param ActiveQuery|Query $query * @param ActiveQuery|Query $query
* @param bool $hasLimit * @param bool $hasLimit
@@ -112,16 +101,14 @@ trait Builder
*/ */
#[Pure] private function builderLimit(ActiveQuery|Query $query, bool $hasLimit = true): string #[Pure] private function builderLimit(ActiveQuery|Query $query, bool $hasLimit = true): string
{ {
if (!is_numeric($query->limit) || $query->limit < 1) { if ($hasLimit) {
return "";
}
if ($query->offset !== null && $hasLimit) {
return ' LIMIT ' . $query->offset . ',' . $query->limit; return ' LIMIT ' . $query->offset . ',' . $query->limit;
} else {
return ' LIMIT ' . $query->limit;
} }
return ' LIMIT ' . $query->limit;
} }
/** /**
* @param $where * @param $where
* @return string * @return string
@@ -134,19 +121,19 @@ trait Builder
if (is_string($where)) return $where; if (is_string($where)) return $where;
foreach ($where as $key => $value) { foreach ($where as $key => $value) {
if (is_null($value)) continue; if (is_null($value)) continue;
if (($_value = $this->resolveCondition($key, $value, $_tmp)) == '') {
$_value = $this->resolveCondition($key, $value, $_tmp); continue;
}
if (empty($_value)) continue;
$_tmp[] = $_value; $_tmp[] = $_value;
} }
if (!empty($_tmp)) { if (!empty($_tmp)) {
return implode(' AND ', $_tmp); return implode(' AND ', $_tmp);
} else {
return '';
} }
return '';
} }
/** /**
* @param $field * @param $field
* @param $condition * @param $condition
@@ -158,16 +145,15 @@ trait Builder
private function resolveCondition($field, $condition, $_tmp): string private function resolveCondition($field, $condition, $_tmp): string
{ {
if (is_string($field)) { if (is_string($field)) {
$_value = sprintf('%s = \'%s\'', $field, $condition); return $field . ' = \'' . $condition . '\'';
} else if (is_string($condition)) { } else if (is_string($condition)) {
$_value = $condition; return $condition;
} else { } else {
$_value = $this->_arrayMap($condition, $_tmp); return $this->_arrayMap($condition, $_tmp);
} }
return $_value;
} }
/** /**
* @param $condition * @param $condition
* @param $array * @param $array
@@ -190,10 +176,10 @@ trait Builder
$builder->oldParams = $array; $builder->oldParams = $array;
} else if (isset(ConditionClassMap::$conditionMap[$stroppier])) { } else if (isset(ConditionClassMap::$conditionMap[$stroppier])) {
$defaultConfig = ConditionClassMap::$conditionMap[$stroppier]; $defaultConfig = ConditionClassMap::$conditionMap[$stroppier];
$class = $defaultConfig['class']; $class = $defaultConfig['class'];
unset($defaultConfig['class']); unset($defaultConfig['class']);
$builder = Kiri::getDi()->make($class, [], $defaultConfig); $builder = Kiri::getDi()->make($class, [], $defaultConfig);
$builder->setValue($condition[2]); $builder->setValue($condition[2]);
$builder->setColumn($condition[1]); $builder->setColumn($condition[1]);
@@ -201,13 +187,13 @@ trait Builder
$builder = Kiri::getDi()->get(HashCondition::class); $builder = Kiri::getDi()->get(HashCondition::class);
$builder->setValue($condition); $builder->setValue($condition);
} }
$array[] = $builder->builder(); $array[] = $builder->builder();
return implode(' AND ', $array); return implode(' AND ', $array);
} }
/** /**
* @param $condition * @param $condition
* @return array * @return array
@@ -217,16 +203,15 @@ trait Builder
$_array = []; $_array = [];
foreach ($condition as $key => $value) { foreach ($condition as $key => $value) {
if (is_null($value)) continue; if (is_null($value)) continue;
$value = is_numeric($value) ? $value : '\'' . $value . '\''; $value = is_numeric($value) ? $value : '\'' . $value . '\'';
if (!is_numeric($key)) { if (!is_numeric($key)) {
$_array[] = sprintf('%s = %s', $key, $value); $_array[] = $key . '=' . $value;
} else { } else {
$_array[] = $value; $_array[] = $value;
} }
} }
return $_array; return $_array;
} }
} }
+6 -6
View File
@@ -31,8 +31,8 @@ trait QueryTrait
public array $select = []; public array $select = [];
public array $join = []; public array $join = [];
public array $order = []; public array $order = [];
public ?int $offset = NULL; public int $offset = 0;
public ?int $limit = NULL; public int $limit = 500;
public string $group = ''; public string $group = '';
public string|Closure|ActiveQuery|null $from = ''; public string|Closure|ActiveQuery|null $from = '';
public string $alias = 't1'; public string $alias = 't1';
@@ -54,14 +54,14 @@ trait QueryTrait
/** /**
* clear * clear
*/ */
public function clear() public function clear(): void
{ {
$this->where = []; $this->where = [];
$this->select = []; $this->select = [];
$this->join = []; $this->join = [];
$this->order = []; $this->order = [];
$this->offset = NULL; $this->offset = 0;
$this->limit = NULL; $this->limit = 500;
$this->group = ''; $this->group = '';
$this->from = ''; $this->from = '';
$this->alias = 't1'; $this->alias = 't1';
@@ -480,7 +480,7 @@ trait QueryTrait
public function select(array|string $column = '*'): static public function select(array|string $column = '*'): static
{ {
if ($column == '*') { if ($column == '*') {
$this->select = $column; $this->select = [$column];
} else { } else {
if (!is_array($column)) { if (!is_array($column)) {
$column = explode(',', $column); $column = explode(',', $column);