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