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' ) );
110 return Status
::newGood();
113 public function getConnection() {
114 $status = $this->getPgConnection( 'create-tables' );
115 if ( $status->isOK() ) {
116 $this->db
= $status->value
;
121 public function openConnection() {
122 return $this->openPgConnection( 'create-tables' );
126 * Open a PG connection with given parameters
127 * @param string $user User name
128 * @param string $password Password
129 * @param string $dbName Database name
132 protected function openConnectionWithParams( $user, $password, $dbName ) {
133 $status = Status
::newGood();
135 $db = new DatabasePostgres(
136 $this->getVar( 'wgDBserver' ),
141 $status->value
= $db;
142 } catch ( DBConnectionError
$e ) {
143 $status->fatal( 'config-connection-error', $e->getMessage() );
149 * Get a special type of connection
150 * @param string $type See openPgConnection() for details.
153 protected function getPgConnection( $type ) {
154 if ( isset( $this->pgConns
[$type] ) ) {
155 return Status
::newGood( $this->pgConns
[$type] );
157 $status = $this->openPgConnection( $type );
159 if ( $status->isOK() ) {
161 * @var $conn DatabaseBase
163 $conn = $status->value
;
164 $conn->clearFlag( DBO_TRX
);
165 $conn->commit( __METHOD__
);
166 $this->pgConns
[$type] = $conn;
172 * Get a connection of a specific PostgreSQL-specific type. Connections
173 * of a given type are cached.
175 * PostgreSQL lacks cross-database operations, so after the new database is
176 * created, you need to make a separate connection to connect to that
177 * database and add tables to it.
179 * New tables are owned by the user that creates them, and MediaWiki's
180 * PostgreSQL support has always assumed that the table owner will be
181 * $wgDBuser. So before we create new tables, we either need to either
182 * connect as the other user or to execute a SET ROLE command. Using a
183 * separate connection for this allows us to avoid accidental cross-module
186 * @param string $type The type of connection to get:
187 * - create-db: A connection for creating DBs, suitable for pre-
189 * - create-schema: A connection to the new DB, for creating schemas and
190 * other similar objects in the new DB.
191 * - create-tables: A connection with a role suitable for creating tables.
193 * @throws MWException
194 * @return Status object. On success, a connection object will be in the
197 protected function openPgConnection( $type ) {
200 return $this->openConnectionToAnyDB(
201 $this->getVar( '_InstallUser' ),
202 $this->getVar( '_InstallPassword' ) );
203 case 'create-schema':
204 return $this->openConnectionWithParams(
205 $this->getVar( '_InstallUser' ),
206 $this->getVar( '_InstallPassword' ),
207 $this->getVar( 'wgDBname' ) );
208 case 'create-tables':
209 $status = $this->openPgConnection( 'create-schema' );
210 if ( $status->isOK() ) {
212 * @var $conn DatabaseBase
214 $conn = $status->value
;
215 $safeRole = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
216 $conn->query( "SET ROLE $safeRole" );
220 throw new MWException( "Invalid special connection type: \"$type\"" );
224 public function openConnectionToAnyDB( $user, $password ) {
229 if ( !in_array( $this->getVar( 'wgDBname' ), $dbs ) ) {
230 array_unshift( $dbs, $this->getVar( 'wgDBname' ) );
233 $status = Status
::newGood();
234 foreach ( $dbs as $db ) {
236 $conn = new DatabasePostgres(
237 $this->getVar( 'wgDBserver' ),
241 } catch ( DBConnectionError
$error ) {
243 $status->fatal( 'config-pg-test-error', $db,
244 $error->getMessage() );
246 if ( $conn !== false ) {
250 if ( $conn !== false ) {
251 return Status
::newGood( $conn );
257 protected function getInstallUserPermissions() {
258 $status = $this->getPgConnection( 'create-db' );
259 if ( !$status->isOK() ) {
263 * @var $conn DatabaseBase
265 $conn = $status->value
;
266 $superuser = $this->getVar( '_InstallUser' );
268 $row = $conn->selectRow( '"pg_catalog"."pg_roles"', '*',
269 array( 'rolname' => $superuser ), __METHOD__
);
273 protected function canCreateAccounts() {
274 $perms = $this->getInstallUserPermissions();
278 return $perms->rolsuper
=== 't' ||
$perms->rolcreaterole
=== 't';
281 protected function isSuperUser() {
282 $perms = $this->getInstallUserPermissions();
286 return $perms->rolsuper
=== 't';
289 public function getSettingsForm() {
290 if ( $this->canCreateAccounts() ) {
291 $noCreateMsg = false;
293 $noCreateMsg = 'config-db-web-no-create-privs';
295 $s = $this->getWebUserBox( $noCreateMsg );
300 public function submitSettingsForm() {
301 $status = $this->submitWebUserBox();
302 if ( !$status->isOK() ) {
306 $same = $this->getVar( 'wgDBuser' ) === $this->getVar( '_InstallUser' );
311 // Check if the web user exists
312 // Connect to the database with the install user
313 $status = $this->getPgConnection( 'create-db' );
314 if ( !$status->isOK() ) {
317 $exists = $status->value
->roleExists( $this->getVar( 'wgDBuser' ) );
320 // Validate the create checkbox
321 if ( $this->canCreateAccounts() && !$same && !$exists ) {
322 $create = $this->getVar( '_CreateDBAccount' );
324 $this->setVar( '_CreateDBAccount', false );
328 if ( !$create && !$exists ) {
329 if ( $this->canCreateAccounts() ) {
330 $msg = 'config-install-user-missing-create';
332 $msg = 'config-install-user-missing';
334 return Status
::newFatal( $msg, $this->getVar( 'wgDBuser' ) );
338 // No more checks to do
339 return Status
::newGood();
342 // Existing web account. Test the connection.
343 $status = $this->openConnectionToAnyDB(
344 $this->getVar( 'wgDBuser' ),
345 $this->getVar( 'wgDBpassword' ) );
346 if ( !$status->isOK() ) {
350 // The web user is conventionally the table owner in PostgreSQL
351 // installations. Make sure the install user is able to create
352 // objects on behalf of the web user.
353 if ( $same ||
$this->canCreateObjectsForWebUser() ) {
354 return Status
::newGood();
356 return Status
::newFatal( 'config-pg-not-in-role' );
361 * Returns true if the install user is able to create objects owned
362 * by the web user, false otherwise.
365 protected function canCreateObjectsForWebUser() {
366 if ( $this->isSuperUser() ) {
370 $status = $this->getPgConnection( 'create-db' );
371 if ( !$status->isOK() ) {
374 $conn = $status->value
;
375 $installerId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
376 array( 'rolname' => $this->getVar( '_InstallUser' ) ), __METHOD__
);
377 $webId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
378 array( 'rolname' => $this->getVar( 'wgDBuser' ) ), __METHOD__
);
380 return $this->isRoleMember( $conn, $installerId, $webId, $this->maxRoleSearchDepth
);
384 * Recursive helper for canCreateObjectsForWebUser().
385 * @param $conn DatabaseBase object
386 * @param int $targetMember Role ID of the member to look for
387 * @param int $group Role ID of the group to look for
388 * @param int $maxDepth Maximum recursive search depth
391 protected function isRoleMember( $conn, $targetMember, $group, $maxDepth ) {
392 if ( $targetMember === $group ) {
393 // A role is always a member of itself
396 // Get all members of the given group
397 $res = $conn->select( '"pg_catalog"."pg_auth_members"', array( 'member' ),
398 array( 'roleid' => $group ), __METHOD__
);
399 foreach ( $res as $row ) {
400 if ( $row->member
== $targetMember ) {
401 // Found target member
404 // Recursively search each member of the group to see if the target
405 // is a member of it, up to the given maximum depth.
406 if ( $maxDepth > 0 ) {
407 if ( $this->isRoleMember( $conn, $targetMember, $row->member
, $maxDepth - 1 ) ) {
408 // Found member of member
416 public function preInstall() {
417 $createDbAccount = array(
419 'callback' => array( $this, 'setupUser' ),
422 'name' => 'pg-commit',
423 'callback' => array( $this, 'commitChanges' ),
426 'name' => 'pg-plpgsql',
427 'callback' => array( $this, 'setupPLpgSQL' ),
431 'callback' => array( $this, 'setupSchema' )
434 if( $this->getVar( '_CreateDBAccount' ) ) {
435 $this->parent
->addInstallStep( $createDbAccount, 'database' );
437 $this->parent
->addInstallStep( $commitCB, 'interwiki' );
438 $this->parent
->addInstallStep( $plpgCB, 'database' );
439 $this->parent
->addInstallStep( $schemaCB, 'database' );
442 function setupDatabase() {
443 $status = $this->getPgConnection( 'create-db' );
444 if ( !$status->isOK() ) {
447 $conn = $status->value
;
449 $dbName = $this->getVar( 'wgDBname' );
451 $exists = $conn->selectField( '"pg_catalog"."pg_database"', '1',
452 array( 'datname' => $dbName ), __METHOD__
);
454 $safedb = $conn->addIdentifierQuotes( $dbName );
455 $conn->query( "CREATE DATABASE $safedb", __METHOD__
);
457 return Status
::newGood();
460 function setupSchema() {
461 // Get a connection to the target database
462 $status = $this->getPgConnection( 'create-schema' );
463 if ( !$status->isOK() ) {
466 $conn = $status->value
;
468 // Create the schema if necessary
469 $schema = $this->getVar( 'wgDBmwschema' );
470 $safeschema = $conn->addIdentifierQuotes( $schema );
471 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
472 if( !$conn->schemaExists( $schema ) ) {
474 $conn->query( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
475 } catch ( DBQueryError
$e ) {
476 return Status
::newFatal( 'config-install-pg-schema-failed',
477 $this->getVar( '_InstallUser' ), $schema );
481 // Select the new schema in the current connection
482 $conn->determineCoreSchema( $schema );
483 return Status
::newGood();
486 function commitChanges() {
487 $this->db
->commit( __METHOD__
);
488 return Status
::newGood();
491 function setupUser() {
492 if ( !$this->getVar( '_CreateDBAccount' ) ) {
493 return Status
::newGood();
496 $status = $this->getPgConnection( 'create-db' );
497 if ( !$status->isOK() ) {
500 $conn = $status->value
;
502 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
503 $safepass = $conn->addQuotes( $this->getVar( 'wgDBpassword' ) );
505 // Check if the user already exists
506 $userExists = $conn->roleExists( $this->getVar( 'wgDBuser' ) );
507 if ( !$userExists ) {
510 $sql = "CREATE ROLE $safeuser NOCREATEDB LOGIN PASSWORD $safepass";
512 // If the install user is not a superuser, we need to make the install
513 // user a member of the new user's group, so that the install user will
514 // be able to create a schema and other objects on behalf of the new user.
515 if ( !$this->isSuperUser() ) {
516 $sql .= ' ROLE' . $conn->addIdentifierQuotes( $this->getVar( '_InstallUser' ) );
519 $conn->query( $sql, __METHOD__
);
520 } catch ( DBQueryError
$e ) {
521 return Status
::newFatal( 'config-install-user-create-failed',
522 $this->getVar( 'wgDBuser' ), $e->getMessage() );
526 return Status
::newGood();
529 function getLocalSettings() {
530 $port = $this->getVar( 'wgDBport' );
531 $schema = $this->getVar( 'wgDBmwschema' );
533 "# Postgres specific settings
534 \$wgDBport = \"{$port}\";
535 \$wgDBmwschema = \"{$schema}\";";
538 public function preUpgrade() {
539 global $wgDBuser, $wgDBpassword;
541 # Normal user and password are selected after this step, so for now
542 # just copy these two
543 $wgDBuser = $this->getVar( '_InstallUser' );
544 $wgDBpassword = $this->getVar( '_InstallPassword' );
547 public function createTables() {
548 $schema = $this->getVar( 'wgDBmwschema' );
550 $status = $this->getConnection();
551 if ( !$status->isOK() ) {
556 * @var $conn DatabaseBase
558 $conn = $status->value
;
560 if( $conn->tableExists( 'archive' ) ) {
561 $status->warning( 'config-install-tables-exist' );
566 $conn->begin( __METHOD__
);
568 if( !$conn->schemaExists( $schema ) ) {
569 $status->fatal( 'config-install-pg-schema-not-exist' );
572 $error = $conn->sourceFile( $conn->getSchemaPath() );
573 if( $error !== true ) {
574 $conn->reportQueryError( $error, 0, '', __METHOD__
);
575 $conn->rollback( __METHOD__
);
576 $status->fatal( 'config-install-tables-failed', $error );
578 $conn->commit( __METHOD__
);
580 // Resume normal operations
581 if( $status->isOk() ) {
587 public function setupPLpgSQL() {
588 // Connect as the install user, since it owns the database and so is
589 // the user that needs to run "CREATE LANGAUGE"
590 $status = $this->getPgConnection( 'create-schema' );
591 if ( !$status->isOK() ) {
595 * @var $conn DatabaseBase
597 $conn = $status->value
;
599 $exists = $conn->selectField( '"pg_catalog"."pg_language"', 1,
600 array( 'lanname' => 'plpgsql' ), __METHOD__
);
602 // Already exists, nothing to do
603 return Status
::newGood();
606 // plpgsql is not installed, but if we have a pg_pltemplate table, we
607 // should be able to create it
608 $exists = $conn->selectField(
609 array( '"pg_catalog"."pg_class"', '"pg_catalog"."pg_namespace"' ),
612 'pg_namespace.oid=relnamespace',
613 'nspname' => 'pg_catalog',
614 'relname' => 'pg_pltemplate',
619 $conn->query( 'CREATE LANGUAGE plpgsql' );
620 } catch ( DBQueryError
$e ) {
621 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
624 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
626 return Status
::newGood();