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;
57 protected $postDatabaseUpdateMaintenance = array(
58 'DeleteDefaultMessages',
59 'PopulateRevisionLength',
60 'PopulateRevisionSha1',
62 'FixExtLinksProtocolRelative',
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 ) {
74 $this->db
->setFlag( DBO_DDLMODE
); // For Oracle's handling of schema files
75 $this->shared
= $shared;
77 $this->maintenance
= $maintenance;
79 $this->maintenance
= new FakeMaintenance
;
81 $this->maintenance
->setDB( $db );
82 $this->initOldGlobals();
83 $this->loadExtensions();
84 wfRunHooks( 'LoadExtensionSchemaUpdates', array( $this ) );
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();
114 return; // no LocalSettings found
116 if ( !isset( $vars['wgHooks'] ) ||
!isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
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 );
137 throw new MWException( __METHOD__
. ' called for unsupported $wgDBtype' );
142 * Get a database connection to run updates
144 * @return DatabaseBase
146 public function getDB() {
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() ) {
159 global $wgCommandLineMode;
160 if( !$wgCommandLineMode ) {
161 $str = htmlspecialchars( $str );
168 * Add a new update coming from an extension. This should be called by
169 * extensions while executing the LoadExtensionSchemaUpdates hook.
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
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)
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 );
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 );
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 );
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 );
236 * @param $tableName string
237 * @param $sqlPath string
239 public function dropExtensionTable( $tableName, $sqlPath ) {
240 $this->extensionUpdates
[] = array( 'dropTable', $tableName, $sqlPath, true );
247 * @param $tableName string
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.
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
270 protected function getExtensionUpdates() {
271 return $this->extensionUpdates
;
279 public function getPostDatabaseUpdateMaintenance() {
280 return $this->postDatabaseUpdateMaintenance
;
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'] ) ) {
307 if ( isset( $what['purge'] ) ) {
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
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 );
335 $this->updates
= array_merge( $this->updates
, $updates );
340 * @param $updates array
342 protected function setAppliedUpdates( $version, $updates = array() ) {
343 $this->db
->clearFlag( DBO_DDLMODE
);
344 if( !$this->canUseNewUpdatelog() ) {
347 $key = "updatelist-$version-" . time();
348 $this->db
->insert( 'updatelog',
349 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
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
358 * @param $key String Name of the key to check for
362 public function updateRowExists( $key ) {
363 $row = $this->db
->selectRow(
366 array( 'ul_key' => $key ),
373 * Helper function: Add a key to the updatelog table
374 * Obviously, only use this for updates that occur after the updatelog table was
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
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.
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 );
420 foreach ( $wgExtNewTables as $tableRecord ) {
422 'addTable', $tableRecord[0], $tableRecord[1], true
426 foreach ( $wgExtNewFields as $fieldRecord ) {
427 if ( $fieldRecord[0] != 'user' ||
$doUser ) {
429 'addField', $fieldRecord[0], $fieldRecord[1],
430 $fieldRecord[2], true
435 foreach ( $wgExtNewIndexes as $fieldRecord ) {
437 'addIndex', $fieldRecord[0], $fieldRecord[1],
438 $fieldRecord[2], true
442 foreach ( $wgExtModifiedFields as $fieldRecord ) {
444 'modifyField', $fieldRecord[0], $fieldRecord[1],
445 $fieldRecord[2], true
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)
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
466 * @param $msg String Description of the patch
468 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
469 if ( $msg === null ) {
470 $msg = "Applying $path patch";
473 if ( !$isFullPath ) {
474 $path = $this->db
->patchPath( $path );
477 $this->output( "$msg ..." );
478 $this->db
->sourceFile( $path );
479 $this->output( "done.\n" );
483 * Add a new table to the database
484 * @param $name String Name of the new table
485 * @param $patch String Path to the patch file
486 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
488 protected function addTable( $name, $patch, $fullpath = false ) {
489 if ( $this->db
->tableExists( $name, __METHOD__
) ) {
490 $this->output( "...$name table already exists.\n" );
492 $this->applyPatch( $patch, $fullpath, "Creating $name table" );
497 * Add a new field to an existing table
498 * @param $table String Name of the table to modify
499 * @param $field String Name of the new field
500 * @param $patch String Path to the patch file
501 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
503 protected function addField( $table, $field, $patch, $fullpath = false ) {
504 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
505 $this->output( "...$table table does not exist, skipping new field patch.\n" );
506 } elseif ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
507 $this->output( "...have $field field in $table table.\n" );
509 $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
514 * Add a new index to an existing table
515 * @param $table String Name of the table to modify
516 * @param $index String Name of the new index
517 * @param $patch String Path to the patch file
518 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
520 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
521 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
522 $this->output( "...index $index already set on $table table.\n" );
524 $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
529 * Drop a field from an existing table
531 * @param $table String Name of the table to modify
532 * @param $field String Name of the old field
533 * @param $patch String Path to the patch file
534 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
536 protected function dropField( $table, $field, $patch, $fullpath = false ) {
537 if ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
538 $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
540 $this->output( "...$table table does not contain $field field.\n" );
545 * Drop an index from an existing table
547 * @param $table String: Name of the table to modify
548 * @param $index String: Name of the old index
549 * @param $patch String: Path to the patch file
550 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
552 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
553 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
554 $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
556 $this->output( "...$index key doesn't exist.\n" );
561 * If the specified table exists, drop it, or execute the
562 * patch if one is provided.
566 * @param $table string
567 * @param $patch string|false
568 * @param $fullpath bool
570 public function dropTable( $table, $patch = false, $fullpath = false ) {
571 if ( $this->db
->tableExists( $table, __METHOD__
) ) {
572 $msg = "Dropping table $table";
574 if ( $patch === false ) {
575 $this->output( "$msg ..." );
576 $this->db
->dropTable( $table, __METHOD__
);
577 $this->output( "done.\n" );
580 $this->applyPatch( $patch, $fullpath, $msg );
584 $this->output( "...$table doesn't exist.\n" );
589 * Modify an existing field
591 * @param $table String: name of the table to which the field belongs
592 * @param $field String: name of the field to modify
593 * @param $patch String: path to the patch file
594 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
596 public function modifyField( $table, $field, $patch, $fullpath = false ) {
597 $updateKey = "$table-$field-$patch";
598 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
599 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
600 } elseif ( !$this->db
->fieldExists( $table, $field, __METHOD__
) ) {
601 $this->output( "...$field field does not exist in $table table, skipping modify field patch.\n" );
602 } elseif( $this->updateRowExists( $updateKey ) ) {
603 $this->output( "...$field in table $table already modified by patch $patch.\n" );
605 $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
606 $this->insertUpdateRow( $updateKey );
611 * Purge the objectcache table
613 protected function purgeCache() {
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 $this->output( "done.\n" );
622 * Check the site_stats table is not properly populated.
624 protected function checkStats() {
625 $this->output( "...site_stats is populated..." );
626 $row = $this->db
->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__
);
627 if ( $row === false ) {
628 $this->output( "data is missing! rebuilding...\n" );
629 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
630 $this->output( "missing ss_total_pages, rebuilding...\n" );
632 $this->output( "done.\n" );
635 SiteStatsInit
::doAllAndCommit( $this->db
);
638 # Common updater functions
641 * Sets the number of active users in the site_stats table
643 protected function doActiveUsersInit() {
644 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', false, __METHOD__
);
645 if ( $activeUsers == -1 ) {
646 $activeUsers = $this->db
->selectField( 'recentchanges',
647 'COUNT( DISTINCT rc_user_text )',
648 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
650 $this->db
->update( 'site_stats',
651 array( 'ss_active_users' => intval( $activeUsers ) ),
652 array( 'ss_row_id' => 1 ), __METHOD__
, array( 'LIMIT' => 1 )
655 $this->output( "...ss_active_users user count set...\n" );
659 * Populates the log_user_text field in the logging table
661 protected function doLogUsertextPopulation() {
662 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
664 "Populating log_user_text field, printing progress markers. For large\n" .
665 "databases, you may want to hit Ctrl-C and do this manually with\n" .
666 "maintenance/populateLogUsertext.php.\n" );
668 $task = $this->maintenance
->runChild( 'PopulateLogUsertext' );
670 $this->output( "done.\n" );
675 * Migrate log params to new table and index for searching
677 protected function doLogSearchPopulation() {
678 if ( !$this->updateRowExists( 'populate log_search' ) ) {
680 "Populating log_search table, printing progress markers. For large\n" .
681 "databases, you may want to hit Ctrl-C and do this manually with\n" .
682 "maintenance/populateLogSearch.php.\n" );
684 $task = $this->maintenance
->runChild( 'PopulateLogSearch' );
686 $this->output( "done.\n" );
691 * Updates the timestamps in the transcache table
693 protected function doUpdateTranscacheField() {
694 if ( $this->updateRowExists( 'convert transcache field' ) ) {
695 $this->output( "...transcache tc_time already converted.\n" );
699 $this->applyPatch( 'patch-tc-timestamp.sql', false, "Converting tc_time from UNIX epoch to MediaWiki timestamp" );
703 * Update CategoryLinks collation
705 protected function doCollationUpdate() {
706 global $wgCategoryCollation;
707 if ( $this->db
->selectField(
710 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
713 $this->output( "...collations up-to-date.\n" );
717 $this->output( "Updating category collations..." );
718 $task = $this->maintenance
->runChild( 'UpdateCollation' );
720 $this->output( "...done.\n" );
724 * Migrates user options from the user table blob to user_properties
726 protected function doMigrateUserOptions() {
727 $cl = $this->maintenance
->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
729 $this->output( "done.\n" );
733 * Rebuilds the localisation cache
735 protected function rebuildLocalisationCache() {
737 * @var $cl RebuildLocalisationCache
739 $cl = $this->maintenance
->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
740 $this->output( "Rebuilding localisation cache...\n" );
743 $this->output( "done.\n" );