MediaWiki  1.32.0
populateContentTables.php
Go to the documentation of this file.
1 <?php
26 use Wikimedia\Assert\Assert;
29 
30 require_once __DIR__ . '/Maintenance.php';
31 
37 
39  private $dbw;
40 
43 
45  private $mainRoleId;
46 
48  private $contentRowMap = null;
49 
50  private $count = 0, $totalCount = 0;
51 
52  public function __construct() {
53  parent::__construct();
54 
55  $this->addDescription( 'Populate content and slot tables' );
56  $this->addOption( 'table', 'revision or archive table, or `all` to populate both', false,
57  true );
58  $this->addOption( 'reuse-content',
59  'Reuse content table rows when the address and model are the same. '
60  . 'This will increase the script\'s time and memory usage, perhaps significantly.',
61  false, false );
62  $this->addOption( 'start-revision', 'The rev_id to start at', false, true );
63  $this->addOption( 'start-archive', 'The ar_rev_id to start at', false, true );
64  $this->setBatchSize( 500 );
65  }
66 
67  private function initServices() {
68  $this->dbw = $this->getDB( DB_MASTER );
69  $this->contentModelStore = MediaWikiServices::getInstance()->getContentModelStore();
70  $this->mainRoleId = MediaWikiServices::getInstance()->getSlotRoleStore()
71  ->acquireId( SlotRecord::MAIN );
72  }
73 
74  public function execute() {
76 
77  $t0 = microtime( true );
78 
80  $this->writeln(
81  '...cannot update while \$wgMultiContentRevisionSchemaMigrationStage '
82  . 'does not have the SCHEMA_COMPAT_WRITE_NEW bit set.'
83  );
84  return false;
85  }
86 
87  $this->initServices();
88 
89  if ( $this->getOption( 'reuse-content', false ) ) {
90  $this->loadContentMap();
91  }
92 
93  foreach ( $this->getTables() as $table ) {
94  $this->populateTable( $table );
95  }
96 
97  $elapsed = microtime( true ) - $t0;
98  $this->writeln( "Done. Processed $this->totalCount rows in $elapsed seconds" );
99  return true;
100  }
101 
105  private function getTables() {
106  $table = $this->getOption( 'table', 'all' );
107  $validTableOptions = [ 'all', 'revision', 'archive' ];
108 
109  if ( !in_array( $table, $validTableOptions ) ) {
110  $this->fatalError( 'Invalid table. Must be either `revision` or `archive` or `all`' );
111  }
112 
113  if ( $table === 'all' ) {
114  $tables = [ 'revision', 'archive' ];
115  } else {
116  $tables = [ $table ];
117  }
118 
119  return $tables;
120  }
121 
122  private function loadContentMap() {
123  $t0 = microtime( true );
124  $this->writeln( "Loading existing content table rows..." );
125  $this->contentRowMap = [];
126  $dbr = $this->getDB( DB_REPLICA );
127  $from = false;
128  while ( true ) {
129  $res = $dbr->select(
130  'content',
131  [ 'content_id', 'content_address', 'content_model' ],
132  $from ? "content_id > $from" : '',
133  __METHOD__,
134  [ 'ORDER BY' => 'content_id', 'LIMIT' => $this->getBatchSize() ]
135  );
136  if ( !$res || !$res->numRows() ) {
137  break;
138  }
139  foreach ( $res as $row ) {
140  $from = $row->content_id;
141  $this->contentRowMap["{$row->content_model}:{$row->content_address}"] = $row->content_id;
142  }
143  }
144  $elapsed = microtime( true ) - $t0;
145  $this->writeln( "Loaded " . count( $this->contentRowMap ) . " rows in $elapsed seconds" );
146  }
147 
151  private function populateTable( $table ) {
152  $t0 = microtime( true );
153  $this->count = 0;
154  $this->writeln( "Populating $table..." );
155 
156  if ( $table === 'revision' ) {
157  $idField = 'rev_id';
158  $tables = [ 'revision', 'slots', 'page' ];
159  $fields = [
160  'rev_id',
161  'len' => 'rev_len',
162  'sha1' => 'rev_sha1',
163  'text_id' => 'rev_text_id',
164  'content_model' => 'rev_content_model',
165  'namespace' => 'page_namespace',
166  'title' => 'page_title',
167  ];
168  $joins = [
169  'slots' => [ 'LEFT JOIN', 'rev_id=slot_revision_id' ],
170  'page' => [ 'LEFT JOIN', 'rev_page=page_id' ],
171  ];
172  $startOption = 'start-revision';
173  } else {
174  $idField = 'ar_rev_id';
175  $tables = [ 'archive', 'slots' ];
176  $fields = [
177  'rev_id' => 'ar_rev_id',
178  'len' => 'ar_len',
179  'sha1' => 'ar_sha1',
180  'text_id' => 'ar_text_id',
181  'content_model' => 'ar_content_model',
182  'namespace' => 'ar_namespace',
183  'title' => 'ar_title',
184  ];
185  $joins = [
186  'slots' => [ 'LEFT JOIN', 'ar_rev_id=slot_revision_id' ],
187  ];
188  $startOption = 'start-archive';
189  }
190 
191  $minmax = $this->dbw->selectRow(
192  $table,
193  [ 'min' => "MIN( $idField )", 'max' => "MAX( $idField )" ],
194  '',
195  __METHOD__
196  );
197  if ( $this->hasOption( $startOption ) ) {
198  $minmax->min = (int)$this->getOption( $startOption );
199  }
200  if ( !$minmax || !is_numeric( $minmax->min ) || !is_numeric( $minmax->max ) ) {
201  // No rows?
202  $minmax = (object)[ 'min' => 1, 'max' => 0 ];
203  }
204 
205  $batchSize = $this->getBatchSize();
206 
207  for ( $startId = $minmax->min; $startId <= $minmax->max; $startId += $batchSize ) {
208  $endId = min( $startId + $batchSize - 1, $minmax->max );
209  $rows = $this->dbw->select(
210  $tables,
211  $fields,
212  [
213  "$idField >= $startId",
214  "$idField <= $endId",
215  'slot_revision_id IS NULL',
216  ],
217  __METHOD__,
218  [ 'ORDER BY' => 'rev_id' ],
219  $joins
220  );
221  if ( $rows->numRows() !== 0 ) {
222  $this->populateContentTablesForRowBatch( $rows, $startId, $table );
223  }
224 
225  $elapsed = microtime( true ) - $t0;
226  $this->writeln(
227  "... $table processed up to revision id $endId of {$minmax->max}"
228  . " ($this->count rows in $elapsed seconds)"
229  );
230  }
231 
232  $elapsed = microtime( true ) - $t0;
233  $this->writeln( "Done populating $table table. Processed $this->count rows in $elapsed seconds" );
234  }
235 
242  private function populateContentTablesForRowBatch( ResultWrapper $rows, $startId, $table ) {
243  $this->beginTransaction( $this->dbw, __METHOD__ );
244 
245  if ( $this->contentRowMap === null ) {
246  $map = [];
247  } else {
248  $map = &$this->contentRowMap;
249  }
250  $contentKeys = [];
251 
252  try {
253  // Step 1: Figure out content rows needing insertion.
254  $contentRows = [];
255  foreach ( $rows as $row ) {
256  $revisionId = $row->rev_id;
257 
258  Assert::invariant( $revisionId !== null, 'rev_id must not be null' );
259 
260  $modelId = $this->contentModelStore->acquireId( $this->getContentModel( $row ) );
261  $address = SqlBlobStore::makeAddressFromTextId( $row->text_id );
262 
263  $key = "{$modelId}:{$address}";
264  $contentKeys[$revisionId] = $key;
265 
266  if ( !isset( $map[$key] ) ) {
267  $map[$key] = false;
268  $contentRows[] = [
269  'content_size' => (int)$row->len,
270  'content_sha1' => $row->sha1,
271  'content_model' => $modelId,
272  'content_address' => $address,
273  ];
274  }
275  }
276 
277  // Step 2: Insert them, then read them back in for use in the next step.
278  if ( $contentRows ) {
279  $id = $this->dbw->selectField( 'content', 'MAX(content_id)', '', __METHOD__ );
280  $this->dbw->insert( 'content', $contentRows, __METHOD__ );
281  $res = $this->dbw->select(
282  'content',
283  [ 'content_id', 'content_model', 'content_address' ],
284  'content_id > ' . (int)$id,
285  __METHOD__
286  );
287  foreach ( $res as $row ) {
288  $key = $row->content_model . ':' . $row->content_address;
289  $map[$key] = $row->content_id;
290  }
291  }
292 
293  // Step 3: Insert the slot rows.
294  $slotRows = [];
295  foreach ( $rows as $row ) {
296  $revisionId = $row->rev_id;
297  $contentId = $map[$contentKeys[$revisionId]] ?? false;
298  if ( $contentId === false ) {
299  throw new \RuntimeException( "Content row for $revisionId not found after content insert" );
300  }
301  $slotRows[] = [
302  'slot_revision_id' => $revisionId,
303  'slot_role_id' => $this->mainRoleId,
304  'slot_content_id' => $contentId,
305  // There's no way to really know the previous revision, so assume no inheriting.
306  // rev_parent_id can get changed on undeletions, and deletions can screw up
307  // rev_timestamp ordering.
308  'slot_origin' => $revisionId,
309  ];
310  }
311  $this->dbw->insert( 'slots', $slotRows, __METHOD__ );
312  $this->count += count( $slotRows );
313  $this->totalCount += count( $slotRows );
314  } catch ( \Exception $e ) {
315  $this->rollbackTransaction( $this->dbw, __METHOD__ );
316  $this->fatalError( "Failed to populate content table $table row batch starting at $startId "
317  . "due to exception: " . $e->__toString() );
318  }
319 
320  $this->commitTransaction( $this->dbw, __METHOD__ );
321  }
322 
327  private function getContentModel( $row ) {
328  if ( isset( $row->content_model ) ) {
329  return $row->content_model;
330  }
331 
332  $title = Title::makeTitle( $row->namespace, $row->title );
333 
335  }
336 
340  private function writeln( $msg ) {
341  $this->output( "$msg\n" );
342  }
343 }
344 
345 $maintClass = 'PopulateContentTables';
346 require_once RUN_MAINTENANCE_IF_MAIN;
PopulateContentTables\$totalCount
$totalCount
Definition: populateContentTables.php:50
PopulateContentTables\$count
$count
Definition: populateContentTables.php:50
Maintenance\fatalError
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Definition: Maintenance.php:465
captcha-old.count
count
Definition: captcha-old.py:249
MediaWiki\Storage\SqlBlobStore
Service for storing and loading Content objects.
Definition: SqlBlobStore.php:50
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:317
PopulateContentTables\$mainRoleId
int $mainRoleId
Definition: populateContentTables.php:45
PopulateContentTables\loadContentMap
loadContentMap()
Definition: populateContentTables.php:122
PopulateContentTables\populateTable
populateTable( $table)
Definition: populateContentTables.php:151
$tables
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:1018
RUN_MAINTENANCE_IF_MAIN
require_once RUN_MAINTENANCE_IF_MAIN
Definition: maintenance.txt:50
$wgMultiContentRevisionSchemaMigrationStage
int $wgMultiContentRevisionSchemaMigrationStage
RevisionStore table schema migration stage (content, slots, content_models & slot_roles tables).
Definition: DefaultSettings.php:8988
$maintClass
$maintClass
Definition: populateContentTables.php:345
$res
$res
Definition: database.txt:21
Wikimedia\Rdbms\ResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: ResultWrapper.php:24
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
PopulateContentTables\$contentRowMap
array null $contentRowMap
Map "{$modelId}:{$address}" to content_id.
Definition: populateContentTables.php:48
php
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
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:39
$dbr
$dbr
Definition: testCompression.php:50
Maintenance\rollbackTransaction
rollbackTransaction(IDatabase $dbw, $fname)
Rollback the transcation on a DB handle.
Definition: Maintenance.php:1413
Maintenance\beginTransaction
beginTransaction(IDatabase $dbw, $fname)
Begin a transcation on a DB.
Definition: Maintenance.php:1378
PopulateContentTables\populateContentTablesForRowBatch
populateContentTablesForRowBatch(ResultWrapper $rows, $startId, $table)
Definition: populateContentTables.php:242
PopulateContentTables
Populate the content and slot tables.
Definition: populateContentTables.php:36
PopulateContentTables\writeln
writeln( $msg)
Definition: populateContentTables.php:340
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:182
PopulateContentTables\$contentModelStore
NameTableStore $contentModelStore
Definition: populateContentTables.php:42
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:964
PopulateContentTables\getTables
getTables()
Definition: populateContentTables.php:105
PopulateContentTables\__construct
__construct()
Default constructor.
Definition: populateContentTables.php:52
PopulateContentTables\execute
execute()
Do the actual work.
Definition: populateContentTables.php:74
Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:236
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:545
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
DB_MASTER
const DB_MASTER
Definition: defines.php:26
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
PopulateContentTables\initServices
initServices()
Definition: populateContentTables.php:67
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2213
SCHEMA_COMPAT_WRITE_NEW
const SCHEMA_COMPAT_WRITE_NEW
Definition: Defines.php:286
Maintenance\commitTransaction
commitTransaction(IDatabase $dbw, $fname)
Commit the transcation on a DB handle and wait for replica DBs to catch up.
Definition: Maintenance.php:1393
MediaWiki\Storage\NameTableStore
Definition: NameTableStore.php:35
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:271
$rows
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:2675
Maintenance\getBatchSize
getBatchSize()
Returns batch size.
Definition: Maintenance.php:347
as
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
Maintenance\getDB
getDB( $db, $groups=[], $wiki=false)
Returns a database to be used by current maintenance script.
Definition: Maintenance.php:1351
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:414
PopulateContentTables\getContentModel
getContentModel( $row)
Definition: populateContentTables.php:327
object
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
MediaWikiServices
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
Maintenance\hasOption
hasOption( $name)
Checks to see if a particular option exists.
Definition: Maintenance.php:257
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:355