MediaWiki 1.41.2
updateCollation.php
Go to the documentation of this file.
1<?php
27require_once __DIR__ . '/Maintenance.php';
28
36
45 public $sizeHistogram = [];
46
48 private $numRowsProcessed = 0;
49
51 private $dryRun;
52
54 private $force;
55
57 private $verboseStats;
58
60 private $collation;
61
63 private $collationName;
64
66 private $targetTable;
67
69 private $dbr;
70
72 private $dbw;
73
75 private $lbFactory;
76
78 private $namespaceInfo;
79
80 public function __construct() {
81 parent::__construct();
82
83 $this->addDescription( <<<TEXT
84This script will find all rows in the categorylinks table whose collation is
85out-of-date (cl_collation is not the same as \$wgCategoryCollation) and
86repopulate cl_sortkey using the page title and cl_sortkey_prefix. If all
87collations are up-to-date, it will do nothing.
88TEXT
89 );
90
91 $this->setBatchSize( 100 );
92 $this->addOption( 'force', 'Run on all rows, even if the collation is ' .
93 'supposed to be up-to-date.', false, false, 'f' );
94 $this->addOption( 'previous-collation', 'Set the previous value of ' .
95 '$wgCategoryCollation here to speed up this script, especially if your ' .
96 'categorylinks table is large. This will only update rows with that ' .
97 'collation, though, so it may miss out-of-date rows with a different, ' .
98 'even older collation.', false, true );
99 $this->addOption( 'target-collation', 'Set this to the new collation type to ' .
100 'use instead of $wgCategoryCollation. Usually you should not use this, ' .
101 'you should just update $wgCategoryCollation in LocalSettings.php.',
102 false, true );
103 $this->addOption( 'target-table', 'Copy rows from categorylinks into the ' .
104 'specified table instead of updating them in place.', false, true );
105 $this->addOption( 'remote', 'Use Shellbox to calculate the new sort keys ' .
106 'remotely.' );
107 $this->addOption( 'dry-run', 'Don\'t actually change the collations, just ' .
108 'compile statistics.' );
109 $this->addOption( 'verbose-stats', 'Show more statistics.' );
110 }
111
115 private function init() {
116 $services = $this->getServiceContainer();
117 $this->namespaceInfo = $services->getNamespaceInfo();
118 $this->lbFactory = $services->getDBLoadBalancerFactory();
119
120 if ( $this->hasOption( 'target-collation' ) ) {
121 $this->collationName = $this->getOption( 'target-collation' );
122 } else {
123 $this->collationName = $this->getConfig()->get( MainConfigNames::CategoryCollation );
124 }
125 if ( $this->hasOption( 'remote' ) ) {
126 $realCollationName = 'remote-' . $this->collationName;
127 } else {
128 $realCollationName = $this->collationName;
129 }
130 $this->collation = $services->getCollationFactory()->makeCollation( $realCollationName );
131
132 // Collation check: in some cases the constructor will work,
133 // but this will raise an exception, breaking all category pages
134 $this->collation->getSortKey( 'MediaWiki' );
135
136 $this->force = $this->getOption( 'force' );
137 $this->dryRun = $this->getOption( 'dry-run' );
138 $this->verboseStats = $this->getOption( 'verbose-stats' );
139 $this->dbw = $this->getDB( DB_PRIMARY );
140 $this->dbr = $this->getDB( DB_REPLICA );
141 $this->targetTable = $this->getOption( 'target-table' );
142 }
143
144 public function execute() {
145 $this->init();
146 $batchSize = $this->getBatchSize();
147
148 if ( $this->targetTable ) {
149 if ( !$this->dbw->tableExists( $this->targetTable, __METHOD__ ) ) {
150 $this->output( "Creating table {$this->targetTable}\n" );
151 $this->dbw->query(
152 'CREATE TABLE ' . $this->dbw->tableName( $this->targetTable ) .
153 ' LIKE ' . $this->dbw->tableName( 'categorylinks' ),
154 __METHOD__
155 );
156 }
157 }
158
159 // Locally at least, (my local is a rather old version of mysql)
160 // mysql seems to filesort if there is both an equality
161 // (but not for an inequality) condition on cl_collation in the
162 // WHERE and it is also the first item in the ORDER BY.
163 if ( $this->hasOption( 'previous-collation' ) ) {
164 $orderBy = 'cl_to, cl_type, cl_from';
165 } else {
166 $orderBy = 'cl_collation, cl_to, cl_type, cl_from';
167 }
168
169 $collationConds = [];
170 if ( !$this->force && !$this->targetTable ) {
171 if ( $this->hasOption( 'previous-collation' ) ) {
172 $collationConds['cl_collation'] = $this->getOption( 'previous-collation' );
173 } else {
174 $collationConds = [
175 0 => 'cl_collation != ' . $this->dbr->addQuotes( $this->collationName )
176 ];
177 }
178
179 $count = $this->dbr->estimateRowCount(
180 'categorylinks',
181 '*',
182 $collationConds,
183 __METHOD__
184 );
185 // Improve estimate if feasible
186 if ( $count < 1000000 ) {
187 $count = $this->dbr->newSelectQueryBuilder()
188 ->select( 'COUNT(*)' )
189 ->from( 'categorylinks' )
190 ->where( $collationConds )
191 ->caller( __METHOD__ )->fetchField();
192 }
193 if ( $count == 0 ) {
194 $this->output( "Collations up-to-date.\n" );
195
196 return;
197 }
198 if ( $this->dryRun ) {
199 $this->output( "$count rows would be updated.\n" );
200 } else {
201 $this->output( "Fixing collation for $count rows.\n" );
202 }
203 }
204 $batchConds = [];
205 do {
206 $this->output( "Selecting next $batchSize rows..." );
207
208 // cl_type must be selected as a number for proper paging because
209 // enums suck.
210 if ( $this->dbw->getType() === 'mysql' ) {
211 $clType = 'cl_type+0 AS "cl_type_numeric"';
212 } else {
213 $clType = 'cl_type';
214 }
215 $res = $this->dbw->newSelectQueryBuilder()
216 ->select( [
217 'cl_from', 'cl_to', 'cl_sortkey_prefix', 'cl_collation',
218 'cl_sortkey', $clType, 'cl_timestamp',
219 'page_namespace', 'page_title'
220 ] )
221 ->from( 'categorylinks' )
222 // per T58041
223 ->straightJoin( 'page', null, 'cl_from = page_id' )
224 ->where( $collationConds )
225 ->andWhere( $batchConds )
226 ->limit( $batchSize )
227 ->orderBy( $orderBy )
228 ->caller( __METHOD__ )->fetchResultSet();
229 $this->output( " processing..." );
230
231 if ( $res->numRows() ) {
232 if ( $this->targetTable ) {
233 $this->copyBatch( $res );
234 } else {
235 $this->updateBatch( $res );
236 }
237 $res->seek( $res->numRows() - 1 );
238 $lastRow = $res->fetchObject();
239 $batchConds = [ $this->getBatchCondition( $lastRow, $this->dbw ) ];
240 }
241
242 if ( $this->dryRun ) {
243 $this->output( "{$this->numRowsProcessed} rows would be updated so far.\n" );
244 } else {
245 $this->output( "{$this->numRowsProcessed} done.\n" );
246 }
247 } while ( $res->numRows() == $batchSize );
248
249 if ( !$this->dryRun ) {
250 $this->output( "{$this->numRowsProcessed} rows processed\n" );
251 }
252
253 if ( $this->verboseStats ) {
254 $this->output( "\n" );
255 $this->showSortKeySizeHistogram();
256 }
257 }
258
266 private function getBatchCondition( $row, $dbw ) {
267 if ( $this->hasOption( 'previous-collation' ) ) {
268 $fields = [ 'cl_to', 'cl_type', 'cl_from' ];
269 } else {
270 $fields = [ 'cl_collation', 'cl_to', 'cl_type', 'cl_from' ];
271 }
272 $conds = [];
273 foreach ( $fields as $field ) {
274 if ( $dbw->getType() === 'mysql' && $field === 'cl_type' ) {
275 // Range conditions with enums are weird in mysql
276 // This must be a numeric literal, or it won't work.
277 $value = intval( $row->cl_type_numeric );
278 } else {
279 $value = $row->$field;
280 }
281 $conds[ $field ] = $value;
282 }
283
284 return $dbw->buildComparison( '>', $conds );
285 }
286
292 private function updateBatch( $res ) {
293 if ( !$this->dryRun ) {
294 $this->beginTransaction( $this->dbw, __METHOD__ );
295 }
296 foreach ( $res as $row ) {
297 $title = Title::newFromRow( $row );
298 if ( !$row->cl_collation ) {
299 # This is an old-style row, so the sortkey needs to be
300 # converted.
301 if ( $row->cl_sortkey == $title->getText()
302 || $row->cl_sortkey == $title->getPrefixedText()
303 ) {
304 $prefix = '';
305 } else {
306 # Custom sortkey, use it as a prefix
307 $prefix = $row->cl_sortkey;
308 }
309 } else {
310 $prefix = $row->cl_sortkey_prefix;
311 }
312 # cl_type will be wrong for lots of pages if cl_collation is 0,
313 # so let's update it while we're here.
314 $type = $this->namespaceInfo->getCategoryLinkType( $row->page_namespace );
315 $newSortKey = $this->collation->getSortKey(
316 $title->getCategorySortkey( $prefix ) );
317 $this->updateSortKeySizeHistogram( $newSortKey );
318 // Truncate to 230 bytes to avoid DB error
319 $newSortKey = substr( $newSortKey, 0, 230 );
320
321 if ( $this->dryRun ) {
322 // Add 1 to the count if the sortkey was changed. (Note that this doesn't count changes in
323 // other fields, if any, those usually only happen when upgrading old MediaWikis.)
324 $this->numRowsProcessed += ( $row->cl_sortkey !== $newSortKey );
325 } else {
326 $this->dbw->update(
327 'categorylinks',
328 [
329 'cl_sortkey' => $newSortKey,
330 'cl_sortkey_prefix' => $prefix,
331 'cl_collation' => $this->collationName,
332 'cl_type' => $type,
333 'cl_timestamp = cl_timestamp',
334 ],
335 [ 'cl_from' => $row->cl_from, 'cl_to' => $row->cl_to ],
336 __METHOD__
337 );
338 $this->numRowsProcessed++;
339 }
340 }
341 if ( !$this->dryRun ) {
342 $this->commitTransaction( $this->dbw, __METHOD__ );
343 }
344 }
345
351 private function copyBatch( $res ) {
352 $sortKeyInputs = [];
353 foreach ( $res as $row ) {
354 $title = Title::newFromRow( $row );
355 $sortKeyInputs[] = $title->getCategorySortkey( $row->cl_sortkey_prefix );
356 }
357 $sortKeys = $this->collation->getSortKeys( $sortKeyInputs );
358 $rowsToInsert = [];
359 foreach ( $res as $i => $row ) {
360 if ( !isset( $sortKeys[$i] ) ) {
361 throw new RuntimeException( 'Unable to get sort key' );
362 }
363 $newSortKey = $sortKeys[$i];
364 $this->updateSortKeySizeHistogram( $newSortKey );
365 // Truncate to 230 bytes to avoid DB error
366 $newSortKey = substr( $newSortKey, 0, 230 );
367 $type = $this->namespaceInfo->getCategoryLinkType( $row->page_namespace );
368 $rowsToInsert[] = [
369 'cl_from' => $row->cl_from,
370 'cl_to' => $row->cl_to,
371 'cl_sortkey' => $newSortKey,
372 'cl_sortkey_prefix' => $row->cl_sortkey_prefix,
373 'cl_collation' => $this->collationName,
374 'cl_type' => $type,
375 'cl_timestamp' => $row->cl_timestamp
376 ];
377 }
378 if ( $this->dryRun ) {
379 $this->numRowsProcessed += count( $rowsToInsert );
380 } else {
381 $this->beginTransaction( $this->dbw, __METHOD__ );
382 $this->dbw->insert( $this->targetTable, $rowsToInsert, __METHOD__, [ 'IGNORE' ] );
383 $this->numRowsProcessed += $this->dbw->affectedRows();
384 $this->commitTransaction( $this->dbw, __METHOD__ );
385 }
386 }
387
393 private function updateSortKeySizeHistogram( $key ) {
394 if ( !$this->verboseStats ) {
395 return;
396 }
397 $length = strlen( $key );
398 if ( !isset( $this->sizeHistogram[$length] ) ) {
399 $this->sizeHistogram[$length] = 0;
400 }
401 $this->sizeHistogram[$length]++;
402 }
403
407 private function showSortKeySizeHistogram() {
408 if ( !$this->sizeHistogram ) {
409 return;
410 }
411 $maxLength = max( array_keys( $this->sizeHistogram ) );
412 if ( $maxLength == 0 ) {
413 return;
414 }
415 $numBins = 20;
416 $coarseHistogram = array_fill( 0, $numBins, 0 );
417 $coarseBoundaries = [];
418 $boundary = 0;
419 for ( $i = 0; $i < $numBins - 1; $i++ ) {
420 $boundary += $maxLength / $numBins;
421 $coarseBoundaries[$i] = round( $boundary );
422 }
423 $coarseBoundaries[$numBins - 1] = $maxLength + 1;
424 $raw = '';
425 for ( $i = 0; $i <= $maxLength; $i++ ) {
426 if ( $raw !== '' ) {
427 $raw .= ', ';
428 }
429 $val = $this->sizeHistogram[$i] ?? 0;
430 for ( $coarseIndex = 0; $coarseIndex < $numBins - 1; $coarseIndex++ ) {
431 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
432 if ( $coarseBoundaries[$coarseIndex] > $i ) {
433 $coarseHistogram[$coarseIndex] += $val;
434 break;
435 }
436 }
437 if ( $coarseIndex == $numBins - 1 ) {
438 $coarseHistogram[$coarseIndex] += $val;
439 }
440 $raw .= $val;
441 }
442
443 $this->output( "Sort key size histogram\nRaw data: $raw\n\n" );
444
445 $maxBinVal = max( $coarseHistogram );
446 $scale = (int)( 60 / $maxBinVal );
447 $prevBoundary = 0;
448 for ( $coarseIndex = 0; $coarseIndex < $numBins; $coarseIndex++ ) {
449 $val = $coarseHistogram[$coarseIndex] ?? 0;
450 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
451 $boundary = $coarseBoundaries[$coarseIndex];
452 $this->output( sprintf( "%-10s %-10d |%s\n",
453 $prevBoundary . '-' . ( $boundary - 1 ) . ': ',
454 $val,
455 str_repeat( '*', $scale * $val ) ) );
456 $prevBoundary = $boundary;
457 }
458 }
459}
460
461$maintClass = UpdateCollation::class;
462require_once RUN_MAINTENANCE_IF_MAIN;
getDB()
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
beginTransaction(IDatabase $dbw, $fname)
Begin a transaction on a DB.
commitTransaction(IDatabase $dbw, $fname)
Commit the transaction on a DB handle and wait for replica DBs to catch up.
output( $out, $channel=null)
Throw some output to the user.
hasOption( $name)
Checks to see if a particular option was set.
getServiceContainer()
Returns the main service container.
getBatchSize()
Returns batch size.
addDescription( $text)
Set the description text.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getOption( $name, $default=null)
Get an option, or return the default.
setBatchSize( $s=0)
A class containing constants representing the names of configuration variables.
This is a utility class for dealing with namespaces that encodes all the "magic" behaviors of them ba...
Represents a title within MediaWiki.
Definition Title.php:76
Maintenance script that will find all rows in the categorylinks table whose collation is out-of-date.
execute()
Do the actual work.
__construct()
Default constructor.
$wgCategoryCollation
Config variable stub for the CategoryCollation setting, for use by phpdoc and IDEs.
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:36
Advanced database interface for IDatabase handles that include maintenance methods.
getType()
Get the RDBMS type of the server (e.g.
Result wrapper for grabbing data queried from an IDatabase object.
buildComparison(string $op, array $conds)
Build a condition comparing multiple values, for use with indexes that cover multiple fields,...
const DB_REPLICA
Definition defines.php:26
const DB_PRIMARY
Definition defines.php:28