rdbms: Avoid selectDB() call in LoadMonitor new connections
[mediawiki.git] / includes / installer / DatabaseInstaller.php
blob6c56b3d430c987ff23f0587aac8a26f58ace775a
1 <?php
2 /**
3 * DBMS-specific installation helper.
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
20 * @file
21 * @ingroup Deployment
23 use Wikimedia\Rdbms\LBFactorySingle;
24 use Wikimedia\Rdbms\Database;
25 use Wikimedia\Rdbms\IDatabase;
27 /**
28 * Base class for DBMS-specific installation helper classes.
30 * @ingroup Deployment
31 * @since 1.17
33 abstract class DatabaseInstaller {
35 /**
36 * The Installer object.
38 * @todo Naming this parent is confusing, 'installer' would be clearer.
40 * @var WebInstaller
42 public $parent;
44 /**
45 * The database connection.
47 * @var Database
49 public $db = null;
51 /**
52 * Internal variables for installation.
54 * @var array
56 protected $internalDefaults = [];
58 /**
59 * Array of MW configuration globals this class uses.
61 * @var array
63 protected $globalNames = [];
65 /**
66 * Return the internal name, e.g. 'mysql', or 'sqlite'.
68 abstract public function getName();
70 /**
71 * @return bool Returns true if the client library is compiled in.
73 abstract public function isCompiled();
75 /**
76 * Checks for installation prerequisites other than those checked by isCompiled()
77 * @since 1.19
78 * @return Status
80 public function checkPrerequisites() {
81 return Status::newGood();
84 /**
85 * Get HTML for a web form that configures this database. Configuration
86 * at this time should be the minimum needed to connect and test
87 * whether install or upgrade is required.
89 * If this is called, $this->parent can be assumed to be a WebInstaller.
91 abstract public function getConnectForm();
93 /**
94 * Set variables based on the request array, assuming it was submitted
95 * via the form returned by getConnectForm(). Validate the connection
96 * settings by attempting to connect with them.
98 * If this is called, $this->parent can be assumed to be a WebInstaller.
100 * @return Status
102 abstract public function submitConnectForm();
105 * Get HTML for a web form that retrieves settings used for installation.
106 * $this->parent can be assumed to be a WebInstaller.
107 * If the DB type has no settings beyond those already configured with
108 * getConnectForm(), this should return false.
109 * @return bool
111 public function getSettingsForm() {
112 return false;
116 * Set variables based on the request array, assuming it was submitted via
117 * the form return by getSettingsForm().
119 * @return Status
121 public function submitSettingsForm() {
122 return Status::newGood();
126 * Open a connection to the database using the administrative user/password
127 * currently defined in the session, without any caching. Returns a status
128 * object. On success, the status object will contain a Database object in
129 * its value member.
131 * @return Status
133 abstract public function openConnection();
136 * Create the database and return a Status object indicating success or
137 * failure.
139 * @return Status
141 abstract public function setupDatabase();
144 * Connect to the database using the administrative user/password currently
145 * defined in the session. Returns a status object. On success, the status
146 * object will contain a Database object in its value member.
148 * This will return a cached connection if one is available.
150 * @return Status
152 public function getConnection() {
153 if ( $this->db ) {
154 return Status::newGood( $this->db );
157 $status = $this->openConnection();
158 if ( $status->isOK() ) {
159 $this->db = $status->value;
160 // Enable autocommit
161 $this->db->clearFlag( DBO_TRX );
162 $this->db->commit( __METHOD__ );
165 return $status;
169 * Apply a SQL source file to the database as part of running an installation step.
171 * @param string $sourceFileMethod
172 * @param string $stepName
173 * @param bool $archiveTableMustNotExist
174 * @return Status
176 private function stepApplySourceFile(
177 $sourceFileMethod,
178 $stepName,
179 $archiveTableMustNotExist = false
181 $status = $this->getConnection();
182 if ( !$status->isOK() ) {
183 return $status;
185 $this->db->selectDB( $this->getVar( 'wgDBname' ) );
187 if ( $archiveTableMustNotExist && $this->db->tableExists( 'archive', __METHOD__ ) ) {
188 $status->warning( "config-$stepName-tables-exist" );
189 $this->enableLB();
191 return $status;
194 $this->db->setFlag( DBO_DDLMODE ); // For Oracle's handling of schema files
195 $this->db->begin( __METHOD__ );
197 $error = $this->db->sourceFile(
198 call_user_func( [ $this, $sourceFileMethod ], $this->db )
200 if ( $error !== true ) {
201 $this->db->reportQueryError( $error, 0, '', __METHOD__ );
202 $this->db->rollback( __METHOD__ );
203 $status->fatal( "config-$stepName-tables-failed", $error );
204 } else {
205 $this->db->commit( __METHOD__ );
207 // Resume normal operations
208 if ( $status->isOK() ) {
209 $this->enableLB();
212 return $status;
216 * Create database tables from scratch.
218 * @return Status
220 public function createTables() {
221 return $this->stepApplySourceFile( 'getSchemaPath', 'install', true );
225 * Insert update keys into table to prevent running unneded updates.
227 * @return Status
229 public function insertUpdateKeys() {
230 return $this->stepApplySourceFile( 'getUpdateKeysPath', 'updates', false );
234 * Return a path to the DBMS-specific SQL file if it exists,
235 * otherwise default SQL file
237 * @param IDatabase $db
238 * @param string $filename
239 * @return string
241 private function getSqlFilePath( $db, $filename ) {
242 global $IP;
244 $dbmsSpecificFilePath = "$IP/maintenance/" . $db->getType() . "/$filename";
245 if ( file_exists( $dbmsSpecificFilePath ) ) {
246 return $dbmsSpecificFilePath;
247 } else {
248 return "$IP/maintenance/$filename";
253 * Return a path to the DBMS-specific schema file,
254 * otherwise default to tables.sql
256 * @param IDatabase $db
257 * @return string
259 public function getSchemaPath( $db ) {
260 return $this->getSqlFilePath( $db, 'tables.sql' );
264 * Return a path to the DBMS-specific update key file,
265 * otherwise default to update-keys.sql
267 * @param IDatabase $db
268 * @return string
270 public function getUpdateKeysPath( $db ) {
271 return $this->getSqlFilePath( $db, 'update-keys.sql' );
275 * Create the tables for each extension the user enabled
276 * @return Status
278 public function createExtensionTables() {
279 $status = $this->getConnection();
280 if ( !$status->isOK() ) {
281 return $status;
284 // Now run updates to create tables for old extensions
285 DatabaseUpdater::newForDB( $this->db )->doUpdates( [ 'extensions' ] );
287 return $status;
291 * Get the DBMS-specific options for LocalSettings.php generation.
293 * @return string
295 abstract public function getLocalSettings();
298 * Override this to provide DBMS-specific schema variables, to be
299 * substituted into tables.sql and other schema files.
300 * @return array
302 public function getSchemaVars() {
303 return [];
307 * Set appropriate schema variables in the current database connection.
309 * This should be called after any request data has been imported, but before
310 * any write operations to the database.
312 public function setupSchemaVars() {
313 $status = $this->getConnection();
314 if ( $status->isOK() ) {
315 $status->value->setSchemaVars( $this->getSchemaVars() );
316 } else {
317 $msg = __METHOD__ . ': unexpected error while establishing'
318 . ' a database connection with message: '
319 . $status->getMessage()->plain();
320 throw new MWException( $msg );
325 * Set up LBFactory so that wfGetDB() etc. works.
326 * We set up a special LBFactory instance which returns the current
327 * installer connection.
329 public function enableLB() {
330 $status = $this->getConnection();
331 if ( !$status->isOK() ) {
332 throw new MWException( __METHOD__ . ': unexpected DB connection error' );
335 \MediaWiki\MediaWikiServices::resetGlobalInstance();
336 $services = \MediaWiki\MediaWikiServices::getInstance();
338 $connection = $status->value;
339 $services->redefineService( 'DBLoadBalancerFactory', function () use ( $connection ) {
340 return LBFactorySingle::newFromConnection( $connection );
341 } );
345 * Perform database upgrades
347 * @return bool
349 public function doUpgrade() {
350 $this->setupSchemaVars();
351 $this->enableLB();
353 $ret = true;
354 ob_start( [ $this, 'outputHandler' ] );
355 $up = DatabaseUpdater::newForDB( $this->db );
356 try {
357 $up->doUpdates();
358 } catch ( MWException $e ) {
359 echo "\nAn error occurred:\n";
360 echo $e->getText();
361 $ret = false;
362 } catch ( Exception $e ) {
363 echo "\nAn error occurred:\n";
364 echo $e->getMessage();
365 $ret = false;
367 $up->purgeCache();
368 ob_end_flush();
370 return $ret;
374 * Allow DB installers a chance to make last-minute changes before installation
375 * occurs. This happens before setupDatabase() or createTables() is called, but
376 * long after the constructor. Helpful for things like modifying setup steps :)
378 public function preInstall() {
382 * Allow DB installers a chance to make checks before upgrade.
384 public function preUpgrade() {
388 * Get an array of MW configuration globals that will be configured by this class.
389 * @return array
391 public function getGlobalNames() {
392 return $this->globalNames;
396 * Construct and initialise parent.
397 * This is typically only called from Installer::getDBInstaller()
398 * @param WebInstaller $parent
400 public function __construct( $parent ) {
401 $this->parent = $parent;
405 * Convenience function.
406 * Check if a named extension is present.
408 * @param string $name
409 * @return bool
411 protected static function checkExtension( $name ) {
412 return extension_loaded( $name );
416 * Get the internationalised name for this DBMS.
417 * @return string
419 public function getReadableName() {
420 // Messages: config-type-mysql, config-type-postgres, config-type-sqlite,
421 // config-type-oracle
422 return wfMessage( 'config-type-' . $this->getName() )->text();
426 * Get a name=>value map of MW configuration globals for the default values.
427 * @return array
429 public function getGlobalDefaults() {
430 $defaults = [];
431 foreach ( $this->getGlobalNames() as $var ) {
432 if ( isset( $GLOBALS[$var] ) ) {
433 $defaults[$var] = $GLOBALS[$var];
436 return $defaults;
440 * Get a name=>value map of internal variables used during installation.
441 * @return array
443 public function getInternalDefaults() {
444 return $this->internalDefaults;
448 * Get a variable, taking local defaults into account.
449 * @param string $var
450 * @param mixed|null $default
451 * @return mixed
453 public function getVar( $var, $default = null ) {
454 $defaults = $this->getGlobalDefaults();
455 $internal = $this->getInternalDefaults();
456 if ( isset( $defaults[$var] ) ) {
457 $default = $defaults[$var];
458 } elseif ( isset( $internal[$var] ) ) {
459 $default = $internal[$var];
462 return $this->parent->getVar( $var, $default );
466 * Convenience alias for $this->parent->setVar()
467 * @param string $name
468 * @param mixed $value
470 public function setVar( $name, $value ) {
471 $this->parent->setVar( $name, $value );
475 * Get a labelled text box to configure a local variable.
477 * @param string $var
478 * @param string $label
479 * @param array $attribs
480 * @param string $helpData
481 * @return string
483 public function getTextBox( $var, $label, $attribs = [], $helpData = "" ) {
484 $name = $this->getName() . '_' . $var;
485 $value = $this->getVar( $var );
486 if ( !isset( $attribs ) ) {
487 $attribs = [];
490 return $this->parent->getTextBox( [
491 'var' => $var,
492 'label' => $label,
493 'attribs' => $attribs,
494 'controlName' => $name,
495 'value' => $value,
496 'help' => $helpData
497 ] );
501 * Get a labelled password box to configure a local variable.
502 * Implements password hiding.
504 * @param string $var
505 * @param string $label
506 * @param array $attribs
507 * @param string $helpData
508 * @return string
510 public function getPasswordBox( $var, $label, $attribs = [], $helpData = "" ) {
511 $name = $this->getName() . '_' . $var;
512 $value = $this->getVar( $var );
513 if ( !isset( $attribs ) ) {
514 $attribs = [];
517 return $this->parent->getPasswordBox( [
518 'var' => $var,
519 'label' => $label,
520 'attribs' => $attribs,
521 'controlName' => $name,
522 'value' => $value,
523 'help' => $helpData
524 ] );
528 * Get a labelled checkbox to configure a local boolean variable.
530 * @param string $var
531 * @param string $label
532 * @param array $attribs Optional.
533 * @param string $helpData Optional.
534 * @return string
536 public function getCheckBox( $var, $label, $attribs = [], $helpData = "" ) {
537 $name = $this->getName() . '_' . $var;
538 $value = $this->getVar( $var );
540 return $this->parent->getCheckBox( [
541 'var' => $var,
542 'label' => $label,
543 'attribs' => $attribs,
544 'controlName' => $name,
545 'value' => $value,
546 'help' => $helpData
547 ] );
551 * Get a set of labelled radio buttons.
553 * @param array $params Parameters are:
554 * var: The variable to be configured (required)
555 * label: The message name for the label (required)
556 * itemLabelPrefix: The message name prefix for the item labels (required)
557 * values: List of allowed values (required)
558 * itemAttribs Array of attribute arrays, outer key is the value name (optional)
560 * @return string
562 public function getRadioSet( $params ) {
563 $params['controlName'] = $this->getName() . '_' . $params['var'];
564 $params['value'] = $this->getVar( $params['var'] );
566 return $this->parent->getRadioSet( $params );
570 * Convenience function to set variables based on form data.
571 * Assumes that variables containing "password" in the name are (potentially
572 * fake) passwords.
573 * @param array $varNames
574 * @return array
576 public function setVarsFromRequest( $varNames ) {
577 return $this->parent->setVarsFromRequest( $varNames, $this->getName() . '_' );
581 * Determine whether an existing installation of MediaWiki is present in
582 * the configured administrative connection. Returns true if there is
583 * such a wiki, false if the database doesn't exist.
585 * Traditionally, this is done by testing for the existence of either
586 * the revision table or the cur table.
588 * @return bool
590 public function needsUpgrade() {
591 $status = $this->getConnection();
592 if ( !$status->isOK() ) {
593 return false;
596 if ( !$this->db->selectDB( $this->getVar( 'wgDBname' ) ) ) {
597 return false;
600 return $this->db->tableExists( 'cur', __METHOD__ ) ||
601 $this->db->tableExists( 'revision', __METHOD__ );
605 * Get a standard install-user fieldset.
607 * @return string
609 public function getInstallUserBox() {
610 return Html::openElement( 'fieldset' ) .
611 Html::element( 'legend', [], wfMessage( 'config-db-install-account' )->text() ) .
612 $this->getTextBox(
613 '_InstallUser',
614 'config-db-username',
615 [ 'dir' => 'ltr' ],
616 $this->parent->getHelpBox( 'config-db-install-username' )
618 $this->getPasswordBox(
619 '_InstallPassword',
620 'config-db-password',
621 [ 'dir' => 'ltr' ],
622 $this->parent->getHelpBox( 'config-db-install-password' )
624 Html::closeElement( 'fieldset' );
628 * Submit a standard install user fieldset.
629 * @return Status
631 public function submitInstallUserBox() {
632 $this->setVarsFromRequest( [ '_InstallUser', '_InstallPassword' ] );
634 return Status::newGood();
638 * Get a standard web-user fieldset
639 * @param string|bool $noCreateMsg Message to display instead of the creation checkbox.
640 * Set this to false to show a creation checkbox (default).
642 * @return string
644 public function getWebUserBox( $noCreateMsg = false ) {
645 $wrapperStyle = $this->getVar( '_SameAccount' ) ? 'display: none' : '';
646 $s = Html::openElement( 'fieldset' ) .
647 Html::element( 'legend', [], wfMessage( 'config-db-web-account' )->text() ) .
648 $this->getCheckBox(
649 '_SameAccount', 'config-db-web-account-same',
650 [ 'class' => 'hideShowRadio', 'rel' => 'dbOtherAccount' ]
652 Html::openElement( 'div', [ 'id' => 'dbOtherAccount', 'style' => $wrapperStyle ] ) .
653 $this->getTextBox( 'wgDBuser', 'config-db-username' ) .
654 $this->getPasswordBox( 'wgDBpassword', 'config-db-password' ) .
655 $this->parent->getHelpBox( 'config-db-web-help' );
656 if ( $noCreateMsg ) {
657 $s .= $this->parent->getWarningBox( wfMessage( $noCreateMsg )->plain() );
658 } else {
659 $s .= $this->getCheckBox( '_CreateDBAccount', 'config-db-web-create' );
661 $s .= Html::closeElement( 'div' ) . Html::closeElement( 'fieldset' );
663 return $s;
667 * Submit the form from getWebUserBox().
669 * @return Status
671 public function submitWebUserBox() {
672 $this->setVarsFromRequest(
673 [ 'wgDBuser', 'wgDBpassword', '_SameAccount', '_CreateDBAccount' ]
676 if ( $this->getVar( '_SameAccount' ) ) {
677 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
678 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
681 if ( $this->getVar( '_CreateDBAccount' ) && strval( $this->getVar( 'wgDBpassword' ) ) == '' ) {
682 return Status::newFatal( 'config-db-password-empty', $this->getVar( 'wgDBuser' ) );
685 return Status::newGood();
689 * Common function for databases that don't understand the MySQLish syntax of interwiki.sql.
691 * @return Status
693 public function populateInterwikiTable() {
694 $status = $this->getConnection();
695 if ( !$status->isOK() ) {
696 return $status;
698 $this->db->selectDB( $this->getVar( 'wgDBname' ) );
700 if ( $this->db->selectRow( 'interwiki', '*', [], __METHOD__ ) ) {
701 $status->warning( 'config-install-interwiki-exists' );
703 return $status;
705 global $IP;
706 MediaWiki\suppressWarnings();
707 $rows = file( "$IP/maintenance/interwiki.list",
708 FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
709 MediaWiki\restoreWarnings();
710 $interwikis = [];
711 if ( !$rows ) {
712 return Status::newFatal( 'config-install-interwiki-list' );
714 foreach ( $rows as $row ) {
715 $row = preg_replace( '/^\s*([^#]*?)\s*(#.*)?$/', '\\1', $row ); // strip comments - whee
716 if ( $row == "" ) {
717 continue;
719 $row .= "|";
720 $interwikis[] = array_combine(
721 [ 'iw_prefix', 'iw_url', 'iw_local', 'iw_api', 'iw_wikiid' ],
722 explode( '|', $row )
725 $this->db->insert( 'interwiki', $interwikis, __METHOD__ );
727 return Status::newGood();
730 public function outputHandler( $string ) {
731 return htmlspecialchars( $string );