updateCollation.php 10 KB

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