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() ) {
83 $conn = $status->value;
86 $version = $conn->getServerVersion();
87 if ( version_compare( $version, $this->minimumVersion ) < 0 ) {
88 return Status::newFatal( 'config-postgres-old', $this->minimumVersion, $version );
91 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
92 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
93 return Status::newGood();
96 public function getConnection() {
97 $status = $this->getPgConnection( 'create-tables' );
98 if ( $status->isOK() ) {
99 $this->db = $status->value;
104 public function openConnection() {
105 return $this->openPgConnection( 'create-tables' );
109 * Open a PG connection with given parameters
110 * @param $user User name
111 * @param $password Password
112 * @param $dbName Database name
115 protected function openConnectionWithParams( $user, $password, $dbName ) {
116 $status = Status::newGood();
118 $GLOBALS['wgDBport'] = $this->getVar( 'wgDBport' );
119 $db = new DatabasePostgres(
120 $this->getVar( 'wgDBserver' ),
124 $status->value = $db;
125 } catch ( DBConnectionError $e ) {
126 $status->fatal( 'config-connection-error', $e->getMessage() );
132 * Get a special type of connection
133 * @param $type See openPgConnection() for details.
136 protected function getPgConnection( $type ) {
137 if ( isset( $this->pgConns[$type] ) ) {
138 return Status::newGood( $this->pgConns[$type] );
140 $status = $this->openPgConnection( $type );
142 if ( $status->isOK() ) {
143 $conn = $status->value;
144 $conn->clearFlag( DBO_TRX );
146 $this->pgConns[$type] = $conn;
152 * Get a connection of a specific PostgreSQL-specific type. Connections
153 * of a given type are cached.
155 * PostgreSQL lacks cross-database operations, so after the new database is
156 * created, you need to make a separate connection to connect to that
157 * database and add tables to it.
159 * New tables are owned by the user that creates them, and MediaWiki's
160 * PostgreSQL support has always assumed that the table owner will be
161 * $wgDBuser. So before we create new tables, we either need to either
162 * connect as the other user or to execute a SET ROLE command. Using a
163 * separate connection for this allows us to avoid accidental cross-module
166 * @param $type The type of connection to get:
167 * - create-db: A connection for creating DBs, suitable for pre-
169 * - create-schema: A connection to the new DB, for creating schemas and
170 * other similar objects in the new DB.
171 * - create-tables: A connection with a role suitable for creating tables.
173 * @return A Status object. On success, a connection object will be in the
176 protected function openPgConnection( $type ) {
179 return $this->openConnectionToAnyDB(
180 $this->getVar( '_InstallUser' ),
181 $this->getVar( '_InstallPassword' ) );
182 case 'create-schema':
183 return $this->openConnectionWithParams(
184 $this->getVar( '_InstallUser' ),
185 $this->getVar( '_InstallPassword' ),
186 $this->getVar( 'wgDBname' ) );
187 case 'create-tables':
188 $status = $this->openPgConnection( 'create-schema' );
189 if ( $status->isOK() ) {
190 $conn = $status->value;
191 $safeRole = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
192 $conn->query( "SET ROLE $safeRole" );
196 throw new MWException( "Invalid special connection type: \"$type\"" );
200 public function openConnectionToAnyDB( $user, $password ) {
205 if ( !in_array( $this->getVar( 'wgDBname' ), $dbs ) ) {
206 array_unshift( $dbs, $this->getVar( 'wgDBname' ) );
208 $status = Status::newGood();
209 foreach ( $dbs as $db ) {
211 $GLOBALS['wgDBport'] = $this->getVar( 'wgDBport' );
212 $conn = new DatabasePostgres(
213 $this->getVar( 'wgDBserver' ),
217 } catch ( DBConnectionError $error ) {
219 $status->fatal( 'config-pg-test-error', $db,
220 $error->getMessage() );
222 if ( $conn !== false ) {
226 if ( $conn !== false ) {
227 return Status::newGood( $conn );
233 protected function getInstallUserPermissions() {
234 $status = $this->getPgConnection( 'create-db' );
235 if ( !$status->isOK() ) {
238 $conn = $status->value;
239 $superuser = $this->getVar( '_InstallUser' );
241 $row = $conn->selectRow( '"pg_catalog"."pg_roles"', '*',
242 array( 'rolname' => $superuser ), __METHOD__ );
246 protected function canCreateAccounts() {
247 $perms = $this->getInstallUserPermissions();
251 return $perms->rolsuper === 't' || $perms->rolcreaterole === 't';
254 protected function isSuperUser() {
255 $perms = $this->getInstallUserPermissions();
259 return $perms->rolsuper === 't';
262 public function getSettingsForm() {
263 if ( $this->canCreateAccounts() ) {
264 $noCreateMsg = false;
266 $noCreateMsg = 'config-db-web-no-create-privs';
268 $s = $this->getWebUserBox( $noCreateMsg );
273 public function submitSettingsForm() {
274 $status = $this->submitWebUserBox();
275 if ( !$status->isOK() ) {
279 $same = $this->getVar( 'wgDBuser' ) === $this->getVar( '_InstallUser' );
284 // Check if the web user exists
285 // Connect to the database with the install user
286 $status = $this->getPgConnection( 'create-db' );
287 if ( !$status->isOK() ) {
290 $exists = $status->value->roleExists( $this->getVar( 'wgDBuser' ) );
293 // Validate the create checkbox
294 if ( $this->canCreateAccounts() && !$same && !$exists ) {
295 $create = $this->getVar( '_CreateDBAccount' );
297 $this->setVar( '_CreateDBAccount', false );
301 if ( !$create && !$exists ) {
302 if ( $this->canCreateAccounts() ) {
303 $msg = 'config-install-user-missing-create';
305 $msg = 'config-install-user-missing';
307 return Status::newFatal( $msg, $this->getVar( 'wgDBuser' ) );
311 // No more checks to do
312 return Status::newGood();
315 // Existing web account. Test the connection.
316 $status = $this->openConnectionToAnyDB(
317 $this->getVar( 'wgDBuser' ),
318 $this->getVar( 'wgDBpassword' ) );
319 if ( !$status->isOK() ) {
323 // The web user is conventionally the table owner in PostgreSQL
324 // installations. Make sure the install user is able to create
325 // objects on behalf of the web user.
326 if ( $same || $this->canCreateObjectsForWebUser() ) {
327 return Status::newGood();
329 return Status::newFatal( 'config-pg-not-in-role' );
334 * Returns true if the install user is able to create objects owned
335 * by the web user, false otherwise.
337 protected function canCreateObjectsForWebUser() {
338 if ( $this->isSuperUser() ) {
342 $status = $this->getPgConnection( 'create-db' );
343 if ( !$status->isOK() ) {
346 $conn = $status->value;
347 $installerId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
348 array( 'rolname' => $this->getVar( '_InstallUser' ) ), __METHOD__ );
349 $webId = $conn->selectField( '"pg_catalog"."pg_roles"', 'oid',
350 array( 'rolname' => $this->getVar( 'wgDBuser' ) ), __METHOD__ );
352 return $this->isRoleMember( $conn, $installerId, $webId, $this->maxRoleSearchDepth );
356 * Recursive helper for canCreateObjectsForWebUser().
357 * @param $conn Database object
358 * @param $targetMember Role ID of the member to look for
359 * @param $group Role ID of the group to look for
360 * @param $maxDepth Maximum recursive search depth
362 protected function isRoleMember( $conn, $targetMember, $group, $maxDepth ) {
363 if ( $targetMember === $group ) {
364 // A role is always a member of itself
367 // Get all members of the given group
368 $res = $conn->select( '"pg_catalog"."pg_auth_members"', array( 'member' ),
369 array( 'roleid' => $group ), __METHOD__ );
370 foreach ( $res as $row ) {
371 if ( $row->member == $targetMember ) {
372 // Found target member
375 // Recursively search each member of the group to see if the target
376 // is a member of it, up to the given maximum depth.
377 if ( $maxDepth > 0 ) {
378 if ( $this->isRoleMember( $conn, $targetMember, $row->member, $maxDepth - 1 ) ) {
379 // Found member of member
387 public function preInstall() {
389 'name' => 'pg-commit',
390 'callback' => array( $this, 'commitChanges' ),
393 'name' => 'pg-plpgsql',
394 'callback' => array( $this, 'setupPLpgSQL' ),
398 'callback' => array( $this, 'setupSchema' )
400 $this->parent->addInstallStep( $commitCB, 'interwiki' );
401 $this->parent->addInstallStep( $plpgCB, 'database' );
402 $this->parent->addInstallStep( $schemaCB, 'database' );
403 if( $this->getVar( '_CreateDBAccount' ) ) {
404 $this->parent->addInstallStep( array(
406 'callback' => array( $this, 'setupUser' ),
411 function setupDatabase() {
412 $status = $this->getPgConnection( 'create-db' );
413 if ( !$status->isOK() ) {
416 $conn = $status->value;
418 $dbName = $this->getVar( 'wgDBname' );
419 $schema = $this->getVar( 'wgDBmwschema' );
420 $user = $this->getVar( 'wgDBuser' );
421 $safeschema = $conn->addIdentifierQuotes( $schema );
422 $safeuser = $conn->addIdentifierQuotes( $user );
424 $exists = $conn->selectField( '"pg_catalog"."pg_database"', '1',
425 array( 'datname' => $dbName ), __METHOD__ );
427 $safedb = $conn->addIdentifierQuotes( $dbName );
428 $conn->query( "CREATE DATABASE $safedb", __METHOD__ );
430 return Status::newGood();
433 function setupSchema() {
434 // Get a connection to the target database
435 $status = $this->getPgConnection( 'create-schema' );
436 if ( !$status->isOK() ) {
439 $conn = $status->value;
441 // Create the schema if necessary
442 $schema = $this->getVar( 'wgDBmwschema' );
443 $safeschema = $conn->addIdentifierQuotes( $schema );
444 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
445 if( !$conn->schemaExists( $schema ) ) {
447 $conn->query( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
448 } catch ( DBQueryError $e ) {
449 return Status::newFatal( 'config-install-pg-schema-failed',
450 $this->getVar( '_InstallUser' ), $schema );
454 // If we created a user, alter it now to search the new schema by default
455 if ( $this->getVar( '_CreateDBAccount' ) ) {
456 $conn->query( "ALTER ROLE $safeuser SET search_path = $safeschema, public",
460 // Select the new schema in the current connection
461 $conn->query( "SET search_path = $safeschema" );
462 return Status::newGood();
465 function commitChanges() {
466 $this->db->query( 'COMMIT' );
467 return Status::newGood();
470 function setupUser() {
471 if ( !$this->getVar( '_CreateDBAccount' ) ) {
472 return Status::newGood();
475 $status = $this->getPgConnection( 'create-db' );
476 if ( !$status->isOK() ) {
479 $conn = $status->value;
481 $schema = $this->getVar( 'wgDBmwschema' );
482 $safeuser = $conn->addIdentifierQuotes( $this->getVar( 'wgDBuser' ) );
483 $safepass = $conn->addQuotes( $this->getVar( 'wgDBpassword' ) );
484 $safeschema = $conn->addIdentifierQuotes( $schema );
486 // Check if the user already exists
487 $userExists = $conn->roleExists( $this->getVar( 'wgDBuser' ) );
488 if ( !$userExists ) {
491 $sql = "CREATE ROLE $safeuser NOCREATEDB LOGIN PASSWORD $safepass";
493 // If the install user is not a superuser, we need to make the install
494 // user a member of the new user's group, so that the install user will
495 // be able to create a schema and other objects on behalf of the new user.
496 if ( !$this->isSuperUser() ) {
497 $sql .= ' ROLE' . $conn->addIdentifierQuotes( $this->getVar( '_InstallUser' ) );
500 $conn->query( $sql, __METHOD__ );
501 } catch ( DBQueryError $e ) {
502 return Status::newFatal( 'config-install-user-create-failed',
503 $this->getVar( 'wgDBuser' ), $e->getMessage() );
507 return Status::newGood();
510 function getLocalSettings() {
511 $port = $this->getVar( 'wgDBport' );
512 $schema = $this->getVar( 'wgDBmwschema' );
514 "# Postgres specific settings
515 \$wgDBport = \"{$port}\";
516 \$wgDBmwschema = \"{$schema}\";";
519 public function preUpgrade() {
520 global $wgDBuser, $wgDBpassword;
522 # Normal user and password are selected after this step, so for now
523 # just copy these two
524 $wgDBuser = $this->getVar( '_InstallUser' );
525 $wgDBpassword = $this->getVar( '_InstallPassword' );
528 public function createTables() {
529 $schema = $this->getVar( 'wgDBmwschema' );
531 $status = $this->getConnection();
532 if ( !$status->isOK() ) {
535 $conn = $status->value;
537 if( $conn->tableExists( 'user' ) ) {
538 $status->warning( 'config-install-tables-exist' );
542 $conn->begin( __METHOD__ );
544 if( !$conn->schemaExists( $schema ) ) {
545 $status->fatal( 'config-install-pg-schema-not-exist' );
548 $error = $conn->sourceFile( $conn->getSchema() );
549 if( $error !== true ) {
550 $conn->reportQueryError( $error, 0, '', __METHOD__ );
551 $conn->rollback( __METHOD__ );
552 $status->fatal( 'config-install-tables-failed', $error );
554 $conn->commit( __METHOD__ );
556 // Resume normal operations
557 if( $status->isOk() ) {
563 public function setupPLpgSQL() {
564 // Connect as the install user, since it owns the database and so is
565 // the user that needs to run "CREATE LANGAUGE"
566 $status = $this->getPgConnection( 'create-schema' );
567 if ( !$status->isOK() ) {
570 $conn = $status->value;
572 $exists = $conn->selectField( '"pg_catalog"."pg_language"', 1,
573 array( 'lanname' => 'plpgsql' ), __METHOD__ );
575 // Already exists, nothing to do
576 return Status::newGood();
579 // plpgsql is not installed, but if we have a pg_pltemplate table, we
580 // should be able to create it
581 $exists = $conn->selectField(
582 array( '"pg_catalog"."pg_class"', '"pg_catalog"."pg_namespace"' ),
585 'pg_namespace.oid=relnamespace',
586 'nspname' => 'pg_catalog',
587 'relname' => 'pg_pltemplate',
592 $conn->query( 'CREATE LANGUAGE plpgsql' );
593 } catch ( DBQueryError $e ) {
594 return Status::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
597 return Status::newFatal( 'config-pg-no-plpgsql', $this->getVar( 'wgDBname' ) );
599 return Status::newGood();