MediaWiki  master
DatabaseUpdater.php
Go to the documentation of this file.
1 <?php
26 
27 require_once __DIR__ . '/../../maintenance/Maintenance.php';
28 
37 abstract class DatabaseUpdater {
38  public const REPLICATION_WAIT_TIMEOUT = 300;
39 
45  protected $updates = [];
46 
52  protected $updatesSkipped = [];
53 
58  protected $extensionUpdates = [];
59 
65  protected $db;
66 
70  protected $maintenance;
71 
72  protected $shared = false;
73 
79  DeleteDefaultMessages::class,
80  PopulateRevisionLength::class,
81  PopulateRevisionSha1::class,
82  PopulateImageSha1::class,
83  FixExtLinksProtocolRelative::class,
84  PopulateFilearchiveSha1::class,
85  PopulateBacklinkNamespace::class,
86  FixDefaultJsonContentPages::class,
87  CleanupEmptyCategories::class,
88  AddRFCandPMIDInterwiki::class,
89  PopulatePPSortKey::class,
90  PopulateIpChanges::class,
91  RefreshExternallinksIndex::class,
92  ];
93 
99  protected $fileHandle = null;
100 
106  protected $skipSchema = false;
107 
114  protected function __construct(
116  $shared,
118  ) {
119  $this->db = $db;
120  $this->db->setFlag( DBO_DDLMODE ); // For Oracle's handling of schema files
121  $this->shared = $shared;
122  if ( $maintenance ) {
123  $this->maintenance = $maintenance;
124  $this->fileHandle = $maintenance->fileHandle;
125  } else {
126  $this->maintenance = new FakeMaintenance;
127  }
128  $this->maintenance->setDB( $db );
129  }
130 
134  private function loadExtensionSchemaUpdates() {
135  $this->initOldGlobals();
136  $this->loadExtensions();
137  Hooks::runner()->onLoadExtensionSchemaUpdates( $this );
138  }
139 
144  private function initOldGlobals() {
145  global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
146  $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
147 
148  # For extensions only, should be populated via hooks
149  # $wgDBtype should be checked to specify the proper file
150  $wgExtNewTables = []; // table, dir
151  $wgExtNewFields = []; // table, column, dir
152  $wgExtPGNewFields = []; // table, column, column attributes; for PostgreSQL
153  $wgExtPGAlteredFields = []; // table, column, new type, conversion method; for PostgreSQL
154  $wgExtNewIndexes = []; // table, index, dir
155  $wgExtModifiedFields = []; // table, index, dir
156  }
157 
162  private function loadExtensions() {
163  if ( !defined( 'MEDIAWIKI_INSTALL' ) || defined( 'MW_EXTENSIONS_LOADED' ) ) {
164  return; // already loaded
165  }
167 
168  $registry = ExtensionRegistry::getInstance();
169  $queue = $registry->getQueue();
170  // Don't accidentally load extensions in the future
171  $registry->clearQueue();
172 
173  // This will automatically add "AutoloadClasses" to $wgAutoloadClasses
174  $data = $registry->readFromQueue( $queue );
175  $hooks = $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ?? [];
176  if ( $vars && isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
177  $hooks = array_merge_recursive( $hooks, $vars['wgHooks']['LoadExtensionSchemaUpdates'] );
178  }
180  $wgHooks['LoadExtensionSchemaUpdates'] = $hooks;
181  if ( $vars && isset( $vars['wgAutoloadClasses'] ) ) {
182  $wgAutoloadClasses += $vars['wgAutoloadClasses'];
183  }
184  }
185 
194  public static function newForDB(
196  $shared = false,
198  ) {
199  $type = $db->getType();
200  if ( in_array( $type, Installer::getDBTypes() ) ) {
201  $class = ucfirst( $type ) . 'Updater';
202 
203  return new $class( $db, $shared, $maintenance );
204  } else {
205  throw new MWException( __METHOD__ . ' called for unsupported $wgDBtype' );
206  }
207  }
208 
214  public function getDB() {
215  return $this->db;
216  }
217 
224  public function output( $str ) {
225  if ( $this->maintenance->isQuiet() ) {
226  return;
227  }
228  global $wgCommandLineMode;
229  if ( !$wgCommandLineMode ) {
230  $str = htmlspecialchars( $str );
231  }
232  echo $str;
233  flush();
234  }
235 
248  public function addExtensionUpdate( array $update ) {
249  $this->extensionUpdates[] = $update;
250  }
251 
262  public function addExtensionTable( $tableName, $sqlPath ) {
263  $this->extensionUpdates[] = [ 'addTable', $tableName, $sqlPath, true ];
264  }
265 
276  public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
277  $this->extensionUpdates[] = [ 'addIndex', $tableName, $indexName, $sqlPath, true ];
278  }
279 
290  public function addExtensionField( $tableName, $columnName, $sqlPath ) {
291  $this->extensionUpdates[] = [ 'addField', $tableName, $columnName, $sqlPath, true ];
292  }
293 
304  public function dropExtensionField( $tableName, $columnName, $sqlPath ) {
305  $this->extensionUpdates[] = [ 'dropField', $tableName, $columnName, $sqlPath, true ];
306  }
307 
318  public function dropExtensionIndex( $tableName, $indexName, $sqlPath ) {
319  $this->extensionUpdates[] = [ 'dropIndex', $tableName, $indexName, $sqlPath, true ];
320  }
321 
331  public function dropExtensionTable( $tableName, $sqlPath = false ) {
332  $this->extensionUpdates[] = [ 'dropTable', $tableName, $sqlPath, true ];
333  }
334 
348  public function renameExtensionIndex( $tableName, $oldIndexName, $newIndexName,
349  $sqlPath, $skipBothIndexExistWarning = false
350  ) {
351  $this->extensionUpdates[] = [
352  'renameIndex',
353  $tableName,
354  $oldIndexName,
355  $newIndexName,
356  $skipBothIndexExistWarning,
357  $sqlPath,
358  true
359  ];
360  }
361 
372  public function modifyExtensionField( $tableName, $fieldName, $sqlPath ) {
373  $this->extensionUpdates[] = [ 'modifyField', $tableName, $fieldName, $sqlPath, true ];
374  }
375 
385  public function modifyExtensionTable( $tableName, $sqlPath ) {
386  $this->extensionUpdates[] = [ 'modifyTable', $tableName, $sqlPath, true ];
387  }
388 
395  public function tableExists( $tableName ) {
396  return ( $this->db->tableExists( $tableName, __METHOD__ ) );
397  }
398 
408  public function addPostDatabaseUpdateMaintenance( $class ) {
409  $this->postDatabaseUpdateMaintenance[] = $class;
410  }
411 
417  protected function getExtensionUpdates() {
419  }
420 
428  }
429 
436  private function writeSchemaUpdateFile( array $schemaUpdate = [] ) {
438  $this->updatesSkipped = [];
439 
440  foreach ( $updates as $funcList ) {
441  list( $func, $args, $origParams ) = $funcList;
442  // @phan-suppress-next-line PhanUndeclaredInvokeInCallable
443  $func( ...$args );
444  flush();
445  $this->updatesSkipped[] = $origParams;
446  }
447  }
448 
460  public function getSchemaVars() {
461  return []; // DB-type specific
462  }
463 
469  public function doUpdates( array $what = [ 'core', 'extensions', 'stats' ] ) {
470  $this->db->setSchemaVars( $this->getSchemaVars() );
471 
472  $what = array_flip( $what );
473  $this->skipSchema = isset( $what['noschema'] ) || $this->fileHandle !== null;
474  if ( isset( $what['core'] ) ) {
475  $this->runUpdates( $this->getCoreUpdateList(), false );
476  }
477  if ( isset( $what['extensions'] ) ) {
479  $this->runUpdates( $this->getOldGlobalUpdates(), false );
480  $this->runUpdates( $this->getExtensionUpdates(), true );
481  }
482 
483  if ( isset( $what['stats'] ) ) {
484  $this->checkStats();
485  }
486 
487  if ( $this->fileHandle ) {
488  $this->skipSchema = false;
489  $this->writeSchemaUpdateFile();
490  }
491  }
492 
499  private function runUpdates( array $updates, $passSelf ) {
500  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
501 
502  $updatesDone = [];
503  $updatesSkipped = [];
504  foreach ( $updates as $params ) {
505  $origParams = $params;
506  $func = array_shift( $params );
507  if ( !is_array( $func ) && method_exists( $this, $func ) ) {
508  $func = [ $this, $func ];
509  } elseif ( $passSelf ) {
510  array_unshift( $params, $this );
511  }
512  $ret = $func( ...$params );
513  flush();
514  if ( $ret !== false ) {
515  $updatesDone[] = $origParams;
516  $lbFactory->waitForReplication( [ 'timeout' => self::REPLICATION_WAIT_TIMEOUT ] );
517  } else {
518  $updatesSkipped[] = [ $func, $params, $origParams ];
519  }
520  }
521  $this->updatesSkipped = array_merge( $this->updatesSkipped, $updatesSkipped );
522  $this->updates = array_merge( $this->updates, $updatesDone );
523  }
524 
532  public function updateRowExists( $key ) {
533  $row = $this->db->selectRow(
534  'updatelog',
535  # T67813
536  '1 AS X',
537  [ 'ul_key' => $key ],
538  __METHOD__
539  );
540 
541  return (bool)$row;
542  }
543 
557  public function insertUpdateRow( $key, $val = null ) {
558  $this->db->clearFlag( DBO_DDLMODE );
559  $values = [ 'ul_key' => $key ];
560  if ( $val && $this->canUseNewUpdatelog() ) {
561  $values['ul_value'] = $val;
562  }
563  $this->db->insert( 'updatelog', $values, __METHOD__, [ 'IGNORE' ] );
564  $this->db->setFlag( DBO_DDLMODE );
565  }
566 
575  protected function canUseNewUpdatelog() {
576  return $this->db->tableExists( 'updatelog', __METHOD__ ) &&
577  $this->db->fieldExists( 'updatelog', 'ul_value', __METHOD__ );
578  }
579 
588  protected function doTable( $name ) {
590 
591  // Don't bother to check $wgSharedTables if there isn't a shared database
592  // or the user actually also wants to do updates on the shared database.
593  if ( $wgSharedDB === null || $this->shared ) {
594  return true;
595  }
596 
597  if ( in_array( $name, $wgSharedTables ) ) {
598  $this->output( "...skipping update to shared table $name.\n" );
599  return false;
600  } else {
601  return true;
602  }
603  }
604 
614  protected function getOldGlobalUpdates() {
615  global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
616  $wgExtNewIndexes;
617 
618  $updates = [];
619 
620  foreach ( $wgExtNewTables as $tableRecord ) {
621  $updates[] = [
622  'addTable', $tableRecord[0], $tableRecord[1], true
623  ];
624  }
625 
626  foreach ( $wgExtNewFields as $fieldRecord ) {
627  $updates[] = [
628  'addField', $fieldRecord[0], $fieldRecord[1],
629  $fieldRecord[2], true
630  ];
631  }
632 
633  foreach ( $wgExtNewIndexes as $fieldRecord ) {
634  $updates[] = [
635  'addIndex', $fieldRecord[0], $fieldRecord[1],
636  $fieldRecord[2], true
637  ];
638  }
639 
640  foreach ( $wgExtModifiedFields as $fieldRecord ) {
641  $updates[] = [
642  'modifyField', $fieldRecord[0], $fieldRecord[1],
643  $fieldRecord[2], true
644  ];
645  }
646 
647  return $updates;
648  }
649 
658  abstract protected function getCoreUpdateList();
659 
667  protected function copyFile( $filename ) {
668  $this->db->sourceFile(
669  $filename,
670  null,
671  null,
672  __METHOD__,
673  [ $this, 'appendLine' ]
674  );
675  }
676 
689  protected function appendLine( $line ) {
690  $line = rtrim( $line ) . ";\n";
691  if ( fwrite( $this->fileHandle, $line ) === false ) {
692  throw new MWException( "trouble writing file" );
693  }
694 
695  return false;
696  }
697 
709  protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
710  if ( $msg === null ) {
711  $msg = "Applying $path patch";
712  }
713  if ( $this->skipSchema ) {
714  $this->output( "...skipping schema change ($msg).\n" );
715 
716  return false;
717  }
718 
719  $this->output( "$msg ..." );
720 
721  if ( !$isFullPath ) {
722  $path = $this->patchPath( $this->db, $path );
723  }
724  if ( $this->fileHandle !== null ) {
725  $this->copyFile( $path );
726  } else {
727  $this->db->sourceFile( $path );
728  }
729  $this->output( "done.\n" );
730 
731  return true;
732  }
733 
743  public function patchPath( IDatabase $db, $patch ) {
744  global $IP;
745 
746  $dbType = $db->getType();
747  if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
748  return "$IP/maintenance/$dbType/archives/$patch";
749  } else {
750  return "$IP/maintenance/archives/$patch";
751  }
752  }
753 
765  protected function addTable( $name, $patch, $fullpath = false ) {
766  if ( !$this->doTable( $name ) ) {
767  return true;
768  }
769 
770  if ( $this->db->tableExists( $name, __METHOD__ ) ) {
771  $this->output( "...$name table already exists.\n" );
772  } else {
773  return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
774  }
775 
776  return true;
777  }
778 
791  protected function addField( $table, $field, $patch, $fullpath = false ) {
792  if ( !$this->doTable( $table ) ) {
793  return true;
794  }
795 
796  if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
797  $this->output( "...$table table does not exist, skipping new field patch.\n" );
798  } elseif ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
799  $this->output( "...have $field field in $table table.\n" );
800  } else {
801  return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
802  }
803 
804  return true;
805  }
806 
819  protected function addIndex( $table, $index, $patch, $fullpath = false ) {
820  if ( !$this->doTable( $table ) ) {
821  return true;
822  }
823 
824  if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
825  $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
826  } elseif ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
827  $this->output( "...index $index already set on $table table.\n" );
828  } else {
829  return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
830  }
831 
832  return true;
833  }
834 
845  protected function addIndexIfNoneExist( $table, $indexes, $patch, $fullpath = false ) {
846  if ( !$this->doTable( $table ) ) {
847  return true;
848  }
849 
850  if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
851  $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
852  return true;
853  }
854 
855  $newIndex = $indexes[0];
856  foreach ( $indexes as $index ) {
857  if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
858  $this->output(
859  "...skipping index $newIndex because index $index already set on $table table.\n"
860  );
861  return true;
862  }
863  }
864 
865  return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
866  }
867 
880  protected function dropField( $table, $field, $patch, $fullpath = false ) {
881  if ( !$this->doTable( $table ) ) {
882  return true;
883  }
884 
885  if ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
886  return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
887  } else {
888  $this->output( "...$table table does not contain $field field.\n" );
889  }
890 
891  return true;
892  }
893 
906  protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
907  if ( !$this->doTable( $table ) ) {
908  return true;
909  }
910 
911  if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
912  return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
913  } else {
914  $this->output( "...$index key doesn't exist.\n" );
915  }
916 
917  return true;
918  }
919 
936  protected function renameIndex( $table, $oldIndex, $newIndex,
937  $skipBothIndexExistWarning, $patch, $fullpath = false
938  ) {
939  if ( !$this->doTable( $table ) ) {
940  return true;
941  }
942 
943  // First requirement: the table must exist
944  if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
945  $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
946 
947  return true;
948  }
949 
950  // Second requirement: the new index must be missing
951  if ( $this->db->indexExists( $table, $newIndex, __METHOD__ ) ) {
952  $this->output( "...index $newIndex already set on $table table.\n" );
953  if ( !$skipBothIndexExistWarning &&
954  $this->db->indexExists( $table, $oldIndex, __METHOD__ )
955  ) {
956  $this->output( "...WARNING: $oldIndex still exists, despite it has " .
957  "been renamed into $newIndex (which also exists).\n" .
958  " $oldIndex should be manually removed if not needed anymore.\n" );
959  }
960 
961  return true;
962  }
963 
964  // Third requirement: the old index must exist
965  if ( !$this->db->indexExists( $table, $oldIndex, __METHOD__ ) ) {
966  $this->output( "...skipping: index $oldIndex doesn't exist.\n" );
967 
968  return true;
969  }
970 
971  // Requirements have been satisfied, patch can be applied
972  return $this->applyPatch(
973  $patch,
974  $fullpath,
975  "Renaming index $oldIndex into $newIndex to table $table"
976  );
977  }
978 
993  protected function dropTable( $table, $patch = false, $fullpath = false ) {
994  if ( !$this->doTable( $table ) ) {
995  return true;
996  }
997 
998  if ( $this->db->tableExists( $table, __METHOD__ ) ) {
999  $msg = "Dropping table $table";
1000 
1001  if ( $patch === false ) {
1002  $this->output( "$msg ..." );
1003  $this->db->dropTable( $table, __METHOD__ );
1004  $this->output( "done.\n" );
1005  } else {
1006  return $this->applyPatch( $patch, $fullpath, $msg );
1007  }
1008  } else {
1009  $this->output( "...$table doesn't exist.\n" );
1010  }
1011 
1012  return true;
1013  }
1014 
1029  protected function modifyField( $table, $field, $patch, $fullpath = false ) {
1030  if ( !$this->doTable( $table ) ) {
1031  return true;
1032  }
1033 
1034  $updateKey = "$table-$field-$patch";
1035  if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
1036  $this->output( "...$table table does not exist, skipping modify field patch.\n" );
1037  } elseif ( !$this->db->fieldExists( $table, $field, __METHOD__ ) ) {
1038  $this->output( "...$field field does not exist in $table table, " .
1039  "skipping modify field patch.\n" );
1040  } elseif ( $this->updateRowExists( $updateKey ) ) {
1041  $this->output( "...$field in table $table already modified by patch $patch.\n" );
1042  } else {
1043  $apply = $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
1044  if ( $apply ) {
1045  $this->insertUpdateRow( $updateKey );
1046  }
1047  return $apply;
1048  }
1049  return true;
1050  }
1051 
1066  protected function modifyTable( $table, $patch, $fullpath = false ) {
1067  if ( !$this->doTable( $table ) ) {
1068  return true;
1069  }
1070 
1071  $updateKey = "$table-$patch";
1072  if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
1073  $this->output( "...$table table does not exist, skipping modify table patch.\n" );
1074  } elseif ( $this->updateRowExists( $updateKey ) ) {
1075  $this->output( "...table $table already modified by patch $patch.\n" );
1076  } else {
1077  $apply = $this->applyPatch( $patch, $fullpath, "Modifying table $table" );
1078  if ( $apply ) {
1079  $this->insertUpdateRow( $updateKey );
1080  }
1081  return $apply;
1082  }
1083  return true;
1084  }
1085 
1106  protected function runMaintenance( $class, $script ) {
1107  $this->output( "Running $script...\n" );
1108  $task = $this->maintenance->runChild( $class );
1109  $ok = $task->execute();
1110  if ( !$ok ) {
1111  throw new RuntimeException( "Execution of $script did not complete successfully." );
1112  }
1113  $this->output( "done.\n" );
1114  }
1115 
1121  public function setFileAccess() {
1122  $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
1123  $zonePath = $repo->getZonePath( 'temp' );
1124  if ( $repo->getBackend()->directoryExists( [ 'dir' => $zonePath ] ) ) {
1125  // If the directory was never made, then it will have the right ACLs when it is made
1126  $status = $repo->getBackend()->secure( [
1127  'dir' => $zonePath,
1128  'noAccess' => true,
1129  'noListing' => true
1130  ] );
1131  if ( $status->isOK() ) {
1132  $this->output( "Set the local repo temp zone container to be private.\n" );
1133  } else {
1134  $this->output( "Failed to set the local repo temp zone container to be private.\n" );
1135  }
1136  }
1137  }
1138 
1142  public function purgeCache() {
1143  global $wgLocalisationCacheConf;
1144  // We can't guarantee that the user will be able to use TRUNCATE,
1145  // but we know that DELETE is available to us
1146  $this->output( "Purging caches..." );
1147 
1148  // ObjectCache
1149  $this->db->delete( 'objectcache', '*', __METHOD__ );
1150 
1151  // LocalisationCache
1152  if ( $wgLocalisationCacheConf['manualRecache'] ) {
1153  $this->rebuildLocalisationCache();
1154  }
1155 
1156  // ResourceLoader: Message cache
1157  $services = MediaWikiServices::getInstance();
1158  $blobStore = new MessageBlobStore(
1159  $services->getResourceLoader(),
1160  null,
1161  $services->getMainWANObjectCache()
1162  );
1163  $blobStore->clear();
1164 
1165  // ResourceLoader: File-dependency cache
1166  $this->db->delete( 'module_deps', '*', __METHOD__ );
1167  $this->output( "done.\n" );
1168  }
1169 
1173  protected function checkStats() {
1174  $this->output( "...site_stats is populated..." );
1175  $row = $this->db->selectRow( 'site_stats', '*', [ 'ss_row_id' => 1 ], __METHOD__ );
1176  if ( $row === false ) {
1177  $this->output( "data is missing! rebuilding...\n" );
1178  } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
1179  $this->output( "missing ss_total_pages, rebuilding...\n" );
1180  } else {
1181  $this->output( "done.\n" );
1182 
1183  return;
1184  }
1185  SiteStatsInit::doAllAndCommit( $this->db );
1186  }
1187 
1188  # Common updater functions
1189 
1193  protected function doActiveUsersInit() {
1194  $activeUsers = $this->db->selectField( 'site_stats', 'ss_active_users', '', __METHOD__ );
1195  if ( $activeUsers == -1 ) {
1196  $activeUsers = $this->db->selectField( 'recentchanges',
1197  'COUNT( DISTINCT rc_user_text )',
1198  [ 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ], __METHOD__
1199  );
1200  $this->db->update( 'site_stats',
1201  [ 'ss_active_users' => intval( $activeUsers ) ],
1202  [ 'ss_row_id' => 1 ], __METHOD__, [ 'LIMIT' => 1 ]
1203  );
1204  }
1205  $this->output( "...ss_active_users user count set...\n" );
1206  }
1207 
1211  protected function doLogUsertextPopulation() {
1212  if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
1213  $this->output(
1214  "Populating log_user_text field, printing progress markers. For large\n" .
1215  "databases, you may want to hit Ctrl-C and do this manually with\n" .
1216  "maintenance/populateLogUsertext.php.\n"
1217  );
1218 
1219  $task = $this->maintenance->runChild( PopulateLogUsertext::class );
1220  $task->execute();
1221  $this->output( "done.\n" );
1222  }
1223  }
1224 
1228  protected function doLogSearchPopulation() {
1229  if ( !$this->updateRowExists( 'populate log_search' ) ) {
1230  $this->output(
1231  "Populating log_search table, printing progress markers. For large\n" .
1232  "databases, you may want to hit Ctrl-C and do this manually with\n" .
1233  "maintenance/populateLogSearch.php.\n" );
1234 
1235  $task = $this->maintenance->runChild( PopulateLogSearch::class );
1236  $task->execute();
1237  $this->output( "done.\n" );
1238  }
1239  }
1240 
1244  protected function doCollationUpdate() {
1245  global $wgCategoryCollation;
1246  if ( $this->db->fieldExists( 'categorylinks', 'cl_collation', __METHOD__ ) ) {
1247  if ( $this->db->selectField(
1248  'categorylinks',
1249  'COUNT(*)',
1250  'cl_collation != ' . $this->db->addQuotes( $wgCategoryCollation ),
1251  __METHOD__
1252  ) == 0
1253  ) {
1254  $this->output( "...collations up-to-date.\n" );
1255 
1256  return;
1257  }
1258 
1259  $this->output( "Updating category collations..." );
1260  $task = $this->maintenance->runChild( UpdateCollation::class );
1261  $task->execute();
1262  $this->output( "...done.\n" );
1263  }
1264  }
1265 
1269  protected function doMigrateUserOptions() {
1270  if ( $this->db->tableExists( 'user_properties', __METHOD__ ) ) {
1271  $cl = $this->maintenance->runChild( ConvertUserOptions::class, 'convertUserOptions.php' );
1272  $cl->execute();
1273  $this->output( "done.\n" );
1274  }
1275  }
1276 
1280  protected function rebuildLocalisationCache() {
1284  $cl = $this->maintenance->runChild(
1285  RebuildLocalisationCache::class, 'rebuildLocalisationCache.php'
1286  );
1287  '@phan-var RebuildLocalisationCache $cl';
1288  $this->output( "Rebuilding localisation cache...\n" );
1289  $cl->setForce();
1290  $cl->execute();
1291  $this->output( "done.\n" );
1292  }
1293 
1298  protected function migrateComments() {
1299  if ( !$this->updateRowExists( 'MigrateComments' ) ) {
1300  $this->output(
1301  "Migrating comments to the 'comments' table, printing progress markers. For large\n" .
1302  "databases, you may want to hit Ctrl-C and do this manually with\n" .
1303  "maintenance/migrateComments.php.\n"
1304  );
1305  $task = $this->maintenance->runChild( MigrateComments::class, 'migrateComments.php' );
1306  $ok = $task->execute();
1307  $this->output( $ok ? "done.\n" : "errors were encountered.\n" );
1308  }
1309  }
1310 
1315  protected function migrateImageCommentTemp() {
1316  if ( $this->tableExists( 'image_comment_temp' ) ) {
1317  $this->output( "Merging image_comment_temp into the image table\n" );
1318  $task = $this->maintenance->runChild(
1319  MigrateImageCommentTemp::class, 'migrateImageCommentTemp.php'
1320  );
1321  // @phan-suppress-next-line PhanUndeclaredMethod
1322  $task->setForce();
1323  $ok = $task->execute();
1324  $this->output( $ok ? "done.\n" : "errors were encountered.\n" );
1325  if ( $ok ) {
1326  $this->dropTable( 'image_comment_temp' );
1327  }
1328  }
1329  }
1330 
1335  protected function migrateActors() {
1336  if ( !$this->updateRowExists( 'MigrateActors' ) ) {
1337  $this->output(
1338  "Migrating actors to the 'actor' table, printing progress markers. For large\n" .
1339  "databases, you may want to hit Ctrl-C and do this manually with\n" .
1340  "maintenance/migrateActors.php.\n"
1341  );
1342  $task = $this->maintenance->runChild( 'MigrateActors', 'migrateActors.php' );
1343  $ok = $task->execute();
1344  $this->output( $ok ? "done.\n" : "errors were encountered.\n" );
1345  }
1346  }
1347 
1352  protected function migrateArchiveText() {
1353  if ( $this->db->fieldExists( 'archive', 'ar_text', __METHOD__ ) ) {
1354  $this->output( "Migrating archive ar_text to modern storage.\n" );
1355  $task = $this->maintenance->runChild( MigrateArchiveText::class, 'migrateArchiveText.php' );
1356  // @phan-suppress-next-line PhanUndeclaredMethod
1357  $task->setForce();
1358  if ( $task->execute() ) {
1359  $this->applyPatch( 'patch-drop-ar_text.sql', false,
1360  'Dropping ar_text and ar_flags columns' );
1361  }
1362  }
1363  }
1364 
1369  protected function populateArchiveRevId() {
1370  $info = $this->db->fieldInfo( 'archive', 'ar_rev_id' );
1371  if ( !$info ) {
1372  throw new MWException( 'Missing ar_rev_id field of archive table. Should not happen.' );
1373  }
1374  if ( $info->isNullable() ) {
1375  $this->output( "Populating ar_rev_id.\n" );
1376  $task = $this->maintenance->runChild( 'PopulateArchiveRevId', 'populateArchiveRevId.php' );
1377  if ( $task->execute() ) {
1378  $this->applyPatch( 'patch-ar_rev_id-not-null.sql', false,
1379  'Making ar_rev_id not nullable' );
1380  }
1381  }
1382  }
1383 
1388  protected function populateExternallinksIndex60() {
1389  if ( !$this->updateRowExists( 'populate externallinks.el_index_60' ) ) {
1390  $this->output(
1391  "Populating el_index_60 field, printing progress markers. For large\n" .
1392  "databases, you may want to hit Ctrl-C and do this manually with\n" .
1393  "maintenance/populateExternallinksIndex60.php.\n"
1394  );
1395  $task = $this->maintenance->runChild( 'PopulateExternallinksIndex60',
1396  'populateExternallinksIndex60.php' );
1397  $task->execute();
1398  $this->output( "done.\n" );
1399  }
1400  }
1401 
1406  protected function populateContentTables() {
1407  if ( !$this->updateRowExists( 'PopulateContentTables' ) ) {
1408  $this->output(
1409  "Migrating revision data to the MCR 'slot' and 'content' tables, printing progress markers.\n" .
1410  "For large databases, you may want to hit Ctrl-C and do this manually with\n" .
1411  "maintenance/populateContentTables.php.\n"
1412  );
1413  $task = $this->maintenance->runChild(
1414  PopulateContentTables::class, 'populateContentTables.php'
1415  );
1416  $ok = $task->execute();
1417  $this->output( $ok ? "done.\n" : "errors were encountered.\n" );
1418  if ( $ok ) {
1419  $this->insertUpdateRow( 'PopulateContentTables' );
1420  }
1421  }
1422  }
1423 
1427  protected function ifNoActorTable( $func, ...$params ) {
1428  wfDeprecated( __METHOD__, '1.35' );
1429  return $this->ifTableNotExists( 'actor', $func, ...$params );
1430  }
1431 
1445  protected function ifTableNotExists( $table, $func, ...$params ) {
1446  // Handle $passSelf from runUpdates().
1447  $passSelf = false;
1448  if ( $table === $this ) {
1449  $passSelf = true;
1450  $table = $func;
1451  $func = array_shift( $params );
1452  }
1453 
1454  if ( $this->db->tableExists( $table, __METHOD__ ) ) {
1455  return null;
1456  }
1457 
1458  if ( !is_array( $func ) && method_exists( $this, $func ) ) {
1459  $func = [ $this, $func ];
1460  } elseif ( $passSelf ) {
1461  array_unshift( $params, $this );
1462  }
1463 
1464  // @phan-suppress-next-line PhanUndeclaredInvokeInCallable Phan is confused
1465  return $func( ...$params );
1466  }
1467 
1482  protected function ifFieldExists( $table, $field, $func, ...$params ) {
1483  // Handle $passSelf from runUpdates().
1484  $passSelf = false;
1485  if ( $table === $this ) {
1486  $passSelf = true;
1487  $table = $field;
1488  $field = $func;
1489  $func = array_shift( $params );
1490  }
1491 
1492  if ( !$this->db->tableExists( $table, __METHOD__ ) ||
1493  !$this->db->fieldExists( $table, $field, __METHOD__ )
1494  ) {
1495  return null;
1496  }
1497 
1498  if ( !is_array( $func ) && method_exists( $this, $func ) ) {
1499  $func = [ $this, $func ];
1500  } elseif ( $passSelf ) {
1501  array_unshift( $params, $this );
1502  }
1503 
1504  // @phan-suppress-next-line PhanUndeclaredInvokeInCallable Phan is confused
1505  return $func( ...$params );
1506  }
1507 }
DatabaseUpdater\output
output( $str)
Output some text.
Definition: DatabaseUpdater.php:224
DatabaseUpdater\dropIndex
dropIndex( $table, $index, $patch, $fullpath=false)
Drop an index from an existing table.
Definition: DatabaseUpdater.php:906
DatabaseUpdater\modifyExtensionTable
modifyExtensionTable( $tableName, $sqlPath)
Modify an existing extension table.
Definition: DatabaseUpdater.php:385
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:993
DatabaseUpdater\copyFile
copyFile( $filename)
Append an SQL fragment to the open file handle.
Definition: DatabaseUpdater.php:667
DatabaseUpdater\$updatesSkipped
array $updatesSkipped
Array of updates that were skipped.
Definition: DatabaseUpdater.php:52
DatabaseUpdater\newForDB
static newForDB(IMaintainableDatabase $db, $shared=false, Maintenance $maintenance=null)
Definition: DatabaseUpdater.php:194
DatabaseUpdater\applyPatch
applyPatch( $path, $isFullPath=false, $msg=null)
Applies a SQL patch.
Definition: DatabaseUpdater.php:709
DatabaseUpdater\doCollationUpdate
doCollationUpdate()
Update CategoryLinks collation.
Definition: DatabaseUpdater.php:1244
DatabaseUpdater\dropExtensionTable
dropExtensionTable( $tableName, $sqlPath=false)
Drop an extension table.
Definition: DatabaseUpdater.php:331
SiteStatsInit\doAllAndCommit
static doAllAndCommit( $database, array $options=[])
Do all updates and commit them.
Definition: SiteStatsInit.php:134
$wgSharedTables
$wgSharedTables
Definition: DefaultSettings.php:2162
DatabaseUpdater
Class for handling database updates.
Definition: DatabaseUpdater.php:37
DatabaseUpdater\populateExternallinksIndex60
populateExternallinksIndex60()
Populates the externallinks.el_index_60 field.
Definition: DatabaseUpdater.php:1388
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:154
DatabaseUpdater\addPostDatabaseUpdateMaintenance
addPostDatabaseUpdateMaintenance( $class)
Add a maintenance script to be run after the database updates are complete.
Definition: DatabaseUpdater.php:408
DatabaseUpdater\checkStats
checkStats()
Check the site_stats table is not properly populated.
Definition: DatabaseUpdater.php:1173
true
return true
Definition: router.php:90
$wgSharedDB
$wgSharedDB
Shared database for multiple wikis.
Definition: DefaultSettings.php:2152
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:1315
DatabaseUpdater\doMigrateUserOptions
doMigrateUserOptions()
Migrates user options from the user table blob to user_properties.
Definition: DatabaseUpdater.php:1269
DatabaseUpdater\populateContentTables
populateContentTables()
Populates the MCR content tables.
Definition: DatabaseUpdater.php:1406
DatabaseUpdater\dropField
dropField( $table, $field, $patch, $fullpath=false)
Drop a field from an existing table.
Definition: DatabaseUpdater.php:880
DatabaseUpdater\addField
addField( $table, $field, $patch, $fullpath=false)
Add a new field to an existing table.
Definition: DatabaseUpdater.php:791
DatabaseUpdater\doTable
doTable( $name)
Returns whether updates should be executed on the database table $name.
Definition: DatabaseUpdater.php:588
DatabaseUpdater\getPostDatabaseUpdateMaintenance
getPostDatabaseUpdateMaintenance()
Definition: DatabaseUpdater.php:426
DatabaseUpdater\appendLine
appendLine( $line)
Append a line to the open filehandle.
Definition: DatabaseUpdater.php:689
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: Maintenance.php:55
DatabaseUpdater\patchPath
patchPath(IDatabase $db, $patch)
Get the full path of a patch file.
Definition: DatabaseUpdater.php:743
DatabaseUpdater\getSchemaVars
getSchemaVars()
Get appropriate schema variables in the current database connection.
Definition: DatabaseUpdater.php:460
DatabaseUpdater\REPLICATION_WAIT_TIMEOUT
const REPLICATION_WAIT_TIMEOUT
Definition: DatabaseUpdater.php:38
DatabaseUpdater\addExtensionIndex
addExtensionIndex( $tableName, $indexName, $sqlPath)
Add an index to an existing extension table.
Definition: DatabaseUpdater.php:276
DatabaseUpdater\migrateComments
migrateComments()
Migrate comments to the new 'comment' table.
Definition: DatabaseUpdater.php:1298
DatabaseUpdater\__construct
__construct(IMaintainableDatabase &$db, $shared, Maintenance $maintenance=null)
Stable to call.
Definition: DatabaseUpdater.php:114
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:1193
DatabaseUpdater\dropExtensionIndex
dropExtensionIndex( $tableName, $indexName, $sqlPath)
Drop an index from an extension table Intended for use in LoadExtensionSchemaUpdates hook handlers.
Definition: DatabaseUpdater.php:318
DatabaseUpdater\$updates
array $updates
Array of updates to perform on the database.
Definition: DatabaseUpdater.php:45
ExtensionRegistry\getInstance
static getInstance()
Definition: ExtensionRegistry.php:136
DatabaseUpdater\addExtensionUpdate
addExtensionUpdate(array $update)
Add a new update coming from an extension.
Definition: DatabaseUpdater.php:248
DatabaseUpdater\setFileAccess
setFileAccess()
Set any .htaccess files or equivilent for storage repos.
Definition: DatabaseUpdater.php:1121
DatabaseUpdater\loadExtensionSchemaUpdates
loadExtensionSchemaUpdates()
Cause extensions to register any updates they need to perform.
Definition: DatabaseUpdater.php:134
$wgHooks
$wgHooks
Global list of hooks.
Definition: DefaultSettings.php:7928
MWException
MediaWiki exception.
Definition: MWException.php:29
DatabaseUpdater\renameIndex
renameIndex( $table, $oldIndex, $newIndex, $skipBothIndexExistWarning, $patch, $fullpath=false)
Rename an index from an existing table Stable to override.
Definition: DatabaseUpdater.php:936
DatabaseUpdater\getExtensionUpdates
getExtensionUpdates()
Get the list of extension-defined updates.
Definition: DatabaseUpdater.php:417
DatabaseUpdater\migrateArchiveText
migrateArchiveText()
Migrate ar_text to modern storage.
Definition: DatabaseUpdater.php:1352
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1026
DatabaseUpdater\$maintenance
Maintenance $maintenance
Definition: DatabaseUpdater.php:70
DatabaseUpdater\modifyTable
modifyTable( $table, $patch, $fullpath=false)
Modify an existing table, similar to modifyField.
Definition: DatabaseUpdater.php:1066
DatabaseUpdater\$db
IMaintainableDatabase $db
Handle to the database subclass.
Definition: DatabaseUpdater.php:65
$wgCommandLineMode
global $wgCommandLineMode
Definition: DevelopmentSettings.php:29
DatabaseUpdater\modifyExtensionField
modifyExtensionField( $tableName, $fieldName, $sqlPath)
Modify an existing field in an extension table.
Definition: DatabaseUpdater.php:372
DatabaseUpdater\rebuildLocalisationCache
rebuildLocalisationCache()
Rebuilds the localisation cache.
Definition: DatabaseUpdater.php:1280
$queue
$queue
Definition: mergeMessageFileList.php:157
$args
if( $line===false) $args
Definition: mcc.php:124
DatabaseUpdater\ifNoActorTable
ifNoActorTable( $func,... $params)
Definition: DatabaseUpdater.php:1427
Installer\getExistingLocalSettings
static getExistingLocalSettings()
Determine if LocalSettings.php exists.
Definition: Installer.php:598
DatabaseUpdater\getDB
getDB()
Get a database connection to run updates.
Definition: DatabaseUpdater.php:214
DatabaseUpdater\ifTableNotExists
ifTableNotExists( $table, $func,... $params)
Only run a function if a table does not exist.
Definition: DatabaseUpdater.php:1445
$wgLocalisationCacheConf
$wgLocalisationCacheConf
Localisation cache configuration.
Definition: DefaultSettings.php:2754
DatabaseUpdater\runUpdates
runUpdates(array $updates, $passSelf)
Helper function for doUpdates()
Definition: DatabaseUpdater.php:499
DatabaseUpdater\doUpdates
doUpdates(array $what=[ 'core', 'extensions', 'stats'])
Do all the updates.
Definition: DatabaseUpdater.php:469
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:532
DatabaseUpdater\doLogSearchPopulation
doLogSearchPopulation()
Migrate log params to new table and index for searching.
Definition: DatabaseUpdater.php:1228
DBO_DDLMODE
const DBO_DDLMODE
Definition: defines.php:16
DatabaseUpdater\populateArchiveRevId
populateArchiveRevId()
Populate ar_rev_id, then make it not nullable.
Definition: DatabaseUpdater.php:1369
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:575
DatabaseUpdater\ifFieldExists
ifFieldExists( $table, $field, $func,... $params)
Only run a function if the named field exists.
Definition: DatabaseUpdater.php:1482
DatabaseUpdater\runMaintenance
runMaintenance( $class, $script)
Run a maintenance script.
Definition: DatabaseUpdater.php:1106
Hooks\runner
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Definition: Hooks.php:172
$line
$line
Definition: mcc.php:119
DatabaseUpdater\$fileHandle
resource $fileHandle
File handle for SQL output.
Definition: DatabaseUpdater.php:99
DatabaseUpdater\getOldGlobalUpdates
getOldGlobalUpdates()
Before 1.17, we used to handle updates via stuff like $wgExtNewTables/Fields/Indexes.
Definition: DatabaseUpdater.php:614
$wgAutoloadClasses
$wgAutoloadClasses
Array mapping class names to filenames, for autoloading.
Definition: DefaultSettings.php:7823
DatabaseUpdater\doLogUsertextPopulation
doLogUsertextPopulation()
Populates the log_user_text field in the logging table.
Definition: DatabaseUpdater.php:1211
DatabaseUpdater\tableExists
tableExists( $tableName)
Definition: DatabaseUpdater.php:395
DatabaseUpdater\addExtensionField
addExtensionField( $tableName, $columnName, $sqlPath)
Add a field to an existing extension table.
Definition: DatabaseUpdater.php:290
DatabaseUpdater\modifyField
modifyField( $table, $field, $patch, $fullpath=false)
Modify an existing field.
Definition: DatabaseUpdater.php:1029
DatabaseUpdater\writeSchemaUpdateFile
writeSchemaUpdateFile(array $schemaUpdate=[])
Definition: DatabaseUpdater.php:436
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:845
DatabaseUpdater\loadExtensions
loadExtensions()
Loads LocalSettings.php, if needed, and initialises everything needed for LoadExtensionSchemaUpdates ...
Definition: DatabaseUpdater.php:162
$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:348
DatabaseUpdater\addTable
addTable( $name, $patch, $fullpath=false)
Add a new table to the database.
Definition: DatabaseUpdater.php:765
DatabaseUpdater\$shared
$shared
Definition: DatabaseUpdater.php:72
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:1335
Maintenance\setDB
setDB(IMaintainableDatabase $db)
Sets database object to be returned by getDB().
Definition: Maintenance.php:1383
DatabaseUpdater\dropExtensionField
dropExtensionField( $tableName, $columnName, $sqlPath)
Drop a field from an extension table.
Definition: DatabaseUpdater.php:304
DatabaseUpdater\purgeCache
purgeCache()
Purge various database caches.
Definition: DatabaseUpdater.php:1142
$wgCategoryCollation
$wgCategoryCollation
Specify how category names should be sorted, when listed on a category page.
Definition: DefaultSettings.php:8108
DatabaseUpdater\$skipSchema
bool $skipSchema
Flag specifying whether or not to skip schema (e.g.
Definition: DatabaseUpdater.php:106
DatabaseUpdater\addExtensionTable
addExtensionTable( $tableName, $sqlPath)
Convenience wrapper for addExtensionUpdate() when adding a new table (which is the most common usage ...
Definition: DatabaseUpdater.php:262
Installer\getDBTypes
static getDBTypes()
Get a list of known DB types.
Definition: Installer.php:479
DatabaseUpdater\initOldGlobals
initOldGlobals()
Initialize all of the old globals.
Definition: DatabaseUpdater.php:144
DatabaseUpdater\addIndex
addIndex( $table, $index, $patch, $fullpath=false)
Add a new index to an existing table.
Definition: DatabaseUpdater.php:819
DatabaseUpdater\$extensionUpdates
array $extensionUpdates
List of extension-provided database updates.
Definition: DatabaseUpdater.php:58
DatabaseUpdater\insertUpdateRow
insertUpdateRow( $key, $val=null)
Helper function: Add a key to the updatelog table.
Definition: DatabaseUpdater.php:557
$IP
$IP
Definition: WebStart.php:49
Wikimedia\Rdbms\IDatabase\setFlag
setFlag( $flag, $remember=self::REMEMBER_NOTHING)
Set a flag for this connection.
DatabaseUpdater\$postDatabaseUpdateMaintenance
string[] $postDatabaseUpdateMaintenance
Scripts to run after database update Should be a subclass of LoggedUpdateMaintenance.
Definition: DatabaseUpdater.php:78
Wikimedia\Rdbms\IMaintainableDatabase
Advanced database interface for IDatabase handles that include maintenance methods.
Definition: IMaintainableDatabase.php:38
$type
$type
Definition: testCompression.php:52