212ff315a8b2a19f01af63cfc1687430b6fd4c9d
3 namespace Wikimedia\Rdbms
;
5 use InvalidArgumentException
;
8 * Database connection manager.
10 * This manages access to master and replica databases.
17 class ConnectionManager
{
22 private $loadBalancer;
25 * The symbolic name of the target database, or false for the local wiki's database.
37 * @param LoadBalancer $loadBalancer
38 * @param string|bool $domain Optional logical DB name, defaults to current wiki.
39 * This follows the convention for database names used by $loadBalancer.
40 * @param string[] $groups see LoadBalancer::getConnection
42 * @throws InvalidArgumentException
44 public function __construct( LoadBalancer
$loadBalancer, $domain = false, array $groups = [] ) {
45 if ( !is_string( $domain ) && $domain !== false ) {
46 throw new InvalidArgumentException( '$dbName must be a string, or false.' );
49 $this->loadBalancer
= $loadBalancer;
50 $this->domain
= $domain;
51 $this->groups
= $groups;
56 * @param string[]|null $groups
60 private function getConnection( $i, array $groups = null ) {
61 $groups = $groups === null ?
$this->groups
: $groups;
62 return $this->loadBalancer
->getConnection( $i, $groups, $this->domain
);
67 * @param string[]|null $groups
71 private function getConnectionRef( $i, array $groups = null ) {
72 $groups = $groups === null ?
$this->groups
: $groups;
73 return $this->loadBalancer
->getConnectionRef( $i, $groups, $this->domain
);
77 * Returns a connection to the master DB, for updating. The connection should later be released
78 * by calling releaseConnection().
84 public function getWriteConnection() {
85 return $this->getConnection( DB_MASTER
);
89 * Returns a database connection for reading. The connection should later be released by
90 * calling releaseConnection().
94 * @param string[]|null $groups
98 public function getReadConnection( array $groups = null ) {
99 $groups = $groups === null ?
$this->groups
: $groups;
100 return $this->getConnection( DB_REPLICA
, $groups );
106 * @param IDatabase $db
108 public function releaseConnection( IDatabase
$db ) {
109 $this->loadBalancer
->reuseConnection( $db );
113 * Returns a connection ref to the master DB, for updating.
119 public function getWriteConnectionRef() {
120 return $this->getConnectionRef( DB_MASTER
);
124 * Returns a database connection ref for reading.
128 * @param string[]|null $groups
132 public function getReadConnectionRef( array $groups = null ) {
133 $groups = $groups === null ?
$this->groups
: $groups;
134 return $this->getConnectionRef( DB_REPLICA
, $groups );