Follow-up r101449 and friends: no need to consider LC rebuild a database update and...
[lhc/web/wiklou.git] / includes / installer / DatabaseUpdater.php
1 <?php
2 /**
3 * DBMS-specific updater helper.
4 *
5 * @file
6 * @ingroup Deployment
7 */
8
9 require_once( dirname(__FILE__) . '/../../maintenance/Maintenance.php' );
10
11 /**
12 * Class for handling database updates. Roughly based off of updaters.inc, with
13 * a few improvements :)
14 *
15 * @ingroup Deployment
16 * @since 1.17
17 */
18 abstract class DatabaseUpdater {
19
20 /**
21 * Array of updates to perform on the database
22 *
23 * @var array
24 */
25 protected $updates = array();
26
27 /**
28 * List of extension-provided database updates
29 * @var array
30 */
31 protected $extensionUpdates = array();
32
33 /**
34 * Handle to the database subclass
35 *
36 * @var DatabaseBase
37 */
38 protected $db;
39
40 protected $shared = false;
41
42 protected $postDatabaseUpdateMaintenance = array(
43 'DeleteDefaultMessages',
44 'PopulateRevisionLength',
45 'PopulateRevisionSha1',
46 'PopulateImageSha1',
47 'FixExtLinksProtocolRelative',
48 );
49
50 /**
51 * Constructor
52 *
53 * @param $db DatabaseBase object to perform updates on
54 * @param $shared bool Whether to perform updates on shared tables
55 * @param $maintenance Maintenance Maintenance object which created us
56 */
57 protected function __construct( DatabaseBase &$db, $shared, Maintenance $maintenance = null ) {
58 $this->db = $db;
59 $this->db->setFlag( DBO_DDLMODE ); // For Oracle's handling of schema files
60 $this->shared = $shared;
61 if ( $maintenance ) {
62 $this->maintenance = $maintenance;
63 } else {
64 $this->maintenance = new FakeMaintenance;
65 }
66 $this->maintenance->setDB( $db );
67 $this->initOldGlobals();
68 $this->loadExtensions();
69 wfRunHooks( 'LoadExtensionSchemaUpdates', array( $this ) );
70 }
71
72 /**
73 * Initialize all of the old globals. One day this should all become
74 * something much nicer
75 */
76 private function initOldGlobals() {
77 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
78 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
79
80 # For extensions only, should be populated via hooks
81 # $wgDBtype should be checked to specifiy the proper file
82 $wgExtNewTables = array(); // table, dir
83 $wgExtNewFields = array(); // table, column, dir
84 $wgExtPGNewFields = array(); // table, column, column attributes; for PostgreSQL
85 $wgExtPGAlteredFields = array(); // table, column, new type, conversion method; for PostgreSQL
86 $wgExtNewIndexes = array(); // table, index, dir
87 $wgExtModifiedFields = array(); // table, index, dir
88 }
89
90 /**
91 * Loads LocalSettings.php, if needed, and initialises everything needed for LoadExtensionSchemaUpdates hook
92 */
93 private function loadExtensions() {
94 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
95 return; // already loaded
96 }
97 $vars = Installer::getExistingLocalSettings();
98 if ( !$vars ) {
99 return; // no LocalSettings found
100 }
101 if ( !isset( $vars['wgHooks'] ) || !isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
102 return;
103 }
104 global $wgHooks, $wgAutoloadClasses;
105 $wgHooks['LoadExtensionSchemaUpdates'] = $vars['wgHooks']['LoadExtensionSchemaUpdates'];
106 $wgAutoloadClasses = $wgAutoloadClasses + $vars['wgAutoloadClasses'];
107 }
108
109 /**
110 * @throws MWException
111 * @param DatabaseBase $db
112 * @param bool $shared
113 * @param null $maintenance
114 * @return DatabaseUpdater
115 */
116 public static function newForDB( &$db, $shared = false, $maintenance = null ) {
117 $type = $db->getType();
118 if( in_array( $type, Installer::getDBTypes() ) ) {
119 $class = ucfirst( $type ) . 'Updater';
120 return new $class( $db, $shared, $maintenance );
121 } else {
122 throw new MWException( __METHOD__ . ' called for unsupported $wgDBtype' );
123 }
124 }
125
126 /**
127 * Get a database connection to run updates
128 *
129 * @return DatabaseBase
130 */
131 public function getDB() {
132 return $this->db;
133 }
134
135 /**
136 * Output some text. If we're running from web, escape the text first.
137 *
138 * @param $str String: Text to output
139 */
140 public function output( $str ) {
141 if ( $this->maintenance->isQuiet() ) {
142 return;
143 }
144 global $wgCommandLineMode;
145 if( !$wgCommandLineMode ) {
146 $str = htmlspecialchars( $str );
147 }
148 echo $str;
149 flush();
150 }
151
152 /**
153 * Add a new update coming from an extension. This should be called by
154 * extensions while executing the LoadExtensionSchemaUpdates hook.
155 *
156 * @param $update Array: the update to run. Format is the following:
157 * first item is the callback function, it also can be a
158 * simple string with the name of a function in this class,
159 * following elements are parameters to the function.
160 * Note that callback functions will receive this object as
161 * first parameter.
162 */
163 public function addExtensionUpdate( Array $update ) {
164 $this->extensionUpdates[] = $update;
165 }
166
167 /**
168 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
169 * is the most common usage of updaters in an extension)
170 * @param $tableName String Name of table to create
171 * @param $sqlPath String Full path to the schema file
172 */
173 public function addExtensionTable( $tableName, $sqlPath ) {
174 $this->extensionUpdates[] = array( 'addTable', $tableName, $sqlPath, true );
175 }
176
177 /**
178 * @param $tableName string
179 * @param $indexName string
180 * @param $sqlPath string
181 */
182 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
183 $this->extensionUpdates[] = array( 'addIndex', $tableName, $indexName, $sqlPath, true );
184 }
185
186 /**
187 * @param $tableName string
188 * @param $columnName string
189 * @param $sqlPath string
190 */
191 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
192 $this->extensionUpdates[] = array( 'addField', $tableName, $columnName, $sqlPath, true );
193 }
194
195 /**
196 * Add a maintenance script to be run after the database updates are complete
197 * @param $class string Name of a Maintenance subclass
198 */
199 public function addPostDatabaseUpdateMaintenance( $class ) {
200 $this->postDatabaseUpdateMaintenance[] = $class;
201 }
202
203 /**
204 * Get the list of extension-defined updates
205 *
206 * @return Array
207 */
208 protected function getExtensionUpdates() {
209 return $this->extensionUpdates;
210 }
211
212 /**
213 * @return array
214 */
215 public function getPostDatabaseUpdateMaintenance() {
216 return $this->postDatabaseUpdateMaintenance;
217 }
218
219 /**
220 * Do all the updates
221 *
222 * @param $what Array: what updates to perform
223 */
224 public function doUpdates( $what = array( 'core', 'extensions', 'purge', 'stats' ) ) {
225 global $wgVersion;
226
227 $what = array_flip( $what );
228 if ( isset( $what['core'] ) ) {
229 $this->runUpdates( $this->getCoreUpdateList(), false );
230 }
231 if ( isset( $what['extensions'] ) ) {
232 $this->runUpdates( $this->getOldGlobalUpdates(), false );
233 $this->runUpdates( $this->getExtensionUpdates(), true );
234 }
235
236 $this->setAppliedUpdates( $wgVersion, $this->updates );
237
238 if( isset( $what['purge'] ) ) {
239 $this->purgeCache();
240 $this->rebuildLocalisationCache();
241 }
242 if ( isset( $what['stats'] ) ) {
243 $this->checkStats();
244 }
245 }
246
247 /**
248 * Helper function for doUpdates()
249 *
250 * @param $updates Array of updates to run
251 * @param $passSelf Boolean: whether to pass this object we calling external
252 * functions
253 */
254 private function runUpdates( array $updates, $passSelf ) {
255 foreach ( $updates as $params ) {
256 $func = array_shift( $params );
257 if( !is_array( $func ) && method_exists( $this, $func ) ) {
258 $func = array( $this, $func );
259 } elseif ( $passSelf ) {
260 array_unshift( $params, $this );
261 }
262 call_user_func_array( $func, $params );
263 flush();
264 }
265 $this->updates = array_merge( $this->updates, $updates );
266 }
267
268 /**
269 * @param $version
270 * @param $updates array
271 */
272 protected function setAppliedUpdates( $version, $updates = array() ) {
273 $this->db->clearFlag( DBO_DDLMODE );
274 if( !$this->canUseNewUpdatelog() ) {
275 return;
276 }
277 $key = "updatelist-$version-" . time();
278 $this->db->insert( 'updatelog',
279 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
280 __METHOD__ );
281 $this->db->setFlag( DBO_DDLMODE );
282 }
283
284 /**
285 * Helper function: check if the given key is present in the updatelog table.
286 * Obviously, only use this for updates that occur after the updatelog table was
287 * created!
288 * @param $key String Name of the key to check for
289 *
290 * @return bool
291 */
292 public function updateRowExists( $key ) {
293 $row = $this->db->selectRow(
294 'updatelog',
295 '1',
296 array( 'ul_key' => $key ),
297 __METHOD__
298 );
299 return (bool)$row;
300 }
301
302 /**
303 * Helper function: Add a key to the updatelog table
304 * Obviously, only use this for updates that occur after the updatelog table was
305 * created!
306 * @param $key String Name of key to insert
307 * @param $val String [optional] value to insert along with the key
308 */
309 public function insertUpdateRow( $key, $val = null ) {
310 $this->db->clearFlag( DBO_DDLMODE );
311 $values = array( 'ul_key' => $key );
312 if( $val && $this->canUseNewUpdatelog() ) {
313 $values['ul_value'] = $val;
314 }
315 $this->db->insert( 'updatelog', $values, __METHOD__, 'IGNORE' );
316 $this->db->setFlag( DBO_DDLMODE );
317 }
318
319 /**
320 * Updatelog was changed in 1.17 to have a ul_value column so we can record
321 * more information about what kind of updates we've done (that's what this
322 * class does). Pre-1.17 wikis won't have this column, and really old wikis
323 * might not even have updatelog at all
324 *
325 * @return boolean
326 */
327 protected function canUseNewUpdatelog() {
328 return $this->db->tableExists( 'updatelog', __METHOD__ ) &&
329 $this->db->fieldExists( 'updatelog', 'ul_value', __METHOD__ );
330 }
331
332 /**
333 * Before 1.17, we used to handle updates via stuff like
334 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
335 * of this in 1.17 but we want to remain back-compatible for a while. So
336 * load up these old global-based things into our update list.
337 *
338 * @return array
339 */
340 protected function getOldGlobalUpdates() {
341 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
342 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
343
344 $doUser = $this->shared ?
345 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
346 !$wgSharedDB || !in_array( 'user', $wgSharedTables );
347
348 $updates = array();
349
350 foreach ( $wgExtNewTables as $tableRecord ) {
351 $updates[] = array(
352 'addTable', $tableRecord[0], $tableRecord[1], true
353 );
354 }
355
356 foreach ( $wgExtNewFields as $fieldRecord ) {
357 if ( $fieldRecord[0] != 'user' || $doUser ) {
358 $updates[] = array(
359 'addField', $fieldRecord[0], $fieldRecord[1],
360 $fieldRecord[2], true
361 );
362 }
363 }
364
365 foreach ( $wgExtNewIndexes as $fieldRecord ) {
366 $updates[] = array(
367 'addIndex', $fieldRecord[0], $fieldRecord[1],
368 $fieldRecord[2], true
369 );
370 }
371
372 foreach ( $wgExtModifiedFields as $fieldRecord ) {
373 $updates[] = array(
374 'modifyField', $fieldRecord[0], $fieldRecord[1],
375 $fieldRecord[2], true
376 );
377 }
378
379 return $updates;
380 }
381
382 /**
383 * Get an array of updates to perform on the database. Should return a
384 * multi-dimensional array. The main key is the MediaWiki version (1.12,
385 * 1.13...) with the values being arrays of updates, identical to how
386 * updaters.inc did it (for now)
387 *
388 * @return Array
389 */
390 protected abstract function getCoreUpdateList();
391
392 /**
393 * Applies a SQL patch
394 * @param $path String Path to the patch file
395 * @param $isFullPath Boolean Whether to treat $path as a relative or not
396 */
397 protected function applyPatch( $path, $isFullPath = false ) {
398 if ( $isFullPath ) {
399 $this->db->sourceFile( $path );
400 } else {
401 $this->db->sourceFile( $this->db->patchPath( $path ) );
402 }
403 }
404
405 /**
406 * Add a new table to the database
407 * @param $name String Name of the new table
408 * @param $patch String Path to the patch file
409 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
410 */
411 protected function addTable( $name, $patch, $fullpath = false ) {
412 if ( $this->db->tableExists( $name, __METHOD__ ) ) {
413 $this->output( "...$name table already exists.\n" );
414 } else {
415 $this->output( "Creating $name table..." );
416 $this->applyPatch( $patch, $fullpath );
417 $this->output( "ok\n" );
418 }
419 }
420
421 /**
422 * Add a new field to an existing table
423 * @param $table String Name of the table to modify
424 * @param $field String Name of the new field
425 * @param $patch String Path to the patch file
426 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
427 */
428 protected function addField( $table, $field, $patch, $fullpath = false ) {
429 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
430 $this->output( "...$table table does not exist, skipping new field patch\n" );
431 } elseif ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
432 $this->output( "...have $field field in $table table.\n" );
433 } else {
434 $this->output( "Adding $field field to table $table..." );
435 $this->applyPatch( $patch, $fullpath );
436 $this->output( "ok\n" );
437 }
438 }
439
440 /**
441 * Add a new index to an existing table
442 * @param $table String Name of the table to modify
443 * @param $index String Name of the new index
444 * @param $patch String Path to the patch file
445 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
446 */
447 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
448 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
449 $this->output( "...$index key already set on $table table.\n" );
450 } else {
451 $this->output( "Adding $index key to table $table... " );
452 $this->applyPatch( $patch, $fullpath );
453 $this->output( "ok\n" );
454 }
455 }
456
457 /**
458 * Drop a field from an existing table
459 *
460 * @param $table String Name of the table to modify
461 * @param $field String Name of the old field
462 * @param $patch String Path to the patch file
463 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
464 */
465 protected function dropField( $table, $field, $patch, $fullpath = false ) {
466 if ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
467 $this->output( "Table $table contains $field field. Dropping... " );
468 $this->applyPatch( $patch, $fullpath );
469 $this->output( "ok\n" );
470 } else {
471 $this->output( "...$table table does not contain $field field.\n" );
472 }
473 }
474
475 /**
476 * Drop an index from an existing table
477 *
478 * @param $table String: Name of the table to modify
479 * @param $index String: Name of the old index
480 * @param $patch String: Path to the patch file
481 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
482 */
483 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
484 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
485 $this->output( "Dropping $index key from table $table... " );
486 $this->applyPatch( $patch, $fullpath );
487 $this->output( "ok\n" );
488 } else {
489 $this->output( "...$index key doesn't exist.\n" );
490 }
491 }
492
493 /**
494 * @param $table string
495 * @param $patch string
496 * @param $fullpath bool
497 */
498 protected function dropTable( $table, $patch, $fullpath = false ) {
499 if ( $this->db->tableExists( $table, __METHOD__ ) ) {
500 $this->output( "Dropping table $table... " );
501 $this->applyPatch( $patch, $fullpath );
502 $this->output( "ok\n" );
503 } else {
504 $this->output( "...$table doesn't exist.\n" );
505 }
506 }
507
508 /**
509 * Modify an existing field
510 *
511 * @param $table String: name of the table to which the field belongs
512 * @param $field String: name of the field to modify
513 * @param $patch String: path to the patch file
514 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
515 */
516 public function modifyField( $table, $field, $patch, $fullpath = false ) {
517 $updateKey = "$table-$field-$patch";
518 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
519 $this->output( "...$table table does not exist, skipping modify field patch\n" );
520 } elseif ( !$this->db->fieldExists( $table, $field, __METHOD__ ) ) {
521 $this->output( "...$field field does not exist in $table table, skipping modify field patch\n" );
522 } elseif( $this->updateRowExists( $updateKey ) ) {
523 $this->output( "...$field in table $table already modified by patch $patch\n" );
524 } else {
525 $this->output( "Modifying $field field of table $table..." );
526 $this->applyPatch( $patch, $fullpath );
527 $this->insertUpdateRow( $updateKey );
528 $this->output( "ok\n" );
529 }
530 }
531
532 /**
533 * Purge the objectcache table
534 */
535 protected function purgeCache() {
536 # We can't guarantee that the user will be able to use TRUNCATE,
537 # but we know that DELETE is available to us
538 $this->output( "Purging caches..." );
539 $this->db->delete( 'objectcache', '*', __METHOD__ );
540 $this->output( "done.\n" );
541 }
542
543 /**
544 * Check the site_stats table is not properly populated.
545 */
546 protected function checkStats() {
547 $this->output( "Checking site_stats row..." );
548 $row = $this->db->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
549 if ( $row === false ) {
550 $this->output( "data is missing! rebuilding...\n" );
551 } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
552 $this->output( "missing ss_total_pages, rebuilding...\n" );
553 } else {
554 $this->output( "done.\n" );
555 return;
556 }
557 SiteStatsInit::doAllAndCommit( $this->db );
558 }
559
560 # Common updater functions
561
562 /**
563 * Sets the number of active users in the site_stats table
564 */
565 protected function doActiveUsersInit() {
566 $activeUsers = $this->db->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
567 if ( $activeUsers == -1 ) {
568 $activeUsers = $this->db->selectField( 'recentchanges',
569 'COUNT( DISTINCT rc_user_text )',
570 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
571 );
572 $this->db->update( 'site_stats',
573 array( 'ss_active_users' => intval( $activeUsers ) ),
574 array( 'ss_row_id' => 1 ), __METHOD__, array( 'LIMIT' => 1 )
575 );
576 }
577 $this->output( "...ss_active_users user count set...\n" );
578 }
579
580 /**
581 * Populates the log_user_text field in the logging table
582 */
583 protected function doLogUsertextPopulation() {
584 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
585 $this->output(
586 "Populating log_user_text field, printing progress markers. For large\n" .
587 "databases, you may want to hit Ctrl-C and do this manually with\n" .
588 "maintenance/populateLogUsertext.php.\n" );
589
590 $task = $this->maintenance->runChild( 'PopulateLogUsertext' );
591 $task->execute();
592 }
593 }
594
595 /**
596 * Migrate log params to new table and index for searching
597 */
598 protected function doLogSearchPopulation() {
599 if ( !$this->updateRowExists( 'populate log_search' ) ) {
600 $this->output(
601 "Populating log_search table, printing progress markers. For large\n" .
602 "databases, you may want to hit Ctrl-C and do this manually with\n" .
603 "maintenance/populateLogSearch.php.\n" );
604
605 $task = $this->maintenance->runChild( 'PopulateLogSearch' );
606 $task->execute();
607 }
608 }
609
610 /**
611 * Updates the timestamps in the transcache table
612 */
613 protected function doUpdateTranscacheField() {
614 if ( $this->updateRowExists( 'convert transcache field' ) ) {
615 $this->output( "...transcache tc_time already converted.\n" );
616 return;
617 }
618
619 $this->output( "Converting tc_time from UNIX epoch to MediaWiki timestamp... " );
620 $this->applyPatch( 'patch-tc-timestamp.sql' );
621 $this->output( "ok\n" );
622 }
623
624 /**
625 * Update CategoryLinks collation
626 */
627 protected function doCollationUpdate() {
628 global $wgCategoryCollation;
629 if ( $this->db->selectField(
630 'categorylinks',
631 'COUNT(*)',
632 'cl_collation != ' . $this->db->addQuotes( $wgCategoryCollation ),
633 __METHOD__
634 ) == 0 ) {
635 $this->output( "...collations up-to-date.\n" );
636 return;
637 }
638
639 $task = $this->maintenance->runChild( 'UpdateCollation' );
640 $task->execute();
641 }
642
643 /**
644 * Migrates user options from the user table blob to user_properties
645 */
646 protected function doMigrateUserOptions() {
647 $cl = $this->maintenance->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
648 $this->output( "Migrating remaining user_options... " );
649 $cl->execute();
650 $this->output( "done.\n" );
651 }
652
653 /**
654 * Rebuilds the localisation cache
655 */
656 protected function rebuildLocalisationCache() {
657 /**
658 * @var $cl RebuildLocalisationCache
659 */
660 $cl = $this->maintenance->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
661 $this->output( "Rebuilding localisation cache...\n" );
662 $cl->setForce();
663 $cl->execute();
664 $this->output( "Rebuilding localisation cache done.\n" );
665 }
666 }