1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Doctrine\DBAL\Connections\Connector; |
4
|
|
|
|
5
|
|
|
use Doctrine\DBAL\Driver; |
6
|
|
|
use Doctrine\DBAL\Driver\DriverException; |
7
|
|
|
use Doctrine\DBAL\Exception\ConnectionException; |
8
|
|
|
use Exception; |
9
|
|
|
use function array_pop; |
10
|
|
|
use function shuffle; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* HighAvailabilityConnector is connection to the first random slave connection that is available |
14
|
|
|
*/ |
15
|
|
|
class HighAvailabilityConnector extends AbstractMasterSlaveConnector implements Connector |
16
|
|
|
{ |
17
|
|
|
public const STRATEGY = 'high_availability'; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Connects to a specific connection. |
21
|
|
|
* |
22
|
|
|
* @param string $connectionName |
23
|
|
|
* |
24
|
|
|
* @return Driver\Connection |
25
|
|
|
* |
26
|
|
|
* @throws ConnectionException |
27
|
|
|
*/ |
28
|
96 |
|
public function connectTo($connectionName) |
29
|
|
|
{ |
30
|
96 |
|
return $connectionName === 'master' ? |
31
|
96 |
|
$this->connectToMaster() : |
32
|
96 |
|
$this->connectToSlave(); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Connets to a master |
37
|
|
|
* |
38
|
|
|
* @return Driver\Connection |
39
|
|
|
*/ |
40
|
96 |
|
private function connectToMaster() |
41
|
|
|
{ |
42
|
96 |
|
return $this->connectWithParams($this->_params['master']); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Connets to a random slave and tries others until if found a server that is alive |
47
|
|
|
* |
48
|
|
|
* @return Driver\Connection |
49
|
|
|
* |
50
|
|
|
* @throws ConnectionException |
51
|
|
|
*/ |
52
|
96 |
|
private function connectToSlave() |
53
|
|
|
{ |
54
|
96 |
|
$params = $this->_params; |
55
|
|
|
|
56
|
96 |
|
shuffle($params['slaves']); |
57
|
|
|
|
58
|
96 |
|
while ($config = array_pop($params['slaves'])) { |
59
|
|
|
try { |
60
|
96 |
|
return $this->connectWithParams($config); |
61
|
48 |
|
} catch (ConnectionException $e) { |
62
|
|
|
// try next one |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
$previous = new /** @psalm-immutable */ class() extends Exception implements DriverException { |
67
|
|
|
public function getErrorCode() |
68
|
|
|
{ |
69
|
|
|
return null; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
public function getSQLState() |
73
|
|
|
{ |
74
|
|
|
return null; |
75
|
|
|
} |
76
|
|
|
}; |
77
|
|
|
|
78
|
|
|
if (isset($e) && $e->getPrevious() instanceof DriverException) { |
79
|
|
|
$previous = $e->getPrevious(); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
throw new ConnectionException('No slaves are available', $previous); |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|