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;
424 $this->updatesSkipped
[] = $origParams;
429 * Get appropriate schema variables in the current database connection.
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.
438 public function getSchemaVars() {
439 return []; // DB-type specific
445 * @param array $what What updates to perform
447 public function doUpdates( array $what = [ 'core', 'extensions', 'stats' ] ) {
448 $this->db
->setSchemaVars( $this->getSchemaVars() );
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 );
455 if ( isset( $what['extensions'] ) ) {
456 $this->runUpdates( $this->getOldGlobalUpdates(), false );
457 $this->runUpdates( $this->getExtensionUpdates(), true );
460 if ( isset( $what['stats'] ) ) {
464 if ( $this->fileHandle
) {
465 $this->skipSchema
= false;
466 $this->writeSchemaUpdateFile();
471 * Helper function for doUpdates()
473 * @param array $updates Array of updates to run
474 * @param bool $passSelf Whether to pass this object we calling external functions
476 private function runUpdates( array $updates, $passSelf ) {
477 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
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 );
489 $ret = $func( ...$params );
491 if ( $ret !== false ) {
492 $updatesDone[] = $origParams;
493 $lbFactory->waitForReplication( [ 'timeout' => self
::REPLICATION_WAIT_TIMEOUT
] );
495 $updatesSkipped[] = [ $func, $params, $origParams ];
498 $this->updatesSkipped
= array_merge( $this->updatesSkipped
, $updatesSkipped );
499 $this->updates
= array_merge( $this->updates
, $updatesDone );
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
506 * @param string $key Name of the key to check for
509 public function updateRowExists( $key ) {
510 $row = $this->db
->selectRow(
514 [ 'ul_key' => $key ],
522 * Helper function: Add a key to the updatelog table
523 * Obviously, only use this for updates that occur after the updatelog table was
525 * @param string $key Name of key to insert
526 * @param string|null $val [optional] Value to insert along with the key
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;
534 $this->db
->insert( 'updatelog', $values, __METHOD__
, 'IGNORE' );
535 $this->db
->setFlag( DBO_DDLMODE
);
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
546 protected function canUseNewUpdatelog() {
547 return $this->db
->tableExists( 'updatelog', __METHOD__
) &&
548 $this->db
->fieldExists( 'updatelog', 'ul_value', __METHOD__
);
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.
556 * @param string $name Table name
559 protected function doTable( $name ) {
560 global $wgSharedDB, $wgSharedTables;
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
) {
568 if ( in_array( $name, $wgSharedTables ) ) {
569 $this->output( "...skipping update to shared table $name.\n" );
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.
584 protected function getOldGlobalUpdates() {
585 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
590 foreach ( $wgExtNewTables as $tableRecord ) {
592 'addTable', $tableRecord[0], $tableRecord[1], true
596 foreach ( $wgExtNewFields as $fieldRecord ) {
598 'addField', $fieldRecord[0], $fieldRecord[1],
599 $fieldRecord[2], true
603 foreach ( $wgExtNewIndexes as $fieldRecord ) {
605 'addIndex', $fieldRecord[0], $fieldRecord[1],
606 $fieldRecord[2], true
610 foreach ( $wgExtModifiedFields as $fieldRecord ) {
612 'modifyField', $fieldRecord[0], $fieldRecord[1],
613 $fieldRecord[2], true
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)
628 abstract protected function getCoreUpdateList();
631 * Append an SQL fragment to the open file handle.
633 * @param string $filename File name to open
635 public function copyFile( $filename ) {
636 $this->db
->sourceFile(
641 [ $this, 'appendLine' ]
646 * Append a line to the open filehandle. The line is assumed to
647 * be a complete SQL statement.
649 * This is used as a callback for sourceLine().
651 * @param string $line Text to append to the file
652 * @return bool False to skip actually executing the file
653 * @throws MWException
655 public function appendLine( $line ) {
656 $line = rtrim( $line ) . ";\n";
657 if ( fwrite( $this->fileHandle
, $line ) === false ) {
658 throw new MWException( "trouble writing file" );
665 * Applies a SQL patch
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.
672 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
673 if ( $msg === null ) {
674 $msg = "Applying $path patch";
676 if ( $this->skipSchema
) {
677 $this->output( "...skipping schema change ($msg).\n" );
682 $this->output( "$msg ..." );
684 if ( !$isFullPath ) {
685 $path = $this->patchPath( $this->db
, $path );
687 if ( $this->fileHandle
!== null ) {
688 $this->copyFile( $path );
690 $this->db
->sourceFile( $path );
692 $this->output( "done.\n" );
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
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
706 public function patchPath( IDatabase
$db, $patch ) {
709 $dbType = $db->getType();
710 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
711 return "$IP/maintenance/$dbType/archives/$patch";
713 return "$IP/maintenance/archives/$patch";
718 * Add a new table to the database
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
725 protected function addTable( $name, $patch, $fullpath = false ) {
726 if ( !$this->doTable( $name ) ) {
730 if ( $this->db
->tableExists( $name, __METHOD__
) ) {
731 $this->output( "...$name table already exists.\n" );
733 return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
740 * Add a new field to an existing table
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
748 protected function addField( $table, $field, $patch, $fullpath = false ) {
749 if ( !$this->doTable( $table ) ) {
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" );
758 return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
765 * Add a new index to an existing table
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
773 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
774 if ( !$this->doTable( $table ) ) {
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" );
783 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
790 * Add a new index to an existing table if none of the given indexes exist
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
799 protected function addIndexIfNoneExist( $table, $indexes, $patch, $fullpath = false ) {
800 if ( !$this->doTable( $table ) ) {
804 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
805 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
809 $newIndex = $indexes[0];
810 foreach ( $indexes as $index ) {
811 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
813 "...skipping index $newIndex because index $index already set on $table table.\n"
819 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
823 * Drop a field from an existing table
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
831 protected function dropField( $table, $field, $patch, $fullpath = false ) {
832 if ( !$this->doTable( $table ) ) {
836 if ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
837 return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
839 $this->output( "...$table table does not contain $field field.\n" );
846 * Drop an index from an existing table
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
854 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
855 if ( !$this->doTable( $table ) ) {
859 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
860 return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
862 $this->output( "...$index key doesn't exist.\n" );
869 * Rename an index from an existing table
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
880 protected function renameIndex( $table, $oldIndex, $newIndex,
881 $skipBothIndexExistWarning, $patch, $fullpath = false
883 if ( !$this->doTable( $table ) ) {
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" );
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__
)
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" );
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" );
915 // Requirements have been satisfied, patch can be applied
916 return $this->applyPatch(
919 "Renaming index $oldIndex into $newIndex to table $table"
924 * If the specified table exists, drop it, or execute the
925 * patch if one is provided.
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
934 public function dropTable( $table, $patch = false, $fullpath = false ) {
935 if ( !$this->doTable( $table ) ) {
939 if ( $this->db
->tableExists( $table, __METHOD__
) ) {
940 $msg = "Dropping table $table";
942 if ( $patch === false ) {
943 $this->output( "$msg ..." );
944 $this->db
->dropTable( $table, __METHOD__
);
945 $this->output( "done.\n" );
947 return $this->applyPatch( $patch, $fullpath, $msg );
950 $this->output( "...$table doesn't exist.\n" );
957 * Modify an existing field
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
965 public function modifyField( $table, $field, $patch, $fullpath = false ) {
966 if ( !$this->doTable( $table ) ) {
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" );
979 $apply = $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
981 $this->insertUpdateRow( $updateKey );
989 * Modify an existing table, similar to modifyField. Intended for changes that
990 * touch more than one column on a table.
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
997 public function modifyTable( $table, $patch, $fullpath = false ) {
998 if ( !$this->doTable( $table ) ) {
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" );
1008 $apply = $this->applyPatch( $patch, $fullpath, "Modifying table $table" );
1010 $this->insertUpdateRow( $updateKey );
1018 * Run a maintenance script
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.
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.
1029 * @param string $class Maintenance subclass
1030 * @param string $script Script path and filename, usually "maintenance/fooBar.php"
1032 public function runMaintenance( $class, $script ) {
1033 $this->output( "Running $script...\n" );
1034 $task = $this->maintenance
->runChild( $class );
1035 $ok = $task->execute();
1037 throw new RuntimeException( "Execution of $script did not complete successfully." );
1039 $this->output( "done.\n" );
1043 * Set any .htaccess files or equivilent for storage repos
1045 * Some zones (e.g. "temp") used to be public and may have been initialized as such
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( [
1057 if ( $status->isOK() ) {
1058 $this->output( "Set the local repo temp zone container to be private.\n" );
1060 $this->output( "Failed to set the local repo temp zone container to be private.\n" );
1066 * Purge various database caches
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..." );
1075 $this->db
->delete( 'objectcache', '*', __METHOD__
);
1077 // LocalisationCache
1078 if ( $wgLocalisationCacheConf['manualRecache'] ) {
1079 $this->rebuildLocalisationCache();
1082 // ResourceLoader: Message cache
1083 $blobStore = new MessageBlobStore(
1084 MediaWikiServices
::getInstance()->getResourceLoader()
1086 $blobStore->clear();
1088 // ResourceLoader: File-dependency cache
1089 $this->db
->delete( 'module_deps', '*', __METHOD__
);
1090 $this->output( "done.\n" );
1094 * Check the site_stats table is not properly populated.
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" );
1104 $this->output( "done.\n" );
1108 SiteStatsInit
::doAllAndCommit( $this->db
);
1111 # Common updater functions
1114 * Sets the number of active users in the site_stats table
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__
1123 $this->db
->update( 'site_stats',
1124 [ 'ss_active_users' => intval( $activeUsers ) ],
1125 [ 'ss_row_id' => 1 ], __METHOD__
, [ 'LIMIT' => 1 ]
1128 $this->output( "...ss_active_users user count set...\n" );
1132 * Populates the log_user_text field in the logging table
1134 protected function doLogUsertextPopulation() {
1135 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
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"
1142 $task = $this->maintenance
->runChild( PopulateLogUsertext
::class );
1144 $this->output( "done.\n" );
1149 * Migrate log params to new table and index for searching
1151 protected function doLogSearchPopulation() {
1152 if ( !$this->updateRowExists( 'populate log_search' ) ) {
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" );
1158 $task = $this->maintenance
->runChild( PopulateLogSearch
::class );
1160 $this->output( "done.\n" );
1165 * Update CategoryLinks collation
1167 protected function doCollationUpdate() {
1168 global $wgCategoryCollation;
1169 if ( $this->db
->fieldExists( 'categorylinks', 'cl_collation', __METHOD__
) ) {
1170 if ( $this->db
->selectField(
1173 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
1177 $this->output( "...collations up-to-date.\n" );
1182 $this->output( "Updating category collations..." );
1183 $task = $this->maintenance
->runChild( UpdateCollation
::class );
1185 $this->output( "...done.\n" );
1190 * Migrates user options from the user table blob to user_properties
1192 protected function doMigrateUserOptions() {
1193 if ( $this->db
->tableExists( 'user_properties' ) ) {
1194 $cl = $this->maintenance
->runChild( ConvertUserOptions
::class, 'convertUserOptions.php' );
1196 $this->output( "done.\n" );
1201 * Enable profiling table when it's turned on
1203 protected function doEnableProfiling() {
1206 if ( !$this->doTable( 'profiling' ) ) {
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;
1220 if ( $profileToDb && !$this->db
->tableExists( 'profiling', __METHOD__
) ) {
1221 $this->applyPatch( 'patch-profiling.sql', false, 'Add profiling table' );
1226 * Rebuilds the localisation cache
1228 protected function rebuildLocalisationCache() {
1230 * @var RebuildLocalisationCache $cl
1232 $cl = $this->maintenance
->runChild(
1233 RebuildLocalisationCache
::class, 'rebuildLocalisationCache.php'
1235 $this->output( "Rebuilding localisation cache...\n" );
1238 $this->output( "done.\n" );
1242 * Turns off content handler fields during parts of the upgrade
1243 * where they aren't available.
1245 protected function disableContentHandlerUseDB() {
1246 global $wgContentHandlerUseDB;
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;
1256 * Turns content handler fields back on.
1258 protected function enableContentHandlerUseDB() {
1259 global $wgContentHandlerUseDB;
1261 if ( $this->holdContentHandlerUseDB
) {
1262 $this->output( "Content Handler DB fields should be usable now.\n" );
1263 $wgContentHandlerUseDB = $this->holdContentHandlerUseDB
;
1268 * Migrate comments to the new 'comment' table
1271 protected function migrateComments() {
1272 if ( !$this->updateRowExists( 'MigrateComments' ) ) {
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"
1278 $task = $this->maintenance
->runChild( MigrateComments
::class, 'migrateComments.php' );
1279 $ok = $task->execute();
1280 $this->output( $ok ?
"done.\n" : "errors were encountered.\n" );
1285 * Merge `image_comment_temp` into the `image` table
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'
1295 $ok = $task->execute();
1296 $this->output( $ok ?
"done.\n" : "errors were encountered.\n" );
1298 $this->dropTable( 'image_comment_temp' );
1304 * Migrate actors to the new 'actor' table
1307 protected function migrateActors() {
1308 global $wgActorTableSchemaMigrationStage;
1309 if ( ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) &&
1310 !$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' );
1332 if ( $task->execute() ) {
1333 $this->applyPatch( 'patch-drop-ar_text.sql', false,
1334 'Dropping ar_text and ar_flags columns' );
1340 * Populate ar_rev_id, then make it not nullable
1343 protected function populateArchiveRevId() {
1344 $info = $this->db
->fieldInfo( 'archive', 'ar_rev_id', __METHOD__
);
1346 throw new MWException( 'Missing ar_rev_id field of archive table. Should not happen.' );
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' );
1359 * Populates the externallinks.el_index_60 field
1362 protected function populateExternallinksIndex60() {
1363 if ( !$this->updateRowExists( 'populate externallinks.el_index_60' ) ) {
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"
1369 $task = $this->maintenance
->runChild( 'PopulateExternallinksIndex60',
1370 'populateExternallinksIndex60.php' );
1372 $this->output( "done.\n" );
1377 * Populates the MCR content tables
1380 protected function populateContentTables() {
1381 global $wgMultiContentRevisionSchemaMigrationStage;
1382 if ( ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) &&
1383 !$this->updateRowExists( 'PopulateContentTables' )
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"
1390 $task = $this->maintenance
->runChild(
1391 PopulateContentTables
::class, 'populateContentTables.php'
1393 $ok = $task->execute();
1394 $this->output( $ok ?
"done.\n" : "errors were encountered.\n" );
1396 $this->insertUpdateRow( 'PopulateContentTables' );