Merge "build: Update grunt-karma from 2.0.0 to 3.0.0"
[lhc/web/wiklou.git] / maintenance / populateContentTables.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @ingroup Maintenance
20 */
21
22 use MediaWiki\MediaWikiServices;
23 use MediaWiki\Storage\NameTableStore;
24 use MediaWiki\Storage\SqlBlobStore;
25 use Wikimedia\Assert\Assert;
26 use Wikimedia\Rdbms\IDatabase;
27 use Wikimedia\Rdbms\ResultWrapper;
28
29 require_once __DIR__ . '/Maintenance.php';
30
31 /**
32 * Populate the content and slot tables.
33 * @since 1.32
34 */
35 class PopulateContentTables extends Maintenance {
36
37 /** @var IDatabase */
38 private $dbw;
39
40 /** @var NameTableStore */
41 private $contentModelStore;
42
43 /** @var int */
44 private $mainRoleId;
45
46 /** @var array|null Map "{$modelId}:{$address}" to content_id */
47 private $contentRowMap = null;
48
49 private $count = 0, $totalCount = 0;
50
51 public function __construct() {
52 parent::__construct();
53
54 $this->addDescription( 'Populate content and slot tables' );
55 $this->addOption( 'table', 'revision or archive table, or `all` to populate both', false,
56 true );
57 $this->addOption( 'reuse-content',
58 'Reuse content table rows when the address and model are the same. '
59 . 'This will increase the script\'s time and memory usage, perhaps significantly.',
60 false, false );
61 $this->addOption( 'start-revision', 'The rev_id to start at', false, true );
62 $this->addOption( 'start-archive', 'The ar_rev_id to start at', false, true );
63 $this->setBatchSize( 500 );
64 }
65
66 private function initServices() {
67 $this->dbw = $this->getDB( DB_MASTER );
68 $this->contentModelStore = MediaWikiServices::getInstance()->getContentModelStore();
69 $this->mainRoleId = MediaWikiServices::getInstance()->getSlotRoleStore()->acquireId( 'main' );
70 }
71
72 public function execute() {
73 global $wgMultiContentRevisionSchemaMigrationStage;
74
75 $t0 = microtime( true );
76
77 if ( ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) === 0 ) {
78 $this->writeln(
79 '...cannot update while \$wgMultiContentRevisionSchemaMigrationStage '
80 . 'does not have the SCHEMA_COMPAT_WRITE_NEW bit set.'
81 );
82 return false;
83 }
84
85 $this->initServices();
86
87 if ( $this->getOption( 'reuse-content', false ) ) {
88 $this->loadContentMap();
89 }
90
91 foreach ( $this->getTables() as $table ) {
92 $this->populateTable( $table );
93 }
94
95 $elapsed = microtime( true ) - $t0;
96 $this->writeln( "Done. Processed $this->totalCount rows in $elapsed seconds" );
97 return true;
98 }
99
100 /**
101 * @return string[]
102 */
103 private function getTables() {
104 $table = $this->getOption( 'table', 'all' );
105 $validTableOptions = [ 'all', 'revision', 'archive' ];
106
107 if ( !in_array( $table, $validTableOptions ) ) {
108 $this->fatalError( 'Invalid table. Must be either `revision` or `archive` or `all`' );
109 }
110
111 if ( $table === 'all' ) {
112 $tables = [ 'revision', 'archive' ];
113 } else {
114 $tables = [ $table ];
115 }
116
117 return $tables;
118 }
119
120 private function loadContentMap() {
121 $t0 = microtime( true );
122 $this->writeln( "Loading existing content table rows..." );
123 $this->contentRowMap = [];
124 $dbr = $this->getDB( DB_REPLICA );
125 $from = false;
126 while ( true ) {
127 $res = $dbr->select(
128 'content',
129 [ 'content_id', 'content_address', 'content_model' ],
130 $from ? "content_id > $from" : '',
131 __METHOD__,
132 [ 'ORDER BY' => 'content_id', 'LIMIT' => $this->getBatchSize() ]
133 );
134 if ( !$res || !$res->numRows() ) {
135 break;
136 }
137 foreach ( $res as $row ) {
138 $from = $row->content_id;
139 $this->contentRowMap["{$row->content_model}:{$row->content_address}"] = $row->content_id;
140 }
141 }
142 $elapsed = microtime( true ) - $t0;
143 $this->writeln( "Loaded " . count( $this->contentRowMap ) . " rows in $elapsed seconds" );
144 }
145
146 /**
147 * @param string $table
148 */
149 private function populateTable( $table ) {
150 $t0 = microtime( true );
151 $this->count = 0;
152 $this->writeln( "Populating $table..." );
153
154 if ( $table === 'revision' ) {
155 $idField = 'rev_id';
156 $tables = [ 'revision', 'slots', 'page' ];
157 $fields = [
158 'rev_id',
159 'len' => 'rev_len',
160 'sha1' => 'rev_sha1',
161 'text_id' => 'rev_text_id',
162 'content_model' => 'rev_content_model',
163 'namespace' => 'page_namespace',
164 'title' => 'page_title',
165 ];
166 $joins = [
167 'slots' => [ 'LEFT JOIN', 'rev_id=slot_revision_id' ],
168 'page' => [ 'LEFT JOIN', 'rev_page=page_id' ],
169 ];
170 $startOption = 'start-revision';
171 } else {
172 $idField = 'ar_rev_id';
173 $tables = [ 'archive', 'slots' ];
174 $fields = [
175 'rev_id' => 'ar_rev_id',
176 'len' => 'ar_len',
177 'sha1' => 'ar_sha1',
178 'text_id' => 'ar_text_id',
179 'content_model' => 'ar_content_model',
180 'namespace' => 'ar_namespace',
181 'title' => 'ar_title',
182 ];
183 $joins = [
184 'slots' => [ 'LEFT JOIN', 'ar_rev_id=slot_revision_id' ],
185 ];
186 $startOption = 'start-archive';
187 }
188
189 $minmax = $this->dbw->selectRow(
190 $table,
191 [ 'min' => "MIN( $idField )", 'max' => "MAX( $idField )" ],
192 '',
193 __METHOD__
194 );
195 if ( $this->hasOption( $startOption ) ) {
196 $minmax->min = (int)$this->getOption( $startOption );
197 }
198 if ( !$minmax || !is_numeric( $minmax->min ) || !is_numeric( $minmax->max ) ) {
199 // No rows?
200 $minmax = (object)[ 'min' => 1, 'max' => 0 ];
201 }
202
203 $batchSize = $this->getBatchSize();
204
205 for ( $startId = $minmax->min; $startId <= $minmax->max; $startId += $batchSize ) {
206 $endId = min( $startId + $batchSize - 1, $minmax->max );
207 $rows = $this->dbw->select(
208 $tables,
209 $fields,
210 [
211 "$idField >= $startId",
212 "$idField <= $endId",
213 'slot_revision_id IS NULL',
214 ],
215 __METHOD__,
216 [ 'ORDER BY' => 'rev_id' ],
217 $joins
218 );
219 if ( $rows->numRows() !== 0 ) {
220 $this->populateContentTablesForRowBatch( $rows, $startId, $table );
221 }
222
223 $elapsed = microtime( true ) - $t0;
224 $this->writeln(
225 "... $table processed up to revision id $endId of {$minmax->max}"
226 . " ($this->count rows in $elapsed seconds)"
227 );
228 }
229
230 $elapsed = microtime( true ) - $t0;
231 $this->writeln( "Done populating $table table. Processed $this->count rows in $elapsed seconds" );
232 }
233
234 /**
235 * @param ResultWrapper $rows
236 * @param int $startId
237 * @param string $table
238 * @return int|null
239 */
240 private function populateContentTablesForRowBatch( ResultWrapper $rows, $startId, $table ) {
241 $this->beginTransaction( $this->dbw, __METHOD__ );
242
243 if ( $this->contentRowMap === null ) {
244 $map = [];
245 } else {
246 $map = &$this->contentRowMap;
247 }
248 $contentKeys = [];
249
250 try {
251 // Step 1: Figure out content rows needing insertion.
252 $contentRows = [];
253 foreach ( $rows as $row ) {
254 $revisionId = $row->rev_id;
255
256 Assert::invariant( $revisionId !== null, 'rev_id must not be null' );
257
258 $modelId = $this->contentModelStore->acquireId( $this->getContentModel( $row ) );
259 $address = SqlBlobStore::makeAddressFromTextId( $row->text_id );
260
261 $key = "{$modelId}:{$address}";
262 $contentKeys[$revisionId] = $key;
263
264 if ( !isset( $map[$key] ) ) {
265 $map[$key] = false;
266 $contentRows[] = [
267 'content_size' => (int)$row->len,
268 'content_sha1' => $row->sha1,
269 'content_model' => $modelId,
270 'content_address' => $address,
271 ];
272 }
273 }
274
275 // Step 2: Insert them, then read them back in for use in the next step.
276 if ( $contentRows ) {
277 $id = $this->dbw->selectField( 'content', 'MAX(content_id)', '', __METHOD__ );
278 $this->dbw->insert( 'content', $contentRows, __METHOD__ );
279 $res = $this->dbw->select(
280 'content',
281 [ 'content_id', 'content_model', 'content_address' ],
282 'content_id > ' . (int)$id,
283 __METHOD__
284 );
285 foreach ( $res as $row ) {
286 $key = $row->content_model . ':' . $row->content_address;
287 $map[$key] = $row->content_id;
288 }
289 }
290
291 // Step 3: Insert the slot rows.
292 $slotRows = [];
293 foreach ( $rows as $row ) {
294 $revisionId = $row->rev_id;
295 $contentId = $map[$contentKeys[$revisionId]] ?? false;
296 if ( $contentId === false ) {
297 throw new \RuntimeException( "Content row for $revisionId not found after content insert" );
298 }
299 $slotRows[] = [
300 'slot_revision_id' => $revisionId,
301 'slot_role_id' => $this->mainRoleId,
302 'slot_content_id' => $contentId,
303 // There's no way to really know the previous revision, so assume no inheriting.
304 // rev_parent_id can get changed on undeletions, and deletions can screw up
305 // rev_timestamp ordering.
306 'slot_origin' => $revisionId,
307 ];
308 }
309 $this->dbw->insert( 'slots', $slotRows, __METHOD__ );
310 $this->count += count( $slotRows );
311 $this->totalCount += count( $slotRows );
312 } catch ( \Exception $e ) {
313 $this->rollbackTransaction( $this->dbw, __METHOD__ );
314 $this->fatalError( "Failed to populate content table $table row batch starting at $startId "
315 . "due to exception: " . $e->__toString() );
316 }
317
318 $this->commitTransaction( $this->dbw, __METHOD__ );
319 }
320
321 /**
322 * @param \stdClass $row
323 * @return string
324 */
325 private function getContentModel( $row ) {
326 if ( isset( $row->content_model ) ) {
327 return $row->content_model;
328 }
329
330 $title = Title::makeTitle( $row->namespace, $row->title );
331
332 return ContentHandler::getDefaultModelFor( $title );
333 }
334
335 /**
336 * @param string $msg
337 */
338 private function writeln( $msg ) {
339 $this->output( "$msg\n" );
340 }
341 }
342
343 $maintClass = 'PopulateContentTables';
344 require_once RUN_MAINTENANCE_IF_MAIN;