3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
20 namespace Wikimedia\Rdbms
;
22 use InvalidArgumentException
;
25 * Database connection manager.
27 * This manages access to primary and replica databases.
33 class ConnectionManager
{
38 private $loadBalancer;
41 * The symbolic name of the target database, or false for the local wiki's database.
53 * @param ILoadBalancer $loadBalancer
54 * @param string|false $domain Optional logical DB name, defaults to current wiki.
55 * This follows the convention for database names used by $loadBalancer.
56 * @param string[] $groups see LoadBalancer::getConnection
58 * @throws InvalidArgumentException
60 public function __construct( ILoadBalancer
$loadBalancer, $domain = false, array $groups = [] ) {
61 if ( !is_string( $domain ) && $domain !== false ) {
62 throw new InvalidArgumentException( '$dbName must be a string, or false.' );
65 $this->loadBalancer
= $loadBalancer;
66 $this->domain
= $domain;
67 $this->groups
= $groups;
72 * @param string[]|null $groups
76 private function getConnection( $i, ?
array $groups = null, int $flags = 0 ) {
77 $groups ??
= $this->groups
;
78 return $this->loadBalancer
->getConnection( $i, $groups, $this->domain
, $flags );
82 * Returns a connection to the primary DB, for updating.
85 * @since 1.37 Added optional $flags parameter
89 public function getWriteConnection( int $flags = 0 ) {
90 return $this->getConnection( DB_PRIMARY
, null, $flags );
94 * Returns a database connection for reading.
97 * @since 1.37 Added optional $flags parameter
98 * @param string[]|null $groups
100 * @return IReadableDatabase
102 public function getReadConnection( ?
array $groups = null, int $flags = 0 ) {
103 $groups ??
= $this->groups
;
104 return $this->getConnection( DB_REPLICA
, $groups, $flags );