37 public $sizeHistogram = [];
40 private $numRowsProcessed = 0;
49 private $verboseStats;
55 private $collationName;
63 private bool $normalization =
false;
75 parent::__construct();
78This script will find all rows in the categorylinks table whose collation is
80repopulate cl_sortkey
using the page title and cl_sortkey_prefix. If all
81collations are up-to-date, it will
do nothing.
86 $this->
addOption(
'force',
'Run on all rows, even if the collation is ' .
87 'supposed to be up-to-date.',
false,
false,
'f' );
88 $this->
addOption(
'previous-collation',
'Set the previous value of ' .
89 '$wgCategoryCollation here to speed up this script, especially if your ' .
90 'categorylinks table is large. This will only update rows with that ' .
91 'collation, though, so it may miss out-of-date rows with a different, ' .
92 'even older collation.',
false,
true );
93 $this->
addOption(
'target-collation',
'Set this to the new collation type to ' .
94 'use instead of $wgCategoryCollation. Usually you should not use this, ' .
95 'you should just update $wgCategoryCollation in LocalSettings.php.',
97 $this->
addOption(
'table',
'Table relative to which updates are generated. This ' .
98 'table will be updated in place, unless --target-table is set. Defaults to ' .
99 'categorylinks.',
false,
true );
100 $this->
addOption(
'target-table',
'Copy rows from table into the ' .
101 'specified table instead of updating them in place.',
false,
true );
102 $this->
addOption(
'only-migrate-normalization',
'Only backfill cl_collation_id ' .
103 'field from cl_collation',
false );
104 $this->
addOption(
'remote',
'Use Shellbox to calculate the new sort keys ' .
106 $this->
addOption(
'dry-run',
'Don\'t actually change the collations, just ' .
107 'compile statistics.' );
108 $this->
addOption(
'verbose-stats',
'Show more statistics.' );
114 private function init() {
115 $services = $this->getServiceContainer();
116 $this->namespaceInfo = $services->getNamespaceInfo();
118 $this->getServiceContainer()->getDBLoadBalancer(),
119 $this->getServiceContainer()->getMainWANObjectCache(),
120 LoggerFactory::getInstance(
'SecondaryDataUpdate' ),
126 if ( $this->hasOption(
'target-collation' ) ) {
127 $this->collationName = $this->getOption(
'target-collation' );
129 $this->collationName = $this->
getConfig()->get( MainConfigNames::CategoryCollation );
132 $realCollationName =
'remote-' . $this->collationName;
134 $realCollationName = $this->collationName;
136 $this->collation = $services->getCollationFactory()->makeCollation( $realCollationName );
140 $this->collation->getSortKey(
'MediaWiki' );
142 $this->force = $this->
getOption(
'force' );
143 $this->dryRun = $this->
getOption(
'dry-run' );
144 $this->verboseStats = $this->
getOption(
'verbose-stats' );
147 $this->table = $this->
getOption(
'table',
'categorylinks' );
148 $this->targetTable = $this->
getOption(
'target-table' );
149 $this->normalization = $this->
getOption(
'only-migrate-normalization',
false );
156 if ( $this->normalization ) {
157 $this->runNormalizationMigration();
161 if ( $this->targetTable ) {
162 if ( !$this->dbw->tableExists( $this->targetTable, __METHOD__ ) ) {
163 $this->
output(
"Creating table {$this->targetTable}\n" );
165 'CREATE TABLE ' . $this->dbw->tableName( $this->targetTable ) .
166 ' LIKE ' . $this->dbw->tableName( $this->table ),
172 $collationConds = [];
173 if ( !$this->force && !$this->targetTable ) {
174 if ( $this->
hasOption(
'previous-collation' ) ) {
175 $collationConds[
'collation_name'] = $this->
getOption(
'previous-collation' );
177 $collationConds[] = $this->dbr->expr(
'collation_name',
'!=', $this->collationName );
180 $maxPageId = (int)$this->dbr->newSelectQueryBuilder()
181 ->select(
'MAX(page_id)' )
183 ->caller( __METHOD__ )->fetchField();
186 $this->
output(
"Selecting next $batchSize pages from cl_from = $batchValue... " );
190 if ( $this->dbw->getType() ===
'mysql' ) {
191 $clType =
'cl_type+0 AS "cl_type_numeric"';
195 $res = $this->dbw->newSelectQueryBuilder()
197 'cl_from',
'cl_target_id',
'cl_sortkey_prefix',
'cl_sortkey', $clType,
198 'cl_timestamp',
'collation_name',
'page_namespace',
'page_title'
200 ->from( $this->table )
201 ->join(
'collation',
null,
'cl_collation_id = collation_id' )
203 ->straightJoin(
'page',
null,
'cl_from = page_id' )
204 ->where( $collationConds )
206 $this->dbw->expr(
'cl_from',
'>=', $batchValue )
207 ->and(
'cl_from',
'<', $batchValue + $this->getBatchSize() )
209 ->orderBy(
'cl_from' )
210 ->caller( __METHOD__ )->fetchResultSet();
211 $this->
output(
"processing... " );
214 if ( $this->targetTable ) {
215 $this->copyBatch( $res );
217 $this->updateBatch( $res );
222 if ( $this->dryRun ) {
223 $this->
output(
"{$this->numRowsProcessed} rows would be updated so far.\n" );
225 $this->
output(
"{$this->numRowsProcessed} done.\n" );
227 }
while ( $maxPageId >= $batchValue );
229 if ( !$this->dryRun ) {
230 $this->
output(
"{$this->numRowsProcessed} rows processed\n" );
233 if ( $this->verboseStats ) {
235 $this->showSortKeySizeHistogram();
243 if ( !$this->dryRun ) {
244 $this->beginTransactionRound( __METHOD__ );
246 foreach ( $res as $row ) {
247 $title = Title::newFromRow( $row );
248 if ( !$row->collation_name ) {
249 # This is an old-style row, so the sortkey needs to be
251 if ( $row->cl_sortkey === $title->getText()
252 || $row->cl_sortkey === $title->getPrefixedText()
256 # Custom sortkey, so use it as a prefix
257 $prefix = $row->cl_sortkey;
260 $prefix = $row->cl_sortkey_prefix;
262 # cl_type will be wrong for lots of pages if cl_collation is 0,
263 # so let's update it while we're here.
264 $type = $this->namespaceInfo->getCategoryLinkType( $row->page_namespace );
265 $newSortKey = $this->collation->getSortKey(
266 $title->getCategorySortkey( $prefix ) );
267 $this->updateSortKeySizeHistogram( $newSortKey );
269 $newSortKey = substr( $newSortKey, 0, 230 );
271 if ( $this->dryRun ) {
274 $this->numRowsProcessed += ( $row->cl_sortkey !== $newSortKey );
276 $collationId = $this->collationNameStore->acquireId( $this->collationName );
277 $this->dbw->newUpdateQueryBuilder()
278 ->update( $this->table )
280 'cl_sortkey' => $newSortKey,
281 'cl_sortkey_prefix' => $prefix,
282 'cl_collation_id' => $collationId,
284 'cl_timestamp = cl_timestamp',
286 ->where( [
'cl_from' => $row->cl_from,
'cl_target_id' => $row->cl_target_id ] )
287 ->caller( __METHOD__ )
289 $this->numRowsProcessed++;
292 if ( !$this->dryRun ) {
302 foreach ( $res as $row ) {
303 $title = Title::newFromRow( $row );
304 $sortKeyInputs[] = $title->getCategorySortkey( $row->cl_sortkey_prefix );
306 $sortKeys = $this->collation->getSortKeys( $sortKeyInputs );
308 foreach ( $res as $i => $row ) {
309 if ( !isset( $sortKeys[$i] ) ) {
310 throw new RuntimeException(
'Unable to get sort key' );
312 $newSortKey = $sortKeys[$i];
313 $this->updateSortKeySizeHistogram( $newSortKey );
315 $newSortKey = substr( $newSortKey, 0, 230 );
316 $type = $this->namespaceInfo->getCategoryLinkType( $row->page_namespace );
317 $collationId = $this->collationNameStore->acquireId( $this->collationName );
319 'cl_from' => $row->cl_from,
320 'cl_target_id' => $row->cl_target_id,
321 'cl_sortkey' => $newSortKey,
322 'cl_sortkey_prefix' => $row->cl_sortkey_prefix,
323 'cl_collation_id' => $collationId,
325 'cl_timestamp' => $row->cl_timestamp
328 if ( $this->dryRun ) {
329 $this->numRowsProcessed += count( $rowsToInsert );
332 $this->dbw->newInsertQueryBuilder()
333 ->insertInto( $this->targetTable )
335 ->rows( $rowsToInsert )
336 ->caller( __METHOD__ )->execute();
337 $this->numRowsProcessed += $this->dbw->affectedRows();
345 private function updateSortKeySizeHistogram(
string $key ) {
346 if ( !$this->verboseStats ) {
349 $length = strlen( $key );
350 if ( !isset( $this->sizeHistogram[$length] ) ) {
351 $this->sizeHistogram[$length] = 0;
353 $this->sizeHistogram[$length]++;
359 private function showSortKeySizeHistogram() {
360 if ( !$this->sizeHistogram ) {
363 $maxLength = max( array_keys( $this->sizeHistogram ) );
364 if ( $maxLength === 0 ) {
368 $coarseHistogram = array_fill( 0, $numBins, 0 );
369 $coarseBoundaries = [];
371 for ( $i = 0; $i < $numBins - 1; $i++ ) {
372 $boundary += $maxLength / $numBins;
373 $coarseBoundaries[$i] = round( $boundary );
375 $coarseBoundaries[$numBins - 1] = $maxLength + 1;
377 for ( $i = 0; $i <= $maxLength; $i++ ) {
381 $val = $this->sizeHistogram[$i] ?? 0;
382 for ( $coarseIndex = 0; $coarseIndex < $numBins - 1; $coarseIndex++ ) {
383 if ( $coarseBoundaries[$coarseIndex] > $i ) {
384 $coarseHistogram[$coarseIndex] += $val;
388 if ( $coarseIndex === ( $numBins - 1 ) ) {
389 $coarseHistogram[$coarseIndex] += $val;
394 $this->
output(
"Sort key size histogram\nRaw data: $raw\n\n" );
396 $maxBinVal = max( $coarseHistogram );
397 $scale = (int)( 60 / $maxBinVal );
399 for ( $coarseIndex = 0; $coarseIndex < $numBins; $coarseIndex++ ) {
400 $val = $coarseHistogram[$coarseIndex] ?? 0;
401 $boundary = $coarseBoundaries[$coarseIndex];
403 sprintf(
"%-10s %-10d |%s\n",
404 $prevBoundary .
'-' . ( $boundary - 1 ) .
': ',
406 str_repeat(
'*', $scale * $val )
409 $prevBoundary = $boundary;
413 private function runNormalizationMigration() {
414 if ( !$this->dbw->fieldExists( $this->table,
'cl_collation', __METHOD__ ) ) {
415 $this->
output(
"The cl_collation column appears to already be normalized. Skipping.\n" );
418 if ( !$this->dbw->fieldExists( $this->table,
'cl_collation_id', __METHOD__ ) ) {
419 $this->
output(
"The cl_collation_id column doesn't exist. Run update.php to create it.\n" );
422 if ( !$this->dbw->tableExists(
'collation', __METHOD__ ) ) {
423 $this->
output(
"The collation table doesn't exist. Run update.php to create it.\n" );
427 $maxPageId = (int)$this->dbr->newSelectQueryBuilder()
428 ->select(
'MAX(page_id)' )
430 ->caller( __METHOD__ )->fetchField();
435 $this->
output(
"Selecting next $batchSize pages from cl_from = $batchValue... " );
437 $res = $this->dbw->newSelectQueryBuilder()
438 ->select( [
'cl_collation' ] )
440 ->from( $this->table )
441 ->where( [
'cl_collation_id' => 0 ] )
443 $this->dbw->expr(
'cl_from',
'>=', $batchValue )
444 ->and(
'cl_from',
'<', $batchValue + $this->getBatchSize() )
446 ->caller( __METHOD__ )->fetchResultSet();
447 $this->
output(
"processing... " );
449 if ( $res->
numRows() && !$this->dryRun ) {
450 foreach ( $res as $row ) {
451 $collationName = $row->cl_collation;
452 $collationId = $this->collationNameStore->acquireId( $collationName );
453 $this->dbw->newUpdateQueryBuilder()
454 ->update( $this->table )
455 ->set( [
'cl_collation_id' => $collationId ] )
456 ->where( [
'cl_collation' => $collationName ] )
458 $this->dbw->expr(
'cl_from',
'>=', $batchValue )
459 ->and(
'cl_from',
'<', $batchValue + $this->getBatchSize() )
461 ->caller( __METHOD__ )->execute();
462 $this->numRowsProcessed += $this->dbw->affectedRows();
469 $this->
output(
"{$this->numRowsProcessed} done.\n" );
470 }
while ( $maxPageId >= $batchValue );
472 if ( !$this->dryRun ) {
473 $this->
output(
"{$this->numRowsProcessed} rows processed\n" );