Merge "Fix 'Tags' padding to keep it farther from the edge and document the source...
[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->setBatchSize( 500 );
62 }
63
64 private function initServices() {
65 $this->dbw = $this->getDB( DB_MASTER );
66 $this->contentModelStore = MediaWikiServices::getInstance()->getContentModelStore();
67 $this->mainRoleId = MediaWikiServices::getInstance()->getSlotRoleStore()->acquireId( 'main' );
68 }
69
70 public function execute() {
71 global $wgMultiContentRevisionSchemaMigrationStage;
72
73 $t0 = microtime( true );
74
75 if ( $wgMultiContentRevisionSchemaMigrationStage < MIGRATION_WRITE_BOTH ) {
76 $this->writeln(
77 "...cannot update while \$wgMultiContentRevisionSchemaMigrationStage < MIGRATION_WRITE_BOTH"
78 );
79 return false;
80 }
81
82 $this->initServices();
83
84 if ( $this->getOption( 'reuse-content', false ) ) {
85 $this->loadContentMap();
86 }
87
88 foreach ( $this->getTables() as $table ) {
89 $this->populateTable( $table );
90 }
91
92 $elapsed = microtime( true ) - $t0;
93 $this->writeln( "Done. Processed $this->totalCount rows in $elapsed seconds" );
94 }
95
96 /**
97 * @return string[]
98 */
99 private function getTables() {
100 $table = $this->getOption( 'table', 'all' );
101 $validTableOptions = [ 'all', 'revision', 'archive' ];
102
103 if ( !in_array( $table, $validTableOptions ) ) {
104 $this->fatalError( 'Invalid table. Must be either `revision` or `archive` or `all`' );
105 }
106
107 if ( $table === 'all' ) {
108 $tables = [ 'revision', 'archive' ];
109 } else {
110 $tables = [ $table ];
111 }
112
113 return $tables;
114 }
115
116 private function loadContentMap() {
117 $t0 = microtime( true );
118 $this->writeln( "Loading existing content table rows..." );
119 $this->contentRowMap = [];
120 $dbr = $this->getDB( DB_REPLICA );
121 $from = false;
122 while ( true ) {
123 $res = $dbr->select(
124 'content',
125 [ 'content_id', 'content_address', 'content_model' ],
126 $from ? "content_id > $from" : '',
127 __METHOD__,
128 [ 'ORDER BY' => 'content_id', 'LIMIT' => $this->getBatchSize() ]
129 );
130 if ( !$res || !$res->numRows() ) {
131 break;
132 }
133 foreach ( $res as $row ) {
134 $from = $row->content_id;
135 $this->contentRowMap["{$row->content_model}:{$row->content_address}"] = $row->content_id;
136 }
137 }
138 $elapsed = microtime( true ) - $t0;
139 $this->writeln( "Loaded " . count( $this->contentRowMap ) . " rows in $elapsed seconds" );
140 }
141
142 /**
143 * @param string $table
144 */
145 private function populateTable( $table ) {
146 $t0 = microtime( true );
147 $this->count = 0;
148 $this->writeln( "Populating $table..." );
149
150 if ( $table === 'revision' ) {
151 $idField = 'rev_id';
152 $tables = [ 'revision', 'slots', 'page' ];
153 $fields = [
154 'rev_id',
155 'len' => 'rev_len',
156 'sha1' => 'rev_sha1',
157 'text_id' => 'rev_text_id',
158 'content_model' => 'rev_content_model',
159 'namespace' => 'page_namespace',
160 'title' => 'page_title',
161 ];
162 $joins = [
163 'slots' => [ 'LEFT JOIN', 'rev_id=slot_revision_id' ],
164 'page' => [ 'LEFT JOIN', 'rev_page=page_id' ],
165 ];
166 } else {
167 $idField = 'ar_rev_id';
168 $tables = [ 'archive', 'slots' ];
169 $fields = [
170 'rev_id' => 'ar_rev_id',
171 'len' => 'ar_len',
172 'sha1' => 'ar_sha1',
173 'text_id' => 'ar_text_id',
174 'content_model' => 'ar_content_model',
175 'namespace' => 'ar_namespace',
176 'title' => 'ar_title',
177 ];
178 $joins = [
179 'slots' => [ 'LEFT JOIN', 'ar_rev_id=slot_revision_id' ],
180 ];
181 }
182
183 $minmax = $this->dbw->selectRow(
184 $table,
185 [ 'min' => "MIN( $idField )", 'max' => "MAX( $idField )" ],
186 '',
187 __METHOD__
188 );
189 $batchSize = $this->getBatchSize();
190
191 for ( $startId = $minmax->min; $startId <= $minmax->max; $startId += $batchSize ) {
192 $endId = min( $startId + $batchSize - 1, $minmax->max );
193 $rows = $this->dbw->select(
194 $tables,
195 $fields,
196 [
197 "$idField >= $startId",
198 "$idField <= $endId",
199 'slot_revision_id IS NULL',
200 ],
201 __METHOD__,
202 [ 'ORDER BY' => 'rev_id' ],
203 $joins
204 );
205 if ( $rows->numRows() !== 0 ) {
206 $this->populateContentTablesForRowBatch( $rows, $startId, $table );
207 }
208
209 $elapsed = microtime( true ) - $t0;
210 $this->writeln(
211 "... $table processed up to revision id $endId of {$minmax->max}"
212 . " ($this->count rows in $elapsed seconds)"
213 );
214 }
215
216 $elapsed = microtime( true ) - $t0;
217 $this->writeln( "Done populating $table table. Processed $this->count rows in $elapsed seconds" );
218 }
219
220 /**
221 * @param ResultWrapper $rows
222 * @param int $startId
223 * @param string $table
224 * @return int|null
225 */
226 private function populateContentTablesForRowBatch( ResultWrapper $rows, $startId, $table ) {
227 $this->beginTransaction( $this->dbw, __METHOD__ );
228
229 if ( $this->contentRowMap === null ) {
230 $map = [];
231 } else {
232 $map = &$this->contentRowMap;
233 }
234 $contentKeys = [];
235
236 try {
237 // Step 1: Figure out content rows needing insertion.
238 $contentRows = [];
239 foreach ( $rows as $row ) {
240 $revisionId = $row->rev_id;
241
242 Assert::invariant( $revisionId !== null, 'rev_id must not be null' );
243
244 $modelId = $this->contentModelStore->acquireId( $this->getContentModel( $row ) );
245 $address = SqlBlobStore::makeAddressFromTextId( $row->text_id );
246
247 $key = "{$modelId}:{$address}";
248 $contentKeys[$revisionId] = $key;
249
250 if ( !isset( $map[$key] ) ) {
251 $map[$key] = false;
252 $contentRows[] = [
253 'content_size' => (int)$row->len,
254 'content_sha1' => $row->sha1,
255 'content_model' => $modelId,
256 'content_address' => $address,
257 ];
258 }
259 }
260
261 // Step 2: Insert them, then read them back in for use in the next step.
262 if ( $contentRows ) {
263 $id = $this->dbw->selectField( 'content', 'MAX(content_id)', '', __METHOD__ );
264 $this->dbw->insert( 'content', $contentRows, __METHOD__ );
265 $res = $this->dbw->select(
266 'content',
267 [ 'content_id', 'content_model', 'content_address' ],
268 'content_id > ' . (int)$id,
269 __METHOD__
270 );
271 foreach ( $res as $row ) {
272 $key = $row->content_model . ':' . $row->content_address;
273 $map[$key] = $row->content_id;
274 }
275 }
276
277 // Step 3: Insert the slot rows.
278 $slotRows = [];
279 foreach ( $rows as $row ) {
280 $revisionId = $row->rev_id;
281 $contentId = $map[$contentKeys[$revisionId]] ?? false;
282 if ( $contentId === false ) {
283 throw new \RuntimeException( "Content row for $revisionId not found after content insert" );
284 }
285 $slotRows[] = [
286 'slot_revision_id' => $revisionId,
287 'slot_role_id' => $this->mainRoleId,
288 'slot_content_id' => $contentId,
289 // There's no way to really know the previous revision, so assume no inheriting.
290 // rev_parent_id can get changed on undeletions, and deletions can screw up
291 // rev_timestamp ordering.
292 'slot_origin' => $revisionId,
293 ];
294 }
295 $this->dbw->insert( 'slots', $slotRows, __METHOD__ );
296 $this->count += count( $slotRows );
297 $this->totalCount += count( $slotRows );
298 } catch ( \Exception $e ) {
299 $this->rollbackTransaction( $this->dbw, __METHOD__ );
300 $this->fatalError( "Failed to populate content table $table row batch starting at $startId "
301 . "due to exception: " . $e->__toString() );
302 }
303
304 $this->commitTransaction( $this->dbw, __METHOD__ );
305 }
306
307 /**
308 * @param \stdClass $row
309 * @return string
310 */
311 private function getContentModel( $row ) {
312 if ( isset( $row->content_model ) ) {
313 return $row->content_model;
314 }
315
316 $title = Title::makeTitle( $row->namespace, $row->title );
317
318 return ContentHandler::getDefaultModelFor( $title );
319 }
320
321 /**
322 * @param string $msg
323 */
324 private function writeln( $msg ) {
325 $this->output( "$msg\n" );
326 }
327 }
328
329 $maintClass = 'PopulateContentTables';
330 require_once RUN_MAINTENANCE_IF_MAIN;