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', 'stats' ) ) {
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'] ) ) {
313 $this->db
->commit( __METHOD__
);
317 * Helper function for doUpdates()
319 * @param $updates Array of updates to run
320 * @param $passSelf Boolean: whether to pass this object we calling external
323 private function runUpdates( array $updates, $passSelf ) {
324 foreach ( $updates as $params ) {
325 $func = array_shift( $params );
326 if( !is_array( $func ) && method_exists( $this, $func ) ) {
327 $func = array( $this, $func );
328 } elseif ( $passSelf ) {
329 array_unshift( $params, $this );
331 call_user_func_array( $func, $params );
334 $this->updates
= array_merge( $this->updates
, $updates );
339 * @param $updates array
341 protected function setAppliedUpdates( $version, $updates = array() ) {
342 $this->db
->clearFlag( DBO_DDLMODE
);
343 if( !$this->canUseNewUpdatelog() ) {
346 $key = "updatelist-$version-" . time();
347 $this->db
->insert( 'updatelog',
348 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
350 $this->db
->setFlag( DBO_DDLMODE
);
354 * Helper function: check if the given key is present in the updatelog table.
355 * Obviously, only use this for updates that occur after the updatelog table was
357 * @param $key String Name of the key to check for
361 public function updateRowExists( $key ) {
362 $row = $this->db
->selectRow(
365 array( 'ul_key' => $key ),
372 * Helper function: Add a key to the updatelog table
373 * Obviously, only use this for updates that occur after the updatelog table was
375 * @param $key String Name of key to insert
376 * @param $val String [optional] value to insert along with the key
378 public function insertUpdateRow( $key, $val = null ) {
379 $this->db
->clearFlag( DBO_DDLMODE
);
380 $values = array( 'ul_key' => $key );
381 if( $val && $this->canUseNewUpdatelog() ) {
382 $values['ul_value'] = $val;
384 $this->db
->insert( 'updatelog', $values, __METHOD__
, 'IGNORE' );
385 $this->db
->setFlag( DBO_DDLMODE
);
389 * Updatelog was changed in 1.17 to have a ul_value column so we can record
390 * more information about what kind of updates we've done (that's what this
391 * class does). Pre-1.17 wikis won't have this column, and really old wikis
392 * might not even have updatelog at all
396 protected function canUseNewUpdatelog() {
397 return $this->db
->tableExists( 'updatelog', __METHOD__
) &&
398 $this->db
->fieldExists( 'updatelog', 'ul_value', __METHOD__
);
402 * Before 1.17, we used to handle updates via stuff like
403 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
404 * of this in 1.17 but we want to remain back-compatible for a while. So
405 * load up these old global-based things into our update list.
409 protected function getOldGlobalUpdates() {
410 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
411 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
413 $doUser = $this->shared ?
414 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
415 !$wgSharedDB ||
!in_array( 'user', $wgSharedTables );
419 foreach ( $wgExtNewTables as $tableRecord ) {
421 'addTable', $tableRecord[0], $tableRecord[1], true
425 foreach ( $wgExtNewFields as $fieldRecord ) {
426 if ( $fieldRecord[0] != 'user' ||
$doUser ) {
428 'addField', $fieldRecord[0], $fieldRecord[1],
429 $fieldRecord[2], true
434 foreach ( $wgExtNewIndexes as $fieldRecord ) {
436 'addIndex', $fieldRecord[0], $fieldRecord[1],
437 $fieldRecord[2], true
441 foreach ( $wgExtModifiedFields as $fieldRecord ) {
443 'modifyField', $fieldRecord[0], $fieldRecord[1],
444 $fieldRecord[2], true
452 * Get an array of updates to perform on the database. Should return a
453 * multi-dimensional array. The main key is the MediaWiki version (1.12,
454 * 1.13...) with the values being arrays of updates, identical to how
455 * updaters.inc did it (for now)
459 protected abstract function getCoreUpdateList();
462 * Applies a SQL patch
463 * @param $path String Path to the patch file
464 * @param $isFullPath Boolean Whether to treat $path as a relative or not
465 * @param $msg String Description of the patch
467 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
468 if ( $msg === null ) {
469 $msg = "Applying $path patch";
472 if ( !$isFullPath ) {
473 $path = $this->db
->patchPath( $path );
476 $this->output( "$msg ..." );
477 $this->db
->sourceFile( $path );
478 $this->output( "done.\n" );
482 * Add a new table to the database
483 * @param $name String Name of the new table
484 * @param $patch String Path to the patch file
485 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
487 protected function addTable( $name, $patch, $fullpath = false ) {
488 if ( $this->db
->tableExists( $name, __METHOD__
) ) {
489 $this->output( "...$name table already exists.\n" );
491 $this->applyPatch( $patch, $fullpath, "Creating $name table" );
496 * Add a new field to an existing table
497 * @param $table String Name of the table to modify
498 * @param $field String Name of the new field
499 * @param $patch String Path to the patch file
500 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
502 protected function addField( $table, $field, $patch, $fullpath = false ) {
503 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
504 $this->output( "...$table table does not exist, skipping new field patch.\n" );
505 } elseif ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
506 $this->output( "...have $field field in $table table.\n" );
508 $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
513 * Add a new index to an existing table
514 * @param $table String Name of the table to modify
515 * @param $index String Name of the new index
516 * @param $patch String Path to the patch file
517 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
519 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
520 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
521 $this->output( "...index $index already set on $table table.\n" );
523 $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
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->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
539 $this->output( "...$table table does not contain $field field.\n" );
544 * Drop an index from an existing table
546 * @param $table String: Name of the table to modify
547 * @param $index String: Name of the old index
548 * @param $patch String: Path to the patch file
549 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
551 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
552 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
553 $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
555 $this->output( "...$index key doesn't exist.\n" );
560 * If the specified table exists, drop it, or execute the
561 * patch if one is provided.
565 * @param $table string
566 * @param $patch string|false
567 * @param $fullpath bool
569 public function dropTable( $table, $patch = false, $fullpath = false ) {
570 if ( $this->db
->tableExists( $table, __METHOD__
) ) {
571 $msg = "Dropping table $table";
573 if ( $patch === false ) {
574 $this->output( "$msg ..." );
575 $this->db
->dropTable( $table, __METHOD__
);
576 $this->output( "done.\n" );
579 $this->applyPatch( $patch, $fullpath, $msg );
583 $this->output( "...$table doesn't exist.\n" );
588 * Modify an existing field
590 * @param $table String: name of the table to which the field belongs
591 * @param $field String: name of the field to modify
592 * @param $patch String: path to the patch file
593 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
595 public function modifyField( $table, $field, $patch, $fullpath = false ) {
596 $updateKey = "$table-$field-$patch";
597 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
598 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
599 } elseif ( !$this->db
->fieldExists( $table, $field, __METHOD__
) ) {
600 $this->output( "...$field field does not exist in $table table, skipping modify field patch.\n" );
601 } elseif( $this->updateRowExists( $updateKey ) ) {
602 $this->output( "...$field in table $table already modified by patch $patch.\n" );
604 $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
605 $this->insertUpdateRow( $updateKey );
610 * Purge the objectcache table
612 public function purgeCache() {
613 global $wgLocalisationCacheConf;
614 # We can't guarantee that the user will be able to use TRUNCATE,
615 # but we know that DELETE is available to us
616 $this->output( "Purging caches..." );
617 $this->db
->delete( 'objectcache', '*', __METHOD__
);
618 if ( $wgLocalisationCacheConf['manualRecache'] ) {
619 $this->rebuildLocalisationCache();
621 $this->output( "done.\n" );
625 * Check the site_stats table is not properly populated.
627 protected function checkStats() {
628 $this->output( "...site_stats is populated..." );
629 $row = $this->db
->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__
);
630 if ( $row === false ) {
631 $this->output( "data is missing! rebuilding...\n" );
632 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
633 $this->output( "missing ss_total_pages, rebuilding...\n" );
635 $this->output( "done.\n" );
638 SiteStatsInit
::doAllAndCommit( $this->db
);
641 # Common updater functions
644 * Sets the number of active users in the site_stats table
646 protected function doActiveUsersInit() {
647 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', false, __METHOD__
);
648 if ( $activeUsers == -1 ) {
649 $activeUsers = $this->db
->selectField( 'recentchanges',
650 'COUNT( DISTINCT rc_user_text )',
651 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
653 $this->db
->update( 'site_stats',
654 array( 'ss_active_users' => intval( $activeUsers ) ),
655 array( 'ss_row_id' => 1 ), __METHOD__
, array( 'LIMIT' => 1 )
658 $this->output( "...ss_active_users user count set...\n" );
662 * Populates the log_user_text field in the logging table
664 protected function doLogUsertextPopulation() {
665 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
667 "Populating log_user_text field, printing progress markers. For large\n" .
668 "databases, you may want to hit Ctrl-C and do this manually with\n" .
669 "maintenance/populateLogUsertext.php.\n" );
671 $task = $this->maintenance
->runChild( 'PopulateLogUsertext' );
673 $this->output( "done.\n" );
678 * Migrate log params to new table and index for searching
680 protected function doLogSearchPopulation() {
681 if ( !$this->updateRowExists( 'populate log_search' ) ) {
683 "Populating log_search table, printing progress markers. For large\n" .
684 "databases, you may want to hit Ctrl-C and do this manually with\n" .
685 "maintenance/populateLogSearch.php.\n" );
687 $task = $this->maintenance
->runChild( 'PopulateLogSearch' );
689 $this->output( "done.\n" );
694 * Updates the timestamps in the transcache table
696 protected function doUpdateTranscacheField() {
697 if ( $this->updateRowExists( 'convert transcache field' ) ) {
698 $this->output( "...transcache tc_time already converted.\n" );
702 $this->applyPatch( 'patch-tc-timestamp.sql', false, "Converting tc_time from UNIX epoch to MediaWiki timestamp" );
706 * Update CategoryLinks collation
708 protected function doCollationUpdate() {
709 global $wgCategoryCollation;
710 if ( $this->db
->selectField(
713 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
716 $this->output( "...collations up-to-date.\n" );
720 $this->output( "Updating category collations..." );
721 $task = $this->maintenance
->runChild( 'UpdateCollation' );
723 $this->output( "...done.\n" );
727 * Migrates user options from the user table blob to user_properties
729 protected function doMigrateUserOptions() {
730 $cl = $this->maintenance
->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
732 $this->output( "done.\n" );
736 * Rebuilds the localisation cache
738 protected function rebuildLocalisationCache() {
740 * @var $cl RebuildLocalisationCache
742 $cl = $this->maintenance
->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
743 $this->output( "Rebuilding localisation cache...\n" );
746 $this->output( "done.\n" );