3 namespace Wikimedia\Rdbms
;
6 use InvalidArgumentException
;
9 * Database connection manager.
11 * This manages access to master and replica databases.
18 class ConnectionManager
{
23 private $loadBalancer;
26 * The symbolic name of the target database, or false for the local wiki's database.
38 * @param LoadBalancer $loadBalancer
39 * @param string|bool $domain Optional logical DB name, defaults to current wiki.
40 * This follows the convention for database names used by $loadBalancer.
41 * @param string[] $groups see LoadBalancer::getConnection
43 * @throws InvalidArgumentException
45 public function __construct( LoadBalancer
$loadBalancer, $domain = false, array $groups = [] ) {
46 if ( !is_string( $domain ) && $domain !== false ) {
47 throw new InvalidArgumentException( '$dbName must be a string, or false.' );
50 $this->loadBalancer
= $loadBalancer;
51 $this->domain
= $domain;
52 $this->groups
= $groups;
57 * @param string[]|null $groups
61 private function getConnection( $i, array $groups = null ) {
62 $groups = $groups === null ?
$this->groups
: $groups;
63 return $this->loadBalancer
->getConnection( $i, $groups, $this->domain
);
68 * @param string[]|null $groups
72 private function getConnectionRef( $i, array $groups = null ) {
73 $groups = $groups === null ?
$this->groups
: $groups;
74 return $this->loadBalancer
->getConnectionRef( $i, $groups, $this->domain
);
78 * Returns a connection to the master DB, for updating. The connection should later be released
79 * by calling releaseConnection().
85 public function getWriteConnection() {
86 return $this->getConnection( DB_MASTER
);
90 * Returns a database connection for reading. The connection should later be released by
91 * calling releaseConnection().
95 * @param string[]|null $groups
99 public function getReadConnection( array $groups = null ) {
100 $groups = $groups === null ?
$this->groups
: $groups;
101 return $this->getConnection( DB_REPLICA
, $groups );
107 * @param IDatabase $db
109 public function releaseConnection( IDatabase
$db ) {
110 $this->loadBalancer
->reuseConnection( $db );
114 * Returns a connection ref to the master DB, for updating.
120 public function getWriteConnectionRef() {
121 return $this->getConnectionRef( DB_MASTER
);
125 * Returns a database connection ref for reading.
129 * @param string[]|null $groups
133 public function getReadConnectionRef( array $groups = null ) {
134 $groups = $groups === null ?
$this->groups
: $groups;
135 return $this->getConnectionRef( DB_REPLICA
, $groups );