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',
72 * @param $db DatabaseBase object to perform updates on
73 * @param $shared bool Whether to perform updates on shared tables
74 * @param $maintenance Maintenance Maintenance object which created us
76 protected function __construct( DatabaseBase
&$db, $shared, Maintenance
$maintenance = null ) {
78 $this->db
->setFlag( DBO_DDLMODE
); // For Oracle's handling of schema files
79 $this->shared
= $shared;
81 $this->maintenance
= $maintenance;
83 $this->maintenance
= new FakeMaintenance
;
85 $this->maintenance
->setDB( $db );
86 $this->initOldGlobals();
87 $this->loadExtensions();
88 wfRunHooks( 'LoadExtensionSchemaUpdates', array( $this ) );
92 * Initialize all of the old globals. One day this should all become
93 * something much nicer
95 private function initOldGlobals() {
96 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
97 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
99 # For extensions only, should be populated via hooks
100 # $wgDBtype should be checked to specifiy the proper file
101 $wgExtNewTables = array(); // table, dir
102 $wgExtNewFields = array(); // table, column, dir
103 $wgExtPGNewFields = array(); // table, column, column attributes; for PostgreSQL
104 $wgExtPGAlteredFields = array(); // table, column, new type, conversion method; for PostgreSQL
105 $wgExtNewIndexes = array(); // table, index, dir
106 $wgExtModifiedFields = array(); // table, index, dir
110 * Loads LocalSettings.php, if needed, and initialises everything needed for LoadExtensionSchemaUpdates hook
112 private function loadExtensions() {
113 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
114 return; // already loaded
116 $vars = Installer
::getExistingLocalSettings();
118 return; // no LocalSettings found
120 if ( !isset( $vars['wgHooks'] ) ||
!isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
123 global $wgHooks, $wgAutoloadClasses;
124 $wgHooks['LoadExtensionSchemaUpdates'] = $vars['wgHooks']['LoadExtensionSchemaUpdates'];
125 $wgAutoloadClasses = $wgAutoloadClasses +
$vars['wgAutoloadClasses'];
129 * @throws MWException
130 * @param DatabaseBase $db
131 * @param bool $shared
132 * @param null $maintenance
133 * @return DatabaseUpdater
135 public static function newForDB( &$db, $shared = false, $maintenance = null ) {
136 $type = $db->getType();
137 if( in_array( $type, Installer
::getDBTypes() ) ) {
138 $class = ucfirst( $type ) . 'Updater';
139 return new $class( $db, $shared, $maintenance );
141 throw new MWException( __METHOD__
. ' called for unsupported $wgDBtype' );
146 * Get a database connection to run updates
148 * @return DatabaseBase
150 public function getDB() {
155 * Output some text. If we're running from web, escape the text first.
157 * @param $str String: Text to output
159 public function output( $str ) {
160 if ( $this->maintenance
->isQuiet() ) {
163 global $wgCommandLineMode;
164 if( !$wgCommandLineMode ) {
165 $str = htmlspecialchars( $str );
172 * Add a new update coming from an extension. This should be called by
173 * extensions while executing the LoadExtensionSchemaUpdates hook.
177 * @param $update Array: the update to run. Format is the following:
178 * first item is the callback function, it also can be a
179 * simple string with the name of a function in this class,
180 * following elements are parameters to the function.
181 * Note that callback functions will receive this object as
184 public function addExtensionUpdate( array $update ) {
185 $this->extensionUpdates
[] = $update;
189 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
190 * is the most common usage of updaters in an extension)
194 * @param $tableName String Name of table to create
195 * @param $sqlPath String Full path to the schema file
197 public function addExtensionTable( $tableName, $sqlPath ) {
198 $this->extensionUpdates
[] = array( 'addTable', $tableName, $sqlPath, true );
204 * @param $tableName string
205 * @param $indexName string
206 * @param $sqlPath string
208 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
209 $this->extensionUpdates
[] = array( 'addIndex', $tableName, $indexName, $sqlPath, true );
216 * @param $tableName string
217 * @param $columnName string
218 * @param $sqlPath string
220 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
221 $this->extensionUpdates
[] = array( 'addField', $tableName, $columnName, $sqlPath, true );
228 * @param $tableName string
229 * @param $columnName string
230 * @param $sqlPath string
232 public function dropExtensionField( $tableName, $columnName, $sqlPath ) {
233 $this->extensionUpdates
[] = array( 'dropField', $tableName, $columnName, $sqlPath, true );
240 * @param $tableName string
241 * @param $sqlPath string
243 public function dropExtensionTable( $tableName, $sqlPath ) {
244 $this->extensionUpdates
[] = array( 'dropTable', $tableName, $sqlPath, true );
251 * @param $tableName string
254 public function tableExists( $tableName ) {
255 return ( $this->db
->tableExists( $tableName, __METHOD__
) );
259 * Add a maintenance script to be run after the database updates are complete.
261 * Script should subclass LoggedUpdateMaintenance
265 * @param $class string Name of a Maintenance subclass
267 public function addPostDatabaseUpdateMaintenance( $class ) {
268 $this->postDatabaseUpdateMaintenance
[] = $class;
272 * Get the list of extension-defined updates
276 protected function getExtensionUpdates() {
277 return $this->extensionUpdates
;
285 public function getPostDatabaseUpdateMaintenance() {
286 return $this->postDatabaseUpdateMaintenance
;
292 * @param $what Array: what updates to perform
294 public function doUpdates( $what = array( 'core', 'extensions', 'purge', 'stats' ) ) {
295 global $wgLocalisationCacheConf, $wgVersion;
297 $this->db
->begin( __METHOD__
);
298 $what = array_flip( $what );
299 if ( isset( $what['core'] ) ) {
300 $this->runUpdates( $this->getCoreUpdateList(), false );
302 if ( isset( $what['extensions'] ) ) {
303 $this->runUpdates( $this->getOldGlobalUpdates(), false );
304 $this->runUpdates( $this->getExtensionUpdates(), true );
307 $this->setAppliedUpdates( $wgVersion, $this->updates
);
309 if ( isset( $what['stats'] ) ) {
313 if ( isset( $what['purge'] ) ) {
316 if ( $wgLocalisationCacheConf['manualRecache'] ) {
317 $this->rebuildLocalisationCache();
320 $this->db
->commit( __METHOD__
);
324 * Helper function for doUpdates()
326 * @param $updates Array of updates to run
327 * @param $passSelf Boolean: whether to pass this object we calling external
330 private function runUpdates( array $updates, $passSelf ) {
331 foreach ( $updates as $params ) {
332 $func = array_shift( $params );
333 if( !is_array( $func ) && method_exists( $this, $func ) ) {
334 $func = array( $this, $func );
335 } elseif ( $passSelf ) {
336 array_unshift( $params, $this );
338 call_user_func_array( $func, $params );
341 $this->updates
= array_merge( $this->updates
, $updates );
346 * @param $updates array
348 protected function setAppliedUpdates( $version, $updates = array() ) {
349 $this->db
->clearFlag( DBO_DDLMODE
);
350 if( !$this->canUseNewUpdatelog() ) {
353 $key = "updatelist-$version-" . time();
354 $this->db
->insert( 'updatelog',
355 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
357 $this->db
->setFlag( DBO_DDLMODE
);
361 * Helper function: check if the given key is present in the updatelog table.
362 * Obviously, only use this for updates that occur after the updatelog table was
364 * @param $key String Name of the key to check for
368 public function updateRowExists( $key ) {
369 $row = $this->db
->selectRow(
372 array( 'ul_key' => $key ),
379 * Helper function: Add a key to the updatelog table
380 * Obviously, only use this for updates that occur after the updatelog table was
382 * @param $key String Name of key to insert
383 * @param $val String [optional] value to insert along with the key
385 public function insertUpdateRow( $key, $val = null ) {
386 $this->db
->clearFlag( DBO_DDLMODE
);
387 $values = array( 'ul_key' => $key );
388 if( $val && $this->canUseNewUpdatelog() ) {
389 $values['ul_value'] = $val;
391 $this->db
->insert( 'updatelog', $values, __METHOD__
, 'IGNORE' );
392 $this->db
->setFlag( DBO_DDLMODE
);
396 * Updatelog was changed in 1.17 to have a ul_value column so we can record
397 * more information about what kind of updates we've done (that's what this
398 * class does). Pre-1.17 wikis won't have this column, and really old wikis
399 * might not even have updatelog at all
403 protected function canUseNewUpdatelog() {
404 return $this->db
->tableExists( 'updatelog', __METHOD__
) &&
405 $this->db
->fieldExists( 'updatelog', 'ul_value', __METHOD__
);
409 * Before 1.17, we used to handle updates via stuff like
410 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
411 * of this in 1.17 but we want to remain back-compatible for a while. So
412 * load up these old global-based things into our update list.
416 protected function getOldGlobalUpdates() {
417 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
418 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
420 $doUser = $this->shared ?
421 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
422 !$wgSharedDB ||
!in_array( 'user', $wgSharedTables );
426 foreach ( $wgExtNewTables as $tableRecord ) {
428 'addTable', $tableRecord[0], $tableRecord[1], true
432 foreach ( $wgExtNewFields as $fieldRecord ) {
433 if ( $fieldRecord[0] != 'user' ||
$doUser ) {
435 'addField', $fieldRecord[0], $fieldRecord[1],
436 $fieldRecord[2], true
441 foreach ( $wgExtNewIndexes as $fieldRecord ) {
443 'addIndex', $fieldRecord[0], $fieldRecord[1],
444 $fieldRecord[2], true
448 foreach ( $wgExtModifiedFields as $fieldRecord ) {
450 'modifyField', $fieldRecord[0], $fieldRecord[1],
451 $fieldRecord[2], true
459 * Get an array of updates to perform on the database. Should return a
460 * multi-dimensional array. The main key is the MediaWiki version (1.12,
461 * 1.13...) with the values being arrays of updates, identical to how
462 * updaters.inc did it (for now)
466 protected abstract function getCoreUpdateList();
469 * Applies a SQL patch
470 * @param $path String Path to the patch file
471 * @param $isFullPath Boolean Whether to treat $path as a relative or not
472 * @param $msg String Description of the patch
474 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
475 if ( $msg === null ) {
476 $msg = "Applying $path patch";
479 if ( !$isFullPath ) {
480 $path = $this->db
->patchPath( $path );
483 $this->output( "$msg ..." );
484 $this->db
->sourceFile( $path );
485 $this->output( "done.\n" );
489 * Add a new table to the database
490 * @param $name String Name of the new table
491 * @param $patch String Path to the patch file
492 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
494 protected function addTable( $name, $patch, $fullpath = false ) {
495 if ( $this->db
->tableExists( $name, __METHOD__
) ) {
496 $this->output( "...$name table already exists.\n" );
498 $this->applyPatch( $patch, $fullpath, "Creating $name table" );
503 * Add a new field to an existing table
504 * @param $table String Name of the table to modify
505 * @param $field String Name of the new field
506 * @param $patch String Path to the patch file
507 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
509 protected function addField( $table, $field, $patch, $fullpath = false ) {
510 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
511 $this->output( "...$table table does not exist, skipping new field patch.\n" );
512 } elseif ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
513 $this->output( "...have $field field in $table table.\n" );
515 $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
520 * Add a new index to an existing table
521 * @param $table String Name of the table to modify
522 * @param $index String Name of the new index
523 * @param $patch String Path to the patch file
524 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
526 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
527 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
528 $this->output( "...index $index already set on $table table.\n" );
530 $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
535 * Drop a field from an existing table
537 * @param $table String Name of the table to modify
538 * @param $field String Name of the old field
539 * @param $patch String Path to the patch file
540 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
542 protected function dropField( $table, $field, $patch, $fullpath = false ) {
543 if ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
544 $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
546 $this->output( "...$table table does not contain $field field.\n" );
551 * Drop an index from an existing table
553 * @param $table String: Name of the table to modify
554 * @param $index String: Name of the old index
555 * @param $patch String: Path to the patch file
556 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
558 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
559 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
560 $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
562 $this->output( "...$index key doesn't exist.\n" );
567 * If the specified table exists, drop it, or execute the
568 * patch if one is provided.
572 * @param $table string
573 * @param $patch string|false
574 * @param $fullpath bool
576 public function dropTable( $table, $patch = false, $fullpath = false ) {
577 if ( $this->db
->tableExists( $table, __METHOD__
) ) {
578 $msg = "Dropping table $table";
580 if ( $patch === false ) {
581 $this->output( "$msg ..." );
582 $this->db
->dropTable( $table, __METHOD__
);
583 $this->output( "done.\n" );
586 $this->applyPatch( $patch, $fullpath, $msg );
590 $this->output( "...$table doesn't exist.\n" );
595 * Modify an existing field
597 * @param $table String: name of the table to which the field belongs
598 * @param $field String: name of the field to modify
599 * @param $patch String: path to the patch file
600 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
602 public function modifyField( $table, $field, $patch, $fullpath = false ) {
603 $updateKey = "$table-$field-$patch";
604 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
605 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
606 } elseif ( !$this->db
->fieldExists( $table, $field, __METHOD__
) ) {
607 $this->output( "...$field field does not exist in $table table, skipping modify field patch.\n" );
608 } elseif( $this->updateRowExists( $updateKey ) ) {
609 $this->output( "...$field in table $table already modified by patch $patch.\n" );
611 $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
612 $this->insertUpdateRow( $updateKey );
617 * Purge the objectcache table
619 protected function purgeCache() {
620 # We can't guarantee that the user will be able to use TRUNCATE,
621 # but we know that DELETE is available to us
622 $this->output( "Purging caches..." );
623 $this->db
->delete( 'objectcache', '*', __METHOD__
);
624 $this->output( "done.\n" );
628 * Check the site_stats table is not properly populated.
630 protected function checkStats() {
631 $this->output( "...site_stats is populated..." );
632 $row = $this->db
->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__
);
633 if ( $row === false ) {
634 $this->output( "data is missing! rebuilding...\n" );
635 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
636 $this->output( "missing ss_total_pages, rebuilding...\n" );
638 $this->output( "done.\n" );
641 SiteStatsInit
::doAllAndCommit( $this->db
);
644 # Common updater functions
647 * Sets the number of active users in the site_stats table
649 protected function doActiveUsersInit() {
650 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', false, __METHOD__
);
651 if ( $activeUsers == -1 ) {
652 $activeUsers = $this->db
->selectField( 'recentchanges',
653 'COUNT( DISTINCT rc_user_text )',
654 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
656 $this->db
->update( 'site_stats',
657 array( 'ss_active_users' => intval( $activeUsers ) ),
658 array( 'ss_row_id' => 1 ), __METHOD__
, array( 'LIMIT' => 1 )
661 $this->output( "...ss_active_users user count set...\n" );
665 * Populates the log_user_text field in the logging table
667 protected function doLogUsertextPopulation() {
668 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
670 "Populating log_user_text field, printing progress markers. For large\n" .
671 "databases, you may want to hit Ctrl-C and do this manually with\n" .
672 "maintenance/populateLogUsertext.php.\n" );
674 $task = $this->maintenance
->runChild( 'PopulateLogUsertext' );
676 $this->output( "done.\n" );
681 * Migrate log params to new table and index for searching
683 protected function doLogSearchPopulation() {
684 if ( !$this->updateRowExists( 'populate log_search' ) ) {
686 "Populating log_search table, printing progress markers. For large\n" .
687 "databases, you may want to hit Ctrl-C and do this manually with\n" .
688 "maintenance/populateLogSearch.php.\n" );
690 $task = $this->maintenance
->runChild( 'PopulateLogSearch' );
692 $this->output( "done.\n" );
697 * Updates the timestamps in the transcache table
699 protected function doUpdateTranscacheField() {
700 if ( $this->updateRowExists( 'convert transcache field' ) ) {
701 $this->output( "...transcache tc_time already converted.\n" );
705 $this->applyPatch( 'patch-tc-timestamp.sql', false, "Converting tc_time from UNIX epoch to MediaWiki timestamp" );
709 * Update CategoryLinks collation
711 protected function doCollationUpdate() {
712 global $wgCategoryCollation;
713 if ( $this->db
->selectField(
716 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
719 $this->output( "...collations up-to-date.\n" );
723 $this->output( "Updating category collations..." );
724 $task = $this->maintenance
->runChild( 'UpdateCollation' );
726 $this->output( "...done.\n" );
730 * Migrates user options from the user table blob to user_properties
732 protected function doMigrateUserOptions() {
733 $cl = $this->maintenance
->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
735 $this->output( "done.\n" );
739 * Rebuilds the localisation cache
741 protected function rebuildLocalisationCache() {
743 * @var $cl RebuildLocalisationCache
745 $cl = $this->maintenance
->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
746 $this->output( "Rebuilding localisation cache...\n" );
749 $this->output( "done.\n" );