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 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
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 Database &$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( Database
&$db, $shared, Maintenance
$maintenance = null ) {
119 $this->db
->setFlag( DBO_DDLMODE
); // For Oracle's handling of schema files
120 $this->shared
= $shared;
121 if ( $maintenance ) {
122 $this->maintenance
= $maintenance;
123 $this->fileHandle
= $maintenance->fileHandle
;
125 $this->maintenance
= new FakeMaintenance
;
127 $this->maintenance
->setDB( $db );
128 $this->initOldGlobals();
129 $this->loadExtensions();
130 Hooks
::run( 'LoadExtensionSchemaUpdates', [ $this ] );
134 * Initialize all of the old globals. One day this should all become
135 * something much nicer
137 private function initOldGlobals() {
138 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
139 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
141 # For extensions only, should be populated via hooks
142 # $wgDBtype should be checked to specify the proper file
143 $wgExtNewTables = []; // table, dir
144 $wgExtNewFields = []; // table, column, dir
145 $wgExtPGNewFields = []; // table, column, column attributes; for PostgreSQL
146 $wgExtPGAlteredFields = []; // table, column, new type, conversion method; for PostgreSQL
147 $wgExtNewIndexes = []; // table, index, dir
148 $wgExtModifiedFields = []; // table, index, dir
152 * Loads LocalSettings.php, if needed, and initialises everything needed for
153 * LoadExtensionSchemaUpdates hook.
155 private function loadExtensions() {
156 if ( !defined( 'MEDIAWIKI_INSTALL' ) ||
defined( 'MW_EXTENSIONS_LOADED' ) ) {
157 return; // already loaded
159 $vars = Installer
::getExistingLocalSettings();
161 $registry = ExtensionRegistry
::getInstance();
162 $queue = $registry->getQueue();
163 // Don't accidentally load extensions in the future
164 $registry->clearQueue();
166 // This will automatically add "AutoloadClasses" to $wgAutoloadClasses
167 $data = $registry->readFromQueue( $queue );
168 $hooks = $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ??
[];
169 if ( $vars && isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
170 $hooks = array_merge_recursive( $hooks, $vars['wgHooks']['LoadExtensionSchemaUpdates'] );
172 global $wgHooks, $wgAutoloadClasses;
173 $wgHooks['LoadExtensionSchemaUpdates'] = $hooks;
174 if ( $vars && isset( $vars['wgAutoloadClasses'] ) ) {
175 $wgAutoloadClasses +
= $vars['wgAutoloadClasses'];
180 * @param Database $db
181 * @param bool $shared
182 * @param Maintenance|null $maintenance
184 * @throws MWException
185 * @return DatabaseUpdater
187 public static function newForDB( Database
$db, $shared = false, Maintenance
$maintenance = null ) {
188 $type = $db->getType();
189 if ( in_array( $type, Installer
::getDBTypes() ) ) {
190 $class = ucfirst( $type ) . 'Updater';
192 return new $class( $db, $shared, $maintenance );
194 throw new MWException( __METHOD__
. ' called for unsupported $wgDBtype' );
199 * Get a database connection to run updates
203 public function getDB() {
208 * Output some text. If we're running from web, escape the text first.
210 * @param string $str Text to output
211 * @param-taint $str escapes_html
213 public function output( $str ) {
214 if ( $this->maintenance
->isQuiet() ) {
217 global $wgCommandLineMode;
218 if ( !$wgCommandLineMode ) {
219 $str = htmlspecialchars( $str );
226 * Add a new update coming from an extension. This should be called by
227 * extensions while executing the LoadExtensionSchemaUpdates hook.
231 * @param array $update The update to run. Format is [ $callback, $params... ]
232 * $callback is the method to call; either a DatabaseUpdater method name or a callable.
233 * Must be serializable (ie. no anonymous functions allowed). The rest of the parameters
234 * (if any) will be passed to the callback. The first parameter passed to the callback
235 * is always this object.
237 public function addExtensionUpdate( array $update ) {
238 $this->extensionUpdates
[] = $update;
242 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
243 * is the most common usage of updaters in an extension)
247 * @param string $tableName Name of table to create
248 * @param string $sqlPath Full path to the schema file
250 public function addExtensionTable( $tableName, $sqlPath ) {
251 $this->extensionUpdates
[] = [ 'addTable', $tableName, $sqlPath, true ];
257 * @param string $tableName
258 * @param string $indexName
259 * @param string $sqlPath
261 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
262 $this->extensionUpdates
[] = [ 'addIndex', $tableName, $indexName, $sqlPath, true ];
269 * @param string $tableName
270 * @param string $columnName
271 * @param string $sqlPath
273 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
274 $this->extensionUpdates
[] = [ 'addField', $tableName, $columnName, $sqlPath, true ];
281 * @param string $tableName
282 * @param string $columnName
283 * @param string $sqlPath
285 public function dropExtensionField( $tableName, $columnName, $sqlPath ) {
286 $this->extensionUpdates
[] = [ 'dropField', $tableName, $columnName, $sqlPath, true ];
290 * Drop an index from an extension table
294 * @param string $tableName The table name
295 * @param string $indexName The index name
296 * @param string $sqlPath The path to the SQL change path
298 public function dropExtensionIndex( $tableName, $indexName, $sqlPath ) {
299 $this->extensionUpdates
[] = [ 'dropIndex', $tableName, $indexName, $sqlPath, true ];
306 * @param string $tableName
307 * @param string $sqlPath
309 public function dropExtensionTable( $tableName, $sqlPath ) {
310 $this->extensionUpdates
[] = [ 'dropTable', $tableName, $sqlPath, true ];
314 * Rename an index on an extension table
318 * @param string $tableName The table name
319 * @param string $oldIndexName The old index name
320 * @param string $newIndexName The new index name
321 * @param string $sqlPath The path to the SQL change path
322 * @param bool $skipBothIndexExistWarning Whether to warn if both the old
323 * and the new indexes exist. [facultative; by default, false]
325 public function renameExtensionIndex( $tableName, $oldIndexName, $newIndexName,
326 $sqlPath, $skipBothIndexExistWarning = false
328 $this->extensionUpdates
[] = [
333 $skipBothIndexExistWarning,
342 * @param string $tableName The table name
343 * @param string $fieldName The field to be modified
344 * @param string $sqlPath The path to the SQL patch
346 public function modifyExtensionField( $tableName, $fieldName, $sqlPath ) {
347 $this->extensionUpdates
[] = [ 'modifyField', $tableName, $fieldName, $sqlPath, true ];
353 * @param string $tableName The table name
354 * @param string $sqlPath The path to the SQL patch
356 public function modifyExtensionTable( $tableName, $sqlPath ) {
357 $this->extensionUpdates
[] = [ 'modifyTable', $tableName, $sqlPath, true ];
364 * @param string $tableName
367 public function tableExists( $tableName ) {
368 return ( $this->db
->tableExists( $tableName, __METHOD__
) );
372 * Add a maintenance script to be run after the database updates are complete.
374 * Script should subclass LoggedUpdateMaintenance
378 * @param string $class Name of a Maintenance subclass
380 public function addPostDatabaseUpdateMaintenance( $class ) {
381 $this->postDatabaseUpdateMaintenance
[] = $class;
385 * Get the list of extension-defined updates
389 protected function getExtensionUpdates() {
390 return $this->extensionUpdates
;
398 public function getPostDatabaseUpdateMaintenance() {
399 return $this->postDatabaseUpdateMaintenance
;
405 * Writes the schema updates desired to a file for the DB Admin to run.
406 * @param array $schemaUpdate
408 private function writeSchemaUpdateFile( array $schemaUpdate = [] ) {
409 $updates = $this->updatesSkipped
;
410 $this->updatesSkipped
= [];
412 foreach ( $updates as $funcList ) {
413 list( $func, $args, $origParams ) = $funcList;
416 $this->updatesSkipped
[] = $origParams;
421 * Get appropriate schema variables in the current database connection.
423 * This should be called after any request data has been imported, but before
424 * any write operations to the database. The result should be passed to the DB
425 * setSchemaVars() method.
430 public function getSchemaVars() {
431 return []; // DB-type specific
437 * @param array $what What updates to perform
439 public function doUpdates( array $what = [ 'core', 'extensions', 'stats' ] ) {
440 $this->db
->setSchemaVars( $this->getSchemaVars() );
442 $what = array_flip( $what );
443 $this->skipSchema
= isset( $what['noschema'] ) ||
$this->fileHandle
!== null;
444 if ( isset( $what['core'] ) ) {
445 $this->runUpdates( $this->getCoreUpdateList(), false );
447 if ( isset( $what['extensions'] ) ) {
448 $this->runUpdates( $this->getOldGlobalUpdates(), false );
449 $this->runUpdates( $this->getExtensionUpdates(), true );
452 if ( isset( $what['stats'] ) ) {
456 if ( $this->fileHandle
) {
457 $this->skipSchema
= false;
458 $this->writeSchemaUpdateFile();
463 * Helper function for doUpdates()
465 * @param array $updates Array of updates to run
466 * @param bool $passSelf Whether to pass this object we calling external functions
468 private function runUpdates( array $updates, $passSelf ) {
469 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
472 $updatesSkipped = [];
473 foreach ( $updates as $params ) {
474 $origParams = $params;
475 $func = array_shift( $params );
476 if ( !is_array( $func ) && method_exists( $this, $func ) ) {
477 $func = [ $this, $func ];
478 } elseif ( $passSelf ) {
479 array_unshift( $params, $this );
481 $ret = $func( ...$params );
483 if ( $ret !== false ) {
484 $updatesDone[] = $origParams;
485 $lbFactory->waitForReplication( [ 'timeout' => self
::REPLICATION_WAIT_TIMEOUT
] );
487 $updatesSkipped[] = [ $func, $params, $origParams ];
490 $this->updatesSkipped
= array_merge( $this->updatesSkipped
, $updatesSkipped );
491 $this->updates
= array_merge( $this->updates
, $updatesDone );
495 * Helper function: check if the given key is present in the updatelog table.
496 * Obviously, only use this for updates that occur after the updatelog table was
498 * @param string $key Name of the key to check for
501 public function updateRowExists( $key ) {
502 $row = $this->db
->selectRow(
506 [ 'ul_key' => $key ],
514 * Helper function: Add a key to the updatelog table
515 * Obviously, only use this for updates that occur after the updatelog table was
517 * @param string $key Name of key to insert
518 * @param string|null $val [optional] Value to insert along with the key
520 public function insertUpdateRow( $key, $val = null ) {
521 $this->db
->clearFlag( DBO_DDLMODE
);
522 $values = [ 'ul_key' => $key ];
523 if ( $val && $this->canUseNewUpdatelog() ) {
524 $values['ul_value'] = $val;
526 $this->db
->insert( 'updatelog', $values, __METHOD__
, 'IGNORE' );
527 $this->db
->setFlag( DBO_DDLMODE
);
531 * Updatelog was changed in 1.17 to have a ul_value column so we can record
532 * more information about what kind of updates we've done (that's what this
533 * class does). Pre-1.17 wikis won't have this column, and really old wikis
534 * might not even have updatelog at all
538 protected function canUseNewUpdatelog() {
539 return $this->db
->tableExists( 'updatelog', __METHOD__
) &&
540 $this->db
->fieldExists( 'updatelog', 'ul_value', __METHOD__
);
544 * Returns whether updates should be executed on the database table $name.
545 * Updates will be prevented if the table is a shared table and it is not
546 * specified to run updates on shared tables.
548 * @param string $name Table name
551 protected function doTable( $name ) {
552 global $wgSharedDB, $wgSharedTables;
554 // Don't bother to check $wgSharedTables if there isn't a shared database
555 // or the user actually also wants to do updates on the shared database.
556 if ( $wgSharedDB === null ||
$this->shared
) {
560 if ( in_array( $name, $wgSharedTables ) ) {
561 $this->output( "...skipping update to shared table $name.\n" );
569 * Before 1.17, we used to handle updates via stuff like
570 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
571 * of this in 1.17 but we want to remain back-compatible for a while. So
572 * load up these old global-based things into our update list.
576 protected function getOldGlobalUpdates() {
577 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
582 foreach ( $wgExtNewTables as $tableRecord ) {
584 'addTable', $tableRecord[0], $tableRecord[1], true
588 foreach ( $wgExtNewFields as $fieldRecord ) {
590 'addField', $fieldRecord[0], $fieldRecord[1],
591 $fieldRecord[2], true
595 foreach ( $wgExtNewIndexes as $fieldRecord ) {
597 'addIndex', $fieldRecord[0], $fieldRecord[1],
598 $fieldRecord[2], true
602 foreach ( $wgExtModifiedFields as $fieldRecord ) {
604 'modifyField', $fieldRecord[0], $fieldRecord[1],
605 $fieldRecord[2], true
613 * Get an array of updates to perform on the database. Should return a
614 * multi-dimensional array. The main key is the MediaWiki version (1.12,
615 * 1.13...) with the values being arrays of updates, identical to how
616 * updaters.inc did it (for now)
620 abstract protected function getCoreUpdateList();
623 * Append an SQL fragment to the open file handle.
625 * @param string $filename File name to open
627 public function copyFile( $filename ) {
628 $this->db
->sourceFile(
633 [ $this, 'appendLine' ]
638 * Append a line to the open filehandle. The line is assumed to
639 * be a complete SQL statement.
641 * This is used as a callback for sourceLine().
643 * @param string $line Text to append to the file
644 * @return bool False to skip actually executing the file
645 * @throws MWException
647 public function appendLine( $line ) {
648 $line = rtrim( $line ) . ";\n";
649 if ( fwrite( $this->fileHandle
, $line ) === false ) {
650 throw new MWException( "trouble writing file" );
657 * Applies a SQL patch
659 * @param string $path Path to the patch file
660 * @param bool $isFullPath Whether to treat $path as a relative or not
661 * @param string|null $msg Description of the patch
662 * @return bool False if patch is skipped.
664 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
665 if ( $msg === null ) {
666 $msg = "Applying $path patch";
668 if ( $this->skipSchema
) {
669 $this->output( "...skipping schema change ($msg).\n" );
674 $this->output( "$msg ..." );
676 if ( !$isFullPath ) {
677 $path = $this->patchPath( $this->db
, $path );
679 if ( $this->fileHandle
!== null ) {
680 $this->copyFile( $path );
682 $this->db
->sourceFile( $path );
684 $this->output( "done.\n" );
690 * Get the full path of a patch file. Originally based on archive()
691 * from updaters.inc. Keep in mind this always returns a patch, as
692 * it fails back to MySQL if no DB-specific patch can be found
694 * @param IDatabase $db
695 * @param string $patch The name of the patch, like patch-something.sql
696 * @return string Full path to patch file
698 public function patchPath( IDatabase
$db, $patch ) {
701 $dbType = $db->getType();
702 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
703 return "$IP/maintenance/$dbType/archives/$patch";
705 return "$IP/maintenance/archives/$patch";
710 * Add a new table to the database
712 * @param string $name Name of the new table
713 * @param string $patch Path to the patch file
714 * @param bool $fullpath Whether to treat $patch path as a relative or not
715 * @return bool False if this was skipped because schema changes are skipped
717 protected function addTable( $name, $patch, $fullpath = false ) {
718 if ( !$this->doTable( $name ) ) {
722 if ( $this->db
->tableExists( $name, __METHOD__
) ) {
723 $this->output( "...$name table already exists.\n" );
725 return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
732 * Add a new field to an existing table
734 * @param string $table Name of the table to modify
735 * @param string $field Name of the new field
736 * @param string $patch Path to the patch file
737 * @param bool $fullpath Whether to treat $patch path as a relative or not
738 * @return bool False if this was skipped because schema changes are skipped
740 protected function addField( $table, $field, $patch, $fullpath = false ) {
741 if ( !$this->doTable( $table ) ) {
745 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
746 $this->output( "...$table table does not exist, skipping new field patch.\n" );
747 } elseif ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
748 $this->output( "...have $field field in $table table.\n" );
750 return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
757 * Add a new index to an existing table
759 * @param string $table Name of the table to modify
760 * @param string $index Name of the new index
761 * @param string $patch Path to the patch file
762 * @param bool $fullpath Whether to treat $patch path as a relative or not
763 * @return bool False if this was skipped because schema changes are skipped
765 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
766 if ( !$this->doTable( $table ) ) {
770 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
771 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
772 } elseif ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
773 $this->output( "...index $index already set on $table table.\n" );
775 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
782 * Add a new index to an existing table if none of the given indexes exist
784 * @param string $table Name of the table to modify
785 * @param string[] $indexes Name of the indexes to check. $indexes[0] should
786 * be the one actually being added.
787 * @param string $patch Path to the patch file
788 * @param bool $fullpath Whether to treat $patch path as a relative or not
789 * @return bool False if this was skipped because schema changes are skipped
791 protected function addIndexIfNoneExist( $table, $indexes, $patch, $fullpath = false ) {
792 if ( !$this->doTable( $table ) ) {
796 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
797 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
801 $newIndex = $indexes[0];
802 foreach ( $indexes as $index ) {
803 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
805 "...skipping index $newIndex because index $index already set on $table table.\n"
811 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
815 * Drop a field from an existing table
817 * @param string $table Name of the table to modify
818 * @param string $field Name of the old field
819 * @param string $patch Path to the patch file
820 * @param bool $fullpath Whether to treat $patch path as a relative or not
821 * @return bool False if this was skipped because schema changes are skipped
823 protected function dropField( $table, $field, $patch, $fullpath = false ) {
824 if ( !$this->doTable( $table ) ) {
828 if ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
829 return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
831 $this->output( "...$table table does not contain $field field.\n" );
838 * Drop an index from an existing table
840 * @param string $table Name of the table to modify
841 * @param string $index Name of the index
842 * @param string $patch Path to the patch file
843 * @param bool $fullpath Whether to treat $patch path as a relative or not
844 * @return bool False if this was skipped because schema changes are skipped
846 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
847 if ( !$this->doTable( $table ) ) {
851 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
852 return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
854 $this->output( "...$index key doesn't exist.\n" );
861 * Rename an index from an existing table
863 * @param string $table Name of the table to modify
864 * @param string $oldIndex Old name of the index
865 * @param string $newIndex New name of the index
866 * @param bool $skipBothIndexExistWarning Whether to warn if both the
867 * old and the new indexes exist.
868 * @param string $patch Path to the patch file
869 * @param bool $fullpath Whether to treat $patch path as a relative or not
870 * @return bool False if this was skipped because schema changes are skipped
872 protected function renameIndex( $table, $oldIndex, $newIndex,
873 $skipBothIndexExistWarning, $patch, $fullpath = false
875 if ( !$this->doTable( $table ) ) {
879 // First requirement: the table must exist
880 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
881 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
886 // Second requirement: the new index must be missing
887 if ( $this->db
->indexExists( $table, $newIndex, __METHOD__
) ) {
888 $this->output( "...index $newIndex already set on $table table.\n" );
889 if ( !$skipBothIndexExistWarning &&
890 $this->db
->indexExists( $table, $oldIndex, __METHOD__
)
892 $this->output( "...WARNING: $oldIndex still exists, despite it has " .
893 "been renamed into $newIndex (which also exists).\n" .
894 " $oldIndex should be manually removed if not needed anymore.\n" );
900 // Third requirement: the old index must exist
901 if ( !$this->db
->indexExists( $table, $oldIndex, __METHOD__
) ) {
902 $this->output( "...skipping: index $oldIndex doesn't exist.\n" );
907 // Requirements have been satisfied, patch can be applied
908 return $this->applyPatch(
911 "Renaming index $oldIndex into $newIndex to table $table"
916 * If the specified table exists, drop it, or execute the
917 * patch if one is provided.
921 * @param string $table Table to drop.
922 * @param string|bool $patch String of patch file that will drop the table. Default: false.
923 * @param bool $fullpath Whether $patch is a full path. Default: false.
924 * @return bool False if this was skipped because schema changes are skipped
926 public function dropTable( $table, $patch = false, $fullpath = false ) {
927 if ( !$this->doTable( $table ) ) {
931 if ( $this->db
->tableExists( $table, __METHOD__
) ) {
932 $msg = "Dropping table $table";
934 if ( $patch === false ) {
935 $this->output( "$msg ..." );
936 $this->db
->dropTable( $table, __METHOD__
);
937 $this->output( "done.\n" );
939 return $this->applyPatch( $patch, $fullpath, $msg );
942 $this->output( "...$table doesn't exist.\n" );
949 * Modify an existing field
951 * @param string $table Name of the table to which the field belongs
952 * @param string $field Name of the field to modify
953 * @param string $patch Path to the patch file
954 * @param bool $fullpath Whether to treat $patch path as a relative or not
955 * @return bool False if this was skipped because schema changes are skipped
957 public function modifyField( $table, $field, $patch, $fullpath = false ) {
958 if ( !$this->doTable( $table ) ) {
962 $updateKey = "$table-$field-$patch";
963 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
964 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
965 } elseif ( !$this->db
->fieldExists( $table, $field, __METHOD__
) ) {
966 $this->output( "...$field field does not exist in $table table, " .
967 "skipping modify field patch.\n" );
968 } elseif ( $this->updateRowExists( $updateKey ) ) {
969 $this->output( "...$field in table $table already modified by patch $patch.\n" );
971 $apply = $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
973 $this->insertUpdateRow( $updateKey );
981 * Modify an existing table, similar to modifyField. Intended for changes that
982 * touch more than one column on a table.
984 * @param string $table Name of the table to modify
985 * @param string $patch Name of the patch file to apply
986 * @param string|bool $fullpath Whether to treat $patch path as relative or not, defaults to false
987 * @return bool False if this was skipped because of schema changes being skipped
989 public function modifyTable( $table, $patch, $fullpath = false ) {
990 if ( !$this->doTable( $table ) ) {
994 $updateKey = "$table-$patch";
995 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
996 $this->output( "...$table table does not exist, skipping modify table patch.\n" );
997 } elseif ( $this->updateRowExists( $updateKey ) ) {
998 $this->output( "...table $table already modified by patch $patch.\n" );
1000 $apply = $this->applyPatch( $patch, $fullpath, "Modifying table $table" );
1002 $this->insertUpdateRow( $updateKey );
1010 * Run a maintenance script
1012 * This should only be used when the maintenance script must run before
1013 * later updates. If later updates don't depend on the script, add it to
1014 * DatabaseUpdater::$postDatabaseUpdateMaintenance instead.
1016 * The script's execute() method must return true to indicate successful
1017 * completion, and must return false (or throw an exception) to indicate
1018 * unsuccessful completion.
1021 * @param string $class Maintenance subclass
1022 * @param string $script Script path and filename, usually "maintenance/fooBar.php"
1024 public function runMaintenance( $class, $script ) {
1025 $this->output( "Running $script...\n" );
1026 $task = $this->maintenance
->runChild( $class );
1027 $ok = $task->execute();
1029 throw new RuntimeException( "Execution of $script did not complete successfully." );
1031 $this->output( "done.\n" );
1035 * Set any .htaccess files or equivilent for storage repos
1037 * Some zones (e.g. "temp") used to be public and may have been initialized as such
1039 public function setFileAccess() {
1040 $repo = RepoGroup
::singleton()->getLocalRepo();
1041 $zonePath = $repo->getZonePath( 'temp' );
1042 if ( $repo->getBackend()->directoryExists( [ 'dir' => $zonePath ] ) ) {
1043 // If the directory was never made, then it will have the right ACLs when it is made
1044 $status = $repo->getBackend()->secure( [
1049 if ( $status->isOK() ) {
1050 $this->output( "Set the local repo temp zone container to be private.\n" );
1052 $this->output( "Failed to set the local repo temp zone container to be private.\n" );
1058 * Purge various database caches
1060 public function purgeCache() {
1061 global $wgLocalisationCacheConf;
1062 // We can't guarantee that the user will be able to use TRUNCATE,
1063 // but we know that DELETE is available to us
1064 $this->output( "Purging caches..." );
1067 $this->db
->delete( 'objectcache', '*', __METHOD__
);
1069 // LocalisationCache
1070 if ( $wgLocalisationCacheConf['manualRecache'] ) {
1071 $this->rebuildLocalisationCache();
1074 // ResourceLoader: Message cache
1075 $blobStore = new MessageBlobStore(
1076 MediaWikiServices
::getInstance()->getResourceLoader()
1078 $blobStore->clear();
1080 // ResourceLoader: File-dependency cache
1081 $this->db
->delete( 'module_deps', '*', __METHOD__
);
1082 $this->output( "done.\n" );
1086 * Check the site_stats table is not properly populated.
1088 protected function checkStats() {
1089 $this->output( "...site_stats is populated..." );
1090 $row = $this->db
->selectRow( 'site_stats', '*', [ 'ss_row_id' => 1 ], __METHOD__
);
1091 if ( $row === false ) {
1092 $this->output( "data is missing! rebuilding...\n" );
1093 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
1094 $this->output( "missing ss_total_pages, rebuilding...\n" );
1096 $this->output( "done.\n" );
1100 SiteStatsInit
::doAllAndCommit( $this->db
);
1103 # Common updater functions
1106 * Sets the number of active users in the site_stats table
1108 protected function doActiveUsersInit() {
1109 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', '', __METHOD__
);
1110 if ( $activeUsers == -1 ) {
1111 $activeUsers = $this->db
->selectField( 'recentchanges',
1112 'COUNT( DISTINCT rc_user_text )',
1113 [ 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ], __METHOD__
1115 $this->db
->update( 'site_stats',
1116 [ 'ss_active_users' => intval( $activeUsers ) ],
1117 [ 'ss_row_id' => 1 ], __METHOD__
, [ 'LIMIT' => 1 ]
1120 $this->output( "...ss_active_users user count set...\n" );
1124 * Populates the log_user_text field in the logging table
1126 protected function doLogUsertextPopulation() {
1127 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
1129 "Populating log_user_text field, printing progress markers. For large\n" .
1130 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1131 "maintenance/populateLogUsertext.php.\n"
1134 $task = $this->maintenance
->runChild( PopulateLogUsertext
::class );
1136 $this->output( "done.\n" );
1141 * Migrate log params to new table and index for searching
1143 protected function doLogSearchPopulation() {
1144 if ( !$this->updateRowExists( 'populate log_search' ) ) {
1146 "Populating log_search table, printing progress markers. For large\n" .
1147 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1148 "maintenance/populateLogSearch.php.\n" );
1150 $task = $this->maintenance
->runChild( PopulateLogSearch
::class );
1152 $this->output( "done.\n" );
1157 * Update CategoryLinks collation
1159 protected function doCollationUpdate() {
1160 global $wgCategoryCollation;
1161 if ( $this->db
->fieldExists( 'categorylinks', 'cl_collation', __METHOD__
) ) {
1162 if ( $this->db
->selectField(
1165 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
1169 $this->output( "...collations up-to-date.\n" );
1174 $this->output( "Updating category collations..." );
1175 $task = $this->maintenance
->runChild( UpdateCollation
::class );
1177 $this->output( "...done.\n" );
1182 * Migrates user options from the user table blob to user_properties
1184 protected function doMigrateUserOptions() {
1185 if ( $this->db
->tableExists( 'user_properties' ) ) {
1186 $cl = $this->maintenance
->runChild( ConvertUserOptions
::class, 'convertUserOptions.php' );
1188 $this->output( "done.\n" );
1193 * Enable profiling table when it's turned on
1195 protected function doEnableProfiling() {
1198 if ( !$this->doTable( 'profiling' ) ) {
1202 $profileToDb = false;
1203 if ( isset( $wgProfiler['output'] ) ) {
1204 $out = $wgProfiler['output'];
1205 if ( $out === 'db' ) {
1206 $profileToDb = true;
1207 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
1208 $profileToDb = true;
1212 if ( $profileToDb && !$this->db
->tableExists( 'profiling', __METHOD__
) ) {
1213 $this->applyPatch( 'patch-profiling.sql', false, 'Add profiling table' );
1218 * Rebuilds the localisation cache
1220 protected function rebuildLocalisationCache() {
1222 * @var $cl RebuildLocalisationCache
1224 $cl = $this->maintenance
->runChild(
1225 RebuildLocalisationCache
::class, 'rebuildLocalisationCache.php'
1227 $this->output( "Rebuilding localisation cache...\n" );
1230 $this->output( "done.\n" );
1234 * Turns off content handler fields during parts of the upgrade
1235 * where they aren't available.
1237 protected function disableContentHandlerUseDB() {
1238 global $wgContentHandlerUseDB;
1240 if ( $wgContentHandlerUseDB ) {
1241 $this->output( "Turning off Content Handler DB fields for this part of upgrade.\n" );
1242 $this->holdContentHandlerUseDB
= $wgContentHandlerUseDB;
1243 $wgContentHandlerUseDB = false;
1248 * Turns content handler fields back on.
1250 protected function enableContentHandlerUseDB() {
1251 global $wgContentHandlerUseDB;
1253 if ( $this->holdContentHandlerUseDB
) {
1254 $this->output( "Content Handler DB fields should be usable now.\n" );
1255 $wgContentHandlerUseDB = $this->holdContentHandlerUseDB
;
1260 * Migrate comments to the new 'comment' table
1263 protected function migrateComments() {
1264 if ( !$this->updateRowExists( 'MigrateComments' ) ) {
1266 "Migrating comments to the 'comments' table, printing progress markers. For large\n" .
1267 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1268 "maintenance/migrateComments.php.\n"
1270 $task = $this->maintenance
->runChild( MigrateComments
::class, 'migrateComments.php' );
1271 $ok = $task->execute();
1272 $this->output( $ok ?
"done.\n" : "errors were encountered.\n" );
1277 * Merge `image_comment_temp` into the `image` table
1280 protected function migrateImageCommentTemp() {
1281 if ( $this->tableExists( 'image_comment_temp' ) ) {
1282 $this->output( "Merging image_comment_temp into the image table\n" );
1283 $task = $this->maintenance
->runChild(
1284 MigrateImageCommentTemp
::class, 'migrateImageCommentTemp.php'
1287 $ok = $task->execute();
1288 $this->output( $ok ?
"done.\n" : "errors were encountered.\n" );
1290 $this->dropTable( 'image_comment_temp' );
1296 * Migrate actors to the new 'actor' table
1299 protected function migrateActors() {
1300 global $wgActorTableSchemaMigrationStage;
1301 if ( ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) &&
1302 !$this->updateRowExists( 'MigrateActors' )
1305 "Migrating actors to the 'actor' table, printing progress markers. For large\n" .
1306 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1307 "maintenance/migrateActors.php.\n"
1309 $task = $this->maintenance
->runChild( 'MigrateActors', 'migrateActors.php' );
1310 $ok = $task->execute();
1311 $this->output( $ok ?
"done.\n" : "errors were encountered.\n" );
1316 * Migrate ar_text to modern storage
1319 protected function migrateArchiveText() {
1320 if ( $this->db
->fieldExists( 'archive', 'ar_text', __METHOD__
) ) {
1321 $this->output( "Migrating archive ar_text to modern storage.\n" );
1322 $task = $this->maintenance
->runChild( MigrateArchiveText
::class, 'migrateArchiveText.php' );
1324 if ( $task->execute() ) {
1325 $this->applyPatch( 'patch-drop-ar_text.sql', false,
1326 'Dropping ar_text and ar_flags columns' );
1332 * Populate ar_rev_id, then make it not nullable
1335 protected function populateArchiveRevId() {
1336 $info = $this->db
->fieldInfo( 'archive', 'ar_rev_id', __METHOD__
);
1338 throw new MWException( 'Missing ar_rev_id field of archive table. Should not happen.' );
1340 if ( $info->isNullable() ) {
1341 $this->output( "Populating ar_rev_id.\n" );
1342 $task = $this->maintenance
->runChild( 'PopulateArchiveRevId', 'populateArchiveRevId.php' );
1343 if ( $task->execute() ) {
1344 $this->applyPatch( 'patch-ar_rev_id-not-null.sql', false,
1345 'Making ar_rev_id not nullable' );
1351 * Populates the externallinks.el_index_60 field
1354 protected function populateExternallinksIndex60() {
1355 if ( !$this->updateRowExists( 'populate externallinks.el_index_60' ) ) {
1357 "Populating el_index_60 field, printing progress markers. For large\n" .
1358 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1359 "maintenance/populateExternallinksIndex60.php.\n"
1361 $task = $this->maintenance
->runChild( 'PopulateExternallinksIndex60',
1362 'populateExternallinksIndex60.php' );
1364 $this->output( "done.\n" );
1369 * Populates the MCR content tables
1372 protected function populateContentTables() {
1373 global $wgMultiContentRevisionSchemaMigrationStage;
1374 if ( ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) &&
1375 !$this->updateRowExists( 'PopulateContentTables' )
1378 "Migrating revision data to the MCR 'slot' and 'content' tables, printing progress markers.\n" .
1379 "For large databases, you may want to hit Ctrl-C and do this manually with\n" .
1380 "maintenance/populateContentTables.php.\n"
1382 $task = $this->maintenance
->runChild(
1383 PopulateContentTables
::class, 'populateContentTables.php'
1385 $ok = $task->execute();
1386 $this->output( $ok ?
"done.\n" : "errors were encountered.\n" );
1388 $this->insertUpdateRow( 'PopulateContentTables' );