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(
87 'wgDBserver', 'wgDBport', 'wgDBname', 'wgDBmwschema',
88 '_InstallUser', '_InstallPassword'
92 $status = Status
::newGood();
93 if ( !strlen( $newValues['wgDBname'] ) ) {
94 $status->fatal( 'config-missing-db-name' );
95 } elseif ( !preg_match( '/^[a-zA-Z0-9_]+$/', $newValues['wgDBname'] ) ) {
96 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
98 if ( !preg_match( '/^[a-zA-Z0-9_]*$/', $newValues['wgDBmwschema'] ) ) {
99 $status->fatal( 'config-invalid-schema', $newValues['wgDBmwschema'] );
101 if ( !strlen( $newValues['_InstallUser'] ) ) {
102 $status->fatal( 'config-db-username-empty' );
104 if ( !strlen( $newValues['_InstallPassword'] ) ) {
105 $status->fatal( 'config-db-password-empty', $newValues['_InstallUser'] );
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 DatabaseBase
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 = DatabaseBase
::factory( 'postgres', array(
162 'host' => $this->getVar( 'wgDBserver' ),
164 'password' => $password,
166 'schema' => $schema ) );
167 $status->value
= $db;
168 } catch ( DBConnectionError
$e ) {
169 $status->fatal( 'config-connection-error', $e->getMessage() );
176 * Get a special type of connection
177 * @param string $type See openPgConnection() for details.
180 protected function getPgConnection( $type ) {
181 if ( isset( $this->pgConns
[$type] ) ) {
182 return Status
::newGood( $this->pgConns
[$type] );
184 $status = $this->openPgConnection( $type );
186 if ( $status->isOK() ) {
188 * @var $conn DatabaseBase
190 $conn = $status->value
;
191 $conn->clearFlag( DBO_TRX
);
192 $conn->commit( __METHOD__
);
193 $this->pgConns
[$type] = $conn;
200 * Get a connection of a specific PostgreSQL-specific type. Connections
201 * of a given type are cached.
203 * PostgreSQL lacks cross-database operations, so after the new database is
204 * created, you need to make a separate connection to connect to that
205 * database and add tables to it.
207 * New tables are owned by the user that creates them, and MediaWiki's
208 * PostgreSQL support has always assumed that the table owner will be
209 * $wgDBuser. So before we create new tables, we either need to either
210 * connect as the other user or to execute a SET ROLE command. Using a
211 * separate connection for this allows us to avoid accidental cross-module
214 * @param string $type The type of connection to get:
215 * - create-db: A connection for creating DBs, suitable for pre-
217 * - create-schema: A connection to the new DB, for creating schemas and
218 * other similar objects in the new DB.
219 * - create-tables: A connection with a role suitable for creating tables.
221 * @throws MWException
222 * @return Status On success, a connection object will be in the value member.
224 protected function openPgConnection( $type ) {
227 return $this->openConnectionToAnyDB(
228 $this->getVar( '_InstallUser' ),
229 $this->getVar( '_InstallPassword' ) );
230 case 'create-schema':
231 return $this->openConnectionWithParams(
232 $this->getVar( '_InstallUser' ),
233 $this->getVar( '_InstallPassword' ),
234 $this->getVar( 'wgDBname' ),
235 $this->getVar( 'wgDBmwschema' ) );
236 case 'create-tables':
237 $status = $this->openPgConnection( 'create-schema' );
238 if ( $status->isOK() ) {
240 * @var $conn DatabaseBase
242 $conn = $status->value
;
243 $safeRole = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
244 $conn->query( "SET ROLE $safeRole" );
249 throw new MWException( "Invalid special connection type: \"$type\"" );
253 public function openConnectionToAnyDB( $user, $password ) {
258 if ( !in_array( $this->getVar( 'wgDBname' ), $dbs ) ) {
259 array_unshift( $dbs, $this->getVar( 'wgDBname' ) );
262 $status = Status
::newGood();
263 foreach ( $dbs as $db ) {
266 'host' => $this->getVar( 'wgDBserver' ),
268 'password' => $password,
271 $conn = DatabaseBase
::factory( 'postgres', $p );
272 } catch ( DBConnectionError
$error ) {
274 $status->fatal( 'config-pg-test-error', $db,
275 $error->getMessage() );
277 if ( $conn !== false ) {
281 if ( $conn !== false ) {
282 return Status
::newGood( $conn );
288 protected function getInstallUserPermissions() {
289 $status = $this->getPgConnection( 'create-db' );
290 if ( !$status->isOK() ) {
294 * @var $conn DatabaseBase
296 $conn = $status->value
;
297 $superuser = $this->getVar( '_InstallUser' );
299 $row = $conn->selectRow( '"pg_catalog"."pg_roles"', '*',
300 array( 'rolname' => $superuser ), __METHOD__
);
305 protected function canCreateAccounts() {
306 $perms = $this->getInstallUserPermissions();
311 return $perms->rolsuper
=== 't' ||
$perms->rolcreaterole
=== 't';
314 protected function isSuperUser() {
315 $perms = $this->getInstallUserPermissions();
320 return $perms->rolsuper
=== 't';
323 public function getSettingsForm() {
324 if ( $this->canCreateAccounts() ) {
325 $noCreateMsg = false;
327 $noCreateMsg = 'config-db-web-no-create-privs';
329 $s = $this->getWebUserBox( $noCreateMsg );
334 public function submitSettingsForm() {
335 $status = $this->submitWebUserBox();
336 if ( !$status->isOK() ) {
340 $same = $this->getVar( 'wgDBuser' ) === $this->getVar( '_InstallUser' );
345 // Check if the web user exists
346 // Connect to the database with the install user
347 $status = $this->getPgConnection( 'create-db' );
348 if ( !$status->isOK() ) {
351 $exists = $status->value
->roleExists( $this->getVar( 'wgDBuser' ) );
354 // Validate the create checkbox
355 if ( $this->canCreateAccounts() && !$same && !$exists ) {
356 $create = $this->getVar( '_CreateDBAccount' );
358 $this->setVar( '_CreateDBAccount', false );
362 if ( !$create && !$exists ) {
363 if ( $this->canCreateAccounts() ) {
364 $msg = 'config-install-user-missing-create';
366 $msg = 'config-install-user-missing';
369 return Status
::newFatal( $msg, $this->getVar( 'wgDBuser' ) );
373 // No more checks to do
374 return Status
::newGood();
377 // Existing web account. Test the connection.
378 $status = $this->openConnectionToAnyDB(
379 $this->getVar( 'wgDBuser' ),
380 $this->getVar( 'wgDBpassword' ) );
381 if ( !$status->isOK() ) {
385 // The web user is conventionally the table owner in PostgreSQL
386 // installations. Make sure the install user is able to create
387 // objects on behalf of the web user.
388 if ( $same ||
$this->canCreateObjectsForWebUser() ) {
389 return Status
::newGood();
391 return Status
::newFatal( 'config-pg-not-in-role' );
396 * Returns true if the install user is able to create objects owned
397 * by the web user, false otherwise.
400 protected function canCreateObjectsForWebUser() {
401 if ( $this->isSuperUser() ) {
405 $status = $this->getPgConnection( 'create-db' );
406 if ( !$status->isOK() ) {
409 $conn = $status->value
;
410 $installerId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
411 array( 'rolname' => $this->getVar( '_InstallUser' ) ), __METHOD__
);
412 $webId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
413 array( 'rolname' => $this->getVar( 'wgDBuser' ) ), __METHOD__
);
415 return $this->isRoleMember( $conn, $installerId, $webId, $this->maxRoleSearchDepth
);
419 * Recursive helper for canCreateObjectsForWebUser().
420 * @param DatabaseBase $conn
421 * @param int $targetMember Role ID of the member to look for
422 * @param int $group Role ID of the group to look for
423 * @param int $maxDepth Maximum recursive search depth
426 protected function isRoleMember( $conn, $targetMember, $group, $maxDepth ) {
427 if ( $targetMember === $group ) {
428 // A role is always a member of itself
431 // Get all members of the given group
432 $res = $conn->select( '"pg_catalog"."pg_auth_members"', array( 'member' ),
433 array( 'roleid' => $group ), __METHOD__
);
434 foreach ( $res as $row ) {
435 if ( $row->member
== $targetMember ) {
436 // Found target member
439 // Recursively search each member of the group to see if the target
440 // is a member of it, up to the given maximum depth.
441 if ( $maxDepth > 0 ) {
442 if ( $this->isRoleMember( $conn, $targetMember, $row->member
, $maxDepth - 1 ) ) {
443 // Found member of member
452 public function preInstall() {
453 $createDbAccount = array(
455 'callback' => array( $this, 'setupUser' ),
458 'name' => 'pg-commit',
459 'callback' => array( $this, 'commitChanges' ),
462 'name' => 'pg-plpgsql',
463 'callback' => array( $this, 'setupPLpgSQL' ),
467 'callback' => array( $this, 'setupSchema' )
470 if ( $this->getVar( '_CreateDBAccount' ) ) {
471 $this->parent
->addInstallStep( $createDbAccount, 'database' );
473 $this->parent
->addInstallStep( $commitCB, 'interwiki' );
474 $this->parent
->addInstallStep( $plpgCB, 'database' );
475 $this->parent
->addInstallStep( $schemaCB, 'database' );
478 function setupDatabase() {
479 $status = $this->getPgConnection( 'create-db' );
480 if ( !$status->isOK() ) {
483 $conn = $status->value
;
485 $dbName = $this->getVar( 'wgDBname' );
487 $exists = $conn->selectField( '"pg_catalog"."pg_database"', '1',
488 array( 'datname' => $dbName ), __METHOD__
);
490 $safedb = $conn->addIdentifierQuotes( $dbName );
491 $conn->query( "CREATE DATABASE $safedb", __METHOD__
);
494 return Status
::newGood();
497 function setupSchema() {
498 // Get a connection to the target database
499 $status = $this->getPgConnection( 'create-schema' );
500 if ( !$status->isOK() ) {
503 $conn = $status->value
;
505 // Create the schema if necessary
506 $schema = $this->getVar( 'wgDBmwschema' );
507 $safeschema = $conn->addIdentifierQuotes( $schema );
508 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
509 if ( !$conn->schemaExists( $schema ) ) {
511 $conn->query( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
512 } catch ( DBQueryError
$e ) {
513 return Status
::newFatal( 'config-install-pg-schema-failed',
514 $this->getVar( '_InstallUser' ), $schema );
518 // Select the new schema in the current connection
519 $conn->determineCoreSchema( $schema );
521 return Status
::newGood();
524 function commitChanges() {
525 $this->db
->commit( __METHOD__
);
527 return Status
::newGood();
530 function setupUser() {
531 if ( !$this->getVar( '_CreateDBAccount' ) ) {
532 return Status
::newGood();
535 $status = $this->getPgConnection( 'create-db' );
536 if ( !$status->isOK() ) {
539 $conn = $status->value
;
541 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
542 $safepass = $conn->addQuotes( $this->getVar( 'wgDBpassword' ) );
544 // Check if the user already exists
545 $userExists = $conn->roleExists( $this->getVar( 'wgDBuser' ) );
546 if ( !$userExists ) {
549 $sql = "CREATE ROLE $safeuser NOCREATEDB LOGIN PASSWORD $safepass";
551 // If the install user is not a superuser, we need to make the install
552 // user a member of the new user's group, so that the install user will
553 // be able to create a schema and other objects on behalf of the new user.
554 if ( !$this->isSuperUser() ) {
555 $sql .= ' ROLE' . $conn->addIdentifierQuotes( $this->getVar( '_InstallUser' ) );
558 $conn->query( $sql, __METHOD__
);
559 } catch ( DBQueryError
$e ) {
560 return Status
::newFatal( 'config-install-user-create-failed',
561 $this->getVar( 'wgDBuser' ), $e->getMessage() );
565 return Status
::newGood();
568 function getLocalSettings() {
569 $port = $this->getVar( 'wgDBport' );
570 $schema = $this->getVar( 'wgDBmwschema' );
572 return "# Postgres specific settings
573 \$wgDBport = \"{$port}\";
574 \$wgDBmwschema = \"{$schema}\";";
577 public function preUpgrade() {
578 global $wgDBuser, $wgDBpassword;
580 # Normal user and password are selected after this step, so for now
581 # just copy these two
582 $wgDBuser = $this->getVar( '_InstallUser' );
583 $wgDBpassword = $this->getVar( '_InstallPassword' );
586 public function createTables() {
587 $schema = $this->getVar( 'wgDBmwschema' );
589 $status = $this->getConnection();
590 if ( !$status->isOK() ) {
595 * @var $conn DatabaseBase
597 $conn = $status->value
;
599 if ( $conn->tableExists( 'archive' ) ) {
600 $status->warning( 'config-install-tables-exist' );
606 $conn->begin( __METHOD__
);
608 if ( !$conn->schemaExists( $schema ) ) {
609 $status->fatal( 'config-install-pg-schema-not-exist' );
613 $error = $conn->sourceFile( $conn->getSchemaPath() );
614 if ( $error !== true ) {
615 $conn->reportQueryError( $error, 0, '', __METHOD__
);
616 $conn->rollback( __METHOD__
);
617 $status->fatal( 'config-install-tables-failed', $error );
619 $conn->commit( __METHOD__
);
621 // Resume normal operations
622 if ( $status->isOk() ) {
629 public function getGlobalDefaults() {
630 // The default $wgDBmwschema is null, which breaks Postgres and other DBMSes that require
631 // the use of a schema, so we need to set it here
632 return array_merge( parent
::getGlobalDefaults(), array(
633 'wgDBmwschema' => 'mediawiki',
637 public function setupPLpgSQL() {
638 // Connect as the install user, since it owns the database and so is
639 // the user that needs to run "CREATE LANGAUGE"
640 $status = $this->getPgConnection( 'create-schema' );
641 if ( !$status->isOK() ) {
645 * @var $conn DatabaseBase
647 $conn = $status->value
;
649 $exists = $conn->selectField( '"pg_catalog"."pg_language"', 1,
650 array( 'lanname' => 'plpgsql' ), __METHOD__
);
652 // Already exists, nothing to do
653 return Status
::newGood();
656 // plpgsql is not installed, but if we have a pg_pltemplate table, we
657 // should be able to create it
658 $exists = $conn->selectField(
659 array( '"pg_catalog"."pg_class"', '"pg_catalog"."pg_namespace"' ),
662 'pg_namespace.oid=relnamespace',
663 'nspname' => 'pg_catalog',
664 'relname' => 'pg_pltemplate',
669 $conn->query( 'CREATE LANGUAGE plpgsql' );
670 } catch ( DBQueryError
$e ) {
671 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
674 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
677 return Status
::newGood();