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\Database
;
24 use Wikimedia\Rdbms\IDatabase
;
25 use Wikimedia\Rdbms\IMaintainableDatabase
;
26 use MediaWiki\MediaWikiServices
;
28 require_once __DIR__
. '/../../maintenance/Maintenance.php';
31 * Class for handling database updates. Roughly based off of updaters.inc, with
32 * a few improvements :)
37 abstract class DatabaseUpdater
{
38 const REPLICATION_WAIT_TIMEOUT
= 300;
41 * Array of updates to perform on the database
45 protected $updates = [];
48 * Array of updates that were skipped
52 protected $updatesSkipped = [];
55 * List of extension-provided database updates
58 protected $extensionUpdates = [];
61 * Handle to the database subclass
70 protected $maintenance;
72 protected $shared = false;
75 * @var string[] Scripts to run after database update
76 * Should be a subclass of LoggedUpdateMaintenance
78 protected $postDatabaseUpdateMaintenance = [
79 DeleteDefaultMessages
::class,
80 PopulateRevisionLength
::class,
81 PopulateRevisionSha1
::class,
82 PopulateImageSha1
::class,
83 FixExtLinksProtocolRelative
::class,
84 PopulateFilearchiveSha1
::class,
85 PopulateBacklinkNamespace
::class,
86 FixDefaultJsonContentPages
::class,
87 CleanupEmptyCategories
::class,
88 AddRFCandPMIDInterwiki
::class,
89 PopulatePPSortKey
::class,
90 PopulateIpChanges
::class,
91 RefreshExternallinksIndex
::class,
95 * File handle for SQL output.
99 protected $fileHandle = null;
102 * Flag specifying whether or not to skip schema (e.g. SQL-only) updates.
106 protected $skipSchema = false;
109 * Hold the value of $wgContentHandlerUseDB during the upgrade.
111 protected $holdContentHandlerUseDB = true;
114 * @param Database &$db To perform updates on
115 * @param bool $shared Whether to perform updates on shared tables
116 * @param Maintenance|null $maintenance Maintenance object which created us
118 protected function __construct( Database
&$db, $shared, Maintenance
$maintenance = null ) {
120 $this->db
->setFlag( DBO_DDLMODE
); // For Oracle's handling of schema files
121 $this->shared
= $shared;
122 if ( $maintenance ) {
123 $this->maintenance
= $maintenance;
124 $this->fileHandle
= $maintenance->fileHandle
;
126 $this->maintenance
= new FakeMaintenance
;
128 $this->maintenance
->setDB( $db );
129 $this->initOldGlobals();
130 $this->loadExtensions();
131 Hooks
::run( 'LoadExtensionSchemaUpdates', [ $this ] );
135 * Initialize all of the old globals. One day this should all become
136 * something much nicer
138 private function initOldGlobals() {
139 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
140 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
142 # For extensions only, should be populated via hooks
143 # $wgDBtype should be checked to specify the proper file
144 $wgExtNewTables = []; // table, dir
145 $wgExtNewFields = []; // table, column, dir
146 $wgExtPGNewFields = []; // table, column, column attributes; for PostgreSQL
147 $wgExtPGAlteredFields = []; // table, column, new type, conversion method; for PostgreSQL
148 $wgExtNewIndexes = []; // table, index, dir
149 $wgExtModifiedFields = []; // table, index, dir
153 * Loads LocalSettings.php, if needed, and initialises everything needed for
154 * LoadExtensionSchemaUpdates hook.
156 private function loadExtensions() {
157 if ( !defined( 'MEDIAWIKI_INSTALL' ) ||
defined( 'MW_EXTENSIONS_LOADED' ) ) {
158 return; // already loaded
160 $vars = Installer
::getExistingLocalSettings();
162 $registry = ExtensionRegistry
::getInstance();
163 $queue = $registry->getQueue();
164 // Don't accidentally load extensions in the future
165 $registry->clearQueue();
167 // This will automatically add "AutoloadClasses" to $wgAutoloadClasses
168 $data = $registry->readFromQueue( $queue );
169 $hooks = $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ??
[];
170 if ( $vars && isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
171 $hooks = array_merge_recursive( $hooks, $vars['wgHooks']['LoadExtensionSchemaUpdates'] );
173 global $wgHooks, $wgAutoloadClasses;
174 $wgHooks['LoadExtensionSchemaUpdates'] = $hooks;
175 if ( $vars && isset( $vars['wgAutoloadClasses'] ) ) {
176 $wgAutoloadClasses +
= $vars['wgAutoloadClasses'];
181 * @param IMaintainableDatabase $db
182 * @param bool $shared
183 * @param Maintenance|null $maintenance
185 * @throws MWException
186 * @return DatabaseUpdater
188 public static function newForDB(
189 IMaintainableDatabase
$db,
191 Maintenance
$maintenance = null
193 $type = $db->getType();
194 if ( in_array( $type, Installer
::getDBTypes() ) ) {
195 $class = ucfirst( $type ) . 'Updater';
197 return new $class( $db, $shared, $maintenance );
199 throw new MWException( __METHOD__
. ' called for unsupported $wgDBtype' );
204 * Get a database connection to run updates
208 public function getDB() {
213 * Output some text. If we're running from web, escape the text first.
215 * @param string $str Text to output
216 * @param-taint $str escapes_html
218 public function output( $str ) {
219 if ( $this->maintenance
->isQuiet() ) {
222 global $wgCommandLineMode;
223 if ( !$wgCommandLineMode ) {
224 $str = htmlspecialchars( $str );
231 * Add a new update coming from an extension. This should be called by
232 * extensions while executing the LoadExtensionSchemaUpdates hook.
236 * @param array $update The update to run. Format is [ $callback, $params... ]
237 * $callback is the method to call; either a DatabaseUpdater method name or a callable.
238 * Must be serializable (ie. no anonymous functions allowed). The rest of the parameters
239 * (if any) will be passed to the callback. The first parameter passed to the callback
240 * is always this object.
242 public function addExtensionUpdate( array $update ) {
243 $this->extensionUpdates
[] = $update;
247 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
248 * is the most common usage of updaters in an extension)
252 * @param string $tableName Name of table to create
253 * @param string $sqlPath Full path to the schema file
255 public function addExtensionTable( $tableName, $sqlPath ) {
256 $this->extensionUpdates
[] = [ 'addTable', $tableName, $sqlPath, true ];
262 * @param string $tableName
263 * @param string $indexName
264 * @param string $sqlPath
266 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
267 $this->extensionUpdates
[] = [ 'addIndex', $tableName, $indexName, $sqlPath, true ];
274 * @param string $tableName
275 * @param string $columnName
276 * @param string $sqlPath
278 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
279 $this->extensionUpdates
[] = [ 'addField', $tableName, $columnName, $sqlPath, true ];
286 * @param string $tableName
287 * @param string $columnName
288 * @param string $sqlPath
290 public function dropExtensionField( $tableName, $columnName, $sqlPath ) {
291 $this->extensionUpdates
[] = [ 'dropField', $tableName, $columnName, $sqlPath, true ];
295 * Drop an index from an extension table
299 * @param string $tableName The table name
300 * @param string $indexName The index name
301 * @param string $sqlPath The path to the SQL change path
303 public function dropExtensionIndex( $tableName, $indexName, $sqlPath ) {
304 $this->extensionUpdates
[] = [ 'dropIndex', $tableName, $indexName, $sqlPath, true ];
311 * @param string $tableName
312 * @param string $sqlPath
314 public function dropExtensionTable( $tableName, $sqlPath ) {
315 $this->extensionUpdates
[] = [ 'dropTable', $tableName, $sqlPath, true ];
319 * Rename an index on an extension table
323 * @param string $tableName The table name
324 * @param string $oldIndexName The old index name
325 * @param string $newIndexName The new index name
326 * @param string $sqlPath The path to the SQL change path
327 * @param bool $skipBothIndexExistWarning Whether to warn if both the old
328 * and the new indexes exist. [facultative; by default, false]
330 public function renameExtensionIndex( $tableName, $oldIndexName, $newIndexName,
331 $sqlPath, $skipBothIndexExistWarning = false
333 $this->extensionUpdates
[] = [
338 $skipBothIndexExistWarning,
347 * @param string $tableName The table name
348 * @param string $fieldName The field to be modified
349 * @param string $sqlPath The path to the SQL patch
351 public function modifyExtensionField( $tableName, $fieldName, $sqlPath ) {
352 $this->extensionUpdates
[] = [ 'modifyField', $tableName, $fieldName, $sqlPath, true ];
358 * @param string $tableName The table name
359 * @param string $sqlPath The path to the SQL patch
361 public function modifyExtensionTable( $tableName, $sqlPath ) {
362 $this->extensionUpdates
[] = [ 'modifyTable', $tableName, $sqlPath, true ];
369 * @param string $tableName
372 public function tableExists( $tableName ) {
373 return ( $this->db
->tableExists( $tableName, __METHOD__
) );
377 * Add a maintenance script to be run after the database updates are complete.
379 * Script should subclass LoggedUpdateMaintenance
383 * @param string $class Name of a Maintenance subclass
385 public function addPostDatabaseUpdateMaintenance( $class ) {
386 $this->postDatabaseUpdateMaintenance
[] = $class;
390 * Get the list of extension-defined updates
394 protected function getExtensionUpdates() {
395 return $this->extensionUpdates
;
403 public function getPostDatabaseUpdateMaintenance() {
404 return $this->postDatabaseUpdateMaintenance
;
410 * Writes the schema updates desired to a file for the DB Admin to run.
411 * @param array $schemaUpdate
413 private function writeSchemaUpdateFile( array $schemaUpdate = [] ) {
414 $updates = $this->updatesSkipped
;
415 $this->updatesSkipped
= [];
417 foreach ( $updates as $funcList ) {
418 list( $func, $args, $origParams ) = $funcList;
421 $this->updatesSkipped
[] = $origParams;
426 * Get appropriate schema variables in the current database connection.
428 * This should be called after any request data has been imported, but before
429 * any write operations to the database. The result should be passed to the DB
430 * setSchemaVars() method.
435 public function getSchemaVars() {
436 return []; // DB-type specific
442 * @param array $what What updates to perform
444 public function doUpdates( array $what = [ 'core', 'extensions', 'stats' ] ) {
445 $this->db
->setSchemaVars( $this->getSchemaVars() );
447 $what = array_flip( $what );
448 $this->skipSchema
= isset( $what['noschema'] ) ||
$this->fileHandle
!== null;
449 if ( isset( $what['core'] ) ) {
450 $this->runUpdates( $this->getCoreUpdateList(), false );
452 if ( isset( $what['extensions'] ) ) {
453 $this->runUpdates( $this->getOldGlobalUpdates(), false );
454 $this->runUpdates( $this->getExtensionUpdates(), true );
457 if ( isset( $what['stats'] ) ) {
461 if ( $this->fileHandle
) {
462 $this->skipSchema
= false;
463 $this->writeSchemaUpdateFile();
468 * Helper function for doUpdates()
470 * @param array $updates Array of updates to run
471 * @param bool $passSelf Whether to pass this object we calling external functions
473 private function runUpdates( array $updates, $passSelf ) {
474 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
477 $updatesSkipped = [];
478 foreach ( $updates as $params ) {
479 $origParams = $params;
480 $func = array_shift( $params );
481 if ( !is_array( $func ) && method_exists( $this, $func ) ) {
482 $func = [ $this, $func ];
483 } elseif ( $passSelf ) {
484 array_unshift( $params, $this );
486 $ret = $func( ...$params );
488 if ( $ret !== false ) {
489 $updatesDone[] = $origParams;
490 $lbFactory->waitForReplication( [ 'timeout' => self
::REPLICATION_WAIT_TIMEOUT
] );
492 $updatesSkipped[] = [ $func, $params, $origParams ];
495 $this->updatesSkipped
= array_merge( $this->updatesSkipped
, $updatesSkipped );
496 $this->updates
= array_merge( $this->updates
, $updatesDone );
500 * Helper function: check if the given key is present in the updatelog table.
501 * Obviously, only use this for updates that occur after the updatelog table was
503 * @param string $key Name of the key to check for
506 public function updateRowExists( $key ) {
507 $row = $this->db
->selectRow(
511 [ 'ul_key' => $key ],
519 * Helper function: Add a key to the updatelog table
520 * Obviously, only use this for updates that occur after the updatelog table was
522 * @param string $key Name of key to insert
523 * @param string|null $val [optional] Value to insert along with the key
525 public function insertUpdateRow( $key, $val = null ) {
526 $this->db
->clearFlag( DBO_DDLMODE
);
527 $values = [ 'ul_key' => $key ];
528 if ( $val && $this->canUseNewUpdatelog() ) {
529 $values['ul_value'] = $val;
531 $this->db
->insert( 'updatelog', $values, __METHOD__
, 'IGNORE' );
532 $this->db
->setFlag( DBO_DDLMODE
);
536 * Updatelog was changed in 1.17 to have a ul_value column so we can record
537 * more information about what kind of updates we've done (that's what this
538 * class does). Pre-1.17 wikis won't have this column, and really old wikis
539 * might not even have updatelog at all
543 protected function canUseNewUpdatelog() {
544 return $this->db
->tableExists( 'updatelog', __METHOD__
) &&
545 $this->db
->fieldExists( 'updatelog', 'ul_value', __METHOD__
);
549 * Returns whether updates should be executed on the database table $name.
550 * Updates will be prevented if the table is a shared table and it is not
551 * specified to run updates on shared tables.
553 * @param string $name Table name
556 protected function doTable( $name ) {
557 global $wgSharedDB, $wgSharedTables;
559 // Don't bother to check $wgSharedTables if there isn't a shared database
560 // or the user actually also wants to do updates on the shared database.
561 if ( $wgSharedDB === null ||
$this->shared
) {
565 if ( in_array( $name, $wgSharedTables ) ) {
566 $this->output( "...skipping update to shared table $name.\n" );
574 * Before 1.17, we used to handle updates via stuff like
575 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
576 * of this in 1.17 but we want to remain back-compatible for a while. So
577 * load up these old global-based things into our update list.
581 protected function getOldGlobalUpdates() {
582 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
587 foreach ( $wgExtNewTables as $tableRecord ) {
589 'addTable', $tableRecord[0], $tableRecord[1], true
593 foreach ( $wgExtNewFields as $fieldRecord ) {
595 'addField', $fieldRecord[0], $fieldRecord[1],
596 $fieldRecord[2], true
600 foreach ( $wgExtNewIndexes as $fieldRecord ) {
602 'addIndex', $fieldRecord[0], $fieldRecord[1],
603 $fieldRecord[2], true
607 foreach ( $wgExtModifiedFields as $fieldRecord ) {
609 'modifyField', $fieldRecord[0], $fieldRecord[1],
610 $fieldRecord[2], true
618 * Get an array of updates to perform on the database. Should return a
619 * multi-dimensional array. The main key is the MediaWiki version (1.12,
620 * 1.13...) with the values being arrays of updates, identical to how
621 * updaters.inc did it (for now)
625 abstract protected function getCoreUpdateList();
628 * Append an SQL fragment to the open file handle.
630 * @param string $filename File name to open
632 public function copyFile( $filename ) {
633 $this->db
->sourceFile(
638 [ $this, 'appendLine' ]
643 * Append a line to the open filehandle. The line is assumed to
644 * be a complete SQL statement.
646 * This is used as a callback for sourceLine().
648 * @param string $line Text to append to the file
649 * @return bool False to skip actually executing the file
650 * @throws MWException
652 public function appendLine( $line ) {
653 $line = rtrim( $line ) . ";\n";
654 if ( fwrite( $this->fileHandle
, $line ) === false ) {
655 throw new MWException( "trouble writing file" );
662 * Applies a SQL patch
664 * @param string $path Path to the patch file
665 * @param bool $isFullPath Whether to treat $path as a relative or not
666 * @param string|null $msg Description of the patch
667 * @return bool False if patch is skipped.
669 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
670 if ( $msg === null ) {
671 $msg = "Applying $path patch";
673 if ( $this->skipSchema
) {
674 $this->output( "...skipping schema change ($msg).\n" );
679 $this->output( "$msg ..." );
681 if ( !$isFullPath ) {
682 $path = $this->patchPath( $this->db
, $path );
684 if ( $this->fileHandle
!== null ) {
685 $this->copyFile( $path );
687 $this->db
->sourceFile( $path );
689 $this->output( "done.\n" );
695 * Get the full path of a patch file. Originally based on archive()
696 * from updaters.inc. Keep in mind this always returns a patch, as
697 * it fails back to MySQL if no DB-specific patch can be found
699 * @param IDatabase $db
700 * @param string $patch The name of the patch, like patch-something.sql
701 * @return string Full path to patch file
703 public function patchPath( IDatabase
$db, $patch ) {
706 $dbType = $db->getType();
707 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
708 return "$IP/maintenance/$dbType/archives/$patch";
710 return "$IP/maintenance/archives/$patch";
715 * Add a new table to the database
717 * @param string $name Name of the new table
718 * @param string $patch Path to the patch file
719 * @param bool $fullpath Whether to treat $patch path as a relative or not
720 * @return bool False if this was skipped because schema changes are skipped
722 protected function addTable( $name, $patch, $fullpath = false ) {
723 if ( !$this->doTable( $name ) ) {
727 if ( $this->db
->tableExists( $name, __METHOD__
) ) {
728 $this->output( "...$name table already exists.\n" );
730 return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
737 * Add a new field to an existing table
739 * @param string $table Name of the table to modify
740 * @param string $field Name of the new field
741 * @param string $patch Path to the patch file
742 * @param bool $fullpath Whether to treat $patch path as a relative or not
743 * @return bool False if this was skipped because schema changes are skipped
745 protected function addField( $table, $field, $patch, $fullpath = false ) {
746 if ( !$this->doTable( $table ) ) {
750 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
751 $this->output( "...$table table does not exist, skipping new field patch.\n" );
752 } elseif ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
753 $this->output( "...have $field field in $table table.\n" );
755 return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
762 * Add a new index to an existing table
764 * @param string $table Name of the table to modify
765 * @param string $index Name of the new index
766 * @param string $patch Path to the patch file
767 * @param bool $fullpath Whether to treat $patch path as a relative or not
768 * @return bool False if this was skipped because schema changes are skipped
770 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
771 if ( !$this->doTable( $table ) ) {
775 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
776 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
777 } elseif ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
778 $this->output( "...index $index already set on $table table.\n" );
780 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
787 * Add a new index to an existing table if none of the given indexes exist
789 * @param string $table Name of the table to modify
790 * @param string[] $indexes Name of the indexes to check. $indexes[0] should
791 * be the one actually being added.
792 * @param string $patch Path to the patch file
793 * @param bool $fullpath Whether to treat $patch path as a relative or not
794 * @return bool False if this was skipped because schema changes are skipped
796 protected function addIndexIfNoneExist( $table, $indexes, $patch, $fullpath = false ) {
797 if ( !$this->doTable( $table ) ) {
801 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
802 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
806 $newIndex = $indexes[0];
807 foreach ( $indexes as $index ) {
808 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
810 "...skipping index $newIndex because index $index already set on $table table.\n"
816 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
820 * Drop a field from an existing table
822 * @param string $table Name of the table to modify
823 * @param string $field Name of the old field
824 * @param string $patch Path to the patch file
825 * @param bool $fullpath Whether to treat $patch path as a relative or not
826 * @return bool False if this was skipped because schema changes are skipped
828 protected function dropField( $table, $field, $patch, $fullpath = false ) {
829 if ( !$this->doTable( $table ) ) {
833 if ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
834 return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
836 $this->output( "...$table table does not contain $field field.\n" );
843 * Drop an index from an existing table
845 * @param string $table Name of the table to modify
846 * @param string $index Name of the index
847 * @param string $patch Path to the patch file
848 * @param bool $fullpath Whether to treat $patch path as a relative or not
849 * @return bool False if this was skipped because schema changes are skipped
851 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
852 if ( !$this->doTable( $table ) ) {
856 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
857 return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
859 $this->output( "...$index key doesn't exist.\n" );
866 * Rename an index from an existing table
868 * @param string $table Name of the table to modify
869 * @param string $oldIndex Old name of the index
870 * @param string $newIndex New name of the index
871 * @param bool $skipBothIndexExistWarning Whether to warn if both the
872 * old and the new indexes exist.
873 * @param string $patch Path to the patch file
874 * @param bool $fullpath Whether to treat $patch path as a relative or not
875 * @return bool False if this was skipped because schema changes are skipped
877 protected function renameIndex( $table, $oldIndex, $newIndex,
878 $skipBothIndexExistWarning, $patch, $fullpath = false
880 if ( !$this->doTable( $table ) ) {
884 // First requirement: the table must exist
885 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
886 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
891 // Second requirement: the new index must be missing
892 if ( $this->db
->indexExists( $table, $newIndex, __METHOD__
) ) {
893 $this->output( "...index $newIndex already set on $table table.\n" );
894 if ( !$skipBothIndexExistWarning &&
895 $this->db
->indexExists( $table, $oldIndex, __METHOD__
)
897 $this->output( "...WARNING: $oldIndex still exists, despite it has " .
898 "been renamed into $newIndex (which also exists).\n" .
899 " $oldIndex should be manually removed if not needed anymore.\n" );
905 // Third requirement: the old index must exist
906 if ( !$this->db
->indexExists( $table, $oldIndex, __METHOD__
) ) {
907 $this->output( "...skipping: index $oldIndex doesn't exist.\n" );
912 // Requirements have been satisfied, patch can be applied
913 return $this->applyPatch(
916 "Renaming index $oldIndex into $newIndex to table $table"
921 * If the specified table exists, drop it, or execute the
922 * patch if one is provided.
926 * @param string $table Table to drop.
927 * @param string|bool $patch String of patch file that will drop the table. Default: false.
928 * @param bool $fullpath Whether $patch is a full path. Default: false.
929 * @return bool False if this was skipped because schema changes are skipped
931 public function dropTable( $table, $patch = false, $fullpath = false ) {
932 if ( !$this->doTable( $table ) ) {
936 if ( $this->db
->tableExists( $table, __METHOD__
) ) {
937 $msg = "Dropping table $table";
939 if ( $patch === false ) {
940 $this->output( "$msg ..." );
941 $this->db
->dropTable( $table, __METHOD__
);
942 $this->output( "done.\n" );
944 return $this->applyPatch( $patch, $fullpath, $msg );
947 $this->output( "...$table doesn't exist.\n" );
954 * Modify an existing field
956 * @param string $table Name of the table to which the field belongs
957 * @param string $field Name of the field to modify
958 * @param string $patch Path to the patch file
959 * @param bool $fullpath Whether to treat $patch path as a relative or not
960 * @return bool False if this was skipped because schema changes are skipped
962 public function modifyField( $table, $field, $patch, $fullpath = false ) {
963 if ( !$this->doTable( $table ) ) {
967 $updateKey = "$table-$field-$patch";
968 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
969 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
970 } elseif ( !$this->db
->fieldExists( $table, $field, __METHOD__
) ) {
971 $this->output( "...$field field does not exist in $table table, " .
972 "skipping modify field patch.\n" );
973 } elseif ( $this->updateRowExists( $updateKey ) ) {
974 $this->output( "...$field in table $table already modified by patch $patch.\n" );
976 $apply = $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
978 $this->insertUpdateRow( $updateKey );
986 * Modify an existing table, similar to modifyField. Intended for changes that
987 * touch more than one column on a table.
989 * @param string $table Name of the table to modify
990 * @param string $patch Name of the patch file to apply
991 * @param string|bool $fullpath Whether to treat $patch path as relative or not, defaults to false
992 * @return bool False if this was skipped because of schema changes being skipped
994 public function modifyTable( $table, $patch, $fullpath = false ) {
995 if ( !$this->doTable( $table ) ) {
999 $updateKey = "$table-$patch";
1000 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
1001 $this->output( "...$table table does not exist, skipping modify table patch.\n" );
1002 } elseif ( $this->updateRowExists( $updateKey ) ) {
1003 $this->output( "...table $table already modified by patch $patch.\n" );
1005 $apply = $this->applyPatch( $patch, $fullpath, "Modifying table $table" );
1007 $this->insertUpdateRow( $updateKey );
1015 * Run a maintenance script
1017 * This should only be used when the maintenance script must run before
1018 * later updates. If later updates don't depend on the script, add it to
1019 * DatabaseUpdater::$postDatabaseUpdateMaintenance instead.
1021 * The script's execute() method must return true to indicate successful
1022 * completion, and must return false (or throw an exception) to indicate
1023 * unsuccessful completion.
1026 * @param string $class Maintenance subclass
1027 * @param string $script Script path and filename, usually "maintenance/fooBar.php"
1029 public function runMaintenance( $class, $script ) {
1030 $this->output( "Running $script...\n" );
1031 $task = $this->maintenance
->runChild( $class );
1032 $ok = $task->execute();
1034 throw new RuntimeException( "Execution of $script did not complete successfully." );
1036 $this->output( "done.\n" );
1040 * Set any .htaccess files or equivilent for storage repos
1042 * Some zones (e.g. "temp") used to be public and may have been initialized as such
1044 public function setFileAccess() {
1045 $repo = RepoGroup
::singleton()->getLocalRepo();
1046 $zonePath = $repo->getZonePath( 'temp' );
1047 if ( $repo->getBackend()->directoryExists( [ 'dir' => $zonePath ] ) ) {
1048 // If the directory was never made, then it will have the right ACLs when it is made
1049 $status = $repo->getBackend()->secure( [
1054 if ( $status->isOK() ) {
1055 $this->output( "Set the local repo temp zone container to be private.\n" );
1057 $this->output( "Failed to set the local repo temp zone container to be private.\n" );
1063 * Purge various database caches
1065 public function purgeCache() {
1066 global $wgLocalisationCacheConf;
1067 // We can't guarantee that the user will be able to use TRUNCATE,
1068 // but we know that DELETE is available to us
1069 $this->output( "Purging caches..." );
1072 $this->db
->delete( 'objectcache', '*', __METHOD__
);
1074 // LocalisationCache
1075 if ( $wgLocalisationCacheConf['manualRecache'] ) {
1076 $this->rebuildLocalisationCache();
1079 // ResourceLoader: Message cache
1080 $blobStore = new MessageBlobStore(
1081 MediaWikiServices
::getInstance()->getResourceLoader()
1083 $blobStore->clear();
1085 // ResourceLoader: File-dependency cache
1086 $this->db
->delete( 'module_deps', '*', __METHOD__
);
1087 $this->output( "done.\n" );
1091 * Check the site_stats table is not properly populated.
1093 protected function checkStats() {
1094 $this->output( "...site_stats is populated..." );
1095 $row = $this->db
->selectRow( 'site_stats', '*', [ 'ss_row_id' => 1 ], __METHOD__
);
1096 if ( $row === false ) {
1097 $this->output( "data is missing! rebuilding...\n" );
1098 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
1099 $this->output( "missing ss_total_pages, rebuilding...\n" );
1101 $this->output( "done.\n" );
1105 SiteStatsInit
::doAllAndCommit( $this->db
);
1108 # Common updater functions
1111 * Sets the number of active users in the site_stats table
1113 protected function doActiveUsersInit() {
1114 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', '', __METHOD__
);
1115 if ( $activeUsers == -1 ) {
1116 $activeUsers = $this->db
->selectField( 'recentchanges',
1117 'COUNT( DISTINCT rc_user_text )',
1118 [ 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ], __METHOD__
1120 $this->db
->update( 'site_stats',
1121 [ 'ss_active_users' => intval( $activeUsers ) ],
1122 [ 'ss_row_id' => 1 ], __METHOD__
, [ 'LIMIT' => 1 ]
1125 $this->output( "...ss_active_users user count set...\n" );
1129 * Populates the log_user_text field in the logging table
1131 protected function doLogUsertextPopulation() {
1132 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
1134 "Populating log_user_text field, printing progress markers. For large\n" .
1135 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1136 "maintenance/populateLogUsertext.php.\n"
1139 $task = $this->maintenance
->runChild( PopulateLogUsertext
::class );
1141 $this->output( "done.\n" );
1146 * Migrate log params to new table and index for searching
1148 protected function doLogSearchPopulation() {
1149 if ( !$this->updateRowExists( 'populate log_search' ) ) {
1151 "Populating log_search table, printing progress markers. For large\n" .
1152 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1153 "maintenance/populateLogSearch.php.\n" );
1155 $task = $this->maintenance
->runChild( PopulateLogSearch
::class );
1157 $this->output( "done.\n" );
1162 * Update CategoryLinks collation
1164 protected function doCollationUpdate() {
1165 global $wgCategoryCollation;
1166 if ( $this->db
->fieldExists( 'categorylinks', 'cl_collation', __METHOD__
) ) {
1167 if ( $this->db
->selectField(
1170 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
1174 $this->output( "...collations up-to-date.\n" );
1179 $this->output( "Updating category collations..." );
1180 $task = $this->maintenance
->runChild( UpdateCollation
::class );
1182 $this->output( "...done.\n" );
1187 * Migrates user options from the user table blob to user_properties
1189 protected function doMigrateUserOptions() {
1190 if ( $this->db
->tableExists( 'user_properties' ) ) {
1191 $cl = $this->maintenance
->runChild( ConvertUserOptions
::class, 'convertUserOptions.php' );
1193 $this->output( "done.\n" );
1198 * Enable profiling table when it's turned on
1200 protected function doEnableProfiling() {
1203 if ( !$this->doTable( 'profiling' ) ) {
1207 $profileToDb = false;
1208 if ( isset( $wgProfiler['output'] ) ) {
1209 $out = $wgProfiler['output'];
1210 if ( $out === 'db' ) {
1211 $profileToDb = true;
1212 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
1213 $profileToDb = true;
1217 if ( $profileToDb && !$this->db
->tableExists( 'profiling', __METHOD__
) ) {
1218 $this->applyPatch( 'patch-profiling.sql', false, 'Add profiling table' );
1223 * Rebuilds the localisation cache
1225 protected function rebuildLocalisationCache() {
1227 * @var $cl RebuildLocalisationCache
1229 $cl = $this->maintenance
->runChild(
1230 RebuildLocalisationCache
::class, 'rebuildLocalisationCache.php'
1232 $this->output( "Rebuilding localisation cache...\n" );
1235 $this->output( "done.\n" );
1239 * Turns off content handler fields during parts of the upgrade
1240 * where they aren't available.
1242 protected function disableContentHandlerUseDB() {
1243 global $wgContentHandlerUseDB;
1245 if ( $wgContentHandlerUseDB ) {
1246 $this->output( "Turning off Content Handler DB fields for this part of upgrade.\n" );
1247 $this->holdContentHandlerUseDB
= $wgContentHandlerUseDB;
1248 $wgContentHandlerUseDB = false;
1253 * Turns content handler fields back on.
1255 protected function enableContentHandlerUseDB() {
1256 global $wgContentHandlerUseDB;
1258 if ( $this->holdContentHandlerUseDB
) {
1259 $this->output( "Content Handler DB fields should be usable now.\n" );
1260 $wgContentHandlerUseDB = $this->holdContentHandlerUseDB
;
1265 * Migrate comments to the new 'comment' table
1268 protected function migrateComments() {
1269 if ( !$this->updateRowExists( 'MigrateComments' ) ) {
1271 "Migrating comments to the 'comments' table, printing progress markers. For large\n" .
1272 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1273 "maintenance/migrateComments.php.\n"
1275 $task = $this->maintenance
->runChild( MigrateComments
::class, 'migrateComments.php' );
1276 $ok = $task->execute();
1277 $this->output( $ok ?
"done.\n" : "errors were encountered.\n" );
1282 * Merge `image_comment_temp` into the `image` table
1285 protected function migrateImageCommentTemp() {
1286 if ( $this->tableExists( 'image_comment_temp' ) ) {
1287 $this->output( "Merging image_comment_temp into the image table\n" );
1288 $task = $this->maintenance
->runChild(
1289 MigrateImageCommentTemp
::class, 'migrateImageCommentTemp.php'
1292 $ok = $task->execute();
1293 $this->output( $ok ?
"done.\n" : "errors were encountered.\n" );
1295 $this->dropTable( 'image_comment_temp' );
1301 * Migrate actors to the new 'actor' table
1304 protected function migrateActors() {
1305 global $wgActorTableSchemaMigrationStage;
1306 if ( ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) &&
1307 !$this->updateRowExists( 'MigrateActors' )
1310 "Migrating actors to the 'actor' table, printing progress markers. For large\n" .
1311 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1312 "maintenance/migrateActors.php.\n"
1314 $task = $this->maintenance
->runChild( 'MigrateActors', 'migrateActors.php' );
1315 $ok = $task->execute();
1316 $this->output( $ok ?
"done.\n" : "errors were encountered.\n" );
1321 * Migrate ar_text to modern storage
1324 protected function migrateArchiveText() {
1325 if ( $this->db
->fieldExists( 'archive', 'ar_text', __METHOD__
) ) {
1326 $this->output( "Migrating archive ar_text to modern storage.\n" );
1327 $task = $this->maintenance
->runChild( MigrateArchiveText
::class, 'migrateArchiveText.php' );
1329 if ( $task->execute() ) {
1330 $this->applyPatch( 'patch-drop-ar_text.sql', false,
1331 'Dropping ar_text and ar_flags columns' );
1337 * Populate ar_rev_id, then make it not nullable
1340 protected function populateArchiveRevId() {
1341 $info = $this->db
->fieldInfo( 'archive', 'ar_rev_id', __METHOD__
);
1343 throw new MWException( 'Missing ar_rev_id field of archive table. Should not happen.' );
1345 if ( $info->isNullable() ) {
1346 $this->output( "Populating ar_rev_id.\n" );
1347 $task = $this->maintenance
->runChild( 'PopulateArchiveRevId', 'populateArchiveRevId.php' );
1348 if ( $task->execute() ) {
1349 $this->applyPatch( 'patch-ar_rev_id-not-null.sql', false,
1350 'Making ar_rev_id not nullable' );
1356 * Populates the externallinks.el_index_60 field
1359 protected function populateExternallinksIndex60() {
1360 if ( !$this->updateRowExists( 'populate externallinks.el_index_60' ) ) {
1362 "Populating el_index_60 field, printing progress markers. For large\n" .
1363 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1364 "maintenance/populateExternallinksIndex60.php.\n"
1366 $task = $this->maintenance
->runChild( 'PopulateExternallinksIndex60',
1367 'populateExternallinksIndex60.php' );
1369 $this->output( "done.\n" );
1374 * Populates the MCR content tables
1377 protected function populateContentTables() {
1378 global $wgMultiContentRevisionSchemaMigrationStage;
1379 if ( ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) &&
1380 !$this->updateRowExists( 'PopulateContentTables' )
1383 "Migrating revision data to the MCR 'slot' and 'content' tables, printing progress markers.\n" .
1384 "For large databases, you may want to hit Ctrl-C and do this manually with\n" .
1385 "maintenance/populateContentTables.php.\n"
1387 $task = $this->maintenance
->runChild(
1388 PopulateContentTables
::class, 'populateContentTables.php'
1390 $ok = $task->execute();
1391 $this->output( $ok ?
"done.\n" : "errors were encountered.\n" );
1393 $this->insertUpdateRow( 'PopulateContentTables' );