MediaWiki REL1_34
DatabaseUpdater.php
Go to the documentation of this file.
1<?php
26
27require_once __DIR__ . '/../../maintenance/Maintenance.php';
28
36abstract class DatabaseUpdater {
38
44 protected $updates = [];
45
51 protected $updatesSkipped = [];
52
57 protected $extensionUpdates = [];
58
64 protected $db;
65
69 protected $maintenance;
70
71 protected $shared = false;
72
78 DeleteDefaultMessages::class,
79 PopulateRevisionLength::class,
80 PopulateRevisionSha1::class,
81 PopulateImageSha1::class,
82 FixExtLinksProtocolRelative::class,
83 PopulateFilearchiveSha1::class,
84 PopulateBacklinkNamespace::class,
85 FixDefaultJsonContentPages::class,
86 CleanupEmptyCategories::class,
87 AddRFCandPMIDInterwiki::class,
88 PopulatePPSortKey::class,
89 PopulateIpChanges::class,
90 RefreshExternallinksIndex::class,
91 ];
92
98 protected $fileHandle = null;
99
105 protected $skipSchema = false;
106
110 protected $holdContentHandlerUseDB = true;
111
117 protected function __construct(
119 $shared,
121 ) {
122 $this->db = $db;
123 $this->db->setFlag( DBO_DDLMODE ); // For Oracle's handling of schema files
124 $this->shared = $shared;
125 if ( $maintenance ) {
126 $this->maintenance = $maintenance;
127 $this->fileHandle = $maintenance->fileHandle;
128 } else {
129 $this->maintenance = new FakeMaintenance;
130 }
131 $this->maintenance->setDB( $db );
132 $this->initOldGlobals();
133 $this->loadExtensions();
134 Hooks::run( 'LoadExtensionSchemaUpdates', [ $this ] );
135 }
136
141 private function initOldGlobals() {
142 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
143 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
144
145 # For extensions only, should be populated via hooks
146 # $wgDBtype should be checked to specify the proper file
147 $wgExtNewTables = []; // table, dir
148 $wgExtNewFields = []; // table, column, dir
149 $wgExtPGNewFields = []; // table, column, column attributes; for PostgreSQL
150 $wgExtPGAlteredFields = []; // table, column, new type, conversion method; for PostgreSQL
151 $wgExtNewIndexes = []; // table, index, dir
152 $wgExtModifiedFields = []; // table, index, dir
153 }
154
159 private function loadExtensions() {
160 if ( !defined( 'MEDIAWIKI_INSTALL' ) || defined( 'MW_EXTENSIONS_LOADED' ) ) {
161 return; // already loaded
162 }
164
165 $registry = ExtensionRegistry::getInstance();
166 $queue = $registry->getQueue();
167 // Don't accidentally load extensions in the future
168 $registry->clearQueue();
169
170 // This will automatically add "AutoloadClasses" to $wgAutoloadClasses
171 $data = $registry->readFromQueue( $queue );
172 $hooks = $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ?? [];
173 if ( $vars && isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
174 $hooks = array_merge_recursive( $hooks, $vars['wgHooks']['LoadExtensionSchemaUpdates'] );
175 }
177 $wgHooks['LoadExtensionSchemaUpdates'] = $hooks;
178 if ( $vars && isset( $vars['wgAutoloadClasses'] ) ) {
179 $wgAutoloadClasses += $vars['wgAutoloadClasses'];
180 }
181 }
182
191 public static function newForDB(
193 $shared = false,
195 ) {
196 $type = $db->getType();
197 if ( in_array( $type, Installer::getDBTypes() ) ) {
198 $class = ucfirst( $type ) . 'Updater';
199
200 return new $class( $db, $shared, $maintenance );
201 } else {
202 throw new MWException( __METHOD__ . ' called for unsupported $wgDBtype' );
203 }
204 }
205
211 public function getDB() {
212 return $this->db;
213 }
214
221 public function output( $str ) {
222 if ( $this->maintenance->isQuiet() ) {
223 return;
224 }
225 global $wgCommandLineMode;
226 if ( !$wgCommandLineMode ) {
227 $str = htmlspecialchars( $str );
228 }
229 echo $str;
230 flush();
231 }
232
245 public function addExtensionUpdate( array $update ) {
246 $this->extensionUpdates[] = $update;
247 }
248
258 public function addExtensionTable( $tableName, $sqlPath ) {
259 $this->extensionUpdates[] = [ 'addTable', $tableName, $sqlPath, true ];
260 }
261
269 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
270 $this->extensionUpdates[] = [ 'addIndex', $tableName, $indexName, $sqlPath, true ];
271 }
272
281 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
282 $this->extensionUpdates[] = [ 'addField', $tableName, $columnName, $sqlPath, true ];
283 }
284
293 public function dropExtensionField( $tableName, $columnName, $sqlPath ) {
294 $this->extensionUpdates[] = [ 'dropField', $tableName, $columnName, $sqlPath, true ];
295 }
296
306 public function dropExtensionIndex( $tableName, $indexName, $sqlPath ) {
307 $this->extensionUpdates[] = [ 'dropIndex', $tableName, $indexName, $sqlPath, true ];
308 }
309
317 public function dropExtensionTable( $tableName, $sqlPath ) {
318 $this->extensionUpdates[] = [ 'dropTable', $tableName, $sqlPath, true ];
319 }
320
333 public function renameExtensionIndex( $tableName, $oldIndexName, $newIndexName,
334 $sqlPath, $skipBothIndexExistWarning = false
335 ) {
336 $this->extensionUpdates[] = [
337 'renameIndex',
338 $tableName,
339 $oldIndexName,
340 $newIndexName,
341 $skipBothIndexExistWarning,
342 $sqlPath,
343 true
344 ];
345 }
346
354 public function modifyExtensionField( $tableName, $fieldName, $sqlPath ) {
355 $this->extensionUpdates[] = [ 'modifyField', $tableName, $fieldName, $sqlPath, true ];
356 }
357
364 public function modifyExtensionTable( $tableName, $sqlPath ) {
365 $this->extensionUpdates[] = [ 'modifyTable', $tableName, $sqlPath, true ];
366 }
367
375 public function tableExists( $tableName ) {
376 return ( $this->db->tableExists( $tableName, __METHOD__ ) );
377 }
378
388 public function addPostDatabaseUpdateMaintenance( $class ) {
389 $this->postDatabaseUpdateMaintenance[] = $class;
390 }
391
397 protected function getExtensionUpdates() {
399 }
400
409
416 private function writeSchemaUpdateFile( array $schemaUpdate = [] ) {
418 $this->updatesSkipped = [];
419
420 foreach ( $updates as $funcList ) {
421 list( $func, $args, $origParams ) = $funcList;
422 // @phan-suppress-next-line PhanUndeclaredInvokeInCallable
423 $func( ...$args );
424 flush();
425 $this->updatesSkipped[] = $origParams;
426 }
427 }
428
439 public function getSchemaVars() {
440 return []; // DB-type specific
441 }
442
448 public function doUpdates( array $what = [ 'core', 'extensions', 'stats' ] ) {
449 $this->db->setSchemaVars( $this->getSchemaVars() );
450
451 $what = array_flip( $what );
452 $this->skipSchema = isset( $what['noschema'] ) || $this->fileHandle !== null;
453 if ( isset( $what['core'] ) ) {
454 $this->runUpdates( $this->getCoreUpdateList(), false );
455 }
456 if ( isset( $what['extensions'] ) ) {
457 $this->runUpdates( $this->getOldGlobalUpdates(), false );
458 $this->runUpdates( $this->getExtensionUpdates(), true );
459 }
460
461 if ( isset( $what['stats'] ) ) {
462 $this->checkStats();
463 }
464
465 if ( $this->fileHandle ) {
466 $this->skipSchema = false;
467 $this->writeSchemaUpdateFile();
468 }
469 }
470
477 private function runUpdates( array $updates, $passSelf ) {
478 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
479
480 $updatesDone = [];
481 $updatesSkipped = [];
482 foreach ( $updates as $params ) {
483 $origParams = $params;
484 $func = array_shift( $params );
485 if ( !is_array( $func ) && method_exists( $this, $func ) ) {
486 $func = [ $this, $func ];
487 } elseif ( $passSelf ) {
488 array_unshift( $params, $this );
489 }
490 $ret = $func( ...$params );
491 flush();
492 if ( $ret !== false ) {
493 $updatesDone[] = $origParams;
494 $lbFactory->waitForReplication( [ 'timeout' => self::REPLICATION_WAIT_TIMEOUT ] );
495 } else {
496 $updatesSkipped[] = [ $func, $params, $origParams ];
497 }
498 }
499 $this->updatesSkipped = array_merge( $this->updatesSkipped, $updatesSkipped );
500 $this->updates = array_merge( $this->updates, $updatesDone );
501 }
502
510 public function updateRowExists( $key ) {
511 $row = $this->db->selectRow(
512 'updatelog',
513 # T67813
514 '1 AS X',
515 [ 'ul_key' => $key ],
516 __METHOD__
517 );
518
519 return (bool)$row;
520 }
521
529 public function insertUpdateRow( $key, $val = null ) {
530 $this->db->clearFlag( DBO_DDLMODE );
531 $values = [ 'ul_key' => $key ];
532 if ( $val && $this->canUseNewUpdatelog() ) {
533 $values['ul_value'] = $val;
534 }
535 $this->db->insert( 'updatelog', $values, __METHOD__, [ 'IGNORE' ] );
536 $this->db->setFlag( DBO_DDLMODE );
537 }
538
547 protected function canUseNewUpdatelog() {
548 return $this->db->tableExists( 'updatelog', __METHOD__ ) &&
549 $this->db->fieldExists( 'updatelog', 'ul_value', __METHOD__ );
550 }
551
560 protected function doTable( $name ) {
562
563 // Don't bother to check $wgSharedTables if there isn't a shared database
564 // or the user actually also wants to do updates on the shared database.
565 if ( $wgSharedDB === null || $this->shared ) {
566 return true;
567 }
568
569 if ( in_array( $name, $wgSharedTables ) ) {
570 $this->output( "...skipping update to shared table $name.\n" );
571 return false;
572 } else {
573 return true;
574 }
575 }
576
585 protected function getOldGlobalUpdates() {
586 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
587 $wgExtNewIndexes;
588
589 $updates = [];
590
591 foreach ( $wgExtNewTables as $tableRecord ) {
592 $updates[] = [
593 'addTable', $tableRecord[0], $tableRecord[1], true
594 ];
595 }
596
597 foreach ( $wgExtNewFields as $fieldRecord ) {
598 $updates[] = [
599 'addField', $fieldRecord[0], $fieldRecord[1],
600 $fieldRecord[2], true
601 ];
602 }
603
604 foreach ( $wgExtNewIndexes as $fieldRecord ) {
605 $updates[] = [
606 'addIndex', $fieldRecord[0], $fieldRecord[1],
607 $fieldRecord[2], true
608 ];
609 }
610
611 foreach ( $wgExtModifiedFields as $fieldRecord ) {
612 $updates[] = [
613 'modifyField', $fieldRecord[0], $fieldRecord[1],
614 $fieldRecord[2], true
615 ];
616 }
617
618 return $updates;
619 }
620
629 abstract protected function getCoreUpdateList();
630
636 public function copyFile( $filename ) {
637 $this->db->sourceFile(
638 $filename,
639 null,
640 null,
641 __METHOD__,
642 [ $this, 'appendLine' ]
643 );
644 }
645
656 public function appendLine( $line ) {
657 $line = rtrim( $line ) . ";\n";
658 if ( fwrite( $this->fileHandle, $line ) === false ) {
659 throw new MWException( "trouble writing file" );
660 }
661
662 return false;
663 }
664
673 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
674 if ( $msg === null ) {
675 $msg = "Applying $path patch";
676 }
677 if ( $this->skipSchema ) {
678 $this->output( "...skipping schema change ($msg).\n" );
679
680 return false;
681 }
682
683 $this->output( "$msg ..." );
684
685 if ( !$isFullPath ) {
686 $path = $this->patchPath( $this->db, $path );
687 }
688 if ( $this->fileHandle !== null ) {
689 $this->copyFile( $path );
690 } else {
691 $this->db->sourceFile( $path );
692 }
693 $this->output( "done.\n" );
694
695 return true;
696 }
697
707 public function patchPath( IDatabase $db, $patch ) {
708 global $IP;
709
710 $dbType = $db->getType();
711 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
712 return "$IP/maintenance/$dbType/archives/$patch";
713 } else {
714 return "$IP/maintenance/archives/$patch";
715 }
716 }
717
726 protected function addTable( $name, $patch, $fullpath = false ) {
727 if ( !$this->doTable( $name ) ) {
728 return true;
729 }
730
731 if ( $this->db->tableExists( $name, __METHOD__ ) ) {
732 $this->output( "...$name table already exists.\n" );
733 } else {
734 return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
735 }
736
737 return true;
738 }
739
749 protected function addField( $table, $field, $patch, $fullpath = false ) {
750 if ( !$this->doTable( $table ) ) {
751 return true;
752 }
753
754 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
755 $this->output( "...$table table does not exist, skipping new field patch.\n" );
756 } elseif ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
757 $this->output( "...have $field field in $table table.\n" );
758 } else {
759 return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
760 }
761
762 return true;
763 }
764
774 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
775 if ( !$this->doTable( $table ) ) {
776 return true;
777 }
778
779 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
780 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
781 } elseif ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
782 $this->output( "...index $index already set on $table table.\n" );
783 } else {
784 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
785 }
786
787 return true;
788 }
789
800 protected function addIndexIfNoneExist( $table, $indexes, $patch, $fullpath = false ) {
801 if ( !$this->doTable( $table ) ) {
802 return true;
803 }
804
805 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
806 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
807 return true;
808 }
809
810 $newIndex = $indexes[0];
811 foreach ( $indexes as $index ) {
812 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
813 $this->output(
814 "...skipping index $newIndex because index $index already set on $table table.\n"
815 );
816 return true;
817 }
818 }
819
820 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
821 }
822
832 protected function dropField( $table, $field, $patch, $fullpath = false ) {
833 if ( !$this->doTable( $table ) ) {
834 return true;
835 }
836
837 if ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
838 return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
839 } else {
840 $this->output( "...$table table does not contain $field field.\n" );
841 }
842
843 return true;
844 }
845
855 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
856 if ( !$this->doTable( $table ) ) {
857 return true;
858 }
859
860 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
861 return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
862 } else {
863 $this->output( "...$index key doesn't exist.\n" );
864 }
865
866 return true;
867 }
868
881 protected function renameIndex( $table, $oldIndex, $newIndex,
882 $skipBothIndexExistWarning, $patch, $fullpath = false
883 ) {
884 if ( !$this->doTable( $table ) ) {
885 return true;
886 }
887
888 // First requirement: the table must exist
889 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
890 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
891
892 return true;
893 }
894
895 // Second requirement: the new index must be missing
896 if ( $this->db->indexExists( $table, $newIndex, __METHOD__ ) ) {
897 $this->output( "...index $newIndex already set on $table table.\n" );
898 if ( !$skipBothIndexExistWarning &&
899 $this->db->indexExists( $table, $oldIndex, __METHOD__ )
900 ) {
901 $this->output( "...WARNING: $oldIndex still exists, despite it has " .
902 "been renamed into $newIndex (which also exists).\n" .
903 " $oldIndex should be manually removed if not needed anymore.\n" );
904 }
905
906 return true;
907 }
908
909 // Third requirement: the old index must exist
910 if ( !$this->db->indexExists( $table, $oldIndex, __METHOD__ ) ) {
911 $this->output( "...skipping: index $oldIndex doesn't exist.\n" );
912
913 return true;
914 }
915
916 // Requirements have been satisfied, patch can be applied
917 return $this->applyPatch(
918 $patch,
919 $fullpath,
920 "Renaming index $oldIndex into $newIndex to table $table"
921 );
922 }
923
935 public function dropTable( $table, $patch = false, $fullpath = false ) {
936 if ( !$this->doTable( $table ) ) {
937 return true;
938 }
939
940 if ( $this->db->tableExists( $table, __METHOD__ ) ) {
941 $msg = "Dropping table $table";
942
943 if ( $patch === false ) {
944 $this->output( "$msg ..." );
945 $this->db->dropTable( $table, __METHOD__ );
946 $this->output( "done.\n" );
947 } else {
948 return $this->applyPatch( $patch, $fullpath, $msg );
949 }
950 } else {
951 $this->output( "...$table doesn't exist.\n" );
952 }
953
954 return true;
955 }
956
966 public function modifyField( $table, $field, $patch, $fullpath = false ) {
967 if ( !$this->doTable( $table ) ) {
968 return true;
969 }
970
971 $updateKey = "$table-$field-$patch";
972 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
973 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
974 } elseif ( !$this->db->fieldExists( $table, $field, __METHOD__ ) ) {
975 $this->output( "...$field field does not exist in $table table, " .
976 "skipping modify field patch.\n" );
977 } elseif ( $this->updateRowExists( $updateKey ) ) {
978 $this->output( "...$field in table $table already modified by patch $patch.\n" );
979 } else {
980 $apply = $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
981 if ( $apply ) {
982 $this->insertUpdateRow( $updateKey );
983 }
984 return $apply;
985 }
986 return true;
987 }
988
998 public function modifyTable( $table, $patch, $fullpath = false ) {
999 if ( !$this->doTable( $table ) ) {
1000 return true;
1001 }
1002
1003 $updateKey = "$table-$patch";
1004 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
1005 $this->output( "...$table table does not exist, skipping modify table patch.\n" );
1006 } elseif ( $this->updateRowExists( $updateKey ) ) {
1007 $this->output( "...table $table already modified by patch $patch.\n" );
1008 } else {
1009 $apply = $this->applyPatch( $patch, $fullpath, "Modifying table $table" );
1010 if ( $apply ) {
1011 $this->insertUpdateRow( $updateKey );
1012 }
1013 return $apply;
1014 }
1015 return true;
1016 }
1017
1033 public function runMaintenance( $class, $script ) {
1034 $this->output( "Running $script...\n" );
1035 $task = $this->maintenance->runChild( $class );
1036 $ok = $task->execute();
1037 if ( !$ok ) {
1038 throw new RuntimeException( "Execution of $script did not complete successfully." );
1039 }
1040 $this->output( "done.\n" );
1041 }
1042
1048 public function setFileAccess() {
1049 $repo = RepoGroup::singleton()->getLocalRepo();
1050 $zonePath = $repo->getZonePath( 'temp' );
1051 if ( $repo->getBackend()->directoryExists( [ 'dir' => $zonePath ] ) ) {
1052 // If the directory was never made, then it will have the right ACLs when it is made
1053 $status = $repo->getBackend()->secure( [
1054 'dir' => $zonePath,
1055 'noAccess' => true,
1056 'noListing' => true
1057 ] );
1058 if ( $status->isOK() ) {
1059 $this->output( "Set the local repo temp zone container to be private.\n" );
1060 } else {
1061 $this->output( "Failed to set the local repo temp zone container to be private.\n" );
1062 }
1063 }
1064 }
1065
1069 public function purgeCache() {
1071 // We can't guarantee that the user will be able to use TRUNCATE,
1072 // but we know that DELETE is available to us
1073 $this->output( "Purging caches..." );
1074
1075 // ObjectCache
1076 $this->db->delete( 'objectcache', '*', __METHOD__ );
1077
1078 // LocalisationCache
1079 if ( $wgLocalisationCacheConf['manualRecache'] ) {
1080 $this->rebuildLocalisationCache();
1081 }
1082
1083 // ResourceLoader: Message cache
1084 $blobStore = new MessageBlobStore(
1085 MediaWikiServices::getInstance()->getResourceLoader()
1086 );
1087 $blobStore->clear();
1088
1089 // ResourceLoader: File-dependency cache
1090 $this->db->delete( 'module_deps', '*', __METHOD__ );
1091 $this->output( "done.\n" );
1092 }
1093
1097 protected function checkStats() {
1098 $this->output( "...site_stats is populated..." );
1099 $row = $this->db->selectRow( 'site_stats', '*', [ 'ss_row_id' => 1 ], __METHOD__ );
1100 if ( $row === false ) {
1101 $this->output( "data is missing! rebuilding...\n" );
1102 } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
1103 $this->output( "missing ss_total_pages, rebuilding...\n" );
1104 } else {
1105 $this->output( "done.\n" );
1106
1107 return;
1108 }
1109 SiteStatsInit::doAllAndCommit( $this->db );
1110 }
1111
1112 # Common updater functions
1113
1117 protected function doActiveUsersInit() {
1118 $activeUsers = $this->db->selectField( 'site_stats', 'ss_active_users', '', __METHOD__ );
1119 if ( $activeUsers == -1 ) {
1120 $activeUsers = $this->db->selectField( 'recentchanges',
1121 'COUNT( DISTINCT rc_user_text )',
1122 [ 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ], __METHOD__
1123 );
1124 $this->db->update( 'site_stats',
1125 [ 'ss_active_users' => intval( $activeUsers ) ],
1126 [ 'ss_row_id' => 1 ], __METHOD__, [ 'LIMIT' => 1 ]
1127 );
1128 }
1129 $this->output( "...ss_active_users user count set...\n" );
1130 }
1131
1135 protected function doLogUsertextPopulation() {
1136 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
1137 $this->output(
1138 "Populating log_user_text field, printing progress markers. For large\n" .
1139 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1140 "maintenance/populateLogUsertext.php.\n"
1141 );
1142
1143 $task = $this->maintenance->runChild( PopulateLogUsertext::class );
1144 $task->execute();
1145 $this->output( "done.\n" );
1146 }
1147 }
1148
1152 protected function doLogSearchPopulation() {
1153 if ( !$this->updateRowExists( 'populate log_search' ) ) {
1154 $this->output(
1155 "Populating log_search table, printing progress markers. For large\n" .
1156 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1157 "maintenance/populateLogSearch.php.\n" );
1158
1159 $task = $this->maintenance->runChild( PopulateLogSearch::class );
1160 $task->execute();
1161 $this->output( "done.\n" );
1162 }
1163 }
1164
1168 protected function doCollationUpdate() {
1169 global $wgCategoryCollation;
1170 if ( $this->db->fieldExists( 'categorylinks', 'cl_collation', __METHOD__ ) ) {
1171 if ( $this->db->selectField(
1172 'categorylinks',
1173 'COUNT(*)',
1174 'cl_collation != ' . $this->db->addQuotes( $wgCategoryCollation ),
1175 __METHOD__
1176 ) == 0
1177 ) {
1178 $this->output( "...collations up-to-date.\n" );
1179
1180 return;
1181 }
1182
1183 $this->output( "Updating category collations..." );
1184 $task = $this->maintenance->runChild( UpdateCollation::class );
1185 $task->execute();
1186 $this->output( "...done.\n" );
1187 }
1188 }
1189
1193 protected function doMigrateUserOptions() {
1194 if ( $this->db->tableExists( 'user_properties' ) ) {
1195 $cl = $this->maintenance->runChild( ConvertUserOptions::class, 'convertUserOptions.php' );
1196 $cl->execute();
1197 $this->output( "done.\n" );
1198 }
1199 }
1200
1204 protected function doEnableProfiling() {
1205 global $wgProfiler;
1206
1207 if ( !$this->doTable( 'profiling' ) ) {
1208 return;
1209 }
1210
1211 $profileToDb = false;
1212 if ( isset( $wgProfiler['output'] ) ) {
1213 $out = $wgProfiler['output'];
1214 if ( $out === 'db' ) {
1215 $profileToDb = true;
1216 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
1217 $profileToDb = true;
1218 }
1219 }
1220
1221 if ( $profileToDb && !$this->db->tableExists( 'profiling', __METHOD__ ) ) {
1222 $this->applyPatch( 'patch-profiling.sql', false, 'Add profiling table' );
1223 }
1224 }
1225
1229 protected function rebuildLocalisationCache() {
1233 $cl = $this->maintenance->runChild(
1234 RebuildLocalisationCache::class, 'rebuildLocalisationCache.php'
1235 );
1236 '@phan-var RebuildLocalisationCache $cl';
1237 $this->output( "Rebuilding localisation cache...\n" );
1238 $cl->setForce();
1239 $cl->execute();
1240 $this->output( "done.\n" );
1241 }
1242
1247 protected function disableContentHandlerUseDB() {
1249
1250 if ( $wgContentHandlerUseDB ) {
1251 $this->output( "Turning off Content Handler DB fields for this part of upgrade.\n" );
1252 $this->holdContentHandlerUseDB = $wgContentHandlerUseDB;
1253 $wgContentHandlerUseDB = false;
1254 }
1255 }
1256
1260 protected function enableContentHandlerUseDB() {
1262
1263 if ( $this->holdContentHandlerUseDB ) {
1264 $this->output( "Content Handler DB fields should be usable now.\n" );
1265 $wgContentHandlerUseDB = $this->holdContentHandlerUseDB;
1266 }
1267 }
1268
1273 protected function migrateComments() {
1274 if ( !$this->updateRowExists( 'MigrateComments' ) ) {
1275 $this->output(
1276 "Migrating comments to the 'comments' table, printing progress markers. For large\n" .
1277 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1278 "maintenance/migrateComments.php.\n"
1279 );
1280 $task = $this->maintenance->runChild( MigrateComments::class, 'migrateComments.php' );
1281 $ok = $task->execute();
1282 $this->output( $ok ? "done.\n" : "errors were encountered.\n" );
1283 }
1284 }
1285
1290 protected function migrateImageCommentTemp() {
1291 if ( $this->tableExists( 'image_comment_temp' ) ) {
1292 $this->output( "Merging image_comment_temp into the image table\n" );
1293 $task = $this->maintenance->runChild(
1294 MigrateImageCommentTemp::class, 'migrateImageCommentTemp.php'
1295 );
1296 // @phan-suppress-next-line PhanUndeclaredMethod
1297 $task->setForce();
1298 $ok = $task->execute();
1299 $this->output( $ok ? "done.\n" : "errors were encountered.\n" );
1300 if ( $ok ) {
1301 $this->dropTable( 'image_comment_temp' );
1302 }
1303 }
1304 }
1305
1310 protected function migrateActors() {
1311 if ( !$this->updateRowExists( 'MigrateActors' ) ) {
1312 $this->output(
1313 "Migrating actors to the 'actor' table, printing progress markers. For large\n" .
1314 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1315 "maintenance/migrateActors.php.\n"
1316 );
1317 $task = $this->maintenance->runChild( 'MigrateActors', 'migrateActors.php' );
1318 $ok = $task->execute();
1319 $this->output( $ok ? "done.\n" : "errors were encountered.\n" );
1320 }
1321 }
1322
1327 protected function migrateArchiveText() {
1328 if ( $this->db->fieldExists( 'archive', 'ar_text', __METHOD__ ) ) {
1329 $this->output( "Migrating archive ar_text to modern storage.\n" );
1330 $task = $this->maintenance->runChild( MigrateArchiveText::class, 'migrateArchiveText.php' );
1331 // @phan-suppress-next-line PhanUndeclaredMethod
1332 $task->setForce();
1333 if ( $task->execute() ) {
1334 $this->applyPatch( 'patch-drop-ar_text.sql', false,
1335 'Dropping ar_text and ar_flags columns' );
1336 }
1337 }
1338 }
1339
1344 protected function populateArchiveRevId() {
1345 $info = $this->db->fieldInfo( 'archive', 'ar_rev_id', __METHOD__ );
1346 if ( !$info ) {
1347 throw new MWException( 'Missing ar_rev_id field of archive table. Should not happen.' );
1348 }
1349 if ( $info->isNullable() ) {
1350 $this->output( "Populating ar_rev_id.\n" );
1351 $task = $this->maintenance->runChild( 'PopulateArchiveRevId', 'populateArchiveRevId.php' );
1352 if ( $task->execute() ) {
1353 $this->applyPatch( 'patch-ar_rev_id-not-null.sql', false,
1354 'Making ar_rev_id not nullable' );
1355 }
1356 }
1357 }
1358
1363 protected function populateExternallinksIndex60() {
1364 if ( !$this->updateRowExists( 'populate externallinks.el_index_60' ) ) {
1365 $this->output(
1366 "Populating el_index_60 field, printing progress markers. For large\n" .
1367 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1368 "maintenance/populateExternallinksIndex60.php.\n"
1369 );
1370 $task = $this->maintenance->runChild( 'PopulateExternallinksIndex60',
1371 'populateExternallinksIndex60.php' );
1372 $task->execute();
1373 $this->output( "done.\n" );
1374 }
1375 }
1376
1381 protected function populateContentTables() {
1384 !$this->updateRowExists( 'PopulateContentTables' )
1385 ) {
1386 $this->output(
1387 "Migrating revision data to the MCR 'slot' and 'content' tables, printing progress markers.\n" .
1388 "For large databases, you may want to hit Ctrl-C and do this manually with\n" .
1389 "maintenance/populateContentTables.php.\n"
1390 );
1391 $task = $this->maintenance->runChild(
1392 PopulateContentTables::class, 'populateContentTables.php'
1393 );
1394 $ok = $task->execute();
1395 $this->output( $ok ? "done.\n" : "errors were encountered.\n" );
1396 if ( $ok ) {
1397 $this->insertUpdateRow( 'PopulateContentTables' );
1398 }
1399 }
1400 }
1401
1419 protected function ifNoActorTable( $func, ...$params ) {
1420 if ( $this->tableExists( 'actor' ) ) {
1421 return null;
1422 }
1423
1424 // Handle $passSelf from runUpdates().
1425 $passSelf = false;
1426 if ( $func === $this ) {
1427 $passSelf = true;
1428 $func = array_shift( $params );
1429 }
1430
1431 if ( !is_array( $func ) && method_exists( $this, $func ) ) {
1432 $func = [ $this, $func ];
1433 } elseif ( $passSelf ) {
1434 array_unshift( $params, $this );
1435 }
1436
1437 // @phan-suppress-next-line PhanUndeclaredInvokeInCallable Phan is confused
1438 return $func( ...$params );
1439 }
1440}
int $wgMultiContentRevisionSchemaMigrationStage
RevisionStore table schema migration stage (content, slots, content_models & slot_roles tables).
$wgSharedTables
$wgAutoloadClasses
Array mapping class names to filenames, for autoloading.
$wgProfiler
Profiler configuration.
$wgCategoryCollation
Specify how category names should be sorted, when listed on a category page.
$wgHooks
Global list of hooks.
$wgSharedDB
Shared database for multiple wikis.
$wgContentHandlerUseDB
Set to false to disable use of the database fields introduced by the ContentHandler facility.
$wgLocalisationCacheConf
Localisation cache configuration.
global $wgCommandLineMode
$IP
Definition WebStart.php:41
$line
Definition cdb.php:59
if( $line===false) $args
Definition cdb.php:64
Class for handling database updates.
purgeCache()
Purge various database caches.
addExtensionTable( $tableName, $sqlPath)
Convenience wrapper for addExtensionUpdate() when adding a new table (which is the most common usage ...
getDB()
Get a database connection to run updates.
setFileAccess()
Set any .htaccess files or equivilent for storage repos.
migrateImageCommentTemp()
Merge image_comment_temp into the image table.
loadExtensions()
Loads LocalSettings.php, if needed, and initialises everything needed for LoadExtensionSchemaUpdates ...
addIndex( $table, $index, $patch, $fullpath=false)
Add a new index to an existing table.
array $updates
Array of updates to perform on the database.
$holdContentHandlerUseDB
Hold the value of $wgContentHandlerUseDB during the upgrade.
modifyExtensionTable( $tableName, $sqlPath)
disableContentHandlerUseDB()
Turns off content handler fields during parts of the upgrade where they aren't available.
bool $skipSchema
Flag specifying whether or not to skip schema (e.g.
populateArchiveRevId()
Populate ar_rev_id, then make it not nullable.
runMaintenance( $class, $script)
Run a maintenance script.
migrateArchiveText()
Migrate ar_text to modern storage.
addField( $table, $field, $patch, $fullpath=false)
Add a new field to an existing table.
addExtensionIndex( $tableName, $indexName, $sqlPath)
modifyTable( $table, $patch, $fullpath=false)
Modify an existing table, similar to modifyField.
doUpdates(array $what=[ 'core', 'extensions', 'stats'])
Do all the updates.
Maintenance $maintenance
updateRowExists( $key)
Helper function: check if the given key is present in the updatelog table.
runUpdates(array $updates, $passSelf)
Helper function for doUpdates()
getCoreUpdateList()
Get an array of updates to perform on the database.
enableContentHandlerUseDB()
Turns content handler fields back on.
populateExternallinksIndex60()
Populates the externallinks.el_index_60 field.
output( $str)
Output some text.
doLogSearchPopulation()
Migrate log params to new table and index for searching.
doLogUsertextPopulation()
Populates the log_user_text field in the logging table.
getExtensionUpdates()
Get the list of extension-defined updates.
insertUpdateRow( $key, $val=null)
Helper function: Add a key to the updatelog table Obviously, only use this for updates that occur aft...
canUseNewUpdatelog()
Updatelog was changed in 1.17 to have a ul_value column so we can record more information about what ...
patchPath(IDatabase $db, $patch)
Get the full path of a patch file.
copyFile( $filename)
Append an SQL fragment to the open file handle.
tableExists( $tableName)
string[] $postDatabaseUpdateMaintenance
Scripts to run after database update Should be a subclass of LoggedUpdateMaintenance.
renameIndex( $table, $oldIndex, $newIndex, $skipBothIndexExistWarning, $patch, $fullpath=false)
Rename an index from an existing table.
writeSchemaUpdateFile(array $schemaUpdate=[])
rebuildLocalisationCache()
Rebuilds the localisation cache.
addExtensionField( $tableName, $columnName, $sqlPath)
IMaintainableDatabase $db
Handle to the database subclass.
dropExtensionTable( $tableName, $sqlPath)
addTable( $name, $patch, $fullpath=false)
Add a new table to the database.
modifyField( $table, $field, $patch, $fullpath=false)
Modify an existing field.
doActiveUsersInit()
Sets the number of active users in the site_stats table.
addIndexIfNoneExist( $table, $indexes, $patch, $fullpath=false)
Add a new index to an existing table if none of the given indexes exist.
dropExtensionField( $tableName, $columnName, $sqlPath)
static newForDB(IMaintainableDatabase $db, $shared=false, Maintenance $maintenance=null)
getOldGlobalUpdates()
Before 1.17, we used to handle updates via stuff like $wgExtNewTables/Fields/Indexes.
addPostDatabaseUpdateMaintenance( $class)
Add a maintenance script to be run after the database updates are complete.
dropField( $table, $field, $patch, $fullpath=false)
Drop a field from an existing table.
doCollationUpdate()
Update CategoryLinks collation.
renameExtensionIndex( $tableName, $oldIndexName, $newIndexName, $sqlPath, $skipBothIndexExistWarning=false)
Rename an index on an extension table.
migrateActors()
Migrate actors to the new 'actor' table.
addExtensionUpdate(array $update)
Add a new update coming from an extension.
array $updatesSkipped
Array of updates that were skipped.
resource $fileHandle
File handle for SQL output.
appendLine( $line)
Append a line to the open filehandle.
dropExtensionIndex( $tableName, $indexName, $sqlPath)
Drop an index from an extension table.
initOldGlobals()
Initialize all of the old globals.
doEnableProfiling()
Enable profiling table when it's turned on.
array $extensionUpdates
List of extension-provided database updates.
checkStats()
Check the site_stats table is not properly populated.
modifyExtensionField( $tableName, $fieldName, $sqlPath)
applyPatch( $path, $isFullPath=false, $msg=null)
Applies a SQL patch.
dropIndex( $table, $index, $patch, $fullpath=false)
Drop an index from an existing table.
populateContentTables()
Populates the MCR content tables.
__construct(IMaintainableDatabase &$db, $shared, Maintenance $maintenance=null)
dropTable( $table, $patch=false, $fullpath=false)
If the specified table exists, drop it, or execute the patch if one is provided.
migrateComments()
Migrate comments to the new 'comment' table.
ifNoActorTable( $func,... $params)
Only run a function if the actor table does not exist.
getSchemaVars()
Get appropriate schema variables in the current database connection.
doTable( $name)
Returns whether updates should be executed on the database table $name.
doMigrateUserOptions()
Migrates user options from the user table blob to user_properties.
Fake maintenance wrapper, mostly used for the web installer/updater.
static getExistingLocalSettings()
Determine if LocalSettings.php exists.
static getDBTypes()
Get a list of known DB types.
MediaWiki exception.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
setDB(IMaintainableDatabase $db)
Sets database object to be returned by getDB().
MediaWikiServices is the service locator for the application scope of MediaWiki.
This class generates message blobs for use by ResourceLoader.
static doAllAndCommit( $database, array $options=[])
Do all updates and commit them.
const SCHEMA_COMPAT_WRITE_NEW
Definition Defines.php:275
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:38
getType()
Get the type of the DBMS (e.g.
setFlag( $flag, $remember=self::REMEMBER_NOTHING)
Set a flag for this connection.
Advanced database interface for IDatabase handles that include maintenance methods.
const DBO_DDLMODE
Definition defines.php:16
return true
Definition router.php:94