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
{
38 * Array of updates to perform on the database
42 protected $updates = [];
45 * Array of updates that were skipped
49 protected $updatesSkipped = [];
52 * List of extension-provided database updates
55 protected $extensionUpdates = [];
58 * Handle to the database subclass
67 protected $maintenance;
69 protected $shared = false;
72 * @var string[] Scripts to run after database update
73 * Should be a subclass of LoggedUpdateMaintenance
75 protected $postDatabaseUpdateMaintenance = [
76 DeleteDefaultMessages
::class,
77 PopulateRevisionLength
::class,
78 PopulateRevisionSha1
::class,
79 PopulateImageSha1
::class,
80 FixExtLinksProtocolRelative
::class,
81 PopulateFilearchiveSha1
::class,
82 PopulateBacklinkNamespace
::class,
83 FixDefaultJsonContentPages
::class,
84 CleanupEmptyCategories
::class,
85 AddRFCAndPMIDInterwiki
::class,
86 PopulatePPSortKey
::class
90 * File handle for SQL output.
94 protected $fileHandle = null;
97 * Flag specifying whether or not to skip schema (e.g. SQL-only) updates.
101 protected $skipSchema = false;
104 * Hold the value of $wgContentHandlerUseDB during the upgrade.
106 protected $holdContentHandlerUseDB = true;
111 * @param Database $db To perform updates on
112 * @param bool $shared Whether to perform updates on shared tables
113 * @param Maintenance $maintenance Maintenance object which created us
115 protected function __construct( Database
&$db, $shared, Maintenance
$maintenance = null ) {
117 $this->db
->setFlag( DBO_DDLMODE
); // For Oracle's handling of schema files
118 $this->shared
= $shared;
119 if ( $maintenance ) {
120 $this->maintenance
= $maintenance;
121 $this->fileHandle
= $maintenance->fileHandle
;
123 $this->maintenance
= new FakeMaintenance
;
125 $this->maintenance
->setDB( $db );
126 $this->initOldGlobals();
127 $this->loadExtensions();
128 Hooks
::run( 'LoadExtensionSchemaUpdates', [ $this ] );
132 * Initialize all of the old globals. One day this should all become
133 * something much nicer
135 private function initOldGlobals() {
136 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
137 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
139 # For extensions only, should be populated via hooks
140 # $wgDBtype should be checked to specifiy the proper file
141 $wgExtNewTables = []; // table, dir
142 $wgExtNewFields = []; // table, column, dir
143 $wgExtPGNewFields = []; // table, column, column attributes; for PostgreSQL
144 $wgExtPGAlteredFields = []; // table, column, new type, conversion method; for PostgreSQL
145 $wgExtNewIndexes = []; // table, index, dir
146 $wgExtModifiedFields = []; // table, index, dir
150 * Loads LocalSettings.php, if needed, and initialises everything needed for
151 * LoadExtensionSchemaUpdates hook.
153 private function loadExtensions() {
154 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
155 return; // already loaded
157 $vars = Installer
::getExistingLocalSettings();
159 $registry = ExtensionRegistry
::getInstance();
160 $queue = $registry->getQueue();
161 // Don't accidentally load extensions in the future
162 $registry->clearQueue();
164 // This will automatically add "AutoloadClasses" to $wgAutoloadClasses
165 $data = $registry->readFromQueue( $queue );
166 $hooks = [ 'wgHooks' => [ 'LoadExtensionSchemaUpdates' => [] ] ];
167 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
168 $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 Database $db
182 * @param bool $shared
183 * @param Maintenance $maintenance
185 * @throws MWException
186 * @return DatabaseUpdater
188 public static function newForDB( Database
$db, $shared = false, $maintenance = null ) {
189 $type = $db->getType();
190 if ( in_array( $type, Installer
::getDBTypes() ) ) {
191 $class = ucfirst( $type ) . 'Updater';
193 return new $class( $db, $shared, $maintenance );
195 throw new MWException( __METHOD__
. ' called for unsupported $wgDBtype' );
200 * Get a database connection to run updates
204 public function getDB() {
209 * Output some text. If we're running from web, escape the text first.
211 * @param string $str Text to output
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 change path
346 public function modifyExtensionField( $tableName, $fieldName, $sqlPath ) {
347 $this->extensionUpdates
[] = [ 'modifyField', $tableName, $fieldName, $sqlPath, true ];
354 * @param string $tableName
357 public function tableExists( $tableName ) {
358 return ( $this->db
->tableExists( $tableName, __METHOD__
) );
362 * Add a maintenance script to be run after the database updates are complete.
364 * Script should subclass LoggedUpdateMaintenance
368 * @param string $class Name of a Maintenance subclass
370 public function addPostDatabaseUpdateMaintenance( $class ) {
371 $this->postDatabaseUpdateMaintenance
[] = $class;
375 * Get the list of extension-defined updates
379 protected function getExtensionUpdates() {
380 return $this->extensionUpdates
;
388 public function getPostDatabaseUpdateMaintenance() {
389 return $this->postDatabaseUpdateMaintenance
;
395 * Writes the schema updates desired to a file for the DB Admin to run.
396 * @param array $schemaUpdate
398 private function writeSchemaUpdateFile( array $schemaUpdate = [] ) {
399 $updates = $this->updatesSkipped
;
400 $this->updatesSkipped
= [];
402 foreach ( $updates as $funcList ) {
403 $func = $funcList[0];
405 $origParams = $funcList[2];
406 call_user_func_array( $func, $arg );
408 $this->updatesSkipped
[] = $origParams;
413 * Get appropriate schema variables in the current database connection.
415 * This should be called after any request data has been imported, but before
416 * any write operations to the database. The result should be passed to the DB
417 * setSchemaVars() method.
422 public function getSchemaVars() {
423 return []; // DB-type specific
429 * @param array $what What updates to perform
431 public function doUpdates( array $what = [ 'core', 'extensions', 'stats' ] ) {
432 $this->db
->setSchemaVars( $this->getSchemaVars() );
434 $what = array_flip( $what );
435 $this->skipSchema
= isset( $what['noschema'] ) ||
$this->fileHandle
!== null;
436 if ( isset( $what['core'] ) ) {
437 $this->runUpdates( $this->getCoreUpdateList(), false );
439 if ( isset( $what['extensions'] ) ) {
440 $this->runUpdates( $this->getOldGlobalUpdates(), false );
441 $this->runUpdates( $this->getExtensionUpdates(), true );
444 if ( isset( $what['stats'] ) ) {
448 if ( $this->fileHandle
) {
449 $this->skipSchema
= false;
450 $this->writeSchemaUpdateFile();
455 * Helper function for doUpdates()
457 * @param array $updates Array of updates to run
458 * @param bool $passSelf Whether to pass this object we calling external functions
460 private function runUpdates( array $updates, $passSelf ) {
461 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
464 $updatesSkipped = [];
465 foreach ( $updates as $params ) {
466 $origParams = $params;
467 $func = array_shift( $params );
468 if ( !is_array( $func ) && method_exists( $this, $func ) ) {
469 $func = [ $this, $func ];
470 } elseif ( $passSelf ) {
471 array_unshift( $params, $this );
473 $ret = call_user_func_array( $func, $params );
475 if ( $ret !== false ) {
476 $updatesDone[] = $origParams;
477 $lbFactory->waitForReplication();
479 $updatesSkipped[] = [ $func, $params, $origParams ];
482 $this->updatesSkipped
= array_merge( $this->updatesSkipped
, $updatesSkipped );
483 $this->updates
= array_merge( $this->updates
, $updatesDone );
487 * Helper function: check if the given key is present in the updatelog table.
488 * Obviously, only use this for updates that occur after the updatelog table was
490 * @param string $key Name of the key to check for
493 public function updateRowExists( $key ) {
494 $row = $this->db
->selectRow(
498 [ 'ul_key' => $key ],
506 * Helper function: Add a key to the updatelog table
507 * Obviously, only use this for updates that occur after the updatelog table was
509 * @param string $key Name of key to insert
510 * @param string $val [optional] Value to insert along with the key
512 public function insertUpdateRow( $key, $val = null ) {
513 $this->db
->clearFlag( DBO_DDLMODE
);
514 $values = [ 'ul_key' => $key ];
515 if ( $val && $this->canUseNewUpdatelog() ) {
516 $values['ul_value'] = $val;
518 $this->db
->insert( 'updatelog', $values, __METHOD__
, 'IGNORE' );
519 $this->db
->setFlag( DBO_DDLMODE
);
523 * Updatelog was changed in 1.17 to have a ul_value column so we can record
524 * more information about what kind of updates we've done (that's what this
525 * class does). Pre-1.17 wikis won't have this column, and really old wikis
526 * might not even have updatelog at all
530 protected function canUseNewUpdatelog() {
531 return $this->db
->tableExists( 'updatelog', __METHOD__
) &&
532 $this->db
->fieldExists( 'updatelog', 'ul_value', __METHOD__
);
536 * Returns whether updates should be executed on the database table $name.
537 * Updates will be prevented if the table is a shared table and it is not
538 * specified to run updates on shared tables.
540 * @param string $name Table name
543 protected function doTable( $name ) {
544 global $wgSharedDB, $wgSharedTables;
546 // Don't bother to check $wgSharedTables if there isn't a shared database
547 // or the user actually also wants to do updates on the shared database.
548 if ( $wgSharedDB === null ||
$this->shared
) {
552 if ( in_array( $name, $wgSharedTables ) ) {
553 $this->output( "...skipping update to shared table $name.\n" );
561 * Before 1.17, we used to handle updates via stuff like
562 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
563 * of this in 1.17 but we want to remain back-compatible for a while. So
564 * load up these old global-based things into our update list.
568 protected function getOldGlobalUpdates() {
569 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
574 foreach ( $wgExtNewTables as $tableRecord ) {
576 'addTable', $tableRecord[0], $tableRecord[1], true
580 foreach ( $wgExtNewFields as $fieldRecord ) {
582 'addField', $fieldRecord[0], $fieldRecord[1],
583 $fieldRecord[2], true
587 foreach ( $wgExtNewIndexes as $fieldRecord ) {
589 'addIndex', $fieldRecord[0], $fieldRecord[1],
590 $fieldRecord[2], true
594 foreach ( $wgExtModifiedFields as $fieldRecord ) {
596 'modifyField', $fieldRecord[0], $fieldRecord[1],
597 $fieldRecord[2], true
605 * Get an array of updates to perform on the database. Should return a
606 * multi-dimensional array. The main key is the MediaWiki version (1.12,
607 * 1.13...) with the values being arrays of updates, identical to how
608 * updaters.inc did it (for now)
612 abstract protected function getCoreUpdateList();
615 * Append an SQL fragment to the open file handle.
617 * @param string $filename File name to open
619 public function copyFile( $filename ) {
620 $this->db
->sourceFile(
625 [ $this, 'appendLine' ]
630 * Append a line to the open filehandle. The line is assumed to
631 * be a complete SQL statement.
633 * This is used as a callback for sourceLine().
635 * @param string $line Text to append to the file
636 * @return bool False to skip actually executing the file
637 * @throws MWException
639 public function appendLine( $line ) {
640 $line = rtrim( $line ) . ";\n";
641 if ( fwrite( $this->fileHandle
, $line ) === false ) {
642 throw new MWException( "trouble writing file" );
649 * Applies a SQL patch
651 * @param string $path Path to the patch file
652 * @param bool $isFullPath Whether to treat $path as a relative or not
653 * @param string $msg Description of the patch
654 * @return bool False if patch is skipped.
656 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
657 if ( $msg === null ) {
658 $msg = "Applying $path patch";
660 if ( $this->skipSchema
) {
661 $this->output( "...skipping schema change ($msg).\n" );
666 $this->output( "$msg ..." );
668 if ( !$isFullPath ) {
669 $path = $this->patchPath( $this->db
, $path );
671 if ( $this->fileHandle
!== null ) {
672 $this->copyFile( $path );
674 $this->db
->sourceFile( $path );
676 $this->output( "done.\n" );
682 * Get the full path of a patch file. Originally based on archive()
683 * from updaters.inc. Keep in mind this always returns a patch, as
684 * it fails back to MySQL if no DB-specific patch can be found
686 * @param IDatabase $db
687 * @param string $patch The name of the patch, like patch-something.sql
688 * @return string Full path to patch file
690 public function patchPath( IDatabase
$db, $patch ) {
693 $dbType = $db->getType();
694 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
695 return "$IP/maintenance/$dbType/archives/$patch";
697 return "$IP/maintenance/archives/$patch";
702 * Add a new table to the database
704 * @param string $name Name of the new table
705 * @param string $patch Path to the patch file
706 * @param bool $fullpath Whether to treat $patch path as a relative or not
707 * @return bool False if this was skipped because schema changes are skipped
709 protected function addTable( $name, $patch, $fullpath = false ) {
710 if ( !$this->doTable( $name ) ) {
714 if ( $this->db
->tableExists( $name, __METHOD__
) ) {
715 $this->output( "...$name table already exists.\n" );
717 return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
724 * Add a new field to an existing table
726 * @param string $table Name of the table to modify
727 * @param string $field Name of the new field
728 * @param string $patch Path to the patch file
729 * @param bool $fullpath Whether to treat $patch path as a relative or not
730 * @return bool False if this was skipped because schema changes are skipped
732 protected function addField( $table, $field, $patch, $fullpath = false ) {
733 if ( !$this->doTable( $table ) ) {
737 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
738 $this->output( "...$table table does not exist, skipping new field patch.\n" );
739 } elseif ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
740 $this->output( "...have $field field in $table table.\n" );
742 return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
749 * Add a new index to an existing table
751 * @param string $table Name of the table to modify
752 * @param string $index Name of the new index
753 * @param string $patch Path to the patch file
754 * @param bool $fullpath Whether to treat $patch path as a relative or not
755 * @return bool False if this was skipped because schema changes are skipped
757 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
758 if ( !$this->doTable( $table ) ) {
762 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
763 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
764 } elseif ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
765 $this->output( "...index $index already set on $table table.\n" );
767 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
774 * Drop a field from an existing table
776 * @param string $table Name of the table to modify
777 * @param string $field Name of the old field
778 * @param string $patch Path to the patch file
779 * @param bool $fullpath Whether to treat $patch path as a relative or not
780 * @return bool False if this was skipped because schema changes are skipped
782 protected function dropField( $table, $field, $patch, $fullpath = false ) {
783 if ( !$this->doTable( $table ) ) {
787 if ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
788 return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
790 $this->output( "...$table table does not contain $field field.\n" );
797 * Drop an index from an existing table
799 * @param string $table Name of the table to modify
800 * @param string $index Name of the index
801 * @param string $patch Path to the patch file
802 * @param bool $fullpath Whether to treat $patch path as a relative or not
803 * @return bool False if this was skipped because schema changes are skipped
805 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
806 if ( !$this->doTable( $table ) ) {
810 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
811 return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
813 $this->output( "...$index key doesn't exist.\n" );
820 * Rename an index from an existing table
822 * @param string $table Name of the table to modify
823 * @param string $oldIndex Old name of the index
824 * @param string $newIndex New name of the index
825 * @param bool $skipBothIndexExistWarning Whether to warn if both the
826 * old and the new indexes exist.
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 renameIndex( $table, $oldIndex, $newIndex,
832 $skipBothIndexExistWarning, $patch, $fullpath = false
834 if ( !$this->doTable( $table ) ) {
838 // First requirement: the table must exist
839 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
840 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
845 // Second requirement: the new index must be missing
846 if ( $this->db
->indexExists( $table, $newIndex, __METHOD__
) ) {
847 $this->output( "...index $newIndex already set on $table table.\n" );
848 if ( !$skipBothIndexExistWarning &&
849 $this->db
->indexExists( $table, $oldIndex, __METHOD__
)
851 $this->output( "...WARNING: $oldIndex still exists, despite it has " .
852 "been renamed into $newIndex (which also exists).\n" .
853 " $oldIndex should be manually removed if not needed anymore.\n" );
859 // Third requirement: the old index must exist
860 if ( !$this->db
->indexExists( $table, $oldIndex, __METHOD__
) ) {
861 $this->output( "...skipping: index $oldIndex doesn't exist.\n" );
866 // Requirements have been satisfied, patch can be applied
867 return $this->applyPatch(
870 "Renaming index $oldIndex into $newIndex to table $table"
875 * If the specified table exists, drop it, or execute the
876 * patch if one is provided.
880 * @param string $table Table to drop.
881 * @param string|bool $patch String of patch file that will drop the table. Default: false.
882 * @param bool $fullpath Whether $patch is a full path. Default: false.
883 * @return bool False if this was skipped because schema changes are skipped
885 public function dropTable( $table, $patch = false, $fullpath = false ) {
886 if ( !$this->doTable( $table ) ) {
890 if ( $this->db
->tableExists( $table, __METHOD__
) ) {
891 $msg = "Dropping table $table";
893 if ( $patch === false ) {
894 $this->output( "$msg ..." );
895 $this->db
->dropTable( $table, __METHOD__
);
896 $this->output( "done.\n" );
898 return $this->applyPatch( $patch, $fullpath, $msg );
901 $this->output( "...$table doesn't exist.\n" );
908 * Modify an existing field
910 * @param string $table Name of the table to which the field belongs
911 * @param string $field Name of the field to modify
912 * @param string $patch Path to the patch file
913 * @param bool $fullpath Whether to treat $patch path as a relative or not
914 * @return bool False if this was skipped because schema changes are skipped
916 public function modifyField( $table, $field, $patch, $fullpath = false ) {
917 if ( !$this->doTable( $table ) ) {
921 $updateKey = "$table-$field-$patch";
922 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
923 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
924 } elseif ( !$this->db
->fieldExists( $table, $field, __METHOD__
) ) {
925 $this->output( "...$field field does not exist in $table table, " .
926 "skipping modify field patch.\n" );
927 } elseif ( $this->updateRowExists( $updateKey ) ) {
928 $this->output( "...$field in table $table already modified by patch $patch.\n" );
930 $apply = $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
932 $this->insertUpdateRow( $updateKey );
940 * Modify an existing table, similar to modifyField. Intended for changes that
941 * touch more than one column on a table.
943 * @param string $table Name of the table to modify
944 * @param string $patch Name of the patch file to apply
945 * @param string $fullpath Whether to treat $patch path as relative or not, defaults to false
946 * @return bool False if this was skipped because of schema changes being skipped
948 public function modifyTable( $table, $patch, $fullpath = false ) {
949 if ( !$this->doTable( $table ) ) {
953 $updateKey = "$table-$patch";
954 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
955 $this->output( "...$table table does not exist, skipping modify table patch.\n" );
956 } elseif ( $this->updateRowExists( $updateKey ) ) {
957 $this->output( "...table $table already modified by patch $patch.\n" );
959 $apply = $this->applyPatch( $patch, $fullpath, "Modifying table $table" );
961 $this->insertUpdateRow( $updateKey );
969 * Set any .htaccess files or equivilent for storage repos
971 * Some zones (e.g. "temp") used to be public and may have been initialized as such
973 public function setFileAccess() {
974 $repo = RepoGroup
::singleton()->getLocalRepo();
975 $zonePath = $repo->getZonePath( 'temp' );
976 if ( $repo->getBackend()->directoryExists( [ 'dir' => $zonePath ] ) ) {
977 // If the directory was never made, then it will have the right ACLs when it is made
978 $status = $repo->getBackend()->secure( [
983 if ( $status->isOK() ) {
984 $this->output( "Set the local repo temp zone container to be private.\n" );
986 $this->output( "Failed to set the local repo temp zone container to be private.\n" );
992 * Purge the objectcache table
994 public function purgeCache() {
995 global $wgLocalisationCacheConf;
996 # We can't guarantee that the user will be able to use TRUNCATE,
997 # but we know that DELETE is available to us
998 $this->output( "Purging caches..." );
999 $this->db
->delete( 'objectcache', '*', __METHOD__
);
1000 if ( $wgLocalisationCacheConf['manualRecache'] ) {
1001 $this->rebuildLocalisationCache();
1003 $blobStore = new MessageBlobStore();
1004 $blobStore->clear();
1005 $this->db
->delete( 'module_deps', '*', __METHOD__
);
1006 $this->output( "done.\n" );
1010 * Check the site_stats table is not properly populated.
1012 protected function checkStats() {
1013 $this->output( "...site_stats is populated..." );
1014 $row = $this->db
->selectRow( 'site_stats', '*', [ 'ss_row_id' => 1 ], __METHOD__
);
1015 if ( $row === false ) {
1016 $this->output( "data is missing! rebuilding...\n" );
1017 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
1018 $this->output( "missing ss_total_pages, rebuilding...\n" );
1020 $this->output( "done.\n" );
1024 SiteStatsInit
::doAllAndCommit( $this->db
);
1027 # Common updater functions
1030 * Sets the number of active users in the site_stats table
1032 protected function doActiveUsersInit() {
1033 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', false, __METHOD__
);
1034 if ( $activeUsers == -1 ) {
1035 $activeUsers = $this->db
->selectField( 'recentchanges',
1036 'COUNT( DISTINCT rc_user_text )',
1037 [ 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ], __METHOD__
1039 $this->db
->update( 'site_stats',
1040 [ 'ss_active_users' => intval( $activeUsers ) ],
1041 [ 'ss_row_id' => 1 ], __METHOD__
, [ 'LIMIT' => 1 ]
1044 $this->output( "...ss_active_users user count set...\n" );
1048 * Populates the log_user_text field in the logging table
1050 protected function doLogUsertextPopulation() {
1051 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
1053 "Populating log_user_text field, printing progress markers. For large\n" .
1054 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1055 "maintenance/populateLogUsertext.php.\n"
1058 $task = $this->maintenance
->runChild( 'PopulateLogUsertext' );
1060 $this->output( "done.\n" );
1065 * Migrate log params to new table and index for searching
1067 protected function doLogSearchPopulation() {
1068 if ( !$this->updateRowExists( 'populate log_search' ) ) {
1070 "Populating log_search table, printing progress markers. For large\n" .
1071 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1072 "maintenance/populateLogSearch.php.\n" );
1074 $task = $this->maintenance
->runChild( 'PopulateLogSearch' );
1076 $this->output( "done.\n" );
1081 * Updates the timestamps in the transcache table
1084 protected function doUpdateTranscacheField() {
1085 if ( $this->updateRowExists( 'convert transcache field' ) ) {
1086 $this->output( "...transcache tc_time already converted.\n" );
1091 return $this->applyPatch( 'patch-tc-timestamp.sql', false,
1092 "Converting tc_time from UNIX epoch to MediaWiki timestamp" );
1096 * Update CategoryLinks collation
1098 protected function doCollationUpdate() {
1099 global $wgCategoryCollation;
1100 if ( $this->db
->fieldExists( 'categorylinks', 'cl_collation', __METHOD__
) ) {
1101 if ( $this->db
->selectField(
1104 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
1108 $this->output( "...collations up-to-date.\n" );
1113 $this->output( "Updating category collations..." );
1114 $task = $this->maintenance
->runChild( 'UpdateCollation' );
1116 $this->output( "...done.\n" );
1121 * Migrates user options from the user table blob to user_properties
1123 protected function doMigrateUserOptions() {
1124 if ( $this->db
->tableExists( 'user_properties' ) ) {
1125 $cl = $this->maintenance
->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
1127 $this->output( "done.\n" );
1132 * Enable profiling table when it's turned on
1134 protected function doEnableProfiling() {
1137 if ( !$this->doTable( 'profiling' ) ) {
1141 $profileToDb = false;
1142 if ( isset( $wgProfiler['output'] ) ) {
1143 $out = $wgProfiler['output'];
1144 if ( $out === 'db' ) {
1145 $profileToDb = true;
1146 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
1147 $profileToDb = true;
1151 if ( $profileToDb && !$this->db
->tableExists( 'profiling', __METHOD__
) ) {
1152 $this->applyPatch( 'patch-profiling.sql', false, 'Add profiling table' );
1157 * Rebuilds the localisation cache
1159 protected function rebuildLocalisationCache() {
1161 * @var $cl RebuildLocalisationCache
1163 $cl = $this->maintenance
->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
1164 $this->output( "Rebuilding localisation cache...\n" );
1167 $this->output( "done.\n" );
1171 * Turns off content handler fields during parts of the upgrade
1172 * where they aren't available.
1174 protected function disableContentHandlerUseDB() {
1175 global $wgContentHandlerUseDB;
1177 if ( $wgContentHandlerUseDB ) {
1178 $this->output( "Turning off Content Handler DB fields for this part of upgrade.\n" );
1179 $this->holdContentHandlerUseDB
= $wgContentHandlerUseDB;
1180 $wgContentHandlerUseDB = false;
1185 * Turns content handler fields back on.
1187 protected function enableContentHandlerUseDB() {
1188 global $wgContentHandlerUseDB;
1190 if ( $this->holdContentHandlerUseDB
) {
1191 $this->output( "Content Handler DB fields should be usable now.\n" );
1192 $wgContentHandlerUseDB = $this->holdContentHandlerUseDB
;