1<?php
2/**
3 * Simple generator of database connections that always returns the same object.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Database
22 */
23
24namespace Wikimedia\Rdbms;
25
26use InvalidArgumentException;
27
28/**
29 * Trivial LoadBalancer that always returns an injected connection handle.
30 */
31class LoadBalancerSingle extends LoadBalancer {
32	/** @var IDatabase */
33	private $db;
34
35	/**
36	 * @param array $params An associative array with one member:
37	 *   - connection: An IDatabase connection object
38	 */
39	public function __construct( array $params ) {
40		/** @var IDatabase $conn */
41		$conn = $params['connection'] ?? null;
42		if ( !$conn ) {
43			throw new InvalidArgumentException( "Missing 'connection' argument." );
44		}
45
46		$this->db = $conn;
47
48		parent::__construct( [
49			'servers' => [ [
50				'type' => $conn->getType(),
51				'host' => $conn->getServer(),
52				'dbname' => $conn->getDBname(),
53				'load' => 1,
54			] ],
55			'trxProfiler' => $params['trxProfiler'] ?? null,
56			'srvCache' => $params['srvCache'] ?? null,
57			'wanCache' => $params['wanCache'] ?? null,
58			'localDomain' => $params['localDomain'] ?? $this->db->getDomainID(),
59			'readOnlyReason' => $params['readOnlyReason'] ?? false,
60		] );
61
62		if ( isset( $params['readOnlyReason'] ) ) {
63			$conn->setLBInfo( $conn::LB_READ_ONLY_REASON, $params['readOnlyReason'] );
64		}
65	}
66
67	/**
68	 * @param IDatabase $db Live connection handle
69	 * @param array $params Parameter map to LoadBalancerSingle::__constructs()
70	 * @return LoadBalancerSingle
71	 * @since 1.28
72	 */
73	public static function newFromConnection( IDatabase $db, array $params = [] ) {
74		return new static( array_merge(
75			[ 'localDomain' => $db->getDomainID() ],
76			$params,
77			[ 'connection' => $db ]
78		) );
79	}
80
81	protected function reallyOpenConnection( $i, DatabaseDomain $domain, array $lbInfo = [] ) {
82		return $this->db;
83	}
84
85	public function __destruct() {
86		// do nothing since the connection was injected
87	}
88}
89
90/**
91 * @deprecated since 1.29
92 */
93class_alias( LoadBalancerSingle::class, 'LoadBalancerSingle' );
94