MediaWiki  master
DatabaseUpdater.php
Go to the documentation of this file.
1 <?php
26 
27 require_once __DIR__ . '/../../maintenance/Maintenance.php';
28 
36 abstract class DatabaseUpdater {
37  public const REPLICATION_WAIT_TIMEOUT = 300;
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 
112  protected function __construct(
114  $shared,
116  ) {
117  $this->db = $db;
118  $this->db->setFlag( DBO_DDLMODE ); // For Oracle's handling of schema files
119  $this->shared = $shared;
120  if ( $maintenance ) {
121  $this->maintenance = $maintenance;
122  $this->fileHandle = $maintenance->fileHandle;
123  } else {
124  $this->maintenance = new FakeMaintenance;
125  }
126  $this->maintenance->setDB( $db );
127  }
128 
132  private function loadExtensionSchemaUpdates() {
133  $this->initOldGlobals();
134  $this->loadExtensions();
135  Hooks::run( 'LoadExtensionSchemaUpdates', [ $this ] );
136  }
137 
142  private function initOldGlobals() {
143  global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
144  $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
145 
146  # For extensions only, should be populated via hooks
147  # $wgDBtype should be checked to specify the proper file
148  $wgExtNewTables = []; // table, dir
149  $wgExtNewFields = []; // table, column, dir
150  $wgExtPGNewFields = []; // table, column, column attributes; for PostgreSQL
151  $wgExtPGAlteredFields = []; // table, column, new type, conversion method; for PostgreSQL
152  $wgExtNewIndexes = []; // table, index, dir
153  $wgExtModifiedFields = []; // table, index, dir
154  }
155 
160  private function loadExtensions() {
161  if ( !defined( 'MEDIAWIKI_INSTALL' ) || defined( 'MW_EXTENSIONS_LOADED' ) ) {
162  return; // already loaded
163  }
165 
166  $registry = ExtensionRegistry::getInstance();
167  $queue = $registry->getQueue();
168  // Don't accidentally load extensions in the future
169  $registry->clearQueue();
170 
171  // This will automatically add "AutoloadClasses" to $wgAutoloadClasses
172  $data = $registry->readFromQueue( $queue );
173  $hooks = $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ?? [];
174  if ( $vars && isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
175  $hooks = array_merge_recursive( $hooks, $vars['wgHooks']['LoadExtensionSchemaUpdates'] );
176  }
178  $wgHooks['LoadExtensionSchemaUpdates'] = $hooks;
179  if ( $vars && isset( $vars['wgAutoloadClasses'] ) ) {
180  $wgAutoloadClasses += $vars['wgAutoloadClasses'];
181  }
182  }
183 
192  public static function newForDB(
194  $shared = false,
196  ) {
197  $type = $db->getType();
198  if ( in_array( $type, Installer::getDBTypes() ) ) {
199  $class = ucfirst( $type ) . 'Updater';
200 
201  return new $class( $db, $shared, $maintenance );
202  } else {
203  throw new MWException( __METHOD__ . ' called for unsupported $wgDBtype' );
204  }
205  }
206 
212  public function getDB() {
213  return $this->db;
214  }
215 
222  public function output( $str ) {
223  if ( $this->maintenance->isQuiet() ) {
224  return;
225  }
226  global $wgCommandLineMode;
227  if ( !$wgCommandLineMode ) {
228  $str = htmlspecialchars( $str );
229  }
230  echo $str;
231  flush();
232  }
233 
246  public function addExtensionUpdate( array $update ) {
247  $this->extensionUpdates[] = $update;
248  }
249 
260  public function addExtensionTable( $tableName, $sqlPath ) {
261  $this->extensionUpdates[] = [ 'addTable', $tableName, $sqlPath, true ];
262  }
263 
274  public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
275  $this->extensionUpdates[] = [ 'addIndex', $tableName, $indexName, $sqlPath, true ];
276  }
277 
288  public function addExtensionField( $tableName, $columnName, $sqlPath ) {
289  $this->extensionUpdates[] = [ 'addField', $tableName, $columnName, $sqlPath, true ];
290  }
291 
302  public function dropExtensionField( $tableName, $columnName, $sqlPath ) {
303  $this->extensionUpdates[] = [ 'dropField', $tableName, $columnName, $sqlPath, true ];
304  }
305 
316  public function dropExtensionIndex( $tableName, $indexName, $sqlPath ) {
317  $this->extensionUpdates[] = [ 'dropIndex', $tableName, $indexName, $sqlPath, true ];
318  }
319 
329  public function dropExtensionTable( $tableName, $sqlPath = false ) {
330  $this->extensionUpdates[] = [ 'dropTable', $tableName, $sqlPath, true ];
331  }
332 
346  public function renameExtensionIndex( $tableName, $oldIndexName, $newIndexName,
347  $sqlPath, $skipBothIndexExistWarning = false
348  ) {
349  $this->extensionUpdates[] = [
350  'renameIndex',
351  $tableName,
352  $oldIndexName,
353  $newIndexName,
354  $skipBothIndexExistWarning,
355  $sqlPath,
356  true
357  ];
358  }
359 
370  public function modifyExtensionField( $tableName, $fieldName, $sqlPath ) {
371  $this->extensionUpdates[] = [ 'modifyField', $tableName, $fieldName, $sqlPath, true ];
372  }
373 
383  public function modifyExtensionTable( $tableName, $sqlPath ) {
384  $this->extensionUpdates[] = [ 'modifyTable', $tableName, $sqlPath, true ];
385  }
386 
393  public function tableExists( $tableName ) {
394  return ( $this->db->tableExists( $tableName, __METHOD__ ) );
395  }
396 
406  public function addPostDatabaseUpdateMaintenance( $class ) {
407  $this->postDatabaseUpdateMaintenance[] = $class;
408  }
409 
415  protected function getExtensionUpdates() {
417  }
418 
426  }
427 
434  private function writeSchemaUpdateFile( array $schemaUpdate = [] ) {
436  $this->updatesSkipped = [];
437 
438  foreach ( $updates as $funcList ) {
439  list( $func, $args, $origParams ) = $funcList;
440  // @phan-suppress-next-line PhanUndeclaredInvokeInCallable
441  $func( ...$args );
442  flush();
443  $this->updatesSkipped[] = $origParams;
444  }
445  }
446 
457  public function getSchemaVars() {
458  return []; // DB-type specific
459  }
460 
466  public function doUpdates( array $what = [ 'core', 'extensions', 'stats' ] ) {
467  $this->db->setSchemaVars( $this->getSchemaVars() );
468 
469  $what = array_flip( $what );
470  $this->skipSchema = isset( $what['noschema'] ) || $this->fileHandle !== null;
471  if ( isset( $what['core'] ) ) {
472  $this->runUpdates( $this->getCoreUpdateList(), false );
473  }
474  if ( isset( $what['extensions'] ) ) {
476  $this->runUpdates( $this->getOldGlobalUpdates(), false );
477  $this->runUpdates( $this->getExtensionUpdates(), true );
478  }
479 
480  if ( isset( $what['stats'] ) ) {
481  $this->checkStats();
482  }
483 
484  if ( $this->fileHandle ) {
485  $this->skipSchema = false;
486  $this->writeSchemaUpdateFile();
487  }
488  }
489 
496  private function runUpdates( array $updates, $passSelf ) {
497  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
498 
499  $updatesDone = [];
500  $updatesSkipped = [];
501  foreach ( $updates as $params ) {
502  $origParams = $params;
503  $func = array_shift( $params );
504  if ( !is_array( $func ) && method_exists( $this, $func ) ) {
505  $func = [ $this, $func ];
506  } elseif ( $passSelf ) {
507  array_unshift( $params, $this );
508  }
509  $ret = $func( ...$params );
510  flush();
511  if ( $ret !== false ) {
512  $updatesDone[] = $origParams;
513  $lbFactory->waitForReplication( [ 'timeout' => self::REPLICATION_WAIT_TIMEOUT ] );
514  } else {
515  $updatesSkipped[] = [ $func, $params, $origParams ];
516  }
517  }
518  $this->updatesSkipped = array_merge( $this->updatesSkipped, $updatesSkipped );
519  $this->updates = array_merge( $this->updates, $updatesDone );
520  }
521 
529  public function updateRowExists( $key ) {
530  $row = $this->db->selectRow(
531  'updatelog',
532  # T67813
533  '1 AS X',
534  [ 'ul_key' => $key ],
535  __METHOD__
536  );
537 
538  return (bool)$row;
539  }
540 
554  public function insertUpdateRow( $key, $val = null ) {
555  $this->db->clearFlag( DBO_DDLMODE );
556  $values = [ 'ul_key' => $key ];
557  if ( $val && $this->canUseNewUpdatelog() ) {
558  $values['ul_value'] = $val;
559  }
560  $this->db->insert( 'updatelog', $values, __METHOD__, [ 'IGNORE' ] );
561  $this->db->setFlag( DBO_DDLMODE );
562  }
563 
572  protected function canUseNewUpdatelog() {
573  return $this->db->tableExists( 'updatelog', __METHOD__ ) &&
574  $this->db->fieldExists( 'updatelog', 'ul_value', __METHOD__ );
575  }
576 
585  protected function doTable( $name ) {
587 
588  // Don't bother to check $wgSharedTables if there isn't a shared database
589  // or the user actually also wants to do updates on the shared database.
590  if ( $wgSharedDB === null || $this->shared ) {
591  return true;
592  }
593 
594  if ( in_array( $name, $wgSharedTables ) ) {
595  $this->output( "...skipping update to shared table $name.\n" );
596  return false;
597  } else {
598  return true;
599  }
600  }
601 
610  protected function getOldGlobalUpdates() {
611  global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
612  $wgExtNewIndexes;
613 
614  $updates = [];
615 
616  foreach ( $wgExtNewTables as $tableRecord ) {
617  $updates[] = [
618  'addTable', $tableRecord[0], $tableRecord[1], true
619  ];
620  }
621 
622  foreach ( $wgExtNewFields as $fieldRecord ) {
623  $updates[] = [
624  'addField', $fieldRecord[0], $fieldRecord[1],
625  $fieldRecord[2], true
626  ];
627  }
628 
629  foreach ( $wgExtNewIndexes as $fieldRecord ) {
630  $updates[] = [
631  'addIndex', $fieldRecord[0], $fieldRecord[1],
632  $fieldRecord[2], true
633  ];
634  }
635 
636  foreach ( $wgExtModifiedFields as $fieldRecord ) {
637  $updates[] = [
638  'modifyField', $fieldRecord[0], $fieldRecord[1],
639  $fieldRecord[2], true
640  ];
641  }
642 
643  return $updates;
644  }
645 
654  abstract protected function getCoreUpdateList();
655 
663  protected function copyFile( $filename ) {
664  $this->db->sourceFile(
665  $filename,
666  null,
667  null,
668  __METHOD__,
669  [ $this, 'appendLine' ]
670  );
671  }
672 
685  protected function appendLine( $line ) {
686  $line = rtrim( $line ) . ";\n";
687  if ( fwrite( $this->fileHandle, $line ) === false ) {
688  throw new MWException( "trouble writing file" );
689  }
690 
691  return false;
692  }
693 
705  protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
706  if ( $msg === null ) {
707  $msg = "Applying $path patch";
708  }
709  if ( $this->skipSchema ) {
710  $this->output( "...skipping schema change ($msg).\n" );
711 
712  return false;
713  }
714 
715  $this->output( "$msg ..." );
716 
717  if ( !$isFullPath ) {
718  $path = $this->patchPath( $this->db, $path );
719  }
720  if ( $this->fileHandle !== null ) {
721  $this->copyFile( $path );
722  } else {
723  $this->db->sourceFile( $path );
724  }
725  $this->output( "done.\n" );
726 
727  return true;
728  }
729 
739  public function patchPath( IDatabase $db, $patch ) {
740  global $IP;
741 
742  $dbType = $db->getType();
743  if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
744  return "$IP/maintenance/$dbType/archives/$patch";
745  } else {
746  return "$IP/maintenance/archives/$patch";
747  }
748  }
749 
761  protected function addTable( $name, $patch, $fullpath = false ) {
762  if ( !$this->doTable( $name ) ) {
763  return true;
764  }
765 
766  if ( $this->db->tableExists( $name, __METHOD__ ) ) {
767  $this->output( "...$name table already exists.\n" );
768  } else {
769  return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
770  }
771 
772  return true;
773  }
774 
787  protected function addField( $table, $field, $patch, $fullpath = false ) {
788  if ( !$this->doTable( $table ) ) {
789  return true;
790  }
791 
792  if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
793  $this->output( "...$table table does not exist, skipping new field patch.\n" );
794  } elseif ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
795  $this->output( "...have $field field in $table table.\n" );
796  } else {
797  return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
798  }
799 
800  return true;
801  }
802 
815  protected function addIndex( $table, $index, $patch, $fullpath = false ) {
816  if ( !$this->doTable( $table ) ) {
817  return true;
818  }
819 
820  if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
821  $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
822  } elseif ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
823  $this->output( "...index $index already set on $table table.\n" );
824  } else {
825  return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
826  }
827 
828  return true;
829  }
830 
841  protected function addIndexIfNoneExist( $table, $indexes, $patch, $fullpath = false ) {
842  if ( !$this->doTable( $table ) ) {
843  return true;
844  }
845 
846  if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
847  $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
848  return true;
849  }
850 
851  $newIndex = $indexes[0];
852  foreach ( $indexes as $index ) {
853  if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
854  $this->output(
855  "...skipping index $newIndex because index $index already set on $table table.\n"
856  );
857  return true;
858  }
859  }
860 
861  return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
862  }
863 
876  protected function dropField( $table, $field, $patch, $fullpath = false ) {
877  if ( !$this->doTable( $table ) ) {
878  return true;
879  }
880 
881  if ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
882  return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
883  } else {
884  $this->output( "...$table table does not contain $field field.\n" );
885  }
886 
887  return true;
888  }
889 
902  protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
903  if ( !$this->doTable( $table ) ) {
904  return true;
905  }
906 
907  if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
908  return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
909  } else {
910  $this->output( "...$index key doesn't exist.\n" );
911  }
912 
913  return true;
914  }
915 
931  protected function renameIndex( $table, $oldIndex, $newIndex,
932  $skipBothIndexExistWarning, $patch, $fullpath = false
933  ) {
934  if ( !$this->doTable( $table ) ) {
935  return true;
936  }
937 
938  // First requirement: the table must exist
939  if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
940  $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
941 
942  return true;
943  }
944 
945  // Second requirement: the new index must be missing
946  if ( $this->db->indexExists( $table, $newIndex, __METHOD__ ) ) {
947  $this->output( "...index $newIndex already set on $table table.\n" );
948  if ( !$skipBothIndexExistWarning &&
949  $this->db->indexExists( $table, $oldIndex, __METHOD__ )
950  ) {
951  $this->output( "...WARNING: $oldIndex still exists, despite it has " .
952  "been renamed into $newIndex (which also exists).\n" .
953  " $oldIndex should be manually removed if not needed anymore.\n" );
954  }
955 
956  return true;
957  }
958 
959  // Third requirement: the old index must exist
960  if ( !$this->db->indexExists( $table, $oldIndex, __METHOD__ ) ) {
961  $this->output( "...skipping: index $oldIndex doesn't exist.\n" );
962 
963  return true;
964  }
965 
966  // Requirements have been satisfied, patch can be applied
967  return $this->applyPatch(
968  $patch,
969  $fullpath,
970  "Renaming index $oldIndex into $newIndex to table $table"
971  );
972  }
973 
988  protected function dropTable( $table, $patch = false, $fullpath = false ) {
989  if ( !$this->doTable( $table ) ) {
990  return true;
991  }
992 
993  if ( $this->db->tableExists( $table, __METHOD__ ) ) {
994  $msg = "Dropping table $table";
995 
996  if ( $patch === false ) {
997  $this->output( "$msg ..." );
998  $this->db->dropTable( $table, __METHOD__ );
999  $this->output( "done.\n" );
1000  } else {
1001  return $this->applyPatch( $patch, $fullpath, $msg );
1002  }
1003  } else {
1004  $this->output( "...$table doesn't exist.\n" );
1005  }
1006 
1007  return true;
1008  }
1009 
1024  protected function modifyField( $table, $field, $patch, $fullpath = false ) {
1025  if ( !$this->doTable( $table ) ) {
1026  return true;
1027  }
1028 
1029  $updateKey = "$table-$field-$patch";
1030  if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
1031  $this->output( "...$table table does not exist, skipping modify field patch.\n" );
1032  } elseif ( !$this->db->fieldExists( $table, $field, __METHOD__ ) ) {
1033  $this->output( "...$field field does not exist in $table table, " .
1034  "skipping modify field patch.\n" );
1035  } elseif ( $this->updateRowExists( $updateKey ) ) {
1036  $this->output( "...$field in table $table already modified by patch $patch.\n" );
1037  } else {
1038  $apply = $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
1039  if ( $apply ) {
1040  $this->insertUpdateRow( $updateKey );
1041  }
1042  return $apply;
1043  }
1044  return true;
1045  }
1046 
1061  protected function modifyTable( $table, $patch, $fullpath = false ) {
1062  if ( !$this->doTable( $table ) ) {
1063  return true;
1064  }
1065 
1066  $updateKey = "$table-$patch";
1067  if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
1068  $this->output( "...$table table does not exist, skipping modify table patch.\n" );
1069  } elseif ( $this->updateRowExists( $updateKey ) ) {
1070  $this->output( "...table $table already modified by patch $patch.\n" );
1071  } else {
1072  $apply = $this->applyPatch( $patch, $fullpath, "Modifying table $table" );
1073  if ( $apply ) {
1074  $this->insertUpdateRow( $updateKey );
1075  }
1076  return $apply;
1077  }
1078  return true;
1079  }
1080 
1101  protected function runMaintenance( $class, $script ) {
1102  $this->output( "Running $script...\n" );
1103  $task = $this->maintenance->runChild( $class );
1104  $ok = $task->execute();
1105  if ( !$ok ) {
1106  throw new RuntimeException( "Execution of $script did not complete successfully." );
1107  }
1108  $this->output( "done.\n" );
1109  }
1110 
1116  public function setFileAccess() {
1117  $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
1118  $zonePath = $repo->getZonePath( 'temp' );
1119  if ( $repo->getBackend()->directoryExists( [ 'dir' => $zonePath ] ) ) {
1120  // If the directory was never made, then it will have the right ACLs when it is made
1121  $status = $repo->getBackend()->secure( [
1122  'dir' => $zonePath,
1123  'noAccess' => true,
1124  'noListing' => true
1125  ] );
1126  if ( $status->isOK() ) {
1127  $this->output( "Set the local repo temp zone container to be private.\n" );
1128  } else {
1129  $this->output( "Failed to set the local repo temp zone container to be private.\n" );
1130  }
1131  }
1132  }
1133 
1137  public function purgeCache() {
1138  global $wgLocalisationCacheConf;
1139  // We can't guarantee that the user will be able to use TRUNCATE,
1140  // but we know that DELETE is available to us
1141  $this->output( "Purging caches..." );
1142 
1143  // ObjectCache
1144  $this->db->delete( 'objectcache', '*', __METHOD__ );
1145 
1146  // LocalisationCache
1147  if ( $wgLocalisationCacheConf['manualRecache'] ) {
1148  $this->rebuildLocalisationCache();
1149  }
1150 
1151  // ResourceLoader: Message cache
1152  $services = MediaWikiServices::getInstance();
1153  $blobStore = new MessageBlobStore(
1154  $services->getResourceLoader(),
1155  null,
1156  $services->getMainWANObjectCache()
1157  );
1158  $blobStore->clear();
1159 
1160  // ResourceLoader: File-dependency cache
1161  $this->db->delete( 'module_deps', '*', __METHOD__ );
1162  $this->output( "done.\n" );
1163  }
1164 
1168  protected function checkStats() {
1169  $this->output( "...site_stats is populated..." );
1170  $row = $this->db->selectRow( 'site_stats', '*', [ 'ss_row_id' => 1 ], __METHOD__ );
1171  if ( $row === false ) {
1172  $this->output( "data is missing! rebuilding...\n" );
1173  } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
1174  $this->output( "missing ss_total_pages, rebuilding...\n" );
1175  } else {
1176  $this->output( "done.\n" );
1177 
1178  return;
1179  }
1180  SiteStatsInit::doAllAndCommit( $this->db );
1181  }
1182 
1183  # Common updater functions
1184 
1188  protected function doActiveUsersInit() {
1189  $activeUsers = $this->db->selectField( 'site_stats', 'ss_active_users', '', __METHOD__ );
1190  if ( $activeUsers == -1 ) {
1191  $activeUsers = $this->db->selectField( 'recentchanges',
1192  'COUNT( DISTINCT rc_user_text )',
1193  [ 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ], __METHOD__
1194  );
1195  $this->db->update( 'site_stats',
1196  [ 'ss_active_users' => intval( $activeUsers ) ],
1197  [ 'ss_row_id' => 1 ], __METHOD__, [ 'LIMIT' => 1 ]
1198  );
1199  }
1200  $this->output( "...ss_active_users user count set...\n" );
1201  }
1202 
1206  protected function doLogUsertextPopulation() {
1207  if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
1208  $this->output(
1209  "Populating log_user_text field, printing progress markers. For large\n" .
1210  "databases, you may want to hit Ctrl-C and do this manually with\n" .
1211  "maintenance/populateLogUsertext.php.\n"
1212  );
1213 
1214  $task = $this->maintenance->runChild( PopulateLogUsertext::class );
1215  $task->execute();
1216  $this->output( "done.\n" );
1217  }
1218  }
1219 
1223  protected function doLogSearchPopulation() {
1224  if ( !$this->updateRowExists( 'populate log_search' ) ) {
1225  $this->output(
1226  "Populating log_search table, printing progress markers. For large\n" .
1227  "databases, you may want to hit Ctrl-C and do this manually with\n" .
1228  "maintenance/populateLogSearch.php.\n" );
1229 
1230  $task = $this->maintenance->runChild( PopulateLogSearch::class );
1231  $task->execute();
1232  $this->output( "done.\n" );
1233  }
1234  }
1235 
1239  protected function doCollationUpdate() {
1240  global $wgCategoryCollation;
1241  if ( $this->db->fieldExists( 'categorylinks', 'cl_collation', __METHOD__ ) ) {
1242  if ( $this->db->selectField(
1243  'categorylinks',
1244  'COUNT(*)',
1245  'cl_collation != ' . $this->db->addQuotes( $wgCategoryCollation ),
1246  __METHOD__
1247  ) == 0
1248  ) {
1249  $this->output( "...collations up-to-date.\n" );
1250 
1251  return;
1252  }
1253 
1254  $this->output( "Updating category collations..." );
1255  $task = $this->maintenance->runChild( UpdateCollation::class );
1256  $task->execute();
1257  $this->output( "...done.\n" );
1258  }
1259  }
1260 
1264  protected function doMigrateUserOptions() {
1265  if ( $this->db->tableExists( 'user_properties' ) ) {
1266  $cl = $this->maintenance->runChild( ConvertUserOptions::class, 'convertUserOptions.php' );
1267  $cl->execute();
1268  $this->output( "done.\n" );
1269  }
1270  }
1271 
1275  protected function rebuildLocalisationCache() {
1279  $cl = $this->maintenance->runChild(
1280  RebuildLocalisationCache::class, 'rebuildLocalisationCache.php'
1281  );
1282  '@phan-var RebuildLocalisationCache $cl';
1283  $this->output( "Rebuilding localisation cache...\n" );
1284  $cl->setForce();
1285  $cl->execute();
1286  $this->output( "done.\n" );
1287  }
1288 
1293  protected function migrateComments() {
1294  if ( !$this->updateRowExists( 'MigrateComments' ) ) {
1295  $this->output(
1296  "Migrating comments to the 'comments' table, printing progress markers. For large\n" .
1297  "databases, you may want to hit Ctrl-C and do this manually with\n" .
1298  "maintenance/migrateComments.php.\n"
1299  );
1300  $task = $this->maintenance->runChild( MigrateComments::class, 'migrateComments.php' );
1301  $ok = $task->execute();
1302  $this->output( $ok ? "done.\n" : "errors were encountered.\n" );
1303  }
1304  }
1305 
1310  protected function migrateImageCommentTemp() {
1311  if ( $this->tableExists( 'image_comment_temp' ) ) {
1312  $this->output( "Merging image_comment_temp into the image table\n" );
1313  $task = $this->maintenance->runChild(
1314  MigrateImageCommentTemp::class, 'migrateImageCommentTemp.php'
1315  );
1316  // @phan-suppress-next-line PhanUndeclaredMethod
1317  $task->setForce();
1318  $ok = $task->execute();
1319  $this->output( $ok ? "done.\n" : "errors were encountered.\n" );
1320  if ( $ok ) {
1321  $this->dropTable( 'image_comment_temp' );
1322  }
1323  }
1324  }
1325 
1330  protected function migrateActors() {
1331  if ( !$this->updateRowExists( 'MigrateActors' ) ) {
1332  $this->output(
1333  "Migrating actors to the 'actor' table, printing progress markers. For large\n" .
1334  "databases, you may want to hit Ctrl-C and do this manually with\n" .
1335  "maintenance/migrateActors.php.\n"
1336  );
1337  $task = $this->maintenance->runChild( 'MigrateActors', 'migrateActors.php' );
1338  $ok = $task->execute();
1339  $this->output( $ok ? "done.\n" : "errors were encountered.\n" );
1340  }
1341  }
1342 
1347  protected function migrateArchiveText() {
1348  if ( $this->db->fieldExists( 'archive', 'ar_text', __METHOD__ ) ) {
1349  $this->output( "Migrating archive ar_text to modern storage.\n" );
1350  $task = $this->maintenance->runChild( MigrateArchiveText::class, 'migrateArchiveText.php' );
1351  // @phan-suppress-next-line PhanUndeclaredMethod
1352  $task->setForce();
1353  if ( $task->execute() ) {
1354  $this->applyPatch( 'patch-drop-ar_text.sql', false,
1355  'Dropping ar_text and ar_flags columns' );
1356  }
1357  }
1358  }
1359 
1364  protected function populateArchiveRevId() {
1365  $info = $this->db->fieldInfo( 'archive', 'ar_rev_id' );
1366  if ( !$info ) {
1367  throw new MWException( 'Missing ar_rev_id field of archive table. Should not happen.' );
1368  }
1369  if ( $info->isNullable() ) {
1370  $this->output( "Populating ar_rev_id.\n" );
1371  $task = $this->maintenance->runChild( 'PopulateArchiveRevId', 'populateArchiveRevId.php' );
1372  if ( $task->execute() ) {
1373  $this->applyPatch( 'patch-ar_rev_id-not-null.sql', false,
1374  'Making ar_rev_id not nullable' );
1375  }
1376  }
1377  }
1378 
1383  protected function populateExternallinksIndex60() {
1384  if ( !$this->updateRowExists( 'populate externallinks.el_index_60' ) ) {
1385  $this->output(
1386  "Populating el_index_60 field, printing progress markers. For large\n" .
1387  "databases, you may want to hit Ctrl-C and do this manually with\n" .
1388  "maintenance/populateExternallinksIndex60.php.\n"
1389  );
1390  $task = $this->maintenance->runChild( 'PopulateExternallinksIndex60',
1391  'populateExternallinksIndex60.php' );
1392  $task->execute();
1393  $this->output( "done.\n" );
1394  }
1395  }
1396 
1401  protected function populateContentTables() {
1402  if ( !$this->updateRowExists( 'PopulateContentTables' ) ) {
1403  $this->output(
1404  "Migrating revision data to the MCR 'slot' and 'content' tables, printing progress markers.\n" .
1405  "For large databases, you may want to hit Ctrl-C and do this manually with\n" .
1406  "maintenance/populateContentTables.php.\n"
1407  );
1408  $task = $this->maintenance->runChild(
1409  PopulateContentTables::class, 'populateContentTables.php'
1410  );
1411  $ok = $task->execute();
1412  $this->output( $ok ? "done.\n" : "errors were encountered.\n" );
1413  if ( $ok ) {
1414  $this->insertUpdateRow( 'PopulateContentTables' );
1415  }
1416  }
1417  }
1418 
1422  protected function ifNoActorTable( $func, ...$params ) {
1423  wfDeprecated( __METHOD__, '1.35' );
1424  return $this->ifTableNotExists( 'actor', $func, ...$params );
1425  }
1426 
1440  protected function ifTableNotExists( $table, $func, ...$params ) {
1441  // Handle $passSelf from runUpdates().
1442  $passSelf = false;
1443  if ( $table === $this ) {
1444  $passSelf = true;
1445  $table = $func;
1446  $func = array_shift( $params );
1447  }
1448 
1449  if ( $this->db->tableExists( $table ) ) {
1450  return null;
1451  }
1452 
1453  if ( !is_array( $func ) && method_exists( $this, $func ) ) {
1454  $func = [ $this, $func ];
1455  } elseif ( $passSelf ) {
1456  array_unshift( $params, $this );
1457  }
1458 
1459  // @phan-suppress-next-line PhanUndeclaredInvokeInCallable Phan is confused
1460  return $func( ...$params );
1461  }
1462 
1477  protected function ifFieldExists( $table, $field, $func, ...$params ) {
1478  // Handle $passSelf from runUpdates().
1479  $passSelf = false;
1480  if ( $table === $this ) {
1481  $passSelf = true;
1482  $table = $field;
1483  $field = $func;
1484  $func = array_shift( $params );
1485  }
1486 
1487  if ( !$this->db->tableExists( $table ) || !$this->db->fieldExists( $table, $field ) ) {
1488  return null;
1489  }
1490 
1491  if ( !is_array( $func ) && method_exists( $this, $func ) ) {
1492  $func = [ $this, $func ];
1493  } elseif ( $passSelf ) {
1494  array_unshift( $params, $this );
1495  }
1496 
1497  // @phan-suppress-next-line PhanUndeclaredInvokeInCallable Phan is confused
1498  return $func( ...$params );
1499  }
1500 }
DatabaseUpdater\output
output( $str)
Output some text.
Definition: DatabaseUpdater.php:222
DatabaseUpdater\dropIndex
dropIndex( $table, $index, $patch, $fullpath=false)
Drop an index from an existing table.
Definition: DatabaseUpdater.php:902
DatabaseUpdater\modifyExtensionTable
modifyExtensionTable( $tableName, $sqlPath)
Modify an existing extension table.
Definition: DatabaseUpdater.php:383
DatabaseUpdater\dropTable
dropTable( $table, $patch=false, $fullpath=false)
If the specified table exists, drop it, or execute the patch if one is provided.
Definition: DatabaseUpdater.php:988
DatabaseUpdater\copyFile
copyFile( $filename)
Append an SQL fragment to the open file handle.
Definition: DatabaseUpdater.php:663
DatabaseUpdater\$updatesSkipped
array $updatesSkipped
Array of updates that were skipped.
Definition: DatabaseUpdater.php:51
DatabaseUpdater\newForDB
static newForDB(IMaintainableDatabase $db, $shared=false, Maintenance $maintenance=null)
Definition: DatabaseUpdater.php:192
DatabaseUpdater\applyPatch
applyPatch( $path, $isFullPath=false, $msg=null)
Applies a SQL patch.
Definition: DatabaseUpdater.php:705
DatabaseUpdater\doCollationUpdate
doCollationUpdate()
Update CategoryLinks collation.
Definition: DatabaseUpdater.php:1239
DatabaseUpdater\dropExtensionTable
dropExtensionTable( $tableName, $sqlPath=false)
Drop an extension table.
Definition: DatabaseUpdater.php:329
SiteStatsInit\doAllAndCommit
static doAllAndCommit( $database, array $options=[])
Do all updates and commit them.
Definition: SiteStatsInit.php:134
$wgSharedTables
$wgSharedTables
Definition: DefaultSettings.php:2134
DatabaseUpdater
Class for handling database updates.
Definition: DatabaseUpdater.php:36
DatabaseUpdater\populateExternallinksIndex60
populateExternallinksIndex60()
Populates the externallinks.el_index_60 field.
Definition: DatabaseUpdater.php:1383
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:144
DatabaseUpdater\addPostDatabaseUpdateMaintenance
addPostDatabaseUpdateMaintenance( $class)
Add a maintenance script to be run after the database updates are complete.
Definition: DatabaseUpdater.php:406
DatabaseUpdater\checkStats
checkStats()
Check the site_stats table is not properly populated.
Definition: DatabaseUpdater.php:1168
true
return true
Definition: router.php:90
$wgSharedDB
$wgSharedDB
Shared database for multiple wikis.
Definition: DefaultSettings.php:2124
DatabaseUpdater\getCoreUpdateList
getCoreUpdateList()
Get an array of updates to perform on the database.
DatabaseUpdater\migrateImageCommentTemp
migrateImageCommentTemp()
Merge image_comment_temp into the image table.
Definition: DatabaseUpdater.php:1310
DatabaseUpdater\doMigrateUserOptions
doMigrateUserOptions()
Migrates user options from the user table blob to user_properties.
Definition: DatabaseUpdater.php:1264
DatabaseUpdater\populateContentTables
populateContentTables()
Populates the MCR content tables.
Definition: DatabaseUpdater.php:1401
DatabaseUpdater\dropField
dropField( $table, $field, $patch, $fullpath=false)
Drop a field from an existing table.
Definition: DatabaseUpdater.php:876
DatabaseUpdater\addField
addField( $table, $field, $patch, $fullpath=false)
Add a new field to an existing table.
Definition: DatabaseUpdater.php:787
DatabaseUpdater\doTable
doTable( $name)
Returns whether updates should be executed on the database table $name.
Definition: DatabaseUpdater.php:585
DatabaseUpdater\getPostDatabaseUpdateMaintenance
getPostDatabaseUpdateMaintenance()
Definition: DatabaseUpdater.php:424
DatabaseUpdater\appendLine
appendLine( $line)
Append a line to the open filehandle.
Definition: DatabaseUpdater.php:685
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: Maintenance.php:51
DatabaseUpdater\patchPath
patchPath(IDatabase $db, $patch)
Get the full path of a patch file.
Definition: DatabaseUpdater.php:739
DatabaseUpdater\getSchemaVars
getSchemaVars()
Get appropriate schema variables in the current database connection.
Definition: DatabaseUpdater.php:457
DatabaseUpdater\REPLICATION_WAIT_TIMEOUT
const REPLICATION_WAIT_TIMEOUT
Definition: DatabaseUpdater.php:37
DatabaseUpdater\addExtensionIndex
addExtensionIndex( $tableName, $indexName, $sqlPath)
Add an index to an existing extension table.
Definition: DatabaseUpdater.php:274
DatabaseUpdater\migrateComments
migrateComments()
Migrate comments to the new 'comment' table.
Definition: DatabaseUpdater.php:1293
DatabaseUpdater\__construct
__construct(IMaintainableDatabase &$db, $shared, Maintenance $maintenance=null)
Definition: DatabaseUpdater.php:112
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
DatabaseUpdater\doActiveUsersInit
doActiveUsersInit()
Sets the number of active users in the site_stats table.
Definition: DatabaseUpdater.php:1188
DatabaseUpdater\dropExtensionIndex
dropExtensionIndex( $tableName, $indexName, $sqlPath)
Drop an index from an extension table Intended for use in LoadExtensionSchemaUpdates hook handlers.
Definition: DatabaseUpdater.php:316
DatabaseUpdater\$updates
array $updates
Array of updates to perform on the database.
Definition: DatabaseUpdater.php:44
ExtensionRegistry\getInstance
static getInstance()
Definition: ExtensionRegistry.php:136
DatabaseUpdater\addExtensionUpdate
addExtensionUpdate(array $update)
Add a new update coming from an extension.
Definition: DatabaseUpdater.php:246
DatabaseUpdater\setFileAccess
setFileAccess()
Set any .htaccess files or equivilent for storage repos.
Definition: DatabaseUpdater.php:1116
DatabaseUpdater\loadExtensionSchemaUpdates
loadExtensionSchemaUpdates()
Cause extensions to register any updates they need to perform.
Definition: DatabaseUpdater.php:132
$wgHooks
$wgHooks
Global list of hooks.
Definition: DefaultSettings.php:7856
MWException
MediaWiki exception.
Definition: MWException.php:26
DatabaseUpdater\renameIndex
renameIndex( $table, $oldIndex, $newIndex, $skipBothIndexExistWarning, $patch, $fullpath=false)
Rename an index from an existing table.
Definition: DatabaseUpdater.php:931
DatabaseUpdater\getExtensionUpdates
getExtensionUpdates()
Get the list of extension-defined updates.
Definition: DatabaseUpdater.php:415
DatabaseUpdater\migrateArchiveText
migrateArchiveText()
Migrate ar_text to modern storage.
Definition: DatabaseUpdater.php:1347
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1030
DatabaseUpdater\$maintenance
Maintenance $maintenance
Definition: DatabaseUpdater.php:69
DatabaseUpdater\modifyTable
modifyTable( $table, $patch, $fullpath=false)
Modify an existing table, similar to modifyField.
Definition: DatabaseUpdater.php:1061
DatabaseUpdater\$db
IMaintainableDatabase $db
Handle to the database subclass.
Definition: DatabaseUpdater.php:64
$wgCommandLineMode
global $wgCommandLineMode
Definition: DevelopmentSettings.php:29
DatabaseUpdater\modifyExtensionField
modifyExtensionField( $tableName, $fieldName, $sqlPath)
Modify an existing field in an extension table.
Definition: DatabaseUpdater.php:370
DatabaseUpdater\rebuildLocalisationCache
rebuildLocalisationCache()
Rebuilds the localisation cache.
Definition: DatabaseUpdater.php:1275
$queue
$queue
Definition: mergeMessageFileList.php:157
$args
if( $line===false) $args
Definition: mcc.php:124
DatabaseUpdater\ifNoActorTable
ifNoActorTable( $func,... $params)
Definition: DatabaseUpdater.php:1422
Installer\getExistingLocalSettings
static getExistingLocalSettings()
Determine if LocalSettings.php exists.
Definition: Installer.php:599
DatabaseUpdater\getDB
getDB()
Get a database connection to run updates.
Definition: DatabaseUpdater.php:212
DatabaseUpdater\ifTableNotExists
ifTableNotExists( $table, $func,... $params)
Only run a function if a table does not exist.
Definition: DatabaseUpdater.php:1440
$wgLocalisationCacheConf
$wgLocalisationCacheConf
Localisation cache configuration.
Definition: DefaultSettings.php:2724
DatabaseUpdater\runUpdates
runUpdates(array $updates, $passSelf)
Helper function for doUpdates()
Definition: DatabaseUpdater.php:496
DatabaseUpdater\doUpdates
doUpdates(array $what=[ 'core', 'extensions', 'stats'])
Do all the updates.
Definition: DatabaseUpdater.php:466
FakeMaintenance
Fake maintenance wrapper, mostly used for the web installer/updater.
Definition: FakeMaintenance.php:25
DatabaseUpdater\updateRowExists
updateRowExists( $key)
Helper function: check if the given key is present in the updatelog table.
Definition: DatabaseUpdater.php:529
DatabaseUpdater\doLogSearchPopulation
doLogSearchPopulation()
Migrate log params to new table and index for searching.
Definition: DatabaseUpdater.php:1223
DBO_DDLMODE
const DBO_DDLMODE
Definition: defines.php:16
DatabaseUpdater\populateArchiveRevId
populateArchiveRevId()
Populate ar_rev_id, then make it not nullable.
Definition: DatabaseUpdater.php:1364
DatabaseUpdater\canUseNewUpdatelog
canUseNewUpdatelog()
Updatelog was changed in 1.17 to have a ul_value column so we can record more information about what ...
Definition: DatabaseUpdater.php:572
DatabaseUpdater\ifFieldExists
ifFieldExists( $table, $field, $func,... $params)
Only run a function if the named field exists.
Definition: DatabaseUpdater.php:1477
DatabaseUpdater\runMaintenance
runMaintenance( $class, $script)
Run a maintenance script.
Definition: DatabaseUpdater.php:1101
$line
$line
Definition: mcc.php:119
DatabaseUpdater\$fileHandle
resource $fileHandle
File handle for SQL output.
Definition: DatabaseUpdater.php:98
DatabaseUpdater\getOldGlobalUpdates
getOldGlobalUpdates()
Before 1.17, we used to handle updates via stuff like $wgExtNewTables/Fields/Indexes.
Definition: DatabaseUpdater.php:610
$wgAutoloadClasses
$wgAutoloadClasses
Array mapping class names to filenames, for autoloading.
Definition: DefaultSettings.php:7751
DatabaseUpdater\doLogUsertextPopulation
doLogUsertextPopulation()
Populates the log_user_text field in the logging table.
Definition: DatabaseUpdater.php:1206
DatabaseUpdater\tableExists
tableExists( $tableName)
Definition: DatabaseUpdater.php:393
DatabaseUpdater\addExtensionField
addExtensionField( $tableName, $columnName, $sqlPath)
Add a field to an existing extension table.
Definition: DatabaseUpdater.php:288
DatabaseUpdater\modifyField
modifyField( $table, $field, $patch, $fullpath=false)
Modify an existing field.
Definition: DatabaseUpdater.php:1024
DatabaseUpdater\writeSchemaUpdateFile
writeSchemaUpdateFile(array $schemaUpdate=[])
Definition: DatabaseUpdater.php:434
DatabaseUpdater\addIndexIfNoneExist
addIndexIfNoneExist( $table, $indexes, $patch, $fullpath=false)
Add a new index to an existing table if none of the given indexes exist.
Definition: DatabaseUpdater.php:841
DatabaseUpdater\loadExtensions
loadExtensions()
Loads LocalSettings.php, if needed, and initialises everything needed for LoadExtensionSchemaUpdates ...
Definition: DatabaseUpdater.php:160
$path
$path
Definition: NoLocalSettings.php:25
DatabaseUpdater\renameExtensionIndex
renameExtensionIndex( $tableName, $oldIndexName, $newIndexName, $sqlPath, $skipBothIndexExistWarning=false)
Rename an index on an extension table Intended for use in LoadExtensionSchemaUpdates hook handlers.
Definition: DatabaseUpdater.php:346
DatabaseUpdater\addTable
addTable( $name, $patch, $fullpath=false)
Add a new table to the database.
Definition: DatabaseUpdater.php:761
DatabaseUpdater\$shared
$shared
Definition: DatabaseUpdater.php:71
MessageBlobStore
This class generates message blobs for use by ResourceLoader.
Definition: MessageBlobStore.php:38
Wikimedia\Rdbms\IDatabase\getType
getType()
Get the type of the DBMS (e.g.
DatabaseUpdater\migrateActors
migrateActors()
Migrate actors to the new 'actor' table.
Definition: DatabaseUpdater.php:1330
Maintenance\setDB
setDB(IMaintainableDatabase $db)
Sets database object to be returned by getDB().
Definition: Maintenance.php:1358
DatabaseUpdater\dropExtensionField
dropExtensionField( $tableName, $columnName, $sqlPath)
Drop a field from an extension table.
Definition: DatabaseUpdater.php:302
DatabaseUpdater\purgeCache
purgeCache()
Purge various database caches.
Definition: DatabaseUpdater.php:1137
$wgCategoryCollation
$wgCategoryCollation
Specify how category names should be sorted, when listed on a category page.
Definition: DefaultSettings.php:8035
DatabaseUpdater\$skipSchema
bool $skipSchema
Flag specifying whether or not to skip schema (e.g.
Definition: DatabaseUpdater.php:105
DatabaseUpdater\addExtensionTable
addExtensionTable( $tableName, $sqlPath)
Convenience wrapper for addExtensionUpdate() when adding a new table (which is the most common usage ...
Definition: DatabaseUpdater.php:260
Installer\getDBTypes
static getDBTypes()
Get a list of known DB types.
Definition: Installer.php:480
DatabaseUpdater\initOldGlobals
initOldGlobals()
Initialize all of the old globals.
Definition: DatabaseUpdater.php:142
DatabaseUpdater\addIndex
addIndex( $table, $index, $patch, $fullpath=false)
Add a new index to an existing table.
Definition: DatabaseUpdater.php:815
DatabaseUpdater\$extensionUpdates
array $extensionUpdates
List of extension-provided database updates.
Definition: DatabaseUpdater.php:57
DatabaseUpdater\insertUpdateRow
insertUpdateRow( $key, $val=null)
Helper function: Add a key to the updatelog table.
Definition: DatabaseUpdater.php:554
$IP
$IP
Definition: WebStart.php:49
Wikimedia\Rdbms\IDatabase\setFlag
setFlag( $flag, $remember=self::REMEMBER_NOTHING)
Set a flag for this connection.
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:133
DatabaseUpdater\$postDatabaseUpdateMaintenance
string[] $postDatabaseUpdateMaintenance
Scripts to run after database update Should be a subclass of LoggedUpdateMaintenance.
Definition: DatabaseUpdater.php:77
Wikimedia\Rdbms\IMaintainableDatabase
Advanced database interface for IDatabase handles that include maintenance methods.
Definition: IMaintainableDatabase.php:38
$type
$type
Definition: testCompression.php:52