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 ) {
265 $conn = new DatabasePostgres(
266 $this->getVar( 'wgDBserver' ),
270 } catch ( DBConnectionError
$error ) {
272 $status->fatal( 'config-pg-test-error', $db,
273 $error->getMessage() );
275 if ( $conn !== false ) {
279 if ( $conn !== false ) {
280 return Status
::newGood( $conn );
286 protected function getInstallUserPermissions() {
287 $status = $this->getPgConnection( 'create-db' );
288 if ( !$status->isOK() ) {
292 * @var $conn DatabaseBase
294 $conn = $status->value
;
295 $superuser = $this->getVar( '_InstallUser' );
297 $row = $conn->selectRow( '"pg_catalog"."pg_roles"', '*',
298 array( 'rolname' => $superuser ), __METHOD__
);
303 protected function canCreateAccounts() {
304 $perms = $this->getInstallUserPermissions();
309 return $perms->rolsuper
=== 't' ||
$perms->rolcreaterole
=== 't';
312 protected function isSuperUser() {
313 $perms = $this->getInstallUserPermissions();
318 return $perms->rolsuper
=== 't';
321 public function getSettingsForm() {
322 if ( $this->canCreateAccounts() ) {
323 $noCreateMsg = false;
325 $noCreateMsg = 'config-db-web-no-create-privs';
327 $s = $this->getWebUserBox( $noCreateMsg );
332 public function submitSettingsForm() {
333 $status = $this->submitWebUserBox();
334 if ( !$status->isOK() ) {
338 $same = $this->getVar( 'wgDBuser' ) === $this->getVar( '_InstallUser' );
343 // Check if the web user exists
344 // Connect to the database with the install user
345 $status = $this->getPgConnection( 'create-db' );
346 if ( !$status->isOK() ) {
349 $exists = $status->value
->roleExists( $this->getVar( 'wgDBuser' ) );
352 // Validate the create checkbox
353 if ( $this->canCreateAccounts() && !$same && !$exists ) {
354 $create = $this->getVar( '_CreateDBAccount' );
356 $this->setVar( '_CreateDBAccount', false );
360 if ( !$create && !$exists ) {
361 if ( $this->canCreateAccounts() ) {
362 $msg = 'config-install-user-missing-create';
364 $msg = 'config-install-user-missing';
367 return Status
::newFatal( $msg, $this->getVar( 'wgDBuser' ) );
371 // No more checks to do
372 return Status
::newGood();
375 // Existing web account. Test the connection.
376 $status = $this->openConnectionToAnyDB(
377 $this->getVar( 'wgDBuser' ),
378 $this->getVar( 'wgDBpassword' ) );
379 if ( !$status->isOK() ) {
383 // The web user is conventionally the table owner in PostgreSQL
384 // installations. Make sure the install user is able to create
385 // objects on behalf of the web user.
386 if ( $same ||
$this->canCreateObjectsForWebUser() ) {
387 return Status
::newGood();
389 return Status
::newFatal( 'config-pg-not-in-role' );
394 * Returns true if the install user is able to create objects owned
395 * by the web user, false otherwise.
398 protected function canCreateObjectsForWebUser() {
399 if ( $this->isSuperUser() ) {
403 $status = $this->getPgConnection( 'create-db' );
404 if ( !$status->isOK() ) {
407 $conn = $status->value
;
408 $installerId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
409 array( 'rolname' => $this->getVar( '_InstallUser' ) ), __METHOD__
);
410 $webId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
411 array( 'rolname' => $this->getVar( 'wgDBuser' ) ), __METHOD__
);
413 return $this->isRoleMember( $conn, $installerId, $webId, $this->maxRoleSearchDepth
);
417 * Recursive helper for canCreateObjectsForWebUser().
418 * @param DatabaseBase $conn
419 * @param int $targetMember Role ID of the member to look for
420 * @param int $group Role ID of the group to look for
421 * @param int $maxDepth Maximum recursive search depth
424 protected function isRoleMember( $conn, $targetMember, $group, $maxDepth ) {
425 if ( $targetMember === $group ) {
426 // A role is always a member of itself
429 // Get all members of the given group
430 $res = $conn->select( '"pg_catalog"."pg_auth_members"', array( 'member' ),
431 array( 'roleid' => $group ), __METHOD__
);
432 foreach ( $res as $row ) {
433 if ( $row->member
== $targetMember ) {
434 // Found target member
437 // Recursively search each member of the group to see if the target
438 // is a member of it, up to the given maximum depth.
439 if ( $maxDepth > 0 ) {
440 if ( $this->isRoleMember( $conn, $targetMember, $row->member
, $maxDepth - 1 ) ) {
441 // Found member of member
450 public function preInstall() {
451 $createDbAccount = array(
453 'callback' => array( $this, 'setupUser' ),
456 'name' => 'pg-commit',
457 'callback' => array( $this, 'commitChanges' ),
460 'name' => 'pg-plpgsql',
461 'callback' => array( $this, 'setupPLpgSQL' ),
465 'callback' => array( $this, 'setupSchema' )
468 if ( $this->getVar( '_CreateDBAccount' ) ) {
469 $this->parent
->addInstallStep( $createDbAccount, 'database' );
471 $this->parent
->addInstallStep( $commitCB, 'interwiki' );
472 $this->parent
->addInstallStep( $plpgCB, 'database' );
473 $this->parent
->addInstallStep( $schemaCB, 'database' );
476 function setupDatabase() {
477 $status = $this->getPgConnection( 'create-db' );
478 if ( !$status->isOK() ) {
481 $conn = $status->value
;
483 $dbName = $this->getVar( 'wgDBname' );
485 $exists = $conn->selectField( '"pg_catalog"."pg_database"', '1',
486 array( 'datname' => $dbName ), __METHOD__
);
488 $safedb = $conn->addIdentifierQuotes( $dbName );
489 $conn->query( "CREATE DATABASE $safedb", __METHOD__
);
492 return Status
::newGood();
495 function setupSchema() {
496 // Get a connection to the target database
497 $status = $this->getPgConnection( 'create-schema' );
498 if ( !$status->isOK() ) {
501 $conn = $status->value
;
503 // Create the schema if necessary
504 $schema = $this->getVar( 'wgDBmwschema' );
505 $safeschema = $conn->addIdentifierQuotes( $schema );
506 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
507 if ( !$conn->schemaExists( $schema ) ) {
509 $conn->query( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
510 } catch ( DBQueryError
$e ) {
511 return Status
::newFatal( 'config-install-pg-schema-failed',
512 $this->getVar( '_InstallUser' ), $schema );
516 // Select the new schema in the current connection
517 $conn->determineCoreSchema( $schema );
519 return Status
::newGood();
522 function commitChanges() {
523 $this->db
->commit( __METHOD__
);
525 return Status
::newGood();
528 function setupUser() {
529 if ( !$this->getVar( '_CreateDBAccount' ) ) {
530 return Status
::newGood();
533 $status = $this->getPgConnection( 'create-db' );
534 if ( !$status->isOK() ) {
537 $conn = $status->value
;
539 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
540 $safepass = $conn->addQuotes( $this->getVar( 'wgDBpassword' ) );
542 // Check if the user already exists
543 $userExists = $conn->roleExists( $this->getVar( 'wgDBuser' ) );
544 if ( !$userExists ) {
547 $sql = "CREATE ROLE $safeuser NOCREATEDB LOGIN PASSWORD $safepass";
549 // If the install user is not a superuser, we need to make the install
550 // user a member of the new user's group, so that the install user will
551 // be able to create a schema and other objects on behalf of the new user.
552 if ( !$this->isSuperUser() ) {
553 $sql .= ' ROLE' . $conn->addIdentifierQuotes( $this->getVar( '_InstallUser' ) );
556 $conn->query( $sql, __METHOD__
);
557 } catch ( DBQueryError
$e ) {
558 return Status
::newFatal( 'config-install-user-create-failed',
559 $this->getVar( 'wgDBuser' ), $e->getMessage() );
563 return Status
::newGood();
566 function getLocalSettings() {
567 $port = $this->getVar( 'wgDBport' );
568 $schema = $this->getVar( 'wgDBmwschema' );
570 return "# Postgres specific settings
571 \$wgDBport = \"{$port}\";
572 \$wgDBmwschema = \"{$schema}\";";
575 public function preUpgrade() {
576 global $wgDBuser, $wgDBpassword;
578 # Normal user and password are selected after this step, so for now
579 # just copy these two
580 $wgDBuser = $this->getVar( '_InstallUser' );
581 $wgDBpassword = $this->getVar( '_InstallPassword' );
584 public function createTables() {
585 $schema = $this->getVar( 'wgDBmwschema' );
587 $status = $this->getConnection();
588 if ( !$status->isOK() ) {
593 * @var $conn DatabaseBase
595 $conn = $status->value
;
597 if ( $conn->tableExists( 'archive' ) ) {
598 $status->warning( 'config-install-tables-exist' );
604 $conn->begin( __METHOD__
);
606 if ( !$conn->schemaExists( $schema ) ) {
607 $status->fatal( 'config-install-pg-schema-not-exist' );
611 $error = $conn->sourceFile( $conn->getSchemaPath() );
612 if ( $error !== true ) {
613 $conn->reportQueryError( $error, 0, '', __METHOD__
);
614 $conn->rollback( __METHOD__
);
615 $status->fatal( 'config-install-tables-failed', $error );
617 $conn->commit( __METHOD__
);
619 // Resume normal operations
620 if ( $status->isOk() ) {
627 public function getGlobalDefaults() {
628 // The default $wgDBmwschema is null, which breaks Postgres and other DBMSes that require
629 // the use of a schema, so we need to set it here
631 'wgDBmwschema' => 'mediawiki',
635 public function setupPLpgSQL() {
636 // Connect as the install user, since it owns the database and so is
637 // the user that needs to run "CREATE LANGAUGE"
638 $status = $this->getPgConnection( 'create-schema' );
639 if ( !$status->isOK() ) {
643 * @var $conn DatabaseBase
645 $conn = $status->value
;
647 $exists = $conn->selectField( '"pg_catalog"."pg_language"', 1,
648 array( 'lanname' => 'plpgsql' ), __METHOD__
);
650 // Already exists, nothing to do
651 return Status
::newGood();
654 // plpgsql is not installed, but if we have a pg_pltemplate table, we
655 // should be able to create it
656 $exists = $conn->selectField(
657 array( '"pg_catalog"."pg_class"', '"pg_catalog"."pg_namespace"' ),
660 'pg_namespace.oid=relnamespace',
661 'nspname' => 'pg_catalog',
662 'relname' => 'pg_pltemplate',
667 $conn->query( 'CREATE LANGUAGE plpgsql' );
668 } catch ( DBQueryError
$e ) {
669 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
672 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
675 return Status
::newGood();