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(
642 [ $this, 'appendLine' ]
647 * Append a line to the open filehandle. The line is assumed to
648 * be a complete SQL statement.
650 * This is used as a callback for sourceLine().
652 * @param string $line Text to append to the file
653 * @return bool False to skip actually executing the file
654 * @throws MWException
656 public function appendLine( $line ) {
657 $line = rtrim( $line ) . ";\n";
658 if ( fwrite( $this->fileHandle
, $line ) === false ) {
659 throw new MWException( "trouble writing file" );
666 * Applies a SQL patch
668 * @param string $path Path to the patch file
669 * @param bool $isFullPath Whether to treat $path as a relative or not
670 * @param string $msg Description of the patch
671 * @return bool False if patch is skipped.
673 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
674 if ( $msg === null ) {
675 $msg = "Applying $path patch";
677 if ( $this->skipSchema
) {
678 $this->output( "...skipping schema change ($msg).\n" );
683 $this->output( "$msg ..." );
685 if ( !$isFullPath ) {
686 $path = $this->patchPath( $this->db
, $path );
688 if ( $this->fileHandle
!== null ) {
689 $this->copyFile( $path );
691 $this->db
->sourceFile( $path );
693 $this->output( "done.\n" );
699 * Get the full path of a patch file. Originally based on archive()
700 * from updaters.inc. Keep in mind this always returns a patch, as
701 * it fails back to MySQL if no DB-specific patch can be found
703 * @param IDatabase $db
704 * @param string $patch The name of the patch, like patch-something.sql
705 * @return string Full path to patch file
707 public function patchPath( IDatabase
$db, $patch ) {
710 $dbType = $db->getType();
711 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
712 return "$IP/maintenance/$dbType/archives/$patch";
714 return "$IP/maintenance/archives/$patch";
719 * Add a new table to the database
721 * @param string $name Name of the new table
722 * @param string $patch Path to the patch file
723 * @param bool $fullpath Whether to treat $patch path as a relative or not
724 * @return bool False if this was skipped because schema changes are skipped
726 protected function addTable( $name, $patch, $fullpath = false ) {
727 if ( !$this->doTable( $name ) ) {
731 if ( $this->db
->tableExists( $name, __METHOD__
) ) {
732 $this->output( "...$name table already exists.\n" );
734 return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
741 * Add a new field to an existing table
743 * @param string $table Name of the table to modify
744 * @param string $field Name of the new field
745 * @param string $patch Path to the patch file
746 * @param bool $fullpath Whether to treat $patch path as a relative or not
747 * @return bool False if this was skipped because schema changes are skipped
749 protected function addField( $table, $field, $patch, $fullpath = false ) {
750 if ( !$this->doTable( $table ) ) {
754 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
755 $this->output( "...$table table does not exist, skipping new field patch.\n" );
756 } elseif ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
757 $this->output( "...have $field field in $table table.\n" );
759 return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
766 * Add a new index to an existing table
768 * @param string $table Name of the table to modify
769 * @param string $index Name of the new index
770 * @param string $patch Path to the patch file
771 * @param bool $fullpath Whether to treat $patch path as a relative or not
772 * @return bool False if this was skipped because schema changes are skipped
774 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
775 if ( !$this->doTable( $table ) ) {
779 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
780 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
781 } elseif ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
782 $this->output( "...index $index already set on $table table.\n" );
784 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
791 * Drop a field from an existing table
793 * @param string $table Name of the table to modify
794 * @param string $field Name of the old field
795 * @param string $patch Path to the patch file
796 * @param bool $fullpath Whether to treat $patch path as a relative or not
797 * @return bool False if this was skipped because schema changes are skipped
799 protected function dropField( $table, $field, $patch, $fullpath = false ) {
800 if ( !$this->doTable( $table ) ) {
804 if ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
805 return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
807 $this->output( "...$table table does not contain $field field.\n" );
814 * Drop an index from an existing table
816 * @param string $table Name of the table to modify
817 * @param string $index Name of the index
818 * @param string $patch Path to the patch file
819 * @param bool $fullpath Whether to treat $patch path as a relative or not
820 * @return bool False if this was skipped because schema changes are skipped
822 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
823 if ( !$this->doTable( $table ) ) {
827 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
828 return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
830 $this->output( "...$index key doesn't exist.\n" );
837 * Rename an index from an existing table
839 * @param string $table Name of the table to modify
840 * @param string $oldIndex Old name of the index
841 * @param string $newIndex New name of the index
842 * @param bool $skipBothIndexExistWarning Whether to warn if both the
843 * old and the new indexes exist.
844 * @param string $patch Path to the patch file
845 * @param bool $fullpath Whether to treat $patch path as a relative or not
846 * @return bool False if this was skipped because schema changes are skipped
848 protected function renameIndex( $table, $oldIndex, $newIndex,
849 $skipBothIndexExistWarning, $patch, $fullpath = false
851 if ( !$this->doTable( $table ) ) {
855 // First requirement: the table must exist
856 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
857 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
862 // Second requirement: the new index must be missing
863 if ( $this->db
->indexExists( $table, $newIndex, __METHOD__
) ) {
864 $this->output( "...index $newIndex already set on $table table.\n" );
865 if ( !$skipBothIndexExistWarning &&
866 $this->db
->indexExists( $table, $oldIndex, __METHOD__
)
868 $this->output( "...WARNING: $oldIndex still exists, despite it has " .
869 "been renamed into $newIndex (which also exists).\n" .
870 " $oldIndex should be manually removed if not needed anymore.\n" );
876 // Third requirement: the old index must exist
877 if ( !$this->db
->indexExists( $table, $oldIndex, __METHOD__
) ) {
878 $this->output( "...skipping: index $oldIndex doesn't exist.\n" );
883 // Requirements have been satisfied, patch can be applied
884 return $this->applyPatch(
887 "Renaming index $oldIndex into $newIndex to table $table"
892 * If the specified table exists, drop it, or execute the
893 * patch if one is provided.
897 * @param string $table Table to drop.
898 * @param string|bool $patch String of patch file that will drop the table. Default: false.
899 * @param bool $fullpath Whether $patch is a full path. Default: false.
900 * @return bool False if this was skipped because schema changes are skipped
902 public function dropTable( $table, $patch = false, $fullpath = false ) {
903 if ( !$this->doTable( $table ) ) {
907 if ( $this->db
->tableExists( $table, __METHOD__
) ) {
908 $msg = "Dropping table $table";
910 if ( $patch === false ) {
911 $this->output( "$msg ..." );
912 $this->db
->dropTable( $table, __METHOD__
);
913 $this->output( "done.\n" );
915 return $this->applyPatch( $patch, $fullpath, $msg );
918 $this->output( "...$table doesn't exist.\n" );
925 * Modify an existing field
927 * @param string $table Name of the table to which the field belongs
928 * @param string $field Name of the field to modify
929 * @param string $patch Path to the patch file
930 * @param bool $fullpath Whether to treat $patch path as a relative or not
931 * @return bool False if this was skipped because schema changes are skipped
933 public function modifyField( $table, $field, $patch, $fullpath = false ) {
934 if ( !$this->doTable( $table ) ) {
938 $updateKey = "$table-$field-$patch";
939 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
940 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
941 } elseif ( !$this->db
->fieldExists( $table, $field, __METHOD__
) ) {
942 $this->output( "...$field field does not exist in $table table, " .
943 "skipping modify field patch.\n" );
944 } elseif ( $this->updateRowExists( $updateKey ) ) {
945 $this->output( "...$field in table $table already modified by patch $patch.\n" );
947 $this->insertUpdateRow( $updateKey );
949 return $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
956 * Set any .htaccess files or equivilent for storage repos
958 * Some zones (e.g. "temp") used to be public and may have been initialized as such
960 public function setFileAccess() {
961 $repo = RepoGroup
::singleton()->getLocalRepo();
962 $zonePath = $repo->getZonePath( 'temp' );
963 if ( $repo->getBackend()->directoryExists( [ 'dir' => $zonePath ] ) ) {
964 // If the directory was never made, then it will have the right ACLs when it is made
965 $status = $repo->getBackend()->secure( [
970 if ( $status->isOK() ) {
971 $this->output( "Set the local repo temp zone container to be private.\n" );
973 $this->output( "Failed to set the local repo temp zone container to be private.\n" );
979 * Purge the objectcache table
981 public function purgeCache() {
982 global $wgLocalisationCacheConf;
983 # We can't guarantee that the user will be able to use TRUNCATE,
984 # but we know that DELETE is available to us
985 $this->output( "Purging caches..." );
986 $this->db
->delete( 'objectcache', '*', __METHOD__
);
987 if ( $wgLocalisationCacheConf['manualRecache'] ) {
988 $this->rebuildLocalisationCache();
990 $blobStore = new MessageBlobStore();
992 $this->db
->delete( 'module_deps', '*', __METHOD__
);
993 $this->output( "done.\n" );
997 * Check the site_stats table is not properly populated.
999 protected function checkStats() {
1000 $this->output( "...site_stats is populated..." );
1001 $row = $this->db
->selectRow( 'site_stats', '*', [ 'ss_row_id' => 1 ], __METHOD__
);
1002 if ( $row === false ) {
1003 $this->output( "data is missing! rebuilding...\n" );
1004 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
1005 $this->output( "missing ss_total_pages, rebuilding...\n" );
1007 $this->output( "done.\n" );
1011 SiteStatsInit
::doAllAndCommit( $this->db
);
1014 # Common updater functions
1017 * Sets the number of active users in the site_stats table
1019 protected function doActiveUsersInit() {
1020 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', false, __METHOD__
);
1021 if ( $activeUsers == -1 ) {
1022 $activeUsers = $this->db
->selectField( 'recentchanges',
1023 'COUNT( DISTINCT rc_user_text )',
1024 [ 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ], __METHOD__
1026 $this->db
->update( 'site_stats',
1027 [ 'ss_active_users' => intval( $activeUsers ) ],
1028 [ 'ss_row_id' => 1 ], __METHOD__
, [ 'LIMIT' => 1 ]
1031 $this->output( "...ss_active_users user count set...\n" );
1035 * Populates the log_user_text field in the logging table
1037 protected function doLogUsertextPopulation() {
1038 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
1040 "Populating log_user_text field, printing progress markers. For large\n" .
1041 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1042 "maintenance/populateLogUsertext.php.\n"
1045 $task = $this->maintenance
->runChild( 'PopulateLogUsertext' );
1047 $this->output( "done.\n" );
1052 * Migrate log params to new table and index for searching
1054 protected function doLogSearchPopulation() {
1055 if ( !$this->updateRowExists( 'populate log_search' ) ) {
1057 "Populating log_search table, printing progress markers. For large\n" .
1058 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1059 "maintenance/populateLogSearch.php.\n" );
1061 $task = $this->maintenance
->runChild( 'PopulateLogSearch' );
1063 $this->output( "done.\n" );
1068 * Updates the timestamps in the transcache table
1071 protected function doUpdateTranscacheField() {
1072 if ( $this->updateRowExists( 'convert transcache field' ) ) {
1073 $this->output( "...transcache tc_time already converted.\n" );
1078 return $this->applyPatch( 'patch-tc-timestamp.sql', false,
1079 "Converting tc_time from UNIX epoch to MediaWiki timestamp" );
1083 * Update CategoryLinks collation
1085 protected function doCollationUpdate() {
1086 global $wgCategoryCollation;
1087 if ( $this->db
->fieldExists( 'categorylinks', 'cl_collation', __METHOD__
) ) {
1088 if ( $this->db
->selectField(
1091 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
1095 $this->output( "...collations up-to-date.\n" );
1100 $this->output( "Updating category collations..." );
1101 $task = $this->maintenance
->runChild( 'UpdateCollation' );
1103 $this->output( "...done.\n" );
1108 * Migrates user options from the user table blob to user_properties
1110 protected function doMigrateUserOptions() {
1111 if ( $this->db
->tableExists( 'user_properties' ) ) {
1112 $cl = $this->maintenance
->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
1114 $this->output( "done.\n" );
1119 * Enable profiling table when it's turned on
1121 protected function doEnableProfiling() {
1124 if ( !$this->doTable( 'profiling' ) ) {
1128 $profileToDb = false;
1129 if ( isset( $wgProfiler['output'] ) ) {
1130 $out = $wgProfiler['output'];
1131 if ( $out === 'db' ) {
1132 $profileToDb = true;
1133 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
1134 $profileToDb = true;
1138 if ( $profileToDb && !$this->db
->tableExists( 'profiling', __METHOD__
) ) {
1139 $this->applyPatch( 'patch-profiling.sql', false, 'Add profiling table' );
1144 * Rebuilds the localisation cache
1146 protected function rebuildLocalisationCache() {
1148 * @var $cl RebuildLocalisationCache
1150 $cl = $this->maintenance
->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
1151 $this->output( "Rebuilding localisation cache...\n" );
1154 $this->output( "done.\n" );
1158 * Turns off content handler fields during parts of the upgrade
1159 * where they aren't available.
1161 protected function disableContentHandlerUseDB() {
1162 global $wgContentHandlerUseDB;
1164 if ( $wgContentHandlerUseDB ) {
1165 $this->output( "Turning off Content Handler DB fields for this part of upgrade.\n" );
1166 $this->holdContentHandlerUseDB
= $wgContentHandlerUseDB;
1167 $wgContentHandlerUseDB = false;
1172 * Turns content handler fields back on.
1174 protected function enableContentHandlerUseDB() {
1175 global $wgContentHandlerUseDB;
1177 if ( $this->holdContentHandlerUseDB
) {
1178 $this->output( "Content Handler DB fields should be usable now.\n" );
1179 $wgContentHandlerUseDB = $this->holdContentHandlerUseDB
;