Merge "Print chained exceptions when maintenance script fails."
[lhc/web/wiklou.git] / maintenance / updateCollation.php
1 <?php
2 /**
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.
6 *
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.
11 *
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.
16 *
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
21 *
22 * @file
23 * @ingroup Maintenance
24 * @author Aryeh Gregor (Simetrical)
25 */
26
27 require_once __DIR__ . '/Maintenance.php';
28
29 use MediaWiki\MediaWikiServices;
30 use Wikimedia\Rdbms\IDatabase;
31
32 /**
33 * Maintenance script that will find all rows in the categorylinks table
34 * whose collation is out-of-date.
35 *
36 * @ingroup Maintenance
37 */
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
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
242 /**
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
247 * @return string
248 */
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
289 function showSortKeySizeHistogram() {
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
338 $maintClass = UpdateCollation::class;
339 require_once RUN_MAINTENANCE_IF_MAIN;