3 * PostgreSQL-specific installer.
10 * Class for setting up the MediaWiki database using Postgres.
15 class PostgresInstaller
extends DatabaseInstaller
{
17 protected $globalNames = array(
26 protected $internalDefaults = array(
27 '_InstallUser' => 'postgres',
30 var $minimumVersion = '8.3';
31 var $maxRoleSearchDepth = 5;
33 protected $pgConns = array();
39 public function isCompiled() {
40 return self
::checkExtension( 'pgsql' );
43 function getConnectForm() {
45 $this->getTextBox( 'wgDBserver', 'config-db-host', array(), $this->parent
->getHelpBox( 'config-db-host-help' ) ) .
46 $this->getTextBox( 'wgDBport', 'config-db-port' ) .
47 Html
::openElement( 'fieldset' ) .
48 Html
::element( 'legend', array(), wfMsg( 'config-db-wiki-settings' ) ) .
49 $this->getTextBox( 'wgDBname', 'config-db-name', array(), $this->parent
->getHelpBox( 'config-db-name-help' ) ) .
50 $this->getTextBox( 'wgDBmwschema', 'config-db-schema', array(), $this->parent
->getHelpBox( 'config-db-schema-help' ) ) .
51 Html
::closeElement( 'fieldset' ) .
52 $this->getInstallUserBox();
55 function submitConnectForm() {
56 // Get variables from the request
57 $newValues = $this->setVarsFromRequest( array( 'wgDBserver', 'wgDBport',
58 'wgDBname', 'wgDBmwschema' ) );
61 $status = Status
::newGood();
62 if ( !strlen( $newValues['wgDBname'] ) ) {
63 $status->fatal( 'config-missing-db-name' );
64 } elseif ( !preg_match( '/^[a-zA-Z0-9_]+$/', $newValues['wgDBname'] ) ) {
65 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
67 if ( !preg_match( '/^[a-zA-Z0-9_]*$/', $newValues['wgDBmwschema'] ) ) {
68 $status->fatal( 'config-invalid-schema', $newValues['wgDBmwschema'] );
72 if ( $status->isOK() ) {
73 $status->merge( $this->submitInstallUserBox() );
75 if ( !$status->isOK() ) {
79 $status = $this->getPgConnection( 'create-db' );
80 if ( !$status->isOK() ) {
84 * @var $conn DatabaseBase
86 $conn = $status->value
;
89 $version = $conn->getServerVersion();
90 if ( version_compare( $version, $this->minimumVersion
) < 0 ) {
91 return Status
::newFatal( 'config-postgres-old', $this->minimumVersion
, $version );
94 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
95 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
96 return Status
::newGood();
99 public function getConnection() {
100 $status = $this->getPgConnection( 'create-tables' );
101 if ( $status->isOK() ) {
102 $this->db
= $status->value
;
107 public function openConnection() {
108 return $this->openPgConnection( 'create-tables' );
112 * Open a PG connection with given parameters
113 * @param $user string User name
114 * @param $password string Password
115 * @param $dbName string Database name
118 protected function openConnectionWithParams( $user, $password, $dbName ) {
119 $status = Status
::newGood();
121 $db = new DatabasePostgres(
122 $this->getVar( 'wgDBserver' ),
126 $status->value
= $db;
127 } catch ( DBConnectionError
$e ) {
128 $status->fatal( 'config-connection-error', $e->getMessage() );
134 * Get a special type of connection
135 * @param $type string See openPgConnection() for details.
138 protected function getPgConnection( $type ) {
139 if ( isset( $this->pgConns
[$type] ) ) {
140 return Status
::newGood( $this->pgConns
[$type] );
142 $status = $this->openPgConnection( $type );
144 if ( $status->isOK() ) {
146 * @var $conn DatabaseBase
148 $conn = $status->value
;
149 $conn->clearFlag( DBO_TRX
);
150 $conn->commit( __METHOD__
);
151 $this->pgConns
[$type] = $conn;
157 * Get a connection of a specific PostgreSQL-specific type. Connections
158 * of a given type are cached.
160 * PostgreSQL lacks cross-database operations, so after the new database is
161 * created, you need to make a separate connection to connect to that
162 * database and add tables to it.
164 * New tables are owned by the user that creates them, and MediaWiki's
165 * PostgreSQL support has always assumed that the table owner will be
166 * $wgDBuser. So before we create new tables, we either need to either
167 * connect as the other user or to execute a SET ROLE command. Using a
168 * separate connection for this allows us to avoid accidental cross-module
171 * @param $type string The type of connection to get:
172 * - create-db: A connection for creating DBs, suitable for pre-
174 * - create-schema: A connection to the new DB, for creating schemas and
175 * other similar objects in the new DB.
176 * - create-tables: A connection with a role suitable for creating tables.
178 * @return Status object. On success, a connection object will be in the
181 protected function openPgConnection( $type ) {
184 return $this->openConnectionToAnyDB(
185 $this->getVar( '_InstallUser' ),
186 $this->getVar( '_InstallPassword' ) );
187 case 'create-schema':
188 return $this->openConnectionWithParams(
189 $this->getVar( '_InstallUser' ),
190 $this->getVar( '_InstallPassword' ),
191 $this->getVar( 'wgDBname' ) );
192 case 'create-tables':
193 $status = $this->openPgConnection( 'create-schema' );
194 if ( $status->isOK() ) {
196 * @var $conn DatabaseBase
198 $conn = $status->value
;
199 $safeRole = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
200 $conn->query( "SET ROLE $safeRole" );
204 throw new MWException( "Invalid special connection type: \"$type\"" );
208 public function openConnectionToAnyDB( $user, $password ) {
213 if ( !in_array( $this->getVar( 'wgDBname' ), $dbs ) ) {
214 array_unshift( $dbs, $this->getVar( 'wgDBname' ) );
217 $status = Status
::newGood();
218 foreach ( $dbs as $db ) {
220 $conn = new DatabasePostgres(
221 $this->getVar( 'wgDBserver' ),
225 } catch ( DBConnectionError
$error ) {
227 $status->fatal( 'config-pg-test-error', $db,
228 $error->getMessage() );
230 if ( $conn !== false ) {
234 if ( $conn !== false ) {
235 return Status
::newGood( $conn );
241 protected function getInstallUserPermissions() {
242 $status = $this->getPgConnection( 'create-db' );
243 if ( !$status->isOK() ) {
247 * @var $conn DatabaseBase
249 $conn = $status->value
;
250 $superuser = $this->getVar( '_InstallUser' );
252 $row = $conn->selectRow( '"pg_catalog"."pg_roles"', '*',
253 array( 'rolname' => $superuser ), __METHOD__
);
257 protected function canCreateAccounts() {
258 $perms = $this->getInstallUserPermissions();
262 return $perms->rolsuper
=== 't' ||
$perms->rolcreaterole
=== 't';
265 protected function isSuperUser() {
266 $perms = $this->getInstallUserPermissions();
270 return $perms->rolsuper
=== 't';
273 public function getSettingsForm() {
274 if ( $this->canCreateAccounts() ) {
275 $noCreateMsg = false;
277 $noCreateMsg = 'config-db-web-no-create-privs';
279 $s = $this->getWebUserBox( $noCreateMsg );
284 public function submitSettingsForm() {
285 $status = $this->submitWebUserBox();
286 if ( !$status->isOK() ) {
290 $same = $this->getVar( 'wgDBuser' ) === $this->getVar( '_InstallUser' );
295 // Check if the web user exists
296 // Connect to the database with the install user
297 $status = $this->getPgConnection( 'create-db' );
298 if ( !$status->isOK() ) {
301 $exists = $status->value
->roleExists( $this->getVar( 'wgDBuser' ) );
304 // Validate the create checkbox
305 if ( $this->canCreateAccounts() && !$same && !$exists ) {
306 $create = $this->getVar( '_CreateDBAccount' );
308 $this->setVar( '_CreateDBAccount', false );
312 if ( !$create && !$exists ) {
313 if ( $this->canCreateAccounts() ) {
314 $msg = 'config-install-user-missing-create';
316 $msg = 'config-install-user-missing';
318 return Status
::newFatal( $msg, $this->getVar( 'wgDBuser' ) );
322 // No more checks to do
323 return Status
::newGood();
326 // Existing web account. Test the connection.
327 $status = $this->openConnectionToAnyDB(
328 $this->getVar( 'wgDBuser' ),
329 $this->getVar( 'wgDBpassword' ) );
330 if ( !$status->isOK() ) {
334 // The web user is conventionally the table owner in PostgreSQL
335 // installations. Make sure the install user is able to create
336 // objects on behalf of the web user.
337 if ( $same ||
$this->canCreateObjectsForWebUser() ) {
338 return Status
::newGood();
340 return Status
::newFatal( 'config-pg-not-in-role' );
345 * Returns true if the install user is able to create objects owned
346 * by the web user, false otherwise.
349 protected function canCreateObjectsForWebUser() {
350 if ( $this->isSuperUser() ) {
354 $status = $this->getPgConnection( 'create-db' );
355 if ( !$status->isOK() ) {
358 $conn = $status->value
;
359 $installerId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
360 array( 'rolname' => $this->getVar( '_InstallUser' ) ), __METHOD__
);
361 $webId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
362 array( 'rolname' => $this->getVar( 'wgDBuser' ) ), __METHOD__
);
364 return $this->isRoleMember( $conn, $installerId, $webId, $this->maxRoleSearchDepth
);
368 * Recursive helper for canCreateObjectsForWebUser().
369 * @param $conn DatabaseBase object
370 * @param $targetMember int Role ID of the member to look for
371 * @param $group int Role ID of the group to look for
372 * @param $maxDepth int Maximum recursive search depth
375 protected function isRoleMember( $conn, $targetMember, $group, $maxDepth ) {
376 if ( $targetMember === $group ) {
377 // A role is always a member of itself
380 // Get all members of the given group
381 $res = $conn->select( '"pg_catalog"."pg_auth_members"', array( 'member' ),
382 array( 'roleid' => $group ), __METHOD__
);
383 foreach ( $res as $row ) {
384 if ( $row->member
== $targetMember ) {
385 // Found target member
388 // Recursively search each member of the group to see if the target
389 // is a member of it, up to the given maximum depth.
390 if ( $maxDepth > 0 ) {
391 if ( $this->isRoleMember( $conn, $targetMember, $row->member
, $maxDepth - 1 ) ) {
392 // Found member of member
400 public function preInstall() {
401 $createDbAccount = array(
403 'callback' => array( $this, 'setupUser' ),
406 'name' => 'pg-commit',
407 'callback' => array( $this, 'commitChanges' ),
410 'name' => 'pg-plpgsql',
411 'callback' => array( $this, 'setupPLpgSQL' ),
415 'callback' => array( $this, 'setupSchema' )
418 if( $this->getVar( '_CreateDBAccount' ) ) {
419 $this->parent
->addInstallStep( $createDbAccount, 'database' );
421 $this->parent
->addInstallStep( $commitCB, 'interwiki' );
422 $this->parent
->addInstallStep( $plpgCB, 'database' );
423 $this->parent
->addInstallStep( $schemaCB, 'database' );
426 function setupDatabase() {
427 $status = $this->getPgConnection( 'create-db' );
428 if ( !$status->isOK() ) {
431 $conn = $status->value
;
433 $dbName = $this->getVar( 'wgDBname' );
434 //$schema = $this->getVar( 'wgDBmwschema' );
435 //$user = $this->getVar( 'wgDBuser' );
436 //$safeschema = $conn->addIdentifierQuotes( $schema );
437 //$safeuser = $conn->addIdentifierQuotes( $user );
439 $exists = $conn->selectField( '"pg_catalog"."pg_database"', '1',
440 array( 'datname' => $dbName ), __METHOD__
);
442 $safedb = $conn->addIdentifierQuotes( $dbName );
443 $conn->query( "CREATE DATABASE $safedb", __METHOD__
);
445 return Status
::newGood();
448 function setupSchema() {
449 // Get a connection to the target database
450 $status = $this->getPgConnection( 'create-schema' );
451 if ( !$status->isOK() ) {
454 $conn = $status->value
;
456 // Create the schema if necessary
457 $schema = $this->getVar( 'wgDBmwschema' );
458 $safeschema = $conn->addIdentifierQuotes( $schema );
459 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
460 if( !$conn->schemaExists( $schema ) ) {
462 $conn->query( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
463 } catch ( DBQueryError
$e ) {
464 return Status
::newFatal( 'config-install-pg-schema-failed',
465 $this->getVar( '_InstallUser' ), $schema );
469 // If we created a user, alter it now to search the new schema by default
470 if ( $this->getVar( '_CreateDBAccount' ) ) {
471 $conn->query( "ALTER ROLE $safeuser SET search_path = $safeschema, public",
475 // Select the new schema in the current connection
476 $conn->query( "SET search_path = $safeschema" );
477 return Status
::newGood();
480 function commitChanges() {
481 $this->db
->commit( __METHOD__
);
482 return Status
::newGood();
485 function setupUser() {
486 if ( !$this->getVar( '_CreateDBAccount' ) ) {
487 return Status
::newGood();
490 $status = $this->getPgConnection( 'create-db' );
491 if ( !$status->isOK() ) {
494 $conn = $status->value
;
496 //$schema = $this->getVar( 'wgDBmwschema' );
497 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
498 $safepass = $conn->addQuotes( $this->getVar( 'wgDBpassword' ) );
499 //$safeschema = $conn->addIdentifierQuotes( $schema );
501 // Check if the user already exists
502 $userExists = $conn->roleExists( $this->getVar( 'wgDBuser' ) );
503 if ( !$userExists ) {
506 $sql = "CREATE ROLE $safeuser NOCREATEDB LOGIN PASSWORD $safepass";
508 // If the install user is not a superuser, we need to make the install
509 // user a member of the new user's group, so that the install user will
510 // be able to create a schema and other objects on behalf of the new user.
511 if ( !$this->isSuperUser() ) {
512 $sql .= ' ROLE' . $conn->addIdentifierQuotes( $this->getVar( '_InstallUser' ) );
515 $conn->query( $sql, __METHOD__
);
516 } catch ( DBQueryError
$e ) {
517 return Status
::newFatal( 'config-install-user-create-failed',
518 $this->getVar( 'wgDBuser' ), $e->getMessage() );
522 return Status
::newGood();
525 function getLocalSettings() {
526 $port = $this->getVar( 'wgDBport' );
527 $schema = $this->getVar( 'wgDBmwschema' );
529 "# Postgres specific settings
530 \$wgDBport = \"{$port}\";
531 \$wgDBmwschema = \"{$schema}\";";
534 public function preUpgrade() {
535 global $wgDBuser, $wgDBpassword;
537 # Normal user and password are selected after this step, so for now
538 # just copy these two
539 $wgDBuser = $this->getVar( '_InstallUser' );
540 $wgDBpassword = $this->getVar( '_InstallPassword' );
543 public function createTables() {
544 $schema = $this->getVar( 'wgDBmwschema' );
546 $status = $this->getConnection();
547 if ( !$status->isOK() ) {
552 * @var $conn DatabaseBase
554 $conn = $status->value
;
556 if( $conn->tableExists( 'user' ) ) {
557 $status->warning( 'config-install-tables-exist' );
562 $conn->begin( __METHOD__
);
564 if( !$conn->schemaExists( $schema ) ) {
565 $status->fatal( 'config-install-pg-schema-not-exist' );
568 $error = $conn->sourceFile( $conn->getSchemaPath() );
569 if( $error !== true ) {
570 $conn->reportQueryError( $error, 0, '', __METHOD__
);
571 $conn->rollback( __METHOD__
);
572 $status->fatal( 'config-install-tables-failed', $error );
574 $conn->commit( __METHOD__
);
576 // Resume normal operations
577 if( $status->isOk() ) {
583 public function setupPLpgSQL() {
584 // Connect as the install user, since it owns the database and so is
585 // the user that needs to run "CREATE LANGAUGE"
586 $status = $this->getPgConnection( 'create-schema' );
587 if ( !$status->isOK() ) {
591 * @var $conn DatabaseBase
593 $conn = $status->value
;
595 $exists = $conn->selectField( '"pg_catalog"."pg_language"', 1,
596 array( 'lanname' => 'plpgsql' ), __METHOD__
);
598 // Already exists, nothing to do
599 return Status
::newGood();
602 // plpgsql is not installed, but if we have a pg_pltemplate table, we
603 // should be able to create it
604 $exists = $conn->selectField(
605 array( '"pg_catalog"."pg_class"', '"pg_catalog"."pg_namespace"' ),
608 'pg_namespace.oid=relnamespace',
609 'nspname' => 'pg_catalog',
610 'relname' => 'pg_pltemplate',
615 $conn->query( 'CREATE LANGUAGE plpgsql' );
616 } catch ( DBQueryError
$e ) {
617 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
620 return Status
::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
622 return Status
::newGood();