Repository navigation
Expand file tree
/
Copy pathConnectionResolver.php
More file actions
98 lines (84 loc) · 2.59 KB
/
Copy pathConnectionResolver.php
File metadata and controls
98 lines (84 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\DbConnection;
use Hyperf\Context\Context;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Database\ConnectionInterface;
use Hyperf\Database\ConnectionResolverInterface;
use Hyperf\DbConnection\Pool\PoolFactory;
use Psr\Container\ContainerInterface;
use function Hyperf\Coroutine\defer;
class ConnectionResolver implements ConnectionResolverInterface
{
/**
* The default connection name.
*/
protected string $default = 'default';
protected PoolFactory $factory;
public function __construct(protected ContainerInterface $container)
{
$this->factory = $container->get(PoolFactory::class);
}
/**
* Get a database connection instance.
*/
public function connection(?string $name = null): ConnectionInterface
{
if (is_null($name)) {
$name = $this->getDefaultConnection();
}
$connection = null;
$id = $this->getContextKey($name);
if (Context::has($id)) {
$connection = Context::get($id);
}
if (! $connection instanceof ConnectionInterface) {
$pool = $this->factory->getPool($name);
$connection = $pool->get();
try {
// PDO is initialized as an anonymous function, so there is no IO exception,
// but if other exceptions are thrown, the connection will not return to the connection pool properly.
$connection = $connection->getConnection();
Context::set($id, $connection);
} finally {
if (Coroutine::inCoroutine()) {
defer(function () use ($connection, $id) {
Context::set($id, null);
$connection->release();
});
}
}
}
return $connection;
}
/**
* Get the default connection name.
*/
public function getDefaultConnection(): string
{
return $this->default;
}
/**
* Set the default connection name.
*/
public function setDefaultConnection(string $name): void
{
$this->default = $name;
}
/**
* The key to identify the connection object in coroutine context.
* @param mixed $name
*/
private function getContextKey($name): string
{
return sprintf('database.connection.%s', $name);
}
}