MediaWiki  master
updateCollation.php
Go to the documentation of this file.
1 <?php
27 require_once __DIR__ . '/Maintenance.php';
28 
31 
39  const BATCH_SIZE = 100; // Number of rows to process in one batch
40  const SYNC_INTERVAL = 5; // Wait for replica DBs after this many batches
41 
42  public $sizeHistogram = [];
43 
44  public function __construct() {
45  parent::__construct();
46 
47  global $wgCategoryCollation;
48  $this->addDescription( <<<TEXT
49 This script will find all rows in the categorylinks table whose collation is
50 out-of-date (cl_collation != '$wgCategoryCollation') and repopulate cl_sortkey
51 using the page title and cl_sortkey_prefix. If all collations are
52 up-to-date, it will do nothing.
53 TEXT
54  );
55 
56  $this->addOption( 'force', 'Run on all rows, even if the collation is ' .
57  'supposed to be up-to-date.', false, false, 'f' );
58  $this->addOption( 'previous-collation', 'Set the previous value of ' .
59  '$wgCategoryCollation here to speed up this script, especially if your ' .
60  'categorylinks table is large. This will only update rows with that ' .
61  'collation, though, so it may miss out-of-date rows with a different, ' .
62  'even older collation.', false, true );
63  $this->addOption( 'target-collation', 'Set this to the new collation type to ' .
64  'use instead of $wgCategoryCollation. Usually you should not use this, ' .
65  'you should just update $wgCategoryCollation in LocalSettings.php.',
66  false, true );
67  $this->addOption( 'dry-run', 'Don\'t actually change the collations, just ' .
68  'compile statistics.' );
69  $this->addOption( 'verbose-stats', 'Show more statistics.' );
70  }
71 
72  public function execute() {
73  global $wgCategoryCollation;
74 
75  $dbw = $this->getDB( DB_MASTER );
76  $dbr = $this->getDB( DB_REPLICA );
77  $force = $this->getOption( 'force' );
78  $dryRun = $this->getOption( 'dry-run' );
79  $verboseStats = $this->getOption( 'verbose-stats' );
80  if ( $this->hasOption( 'target-collation' ) ) {
81  $collationName = $this->getOption( 'target-collation' );
82  $collation = Collation::factory( $collationName );
83  } else {
84  $collationName = $wgCategoryCollation;
85  $collation = Collation::singleton();
86  }
87 
88  // Collation sanity check: in some cases the constructor will work,
89  // but this will raise an exception, breaking all category pages
90  $collation->getFirstLetter( 'MediaWiki' );
91 
92  // Locally at least, (my local is a rather old version of mysql)
93  // mysql seems to filesort if there is both an equality
94  // (but not for an inequality) condition on cl_collation in the
95  // WHERE and it is also the first item in the ORDER BY.
96  if ( $this->hasOption( 'previous-collation' ) ) {
97  $orderBy = 'cl_to, cl_type, cl_from';
98  } else {
99  $orderBy = 'cl_collation, cl_to, cl_type, cl_from';
100  }
101  $options = [
102  'LIMIT' => self::BATCH_SIZE,
103  'ORDER BY' => $orderBy,
104  'STRAIGHT_JOIN' // per T58041
105  ];
106 
107  if ( $force ) {
108  $collationConds = [];
109  } else {
110  if ( $this->hasOption( 'previous-collation' ) ) {
111  $collationConds['cl_collation'] = $this->getOption( 'previous-collation' );
112  } else {
113  $collationConds = [ 0 =>
114  'cl_collation != ' . $dbw->addQuotes( $collationName )
115  ];
116  }
117 
118  $count = $dbr->estimateRowCount(
119  'categorylinks',
120  '*',
121  $collationConds,
122  __METHOD__
123  );
124  // Improve estimate if feasible
125  if ( $count < 1000000 ) {
126  $count = $dbr->selectField(
127  'categorylinks',
128  'COUNT(*)',
129  $collationConds,
130  __METHOD__
131  );
132  }
133  if ( $count == 0 ) {
134  $this->output( "Collations up-to-date.\n" );
135 
136  return;
137  }
138  if ( $dryRun ) {
139  $this->output( "$count rows would be updated.\n" );
140  } else {
141  $this->output( "Fixing collation for $count rows.\n" );
142  }
143  wfWaitForSlaves();
144  }
145  $count = 0;
146  $batchConds = [];
147  do {
148  $this->output( "Selecting next " . self::BATCH_SIZE . " rows..." );
149 
150  // cl_type must be selected as a number for proper paging because
151  // enums suck.
152  if ( $dbw->getType() === 'mysql' ) {
153  $clType = 'cl_type+0 AS "cl_type_numeric"';
154  } else {
155  $clType = 'cl_type';
156  }
157  $res = $dbw->select(
158  [ 'categorylinks', 'page' ],
159  [ 'cl_from', 'cl_to', 'cl_sortkey_prefix', 'cl_collation',
160  'cl_sortkey', $clType,
161  'page_namespace', 'page_title'
162  ],
163  array_merge( $collationConds, $batchConds, [ 'cl_from = page_id' ] ),
164  __METHOD__,
165  $options
166  );
167  $this->output( " processing..." );
168 
169  if ( !$dryRun ) {
170  $this->beginTransaction( $dbw, __METHOD__ );
171  }
172  foreach ( $res as $row ) {
173  $title = Title::newFromRow( $row );
174  if ( !$row->cl_collation ) {
175  # This is an old-style row, so the sortkey needs to be
176  # converted.
177  if ( $row->cl_sortkey == $title->getText()
178  || $row->cl_sortkey == $title->getPrefixedText()
179  ) {
180  $prefix = '';
181  } else {
182  # Custom sortkey, use it as a prefix
183  $prefix = $row->cl_sortkey;
184  }
185  } else {
186  $prefix = $row->cl_sortkey_prefix;
187  }
188  # cl_type will be wrong for lots of pages if cl_collation is 0,
189  # so let's update it while we're here.
190  $type = MediaWikiServices::getInstance()->getNamespaceInfo()->
191  getCategoryLinkType( $title->getNamespace() );
192  $newSortKey = $collation->getSortKey(
193  $title->getCategorySortkey( $prefix ) );
194  if ( $verboseStats ) {
195  $this->updateSortKeySizeHistogram( $newSortKey );
196  }
197 
198  if ( $dryRun ) {
199  // Add 1 to the count if the sortkey was changed. (Note that this doesn't count changes in
200  // other fields, if any, those usually only happen when upgrading old MediaWikis.)
201  $count += ( $row->cl_sortkey !== $newSortKey );
202  } else {
203  $dbw->update(
204  'categorylinks',
205  [
206  'cl_sortkey' => $newSortKey,
207  'cl_sortkey_prefix' => $prefix,
208  'cl_collation' => $collationName,
209  'cl_type' => $type,
210  'cl_timestamp = cl_timestamp',
211  ],
212  [ 'cl_from' => $row->cl_from, 'cl_to' => $row->cl_to ],
213  __METHOD__
214  );
215  $count++;
216  }
217  if ( $row ) {
218  $batchConds = [ $this->getBatchCondition( $row, $dbw ) ];
219  }
220  }
221  if ( !$dryRun ) {
222  $this->commitTransaction( $dbw, __METHOD__ );
223  }
224 
225  if ( $dryRun ) {
226  $this->output( "$count rows would be updated so far.\n" );
227  } else {
228  $this->output( "$count done.\n" );
229  }
230  } while ( $res->numRows() == self::BATCH_SIZE );
231 
232  if ( !$dryRun ) {
233  $this->output( "$count rows processed\n" );
234  }
235 
236  if ( $verboseStats ) {
237  $this->output( "\n" );
238  $this->showSortKeySizeHistogram();
239  }
240  }
241 
249  function getBatchCondition( $row, $dbw ) {
250  if ( $this->hasOption( 'previous-collation' ) ) {
251  $fields = [ 'cl_to', 'cl_type', 'cl_from' ];
252  } else {
253  $fields = [ 'cl_collation', 'cl_to', 'cl_type', 'cl_from' ];
254  }
255  $first = true;
256  $cond = false;
257  $prefix = false;
258  foreach ( $fields as $field ) {
259  if ( $dbw->getType() === 'mysql' && $field === 'cl_type' ) {
260  // Range conditions with enums are weird in mysql
261  // This must be a numeric literal, or it won't work.
262  $encValue = intval( $row->cl_type_numeric );
263  } else {
264  $encValue = $dbw->addQuotes( $row->$field );
265  }
266  $inequality = "$field > $encValue";
267  $equality = "$field = $encValue";
268  if ( $first ) {
269  $cond = $inequality;
270  $prefix = $equality;
271  $first = false;
272  } else {
273  $cond .= " OR ($prefix AND $inequality)";
274  $prefix .= " AND $equality";
275  }
276  }
277 
278  return $cond;
279  }
280 
281  function updateSortKeySizeHistogram( $key ) {
282  $length = strlen( $key );
283  if ( !isset( $this->sizeHistogram[$length] ) ) {
284  $this->sizeHistogram[$length] = 0;
285  }
286  $this->sizeHistogram[$length]++;
287  }
288 
290  $maxLength = max( array_keys( $this->sizeHistogram ) );
291  if ( $maxLength == 0 ) {
292  return;
293  }
294  $numBins = 20;
295  $coarseHistogram = array_fill( 0, $numBins, 0 );
296  $coarseBoundaries = [];
297  $boundary = 0;
298  for ( $i = 0; $i < $numBins - 1; $i++ ) {
299  $boundary += $maxLength / $numBins;
300  $coarseBoundaries[$i] = round( $boundary );
301  }
302  $coarseBoundaries[$numBins - 1] = $maxLength + 1;
303  $raw = '';
304  for ( $i = 0; $i <= $maxLength; $i++ ) {
305  if ( $raw !== '' ) {
306  $raw .= ', ';
307  }
308  $val = $this->sizeHistogram[$i] ?? 0;
309  for ( $coarseIndex = 0; $coarseIndex < $numBins - 1; $coarseIndex++ ) {
310  if ( $coarseBoundaries[$coarseIndex] > $i ) {
311  $coarseHistogram[$coarseIndex] += $val;
312  break;
313  }
314  }
315  if ( $coarseIndex == $numBins - 1 ) {
316  $coarseHistogram[$coarseIndex] += $val;
317  }
318  $raw .= $val;
319  }
320 
321  $this->output( "Sort key size histogram\nRaw data: $raw\n\n" );
322 
323  $maxBinVal = max( $coarseHistogram );
324  $scale = 60 / $maxBinVal;
325  $prevBoundary = 0;
326  for ( $coarseIndex = 0; $coarseIndex < $numBins; $coarseIndex++ ) {
327  $val = $coarseHistogram[$coarseIndex] ?? 0;
328  $boundary = $coarseBoundaries[$coarseIndex];
329  $this->output( sprintf( "%-10s %-10d |%s\n",
330  $prevBoundary . '-' . ( $boundary - 1 ) . ': ',
331  $val,
332  str_repeat( '*', $scale * $val ) ) );
333  $prevBoundary = $boundary;
334  }
335  }
336 }
337 
339 require_once RUN_MAINTENANCE_IF_MAIN;
commitTransaction(IDatabase $dbw, $fname)
Commit the transcation on a DB handle and wait for replica DBs to catch up.
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set up
Definition: hooks.txt:2217
$maintClass
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
getOption( $name, $default=null)
Get an option, or return the default.
globals txt Globals are evil The original MediaWiki code relied on globals for processing context far too often MediaWiki development since then has been a story of slowly moving context out of global variables and into objects Storing processing context in object member variables allows those objects to be reused in a much more flexible way Consider the elegance of
database rows
Definition: globals.txt:10
static singleton()
Definition: Collation.php:36
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
null for the local wiki Added in
Definition: hooks.txt:1585
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
hasOption( $name)
Checks to see if a particular option exists.
require_once RUN_MAINTENANCE_IF_MAIN
Definition: maintenance.txt:50
target page
static newFromRow( $row)
Make a Title object from a DB row.
Definition: Title.php:519
title
$wgCategoryCollation
Specify how category names should be sorted, when listed on a category page.
const DB_MASTER
Definition: defines.php:26
This document provides an overview of the usage of PageUpdater and that is
Definition: pageupdater.txt:3
getBatchCondition( $row, $dbw)
Return an SQL expression selecting rows which sort above the given row, assuming an ordering of cl_co...
The ContentHandler facility adds support for arbitrary content types on wiki instead of relying on wikitext for everything It was introduced in MediaWiki Each kind of and so on Built in content types are
$res
Definition: database.txt:21
wfWaitForSlaves( $ifWritesSince=null, $wiki=false, $cluster=false, $timeout=null)
Waits for the replica DBs to catch up to the master position.
addDescription( $text)
Set the description text.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1982
and(b) You must cause any modified files to carry prominent notices stating that You changed the files
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
getDB( $db, $groups=[], $wiki=false)
Returns a database to be used by current maintenance script.
output( $out, $channel=null)
Throw some output to the user.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global then executing the whole list after the page is displayed We don t do anything smart like collating updates to the same table or such because the list is almost always going to have just one item on if so it s not worth the trouble Since there is a job queue in the jobs table
Definition: deferred.txt:11
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
static factory( $collationName)
Definition: Collation.php:50
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Maintenance script that will find all rows in the categorylinks table whose collation is out-of-date...
const DB_REPLICA
Definition: defines.php:25
</td >< td > &</td >< td > t want your writing to be edited mercilessly and redistributed at will
=Architecture==Two class hierarchies are used to provide the functionality associated with the different content models:*Content interface(and AbstractContent base class) define functionality that acts on the concrete content of a page, and *ContentHandler base class provides functionality specific to a content model, but not acting on concrete content. The most important function of ContentHandler is to act as a factory for the appropriate implementation of Content. These Content objects are to be used by MediaWiki everywhere, instead of passing page content around as text. All manipulation and analysis of page content must be done via the appropriate methods of the Content object. For each content model, a subclass of ContentHandler has to be registered with $wgContentHandlers. The ContentHandler object for a given content model can be obtained using ContentHandler::getForModelID($id). Also Title, WikiPage and Revision now have getContentHandler() methods for convenience. ContentHandler objects are singletons that provide functionality specific to the content type, but not directly acting on the content of some page. ContentHandler::makeEmptyContent() and ContentHandler::unserializeContent() can be used to create a Content object of the appropriate type. However, it is recommended to instead use WikiPage::getContent() resp. Revision::getContent() to get a page 's content as a Content object. These two methods should be the ONLY way in which page content is accessed. Another important function of ContentHandler objects is to define custom action handlers for a content model, see ContentHandler::getActionOverrides(). This is similar to what WikiPage::getActionOverrides() was already doing.==Serialization==With the ContentHandler facility, page content no longer has to be text based. Objects implementing the Content interface are used to represent and handle the content internally. For storage and data exchange, each content model supports at least one serialization format via ContentHandler::serializeContent($content). The list of supported formats for a given content model can be accessed using ContentHandler::getSupportedFormats(). Content serialization formats are identified using MIME type like strings. The following formats are built in:*text/x-wiki - wikitext *text/javascript - for js pages *text/css - for css pages *text/plain - for future use, e.g. with plain text messages. *text/html - for future use, e.g. with plain html messages. *application/vnd.php.serialized - for future use with the api and for extensions *application/json - for future use with the api, and for use by extensions *application/xml - for future use with the api, and for use by extensions In PHP, use the corresponding CONTENT_FORMAT_XXX constant. Note that when using the API to access page content, especially action=edit, action=parse and action=query &prop=revisions, the model and format of the content should always be handled explicitly. Without that information, interpretation of the provided content is not reliable. The same applies to XML dumps generated via maintenance/dumpBackup.php or Special:Export. Also note that the API will provide encapsulated, serialized content - so if the API was called with format=json, and contentformat is also json(or rather, application/json), the page content is represented as a string containing an escaped json structure. Extensions that use JSON to serialize some types of page content may provide specialized API modules that allow access to that content in a more natural form.==Compatibility==The ContentHandler facility is introduced in a way that should allow all existing code to keep functioning at least for pages that contain wikitext or other text based content. However, a number of functions and hooks have been deprecated in favor of new versions that are aware of the page 's content model, and will now generate warnings when used. Most importantly, the following functions have been deprecated:*Revisions::getText() is deprecated in favor Revisions::getContent() *WikiPage::getText() is deprecated in favor WikiPage::getContent() Also, the old Article::getContent()(which returns text) is superceded by Article::getContentObject(). However, both methods should be avoided since they do not provide clean access to the page 's actual content. For instance, they may return a system message for non-existing pages. Use WikiPage::getContent() instead. Code that relies on a textual representation of the page content should eventually be rewritten. However, ContentHandler::getContentText() provides a stop-gap that can be used to get text for a page. Its behavior is controlled by $wgContentHandlerTextFallback it
updateSortKeySizeHistogram( $key)
beginTransaction(IDatabase $dbw, $fname)
Begin a transcation on a DB.