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
157 protected function openConnectionWithParams( $user, $password, $dbName ) {
158 $status = Status
::newGood();
160 $db = new DatabasePostgres(
161 $this->getVar( 'wgDBserver' ),
166 $status->value
= $db;
167 } catch ( DBConnectionError
$e ) {
168 $status->fatal( 'config-connection-error', $e->getMessage() );
175 * Get a special type of connection
176 * @param string $type See openPgConnection() for details.
179 protected function getPgConnection( $type ) {
180 if ( isset( $this->pgConns
[$type] ) ) {
181 return Status
::newGood( $this->pgConns
[$type] );
183 $status = $this->openPgConnection( $type );
185 if ( $status->isOK() ) {
187 * @var $conn DatabaseBase
189 $conn = $status->value
;
190 $conn->clearFlag( DBO_TRX
);
191 $conn->commit( __METHOD__
);
192 $this->pgConns
[$type] = $conn;
199 * Get a connection of a specific PostgreSQL-specific type. Connections
200 * of a given type are cached.
202 * PostgreSQL lacks cross-database operations, so after the new database is
203 * created, you need to make a separate connection to connect to that
204 * database and add tables to it.
206 * New tables are owned by the user that creates them, and MediaWiki's
207 * PostgreSQL support has always assumed that the table owner will be
208 * $wgDBuser. So before we create new tables, we either need to either
209 * connect as the other user or to execute a SET ROLE command. Using a
210 * separate connection for this allows us to avoid accidental cross-module
213 * @param string $type The type of connection to get:
214 * - create-db: A connection for creating DBs, suitable for pre-
216 * - create-schema: A connection to the new DB, for creating schemas and
217 * other similar objects in the new DB.
218 * - create-tables: A connection with a role suitable for creating tables.
220 * @throws MWException
221 * @return Status object. On success, a connection object will be in the
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 case 'create-tables':
236 $status = $this->openPgConnection( 'create-schema' );
237 if ( $status->isOK() ) {
239 * @var $conn DatabaseBase
241 $conn = $status->value
;
242 $safeRole = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
243 $conn->query( "SET ROLE $safeRole" );
248 throw new MWException( "Invalid special connection type: \"$type\"" );
252 public function openConnectionToAnyDB( $user, $password ) {
257 if ( !in_array( $this->getVar( 'wgDBname' ), $dbs ) ) {
258 array_unshift( $dbs, $this->getVar( 'wgDBname' ) );
261 $status = Status
::newGood();
262 foreach ( $dbs as $db ) {
264 $conn = new DatabasePostgres(
265 $this->getVar( 'wgDBserver' ),
269 } catch ( DBConnectionError
$error ) {
271 $status->fatal( 'config-pg-test-error', $db,
272 $error->getMessage() );
274 if ( $conn !== false ) {
278 if ( $conn !== false ) {
279 return Status
::newGood( $conn );
285 protected function getInstallUserPermissions() {
286 $status = $this->getPgConnection( 'create-db' );
287 if ( !$status->isOK() ) {
291 * @var $conn DatabaseBase
293 $conn = $status->value
;
294 $superuser = $this->getVar( '_InstallUser' );
296 $row = $conn->selectRow( '"pg_catalog"."pg_roles"', '*',
297 array( 'rolname' => $superuser ), __METHOD__
);
302 protected function canCreateAccounts() {
303 $perms = $this->getInstallUserPermissions();
308 return $perms->rolsuper
=== 't' ||
$perms->rolcreaterole
=== 't';
311 protected function isSuperUser() {
312 $perms = $this->getInstallUserPermissions();
317 return $perms->rolsuper
=== 't';
320 public function getSettingsForm() {
321 if ( $this->canCreateAccounts() ) {
322 $noCreateMsg = false;
324 $noCreateMsg = 'config-db-web-no-create-privs';
326 $s = $this->getWebUserBox( $noCreateMsg );
331 public function submitSettingsForm() {
332 $status = $this->submitWebUserBox();
333 if ( !$status->isOK() ) {
337 $same = $this->getVar( 'wgDBuser' ) === $this->getVar( '_InstallUser' );
342 // Check if the web user exists
343 // Connect to the database with the install user
344 $status = $this->getPgConnection( 'create-db' );
345 if ( !$status->isOK() ) {
348 $exists = $status->value
->roleExists( $this->getVar( 'wgDBuser' ) );
351 // Validate the create checkbox
352 if ( $this->canCreateAccounts() && !$same && !$exists ) {
353 $create = $this->getVar( '_CreateDBAccount' );
355 $this->setVar( '_CreateDBAccount', false );
359 if ( !$create && !$exists ) {
360 if ( $this->canCreateAccounts() ) {
361 $msg = 'config-install-user-missing-create';
363 $msg = 'config-install-user-missing';
366 return Status
::newFatal( $msg, $this->getVar( 'wgDBuser' ) );
370 // No more checks to do
371 return Status
::newGood();
374 // Existing web account. Test the connection.
375 $status = $this->openConnectionToAnyDB(
376 $this->getVar( 'wgDBuser' ),
377 $this->getVar( 'wgDBpassword' ) );
378 if ( !$status->isOK() ) {
382 // The web user is conventionally the table owner in PostgreSQL
383 // installations. Make sure the install user is able to create
384 // objects on behalf of the web user.
385 if ( $same ||
$this->canCreateObjectsForWebUser() ) {
386 return Status
::newGood();
388 return Status
::newFatal( 'config-pg-not-in-role' );
393 * Returns true if the install user is able to create objects owned
394 * by the web user, false otherwise.
397 protected function canCreateObjectsForWebUser() {
398 if ( $this->isSuperUser() ) {
402 $status = $this->getPgConnection( 'create-db' );
403 if ( !$status->isOK() ) {
406 $conn = $status->value
;
407 $installerId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
408 array( 'rolname' => $this->getVar( '_InstallUser' ) ), __METHOD__
);
409 $webId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
410 array( 'rolname' => $this->getVar( 'wgDBuser' ) ), __METHOD__
);
412 return $this->isRoleMember( $conn, $installerId, $webId, $this->maxRoleSearchDepth
);
416 * Recursive helper for canCreateObjectsForWebUser().
417 * @param $conn DatabaseBase object
418 * @param int $targetMember Role ID of the member to look for
419 * @param int $group Role ID of the group to look for
420 * @param int $maxDepth Maximum recursive search depth
423 protected function isRoleMember( $conn, $targetMember, $group, $maxDepth ) {
424 if ( $targetMember === $group ) {
425 // A role is always a member of itself
428 // Get all members of the given group
429 $res = $conn->select( '"pg_catalog"."pg_auth_members"', array( 'member' ),
430 array( 'roleid' => $group ), __METHOD__
);
431 foreach ( $res as $row ) {
432 if ( $row->member
== $targetMember ) {
433 // Found target member
436 // Recursively search each member of the group to see if the target
437 // is a member of it, up to the given maximum depth.
438 if ( $maxDepth > 0 ) {
439 if ( $this->isRoleMember( $conn, $targetMember, $row->member
, $maxDepth - 1 ) ) {
440 // Found member of member
449 public function preInstall() {
450 $createDbAccount = array(
452 'callback' => array( $this, 'setupUser' ),
455 'name' => 'pg-commit',
456 'callback' => array( $this, 'commitChanges' ),
459 'name' => 'pg-plpgsql',
460 'callback' => array( $this, 'setupPLpgSQL' ),
464 'callback' => array( $this, 'setupSchema' )
467 if ( $this->getVar( '_CreateDBAccount' ) ) {
468 $this->parent
->addInstallStep( $createDbAccount, 'database' );
470 $this->parent
->addInstallStep( $commitCB, 'interwiki' );
471 $this->parent
->addInstallStep( $plpgCB, 'database' );
472 $this->parent
->addInstallStep( $schemaCB, 'database' );
475 function setupDatabase() {
476 $status = $this->getPgConnection( 'create-db' );
477 if ( !$status->isOK() ) {
480 $conn = $status->value
;
482 $dbName = $this->getVar( 'wgDBname' );
484 $exists = $conn->selectField( '"pg_catalog"."pg_database"', '1',
485 array( 'datname' => $dbName ), __METHOD__
);
487 $safedb = $conn->addIdentifierQuotes( $dbName );
488 $conn->query( "CREATE DATABASE $safedb", __METHOD__
);
491 return Status
::newGood();
494 function setupSchema() {
495 // Get a connection to the target database
496 $status = $this->getPgConnection( 'create-schema' );
497 if ( !$status->isOK() ) {
500 $conn = $status->value
;
502 // Create the schema if necessary
503 $schema = $this->getVar( 'wgDBmwschema' );
504 $safeschema = $conn->addIdentifierQuotes( $schema );
505 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
506 if ( !$conn->schemaExists( $schema ) ) {
508 $conn->query( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
509 } catch ( DBQueryError
$e ) {
510 return Status
::newFatal( 'config-install-pg-schema-failed',
511 $this->getVar( '_InstallUser' ), $schema );
515 // Select the new schema in the current connection
516 $conn->determineCoreSchema( $schema );
518 return Status
::newGood();
521 function commitChanges() {
522 $this->db
->commit( __METHOD__
);
524 return Status
::newGood();
527 function setupUser() {
528 if ( !$this->getVar( '_CreateDBAccount' ) ) {
529 return Status
::newGood();
532 $status = $this->getPgConnection( 'create-db' );
533 if ( !$status->isOK() ) {
536 $conn = $status->value
;
538 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
539 $safepass = $conn->addQuotes( $this->getVar( 'wgDBpassword' ) );
541 // Check if the user already exists
542 $userExists = $conn->roleExists( $this->getVar( 'wgDBuser' ) );
543 if ( !$userExists ) {
546 $sql = "CREATE ROLE $safeuser NOCREATEDB LOGIN PASSWORD $safepass";
548 // If the install user is not a superuser, we need to make the install
549 // user a member of the new user's group, so that the install user will
550 // be able to create a schema and other objects on behalf of the new user.
551 if ( !$this->isSuperUser() ) {
552 $sql .= ' ROLE' . $conn->addIdentifierQuotes( $this->getVar( '_InstallUser' ) );
555 $conn->query( $sql, __METHOD__
);
556 } catch ( DBQueryError
$e ) {
557 return Status
::newFatal( 'config-install-user-create-failed',
558 $this->getVar( 'wgDBuser' ), $e->getMessage() );
562 return Status
::newGood();
565 function getLocalSettings() {
566 $port = $this->getVar( 'wgDBport' );
567 $schema = $this->getVar( 'wgDBmwschema' );
569 return "# Postgres specific settings
570 \$wgDBport = \"{$port}\";
571 \$wgDBmwschema = \"{$schema}\";";
574 public function preUpgrade() {
575 global $wgDBuser, $wgDBpassword;
577 # Normal user and password are selected after this step, so for now
578 # just copy these two
579 $wgDBuser = $this->getVar( '_InstallUser' );
580 $wgDBpassword = $this->getVar( '_InstallPassword' );
583 public function createTables() {
584 $schema = $this->getVar( 'wgDBmwschema' );
586 $status = $this->getConnection();
587 if ( !$status->isOK() ) {
592 * @var $conn DatabaseBase
594 $conn = $status->value
;
596 if ( $conn->tableExists( 'archive' ) ) {
597 $status->warning( 'config-install-tables-exist' );
603 $conn->begin( __METHOD__
);
605 if ( !$conn->schemaExists( $schema ) ) {
606 $status->fatal( 'config-install-pg-schema-not-exist' );
610 $error = $conn->sourceFile( $conn->getSchemaPath() );
611 if ( $error !== true ) {
612 $conn->reportQueryError( $error, 0, '', __METHOD__
);
613 $conn->rollback( __METHOD__
);
614 $status->fatal( 'config-install-tables-failed', $error );
616 $conn->commit( __METHOD__
);
618 // Resume normal operations
619 if ( $status->isOk() ) {
626 public function setupPLpgSQL() {
627 // Connect as the install user, since it owns the database and so is
628 // the user that needs to run "CREATE LANGAUGE"
629 $status = $this->getPgConnection( 'create-schema' );
630 if ( !$status->isOK() ) {
634 * @var $conn DatabaseBase
636 $conn = $status->value
;
638 $exists = $conn->selectField( '"pg_catalog"."pg_language"', 1,
639 array( 'lanname' => 'plpgsql' ), __METHOD__
);
641 // Already exists, nothing to do
642 return Status
::newGood();
645 // plpgsql is not installed, but if we have a pg_pltemplate table, we
646 // should be able to create it
647 $exists = $conn->selectField(
648 array( '"pg_catalog"."pg_class"', '"pg_catalog"."pg_namespace"' ),
651 'pg_namespace.oid=relnamespace',
652 'nspname' => 'pg_catalog',
653 'relname' => 'pg_pltemplate',
658 $conn->query( 'CREATE LANGUAGE plpgsql' );
659 } catch ( DBQueryError
$e ) {
660 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
663 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
666 return Status
::newGood();