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
24 use Wikimedia\Rdbms\Database
;
25 use Wikimedia\Rdbms\DatabasePostgres
;
26 use Wikimedia\Rdbms\DBQueryError
;
27 use Wikimedia\Rdbms\DBConnectionError
;
30 * Class for setting up the MediaWiki database using Postgres.
35 class PostgresInstaller
extends DatabaseInstaller
{
37 protected $globalNames = [
46 protected $internalDefaults = [
47 '_InstallUser' => 'postgres',
50 public static $minimumVersion = '9.2';
51 protected static $notMinimumVersionMessage = 'config-postgres-old';
52 public $maxRoleSearchDepth = 5;
54 protected $pgConns = [];
60 public function isCompiled() {
61 return self
::checkExtension( 'pgsql' );
64 function getConnectForm() {
65 return $this->getTextBox(
69 $this->parent
->getHelpBox( 'config-db-host-help' )
71 $this->getTextBox( 'wgDBport', 'config-db-port' ) .
72 Html
::openElement( 'fieldset' ) .
73 Html
::element( 'legend', [], wfMessage( 'config-db-wiki-settings' )->text() ) .
78 $this->parent
->getHelpBox( 'config-db-name-help' )
84 $this->parent
->getHelpBox( 'config-db-schema-help' )
86 Html
::closeElement( 'fieldset' ) .
87 $this->getInstallUserBox();
90 function submitConnectForm() {
91 // Get variables from the request
92 $newValues = $this->setVarsFromRequest( [
100 $status = Status
::newGood();
101 if ( !strlen( $newValues['wgDBname'] ) ) {
102 $status->fatal( 'config-missing-db-name' );
103 } elseif ( !preg_match( '/^[a-zA-Z0-9_]+$/', $newValues['wgDBname'] ) ) {
104 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
106 if ( !preg_match( '/^[a-zA-Z0-9_]*$/', $newValues['wgDBmwschema'] ) ) {
107 $status->fatal( 'config-invalid-schema', $newValues['wgDBmwschema'] );
111 if ( $status->isOK() ) {
112 $status->merge( $this->submitInstallUserBox() );
114 if ( !$status->isOK() ) {
118 $status = $this->getPgConnection( 'create-db' );
119 if ( !$status->isOK() ) {
123 * @var Database $conn
125 $conn = $status->value
;
128 $version = $conn->getServerVersion();
129 $status = static::meetsMinimumRequirement( $version );
130 if ( !$status->isOK() ) {
134 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
135 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
137 return Status
::newGood();
140 public function getConnection() {
141 $status = $this->getPgConnection( 'create-tables' );
142 if ( $status->isOK() ) {
143 $this->db
= $status->value
;
149 public function openConnection() {
150 return $this->openPgConnection( 'create-tables' );
154 * Open a PG connection with given parameters
155 * @param string $user User name
156 * @param string $password
157 * @param string $dbName Database name
158 * @param string $schema Database schema
161 protected function openConnectionWithParams( $user, $password, $dbName, $schema ) {
162 $status = Status
::newGood();
164 $db = Database
::factory( 'postgres', [
165 'host' => $this->getVar( 'wgDBserver' ),
166 'port' => $this->getVar( 'wgDBport' ),
168 'password' => $password,
171 'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ],
173 $status->value
= $db;
174 } catch ( DBConnectionError
$e ) {
175 $status->fatal( 'config-connection-error', $e->getMessage() );
182 * Get a special type of connection
183 * @param string $type See openPgConnection() for details.
186 protected function getPgConnection( $type ) {
187 if ( isset( $this->pgConns
[$type] ) ) {
188 return Status
::newGood( $this->pgConns
[$type] );
190 $status = $this->openPgConnection( $type );
192 if ( $status->isOK() ) {
194 * @var Database $conn
196 $conn = $status->value
;
197 $conn->clearFlag( DBO_TRX
);
198 $conn->commit( __METHOD__
);
199 $this->pgConns
[$type] = $conn;
206 * Get a connection of a specific PostgreSQL-specific type. Connections
207 * of a given type are cached.
209 * PostgreSQL lacks cross-database operations, so after the new database is
210 * created, you need to make a separate connection to connect to that
211 * database and add tables to it.
213 * New tables are owned by the user that creates them, and MediaWiki's
214 * PostgreSQL support has always assumed that the table owner will be
215 * $wgDBuser. So before we create new tables, we either need to either
216 * connect as the other user or to execute a SET ROLE command. Using a
217 * separate connection for this allows us to avoid accidental cross-module
220 * @param string $type The type of connection to get:
221 * - create-db: A connection for creating DBs, suitable for pre-
223 * - create-schema: A connection to the new DB, for creating schemas and
224 * other similar objects in the new DB.
225 * - create-tables: A connection with a role suitable for creating tables.
227 * @throws MWException
228 * @return Status On success, a connection object will be in the value member.
230 protected function openPgConnection( $type ) {
233 return $this->openConnectionToAnyDB(
234 $this->getVar( '_InstallUser' ),
235 $this->getVar( '_InstallPassword' ) );
236 case 'create-schema':
237 return $this->openConnectionWithParams(
238 $this->getVar( '_InstallUser' ),
239 $this->getVar( '_InstallPassword' ),
240 $this->getVar( 'wgDBname' ),
241 $this->getVar( 'wgDBmwschema' ) );
242 case 'create-tables':
243 $status = $this->openPgConnection( 'create-schema' );
244 if ( $status->isOK() ) {
246 * @var Database $conn
248 $conn = $status->value
;
249 $safeRole = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
250 $conn->query( "SET ROLE $safeRole" );
255 throw new MWException( "Invalid special connection type: \"$type\"" );
259 public function openConnectionToAnyDB( $user, $password ) {
264 if ( !in_array( $this->getVar( 'wgDBname' ), $dbs ) ) {
265 array_unshift( $dbs, $this->getVar( 'wgDBname' ) );
268 $status = Status
::newGood();
269 foreach ( $dbs as $db ) {
272 'host' => $this->getVar( 'wgDBserver' ),
274 'password' => $password,
277 $conn = Database
::factory( 'postgres', $p );
278 } catch ( DBConnectionError
$error ) {
280 $status->fatal( 'config-pg-test-error', $db,
281 $error->getMessage() );
283 if ( $conn !== false ) {
287 if ( $conn !== false ) {
288 return Status
::newGood( $conn );
294 protected function getInstallUserPermissions() {
295 $status = $this->getPgConnection( 'create-db' );
296 if ( !$status->isOK() ) {
300 * @var Database $conn
302 $conn = $status->value
;
303 $superuser = $this->getVar( '_InstallUser' );
305 $row = $conn->selectRow( '"pg_catalog"."pg_roles"', '*',
306 [ 'rolname' => $superuser ], __METHOD__
);
311 protected function canCreateAccounts() {
312 $perms = $this->getInstallUserPermissions();
317 return $perms->rolsuper
=== 't' ||
$perms->rolcreaterole
=== 't';
320 protected function isSuperUser() {
321 $perms = $this->getInstallUserPermissions();
326 return $perms->rolsuper
=== 't';
329 public function getSettingsForm() {
330 if ( $this->canCreateAccounts() ) {
331 $noCreateMsg = false;
333 $noCreateMsg = 'config-db-web-no-create-privs';
335 $s = $this->getWebUserBox( $noCreateMsg );
340 public function submitSettingsForm() {
341 $status = $this->submitWebUserBox();
342 if ( !$status->isOK() ) {
346 $same = $this->getVar( 'wgDBuser' ) === $this->getVar( '_InstallUser' );
351 // Check if the web user exists
352 // Connect to the database with the install user
353 $status = $this->getPgConnection( 'create-db' );
354 if ( !$status->isOK() ) {
357 // @phan-suppress-next-line PhanUndeclaredMethod
358 $exists = $status->value
->roleExists( $this->getVar( 'wgDBuser' ) );
361 // Validate the create checkbox
362 if ( $this->canCreateAccounts() && !$same && !$exists ) {
363 $create = $this->getVar( '_CreateDBAccount' );
365 $this->setVar( '_CreateDBAccount', false );
369 if ( !$create && !$exists ) {
370 if ( $this->canCreateAccounts() ) {
371 $msg = 'config-install-user-missing-create';
373 $msg = 'config-install-user-missing';
376 return Status
::newFatal( $msg, $this->getVar( 'wgDBuser' ) );
380 // No more checks to do
381 return Status
::newGood();
384 // Existing web account. Test the connection.
385 $status = $this->openConnectionToAnyDB(
386 $this->getVar( 'wgDBuser' ),
387 $this->getVar( 'wgDBpassword' ) );
388 if ( !$status->isOK() ) {
392 // The web user is conventionally the table owner in PostgreSQL
393 // installations. Make sure the install user is able to create
394 // objects on behalf of the web user.
395 if ( $same ||
$this->canCreateObjectsForWebUser() ) {
396 return Status
::newGood();
398 return Status
::newFatal( 'config-pg-not-in-role' );
403 * Returns true if the install user is able to create objects owned
404 * by the web user, false otherwise.
407 protected function canCreateObjectsForWebUser() {
408 if ( $this->isSuperUser() ) {
412 $status = $this->getPgConnection( 'create-db' );
413 if ( !$status->isOK() ) {
416 $conn = $status->value
;
417 $installerId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
418 [ 'rolname' => $this->getVar( '_InstallUser' ) ], __METHOD__
);
419 $webId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
420 [ 'rolname' => $this->getVar( 'wgDBuser' ) ], __METHOD__
);
422 return $this->isRoleMember( $conn, $installerId, $webId, $this->maxRoleSearchDepth
);
426 * Recursive helper for canCreateObjectsForWebUser().
427 * @param Database $conn
428 * @param int $targetMember Role ID of the member to look for
429 * @param int $group Role ID of the group to look for
430 * @param int $maxDepth Maximum recursive search depth
433 protected function isRoleMember( $conn, $targetMember, $group, $maxDepth ) {
434 if ( $targetMember === $group ) {
435 // A role is always a member of itself
438 // Get all members of the given group
439 $res = $conn->select( '"pg_catalog"."pg_auth_members"', [ 'member' ],
440 [ 'roleid' => $group ], __METHOD__
);
441 foreach ( $res as $row ) {
442 if ( $row->member
== $targetMember ) {
443 // Found target member
446 // Recursively search each member of the group to see if the target
447 // is a member of it, up to the given maximum depth.
448 if ( $maxDepth > 0 &&
449 $this->isRoleMember( $conn, $targetMember, $row->member
, $maxDepth - 1 )
451 // Found member of member
459 public function preInstall() {
462 'callback' => [ $this, 'setupUser' ],
465 'name' => 'pg-commit',
466 'callback' => [ $this, 'commitChanges' ],
469 'name' => 'pg-plpgsql',
470 'callback' => [ $this, 'setupPLpgSQL' ],
474 'callback' => [ $this, 'setupSchema' ]
477 if ( $this->getVar( '_CreateDBAccount' ) ) {
478 $this->parent
->addInstallStep( $createDbAccount, 'database' );
480 $this->parent
->addInstallStep( $commitCB, 'interwiki' );
481 $this->parent
->addInstallStep( $plpgCB, 'database' );
482 $this->parent
->addInstallStep( $schemaCB, 'database' );
485 function setupDatabase() {
486 $status = $this->getPgConnection( 'create-db' );
487 if ( !$status->isOK() ) {
490 $conn = $status->value
;
492 $dbName = $this->getVar( 'wgDBname' );
494 $exists = $conn->selectField( '"pg_catalog"."pg_database"', '1',
495 [ 'datname' => $dbName ], __METHOD__
);
497 $safedb = $conn->addIdentifierQuotes( $dbName );
498 $conn->query( "CREATE DATABASE $safedb", __METHOD__
);
501 return Status
::newGood();
504 function setupSchema() {
505 // Get a connection to the target database
506 $status = $this->getPgConnection( 'create-schema' );
507 if ( !$status->isOK() ) {
510 /** @var DatabasePostgres $conn */
511 $conn = $status->value
;
512 '@phan-var DatabasePostgres $conn';
514 // Create the schema if necessary
515 $schema = $this->getVar( 'wgDBmwschema' );
516 $safeschema = $conn->addIdentifierQuotes( $schema );
517 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
518 if ( !$conn->schemaExists( $schema ) ) {
520 $conn->query( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
521 } catch ( DBQueryError
$e ) {
522 return Status
::newFatal( 'config-install-pg-schema-failed',
523 $this->getVar( '_InstallUser' ), $schema );
527 // Select the new schema in the current connection
528 $conn->determineCoreSchema( $schema );
530 return Status
::newGood();
533 function commitChanges() {
534 $this->db
->commit( __METHOD__
);
536 return Status
::newGood();
539 function setupUser() {
540 if ( !$this->getVar( '_CreateDBAccount' ) ) {
541 return Status
::newGood();
544 $status = $this->getPgConnection( 'create-db' );
545 if ( !$status->isOK() ) {
548 /** @var DatabasePostgres $conn */
549 $conn = $status->value
;
550 '@phan-var DatabasePostgres $conn';
552 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
553 $safepass = $conn->addQuotes( $this->getVar( 'wgDBpassword' ) );
555 // Check if the user already exists
556 $userExists = $conn->roleExists( $this->getVar( 'wgDBuser' ) );
557 if ( !$userExists ) {
560 $sql = "CREATE ROLE $safeuser NOCREATEDB LOGIN PASSWORD $safepass";
562 // If the install user is not a superuser, we need to make the install
563 // user a member of the new user's group, so that the install user will
564 // be able to create a schema and other objects on behalf of the new user.
565 if ( !$this->isSuperUser() ) {
566 $sql .= ' ROLE' . $conn->addIdentifierQuotes( $this->getVar( '_InstallUser' ) );
569 $conn->query( $sql, __METHOD__
);
570 } catch ( DBQueryError
$e ) {
571 return Status
::newFatal( 'config-install-user-create-failed',
572 $this->getVar( 'wgDBuser' ), $e->getMessage() );
576 return Status
::newGood();
579 function getLocalSettings() {
580 $port = $this->getVar( 'wgDBport' );
581 $schema = $this->getVar( 'wgDBmwschema' );
583 return "# Postgres specific settings
584 \$wgDBport = \"{$port}\";
585 \$wgDBmwschema = \"{$schema}\";";
588 public function preUpgrade() {
589 global $wgDBuser, $wgDBpassword;
591 # Normal user and password are selected after this step, so for now
592 # just copy these two
593 $wgDBuser = $this->getVar( '_InstallUser' );
594 $wgDBpassword = $this->getVar( '_InstallPassword' );
597 public function createTables() {
598 $schema = $this->getVar( 'wgDBmwschema' );
600 $status = $this->getConnection();
601 if ( !$status->isOK() ) {
605 /** @var DatabasePostgres $conn */
606 $conn = $status->value
;
607 '@phan-var DatabasePostgres $conn';
609 if ( $conn->tableExists( 'archive' ) ) {
610 $status->warning( 'config-install-tables-exist' );
616 $conn->begin( __METHOD__
);
618 if ( !$conn->schemaExists( $schema ) ) {
619 $status->fatal( 'config-install-pg-schema-not-exist' );
623 $error = $conn->sourceFile( $this->getSchemaPath( $conn ) );
624 if ( $error !== true ) {
625 $conn->reportQueryError( $error, 0, '', __METHOD__
);
626 $conn->rollback( __METHOD__
);
627 $status->fatal( 'config-install-tables-failed', $error );
629 $conn->commit( __METHOD__
);
631 // Resume normal operations
632 if ( $status->isOK() ) {
639 public function getGlobalDefaults() {
640 // The default $wgDBmwschema is null, which breaks Postgres and other DBMSes that require
641 // the use of a schema, so we need to set it here
642 return array_merge( parent
::getGlobalDefaults(), [
643 'wgDBmwschema' => 'mediawiki',
647 public function setupPLpgSQL() {
648 // Connect as the install user, since it owns the database and so is
649 // the user that needs to run "CREATE LANGUAGE"
650 $status = $this->getPgConnection( 'create-schema' );
651 if ( !$status->isOK() ) {
655 * @var Database $conn
657 $conn = $status->value
;
659 $exists = $conn->selectField( '"pg_catalog"."pg_language"', 1,
660 [ 'lanname' => 'plpgsql' ], __METHOD__
);
662 // Already exists, nothing to do
663 return Status
::newGood();
666 // plpgsql is not installed, but if we have a pg_pltemplate table, we
667 // should be able to create it
668 $exists = $conn->selectField(
669 [ '"pg_catalog"."pg_class"', '"pg_catalog"."pg_namespace"' ],
672 'pg_namespace.oid=relnamespace',
673 'nspname' => 'pg_catalog',
674 'relname' => 'pg_pltemplate',
679 $conn->query( 'CREATE LANGUAGE plpgsql' );
680 } catch ( DBQueryError
$e ) {
681 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
684 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
687 return Status
::newGood();