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