Use adaptive CDN TTLs for page views
[mediawiki.git] / includes / installer / DatabaseUpdater.php
blob86b2f3bde4a740650cf2ec9a8825956185d313a3
1 <?php
2 /**
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
20 * @file
21 * @ingroup Deployment
24 require_once __DIR__ . '/../../maintenance/Maintenance.php';
26 /**
27 * Class for handling database updates. Roughly based off of updaters.inc, with
28 * a few improvements :)
30 * @ingroup Deployment
31 * @since 1.17
33 abstract class DatabaseUpdater {
34 protected static $updateCounter = 0;
36 /**
37 * Array of updates to perform on the database
39 * @var array
41 protected $updates = [];
43 /**
44 * Array of updates that were skipped
46 * @var array
48 protected $updatesSkipped = [];
50 /**
51 * List of extension-provided database updates
52 * @var array
54 protected $extensionUpdates = [];
56 /**
57 * Handle to the database subclass
59 * @var DatabaseBase
61 protected $db;
63 protected $shared = false;
65 /**
66 * @var string[] Scripts to run after database update
67 * Should be a subclass of LoggedUpdateMaintenance
69 protected $postDatabaseUpdateMaintenance = [
70 DeleteDefaultMessages::class,
71 PopulateRevisionLength::class,
72 PopulateRevisionSha1::class,
73 PopulateImageSha1::class,
74 FixExtLinksProtocolRelative::class,
75 PopulateFilearchiveSha1::class,
76 PopulateBacklinkNamespace::class,
77 FixDefaultJsonContentPages::class,
78 CleanupEmptyCategories::class,
81 /**
82 * File handle for SQL output.
84 * @var resource
86 protected $fileHandle = null;
88 /**
89 * Flag specifying whether or not to skip schema (e.g. SQL-only) updates.
91 * @var bool
93 protected $skipSchema = false;
95 /**
96 * Hold the value of $wgContentHandlerUseDB during the upgrade.
98 protected $holdContentHandlerUseDB = true;
101 * Constructor
103 * @param DatabaseBase $db To perform updates on
104 * @param bool $shared Whether to perform updates on shared tables
105 * @param Maintenance $maintenance Maintenance object which created us
107 protected function __construct( DatabaseBase &$db, $shared, Maintenance $maintenance = null ) {
108 $this->db = $db;
109 $this->db->setFlag( DBO_DDLMODE ); // For Oracle's handling of schema files
110 $this->shared = $shared;
111 if ( $maintenance ) {
112 $this->maintenance = $maintenance;
113 $this->fileHandle = $maintenance->fileHandle;
114 } else {
115 $this->maintenance = new FakeMaintenance;
117 $this->maintenance->setDB( $db );
118 $this->initOldGlobals();
119 $this->loadExtensions();
120 Hooks::run( 'LoadExtensionSchemaUpdates', [ $this ] );
124 * Initialize all of the old globals. One day this should all become
125 * something much nicer
127 private function initOldGlobals() {
128 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
129 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
131 # For extensions only, should be populated via hooks
132 # $wgDBtype should be checked to specifiy the proper file
133 $wgExtNewTables = []; // table, dir
134 $wgExtNewFields = []; // table, column, dir
135 $wgExtPGNewFields = []; // table, column, column attributes; for PostgreSQL
136 $wgExtPGAlteredFields = []; // table, column, new type, conversion method; for PostgreSQL
137 $wgExtNewIndexes = []; // table, index, dir
138 $wgExtModifiedFields = []; // table, index, dir
142 * Loads LocalSettings.php, if needed, and initialises everything needed for
143 * LoadExtensionSchemaUpdates hook.
145 private function loadExtensions() {
146 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
147 return; // already loaded
149 $vars = Installer::getExistingLocalSettings();
151 $registry = ExtensionRegistry::getInstance();
152 $queue = $registry->getQueue();
153 // Don't accidentally load extensions in the future
154 $registry->clearQueue();
156 // This will automatically add "AutoloadClasses" to $wgAutoloadClasses
157 $data = $registry->readFromQueue( $queue );
158 $hooks = [ 'wgHooks' => [ 'LoadExtensionSchemaUpdates' => [] ] ];
159 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
160 $hooks = $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'];
162 if ( $vars && isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
163 $hooks = array_merge_recursive( $hooks, $vars['wgHooks']['LoadExtensionSchemaUpdates'] );
165 global $wgHooks, $wgAutoloadClasses;
166 $wgHooks['LoadExtensionSchemaUpdates'] = $hooks;
167 if ( $vars && isset( $vars['wgAutoloadClasses'] ) ) {
168 $wgAutoloadClasses += $vars['wgAutoloadClasses'];
173 * @param DatabaseBase $db
174 * @param bool $shared
175 * @param Maintenance $maintenance
177 * @throws MWException
178 * @return DatabaseUpdater
180 public static function newForDB( &$db, $shared = false, $maintenance = null ) {
181 $type = $db->getType();
182 if ( in_array( $type, Installer::getDBTypes() ) ) {
183 $class = ucfirst( $type ) . 'Updater';
185 return new $class( $db, $shared, $maintenance );
186 } else {
187 throw new MWException( __METHOD__ . ' called for unsupported $wgDBtype' );
192 * Get a database connection to run updates
194 * @return DatabaseBase
196 public function getDB() {
197 return $this->db;
201 * Output some text. If we're running from web, escape the text first.
203 * @param string $str Text to output
205 public function output( $str ) {
206 if ( $this->maintenance->isQuiet() ) {
207 return;
209 global $wgCommandLineMode;
210 if ( !$wgCommandLineMode ) {
211 $str = htmlspecialchars( $str );
213 echo $str;
214 flush();
218 * Add a new update coming from an extension. This should be called by
219 * extensions while executing the LoadExtensionSchemaUpdates hook.
221 * @since 1.17
223 * @param array $update The update to run. Format is the following:
224 * first item is the callback function, it also can be a
225 * simple string with the name of a function in this class,
226 * following elements are parameters to the function.
227 * Note that callback functions will receive this object as
228 * first parameter.
230 public function addExtensionUpdate( array $update ) {
231 $this->extensionUpdates[] = $update;
235 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
236 * is the most common usage of updaters in an extension)
238 * @since 1.18
240 * @param string $tableName Name of table to create
241 * @param string $sqlPath Full path to the schema file
243 public function addExtensionTable( $tableName, $sqlPath ) {
244 $this->extensionUpdates[] = [ 'addTable', $tableName, $sqlPath, true ];
248 * @since 1.19
250 * @param string $tableName
251 * @param string $indexName
252 * @param string $sqlPath
254 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
255 $this->extensionUpdates[] = [ 'addIndex', $tableName, $indexName, $sqlPath, true ];
260 * @since 1.19
262 * @param string $tableName
263 * @param string $columnName
264 * @param string $sqlPath
266 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
267 $this->extensionUpdates[] = [ 'addField', $tableName, $columnName, $sqlPath, true ];
272 * @since 1.20
274 * @param string $tableName
275 * @param string $columnName
276 * @param string $sqlPath
278 public function dropExtensionField( $tableName, $columnName, $sqlPath ) {
279 $this->extensionUpdates[] = [ 'dropField', $tableName, $columnName, $sqlPath, true ];
283 * Drop an index from an extension table
285 * @since 1.21
287 * @param string $tableName The table name
288 * @param string $indexName The index name
289 * @param string $sqlPath The path to the SQL change path
291 public function dropExtensionIndex( $tableName, $indexName, $sqlPath ) {
292 $this->extensionUpdates[] = [ 'dropIndex', $tableName, $indexName, $sqlPath, true ];
297 * @since 1.20
299 * @param string $tableName
300 * @param string $sqlPath
302 public function dropExtensionTable( $tableName, $sqlPath ) {
303 $this->extensionUpdates[] = [ 'dropTable', $tableName, $sqlPath, true ];
307 * Rename an index on an extension table
309 * @since 1.21
311 * @param string $tableName The table name
312 * @param string $oldIndexName The old index name
313 * @param string $newIndexName The new index name
314 * @param string $sqlPath The path to the SQL change path
315 * @param bool $skipBothIndexExistWarning Whether to warn if both the old
316 * and the new indexes exist. [facultative; by default, false]
318 public function renameExtensionIndex( $tableName, $oldIndexName, $newIndexName,
319 $sqlPath, $skipBothIndexExistWarning = false
321 $this->extensionUpdates[] = [
322 'renameIndex',
323 $tableName,
324 $oldIndexName,
325 $newIndexName,
326 $skipBothIndexExistWarning,
327 $sqlPath,
328 true
333 * @since 1.21
335 * @param string $tableName The table name
336 * @param string $fieldName The field to be modified
337 * @param string $sqlPath The path to the SQL change path
339 public function modifyExtensionField( $tableName, $fieldName, $sqlPath ) {
340 $this->extensionUpdates[] = [ 'modifyField', $tableName, $fieldName, $sqlPath, true ];
345 * @since 1.20
347 * @param string $tableName
348 * @return bool
350 public function tableExists( $tableName ) {
351 return ( $this->db->tableExists( $tableName, __METHOD__ ) );
355 * Add a maintenance script to be run after the database updates are complete.
357 * Script should subclass LoggedUpdateMaintenance
359 * @since 1.19
361 * @param string $class Name of a Maintenance subclass
363 public function addPostDatabaseUpdateMaintenance( $class ) {
364 $this->postDatabaseUpdateMaintenance[] = $class;
368 * Get the list of extension-defined updates
370 * @return array
372 protected function getExtensionUpdates() {
373 return $this->extensionUpdates;
377 * @since 1.17
379 * @return string[]
381 public function getPostDatabaseUpdateMaintenance() {
382 return $this->postDatabaseUpdateMaintenance;
386 * @since 1.21
388 * Writes the schema updates desired to a file for the DB Admin to run.
389 * @param array $schemaUpdate
391 private function writeSchemaUpdateFile( $schemaUpdate = [] ) {
392 $updates = $this->updatesSkipped;
393 $this->updatesSkipped = [];
395 foreach ( $updates as $funcList ) {
396 $func = $funcList[0];
397 $arg = $funcList[1];
398 $origParams = $funcList[2];
399 call_user_func_array( $func, $arg );
400 flush();
401 $this->updatesSkipped[] = $origParams;
406 * Do all the updates
408 * @param array $what What updates to perform
410 public function doUpdates( $what = [ 'core', 'extensions', 'stats' ] ) {
411 global $wgVersion;
413 $what = array_flip( $what );
414 $this->skipSchema = isset( $what['noschema'] ) || $this->fileHandle !== null;
415 if ( isset( $what['core'] ) ) {
416 $this->runUpdates( $this->getCoreUpdateList(), false );
418 if ( isset( $what['extensions'] ) ) {
419 $this->runUpdates( $this->getOldGlobalUpdates(), false );
420 $this->runUpdates( $this->getExtensionUpdates(), true );
423 if ( isset( $what['stats'] ) ) {
424 $this->checkStats();
427 $this->setAppliedUpdates( $wgVersion, $this->updates );
429 if ( $this->fileHandle ) {
430 $this->skipSchema = false;
431 $this->writeSchemaUpdateFile();
432 $this->setAppliedUpdates( "$wgVersion-schema", $this->updatesSkipped );
437 * Helper function for doUpdates()
439 * @param array $updates Array of updates to run
440 * @param bool $passSelf Whether to pass this object we calling external functions
442 private function runUpdates( array $updates, $passSelf ) {
443 $updatesDone = [];
444 $updatesSkipped = [];
445 foreach ( $updates as $params ) {
446 $origParams = $params;
447 $func = array_shift( $params );
448 if ( !is_array( $func ) && method_exists( $this, $func ) ) {
449 $func = [ $this, $func ];
450 } elseif ( $passSelf ) {
451 array_unshift( $params, $this );
453 $ret = call_user_func_array( $func, $params );
454 flush();
455 if ( $ret !== false ) {
456 $updatesDone[] = $origParams;
457 wfGetLBFactory()->waitForReplication();
458 } else {
459 $updatesSkipped[] = [ $func, $params, $origParams ];
462 $this->updatesSkipped = array_merge( $this->updatesSkipped, $updatesSkipped );
463 $this->updates = array_merge( $this->updates, $updatesDone );
467 * @param string $version
468 * @param array $updates
470 protected function setAppliedUpdates( $version, $updates = [] ) {
471 $this->db->clearFlag( DBO_DDLMODE );
472 if ( !$this->canUseNewUpdatelog() ) {
473 return;
475 $key = "updatelist-$version-" . time() . self::$updateCounter;
476 self::$updateCounter++;
477 $this->db->insert( 'updatelog',
478 [ 'ul_key' => $key, 'ul_value' => serialize( $updates ) ],
479 __METHOD__ );
480 $this->db->setFlag( DBO_DDLMODE );
484 * Helper function: check if the given key is present in the updatelog table.
485 * Obviously, only use this for updates that occur after the updatelog table was
486 * created!
487 * @param string $key Name of the key to check for
488 * @return bool
490 public function updateRowExists( $key ) {
491 $row = $this->db->selectRow(
492 'updatelog',
493 # Bug 65813
494 '1 AS X',
495 [ 'ul_key' => $key ],
496 __METHOD__
499 return (bool)$row;
503 * Helper function: Add a key to the updatelog table
504 * Obviously, only use this for updates that occur after the updatelog table was
505 * created!
506 * @param string $key Name of key to insert
507 * @param string $val [optional] Value to insert along with the key
509 public function insertUpdateRow( $key, $val = null ) {
510 $this->db->clearFlag( DBO_DDLMODE );
511 $values = [ 'ul_key' => $key ];
512 if ( $val && $this->canUseNewUpdatelog() ) {
513 $values['ul_value'] = $val;
515 $this->db->insert( 'updatelog', $values, __METHOD__, 'IGNORE' );
516 $this->db->setFlag( DBO_DDLMODE );
520 * Updatelog was changed in 1.17 to have a ul_value column so we can record
521 * more information about what kind of updates we've done (that's what this
522 * class does). Pre-1.17 wikis won't have this column, and really old wikis
523 * might not even have updatelog at all
525 * @return bool
527 protected function canUseNewUpdatelog() {
528 return $this->db->tableExists( 'updatelog', __METHOD__ ) &&
529 $this->db->fieldExists( 'updatelog', 'ul_value', __METHOD__ );
533 * Returns whether updates should be executed on the database table $name.
534 * Updates will be prevented if the table is a shared table and it is not
535 * specified to run updates on shared tables.
537 * @param string $name Table name
538 * @return bool
540 protected function doTable( $name ) {
541 global $wgSharedDB, $wgSharedTables;
543 // Don't bother to check $wgSharedTables if there isn't a shared database
544 // or the user actually also wants to do updates on the shared database.
545 if ( $wgSharedDB === null || $this->shared ) {
546 return true;
549 if ( in_array( $name, $wgSharedTables ) ) {
550 $this->output( "...skipping update to shared table $name.\n" );
551 return false;
552 } else {
553 return true;
558 * Before 1.17, we used to handle updates via stuff like
559 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
560 * of this in 1.17 but we want to remain back-compatible for a while. So
561 * load up these old global-based things into our update list.
563 * @return array
565 protected function getOldGlobalUpdates() {
566 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
567 $wgExtNewIndexes;
569 $updates = [];
571 foreach ( $wgExtNewTables as $tableRecord ) {
572 $updates[] = [
573 'addTable', $tableRecord[0], $tableRecord[1], true
577 foreach ( $wgExtNewFields as $fieldRecord ) {
578 $updates[] = [
579 'addField', $fieldRecord[0], $fieldRecord[1],
580 $fieldRecord[2], true
584 foreach ( $wgExtNewIndexes as $fieldRecord ) {
585 $updates[] = [
586 'addIndex', $fieldRecord[0], $fieldRecord[1],
587 $fieldRecord[2], true
591 foreach ( $wgExtModifiedFields as $fieldRecord ) {
592 $updates[] = [
593 'modifyField', $fieldRecord[0], $fieldRecord[1],
594 $fieldRecord[2], true
598 return $updates;
602 * Get an array of updates to perform on the database. Should return a
603 * multi-dimensional array. The main key is the MediaWiki version (1.12,
604 * 1.13...) with the values being arrays of updates, identical to how
605 * updaters.inc did it (for now)
607 * @return array
609 abstract protected function getCoreUpdateList();
612 * Append an SQL fragment to the open file handle.
614 * @param string $filename File name to open
616 public function copyFile( $filename ) {
617 $this->db->sourceFile( $filename, false, false, false,
618 [ $this, 'appendLine' ]
623 * Append a line to the open filehandle. The line is assumed to
624 * be a complete SQL statement.
626 * This is used as a callback for sourceLine().
628 * @param string $line Text to append to the file
629 * @return bool False to skip actually executing the file
630 * @throws MWException
632 public function appendLine( $line ) {
633 $line = rtrim( $line ) . ";\n";
634 if ( fwrite( $this->fileHandle, $line ) === false ) {
635 throw new MWException( "trouble writing file" );
638 return false;
642 * Applies a SQL patch
644 * @param string $path Path to the patch file
645 * @param bool $isFullPath Whether to treat $path as a relative or not
646 * @param string $msg Description of the patch
647 * @return bool False if patch is skipped.
649 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
650 if ( $msg === null ) {
651 $msg = "Applying $path patch";
653 if ( $this->skipSchema ) {
654 $this->output( "...skipping schema change ($msg).\n" );
656 return false;
659 $this->output( "$msg ..." );
661 if ( !$isFullPath ) {
662 $path = $this->db->patchPath( $path );
664 if ( $this->fileHandle !== null ) {
665 $this->copyFile( $path );
666 } else {
667 $this->db->sourceFile( $path );
669 $this->output( "done.\n" );
671 return true;
675 * Add a new table to the database
677 * @param string $name Name of the new table
678 * @param string $patch Path to the patch file
679 * @param bool $fullpath Whether to treat $patch path as a relative or not
680 * @return bool False if this was skipped because schema changes are skipped
682 protected function addTable( $name, $patch, $fullpath = false ) {
683 if ( !$this->doTable( $name ) ) {
684 return true;
687 if ( $this->db->tableExists( $name, __METHOD__ ) ) {
688 $this->output( "...$name table already exists.\n" );
689 } else {
690 return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
693 return true;
697 * Add a new field to an existing table
699 * @param string $table Name of the table to modify
700 * @param string $field Name of the new field
701 * @param string $patch Path to the patch file
702 * @param bool $fullpath Whether to treat $patch path as a relative or not
703 * @return bool False if this was skipped because schema changes are skipped
705 protected function addField( $table, $field, $patch, $fullpath = false ) {
706 if ( !$this->doTable( $table ) ) {
707 return true;
710 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
711 $this->output( "...$table table does not exist, skipping new field patch.\n" );
712 } elseif ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
713 $this->output( "...have $field field in $table table.\n" );
714 } else {
715 return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
718 return true;
722 * Add a new index to an existing table
724 * @param string $table Name of the table to modify
725 * @param string $index Name of the new index
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 addIndex( $table, $index, $patch, $fullpath = false ) {
731 if ( !$this->doTable( $table ) ) {
732 return true;
735 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
736 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
737 } elseif ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
738 $this->output( "...index $index already set on $table table.\n" );
739 } else {
740 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
743 return true;
747 * Drop a field from an existing table
749 * @param string $table Name of the table to modify
750 * @param string $field Name of the old field
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 dropField( $table, $field, $patch, $fullpath = false ) {
756 if ( !$this->doTable( $table ) ) {
757 return true;
760 if ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
761 return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
762 } else {
763 $this->output( "...$table table does not contain $field field.\n" );
766 return true;
770 * Drop an index from an existing table
772 * @param string $table Name of the table to modify
773 * @param string $index Name of the index
774 * @param string $patch Path to the patch file
775 * @param bool $fullpath Whether to treat $patch path as a relative or not
776 * @return bool False if this was skipped because schema changes are skipped
778 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
779 if ( !$this->doTable( $table ) ) {
780 return true;
783 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
784 return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
785 } else {
786 $this->output( "...$index key doesn't exist.\n" );
789 return true;
793 * Rename an index from an existing table
795 * @param string $table Name of the table to modify
796 * @param string $oldIndex Old name of the index
797 * @param string $newIndex New name of the index
798 * @param bool $skipBothIndexExistWarning Whether to warn if both the
799 * old and the new indexes exist.
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 renameIndex( $table, $oldIndex, $newIndex,
805 $skipBothIndexExistWarning, $patch, $fullpath = false
807 if ( !$this->doTable( $table ) ) {
808 return true;
811 // First requirement: the table must exist
812 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
813 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
815 return true;
818 // Second requirement: the new index must be missing
819 if ( $this->db->indexExists( $table, $newIndex, __METHOD__ ) ) {
820 $this->output( "...index $newIndex already set on $table table.\n" );
821 if ( !$skipBothIndexExistWarning &&
822 $this->db->indexExists( $table, $oldIndex, __METHOD__ )
824 $this->output( "...WARNING: $oldIndex still exists, despite it has " .
825 "been renamed into $newIndex (which also exists).\n" .
826 " $oldIndex should be manually removed if not needed anymore.\n" );
829 return true;
832 // Third requirement: the old index must exist
833 if ( !$this->db->indexExists( $table, $oldIndex, __METHOD__ ) ) {
834 $this->output( "...skipping: index $oldIndex doesn't exist.\n" );
836 return true;
839 // Requirements have been satisfied, patch can be applied
840 return $this->applyPatch(
841 $patch,
842 $fullpath,
843 "Renaming index $oldIndex into $newIndex to table $table"
848 * If the specified table exists, drop it, or execute the
849 * patch if one is provided.
851 * Public @since 1.20
853 * @param string $table Table to drop.
854 * @param string|bool $patch String of patch file that will drop the table. Default: false.
855 * @param bool $fullpath Whether $patch is a full path. Default: false.
856 * @return bool False if this was skipped because schema changes are skipped
858 public function dropTable( $table, $patch = false, $fullpath = false ) {
859 if ( !$this->doTable( $table ) ) {
860 return true;
863 if ( $this->db->tableExists( $table, __METHOD__ ) ) {
864 $msg = "Dropping table $table";
866 if ( $patch === false ) {
867 $this->output( "$msg ..." );
868 $this->db->dropTable( $table, __METHOD__ );
869 $this->output( "done.\n" );
870 } else {
871 return $this->applyPatch( $patch, $fullpath, $msg );
873 } else {
874 $this->output( "...$table doesn't exist.\n" );
877 return true;
881 * Modify an existing field
883 * @param string $table Name of the table to which the field belongs
884 * @param string $field Name of the field to modify
885 * @param string $patch Path to the patch file
886 * @param bool $fullpath Whether to treat $patch path as a relative or not
887 * @return bool False if this was skipped because schema changes are skipped
889 public function modifyField( $table, $field, $patch, $fullpath = false ) {
890 if ( !$this->doTable( $table ) ) {
891 return true;
894 $updateKey = "$table-$field-$patch";
895 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
896 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
897 } elseif ( !$this->db->fieldExists( $table, $field, __METHOD__ ) ) {
898 $this->output( "...$field field does not exist in $table table, " .
899 "skipping modify field patch.\n" );
900 } elseif ( $this->updateRowExists( $updateKey ) ) {
901 $this->output( "...$field in table $table already modified by patch $patch.\n" );
902 } else {
903 $this->insertUpdateRow( $updateKey );
905 return $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
908 return true;
912 * Set any .htaccess files or equivilent for storage repos
914 * Some zones (e.g. "temp") used to be public and may have been initialized as such
916 public function setFileAccess() {
917 $repo = RepoGroup::singleton()->getLocalRepo();
918 $zonePath = $repo->getZonePath( 'temp' );
919 if ( $repo->getBackend()->directoryExists( [ 'dir' => $zonePath ] ) ) {
920 // If the directory was never made, then it will have the right ACLs when it is made
921 $status = $repo->getBackend()->secure( [
922 'dir' => $zonePath,
923 'noAccess' => true,
924 'noListing' => true
925 ] );
926 if ( $status->isOK() ) {
927 $this->output( "Set the local repo temp zone container to be private.\n" );
928 } else {
929 $this->output( "Failed to set the local repo temp zone container to be private.\n" );
935 * Purge the objectcache table
937 public function purgeCache() {
938 global $wgLocalisationCacheConf;
939 # We can't guarantee that the user will be able to use TRUNCATE,
940 # but we know that DELETE is available to us
941 $this->output( "Purging caches..." );
942 $this->db->delete( 'objectcache', '*', __METHOD__ );
943 if ( $wgLocalisationCacheConf['manualRecache'] ) {
944 $this->rebuildLocalisationCache();
946 $blobStore = new MessageBlobStore();
947 $blobStore->clear();
948 $this->db->delete( 'module_deps', '*', __METHOD__ );
949 $this->output( "done.\n" );
953 * Check the site_stats table is not properly populated.
955 protected function checkStats() {
956 $this->output( "...site_stats is populated..." );
957 $row = $this->db->selectRow( 'site_stats', '*', [ 'ss_row_id' => 1 ], __METHOD__ );
958 if ( $row === false ) {
959 $this->output( "data is missing! rebuilding...\n" );
960 } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
961 $this->output( "missing ss_total_pages, rebuilding...\n" );
962 } else {
963 $this->output( "done.\n" );
965 return;
967 SiteStatsInit::doAllAndCommit( $this->db );
970 # Common updater functions
973 * Sets the number of active users in the site_stats table
975 protected function doActiveUsersInit() {
976 $activeUsers = $this->db->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
977 if ( $activeUsers == -1 ) {
978 $activeUsers = $this->db->selectField( 'recentchanges',
979 'COUNT( DISTINCT rc_user_text )',
980 [ 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ], __METHOD__
982 $this->db->update( 'site_stats',
983 [ 'ss_active_users' => intval( $activeUsers ) ],
984 [ 'ss_row_id' => 1 ], __METHOD__, [ 'LIMIT' => 1 ]
987 $this->output( "...ss_active_users user count set...\n" );
991 * Populates the log_user_text field in the logging table
993 protected function doLogUsertextPopulation() {
994 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
995 $this->output(
996 "Populating log_user_text field, printing progress markers. For large\n" .
997 "databases, you may want to hit Ctrl-C and do this manually with\n" .
998 "maintenance/populateLogUsertext.php.\n"
1001 $task = $this->maintenance->runChild( 'PopulateLogUsertext' );
1002 $task->execute();
1003 $this->output( "done.\n" );
1008 * Migrate log params to new table and index for searching
1010 protected function doLogSearchPopulation() {
1011 if ( !$this->updateRowExists( 'populate log_search' ) ) {
1012 $this->output(
1013 "Populating log_search table, printing progress markers. For large\n" .
1014 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1015 "maintenance/populateLogSearch.php.\n" );
1017 $task = $this->maintenance->runChild( 'PopulateLogSearch' );
1018 $task->execute();
1019 $this->output( "done.\n" );
1024 * Updates the timestamps in the transcache table
1025 * @return bool
1027 protected function doUpdateTranscacheField() {
1028 if ( $this->updateRowExists( 'convert transcache field' ) ) {
1029 $this->output( "...transcache tc_time already converted.\n" );
1031 return true;
1034 return $this->applyPatch( 'patch-tc-timestamp.sql', false,
1035 "Converting tc_time from UNIX epoch to MediaWiki timestamp" );
1039 * Update CategoryLinks collation
1041 protected function doCollationUpdate() {
1042 global $wgCategoryCollation;
1043 if ( $this->db->fieldExists( 'categorylinks', 'cl_collation', __METHOD__ ) ) {
1044 if ( $this->db->selectField(
1045 'categorylinks',
1046 'COUNT(*)',
1047 'cl_collation != ' . $this->db->addQuotes( $wgCategoryCollation ),
1048 __METHOD__
1049 ) == 0
1051 $this->output( "...collations up-to-date.\n" );
1053 return;
1056 $this->output( "Updating category collations..." );
1057 $task = $this->maintenance->runChild( 'UpdateCollation' );
1058 $task->execute();
1059 $this->output( "...done.\n" );
1064 * Migrates user options from the user table blob to user_properties
1066 protected function doMigrateUserOptions() {
1067 if ( $this->db->tableExists( 'user_properties' ) ) {
1068 $cl = $this->maintenance->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
1069 $cl->execute();
1070 $this->output( "done.\n" );
1075 * Enable profiling table when it's turned on
1077 protected function doEnableProfiling() {
1078 global $wgProfiler;
1080 if ( !$this->doTable( 'profiling' ) ) {
1081 return true;
1084 $profileToDb = false;
1085 if ( isset( $wgProfiler['output'] ) ) {
1086 $out = $wgProfiler['output'];
1087 if ( $out === 'db' ) {
1088 $profileToDb = true;
1089 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
1090 $profileToDb = true;
1094 if ( $profileToDb && !$this->db->tableExists( 'profiling', __METHOD__ ) ) {
1095 $this->applyPatch( 'patch-profiling.sql', false, 'Add profiling table' );
1100 * Rebuilds the localisation cache
1102 protected function rebuildLocalisationCache() {
1104 * @var $cl RebuildLocalisationCache
1106 $cl = $this->maintenance->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
1107 $this->output( "Rebuilding localisation cache...\n" );
1108 $cl->setForce();
1109 $cl->execute();
1110 $this->output( "done.\n" );
1114 * Turns off content handler fields during parts of the upgrade
1115 * where they aren't available.
1117 protected function disableContentHandlerUseDB() {
1118 global $wgContentHandlerUseDB;
1120 if ( $wgContentHandlerUseDB ) {
1121 $this->output( "Turning off Content Handler DB fields for this part of upgrade.\n" );
1122 $this->holdContentHandlerUseDB = $wgContentHandlerUseDB;
1123 $wgContentHandlerUseDB = false;
1128 * Turns content handler fields back on.
1130 protected function enableContentHandlerUseDB() {
1131 global $wgContentHandlerUseDB;
1133 if ( $this->holdContentHandlerUseDB ) {
1134 $this->output( "Content Handler DB fields should be usable now.\n" );
1135 $wgContentHandlerUseDB = $this->holdContentHandlerUseDB;