3 * DBMS-specific updater helper.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use Wikimedia\Rdbms\IDatabase
;
24 use Wikimedia\Rdbms\IMaintainableDatabase
;
25 use MediaWiki\MediaWikiServices
;
27 require_once __DIR__
. '/../../maintenance/Maintenance.php';
30 * Class for handling database updates. Roughly based off of updaters.inc, with
31 * a few improvements :)
36 abstract class DatabaseUpdater
{
37 const REPLICATION_WAIT_TIMEOUT
= 300;
40 * Array of updates to perform on the database
44 protected $updates = [];
47 * Array of updates that were skipped
51 protected $updatesSkipped = [];
54 * List of extension-provided database updates
57 protected $extensionUpdates = [];
60 * Handle to the database subclass
62 * @var IMaintainableDatabase
69 protected $maintenance;
71 protected $shared = false;
74 * @var string[] Scripts to run after database update
75 * Should be a subclass of LoggedUpdateMaintenance
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,
94 * File handle for SQL output.
98 protected $fileHandle = null;
101 * Flag specifying whether or not to skip schema (e.g. SQL-only) updates.
105 protected $skipSchema = false;
108 * Hold the value of $wgContentHandlerUseDB during the upgrade.
110 protected $holdContentHandlerUseDB = true;
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
117 protected function __construct(
118 IMaintainableDatabase
&$db,
120 Maintenance
$maintenance = null
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
;
129 $this->maintenance
= new FakeMaintenance
;
131 $this->maintenance
->setDB( $db );
132 $this->initOldGlobals();
133 $this->loadExtensions();
134 Hooks
::run( 'LoadExtensionSchemaUpdates', [ $this ] );
138 * Initialize all of the old globals. One day this should all become
139 * something much nicer
141 private function initOldGlobals() {
142 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
143 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
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
156 * Loads LocalSettings.php, if needed, and initialises everything needed for
157 * LoadExtensionSchemaUpdates hook.
159 private function loadExtensions() {
160 if ( !defined( 'MEDIAWIKI_INSTALL' ) ||
defined( 'MW_EXTENSIONS_LOADED' ) ) {
161 return; // already loaded
163 $vars = Installer
::getExistingLocalSettings();
165 $registry = ExtensionRegistry
::getInstance();
166 $queue = $registry->getQueue();
167 // Don't accidentally load extensions in the future
168 $registry->clearQueue();
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'] );
176 global $wgHooks, $wgAutoloadClasses;
177 $wgHooks['LoadExtensionSchemaUpdates'] = $hooks;
178 if ( $vars && isset( $vars['wgAutoloadClasses'] ) ) {
179 $wgAutoloadClasses +
= $vars['wgAutoloadClasses'];
184 * @param IMaintainableDatabase $db
185 * @param bool $shared
186 * @param Maintenance|null $maintenance
188 * @throws MWException
189 * @return DatabaseUpdater
191 public static function newForDB(
192 IMaintainableDatabase
$db,
194 Maintenance
$maintenance = null
196 $type = $db->getType();
197 if ( in_array( $type, Installer
::getDBTypes() ) ) {
198 $class = ucfirst( $type ) . 'Updater';
200 return new $class( $db, $shared, $maintenance );
202 throw new MWException( __METHOD__
. ' called for unsupported $wgDBtype' );
207 * Get a database connection to run updates
209 * @return IMaintainableDatabase
211 public function getDB() {
216 * Output some text. If we're running from web, escape the text first.
218 * @param string $str Text to output
219 * @param-taint $str escapes_html
221 public function output( $str ) {
222 if ( $this->maintenance
->isQuiet() ) {
225 global $wgCommandLineMode;
226 if ( !$wgCommandLineMode ) {
227 $str = htmlspecialchars( $str );
234 * Add a new update coming from an extension. This should be called by
235 * extensions while executing the LoadExtensionSchemaUpdates hook.
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.
245 public function addExtensionUpdate( array $update ) {
246 $this->extensionUpdates
[] = $update;
250 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
251 * is the most common usage of updaters in an extension)
255 * @param string $tableName Name of table to create
256 * @param string $sqlPath Full path to the schema file
258 public function addExtensionTable( $tableName, $sqlPath ) {
259 $this->extensionUpdates
[] = [ 'addTable', $tableName, $sqlPath, true ];
265 * @param string $tableName
266 * @param string $indexName
267 * @param string $sqlPath
269 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
270 $this->extensionUpdates
[] = [ 'addIndex', $tableName, $indexName, $sqlPath, true ];
277 * @param string $tableName
278 * @param string $columnName
279 * @param string $sqlPath
281 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
282 $this->extensionUpdates
[] = [ 'addField', $tableName, $columnName, $sqlPath, true ];
289 * @param string $tableName
290 * @param string $columnName
291 * @param string $sqlPath
293 public function dropExtensionField( $tableName, $columnName, $sqlPath ) {
294 $this->extensionUpdates
[] = [ 'dropField', $tableName, $columnName, $sqlPath, true ];
298 * Drop an index from an extension table
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
306 public function dropExtensionIndex( $tableName, $indexName, $sqlPath ) {
307 $this->extensionUpdates
[] = [ 'dropIndex', $tableName, $indexName, $sqlPath, true ];
314 * @param string $tableName
315 * @param string $sqlPath
317 public function dropExtensionTable( $tableName, $sqlPath ) {
318 $this->extensionUpdates
[] = [ 'dropTable', $tableName, $sqlPath, true ];
322 * Rename an index on an extension table
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]
333 public function renameExtensionIndex( $tableName, $oldIndexName, $newIndexName,
334 $sqlPath, $skipBothIndexExistWarning = false
336 $this->extensionUpdates
[] = [
341 $skipBothIndexExistWarning,
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
354 public function modifyExtensionField( $tableName, $fieldName, $sqlPath ) {
355 $this->extensionUpdates
[] = [ 'modifyField', $tableName, $fieldName, $sqlPath, true ];
361 * @param string $tableName The table name
362 * @param string $sqlPath The path to the SQL patch
364 public function modifyExtensionTable( $tableName, $sqlPath ) {
365 $this->extensionUpdates
[] = [ 'modifyTable', $tableName, $sqlPath, true ];
372 * @param string $tableName
375 public function tableExists( $tableName ) {
376 return ( $this->db
->tableExists( $tableName, __METHOD__
) );
380 * Add a maintenance script to be run after the database updates are complete.
382 * Script should subclass LoggedUpdateMaintenance
386 * @param string $class Name of a Maintenance subclass
388 public function addPostDatabaseUpdateMaintenance( $class ) {
389 $this->postDatabaseUpdateMaintenance
[] = $class;
393 * Get the list of extension-defined updates
397 protected function getExtensionUpdates() {
398 return $this->extensionUpdates
;
406 public function getPostDatabaseUpdateMaintenance() {
407 return $this->postDatabaseUpdateMaintenance
;
413 * Writes the schema updates desired to a file for the DB Admin to run.
414 * @param array $schemaUpdate
416 private function writeSchemaUpdateFile( array $schemaUpdate = [] ) {
417 $updates = $this->updatesSkipped
;
418 $this->updatesSkipped
= [];
420 foreach ( $updates as $funcList ) {
421 list( $func, $args, $origParams ) = $funcList;
422 // @phan-suppress-next-line PhanUndeclaredInvokeInCallable
425 $this->updatesSkipped
[] = $origParams;
430 * Get appropriate schema variables in the current database connection.
432 * This should be called after any request data has been imported, but before
433 * any write operations to the database. The result should be passed to the DB
434 * setSchemaVars() method.
439 public function getSchemaVars() {
440 return []; // DB-type specific
446 * @param array $what What updates to perform
448 public function doUpdates( array $what = [ 'core', 'extensions', 'stats' ] ) {
449 $this->db
->setSchemaVars( $this->getSchemaVars() );
451 $what = array_flip( $what );
452 $this->skipSchema
= isset( $what['noschema'] ) ||
$this->fileHandle
!== null;
453 if ( isset( $what['core'] ) ) {
454 $this->runUpdates( $this->getCoreUpdateList(), false );
456 if ( isset( $what['extensions'] ) ) {
457 $this->runUpdates( $this->getOldGlobalUpdates(), false );
458 $this->runUpdates( $this->getExtensionUpdates(), true );
461 if ( isset( $what['stats'] ) ) {
465 if ( $this->fileHandle
) {
466 $this->skipSchema
= false;
467 $this->writeSchemaUpdateFile();
472 * Helper function for doUpdates()
474 * @param array $updates Array of updates to run
475 * @param bool $passSelf Whether to pass this object we calling external functions
477 private function runUpdates( array $updates, $passSelf ) {
478 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
481 $updatesSkipped = [];
482 foreach ( $updates as $params ) {
483 $origParams = $params;
484 $func = array_shift( $params );
485 if ( !is_array( $func ) && method_exists( $this, $func ) ) {
486 $func = [ $this, $func ];
487 } elseif ( $passSelf ) {
488 array_unshift( $params, $this );
490 $ret = $func( ...$params );
492 if ( $ret !== false ) {
493 $updatesDone[] = $origParams;
494 $lbFactory->waitForReplication( [ 'timeout' => self
::REPLICATION_WAIT_TIMEOUT
] );
496 $updatesSkipped[] = [ $func, $params, $origParams ];
499 $this->updatesSkipped
= array_merge( $this->updatesSkipped
, $updatesSkipped );
500 $this->updates
= array_merge( $this->updates
, $updatesDone );
504 * Helper function: check if the given key is present in the updatelog table.
505 * Obviously, only use this for updates that occur after the updatelog table was
507 * @param string $key Name of the key to check for
510 public function updateRowExists( $key ) {
511 $row = $this->db
->selectRow(
515 [ 'ul_key' => $key ],
523 * Helper function: Add a key to the updatelog table
524 * Obviously, only use this for updates that occur after the updatelog table was
526 * @param string $key Name of key to insert
527 * @param string|null $val [optional] Value to insert along with the key
529 public function insertUpdateRow( $key, $val = null ) {
530 $this->db
->clearFlag( DBO_DDLMODE
);
531 $values = [ 'ul_key' => $key ];
532 if ( $val && $this->canUseNewUpdatelog() ) {
533 $values['ul_value'] = $val;
535 $this->db
->insert( 'updatelog', $values, __METHOD__
, [ 'IGNORE' ] );
536 $this->db
->setFlag( DBO_DDLMODE
);
540 * Updatelog was changed in 1.17 to have a ul_value column so we can record
541 * more information about what kind of updates we've done (that's what this
542 * class does). Pre-1.17 wikis won't have this column, and really old wikis
543 * might not even have updatelog at all
547 protected function canUseNewUpdatelog() {
548 return $this->db
->tableExists( 'updatelog', __METHOD__
) &&
549 $this->db
->fieldExists( 'updatelog', 'ul_value', __METHOD__
);
553 * Returns whether updates should be executed on the database table $name.
554 * Updates will be prevented if the table is a shared table and it is not
555 * specified to run updates on shared tables.
557 * @param string $name Table name
560 protected function doTable( $name ) {
561 global $wgSharedDB, $wgSharedTables;
563 // Don't bother to check $wgSharedTables if there isn't a shared database
564 // or the user actually also wants to do updates on the shared database.
565 if ( $wgSharedDB === null ||
$this->shared
) {
569 if ( in_array( $name, $wgSharedTables ) ) {
570 $this->output( "...skipping update to shared table $name.\n" );
578 * Before 1.17, we used to handle updates via stuff like
579 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
580 * of this in 1.17 but we want to remain back-compatible for a while. So
581 * load up these old global-based things into our update list.
585 protected function getOldGlobalUpdates() {
586 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
591 foreach ( $wgExtNewTables as $tableRecord ) {
593 'addTable', $tableRecord[0], $tableRecord[1], true
597 foreach ( $wgExtNewFields as $fieldRecord ) {
599 'addField', $fieldRecord[0], $fieldRecord[1],
600 $fieldRecord[2], true
604 foreach ( $wgExtNewIndexes as $fieldRecord ) {
606 'addIndex', $fieldRecord[0], $fieldRecord[1],
607 $fieldRecord[2], true
611 foreach ( $wgExtModifiedFields as $fieldRecord ) {
613 'modifyField', $fieldRecord[0], $fieldRecord[1],
614 $fieldRecord[2], true
622 * Get an array of updates to perform on the database. Should return a
623 * multi-dimensional array. The main key is the MediaWiki version (1.12,
624 * 1.13...) with the values being arrays of updates, identical to how
625 * updaters.inc did it (for now)
629 abstract protected function getCoreUpdateList();
632 * Append an SQL fragment to the open file handle.
634 * @param string $filename File name to open
636 public function copyFile( $filename ) {
637 $this->db
->sourceFile(
642 [ $this, 'appendLine' ]
647 * Append a line to the open filehandle. The line is assumed to
648 * be a complete SQL statement.
650 * This is used as a callback for sourceLine().
652 * @param string $line Text to append to the file
653 * @return bool False to skip actually executing the file
654 * @throws MWException
656 public function appendLine( $line ) {
657 $line = rtrim( $line ) . ";\n";
658 if ( fwrite( $this->fileHandle
, $line ) === false ) {
659 throw new MWException( "trouble writing file" );
666 * Applies a SQL patch
668 * @param string $path Path to the patch file
669 * @param bool $isFullPath Whether to treat $path as a relative or not
670 * @param string|null $msg Description of the patch
671 * @return bool False if patch is skipped.
673 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
674 if ( $msg === null ) {
675 $msg = "Applying $path patch";
677 if ( $this->skipSchema
) {
678 $this->output( "...skipping schema change ($msg).\n" );
683 $this->output( "$msg ..." );
685 if ( !$isFullPath ) {
686 $path = $this->patchPath( $this->db
, $path );
688 if ( $this->fileHandle
!== null ) {
689 $this->copyFile( $path );
691 $this->db
->sourceFile( $path );
693 $this->output( "done.\n" );
699 * Get the full path of a patch file. Originally based on archive()
700 * from updaters.inc. Keep in mind this always returns a patch, as
701 * it fails back to MySQL if no DB-specific patch can be found
703 * @param IDatabase $db
704 * @param string $patch The name of the patch, like patch-something.sql
705 * @return string Full path to patch file
707 public function patchPath( IDatabase
$db, $patch ) {
710 $dbType = $db->getType();
711 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
712 return "$IP/maintenance/$dbType/archives/$patch";
714 return "$IP/maintenance/archives/$patch";
719 * Add a new table to the database
721 * @param string $name Name of the new table
722 * @param string $patch Path to the patch file
723 * @param bool $fullpath Whether to treat $patch path as a relative or not
724 * @return bool False if this was skipped because schema changes are skipped
726 protected function addTable( $name, $patch, $fullpath = false ) {
727 if ( !$this->doTable( $name ) ) {
731 if ( $this->db
->tableExists( $name, __METHOD__
) ) {
732 $this->output( "...$name table already exists.\n" );
734 return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
741 * Add a new field to an existing table
743 * @param string $table Name of the table to modify
744 * @param string $field Name of the new field
745 * @param string $patch Path to the patch file
746 * @param bool $fullpath Whether to treat $patch path as a relative or not
747 * @return bool False if this was skipped because schema changes are skipped
749 protected function addField( $table, $field, $patch, $fullpath = false ) {
750 if ( !$this->doTable( $table ) ) {
754 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
755 $this->output( "...$table table does not exist, skipping new field patch.\n" );
756 } elseif ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
757 $this->output( "...have $field field in $table table.\n" );
759 return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
766 * Add a new index to an existing table
768 * @param string $table Name of the table to modify
769 * @param string $index Name of the new index
770 * @param string $patch Path to the patch file
771 * @param bool $fullpath Whether to treat $patch path as a relative or not
772 * @return bool False if this was skipped because schema changes are skipped
774 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
775 if ( !$this->doTable( $table ) ) {
779 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
780 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
781 } elseif ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
782 $this->output( "...index $index already set on $table table.\n" );
784 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
791 * Add a new index to an existing table if none of the given indexes exist
793 * @param string $table Name of the table to modify
794 * @param string[] $indexes Name of the indexes to check. $indexes[0] should
795 * be the one actually being added.
796 * @param string $patch Path to the patch file
797 * @param bool $fullpath Whether to treat $patch path as a relative or not
798 * @return bool False if this was skipped because schema changes are skipped
800 protected function addIndexIfNoneExist( $table, $indexes, $patch, $fullpath = false ) {
801 if ( !$this->doTable( $table ) ) {
805 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
806 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
810 $newIndex = $indexes[0];
811 foreach ( $indexes as $index ) {
812 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
814 "...skipping index $newIndex because index $index already set on $table table.\n"
820 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
824 * Drop a field from an existing table
826 * @param string $table Name of the table to modify
827 * @param string $field Name of the old field
828 * @param string $patch Path to the patch file
829 * @param bool $fullpath Whether to treat $patch path as a relative or not
830 * @return bool False if this was skipped because schema changes are skipped
832 protected function dropField( $table, $field, $patch, $fullpath = false ) {
833 if ( !$this->doTable( $table ) ) {
837 if ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
838 return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
840 $this->output( "...$table table does not contain $field field.\n" );
847 * Drop an index from an existing table
849 * @param string $table Name of the table to modify
850 * @param string $index Name of the index
851 * @param string $patch Path to the patch file
852 * @param bool $fullpath Whether to treat $patch path as a relative or not
853 * @return bool False if this was skipped because schema changes are skipped
855 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
856 if ( !$this->doTable( $table ) ) {
860 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
861 return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
863 $this->output( "...$index key doesn't exist.\n" );
870 * Rename an index from an existing table
872 * @param string $table Name of the table to modify
873 * @param string $oldIndex Old name of the index
874 * @param string $newIndex New name of the index
875 * @param bool $skipBothIndexExistWarning Whether to warn if both the
876 * old and the new indexes exist.
877 * @param string $patch Path to the patch file
878 * @param bool $fullpath Whether to treat $patch path as a relative or not
879 * @return bool False if this was skipped because schema changes are skipped
881 protected function renameIndex( $table, $oldIndex, $newIndex,
882 $skipBothIndexExistWarning, $patch, $fullpath = false
884 if ( !$this->doTable( $table ) ) {
888 // First requirement: the table must exist
889 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
890 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
895 // Second requirement: the new index must be missing
896 if ( $this->db
->indexExists( $table, $newIndex, __METHOD__
) ) {
897 $this->output( "...index $newIndex already set on $table table.\n" );
898 if ( !$skipBothIndexExistWarning &&
899 $this->db
->indexExists( $table, $oldIndex, __METHOD__
)
901 $this->output( "...WARNING: $oldIndex still exists, despite it has " .
902 "been renamed into $newIndex (which also exists).\n" .
903 " $oldIndex should be manually removed if not needed anymore.\n" );
909 // Third requirement: the old index must exist
910 if ( !$this->db
->indexExists( $table, $oldIndex, __METHOD__
) ) {
911 $this->output( "...skipping: index $oldIndex doesn't exist.\n" );
916 // Requirements have been satisfied, patch can be applied
917 return $this->applyPatch(
920 "Renaming index $oldIndex into $newIndex to table $table"
925 * If the specified table exists, drop it, or execute the
926 * patch if one is provided.
930 * @param string $table Table to drop.
931 * @param string|bool $patch String of patch file that will drop the table. Default: false.
932 * @param bool $fullpath Whether $patch is a full path. Default: false.
933 * @return bool False if this was skipped because schema changes are skipped
935 public function dropTable( $table, $patch = false, $fullpath = false ) {
936 if ( !$this->doTable( $table ) ) {
940 if ( $this->db
->tableExists( $table, __METHOD__
) ) {
941 $msg = "Dropping table $table";
943 if ( $patch === false ) {
944 $this->output( "$msg ..." );
945 $this->db
->dropTable( $table, __METHOD__
);
946 $this->output( "done.\n" );
948 return $this->applyPatch( $patch, $fullpath, $msg );
951 $this->output( "...$table doesn't exist.\n" );
958 * Modify an existing field
960 * @param string $table Name of the table to which the field belongs
961 * @param string $field Name of the field to modify
962 * @param string $patch Path to the patch file
963 * @param bool $fullpath Whether to treat $patch path as a relative or not
964 * @return bool False if this was skipped because schema changes are skipped
966 public function modifyField( $table, $field, $patch, $fullpath = false ) {
967 if ( !$this->doTable( $table ) ) {
971 $updateKey = "$table-$field-$patch";
972 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
973 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
974 } elseif ( !$this->db
->fieldExists( $table, $field, __METHOD__
) ) {
975 $this->output( "...$field field does not exist in $table table, " .
976 "skipping modify field patch.\n" );
977 } elseif ( $this->updateRowExists( $updateKey ) ) {
978 $this->output( "...$field in table $table already modified by patch $patch.\n" );
980 $apply = $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
982 $this->insertUpdateRow( $updateKey );
990 * Modify an existing table, similar to modifyField. Intended for changes that
991 * touch more than one column on a table.
993 * @param string $table Name of the table to modify
994 * @param string $patch Name of the patch file to apply
995 * @param string|bool $fullpath Whether to treat $patch path as relative or not, defaults to false
996 * @return bool False if this was skipped because of schema changes being skipped
998 public function modifyTable( $table, $patch, $fullpath = false ) {
999 if ( !$this->doTable( $table ) ) {
1003 $updateKey = "$table-$patch";
1004 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
1005 $this->output( "...$table table does not exist, skipping modify table patch.\n" );
1006 } elseif ( $this->updateRowExists( $updateKey ) ) {
1007 $this->output( "...table $table already modified by patch $patch.\n" );
1009 $apply = $this->applyPatch( $patch, $fullpath, "Modifying table $table" );
1011 $this->insertUpdateRow( $updateKey );
1019 * Run a maintenance script
1021 * This should only be used when the maintenance script must run before
1022 * later updates. If later updates don't depend on the script, add it to
1023 * DatabaseUpdater::$postDatabaseUpdateMaintenance instead.
1025 * The script's execute() method must return true to indicate successful
1026 * completion, and must return false (or throw an exception) to indicate
1027 * unsuccessful completion.
1030 * @param string $class Maintenance subclass
1031 * @param string $script Script path and filename, usually "maintenance/fooBar.php"
1033 public function runMaintenance( $class, $script ) {
1034 $this->output( "Running $script...\n" );
1035 $task = $this->maintenance
->runChild( $class );
1036 $ok = $task->execute();
1038 throw new RuntimeException( "Execution of $script did not complete successfully." );
1040 $this->output( "done.\n" );
1044 * Set any .htaccess files or equivilent for storage repos
1046 * Some zones (e.g. "temp") used to be public and may have been initialized as such
1048 public function setFileAccess() {
1049 $repo = RepoGroup
::singleton()->getLocalRepo();
1050 $zonePath = $repo->getZonePath( 'temp' );
1051 if ( $repo->getBackend()->directoryExists( [ 'dir' => $zonePath ] ) ) {
1052 // If the directory was never made, then it will have the right ACLs when it is made
1053 $status = $repo->getBackend()->secure( [
1058 if ( $status->isOK() ) {
1059 $this->output( "Set the local repo temp zone container to be private.\n" );
1061 $this->output( "Failed to set the local repo temp zone container to be private.\n" );
1067 * Purge various database caches
1069 public function purgeCache() {
1070 global $wgLocalisationCacheConf;
1071 // We can't guarantee that the user will be able to use TRUNCATE,
1072 // but we know that DELETE is available to us
1073 $this->output( "Purging caches..." );
1076 $this->db
->delete( 'objectcache', '*', __METHOD__
);
1078 // LocalisationCache
1079 if ( $wgLocalisationCacheConf['manualRecache'] ) {
1080 $this->rebuildLocalisationCache();
1083 // ResourceLoader: Message cache
1084 $blobStore = new MessageBlobStore(
1085 MediaWikiServices
::getInstance()->getResourceLoader()
1087 $blobStore->clear();
1089 // ResourceLoader: File-dependency cache
1090 $this->db
->delete( 'module_deps', '*', __METHOD__
);
1091 $this->output( "done.\n" );
1095 * Check the site_stats table is not properly populated.
1097 protected function checkStats() {
1098 $this->output( "...site_stats is populated..." );
1099 $row = $this->db
->selectRow( 'site_stats', '*', [ 'ss_row_id' => 1 ], __METHOD__
);
1100 if ( $row === false ) {
1101 $this->output( "data is missing! rebuilding...\n" );
1102 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
1103 $this->output( "missing ss_total_pages, rebuilding...\n" );
1105 $this->output( "done.\n" );
1109 SiteStatsInit
::doAllAndCommit( $this->db
);
1112 # Common updater functions
1115 * Sets the number of active users in the site_stats table
1117 protected function doActiveUsersInit() {
1118 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', '', __METHOD__
);
1119 if ( $activeUsers == -1 ) {
1120 $activeUsers = $this->db
->selectField( 'recentchanges',
1121 'COUNT( DISTINCT rc_user_text )',
1122 [ 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ], __METHOD__
1124 $this->db
->update( 'site_stats',
1125 [ 'ss_active_users' => intval( $activeUsers ) ],
1126 [ 'ss_row_id' => 1 ], __METHOD__
, [ 'LIMIT' => 1 ]
1129 $this->output( "...ss_active_users user count set...\n" );
1133 * Populates the log_user_text field in the logging table
1135 protected function doLogUsertextPopulation() {
1136 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
1138 "Populating log_user_text field, printing progress markers. For large\n" .
1139 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1140 "maintenance/populateLogUsertext.php.\n"
1143 $task = $this->maintenance
->runChild( PopulateLogUsertext
::class );
1145 $this->output( "done.\n" );
1150 * Migrate log params to new table and index for searching
1152 protected function doLogSearchPopulation() {
1153 if ( !$this->updateRowExists( 'populate log_search' ) ) {
1155 "Populating log_search table, printing progress markers. For large\n" .
1156 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1157 "maintenance/populateLogSearch.php.\n" );
1159 $task = $this->maintenance
->runChild( PopulateLogSearch
::class );
1161 $this->output( "done.\n" );
1166 * Update CategoryLinks collation
1168 protected function doCollationUpdate() {
1169 global $wgCategoryCollation;
1170 if ( $this->db
->fieldExists( 'categorylinks', 'cl_collation', __METHOD__
) ) {
1171 if ( $this->db
->selectField(
1174 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
1178 $this->output( "...collations up-to-date.\n" );
1183 $this->output( "Updating category collations..." );
1184 $task = $this->maintenance
->runChild( UpdateCollation
::class );
1186 $this->output( "...done.\n" );
1191 * Migrates user options from the user table blob to user_properties
1193 protected function doMigrateUserOptions() {
1194 if ( $this->db
->tableExists( 'user_properties' ) ) {
1195 $cl = $this->maintenance
->runChild( ConvertUserOptions
::class, 'convertUserOptions.php' );
1197 $this->output( "done.\n" );
1202 * Enable profiling table when it's turned on
1204 protected function doEnableProfiling() {
1207 if ( !$this->doTable( 'profiling' ) ) {
1211 $profileToDb = false;
1212 if ( isset( $wgProfiler['output'] ) ) {
1213 $out = $wgProfiler['output'];
1214 if ( $out === 'db' ) {
1215 $profileToDb = true;
1216 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
1217 $profileToDb = true;
1221 if ( $profileToDb && !$this->db
->tableExists( 'profiling', __METHOD__
) ) {
1222 $this->applyPatch( 'patch-profiling.sql', false, 'Add profiling table' );
1227 * Rebuilds the localisation cache
1229 protected function rebuildLocalisationCache() {
1231 * @var RebuildLocalisationCache $cl
1233 $cl = $this->maintenance
->runChild(
1234 RebuildLocalisationCache
::class, 'rebuildLocalisationCache.php'
1236 '@phan-var RebuildLocalisationCache $cl';
1237 $this->output( "Rebuilding localisation cache...\n" );
1240 $this->output( "done.\n" );
1244 * Turns off content handler fields during parts of the upgrade
1245 * where they aren't available.
1247 protected function disableContentHandlerUseDB() {
1248 global $wgContentHandlerUseDB;
1250 if ( $wgContentHandlerUseDB ) {
1251 $this->output( "Turning off Content Handler DB fields for this part of upgrade.\n" );
1252 $this->holdContentHandlerUseDB
= $wgContentHandlerUseDB;
1253 $wgContentHandlerUseDB = false;
1258 * Turns content handler fields back on.
1260 protected function enableContentHandlerUseDB() {
1261 global $wgContentHandlerUseDB;
1263 if ( $this->holdContentHandlerUseDB
) {
1264 $this->output( "Content Handler DB fields should be usable now.\n" );
1265 $wgContentHandlerUseDB = $this->holdContentHandlerUseDB
;
1270 * Migrate comments to the new 'comment' table
1273 protected function migrateComments() {
1274 if ( !$this->updateRowExists( 'MigrateComments' ) ) {
1276 "Migrating comments to the 'comments' table, printing progress markers. For large\n" .
1277 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1278 "maintenance/migrateComments.php.\n"
1280 $task = $this->maintenance
->runChild( MigrateComments
::class, 'migrateComments.php' );
1281 $ok = $task->execute();
1282 $this->output( $ok ?
"done.\n" : "errors were encountered.\n" );
1287 * Merge `image_comment_temp` into the `image` table
1290 protected function migrateImageCommentTemp() {
1291 if ( $this->tableExists( 'image_comment_temp' ) ) {
1292 $this->output( "Merging image_comment_temp into the image table\n" );
1293 $task = $this->maintenance
->runChild(
1294 MigrateImageCommentTemp
::class, 'migrateImageCommentTemp.php'
1296 // @phan-suppress-next-line PhanUndeclaredMethod
1298 $ok = $task->execute();
1299 $this->output( $ok ?
"done.\n" : "errors were encountered.\n" );
1301 $this->dropTable( 'image_comment_temp' );
1307 * Migrate actors to the new 'actor' table
1310 protected function migrateActors() {
1311 if ( !$this->updateRowExists( 'MigrateActors' ) ) {
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"
1317 $task = $this->maintenance
->runChild( 'MigrateActors', 'migrateActors.php' );
1318 $ok = $task->execute();
1319 $this->output( $ok ?
"done.\n" : "errors were encountered.\n" );
1324 * Migrate ar_text to modern storage
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 // @phan-suppress-next-line PhanUndeclaredMethod
1333 if ( $task->execute() ) {
1334 $this->applyPatch( 'patch-drop-ar_text.sql', false,
1335 'Dropping ar_text and ar_flags columns' );
1341 * Populate ar_rev_id, then make it not nullable
1344 protected function populateArchiveRevId() {
1345 $info = $this->db
->fieldInfo( 'archive', 'ar_rev_id', __METHOD__
);
1347 throw new MWException( 'Missing ar_rev_id field of archive table. Should not happen.' );
1349 if ( $info->isNullable() ) {
1350 $this->output( "Populating ar_rev_id.\n" );
1351 $task = $this->maintenance
->runChild( 'PopulateArchiveRevId', 'populateArchiveRevId.php' );
1352 if ( $task->execute() ) {
1353 $this->applyPatch( 'patch-ar_rev_id-not-null.sql', false,
1354 'Making ar_rev_id not nullable' );
1360 * Populates the externallinks.el_index_60 field
1363 protected function populateExternallinksIndex60() {
1364 if ( !$this->updateRowExists( 'populate externallinks.el_index_60' ) ) {
1366 "Populating el_index_60 field, printing progress markers. For large\n" .
1367 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1368 "maintenance/populateExternallinksIndex60.php.\n"
1370 $task = $this->maintenance
->runChild( 'PopulateExternallinksIndex60',
1371 'populateExternallinksIndex60.php' );
1373 $this->output( "done.\n" );
1378 * Populates the MCR content tables
1381 protected function populateContentTables() {
1382 global $wgMultiContentRevisionSchemaMigrationStage;
1383 if ( ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) &&
1384 !$this->updateRowExists( 'PopulateContentTables' )
1387 "Migrating revision data to the MCR 'slot' and 'content' tables, printing progress markers.\n" .
1388 "For large databases, you may want to hit Ctrl-C and do this manually with\n" .
1389 "maintenance/populateContentTables.php.\n"
1391 $task = $this->maintenance
->runChild(
1392 PopulateContentTables
::class, 'populateContentTables.php'
1394 $ok = $task->execute();
1395 $this->output( $ok ?
"done.\n" : "errors were encountered.\n" );
1397 $this->insertUpdateRow( 'PopulateContentTables' );
1403 * Only run a function if the `actor` table does not exist
1405 * The transition to the actor table is dropping several indexes (and a few
1406 * fields) that old upgrades want to add. This function is used to prevent
1407 * those from running to re-add things when the `actor` table exists, while
1408 * still allowing them to run if this really is an upgrade from an old MW
1412 * @param string|array|static $func Normally this is the string naming the method on $this to
1413 * call. It may also be an array callable. If passed $this, it's assumed to be a call from
1414 * runUpdates() with $passSelf = true: $params[0] is assumed to be the real $func and $this
1415 * is prepended to the rest of $params.
1416 * @param mixed ...$params Parameters for `$func`
1417 * @return mixed Whatever $func returns, or null when skipped.
1419 protected function ifNoActorTable( $func, ...$params ) {
1420 if ( $this->tableExists( 'actor' ) ) {
1424 // Handle $passSelf from runUpdates().
1426 if ( $func === $this ) {
1428 $func = array_shift( $params );
1431 if ( !is_array( $func ) && method_exists( $this, $func ) ) {
1432 $func = [ $this, $func ];
1433 } elseif ( $passSelf ) {
1434 array_unshift( $params, $this );
1437 // @phan-suppress-next-line PhanUndeclaredInvokeInCallable Phan is confused
1438 return $func( ...$params );