MediaWiki  master
populateContentTables.php
Go to the documentation of this file.
1 <?php
30 
31 require_once __DIR__ . '/Maintenance.php';
32 
38 
40  private $dbw;
41 
44 
46  private $blobStore;
47 
49  private $mainRoleId;
50 
52  private $contentRowMap = null;
53 
54  private $count = 0, $totalCount = 0;
55 
56  public function __construct() {
57  parent::__construct();
58 
59  $this->addDescription( 'Populate content and slot tables' );
60  $this->addOption( 'table', 'revision or archive table, or `all` to populate both', false,
61  true );
62  $this->addOption( 'reuse-content',
63  'Reuse content table rows when the address and model are the same. '
64  . 'This will increase the script\'s time and memory usage, perhaps significantly.',
65  false, false );
66  $this->addOption( 'start-revision', 'The rev_id to start at', false, true );
67  $this->addOption( 'start-archive', 'The ar_rev_id to start at', false, true );
68  $this->setBatchSize( 500 );
69  }
70 
71  private function initServices() {
72  $this->dbw = $this->getDB( DB_MASTER );
73  $this->contentModelStore = MediaWikiServices::getInstance()->getContentModelStore();
74  $this->blobStore = MediaWikiServices::getInstance()->getBlobStore();
75  $this->mainRoleId = MediaWikiServices::getInstance()->getSlotRoleStore()
76  ->acquireId( SlotRecord::MAIN );
77  }
78 
79  public function execute() {
81 
82  $t0 = microtime( true );
83 
84  if ( ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) === 0 ) {
85  $this->writeln(
86  '...cannot update while \$wgMultiContentRevisionSchemaMigrationStage '
87  . 'does not have the SCHEMA_COMPAT_WRITE_NEW bit set.'
88  );
89  return false;
90  }
91 
92  $this->initServices();
93 
94  if ( $this->getOption( 'reuse-content', false ) ) {
95  $this->loadContentMap();
96  }
97 
98  foreach ( $this->getTables() as $table ) {
99  $this->populateTable( $table );
100  }
101 
102  $elapsed = microtime( true ) - $t0;
103  $this->writeln( "Done. Processed $this->totalCount rows in $elapsed seconds" );
104  return true;
105  }
106 
110  private function getTables() {
111  $table = $this->getOption( 'table', 'all' );
112  $validTableOptions = [ 'all', 'revision', 'archive' ];
113 
114  if ( !in_array( $table, $validTableOptions ) ) {
115  $this->fatalError( 'Invalid table. Must be either `revision` or `archive` or `all`' );
116  }
117 
118  if ( $table === 'all' ) {
119  $tables = [ 'revision', 'archive' ];
120  } else {
121  $tables = [ $table ];
122  }
123 
124  return $tables;
125  }
126 
127  private function loadContentMap() {
128  $t0 = microtime( true );
129  $this->writeln( "Loading existing content table rows..." );
130  $this->contentRowMap = [];
131  $dbr = $this->getDB( DB_REPLICA );
132  $from = false;
133  while ( true ) {
134  $res = $dbr->select(
135  'content',
136  [ 'content_id', 'content_address', 'content_model' ],
137  $from ? "content_id > $from" : '',
138  __METHOD__,
139  [ 'ORDER BY' => 'content_id', 'LIMIT' => $this->getBatchSize() ]
140  );
141  if ( !$res || !$res->numRows() ) {
142  break;
143  }
144  foreach ( $res as $row ) {
145  $from = $row->content_id;
146  $this->contentRowMap["{$row->content_model}:{$row->content_address}"] = $row->content_id;
147  }
148  }
149  $elapsed = microtime( true ) - $t0;
150  $this->writeln( "Loaded " . count( $this->contentRowMap ) . " rows in $elapsed seconds" );
151  }
152 
156  private function populateTable( $table ) {
157  $t0 = microtime( true );
158  $this->count = 0;
159  $this->writeln( "Populating $table..." );
160 
161  if ( $table === 'revision' ) {
162  $idField = 'rev_id';
163  $tables = [ 'revision', 'slots', 'page' ];
164  $fields = [
165  'rev_id',
166  'len' => 'rev_len',
167  'sha1' => 'rev_sha1',
168  'text_id' => 'rev_text_id',
169  'content_model' => 'rev_content_model',
170  'namespace' => 'page_namespace',
171  'title' => 'page_title',
172  ];
173  $joins = [
174  'slots' => [ 'LEFT JOIN', 'rev_id=slot_revision_id' ],
175  'page' => [ 'LEFT JOIN', 'rev_page=page_id' ],
176  ];
177  $startOption = 'start-revision';
178  } else {
179  $idField = 'ar_rev_id';
180  $tables = [ 'archive', 'slots' ];
181  $fields = [
182  'rev_id' => 'ar_rev_id',
183  'len' => 'ar_len',
184  'sha1' => 'ar_sha1',
185  'text_id' => 'ar_text_id',
186  'content_model' => 'ar_content_model',
187  'namespace' => 'ar_namespace',
188  'title' => 'ar_title',
189  ];
190  $joins = [
191  'slots' => [ 'LEFT JOIN', 'ar_rev_id=slot_revision_id' ],
192  ];
193  $startOption = 'start-archive';
194  }
195 
196  if ( !$this->dbw->fieldExists( $table, $fields['text_id'], __METHOD__ ) ) {
197  $this->writeln( "No need to populate, $table.{$fields['text_id']} field does not exist" );
198  return;
199  }
200 
201  $minmax = $this->dbw->selectRow(
202  $table,
203  [ 'min' => "MIN( $idField )", 'max' => "MAX( $idField )" ],
204  '',
205  __METHOD__
206  );
207  if ( $this->hasOption( $startOption ) ) {
208  $minmax->min = (int)$this->getOption( $startOption );
209  }
210  if ( !$minmax || !is_numeric( $minmax->min ) || !is_numeric( $minmax->max ) ) {
211  // No rows?
212  $minmax = (object)[ 'min' => 1, 'max' => 0 ];
213  }
214 
215  $batchSize = $this->getBatchSize();
216 
217  for ( $startId = $minmax->min; $startId <= $minmax->max; $startId += $batchSize ) {
218  $endId = min( $startId + $batchSize - 1, $minmax->max );
219  $rows = $this->dbw->select(
220  $tables,
221  $fields,
222  [
223  "$idField >= $startId",
224  "$idField <= $endId",
225  'slot_revision_id IS NULL',
226  ],
227  __METHOD__,
228  [ 'ORDER BY' => 'rev_id' ],
229  $joins
230  );
231  if ( $rows->numRows() !== 0 ) {
232  $this->populateContentTablesForRowBatch( $rows, $startId, $table );
233  }
234 
235  $elapsed = microtime( true ) - $t0;
236  $this->writeln(
237  "... $table processed up to revision id $endId of {$minmax->max}"
238  . " ($this->count rows in $elapsed seconds)"
239  );
240  }
241 
242  $elapsed = microtime( true ) - $t0;
243  $this->writeln( "Done populating $table table. Processed $this->count rows in $elapsed seconds" );
244  }
245 
252  private function populateContentTablesForRowBatch( IResultWrapper $rows, $startId, $table ) {
253  $this->beginTransaction( $this->dbw, __METHOD__ );
254 
255  if ( $this->contentRowMap === null ) {
256  $map = [];
257  } else {
258  $map = &$this->contentRowMap;
259  }
260  $contentKeys = [];
261 
262  try {
263  // Step 1: Figure out content rows needing insertion.
264  $contentRows = [];
265  foreach ( $rows as $row ) {
266  $revisionId = $row->rev_id;
267 
268  Assert::invariant( $revisionId !== null, 'rev_id must not be null' );
269 
270  $model = $this->getContentModel( $row );
271  $modelId = $this->contentModelStore->acquireId( $model );
272  $address = SqlBlobStore::makeAddressFromTextId( $row->text_id );
273 
274  $key = "{$modelId}:{$address}";
275  $contentKeys[$revisionId] = $key;
276 
277  if ( !isset( $map[$key] ) ) {
278  $this->fillMissingFields( $row, $model, $address );
279 
280  $map[$key] = false;
281  $contentRows[] = [
282  'content_size' => (int)$row->len,
283  'content_sha1' => $row->sha1,
284  'content_model' => $modelId,
285  'content_address' => $address,
286  ];
287  }
288  }
289 
290  // Step 2: Insert them, then read them back in for use in the next step.
291  if ( $contentRows ) {
292  $id = $this->dbw->selectField( 'content', 'MAX(content_id)', '', __METHOD__ );
293  $this->dbw->insert( 'content', $contentRows, __METHOD__ );
294  $res = $this->dbw->select(
295  'content',
296  [ 'content_id', 'content_model', 'content_address' ],
297  'content_id > ' . (int)$id,
298  __METHOD__
299  );
300  foreach ( $res as $row ) {
301  $key = $row->content_model . ':' . $row->content_address;
302  $map[$key] = $row->content_id;
303  }
304  }
305 
306  // Step 3: Insert the slot rows.
307  $slotRows = [];
308  foreach ( $rows as $row ) {
309  $revisionId = $row->rev_id;
310  $contentId = $map[$contentKeys[$revisionId]] ?? false;
311  if ( $contentId === false ) {
312  throw new \RuntimeException( "Content row for $revisionId not found after content insert" );
313  }
314  $slotRows[] = [
315  'slot_revision_id' => $revisionId,
316  'slot_role_id' => $this->mainRoleId,
317  'slot_content_id' => $contentId,
318  // There's no way to really know the previous revision, so assume no inheriting.
319  // rev_parent_id can get changed on undeletions, and deletions can screw up
320  // rev_timestamp ordering.
321  'slot_origin' => $revisionId,
322  ];
323  }
324  $this->dbw->insert( 'slots', $slotRows, __METHOD__ );
325  $this->count += count( $slotRows );
326  $this->totalCount += count( $slotRows );
327  } catch ( \Exception $e ) {
328  $this->rollbackTransaction( $this->dbw, __METHOD__ );
329  $this->fatalError( "Failed to populate content table $table row batch starting at $startId "
330  . "due to exception: " . $e->__toString() );
331  }
332 
333  $this->commitTransaction( $this->dbw, __METHOD__ );
334  }
335 
340  private function getContentModel( $row ) {
341  if ( isset( $row->content_model ) ) {
342  return $row->content_model;
343  }
344 
345  $title = Title::makeTitle( $row->namespace, $row->title );
346 
348  }
349 
353  private function writeln( $msg ) {
354  $this->output( "$msg\n" );
355  }
356 
365  private function fillMissingFields( $row, $model, $address ) {
366  if ( !isset( $row->content_model ) ) {
367  // just for completeness
368  $row->content_model = $model;
369  }
370 
371  if ( isset( $row->len ) && isset( $row->sha1 ) && $row->sha1 !== '' ) {
372  // No need to load the content, quite now.
373  return;
374  }
375 
376  $blob = $this->blobStore->getBlob( $address );
377 
378  if ( !isset( $row->len ) ) {
379  // NOTE: The nominal size of the content may not be the length of the raw blob.
381  $content = $handler->unserializeContent( $blob );
382 
383  $row->len = $content->getSize();
384  }
385 
386  if ( !isset( $row->sha1 ) || $row->sha1 === '' ) {
387  $row->sha1 = SlotRecord::base36Sha1( $blob );
388  }
389  }
390 }
391 
392 $maintClass = 'PopulateContentTables';
393 require_once RUN_MAINTENANCE_IF_MAIN;
commitTransaction(IDatabase $dbw, $fname)
Commit the transcation on a DB handle and wait for replica DBs to catch up.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction $rows
Definition: hooks.txt:2632
int $wgMultiContentRevisionSchemaMigrationStage
RevisionStore table schema migration stage (content, slots, content_models & slot_roles tables)...
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
getOption( $name, $default=null)
Get an option, or return the default.
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2158
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest object
Definition: globals.txt:25
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
rollbackTransaction(IDatabase $dbw, $fname)
Rollback the transcation on a DB handle.
static getDefaultModelFor(Title $title)
Returns the name of the default content model to be used for the page with the given title...
Populate the content and slot tables.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
setBatchSize( $s=0)
Set the batch size.
hasOption( $name)
Checks to see if a particular option exists.
require_once RUN_MAINTENANCE_IF_MAIN
Definition: maintenance.txt:50
const DB_MASTER
Definition: defines.php:26
this hook is for auditing only RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist & $tables
Definition: hooks.txt:966
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Definition: hooks.txt:773
static getForModelID( $modelId)
Returns the ContentHandler singleton for the given model ID.
fillMissingFields( $row, $model, $address)
Compute any missing fields in $row.
const SCHEMA_COMPAT_WRITE_NEW
Definition: Defines.php:266
$res
Definition: database.txt:21
addDescription( $text)
Set the description text.
Result wrapper for grabbing data queried from an IDatabase object.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:773
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:918
output( $out, $channel=null)
Throw some output to the user.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:592
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
getBatchSize()
Returns batch size.
populateContentTablesForRowBatch(IResultWrapper $rows, $startId, $table)
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
const DB_REPLICA
Definition: defines.php:25
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
$content
Definition: pageupdater.txt:72
array null $contentRowMap
Map "{$modelId}:{$address}" to content_id.
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
beginTransaction(IDatabase $dbw, $fname)
Begin a transcation on a DB.