This commit is contained in:
as2252258@163.com
2021-03-27 03:29:38 +08:00
parent 0e10ee2f75
commit 08f8f417d5
3 changed files with 511 additions and 494 deletions
+257 -254
View File
@@ -21,300 +21,303 @@ use Snowflake\Snowflake;
class ActiveQuery extends Component implements ISqlBuilder class ActiveQuery extends Component implements ISqlBuilder
{ {
use QueryTrait; use QueryTrait;
/** @var array */ /** @var array */
public array $with = []; public array $with = [];
/** @var bool */ /** @var bool */
public bool $asArray = FALSE; public bool $asArray = FALSE;
/** @var bool */ /** @var bool */
public bool $useCache = FALSE; public bool $useCache = FALSE;
/** /**
* @var Connection|null * @var Connection|null
*/ */
public ?Connection $db = NULL; public ?Connection $db = NULL;
/** /**
* @var array * @var array
* 参数绑定 * 参数绑定
*/ */
public array $attributes = []; public array $attributes = [];
private SqlBuilder $builder; private SqlBuilder $builder;
/** /**
* Comply constructor. * Comply constructor.
* @param $model * @param $model
* @param array $config * @param array $config
* @throws * @throws
*/ */
public function __construct($model, $config = []) public function __construct($model, $config = [])
{ {
if (!is_object($model)) { if (!is_object($model)) {
$model = Snowflake::createObject($model); $model = Snowflake::createObject($model);
} }
$this->modelClass = $model; $this->modelClass = $model;
$this->builder = SqlBuilder::builder($this); $this->builder = SqlBuilder::builder($this);
parent::__construct($config); parent::__construct($config);
} }
/** /**
* 清除不完整数据 * 清除不完整数据
*/ */
public function clear() public function clear()
{ {
$this->db = null; $this->db = null;
$this->useCache = false; $this->useCache = false;
$this->with = []; $this->with = [];
} }
/** /**
* @param $key * @param $key
* @param $value * @param $value
* @return $this * @return $this
*/ */
public function addParam($key, $value): static public function addParam($key, $value): static
{ {
$this->attributes[$key] = $value; $this->attributes[$key] = $value;
return $this; return $this;
} }
/** /**
* @param array $values * @param array $values
* @return $this * @return $this
*/ */
public function addParams(array $values): static public function addParams(array $values): static
{ {
foreach ($values as $key => $val) { foreach ($values as $key => $val) {
$this->addParam($key, $val); $this->addParam($key, $val);
} }
return $this; return $this;
} }
/** /**
* @param $name * @param $name
* @return $this * @return $this
*/ */
public function with($name): static public function with($name): static
{ {
if (empty($name)) { if (empty($name)) {
return $this; return $this;
} }
if (is_string($name)) { if (is_string($name)) {
$name = explode(',', $name); $name = explode(',', $name);
} }
foreach ($name as $key => $val) { foreach ($name as $key => $val) {
array_push($this->with, $val); array_push($this->with, $val);
} }
return $this; return $this;
} }
/** /**
* @param bool $isArray * @param bool $isArray
* @return $this * @return $this
*/ */
public function asArray($isArray = TRUE): static public function asArray($isArray = TRUE): static
{ {
$this->asArray = $isArray; $this->asArray = $isArray;
return $this; return $this;
} }
/** /**
* @param $sql * @param $sql
* @return mixed * @return mixed
*/ */
public function execute($sql): Command public function execute($sql): Command
{ {
return $this->modelClass::getDb()->createCommand($sql); return $this->modelClass::getDb()->createCommand($sql);
} }
/** /**
* @return ActiveRecord|array|null * @return ActiveRecord|array|null
* @throws Exception * @throws Exception
*/ */
public function first(): ActiveRecord|array|null public function first(): ActiveRecord|array|null
{ {
$data = $this->execute($this->builder->one())->one(); $data = $this->execute($this->builder->one())->one();
if (empty($data)) { if (empty($data)) {
return NULL; return NULL;
} }
$newModel = $this->modelClass; $newModel = $this->modelClass;
$newModel = $this->populate($newModel, $data); $newModel = $this->populate($newModel, $data);
if ($this->asArray) { if ($this->asArray) {
return $newModel->toArray(); return $newModel->toArray();
} }
return $newModel; return $newModel;
} }
/** /**
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public function toSql(): string public function toSql(): string
{ {
return $this->builder->get(); return $this->builder->get();
} }
/** /**
* @return array|Collection * @return array|Collection
*/ */
public function get(): Collection|array public function get(): Collection|array
{ {
return $this->all(); return $this->all();
} }
/** /**
* @throws Exception * @throws Exception
*/ */
public function flush(): array|bool|int|string|null public function flush(): array|bool|int|string|null
{ {
return $this->execute($this->builder->truncate())->exec(); return $this->execute($this->builder->truncate())->exec();
} }
/** /**
* @param int $size * @param int $size
* @param callable $callback * @param callable $callback
* @return Pagination * @return Pagination
* @throws Exception * @throws Exception
*/ */
public function page(int $size, callable $callback): Pagination public function page(int $size, callable $callback): Pagination
{ {
$pagination = new Pagination($this); $pagination = new Pagination($this);
$pagination->setOffset(0); $pagination->setOffset(0);
$pagination->setLimit($size); $pagination->setLimit($size);
$pagination->setCallback($callback); $pagination->setCallback($callback);
return $pagination; return $pagination;
} }
/** /**
* @param string $field * @param string $field
* @param string $setKey * @param string $setKey
* *
* @return array|null * @return array|null
* @throws Exception * @throws Exception
*/ */
public function column(string $field, $setKey = ''): ?array public function column(string $field, $setKey = ''): ?array
{ {
return $this->all()->column($field, $setKey); return $this->all()->column($field, $setKey);
} }
/** /**
* @return array|Collection * @return array|Collection
* @throws * @throws
*/ */
public function all(): Collection|array public function all(): Collection|array
{ {
$data = $this->execute($this->builder->all())->all(); $data = $this->execute($this->builder->all())->all();
$collect = new Collection($this, $data, $this->modelClass); $collect = new Collection($this, $data, $this->modelClass);
if ($this->asArray) { if ($this->asArray) {
return $collect->toArray(); return $collect->toArray();
} }
return $collect; return $collect;
} }
/** /**
* @param ActiveRecord $model * @param ActiveRecord $model
* @param $data * @param $data
* @return ActiveRecord * @return ActiveRecord
* @throws Exception * @throws Exception
*/ */
public function populate(ActiveRecord $model, $data): ActiveRecord public function populate(ActiveRecord $model, $data): ActiveRecord
{ {
return $this->getWith($model::populate($data)); return $this->getWith($model::populate($data));
} }
/** /**
* @param ActiveRecord $model * @param ActiveRecord $model
* @return ActiveRecord * @return ActiveRecord
*/ */
public function getWith(ActiveRecord $model): ActiveRecord public function getWith(ActiveRecord $model): ActiveRecord
{ {
if (empty($this->with) || !is_array($this->with)) { if (empty($this->with) || !is_array($this->with)) {
return $model; return $model;
} }
return $model->setWith($this->with); return $model->setWith($this->with);
} }
/** /**
* @return int * @return int
* @throws Exception * @throws Exception
*/ */
public function count(): int public function count(): int
{ {
$data = $this->execute($this->builder->count())->one(); $data = $this->execute($this->builder->count())->one();
if ($data && is_array($data)) { if ($data && is_array($data)) {
return (int)array_shift($data); return (int)array_shift($data);
} }
return 0; return 0;
} }
/** /**
* @param array $data * @param array $data
* @return array|Command|bool|int|string * @return array|Command|bool|int|string
* @throws Exception * @throws Exception
*/ */
public function batchUpdate(array $data): Command|array|bool|int|string public function batchUpdate(array $data): Command|array|bool|int|string
{ {
$generate = $this->builder->update($data); $generate = $this->builder->update($data);
if (is_bool($generate)) { if (is_bool($generate)) {
return $generate; return $generate;
} }
return $this->execute(...$generate)->exec(); return $this->execute(...$generate)->exec();
} }
/** /**
* @param array $data * @param array $data
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function batchInsert(array $data): bool public function batchInsert(array $data): bool
{ {
return $this->execute($this->builder->insert($data, true))->exec(); return $this->execute($this->builder->insert($data, true))->exec();
} }
/** /**
* @param $filed * @param $filed
* *
* @return null * @return null
* @throws Exception * @throws Exception
*/ */
public function value($filed) public function value($filed)
{ {
return $this->first()[$filed] ?? null; return $this->first()[$filed] ?? null;
} }
/** /**
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function exists(): bool public function exists(): bool
{ {
return $this->execute($this->builder->one())->fetchColumn() !== false; return $this->execute($this->builder->one())->fetchColumn() !== false;
} }
/** /**
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function delete(): bool public function delete($getSql = false): string|bool
{ {
return $this->execute($this->builder->all())->delete(); if ($getSql) {
} return $this->builder->delete();
}
return $this->execute($this->builder->all())->delete();
}
} }
+253 -239
View File
@@ -17,292 +17,306 @@ use Snowflake\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 $query * @param $query
* @return $this * @return $this
*/ */
public static function builder(ISqlBuilder|null $query): static public static function builder(ISqlBuilder|null $query): static
{ {
return new static(['query' => $query]); return new static(['query' => $query]);
} }
/** /**
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public function getCondition(): string public function getCondition(): string
{ {
return $this->conditionToString(); return $this->conditionToString();
} }
/** /**
* @param array $attributes * @param array $attributes
* @return bool|array * @return bool|array
* @throws Exception * @throws Exception
*/ */
public function update(array $attributes): bool|array public function update(array $attributes): bool|array
{ {
[$string, $array] = $this->builderParams($attributes); [$string, $array] = $this->builderParams($attributes);
if (empty($string) || empty($array)) { if (empty($string) || empty($array)) {
return $this->addError('None data update.'); return $this->addError('None data update.');
} }
$condition = $this->conditionToString(); $condition = $this->conditionToString();
if (!empty($condition)) { if (!empty($condition)) {
$condition = ' WHERE ' . $condition; $condition = ' WHERE ' . $condition;
} }
$update = 'UPDATE ' . $this->tableName() . ' SET ' . implode(',', $string) . $condition; $update = 'UPDATE ' . $this->tableName() . ' SET ' . implode(',', $string) . $condition;
$update .= $this->builderLimit($this->query); $update .= $this->builderLimit($this->query);
return [$update, $array]; return [$update, $array];
} }
/** /**
* @param array $attributes * @param array $attributes
* @param string $opera * @param string $opera
* @return bool|array * @return bool|array
* @throws Exception * @throws Exception
*/ */
public function mathematics(array $attributes, $opera = '+'): bool|array public function mathematics(array $attributes, $opera = '+'): bool|array
{ {
$string = $array = []; $string = $array = [];
foreach ($attributes as $attribute => $value) { foreach ($attributes as $attribute => $value) {
$string[] = $attribute . '=' . $attribute . $opera . $value; $string[] = $attribute . '=' . $attribute . $opera . $value;
} }
if (empty($string)) { if (empty($string)) {
return $this->addError('None data update.'); return $this->addError('None data update.');
} }
$condition = $this->conditionToString(); $condition = $this->conditionToString();
if (!empty($condition)) { if (!empty($condition)) {
$condition = ' WHERE ' . $condition; $condition = ' WHERE ' . $condition;
} }
$update = 'UPDATE ' . $this->tableName() . ' SET ' . implode(',', $string) . $condition; $update = 'UPDATE ' . $this->tableName() . ' SET ' . implode(',', $string) . $condition;
$update .= $this->builderLimit($this->query); $update .= $this->builderLimit($this->query);
return [$update, []]; return [$update, []];
} }
/** /**
* @param array $attributes * @param array $attributes
* @param false $isBatch * @param false $isBatch
* @return array * @return array
* @throws Exception * @throws Exception
*/ */
public function insert(array $attributes, $isBatch = false): array public function insert(array $attributes, $isBatch = false): array
{ {
$update = sprintf('INSERT INTO %s', $this->tableName()); $update = sprintf('INSERT INTO %s', $this->tableName());
if ($isBatch === false) { if ($isBatch === false) {
$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];
} }
/** /**
* @param $attributes * @return string
* @return array * @throws Exception
*/ */
#[Pure] private function getFields($attributes): array public function delete()
{ {
return array_keys(current($attributes)); $delete = sprintf('DELETE FROM %s ', $this->query->modelClass::getTable());
}
$this->query->from = null;
return $delete . $this->_prefix(true);
}
/** /**
* @param array $attributes * @param $attributes
* @param bool $isInsert * @return array
* @param array $params */
* @param int $order #[Pure] private function getFields($attributes): array
* @return array[] {
* a=:b, return array_keys(current($attributes));
*/ }
private function builderParams(array $attributes, bool $isInsert = false, $params = [], $order = 0): array
{
$keys = [];
foreach ($attributes as $key => $value) {
if ($isInsert === true) {
$keys[] = ':' . $key . $order;
} else {
$keys[] = $key . '=:' . $key . $order;
}
$params[$key . $order] = $value;
}
return [$keys, $params];
}
/** /**
* @return string * @param array $attributes
* @throws Exception * @param bool $isInsert
*/ * @param array $params
public function one(): string * @param int $order
{ * @return array[]
$this->query->limit(0, 1); * a=:b,
return $this->_prefix(true); */
} private function builderParams(array $attributes, bool $isInsert = false, $params = [], $order = 0): array
{
$keys = [];
foreach ($attributes as $key => $value) {
if ($isInsert === true) {
$keys[] = ':' . $key . $order;
} else {
$keys[] = $key . '=:' . $key . $order;
}
$params[$key . $order] = $value;
}
return [$keys, $params];
}
/** /**
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public function all(): string public function one(): string
{ {
return $this->_prefix(true); $this->query->limit(0, 1);
} return $this->_prefix(true);
}
/** /**
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public function count(): string public function all(): string
{ {
return $this->_prefix(); return $this->_prefix(true);
} }
/** /**
* @param $table * @return string
* @return string * @throws Exception
*/ */
public function columns($table): string public function count(): string
{ {
return 'SHOW FULL FIELDS FROM ' . $table; return $this->_prefix();
} }
/** /**
* @param bool $hasOrder * @param $table
* @return string * @return string
* @throws Exception */
*/ public function columns($table): string
private function _prefix($hasOrder = false): string {
{ return 'SHOW FULL FIELDS FROM ' . $table;
$select = ''; }
if (!empty($this->query->from)) {
$select = $this->_selectPrefix();
}
$select = $this->_wherePrefix($select);
if (!empty($this->query->group)) {
$select .= $this->builderGroup($this->query->group);
}
if ($hasOrder === true && !empty($this->query->order)) {
$select .= $this->builderOrder($this->query->order);
}
return $select . $this->builderLimit($this->query);
}
/** /**
* @param $select * @param bool $hasOrder
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
private function _wherePrefix($select): string private function _prefix($hasOrder = false): string
{ {
$condition = $this->conditionToString(); $select = '';
if (empty($condition)) { if (!empty($this->query->from)) {
return $select; $select = $this->_selectPrefix();
} else if (empty($select)) { }
return $condition; $select = $this->_wherePrefix($select);
} if (!empty($this->query->group)) {
return sprintf('%s WHERE %s', $select, $condition); $select .= $this->builderGroup($this->query->group);
} }
if ($hasOrder === true && !empty($this->query->order)) {
$select .= $this->builderOrder($this->query->order);
}
return $select . $this->builderLimit($this->query);
}
/** /**
* @return string * @param $select
* @throws Exception * @return string
*/ * @throws Exception
private function _selectPrefix(): string */
{ private function _wherePrefix($select): string
$select = $this->builderSelect($this->query->select) . ' FROM ' . $this->tableName(); {
if (!empty($this->query->alias)) { $condition = $this->conditionToString();
$select .= $this->builderAlias($this->query->alias); if (empty($condition)) {
} return $select;
if (!empty($this->query->join)) { } else if (empty($select)) {
$select .= $this->builderJoin($this->query->join); return $condition;
} }
return $select; return sprintf('%s WHERE %s', $select, $condition);
} }
/** /**
* @param false $isCount * @return string
* @return string * @throws Exception
* @throws Exception */
*/ private function _selectPrefix(): string
public function get($isCount = false): string {
{ $select = $this->builderSelect($this->query->select) . ' FROM ' . $this->tableName();
if ($isCount === false) { if (!empty($this->query->alias)) {
return $this->all(); $select .= $this->builderAlias($this->query->alias);
} }
return $this->count(); if (!empty($this->query->join)) {
} $select .= $this->builderJoin($this->query->join);
}
return $select;
}
/** /**
* @return string * @param false $isCount
* @throws Exception * @return string
*/ * @throws Exception
public function truncate(): string */
{ public function get($isCount = false): string
return sprintf('TRUNCATE %s', $this->tableName()); {
} if ($isCount === false) {
return $this->all();
}
return $this->count();
}
/** /**
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
private function conditionToString(): string public function truncate(): string
{ {
return $this->where($this->query->where); return sprintf('TRUNCATE %s', $this->tableName());
} }
/** /**
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public function tableName(): string private function conditionToString(): string
{ {
if ($this->query->from instanceof \Closure) { return $this->where($this->query->where);
$this->query->from = sprintf('(%s)', $this->query->makeClosureFunction($this->query->from)); }
}
if ($this->query->from instanceof ActiveQuery) {
$this->query->from = sprintf('%s', SqlBuilder::builder($this->query->from)->get($this->query->from)); /**
} * @return string
if (empty($this->query->from)) { * @throws Exception
return $this->query->modelClass::getTable(); */
} public function tableName(): string
return $this->query->from; {
} if ($this->query->from instanceof \Closure) {
$this->query->from = sprintf('(%s)', $this->query->makeClosureFunction($this->query->from));
}
if ($this->query->from instanceof ActiveQuery) {
$this->query->from = sprintf('%s', SqlBuilder::builder($this->query->from)->get($this->query->from));
}
if (empty($this->query->from)) {
return $this->query->modelClass::getTable();
}
return $this->query->from;
}
} }
+1 -1
View File
@@ -34,7 +34,7 @@ trait QueryTrait
public ?int $offset = NULL; public ?int $offset = NULL;
public ?int $limit = NULL; public ?int $limit = NULL;
public string $group = ''; public string $group = '';
public string|Closure|ActiveQuery $from = ''; public string|Closure|ActiveQuery|null $from = '';
public string $alias = 't1'; public string $alias = 't1';
public array $filter = []; public array $filter = [];