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 MediaWiki\MediaWikiServices
;
25 require_once __DIR__
. '/../../maintenance/Maintenance.php';
28 * Class for handling database updates. Roughly based off of updaters.inc, with
29 * a few improvements :)
34 abstract class DatabaseUpdater
{
36 * Array of updates to perform on the database
40 protected $updates = [];
43 * Array of updates that were skipped
47 protected $updatesSkipped = [];
50 * List of extension-provided database updates
53 protected $extensionUpdates = [];
56 * Handle to the database subclass
65 protected $maintenance;
67 protected $shared = false;
70 * @var string[] Scripts to run after database update
71 * Should be a subclass of LoggedUpdateMaintenance
73 protected $postDatabaseUpdateMaintenance = [
74 DeleteDefaultMessages
::class,
75 PopulateRevisionLength
::class,
76 PopulateRevisionSha1
::class,
77 PopulateImageSha1
::class,
78 FixExtLinksProtocolRelative
::class,
79 PopulateFilearchiveSha1
::class,
80 PopulateBacklinkNamespace
::class,
81 FixDefaultJsonContentPages
::class,
82 CleanupEmptyCategories
::class,
83 AddRFCAndPMIDInterwiki
::class,
87 * File handle for SQL output.
91 protected $fileHandle = null;
94 * Flag specifying whether or not to skip schema (e.g. SQL-only) updates.
98 protected $skipSchema = false;
101 * Hold the value of $wgContentHandlerUseDB during the upgrade.
103 protected $holdContentHandlerUseDB = true;
108 * @param Database $db To perform updates on
109 * @param bool $shared Whether to perform updates on shared tables
110 * @param Maintenance $maintenance Maintenance object which created us
112 protected function __construct( Database
&$db, $shared, Maintenance
$maintenance = null ) {
114 $this->db
->setFlag( DBO_DDLMODE
); // For Oracle's handling of schema files
115 $this->shared
= $shared;
116 if ( $maintenance ) {
117 $this->maintenance
= $maintenance;
118 $this->fileHandle
= $maintenance->fileHandle
;
120 $this->maintenance
= new FakeMaintenance
;
122 $this->maintenance
->setDB( $db );
123 $this->initOldGlobals();
124 $this->loadExtensions();
125 Hooks
::run( 'LoadExtensionSchemaUpdates', [ $this ] );
129 * Initialize all of the old globals. One day this should all become
130 * something much nicer
132 private function initOldGlobals() {
133 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
134 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
136 # For extensions only, should be populated via hooks
137 # $wgDBtype should be checked to specifiy the proper file
138 $wgExtNewTables = []; // table, dir
139 $wgExtNewFields = []; // table, column, dir
140 $wgExtPGNewFields = []; // table, column, column attributes; for PostgreSQL
141 $wgExtPGAlteredFields = []; // table, column, new type, conversion method; for PostgreSQL
142 $wgExtNewIndexes = []; // table, index, dir
143 $wgExtModifiedFields = []; // table, index, dir
147 * Loads LocalSettings.php, if needed, and initialises everything needed for
148 * LoadExtensionSchemaUpdates hook.
150 private function loadExtensions() {
151 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
152 return; // already loaded
154 $vars = Installer
::getExistingLocalSettings();
156 $registry = ExtensionRegistry
::getInstance();
157 $queue = $registry->getQueue();
158 // Don't accidentally load extensions in the future
159 $registry->clearQueue();
161 // This will automatically add "AutoloadClasses" to $wgAutoloadClasses
162 $data = $registry->readFromQueue( $queue );
163 $hooks = [ 'wgHooks' => [ 'LoadExtensionSchemaUpdates' => [] ] ];
164 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
165 $hooks = $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'];
167 if ( $vars && isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
168 $hooks = array_merge_recursive( $hooks, $vars['wgHooks']['LoadExtensionSchemaUpdates'] );
170 global $wgHooks, $wgAutoloadClasses;
171 $wgHooks['LoadExtensionSchemaUpdates'] = $hooks;
172 if ( $vars && isset( $vars['wgAutoloadClasses'] ) ) {
173 $wgAutoloadClasses +
= $vars['wgAutoloadClasses'];
178 * @param Database $db
179 * @param bool $shared
180 * @param Maintenance $maintenance
182 * @throws MWException
183 * @return DatabaseUpdater
185 public static function newForDB( Database
$db, $shared = false, $maintenance = null ) {
186 $type = $db->getType();
187 if ( in_array( $type, Installer
::getDBTypes() ) ) {
188 $class = ucfirst( $type ) . 'Updater';
190 return new $class( $db, $shared, $maintenance );
192 throw new MWException( __METHOD__
. ' called for unsupported $wgDBtype' );
197 * Get a database connection to run updates
201 public function getDB() {
206 * Output some text. If we're running from web, escape the text first.
208 * @param string $str Text to output
210 public function output( $str ) {
211 if ( $this->maintenance
->isQuiet() ) {
214 global $wgCommandLineMode;
215 if ( !$wgCommandLineMode ) {
216 $str = htmlspecialchars( $str );
223 * Add a new update coming from an extension. This should be called by
224 * extensions while executing the LoadExtensionSchemaUpdates hook.
228 * @param array $update The update to run. Format is [ $callback, $params... ]
229 * $callback is the method to call; either a DatabaseUpdater method name or a callable.
230 * Must be serializable (ie. no anonymous functions allowed). The rest of the parameters
231 * (if any) will be passed to the callback. The first parameter passed to the callback
232 * is always this object.
234 public function addExtensionUpdate( array $update ) {
235 $this->extensionUpdates
[] = $update;
239 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
240 * is the most common usage of updaters in an extension)
244 * @param string $tableName Name of table to create
245 * @param string $sqlPath Full path to the schema file
247 public function addExtensionTable( $tableName, $sqlPath ) {
248 $this->extensionUpdates
[] = [ 'addTable', $tableName, $sqlPath, true ];
254 * @param string $tableName
255 * @param string $indexName
256 * @param string $sqlPath
258 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
259 $this->extensionUpdates
[] = [ 'addIndex', $tableName, $indexName, $sqlPath, true ];
266 * @param string $tableName
267 * @param string $columnName
268 * @param string $sqlPath
270 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
271 $this->extensionUpdates
[] = [ 'addField', $tableName, $columnName, $sqlPath, true ];
278 * @param string $tableName
279 * @param string $columnName
280 * @param string $sqlPath
282 public function dropExtensionField( $tableName, $columnName, $sqlPath ) {
283 $this->extensionUpdates
[] = [ 'dropField', $tableName, $columnName, $sqlPath, true ];
287 * Drop an index from an extension table
291 * @param string $tableName The table name
292 * @param string $indexName The index name
293 * @param string $sqlPath The path to the SQL change path
295 public function dropExtensionIndex( $tableName, $indexName, $sqlPath ) {
296 $this->extensionUpdates
[] = [ 'dropIndex', $tableName, $indexName, $sqlPath, true ];
303 * @param string $tableName
304 * @param string $sqlPath
306 public function dropExtensionTable( $tableName, $sqlPath ) {
307 $this->extensionUpdates
[] = [ 'dropTable', $tableName, $sqlPath, true ];
311 * Rename an index on an extension table
315 * @param string $tableName The table name
316 * @param string $oldIndexName The old index name
317 * @param string $newIndexName The new index name
318 * @param string $sqlPath The path to the SQL change path
319 * @param bool $skipBothIndexExistWarning Whether to warn if both the old
320 * and the new indexes exist. [facultative; by default, false]
322 public function renameExtensionIndex( $tableName, $oldIndexName, $newIndexName,
323 $sqlPath, $skipBothIndexExistWarning = false
325 $this->extensionUpdates
[] = [
330 $skipBothIndexExistWarning,
339 * @param string $tableName The table name
340 * @param string $fieldName The field to be modified
341 * @param string $sqlPath The path to the SQL change path
343 public function modifyExtensionField( $tableName, $fieldName, $sqlPath ) {
344 $this->extensionUpdates
[] = [ 'modifyField', $tableName, $fieldName, $sqlPath, true ];
351 * @param string $tableName
354 public function tableExists( $tableName ) {
355 return ( $this->db
->tableExists( $tableName, __METHOD__
) );
359 * Add a maintenance script to be run after the database updates are complete.
361 * Script should subclass LoggedUpdateMaintenance
365 * @param string $class Name of a Maintenance subclass
367 public function addPostDatabaseUpdateMaintenance( $class ) {
368 $this->postDatabaseUpdateMaintenance
[] = $class;
372 * Get the list of extension-defined updates
376 protected function getExtensionUpdates() {
377 return $this->extensionUpdates
;
385 public function getPostDatabaseUpdateMaintenance() {
386 return $this->postDatabaseUpdateMaintenance
;
392 * Writes the schema updates desired to a file for the DB Admin to run.
393 * @param array $schemaUpdate
395 private function writeSchemaUpdateFile( $schemaUpdate = [] ) {
396 $updates = $this->updatesSkipped
;
397 $this->updatesSkipped
= [];
399 foreach ( $updates as $funcList ) {
400 $func = $funcList[0];
402 $origParams = $funcList[2];
403 call_user_func_array( $func, $arg );
405 $this->updatesSkipped
[] = $origParams;
410 * Get appropriate schema variables in the current database connection.
412 * This should be called after any request data has been imported, but before
413 * any write operations to the database. The result should be passed to the DB
414 * setSchemaVars() method.
419 public function getSchemaVars() {
420 return []; // DB-type specific
426 * @param array $what What updates to perform
428 public function doUpdates( $what = [ 'core', 'extensions', 'stats' ] ) {
429 $this->db
->setSchemaVars( $this->getSchemaVars() );
431 $what = array_flip( $what );
432 $this->skipSchema
= isset( $what['noschema'] ) ||
$this->fileHandle
!== null;
433 if ( isset( $what['core'] ) ) {
434 $this->runUpdates( $this->getCoreUpdateList(), false );
436 if ( isset( $what['extensions'] ) ) {
437 $this->runUpdates( $this->getOldGlobalUpdates(), false );
438 $this->runUpdates( $this->getExtensionUpdates(), true );
441 if ( isset( $what['stats'] ) ) {
445 if ( $this->fileHandle
) {
446 $this->skipSchema
= false;
447 $this->writeSchemaUpdateFile();
452 * Helper function for doUpdates()
454 * @param array $updates Array of updates to run
455 * @param bool $passSelf Whether to pass this object we calling external functions
457 private function runUpdates( array $updates, $passSelf ) {
458 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
461 $updatesSkipped = [];
462 foreach ( $updates as $params ) {
463 $origParams = $params;
464 $func = array_shift( $params );
465 if ( !is_array( $func ) && method_exists( $this, $func ) ) {
466 $func = [ $this, $func ];
467 } elseif ( $passSelf ) {
468 array_unshift( $params, $this );
470 $ret = call_user_func_array( $func, $params );
472 if ( $ret !== false ) {
473 $updatesDone[] = $origParams;
474 $lbFactory->waitForReplication();
476 $updatesSkipped[] = [ $func, $params, $origParams ];
479 $this->updatesSkipped
= array_merge( $this->updatesSkipped
, $updatesSkipped );
480 $this->updates
= array_merge( $this->updates
, $updatesDone );
484 * Helper function: check if the given key is present in the updatelog table.
485 * Obviously, only use this for updates that occur after the updatelog table was
487 * @param string $key Name of the key to check for
490 public function updateRowExists( $key ) {
491 $row = $this->db
->selectRow(
495 [ 'ul_key' => $key ],
503 * Helper function: Add a key to the updatelog table
504 * Obviously, only use this for updates that occur after the updatelog table was
506 * @param string $key Name of key to insert
507 * @param string $val [optional] Value to insert along with the key
509 public function insertUpdateRow( $key, $val = null ) {
510 $this->db
->clearFlag( DBO_DDLMODE
);
511 $values = [ 'ul_key' => $key ];
512 if ( $val && $this->canUseNewUpdatelog() ) {
513 $values['ul_value'] = $val;
515 $this->db
->insert( 'updatelog', $values, __METHOD__
, 'IGNORE' );
516 $this->db
->setFlag( DBO_DDLMODE
);
520 * Updatelog was changed in 1.17 to have a ul_value column so we can record
521 * more information about what kind of updates we've done (that's what this
522 * class does). Pre-1.17 wikis won't have this column, and really old wikis
523 * might not even have updatelog at all
527 protected function canUseNewUpdatelog() {
528 return $this->db
->tableExists( 'updatelog', __METHOD__
) &&
529 $this->db
->fieldExists( 'updatelog', 'ul_value', __METHOD__
);
533 * Returns whether updates should be executed on the database table $name.
534 * Updates will be prevented if the table is a shared table and it is not
535 * specified to run updates on shared tables.
537 * @param string $name Table name
540 protected function doTable( $name ) {
541 global $wgSharedDB, $wgSharedTables;
543 // Don't bother to check $wgSharedTables if there isn't a shared database
544 // or the user actually also wants to do updates on the shared database.
545 if ( $wgSharedDB === null ||
$this->shared
) {
549 if ( in_array( $name, $wgSharedTables ) ) {
550 $this->output( "...skipping update to shared table $name.\n" );
558 * Before 1.17, we used to handle updates via stuff like
559 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
560 * of this in 1.17 but we want to remain back-compatible for a while. So
561 * load up these old global-based things into our update list.
565 protected function getOldGlobalUpdates() {
566 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
571 foreach ( $wgExtNewTables as $tableRecord ) {
573 'addTable', $tableRecord[0], $tableRecord[1], true
577 foreach ( $wgExtNewFields as $fieldRecord ) {
579 'addField', $fieldRecord[0], $fieldRecord[1],
580 $fieldRecord[2], true
584 foreach ( $wgExtNewIndexes as $fieldRecord ) {
586 'addIndex', $fieldRecord[0], $fieldRecord[1],
587 $fieldRecord[2], true
591 foreach ( $wgExtModifiedFields as $fieldRecord ) {
593 'modifyField', $fieldRecord[0], $fieldRecord[1],
594 $fieldRecord[2], true
602 * Get an array of updates to perform on the database. Should return a
603 * multi-dimensional array. The main key is the MediaWiki version (1.12,
604 * 1.13...) with the values being arrays of updates, identical to how
605 * updaters.inc did it (for now)
609 abstract protected function getCoreUpdateList();
612 * Append an SQL fragment to the open file handle.
614 * @param string $filename File name to open
616 public function copyFile( $filename ) {
617 $this->db
->sourceFile(
622 [ $this, 'appendLine' ]
627 * Append a line to the open filehandle. The line is assumed to
628 * be a complete SQL statement.
630 * This is used as a callback for sourceLine().
632 * @param string $line Text to append to the file
633 * @return bool False to skip actually executing the file
634 * @throws MWException
636 public function appendLine( $line ) {
637 $line = rtrim( $line ) . ";\n";
638 if ( fwrite( $this->fileHandle
, $line ) === false ) {
639 throw new MWException( "trouble writing file" );
646 * Applies a SQL patch
648 * @param string $path Path to the patch file
649 * @param bool $isFullPath Whether to treat $path as a relative or not
650 * @param string $msg Description of the patch
651 * @return bool False if patch is skipped.
653 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
654 if ( $msg === null ) {
655 $msg = "Applying $path patch";
657 if ( $this->skipSchema
) {
658 $this->output( "...skipping schema change ($msg).\n" );
663 $this->output( "$msg ..." );
665 if ( !$isFullPath ) {
666 $path = $this->patchPath( $this->db
, $path );
668 if ( $this->fileHandle
!== null ) {
669 $this->copyFile( $path );
671 $this->db
->sourceFile( $path );
673 $this->output( "done.\n" );
679 * Get the full path of a patch file. Originally based on archive()
680 * from updaters.inc. Keep in mind this always returns a patch, as
681 * it fails back to MySQL if no DB-specific patch can be found
683 * @param IDatabase $db
684 * @param string $patch The name of the patch, like patch-something.sql
685 * @return string Full path to patch file
687 public function patchPath( IDatabase
$db, $patch ) {
690 $dbType = $db->getType();
691 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
692 return "$IP/maintenance/$dbType/archives/$patch";
694 return "$IP/maintenance/archives/$patch";
699 * Add a new table to the database
701 * @param string $name Name of the new table
702 * @param string $patch Path to the patch file
703 * @param bool $fullpath Whether to treat $patch path as a relative or not
704 * @return bool False if this was skipped because schema changes are skipped
706 protected function addTable( $name, $patch, $fullpath = false ) {
707 if ( !$this->doTable( $name ) ) {
711 if ( $this->db
->tableExists( $name, __METHOD__
) ) {
712 $this->output( "...$name table already exists.\n" );
714 return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
721 * Add a new field to an existing table
723 * @param string $table Name of the table to modify
724 * @param string $field Name of the new field
725 * @param string $patch Path to the patch file
726 * @param bool $fullpath Whether to treat $patch path as a relative or not
727 * @return bool False if this was skipped because schema changes are skipped
729 protected function addField( $table, $field, $patch, $fullpath = false ) {
730 if ( !$this->doTable( $table ) ) {
734 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
735 $this->output( "...$table table does not exist, skipping new field patch.\n" );
736 } elseif ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
737 $this->output( "...have $field field in $table table.\n" );
739 return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
746 * Add a new index to an existing table
748 * @param string $table Name of the table to modify
749 * @param string $index Name of the new index
750 * @param string $patch Path to the patch file
751 * @param bool $fullpath Whether to treat $patch path as a relative or not
752 * @return bool False if this was skipped because schema changes are skipped
754 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
755 if ( !$this->doTable( $table ) ) {
759 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
760 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
761 } elseif ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
762 $this->output( "...index $index already set on $table table.\n" );
764 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
771 * Drop a field from an existing table
773 * @param string $table Name of the table to modify
774 * @param string $field Name of the old field
775 * @param string $patch Path to the patch file
776 * @param bool $fullpath Whether to treat $patch path as a relative or not
777 * @return bool False if this was skipped because schema changes are skipped
779 protected function dropField( $table, $field, $patch, $fullpath = false ) {
780 if ( !$this->doTable( $table ) ) {
784 if ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
785 return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
787 $this->output( "...$table table does not contain $field field.\n" );
794 * Drop an index from an existing table
796 * @param string $table Name of the table to modify
797 * @param string $index Name of the index
798 * @param string $patch Path to the patch file
799 * @param bool $fullpath Whether to treat $patch path as a relative or not
800 * @return bool False if this was skipped because schema changes are skipped
802 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
803 if ( !$this->doTable( $table ) ) {
807 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
808 return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
810 $this->output( "...$index key doesn't exist.\n" );
817 * Rename an index from an existing table
819 * @param string $table Name of the table to modify
820 * @param string $oldIndex Old name of the index
821 * @param string $newIndex New name of the index
822 * @param bool $skipBothIndexExistWarning Whether to warn if both the
823 * old and the new indexes exist.
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 renameIndex( $table, $oldIndex, $newIndex,
829 $skipBothIndexExistWarning, $patch, $fullpath = false
831 if ( !$this->doTable( $table ) ) {
835 // First requirement: the table must exist
836 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
837 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
842 // Second requirement: the new index must be missing
843 if ( $this->db
->indexExists( $table, $newIndex, __METHOD__
) ) {
844 $this->output( "...index $newIndex already set on $table table.\n" );
845 if ( !$skipBothIndexExistWarning &&
846 $this->db
->indexExists( $table, $oldIndex, __METHOD__
)
848 $this->output( "...WARNING: $oldIndex still exists, despite it has " .
849 "been renamed into $newIndex (which also exists).\n" .
850 " $oldIndex should be manually removed if not needed anymore.\n" );
856 // Third requirement: the old index must exist
857 if ( !$this->db
->indexExists( $table, $oldIndex, __METHOD__
) ) {
858 $this->output( "...skipping: index $oldIndex doesn't exist.\n" );
863 // Requirements have been satisfied, patch can be applied
864 return $this->applyPatch(
867 "Renaming index $oldIndex into $newIndex to table $table"
872 * If the specified table exists, drop it, or execute the
873 * patch if one is provided.
877 * @param string $table Table to drop.
878 * @param string|bool $patch String of patch file that will drop the table. Default: false.
879 * @param bool $fullpath Whether $patch is a full path. Default: false.
880 * @return bool False if this was skipped because schema changes are skipped
882 public function dropTable( $table, $patch = false, $fullpath = false ) {
883 if ( !$this->doTable( $table ) ) {
887 if ( $this->db
->tableExists( $table, __METHOD__
) ) {
888 $msg = "Dropping table $table";
890 if ( $patch === false ) {
891 $this->output( "$msg ..." );
892 $this->db
->dropTable( $table, __METHOD__
);
893 $this->output( "done.\n" );
895 return $this->applyPatch( $patch, $fullpath, $msg );
898 $this->output( "...$table doesn't exist.\n" );
905 * Modify an existing field
907 * @param string $table Name of the table to which the field belongs
908 * @param string $field Name of the field to modify
909 * @param string $patch Path to the patch file
910 * @param bool $fullpath Whether to treat $patch path as a relative or not
911 * @return bool False if this was skipped because schema changes are skipped
913 public function modifyField( $table, $field, $patch, $fullpath = false ) {
914 if ( !$this->doTable( $table ) ) {
918 $updateKey = "$table-$field-$patch";
919 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
920 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
921 } elseif ( !$this->db
->fieldExists( $table, $field, __METHOD__
) ) {
922 $this->output( "...$field field does not exist in $table table, " .
923 "skipping modify field patch.\n" );
924 } elseif ( $this->updateRowExists( $updateKey ) ) {
925 $this->output( "...$field in table $table already modified by patch $patch.\n" );
927 $this->insertUpdateRow( $updateKey );
929 return $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
936 * Set any .htaccess files or equivilent for storage repos
938 * Some zones (e.g. "temp") used to be public and may have been initialized as such
940 public function setFileAccess() {
941 $repo = RepoGroup
::singleton()->getLocalRepo();
942 $zonePath = $repo->getZonePath( 'temp' );
943 if ( $repo->getBackend()->directoryExists( [ 'dir' => $zonePath ] ) ) {
944 // If the directory was never made, then it will have the right ACLs when it is made
945 $status = $repo->getBackend()->secure( [
950 if ( $status->isOK() ) {
951 $this->output( "Set the local repo temp zone container to be private.\n" );
953 $this->output( "Failed to set the local repo temp zone container to be private.\n" );
959 * Purge the objectcache table
961 public function purgeCache() {
962 global $wgLocalisationCacheConf;
963 # We can't guarantee that the user will be able to use TRUNCATE,
964 # but we know that DELETE is available to us
965 $this->output( "Purging caches..." );
966 $this->db
->delete( 'objectcache', '*', __METHOD__
);
967 if ( $wgLocalisationCacheConf['manualRecache'] ) {
968 $this->rebuildLocalisationCache();
970 $blobStore = new MessageBlobStore();
972 $this->db
->delete( 'module_deps', '*', __METHOD__
);
973 $this->output( "done.\n" );
977 * Check the site_stats table is not properly populated.
979 protected function checkStats() {
980 $this->output( "...site_stats is populated..." );
981 $row = $this->db
->selectRow( 'site_stats', '*', [ 'ss_row_id' => 1 ], __METHOD__
);
982 if ( $row === false ) {
983 $this->output( "data is missing! rebuilding...\n" );
984 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
985 $this->output( "missing ss_total_pages, rebuilding...\n" );
987 $this->output( "done.\n" );
991 SiteStatsInit
::doAllAndCommit( $this->db
);
994 # Common updater functions
997 * Sets the number of active users in the site_stats table
999 protected function doActiveUsersInit() {
1000 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', false, __METHOD__
);
1001 if ( $activeUsers == -1 ) {
1002 $activeUsers = $this->db
->selectField( 'recentchanges',
1003 'COUNT( DISTINCT rc_user_text )',
1004 [ 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ], __METHOD__
1006 $this->db
->update( 'site_stats',
1007 [ 'ss_active_users' => intval( $activeUsers ) ],
1008 [ 'ss_row_id' => 1 ], __METHOD__
, [ 'LIMIT' => 1 ]
1011 $this->output( "...ss_active_users user count set...\n" );
1015 * Populates the log_user_text field in the logging table
1017 protected function doLogUsertextPopulation() {
1018 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
1020 "Populating log_user_text field, printing progress markers. For large\n" .
1021 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1022 "maintenance/populateLogUsertext.php.\n"
1025 $task = $this->maintenance
->runChild( 'PopulateLogUsertext' );
1027 $this->output( "done.\n" );
1032 * Migrate log params to new table and index for searching
1034 protected function doLogSearchPopulation() {
1035 if ( !$this->updateRowExists( 'populate log_search' ) ) {
1037 "Populating log_search table, printing progress markers. For large\n" .
1038 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1039 "maintenance/populateLogSearch.php.\n" );
1041 $task = $this->maintenance
->runChild( 'PopulateLogSearch' );
1043 $this->output( "done.\n" );
1048 * Updates the timestamps in the transcache table
1051 protected function doUpdateTranscacheField() {
1052 if ( $this->updateRowExists( 'convert transcache field' ) ) {
1053 $this->output( "...transcache tc_time already converted.\n" );
1058 return $this->applyPatch( 'patch-tc-timestamp.sql', false,
1059 "Converting tc_time from UNIX epoch to MediaWiki timestamp" );
1063 * Update CategoryLinks collation
1065 protected function doCollationUpdate() {
1066 global $wgCategoryCollation;
1067 if ( $this->db
->fieldExists( 'categorylinks', 'cl_collation', __METHOD__
) ) {
1068 if ( $this->db
->selectField(
1071 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
1075 $this->output( "...collations up-to-date.\n" );
1080 $this->output( "Updating category collations..." );
1081 $task = $this->maintenance
->runChild( 'UpdateCollation' );
1083 $this->output( "...done.\n" );
1088 * Migrates user options from the user table blob to user_properties
1090 protected function doMigrateUserOptions() {
1091 if ( $this->db
->tableExists( 'user_properties' ) ) {
1092 $cl = $this->maintenance
->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
1094 $this->output( "done.\n" );
1099 * Enable profiling table when it's turned on
1101 protected function doEnableProfiling() {
1104 if ( !$this->doTable( 'profiling' ) ) {
1108 $profileToDb = false;
1109 if ( isset( $wgProfiler['output'] ) ) {
1110 $out = $wgProfiler['output'];
1111 if ( $out === 'db' ) {
1112 $profileToDb = true;
1113 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
1114 $profileToDb = true;
1118 if ( $profileToDb && !$this->db
->tableExists( 'profiling', __METHOD__
) ) {
1119 $this->applyPatch( 'patch-profiling.sql', false, 'Add profiling table' );
1124 * Rebuilds the localisation cache
1126 protected function rebuildLocalisationCache() {
1128 * @var $cl RebuildLocalisationCache
1130 $cl = $this->maintenance
->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
1131 $this->output( "Rebuilding localisation cache...\n" );
1134 $this->output( "done.\n" );
1138 * Turns off content handler fields during parts of the upgrade
1139 * where they aren't available.
1141 protected function disableContentHandlerUseDB() {
1142 global $wgContentHandlerUseDB;
1144 if ( $wgContentHandlerUseDB ) {
1145 $this->output( "Turning off Content Handler DB fields for this part of upgrade.\n" );
1146 $this->holdContentHandlerUseDB
= $wgContentHandlerUseDB;
1147 $wgContentHandlerUseDB = false;
1152 * Turns content handler fields back on.
1154 protected function enableContentHandlerUseDB() {
1155 global $wgContentHandlerUseDB;
1157 if ( $this->holdContentHandlerUseDB
) {
1158 $this->output( "Content Handler DB fields should be usable now.\n" );
1159 $wgContentHandlerUseDB = $this->holdContentHandlerUseDB
;