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
24 require_once( __DIR__
. '/../../maintenance/Maintenance.php' );
27 * Class for handling database updates. Roughly based off of updaters.inc, with
28 * a few improvements :)
33 abstract class DatabaseUpdater
{
36 * Array of updates to perform on the database
40 protected $updates = array();
43 * List of extension-provided database updates
46 protected $extensionUpdates = array();
49 * Handle to the database subclass
55 protected $shared = false;
58 * Scripts to run after database update
59 * Should be a subclass of LoggedUpdateMaintenance
61 protected $postDatabaseUpdateMaintenance = array(
62 'DeleteDefaultMessages',
63 'PopulateRevisionLength',
64 'PopulateRevisionSha1',
66 'FixExtLinksProtocolRelative',
67 'PopulateFilearchiveSha1',
73 * @param $db DatabaseBase object to perform updates on
74 * @param $shared bool Whether to perform updates on shared tables
75 * @param $maintenance Maintenance Maintenance object which created us
77 protected function __construct( DatabaseBase
&$db, $shared, Maintenance
$maintenance = null ) {
79 $this->db
->setFlag( DBO_DDLMODE
); // For Oracle's handling of schema files
80 $this->shared
= $shared;
82 $this->maintenance
= $maintenance;
84 $this->maintenance
= new FakeMaintenance
;
86 $this->maintenance
->setDB( $db );
87 $this->initOldGlobals();
88 $this->loadExtensions();
89 wfRunHooks( 'LoadExtensionSchemaUpdates', array( $this ) );
93 * Initialize all of the old globals. One day this should all become
94 * something much nicer
96 private function initOldGlobals() {
97 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
98 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
100 # For extensions only, should be populated via hooks
101 # $wgDBtype should be checked to specifiy the proper file
102 $wgExtNewTables = array(); // table, dir
103 $wgExtNewFields = array(); // table, column, dir
104 $wgExtPGNewFields = array(); // table, column, column attributes; for PostgreSQL
105 $wgExtPGAlteredFields = array(); // table, column, new type, conversion method; for PostgreSQL
106 $wgExtNewIndexes = array(); // table, index, dir
107 $wgExtModifiedFields = array(); // table, index, dir
111 * Loads LocalSettings.php, if needed, and initialises everything needed for LoadExtensionSchemaUpdates hook
113 private function loadExtensions() {
114 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
115 return; // already loaded
117 $vars = Installer
::getExistingLocalSettings();
119 return; // no LocalSettings found
121 if ( !isset( $vars['wgHooks'] ) ||
!isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
124 global $wgHooks, $wgAutoloadClasses;
125 $wgHooks['LoadExtensionSchemaUpdates'] = $vars['wgHooks']['LoadExtensionSchemaUpdates'];
126 $wgAutoloadClasses = $wgAutoloadClasses +
$vars['wgAutoloadClasses'];
130 * @throws MWException
131 * @param DatabaseBase $db
132 * @param bool $shared
133 * @param null $maintenance
134 * @return DatabaseUpdater
136 public static function newForDB( &$db, $shared = false, $maintenance = null ) {
137 $type = $db->getType();
138 if( in_array( $type, Installer
::getDBTypes() ) ) {
139 $class = ucfirst( $type ) . 'Updater';
140 return new $class( $db, $shared, $maintenance );
142 throw new MWException( __METHOD__
. ' called for unsupported $wgDBtype' );
147 * Get a database connection to run updates
149 * @return DatabaseBase
151 public function getDB() {
156 * Output some text. If we're running from web, escape the text first.
158 * @param $str String: Text to output
160 public function output( $str ) {
161 if ( $this->maintenance
->isQuiet() ) {
164 global $wgCommandLineMode;
165 if( !$wgCommandLineMode ) {
166 $str = htmlspecialchars( $str );
173 * Add a new update coming from an extension. This should be called by
174 * extensions while executing the LoadExtensionSchemaUpdates hook.
178 * @param $update Array: the update to run. Format is the following:
179 * first item is the callback function, it also can be a
180 * simple string with the name of a function in this class,
181 * following elements are parameters to the function.
182 * Note that callback functions will receive this object as
185 public function addExtensionUpdate( array $update ) {
186 $this->extensionUpdates
[] = $update;
190 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
191 * is the most common usage of updaters in an extension)
195 * @param $tableName String Name of table to create
196 * @param $sqlPath String Full path to the schema file
198 public function addExtensionTable( $tableName, $sqlPath ) {
199 $this->extensionUpdates
[] = array( 'addTable', $tableName, $sqlPath, true );
205 * @param $tableName string
206 * @param $indexName string
207 * @param $sqlPath string
209 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
210 $this->extensionUpdates
[] = array( 'addIndex', $tableName, $indexName, $sqlPath, true );
217 * @param $tableName string
218 * @param $columnName string
219 * @param $sqlPath string
221 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
222 $this->extensionUpdates
[] = array( 'addField', $tableName, $columnName, $sqlPath, true );
229 * @param $tableName string
230 * @param $columnName string
231 * @param $sqlPath string
233 public function dropExtensionField( $tableName, $columnName, $sqlPath ) {
234 $this->extensionUpdates
[] = array( 'dropField', $tableName, $columnName, $sqlPath, true );
241 * @param $tableName string
242 * @param $sqlPath string
244 public function dropExtensionTable( $tableName, $sqlPath ) {
245 $this->extensionUpdates
[] = array( 'dropTable', $tableName, $sqlPath, true );
252 * @param $tableName string
255 public function tableExists( $tableName ) {
256 return ( $this->db
->tableExists( $tableName, __METHOD__
) );
260 * Add a maintenance script to be run after the database updates are complete.
262 * Script should subclass LoggedUpdateMaintenance
266 * @param $class string Name of a Maintenance subclass
268 public function addPostDatabaseUpdateMaintenance( $class ) {
269 $this->postDatabaseUpdateMaintenance
[] = $class;
273 * Get the list of extension-defined updates
277 protected function getExtensionUpdates() {
278 return $this->extensionUpdates
;
286 public function getPostDatabaseUpdateMaintenance() {
287 return $this->postDatabaseUpdateMaintenance
;
293 * @param $what Array: what updates to perform
295 public function doUpdates( $what = array( 'core', 'extensions', 'purge', 'stats' ) ) {
296 global $wgLocalisationCacheConf, $wgVersion;
298 $this->db
->begin( __METHOD__
);
299 $what = array_flip( $what );
300 if ( isset( $what['core'] ) ) {
301 $this->runUpdates( $this->getCoreUpdateList(), false );
303 if ( isset( $what['extensions'] ) ) {
304 $this->runUpdates( $this->getOldGlobalUpdates(), false );
305 $this->runUpdates( $this->getExtensionUpdates(), true );
308 $this->setAppliedUpdates( $wgVersion, $this->updates
);
310 if ( isset( $what['stats'] ) ) {
314 if ( isset( $what['purge'] ) ) {
317 if ( $wgLocalisationCacheConf['manualRecache'] ) {
318 $this->rebuildLocalisationCache();
321 $this->db
->commit( __METHOD__
);
325 * Helper function for doUpdates()
327 * @param $updates Array of updates to run
328 * @param $passSelf Boolean: whether to pass this object we calling external
331 private function runUpdates( array $updates, $passSelf ) {
332 foreach ( $updates as $params ) {
333 $func = array_shift( $params );
334 if( !is_array( $func ) && method_exists( $this, $func ) ) {
335 $func = array( $this, $func );
336 } elseif ( $passSelf ) {
337 array_unshift( $params, $this );
339 call_user_func_array( $func, $params );
342 $this->updates
= array_merge( $this->updates
, $updates );
347 * @param $updates array
349 protected function setAppliedUpdates( $version, $updates = array() ) {
350 $this->db
->clearFlag( DBO_DDLMODE
);
351 if( !$this->canUseNewUpdatelog() ) {
354 $key = "updatelist-$version-" . time();
355 $this->db
->insert( 'updatelog',
356 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
358 $this->db
->setFlag( DBO_DDLMODE
);
362 * Helper function: check if the given key is present in the updatelog table.
363 * Obviously, only use this for updates that occur after the updatelog table was
365 * @param $key String Name of the key to check for
369 public function updateRowExists( $key ) {
370 $row = $this->db
->selectRow(
373 array( 'ul_key' => $key ),
380 * Helper function: Add a key to the updatelog table
381 * Obviously, only use this for updates that occur after the updatelog table was
383 * @param $key String Name of key to insert
384 * @param $val String [optional] value to insert along with the key
386 public function insertUpdateRow( $key, $val = null ) {
387 $this->db
->clearFlag( DBO_DDLMODE
);
388 $values = array( 'ul_key' => $key );
389 if( $val && $this->canUseNewUpdatelog() ) {
390 $values['ul_value'] = $val;
392 $this->db
->insert( 'updatelog', $values, __METHOD__
, 'IGNORE' );
393 $this->db
->setFlag( DBO_DDLMODE
);
397 * Updatelog was changed in 1.17 to have a ul_value column so we can record
398 * more information about what kind of updates we've done (that's what this
399 * class does). Pre-1.17 wikis won't have this column, and really old wikis
400 * might not even have updatelog at all
404 protected function canUseNewUpdatelog() {
405 return $this->db
->tableExists( 'updatelog', __METHOD__
) &&
406 $this->db
->fieldExists( 'updatelog', 'ul_value', __METHOD__
);
410 * Before 1.17, we used to handle updates via stuff like
411 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
412 * of this in 1.17 but we want to remain back-compatible for a while. So
413 * load up these old global-based things into our update list.
417 protected function getOldGlobalUpdates() {
418 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
419 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
421 $doUser = $this->shared ?
422 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
423 !$wgSharedDB ||
!in_array( 'user', $wgSharedTables );
427 foreach ( $wgExtNewTables as $tableRecord ) {
429 'addTable', $tableRecord[0], $tableRecord[1], true
433 foreach ( $wgExtNewFields as $fieldRecord ) {
434 if ( $fieldRecord[0] != 'user' ||
$doUser ) {
436 'addField', $fieldRecord[0], $fieldRecord[1],
437 $fieldRecord[2], true
442 foreach ( $wgExtNewIndexes as $fieldRecord ) {
444 'addIndex', $fieldRecord[0], $fieldRecord[1],
445 $fieldRecord[2], true
449 foreach ( $wgExtModifiedFields as $fieldRecord ) {
451 'modifyField', $fieldRecord[0], $fieldRecord[1],
452 $fieldRecord[2], true
460 * Get an array of updates to perform on the database. Should return a
461 * multi-dimensional array. The main key is the MediaWiki version (1.12,
462 * 1.13...) with the values being arrays of updates, identical to how
463 * updaters.inc did it (for now)
467 protected abstract function getCoreUpdateList();
470 * Applies a SQL patch
471 * @param $path String Path to the patch file
472 * @param $isFullPath Boolean Whether to treat $path as a relative or not
473 * @param $msg String Description of the patch
475 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
476 if ( $msg === null ) {
477 $msg = "Applying $path patch";
480 if ( !$isFullPath ) {
481 $path = $this->db
->patchPath( $path );
484 $this->output( "$msg ..." );
485 $this->db
->sourceFile( $path );
486 $this->output( "done.\n" );
490 * Add a new table to the database
491 * @param $name String Name of the new table
492 * @param $patch String Path to the patch file
493 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
495 protected function addTable( $name, $patch, $fullpath = false ) {
496 if ( $this->db
->tableExists( $name, __METHOD__
) ) {
497 $this->output( "...$name table already exists.\n" );
499 $this->applyPatch( $patch, $fullpath, "Creating $name table" );
504 * Add a new field to an existing table
505 * @param $table String Name of the table to modify
506 * @param $field String Name of the new field
507 * @param $patch String Path to the patch file
508 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
510 protected function addField( $table, $field, $patch, $fullpath = false ) {
511 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
512 $this->output( "...$table table does not exist, skipping new field patch.\n" );
513 } elseif ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
514 $this->output( "...have $field field in $table table.\n" );
516 $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
521 * Add a new index to an existing table
522 * @param $table String Name of the table to modify
523 * @param $index String Name of the new index
524 * @param $patch String Path to the patch file
525 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
527 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
528 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
529 $this->output( "...index $index already set on $table table.\n" );
531 $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
536 * Drop a field from an existing table
538 * @param $table String Name of the table to modify
539 * @param $field String Name of the old field
540 * @param $patch String Path to the patch file
541 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
543 protected function dropField( $table, $field, $patch, $fullpath = false ) {
544 if ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
545 $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
547 $this->output( "...$table table does not contain $field field.\n" );
552 * Drop an index from an existing table
554 * @param $table String: Name of the table to modify
555 * @param $index String: Name of the old index
556 * @param $patch String: Path to the patch file
557 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
559 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
560 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
561 $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
563 $this->output( "...$index key doesn't exist.\n" );
568 * If the specified table exists, drop it, or execute the
569 * patch if one is provided.
573 * @param $table string
574 * @param $patch string|false
575 * @param $fullpath bool
577 public function dropTable( $table, $patch = false, $fullpath = false ) {
578 if ( $this->db
->tableExists( $table, __METHOD__
) ) {
579 $msg = "Dropping table $table";
581 if ( $patch === false ) {
582 $this->output( "$msg ..." );
583 $this->db
->dropTable( $table, __METHOD__
);
584 $this->output( "done.\n" );
587 $this->applyPatch( $patch, $fullpath, $msg );
591 $this->output( "...$table doesn't exist.\n" );
596 * Modify an existing field
598 * @param $table String: name of the table to which the field belongs
599 * @param $field String: name of the field to modify
600 * @param $patch String: path to the patch file
601 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
603 public function modifyField( $table, $field, $patch, $fullpath = false ) {
604 $updateKey = "$table-$field-$patch";
605 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
606 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
607 } elseif ( !$this->db
->fieldExists( $table, $field, __METHOD__
) ) {
608 $this->output( "...$field field does not exist in $table table, skipping modify field patch.\n" );
609 } elseif( $this->updateRowExists( $updateKey ) ) {
610 $this->output( "...$field in table $table already modified by patch $patch.\n" );
612 $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
613 $this->insertUpdateRow( $updateKey );
618 * Purge the objectcache table
620 protected function purgeCache() {
621 # We can't guarantee that the user will be able to use TRUNCATE,
622 # but we know that DELETE is available to us
623 $this->output( "Purging caches..." );
624 $this->db
->delete( 'objectcache', '*', __METHOD__
);
625 $this->output( "done.\n" );
629 * Check the site_stats table is not properly populated.
631 protected function checkStats() {
632 $this->output( "...site_stats is populated..." );
633 $row = $this->db
->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__
);
634 if ( $row === false ) {
635 $this->output( "data is missing! rebuilding...\n" );
636 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
637 $this->output( "missing ss_total_pages, rebuilding...\n" );
639 $this->output( "done.\n" );
642 SiteStatsInit
::doAllAndCommit( $this->db
);
645 # Common updater functions
648 * Sets the number of active users in the site_stats table
650 protected function doActiveUsersInit() {
651 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', false, __METHOD__
);
652 if ( $activeUsers == -1 ) {
653 $activeUsers = $this->db
->selectField( 'recentchanges',
654 'COUNT( DISTINCT rc_user_text )',
655 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
657 $this->db
->update( 'site_stats',
658 array( 'ss_active_users' => intval( $activeUsers ) ),
659 array( 'ss_row_id' => 1 ), __METHOD__
, array( 'LIMIT' => 1 )
662 $this->output( "...ss_active_users user count set...\n" );
666 * Populates the log_user_text field in the logging table
668 protected function doLogUsertextPopulation() {
669 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
671 "Populating log_user_text field, printing progress markers. For large\n" .
672 "databases, you may want to hit Ctrl-C and do this manually with\n" .
673 "maintenance/populateLogUsertext.php.\n" );
675 $task = $this->maintenance
->runChild( 'PopulateLogUsertext' );
677 $this->output( "done.\n" );
682 * Migrate log params to new table and index for searching
684 protected function doLogSearchPopulation() {
685 if ( !$this->updateRowExists( 'populate log_search' ) ) {
687 "Populating log_search table, printing progress markers. For large\n" .
688 "databases, you may want to hit Ctrl-C and do this manually with\n" .
689 "maintenance/populateLogSearch.php.\n" );
691 $task = $this->maintenance
->runChild( 'PopulateLogSearch' );
693 $this->output( "done.\n" );
698 * Updates the timestamps in the transcache table
700 protected function doUpdateTranscacheField() {
701 if ( $this->updateRowExists( 'convert transcache field' ) ) {
702 $this->output( "...transcache tc_time already converted.\n" );
706 $this->applyPatch( 'patch-tc-timestamp.sql', false, "Converting tc_time from UNIX epoch to MediaWiki timestamp" );
710 * Update CategoryLinks collation
712 protected function doCollationUpdate() {
713 global $wgCategoryCollation;
714 if ( $this->db
->selectField(
717 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
720 $this->output( "...collations up-to-date.\n" );
724 $this->output( "Updating category collations..." );
725 $task = $this->maintenance
->runChild( 'UpdateCollation' );
727 $this->output( "...done.\n" );
731 * Migrates user options from the user table blob to user_properties
733 protected function doMigrateUserOptions() {
734 $cl = $this->maintenance
->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
736 $this->output( "done.\n" );
740 * Rebuilds the localisation cache
742 protected function rebuildLocalisationCache() {
744 * @var $cl RebuildLocalisationCache
746 $cl = $this->maintenance
->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
747 $this->output( "Rebuilding localisation cache...\n" );
750 $this->output( "done.\n" );