3 * Find all rows in the categorylinks table whose collation is out-of-date
4 * (cl_collation != $wgCategoryCollation) and repopulate cl_sortkey
5 * using the page title and cl_sortkey_prefix.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
23 * @ingroup Maintenance
24 * @author Aryeh Gregor (Simetrical)
27 require_once __DIR__
. '/Maintenance.php';
29 use MediaWiki\MediaWikiServices
;
30 use Wikimedia\Rdbms\IDatabase
;
33 * Maintenance script that will find all rows in the categorylinks table
34 * whose collation is out-of-date.
36 * @ingroup Maintenance
38 class UpdateCollation
extends Maintenance
{
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
42 public $sizeHistogram = [];
44 public function __construct() {
45 parent
::__construct();
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.
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.',
67 $this->addOption( 'dry-run', 'Don\'t actually change the collations, just ' .
68 'compile statistics.' );
69 $this->addOption( 'verbose-stats', 'Show more statistics.' );
72 public function execute() {
73 global $wgCategoryCollation;
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 );
84 $collationName = $wgCategoryCollation;
85 $collation = Collation
::singleton();
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' );
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';
99 $orderBy = 'cl_collation, cl_to, cl_type, cl_from';
102 'LIMIT' => self
::BATCH_SIZE
,
103 'ORDER BY' => $orderBy,
104 'STRAIGHT_JOIN' // per T58041
108 $collationConds = [];
110 if ( $this->hasOption( 'previous-collation' ) ) {
111 $collationConds['cl_collation'] = $this->getOption( 'previous-collation' );
113 $collationConds = [ 0 =>
114 'cl_collation != ' . $dbw->addQuotes( $collationName )
118 $count = $dbr->estimateRowCount(
124 // Improve estimate if feasible
125 if ( $count < 1000000 ) {
126 $count = $dbr->selectField(
134 $this->output( "Collations up-to-date.\n" );
139 $this->output( "$count rows would be updated.\n" );
141 $this->output( "Fixing collation for $count rows.\n" );
148 $this->output( "Selecting next " . self
::BATCH_SIZE
. " rows..." );
150 // cl_type must be selected as a number for proper paging because
152 if ( $dbw->getType() === 'mysql' ) {
153 $clType = 'cl_type+0 AS "cl_type_numeric"';
158 [ 'categorylinks', 'page' ],
159 [ 'cl_from', 'cl_to', 'cl_sortkey_prefix', 'cl_collation',
160 'cl_sortkey', $clType,
161 'page_namespace', 'page_title'
163 array_merge( $collationConds, $batchConds, [ 'cl_from = page_id' ] ),
167 $this->output( " processing..." );
170 $this->beginTransaction( $dbw, __METHOD__
);
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
177 if ( $row->cl_sortkey
== $title->getText()
178 ||
$row->cl_sortkey
== $title->getPrefixedText()
182 # Custom sortkey, use it as a prefix
183 $prefix = $row->cl_sortkey
;
186 $prefix = $row->cl_sortkey_prefix
;
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 );
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 );
206 'cl_sortkey' => $newSortKey,
207 'cl_sortkey_prefix' => $prefix,
208 'cl_collation' => $collationName,
210 'cl_timestamp = cl_timestamp',
212 [ 'cl_from' => $row->cl_from
, 'cl_to' => $row->cl_to
],
218 $batchConds = [ $this->getBatchCondition( $row, $dbw ) ];
222 $this->commitTransaction( $dbw, __METHOD__
);
226 $this->output( "$count rows would be updated so far.\n" );
228 $this->output( "$count done.\n" );
230 } while ( $res->numRows() == self
::BATCH_SIZE
);
233 $this->output( "$count rows processed\n" );
236 if ( $verboseStats ) {
237 $this->output( "\n" );
238 $this->showSortKeySizeHistogram();
243 * Return an SQL expression selecting rows which sort above the given row,
244 * assuming an ordering of cl_collation, cl_to, cl_type, cl_from
245 * @param stdClass $row
246 * @param IDatabase $dbw
249 function getBatchCondition( $row, $dbw ) {
250 if ( $this->hasOption( 'previous-collation' ) ) {
251 $fields = [ 'cl_to', 'cl_type', 'cl_from' ];
253 $fields = [ 'cl_collation', 'cl_to', 'cl_type', 'cl_from' ];
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
);
264 $encValue = $dbw->addQuotes( $row->$field );
266 $inequality = "$field > $encValue";
267 $equality = "$field = $encValue";
273 $cond .= " OR ($prefix AND $inequality)";
274 $prefix .= " AND $equality";
281 function updateSortKeySizeHistogram( $key ) {
282 $length = strlen( $key );
283 if ( !isset( $this->sizeHistogram
[$length] ) ) {
284 $this->sizeHistogram
[$length] = 0;
286 $this->sizeHistogram
[$length]++
;
289 function showSortKeySizeHistogram() {
290 $maxLength = max( array_keys( $this->sizeHistogram
) );
291 if ( $maxLength == 0 ) {
295 $coarseHistogram = array_fill( 0, $numBins, 0 );
296 $coarseBoundaries = [];
298 for ( $i = 0; $i < $numBins - 1; $i++
) {
299 $boundary +
= $maxLength / $numBins;
300 $coarseBoundaries[$i] = round( $boundary );
302 $coarseBoundaries[$numBins - 1] = $maxLength +
1;
304 for ( $i = 0; $i <= $maxLength; $i++
) {
308 $val = $this->sizeHistogram
[$i] ??
0;
309 for ( $coarseIndex = 0; $coarseIndex < $numBins - 1; $coarseIndex++
) {
310 if ( $coarseBoundaries[$coarseIndex] > $i ) {
311 $coarseHistogram[$coarseIndex] +
= $val;
315 if ( $coarseIndex == $numBins - 1 ) {
316 $coarseHistogram[$coarseIndex] +
= $val;
321 $this->output( "Sort key size histogram\nRaw data: $raw\n\n" );
323 $maxBinVal = max( $coarseHistogram );
324 $scale = 60 / $maxBinVal;
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 ) . ': ',
332 str_repeat( '*', $scale * $val ) ) );
333 $prevBoundary = $boundary;
338 $maintClass = UpdateCollation
::class;
339 require_once RUN_MAINTENANCE_IF_MAIN
;