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,
89 * File handle for SQL output.
93 protected $fileHandle = null;
96 * Flag specifying whether or not to skip schema (e.g. SQL-only) updates.
100 protected $skipSchema = false;
103 * Hold the value of $wgContentHandlerUseDB during the upgrade.
105 protected $holdContentHandlerUseDB = true;
110 * @param Database $db To perform updates on
111 * @param bool $shared Whether to perform updates on shared tables
112 * @param Maintenance $maintenance Maintenance object which created us
114 protected function __construct( Database
&$db, $shared, Maintenance
$maintenance = null ) {
116 $this->db
->setFlag( DBO_DDLMODE
); // For Oracle's handling of schema files
117 $this->shared
= $shared;
118 if ( $maintenance ) {
119 $this->maintenance
= $maintenance;
120 $this->fileHandle
= $maintenance->fileHandle
;
122 $this->maintenance
= new FakeMaintenance
;
124 $this->maintenance
->setDB( $db );
125 $this->initOldGlobals();
126 $this->loadExtensions();
127 Hooks
::run( 'LoadExtensionSchemaUpdates', [ $this ] );
131 * Initialize all of the old globals. One day this should all become
132 * something much nicer
134 private function initOldGlobals() {
135 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
136 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
138 # For extensions only, should be populated via hooks
139 # $wgDBtype should be checked to specifiy the proper file
140 $wgExtNewTables = []; // table, dir
141 $wgExtNewFields = []; // table, column, dir
142 $wgExtPGNewFields = []; // table, column, column attributes; for PostgreSQL
143 $wgExtPGAlteredFields = []; // table, column, new type, conversion method; for PostgreSQL
144 $wgExtNewIndexes = []; // table, index, dir
145 $wgExtModifiedFields = []; // table, index, dir
149 * Loads LocalSettings.php, if needed, and initialises everything needed for
150 * LoadExtensionSchemaUpdates hook.
152 private function loadExtensions() {
153 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
154 return; // already loaded
156 $vars = Installer
::getExistingLocalSettings();
158 $registry = ExtensionRegistry
::getInstance();
159 $queue = $registry->getQueue();
160 // Don't accidentally load extensions in the future
161 $registry->clearQueue();
163 // This will automatically add "AutoloadClasses" to $wgAutoloadClasses
164 $data = $registry->readFromQueue( $queue );
165 $hooks = [ 'wgHooks' => [ 'LoadExtensionSchemaUpdates' => [] ] ];
166 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
167 $hooks = $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'];
169 if ( $vars && isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
170 $hooks = array_merge_recursive( $hooks, $vars['wgHooks']['LoadExtensionSchemaUpdates'] );
172 global $wgHooks, $wgAutoloadClasses;
173 $wgHooks['LoadExtensionSchemaUpdates'] = $hooks;
174 if ( $vars && isset( $vars['wgAutoloadClasses'] ) ) {
175 $wgAutoloadClasses +
= $vars['wgAutoloadClasses'];
180 * @param Database $db
181 * @param bool $shared
182 * @param Maintenance $maintenance
184 * @throws MWException
185 * @return DatabaseUpdater
187 public static function newForDB( Database
$db, $shared = false, $maintenance = null ) {
188 $type = $db->getType();
189 if ( in_array( $type, Installer
::getDBTypes() ) ) {
190 $class = ucfirst( $type ) . 'Updater';
192 return new $class( $db, $shared, $maintenance );
194 throw new MWException( __METHOD__
. ' called for unsupported $wgDBtype' );
199 * Get a database connection to run updates
203 public function getDB() {
208 * Output some text. If we're running from web, escape the text first.
210 * @param string $str Text to output
212 public function output( $str ) {
213 if ( $this->maintenance
->isQuiet() ) {
216 global $wgCommandLineMode;
217 if ( !$wgCommandLineMode ) {
218 $str = htmlspecialchars( $str );
225 * Add a new update coming from an extension. This should be called by
226 * extensions while executing the LoadExtensionSchemaUpdates hook.
230 * @param array $update The update to run. Format is [ $callback, $params... ]
231 * $callback is the method to call; either a DatabaseUpdater method name or a callable.
232 * Must be serializable (ie. no anonymous functions allowed). The rest of the parameters
233 * (if any) will be passed to the callback. The first parameter passed to the callback
234 * is always this object.
236 public function addExtensionUpdate( array $update ) {
237 $this->extensionUpdates
[] = $update;
241 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
242 * is the most common usage of updaters in an extension)
246 * @param string $tableName Name of table to create
247 * @param string $sqlPath Full path to the schema file
249 public function addExtensionTable( $tableName, $sqlPath ) {
250 $this->extensionUpdates
[] = [ 'addTable', $tableName, $sqlPath, true ];
256 * @param string $tableName
257 * @param string $indexName
258 * @param string $sqlPath
260 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
261 $this->extensionUpdates
[] = [ 'addIndex', $tableName, $indexName, $sqlPath, true ];
268 * @param string $tableName
269 * @param string $columnName
270 * @param string $sqlPath
272 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
273 $this->extensionUpdates
[] = [ 'addField', $tableName, $columnName, $sqlPath, true ];
280 * @param string $tableName
281 * @param string $columnName
282 * @param string $sqlPath
284 public function dropExtensionField( $tableName, $columnName, $sqlPath ) {
285 $this->extensionUpdates
[] = [ 'dropField', $tableName, $columnName, $sqlPath, true ];
289 * Drop an index from an extension table
293 * @param string $tableName The table name
294 * @param string $indexName The index name
295 * @param string $sqlPath The path to the SQL change path
297 public function dropExtensionIndex( $tableName, $indexName, $sqlPath ) {
298 $this->extensionUpdates
[] = [ 'dropIndex', $tableName, $indexName, $sqlPath, true ];
305 * @param string $tableName
306 * @param string $sqlPath
308 public function dropExtensionTable( $tableName, $sqlPath ) {
309 $this->extensionUpdates
[] = [ 'dropTable', $tableName, $sqlPath, true ];
313 * Rename an index on an extension table
317 * @param string $tableName The table name
318 * @param string $oldIndexName The old index name
319 * @param string $newIndexName The new index name
320 * @param string $sqlPath The path to the SQL change path
321 * @param bool $skipBothIndexExistWarning Whether to warn if both the old
322 * and the new indexes exist. [facultative; by default, false]
324 public function renameExtensionIndex( $tableName, $oldIndexName, $newIndexName,
325 $sqlPath, $skipBothIndexExistWarning = false
327 $this->extensionUpdates
[] = [
332 $skipBothIndexExistWarning,
341 * @param string $tableName The table name
342 * @param string $fieldName The field to be modified
343 * @param string $sqlPath The path to the SQL change path
345 public function modifyExtensionField( $tableName, $fieldName, $sqlPath ) {
346 $this->extensionUpdates
[] = [ 'modifyField', $tableName, $fieldName, $sqlPath, true ];
353 * @param string $tableName
356 public function tableExists( $tableName ) {
357 return ( $this->db
->tableExists( $tableName, __METHOD__
) );
361 * Add a maintenance script to be run after the database updates are complete.
363 * Script should subclass LoggedUpdateMaintenance
367 * @param string $class Name of a Maintenance subclass
369 public function addPostDatabaseUpdateMaintenance( $class ) {
370 $this->postDatabaseUpdateMaintenance
[] = $class;
374 * Get the list of extension-defined updates
378 protected function getExtensionUpdates() {
379 return $this->extensionUpdates
;
387 public function getPostDatabaseUpdateMaintenance() {
388 return $this->postDatabaseUpdateMaintenance
;
394 * Writes the schema updates desired to a file for the DB Admin to run.
395 * @param array $schemaUpdate
397 private function writeSchemaUpdateFile( array $schemaUpdate = [] ) {
398 $updates = $this->updatesSkipped
;
399 $this->updatesSkipped
= [];
401 foreach ( $updates as $funcList ) {
402 $func = $funcList[0];
404 $origParams = $funcList[2];
405 call_user_func_array( $func, $arg );
407 $this->updatesSkipped
[] = $origParams;
412 * Get appropriate schema variables in the current database connection.
414 * This should be called after any request data has been imported, but before
415 * any write operations to the database. The result should be passed to the DB
416 * setSchemaVars() method.
421 public function getSchemaVars() {
422 return []; // DB-type specific
428 * @param array $what What updates to perform
430 public function doUpdates( array $what = [ 'core', 'extensions', 'stats' ] ) {
431 $this->db
->setSchemaVars( $this->getSchemaVars() );
433 $what = array_flip( $what );
434 $this->skipSchema
= isset( $what['noschema'] ) ||
$this->fileHandle
!== null;
435 if ( isset( $what['core'] ) ) {
436 $this->runUpdates( $this->getCoreUpdateList(), false );
438 if ( isset( $what['extensions'] ) ) {
439 $this->runUpdates( $this->getOldGlobalUpdates(), false );
440 $this->runUpdates( $this->getExtensionUpdates(), true );
443 if ( isset( $what['stats'] ) ) {
447 if ( $this->fileHandle
) {
448 $this->skipSchema
= false;
449 $this->writeSchemaUpdateFile();
454 * Helper function for doUpdates()
456 * @param array $updates Array of updates to run
457 * @param bool $passSelf Whether to pass this object we calling external functions
459 private function runUpdates( array $updates, $passSelf ) {
460 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
463 $updatesSkipped = [];
464 foreach ( $updates as $params ) {
465 $origParams = $params;
466 $func = array_shift( $params );
467 if ( !is_array( $func ) && method_exists( $this, $func ) ) {
468 $func = [ $this, $func ];
469 } elseif ( $passSelf ) {
470 array_unshift( $params, $this );
472 $ret = call_user_func_array( $func, $params );
474 if ( $ret !== false ) {
475 $updatesDone[] = $origParams;
476 $lbFactory->waitForReplication();
478 $updatesSkipped[] = [ $func, $params, $origParams ];
481 $this->updatesSkipped
= array_merge( $this->updatesSkipped
, $updatesSkipped );
482 $this->updates
= array_merge( $this->updates
, $updatesDone );
486 * Helper function: check if the given key is present in the updatelog table.
487 * Obviously, only use this for updates that occur after the updatelog table was
489 * @param string $key Name of the key to check for
492 public function updateRowExists( $key ) {
493 $row = $this->db
->selectRow(
497 [ 'ul_key' => $key ],
505 * Helper function: Add a key to the updatelog table
506 * Obviously, only use this for updates that occur after the updatelog table was
508 * @param string $key Name of key to insert
509 * @param string $val [optional] Value to insert along with the key
511 public function insertUpdateRow( $key, $val = null ) {
512 $this->db
->clearFlag( DBO_DDLMODE
);
513 $values = [ 'ul_key' => $key ];
514 if ( $val && $this->canUseNewUpdatelog() ) {
515 $values['ul_value'] = $val;
517 $this->db
->insert( 'updatelog', $values, __METHOD__
, 'IGNORE' );
518 $this->db
->setFlag( DBO_DDLMODE
);
522 * Updatelog was changed in 1.17 to have a ul_value column so we can record
523 * more information about what kind of updates we've done (that's what this
524 * class does). Pre-1.17 wikis won't have this column, and really old wikis
525 * might not even have updatelog at all
529 protected function canUseNewUpdatelog() {
530 return $this->db
->tableExists( 'updatelog', __METHOD__
) &&
531 $this->db
->fieldExists( 'updatelog', 'ul_value', __METHOD__
);
535 * Returns whether updates should be executed on the database table $name.
536 * Updates will be prevented if the table is a shared table and it is not
537 * specified to run updates on shared tables.
539 * @param string $name Table name
542 protected function doTable( $name ) {
543 global $wgSharedDB, $wgSharedTables;
545 // Don't bother to check $wgSharedTables if there isn't a shared database
546 // or the user actually also wants to do updates on the shared database.
547 if ( $wgSharedDB === null ||
$this->shared
) {
551 if ( in_array( $name, $wgSharedTables ) ) {
552 $this->output( "...skipping update to shared table $name.\n" );
560 * Before 1.17, we used to handle updates via stuff like
561 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
562 * of this in 1.17 but we want to remain back-compatible for a while. So
563 * load up these old global-based things into our update list.
567 protected function getOldGlobalUpdates() {
568 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
573 foreach ( $wgExtNewTables as $tableRecord ) {
575 'addTable', $tableRecord[0], $tableRecord[1], true
579 foreach ( $wgExtNewFields as $fieldRecord ) {
581 'addField', $fieldRecord[0], $fieldRecord[1],
582 $fieldRecord[2], true
586 foreach ( $wgExtNewIndexes as $fieldRecord ) {
588 'addIndex', $fieldRecord[0], $fieldRecord[1],
589 $fieldRecord[2], true
593 foreach ( $wgExtModifiedFields as $fieldRecord ) {
595 'modifyField', $fieldRecord[0], $fieldRecord[1],
596 $fieldRecord[2], true
604 * Get an array of updates to perform on the database. Should return a
605 * multi-dimensional array. The main key is the MediaWiki version (1.12,
606 * 1.13...) with the values being arrays of updates, identical to how
607 * updaters.inc did it (for now)
611 abstract protected function getCoreUpdateList();
614 * Append an SQL fragment to the open file handle.
616 * @param string $filename File name to open
618 public function copyFile( $filename ) {
619 $this->db
->sourceFile(
624 [ $this, 'appendLine' ]
629 * Append a line to the open filehandle. The line is assumed to
630 * be a complete SQL statement.
632 * This is used as a callback for sourceLine().
634 * @param string $line Text to append to the file
635 * @return bool False to skip actually executing the file
636 * @throws MWException
638 public function appendLine( $line ) {
639 $line = rtrim( $line ) . ";\n";
640 if ( fwrite( $this->fileHandle
, $line ) === false ) {
641 throw new MWException( "trouble writing file" );
648 * Applies a SQL patch
650 * @param string $path Path to the patch file
651 * @param bool $isFullPath Whether to treat $path as a relative or not
652 * @param string $msg Description of the patch
653 * @return bool False if patch is skipped.
655 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
656 if ( $msg === null ) {
657 $msg = "Applying $path patch";
659 if ( $this->skipSchema
) {
660 $this->output( "...skipping schema change ($msg).\n" );
665 $this->output( "$msg ..." );
667 if ( !$isFullPath ) {
668 $path = $this->patchPath( $this->db
, $path );
670 if ( $this->fileHandle
!== null ) {
671 $this->copyFile( $path );
673 $this->db
->sourceFile( $path );
675 $this->output( "done.\n" );
681 * Get the full path of a patch file. Originally based on archive()
682 * from updaters.inc. Keep in mind this always returns a patch, as
683 * it fails back to MySQL if no DB-specific patch can be found
685 * @param IDatabase $db
686 * @param string $patch The name of the patch, like patch-something.sql
687 * @return string Full path to patch file
689 public function patchPath( IDatabase
$db, $patch ) {
692 $dbType = $db->getType();
693 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
694 return "$IP/maintenance/$dbType/archives/$patch";
696 return "$IP/maintenance/archives/$patch";
701 * Add a new table to the database
703 * @param string $name Name of the new table
704 * @param string $patch Path to the patch file
705 * @param bool $fullpath Whether to treat $patch path as a relative or not
706 * @return bool False if this was skipped because schema changes are skipped
708 protected function addTable( $name, $patch, $fullpath = false ) {
709 if ( !$this->doTable( $name ) ) {
713 if ( $this->db
->tableExists( $name, __METHOD__
) ) {
714 $this->output( "...$name table already exists.\n" );
716 return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
723 * Add a new field to an existing table
725 * @param string $table Name of the table to modify
726 * @param string $field Name of the new field
727 * @param string $patch Path to the patch file
728 * @param bool $fullpath Whether to treat $patch path as a relative or not
729 * @return bool False if this was skipped because schema changes are skipped
731 protected function addField( $table, $field, $patch, $fullpath = false ) {
732 if ( !$this->doTable( $table ) ) {
736 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
737 $this->output( "...$table table does not exist, skipping new field patch.\n" );
738 } elseif ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
739 $this->output( "...have $field field in $table table.\n" );
741 return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
748 * Add a new index to an existing table
750 * @param string $table Name of the table to modify
751 * @param string $index Name of the new index
752 * @param string $patch Path to the patch file
753 * @param bool $fullpath Whether to treat $patch path as a relative or not
754 * @return bool False if this was skipped because schema changes are skipped
756 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
757 if ( !$this->doTable( $table ) ) {
761 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
762 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
763 } elseif ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
764 $this->output( "...index $index already set on $table table.\n" );
766 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
773 * Drop a field from an existing table
775 * @param string $table Name of the table to modify
776 * @param string $field Name of the old field
777 * @param string $patch Path to the patch file
778 * @param bool $fullpath Whether to treat $patch path as a relative or not
779 * @return bool False if this was skipped because schema changes are skipped
781 protected function dropField( $table, $field, $patch, $fullpath = false ) {
782 if ( !$this->doTable( $table ) ) {
786 if ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
787 return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
789 $this->output( "...$table table does not contain $field field.\n" );
796 * Drop an index from an existing table
798 * @param string $table Name of the table to modify
799 * @param string $index Name of the index
800 * @param string $patch Path to the patch file
801 * @param bool $fullpath Whether to treat $patch path as a relative or not
802 * @return bool False if this was skipped because schema changes are skipped
804 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
805 if ( !$this->doTable( $table ) ) {
809 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
810 return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
812 $this->output( "...$index key doesn't exist.\n" );
819 * Rename an index from an existing table
821 * @param string $table Name of the table to modify
822 * @param string $oldIndex Old name of the index
823 * @param string $newIndex New name of the index
824 * @param bool $skipBothIndexExistWarning Whether to warn if both the
825 * old and the new indexes exist.
826 * @param string $patch Path to the patch file
827 * @param bool $fullpath Whether to treat $patch path as a relative or not
828 * @return bool False if this was skipped because schema changes are skipped
830 protected function renameIndex( $table, $oldIndex, $newIndex,
831 $skipBothIndexExistWarning, $patch, $fullpath = false
833 if ( !$this->doTable( $table ) ) {
837 // First requirement: the table must exist
838 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
839 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
844 // Second requirement: the new index must be missing
845 if ( $this->db
->indexExists( $table, $newIndex, __METHOD__
) ) {
846 $this->output( "...index $newIndex already set on $table table.\n" );
847 if ( !$skipBothIndexExistWarning &&
848 $this->db
->indexExists( $table, $oldIndex, __METHOD__
)
850 $this->output( "...WARNING: $oldIndex still exists, despite it has " .
851 "been renamed into $newIndex (which also exists).\n" .
852 " $oldIndex should be manually removed if not needed anymore.\n" );
858 // Third requirement: the old index must exist
859 if ( !$this->db
->indexExists( $table, $oldIndex, __METHOD__
) ) {
860 $this->output( "...skipping: index $oldIndex doesn't exist.\n" );
865 // Requirements have been satisfied, patch can be applied
866 return $this->applyPatch(
869 "Renaming index $oldIndex into $newIndex to table $table"
874 * If the specified table exists, drop it, or execute the
875 * patch if one is provided.
879 * @param string $table Table to drop.
880 * @param string|bool $patch String of patch file that will drop the table. Default: false.
881 * @param bool $fullpath Whether $patch is a full path. Default: false.
882 * @return bool False if this was skipped because schema changes are skipped
884 public function dropTable( $table, $patch = false, $fullpath = false ) {
885 if ( !$this->doTable( $table ) ) {
889 if ( $this->db
->tableExists( $table, __METHOD__
) ) {
890 $msg = "Dropping table $table";
892 if ( $patch === false ) {
893 $this->output( "$msg ..." );
894 $this->db
->dropTable( $table, __METHOD__
);
895 $this->output( "done.\n" );
897 return $this->applyPatch( $patch, $fullpath, $msg );
900 $this->output( "...$table doesn't exist.\n" );
907 * Modify an existing field
909 * @param string $table Name of the table to which the field belongs
910 * @param string $field Name of the field to modify
911 * @param string $patch Path to the patch file
912 * @param bool $fullpath Whether to treat $patch path as a relative or not
913 * @return bool False if this was skipped because schema changes are skipped
915 public function modifyField( $table, $field, $patch, $fullpath = false ) {
916 if ( !$this->doTable( $table ) ) {
920 $updateKey = "$table-$field-$patch";
921 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
922 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
923 } elseif ( !$this->db
->fieldExists( $table, $field, __METHOD__
) ) {
924 $this->output( "...$field field does not exist in $table table, " .
925 "skipping modify field patch.\n" );
926 } elseif ( $this->updateRowExists( $updateKey ) ) {
927 $this->output( "...$field in table $table already modified by patch $patch.\n" );
929 $this->insertUpdateRow( $updateKey );
931 return $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
938 * Set any .htaccess files or equivilent for storage repos
940 * Some zones (e.g. "temp") used to be public and may have been initialized as such
942 public function setFileAccess() {
943 $repo = RepoGroup
::singleton()->getLocalRepo();
944 $zonePath = $repo->getZonePath( 'temp' );
945 if ( $repo->getBackend()->directoryExists( [ 'dir' => $zonePath ] ) ) {
946 // If the directory was never made, then it will have the right ACLs when it is made
947 $status = $repo->getBackend()->secure( [
952 if ( $status->isOK() ) {
953 $this->output( "Set the local repo temp zone container to be private.\n" );
955 $this->output( "Failed to set the local repo temp zone container to be private.\n" );
961 * Purge the objectcache table
963 public function purgeCache() {
964 global $wgLocalisationCacheConf;
965 # We can't guarantee that the user will be able to use TRUNCATE,
966 # but we know that DELETE is available to us
967 $this->output( "Purging caches..." );
968 $this->db
->delete( 'objectcache', '*', __METHOD__
);
969 if ( $wgLocalisationCacheConf['manualRecache'] ) {
970 $this->rebuildLocalisationCache();
972 $blobStore = new MessageBlobStore();
974 $this->db
->delete( 'module_deps', '*', __METHOD__
);
975 $this->output( "done.\n" );
979 * Check the site_stats table is not properly populated.
981 protected function checkStats() {
982 $this->output( "...site_stats is populated..." );
983 $row = $this->db
->selectRow( 'site_stats', '*', [ 'ss_row_id' => 1 ], __METHOD__
);
984 if ( $row === false ) {
985 $this->output( "data is missing! rebuilding...\n" );
986 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
987 $this->output( "missing ss_total_pages, rebuilding...\n" );
989 $this->output( "done.\n" );
993 SiteStatsInit
::doAllAndCommit( $this->db
);
996 # Common updater functions
999 * Sets the number of active users in the site_stats table
1001 protected function doActiveUsersInit() {
1002 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', false, __METHOD__
);
1003 if ( $activeUsers == -1 ) {
1004 $activeUsers = $this->db
->selectField( 'recentchanges',
1005 'COUNT( DISTINCT rc_user_text )',
1006 [ 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ], __METHOD__
1008 $this->db
->update( 'site_stats',
1009 [ 'ss_active_users' => intval( $activeUsers ) ],
1010 [ 'ss_row_id' => 1 ], __METHOD__
, [ 'LIMIT' => 1 ]
1013 $this->output( "...ss_active_users user count set...\n" );
1017 * Populates the log_user_text field in the logging table
1019 protected function doLogUsertextPopulation() {
1020 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
1022 "Populating log_user_text field, printing progress markers. For large\n" .
1023 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1024 "maintenance/populateLogUsertext.php.\n"
1027 $task = $this->maintenance
->runChild( 'PopulateLogUsertext' );
1029 $this->output( "done.\n" );
1034 * Migrate log params to new table and index for searching
1036 protected function doLogSearchPopulation() {
1037 if ( !$this->updateRowExists( 'populate log_search' ) ) {
1039 "Populating log_search table, printing progress markers. For large\n" .
1040 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1041 "maintenance/populateLogSearch.php.\n" );
1043 $task = $this->maintenance
->runChild( 'PopulateLogSearch' );
1045 $this->output( "done.\n" );
1050 * Updates the timestamps in the transcache table
1053 protected function doUpdateTranscacheField() {
1054 if ( $this->updateRowExists( 'convert transcache field' ) ) {
1055 $this->output( "...transcache tc_time already converted.\n" );
1060 return $this->applyPatch( 'patch-tc-timestamp.sql', false,
1061 "Converting tc_time from UNIX epoch to MediaWiki timestamp" );
1065 * Update CategoryLinks collation
1067 protected function doCollationUpdate() {
1068 global $wgCategoryCollation;
1069 if ( $this->db
->fieldExists( 'categorylinks', 'cl_collation', __METHOD__
) ) {
1070 if ( $this->db
->selectField(
1073 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
1077 $this->output( "...collations up-to-date.\n" );
1082 $this->output( "Updating category collations..." );
1083 $task = $this->maintenance
->runChild( 'UpdateCollation' );
1085 $this->output( "...done.\n" );
1090 * Migrates user options from the user table blob to user_properties
1092 protected function doMigrateUserOptions() {
1093 if ( $this->db
->tableExists( 'user_properties' ) ) {
1094 $cl = $this->maintenance
->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
1096 $this->output( "done.\n" );
1101 * Enable profiling table when it's turned on
1103 protected function doEnableProfiling() {
1106 if ( !$this->doTable( 'profiling' ) ) {
1110 $profileToDb = false;
1111 if ( isset( $wgProfiler['output'] ) ) {
1112 $out = $wgProfiler['output'];
1113 if ( $out === 'db' ) {
1114 $profileToDb = true;
1115 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
1116 $profileToDb = true;
1120 if ( $profileToDb && !$this->db
->tableExists( 'profiling', __METHOD__
) ) {
1121 $this->applyPatch( 'patch-profiling.sql', false, 'Add profiling table' );
1126 * Rebuilds the localisation cache
1128 protected function rebuildLocalisationCache() {
1130 * @var $cl RebuildLocalisationCache
1132 $cl = $this->maintenance
->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
1133 $this->output( "Rebuilding localisation cache...\n" );
1136 $this->output( "done.\n" );
1140 * Turns off content handler fields during parts of the upgrade
1141 * where they aren't available.
1143 protected function disableContentHandlerUseDB() {
1144 global $wgContentHandlerUseDB;
1146 if ( $wgContentHandlerUseDB ) {
1147 $this->output( "Turning off Content Handler DB fields for this part of upgrade.\n" );
1148 $this->holdContentHandlerUseDB
= $wgContentHandlerUseDB;
1149 $wgContentHandlerUseDB = false;
1154 * Turns content handler fields back on.
1156 protected function enableContentHandlerUseDB() {
1157 global $wgContentHandlerUseDB;
1159 if ( $this->holdContentHandlerUseDB
) {
1160 $this->output( "Content Handler DB fields should be usable now.\n" );
1161 $wgContentHandlerUseDB = $this->holdContentHandlerUseDB
;