3 namespace Wikimedia\Rdbms
;
8 use InvalidArgumentException
;
12 * Database connection manager.
14 * This manages access to master and replica databases.
21 class ConnectionManager
{
26 private $loadBalancer;
29 * The symbolic name of the target database, or false for the local wiki's database.
41 * @param LoadBalancer $loadBalancer
42 * @param string|bool $domain Optional logical DB name, defaults to current wiki.
43 * This follows the convention for database names used by $loadBalancer.
44 * @param string[] $groups see LoadBalancer::getConnection
46 * @throws InvalidArgumentException
48 public function __construct( LoadBalancer
$loadBalancer, $domain = false, array $groups = [] ) {
49 if ( !is_string( $domain ) && $domain !== false ) {
50 throw new InvalidArgumentException( '$dbName must be a string, or false.' );
53 $this->loadBalancer
= $loadBalancer;
54 $this->domain
= $domain;
55 $this->groups
= $groups;
60 * @param string[]|null $groups
64 private function getConnection( $i, array $groups = null ) {
65 $groups = $groups === null ?
$this->groups
: $groups;
66 return $this->loadBalancer
->getConnection( $i, $groups, $this->domain
);
71 * @param string[]|null $groups
75 private function getConnectionRef( $i, array $groups = null ) {
76 $groups = $groups === null ?
$this->groups
: $groups;
77 return $this->loadBalancer
->getConnectionRef( $i, $groups, $this->domain
);
81 * Returns a connection to the master DB, for updating. The connection should later be released
82 * by calling releaseConnection().
88 public function getWriteConnection() {
89 return $this->getConnection( DB_MASTER
);
93 * Returns a database connection for reading. The connection should later be released by
94 * calling releaseConnection().
98 * @param string[]|null $groups
102 public function getReadConnection( array $groups = null ) {
103 $groups = $groups === null ?
$this->groups
: $groups;
104 return $this->getConnection( DB_REPLICA
, $groups );
110 * @param IDatabase $db
112 public function releaseConnection( IDatabase
$db ) {
113 $this->loadBalancer
->reuseConnection( $db );
117 * Returns a connection ref to the master DB, for updating.
123 public function getWriteConnectionRef() {
124 return $this->getConnectionRef( DB_MASTER
);
128 * Returns a database connection ref for reading.
132 * @param string[]|null $groups
136 public function getReadConnectionRef( array $groups = null ) {
137 $groups = $groups === null ?
$this->groups
: $groups;
138 return $this->getConnectionRef( DB_REPLICA
, $groups );