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.
158 * @param $update Array: the update to run. Format is the following:
159 * first item is the callback function, it also can be a
160 * simple string with the name of a function in this class,
161 * following elements are parameters to the function.
162 * Note that callback functions will receive this object as
165 public function addExtensionUpdate( Array $update ) {
166 $this->extensionUpdates
[] = $update;
170 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
171 * is the most common usage of updaters in an extension)
175 * @param $tableName String Name of table to create
176 * @param $sqlPath String Full path to the schema file
178 public function addExtensionTable( $tableName, $sqlPath ) {
179 $this->extensionUpdates
[] = array( 'addTable', $tableName, $sqlPath, true );
185 * @param $tableName string
186 * @param $indexName string
187 * @param $sqlPath string
189 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
190 $this->extensionUpdates
[] = array( 'addIndex', $tableName, $indexName, $sqlPath, true );
197 * @param $tableName string
198 * @param $columnName string
199 * @param $sqlPath string
201 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
202 $this->extensionUpdates
[] = array( 'addField', $tableName, $columnName, $sqlPath, true );
209 * @param $tableName string
210 * @param $columnName string
211 * @param $sqlPath string
213 public function dropExtensionField( $tableName, $columnName, $sqlPath ) {
214 $this->extensionUpdates
[] = array( 'dropField', $tableName, $columnName, $sqlPath, true );
221 * @param $tableName string
222 * @param $sqlPath string
224 public function dropExtensionTable( $tableName, $sqlPath ) {
225 $this->extensionUpdates
[] = array( 'dropTable', $tableName, $sqlPath, true );
232 * @param $tableName string
235 public function tableExists( $tableName ) {
236 return ( $this->db
->tableExists( $tableName, __METHOD__
) );
240 * Add a maintenance script to be run after the database updates are complete.
244 * @param $class string Name of a Maintenance subclass
246 public function addPostDatabaseUpdateMaintenance( $class ) {
247 $this->postDatabaseUpdateMaintenance
[] = $class;
251 * Get the list of extension-defined updates
255 protected function getExtensionUpdates() {
256 return $this->extensionUpdates
;
264 public function getPostDatabaseUpdateMaintenance() {
265 return $this->postDatabaseUpdateMaintenance
;
271 * @param $what Array: what updates to perform
273 public function doUpdates( $what = array( 'core', 'extensions', 'purge', 'stats' ) ) {
274 global $wgLocalisationCacheConf, $wgVersion;
276 $this->db
->begin( __METHOD__
);
277 $what = array_flip( $what );
278 if ( isset( $what['core'] ) ) {
279 $this->runUpdates( $this->getCoreUpdateList(), false );
281 if ( isset( $what['extensions'] ) ) {
282 $this->runUpdates( $this->getOldGlobalUpdates(), false );
283 $this->runUpdates( $this->getExtensionUpdates(), true );
286 $this->setAppliedUpdates( $wgVersion, $this->updates
);
288 if ( isset( $what['stats'] ) ) {
292 if ( isset( $what['purge'] ) ) {
295 if ( $wgLocalisationCacheConf['manualRecache'] ) {
296 $this->rebuildLocalisationCache();
299 $this->db
->commit( __METHOD__
);
303 * Helper function for doUpdates()
305 * @param $updates Array of updates to run
306 * @param $passSelf Boolean: whether to pass this object we calling external
309 private function runUpdates( array $updates, $passSelf ) {
310 foreach ( $updates as $params ) {
311 $func = array_shift( $params );
312 if( !is_array( $func ) && method_exists( $this, $func ) ) {
313 $func = array( $this, $func );
314 } elseif ( $passSelf ) {
315 array_unshift( $params, $this );
317 call_user_func_array( $func, $params );
320 $this->updates
= array_merge( $this->updates
, $updates );
325 * @param $updates array
327 protected function setAppliedUpdates( $version, $updates = array() ) {
328 $this->db
->clearFlag( DBO_DDLMODE
);
329 if( !$this->canUseNewUpdatelog() ) {
332 $key = "updatelist-$version-" . time();
333 $this->db
->insert( 'updatelog',
334 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
336 $this->db
->setFlag( DBO_DDLMODE
);
340 * Helper function: check if the given key is present in the updatelog table.
341 * Obviously, only use this for updates that occur after the updatelog table was
343 * @param $key String Name of the key to check for
347 public function updateRowExists( $key ) {
348 $row = $this->db
->selectRow(
351 array( 'ul_key' => $key ),
358 * Helper function: Add a key to the updatelog table
359 * Obviously, only use this for updates that occur after the updatelog table was
361 * @param $key String Name of key to insert
362 * @param $val String [optional] value to insert along with the key
364 public function insertUpdateRow( $key, $val = null ) {
365 $this->db
->clearFlag( DBO_DDLMODE
);
366 $values = array( 'ul_key' => $key );
367 if( $val && $this->canUseNewUpdatelog() ) {
368 $values['ul_value'] = $val;
370 $this->db
->insert( 'updatelog', $values, __METHOD__
, 'IGNORE' );
371 $this->db
->setFlag( DBO_DDLMODE
);
375 * Updatelog was changed in 1.17 to have a ul_value column so we can record
376 * more information about what kind of updates we've done (that's what this
377 * class does). Pre-1.17 wikis won't have this column, and really old wikis
378 * might not even have updatelog at all
382 protected function canUseNewUpdatelog() {
383 return $this->db
->tableExists( 'updatelog', __METHOD__
) &&
384 $this->db
->fieldExists( 'updatelog', 'ul_value', __METHOD__
);
388 * Before 1.17, we used to handle updates via stuff like
389 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
390 * of this in 1.17 but we want to remain back-compatible for a while. So
391 * load up these old global-based things into our update list.
395 protected function getOldGlobalUpdates() {
396 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
397 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
399 $doUser = $this->shared ?
400 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
401 !$wgSharedDB ||
!in_array( 'user', $wgSharedTables );
405 foreach ( $wgExtNewTables as $tableRecord ) {
407 'addTable', $tableRecord[0], $tableRecord[1], true
411 foreach ( $wgExtNewFields as $fieldRecord ) {
412 if ( $fieldRecord[0] != 'user' ||
$doUser ) {
414 'addField', $fieldRecord[0], $fieldRecord[1],
415 $fieldRecord[2], true
420 foreach ( $wgExtNewIndexes as $fieldRecord ) {
422 'addIndex', $fieldRecord[0], $fieldRecord[1],
423 $fieldRecord[2], true
427 foreach ( $wgExtModifiedFields as $fieldRecord ) {
429 'modifyField', $fieldRecord[0], $fieldRecord[1],
430 $fieldRecord[2], true
438 * Get an array of updates to perform on the database. Should return a
439 * multi-dimensional array. The main key is the MediaWiki version (1.12,
440 * 1.13...) with the values being arrays of updates, identical to how
441 * updaters.inc did it (for now)
445 protected abstract function getCoreUpdateList();
448 * Applies a SQL patch
449 * @param $path String Path to the patch file
450 * @param $isFullPath Boolean Whether to treat $path as a relative or not
452 protected function applyPatch( $path, $isFullPath = false ) {
454 $this->db
->sourceFile( $path );
456 $this->db
->sourceFile( $this->db
->patchPath( $path ) );
461 * Add a new table to the database
462 * @param $name String Name of the new table
463 * @param $patch String Path to the patch file
464 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
466 protected function addTable( $name, $patch, $fullpath = false ) {
467 if ( $this->db
->tableExists( $name, __METHOD__
) ) {
468 $this->output( "...$name table already exists.\n" );
470 $this->output( "Creating $name table..." );
471 $this->applyPatch( $patch, $fullpath );
472 $this->output( "done.\n" );
477 * Add a new field to an existing table
478 * @param $table String Name of the table to modify
479 * @param $field String Name of the new field
480 * @param $patch String Path to the patch file
481 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
483 protected function addField( $table, $field, $patch, $fullpath = false ) {
484 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
485 $this->output( "...$table table does not exist, skipping new field patch.\n" );
486 } elseif ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
487 $this->output( "...have $field field in $table table.\n" );
489 $this->output( "Adding $field field to table $table..." );
490 $this->applyPatch( $patch, $fullpath );
491 $this->output( "done.\n" );
496 * Add a new index to an existing table
497 * @param $table String Name of the table to modify
498 * @param $index String Name of the new index
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 addIndex( $table, $index, $patch, $fullpath = false ) {
503 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
504 $this->output( "...index $index already set on $table table.\n" );
506 $this->output( "Adding index $index to table $table... " );
507 $this->applyPatch( $patch, $fullpath );
508 $this->output( "done.\n" );
513 * Drop a field from an existing table
515 * @param $table String Name of the table to modify
516 * @param $field String Name of the old field
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 dropField( $table, $field, $patch, $fullpath = false ) {
521 if ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
522 $this->output( "Table $table contains $field field. Dropping... " );
523 $this->applyPatch( $patch, $fullpath );
524 $this->output( "done.\n" );
526 $this->output( "...$table table does not contain $field field.\n" );
531 * Drop an index from an existing table
533 * @param $table String: Name of the table to modify
534 * @param $index String: Name of the old index
535 * @param $patch String: Path to the patch file
536 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
538 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
539 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
540 $this->output( "Dropping $index index from table $table... " );
541 $this->applyPatch( $patch, $fullpath );
542 $this->output( "done.\n" );
544 $this->output( "...$index key doesn't exist.\n" );
549 * @param $table string
550 * @param $patch string
551 * @param $fullpath bool
553 protected function dropTable( $table, $patch, $fullpath = false ) {
554 if ( $this->db
->tableExists( $table, __METHOD__
) ) {
555 $this->output( "Dropping table $table... " );
556 $this->applyPatch( $patch, $fullpath );
557 $this->output( "done.\n" );
559 $this->output( "...$table doesn't exist.\n" );
564 * Modify an existing field
566 * @param $table String: name of the table to which the field belongs
567 * @param $field String: name of the field to modify
568 * @param $patch String: path to the patch file
569 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
571 public function modifyField( $table, $field, $patch, $fullpath = false ) {
572 $updateKey = "$table-$field-$patch";
573 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
574 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
575 } elseif ( !$this->db
->fieldExists( $table, $field, __METHOD__
) ) {
576 $this->output( "...$field field does not exist in $table table, skipping modify field patch.\n" );
577 } elseif( $this->updateRowExists( $updateKey ) ) {
578 $this->output( "...$field in table $table already modified by patch $patch.\n" );
580 $this->output( "Modifying $field field of table $table..." );
581 $this->applyPatch( $patch, $fullpath );
582 $this->insertUpdateRow( $updateKey );
583 $this->output( "done.\n" );
588 * Purge the objectcache table
590 protected function purgeCache() {
591 # We can't guarantee that the user will be able to use TRUNCATE,
592 # but we know that DELETE is available to us
593 $this->output( "Purging caches..." );
594 $this->db
->delete( 'objectcache', '*', __METHOD__
);
595 $this->output( "done.\n" );
599 * Check the site_stats table is not properly populated.
601 protected function checkStats() {
602 $this->output( "...site_stats is populated..." );
603 $row = $this->db
->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__
);
604 if ( $row === false ) {
605 $this->output( "data is missing! rebuilding...\n" );
606 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
607 $this->output( "missing ss_total_pages, rebuilding...\n" );
609 $this->output( "done.\n" );
612 SiteStatsInit
::doAllAndCommit( $this->db
);
615 # Common updater functions
618 * Sets the number of active users in the site_stats table
620 protected function doActiveUsersInit() {
621 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', false, __METHOD__
);
622 if ( $activeUsers == -1 ) {
623 $activeUsers = $this->db
->selectField( 'recentchanges',
624 'COUNT( DISTINCT rc_user_text )',
625 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
627 $this->db
->update( 'site_stats',
628 array( 'ss_active_users' => intval( $activeUsers ) ),
629 array( 'ss_row_id' => 1 ), __METHOD__
, array( 'LIMIT' => 1 )
632 $this->output( "...ss_active_users user count set...\n" );
636 * Populates the log_user_text field in the logging table
638 protected function doLogUsertextPopulation() {
639 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
641 "Populating log_user_text field, printing progress markers. For large\n" .
642 "databases, you may want to hit Ctrl-C and do this manually with\n" .
643 "maintenance/populateLogUsertext.php.\n" );
645 $task = $this->maintenance
->runChild( 'PopulateLogUsertext' );
647 $this->output( "done.\n" );
652 * Migrate log params to new table and index for searching
654 protected function doLogSearchPopulation() {
655 if ( !$this->updateRowExists( 'populate log_search' ) ) {
657 "Populating log_search table, printing progress markers. For large\n" .
658 "databases, you may want to hit Ctrl-C and do this manually with\n" .
659 "maintenance/populateLogSearch.php.\n" );
661 $task = $this->maintenance
->runChild( 'PopulateLogSearch' );
663 $this->output( "done.\n" );
668 * Updates the timestamps in the transcache table
670 protected function doUpdateTranscacheField() {
671 if ( $this->updateRowExists( 'convert transcache field' ) ) {
672 $this->output( "...transcache tc_time already converted.\n" );
676 $this->output( "Converting tc_time from UNIX epoch to MediaWiki timestamp... " );
677 $this->applyPatch( 'patch-tc-timestamp.sql' );
678 $this->output( "done.\n" );
682 * Update CategoryLinks collation
684 protected function doCollationUpdate() {
685 global $wgCategoryCollation;
686 if ( $this->db
->selectField(
689 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
692 $this->output( "...collations up-to-date.\n" );
696 $this->output( "Updating category collations..." );
697 $task = $this->maintenance
->runChild( 'UpdateCollation' );
699 $this->output( "...done.\n" );
703 * Migrates user options from the user table blob to user_properties
705 protected function doMigrateUserOptions() {
706 $cl = $this->maintenance
->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
708 $this->output( "done.\n" );
712 * Rebuilds the localisation cache
714 protected function rebuildLocalisationCache() {
716 * @var $cl RebuildLocalisationCache
718 $cl = $this->maintenance
->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
719 $this->output( "Rebuilding localisation cache...\n" );
722 $this->output( "done.\n" );