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
{
35 protected static $updateCounter = 0;
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
64 protected $shared = false;
67 * @var string[] Scripts to run after database update
68 * Should be a subclass of LoggedUpdateMaintenance
70 protected $postDatabaseUpdateMaintenance = [
71 DeleteDefaultMessages
::class,
72 PopulateRevisionLength
::class,
73 PopulateRevisionSha1
::class,
74 PopulateImageSha1
::class,
75 FixExtLinksProtocolRelative
::class,
76 PopulateFilearchiveSha1
::class,
77 PopulateBacklinkNamespace
::class,
78 FixDefaultJsonContentPages
::class,
79 CleanupEmptyCategories
::class,
80 AddRFCAndPMIDInterwiki
::class,
84 * File handle for SQL output.
88 protected $fileHandle = null;
91 * Flag specifying whether or not to skip schema (e.g. SQL-only) updates.
95 protected $skipSchema = false;
98 * Hold the value of $wgContentHandlerUseDB during the upgrade.
100 protected $holdContentHandlerUseDB = true;
105 * @param Database $db To perform updates on
106 * @param bool $shared Whether to perform updates on shared tables
107 * @param Maintenance $maintenance Maintenance object which created us
109 protected function __construct( Database
&$db, $shared, Maintenance
$maintenance = null ) {
111 $this->db
->setFlag( DBO_DDLMODE
); // For Oracle's handling of schema files
112 $this->shared
= $shared;
113 if ( $maintenance ) {
114 $this->maintenance
= $maintenance;
115 $this->fileHandle
= $maintenance->fileHandle
;
117 $this->maintenance
= new FakeMaintenance
;
119 $this->maintenance
->setDB( $db );
120 $this->initOldGlobals();
121 $this->loadExtensions();
122 Hooks
::run( 'LoadExtensionSchemaUpdates', [ $this ] );
126 * Initialize all of the old globals. One day this should all become
127 * something much nicer
129 private function initOldGlobals() {
130 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
131 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
133 # For extensions only, should be populated via hooks
134 # $wgDBtype should be checked to specifiy the proper file
135 $wgExtNewTables = []; // table, dir
136 $wgExtNewFields = []; // table, column, dir
137 $wgExtPGNewFields = []; // table, column, column attributes; for PostgreSQL
138 $wgExtPGAlteredFields = []; // table, column, new type, conversion method; for PostgreSQL
139 $wgExtNewIndexes = []; // table, index, dir
140 $wgExtModifiedFields = []; // table, index, dir
144 * Loads LocalSettings.php, if needed, and initialises everything needed for
145 * LoadExtensionSchemaUpdates hook.
147 private function loadExtensions() {
148 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
149 return; // already loaded
151 $vars = Installer
::getExistingLocalSettings();
153 $registry = ExtensionRegistry
::getInstance();
154 $queue = $registry->getQueue();
155 // Don't accidentally load extensions in the future
156 $registry->clearQueue();
158 // This will automatically add "AutoloadClasses" to $wgAutoloadClasses
159 $data = $registry->readFromQueue( $queue );
160 $hooks = [ 'wgHooks' => [ 'LoadExtensionSchemaUpdates' => [] ] ];
161 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
162 $hooks = $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'];
164 if ( $vars && isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
165 $hooks = array_merge_recursive( $hooks, $vars['wgHooks']['LoadExtensionSchemaUpdates'] );
167 global $wgHooks, $wgAutoloadClasses;
168 $wgHooks['LoadExtensionSchemaUpdates'] = $hooks;
169 if ( $vars && isset( $vars['wgAutoloadClasses'] ) ) {
170 $wgAutoloadClasses +
= $vars['wgAutoloadClasses'];
175 * @param Database $db
176 * @param bool $shared
177 * @param Maintenance $maintenance
179 * @throws MWException
180 * @return DatabaseUpdater
182 public static function newForDB( Database
$db, $shared = false, $maintenance = null ) {
183 $type = $db->getType();
184 if ( in_array( $type, Installer
::getDBTypes() ) ) {
185 $class = ucfirst( $type ) . 'Updater';
187 return new $class( $db, $shared, $maintenance );
189 throw new MWException( __METHOD__
. ' called for unsupported $wgDBtype' );
194 * Get a database connection to run updates
198 public function getDB() {
203 * Output some text. If we're running from web, escape the text first.
205 * @param string $str Text to output
207 public function output( $str ) {
208 if ( $this->maintenance
->isQuiet() ) {
211 global $wgCommandLineMode;
212 if ( !$wgCommandLineMode ) {
213 $str = htmlspecialchars( $str );
220 * Add a new update coming from an extension. This should be called by
221 * extensions while executing the LoadExtensionSchemaUpdates hook.
225 * @param array $update The update to run. Format is the following:
226 * first item is the callback function, it also can be a
227 * simple string with the name of a function in this class,
228 * following elements are parameters to the function.
229 * Note that callback functions will receive this object as
232 public function addExtensionUpdate( array $update ) {
233 $this->extensionUpdates
[] = $update;
237 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
238 * is the most common usage of updaters in an extension)
242 * @param string $tableName Name of table to create
243 * @param string $sqlPath Full path to the schema file
245 public function addExtensionTable( $tableName, $sqlPath ) {
246 $this->extensionUpdates
[] = [ 'addTable', $tableName, $sqlPath, true ];
252 * @param string $tableName
253 * @param string $indexName
254 * @param string $sqlPath
256 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
257 $this->extensionUpdates
[] = [ 'addIndex', $tableName, $indexName, $sqlPath, true ];
264 * @param string $tableName
265 * @param string $columnName
266 * @param string $sqlPath
268 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
269 $this->extensionUpdates
[] = [ 'addField', $tableName, $columnName, $sqlPath, true ];
276 * @param string $tableName
277 * @param string $columnName
278 * @param string $sqlPath
280 public function dropExtensionField( $tableName, $columnName, $sqlPath ) {
281 $this->extensionUpdates
[] = [ 'dropField', $tableName, $columnName, $sqlPath, true ];
285 * Drop an index from an extension table
289 * @param string $tableName The table name
290 * @param string $indexName The index name
291 * @param string $sqlPath The path to the SQL change path
293 public function dropExtensionIndex( $tableName, $indexName, $sqlPath ) {
294 $this->extensionUpdates
[] = [ 'dropIndex', $tableName, $indexName, $sqlPath, true ];
301 * @param string $tableName
302 * @param string $sqlPath
304 public function dropExtensionTable( $tableName, $sqlPath ) {
305 $this->extensionUpdates
[] = [ 'dropTable', $tableName, $sqlPath, true ];
309 * Rename an index on an extension table
313 * @param string $tableName The table name
314 * @param string $oldIndexName The old index name
315 * @param string $newIndexName The new index name
316 * @param string $sqlPath The path to the SQL change path
317 * @param bool $skipBothIndexExistWarning Whether to warn if both the old
318 * and the new indexes exist. [facultative; by default, false]
320 public function renameExtensionIndex( $tableName, $oldIndexName, $newIndexName,
321 $sqlPath, $skipBothIndexExistWarning = false
323 $this->extensionUpdates
[] = [
328 $skipBothIndexExistWarning,
337 * @param string $tableName The table name
338 * @param string $fieldName The field to be modified
339 * @param string $sqlPath The path to the SQL change path
341 public function modifyExtensionField( $tableName, $fieldName, $sqlPath ) {
342 $this->extensionUpdates
[] = [ 'modifyField', $tableName, $fieldName, $sqlPath, true ];
349 * @param string $tableName
352 public function tableExists( $tableName ) {
353 return ( $this->db
->tableExists( $tableName, __METHOD__
) );
357 * Add a maintenance script to be run after the database updates are complete.
359 * Script should subclass LoggedUpdateMaintenance
363 * @param string $class Name of a Maintenance subclass
365 public function addPostDatabaseUpdateMaintenance( $class ) {
366 $this->postDatabaseUpdateMaintenance
[] = $class;
370 * Get the list of extension-defined updates
374 protected function getExtensionUpdates() {
375 return $this->extensionUpdates
;
383 public function getPostDatabaseUpdateMaintenance() {
384 return $this->postDatabaseUpdateMaintenance
;
390 * Writes the schema updates desired to a file for the DB Admin to run.
391 * @param array $schemaUpdate
393 private function writeSchemaUpdateFile( $schemaUpdate = [] ) {
394 $updates = $this->updatesSkipped
;
395 $this->updatesSkipped
= [];
397 foreach ( $updates as $funcList ) {
398 $func = $funcList[0];
400 $origParams = $funcList[2];
401 call_user_func_array( $func, $arg );
403 $this->updatesSkipped
[] = $origParams;
408 * Get appropriate schema variables in the current database connection.
410 * This should be called after any request data has been imported, but before
411 * any write operations to the database. The result should be passed to the DB
412 * setSchemaVars() method.
417 public function getSchemaVars() {
418 return []; // DB-type specific
424 * @param array $what What updates to perform
426 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 $this->setAppliedUpdates( $wgVersion, $this->updates
);
447 if ( $this->fileHandle
) {
448 $this->skipSchema
= false;
449 $this->writeSchemaUpdateFile();
450 $this->setAppliedUpdates( "$wgVersion-schema", $this->updatesSkipped
);
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 * @param string $version
488 * @param array $updates
490 protected function setAppliedUpdates( $version, $updates = [] ) {
491 $this->db
->clearFlag( DBO_DDLMODE
);
492 if ( !$this->canUseNewUpdatelog() ) {
495 $key = "updatelist-$version-" . time() . self
::$updateCounter;
496 self
::$updateCounter++
;
497 $this->db
->insert( 'updatelog',
498 [ 'ul_key' => $key, 'ul_value' => serialize( $updates ) ],
500 $this->db
->setFlag( DBO_DDLMODE
);
504 * Helper function: check if the given key is present in the updatelog table.
505 * Obviously, only use this for updates that occur after the updatelog table was
507 * @param string $key Name of the key to check for
510 public function updateRowExists( $key ) {
511 $row = $this->db
->selectRow(
515 [ 'ul_key' => $key ],
523 * Helper function: Add a key to the updatelog table
524 * Obviously, only use this for updates that occur after the updatelog table was
526 * @param string $key Name of key to insert
527 * @param string $val [optional] Value to insert along with the key
529 public function insertUpdateRow( $key, $val = null ) {
530 $this->db
->clearFlag( DBO_DDLMODE
);
531 $values = [ 'ul_key' => $key ];
532 if ( $val && $this->canUseNewUpdatelog() ) {
533 $values['ul_value'] = $val;
535 $this->db
->insert( 'updatelog', $values, __METHOD__
, 'IGNORE' );
536 $this->db
->setFlag( DBO_DDLMODE
);
540 * Updatelog was changed in 1.17 to have a ul_value column so we can record
541 * more information about what kind of updates we've done (that's what this
542 * class does). Pre-1.17 wikis won't have this column, and really old wikis
543 * might not even have updatelog at all
547 protected function canUseNewUpdatelog() {
548 return $this->db
->tableExists( 'updatelog', __METHOD__
) &&
549 $this->db
->fieldExists( 'updatelog', 'ul_value', __METHOD__
);
553 * Returns whether updates should be executed on the database table $name.
554 * Updates will be prevented if the table is a shared table and it is not
555 * specified to run updates on shared tables.
557 * @param string $name Table name
560 protected function doTable( $name ) {
561 global $wgSharedDB, $wgSharedTables;
563 // Don't bother to check $wgSharedTables if there isn't a shared database
564 // or the user actually also wants to do updates on the shared database.
565 if ( $wgSharedDB === null ||
$this->shared
) {
569 if ( in_array( $name, $wgSharedTables ) ) {
570 $this->output( "...skipping update to shared table $name.\n" );
578 * Before 1.17, we used to handle updates via stuff like
579 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
580 * of this in 1.17 but we want to remain back-compatible for a while. So
581 * load up these old global-based things into our update list.
585 protected function getOldGlobalUpdates() {
586 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
591 foreach ( $wgExtNewTables as $tableRecord ) {
593 'addTable', $tableRecord[0], $tableRecord[1], true
597 foreach ( $wgExtNewFields as $fieldRecord ) {
599 'addField', $fieldRecord[0], $fieldRecord[1],
600 $fieldRecord[2], true
604 foreach ( $wgExtNewIndexes as $fieldRecord ) {
606 'addIndex', $fieldRecord[0], $fieldRecord[1],
607 $fieldRecord[2], true
611 foreach ( $wgExtModifiedFields as $fieldRecord ) {
613 'modifyField', $fieldRecord[0], $fieldRecord[1],
614 $fieldRecord[2], true
622 * Get an array of updates to perform on the database. Should return a
623 * multi-dimensional array. The main key is the MediaWiki version (1.12,
624 * 1.13...) with the values being arrays of updates, identical to how
625 * updaters.inc did it (for now)
629 abstract protected function getCoreUpdateList();
632 * Append an SQL fragment to the open file handle.
634 * @param string $filename File name to open
636 public function copyFile( $filename ) {
637 $this->db
->sourceFile( $filename, false, false, false,
638 [ $this, 'appendLine' ]
643 * Append a line to the open filehandle. The line is assumed to
644 * be a complete SQL statement.
646 * This is used as a callback for sourceLine().
648 * @param string $line Text to append to the file
649 * @return bool False to skip actually executing the file
650 * @throws MWException
652 public function appendLine( $line ) {
653 $line = rtrim( $line ) . ";\n";
654 if ( fwrite( $this->fileHandle
, $line ) === false ) {
655 throw new MWException( "trouble writing file" );
662 * Applies a SQL patch
664 * @param string $path Path to the patch file
665 * @param bool $isFullPath Whether to treat $path as a relative or not
666 * @param string $msg Description of the patch
667 * @return bool False if patch is skipped.
669 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
670 if ( $msg === null ) {
671 $msg = "Applying $path patch";
673 if ( $this->skipSchema
) {
674 $this->output( "...skipping schema change ($msg).\n" );
679 $this->output( "$msg ..." );
681 if ( !$isFullPath ) {
682 $path = $this->patchPath( $this->db
, $path );
684 if ( $this->fileHandle
!== null ) {
685 $this->copyFile( $path );
687 $this->db
->sourceFile( $path );
689 $this->output( "done.\n" );
695 * Get the full path of a patch file. Originally based on archive()
696 * from updaters.inc. Keep in mind this always returns a patch, as
697 * it fails back to MySQL if no DB-specific patch can be found
699 * @param IDatabase $db
700 * @param string $patch The name of the patch, like patch-something.sql
701 * @return string Full path to patch file
703 public function patchPath( IDatabase
$db, $patch ) {
706 $dbType = $db->getType();
707 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
708 return "$IP/maintenance/$dbType/archives/$patch";
710 return "$IP/maintenance/archives/$patch";
715 * Add a new table to the database
717 * @param string $name Name of the new table
718 * @param string $patch Path to the patch file
719 * @param bool $fullpath Whether to treat $patch path as a relative or not
720 * @return bool False if this was skipped because schema changes are skipped
722 protected function addTable( $name, $patch, $fullpath = false ) {
723 if ( !$this->doTable( $name ) ) {
727 if ( $this->db
->tableExists( $name, __METHOD__
) ) {
728 $this->output( "...$name table already exists.\n" );
730 return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
737 * Add a new field to an existing table
739 * @param string $table Name of the table to modify
740 * @param string $field Name of the new field
741 * @param string $patch Path to the patch file
742 * @param bool $fullpath Whether to treat $patch path as a relative or not
743 * @return bool False if this was skipped because schema changes are skipped
745 protected function addField( $table, $field, $patch, $fullpath = false ) {
746 if ( !$this->doTable( $table ) ) {
750 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
751 $this->output( "...$table table does not exist, skipping new field patch.\n" );
752 } elseif ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
753 $this->output( "...have $field field in $table table.\n" );
755 return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
762 * Add a new index to an existing table
764 * @param string $table Name of the table to modify
765 * @param string $index Name of the new index
766 * @param string $patch Path to the patch file
767 * @param bool $fullpath Whether to treat $patch path as a relative or not
768 * @return bool False if this was skipped because schema changes are skipped
770 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
771 if ( !$this->doTable( $table ) ) {
775 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
776 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
777 } elseif ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
778 $this->output( "...index $index already set on $table table.\n" );
780 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
787 * Drop a field from an existing table
789 * @param string $table Name of the table to modify
790 * @param string $field Name of the old field
791 * @param string $patch Path to the patch file
792 * @param bool $fullpath Whether to treat $patch path as a relative or not
793 * @return bool False if this was skipped because schema changes are skipped
795 protected function dropField( $table, $field, $patch, $fullpath = false ) {
796 if ( !$this->doTable( $table ) ) {
800 if ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
801 return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
803 $this->output( "...$table table does not contain $field field.\n" );
810 * Drop an index from an existing table
812 * @param string $table Name of the table to modify
813 * @param string $index Name of the index
814 * @param string $patch Path to the patch file
815 * @param bool $fullpath Whether to treat $patch path as a relative or not
816 * @return bool False if this was skipped because schema changes are skipped
818 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
819 if ( !$this->doTable( $table ) ) {
823 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
824 return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
826 $this->output( "...$index key doesn't exist.\n" );
833 * Rename an index from an existing table
835 * @param string $table Name of the table to modify
836 * @param string $oldIndex Old name of the index
837 * @param string $newIndex New name of the index
838 * @param bool $skipBothIndexExistWarning Whether to warn if both the
839 * old and the new indexes exist.
840 * @param string $patch Path to the patch file
841 * @param bool $fullpath Whether to treat $patch path as a relative or not
842 * @return bool False if this was skipped because schema changes are skipped
844 protected function renameIndex( $table, $oldIndex, $newIndex,
845 $skipBothIndexExistWarning, $patch, $fullpath = false
847 if ( !$this->doTable( $table ) ) {
851 // First requirement: the table must exist
852 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
853 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
858 // Second requirement: the new index must be missing
859 if ( $this->db
->indexExists( $table, $newIndex, __METHOD__
) ) {
860 $this->output( "...index $newIndex already set on $table table.\n" );
861 if ( !$skipBothIndexExistWarning &&
862 $this->db
->indexExists( $table, $oldIndex, __METHOD__
)
864 $this->output( "...WARNING: $oldIndex still exists, despite it has " .
865 "been renamed into $newIndex (which also exists).\n" .
866 " $oldIndex should be manually removed if not needed anymore.\n" );
872 // Third requirement: the old index must exist
873 if ( !$this->db
->indexExists( $table, $oldIndex, __METHOD__
) ) {
874 $this->output( "...skipping: index $oldIndex doesn't exist.\n" );
879 // Requirements have been satisfied, patch can be applied
880 return $this->applyPatch(
883 "Renaming index $oldIndex into $newIndex to table $table"
888 * If the specified table exists, drop it, or execute the
889 * patch if one is provided.
893 * @param string $table Table to drop.
894 * @param string|bool $patch String of patch file that will drop the table. Default: false.
895 * @param bool $fullpath Whether $patch is a full path. Default: false.
896 * @return bool False if this was skipped because schema changes are skipped
898 public function dropTable( $table, $patch = false, $fullpath = false ) {
899 if ( !$this->doTable( $table ) ) {
903 if ( $this->db
->tableExists( $table, __METHOD__
) ) {
904 $msg = "Dropping table $table";
906 if ( $patch === false ) {
907 $this->output( "$msg ..." );
908 $this->db
->dropTable( $table, __METHOD__
);
909 $this->output( "done.\n" );
911 return $this->applyPatch( $patch, $fullpath, $msg );
914 $this->output( "...$table doesn't exist.\n" );
921 * Modify an existing field
923 * @param string $table Name of the table to which the field belongs
924 * @param string $field Name of the field to modify
925 * @param string $patch Path to the patch file
926 * @param bool $fullpath Whether to treat $patch path as a relative or not
927 * @return bool False if this was skipped because schema changes are skipped
929 public function modifyField( $table, $field, $patch, $fullpath = false ) {
930 if ( !$this->doTable( $table ) ) {
934 $updateKey = "$table-$field-$patch";
935 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
936 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
937 } elseif ( !$this->db
->fieldExists( $table, $field, __METHOD__
) ) {
938 $this->output( "...$field field does not exist in $table table, " .
939 "skipping modify field patch.\n" );
940 } elseif ( $this->updateRowExists( $updateKey ) ) {
941 $this->output( "...$field in table $table already modified by patch $patch.\n" );
943 $this->insertUpdateRow( $updateKey );
945 return $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
952 * Set any .htaccess files or equivilent for storage repos
954 * Some zones (e.g. "temp") used to be public and may have been initialized as such
956 public function setFileAccess() {
957 $repo = RepoGroup
::singleton()->getLocalRepo();
958 $zonePath = $repo->getZonePath( 'temp' );
959 if ( $repo->getBackend()->directoryExists( [ 'dir' => $zonePath ] ) ) {
960 // If the directory was never made, then it will have the right ACLs when it is made
961 $status = $repo->getBackend()->secure( [
966 if ( $status->isOK() ) {
967 $this->output( "Set the local repo temp zone container to be private.\n" );
969 $this->output( "Failed to set the local repo temp zone container to be private.\n" );
975 * Purge the objectcache table
977 public function purgeCache() {
978 global $wgLocalisationCacheConf;
979 # We can't guarantee that the user will be able to use TRUNCATE,
980 # but we know that DELETE is available to us
981 $this->output( "Purging caches..." );
982 $this->db
->delete( 'objectcache', '*', __METHOD__
);
983 if ( $wgLocalisationCacheConf['manualRecache'] ) {
984 $this->rebuildLocalisationCache();
986 $blobStore = new MessageBlobStore();
988 $this->db
->delete( 'module_deps', '*', __METHOD__
);
989 $this->output( "done.\n" );
993 * Check the site_stats table is not properly populated.
995 protected function checkStats() {
996 $this->output( "...site_stats is populated..." );
997 $row = $this->db
->selectRow( 'site_stats', '*', [ 'ss_row_id' => 1 ], __METHOD__
);
998 if ( $row === false ) {
999 $this->output( "data is missing! rebuilding...\n" );
1000 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
1001 $this->output( "missing ss_total_pages, rebuilding...\n" );
1003 $this->output( "done.\n" );
1007 SiteStatsInit
::doAllAndCommit( $this->db
);
1010 # Common updater functions
1013 * Sets the number of active users in the site_stats table
1015 protected function doActiveUsersInit() {
1016 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', false, __METHOD__
);
1017 if ( $activeUsers == -1 ) {
1018 $activeUsers = $this->db
->selectField( 'recentchanges',
1019 'COUNT( DISTINCT rc_user_text )',
1020 [ 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ], __METHOD__
1022 $this->db
->update( 'site_stats',
1023 [ 'ss_active_users' => intval( $activeUsers ) ],
1024 [ 'ss_row_id' => 1 ], __METHOD__
, [ 'LIMIT' => 1 ]
1027 $this->output( "...ss_active_users user count set...\n" );
1031 * Populates the log_user_text field in the logging table
1033 protected function doLogUsertextPopulation() {
1034 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
1036 "Populating log_user_text field, printing progress markers. For large\n" .
1037 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1038 "maintenance/populateLogUsertext.php.\n"
1041 $task = $this->maintenance
->runChild( 'PopulateLogUsertext' );
1043 $this->output( "done.\n" );
1048 * Migrate log params to new table and index for searching
1050 protected function doLogSearchPopulation() {
1051 if ( !$this->updateRowExists( 'populate log_search' ) ) {
1053 "Populating log_search table, printing progress markers. For large\n" .
1054 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1055 "maintenance/populateLogSearch.php.\n" );
1057 $task = $this->maintenance
->runChild( 'PopulateLogSearch' );
1059 $this->output( "done.\n" );
1064 * Updates the timestamps in the transcache table
1067 protected function doUpdateTranscacheField() {
1068 if ( $this->updateRowExists( 'convert transcache field' ) ) {
1069 $this->output( "...transcache tc_time already converted.\n" );
1074 return $this->applyPatch( 'patch-tc-timestamp.sql', false,
1075 "Converting tc_time from UNIX epoch to MediaWiki timestamp" );
1079 * Update CategoryLinks collation
1081 protected function doCollationUpdate() {
1082 global $wgCategoryCollation;
1083 if ( $this->db
->fieldExists( 'categorylinks', 'cl_collation', __METHOD__
) ) {
1084 if ( $this->db
->selectField(
1087 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
1091 $this->output( "...collations up-to-date.\n" );
1096 $this->output( "Updating category collations..." );
1097 $task = $this->maintenance
->runChild( 'UpdateCollation' );
1099 $this->output( "...done.\n" );
1104 * Migrates user options from the user table blob to user_properties
1106 protected function doMigrateUserOptions() {
1107 if ( $this->db
->tableExists( 'user_properties' ) ) {
1108 $cl = $this->maintenance
->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
1110 $this->output( "done.\n" );
1115 * Enable profiling table when it's turned on
1117 protected function doEnableProfiling() {
1120 if ( !$this->doTable( 'profiling' ) ) {
1124 $profileToDb = false;
1125 if ( isset( $wgProfiler['output'] ) ) {
1126 $out = $wgProfiler['output'];
1127 if ( $out === 'db' ) {
1128 $profileToDb = true;
1129 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
1130 $profileToDb = true;
1134 if ( $profileToDb && !$this->db
->tableExists( 'profiling', __METHOD__
) ) {
1135 $this->applyPatch( 'patch-profiling.sql', false, 'Add profiling table' );
1140 * Rebuilds the localisation cache
1142 protected function rebuildLocalisationCache() {
1144 * @var $cl RebuildLocalisationCache
1146 $cl = $this->maintenance
->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
1147 $this->output( "Rebuilding localisation cache...\n" );
1150 $this->output( "done.\n" );
1154 * Turns off content handler fields during parts of the upgrade
1155 * where they aren't available.
1157 protected function disableContentHandlerUseDB() {
1158 global $wgContentHandlerUseDB;
1160 if ( $wgContentHandlerUseDB ) {
1161 $this->output( "Turning off Content Handler DB fields for this part of upgrade.\n" );
1162 $this->holdContentHandlerUseDB
= $wgContentHandlerUseDB;
1163 $wgContentHandlerUseDB = false;
1168 * Turns content handler fields back on.
1170 protected function enableContentHandlerUseDB() {
1171 global $wgContentHandlerUseDB;
1173 if ( $this->holdContentHandlerUseDB
) {
1174 $this->output( "Content Handler DB fields should be usable now.\n" );
1175 $wgContentHandlerUseDB = $this->holdContentHandlerUseDB
;