aboutsummaryrefslogtreecommitdiffstats
path: root/includes/installer/PostgresInstaller.php
blob: d8b547397444dfc8ef7d9ff000e24ffd73cf55c2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
<?php
/**
 * PostgreSQL-specific installer.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @ingroup Installer
 */

namespace MediaWiki\Installer;

use InvalidArgumentException;
use MediaWiki\MediaWikiServices;
use Wikimedia\Rdbms\DatabaseFactory;
use Wikimedia\Rdbms\DatabasePostgres;
use Wikimedia\Rdbms\DBConnectionError;
use Wikimedia\Rdbms\IMaintainableDatabase;

/**
 * Class for setting up the MediaWiki database using Postgres.
 *
 * @ingroup Installer
 * @since 1.17
 */
class PostgresInstaller extends DatabaseInstaller {

	/** @inheritDoc */
	protected $globalNames = [
		'wgDBserver',
		'wgDBport',
		'wgDBname',
		'wgDBuser',
		'wgDBpassword',
		'wgDBssl',
		'wgDBmwschema',
	];

	/** @inheritDoc */
	protected $internalDefaults = [
		'_InstallUser' => 'postgres',
	];

	/** @inheritDoc */
	public static $minimumVersion = '10';
	/** @inheritDoc */
	protected static $notMinimumVersionMessage = 'config-postgres-old';

	public function getName() {
		return 'postgres';
	}

	public function isCompiled() {
		return self::checkExtension( 'pgsql' );
	}

	public function getConnectForm( WebInstaller $webInstaller ): DatabaseConnectForm {
		return new PostgresConnectForm( $webInstaller, $this );
	}

	public function getSettingsForm( WebInstaller $webInstaller ): DatabaseSettingsForm {
		return new PostgresSettingsForm( $webInstaller, $this );
	}

	/**
	 * Open a PG connection with given parameters
	 * @param string $user User name
	 * @param string $password
	 * @param string $dbName Database name
	 * @param string $schema Database schema
	 * @return ConnectionStatus
	 */
	protected function openConnectionWithParams( $user, $password, $dbName, $schema ) {
		$status = new ConnectionStatus;
		try {
			$db = MediaWikiServices::getInstance()->getDatabaseFactory()->create( 'postgres', [
				'host' => $this->getVar( 'wgDBserver' ),
				'port' => $this->getVar( 'wgDBport' ),
				'user' => $user,
				'password' => $password,
				'ssl' => $this->getVar( 'wgDBssl' ),
				'dbname' => $dbName,
				'schema' => $schema,
			] );
			$status->setDB( $db );
		} catch ( DBConnectionError $e ) {
			$status->fatal( 'config-connection-error', $e->getMessage() );
		}

		return $status;
	}

	/**
	 * Get a connection of a specific PostgreSQL-specific type. Connections
	 * of a given type are cached.
	 *
	 * PostgreSQL lacks cross-database operations, so after the new database is
	 * created, you need to make a separate connection to connect to that
	 * database and add tables to it.
	 *
	 * New tables are owned by the user that creates them, and MediaWiki's
	 * PostgreSQL support has always assumed that the table owner will be
	 * $wgDBuser. So before we create new tables, we either need to either
	 * connect as the other user or to execute a SET ROLE command. Using a
	 * separate connection for this allows us to avoid accidental cross-module
	 * dependencies.
	 *
	 * @param string $type The type of connection to get:
	 *    - self::CONN_CREATE_DATABASE: A connection for creating DBs, suitable for pre-
	 *                                  installation.
	 *    - self::CONN_CREATE_SCHEMA:   A connection to the new DB, for creating schemas and
	 *                                  other similar objects in the new DB.
	 *    - self::CONN_CREATE_TABLES:   A connection with a role suitable for creating tables.
	 * @return ConnectionStatus On success, a connection object will be in the value member.
	 */
	protected function openConnection( string $type ) {
		switch ( $type ) {
			case self::CONN_CREATE_DATABASE:
				return $this->openConnectionToAnyDB(
					$this->getVar( '_InstallUser' ),
					$this->getVar( '_InstallPassword' ) );
			case self::CONN_CREATE_SCHEMA:
				return $this->openConnectionWithParams(
					$this->getVar( '_InstallUser' ),
					$this->getVar( '_InstallPassword' ),
					$this->getVar( 'wgDBname' ),
					$this->getVar( 'wgDBmwschema' ) );
			case self::CONN_CREATE_TABLES:
				$status = $this->openConnection( self::CONN_CREATE_SCHEMA );
				if ( $status->isOK() ) {
					$status->merge( $this->changeConnTypeFromSchemaToTables( $status->getDB() ) );
				}

				return $status;
			default:
				throw new InvalidArgumentException( "Invalid connection type: \"$type\"" );
		}
	}

	protected function changeConnTypeFromSchemaToTables( IMaintainableDatabase $conn ) {
		if ( !( $conn instanceof DatabasePostgres ) ) {
			throw new InvalidArgumentException( 'Invalid connection type' );
		}
		$status = new ConnectionStatus( $conn );
		$schema = $this->getVar( 'wgDBmwschema' );
		if ( !$conn->schemaExists( $schema ) ) {
			$status->fatal( 'config-install-pg-schema-not-exist' );
			return $status;
		}
		$conn->determineCoreSchema( $schema );

		$safeRole = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
		$conn->query( "SET ROLE $safeRole", __METHOD__ );
		return $status;
	}

	public function openConnectionToAnyDB( $user, $password ) {
		$dbs = [
			'template1',
			'postgres',
		];
		if ( !in_array( $this->getVar( 'wgDBname' ), $dbs ) ) {
			array_unshift( $dbs, $this->getVar( 'wgDBname' ) );
		}
		$conn = false;
		$status = new ConnectionStatus;
		foreach ( $dbs as $db ) {
			try {
				$p = [
					'host' => $this->getVar( 'wgDBserver' ),
					'port' => $this->getVar( 'wgDBport' ),
					'user' => $user,
					'password' => $password,
					'ssl' => $this->getVar( 'wgDBssl' ),
					'dbname' => $db
				];
				$conn = ( new DatabaseFactory() )->create( 'postgres', $p );
			} catch ( DBConnectionError $error ) {
				$conn = false;
				$status->fatal( 'config-pg-test-error', $db,
					$error->getMessage() );
			}
			if ( $conn !== false ) {
				break;
			}
		}
		if ( $conn !== false ) {
			return new ConnectionStatus( $conn );
		} else {
			return $status;
		}
	}

	public function getLocalSettings() {
		$port = $this->getVar( 'wgDBport' );
		$useSsl = $this->getVar( 'wgDBssl' ) ? 'true' : 'false';
		$schema = $this->getVar( 'wgDBmwschema' );

		return "# Postgres specific settings
\$wgDBport = \"{$port}\";
\$wgDBssl = {$useSsl};
\$wgDBmwschema = \"{$schema}\";";
	}

	public function preUpgrade() {
		global $wgDBuser, $wgDBpassword;

		# Normal user and password are selected after this step, so for now
		# just copy these two
		$wgDBuser = $this->getVar( '_InstallUser' );
		$wgDBpassword = $this->getVar( '_InstallPassword' );
	}

	public function getGlobalDefaults() {
		// The default $wgDBmwschema is null, which breaks Postgres and other DBMSes that require
		// the use of a schema, so we need to set it here
		return array_merge( parent::getGlobalDefaults(), [
			'wgDBmwschema' => 'mediawiki',
		] );
	}
}