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 var $minimumVersion = '8.3';
46 var $maxRoleSearchDepth = 5;
48 protected $pgConns = array();
54 public function isCompiled() {
55 return self
::checkExtension( 'pgsql' );
58 function getConnectForm() {
59 return $this->getTextBox( 'wgDBserver', 'config-db-host', array(), $this->parent
->getHelpBox( 'config-db-host-help' ) ) .
60 $this->getTextBox( 'wgDBport', 'config-db-port' ) .
61 Html
::openElement( 'fieldset' ) .
62 Html
::element( 'legend', array(), wfMessage( 'config-db-wiki-settings' )->text() ) .
63 $this->getTextBox( 'wgDBname', 'config-db-name', array(), $this->parent
->getHelpBox( 'config-db-name-help' ) ) .
64 $this->getTextBox( 'wgDBmwschema', 'config-db-schema', array(), $this->parent
->getHelpBox( 'config-db-schema-help' ) ) .
65 Html
::closeElement( 'fieldset' ) .
66 $this->getInstallUserBox();
69 function submitConnectForm() {
70 // Get variables from the request
71 $newValues = $this->setVarsFromRequest( array( 'wgDBserver', 'wgDBport',
72 'wgDBname', 'wgDBmwschema' ) );
75 $status = Status
::newGood();
76 if ( !strlen( $newValues['wgDBname'] ) ) {
77 $status->fatal( 'config-missing-db-name' );
78 } elseif ( !preg_match( '/^[a-zA-Z0-9_]+$/', $newValues['wgDBname'] ) ) {
79 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
81 if ( !preg_match( '/^[a-zA-Z0-9_]*$/', $newValues['wgDBmwschema'] ) ) {
82 $status->fatal( 'config-invalid-schema', $newValues['wgDBmwschema'] );
86 if ( $status->isOK() ) {
87 $status->merge( $this->submitInstallUserBox() );
89 if ( !$status->isOK() ) {
93 $status = $this->getPgConnection( 'create-db' );
94 if ( !$status->isOK() ) {
98 * @var $conn DatabaseBase
100 $conn = $status->value
;
103 $version = $conn->getServerVersion();
104 if ( version_compare( $version, $this->minimumVersion
) < 0 ) {
105 return Status
::newFatal( 'config-postgres-old', $this->minimumVersion
, $version );
108 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
109 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
111 return Status
::newGood();
114 public function getConnection() {
115 $status = $this->getPgConnection( 'create-tables' );
116 if ( $status->isOK() ) {
117 $this->db
= $status->value
;
123 public function openConnection() {
124 return $this->openPgConnection( 'create-tables' );
128 * Open a PG connection with given parameters
129 * @param string $user User name
130 * @param string $password Password
131 * @param string $dbName Database name
134 protected function openConnectionWithParams( $user, $password, $dbName ) {
135 $status = Status
::newGood();
137 $db = new DatabasePostgres(
138 $this->getVar( 'wgDBserver' ),
143 $status->value
= $db;
144 } catch ( DBConnectionError
$e ) {
145 $status->fatal( 'config-connection-error', $e->getMessage() );
152 * Get a special type of connection
153 * @param string $type See openPgConnection() for details.
156 protected function getPgConnection( $type ) {
157 if ( isset( $this->pgConns
[$type] ) ) {
158 return Status
::newGood( $this->pgConns
[$type] );
160 $status = $this->openPgConnection( $type );
162 if ( $status->isOK() ) {
164 * @var $conn DatabaseBase
166 $conn = $status->value
;
167 $conn->clearFlag( DBO_TRX
);
168 $conn->commit( __METHOD__
);
169 $this->pgConns
[$type] = $conn;
176 * Get a connection of a specific PostgreSQL-specific type. Connections
177 * of a given type are cached.
179 * PostgreSQL lacks cross-database operations, so after the new database is
180 * created, you need to make a separate connection to connect to that
181 * database and add tables to it.
183 * New tables are owned by the user that creates them, and MediaWiki's
184 * PostgreSQL support has always assumed that the table owner will be
185 * $wgDBuser. So before we create new tables, we either need to either
186 * connect as the other user or to execute a SET ROLE command. Using a
187 * separate connection for this allows us to avoid accidental cross-module
190 * @param string $type The type of connection to get:
191 * - create-db: A connection for creating DBs, suitable for pre-
193 * - create-schema: A connection to the new DB, for creating schemas and
194 * other similar objects in the new DB.
195 * - create-tables: A connection with a role suitable for creating tables.
197 * @throws MWException
198 * @return Status object. On success, a connection object will be in the
201 protected function openPgConnection( $type ) {
204 return $this->openConnectionToAnyDB(
205 $this->getVar( '_InstallUser' ),
206 $this->getVar( '_InstallPassword' ) );
207 case 'create-schema':
208 return $this->openConnectionWithParams(
209 $this->getVar( '_InstallUser' ),
210 $this->getVar( '_InstallPassword' ),
211 $this->getVar( 'wgDBname' ) );
212 case 'create-tables':
213 $status = $this->openPgConnection( 'create-schema' );
214 if ( $status->isOK() ) {
216 * @var $conn DatabaseBase
218 $conn = $status->value
;
219 $safeRole = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
220 $conn->query( "SET ROLE $safeRole" );
225 throw new MWException( "Invalid special connection type: \"$type\"" );
229 public function openConnectionToAnyDB( $user, $password ) {
234 if ( !in_array( $this->getVar( 'wgDBname' ), $dbs ) ) {
235 array_unshift( $dbs, $this->getVar( 'wgDBname' ) );
238 $status = Status
::newGood();
239 foreach ( $dbs as $db ) {
241 $conn = new DatabasePostgres(
242 $this->getVar( 'wgDBserver' ),
246 } catch ( DBConnectionError
$error ) {
248 $status->fatal( 'config-pg-test-error', $db,
249 $error->getMessage() );
251 if ( $conn !== false ) {
255 if ( $conn !== false ) {
256 return Status
::newGood( $conn );
262 protected function getInstallUserPermissions() {
263 $status = $this->getPgConnection( 'create-db' );
264 if ( !$status->isOK() ) {
268 * @var $conn DatabaseBase
270 $conn = $status->value
;
271 $superuser = $this->getVar( '_InstallUser' );
273 $row = $conn->selectRow( '"pg_catalog"."pg_roles"', '*',
274 array( 'rolname' => $superuser ), __METHOD__
);
279 protected function canCreateAccounts() {
280 $perms = $this->getInstallUserPermissions();
285 return $perms->rolsuper
=== 't' ||
$perms->rolcreaterole
=== 't';
288 protected function isSuperUser() {
289 $perms = $this->getInstallUserPermissions();
294 return $perms->rolsuper
=== 't';
297 public function getSettingsForm() {
298 if ( $this->canCreateAccounts() ) {
299 $noCreateMsg = false;
301 $noCreateMsg = 'config-db-web-no-create-privs';
303 $s = $this->getWebUserBox( $noCreateMsg );
308 public function submitSettingsForm() {
309 $status = $this->submitWebUserBox();
310 if ( !$status->isOK() ) {
314 $same = $this->getVar( 'wgDBuser' ) === $this->getVar( '_InstallUser' );
319 // Check if the web user exists
320 // Connect to the database with the install user
321 $status = $this->getPgConnection( 'create-db' );
322 if ( !$status->isOK() ) {
325 $exists = $status->value
->roleExists( $this->getVar( 'wgDBuser' ) );
328 // Validate the create checkbox
329 if ( $this->canCreateAccounts() && !$same && !$exists ) {
330 $create = $this->getVar( '_CreateDBAccount' );
332 $this->setVar( '_CreateDBAccount', false );
336 if ( !$create && !$exists ) {
337 if ( $this->canCreateAccounts() ) {
338 $msg = 'config-install-user-missing-create';
340 $msg = 'config-install-user-missing';
343 return Status
::newFatal( $msg, $this->getVar( 'wgDBuser' ) );
347 // No more checks to do
348 return Status
::newGood();
351 // Existing web account. Test the connection.
352 $status = $this->openConnectionToAnyDB(
353 $this->getVar( 'wgDBuser' ),
354 $this->getVar( 'wgDBpassword' ) );
355 if ( !$status->isOK() ) {
359 // The web user is conventionally the table owner in PostgreSQL
360 // installations. Make sure the install user is able to create
361 // objects on behalf of the web user.
362 if ( $same ||
$this->canCreateObjectsForWebUser() ) {
363 return Status
::newGood();
365 return Status
::newFatal( 'config-pg-not-in-role' );
370 * Returns true if the install user is able to create objects owned
371 * by the web user, false otherwise.
374 protected function canCreateObjectsForWebUser() {
375 if ( $this->isSuperUser() ) {
379 $status = $this->getPgConnection( 'create-db' );
380 if ( !$status->isOK() ) {
383 $conn = $status->value
;
384 $installerId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
385 array( 'rolname' => $this->getVar( '_InstallUser' ) ), __METHOD__
);
386 $webId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
387 array( 'rolname' => $this->getVar( 'wgDBuser' ) ), __METHOD__
);
389 return $this->isRoleMember( $conn, $installerId, $webId, $this->maxRoleSearchDepth
);
393 * Recursive helper for canCreateObjectsForWebUser().
394 * @param $conn DatabaseBase object
395 * @param int $targetMember Role ID of the member to look for
396 * @param int $group Role ID of the group to look for
397 * @param int $maxDepth Maximum recursive search depth
400 protected function isRoleMember( $conn, $targetMember, $group, $maxDepth ) {
401 if ( $targetMember === $group ) {
402 // A role is always a member of itself
405 // Get all members of the given group
406 $res = $conn->select( '"pg_catalog"."pg_auth_members"', array( 'member' ),
407 array( 'roleid' => $group ), __METHOD__
);
408 foreach ( $res as $row ) {
409 if ( $row->member
== $targetMember ) {
410 // Found target member
413 // Recursively search each member of the group to see if the target
414 // is a member of it, up to the given maximum depth.
415 if ( $maxDepth > 0 ) {
416 if ( $this->isRoleMember( $conn, $targetMember, $row->member
, $maxDepth - 1 ) ) {
417 // Found member of member
426 public function preInstall() {
427 $createDbAccount = array(
429 'callback' => array( $this, 'setupUser' ),
432 'name' => 'pg-commit',
433 'callback' => array( $this, 'commitChanges' ),
436 'name' => 'pg-plpgsql',
437 'callback' => array( $this, 'setupPLpgSQL' ),
441 'callback' => array( $this, 'setupSchema' )
444 if ( $this->getVar( '_CreateDBAccount' ) ) {
445 $this->parent
->addInstallStep( $createDbAccount, 'database' );
447 $this->parent
->addInstallStep( $commitCB, 'interwiki' );
448 $this->parent
->addInstallStep( $plpgCB, 'database' );
449 $this->parent
->addInstallStep( $schemaCB, 'database' );
452 function setupDatabase() {
453 $status = $this->getPgConnection( 'create-db' );
454 if ( !$status->isOK() ) {
457 $conn = $status->value
;
459 $dbName = $this->getVar( 'wgDBname' );
461 $exists = $conn->selectField( '"pg_catalog"."pg_database"', '1',
462 array( 'datname' => $dbName ), __METHOD__
);
464 $safedb = $conn->addIdentifierQuotes( $dbName );
465 $conn->query( "CREATE DATABASE $safedb", __METHOD__
);
468 return Status
::newGood();
471 function setupSchema() {
472 // Get a connection to the target database
473 $status = $this->getPgConnection( 'create-schema' );
474 if ( !$status->isOK() ) {
477 $conn = $status->value
;
479 // Create the schema if necessary
480 $schema = $this->getVar( 'wgDBmwschema' );
481 $safeschema = $conn->addIdentifierQuotes( $schema );
482 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
483 if ( !$conn->schemaExists( $schema ) ) {
485 $conn->query( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
486 } catch ( DBQueryError
$e ) {
487 return Status
::newFatal( 'config-install-pg-schema-failed',
488 $this->getVar( '_InstallUser' ), $schema );
492 // Select the new schema in the current connection
493 $conn->determineCoreSchema( $schema );
495 return Status
::newGood();
498 function commitChanges() {
499 $this->db
->commit( __METHOD__
);
501 return Status
::newGood();
504 function setupUser() {
505 if ( !$this->getVar( '_CreateDBAccount' ) ) {
506 return Status
::newGood();
509 $status = $this->getPgConnection( 'create-db' );
510 if ( !$status->isOK() ) {
513 $conn = $status->value
;
515 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
516 $safepass = $conn->addQuotes( $this->getVar( 'wgDBpassword' ) );
518 // Check if the user already exists
519 $userExists = $conn->roleExists( $this->getVar( 'wgDBuser' ) );
520 if ( !$userExists ) {
523 $sql = "CREATE ROLE $safeuser NOCREATEDB LOGIN PASSWORD $safepass";
525 // If the install user is not a superuser, we need to make the install
526 // user a member of the new user's group, so that the install user will
527 // be able to create a schema and other objects on behalf of the new user.
528 if ( !$this->isSuperUser() ) {
529 $sql .= ' ROLE' . $conn->addIdentifierQuotes( $this->getVar( '_InstallUser' ) );
532 $conn->query( $sql, __METHOD__
);
533 } catch ( DBQueryError
$e ) {
534 return Status
::newFatal( 'config-install-user-create-failed',
535 $this->getVar( 'wgDBuser' ), $e->getMessage() );
539 return Status
::newGood();
542 function getLocalSettings() {
543 $port = $this->getVar( 'wgDBport' );
544 $schema = $this->getVar( 'wgDBmwschema' );
546 return "# Postgres specific settings
547 \$wgDBport = \"{$port}\";
548 \$wgDBmwschema = \"{$schema}\";";
551 public function preUpgrade() {
552 global $wgDBuser, $wgDBpassword;
554 # Normal user and password are selected after this step, so for now
555 # just copy these two
556 $wgDBuser = $this->getVar( '_InstallUser' );
557 $wgDBpassword = $this->getVar( '_InstallPassword' );
560 public function createTables() {
561 $schema = $this->getVar( 'wgDBmwschema' );
563 $status = $this->getConnection();
564 if ( !$status->isOK() ) {
569 * @var $conn DatabaseBase
571 $conn = $status->value
;
573 if ( $conn->tableExists( 'archive' ) ) {
574 $status->warning( 'config-install-tables-exist' );
580 $conn->begin( __METHOD__
);
582 if ( !$conn->schemaExists( $schema ) ) {
583 $status->fatal( 'config-install-pg-schema-not-exist' );
587 $error = $conn->sourceFile( $conn->getSchemaPath() );
588 if ( $error !== true ) {
589 $conn->reportQueryError( $error, 0, '', __METHOD__
);
590 $conn->rollback( __METHOD__
);
591 $status->fatal( 'config-install-tables-failed', $error );
593 $conn->commit( __METHOD__
);
595 // Resume normal operations
596 if ( $status->isOk() ) {
603 public function setupPLpgSQL() {
604 // Connect as the install user, since it owns the database and so is
605 // the user that needs to run "CREATE LANGAUGE"
606 $status = $this->getPgConnection( 'create-schema' );
607 if ( !$status->isOK() ) {
611 * @var $conn DatabaseBase
613 $conn = $status->value
;
615 $exists = $conn->selectField( '"pg_catalog"."pg_language"', 1,
616 array( 'lanname' => 'plpgsql' ), __METHOD__
);
618 // Already exists, nothing to do
619 return Status
::newGood();
622 // plpgsql is not installed, but if we have a pg_pltemplate table, we
623 // should be able to create it
624 $exists = $conn->selectField(
625 array( '"pg_catalog"."pg_class"', '"pg_catalog"."pg_namespace"' ),
628 'pg_namespace.oid=relnamespace',
629 'nspname' => 'pg_catalog',
630 'relname' => 'pg_pltemplate',
635 $conn->query( 'CREATE LANGUAGE plpgsql' );
636 } catch ( DBQueryError
$e ) {
637 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
640 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
643 return Status
::newGood();