Debian Codegraph @

includes/installer/DatabaseUpdater.php

raw symbols SCIP
1 <?php
2 /**
3 * DBMS-specific updater helper.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Installer
22 */
23
24 namespace MediaWiki\Installer;
25
26 use AutoLoader;
27 use CleanupEmptyCategories;
28 use DeleteDefaultMessages;
29 use LogicException;
30 use MediaWiki\HookContainer\HookContainer;
31 use MediaWiki\HookContainer\HookRunner;
32 use MediaWiki\HookContainer\StaticHookRegistry;
33 use MediaWiki\MainConfigNames;
34 use MediaWiki\Maintenance\FakeMaintenance;
35 use MediaWiki\Maintenance\Maintenance;
36 use MediaWiki\MediaWikiServices;
37 use MediaWiki\Registration\ExtensionRegistry;
38 use MediaWiki\ResourceLoader\MessageBlobStore;
39 use MediaWiki\SiteStats\SiteStatsInit;
40 use MigrateLinksTable;
41 use RebuildLocalisationCache;
42 use RefreshImageMetadata;
43 use RuntimeException;
44 use UnexpectedValueException;
45 use UpdateCollation;
46 use Wikimedia\Rdbms\IDatabase;
47 use Wikimedia\Rdbms\IMaintainableDatabase;
48 use Wikimedia\Rdbms\Platform\ISQLPlatform;
49
50 require_once __DIR__ . '/../../maintenance/Maintenance.php';
51
52 /**
53 * Class for handling database updates.
54 *
55 * @ingroup Installer
56 * @since 1.17
57 */
58 abstract class DatabaseUpdater {
59 public const REPLICATION_WAIT_TIMEOUT = 300;
60
61 /**
62 * Array of updates to perform on the database
63 *
64 * @var array
65 */
66 protected $updates = [];
67
68 /**
69 * Array of updates that were skipped
70 *
71 * @var array
72 */
73 protected $updatesSkipped = [];
74
75 /**
76 * List of extension-provided database updates
77 * @var array
78 */
79 protected $extensionUpdates = [];
80
81 /**
82 * List of extension-provided database updates on virtual domain dbs
83 * @var array
84 */
85 protected $extensionUpdatesWithVirtualDomains = [];
86
87 /**
88 * Handle to the database subclass
89 *
90 * @var IMaintainableDatabase
91 */
92 protected $db;
93
94 /**
95 * @var Maintenance
96 */
97 protected $maintenance;
98
99 /** @var bool */
100 protected $shared = false;
101
102 /** @var HookContainer|null */
103 protected $autoExtensionHookContainer;
104
105 /**
106 * @var string[] Scripts to run after database update
107 * Should be a subclass of LoggedUpdateMaintenance
108 */
109 protected $postDatabaseUpdateMaintenance = [
110 DeleteDefaultMessages::class,
111 CleanupEmptyCategories::class,
112 ];
113
114 /**
115 * File handle for SQL output.
116 *
117 * @var resource|null
118 */
119 protected $fileHandle = null;
120
121 /**
122 * Flag specifying whether to skip schema (e.g., SQL-only) updates.
123 *
124 * @var bool
125 */
126 protected $skipSchema = false;
127
128 /**
129 * @param IMaintainableDatabase &$db To perform updates on
130 * @param bool $shared Whether to perform updates on shared tables
131 * @param Maintenance|null $maintenance Maintenance object which created us
132 */
133 protected function __construct(
134 IMaintainableDatabase &$db,
135 $shared,
136 ?Maintenance $maintenance = null
137 ) {
138 $this->db = $db;
139 $this->db->setFlag( DBO_DDLMODE );
140 $this->shared = $shared;
141 if ( $maintenance ) {
142 $this->maintenance = $maintenance;
143 $this->fileHandle = $maintenance->fileHandle;
144 } else {
145 $this->maintenance = new FakeMaintenance;
146 }
147 $this->maintenance->setDB( $db );
148 }
149
150 /**
151 * Cause extensions to register any updates they need to perform.
152 */
153 private function loadExtensionSchemaUpdates() {
154 $hookContainer = $this->loadExtensions();
155 ( new HookRunner( $hookContainer ) )->onLoadExtensionSchemaUpdates( $this );
156 }
157
158 /**
159 * Loads LocalSettings.php, if needed, and initialises everything needed for
160 * LoadExtensionSchemaUpdates hook.
161 *
162 * @return HookContainer
163 */
164 private function loadExtensions() {
165 if ( $this->autoExtensionHookContainer ) {
166 // Already injected by installer
167 return $this->autoExtensionHookContainer;
168 }
169 if ( defined( 'MW_EXTENSIONS_LOADED' ) ) {
170 throw new LogicException( __METHOD__ .
171 ' apparently called from installer but no hook container was injected' );
172 }
173 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
174 // Running under update.php: use the global locator
175 return MediaWikiServices::getInstance()->getHookContainer();
176 }
177 $vars = Installer::getExistingLocalSettings();
178
179 $registry = ExtensionRegistry::getInstance();
180 $queue = $registry->getQueue();
181 // Don't accidentally load extensions in the future
182 $registry->clearQueue();
183
184 // Read extension.json files
185 $extInfo = $registry->readFromQueue( $queue );
186
187 // Merge extension attribute hooks with hooks defined by a .php
188 // registration file included from LocalSettings.php
189 $legacySchemaHooks = $extInfo['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ?? [];
190 if ( $vars && isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
191 $legacySchemaHooks = array_merge( $legacySchemaHooks, $vars['wgHooks']['LoadExtensionSchemaUpdates'] );
192 }
193
194 // Register classes defined by extensions that are loaded by including of a file that
195 // updates global variables, rather than having an extension.json manifest.
196 if ( $vars && isset( $vars['wgAutoloadClasses'] ) ) {
197 AutoLoader::registerClasses( $vars['wgAutoloadClasses'] );
198 }
199
200 // Register class definitions from extension.json files
201 if ( !isset( $extInfo['autoloaderPaths'] )
202 || !isset( $extInfo['autoloaderClasses'] )
203 || !isset( $extInfo['autoloaderNS'] )
204 ) {
205 // NOTE: protect against changes to the structure of $extInfo.
206 // It's volatile, and this usage is easy to miss.
207 throw new LogicException( 'Missing autoloader keys from extracted extension info' );
208 }
209 AutoLoader::loadFiles( $extInfo['autoloaderPaths'] );
210 AutoLoader::registerClasses( $extInfo['autoloaderClasses'] );
211 AutoLoader::registerNamespaces( $extInfo['autoloaderNS'] );
212
213 return new HookContainer(
214 new StaticHookRegistry(
215 [ 'LoadExtensionSchemaUpdates' => $legacySchemaHooks ],
216 $extInfo['attributes']['Hooks'] ?? [],
217 $extInfo['attributes']['DeprecatedHooks'] ?? []
218 ),
219 MediaWikiServices::getInstance()->getObjectFactory()
220 );
221 }
222
223 /**
224 * @param IMaintainableDatabase $db
225 * @param bool $shared
226 * @param Maintenance|null $maintenance
227 * @return DatabaseUpdater
228 */
229 public static function newForDB(
230 IMaintainableDatabase $db,
231 $shared = false,
232 ?Maintenance $maintenance = null
233 ) {
234 $type = $db->getType();
235 if ( in_array( $type, Installer::getDBTypes() ) ) {
236 $class = '\\MediaWiki\\Installer\\' . ucfirst( $type ) . 'Updater';
237
238 return new $class( $db, $shared, $maintenance );
239 }
240
241 throw new UnexpectedValueException( __METHOD__ . ' called for unsupported DB type' );
242 }
243
244 /**
245 * Set the HookContainer to use for loading extension schema updates.
246 *
247 * @internal For use by DatabaseInstaller
248 * @since 1.36
249 * @param HookContainer $hookContainer
250 */
251 public function setAutoExtensionHookContainer( HookContainer $hookContainer ) {
252 $this->autoExtensionHookContainer = $hookContainer;
253 }
254
255 /**
256 * Get a database connection to run updates
257 *
258 * @return IMaintainableDatabase
259 */
260 public function getDB() {
261 return $this->db;
262 }
263
264 /**
265 * Output some text. If we're running via the web, escape the text first.
266 *
267 * @param string $str Text to output
268 * @param-taint $str escapes_html
269 */
270 public function output( $str ) {
271 if ( $this->maintenance->isQuiet() ) {
272 return;
273 }
274 if ( MW_ENTRY_POINT !== 'cli' ) {
275 $str = htmlspecialchars( $str );
276 }
277 echo $str;
278 flush();
279 }
280
281 /**
282 * Add a new update coming from an extension.
283 * Intended for use in LoadExtensionSchemaUpdates hook handlers.
284 *
285 * @since 1.17
286 *
287 * @param array $update The update to run. Format is [ $callback, $params... ]
288 * $callback is the method to call; either a DatabaseUpdater method name or a callable.
289 * Must be serializable (i.e., no anonymous functions allowed). The rest of the parameters
290 * (if any) will be passed to the callback. The first parameter passed to the callback
291 * is always this object.
292 */
293 public function addExtensionUpdate( array $update ) {
294 $this->extensionUpdates[] = $update;
295 }
296
297 /**
298 * Add a new update coming from an extension on virtual domain databases.
299 * Intended for use in LoadExtensionSchemaUpdates hook handlers.
300 *
301 * @since 1.42
302 *
303 * @param array $update The update to run. The format is [ $virtualDomain, $callback, $params... ]
304 * similarly to addExtensionUpdate()
305 */
306 public function addExtensionUpdateOnVirtualDomain( array $update ) {
307 $this->extensionUpdatesWithVirtualDomains[] = $update;
308 }
309
310 /**
311 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
312 * is the most common usage of updaters in an extension)
313 * Intended for use in LoadExtensionSchemaUpdates hook handlers.
314 *
315 * @since 1.18
316 *
317 * @param string $tableName Name of table to create
318 * @param string $sqlPath Full path to the schema file
319 */
320 public function addExtensionTable( $tableName, $sqlPath ) {
321 $this->extensionUpdates[] = [ 'addTable', $tableName, $sqlPath, true ];
322 }
323
324 /**
325 * Add an index to an existing extension table.
326 * Intended for use in LoadExtensionSchemaUpdates hook handlers.
327 *
328 * @since 1.19
329 *
330 * @param string $tableName
331 * @param string $indexName
332 * @param string $sqlPath
333 */
334 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
335 $this->extensionUpdates[] = [ 'addIndex', $tableName, $indexName, $sqlPath, true ];
336 }
337
338 /**
339 * Add a field to an existing extension table.
340 * Intended for use in LoadExtensionSchemaUpdates hook handlers.
341 *
342 * @since 1.19
343 *
344 * @param string $tableName
345 * @param string $columnName
346 * @param string $sqlPath
347 */
348 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
349 $this->extensionUpdates[] = [ 'addField', $tableName, $columnName, $sqlPath, true ];
350 }
351
352 /**
353 * Drop a field from an extension table.
354 * Intended for use in LoadExtensionSchemaUpdates hook handlers.
355 *
356 * @since 1.20
357 *
358 * @param string $tableName
359 * @param string $columnName
360 * @param string $sqlPath
361 */
362 public function dropExtensionField( $tableName, $columnName, $sqlPath ) {
363 $this->extensionUpdates[] = [ 'dropField', $tableName, $columnName, $sqlPath, true ];
364 }
365
366 /**
367 * Drop an index from an extension table
368 * Intended for use in LoadExtensionSchemaUpdates hook handlers.
369 *
370 * @since 1.21
371 *
372 * @param string $tableName
373 * @param string $indexName
374 * @param string $sqlPath The path to the SQL change path
375 */
376 public function dropExtensionIndex( $tableName, $indexName, $sqlPath ) {
377 $this->extensionUpdates[] = [ 'dropIndex', $tableName, $indexName, $sqlPath, true ];
378 }
379
380 /**
381 * Drop an extension table.
382 * Intended for use in LoadExtensionSchemaUpdates hook handlers.
383 *
384 * @since 1.20
385 *
386 * @param string $tableName
387 * @param string|bool $sqlPath
388 */
389 public function dropExtensionTable( $tableName, $sqlPath = false ) {
390 $this->extensionUpdates[] = [ 'dropTable', $tableName, $sqlPath, true ];
391 }
392
393 /**
394 * Rename an index on an extension table
395 * Intended for use in LoadExtensionSchemaUpdates hook handlers.
396 *
397 * @since 1.21
398 *
399 * @param string $tableName
400 * @param string $oldIndexName
401 * @param string $newIndexName
402 * @param string $sqlPath The path to the SQL change file
403 * @param bool $skipBothIndexExistWarning Whether to warn if both the old
404 * and the new indexes exist. [facultative; by default, false]
405 */
406 public function renameExtensionIndex( $tableName, $oldIndexName, $newIndexName,
407 $sqlPath, $skipBothIndexExistWarning = false
408 ) {
409 $this->extensionUpdates[] = [
410 'renameIndex',
411 $tableName,
412 $oldIndexName,
413 $newIndexName,
414 $skipBothIndexExistWarning,
415 $sqlPath,
416 true
417 ];
418 }
419
420 /**
421 * Modify an existing field in an extension table.
422 * Intended for use in LoadExtensionSchemaUpdates hook handlers.
423 *
424 * @since 1.21
425 *
426 * @param string $tableName
427 * @param string $fieldName The field to be modified
428 * @param string $sqlPath The path to the SQL patch
429 */
430 public function modifyExtensionField( $tableName, $fieldName, $sqlPath ) {
431 $this->extensionUpdates[] = [ 'modifyField', $tableName, $fieldName, $sqlPath, true ];
432 }
433
434 /**
435 * Modify an existing extension table.
436 * Intended for use in LoadExtensionSchemaUpdates hook handlers.
437 *
438 * @since 1.31
439 *
440 * @param string $tableName
441 * @param string $sqlPath The path to the SQL patch
442 */
443 public function modifyExtensionTable( $tableName, $sqlPath ) {
444 $this->extensionUpdates[] = [ 'modifyTable', $tableName, $sqlPath, true ];
445 }
446
447 /**
448 * @since 1.20
449 *
450 * @param string $tableName
451 * @return bool
452 */
453 public function tableExists( $tableName ) {
454 return ( $this->db->tableExists( $tableName, __METHOD__ ) );
455 }
456
457 /**
458 * @since 1.40
459 *
460 * @param string $tableName
461 * @param string $fieldName
462 * @return bool
463 */
464 public function fieldExists( $tableName, $fieldName ) {
465 return ( $this->db->fieldExists( $tableName, $fieldName, __METHOD__ ) );
466 }
467
468 /**
469 * Add a maintenance script to be run after the database updates are complete.
470 *
471 * Script should subclass LoggedUpdateMaintenance
472 *
473 * @since 1.19
474 *
475 * @param string $class Name of a Maintenance subclass
476 */
477 public function addPostDatabaseUpdateMaintenance( $class ) {
478 $this->postDatabaseUpdateMaintenance[] = $class;
479 }
480
481 /**
482 * Get the list of extension-defined updates
483 *
484 * @return array
485 */
486 protected function getExtensionUpdates() {
487 return $this->extensionUpdates;
488 }
489
490 /**
491 * @since 1.17
492 *
493 * @return string[]
494 */
495 public function getPostDatabaseUpdateMaintenance() {
496 return $this->postDatabaseUpdateMaintenance;
497 }
498
499 /**
500 * @since 1.21
501 *
502 * Writes the schema updates desired to a file for the DB Admin to run.
503 */
504 private function writeSchemaUpdateFile() {
505 $updates = $this->updatesSkipped;
506 $this->updatesSkipped = [];
507
508 foreach ( $updates as [ $func, $args, $origParams ] ) {
509 // @phan-suppress-next-line PhanUndeclaredInvokeInCallable
510 $func( ...$args );
511 flush();
512 $this->updatesSkipped[] = $origParams;
513 }
514 }
515
516 /**
517 * Get appropriate schema variables in the current database connection.
518 *
519 * This should be called after any request data has been imported, but before
520 * any write operations to the database. The result should be passed to the DB
521 * setSchemaVars() method.
522 *
523 * @return array
524 * @since 1.28
525 */
526 public function getSchemaVars() {
527 return []; // DB-type specific
528 }
529
530 /**
531 * Do all the updates
532 *
533 * @param array $what What updates to perform
534 */
535 public function doUpdates( array $what = [ 'core', 'extensions', 'stats' ] ) {
536 $this->db->setSchemaVars( $this->getSchemaVars() );
537
538 $what = array_fill_keys( $what, true );
539 $this->skipSchema = isset( $what['noschema'] ) || $this->fileHandle !== null;
540
541 if ( isset( $what['initial'] ) ) {
542 $this->output( 'Inserting initial update keys...' );
543 $this->insertInitialUpdateKeys();
544 $this->output( "done.\n" );
545 }
546 if ( isset( $what['core'] ) ) {
547 $this->doCollationUpdate();
548 $this->runUpdates( $this->getCoreUpdateList(), false );
549 }
550 if ( isset( $what['extensions'] ) ) {
551 $this->loadExtensionSchemaUpdates();
552 $this->runUpdates( $this->getExtensionUpdates(), true );
553 $this->runUpdates( $this->extensionUpdatesWithVirtualDomains, true, true );
554 }
555
556 if ( isset( $what['stats'] ) ) {
557 $this->checkStats();
558 }
559
560 if ( $this->fileHandle ) {
561 $this->skipSchema = false;
562 $this->writeSchemaUpdateFile();
563 }
564 }
565
566 /**
567 * Helper function for doUpdates()
568 *
569 * @param array $updates Array of updates to run
570 * @param bool $passSelf Whether to pass this object when calling external functions
571 * @param bool $hasVirtualDomain Whether the updates' array include virtual domains
572 */
573 private function runUpdates( array $updates, $passSelf, $hasVirtualDomain = false ) {
574 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
575 $updatesDone = [];
576 $updatesSkipped = [];
577 foreach ( $updates as $params ) {
578 $origParams = $params;
579 $oldDb = null;
580 $virtualDomain = null;
581 if ( $hasVirtualDomain === true ) {
582 $virtualDomain = array_shift( $params );
583 $oldDb = $this->db;
584 $virtualDb = $lbFactory->getPrimaryDatabase( $virtualDomain );
585 '@phan-var IMaintainableDatabase $virtualDb';
586 $this->maintenance->setDB( $virtualDb );
587 $this->db = $virtualDb;
588 }
589 $func = array_shift( $params );
590 if ( !is_array( $func ) && method_exists( $this, $func ) ) {
591 $func = [ $this, $func ];
592 } elseif ( $passSelf ) {
593 array_unshift( $params, $this );
594 }
595 $ret = $func( ...$params );
596 if ( $hasVirtualDomain === true && $oldDb ) {
597 $this->db = $oldDb;
598 $this->maintenance->setDB( $oldDb );
599 }
600
601 flush();
602 if ( $ret !== false ) {
603 $updatesDone[] = $origParams;
604 $lbFactory->waitForReplication( [ 'timeout' => self::REPLICATION_WAIT_TIMEOUT ] );
605 } else {
606 if ( $hasVirtualDomain === true ) {
607 $params = $origParams;
608 $func = array_shift( $params );
609 }
610 $updatesSkipped[] = [ $func, $params, $origParams ];
611 }
612 }
613 $this->updatesSkipped = array_merge( $this->updatesSkipped, $updatesSkipped );
614 $this->updates = array_merge( $this->updates, $updatesDone );
615 }
616
617 /**
618 * Helper function: check if the given key is present in the updatelog table.
619 *
620 * @param string $key Name of the key to check for
621 * @return bool
622 */
623 public function updateRowExists( $key ) {
624 // Return false if the updatelog table does not exist. This can occur if performing schema changes for tables
625 // that are on a virtual database domain.
626 if ( !$this->db->tableExists( 'updatelog', __METHOD__ ) ) {
627 return false;
628 }
629
630 $row = $this->db->newSelectQueryBuilder()
631 ->select( '1 AS X' ) // T67813
632 ->from( 'updatelog' )
633 ->where( [ 'ul_key' => $key ] )
634 ->caller( __METHOD__ )->fetchRow();
635
636 return (bool)$row;
637 }
638
639 /**
640 * Helper function: Add a key to the updatelog table
641 *
642 * @note Extensions must only use this from within callbacks registered with
643 * addExtensionUpdate(). In particular, this method must not be called directly
644 * from a LoadExtensionSchemaUpdates handler.
645 *
646 * @param string $key Name of the key to insert
647 * @param string|null $val [optional] Value to insert along with the key
648 */
649 public function insertUpdateRow( $key, $val = null ) {
650 // We cannot insert anything to the updatelog table if it does not exist. This can occur for schema changes
651 // on tables that are on a virtual database domain.
652 if ( !$this->db->tableExists( 'updatelog', __METHOD__ ) ) {
653 return;
654 }
655
656 $this->db->clearFlag( DBO_DDLMODE );
657 $values = [ 'ul_key' => $key ];
658 if ( $val ) {
659 $values['ul_value'] = $val;
660 }
661 $this->db->newInsertQueryBuilder()
662 ->insertInto( 'updatelog' )
663 ->ignore()
664 ->row( $values )
665 ->caller( __METHOD__ )->execute();
666 $this->db->setFlag( DBO_DDLMODE );
667 }
668
669 /**
670 * Add initial keys to the updatelog table. Should be called during installation.
671 */
672 public function insertInitialUpdateKeys() {
673 $this->db->clearFlag( DBO_DDLMODE );
674 $iqb = $this->db->newInsertQueryBuilder()
675 ->insertInto( 'updatelog' )
676 ->ignore()
677 ->caller( __METHOD__ );
678 foreach ( $this->getInitialUpdateKeys() as $key ) {
679 $iqb->row( [ 'ul_key' => $key ] );
680 }
681 $iqb->execute();
682 $this->db->setFlag( DBO_DDLMODE );
683 }
684
685 /**
686 * Returns whether updates should be executed on the database table $name.
687 * Updates will be prevented if the table is a shared table, and it is not
688 * specified to run updates on shared tables.
689 *
690 * @param string $name Table name
691 * @return bool
692 */
693 protected function doTable( $name ) {
694 global $wgSharedDB, $wgSharedTables;
695
696 // Don't bother to check $wgSharedTables if there isn't a shared database
697 // or the user actually also wants to do updates on the shared database.
698 if ( $wgSharedDB === null || $this->shared ) {
699 return true;
700 }
701
702 if ( in_array( $name, $wgSharedTables ) ) {
703 $this->output( "...skipping update to shared table $name.\n" );
704 return false;
705 }
706
707 return true;
708 }
709
710 /**
711 * Get an array of updates to perform on the database. Should return a
712 * multidimensional array. The main key is the MediaWiki version (1.12,
713 * 1.13...) with the values being arrays of updates.
714 *
715 * @return array[]
716 */
717 abstract protected function getCoreUpdateList();
718
719 /**
720 * Get an array of update keys to insert into the updatelog table after a
721 * new installation. The named operations will then be skipped by a
722 * subsequent update.
723 *
724 * Add keys here to skip updates that are redundant or harmful on a new
725 * installation, for example reducing field sizes, adding constraints, etc.
726 *
727 * @return string[]
728 */
729 abstract protected function getInitialUpdateKeys();
730
731 /**
732 * Append an SQL fragment to the open file handle.
733 *
734 * @note protected since 1.35
735 *
736 * @param string $filename File name to open
737 */
738 protected function copyFile( $filename ) {
739 $this->db->sourceFile(
740 $filename,
741 null,
742 null,
743 __METHOD__,
744 function ( $line ) {
745 return $this->appendLine( $line );
746 }
747 );
748 }
749
750 /**
751 * Append a line to the open file handle. The line is assumed to
752 * be a complete SQL statement.
753 *
754 * This is used as a callback for sourceLine().
755 *
756 * @note protected since 1.35
757 *
758 * @param string $line Text to append to the file
759 * @return bool False to skip actually executing the file
760 */
761 protected function appendLine( $line ) {
762 $line = rtrim( $line ) . ";\n";
763 if ( fwrite( $this->fileHandle, $line ) === false ) {
764 throw new RuntimeException( "trouble writing file" );
765 }
766
767 return false;
768 }
769
770 /**
771 * Applies a SQL patch
772 *
773 * @note Do not use this in a LoadExtensionSchemaUpdates handler,
774 * use addExtensionUpdate instead!
775 *
776 * @param string $path Path to the patch file
777 * @param bool $isFullPath Whether to treat $path as a relative or not
778 * @param string|null $msg Description of the patch
779 * @return bool False if the patch was skipped.
780 */
781 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
782 $msg ??= "Applying $path patch";
783 if ( $this->skipSchema ) {
784 $this->output( "...skipping schema change ($msg).\n" );
785
786 return false;
787 }
788
789 $this->output( "{$msg}..." );
790
791 if ( !$isFullPath ) {
792 $path = $this->patchPath( $this->db, $path );
793 }
794 if ( $this->fileHandle !== null ) {
795 $this->copyFile( $path );
796 } else {
797 $this->db->sourceFile( $path );
798 }
799 $this->output( "done.\n" );
800
801 return true;
802 }
803
804 /**
805 * Get the full path of a patch file. Keep in mind this always returns a patch, as
806 * it fails back to MySQL if no DB-specific patch can be found
807 *
808 * @param IDatabase $db
809 * @param string $patch The name of the patch, like patch-something.sql
810 * @return string Full path to patch file
811 */
812 public function patchPath( IDatabase $db, $patch ) {
813 $baseDir = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::BaseDirectory );
814
815 $dbType = $db->getType();
816 if ( file_exists( "$baseDir/maintenance/$dbType/archives/$patch" ) ) {
817 return "$baseDir/maintenance/$dbType/archives/$patch";
818 }
819
820 return "$baseDir/maintenance/archives/$patch";
821 }
822
823 /**
824 * Add a new table to the database
825 *
826 * @note Code in a LoadExtensionSchemaUpdates handler should
827 * use addExtensionTable instead!
828 *
829 * @param string $name Name of the new table
830 * @param string $patch Path to the patch file
831 * @param bool $fullpath Whether to treat $patch path as a relative or not
832 * @return bool False if this was skipped because schema changes are skipped
833 */
834 protected function addTable( $name, $patch, $fullpath = false ) {
835 if ( !$this->doTable( $name ) ) {
836 return true;
837 }
838
839 if ( $this->db->tableExists( $name, __METHOD__ ) ) {
840 $this->output( "...$name table already exists.\n" );
841 return true;
842 }
843
844 return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
845 }
846
847 /**
848 * Add a new field to an existing table
849 *
850 * @note Code in a LoadExtensionSchemaUpdates handler should
851 * use addExtensionField instead!
852 *
853 * @param string $table Name of the table to modify
854 * @param string $field Name of the new field
855 * @param string $patch Path to the patch file
856 * @param bool $fullpath Whether to treat $patch path as a relative or not
857 * @return bool False if this was skipped because schema changes are skipped
858 */
859 protected function addField( $table, $field, $patch, $fullpath = false ) {
860 if ( !$this->doTable( $table ) ) {
861 return true;
862 }
863
864 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
865 $this->output( "...$table table does not exist, skipping new field patch.\n" );
866 } elseif ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
867 $this->output( "...have $field field in $table table.\n" );
868 } else {
869 return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
870 }
871
872 return true;
873 }
874
875 /**
876 * Add a new index to an existing table
877 *
878 * @note Code in a LoadExtensionSchemaUpdates handler should
879 * use addExtensionIndex instead!
880 *
881 * @param string $table Name of the table to modify
882 * @param string $index Name of the new index
883 * @param string $patch Path to the patch file
884 * @param bool $fullpath Whether to treat $patch path as a relative or not
885 * @return bool False if this was skipped because schema changes are skipped
886 */
887 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
888 if ( !$this->doTable( $table ) ) {
889 return true;
890 }
891
892 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
893 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
894 } elseif ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
895 $this->output( "...index $index already set on $table table.\n" );
896 } else {
897 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
898 }
899
900 return true;
901 }
902
903 /**
904 * Drop a field from an existing table
905 *
906 * @note Code in a LoadExtensionSchemaUpdates handler should
907 * use dropExtensionField instead!
908 *
909 * @param string $table Name of the table to modify
910 * @param string $field Name of the old field
911 * @param string $patch Path to the patch file
912 * @param bool $fullpath Whether to treat $patch path as a relative or not
913 * @return bool False if this was skipped because schema changes are skipped
914 */
915 protected function dropField( $table, $field, $patch, $fullpath = false ) {
916 if ( !$this->doTable( $table ) ) {
917 return true;
918 }
919
920 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
921 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
922
923 return true;
924 }
925
926 if ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
927 return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
928 }
929
930 $this->output( "...$table table does not contain $field field.\n" );
931 return true;
932 }
933
934 /**
935 * Drop an index from an existing table
936 *
937 * @note Code in a LoadExtensionSchemaUpdates handler should
938 * use dropExtensionIndex instead!
939 *
940 * @param string $table Name of the table to modify
941 * @param string $index Name of the index
942 * @param string $patch Path to the patch file
943 * @param bool $fullpath Whether to treat $patch path as a relative or not
944 * @return bool False if this was skipped because schema changes are skipped
945 */
946 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
947 if ( !$this->doTable( $table ) ) {
948 return true;
949 }
950
951 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
952 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
953
954 return true;
955 }
956
957 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
958 return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
959 }
960
961 $this->output( "...$index key doesn't exist.\n" );
962 return true;
963 }
964
965 /**
966 * Rename an index from an existing table
967 *
968 * @note Code in a LoadExtensionSchemaUpdates handler should
969 * use renameExtensionIndex instead!
970 *
971 * @param string $table Name of the table to modify
972 * @param string $oldIndex Old name of the index
973 * @param string $newIndex New name of the index
974 * @param bool $skipBothIndexExistWarning Whether to warn if both the old and new indexes exist.
975 * @param string $patch Path to the patch file
976 * @param bool $fullpath Whether to treat $patch path as a relative or not
977 * @return bool False if this was skipped because schema changes are skipped
978 */
979 protected function renameIndex( $table, $oldIndex, $newIndex,
980 $skipBothIndexExistWarning, $patch, $fullpath = false
981 ) {
982 if ( !$this->doTable( $table ) ) {
983 return true;
984 }
985
986 // First requirement: the table must exist
987 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
988 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
989
990 return true;
991 }
992
993 // Second requirement: the new index must be missing
994 if ( $this->db->indexExists( $table, $newIndex, __METHOD__ ) ) {
995 $this->output( "...index $newIndex already set on $table table.\n" );
996 if ( !$skipBothIndexExistWarning &&
997 $this->db->indexExists( $table, $oldIndex, __METHOD__ )
998 ) {
999 $this->output( "...WARNING: $oldIndex still exists, despite it has " .
1000 "been renamed into $newIndex (which also exists).\n" .
1001 " $oldIndex should be manually removed if not needed anymore.\n" );
1002 }
1003
1004 return true;
1005 }
1006
1007 // Third requirement: the old index must exist
1008 if ( !$this->db->indexExists( $table, $oldIndex, __METHOD__ ) ) {
1009 $this->output( "...skipping: index $oldIndex doesn't exist.\n" );
1010
1011 return true;
1012 }
1013
1014 // Requirements have been satisfied, the patch can be applied
1015 return $this->applyPatch(
1016 $patch,
1017 $fullpath,
1018 "Renaming index $oldIndex into $newIndex to table $table"
1019 );
1020 }
1021
1022 /**
1023 * If the specified table exists, drop it, or execute the
1024 * patch if one is provided.
1025 *
1026 * @note Code in a LoadExtensionSchemaUpdates handler should
1027 * use dropExtensionTable instead!
1028 *
1029 * @note protected since 1.35
1030 *
1031 * @param string $table Table to drop.
1032 * @param string|false $patch String of patch file that will drop the table. Default: false.
1033 * @param bool $fullpath Whether $patch is a full path. Default: false.
1034 * @return bool False if this was skipped because schema changes are skipped
1035 */
1036 protected function dropTable( $table, $patch = false, $fullpath = false ) {
1037 if ( !$this->doTable( $table ) ) {
1038 return true;
1039 }
1040
1041 if ( $this->db->tableExists( $table, __METHOD__ ) ) {
1042 $msg = "Dropping table $table";
1043
1044 if ( $patch === false ) {
1045 $this->output( "$msg ..." );
1046 $this->db->dropTable( $table, __METHOD__ );
1047 $this->output( "done.\n" );
1048 } else {
1049 return $this->applyPatch( $patch, $fullpath, $msg );
1050 }
1051 } else {
1052 $this->output( "...$table doesn't exist.\n" );
1053 }
1054
1055 return true;
1056 }
1057
1058 /**
1059 * Modify an existing field
1060 *
1061 * @note Code in a LoadExtensionSchemaUpdates handler should
1062 * use modifyExtensionField instead!
1063 *
1064 * @note protected since 1.35
1065 *
1066 * @param string $table Name of the table to which the field belongs
1067 * @param string $field Name of the field to modify
1068 * @param string $patch Path to the patch file
1069 * @param bool $fullpath Whether to treat $patch path as a relative or not
1070 * @return bool False if this was skipped because schema changes are skipped
1071 */
1072 protected function modifyField( $table, $field, $patch, $fullpath = false ) {
1073 if ( !$this->doTable( $table ) ) {
1074 return true;
1075 }
1076
1077 $updateKey = "$table-$field-$patch";
1078 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
1079 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
1080 } elseif ( !$this->db->fieldExists( $table, $field, __METHOD__ ) ) {
1081 $this->output( "...$field field does not exist in $table table, " .
1082 "skipping modify field patch.\n" );
1083 } elseif ( $this->updateRowExists( $updateKey ) ) {
1084 $this->output( "...$field in table $table already modified by patch $patch.\n" );
1085 } else {
1086 $apply = $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
1087 if ( $apply ) {
1088 $this->insertUpdateRow( $updateKey );
1089 }
1090 return $apply;
1091 }
1092 return true;
1093 }
1094
1095 /**
1096 * Modify an existing table, similar to modifyField. Intended for changes that
1097 * touch more than one column on a table.
1098 *
1099 * @note Code in a LoadExtensionSchemaUpdates handler should
1100 * use modifyExtensionTable instead!
1101 *
1102 * @note protected since 1.35
1103 *
1104 * @param string $table Name of the table to modify
1105 * @param string $patch Name of the patch file to apply
1106 * @param string|bool $fullpath Whether to treat $patch path as relative or not, defaults to false
1107 * @return bool False if this was skipped because of schema changes being skipped
1108 */
1109 protected function modifyTable( $table, $patch, $fullpath = false ) {
1110 if ( !$this->doTable( $table ) ) {
1111 return true;
1112 }
1113
1114 $updateKey = "$table-$patch";
1115 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
1116 $this->output( "...$table table does not exist, skipping modify table patch.\n" );
1117 } elseif ( $this->updateRowExists( $updateKey ) ) {
1118 $this->output( "...table $table already modified by patch $patch.\n" );
1119 } else {
1120 $apply = $this->applyPatch( $patch, $fullpath, "Modifying table $table" );
1121 if ( $apply ) {
1122 $this->insertUpdateRow( $updateKey );
1123 }
1124 return $apply;
1125 }
1126 return true;
1127 }
1128
1129 /**
1130 * Run a maintenance script
1131 *
1132 * This should only be used when the maintenance script must run before
1133 * later updates. If later updates don't depend on the script, add it to
1134 * DatabaseUpdater::$postDatabaseUpdateMaintenance instead.
1135 *
1136 * The script's execute() method must return true to indicate successful
1137 * completion, and must return false (or throw an exception) to indicate
1138 * unsuccessful completion.
1139 *
1140 * @note Code in a LoadExtensionSchemaUpdates handler should
1141 * use addExtensionUpdate instead!
1142 *
1143 * @note protected since 1.35
1144 *
1145 * @since 1.32
1146 * @param string $class Maintenance subclass
1147 * @param string $unused Unused, kept for compatibility
1148 */
1149 protected function runMaintenance( $class, $unused = '' ) {
1150 $this->output( "Running $class...\n" );
1151 $task = $this->maintenance->runChild( $class );
1152 $ok = $task->execute();
1153 if ( !$ok ) {
1154 throw new RuntimeException( "Execution of $class did not complete successfully." );
1155 }
1156 $this->output( "done.\n" );
1157 }
1158
1159 /**
1160 * Set any .htaccess files or equivalent for storage repos
1161 *
1162 * Some zones (e.g. "temp") used to be public and may have been initialized as such
1163 */
1164 public function setFileAccess() {
1165 $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
1166 $zonePath = $repo->getZonePath( 'temp' );
1167 if ( $repo->getBackend()->directoryExists( [ 'dir' => $zonePath ] ) ) {
1168 // If the directory was never made, then it will have the right ACLs when it is made
1169 $status = $repo->getBackend()->secure( [
1170 'dir' => $zonePath,
1171 'noAccess' => true,
1172 'noListing' => true
1173 ] );
1174 if ( $status->isOK() ) {
1175 $this->output( "Set the local repo temp zone container to be private.\n" );
1176 } else {
1177 $this->output( "Failed to set the local repo temp zone container to be private.\n" );
1178 }
1179 }
1180 }
1181
1182 /**
1183 * Purge various database caches
1184 */
1185 public function purgeCache() {
1186 global $wgLocalisationCacheConf;
1187 // We can't guarantee that the user will be able to use TRUNCATE,
1188 // but we know that DELETE is available to us
1189 $this->output( "Purging caches..." );
1190
1191 // ObjectCache
1192 $this->db->newDeleteQueryBuilder()
1193 ->deleteFrom( 'objectcache' )
1194 ->where( ISQLPlatform::ALL_ROWS )
1195 ->caller( __METHOD__ )
1196 ->execute();
1197
1198 // LocalisationCache
1199 if ( $wgLocalisationCacheConf['manualRecache'] ) {
1200 $this->rebuildLocalisationCache();
1201 }
1202
1203 // ResourceLoader: Message cache
1204 $services = MediaWikiServices::getInstance();
1205 MessageBlobStore::clearGlobalCacheEntry(
1206 $services->getMainWANObjectCache()
1207 );
1208
1209 // ResourceLoader: File-dependency cache
1210 $this->db->newDeleteQueryBuilder()
1211 ->deleteFrom( 'module_deps' )
1212 ->where( ISQLPlatform::ALL_ROWS )
1213 ->caller( __METHOD__ )
1214 ->execute();
1215 $this->output( "done.\n" );
1216 }
1217
1218 /**
1219 * Check the site_stats table is not properly populated.
1220 */
1221 protected function checkStats() {
1222 $this->output( "...site_stats is populated..." );
1223 $row = $this->db->newSelectQueryBuilder()
1224 ->select( '*' )
1225 ->from( 'site_stats' )
1226 ->where( [ 'ss_row_id' => 1 ] )
1227 ->caller( __METHOD__ )->fetchRow();
1228 if ( $row === false ) {
1229 $this->output( "data is missing! rebuilding...\n" );
1230 } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
1231 $this->output( "missing ss_total_pages, rebuilding...\n" );
1232 } else {
1233 $this->output( "done.\n" );
1234
1235 return;
1236 }
1237 SiteStatsInit::doAllAndCommit( $this->db );
1238 }
1239
1240 # Common updater functions
1241
1242 /**
1243 * Update CategoryLinks collation
1244 */
1245 protected function doCollationUpdate() {
1246 global $wgCategoryCollation;
1247 if ( $this->updateRowExists( 'UpdateCollation::' . $wgCategoryCollation ) ) {
1248 $this->output( "...collations up-to-date.\n" );
1249 return;
1250 }
1251 $this->output( "Updating category collations...\n" );
1252 $task = $this->maintenance->runChild( UpdateCollation::class );
1253 $ok = $task->execute();
1254 if ( $ok !== false ) {
1255 $this->output( "...done.\n" );
1256 $this->insertUpdateRow( 'UpdateCollation::' . $wgCategoryCollation );
1257 }
1258 }
1259
1260 protected function doConvertDjvuMetadata() {
1261 if ( $this->updateRowExists( 'ConvertDjvuMetadata' ) ) {
1262 return;
1263 }
1264 $this->output( "Converting djvu metadata..." );
1265 $task = $this->maintenance->runChild( RefreshImageMetadata::class );
1266 '@phan-var RefreshImageMetadata $task';
1267 $task->loadParamsAndArgs( RefreshImageMetadata::class, [
1268 'force' => true,
1269 'mediatype' => 'OFFICE',
1270 'mime' => 'image/*',
1271 'batch-size' => 1,
1272 'sleep' => 1
1273 ] );
1274 $ok = $task->execute();
1275 if ( $ok !== false ) {
1276 $this->output( "...done.\n" );
1277 $this->insertUpdateRow( 'ConvertDjvuMetadata' );
1278 }
1279 }
1280
1281 /**
1282 * Rebuilds the localisation cache
1283 */
1284 protected function rebuildLocalisationCache() {
1285 /**
1286 * @var RebuildLocalisationCache $cl
1287 */
1288 $cl = $this->maintenance->runChild(
1289 RebuildLocalisationCache::class, 'rebuildLocalisationCache.php'
1290 );
1291 '@phan-var RebuildLocalisationCache $cl';
1292 $this->output( "Rebuilding localisation cache...\n" );
1293 $cl->setForce();
1294 $cl->execute();
1295 $this->output( "done.\n" );
1296 }
1297
1298 protected function migrateTemplatelinks() {
1299 if ( $this->updateRowExists( MigrateLinksTable::class . 'templatelinks' ) ) {
1300 $this->output( "...templatelinks table has already been migrated.\n" );
1301 return;
1302 }
1303 /**
1304 * @var MigrateLinksTable $task
1305 */
1306 $task = $this->maintenance->runChild(
1307 MigrateLinksTable::class, 'migrateLinksTable.php'
1308 );
1309 '@phan-var MigrateLinksTable $task';
1310 $task->loadParamsAndArgs( MigrateLinksTable::class, [
1311 'force' => true,
1312 'table' => 'templatelinks'
1313 ] );
1314 $this->output( "Running migrateLinksTable.php on templatelinks...\n" );
1315 $task->execute();
1316 $this->output( "done.\n" );
1317 }
1318
1319 protected function migratePagelinks() {
1320 if ( $this->updateRowExists( MigrateLinksTable::class . 'pagelinks' ) ) {
1321 $this->output( "...pagelinks table has already been migrated.\n" );
1322 return;
1323 }
1324 /**
1325 * @var MigrateLinksTable $task
1326 */
1327 $task = $this->maintenance->runChild(
1328 MigrateLinksTable::class, 'migrateLinksTable.php'
1329 );
1330 '@phan-var MigrateLinksTable $task';
1331 $task->loadParamsAndArgs( MigrateLinksTable::class, [
1332 'force' => true,
1333 'table' => 'pagelinks'
1334 ] );
1335 $this->output( "Running migrateLinksTable.php on pagelinks...\n" );
1336 $task->execute();
1337 $this->output( "done.\n" );
1338 }
1339
1340 /**
1341 * Only run a function if a table does not exist
1342 *
1343 * @since 1.35
1344 * @param string $table Table to check.
1345 * If passed $this, it's assumed to be a call from runUpdates() with
1346 * $passSelf = true: all other parameters are shifted and $this is
1347 * prepended to the rest of $params.
1348 * @param string|array|static $func Normally this is the string naming the method on $this to
1349 * call. It may also be an array style callable.
1350 * @param mixed ...$params Parameters for `$func`
1351 * @return mixed Whatever $func returns, or null when skipped.
1352 */
1353 protected function ifTableNotExists( $table, $func, ...$params ) {
1354 // Handle $passSelf from runUpdates().
1355 $passSelf = false;
1356 if ( $table === $this ) {
1357 $passSelf = true;
1358 $table = $func;
1359 $func = array_shift( $params );
1360 }
1361
1362 if ( $this->db->tableExists( $table, __METHOD__ ) ) {
1363 return null;
1364 }
1365
1366 if ( !is_array( $func ) && method_exists( $this, $func ) ) {
1367 $func = [ $this, $func ];
1368 } elseif ( $passSelf ) {
1369 array_unshift( $params, $this );
1370 }
1371
1372 // @phan-suppress-next-line PhanUndeclaredInvokeInCallable Phan is confused
1373 return $func( ...$params );
1374 }
1375
1376 /**
1377 * Only run a function if the named field exists
1378 *
1379 * @since 1.35
1380 * @param string $table Table to check.
1381 * If passed $this, it's assumed to be a call from runUpdates() with
1382 * $passSelf = true: all other parameters are shifted and $this is
1383 * prepended to the rest of $params.
1384 * @param string $field Field to check
1385 * @param string|array|static $func Normally this is the string naming the method on $this to
1386 * call. It may also be an array style callable.
1387 * @param mixed ...$params Parameters for `$func`
1388 * @return mixed Whatever $func returns, or null when skipped.
1389 */
1390 protected function ifFieldExists( $table, $field, $func, ...$params ) {
1391 // Handle $passSelf from runUpdates().
1392 $passSelf = false;
1393 if ( $table === $this ) {
1394 $passSelf = true;
1395 $table = $field;
1396 $field = $func;
1397 $func = array_shift( $params );
1398 }
1399
1400 if ( !$this->db->tableExists( $table, __METHOD__ ) ||
1401 !$this->db->fieldExists( $table, $field, __METHOD__ )
1402 ) {
1403 return null;
1404 }
1405
1406 if ( !is_array( $func ) && method_exists( $this, $func ) ) {
1407 $func = [ $this, $func ];
1408 } elseif ( $passSelf ) {
1409 array_unshift( $params, $this );
1410 }
1411
1412 // @phan-suppress-next-line PhanUndeclaredInvokeInCallable Phan is confused
1413 return $func( ...$params );
1414 }
1415
1416 }
1417
1418 /** @deprecated class alias since 1.42 */
1419 class_alias( DatabaseUpdater::class, 'DatabaseUpdater' );