This commit is contained in:
2021-07-05 15:49:37 +08:00
parent 74bcdf257e
commit 1a012150ce
5 changed files with 317 additions and 303 deletions
+284 -284
View File
@@ -28,237 +28,237 @@ use Snowflake\Snowflake;
*/ */
class Connection extends Component class Connection extends Component
{ {
const TRANSACTION_COMMIT = 'transaction::commit'; const TRANSACTION_COMMIT = 'transaction::commit';
const TRANSACTION_ROLLBACK = 'transaction::rollback'; const TRANSACTION_ROLLBACK = 'transaction::rollback';
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 = 1900; public int $timeout = 1900;
public int $maxNumber = 30; public int $maxNumber = 30;
public int $minNumber = 10; public int $minNumber = 10;
/** /**
* @var bool * @var bool
* enable database cache * enable database cache
*/ */
public bool $enableCache = false; public bool $enableCache = false;
public string $cacheDriver = 'redis'; public string $cacheDriver = 'redis';
/** /**
* @var array * @var array
* *
* @example [ * @example [
* 'cds' => 'mysql:dbname=dbname;host=127.0.0.1', * 'cds' => 'mysql:dbname=dbname;host=127.0.0.1',
* 'username' => 'root', * 'username' => 'root',
* 'password' => 'root' * 'password' => 'root'
* ] * ]
*/ */
public array $slaveConfig = []; public array $slaveConfig = [];
private ?Schema $_schema = null; private ?Schema $_schema = null;
/** /**
* @throws Exception * @throws Exception
*/ */
public function init() public function init()
{ {
Event::on(Event::SYSTEM_RESOURCE_CLEAN, [$this, 'disconnect']); Event::on(Event::SYSTEM_RESOURCE_CLEAN, [$this, 'disconnect']);
Event::on(Event::SYSTEM_RESOURCE_RELEASES, [$this, 'clear_connection']); Event::on(Event::SYSTEM_RESOURCE_RELEASES, [$this, 'clear_connection']);
} }
/** /**
* @throws Exception * @throws Exception
*/ */
public function enablingTransactions() public function enablingTransactions()
{ {
if (!Db::transactionsActive()) { if (!Db::transactionsActive()) {
return; return;
} }
$this->beginTransaction(); $this->beginTransaction();
Event::on(Connection::TRANSACTION_COMMIT, [$this, 'commit'], false, true); Event::on(Connection::TRANSACTION_COMMIT, [$this, 'commit'], false, true);
Event::on(Connection::TRANSACTION_ROLLBACK, [$this, 'rollback'], false, true); Event::on(Connection::TRANSACTION_ROLLBACK, [$this, 'rollback'], false, true);
} }
/** /**
* @param null $sql * @param null $sql
* @return PDO * @return PDO
* @throws Exception * @throws Exception
*/ */
public function getConnect($sql = NULL): PDO public function getConnect($sql = NULL): PDO
{ {
return $this->getPdo($sql); return $this->getPdo($sql);
} }
/** /**
* @throws Exception * @throws Exception
*/ */
public function fill() public function fill()
{ {
$connections = $this->connections(); $connections = $this->connections();
$pool = Config::get('databases.pool.max',10); $pool = Config::get('databases.pool.max', 10);
$connections->initConnections('mysql', $this->cds, true, $pool); $connections->initConnections($this->cds, true, $pool);
if (!empty($this->slaveConfig) && $this->cds != $this->slaveConfig['cds']) { if (!empty($this->slaveConfig) && $this->cds != $this->slaveConfig['cds']) {
$connections->initConnections('mysql', $this->slaveConfig['cds'], false, $pool); $connections->initConnections($this->slaveConfig['cds'], false, $pool);
} }
} }
/** /**
* @param $sql * @param $sql
* @return PDO * @return PDO
* @throws Exception * @throws Exception
*/ */
private function getPdo($sql): PDO private function getPdo($sql): PDO
{ {
if ($this->isWrite($sql)) { if ($this->isWrite($sql)) {
return $this->masterInstance(); return $this->masterInstance();
} else { } else {
return $this->slaveInstance(); return $this->slaveInstance();
} }
} }
/** /**
* @return mixed * @return mixed
* @throws ReflectionException * @throws ReflectionException
* @throws NotFindClassException * @throws NotFindClassException
*/ */
public function getSchema(): Schema public function getSchema(): Schema
{ {
if ($this->_schema === null) { if ($this->_schema === null) {
$this->_schema = Snowflake::createObject([ $this->_schema = Snowflake::createObject([
'class' => Schema::class, 'class' => Schema::class,
'db' => $this 'db' => $this
]); ]);
} }
return $this->_schema; return $this->_schema;
} }
/** /**
* @param $sql * @param $sql
* @return bool * @return bool
*/ */
#[Pure] public function isWrite($sql): bool #[Pure] public function isWrite($sql): bool
{ {
if (empty($sql)) return false; if (empty($sql)) return false;
if (str_starts_with(strtolower($sql), 'select')) { if (str_starts_with(strtolower($sql), 'select')) {
return false; return false;
} }
return true; return true;
} }
/** /**
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function getCacheDriver(): mixed public function getCacheDriver(): mixed
{ {
if (!$this->enableCache) { if (!$this->enableCache) {
return null; return null;
} }
return Snowflake::app()->get($this->cacheDriver); return Snowflake::app()->get($this->cacheDriver);
} }
/** /**
* @return PDO * @return PDO
* @throws Exception * @throws Exception
*/ */
public function masterInstance(): PDO public function masterInstance(): PDO
{ {
return $this->connections()->get([ return $this->connections()->get([
'cds' => $this->cds, 'cds' => $this->cds,
'username' => $this->username, 'username' => $this->username,
'password' => $this->password, 'password' => $this->password,
'database' => $this->database 'database' => $this->database
], true); ], true);
} }
/** /**
* @return PDO * @return PDO
* @throws Exception * @throws Exception
*/ */
public function slaveInstance(): PDO public function slaveInstance(): PDO
{ {
if (empty($this->slaveConfig) || Db::transactionsActive()) { if (empty($this->slaveConfig) || Db::transactionsActive()) {
return $this->masterInstance(); return $this->masterInstance();
} }
return $this->connections()->get($this->slaveConfig, false); return $this->connections()->get($this->slaveConfig, false);
} }
/** /**
* @return \Snowflake\Pool\Connection * @return \Snowflake\Pool\Connection
* @throws Exception * @throws Exception
*/ */
private function connections(): \Snowflake\Pool\Connection private function connections(): \Snowflake\Pool\Connection
{ {
return Snowflake::app()->getMysqlFromPool(); return Snowflake::app()->getMysqlFromPool();
} }
/** /**
* @return $this * @return $this
* @throws Exception * @throws Exception
*/ */
public function beginTransaction(): static public function beginTransaction(): static
{ {
$this->connections()->beginTransaction($this->cds); $this->connections()->beginTransaction($this->cds);
return $this; return $this;
} }
/** /**
* @return $this|bool * @return $this|bool
* @throws Exception * @throws Exception
*/ */
public function inTransaction(): bool|static public function inTransaction(): bool|static
{ {
return $this->connections()->inTransaction($this->cds); return $this->connections()->inTransaction($this->cds);
} }
/** /**
* @throws Exception * @throws Exception
* 事务回滚 * 事务回滚
*/ */
public function rollback() public function rollback()
{ {
$this->connections()->rollback($this->cds); $this->connections()->rollback($this->cds);
} }
/** /**
* @throws Exception * @throws Exception
* 事务提交 * 事务提交
*/ */
public function commit() public function commit()
{ {
$this->connections()->commit($this->cds); $this->connections()->commit($this->cds);
} }
/** /**
* @param $sql * @param $sql
* @return PDO * @return PDO
* @throws Exception * @throws Exception
*/ */
public function refresh($sql): PDO public function refresh($sql): PDO
{ {
if ($this->isWrite($sql)) { if ($this->isWrite($sql)) {
$instance = $this->masterInstance(); $instance = $this->masterInstance();
} else { } else {
$instance = $this->slaveInstance(); $instance = $this->slaveInstance();
} }
return $instance; return $instance;
} }
/** /**
* @param null $sql * @param null $sql
@@ -267,14 +267,14 @@ class Connection extends Component
* @return Command * @return Command
* @throws Exception * @throws Exception
*/ */
public function createCommand($sql = null, string $dbname = '', array $attributes = []): Command public function createCommand($sql = null, string $dbname = '', array $attributes = []): Command
{ {
if (!empty($dbname)) { if (!empty($dbname)) {
$sql = $this->clear($dbname, $sql); $sql = $this->clear($dbname, $sql);
} }
$command = new Command(['db' => $this, 'sql' => $this->innerJoinMatch($dbname, $sql)]); $command = new Command(['db' => $this, 'sql' => $this->innerJoinMatch($dbname, $sql)]);
return $command->bindValues($attributes); return $command->bindValues($attributes);
} }
/** /**
@@ -282,28 +282,28 @@ class Connection extends Component
* @param $sql * @param $sql
* @return array|string|null * @return array|string|null
*/ */
private function clear($dbname, $sql): array|string|null private function clear($dbname, $sql): array|string|null
{ {
$substr = strtoupper(substr($sql, 0, 6)); $substr = strtoupper(substr($sql, 0, 6));
return match ($substr) { return match ($substr) {
'SELECT', 'SHOW F', 'DELETE' => $this->selectMatch($dbname, $sql), 'SELECT', 'SHOW F', 'DELETE' => $this->selectMatch($dbname, $sql),
'UPDATE' => $this->updateMatch($dbname, $sql), 'UPDATE' => $this->updateMatch($dbname, $sql),
'INSERT' => $this->insertMatch($dbname, $sql), 'INSERT' => $this->insertMatch($dbname, $sql),
'TRUNCA' => $this->truncateMatch($dbname, $sql), 'TRUNCA' => $this->truncateMatch($dbname, $sql),
default => $sql default => $sql
}; };
} }
/** /**
* @param $dbname * @param $dbname
* @param $sql * @param $sql
* @return array|string|string[]|null * @return array|string|string[]|null
*/ */
private function selectMatch($dbname, $sql) private function selectMatch($dbname, $sql)
{ {
return preg_replace('/FROM\s+(\w+)\s+/', 'FROM `' . $dbname . '`.$1 ', $sql); return preg_replace('/FROM\s+(\w+)\s+/', 'FROM `' . $dbname . '`.$1 ', $sql);
} }
/** /**
@@ -311,10 +311,10 @@ class Connection extends Component
* @param $sql * @param $sql
* @return array|string|null * @return array|string|null
*/ */
private function innerJoinMatch($dbname, $sql): array|string|null private function innerJoinMatch($dbname, $sql): array|string|null
{ {
return preg_replace('/(INNER|LEFT|RIGHT) JOIN\s+(\w+)\s/', '$1 JOIN `' . $dbname . '`.$2 ', $sql); return preg_replace('/(INNER|LEFT|RIGHT) JOIN\s+(\w+)\s/', '$1 JOIN `' . $dbname . '`.$2 ', $sql);
} }
/** /**
@@ -322,10 +322,10 @@ class Connection extends Component
* @param $sql * @param $sql
* @return array|string|null * @return array|string|null
*/ */
private function updateMatch($dbname, $sql): array|string|null private function updateMatch($dbname, $sql): array|string|null
{ {
return preg_replace('/UPDATE\s+(\w+)\s+SET/', 'UPDATE `' . $dbname . '`.$1 SET', $sql); return preg_replace('/UPDATE\s+(\w+)\s+SET/', 'UPDATE `' . $dbname . '`.$1 SET', $sql);
} }
/** /**
@@ -333,10 +333,10 @@ class Connection extends Component
* @param $sql * @param $sql
* @return array|string|null * @return array|string|null
*/ */
private function insertMatch($dbname, $sql): array|string|null private function insertMatch($dbname, $sql): array|string|null
{ {
return preg_replace('/INSERT INTO\s+(\w+)/', 'INSERT INTO `' . $dbname . '`.$1', $sql); return preg_replace('/INSERT INTO\s+(\w+)/', 'INSERT INTO `' . $dbname . '`.$1', $sql);
} }
/** /**
@@ -344,59 +344,59 @@ class Connection extends Component
* @param $sql * @param $sql
* @return array|string|null * @return array|string|null
*/ */
private function truncateMatch($dbname, $sql): array|string|null private function truncateMatch($dbname, $sql): array|string|null
{ {
return preg_replace('/TRUNCATE\s+(\w+)\s+/', 'TRUNCATE `' . $dbname . '`.$1', $sql); return preg_replace('/TRUNCATE\s+(\w+)\s+/', 'TRUNCATE `' . $dbname . '`.$1', $sql);
} }
/** /**
* *
* 回收链接 * 回收链接
* @throws * @throws
*/ */
public function release() public function release()
{ {
$connections = $this->connections(); $connections = $this->connections();
$connections->release($this->cds, true); $connections->release($this->cds, true);
$connections->release($this->slaveConfig['cds'], false); $connections->release($this->slaveConfig['cds'], false);
} }
/** /**
* @throws Exception * @throws Exception
*/ */
public function recovery() public function recovery()
{ {
$connections = $this->connections(); $connections = $this->connections();
$connections->release($this->cds, true); $connections->release($this->cds, true);
$connections->release($this->slaveConfig['cds'], false); $connections->release($this->slaveConfig['cds'], false);
} }
/** /**
* *
* 回收链接 * 回收链接
* @throws * @throws
*/ */
public function clear_connection() public function clear_connection()
{ {
$connections = $this->connections(); $connections = $this->connections();
$connections->release($this->cds, true); $connections->release($this->cds, true);
$connections->release($this->slaveConfig['cds'], false); $connections->release($this->slaveConfig['cds'], false);
} }
/** /**
* @throws Exception * @throws Exception
*/ */
public function disconnect() public function disconnect()
{ {
$connections = $this->connections(); $connections = $this->connections();
$connections->disconnect($this->cds, true); $connections->disconnect($this->cds, true);
$connections->disconnect($this->slaveConfig['cds'], false); $connections->disconnect($this->slaveConfig['cds'], false);
} }
} }
+1 -2
View File
@@ -53,11 +53,10 @@ class Redis extends Component
$connections = Snowflake::app()->getRedisFromPool(); $connections = Snowflake::app()->getRedisFromPool();
$config = $this->get_config(); $config = $this->get_config();
$name = $config['host'] . ':' . $config['prefix'] . ':' . $config['databases'];
$length = (int)env('REDIS.POOL_LENGTH', 100); $length = (int)env('REDIS.POOL_LENGTH', 100);
$connections->initConnections('redis', $name, true, $length); $connections->initConnections('Redis:' . $config['host'], true, $length);
} }
+1 -14
View File
@@ -106,18 +106,6 @@ class ClientsPool extends Component
} }
/**
* @param $name
*/
protected function clearCreateLog($name): void
{
if (!isset(static::$hasCreate[$name])) {
return;
}
static::$hasCreate[$name] = 0;
}
/** /**
* @param Channel $channel * @param Channel $channel
* @param $name * @param $name
@@ -140,12 +128,11 @@ class ClientsPool extends Component
/** /**
* @param $driver
* @param $name * @param $name
* @param false $isMaster * @param false $isMaster
* @param int $max * @param int $max
*/ */
public function initConnections($driver, $name, bool $isMaster = false, int $max = 60) public function initConnections($name, bool $isMaster = false, int $max = 60)
{ {
$name = $this->name($name, $isMaster); $name = $this->name($name, $isMaster);
if (isset(static::$_connections[$name]) && static::$_connections[$name] instanceof Channel) { if (isset(static::$_connections[$name]) && static::$_connections[$name] instanceof Channel) {
+19 -3
View File
@@ -113,10 +113,14 @@ class Connection extends Component
if (($pdo = Context::getContext($coroutineName)) instanceof PDO) { if (($pdo = Context::getContext($coroutineName)) instanceof PDO) {
return $pdo; return $pdo;
} }
/** @var PDO $connections */ if (Coroutine::getCid() === -1) {
$connections = $this->getPool()->getFromChannel($coroutineName);
if (empty($connections)) {
$connections = $this->createClient($coroutineName, $config); $connections = $this->createClient($coroutineName, $config);
} else {
/** @var PDO $connections */
$connections = $this->getPool()->getFromChannel($coroutineName);
if (empty($connections)) {
$connections = $this->createClient($coroutineName, $config);
}
} }
if ($number = Context::getContext('begin_' . $coroutineName, Coroutine::getCid())) { if ($number = Context::getContext('begin_' . $coroutineName, Coroutine::getCid())) {
$number > 0 && $connections->beginTransaction(); $number > 0 && $connections->beginTransaction();
@@ -125,6 +129,18 @@ class Connection extends Component
} }
/**
* @param $name
* @param $isMaster
* @param $max
* @throws Exception
*/
public function initConnections($name, $isMaster, $max)
{
$this->getPool()->initConnections($name, $isMaster, $max);
}
/** /**
* @param string $name * @param string $name
* @param mixed $config * @param mixed $config
+12
View File
@@ -126,4 +126,16 @@ class Redis extends Component
} }
/**
* @param $name
* @param $isMaster
* @param $max
* @throws Exception
*/
public function initConnections($name, $isMaster, $max)
{
$this->getPool()->initConnections($name, $isMaster, $max);
}
} }