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