Merge "set tidy = true for action=purge&forcelinkupdate="
[mediawiki.git] / includes / installer / DatabaseUpdater.php
blob6483c4e8ac3e3cc333b011723c351b84a45e6a1a
1 <?php
2 /**
3 * DBMS-specific updater helper.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Deployment
24 require_once( dirname(__FILE__) . '/../../maintenance/Maintenance.php' );
26 /**
27 * Class for handling database updates. Roughly based off of updaters.inc, with
28 * a few improvements :)
30 * @ingroup Deployment
31 * @since 1.17
33 abstract class DatabaseUpdater {
35 /**
36 * Array of updates to perform on the database
38 * @var array
40 protected $updates = array();
42 /**
43 * List of extension-provided database updates
44 * @var array
46 protected $extensionUpdates = array();
48 /**
49 * Handle to the database subclass
51 * @var DatabaseBase
53 protected $db;
55 protected $shared = false;
57 protected $postDatabaseUpdateMaintenance = array(
58 'DeleteDefaultMessages',
59 'PopulateRevisionLength',
60 'PopulateRevisionSha1',
61 'PopulateImageSha1',
62 'FixExtLinksProtocolRelative',
65 /**
66 * Constructor
68 * @param $db DatabaseBase object to perform updates on
69 * @param $shared bool Whether to perform updates on shared tables
70 * @param $maintenance Maintenance Maintenance object which created us
72 protected function __construct( DatabaseBase &$db, $shared, Maintenance $maintenance = null ) {
73 $this->db = $db;
74 $this->db->setFlag( DBO_DDLMODE ); // For Oracle's handling of schema files
75 $this->shared = $shared;
76 if ( $maintenance ) {
77 $this->maintenance = $maintenance;
78 } else {
79 $this->maintenance = new FakeMaintenance;
81 $this->maintenance->setDB( $db );
82 $this->initOldGlobals();
83 $this->loadExtensions();
84 wfRunHooks( 'LoadExtensionSchemaUpdates', array( $this ) );
87 /**
88 * Initialize all of the old globals. One day this should all become
89 * something much nicer
91 private function initOldGlobals() {
92 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
93 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
95 # For extensions only, should be populated via hooks
96 # $wgDBtype should be checked to specifiy the proper file
97 $wgExtNewTables = array(); // table, dir
98 $wgExtNewFields = array(); // table, column, dir
99 $wgExtPGNewFields = array(); // table, column, column attributes; for PostgreSQL
100 $wgExtPGAlteredFields = array(); // table, column, new type, conversion method; for PostgreSQL
101 $wgExtNewIndexes = array(); // table, index, dir
102 $wgExtModifiedFields = array(); // table, index, dir
106 * Loads LocalSettings.php, if needed, and initialises everything needed for LoadExtensionSchemaUpdates hook
108 private function loadExtensions() {
109 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
110 return; // already loaded
112 $vars = Installer::getExistingLocalSettings();
113 if ( !$vars ) {
114 return; // no LocalSettings found
116 if ( !isset( $vars['wgHooks'] ) || !isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
117 return;
119 global $wgHooks, $wgAutoloadClasses;
120 $wgHooks['LoadExtensionSchemaUpdates'] = $vars['wgHooks']['LoadExtensionSchemaUpdates'];
121 $wgAutoloadClasses = $wgAutoloadClasses + $vars['wgAutoloadClasses'];
125 * @throws MWException
126 * @param DatabaseBase $db
127 * @param bool $shared
128 * @param null $maintenance
129 * @return DatabaseUpdater
131 public static function newForDB( &$db, $shared = false, $maintenance = null ) {
132 $type = $db->getType();
133 if( in_array( $type, Installer::getDBTypes() ) ) {
134 $class = ucfirst( $type ) . 'Updater';
135 return new $class( $db, $shared, $maintenance );
136 } else {
137 throw new MWException( __METHOD__ . ' called for unsupported $wgDBtype' );
142 * Get a database connection to run updates
144 * @return DatabaseBase
146 public function getDB() {
147 return $this->db;
151 * Output some text. If we're running from web, escape the text first.
153 * @param $str String: Text to output
155 public function output( $str ) {
156 if ( $this->maintenance->isQuiet() ) {
157 return;
159 global $wgCommandLineMode;
160 if( !$wgCommandLineMode ) {
161 $str = htmlspecialchars( $str );
163 echo $str;
164 flush();
168 * Add a new update coming from an extension. This should be called by
169 * extensions while executing the LoadExtensionSchemaUpdates hook.
171 * @since 1.17
173 * @param $update Array: the update to run. Format is the following:
174 * first item is the callback function, it also can be a
175 * simple string with the name of a function in this class,
176 * following elements are parameters to the function.
177 * Note that callback functions will receive this object as
178 * first parameter.
180 public function addExtensionUpdate( Array $update ) {
181 $this->extensionUpdates[] = $update;
185 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
186 * is the most common usage of updaters in an extension)
188 * @since 1.18
190 * @param $tableName String Name of table to create
191 * @param $sqlPath String Full path to the schema file
193 public function addExtensionTable( $tableName, $sqlPath ) {
194 $this->extensionUpdates[] = array( 'addTable', $tableName, $sqlPath, true );
198 * @since 1.19
200 * @param $tableName string
201 * @param $indexName string
202 * @param $sqlPath string
204 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
205 $this->extensionUpdates[] = array( 'addIndex', $tableName, $indexName, $sqlPath, true );
210 * @since 1.19
212 * @param $tableName string
213 * @param $columnName string
214 * @param $sqlPath string
216 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
217 $this->extensionUpdates[] = array( 'addField', $tableName, $columnName, $sqlPath, true );
222 * @since 1.20
224 * @param $tableName string
225 * @param $columnName string
226 * @param $sqlPath string
228 public function dropExtensionField( $tableName, $columnName, $sqlPath ) {
229 $this->extensionUpdates[] = array( 'dropField', $tableName, $columnName, $sqlPath, true );
234 * @since 1.20
236 * @param $tableName string
237 * @param $sqlPath string
239 public function dropExtensionTable( $tableName, $sqlPath ) {
240 $this->extensionUpdates[] = array( 'dropTable', $tableName, $sqlPath, true );
245 * @since 1.20
247 * @param $tableName string
248 * @return bool
250 public function tableExists( $tableName ) {
251 return ( $this->db->tableExists( $tableName, __METHOD__ ) );
255 * Add a maintenance script to be run after the database updates are complete.
257 * @since 1.19
259 * @param $class string Name of a Maintenance subclass
261 public function addPostDatabaseUpdateMaintenance( $class ) {
262 $this->postDatabaseUpdateMaintenance[] = $class;
266 * Get the list of extension-defined updates
268 * @return Array
270 protected function getExtensionUpdates() {
271 return $this->extensionUpdates;
275 * @since 1.17
277 * @return array
279 public function getPostDatabaseUpdateMaintenance() {
280 return $this->postDatabaseUpdateMaintenance;
284 * Do all the updates
286 * @param $what Array: what updates to perform
288 public function doUpdates( $what = array( 'core', 'extensions', 'purge', 'stats' ) ) {
289 global $wgLocalisationCacheConf, $wgVersion;
291 $this->db->begin( __METHOD__ );
292 $what = array_flip( $what );
293 if ( isset( $what['core'] ) ) {
294 $this->runUpdates( $this->getCoreUpdateList(), false );
296 if ( isset( $what['extensions'] ) ) {
297 $this->runUpdates( $this->getOldGlobalUpdates(), false );
298 $this->runUpdates( $this->getExtensionUpdates(), true );
301 $this->setAppliedUpdates( $wgVersion, $this->updates );
303 if ( isset( $what['stats'] ) ) {
304 $this->checkStats();
307 if ( isset( $what['purge'] ) ) {
308 $this->purgeCache();
310 if ( $wgLocalisationCacheConf['manualRecache'] ) {
311 $this->rebuildLocalisationCache();
314 $this->db->commit( __METHOD__ );
318 * Helper function for doUpdates()
320 * @param $updates Array of updates to run
321 * @param $passSelf Boolean: whether to pass this object we calling external
322 * functions
324 private function runUpdates( array $updates, $passSelf ) {
325 foreach ( $updates as $params ) {
326 $func = array_shift( $params );
327 if( !is_array( $func ) && method_exists( $this, $func ) ) {
328 $func = array( $this, $func );
329 } elseif ( $passSelf ) {
330 array_unshift( $params, $this );
332 call_user_func_array( $func, $params );
333 flush();
335 $this->updates = array_merge( $this->updates, $updates );
339 * @param $version
340 * @param $updates array
342 protected function setAppliedUpdates( $version, $updates = array() ) {
343 $this->db->clearFlag( DBO_DDLMODE );
344 if( !$this->canUseNewUpdatelog() ) {
345 return;
347 $key = "updatelist-$version-" . time();
348 $this->db->insert( 'updatelog',
349 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
350 __METHOD__ );
351 $this->db->setFlag( DBO_DDLMODE );
355 * Helper function: check if the given key is present in the updatelog table.
356 * Obviously, only use this for updates that occur after the updatelog table was
357 * created!
358 * @param $key String Name of the key to check for
360 * @return bool
362 public function updateRowExists( $key ) {
363 $row = $this->db->selectRow(
364 'updatelog',
365 '1',
366 array( 'ul_key' => $key ),
367 __METHOD__
369 return (bool)$row;
373 * Helper function: Add a key to the updatelog table
374 * Obviously, only use this for updates that occur after the updatelog table was
375 * created!
376 * @param $key String Name of key to insert
377 * @param $val String [optional] value to insert along with the key
379 public function insertUpdateRow( $key, $val = null ) {
380 $this->db->clearFlag( DBO_DDLMODE );
381 $values = array( 'ul_key' => $key );
382 if( $val && $this->canUseNewUpdatelog() ) {
383 $values['ul_value'] = $val;
385 $this->db->insert( 'updatelog', $values, __METHOD__, 'IGNORE' );
386 $this->db->setFlag( DBO_DDLMODE );
390 * Updatelog was changed in 1.17 to have a ul_value column so we can record
391 * more information about what kind of updates we've done (that's what this
392 * class does). Pre-1.17 wikis won't have this column, and really old wikis
393 * might not even have updatelog at all
395 * @return boolean
397 protected function canUseNewUpdatelog() {
398 return $this->db->tableExists( 'updatelog', __METHOD__ ) &&
399 $this->db->fieldExists( 'updatelog', 'ul_value', __METHOD__ );
403 * Before 1.17, we used to handle updates via stuff like
404 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
405 * of this in 1.17 but we want to remain back-compatible for a while. So
406 * load up these old global-based things into our update list.
408 * @return array
410 protected function getOldGlobalUpdates() {
411 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
412 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
414 $doUser = $this->shared ?
415 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
416 !$wgSharedDB || !in_array( 'user', $wgSharedTables );
418 $updates = array();
420 foreach ( $wgExtNewTables as $tableRecord ) {
421 $updates[] = array(
422 'addTable', $tableRecord[0], $tableRecord[1], true
426 foreach ( $wgExtNewFields as $fieldRecord ) {
427 if ( $fieldRecord[0] != 'user' || $doUser ) {
428 $updates[] = array(
429 'addField', $fieldRecord[0], $fieldRecord[1],
430 $fieldRecord[2], true
435 foreach ( $wgExtNewIndexes as $fieldRecord ) {
436 $updates[] = array(
437 'addIndex', $fieldRecord[0], $fieldRecord[1],
438 $fieldRecord[2], true
442 foreach ( $wgExtModifiedFields as $fieldRecord ) {
443 $updates[] = array(
444 'modifyField', $fieldRecord[0], $fieldRecord[1],
445 $fieldRecord[2], true
449 return $updates;
453 * Get an array of updates to perform on the database. Should return a
454 * multi-dimensional array. The main key is the MediaWiki version (1.12,
455 * 1.13...) with the values being arrays of updates, identical to how
456 * updaters.inc did it (for now)
458 * @return Array
460 protected abstract function getCoreUpdateList();
463 * Applies a SQL patch
464 * @param $path String Path to the patch file
465 * @param $isFullPath Boolean Whether to treat $path as a relative or not
467 protected function applyPatch( $path, $isFullPath = false ) {
468 if ( $isFullPath ) {
469 $this->db->sourceFile( $path );
470 } else {
471 $this->db->sourceFile( $this->db->patchPath( $path ) );
476 * Add a new table to the database
477 * @param $name String Name of the new table
478 * @param $patch String Path to the patch file
479 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
481 protected function addTable( $name, $patch, $fullpath = false ) {
482 if ( $this->db->tableExists( $name, __METHOD__ ) ) {
483 $this->output( "...$name table already exists.\n" );
484 } else {
485 $this->output( "Creating $name table..." );
486 $this->applyPatch( $patch, $fullpath );
487 $this->output( "done.\n" );
492 * Add a new field to an existing table
493 * @param $table String Name of the table to modify
494 * @param $field String Name of the new field
495 * @param $patch String Path to the patch file
496 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
498 protected function addField( $table, $field, $patch, $fullpath = false ) {
499 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
500 $this->output( "...$table table does not exist, skipping new field patch.\n" );
501 } elseif ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
502 $this->output( "...have $field field in $table table.\n" );
503 } else {
504 $this->output( "Adding $field field to table $table..." );
505 $this->applyPatch( $patch, $fullpath );
506 $this->output( "done.\n" );
511 * Add a new index to an existing table
512 * @param $table String Name of the table to modify
513 * @param $index String Name of the new index
514 * @param $patch String Path to the patch file
515 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
517 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
518 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
519 $this->output( "...index $index already set on $table table.\n" );
520 } else {
521 $this->output( "Adding index $index to table $table... " );
522 $this->applyPatch( $patch, $fullpath );
523 $this->output( "done.\n" );
528 * Drop a field from an existing table
530 * @param $table String Name of the table to modify
531 * @param $field String Name of the old field
532 * @param $patch String Path to the patch file
533 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
535 protected function dropField( $table, $field, $patch, $fullpath = false ) {
536 if ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
537 $this->output( "Table $table contains $field field. Dropping... " );
538 $this->applyPatch( $patch, $fullpath );
539 $this->output( "done.\n" );
540 } else {
541 $this->output( "...$table table does not contain $field field.\n" );
546 * Drop an index from an existing table
548 * @param $table String: Name of the table to modify
549 * @param $index String: Name of the old index
550 * @param $patch String: Path to the patch file
551 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
553 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
554 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
555 $this->output( "Dropping $index index from table $table... " );
556 $this->applyPatch( $patch, $fullpath );
557 $this->output( "done.\n" );
558 } else {
559 $this->output( "...$index key doesn't exist.\n" );
564 * @param $table string
565 * @param $patch string
566 * @param $fullpath bool
568 protected function dropTable( $table, $patch, $fullpath = false ) {
569 if ( $this->db->tableExists( $table, __METHOD__ ) ) {
570 $this->output( "Dropping table $table... " );
571 $this->applyPatch( $patch, $fullpath );
572 $this->output( "done.\n" );
573 } else {
574 $this->output( "...$table doesn't exist.\n" );
579 * Modify an existing field
581 * @param $table String: name of the table to which the field belongs
582 * @param $field String: name of the field to modify
583 * @param $patch String: path to the patch file
584 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
586 public function modifyField( $table, $field, $patch, $fullpath = false ) {
587 $updateKey = "$table-$field-$patch";
588 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
589 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
590 } elseif ( !$this->db->fieldExists( $table, $field, __METHOD__ ) ) {
591 $this->output( "...$field field does not exist in $table table, skipping modify field patch.\n" );
592 } elseif( $this->updateRowExists( $updateKey ) ) {
593 $this->output( "...$field in table $table already modified by patch $patch.\n" );
594 } else {
595 $this->output( "Modifying $field field of table $table..." );
596 $this->applyPatch( $patch, $fullpath );
597 $this->insertUpdateRow( $updateKey );
598 $this->output( "done.\n" );
603 * Purge the objectcache table
605 protected function purgeCache() {
606 # We can't guarantee that the user will be able to use TRUNCATE,
607 # but we know that DELETE is available to us
608 $this->output( "Purging caches..." );
609 $this->db->delete( 'objectcache', '*', __METHOD__ );
610 $this->output( "done.\n" );
614 * Check the site_stats table is not properly populated.
616 protected function checkStats() {
617 $this->output( "...site_stats is populated..." );
618 $row = $this->db->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
619 if ( $row === false ) {
620 $this->output( "data is missing! rebuilding...\n" );
621 } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
622 $this->output( "missing ss_total_pages, rebuilding...\n" );
623 } else {
624 $this->output( "done.\n" );
625 return;
627 SiteStatsInit::doAllAndCommit( $this->db );
630 # Common updater functions
633 * Sets the number of active users in the site_stats table
635 protected function doActiveUsersInit() {
636 $activeUsers = $this->db->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
637 if ( $activeUsers == -1 ) {
638 $activeUsers = $this->db->selectField( 'recentchanges',
639 'COUNT( DISTINCT rc_user_text )',
640 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
642 $this->db->update( 'site_stats',
643 array( 'ss_active_users' => intval( $activeUsers ) ),
644 array( 'ss_row_id' => 1 ), __METHOD__, array( 'LIMIT' => 1 )
647 $this->output( "...ss_active_users user count set...\n" );
651 * Populates the log_user_text field in the logging table
653 protected function doLogUsertextPopulation() {
654 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
655 $this->output(
656 "Populating log_user_text field, printing progress markers. For large\n" .
657 "databases, you may want to hit Ctrl-C and do this manually with\n" .
658 "maintenance/populateLogUsertext.php.\n" );
660 $task = $this->maintenance->runChild( 'PopulateLogUsertext' );
661 $task->execute();
662 $this->output( "done.\n" );
667 * Migrate log params to new table and index for searching
669 protected function doLogSearchPopulation() {
670 if ( !$this->updateRowExists( 'populate log_search' ) ) {
671 $this->output(
672 "Populating log_search table, printing progress markers. For large\n" .
673 "databases, you may want to hit Ctrl-C and do this manually with\n" .
674 "maintenance/populateLogSearch.php.\n" );
676 $task = $this->maintenance->runChild( 'PopulateLogSearch' );
677 $task->execute();
678 $this->output( "done.\n" );
683 * Updates the timestamps in the transcache table
685 protected function doUpdateTranscacheField() {
686 if ( $this->updateRowExists( 'convert transcache field' ) ) {
687 $this->output( "...transcache tc_time already converted.\n" );
688 return;
691 $this->output( "Converting tc_time from UNIX epoch to MediaWiki timestamp... " );
692 $this->applyPatch( 'patch-tc-timestamp.sql' );
693 $this->output( "done.\n" );
697 * Update CategoryLinks collation
699 protected function doCollationUpdate() {
700 global $wgCategoryCollation;
701 if ( $this->db->selectField(
702 'categorylinks',
703 'COUNT(*)',
704 'cl_collation != ' . $this->db->addQuotes( $wgCategoryCollation ),
705 __METHOD__
706 ) == 0 ) {
707 $this->output( "...collations up-to-date.\n" );
708 return;
711 $this->output( "Updating category collations..." );
712 $task = $this->maintenance->runChild( 'UpdateCollation' );
713 $task->execute();
714 $this->output( "...done.\n" );
718 * Migrates user options from the user table blob to user_properties
720 protected function doMigrateUserOptions() {
721 $cl = $this->maintenance->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
722 $cl->execute();
723 $this->output( "done.\n" );
727 * Rebuilds the localisation cache
729 protected function rebuildLocalisationCache() {
731 * @var $cl RebuildLocalisationCache
733 $cl = $this->maintenance->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
734 $this->output( "Rebuilding localisation cache...\n" );
735 $cl->setForce();
736 $cl->execute();
737 $this->output( "done.\n" );