Debian Codegraph @

includes/installer/DatabaseInstaller.php

raw symbols SCIP
1 <?php
2
3 /**
4 * DBMS-specific installation helper.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 * @ingroup Installer
23 */
24
25 namespace MediaWiki\Installer;
26
27 use MediaWiki\Status\Status;
28 use RuntimeException;
29 use Wikimedia\AtEase\AtEase;
30 use Wikimedia\Rdbms\Database;
31 use Wikimedia\Rdbms\DatabaseDomain;
32 use Wikimedia\Rdbms\DBQueryError;
33 use Wikimedia\Rdbms\IDatabase;
34
35 /**
36 * Base class for DBMS-specific installation helper classes.
37 *
38 * @ingroup Installer
39 * @since 1.17
40 */
41 abstract class DatabaseInstaller {
42 /**
43 * A connection for creating DBs, suitable for pre-installation.
44 */
45 public const CONN_CREATE_DATABASE = 'create-database';
46
47 /**
48 * A connection to the new DB, for creating schemas and other similar
49 * objects in the new DB.
50 */
51 public const CONN_CREATE_SCHEMA = 'create-schema';
52
53 /**
54 * A connection with a role suitable for creating tables.
55 */
56 public const CONN_CREATE_TABLES = 'create-tables';
57
58 /**
59 * Legacy default connection type. Before MW 1.43, getConnection() with no
60 * parameters would return the cached connection. The state (especially the
61 * selected domain) would depend on the previously executed install steps.
62 * Using this constant tries to reproduce this behaviour.
63 *
64 * @deprecated since 1.43
65 */
66 public const CONN_DONT_KNOW = 'dont-know';
67
68 /**
69 * The Installer object.
70 *
71 * @var Installer
72 */
73 public $parent;
74
75 /**
76 * @var string Set by subclasses
77 */
78 public static $minimumVersion;
79
80 /**
81 * @var string Set by subclasses
82 */
83 protected static $notMinimumVersionMessage;
84
85 /**
86 * @deprecated since 1.43 -- use definitelyGetConnection()
87 * @var Database
88 */
89 public $db = null;
90
91 /** @var Database|null */
92 private $cachedConn;
93 /** @var string|null */
94 private $cachedConnType;
95
96 /**
97 * Internal variables for installation.
98 *
99 * @var array
100 */
101 protected $internalDefaults = [];
102
103 /**
104 * Array of MW configuration globals this class uses.
105 *
106 * @var array
107 */
108 protected $globalNames = [];
109
110 /**
111 * Whether the provided version meets the necessary requirements for this type
112 *
113 * @param IDatabase $conn
114 * @return Status
115 * @since 1.30
116 */
117 public static function meetsMinimumRequirement( IDatabase $conn ) {
118 $serverVersion = $conn->getServerVersion();
119 if ( version_compare( $serverVersion, static::$minimumVersion ) < 0 ) {
120 return Status::newFatal(
121 static::$notMinimumVersionMessage, static::$minimumVersion, $serverVersion
122 );
123 }
124
125 return Status::newGood();
126 }
127
128 /**
129 * Return the internal name, e.g. 'mysql', or 'sqlite'.
130 */
131 abstract public function getName();
132
133 /**
134 * @return bool Returns true if the client library is compiled in.
135 */
136 abstract public function isCompiled();
137
138 /**
139 * Checks for installation prerequisites other than those checked by isCompiled()
140 * @since 1.19
141 * @return Status
142 */
143 public function checkPrerequisites() {
144 return Status::newGood();
145 }
146
147 /**
148 * Open a connection to the database using the administrative user/password
149 * currently defined in the session, without any caching. Returns a status
150 * object. On success, the status object will contain a Database object in
151 * its value member.
152 *
153 * The database should not be implicitly created.
154 *
155 * @param string $type One of the self::CONN_* constants, except CONN_DONT_KNOW
156 * @return ConnectionStatus
157 */
158 abstract protected function openConnection( string $type );
159
160 /**
161 * Create the database and return a Status object indicating success or
162 * failure.
163 *
164 * @return Status
165 */
166 abstract public function setupDatabase();
167
168 /**
169 * Connect to the database using the administrative user/password currently
170 * defined in the session. Returns a status object. On success, the status
171 * object will contain a Database object in its value member.
172 *
173 * This will return a cached connection if one is available.
174 *
175 * @param string $type One of the self::CONN_* constants. Using CONN_DONT_KNOW
176 * is deprecated and will cause an exception to be thrown in a future release.
177 * @return ConnectionStatus
178 */
179 public function getConnection( $type = self::CONN_DONT_KNOW ) {
180 if ( $type === self::CONN_DONT_KNOW ) {
181 if ( $this->cachedConnType ) {
182 $type = $this->cachedConnType;
183 } else {
184 $type = self::CONN_CREATE_DATABASE;
185 }
186 }
187 if ( $this->cachedConn ) {
188 if ( $this->cachedConnType === $type ) {
189 return new ConnectionStatus( $this->cachedConn );
190 } else {
191 return $this->changeConnType( $this->cachedConn, $this->cachedConnType, $type );
192 }
193 }
194 $status = $this->openConnection( $type );
195 if ( $status->isOK() ) {
196 $this->cachedConn = $status->getDB();
197 $this->cachedConnType = $type;
198 // Assign to $this->db for b/c
199 $this->db = $this->cachedConn;
200
201 if ( $type === self::CONN_CREATE_SCHEMA || $type === self::CONN_CREATE_TABLES ) {
202 $this->cachedConn->setSchemaVars( $this->getSchemaVars() );
203 }
204 }
205
206 return $status;
207 }
208
209 /**
210 * Get a connection and unwrap it from its Status object, throwing an
211 * exception on failure.
212 *
213 * @param string $type
214 * @return Database
215 */
216 public function definitelyGetConnection( string $type ): Database {
217 $status = $this->getConnection( $type );
218 if ( !$status->isOK() ) {
219 throw new RuntimeException( __METHOD__ . ': unexpected DB connection error' );
220 }
221 return $status->getDB();
222 }
223
224 /**
225 * Change the type of a connection.
226 *
227 * CONN_CREATE_DATABASE means the domain is indeterminate and irrelevant,
228 * so converting from this type can be done by selecting the domain, and
229 * converting to it is a no-op.
230 *
231 * CONN_CREATE_SCHEMA means the domain is correct but tables created by
232 * PostgreSQL will have the incorrect role. So to convert from this to
233 * CONN_CREATE_TABLES, we set the role.
234 *
235 * CONN_CREATE_TABLES means a fully-configured connection, suitable for
236 * most tasks, so converting from it is a no-op.
237 *
238 * @param Database $conn
239 * @param string &$storedType One of the self::CONN_* constants. An in/out
240 * parameter, set to the new type on success. It is set to the "real" new
241 * type, reflecting the highest configuration level reached, to avoid
242 * unnecessary selectDomain() calls when we need to temporarily give an
243 * unconfigured connection.
244 * @param string $newType One of the self::CONN_* constants
245 * @return ConnectionStatus
246 */
247 protected function changeConnType( Database $conn, &$storedType, $newType ) {
248 // Change type from database to schema, if requested
249 if ( $storedType === self::CONN_CREATE_DATABASE ) {
250 if ( $newType === self::CONN_CREATE_SCHEMA || $newType === self::CONN_CREATE_TABLES ) {
251 // TODO: catch exceptions from selectDomain and report as a Status
252 $conn->selectDomain( new DatabaseDomain(
253 $this->getVar( 'wgDBname' ),
254 $this->getVar( 'wgDBmwschema' ),
255 $this->getVar( 'wgDBprefix' ) ?? ''
256 ) );
257 $conn->setSchemaVars( $this->getSchemaVars() );
258 $storedType = self::CONN_CREATE_SCHEMA;
259 }
260 }
261 // Change type from schema to tables, if requested
262 if ( $newType === self::CONN_CREATE_TABLES && $storedType === self::CONN_CREATE_SCHEMA ) {
263 $status = $this->changeConnTypeFromSchemaToTables( $conn );
264 if ( $status->isOK() ) {
265 $storedType = self::CONN_CREATE_TABLES;
266 }
267 return $status;
268 }
269 return new ConnectionStatus( $conn );
270 }
271
272 /**
273 * Change the type of a connection from CONN_CREATE_SCHEMA to CONN_CREATE_TABLES.
274 * Postgres overrides this.
275 *
276 * @param Database $conn
277 * @return ConnectionStatus
278 */
279 protected function changeConnTypeFromSchemaToTables( Database $conn ) {
280 return new ConnectionStatus( $conn );
281 }
282
283 /**
284 * Apply a SQL source file to the database as part of running an installation step.
285 *
286 * @param Database $conn
287 * @param string $sqlFile
288 * @return Status
289 */
290 private function applySourceFile( $conn, $sqlFile ) {
291 $status = Status::newGood();
292 try {
293 $conn->doAtomicSection( __METHOD__,
294 static function ( $conn ) use ( $sqlFile ) {
295 $conn->sourceFile( $sqlFile );
296 },
297 IDatabase::ATOMIC_CANCELABLE
298 );
299 } catch ( DBQueryError $e ) {
300 $status->fatal( "config-install-tables-failed", $e->getMessage() );
301 }
302 return $status;
303 }
304
305 /**
306 * Create database tables from scratch from the automatically generated file
307 *
308 * @return Status
309 */
310 public function createTables() {
311 $status = $this->getConnection( self::CONN_CREATE_TABLES );
312 if ( !$status->isOK() ) {
313 return $status;
314 }
315 $conn = $status->getDB();
316 if ( $conn->tableExists( 'archive', __METHOD__ ) ) {
317 $status->warning( "config-install-tables-exist" );
318 return $status;
319 }
320 $status = $this->applySourceFile( $conn,
321 $this->getSqlFilePath( 'tables-generated.sql' ) );
322 if ( !$status->isOK() ) {
323 return $status;
324 }
325 $status->merge( $this->applySourceFile( $conn,
326 $this->getSqlFilePath( 'tables.sql' ) ) );
327 return $status;
328 }
329
330 /**
331 * Insert update keys into table to prevent running unneeded updates.
332 *
333 * @return Status
334 */
335 public function insertUpdateKeys() {
336 $updater = DatabaseUpdater::newForDB(
337 $this->definitelyGetConnection( self::CONN_CREATE_TABLES ) );
338 $updater->insertInitialUpdateKeys();
339 return Status::newGood();
340 }
341
342 /**
343 * Return a path to the DBMS-specific SQL file if it exists,
344 * otherwise default SQL file
345 *
346 * @param string $filename
347 * @return string
348 */
349 private function getSqlFilePath( string $filename ) {
350 global $IP;
351
352 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getName() . "/$filename";
353 if ( file_exists( $dbmsSpecificFilePath ) ) {
354 return $dbmsSpecificFilePath;
355 } else {
356 return "$IP/maintenance/$filename";
357 }
358 }
359
360 /**
361 * Create the tables for each extension the user enabled
362 * @return Status
363 */
364 public function createExtensionTables() {
365 $status = $this->getConnection( self::CONN_CREATE_TABLES );
366 if ( !$status->isOK() ) {
367 return $status;
368 }
369
370 // Now run updates to create tables for old extensions
371 $updater = DatabaseUpdater::newForDB( $status->getDB() );
372 $updater->setAutoExtensionHookContainer( $this->parent->getAutoExtensionHookContainer() );
373 $updater->doUpdates( [ 'extensions' ] );
374
375 return $status;
376 }
377
378 /**
379 * Get the DBMS-specific options for LocalSettings.php generation.
380 *
381 * @return string
382 */
383 abstract public function getLocalSettings();
384
385 /**
386 * Override this to provide DBMS-specific schema variables, to be
387 * substituted into tables.sql and other schema files.
388 * @return array
389 */
390 public function getSchemaVars() {
391 return [];
392 }
393
394 /**
395 * @deprecated since 1.43
396 */
397 public function enableLB() {
398 }
399
400 /**
401 * Allow DB installers a chance to make last-minute changes before installation
402 * occurs. This happens before setupDatabase() or createTables() is called, but
403 * long after the constructor. Helpful for things like modifying setup steps :)
404 */
405 public function preInstall() {
406 }
407
408 /**
409 * Allow DB installers a chance to make checks before upgrade.
410 */
411 public function preUpgrade() {
412 }
413
414 /**
415 * Get an array of MW configuration globals that will be configured by this class.
416 * @return array
417 */
418 public function getGlobalNames() {
419 return $this->globalNames;
420 }
421
422 /**
423 * Construct and initialise parent.
424 * This is typically only called from Installer::getDBInstaller()
425 * @param Installer $parent
426 */
427 public function __construct( $parent ) {
428 $this->parent = $parent;
429 }
430
431 /**
432 * Convenience function.
433 * Check if a named extension is present.
434 *
435 * @param string $name
436 * @return bool
437 */
438 protected static function checkExtension( $name ) {
439 return extension_loaded( $name );
440 }
441
442 /**
443 * Get the internationalised name for this DBMS.
444 * @return string
445 */
446 public function getReadableName() {
447 // Messages: config-type-mysql, config-type-postgres, config-type-sqlite
448 return wfMessage( 'config-type-' . $this->getName() )->text();
449 }
450
451 /**
452 * Get a name=>value map of MW configuration globals for the default values.
453 * @return array
454 * @return-taint none
455 */
456 public function getGlobalDefaults() {
457 $defaults = [];
458 foreach ( $this->getGlobalNames() as $var ) {
459 if ( isset( $GLOBALS[$var] ) ) {
460 $defaults[$var] = $GLOBALS[$var];
461 }
462 }
463 return $defaults;
464 }
465
466 /**
467 * Get a name=>value map of internal variables used during installation.
468 * @return array
469 */
470 public function getInternalDefaults() {
471 return $this->internalDefaults;
472 }
473
474 /**
475 * Get a variable, taking local defaults into account.
476 * @param string $var
477 * @param mixed|null $default
478 * @return mixed
479 */
480 public function getVar( $var, $default = null ) {
481 $defaults = $this->getGlobalDefaults();
482 $internal = $this->getInternalDefaults();
483 if ( isset( $defaults[$var] ) ) {
484 $default = $defaults[$var];
485 } elseif ( isset( $internal[$var] ) ) {
486 $default = $internal[$var];
487 }
488
489 return $this->parent->getVar( $var, $default );
490 }
491
492 /**
493 * Convenience alias for $this->parent->setVar()
494 * @param string $name
495 * @param mixed $value
496 */
497 public function setVar( $name, $value ) {
498 $this->parent->setVar( $name, $value );
499 }
500
501 abstract public function getConnectForm( WebInstaller $webInstaller ): DatabaseConnectForm;
502
503 abstract public function getSettingsForm( WebInstaller $webInstaller ): DatabaseSettingsForm;
504
505 /**
506 * Determine whether an existing installation of MediaWiki is present in
507 * the configured administrative connection. Returns true if there is
508 * such a wiki, false if the database doesn't exist.
509 *
510 * Traditionally, this is done by testing for the existence of either
511 * the revision table or the cur table.
512 *
513 * @return bool
514 */
515 public function needsUpgrade() {
516 $status = $this->getConnection( self::CONN_CREATE_SCHEMA );
517 if ( !$status->isOK() ) {
518 return false;
519 }
520 $db = $status->getDB();
521 return $db->tableExists( 'cur', __METHOD__ ) ||
522 $db->tableExists( 'revision', __METHOD__ );
523 }
524
525 /**
526 * Common function for databases that don't understand the MySQLish syntax of interwiki.list.
527 *
528 * @return Status
529 */
530 public function populateInterwikiTable() {
531 $status = $this->getConnection( self::CONN_CREATE_TABLES );
532 if ( !$status->isOK() ) {
533 return $status;
534 }
535 $conn = $status->getDB();
536
537 $row = $conn->newSelectQueryBuilder()
538 ->select( '1' )
539 ->from( 'interwiki' )
540 ->caller( __METHOD__ )->fetchRow();
541 if ( $row ) {
542 $status->warning( 'config-install-interwiki-exists' );
543
544 return $status;
545 }
546 global $IP;
547 AtEase::suppressWarnings();
548 $rows = file( "$IP/maintenance/interwiki.list",
549 FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
550 AtEase::restoreWarnings();
551 if ( !$rows ) {
552 return Status::newFatal( 'config-install-interwiki-list' );
553 }
554 $insert = $conn->newInsertQueryBuilder()
555 ->insertInto( 'interwiki' );
556 foreach ( $rows as $row ) {
557 $row = preg_replace( '/^\s*([^#]*?)\s*(#.*)?$/', '\\1', $row ); // strip comments - whee
558 if ( $row == "" ) {
559 continue;
560 }
561 $row .= "|";
562 $insert->row(
563 array_combine(
564 [ 'iw_prefix', 'iw_url', 'iw_local', 'iw_api', 'iw_wikiid' ],
565 explode( '|', $row )
566 )
567 );
568 }
569 $insert->caller( __METHOD__ )->execute();
570
571 return Status::newGood();
572 }
573
574 /**
575 * @param Database $conn
576 * @param string $database
577 * @return bool
578 * @since 1.39
579 */
580 protected function selectDatabase( Database $conn, string $database ) {
581 $schema = $conn->dbSchema();
582 $prefix = $conn->tablePrefix();
583
584 $conn->selectDomain( new DatabaseDomain(
585 $database,
586 // DatabaseDomain uses null for unspecified schemas
587 ( $schema !== '' ) ? $schema : null,
588 $prefix
589 ) );
590
591 return true;
592 }
593 }