3 * DBMS-specific updater helper.
9 require_once( dirname(__FILE__
) . '/../../maintenance/Maintenance.php' );
12 * Class for handling database updates. Roughly based off of updaters.inc, with
13 * a few improvements :)
18 abstract class DatabaseUpdater
{
21 * Array of updates to perform on the database
25 protected $updates = array();
28 * List of extension-provided database updates
31 protected $extensionUpdates = array();
34 * Handle to the database subclass
40 protected $shared = false;
42 protected $postDatabaseUpdateMaintenance = array(
43 'DeleteDefaultMessages',
44 'PopulateRevisionLength',
45 'PopulateRevisionSha1',
47 'FixExtLinksProtocolRelative',
53 * @param $db DatabaseBase object to perform updates on
54 * @param $shared bool Whether to perform updates on shared tables
55 * @param $maintenance Maintenance Maintenance object which created us
57 protected function __construct( DatabaseBase
&$db, $shared, Maintenance
$maintenance = null ) {
59 $this->db
->setFlag( DBO_DDLMODE
); // For Oracle's handling of schema files
60 $this->shared
= $shared;
62 $this->maintenance
= $maintenance;
64 $this->maintenance
= new FakeMaintenance
;
66 $this->maintenance
->setDB( $db );
67 $this->initOldGlobals();
68 $this->loadExtensions();
69 wfRunHooks( 'LoadExtensionSchemaUpdates', array( $this ) );
73 * Initialize all of the old globals. One day this should all become
74 * something much nicer
76 private function initOldGlobals() {
77 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
78 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
80 # For extensions only, should be populated via hooks
81 # $wgDBtype should be checked to specifiy the proper file
82 $wgExtNewTables = array(); // table, dir
83 $wgExtNewFields = array(); // table, column, dir
84 $wgExtPGNewFields = array(); // table, column, column attributes; for PostgreSQL
85 $wgExtPGAlteredFields = array(); // table, column, new type, conversion method; for PostgreSQL
86 $wgExtNewIndexes = array(); // table, index, dir
87 $wgExtModifiedFields = array(); // table, index, dir
91 * Loads LocalSettings.php, if needed, and initialises everything needed for LoadExtensionSchemaUpdates hook
93 private function loadExtensions() {
94 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
95 return; // already loaded
97 $vars = Installer
::getExistingLocalSettings();
99 return; // no LocalSettings found
101 if ( !isset( $vars['wgHooks'] ) ||
!isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
104 global $wgHooks, $wgAutoloadClasses;
105 $wgHooks['LoadExtensionSchemaUpdates'] = $vars['wgHooks']['LoadExtensionSchemaUpdates'];
106 $wgAutoloadClasses = $wgAutoloadClasses +
$vars['wgAutoloadClasses'];
110 * @throws MWException
111 * @param DatabaseBase $db
112 * @param bool $shared
113 * @param null $maintenance
114 * @return DatabaseUpdater
116 public static function newForDB( &$db, $shared = false, $maintenance = null ) {
117 $type = $db->getType();
118 if( in_array( $type, Installer
::getDBTypes() ) ) {
119 $class = ucfirst( $type ) . 'Updater';
120 return new $class( $db, $shared, $maintenance );
122 throw new MWException( __METHOD__
. ' called for unsupported $wgDBtype' );
127 * Get a database connection to run updates
129 * @return DatabaseBase
131 public function getDB() {
136 * Output some text. If we're running from web, escape the text first.
138 * @param $str String: Text to output
140 public function output( $str ) {
141 if ( $this->maintenance
->isQuiet() ) {
144 global $wgCommandLineMode;
145 if( !$wgCommandLineMode ) {
146 $str = htmlspecialchars( $str );
153 * Add a new update coming from an extension. This should be called by
154 * extensions while executing the LoadExtensionSchemaUpdates hook.
156 * @param $update Array: the update to run. Format is the following:
157 * first item is the callback function, it also can be a
158 * simple string with the name of a function in this class,
159 * following elements are parameters to the function.
160 * Note that callback functions will receive this object as
163 public function addExtensionUpdate( Array $update ) {
164 $this->extensionUpdates
[] = $update;
168 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
169 * is the most common usage of updaters in an extension)
170 * @param $tableName String Name of table to create
171 * @param $sqlPath String Full path to the schema file
173 public function addExtensionTable( $tableName, $sqlPath ) {
174 $this->extensionUpdates
[] = array( 'addTable', $tableName, $sqlPath, true );
178 * @param $tableName string
179 * @param $indexName string
180 * @param $sqlPath string
182 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
183 $this->extensionUpdates
[] = array( 'addIndex', $tableName, $indexName, $sqlPath, true );
187 * @param $tableName string
188 * @param $columnName string
189 * @param $sqlPath string
191 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
192 $this->extensionUpdates
[] = array( 'addField', $tableName, $columnName, $sqlPath, true );
196 * Add a maintenance script to be run after the database updates are complete
197 * @param $class string Name of a Maintenance subclass
199 public function addPostDatabaseUpdateMaintenance( $class ) {
200 $this->postDatabaseUpdateMaintenance
[] = $class;
204 * Get the list of extension-defined updates
208 protected function getExtensionUpdates() {
209 return $this->extensionUpdates
;
215 public function getPostDatabaseUpdateMaintenance() {
216 return $this->postDatabaseUpdateMaintenance
;
222 * @param $what Array: what updates to perform
224 public function doUpdates( $what = array( 'core', 'extensions', 'purge', 'stats' ) ) {
227 $what = array_flip( $what );
228 if ( isset( $what['core'] ) ) {
229 $this->runUpdates( $this->getCoreUpdateList(), false );
231 if ( isset( $what['extensions'] ) ) {
232 $this->runUpdates( $this->getOldGlobalUpdates(), false );
233 $this->runUpdates( $this->getExtensionUpdates(), true );
236 $this->setAppliedUpdates( $wgVersion, $this->updates
);
238 if( isset( $what['purge'] ) ) {
241 if ( isset( $what['stats'] ) ) {
247 * Helper function for doUpdates()
249 * @param $updates Array of updates to run
250 * @param $passSelf Boolean: whether to pass this object we calling external
253 private function runUpdates( array $updates, $passSelf ) {
254 foreach ( $updates as $params ) {
255 $func = array_shift( $params );
256 if( !is_array( $func ) && method_exists( $this, $func ) ) {
257 $func = array( $this, $func );
258 } elseif ( $passSelf ) {
259 array_unshift( $params, $this );
261 call_user_func_array( $func, $params );
264 $this->updates
= array_merge( $this->updates
, $updates );
269 * @param $updates array
271 protected function setAppliedUpdates( $version, $updates = array() ) {
272 $this->db
->clearFlag( DBO_DDLMODE
);
273 if( !$this->canUseNewUpdatelog() ) {
276 $key = "updatelist-$version-" . time();
277 $this->db
->insert( 'updatelog',
278 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
280 $this->db
->setFlag( DBO_DDLMODE
);
284 * Helper function: check if the given key is present in the updatelog table.
285 * Obviously, only use this for updates that occur after the updatelog table was
287 * @param $key String Name of the key to check for
291 public function updateRowExists( $key ) {
292 $row = $this->db
->selectRow(
295 array( 'ul_key' => $key ),
302 * Helper function: Add a key to the updatelog table
303 * Obviously, only use this for updates that occur after the updatelog table was
305 * @param $key String Name of key to insert
306 * @param $val String [optional] value to insert along with the key
308 public function insertUpdateRow( $key, $val = null ) {
309 $this->db
->clearFlag( DBO_DDLMODE
);
310 $values = array( 'ul_key' => $key );
311 if( $val && $this->canUseNewUpdatelog() ) {
312 $values['ul_value'] = $val;
314 $this->db
->insert( 'updatelog', $values, __METHOD__
, 'IGNORE' );
315 $this->db
->setFlag( DBO_DDLMODE
);
319 * Updatelog was changed in 1.17 to have a ul_value column so we can record
320 * more information about what kind of updates we've done (that's what this
321 * class does). Pre-1.17 wikis won't have this column, and really old wikis
322 * might not even have updatelog at all
326 protected function canUseNewUpdatelog() {
327 return $this->db
->tableExists( 'updatelog', __METHOD__
) &&
328 $this->db
->fieldExists( 'updatelog', 'ul_value', __METHOD__
);
332 * Before 1.17, we used to handle updates via stuff like
333 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
334 * of this in 1.17 but we want to remain back-compatible for a while. So
335 * load up these old global-based things into our update list.
339 protected function getOldGlobalUpdates() {
340 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
341 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
343 $doUser = $this->shared ?
344 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
345 !$wgSharedDB ||
!in_array( 'user', $wgSharedTables );
349 foreach ( $wgExtNewTables as $tableRecord ) {
351 'addTable', $tableRecord[0], $tableRecord[1], true
355 foreach ( $wgExtNewFields as $fieldRecord ) {
356 if ( $fieldRecord[0] != 'user' ||
$doUser ) {
358 'addField', $fieldRecord[0], $fieldRecord[1],
359 $fieldRecord[2], true
364 foreach ( $wgExtNewIndexes as $fieldRecord ) {
366 'addIndex', $fieldRecord[0], $fieldRecord[1],
367 $fieldRecord[2], true
371 foreach ( $wgExtModifiedFields as $fieldRecord ) {
373 'modifyField', $fieldRecord[0], $fieldRecord[1],
374 $fieldRecord[2], true
382 * Get an array of updates to perform on the database. Should return a
383 * multi-dimensional array. The main key is the MediaWiki version (1.12,
384 * 1.13...) with the values being arrays of updates, identical to how
385 * updaters.inc did it (for now)
389 protected abstract function getCoreUpdateList();
392 * Applies a SQL patch
393 * @param $path String Path to the patch file
394 * @param $isFullPath Boolean Whether to treat $path as a relative or not
396 protected function applyPatch( $path, $isFullPath = false ) {
398 $this->db
->sourceFile( $path );
400 $this->db
->sourceFile( $this->db
->patchPath( $path ) );
405 * Add a new table to the database
406 * @param $name String Name of the new table
407 * @param $patch String Path to the patch file
408 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
410 protected function addTable( $name, $patch, $fullpath = false ) {
411 if ( $this->db
->tableExists( $name, __METHOD__
) ) {
412 $this->output( "...$name table already exists.\n" );
414 $this->output( "Creating $name table..." );
415 $this->applyPatch( $patch, $fullpath );
416 $this->output( "ok\n" );
421 * Add a new field to an existing table
422 * @param $table String Name of the table to modify
423 * @param $field String Name of the new field
424 * @param $patch String Path to the patch file
425 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
427 protected function addField( $table, $field, $patch, $fullpath = false ) {
428 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
429 $this->output( "...$table table does not exist, skipping new field patch\n" );
430 } elseif ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
431 $this->output( "...have $field field in $table table.\n" );
433 $this->output( "Adding $field field to table $table..." );
434 $this->applyPatch( $patch, $fullpath );
435 $this->output( "ok\n" );
440 * Add a new index to an existing table
441 * @param $table String Name of the table to modify
442 * @param $index String Name of the new index
443 * @param $patch String Path to the patch file
444 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
446 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
447 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
448 $this->output( "...$index key already set on $table table.\n" );
450 $this->output( "Adding $index key to table $table... " );
451 $this->applyPatch( $patch, $fullpath );
452 $this->output( "ok\n" );
457 * Drop a field from an existing table
459 * @param $table String Name of the table to modify
460 * @param $field String Name of the old field
461 * @param $patch String Path to the patch file
462 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
464 protected function dropField( $table, $field, $patch, $fullpath = false ) {
465 if ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
466 $this->output( "Table $table contains $field field. Dropping... " );
467 $this->applyPatch( $patch, $fullpath );
468 $this->output( "ok\n" );
470 $this->output( "...$table table does not contain $field field.\n" );
475 * Drop an index from an existing table
477 * @param $table String: Name of the table to modify
478 * @param $index String: Name of the old index
479 * @param $patch String: Path to the patch file
480 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
482 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
483 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
484 $this->output( "Dropping $index key from table $table... " );
485 $this->applyPatch( $patch, $fullpath );
486 $this->output( "ok\n" );
488 $this->output( "...$index key doesn't exist.\n" );
493 * @param $table string
494 * @param $patch string
495 * @param $fullpath bool
497 protected function dropTable( $table, $patch, $fullpath = false ) {
498 if ( $this->db
->tableExists( $table, __METHOD__
) ) {
499 $this->output( "Dropping table $table... " );
500 $this->applyPatch( $patch, $fullpath );
501 $this->output( "ok\n" );
503 $this->output( "...$table doesn't exist.\n" );
508 * Modify an existing field
510 * @param $table String: name of the table to which the field belongs
511 * @param $field String: name of the field to modify
512 * @param $patch String: path to the patch file
513 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
515 public function modifyField( $table, $field, $patch, $fullpath = false ) {
516 $updateKey = "$table-$field-$patch";
517 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
518 $this->output( "...$table table does not exist, skipping modify field patch\n" );
519 } elseif ( !$this->db
->fieldExists( $table, $field, __METHOD__
) ) {
520 $this->output( "...$field field does not exist in $table table, skipping modify field patch\n" );
521 } elseif( $this->updateRowExists( $updateKey ) ) {
522 $this->output( "...$field in table $table already modified by patch $patch\n" );
524 $this->output( "Modifying $field field of table $table..." );
525 $this->applyPatch( $patch, $fullpath );
526 $this->insertUpdateRow( $updateKey );
527 $this->output( "ok\n" );
532 * Purge the objectcache table
534 protected function purgeCache() {
535 # We can't guarantee that the user will be able to use TRUNCATE,
536 # but we know that DELETE is available to us
537 $this->output( "Purging caches..." );
538 $this->db
->delete( 'objectcache', '*', __METHOD__
);
539 $this->output( "done.\n" );
543 * Check the site_stats table is not properly populated.
545 protected function checkStats() {
546 $this->output( "Checking site_stats row..." );
547 $row = $this->db
->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__
);
548 if ( $row === false ) {
549 $this->output( "data is missing! rebuilding...\n" );
550 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
551 $this->output( "missing ss_total_pages, rebuilding...\n" );
553 $this->output( "done.\n" );
556 SiteStatsInit
::doAllAndCommit( $this->db
);
559 # Common updater functions
562 * Sets the number of active users in the site_stats table
564 protected function doActiveUsersInit() {
565 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', false, __METHOD__
);
566 if ( $activeUsers == -1 ) {
567 $activeUsers = $this->db
->selectField( 'recentchanges',
568 'COUNT( DISTINCT rc_user_text )',
569 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
571 $this->db
->update( 'site_stats',
572 array( 'ss_active_users' => intval( $activeUsers ) ),
573 array( 'ss_row_id' => 1 ), __METHOD__
, array( 'LIMIT' => 1 )
576 $this->output( "...ss_active_users user count set...\n" );
580 * Populates the log_user_text field in the logging table
582 protected function doLogUsertextPopulation() {
583 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
585 "Populating log_user_text field, printing progress markers. For large\n" .
586 "databases, you may want to hit Ctrl-C and do this manually with\n" .
587 "maintenance/populateLogUsertext.php.\n" );
589 $task = $this->maintenance
->runChild( 'PopulateLogUsertext' );
595 * Migrate log params to new table and index for searching
597 protected function doLogSearchPopulation() {
598 if ( !$this->updateRowExists( 'populate log_search' ) ) {
600 "Populating log_search table, printing progress markers. For large\n" .
601 "databases, you may want to hit Ctrl-C and do this manually with\n" .
602 "maintenance/populateLogSearch.php.\n" );
604 $task = $this->maintenance
->runChild( 'PopulateLogSearch' );
610 * Updates the timestamps in the transcache table
612 protected function doUpdateTranscacheField() {
613 if ( $this->updateRowExists( 'convert transcache field' ) ) {
614 $this->output( "...transcache tc_time already converted.\n" );
618 $this->output( "Converting tc_time from UNIX epoch to MediaWiki timestamp... " );
619 $this->applyPatch( 'patch-tc-timestamp.sql' );
620 $this->output( "ok\n" );
624 * Update CategoryLinks collation
626 protected function doCollationUpdate() {
627 global $wgCategoryCollation;
628 if ( $this->db
->selectField(
631 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
634 $this->output( "...collations up-to-date.\n" );
638 $task = $this->maintenance
->runChild( 'UpdateCollation' );
643 * Migrates user options from the user table blob to user_properties
645 protected function doMigrateUserOptions() {
646 $cl = $this->maintenance
->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
647 $this->output( "Migrating remaining user_options... " );
649 $this->output( "done.\n" );
653 * Rebuilds the localisation cache
655 protected function doRebuildLocalisationCache() {
657 * @var $cl RebuildLocalisationCache
659 $cl = $this->maintenance
->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
660 $this->output( "Rebuilding localisation cache...\n" );
663 $this->output( "Rebuilding localisation cache done.\n" );