Merge "Allow easy suppression of multiple deleted revs"
[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 /**
30 * Maintenance script that will find all rows in the categorylinks table
31 * whose collation is out-of-date.
32 *
33 * @ingroup Maintenance
34 */
35 class UpdateCollation extends Maintenance {
36 const BATCH_SIZE = 10000; // Number of rows to process in one batch
37 const SYNC_INTERVAL = 20; // Wait for slaves after this many batches
38
39 public $sizeHistogram = array();
40
41 public function __construct() {
42 parent::__construct();
43
44 global $wgCategoryCollation;
45 $this->addDescription( <<<TEXT
46 This script will find all rows in the categorylinks table whose collation is
47 out-of-date (cl_collation != '$wgCategoryCollation') and repopulate cl_sortkey
48 using the page title and cl_sortkey_prefix. If all collations are
49 up-to-date, it will do nothing.
50 TEXT
51 );
52
53 $this->addOption( 'force', 'Run on all rows, even if the collation is ' .
54 'supposed to be up-to-date.' );
55 $this->addOption( 'previous-collation', 'Set the previous value of ' .
56 '$wgCategoryCollation here to speed up this script, especially if your ' .
57 'categorylinks table is large. This will only update rows with that ' .
58 'collation, though, so it may miss out-of-date rows with a different, ' .
59 'even older collation.', false, true );
60 $this->addOption( 'target-collation', 'Set this to the new collation type to ' .
61 'use instead of $wgCategoryCollation. Usually you should not use this, ' .
62 'you should just update $wgCategoryCollation in LocalSettings.php.',
63 false, true );
64 $this->addOption( 'dry-run', 'Don\'t actually change the collations, just ' .
65 'compile statistics.' );
66 $this->addOption( 'verbose-stats', 'Show more statistics.' );
67 }
68
69 public function execute() {
70 global $wgCategoryCollation;
71
72 $dbw = $this->getDB( DB_MASTER );
73 $force = $this->getOption( 'force' );
74 $dryRun = $this->getOption( 'dry-run' );
75 $verboseStats = $this->getOption( 'verbose-stats' );
76 if ( $this->hasOption( 'target-collation' ) ) {
77 $collationName = $this->getOption( 'target-collation' );
78 $collation = Collation::factory( $collationName );
79 } else {
80 $collationName = $wgCategoryCollation;
81 $collation = Collation::singleton();
82 }
83
84 // Collation sanity check: in some cases the constructor will work,
85 // but this will raise an exception, breaking all category pages
86 $collation->getFirstLetter( 'MediaWiki' );
87
88 $options = array(
89 'LIMIT' => self::BATCH_SIZE,
90 'ORDER BY' => 'cl_from, cl_to',
91 'STRAIGHT_JOIN',
92 );
93
94 if ( $force || $dryRun ) {
95 $collationConds = array();
96 } else {
97 if ( $this->hasOption( 'previous-collation' ) ) {
98 $collationConds['cl_collation'] = $this->getOption( 'previous-collation' );
99 } else {
100 $collationConds = array( 0 =>
101 'cl_collation != ' . $dbw->addQuotes( $collationName )
102 );
103 }
104
105 $count = $dbw->estimateRowCount(
106 'categorylinks',
107 '*',
108 $collationConds,
109 __METHOD__
110 );
111 // Improve estimate if feasible
112 if ( $count < 1000000 ) {
113 $count = $dbw->selectField(
114 'categorylinks',
115 'COUNT(*)',
116 $collationConds,
117 __METHOD__
118 );
119 }
120 if ( $count == 0 ) {
121 $this->output( "Collations up-to-date.\n" );
122
123 return;
124 }
125 $this->output( "Fixing collation for $count rows.\n" );
126 }
127
128 $count = 0;
129 $batchCount = 0;
130 $batchConds = array();
131 do {
132 $this->output( "Selecting next " . self::BATCH_SIZE . " rows..." );
133 $res = $dbw->select(
134 array( 'categorylinks', 'page' ),
135 array( 'cl_from', 'cl_to', 'cl_sortkey_prefix', 'cl_collation',
136 'cl_sortkey', 'page_namespace', 'page_title'
137 ),
138 array_merge( $collationConds, $batchConds, array( 'cl_from = page_id' ) ),
139 __METHOD__,
140 $options
141 );
142 $this->output( " processing..." );
143
144 if ( !$dryRun ) {
145 $this->beginTransaction( $dbw, __METHOD__ );
146 }
147 foreach ( $res as $row ) {
148 $title = Title::newFromRow( $row );
149 if ( !$row->cl_collation ) {
150 # This is an old-style row, so the sortkey needs to be
151 # converted.
152 if ( $row->cl_sortkey == $title->getText()
153 || $row->cl_sortkey == $title->getPrefixedText()
154 ) {
155 $prefix = '';
156 } else {
157 # Custom sortkey, use it as a prefix
158 $prefix = $row->cl_sortkey;
159 }
160 } else {
161 $prefix = $row->cl_sortkey_prefix;
162 }
163 # cl_type will be wrong for lots of pages if cl_collation is 0,
164 # so let's update it while we're here.
165 if ( $title->getNamespace() == NS_CATEGORY ) {
166 $type = 'subcat';
167 } elseif ( $title->getNamespace() == NS_FILE ) {
168 $type = 'file';
169 } else {
170 $type = 'page';
171 }
172 $newSortKey = $collation->getSortKey(
173 $title->getCategorySortkey( $prefix ) );
174 if ( $verboseStats ) {
175 $this->updateSortKeySizeHistogram( $newSortKey );
176 }
177
178 if ( !$dryRun ) {
179 $dbw->update(
180 'categorylinks',
181 array(
182 'cl_sortkey' => $newSortKey,
183 'cl_sortkey_prefix' => $prefix,
184 'cl_collation' => $collationName,
185 'cl_type' => $type,
186 'cl_timestamp = cl_timestamp',
187 ),
188 array( 'cl_from' => $row->cl_from, 'cl_to' => $row->cl_to ),
189 __METHOD__
190 );
191 }
192 if ( $row ) {
193 $batchConds = array( $this->getBatchCondition( $row, $dbw ) );
194 }
195 }
196 if ( !$dryRun ) {
197 $this->commitTransaction( $dbw, __METHOD__ );
198 }
199
200 $count += $res->numRows();
201 $this->output( "$count done.\n" );
202
203 if ( !$dryRun && ++$batchCount % self::SYNC_INTERVAL == 0 ) {
204 $this->output( "Waiting for slaves ... " );
205 wfWaitForSlaves();
206 $this->output( "done\n" );
207 }
208 } while ( $res->numRows() == self::BATCH_SIZE );
209
210 $this->output( "$count rows processed\n" );
211
212 if ( $verboseStats ) {
213 $this->output( "\n" );
214 $this->showSortKeySizeHistogram();
215 }
216 }
217
218 /**
219 * Return an SQL expression selecting rows which sort above the given row,
220 * assuming an ordering of cl_from, cl_to
221 * @param stdClass $row
222 * @param DatabaseBase $dbw
223 * @return string
224 */
225 function getBatchCondition( $row, $dbw ) {
226 $fields = array( 'cl_from', 'cl_to' );
227 $first = true;
228 $cond = false;
229 $prefix = false;
230 foreach ( $fields as $field ) {
231 $encValue = $dbw->addQuotes( $row->$field );
232 $inequality = "$field > $encValue";
233 $equality = "$field = $encValue";
234 if ( $first ) {
235 $cond = $inequality;
236 $prefix = $equality;
237 $first = false;
238 } else {
239 $cond .= " OR ($prefix AND $inequality)";
240 $prefix .= " AND $equality";
241 }
242 }
243
244 return $cond;
245 }
246
247 function updateSortKeySizeHistogram( $key ) {
248 $length = strlen( $key );
249 if ( !isset( $this->sizeHistogram[$length] ) ) {
250 $this->sizeHistogram[$length] = 0;
251 }
252 $this->sizeHistogram[$length]++;
253 }
254
255 function showSortKeySizeHistogram() {
256 $maxLength = max( array_keys( $this->sizeHistogram ) );
257 if ( $maxLength == 0 ) {
258 return;
259 }
260 $numBins = 20;
261 $coarseHistogram = array_fill( 0, $numBins, 0 );
262 $coarseBoundaries = array();
263 $boundary = 0;
264 for ( $i = 0; $i < $numBins - 1; $i++ ) {
265 $boundary += $maxLength / $numBins;
266 $coarseBoundaries[$i] = round( $boundary );
267 }
268 $coarseBoundaries[$numBins - 1] = $maxLength + 1;
269 $raw = '';
270 for ( $i = 0; $i <= $maxLength; $i++ ) {
271 if ( $raw !== '' ) {
272 $raw .= ', ';
273 }
274 if ( !isset( $this->sizeHistogram[$i] ) ) {
275 $val = 0;
276 } else {
277 $val = $this->sizeHistogram[$i];
278 }
279 for ( $coarseIndex = 0; $coarseIndex < $numBins - 1; $coarseIndex++ ) {
280 if ( $coarseBoundaries[$coarseIndex] > $i ) {
281 $coarseHistogram[$coarseIndex] += $val;
282 break;
283 }
284 }
285 if ( $coarseIndex == $numBins - 1 ) {
286 $coarseHistogram[$coarseIndex] += $val;
287 }
288 $raw .= $val;
289 }
290
291 $this->output( "Sort key size histogram\nRaw data: $raw\n\n" );
292
293 $maxBinVal = max( $coarseHistogram );
294 $scale = 60 / $maxBinVal;
295 $prevBoundary = 0;
296 for ( $coarseIndex = 0; $coarseIndex < $numBins; $coarseIndex++ ) {
297 if ( !isset( $coarseHistogram[$coarseIndex] ) ) {
298 $val = 0;
299 } else {
300 $val = $coarseHistogram[$coarseIndex];
301 }
302 $boundary = $coarseBoundaries[$coarseIndex];
303 $this->output( sprintf( "%-10s %-10d |%s\n",
304 $prevBoundary . '-' . ( $boundary - 1 ) . ': ',
305 $val,
306 str_repeat( '*', $scale * $val ) ) );
307 $prevBoundary = $boundary;
308 }
309 }
310 }
311
312 $maintClass = "UpdateCollation";
313 require_once RUN_MAINTENANCE_IF_MAIN;