3 * DBMS-specific updater helper.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use Wikimedia\Rdbms\Database
;
24 use Wikimedia\Rdbms\IDatabase
;
25 use MediaWiki\MediaWikiServices
;
27 require_once __DIR__
. '/../../maintenance/Maintenance.php';
30 * Class for handling database updates. Roughly based off of updaters.inc, with
31 * a few improvements :)
36 abstract class DatabaseUpdater
{
38 * Array of updates to perform on the database
42 protected $updates = [];
45 * Array of updates that were skipped
49 protected $updatesSkipped = [];
52 * List of extension-provided database updates
55 protected $extensionUpdates = [];
58 * Handle to the database subclass
67 protected $maintenance;
69 protected $shared = false;
72 * @var string[] Scripts to run after database update
73 * Should be a subclass of LoggedUpdateMaintenance
75 protected $postDatabaseUpdateMaintenance = [
76 DeleteDefaultMessages
::class,
77 PopulateRevisionLength
::class,
78 PopulateRevisionSha1
::class,
79 PopulateImageSha1
::class,
80 FixExtLinksProtocolRelative
::class,
81 PopulateFilearchiveSha1
::class,
82 PopulateBacklinkNamespace
::class,
83 FixDefaultJsonContentPages
::class,
84 CleanupEmptyCategories
::class,
85 AddRFCAndPMIDInterwiki
::class,
86 PopulatePPSortKey
::class
90 * File handle for SQL output.
94 protected $fileHandle = null;
97 * Flag specifying whether or not to skip schema (e.g. SQL-only) updates.
101 protected $skipSchema = false;
104 * Hold the value of $wgContentHandlerUseDB during the upgrade.
106 protected $holdContentHandlerUseDB = true;
109 * @param Database &$db To perform updates on
110 * @param bool $shared Whether to perform updates on shared tables
111 * @param Maintenance $maintenance Maintenance object which created us
113 protected function __construct( Database
&$db, $shared, Maintenance
$maintenance = null ) {
115 $this->db
->setFlag( DBO_DDLMODE
); // For Oracle's handling of schema files
116 $this->shared
= $shared;
117 if ( $maintenance ) {
118 $this->maintenance
= $maintenance;
119 $this->fileHandle
= $maintenance->fileHandle
;
121 $this->maintenance
= new FakeMaintenance
;
123 $this->maintenance
->setDB( $db );
124 $this->initOldGlobals();
125 $this->loadExtensions();
126 Hooks
::run( 'LoadExtensionSchemaUpdates', [ $this ] );
130 * Initialize all of the old globals. One day this should all become
131 * something much nicer
133 private function initOldGlobals() {
134 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
135 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
137 # For extensions only, should be populated via hooks
138 # $wgDBtype should be checked to specifiy the proper file
139 $wgExtNewTables = []; // table, dir
140 $wgExtNewFields = []; // table, column, dir
141 $wgExtPGNewFields = []; // table, column, column attributes; for PostgreSQL
142 $wgExtPGAlteredFields = []; // table, column, new type, conversion method; for PostgreSQL
143 $wgExtNewIndexes = []; // table, index, dir
144 $wgExtModifiedFields = []; // table, index, dir
148 * Loads LocalSettings.php, if needed, and initialises everything needed for
149 * LoadExtensionSchemaUpdates hook.
151 private function loadExtensions() {
152 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
153 return; // already loaded
155 $vars = Installer
::getExistingLocalSettings();
157 $registry = ExtensionRegistry
::getInstance();
158 $queue = $registry->getQueue();
159 // Don't accidentally load extensions in the future
160 $registry->clearQueue();
162 // This will automatically add "AutoloadClasses" to $wgAutoloadClasses
163 $data = $registry->readFromQueue( $queue );
164 $hooks = [ 'wgHooks' => [ 'LoadExtensionSchemaUpdates' => [] ] ];
165 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
166 $hooks = $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'];
168 if ( $vars && isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
169 $hooks = array_merge_recursive( $hooks, $vars['wgHooks']['LoadExtensionSchemaUpdates'] );
171 global $wgHooks, $wgAutoloadClasses;
172 $wgHooks['LoadExtensionSchemaUpdates'] = $hooks;
173 if ( $vars && isset( $vars['wgAutoloadClasses'] ) ) {
174 $wgAutoloadClasses +
= $vars['wgAutoloadClasses'];
179 * @param Database $db
180 * @param bool $shared
181 * @param Maintenance $maintenance
183 * @throws MWException
184 * @return DatabaseUpdater
186 public static function newForDB( Database
$db, $shared = false, $maintenance = null ) {
187 $type = $db->getType();
188 if ( in_array( $type, Installer
::getDBTypes() ) ) {
189 $class = ucfirst( $type ) . 'Updater';
191 return new $class( $db, $shared, $maintenance );
193 throw new MWException( __METHOD__
. ' called for unsupported $wgDBtype' );
198 * Get a database connection to run updates
202 public function getDB() {
207 * Output some text. If we're running from web, escape the text first.
209 * @param string $str Text to output
211 public function output( $str ) {
212 if ( $this->maintenance
->isQuiet() ) {
215 global $wgCommandLineMode;
216 if ( !$wgCommandLineMode ) {
217 $str = htmlspecialchars( $str );
224 * Add a new update coming from an extension. This should be called by
225 * extensions while executing the LoadExtensionSchemaUpdates hook.
229 * @param array $update The update to run. Format is [ $callback, $params... ]
230 * $callback is the method to call; either a DatabaseUpdater method name or a callable.
231 * Must be serializable (ie. no anonymous functions allowed). The rest of the parameters
232 * (if any) will be passed to the callback. The first parameter passed to the callback
233 * is always this object.
235 public function addExtensionUpdate( array $update ) {
236 $this->extensionUpdates
[] = $update;
240 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
241 * is the most common usage of updaters in an extension)
245 * @param string $tableName Name of table to create
246 * @param string $sqlPath Full path to the schema file
248 public function addExtensionTable( $tableName, $sqlPath ) {
249 $this->extensionUpdates
[] = [ 'addTable', $tableName, $sqlPath, true ];
255 * @param string $tableName
256 * @param string $indexName
257 * @param string $sqlPath
259 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
260 $this->extensionUpdates
[] = [ 'addIndex', $tableName, $indexName, $sqlPath, true ];
267 * @param string $tableName
268 * @param string $columnName
269 * @param string $sqlPath
271 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
272 $this->extensionUpdates
[] = [ 'addField', $tableName, $columnName, $sqlPath, true ];
279 * @param string $tableName
280 * @param string $columnName
281 * @param string $sqlPath
283 public function dropExtensionField( $tableName, $columnName, $sqlPath ) {
284 $this->extensionUpdates
[] = [ 'dropField', $tableName, $columnName, $sqlPath, true ];
288 * Drop an index from an extension table
292 * @param string $tableName The table name
293 * @param string $indexName The index name
294 * @param string $sqlPath The path to the SQL change path
296 public function dropExtensionIndex( $tableName, $indexName, $sqlPath ) {
297 $this->extensionUpdates
[] = [ 'dropIndex', $tableName, $indexName, $sqlPath, true ];
304 * @param string $tableName
305 * @param string $sqlPath
307 public function dropExtensionTable( $tableName, $sqlPath ) {
308 $this->extensionUpdates
[] = [ 'dropTable', $tableName, $sqlPath, true ];
312 * Rename an index on an extension table
316 * @param string $tableName The table name
317 * @param string $oldIndexName The old index name
318 * @param string $newIndexName The new index name
319 * @param string $sqlPath The path to the SQL change path
320 * @param bool $skipBothIndexExistWarning Whether to warn if both the old
321 * and the new indexes exist. [facultative; by default, false]
323 public function renameExtensionIndex( $tableName, $oldIndexName, $newIndexName,
324 $sqlPath, $skipBothIndexExistWarning = false
326 $this->extensionUpdates
[] = [
331 $skipBothIndexExistWarning,
340 * @param string $tableName The table name
341 * @param string $fieldName The field to be modified
342 * @param string $sqlPath The path to the SQL change path
344 public function modifyExtensionField( $tableName, $fieldName, $sqlPath ) {
345 $this->extensionUpdates
[] = [ 'modifyField', $tableName, $fieldName, $sqlPath, true ];
352 * @param string $tableName
355 public function tableExists( $tableName ) {
356 return ( $this->db
->tableExists( $tableName, __METHOD__
) );
360 * Add a maintenance script to be run after the database updates are complete.
362 * Script should subclass LoggedUpdateMaintenance
366 * @param string $class Name of a Maintenance subclass
368 public function addPostDatabaseUpdateMaintenance( $class ) {
369 $this->postDatabaseUpdateMaintenance
[] = $class;
373 * Get the list of extension-defined updates
377 protected function getExtensionUpdates() {
378 return $this->extensionUpdates
;
386 public function getPostDatabaseUpdateMaintenance() {
387 return $this->postDatabaseUpdateMaintenance
;
393 * Writes the schema updates desired to a file for the DB Admin to run.
394 * @param array $schemaUpdate
396 private function writeSchemaUpdateFile( array $schemaUpdate = [] ) {
397 $updates = $this->updatesSkipped
;
398 $this->updatesSkipped
= [];
400 foreach ( $updates as $funcList ) {
401 $func = $funcList[0];
403 $origParams = $funcList[2];
404 call_user_func_array( $func, $arg );
406 $this->updatesSkipped
[] = $origParams;
411 * Get appropriate schema variables in the current database connection.
413 * This should be called after any request data has been imported, but before
414 * any write operations to the database. The result should be passed to the DB
415 * setSchemaVars() method.
420 public function getSchemaVars() {
421 return []; // DB-type specific
427 * @param array $what What updates to perform
429 public function doUpdates( array $what = [ 'core', 'extensions', 'stats' ] ) {
430 $this->db
->setSchemaVars( $this->getSchemaVars() );
432 $what = array_flip( $what );
433 $this->skipSchema
= isset( $what['noschema'] ) ||
$this->fileHandle
!== null;
434 if ( isset( $what['core'] ) ) {
435 $this->runUpdates( $this->getCoreUpdateList(), false );
437 if ( isset( $what['extensions'] ) ) {
438 $this->runUpdates( $this->getOldGlobalUpdates(), false );
439 $this->runUpdates( $this->getExtensionUpdates(), true );
442 if ( isset( $what['stats'] ) ) {
446 if ( $this->fileHandle
) {
447 $this->skipSchema
= false;
448 $this->writeSchemaUpdateFile();
453 * Helper function for doUpdates()
455 * @param array $updates Array of updates to run
456 * @param bool $passSelf Whether to pass this object we calling external functions
458 private function runUpdates( array $updates, $passSelf ) {
459 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
462 $updatesSkipped = [];
463 foreach ( $updates as $params ) {
464 $origParams = $params;
465 $func = array_shift( $params );
466 if ( !is_array( $func ) && method_exists( $this, $func ) ) {
467 $func = [ $this, $func ];
468 } elseif ( $passSelf ) {
469 array_unshift( $params, $this );
471 $ret = call_user_func_array( $func, $params );
473 if ( $ret !== false ) {
474 $updatesDone[] = $origParams;
475 $lbFactory->waitForReplication();
477 $updatesSkipped[] = [ $func, $params, $origParams ];
480 $this->updatesSkipped
= array_merge( $this->updatesSkipped
, $updatesSkipped );
481 $this->updates
= array_merge( $this->updates
, $updatesDone );
485 * Helper function: check if the given key is present in the updatelog table.
486 * Obviously, only use this for updates that occur after the updatelog table was
488 * @param string $key Name of the key to check for
491 public function updateRowExists( $key ) {
492 $row = $this->db
->selectRow(
496 [ 'ul_key' => $key ],
504 * Helper function: Add a key to the updatelog table
505 * Obviously, only use this for updates that occur after the updatelog table was
507 * @param string $key Name of key to insert
508 * @param string $val [optional] Value to insert along with the key
510 public function insertUpdateRow( $key, $val = null ) {
511 $this->db
->clearFlag( DBO_DDLMODE
);
512 $values = [ 'ul_key' => $key ];
513 if ( $val && $this->canUseNewUpdatelog() ) {
514 $values['ul_value'] = $val;
516 $this->db
->insert( 'updatelog', $values, __METHOD__
, 'IGNORE' );
517 $this->db
->setFlag( DBO_DDLMODE
);
521 * Updatelog was changed in 1.17 to have a ul_value column so we can record
522 * more information about what kind of updates we've done (that's what this
523 * class does). Pre-1.17 wikis won't have this column, and really old wikis
524 * might not even have updatelog at all
528 protected function canUseNewUpdatelog() {
529 return $this->db
->tableExists( 'updatelog', __METHOD__
) &&
530 $this->db
->fieldExists( 'updatelog', 'ul_value', __METHOD__
);
534 * Returns whether updates should be executed on the database table $name.
535 * Updates will be prevented if the table is a shared table and it is not
536 * specified to run updates on shared tables.
538 * @param string $name Table name
541 protected function doTable( $name ) {
542 global $wgSharedDB, $wgSharedTables;
544 // Don't bother to check $wgSharedTables if there isn't a shared database
545 // or the user actually also wants to do updates on the shared database.
546 if ( $wgSharedDB === null ||
$this->shared
) {
550 if ( in_array( $name, $wgSharedTables ) ) {
551 $this->output( "...skipping update to shared table $name.\n" );
559 * Before 1.17, we used to handle updates via stuff like
560 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
561 * of this in 1.17 but we want to remain back-compatible for a while. So
562 * load up these old global-based things into our update list.
566 protected function getOldGlobalUpdates() {
567 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
572 foreach ( $wgExtNewTables as $tableRecord ) {
574 'addTable', $tableRecord[0], $tableRecord[1], true
578 foreach ( $wgExtNewFields as $fieldRecord ) {
580 'addField', $fieldRecord[0], $fieldRecord[1],
581 $fieldRecord[2], true
585 foreach ( $wgExtNewIndexes as $fieldRecord ) {
587 'addIndex', $fieldRecord[0], $fieldRecord[1],
588 $fieldRecord[2], true
592 foreach ( $wgExtModifiedFields as $fieldRecord ) {
594 'modifyField', $fieldRecord[0], $fieldRecord[1],
595 $fieldRecord[2], true
603 * Get an array of updates to perform on the database. Should return a
604 * multi-dimensional array. The main key is the MediaWiki version (1.12,
605 * 1.13...) with the values being arrays of updates, identical to how
606 * updaters.inc did it (for now)
610 abstract protected function getCoreUpdateList();
613 * Append an SQL fragment to the open file handle.
615 * @param string $filename File name to open
617 public function copyFile( $filename ) {
618 $this->db
->sourceFile(
623 [ $this, 'appendLine' ]
628 * Append a line to the open filehandle. The line is assumed to
629 * be a complete SQL statement.
631 * This is used as a callback for sourceLine().
633 * @param string $line Text to append to the file
634 * @return bool False to skip actually executing the file
635 * @throws MWException
637 public function appendLine( $line ) {
638 $line = rtrim( $line ) . ";\n";
639 if ( fwrite( $this->fileHandle
, $line ) === false ) {
640 throw new MWException( "trouble writing file" );
647 * Applies a SQL patch
649 * @param string $path Path to the patch file
650 * @param bool $isFullPath Whether to treat $path as a relative or not
651 * @param string $msg Description of the patch
652 * @return bool False if patch is skipped.
654 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
655 if ( $msg === null ) {
656 $msg = "Applying $path patch";
658 if ( $this->skipSchema
) {
659 $this->output( "...skipping schema change ($msg).\n" );
664 $this->output( "$msg ..." );
666 if ( !$isFullPath ) {
667 $path = $this->patchPath( $this->db
, $path );
669 if ( $this->fileHandle
!== null ) {
670 $this->copyFile( $path );
672 $this->db
->sourceFile( $path );
674 $this->output( "done.\n" );
680 * Get the full path of a patch file. Originally based on archive()
681 * from updaters.inc. Keep in mind this always returns a patch, as
682 * it fails back to MySQL if no DB-specific patch can be found
684 * @param IDatabase $db
685 * @param string $patch The name of the patch, like patch-something.sql
686 * @return string Full path to patch file
688 public function patchPath( IDatabase
$db, $patch ) {
691 $dbType = $db->getType();
692 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
693 return "$IP/maintenance/$dbType/archives/$patch";
695 return "$IP/maintenance/archives/$patch";
700 * Add a new table to the database
702 * @param string $name Name of the new table
703 * @param string $patch Path to the patch file
704 * @param bool $fullpath Whether to treat $patch path as a relative or not
705 * @return bool False if this was skipped because schema changes are skipped
707 protected function addTable( $name, $patch, $fullpath = false ) {
708 if ( !$this->doTable( $name ) ) {
712 if ( $this->db
->tableExists( $name, __METHOD__
) ) {
713 $this->output( "...$name table already exists.\n" );
715 return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
722 * Add a new field to an existing table
724 * @param string $table Name of the table to modify
725 * @param string $field Name of the new field
726 * @param string $patch Path to the patch file
727 * @param bool $fullpath Whether to treat $patch path as a relative or not
728 * @return bool False if this was skipped because schema changes are skipped
730 protected function addField( $table, $field, $patch, $fullpath = false ) {
731 if ( !$this->doTable( $table ) ) {
735 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
736 $this->output( "...$table table does not exist, skipping new field patch.\n" );
737 } elseif ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
738 $this->output( "...have $field field in $table table.\n" );
740 return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
747 * Add a new index to an existing table
749 * @param string $table Name of the table to modify
750 * @param string $index Name of the new index
751 * @param string $patch Path to the patch file
752 * @param bool $fullpath Whether to treat $patch path as a relative or not
753 * @return bool False if this was skipped because schema changes are skipped
755 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
756 if ( !$this->doTable( $table ) ) {
760 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
761 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
762 } elseif ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
763 $this->output( "...index $index already set on $table table.\n" );
765 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
772 * Drop a field from an existing table
774 * @param string $table Name of the table to modify
775 * @param string $field Name of the old field
776 * @param string $patch Path to the patch file
777 * @param bool $fullpath Whether to treat $patch path as a relative or not
778 * @return bool False if this was skipped because schema changes are skipped
780 protected function dropField( $table, $field, $patch, $fullpath = false ) {
781 if ( !$this->doTable( $table ) ) {
785 if ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
786 return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
788 $this->output( "...$table table does not contain $field field.\n" );
795 * Drop an index from an existing table
797 * @param string $table Name of the table to modify
798 * @param string $index Name of the index
799 * @param string $patch Path to the patch file
800 * @param bool $fullpath Whether to treat $patch path as a relative or not
801 * @return bool False if this was skipped because schema changes are skipped
803 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
804 if ( !$this->doTable( $table ) ) {
808 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
809 return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
811 $this->output( "...$index key doesn't exist.\n" );
818 * Rename an index from an existing table
820 * @param string $table Name of the table to modify
821 * @param string $oldIndex Old name of the index
822 * @param string $newIndex New name of the index
823 * @param bool $skipBothIndexExistWarning Whether to warn if both the
824 * old and the new indexes exist.
825 * @param string $patch Path to the patch file
826 * @param bool $fullpath Whether to treat $patch path as a relative or not
827 * @return bool False if this was skipped because schema changes are skipped
829 protected function renameIndex( $table, $oldIndex, $newIndex,
830 $skipBothIndexExistWarning, $patch, $fullpath = false
832 if ( !$this->doTable( $table ) ) {
836 // First requirement: the table must exist
837 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
838 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
843 // Second requirement: the new index must be missing
844 if ( $this->db
->indexExists( $table, $newIndex, __METHOD__
) ) {
845 $this->output( "...index $newIndex already set on $table table.\n" );
846 if ( !$skipBothIndexExistWarning &&
847 $this->db
->indexExists( $table, $oldIndex, __METHOD__
)
849 $this->output( "...WARNING: $oldIndex still exists, despite it has " .
850 "been renamed into $newIndex (which also exists).\n" .
851 " $oldIndex should be manually removed if not needed anymore.\n" );
857 // Third requirement: the old index must exist
858 if ( !$this->db
->indexExists( $table, $oldIndex, __METHOD__
) ) {
859 $this->output( "...skipping: index $oldIndex doesn't exist.\n" );
864 // Requirements have been satisfied, patch can be applied
865 return $this->applyPatch(
868 "Renaming index $oldIndex into $newIndex to table $table"
873 * If the specified table exists, drop it, or execute the
874 * patch if one is provided.
878 * @param string $table Table to drop.
879 * @param string|bool $patch String of patch file that will drop the table. Default: false.
880 * @param bool $fullpath Whether $patch is a full path. Default: false.
881 * @return bool False if this was skipped because schema changes are skipped
883 public function dropTable( $table, $patch = false, $fullpath = false ) {
884 if ( !$this->doTable( $table ) ) {
888 if ( $this->db
->tableExists( $table, __METHOD__
) ) {
889 $msg = "Dropping table $table";
891 if ( $patch === false ) {
892 $this->output( "$msg ..." );
893 $this->db
->dropTable( $table, __METHOD__
);
894 $this->output( "done.\n" );
896 return $this->applyPatch( $patch, $fullpath, $msg );
899 $this->output( "...$table doesn't exist.\n" );
906 * Modify an existing field
908 * @param string $table Name of the table to which the field belongs
909 * @param string $field Name of the field to modify
910 * @param string $patch Path to the patch file
911 * @param bool $fullpath Whether to treat $patch path as a relative or not
912 * @return bool False if this was skipped because schema changes are skipped
914 public function modifyField( $table, $field, $patch, $fullpath = false ) {
915 if ( !$this->doTable( $table ) ) {
919 $updateKey = "$table-$field-$patch";
920 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
921 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
922 } elseif ( !$this->db
->fieldExists( $table, $field, __METHOD__
) ) {
923 $this->output( "...$field field does not exist in $table table, " .
924 "skipping modify field patch.\n" );
925 } elseif ( $this->updateRowExists( $updateKey ) ) {
926 $this->output( "...$field in table $table already modified by patch $patch.\n" );
928 $apply = $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
930 $this->insertUpdateRow( $updateKey );
938 * Modify an existing table, similar to modifyField. Intended for changes that
939 * touch more than one column on a table.
941 * @param string $table Name of the table to modify
942 * @param string $patch Name of the patch file to apply
943 * @param string|bool $fullpath Whether to treat $patch path as relative or not, defaults to false
944 * @return bool False if this was skipped because of schema changes being skipped
946 public function modifyTable( $table, $patch, $fullpath = false ) {
947 if ( !$this->doTable( $table ) ) {
951 $updateKey = "$table-$patch";
952 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
953 $this->output( "...$table table does not exist, skipping modify table patch.\n" );
954 } elseif ( $this->updateRowExists( $updateKey ) ) {
955 $this->output( "...table $table already modified by patch $patch.\n" );
957 $apply = $this->applyPatch( $patch, $fullpath, "Modifying table $table" );
959 $this->insertUpdateRow( $updateKey );
967 * Set any .htaccess files or equivilent for storage repos
969 * Some zones (e.g. "temp") used to be public and may have been initialized as such
971 public function setFileAccess() {
972 $repo = RepoGroup
::singleton()->getLocalRepo();
973 $zonePath = $repo->getZonePath( 'temp' );
974 if ( $repo->getBackend()->directoryExists( [ 'dir' => $zonePath ] ) ) {
975 // If the directory was never made, then it will have the right ACLs when it is made
976 $status = $repo->getBackend()->secure( [
981 if ( $status->isOK() ) {
982 $this->output( "Set the local repo temp zone container to be private.\n" );
984 $this->output( "Failed to set the local repo temp zone container to be private.\n" );
990 * Purge the objectcache table
992 public function purgeCache() {
993 global $wgLocalisationCacheConf;
994 # We can't guarantee that the user will be able to use TRUNCATE,
995 # but we know that DELETE is available to us
996 $this->output( "Purging caches..." );
997 $this->db
->delete( 'objectcache', '*', __METHOD__
);
998 if ( $wgLocalisationCacheConf['manualRecache'] ) {
999 $this->rebuildLocalisationCache();
1001 $blobStore = new MessageBlobStore();
1002 $blobStore->clear();
1003 $this->db
->delete( 'module_deps', '*', __METHOD__
);
1004 $this->output( "done.\n" );
1008 * Check the site_stats table is not properly populated.
1010 protected function checkStats() {
1011 $this->output( "...site_stats is populated..." );
1012 $row = $this->db
->selectRow( 'site_stats', '*', [ 'ss_row_id' => 1 ], __METHOD__
);
1013 if ( $row === false ) {
1014 $this->output( "data is missing! rebuilding...\n" );
1015 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
1016 $this->output( "missing ss_total_pages, rebuilding...\n" );
1018 $this->output( "done.\n" );
1022 SiteStatsInit
::doAllAndCommit( $this->db
);
1025 # Common updater functions
1028 * Sets the number of active users in the site_stats table
1030 protected function doActiveUsersInit() {
1031 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', false, __METHOD__
);
1032 if ( $activeUsers == -1 ) {
1033 $activeUsers = $this->db
->selectField( 'recentchanges',
1034 'COUNT( DISTINCT rc_user_text )',
1035 [ 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ], __METHOD__
1037 $this->db
->update( 'site_stats',
1038 [ 'ss_active_users' => intval( $activeUsers ) ],
1039 [ 'ss_row_id' => 1 ], __METHOD__
, [ 'LIMIT' => 1 ]
1042 $this->output( "...ss_active_users user count set...\n" );
1046 * Populates the log_user_text field in the logging table
1048 protected function doLogUsertextPopulation() {
1049 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
1051 "Populating log_user_text field, printing progress markers. For large\n" .
1052 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1053 "maintenance/populateLogUsertext.php.\n"
1056 $task = $this->maintenance
->runChild( 'PopulateLogUsertext' );
1058 $this->output( "done.\n" );
1063 * Migrate log params to new table and index for searching
1065 protected function doLogSearchPopulation() {
1066 if ( !$this->updateRowExists( 'populate log_search' ) ) {
1068 "Populating log_search table, printing progress markers. For large\n" .
1069 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1070 "maintenance/populateLogSearch.php.\n" );
1072 $task = $this->maintenance
->runChild( 'PopulateLogSearch' );
1074 $this->output( "done.\n" );
1079 * Updates the timestamps in the transcache table
1082 protected function doUpdateTranscacheField() {
1083 if ( $this->updateRowExists( 'convert transcache field' ) ) {
1084 $this->output( "...transcache tc_time already converted.\n" );
1089 return $this->applyPatch( 'patch-tc-timestamp.sql', false,
1090 "Converting tc_time from UNIX epoch to MediaWiki timestamp" );
1094 * Update CategoryLinks collation
1096 protected function doCollationUpdate() {
1097 global $wgCategoryCollation;
1098 if ( $this->db
->fieldExists( 'categorylinks', 'cl_collation', __METHOD__
) ) {
1099 if ( $this->db
->selectField(
1102 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
1106 $this->output( "...collations up-to-date.\n" );
1111 $this->output( "Updating category collations..." );
1112 $task = $this->maintenance
->runChild( 'UpdateCollation' );
1114 $this->output( "...done.\n" );
1119 * Migrates user options from the user table blob to user_properties
1121 protected function doMigrateUserOptions() {
1122 if ( $this->db
->tableExists( 'user_properties' ) ) {
1123 $cl = $this->maintenance
->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
1125 $this->output( "done.\n" );
1130 * Enable profiling table when it's turned on
1132 protected function doEnableProfiling() {
1135 if ( !$this->doTable( 'profiling' ) ) {
1139 $profileToDb = false;
1140 if ( isset( $wgProfiler['output'] ) ) {
1141 $out = $wgProfiler['output'];
1142 if ( $out === 'db' ) {
1143 $profileToDb = true;
1144 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
1145 $profileToDb = true;
1149 if ( $profileToDb && !$this->db
->tableExists( 'profiling', __METHOD__
) ) {
1150 $this->applyPatch( 'patch-profiling.sql', false, 'Add profiling table' );
1155 * Rebuilds the localisation cache
1157 protected function rebuildLocalisationCache() {
1159 * @var $cl RebuildLocalisationCache
1161 $cl = $this->maintenance
->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
1162 $this->output( "Rebuilding localisation cache...\n" );
1165 $this->output( "done.\n" );
1169 * Turns off content handler fields during parts of the upgrade
1170 * where they aren't available.
1172 protected function disableContentHandlerUseDB() {
1173 global $wgContentHandlerUseDB;
1175 if ( $wgContentHandlerUseDB ) {
1176 $this->output( "Turning off Content Handler DB fields for this part of upgrade.\n" );
1177 $this->holdContentHandlerUseDB
= $wgContentHandlerUseDB;
1178 $wgContentHandlerUseDB = false;
1183 * Turns content handler fields back on.
1185 protected function enableContentHandlerUseDB() {
1186 global $wgContentHandlerUseDB;
1188 if ( $this->holdContentHandlerUseDB
) {
1189 $this->output( "Content Handler DB fields should be usable now.\n" );
1190 $wgContentHandlerUseDB = $this->holdContentHandlerUseDB
;