3 namespace Wikimedia\Rdbms
;
8 use InvalidArgumentException
;
11 * Database connection manager.
13 * This manages access to master and replica databases.
20 class ConnectionManager
{
25 private $loadBalancer;
28 * The symbolic name of the target database, or false for the local wiki's database.
40 * @param LoadBalancer $loadBalancer
41 * @param string|bool $domain Optional logical DB name, defaults to current wiki.
42 * This follows the convention for database names used by $loadBalancer.
43 * @param string[] $groups see LoadBalancer::getConnection
45 * @throws InvalidArgumentException
47 public function __construct( LoadBalancer
$loadBalancer, $domain = false, array $groups = [] ) {
48 if ( !is_string( $domain ) && $domain !== false ) {
49 throw new InvalidArgumentException( '$dbName must be a string, or false.' );
52 $this->loadBalancer
= $loadBalancer;
53 $this->domain
= $domain;
54 $this->groups
= $groups;
59 * @param string[]|null $groups
63 private function getConnection( $i, array $groups = null ) {
64 $groups = $groups === null ?
$this->groups
: $groups;
65 return $this->loadBalancer
->getConnection( $i, $groups, $this->domain
);
70 * @param string[]|null $groups
74 private function getConnectionRef( $i, array $groups = null ) {
75 $groups = $groups === null ?
$this->groups
: $groups;
76 return $this->loadBalancer
->getConnectionRef( $i, $groups, $this->domain
);
80 * Returns a connection to the master DB, for updating. The connection should later be released
81 * by calling releaseConnection().
87 public function getWriteConnection() {
88 return $this->getConnection( DB_MASTER
);
92 * Returns a database connection for reading. The connection should later be released by
93 * calling releaseConnection().
97 * @param string[]|null $groups
101 public function getReadConnection( array $groups = null ) {
102 $groups = $groups === null ?
$this->groups
: $groups;
103 return $this->getConnection( DB_REPLICA
, $groups );
109 * @param IDatabase $db
111 public function releaseConnection( IDatabase
$db ) {
112 $this->loadBalancer
->reuseConnection( $db );
116 * Returns a connection ref to the master DB, for updating.
122 public function getWriteConnectionRef() {
123 return $this->getConnectionRef( DB_MASTER
);
127 * Returns a database connection ref for reading.
131 * @param string[]|null $groups
135 public function getReadConnectionRef( array $groups = null ) {
136 $groups = $groups === null ?
$this->groups
: $groups;
137 return $this->getConnectionRef( DB_REPLICA
, $groups );