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\DBQueryError
;
26 use Wikimedia\Rdbms\DBConnectionError
;
29 * Class for setting up the MediaWiki database using Postgres.
34 class PostgresInstaller
extends DatabaseInstaller
{
36 protected $globalNames = [
45 protected $internalDefaults = [
46 '_InstallUser' => 'postgres',
49 public $minimumVersion = '8.3';
50 public $maxRoleSearchDepth = 5;
52 protected $pgConns = [];
58 public function isCompiled() {
59 return self
::checkExtension( 'pgsql' );
62 function getConnectForm() {
63 return $this->getTextBox(
67 $this->parent
->getHelpBox( 'config-db-host-help' )
69 $this->getTextBox( 'wgDBport', 'config-db-port' ) .
70 Html
::openElement( 'fieldset' ) .
71 Html
::element( 'legend', [], wfMessage( 'config-db-wiki-settings' )->text() ) .
76 $this->parent
->getHelpBox( 'config-db-name-help' )
82 $this->parent
->getHelpBox( 'config-db-schema-help' )
84 Html
::closeElement( 'fieldset' ) .
85 $this->getInstallUserBox();
88 function submitConnectForm() {
89 // Get variables from the request
90 $newValues = $this->setVarsFromRequest( [
98 $status = Status
::newGood();
99 if ( !strlen( $newValues['wgDBname'] ) ) {
100 $status->fatal( 'config-missing-db-name' );
101 } elseif ( !preg_match( '/^[a-zA-Z0-9_]+$/', $newValues['wgDBname'] ) ) {
102 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
104 if ( !preg_match( '/^[a-zA-Z0-9_]*$/', $newValues['wgDBmwschema'] ) ) {
105 $status->fatal( 'config-invalid-schema', $newValues['wgDBmwschema'] );
109 if ( $status->isOK() ) {
110 $status->merge( $this->submitInstallUserBox() );
112 if ( !$status->isOK() ) {
116 $status = $this->getPgConnection( 'create-db' );
117 if ( !$status->isOK() ) {
121 * @var $conn Database
123 $conn = $status->value
;
126 $version = $conn->getServerVersion();
127 if ( version_compare( $version, $this->minimumVersion
) < 0 ) {
128 return Status
::newFatal( 'config-postgres-old', $this->minimumVersion
, $version );
131 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
132 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
134 return Status
::newGood();
137 public function getConnection() {
138 $status = $this->getPgConnection( 'create-tables' );
139 if ( $status->isOK() ) {
140 $this->db
= $status->value
;
146 public function openConnection() {
147 return $this->openPgConnection( 'create-tables' );
151 * Open a PG connection with given parameters
152 * @param string $user User name
153 * @param string $password Password
154 * @param string $dbName Database name
155 * @param string $schema Database schema
158 protected function openConnectionWithParams( $user, $password, $dbName, $schema ) {
159 $status = Status
::newGood();
161 $db = Database
::factory( 'postgres', [
162 'host' => $this->getVar( 'wgDBserver' ),
163 'port' => $this->getVar( 'wgDBport' ),
165 'password' => $password,
168 'keywordTableMap' => [ 'user' => 'mwuser', 'text' => 'pagecontent' ],
170 $status->value
= $db;
171 } catch ( DBConnectionError
$e ) {
172 $status->fatal( 'config-connection-error', $e->getMessage() );
179 * Get a special type of connection
180 * @param string $type See openPgConnection() for details.
183 protected function getPgConnection( $type ) {
184 if ( isset( $this->pgConns
[$type] ) ) {
185 return Status
::newGood( $this->pgConns
[$type] );
187 $status = $this->openPgConnection( $type );
189 if ( $status->isOK() ) {
191 * @var $conn Database
193 $conn = $status->value
;
194 $conn->clearFlag( DBO_TRX
);
195 $conn->commit( __METHOD__
);
196 $this->pgConns
[$type] = $conn;
203 * Get a connection of a specific PostgreSQL-specific type. Connections
204 * of a given type are cached.
206 * PostgreSQL lacks cross-database operations, so after the new database is
207 * created, you need to make a separate connection to connect to that
208 * database and add tables to it.
210 * New tables are owned by the user that creates them, and MediaWiki's
211 * PostgreSQL support has always assumed that the table owner will be
212 * $wgDBuser. So before we create new tables, we either need to either
213 * connect as the other user or to execute a SET ROLE command. Using a
214 * separate connection for this allows us to avoid accidental cross-module
217 * @param string $type The type of connection to get:
218 * - create-db: A connection for creating DBs, suitable for pre-
220 * - create-schema: A connection to the new DB, for creating schemas and
221 * other similar objects in the new DB.
222 * - create-tables: A connection with a role suitable for creating tables.
224 * @throws MWException
225 * @return Status On success, a connection object will be in the value member.
227 protected function openPgConnection( $type ) {
230 return $this->openConnectionToAnyDB(
231 $this->getVar( '_InstallUser' ),
232 $this->getVar( '_InstallPassword' ) );
233 case 'create-schema':
234 return $this->openConnectionWithParams(
235 $this->getVar( '_InstallUser' ),
236 $this->getVar( '_InstallPassword' ),
237 $this->getVar( 'wgDBname' ),
238 $this->getVar( 'wgDBmwschema' ) );
239 case 'create-tables':
240 $status = $this->openPgConnection( 'create-schema' );
241 if ( $status->isOK() ) {
243 * @var $conn Database
245 $conn = $status->value
;
246 $safeRole = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
247 $conn->query( "SET ROLE $safeRole" );
252 throw new MWException( "Invalid special connection type: \"$type\"" );
256 public function openConnectionToAnyDB( $user, $password ) {
261 if ( !in_array( $this->getVar( 'wgDBname' ), $dbs ) ) {
262 array_unshift( $dbs, $this->getVar( 'wgDBname' ) );
265 $status = Status
::newGood();
266 foreach ( $dbs as $db ) {
269 'host' => $this->getVar( 'wgDBserver' ),
271 'password' => $password,
274 $conn = Database
::factory( 'postgres', $p );
275 } catch ( DBConnectionError
$error ) {
277 $status->fatal( 'config-pg-test-error', $db,
278 $error->getMessage() );
280 if ( $conn !== false ) {
284 if ( $conn !== false ) {
285 return Status
::newGood( $conn );
291 protected function getInstallUserPermissions() {
292 $status = $this->getPgConnection( 'create-db' );
293 if ( !$status->isOK() ) {
297 * @var $conn Database
299 $conn = $status->value
;
300 $superuser = $this->getVar( '_InstallUser' );
302 $row = $conn->selectRow( '"pg_catalog"."pg_roles"', '*',
303 [ 'rolname' => $superuser ], __METHOD__
);
308 protected function canCreateAccounts() {
309 $perms = $this->getInstallUserPermissions();
314 return $perms->rolsuper
=== 't' ||
$perms->rolcreaterole
=== 't';
317 protected function isSuperUser() {
318 $perms = $this->getInstallUserPermissions();
323 return $perms->rolsuper
=== 't';
326 public function getSettingsForm() {
327 if ( $this->canCreateAccounts() ) {
328 $noCreateMsg = false;
330 $noCreateMsg = 'config-db-web-no-create-privs';
332 $s = $this->getWebUserBox( $noCreateMsg );
337 public function submitSettingsForm() {
338 $status = $this->submitWebUserBox();
339 if ( !$status->isOK() ) {
343 $same = $this->getVar( 'wgDBuser' ) === $this->getVar( '_InstallUser' );
348 // Check if the web user exists
349 // Connect to the database with the install user
350 $status = $this->getPgConnection( 'create-db' );
351 if ( !$status->isOK() ) {
354 $exists = $status->value
->roleExists( $this->getVar( 'wgDBuser' ) );
357 // Validate the create checkbox
358 if ( $this->canCreateAccounts() && !$same && !$exists ) {
359 $create = $this->getVar( '_CreateDBAccount' );
361 $this->setVar( '_CreateDBAccount', false );
365 if ( !$create && !$exists ) {
366 if ( $this->canCreateAccounts() ) {
367 $msg = 'config-install-user-missing-create';
369 $msg = 'config-install-user-missing';
372 return Status
::newFatal( $msg, $this->getVar( 'wgDBuser' ) );
376 // No more checks to do
377 return Status
::newGood();
380 // Existing web account. Test the connection.
381 $status = $this->openConnectionToAnyDB(
382 $this->getVar( 'wgDBuser' ),
383 $this->getVar( 'wgDBpassword' ) );
384 if ( !$status->isOK() ) {
388 // The web user is conventionally the table owner in PostgreSQL
389 // installations. Make sure the install user is able to create
390 // objects on behalf of the web user.
391 if ( $same ||
$this->canCreateObjectsForWebUser() ) {
392 return Status
::newGood();
394 return Status
::newFatal( 'config-pg-not-in-role' );
399 * Returns true if the install user is able to create objects owned
400 * by the web user, false otherwise.
403 protected function canCreateObjectsForWebUser() {
404 if ( $this->isSuperUser() ) {
408 $status = $this->getPgConnection( 'create-db' );
409 if ( !$status->isOK() ) {
412 $conn = $status->value
;
413 $installerId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
414 [ 'rolname' => $this->getVar( '_InstallUser' ) ], __METHOD__
);
415 $webId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
416 [ 'rolname' => $this->getVar( 'wgDBuser' ) ], __METHOD__
);
418 return $this->isRoleMember( $conn, $installerId, $webId, $this->maxRoleSearchDepth
);
422 * Recursive helper for canCreateObjectsForWebUser().
423 * @param Database $conn
424 * @param int $targetMember Role ID of the member to look for
425 * @param int $group Role ID of the group to look for
426 * @param int $maxDepth Maximum recursive search depth
429 protected function isRoleMember( $conn, $targetMember, $group, $maxDepth ) {
430 if ( $targetMember === $group ) {
431 // A role is always a member of itself
434 // Get all members of the given group
435 $res = $conn->select( '"pg_catalog"."pg_auth_members"', [ 'member' ],
436 [ 'roleid' => $group ], __METHOD__
);
437 foreach ( $res as $row ) {
438 if ( $row->member
== $targetMember ) {
439 // Found target member
442 // Recursively search each member of the group to see if the target
443 // is a member of it, up to the given maximum depth.
444 if ( $maxDepth > 0 ) {
445 if ( $this->isRoleMember( $conn, $targetMember, $row->member
, $maxDepth - 1 ) ) {
446 // Found member of member
455 public function preInstall() {
458 'callback' => [ $this, 'setupUser' ],
461 'name' => 'pg-commit',
462 'callback' => [ $this, 'commitChanges' ],
465 'name' => 'pg-plpgsql',
466 'callback' => [ $this, 'setupPLpgSQL' ],
470 'callback' => [ $this, 'setupSchema' ]
473 if ( $this->getVar( '_CreateDBAccount' ) ) {
474 $this->parent
->addInstallStep( $createDbAccount, 'database' );
476 $this->parent
->addInstallStep( $commitCB, 'interwiki' );
477 $this->parent
->addInstallStep( $plpgCB, 'database' );
478 $this->parent
->addInstallStep( $schemaCB, 'database' );
481 function setupDatabase() {
482 $status = $this->getPgConnection( 'create-db' );
483 if ( !$status->isOK() ) {
486 $conn = $status->value
;
488 $dbName = $this->getVar( 'wgDBname' );
490 $exists = $conn->selectField( '"pg_catalog"."pg_database"', '1',
491 [ 'datname' => $dbName ], __METHOD__
);
493 $safedb = $conn->addIdentifierQuotes( $dbName );
494 $conn->query( "CREATE DATABASE $safedb", __METHOD__
);
497 return Status
::newGood();
500 function setupSchema() {
501 // Get a connection to the target database
502 $status = $this->getPgConnection( 'create-schema' );
503 if ( !$status->isOK() ) {
506 $conn = $status->value
;
508 // Create the schema if necessary
509 $schema = $this->getVar( 'wgDBmwschema' );
510 $safeschema = $conn->addIdentifierQuotes( $schema );
511 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
512 if ( !$conn->schemaExists( $schema ) ) {
514 $conn->query( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
515 } catch ( DBQueryError
$e ) {
516 return Status
::newFatal( 'config-install-pg-schema-failed',
517 $this->getVar( '_InstallUser' ), $schema );
521 // Select the new schema in the current connection
522 $conn->determineCoreSchema( $schema );
524 return Status
::newGood();
527 function commitChanges() {
528 $this->db
->commit( __METHOD__
);
530 return Status
::newGood();
533 function setupUser() {
534 if ( !$this->getVar( '_CreateDBAccount' ) ) {
535 return Status
::newGood();
538 $status = $this->getPgConnection( 'create-db' );
539 if ( !$status->isOK() ) {
542 $conn = $status->value
;
544 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
545 $safepass = $conn->addQuotes( $this->getVar( 'wgDBpassword' ) );
547 // Check if the user already exists
548 $userExists = $conn->roleExists( $this->getVar( 'wgDBuser' ) );
549 if ( !$userExists ) {
552 $sql = "CREATE ROLE $safeuser NOCREATEDB LOGIN PASSWORD $safepass";
554 // If the install user is not a superuser, we need to make the install
555 // user a member of the new user's group, so that the install user will
556 // be able to create a schema and other objects on behalf of the new user.
557 if ( !$this->isSuperUser() ) {
558 $sql .= ' ROLE' . $conn->addIdentifierQuotes( $this->getVar( '_InstallUser' ) );
561 $conn->query( $sql, __METHOD__
);
562 } catch ( DBQueryError
$e ) {
563 return Status
::newFatal( 'config-install-user-create-failed',
564 $this->getVar( 'wgDBuser' ), $e->getMessage() );
568 return Status
::newGood();
571 function getLocalSettings() {
572 $port = $this->getVar( 'wgDBport' );
573 $schema = $this->getVar( 'wgDBmwschema' );
575 return "# Postgres specific settings
576 \$wgDBport = \"{$port}\";
577 \$wgDBmwschema = \"{$schema}\";";
580 public function preUpgrade() {
581 global $wgDBuser, $wgDBpassword;
583 # Normal user and password are selected after this step, so for now
584 # just copy these two
585 $wgDBuser = $this->getVar( '_InstallUser' );
586 $wgDBpassword = $this->getVar( '_InstallPassword' );
589 public function createTables() {
590 $schema = $this->getVar( 'wgDBmwschema' );
592 $status = $this->getConnection();
593 if ( !$status->isOK() ) {
597 /** @var $conn DatabasePostgres */
598 $conn = $status->value
;
600 if ( $conn->tableExists( 'archive' ) ) {
601 $status->warning( 'config-install-tables-exist' );
607 $conn->begin( __METHOD__
);
609 if ( !$conn->schemaExists( $schema ) ) {
610 $status->fatal( 'config-install-pg-schema-not-exist' );
614 $error = $conn->sourceFile( $this->getSchemaPath( $conn ) );
615 if ( $error !== true ) {
616 $conn->reportQueryError( $error, 0, '', __METHOD__
);
617 $conn->rollback( __METHOD__
);
618 $status->fatal( 'config-install-tables-failed', $error );
620 $conn->commit( __METHOD__
);
622 // Resume normal operations
623 if ( $status->isOK() ) {
630 public function getGlobalDefaults() {
631 // The default $wgDBmwschema is null, which breaks Postgres and other DBMSes that require
632 // the use of a schema, so we need to set it here
633 return array_merge( parent
::getGlobalDefaults(), [
634 'wgDBmwschema' => 'mediawiki',
638 public function setupPLpgSQL() {
639 // Connect as the install user, since it owns the database and so is
640 // the user that needs to run "CREATE LANGAUGE"
641 $status = $this->getPgConnection( 'create-schema' );
642 if ( !$status->isOK() ) {
646 * @var $conn Database
648 $conn = $status->value
;
650 $exists = $conn->selectField( '"pg_catalog"."pg_language"', 1,
651 [ 'lanname' => 'plpgsql' ], __METHOD__
);
653 // Already exists, nothing to do
654 return Status
::newGood();
657 // plpgsql is not installed, but if we have a pg_pltemplate table, we
658 // should be able to create it
659 $exists = $conn->selectField(
660 [ '"pg_catalog"."pg_class"', '"pg_catalog"."pg_namespace"' ],
663 'pg_namespace.oid=relnamespace',
664 'nspname' => 'pg_catalog',
665 'relname' => 'pg_pltemplate',
670 $conn->query( 'CREATE LANGUAGE plpgsql' );
671 } catch ( DBQueryError
$e ) {
672 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
675 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
678 return Status
::newGood();