MediaWiki  master
populateContentTables.php
Go to the documentation of this file.
1 <?php
27 use Wikimedia\Assert\Assert;
30 
31 require_once __DIR__ . '/Maintenance.php';
32 
38 
40  private $dbw;
41 
44 
46  private $slotRoleStore;
47 
49  private $blobStore;
50 
52  private $mainRoleId;
53 
55  private $contentRowMap = null;
56 
57  private $count = 0, $totalCount = 0;
58 
59  public function __construct() {
60  parent::__construct();
61 
62  $this->addDescription( 'Populate content and slot tables' );
63  $this->addOption( 'table', 'revision or archive table, or `all` to populate both', false,
64  true );
65  $this->addOption( 'reuse-content',
66  'Reuse content table rows when the address and model are the same. '
67  . 'This will increase the script\'s time and memory usage, perhaps significantly.',
68  false, false );
69  $this->addOption( 'start-revision', 'The rev_id to start at', false, true );
70  $this->addOption( 'start-archive', 'The ar_rev_id to start at', false, true );
71  $this->setBatchSize( 500 );
72  }
73 
74  private function initServices() {
75  $this->dbw = $this->getDB( DB_MASTER );
76  $this->contentModelStore = MediaWikiServices::getInstance()->getContentModelStore();
77  $this->slotRoleStore = MediaWikiServices::getInstance()->getSlotRoleStore();
78  $this->blobStore = MediaWikiServices::getInstance()->getBlobStore();
79 
80  // Don't trust the cache for the NameTableStores, in case something went
81  // wrong during a previous run (see T224949#5325895).
82  $this->contentModelStore->reloadMap();
83  $this->slotRoleStore->reloadMap();
84  $this->mainRoleId = $this->slotRoleStore->acquireId( SlotRecord::MAIN );
85  }
86 
87  public function execute() {
88  $t0 = microtime( true );
89 
90  $this->initServices();
91 
92  if ( $this->getOption( 'reuse-content', false ) ) {
93  $this->loadContentMap();
94  }
95 
96  foreach ( $this->getTables() as $table ) {
97  $this->populateTable( $table );
98  }
99 
100  $elapsed = microtime( true ) - $t0;
101  $this->writeln( "Done. Processed $this->totalCount rows in $elapsed seconds" );
102  return true;
103  }
104 
108  private function getTables() {
109  $table = $this->getOption( 'table', 'all' );
110  $validTableOptions = [ 'all', 'revision', 'archive' ];
111 
112  if ( !in_array( $table, $validTableOptions ) ) {
113  $this->fatalError( 'Invalid table. Must be either `revision` or `archive` or `all`' );
114  }
115 
116  if ( $table === 'all' ) {
117  $tables = [ 'revision', 'archive' ];
118  } else {
119  $tables = [ $table ];
120  }
121 
122  return $tables;
123  }
124 
125  private function loadContentMap() {
126  $t0 = microtime( true );
127  $this->writeln( "Loading existing content table rows..." );
128  $this->contentRowMap = [];
129  $dbr = $this->getDB( DB_REPLICA );
130  $from = false;
131  while ( true ) {
132  $res = $dbr->select(
133  'content',
134  [ 'content_id', 'content_address', 'content_model' ],
135  $from ? "content_id > $from" : '',
136  __METHOD__,
137  [ 'ORDER BY' => 'content_id', 'LIMIT' => $this->getBatchSize() ]
138  );
139  if ( !$res || !$res->numRows() ) {
140  break;
141  }
142  foreach ( $res as $row ) {
143  $from = $row->content_id;
144  $this->contentRowMap["{$row->content_model}:{$row->content_address}"] = $row->content_id;
145  }
146  }
147  $elapsed = microtime( true ) - $t0;
148  $this->writeln( "Loaded " . count( $this->contentRowMap ) . " rows in $elapsed seconds" );
149  }
150 
154  private function populateTable( $table ) {
155  $t0 = microtime( true );
156  $this->count = 0;
157  $this->writeln( "Populating $table..." );
158 
159  if ( $table === 'revision' ) {
160  $idField = 'rev_id';
161  $tables = [ 'revision', 'slots', 'page' ];
162  $fields = [
163  'rev_id',
164  'len' => 'rev_len',
165  'sha1' => 'rev_sha1',
166  'text_id' => 'rev_text_id',
167  'content_model' => 'rev_content_model',
168  'namespace' => 'page_namespace',
169  'title' => 'page_title',
170  ];
171  $joins = [
172  'slots' => [ 'LEFT JOIN', 'rev_id=slot_revision_id' ],
173  'page' => [ 'LEFT JOIN', 'rev_page=page_id' ],
174  ];
175  $startOption = 'start-revision';
176  } else {
177  $idField = 'ar_rev_id';
178  $tables = [ 'archive', 'slots' ];
179  $fields = [
180  'rev_id' => 'ar_rev_id',
181  'len' => 'ar_len',
182  'sha1' => 'ar_sha1',
183  'text_id' => 'ar_text_id',
184  'content_model' => 'ar_content_model',
185  'namespace' => 'ar_namespace',
186  'title' => 'ar_title',
187  ];
188  $joins = [
189  'slots' => [ 'LEFT JOIN', 'ar_rev_id=slot_revision_id' ],
190  ];
191  $startOption = 'start-archive';
192  }
193 
194  if ( !$this->dbw->fieldExists( $table, $fields['text_id'], __METHOD__ ) ) {
195  $this->writeln( "No need to populate, $table.{$fields['text_id']} field does not exist" );
196  return;
197  }
198 
199  $minmax = $this->dbw->selectRow(
200  $table,
201  [ 'min' => "MIN( $idField )", 'max' => "MAX( $idField )" ],
202  '',
203  __METHOD__
204  );
205  if ( $this->hasOption( $startOption ) ) {
206  $minmax->min = (int)$this->getOption( $startOption );
207  }
208  if ( !$minmax || !is_numeric( $minmax->min ) || !is_numeric( $minmax->max ) ) {
209  // No rows?
210  $minmax = (object)[ 'min' => 1, 'max' => 0 ];
211  }
212 
213  $batchSize = $this->getBatchSize();
214 
215  for ( $startId = $minmax->min; $startId <= $minmax->max; $startId += $batchSize ) {
216  $endId = min( $startId + $batchSize - 1, $minmax->max );
217  $rows = $this->dbw->select(
218  $tables,
219  $fields,
220  [
221  "$idField >= $startId",
222  "$idField <= $endId",
223  'slot_revision_id IS NULL',
224  ],
225  __METHOD__,
226  [ 'ORDER BY' => 'rev_id' ],
227  $joins
228  );
229  if ( $rows->numRows() !== 0 ) {
230  $this->populateContentTablesForRowBatch( $rows, $startId, $table );
231  }
232 
233  $elapsed = microtime( true ) - $t0;
234  $this->writeln(
235  "... $table processed up to revision id $endId of {$minmax->max}"
236  . " ($this->count rows in $elapsed seconds)"
237  );
238  }
239 
240  $elapsed = microtime( true ) - $t0;
241  $this->writeln( "Done populating $table table. Processed $this->count rows in $elapsed seconds" );
242  }
243 
250  private function populateContentTablesForRowBatch( IResultWrapper $rows, $startId, $table ) {
251  $this->beginTransaction( $this->dbw, __METHOD__ );
252 
253  if ( $this->contentRowMap === null ) {
254  $map = [];
255  } else {
256  $map = &$this->contentRowMap;
257  }
258  $contentKeys = [];
259 
260  try {
261  // Step 1: Figure out content rows needing insertion.
262  $contentRows = [];
263  foreach ( $rows as $row ) {
264  $revisionId = $row->rev_id;
265 
266  Assert::invariant( $revisionId !== null, 'rev_id must not be null' );
267 
268  $model = $this->getContentModel( $row );
269  $modelId = $this->contentModelStore->acquireId( $model );
270  $address = SqlBlobStore::makeAddressFromTextId( $row->text_id );
271 
272  $key = "{$modelId}:{$address}";
273  $contentKeys[$revisionId] = $key;
274 
275  if ( !isset( $map[$key] ) ) {
276  $this->fillMissingFields( $row, $model, $address );
277 
278  $map[$key] = false;
279  $contentRows[] = [
280  'content_size' => (int)$row->len,
281  'content_sha1' => $row->sha1,
282  'content_model' => $modelId,
283  'content_address' => $address,
284  ];
285  }
286  }
287 
288  // Step 2: Insert them, then read them back in for use in the next step.
289  if ( $contentRows ) {
290  $id = $this->dbw->selectField( 'content', 'MAX(content_id)', '', __METHOD__ );
291  $this->dbw->insert( 'content', $contentRows, __METHOD__ );
292  $res = $this->dbw->select(
293  'content',
294  [ 'content_id', 'content_model', 'content_address' ],
295  'content_id > ' . (int)$id,
296  __METHOD__
297  );
298  foreach ( $res as $row ) {
299  $key = $row->content_model . ':' . $row->content_address;
300  $map[$key] = $row->content_id;
301  }
302  }
303 
304  // Step 3: Insert the slot rows.
305  $slotRows = [];
306  foreach ( $rows as $row ) {
307  $revisionId = $row->rev_id;
308  $contentId = $map[$contentKeys[$revisionId]] ?? false;
309  if ( $contentId === false ) {
310  throw new \RuntimeException( "Content row for $revisionId not found after content insert" );
311  }
312  $slotRows[] = [
313  'slot_revision_id' => $revisionId,
314  'slot_role_id' => $this->mainRoleId,
315  'slot_content_id' => $contentId,
316  // There's no way to really know the previous revision, so assume no inheriting.
317  // rev_parent_id can get changed on undeletions, and deletions can screw up
318  // rev_timestamp ordering.
319  'slot_origin' => $revisionId,
320  ];
321  }
322  $this->dbw->insert( 'slots', $slotRows, __METHOD__ );
323  $this->count += count( $slotRows );
324  $this->totalCount += count( $slotRows );
325  } catch ( \Exception $e ) {
326  $this->rollbackTransaction( $this->dbw, __METHOD__ );
327  $this->fatalError( "Failed to populate content table $table row batch starting at $startId "
328  . "due to exception: " . $e->__toString() );
329  }
330 
331  $this->commitTransaction( $this->dbw, __METHOD__ );
332  }
333 
338  private function getContentModel( $row ) {
339  if ( isset( $row->content_model ) ) {
340  return $row->content_model;
341  }
342 
343  $title = Title::makeTitle( $row->namespace, $row->title );
344 
346  }
347 
351  private function writeln( $msg ) {
352  $this->output( "$msg\n" );
353  }
354 
363  private function fillMissingFields( $row, $model, $address ) {
364  if ( !isset( $row->content_model ) ) {
365  // just for completeness
366  $row->content_model = $model;
367  }
368 
369  if ( isset( $row->len ) && isset( $row->sha1 ) && $row->sha1 !== '' ) {
370  // No need to load the content, quite now.
371  return;
372  }
373 
374  $blob = $this->blobStore->getBlob( $address );
375 
376  if ( !isset( $row->len ) ) {
377  // NOTE: The nominal size of the content may not be the length of the raw blob.
378  $row->len = ContentHandler::makeContent( $blob, null, $model )->getSize();
379  }
380 
381  if ( !isset( $row->sha1 ) || $row->sha1 === '' ) {
382  $row->sha1 = SlotRecord::base36Sha1( $blob );
383  }
384  }
385 }
386 
387 $maintClass = PopulateContentTables::class;
388 require_once RUN_MAINTENANCE_IF_MAIN;
RUN_MAINTENANCE_IF_MAIN
const RUN_MAINTENANCE_IF_MAIN
Definition: Maintenance.php:38
PopulateContentTables\$totalCount
$totalCount
Definition: populateContentTables.php:57
PopulateContentTables\$blobStore
BlobStore $blobStore
Definition: populateContentTables.php:49
PopulateContentTables\$count
$count
Definition: populateContentTables.php:57
PopulateContentTables\$slotRoleStore
NameTableStore $slotRoleStore
Definition: populateContentTables.php:46
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:144
Maintenance\fatalError
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Definition: Maintenance.php:472
MediaWiki\Storage\SqlBlobStore
Service for storing and loading Content objects.
Definition: SqlBlobStore.php:51
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:315
PopulateContentTables\$mainRoleId
int $mainRoleId
Definition: populateContentTables.php:52
PopulateContentTables\loadContentMap
loadContentMap()
Definition: populateContentTables.php:125
PopulateContentTables\populateTable
populateTable( $table)
Definition: populateContentTables.php:154
$maintClass
$maintClass
Definition: populateContentTables.php:387
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: Maintenance.php:51
PopulateContentTables\fillMissingFields
fillMissingFields( $row, $model, $address)
Compute any missing fields in $row.
Definition: populateContentTables.php:363
PopulateContentTables\$contentRowMap
array null $contentRowMap
Map "{$modelId}:{$address}" to content_id.
Definition: populateContentTables.php:55
$res
$res
Definition: testCompression.php:57
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
PopulateContentTables\$dbw
IDatabase $dbw
Definition: populateContentTables.php:40
$dbr
$dbr
Definition: testCompression.php:54
PopulateContentTables\populateContentTablesForRowBatch
populateContentTablesForRowBatch(IResultWrapper $rows, $startId, $table)
Definition: populateContentTables.php:250
Maintenance\rollbackTransaction
rollbackTransaction(IDatabase $dbw, $fname)
Rollback the transcation on a DB handle.
Definition: Maintenance.php:1407
Maintenance\beginTransaction
beginTransaction(IDatabase $dbw, $fname)
Begin a transcation on a DB.
Definition: Maintenance.php:1372
PopulateContentTables
Populate the content and slot tables.
Definition: populateContentTables.php:37
PopulateContentTables\writeln
writeln( $msg)
Definition: populateContentTables.php:351
ContentHandler\getDefaultModelFor
static getDefaultModelFor(Title $title)
Returns the name of the default content model to be used for the page with the given title.
Definition: ContentHandler.php:189
PopulateContentTables\$contentModelStore
NameTableStore $contentModelStore
Definition: populateContentTables.php:43
Wikimedia\Rdbms\IResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: IResultWrapper.php:24
PopulateContentTables\getTables
getTables()
Definition: populateContentTables.php:108
$blob
$blob
Definition: testCompression.php:70
PopulateContentTables\__construct
__construct()
Default constructor.
Definition: populateContentTables.php:59
PopulateContentTables\execute
execute()
Do the actual work.
Definition: populateContentTables.php:87
Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:233
$title
$title
Definition: testCompression.php:38
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:595
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
DB_MASTER
const DB_MASTER
Definition: defines.php:26
ContentHandler\makeContent
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
Definition: ContentHandler.php:137
PopulateContentTables\initServices
initServices()
Definition: populateContentTables.php:74
Maintenance\commitTransaction
commitTransaction(IDatabase $dbw, $fname)
Commit the transcation on a DB handle and wait for replica DBs to catch up.
Definition: Maintenance.php:1387
MediaWiki\Storage\NameTableStore
Definition: NameTableStore.php:36
Maintenance\getDB
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
Definition: Maintenance.php:1342
MediaWiki\Storage\BlobStore
Service for loading and storing data blobs.
Definition: BlobStore.php:35
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:269
Maintenance\getBatchSize
getBatchSize()
Returns batch size.
Definition: Maintenance.php:354
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:421
PopulateContentTables\getContentModel
getContentModel( $row)
Definition: populateContentTables.php:338
Maintenance\hasOption
hasOption( $name)
Checks to see if a particular option exists.
Definition: Maintenance.php:254
Revision\SlotRecord
Value object representing a content slot associated with a page revision.
Definition: SlotRecord.php:39
Maintenance\setBatchSize
setBatchSize( $s=0)
Set the batch size.
Definition: Maintenance.php:362