Files
kiri-databases/Connection.php
T

382 lines
8.8 KiB
PHP
Raw Normal View History

2022-01-09 03:49:51 +08:00
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/3/30 0030
* Time: 14:09
*/
declare(strict_types=1);
namespace Database;
use Database\Affair\BeginTransaction;
use Database\Affair\Commit;
use Database\Affair\Rollback;
use Database\Mysql\Schema;
use Exception;
2022-01-14 15:52:38 +08:00
use Kiri;
2023-08-25 09:37:58 +08:00
use Kiri\Server\Events\OnWorkerExit;
2023-08-16 12:00:10 +08:00
use Kiri\Waite;
2022-01-09 03:49:51 +08:00
use Kiri\Abstracts\Component;
2022-12-12 17:31:12 +08:00
use Kiri\Di\Context;
2023-04-06 22:39:31 +08:00
use Kiri\Pool\Pool;
2022-03-03 18:30:59 +08:00
use Kiri\Events\EventProvider;
2022-01-09 03:49:51 +08:00
use Kiri\Exception\NotFindClassException;
2022-12-12 17:31:12 +08:00
use PDO;
2023-08-16 12:36:45 +08:00
use Kiri\Error\StdoutLogger;
2023-08-21 09:38:37 +08:00
use PDOStatement;
2023-08-16 12:00:10 +08:00
use Psr\Log\LoggerInterface;
2022-01-14 15:52:38 +08:00
use ReflectionException;
2023-08-16 01:01:47 +08:00
use Kiri\Server\Events\OnAfterRequest;
2023-08-16 12:15:59 +08:00
use Kiri\Di\Inject\Container;
2022-01-09 03:49:51 +08:00
/**
* Class Connection
* @package Database
*/
class Connection extends Component
{
2023-05-26 09:20:29 +08:00
public string $id = 'db';
public string $cds = '';
public string $password = '';
public string $username = '';
public string $charset = 'utf-8';
public string $tablePrefix = '';
public string $database = '';
2023-08-24 12:06:35 +08:00
public int $connect_timeout = 30;
2023-05-26 09:20:29 +08:00
2023-08-16 16:35:54 +08:00
public int $waite_time = 3;
2023-08-24 13:41:27 +08:00
public int $idle_time = 60;
2023-08-16 14:18:09 +08:00
2023-05-26 09:20:29 +08:00
public array $pool = ['max' => 10, 'min' => 1];
private int $storey = 0;
/**
* @var bool
* enable database cache
*/
public bool $enableCache = false;
private ?PDO $_pdo = null;
/**
* @var string
*/
public string $cacheDriver = 'redis';
/**
* @var array
*/
2023-08-16 14:25:19 +08:00
public array $attributes = [];
2023-05-26 09:20:29 +08:00
2023-08-16 14:22:38 +08:00
/**
* @var Schema|null
*/
2023-05-26 09:20:29 +08:00
private ?Schema $_schema = null;
2023-08-16 12:15:59 +08:00
/**
2023-08-16 12:36:45 +08:00
* @var StdoutLogger
2023-08-16 12:15:59 +08:00
*/
#[Container(LoggerInterface::class)]
2023-08-16 12:36:45 +08:00
public StdoutLogger $logger;
2023-08-16 12:15:59 +08:00
2023-08-16 00:39:55 +08:00
/**
* @param Pool $connections
*/
2023-08-16 12:15:59 +08:00
public function __construct(public Pool $connections)
2023-08-16 00:39:55 +08:00
{
parent::__construct();
}
2023-05-26 09:20:29 +08:00
/**
* @return void
* @throws Exception
*/
public function init(): void
{
$eventProvider = Kiri::getDi()->get(EventProvider::class);
$eventProvider->on(BeginTransaction::class, [$this, 'beginTransaction'], 0);
$eventProvider->on(Rollback::class, [$this, 'rollback'], 0);
$eventProvider->on(Commit::class, [$this, 'commit'], 0);
2023-08-16 01:01:47 +08:00
$eventProvider->on(OnAfterRequest::class, [$this, 'clear']);
2023-05-26 09:20:29 +08:00
}
/**
* @return mixed
* @throws ReflectionException
* @throws NotFindClassException
* @throws Exception
*/
public function getSchema(): Schema
{
if ($this->_schema === null) {
$this->_schema = Kiri::createObject([
'class' => Schema::class,
'db' => $this
]);
}
return $this->_schema;
}
/**
* @return PDO
2023-08-16 00:39:55 +08:00
* @throws Exception
2023-05-26 09:20:29 +08:00
*/
public function getConnection(): PDO
{
2023-08-16 00:55:05 +08:00
if (!$this->inTransaction()) {
2023-08-16 12:27:03 +08:00
return $this->getNormalClientHealth();
2023-08-16 00:55:05 +08:00
} else {
return $this->getTransactionClient();
}
2023-05-26 09:20:29 +08:00
}
2023-08-16 12:00:10 +08:00
/**
* @return PDO
* @throws Exception
*/
2023-08-16 12:27:03 +08:00
protected function getNormalClientHealth(): PDO
2023-08-16 12:00:10 +08:00
{
2023-08-16 16:38:33 +08:00
$data = $this->pool()->get($this->cds, $this->waite_time);
if ($data === false) {
throw new Exception('Pool waite timeout at ' . $this->waite_time);
}
2023-08-18 15:04:39 +08:00
2023-08-16 16:38:33 +08:00
[$client, $time] = $data;
2023-08-24 12:11:23 +08:00
if ((time() - $time) < $this->idle_time && $this->canUse($client)) {
2023-08-16 15:55:50 +08:00
return $client;
2023-08-16 12:00:10 +08:00
}
2023-08-24 11:25:42 +08:00
2023-08-24 14:19:47 +08:00
$this->logger->error('PDO连接已失效, 空闲超时或已不可用,重新获取.', [$this->cds]);
2023-08-16 16:33:56 +08:00
$this->pool()->abandon($this->cds);
2023-08-16 12:00:10 +08:00
Waite::sleep(10);
2023-08-16 12:27:03 +08:00
return $this->getNormalClientHealth();
2023-08-16 12:00:10 +08:00
}
2023-08-24 12:11:35 +08:00
2023-08-16 12:19:47 +08:00
/**
* @param PDO|null $client
* @return bool
*/
protected function canUse(?PDO $client): bool
{
if (is_null($client)) {
return false;
}
try {
2023-08-24 12:29:18 +08:00
if ($client->query('select 1') === false) {
2023-08-24 11:25:42 +08:00
return false;
2023-08-16 12:19:47 +08:00
}
2023-08-24 12:29:18 +08:00
return true;
2023-08-16 12:19:47 +08:00
} catch (\Throwable $exception) {
return false;
}
}
2023-08-24 11:46:27 +08:00
/**
* @return $this
* @throws Exception
*/
public function beginTransaction(): static
{
if ($this->storey == 0) {
/** @var PDO $pdo */
2023-08-25 10:10:09 +08:00
$pdo = Context::get($this->cds);
if ($pdo == null) {
2023-08-25 10:21:35 +08:00
$pdo = $this->getTransactionClient();
2023-08-25 10:10:09 +08:00
}
2023-08-25 10:04:55 +08:00
if (!$pdo->inTransaction()) {
2023-08-24 11:46:27 +08:00
$pdo->beginTransaction();
}
}
$this->storey++;
return $this;
}
2023-05-26 09:20:29 +08:00
/**
* @return PDO
* @throws Exception
*/
public function getTransactionClient(): PDO
{
$pdo = Context::get($this->cds);
if ($pdo === null) {
2023-08-16 14:54:02 +08:00
$pdo = $this->getNormalClientHealth();
2023-08-25 10:21:56 +08:00
if (!$pdo->inTransaction()) {
2023-05-26 09:20:29 +08:00
$pdo->beginTransaction();
}
Context::set($this->cds, $pdo);
}
return $pdo;
}
2023-08-24 12:10:08 +08:00
2023-05-26 09:20:29 +08:00
/**
* @return bool
* @throws Exception
*/
public function inTransaction(): bool
{
return $this->storey > 0;
}
2023-08-24 12:10:08 +08:00
2023-05-26 09:20:29 +08:00
/**
* @throws Exception
* 事务回滚
*/
public function rollback(): void
{
$this->storey--;
if ($this->storey == 0) {
2023-08-25 10:21:35 +08:00
/** @var PDO $pdo */
$pdo = Context::get($this->cds);
if ($pdo === null) {
throw new Exception('Failed to rollback transaction: connection was exists.');
}
if ($this->inTransaction()) {
$pdo->rollback();
}
$this->pool()->push($this->cds, [$pdo, time()]);
Context::remove($this->cds);
2023-05-26 09:20:29 +08:00
}
}
/**
* @throws Exception
* 事务提交
*/
public function commit(): void
{
$this->storey--;
if ($this->storey == 0) {
$pdo = Context::get($this->cds);
if ($pdo === null) {
2023-08-25 10:21:35 +08:00
throw new Exception('Failed to commit transaction: connection was exists.');
2023-05-26 09:20:29 +08:00
}
2023-08-25 10:21:35 +08:00
if ($pdo->inTransaction()) {
2023-05-26 09:20:29 +08:00
$pdo->commit();
}
2023-08-18 15:04:39 +08:00
$this->pool()->push($this->cds, [$pdo, time()]);
2023-05-26 09:20:29 +08:00
Context::remove($this->cds);
}
}
2023-08-16 00:57:33 +08:00
/**
* @return void
* @throws Exception
*/
public function clear(): void
{
/** @var PDO $pdo */
$pdo = Context::get($this->cds);
if ($pdo === null) {
return;
}
2023-08-24 14:13:22 +08:00
if ($this->inTransaction()) {
2023-08-16 00:57:33 +08:00
$pdo->rollback();
}
2023-08-18 15:04:39 +08:00
$this->pool()->push($this->cds, [$pdo, time()]);
2023-08-16 00:57:33 +08:00
Context::remove($this->cds);
}
2023-05-26 09:20:29 +08:00
/**
* @param null $sql
* @param array $attributes
* @return Command
* @throws Exception
*/
public function createCommand($sql = null, array $attributes = []): Command
{
$command = new Command(['connection' => $this, 'sql' => $sql]);
return $command->bindValues($attributes);
}
/**
* 回收链接
* @throws
*/
2023-08-24 11:25:42 +08:00
public function release(PDO $PDO): void
2023-05-26 09:20:29 +08:00
{
2023-08-24 14:15:00 +08:00
if (!$this->inTransaction()) {
$this->pool()->push($this->cds, [$PDO, time()]);
2023-08-16 00:55:05 +08:00
}
2023-05-26 09:20:29 +08:00
}
/**
*
* 回收链接
* @throws
*/
public function clear_connection(): void
{
2023-08-16 00:55:05 +08:00
$this->pool()->flush($this->cds, 0);
2023-05-26 09:20:29 +08:00
}
/**
* @throws Exception
*/
public function disconnect(): void
{
2023-08-16 00:39:55 +08:00
$this->pool()->close($this->cds);
2023-05-26 09:20:29 +08:00
}
2023-08-14 14:14:40 +08:00
/**
2023-08-16 14:47:26 +08:00
* @return array
2023-08-14 14:14:40 +08:00
*/
2023-08-16 14:47:26 +08:00
public function newConnect(): array
2023-08-14 14:14:40 +08:00
{
2023-08-24 12:01:34 +08:00
$options = array_merge($this->attributes, [
2023-08-14 14:14:40 +08:00
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,
2023-08-24 12:06:35 +08:00
PDO::ATTR_TIMEOUT => $this->connect_timeout,
2023-08-14 14:14:40 +08:00
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . $this->charset
2023-08-24 12:01:34 +08:00
]);
2023-08-16 14:39:46 +08:00
$link = new PDO('mysql:dbname=' . $this->database . ';host=' . $this->cds, $this->username, $this->password, $options);
2023-08-16 14:47:26 +08:00
return [$link, time()];
2023-08-14 14:14:40 +08:00
}
2023-05-26 09:20:29 +08:00
/**
* @return Pool
*/
private function pool(): Pool
{
if (!$this->connections->hasChannel($this->cds)) {
2023-08-14 14:14:40 +08:00
$this->connections->created($this->cds, $this->pool['max'] ?? 1, [$this, 'newConnect']);
2023-05-26 09:20:29 +08:00
}
return $this->connections;
}
2022-01-09 03:49:51 +08:00
}