3 namespace Wikimedia\Rdbms
;
7 use InvalidArgumentException
;
10 * Database connection manager.
12 * This manages access to master and replica databases.
19 class ConnectionManager
{
24 private $loadBalancer;
27 * The symbolic name of the target database, or false for the local wiki's database.
39 * @param LoadBalancer $loadBalancer
40 * @param string|bool $domain Optional logical DB name, defaults to current wiki.
41 * This follows the convention for database names used by $loadBalancer.
42 * @param string[] $groups see LoadBalancer::getConnection
44 * @throws InvalidArgumentException
46 public function __construct( LoadBalancer
$loadBalancer, $domain = false, array $groups = [] ) {
47 if ( !is_string( $domain ) && $domain !== false ) {
48 throw new InvalidArgumentException( '$dbName must be a string, or false.' );
51 $this->loadBalancer
= $loadBalancer;
52 $this->domain
= $domain;
53 $this->groups
= $groups;
58 * @param string[]|null $groups
62 private function getConnection( $i, array $groups = null ) {
63 $groups = $groups === null ?
$this->groups
: $groups;
64 return $this->loadBalancer
->getConnection( $i, $groups, $this->domain
);
69 * @param string[]|null $groups
73 private function getConnectionRef( $i, array $groups = null ) {
74 $groups = $groups === null ?
$this->groups
: $groups;
75 return $this->loadBalancer
->getConnectionRef( $i, $groups, $this->domain
);
79 * Returns a connection to the master DB, for updating. The connection should later be released
80 * by calling releaseConnection().
86 public function getWriteConnection() {
87 return $this->getConnection( DB_MASTER
);
91 * Returns a database connection for reading. The connection should later be released by
92 * calling releaseConnection().
96 * @param string[]|null $groups
100 public function getReadConnection( array $groups = null ) {
101 $groups = $groups === null ?
$this->groups
: $groups;
102 return $this->getConnection( DB_REPLICA
, $groups );
108 * @param IDatabase $db
110 public function releaseConnection( IDatabase
$db ) {
111 $this->loadBalancer
->reuseConnection( $db );
115 * Returns a connection ref to the master DB, for updating.
121 public function getWriteConnectionRef() {
122 return $this->getConnectionRef( DB_MASTER
);
126 * Returns a database connection ref for reading.
130 * @param string[]|null $groups
134 public function getReadConnectionRef( array $groups = null ) {
135 $groups = $groups === null ?
$this->groups
: $groups;
136 return $this->getConnectionRef( DB_REPLICA
, $groups );