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() {
60 $this->getTextBox( 'wgDBserver', 'config-db-host', array(), $this->parent
->getHelpBox( 'config-db-host-help' ) ) .
61 $this->getTextBox( 'wgDBport', 'config-db-port' ) .
62 Html
::openElement( 'fieldset' ) .
63 Html
::element( 'legend', array(), wfMsg( 'config-db-wiki-settings' ) ) .
64 $this->getTextBox( 'wgDBname', 'config-db-name', array(), $this->parent
->getHelpBox( 'config-db-name-help' ) ) .
65 $this->getTextBox( 'wgDBmwschema', 'config-db-schema', array(), $this->parent
->getHelpBox( 'config-db-schema-help' ) ) .
66 Html
::closeElement( 'fieldset' ) .
67 $this->getInstallUserBox();
70 function submitConnectForm() {
71 // Get variables from the request
72 $newValues = $this->setVarsFromRequest( array( 'wgDBserver', 'wgDBport',
73 'wgDBname', 'wgDBmwschema' ) );
76 $status = Status
::newGood();
77 if ( !strlen( $newValues['wgDBname'] ) ) {
78 $status->fatal( 'config-missing-db-name' );
79 } elseif ( !preg_match( '/^[a-zA-Z0-9_]+$/', $newValues['wgDBname'] ) ) {
80 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
82 if ( !preg_match( '/^[a-zA-Z0-9_]*$/', $newValues['wgDBmwschema'] ) ) {
83 $status->fatal( 'config-invalid-schema', $newValues['wgDBmwschema'] );
87 if ( $status->isOK() ) {
88 $status->merge( $this->submitInstallUserBox() );
90 if ( !$status->isOK() ) {
94 $status = $this->getPgConnection( 'create-db' );
95 if ( !$status->isOK() ) {
99 * @var $conn DatabaseBase
101 $conn = $status->value
;
104 $version = $conn->getServerVersion();
105 if ( version_compare( $version, $this->minimumVersion
) < 0 ) {
106 return Status
::newFatal( 'config-postgres-old', $this->minimumVersion
, $version );
109 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
110 $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
;
122 public function openConnection() {
123 return $this->openPgConnection( 'create-tables' );
127 * Open a PG connection with given parameters
128 * @param $user string User name
129 * @param $password string Password
130 * @param $dbName string Database name
133 protected function openConnectionWithParams( $user, $password, $dbName ) {
134 $status = Status
::newGood();
136 $db = new DatabasePostgres(
137 $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 $type string 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 $type string 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 * @return Status object. On success, a connection object will be in the
196 protected function openPgConnection( $type ) {
199 return $this->openConnectionToAnyDB(
200 $this->getVar( '_InstallUser' ),
201 $this->getVar( '_InstallPassword' ) );
202 case 'create-schema':
203 return $this->openConnectionWithParams(
204 $this->getVar( '_InstallUser' ),
205 $this->getVar( '_InstallPassword' ),
206 $this->getVar( 'wgDBname' ) );
207 case 'create-tables':
208 $status = $this->openPgConnection( 'create-schema' );
209 if ( $status->isOK() ) {
211 * @var $conn DatabaseBase
213 $conn = $status->value
;
214 $safeRole = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
215 $conn->query( "SET ROLE $safeRole" );
219 throw new MWException( "Invalid special connection type: \"$type\"" );
223 public function openConnectionToAnyDB( $user, $password ) {
228 if ( !in_array( $this->getVar( 'wgDBname' ), $dbs ) ) {
229 array_unshift( $dbs, $this->getVar( 'wgDBname' ) );
232 $status = Status
::newGood();
233 foreach ( $dbs as $db ) {
235 $conn = new DatabasePostgres(
236 $this->getVar( 'wgDBserver' ),
240 } catch ( DBConnectionError
$error ) {
242 $status->fatal( 'config-pg-test-error', $db,
243 $error->getMessage() );
245 if ( $conn !== false ) {
249 if ( $conn !== false ) {
250 return Status
::newGood( $conn );
256 protected function getInstallUserPermissions() {
257 $status = $this->getPgConnection( 'create-db' );
258 if ( !$status->isOK() ) {
262 * @var $conn DatabaseBase
264 $conn = $status->value
;
265 $superuser = $this->getVar( '_InstallUser' );
267 $row = $conn->selectRow( '"pg_catalog"."pg_roles"', '*',
268 array( 'rolname' => $superuser ), __METHOD__
);
272 protected function canCreateAccounts() {
273 $perms = $this->getInstallUserPermissions();
277 return $perms->rolsuper
=== 't' ||
$perms->rolcreaterole
=== 't';
280 protected function isSuperUser() {
281 $perms = $this->getInstallUserPermissions();
285 return $perms->rolsuper
=== 't';
288 public function getSettingsForm() {
289 if ( $this->canCreateAccounts() ) {
290 $noCreateMsg = false;
292 $noCreateMsg = 'config-db-web-no-create-privs';
294 $s = $this->getWebUserBox( $noCreateMsg );
299 public function submitSettingsForm() {
300 $status = $this->submitWebUserBox();
301 if ( !$status->isOK() ) {
305 $same = $this->getVar( 'wgDBuser' ) === $this->getVar( '_InstallUser' );
310 // Check if the web user exists
311 // Connect to the database with the install user
312 $status = $this->getPgConnection( 'create-db' );
313 if ( !$status->isOK() ) {
316 $exists = $status->value
->roleExists( $this->getVar( 'wgDBuser' ) );
319 // Validate the create checkbox
320 if ( $this->canCreateAccounts() && !$same && !$exists ) {
321 $create = $this->getVar( '_CreateDBAccount' );
323 $this->setVar( '_CreateDBAccount', false );
327 if ( !$create && !$exists ) {
328 if ( $this->canCreateAccounts() ) {
329 $msg = 'config-install-user-missing-create';
331 $msg = 'config-install-user-missing';
333 return Status
::newFatal( $msg, $this->getVar( 'wgDBuser' ) );
337 // No more checks to do
338 return Status
::newGood();
341 // Existing web account. Test the connection.
342 $status = $this->openConnectionToAnyDB(
343 $this->getVar( 'wgDBuser' ),
344 $this->getVar( 'wgDBpassword' ) );
345 if ( !$status->isOK() ) {
349 // The web user is conventionally the table owner in PostgreSQL
350 // installations. Make sure the install user is able to create
351 // objects on behalf of the web user.
352 if ( $same ||
$this->canCreateObjectsForWebUser() ) {
353 return Status
::newGood();
355 return Status
::newFatal( 'config-pg-not-in-role' );
360 * Returns true if the install user is able to create objects owned
361 * by the web user, false otherwise.
364 protected function canCreateObjectsForWebUser() {
365 if ( $this->isSuperUser() ) {
369 $status = $this->getPgConnection( 'create-db' );
370 if ( !$status->isOK() ) {
373 $conn = $status->value
;
374 $installerId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
375 array( 'rolname' => $this->getVar( '_InstallUser' ) ), __METHOD__
);
376 $webId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
377 array( 'rolname' => $this->getVar( 'wgDBuser' ) ), __METHOD__
);
379 return $this->isRoleMember( $conn, $installerId, $webId, $this->maxRoleSearchDepth
);
383 * Recursive helper for canCreateObjectsForWebUser().
384 * @param $conn DatabaseBase object
385 * @param $targetMember int Role ID of the member to look for
386 * @param $group int Role ID of the group to look for
387 * @param $maxDepth int Maximum recursive search depth
390 protected function isRoleMember( $conn, $targetMember, $group, $maxDepth ) {
391 if ( $targetMember === $group ) {
392 // A role is always a member of itself
395 // Get all members of the given group
396 $res = $conn->select( '"pg_catalog"."pg_auth_members"', array( 'member' ),
397 array( 'roleid' => $group ), __METHOD__
);
398 foreach ( $res as $row ) {
399 if ( $row->member
== $targetMember ) {
400 // Found target member
403 // Recursively search each member of the group to see if the target
404 // is a member of it, up to the given maximum depth.
405 if ( $maxDepth > 0 ) {
406 if ( $this->isRoleMember( $conn, $targetMember, $row->member
, $maxDepth - 1 ) ) {
407 // Found member of member
415 public function preInstall() {
416 $createDbAccount = array(
418 'callback' => array( $this, 'setupUser' ),
421 'name' => 'pg-commit',
422 'callback' => array( $this, 'commitChanges' ),
425 'name' => 'pg-plpgsql',
426 'callback' => array( $this, 'setupPLpgSQL' ),
430 'callback' => array( $this, 'setupSchema' )
433 if( $this->getVar( '_CreateDBAccount' ) ) {
434 $this->parent
->addInstallStep( $createDbAccount, 'database' );
436 $this->parent
->addInstallStep( $commitCB, 'interwiki' );
437 $this->parent
->addInstallStep( $plpgCB, 'database' );
438 $this->parent
->addInstallStep( $schemaCB, 'database' );
441 function setupDatabase() {
442 $status = $this->getPgConnection( 'create-db' );
443 if ( !$status->isOK() ) {
446 $conn = $status->value
;
448 $dbName = $this->getVar( 'wgDBname' );
450 $exists = $conn->selectField( '"pg_catalog"."pg_database"', '1',
451 array( 'datname' => $dbName ), __METHOD__
);
453 $safedb = $conn->addIdentifierQuotes( $dbName );
454 $conn->query( "CREATE DATABASE $safedb", __METHOD__
);
456 return Status
::newGood();
459 function setupSchema() {
460 // Get a connection to the target database
461 $status = $this->getPgConnection( 'create-schema' );
462 if ( !$status->isOK() ) {
465 $conn = $status->value
;
467 // Create the schema if necessary
468 $schema = $this->getVar( 'wgDBmwschema' );
469 $safeschema = $conn->addIdentifierQuotes( $schema );
470 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
471 if( !$conn->schemaExists( $schema ) ) {
473 $conn->query( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
474 } catch ( DBQueryError
$e ) {
475 return Status
::newFatal( 'config-install-pg-schema-failed',
476 $this->getVar( '_InstallUser' ), $schema );
480 // Select the new schema in the current connection
481 $conn->determineCoreSchema( $schema );
482 return Status
::newGood();
485 function commitChanges() {
486 $this->db
->commit( __METHOD__
);
487 return Status
::newGood();
490 function setupUser() {
491 if ( !$this->getVar( '_CreateDBAccount' ) ) {
492 return Status
::newGood();
495 $status = $this->getPgConnection( 'create-db' );
496 if ( !$status->isOK() ) {
499 $conn = $status->value
;
501 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
502 $safepass = $conn->addQuotes( $this->getVar( 'wgDBpassword' ) );
504 // Check if the user already exists
505 $userExists = $conn->roleExists( $this->getVar( 'wgDBuser' ) );
506 if ( !$userExists ) {
509 $sql = "CREATE ROLE $safeuser NOCREATEDB LOGIN PASSWORD $safepass";
511 // If the install user is not a superuser, we need to make the install
512 // user a member of the new user's group, so that the install user will
513 // be able to create a schema and other objects on behalf of the new user.
514 if ( !$this->isSuperUser() ) {
515 $sql .= ' ROLE' . $conn->addIdentifierQuotes( $this->getVar( '_InstallUser' ) );
518 $conn->query( $sql, __METHOD__
);
519 } catch ( DBQueryError
$e ) {
520 return Status
::newFatal( 'config-install-user-create-failed',
521 $this->getVar( 'wgDBuser' ), $e->getMessage() );
525 return Status
::newGood();
528 function getLocalSettings() {
529 $port = $this->getVar( 'wgDBport' );
530 $schema = $this->getVar( 'wgDBmwschema' );
532 "# Postgres specific settings
533 \$wgDBport = \"{$port}\";
534 \$wgDBmwschema = \"{$schema}\";";
537 public function preUpgrade() {
538 global $wgDBuser, $wgDBpassword;
540 # Normal user and password are selected after this step, so for now
541 # just copy these two
542 $wgDBuser = $this->getVar( '_InstallUser' );
543 $wgDBpassword = $this->getVar( '_InstallPassword' );
546 public function createTables() {
547 $schema = $this->getVar( 'wgDBmwschema' );
549 $status = $this->getConnection();
550 if ( !$status->isOK() ) {
555 * @var $conn DatabaseBase
557 $conn = $status->value
;
559 if( $conn->tableExists( 'archive' ) ) {
560 $status->warning( 'config-install-tables-exist' );
565 $conn->begin( __METHOD__
);
567 if( !$conn->schemaExists( $schema ) ) {
568 $status->fatal( 'config-install-pg-schema-not-exist' );
571 $error = $conn->sourceFile( $conn->getSchemaPath() );
572 if( $error !== true ) {
573 $conn->reportQueryError( $error, 0, '', __METHOD__
);
574 $conn->rollback( __METHOD__
);
575 $status->fatal( 'config-install-tables-failed', $error );
577 $conn->commit( __METHOD__
);
579 // Resume normal operations
580 if( $status->isOk() ) {
586 public function setupPLpgSQL() {
587 // Connect as the install user, since it owns the database and so is
588 // the user that needs to run "CREATE LANGAUGE"
589 $status = $this->getPgConnection( 'create-schema' );
590 if ( !$status->isOK() ) {
594 * @var $conn DatabaseBase
596 $conn = $status->value
;
598 $exists = $conn->selectField( '"pg_catalog"."pg_language"', 1,
599 array( 'lanname' => 'plpgsql' ), __METHOD__
);
601 // Already exists, nothing to do
602 return Status
::newGood();
605 // plpgsql is not installed, but if we have a pg_pltemplate table, we
606 // should be able to create it
607 $exists = $conn->selectField(
608 array( '"pg_catalog"."pg_class"', '"pg_catalog"."pg_namespace"' ),
611 'pg_namespace.oid=relnamespace',
612 'nspname' => 'pg_catalog',
613 'relname' => 'pg_pltemplate',
618 $conn->query( 'CREATE LANGUAGE plpgsql' );
619 } catch ( DBQueryError
$e ) {
620 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
623 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
625 return Status
::newGood();