This commit is contained in:
xl
2023-11-14 15:01:30 +08:00
parent a1238613f9
commit 53dbf7a9b2
12 changed files with 174 additions and 248 deletions
+8 -20
View File
@@ -51,27 +51,17 @@ class ActiveQuery extends Component implements ISqlBuilder
public function __construct($model) public function __construct($model)
{ {
$this->modelClass = $model; $this->modelClass = $model;
$this->builder = SqlBuilder::builder($this);
$this->builder = SqlBuilder::builder($this);
parent::__construct(); parent::__construct();
} }
/** /**
* 清除不完整数据 * @param string $key
*/ * @param mixed $value
public function clear(): void
{
$this->db = NULL;
$this->useCache = FALSE;
}
/**
* @param $key
* @param $value
* @return $this * @return $this
*/ */
public function addParam($key, $value): static public function addParam(string $key, mixed $value): static
{ {
$this->attributes[$key] = $value; $this->attributes[$key] = $value;
return $this; return $this;
@@ -87,13 +77,11 @@ class ActiveQuery extends Component implements ISqlBuilder
#[ArrayShape([])] #[ArrayShape([])]
public function pagination(int $size = 20, int $page = 1): array public function pagination(int $size = 20, int $page = 1): array
{ {
$page = max(1, $page); $page = max(1, $page);
$size = max(1, $size); $size = max(1, $size);
$offset = ($page - 1) * $size; $offset = ($page - 1) * $size;
$count = $this->count();
$count = $this->count(); $lists = $this->offset($offset)->limit($size)->get()->toArray();
$lists = $this->offset($offset)->limit($size)->get()->toArray();
return [ return [
'code' => 0, 'code' => 0,
'message' => 'ok', 'message' => 'ok',
+2 -9
View File
@@ -232,29 +232,23 @@ class BackupCommand extends Command
public function buildLine($key, $percent): string public function buildLine($key, $percent): string
{ {
$repeatTimes = 100; $repeatTimes = 100;
if ($percent > 100) { if ($percent > 100) $percent = 100;
$percent = 100;
}
if ($percent > 0) { if ($percent > 0) {
$hasColor = str_repeat('■', $percent); $hasColor = str_repeat('■', $percent);
} else { } else {
$hasColor = ''; $hasColor = '';
} }
if ($repeatTimes - $percent > 0) { if ($repeatTimes - $percent > 0) {
$noColor = str_repeat(' ', $repeatTimes - $percent); $noColor = str_repeat(' ', $repeatTimes - $percent);
} else { } else {
$noColor = ''; $noColor = '';
} }
$buffer = "[{$hasColor}{$noColor}]";
if ($percent !== 100) { if ($percent !== 100) {
$percentString = sprintf("[ %s %-6s]", $key, $percent . '%'); $percentString = sprintf("[ %s %-6s]", $key, $percent . '%');
} else { } else {
$percentString = sprintf("[ %s %-5s]", $key, 'OK');; $percentString = sprintf("[ %s %-5s]", $key, 'OK');;
} }
return $percentString . "[{$hasColor}{$noColor}]" . "\r";
return $percentString . $buffer . "\r";
} }
/** /**
@@ -290,7 +284,6 @@ class BackupCommand extends Command
$this->outputProgress(true); $this->outputProgress(true);
return; return;
} }
$this->outputProgress(true); $this->outputProgress(true);
usleep(50000); usleep(50000);
} }
+47 -46
View File
@@ -1,6 +1,7 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace Database\Base; namespace Database\Base;
@@ -21,51 +22,51 @@ use Database\Condition\RLikeCondition;
class ConditionClassMap class ConditionClassMap
{ {
public static array $conditionMap = [ public static array $conditionMap = [
'IN' => [ 'IN' => [
'class' => InCondition::class 'class' => InCondition::class
], ],
'NOT IN' => [ 'NOT IN' => [
'class' => NotInCondition::class 'class' => NotInCondition::class
], ],
'LIKE' => [ 'LIKE' => [
'class' => LikeCondition::class 'class' => LikeCondition::class
], ],
'NOT LIKE' => [ 'NOT LIKE' => [
'class' => NotLikeCondition::class 'class' => NotLikeCondition::class
], ],
'LLike' => [ 'LLike' => [
'class' => LLikeCondition::class 'class' => LLikeCondition::class
], ],
'RLike' => [ 'RLike' => [
'class' => RLikeCondition::class 'class' => RLikeCondition::class
], ],
'EQ' => [ 'EQ' => [
'class' => MathematicsCondition::class, 'class' => MathematicsCondition::class,
'type' => 'EQ' 'type' => 'EQ'
], ],
'NEQ' => [ 'NEQ' => [
'class' => MathematicsCondition::class, 'class' => MathematicsCondition::class,
'type' => 'NEQ' 'type' => 'NEQ'
], ],
'GT' => [ 'GT' => [
'class' => MathematicsCondition::class, 'class' => MathematicsCondition::class,
'type' => 'GT' 'type' => 'GT'
], ],
'EGT' => [ 'EGT' => [
'class' => MathematicsCondition::class, 'class' => MathematicsCondition::class,
'type' => 'EGT' 'type' => 'EGT'
], ],
'LT' => [ 'LT' => [
'class' => MathematicsCondition::class, 'class' => MathematicsCondition::class,
'type' => 'LT' 'type' => 'LT'
], ],
'ELT' => [ 'ELT' => [
'class' => MathematicsCondition::class, 'class' => MathematicsCondition::class,
'type' => 'ELT' 'type' => 'ELT'
], ],
'BETWEEN' => BetweenCondition::class, 'BETWEEN' => BetweenCondition::class,
'NOT BETWEEN' => NotBetweenCondition::class, 'NOT BETWEEN' => NotBetweenCondition::class,
]; ];
} }
+10 -15
View File
@@ -136,7 +136,7 @@ abstract class Model extends Component implements ModelInterface, ArrayAccess, \
*/ */
public function clean(): void public function clean(): void
{ {
$this->_attributes = []; $this->_attributes = [];
$this->_oldAttributes = []; $this->_oldAttributes = [];
} }
@@ -432,11 +432,9 @@ abstract class Model extends Component implements ModelInterface, ArrayAccess, \
private function insert(): bool|static private function insert(): bool|static
{ {
[$sql, $param] = SqlBuilder::builder(static::query())->insert($this->_attributes); [$sql, $param] = SqlBuilder::builder(static::query())->insert($this->_attributes);
$connection = $this->getConnection();
$connection = $this->getConnection();
$dbConnection = $connection->createCommand($sql, $param); $dbConnection = $connection->createCommand($sql, $param);
$lastId = $dbConnection->save();
$lastId = $dbConnection->save();
if ($lastId === false) { if ($lastId === false) {
return false; return false;
} else { } else {
@@ -467,7 +465,7 @@ abstract class Model extends Component implements ModelInterface, ArrayAccess, \
} }
$connection = $this->getConnection(); $connection = $this->getConnection();
$command = $connection->createCommand($generate, $query->attributes); $command = $connection->createCommand($generate, $query->attributes);
if ($command->save()) { if ($command->save()) {
return $this->refresh()->afterSave($old, $change); return $this->refresh()->afterSave($old, $change);
} else { } else {
@@ -516,7 +514,7 @@ abstract class Model extends Component implements ModelInterface, ArrayAccess, \
*/ */
public function populates($value): static public function populates($value): static
{ {
$this->_attributes = $value; $this->_attributes = $value;
$this->_oldAttributes = $value; $this->_oldAttributes = $value;
$this->setIsNowExample(); $this->setIsNowExample();
return $this; return $this;
@@ -594,8 +592,7 @@ abstract class Model extends Component implements ModelInterface, ArrayAccess, \
*/ */
public function getTable(): string public function getTable(): string
{ {
$connection = static::getConnection(); $connection = static::getConnection();
$tablePrefix = $connection->tablePrefix; $tablePrefix = $connection->tablePrefix;
if (empty($this->table)) { if (empty($this->table)) {
throw new Exception('You need add static method `tableName` and return table name.'); throw new Exception('You need add static method `tableName` and return table name.');
@@ -762,8 +759,7 @@ abstract class Model extends Component implements ModelInterface, ArrayAccess, \
*/ */
#[ReturnTypeWillChange] public function offsetUnset(mixed $offset) #[ReturnTypeWillChange] public function offsetUnset(mixed $offset)
{ {
if (!isset($this->_attributes[$offset]) if (!isset($this->_attributes[$offset]) && !isset($this->_oldAttributes[$offset])) {
&& !isset($this->_oldAttributes[$offset])) {
return; return;
} }
unset($this->_attributes[$offset]); unset($this->_attributes[$offset]);
@@ -786,8 +782,7 @@ abstract class Model extends Component implements ModelInterface, ArrayAccess, \
*/ */
public function getColumns(): Columns public function getColumns(): Columns
{ {
return $this->getConnection()->getSchema()->getColumns() return $this->getConnection()->getSchema()->getColumns()->table($this->getTable());
->table($this->getTable());
} }
@@ -798,8 +793,8 @@ abstract class Model extends Component implements ModelInterface, ArrayAccess, \
*/ */
public static function populate(array $data): static public static function populate(array $data): static
{ {
$model = new static(); $model = new static();
$model->_attributes = $data; $model->_attributes = $data;
$model->_oldAttributes = $data; $model->_oldAttributes = $data;
$model->setIsNowExample(); $model->setIsNowExample();
return $model; return $model;
+2 -14
View File
@@ -24,21 +24,9 @@ use Throwable;
class Command extends Component class Command extends Component
{ {
const RETRY_NAME = 'db:retry:count';
/**
*
*/
const DB_ERROR_MESSAGE = 'The system is busy, please try again later.';
/** @var Connection */
public Connection $connection; public Connection $connection;
public ?string $sql = '';
/** @var ?string */ public array $params = [];
public ?string $sql = '';
/** @var array */
public array $params = [];
/** /**
+51 -56
View File
@@ -14,69 +14,64 @@ use Kiri\Abstracts\Component;
abstract class Condition extends Component abstract class Condition extends Component
{ {
protected string $column = ''; protected string $column = '';
protected string $opera = '='; protected string $opera = '=';
protected mixed $value;
protected array $attributes = [];
/** @var array|mixed */ abstract public function builder();
protected mixed $value;
const INT_TYPE = ['bit', 'bool', 'tinyint', 'smallint', 'mediumint', 'int', 'bigint', 'float', 'double', 'decimal', 'timestamp']; /**
* @param string $column
*/
public function setColumn(string $column): void
{
$this->column = $column;
}
protected array $attributes = []; /**
* @param string $opera
*/
public function setOpera(string $opera): void
{
$this->opera = $opera;
}
abstract public function builder(); /**
* @param $params
/** */
* @param string $column public function setValue($params): void
*/ {
public function setColumn(string $column): void if (is_array($params)) {
{ $values = [];
$this->column = $column; foreach ($params as $item => $value) {
} $values[$item] = is_numeric($value) ? $value : '\'' . $value . '\'';
}
/** $this->value = $values;
* @param string $opera } else {
*/ $this->value = $this->checkIsSqlString($params);
public function setOpera(string $opera): void }
{ }
$this->opera = $opera;
}
/**
* @param $params
*/
public function setValue($params): void
{
if (is_array($params)) {
$values = [];
foreach ($params as $item => $value) {
$values[$item] = is_numeric($value) ? $value : '\'' . $value . '\'';
}
$this->value = $values;
} else {
$this->value = $this->checkIsSqlString($params);
}
}
/** /**
* @param $params * @param $params
* @return int|string * @return int|string
*/ */
#[Pure] private function checkIsSqlString($params): int|string #[Pure] private function checkIsSqlString($params): int|string
{ {
if (is_numeric($params)) { if (is_numeric($params)) {
return $params; return $params;
} }
$check = ltrim($params, '('); $check = ltrim($params, '(');
$check = strtolower(substr($check, 0, 6)); $check = strtolower(substr($check, 0, 6));
if (in_array($check, ['update', 'select', 'insert', 'delete'])) { if (in_array($check, ['update', 'select', 'insert', 'delete'])) {
return $params; return $params;
} else { } else {
return sprintf('\'%s\'', $params); return sprintf('\'%s\'', $params);
} }
} }
} }
+24 -36
View File
@@ -40,31 +40,23 @@ use Swoole\Timer;
class Connection extends Component class Connection extends Component
{ {
public string $id = 'db'; public string $id = 'db';
public string $cds = ''; public string $cds = '';
public string $password = ''; public string $password = '';
public string $username = ''; public string $username = '';
public string $charset = 'utf-8'; public string $charset = 'utf-8';
public string $tablePrefix = ''; public string $tablePrefix = '';
public string $database = '';
public string $database = ''; public int $timeout = 30;
public int $waite_time = 3;
public int $timeout = 30; public int $tick_time = 60;
public int $idle_count = 3;
public array $pool = ['max' => 10, 'min' => 1];
private int $storey = 0;
protected int $timerId = -1;
public int $waite_time = 3; const ERROR_MSG = 'Failed to rollback transaction: connection was exists.';
public int $tick_time = 60;
public int $idle_count = 3;
public array $pool = ['max' => 10, 'min' => 1];
private int $storey = 0;
protected int $timerId = -1;
/** /**
* @var bool * @var bool
@@ -182,10 +174,7 @@ class Connection extends Component
public function getSchema(): Schema public function getSchema(): Schema
{ {
if ($this->_schema === null) { if ($this->_schema === null) {
$this->_schema = Kiri::createObject([ $this->_schema = Kiri::createObject(['class' => Schema::class, 'db' => $this]);
'class' => Schema::class,
'db' => $this
]);
} }
return $this->_schema; return $this->_schema;
} }
@@ -279,7 +268,7 @@ class Connection extends Component
/** @var PDO $pdo */ /** @var PDO $pdo */
$pdo = Context::get($this->cds); $pdo = Context::get($this->cds);
if ($pdo === null) { if ($pdo === null) {
throw new Exception('Failed to rollback transaction: connection was exists.'); throw new Exception(self::ERROR_MSG);
} }
if ($this->inTransaction()) { if ($this->inTransaction()) {
$pdo->rollback(); $pdo->rollback();
@@ -298,7 +287,7 @@ class Connection extends Component
if ($this->storey == 0) { if ($this->storey == 0) {
$pdo = Context::get($this->cds); $pdo = Context::get($this->cds);
if ($pdo === null) { if ($pdo === null) {
throw new Exception('Failed to commit transaction: connection was exists.'); throw new Exception(self::ERROR_MSG);
} }
if ($this->inTransaction()) { if ($this->inTransaction()) {
$pdo->commit(); $pdo->commit();
@@ -334,8 +323,7 @@ class Connection extends Component
*/ */
public function createCommand($sql = null, array $attributes = []): Command public function createCommand($sql = null, array $attributes = []): Command
{ {
$command = new Command(['connection' => $this, 'sql' => $sql]); return (new Command(['connection' => $this, 'sql' => $sql]))->bindValues($attributes);
return $command->bindValues($attributes);
} }
@@ -381,12 +369,12 @@ class Connection extends Component
{ {
$pdo = new PDO('mysql:dbname=' . $this->database . ';host=' . $this->cds, $pdo = new PDO('mysql:dbname=' . $this->database . ';host=' . $this->cds,
$this->username, $this->password, [ $this->username, $this->password, [
PDO::ATTR_CASE => PDO::CASE_NATURAL, PDO::ATTR_CASE => PDO::CASE_NATURAL,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL, PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
PDO::ATTR_STRINGIFY_FETCHES => false, PDO::ATTR_STRINGIFY_FETCHES => false,
PDO::ATTR_EMULATE_PREPARES => true, PDO::ATTR_EMULATE_PREPARES => true,
PDO::ATTR_TIMEOUT => $this->timeout, PDO::ATTR_TIMEOUT => $this->timeout,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . $this->charset PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . $this->charset
]); ]);
foreach ($this->attributes as $key => $attribute) { foreach ($this->attributes as $key => $attribute) {
+13 -13
View File
@@ -57,19 +57,19 @@ class DatabasesProviders extends Providers
{ {
$clientPool = $database['pool'] ?? ['min' => 1, 'max' => 5, 'tick' => 60]; $clientPool = $database['pool'] ?? ['min' => 1, 'max' => 5, 'tick' => 60];
return [ return [
'id' => $database['id'], 'id' => $database['id'],
'cds' => $database['cds'], 'cds' => $database['cds'],
'class' => Connection::class, 'class' => Connection::class,
'username' => $database['username'], 'username' => $database['username'],
'password' => $database['password'], 'password' => $database['password'],
'tablePrefix' => $database['tablePrefix'], 'tablePrefix' => $database['tablePrefix'],
'database' => $database['database'], 'database' => $database['database'],
'timeout' => $database['timeout'] ?? 10, 'timeout' => $database['timeout'] ?? 10,
'tick_time' => $database['tick_time'] ?? 60, 'tick_time' => $database['tick_time'] ?? 60,
'waite_time' => $database['waite_time'] ?? 3, 'waite_time' => $database['waite_time'] ?? 3,
'pool' => $clientPool, 'pool' => $clientPool,
'attributes' => $database['attributes'] ?? [], 'attributes' => $database['attributes'] ?? [],
'charset' => $database['charset'] ?? 'utf8mb4' 'charset' => $database['charset'] ?? 'utf8mb4'
]; ];
} }
-1
View File
@@ -11,7 +11,6 @@ namespace Database;
use Exception; use Exception;
use Kiri;
use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface; use Psr\Container\NotFoundExceptionInterface;
+4 -24
View File
@@ -25,32 +25,12 @@ use Kiri\Core\Json;
class Columns extends Component class Columns extends Component
{ {
/**
* @var array
* field types
*/
private array $columns = [];
/** private array $columns = [];
* @var string public string $table = '';
* tableName private array $_primary = [];
*/
public string $table = '';
/**
* @var array
* field primary key
*/
private array $_primary = [];
/**
* @var array
* by mysql field auto_increment
*/
private array $_auto_increment = []; private array $_auto_increment = [];
private array $_fields = [];
private array $_fields = [];
/** /**
+4 -5
View File
@@ -77,9 +77,9 @@ class SqlBuilder extends Component
*/ */
public function update(array $attributes): bool|string public function update(array $attributes): bool|string
{ {
$conditions = $this->query->attributes; $conditions = $this->query->attributes;
$this->query->attributes = []; $this->query->attributes = [];
$data = $this->__updateBuilder($this->builderParams($attributes)); $data = $this->__updateBuilder($this->builderParams($attributes));
foreach ($conditions as $condition) { foreach ($conditions as $condition) {
$this->query->pushParam($condition); $this->query->pushParam($condition);
} }
@@ -132,7 +132,7 @@ class SqlBuilder extends Component
$update .= '(' . implode(',', $this->getFields($attributes)) . ') VALUES '; $update .= '(' . implode(',', $this->getFields($attributes)) . ') VALUES ';
$order = 0; $order = 0;
$keys = []; $keys = [];
foreach ($attributes as $attribute) { foreach ($attributes as $attribute) {
$_keys = $this->builderParams($attribute, true, $order); $_keys = $this->builderParams($attribute, true, $order);
@@ -197,8 +197,7 @@ class SqlBuilder extends Component
if (is_null($value)) { if (is_null($value)) {
return $keys; return $keys;
} }
if (is_string($value) && (str_starts_with($value, '+ ') || if (is_string($value) && (str_starts_with($value, '+ ') || str_starts_with($value, '- '))) {
str_starts_with($value, '- '))) {
$keys[] = $key . '=' . $key . ' ' . $value; $keys[] = $key . '=' . $key . ' ' . $value;
} else { } else {
$this->query->pushParam($value); $this->query->pushParam($value);
+9 -9
View File
@@ -53,15 +53,15 @@ trait QueryTrait
*/ */
public function clear(): void public function clear(): void
{ {
$this->where = []; $this->where = [];
$this->select = []; $this->select = [];
$this->join = []; $this->join = [];
$this->order = []; $this->order = [];
$this->offset = 0; $this->offset = 0;
$this->limit = 500; $this->limit = 500;
$this->group = ''; $this->group = '';
$this->from = ''; $this->from = '';
$this->alias = 't1'; $this->alias = 't1';
$this->filter = []; $this->filter = [];
} }
@@ -325,7 +325,7 @@ trait QueryTrait
if (is_array($val)) { if (is_array($val)) {
$tmp[] = $this->toString($array); $tmp[] = $this->toString($array);
} else { } else {
$tmp[] = $key . '=:' . $key; $tmp[] = $key . '=:' . $key;
$this->attributes[':' . $key] = $val; $this->attributes[':' . $key] = $val;
} }
} }
@@ -363,7 +363,7 @@ trait QueryTrait
*/ */
public function distance(string $lngField, string $latField, int $lng1, int $lat1): static public function distance(string $lngField, string $latField, int $lng1, int $lat1): static
{ {
$sql = "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(($lat1 * PI() / 180 - $lat1 * PI() / 180) / 2),2) + COS($lat1 * PI() / 180) * COS($latField * PI() / 180) * POW(SIN(($lng1 * PI() / 180 - $lngField * PI() / 180) / 2),2))) * 1000) AS distance"; $sql = "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(($lat1 * PI() / 180 - $lat1 * PI() / 180) / 2),2) + COS($lat1 * PI() / 180) * COS($latField * PI() / 180) * POW(SIN(($lng1 * PI() / 180 - $lngField * PI() / 180) / 2),2))) * 1000) AS distance";
$this->select[] = $sql; $this->select[] = $sql;
return $this; return $this;
} }