3 * PostgreSQL-specific installer.
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.
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.
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
25 * Class for setting up the MediaWiki database using Postgres.
30 class PostgresInstaller
extends DatabaseInstaller
{
32 protected $globalNames = [
41 protected $internalDefaults = [
42 '_InstallUser' => 'postgres',
45 public $minimumVersion = '8.3';
46 public $maxRoleSearchDepth = 5;
48 protected $pgConns = [];
54 public function isCompiled() {
55 return self
::checkExtension( 'pgsql' );
58 function getConnectForm() {
59 return $this->getTextBox(
63 $this->parent
->getHelpBox( 'config-db-host-help' )
65 $this->getTextBox( 'wgDBport', 'config-db-port' ) .
66 Html
::openElement( 'fieldset' ) .
67 Html
::element( 'legend', [], wfMessage( 'config-db-wiki-settings' )->text() ) .
72 $this->parent
->getHelpBox( 'config-db-name-help' )
78 $this->parent
->getHelpBox( 'config-db-schema-help' )
80 Html
::closeElement( 'fieldset' ) .
81 $this->getInstallUserBox();
84 function submitConnectForm() {
85 // Get variables from the request
86 $newValues = $this->setVarsFromRequest( [
94 $status = Status
::newGood();
95 if ( !strlen( $newValues['wgDBname'] ) ) {
96 $status->fatal( 'config-missing-db-name' );
97 } elseif ( !preg_match( '/^[a-zA-Z0-9_]+$/', $newValues['wgDBname'] ) ) {
98 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
100 if ( !preg_match( '/^[a-zA-Z0-9_]*$/', $newValues['wgDBmwschema'] ) ) {
101 $status->fatal( 'config-invalid-schema', $newValues['wgDBmwschema'] );
105 if ( $status->isOK() ) {
106 $status->merge( $this->submitInstallUserBox() );
108 if ( !$status->isOK() ) {
112 $status = $this->getPgConnection( 'create-db' );
113 if ( !$status->isOK() ) {
117 * @var $conn Database
119 $conn = $status->value
;
122 $version = $conn->getServerVersion();
123 if ( version_compare( $version, $this->minimumVersion
) < 0 ) {
124 return Status
::newFatal( 'config-postgres-old', $this->minimumVersion
, $version );
127 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
128 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
130 return Status
::newGood();
133 public function getConnection() {
134 $status = $this->getPgConnection( 'create-tables' );
135 if ( $status->isOK() ) {
136 $this->db
= $status->value
;
142 public function openConnection() {
143 return $this->openPgConnection( 'create-tables' );
147 * Open a PG connection with given parameters
148 * @param string $user User name
149 * @param string $password Password
150 * @param string $dbName Database name
151 * @param string $schema Database schema
154 protected function openConnectionWithParams( $user, $password, $dbName, $schema ) {
155 $status = Status
::newGood();
157 $db = Database
::factory( 'postgres', [
158 'host' => $this->getVar( 'wgDBserver' ),
159 'port' => $this->getVar( 'wgDBport' ),
161 'password' => $password,
164 'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ],
166 $status->value
= $db;
167 } catch ( DBConnectionError
$e ) {
168 $status->fatal( 'config-connection-error', $e->getMessage() );
175 * Get a special type of connection
176 * @param string $type See openPgConnection() for details.
179 protected function getPgConnection( $type ) {
180 if ( isset( $this->pgConns
[$type] ) ) {
181 return Status
::newGood( $this->pgConns
[$type] );
183 $status = $this->openPgConnection( $type );
185 if ( $status->isOK() ) {
187 * @var $conn Database
189 $conn = $status->value
;
190 $conn->clearFlag( DBO_TRX
);
191 $conn->commit( __METHOD__
);
192 $this->pgConns
[$type] = $conn;
199 * Get a connection of a specific PostgreSQL-specific type. Connections
200 * of a given type are cached.
202 * PostgreSQL lacks cross-database operations, so after the new database is
203 * created, you need to make a separate connection to connect to that
204 * database and add tables to it.
206 * New tables are owned by the user that creates them, and MediaWiki's
207 * PostgreSQL support has always assumed that the table owner will be
208 * $wgDBuser. So before we create new tables, we either need to either
209 * connect as the other user or to execute a SET ROLE command. Using a
210 * separate connection for this allows us to avoid accidental cross-module
213 * @param string $type The type of connection to get:
214 * - create-db: A connection for creating DBs, suitable for pre-
216 * - create-schema: A connection to the new DB, for creating schemas and
217 * other similar objects in the new DB.
218 * - create-tables: A connection with a role suitable for creating tables.
220 * @throws MWException
221 * @return Status On success, a connection object will be in the value member.
223 protected function openPgConnection( $type ) {
226 return $this->openConnectionToAnyDB(
227 $this->getVar( '_InstallUser' ),
228 $this->getVar( '_InstallPassword' ) );
229 case 'create-schema':
230 return $this->openConnectionWithParams(
231 $this->getVar( '_InstallUser' ),
232 $this->getVar( '_InstallPassword' ),
233 $this->getVar( 'wgDBname' ),
234 $this->getVar( 'wgDBmwschema' ) );
235 case 'create-tables':
236 $status = $this->openPgConnection( 'create-schema' );
237 if ( $status->isOK() ) {
239 * @var $conn Database
241 $conn = $status->value
;
242 $safeRole = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
243 $conn->query( "SET ROLE $safeRole" );
248 throw new MWException( "Invalid special connection type: \"$type\"" );
252 public function openConnectionToAnyDB( $user, $password ) {
257 if ( !in_array( $this->getVar( 'wgDBname' ), $dbs ) ) {
258 array_unshift( $dbs, $this->getVar( 'wgDBname' ) );
261 $status = Status
::newGood();
262 foreach ( $dbs as $db ) {
265 'host' => $this->getVar( 'wgDBserver' ),
267 'password' => $password,
270 $conn = Database
::factory( 'postgres', $p );
271 } catch ( DBConnectionError
$error ) {
273 $status->fatal( 'config-pg-test-error', $db,
274 $error->getMessage() );
276 if ( $conn !== false ) {
280 if ( $conn !== false ) {
281 return Status
::newGood( $conn );
287 protected function getInstallUserPermissions() {
288 $status = $this->getPgConnection( 'create-db' );
289 if ( !$status->isOK() ) {
293 * @var $conn Database
295 $conn = $status->value
;
296 $superuser = $this->getVar( '_InstallUser' );
298 $row = $conn->selectRow( '"pg_catalog"."pg_roles"', '*',
299 [ 'rolname' => $superuser ], __METHOD__
);
304 protected function canCreateAccounts() {
305 $perms = $this->getInstallUserPermissions();
310 return $perms->rolsuper
=== 't' ||
$perms->rolcreaterole
=== 't';
313 protected function isSuperUser() {
314 $perms = $this->getInstallUserPermissions();
319 return $perms->rolsuper
=== 't';
322 public function getSettingsForm() {
323 if ( $this->canCreateAccounts() ) {
324 $noCreateMsg = false;
326 $noCreateMsg = 'config-db-web-no-create-privs';
328 $s = $this->getWebUserBox( $noCreateMsg );
333 public function submitSettingsForm() {
334 $status = $this->submitWebUserBox();
335 if ( !$status->isOK() ) {
339 $same = $this->getVar( 'wgDBuser' ) === $this->getVar( '_InstallUser' );
344 // Check if the web user exists
345 // Connect to the database with the install user
346 $status = $this->getPgConnection( 'create-db' );
347 if ( !$status->isOK() ) {
350 $exists = $status->value
->roleExists( $this->getVar( 'wgDBuser' ) );
353 // Validate the create checkbox
354 if ( $this->canCreateAccounts() && !$same && !$exists ) {
355 $create = $this->getVar( '_CreateDBAccount' );
357 $this->setVar( '_CreateDBAccount', false );
361 if ( !$create && !$exists ) {
362 if ( $this->canCreateAccounts() ) {
363 $msg = 'config-install-user-missing-create';
365 $msg = 'config-install-user-missing';
368 return Status
::newFatal( $msg, $this->getVar( 'wgDBuser' ) );
372 // No more checks to do
373 return Status
::newGood();
376 // Existing web account. Test the connection.
377 $status = $this->openConnectionToAnyDB(
378 $this->getVar( 'wgDBuser' ),
379 $this->getVar( 'wgDBpassword' ) );
380 if ( !$status->isOK() ) {
384 // The web user is conventionally the table owner in PostgreSQL
385 // installations. Make sure the install user is able to create
386 // objects on behalf of the web user.
387 if ( $same ||
$this->canCreateObjectsForWebUser() ) {
388 return Status
::newGood();
390 return Status
::newFatal( 'config-pg-not-in-role' );
395 * Returns true if the install user is able to create objects owned
396 * by the web user, false otherwise.
399 protected function canCreateObjectsForWebUser() {
400 if ( $this->isSuperUser() ) {
404 $status = $this->getPgConnection( 'create-db' );
405 if ( !$status->isOK() ) {
408 $conn = $status->value
;
409 $installerId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
410 [ 'rolname' => $this->getVar( '_InstallUser' ) ], __METHOD__
);
411 $webId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
412 [ 'rolname' => $this->getVar( 'wgDBuser' ) ], __METHOD__
);
414 return $this->isRoleMember( $conn, $installerId, $webId, $this->maxRoleSearchDepth
);
418 * Recursive helper for canCreateObjectsForWebUser().
419 * @param Database $conn
420 * @param int $targetMember Role ID of the member to look for
421 * @param int $group Role ID of the group to look for
422 * @param int $maxDepth Maximum recursive search depth
425 protected function isRoleMember( $conn, $targetMember, $group, $maxDepth ) {
426 if ( $targetMember === $group ) {
427 // A role is always a member of itself
430 // Get all members of the given group
431 $res = $conn->select( '"pg_catalog"."pg_auth_members"', [ 'member' ],
432 [ 'roleid' => $group ], __METHOD__
);
433 foreach ( $res as $row ) {
434 if ( $row->member
== $targetMember ) {
435 // Found target member
438 // Recursively search each member of the group to see if the target
439 // is a member of it, up to the given maximum depth.
440 if ( $maxDepth > 0 ) {
441 if ( $this->isRoleMember( $conn, $targetMember, $row->member
, $maxDepth - 1 ) ) {
442 // Found member of member
451 public function preInstall() {
454 'callback' => [ $this, 'setupUser' ],
457 'name' => 'pg-commit',
458 'callback' => [ $this, 'commitChanges' ],
461 'name' => 'pg-plpgsql',
462 'callback' => [ $this, 'setupPLpgSQL' ],
466 'callback' => [ $this, 'setupSchema' ]
469 if ( $this->getVar( '_CreateDBAccount' ) ) {
470 $this->parent
->addInstallStep( $createDbAccount, 'database' );
472 $this->parent
->addInstallStep( $commitCB, 'interwiki' );
473 $this->parent
->addInstallStep( $plpgCB, 'database' );
474 $this->parent
->addInstallStep( $schemaCB, 'database' );
477 function setupDatabase() {
478 $status = $this->getPgConnection( 'create-db' );
479 if ( !$status->isOK() ) {
482 $conn = $status->value
;
484 $dbName = $this->getVar( 'wgDBname' );
486 $exists = $conn->selectField( '"pg_catalog"."pg_database"', '1',
487 [ 'datname' => $dbName ], __METHOD__
);
489 $safedb = $conn->addIdentifierQuotes( $dbName );
490 $conn->query( "CREATE DATABASE $safedb", __METHOD__
);
493 return Status
::newGood();
496 function setupSchema() {
497 // Get a connection to the target database
498 $status = $this->getPgConnection( 'create-schema' );
499 if ( !$status->isOK() ) {
502 $conn = $status->value
;
504 // Create the schema if necessary
505 $schema = $this->getVar( 'wgDBmwschema' );
506 $safeschema = $conn->addIdentifierQuotes( $schema );
507 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
508 if ( !$conn->schemaExists( $schema ) ) {
510 $conn->query( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
511 } catch ( DBQueryError
$e ) {
512 return Status
::newFatal( 'config-install-pg-schema-failed',
513 $this->getVar( '_InstallUser' ), $schema );
517 // Select the new schema in the current connection
518 $conn->determineCoreSchema( $schema );
520 return Status
::newGood();
523 function commitChanges() {
524 $this->db
->commit( __METHOD__
);
526 return Status
::newGood();
529 function setupUser() {
530 if ( !$this->getVar( '_CreateDBAccount' ) ) {
531 return Status
::newGood();
534 $status = $this->getPgConnection( 'create-db' );
535 if ( !$status->isOK() ) {
538 $conn = $status->value
;
540 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
541 $safepass = $conn->addQuotes( $this->getVar( 'wgDBpassword' ) );
543 // Check if the user already exists
544 $userExists = $conn->roleExists( $this->getVar( 'wgDBuser' ) );
545 if ( !$userExists ) {
548 $sql = "CREATE ROLE $safeuser NOCREATEDB LOGIN PASSWORD $safepass";
550 // If the install user is not a superuser, we need to make the install
551 // user a member of the new user's group, so that the install user will
552 // be able to create a schema and other objects on behalf of the new user.
553 if ( !$this->isSuperUser() ) {
554 $sql .= ' ROLE' . $conn->addIdentifierQuotes( $this->getVar( '_InstallUser' ) );
557 $conn->query( $sql, __METHOD__
);
558 } catch ( DBQueryError
$e ) {
559 return Status
::newFatal( 'config-install-user-create-failed',
560 $this->getVar( 'wgDBuser' ), $e->getMessage() );
564 return Status
::newGood();
567 function getLocalSettings() {
568 $port = $this->getVar( 'wgDBport' );
569 $schema = $this->getVar( 'wgDBmwschema' );
571 return "# Postgres specific settings
572 \$wgDBport = \"{$port}\";
573 \$wgDBmwschema = \"{$schema}\";";
576 public function preUpgrade() {
577 global $wgDBuser, $wgDBpassword;
579 # Normal user and password are selected after this step, so for now
580 # just copy these two
581 $wgDBuser = $this->getVar( '_InstallUser' );
582 $wgDBpassword = $this->getVar( '_InstallPassword' );
585 public function createTables() {
586 $schema = $this->getVar( 'wgDBmwschema' );
588 $status = $this->getConnection();
589 if ( !$status->isOK() ) {
593 /** @var $conn DatabasePostgres */
594 $conn = $status->value
;
596 if ( $conn->tableExists( 'archive' ) ) {
597 $status->warning( 'config-install-tables-exist' );
603 $conn->begin( __METHOD__
);
605 if ( !$conn->schemaExists( $schema ) ) {
606 $status->fatal( 'config-install-pg-schema-not-exist' );
610 $error = $conn->sourceFile( $this->getSchemaPath( $conn ) );
611 if ( $error !== true ) {
612 $conn->reportQueryError( $error, 0, '', __METHOD__
);
613 $conn->rollback( __METHOD__
);
614 $status->fatal( 'config-install-tables-failed', $error );
616 $conn->commit( __METHOD__
);
618 // Resume normal operations
619 if ( $status->isOK() ) {
626 public function getGlobalDefaults() {
627 // The default $wgDBmwschema is null, which breaks Postgres and other DBMSes that require
628 // the use of a schema, so we need to set it here
629 return array_merge( parent
::getGlobalDefaults(), [
630 'wgDBmwschema' => 'mediawiki',
634 public function setupPLpgSQL() {
635 // Connect as the install user, since it owns the database and so is
636 // the user that needs to run "CREATE LANGAUGE"
637 $status = $this->getPgConnection( 'create-schema' );
638 if ( !$status->isOK() ) {
642 * @var $conn Database
644 $conn = $status->value
;
646 $exists = $conn->selectField( '"pg_catalog"."pg_language"', 1,
647 [ 'lanname' => 'plpgsql' ], __METHOD__
);
649 // Already exists, nothing to do
650 return Status
::newGood();
653 // plpgsql is not installed, but if we have a pg_pltemplate table, we
654 // should be able to create it
655 $exists = $conn->selectField(
656 [ '"pg_catalog"."pg_class"', '"pg_catalog"."pg_namespace"' ],
659 'pg_namespace.oid=relnamespace',
660 'nspname' => 'pg_catalog',
661 'relname' => 'pg_pltemplate',
666 $conn->query( 'CREATE LANGUAGE plpgsql' );
667 } catch ( DBQueryError
$e ) {
668 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
671 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
674 return Status
::newGood();