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 = array(
41 protected $internalDefaults = array(
42 '_InstallUser' => 'postgres',
45 public $minimumVersion = '8.3';
46 public $maxRoleSearchDepth = 5;
48 protected $pgConns = array();
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', array(), 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( array( 'wgDBserver', 'wgDBport',
87 'wgDBname', 'wgDBmwschema' ) );
90 $status = Status
::newGood();
91 if ( !strlen( $newValues['wgDBname'] ) ) {
92 $status->fatal( 'config-missing-db-name' );
93 } elseif ( !preg_match( '/^[a-zA-Z0-9_]+$/', $newValues['wgDBname'] ) ) {
94 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
96 if ( !preg_match( '/^[a-zA-Z0-9_]*$/', $newValues['wgDBmwschema'] ) ) {
97 $status->fatal( 'config-invalid-schema', $newValues['wgDBmwschema'] );
101 if ( $status->isOK() ) {
102 $status->merge( $this->submitInstallUserBox() );
104 if ( !$status->isOK() ) {
108 $status = $this->getPgConnection( 'create-db' );
109 if ( !$status->isOK() ) {
113 * @var $conn DatabaseBase
115 $conn = $status->value
;
118 $version = $conn->getServerVersion();
119 if ( version_compare( $version, $this->minimumVersion
) < 0 ) {
120 return Status
::newFatal( 'config-postgres-old', $this->minimumVersion
, $version );
123 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
124 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
126 return Status
::newGood();
129 public function getConnection() {
130 $status = $this->getPgConnection( 'create-tables' );
131 if ( $status->isOK() ) {
132 $this->db
= $status->value
;
138 public function openConnection() {
139 return $this->openPgConnection( 'create-tables' );
143 * Open a PG connection with given parameters
144 * @param string $user User name
145 * @param string $password Password
146 * @param string $dbName Database name
149 protected function openConnectionWithParams( $user, $password, $dbName ) {
150 $status = Status
::newGood();
152 $db = new DatabasePostgres(
153 $this->getVar( 'wgDBserver' ),
158 $status->value
= $db;
159 } catch ( DBConnectionError
$e ) {
160 $status->fatal( 'config-connection-error', $e->getMessage() );
167 * Get a special type of connection
168 * @param string $type See openPgConnection() for details.
171 protected function getPgConnection( $type ) {
172 if ( isset( $this->pgConns
[$type] ) ) {
173 return Status
::newGood( $this->pgConns
[$type] );
175 $status = $this->openPgConnection( $type );
177 if ( $status->isOK() ) {
179 * @var $conn DatabaseBase
181 $conn = $status->value
;
182 $conn->clearFlag( DBO_TRX
);
183 $conn->commit( __METHOD__
);
184 $this->pgConns
[$type] = $conn;
191 * Get a connection of a specific PostgreSQL-specific type. Connections
192 * of a given type are cached.
194 * PostgreSQL lacks cross-database operations, so after the new database is
195 * created, you need to make a separate connection to connect to that
196 * database and add tables to it.
198 * New tables are owned by the user that creates them, and MediaWiki's
199 * PostgreSQL support has always assumed that the table owner will be
200 * $wgDBuser. So before we create new tables, we either need to either
201 * connect as the other user or to execute a SET ROLE command. Using a
202 * separate connection for this allows us to avoid accidental cross-module
205 * @param string $type The type of connection to get:
206 * - create-db: A connection for creating DBs, suitable for pre-
208 * - create-schema: A connection to the new DB, for creating schemas and
209 * other similar objects in the new DB.
210 * - create-tables: A connection with a role suitable for creating tables.
212 * @throws MWException
213 * @return Status object. On success, a connection object will be in the
216 protected function openPgConnection( $type ) {
219 return $this->openConnectionToAnyDB(
220 $this->getVar( '_InstallUser' ),
221 $this->getVar( '_InstallPassword' ) );
222 case 'create-schema':
223 return $this->openConnectionWithParams(
224 $this->getVar( '_InstallUser' ),
225 $this->getVar( '_InstallPassword' ),
226 $this->getVar( 'wgDBname' ) );
227 case 'create-tables':
228 $status = $this->openPgConnection( 'create-schema' );
229 if ( $status->isOK() ) {
231 * @var $conn DatabaseBase
233 $conn = $status->value
;
234 $safeRole = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
235 $conn->query( "SET ROLE $safeRole" );
240 throw new MWException( "Invalid special connection type: \"$type\"" );
244 public function openConnectionToAnyDB( $user, $password ) {
249 if ( !in_array( $this->getVar( 'wgDBname' ), $dbs ) ) {
250 array_unshift( $dbs, $this->getVar( 'wgDBname' ) );
253 $status = Status
::newGood();
254 foreach ( $dbs as $db ) {
256 $conn = new DatabasePostgres(
257 $this->getVar( 'wgDBserver' ),
261 } catch ( DBConnectionError
$error ) {
263 $status->fatal( 'config-pg-test-error', $db,
264 $error->getMessage() );
266 if ( $conn !== false ) {
270 if ( $conn !== false ) {
271 return Status
::newGood( $conn );
277 protected function getInstallUserPermissions() {
278 $status = $this->getPgConnection( 'create-db' );
279 if ( !$status->isOK() ) {
283 * @var $conn DatabaseBase
285 $conn = $status->value
;
286 $superuser = $this->getVar( '_InstallUser' );
288 $row = $conn->selectRow( '"pg_catalog"."pg_roles"', '*',
289 array( 'rolname' => $superuser ), __METHOD__
);
294 protected function canCreateAccounts() {
295 $perms = $this->getInstallUserPermissions();
300 return $perms->rolsuper
=== 't' ||
$perms->rolcreaterole
=== 't';
303 protected function isSuperUser() {
304 $perms = $this->getInstallUserPermissions();
309 return $perms->rolsuper
=== 't';
312 public function getSettingsForm() {
313 if ( $this->canCreateAccounts() ) {
314 $noCreateMsg = false;
316 $noCreateMsg = 'config-db-web-no-create-privs';
318 $s = $this->getWebUserBox( $noCreateMsg );
323 public function submitSettingsForm() {
324 $status = $this->submitWebUserBox();
325 if ( !$status->isOK() ) {
329 $same = $this->getVar( 'wgDBuser' ) === $this->getVar( '_InstallUser' );
334 // Check if the web user exists
335 // Connect to the database with the install user
336 $status = $this->getPgConnection( 'create-db' );
337 if ( !$status->isOK() ) {
340 $exists = $status->value
->roleExists( $this->getVar( 'wgDBuser' ) );
343 // Validate the create checkbox
344 if ( $this->canCreateAccounts() && !$same && !$exists ) {
345 $create = $this->getVar( '_CreateDBAccount' );
347 $this->setVar( '_CreateDBAccount', false );
351 if ( !$create && !$exists ) {
352 if ( $this->canCreateAccounts() ) {
353 $msg = 'config-install-user-missing-create';
355 $msg = 'config-install-user-missing';
358 return Status
::newFatal( $msg, $this->getVar( 'wgDBuser' ) );
362 // No more checks to do
363 return Status
::newGood();
366 // Existing web account. Test the connection.
367 $status = $this->openConnectionToAnyDB(
368 $this->getVar( 'wgDBuser' ),
369 $this->getVar( 'wgDBpassword' ) );
370 if ( !$status->isOK() ) {
374 // The web user is conventionally the table owner in PostgreSQL
375 // installations. Make sure the install user is able to create
376 // objects on behalf of the web user.
377 if ( $same ||
$this->canCreateObjectsForWebUser() ) {
378 return Status
::newGood();
380 return Status
::newFatal( 'config-pg-not-in-role' );
385 * Returns true if the install user is able to create objects owned
386 * by the web user, false otherwise.
389 protected function canCreateObjectsForWebUser() {
390 if ( $this->isSuperUser() ) {
394 $status = $this->getPgConnection( 'create-db' );
395 if ( !$status->isOK() ) {
398 $conn = $status->value
;
399 $installerId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
400 array( 'rolname' => $this->getVar( '_InstallUser' ) ), __METHOD__
);
401 $webId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
402 array( 'rolname' => $this->getVar( 'wgDBuser' ) ), __METHOD__
);
404 return $this->isRoleMember( $conn, $installerId, $webId, $this->maxRoleSearchDepth
);
408 * Recursive helper for canCreateObjectsForWebUser().
409 * @param $conn DatabaseBase object
410 * @param int $targetMember Role ID of the member to look for
411 * @param int $group Role ID of the group to look for
412 * @param int $maxDepth Maximum recursive search depth
415 protected function isRoleMember( $conn, $targetMember, $group, $maxDepth ) {
416 if ( $targetMember === $group ) {
417 // A role is always a member of itself
420 // Get all members of the given group
421 $res = $conn->select( '"pg_catalog"."pg_auth_members"', array( 'member' ),
422 array( 'roleid' => $group ), __METHOD__
);
423 foreach ( $res as $row ) {
424 if ( $row->member
== $targetMember ) {
425 // Found target member
428 // Recursively search each member of the group to see if the target
429 // is a member of it, up to the given maximum depth.
430 if ( $maxDepth > 0 ) {
431 if ( $this->isRoleMember( $conn, $targetMember, $row->member
, $maxDepth - 1 ) ) {
432 // Found member of member
441 public function preInstall() {
442 $createDbAccount = array(
444 'callback' => array( $this, 'setupUser' ),
447 'name' => 'pg-commit',
448 'callback' => array( $this, 'commitChanges' ),
451 'name' => 'pg-plpgsql',
452 'callback' => array( $this, 'setupPLpgSQL' ),
456 'callback' => array( $this, 'setupSchema' )
459 if ( $this->getVar( '_CreateDBAccount' ) ) {
460 $this->parent
->addInstallStep( $createDbAccount, 'database' );
462 $this->parent
->addInstallStep( $commitCB, 'interwiki' );
463 $this->parent
->addInstallStep( $plpgCB, 'database' );
464 $this->parent
->addInstallStep( $schemaCB, 'database' );
467 function setupDatabase() {
468 $status = $this->getPgConnection( 'create-db' );
469 if ( !$status->isOK() ) {
472 $conn = $status->value
;
474 $dbName = $this->getVar( 'wgDBname' );
476 $exists = $conn->selectField( '"pg_catalog"."pg_database"', '1',
477 array( 'datname' => $dbName ), __METHOD__
);
479 $safedb = $conn->addIdentifierQuotes( $dbName );
480 $conn->query( "CREATE DATABASE $safedb", __METHOD__
);
483 return Status
::newGood();
486 function setupSchema() {
487 // Get a connection to the target database
488 $status = $this->getPgConnection( 'create-schema' );
489 if ( !$status->isOK() ) {
492 $conn = $status->value
;
494 // Create the schema if necessary
495 $schema = $this->getVar( 'wgDBmwschema' );
496 $safeschema = $conn->addIdentifierQuotes( $schema );
497 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
498 if ( !$conn->schemaExists( $schema ) ) {
500 $conn->query( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
501 } catch ( DBQueryError
$e ) {
502 return Status
::newFatal( 'config-install-pg-schema-failed',
503 $this->getVar( '_InstallUser' ), $schema );
507 // Select the new schema in the current connection
508 $conn->determineCoreSchema( $schema );
510 return Status
::newGood();
513 function commitChanges() {
514 $this->db
->commit( __METHOD__
);
516 return Status
::newGood();
519 function setupUser() {
520 if ( !$this->getVar( '_CreateDBAccount' ) ) {
521 return Status
::newGood();
524 $status = $this->getPgConnection( 'create-db' );
525 if ( !$status->isOK() ) {
528 $conn = $status->value
;
530 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
531 $safepass = $conn->addQuotes( $this->getVar( 'wgDBpassword' ) );
533 // Check if the user already exists
534 $userExists = $conn->roleExists( $this->getVar( 'wgDBuser' ) );
535 if ( !$userExists ) {
538 $sql = "CREATE ROLE $safeuser NOCREATEDB LOGIN PASSWORD $safepass";
540 // If the install user is not a superuser, we need to make the install
541 // user a member of the new user's group, so that the install user will
542 // be able to create a schema and other objects on behalf of the new user.
543 if ( !$this->isSuperUser() ) {
544 $sql .= ' ROLE' . $conn->addIdentifierQuotes( $this->getVar( '_InstallUser' ) );
547 $conn->query( $sql, __METHOD__
);
548 } catch ( DBQueryError
$e ) {
549 return Status
::newFatal( 'config-install-user-create-failed',
550 $this->getVar( 'wgDBuser' ), $e->getMessage() );
554 return Status
::newGood();
557 function getLocalSettings() {
558 $port = $this->getVar( 'wgDBport' );
559 $schema = $this->getVar( 'wgDBmwschema' );
561 return "# Postgres specific settings
562 \$wgDBport = \"{$port}\";
563 \$wgDBmwschema = \"{$schema}\";";
566 public function preUpgrade() {
567 global $wgDBuser, $wgDBpassword;
569 # Normal user and password are selected after this step, so for now
570 # just copy these two
571 $wgDBuser = $this->getVar( '_InstallUser' );
572 $wgDBpassword = $this->getVar( '_InstallPassword' );
575 public function createTables() {
576 $schema = $this->getVar( 'wgDBmwschema' );
578 $status = $this->getConnection();
579 if ( !$status->isOK() ) {
584 * @var $conn DatabaseBase
586 $conn = $status->value
;
588 if ( $conn->tableExists( 'archive' ) ) {
589 $status->warning( 'config-install-tables-exist' );
595 $conn->begin( __METHOD__
);
597 if ( !$conn->schemaExists( $schema ) ) {
598 $status->fatal( 'config-install-pg-schema-not-exist' );
602 $error = $conn->sourceFile( $conn->getSchemaPath() );
603 if ( $error !== true ) {
604 $conn->reportQueryError( $error, 0, '', __METHOD__
);
605 $conn->rollback( __METHOD__
);
606 $status->fatal( 'config-install-tables-failed', $error );
608 $conn->commit( __METHOD__
);
610 // Resume normal operations
611 if ( $status->isOk() ) {
618 public function setupPLpgSQL() {
619 // Connect as the install user, since it owns the database and so is
620 // the user that needs to run "CREATE LANGAUGE"
621 $status = $this->getPgConnection( 'create-schema' );
622 if ( !$status->isOK() ) {
626 * @var $conn DatabaseBase
628 $conn = $status->value
;
630 $exists = $conn->selectField( '"pg_catalog"."pg_language"', 1,
631 array( 'lanname' => 'plpgsql' ), __METHOD__
);
633 // Already exists, nothing to do
634 return Status
::newGood();
637 // plpgsql is not installed, but if we have a pg_pltemplate table, we
638 // should be able to create it
639 $exists = $conn->selectField(
640 array( '"pg_catalog"."pg_class"', '"pg_catalog"."pg_namespace"' ),
643 'pg_namespace.oid=relnamespace',
644 'nspname' => 'pg_catalog',
645 'relname' => 'pg_pltemplate',
650 $conn->query( 'CREATE LANGUAGE plpgsql' );
651 } catch ( DBQueryError
$e ) {
652 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
655 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
658 return Status
::newGood();