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 * Used to hold schema files during installation process
37 protected $newExtensions = array();
40 * Handle to the database subclass
46 protected $shared = false;
48 protected $postDatabaseUpdateMaintenance = array(
49 'DeleteDefaultMessages'
55 * @param $db DatabaseBase object to perform updates on
56 * @param $shared bool Whether to perform updates on shared tables
57 * @param $maintenance Maintenance Maintenance object which created us
59 protected function __construct( DatabaseBase
&$db, $shared, Maintenance
$maintenance = null ) {
61 $this->db
->setFlag( DBO_DDLMODE
); // For Oracle's handling of schema files
62 $this->shared
= $shared;
64 $this->maintenance
= $maintenance;
66 $this->maintenance
= new FakeMaintenance
;
68 $this->maintenance
->setDB( $db );
69 $this->initOldGlobals();
70 $this->loadExtensions();
71 wfRunHooks( 'LoadExtensionSchemaUpdates', array( $this ) );
75 * Initialize all of the old globals. One day this should all become
76 * something much nicer
78 private function initOldGlobals() {
79 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
80 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
82 # For extensions only, should be populated via hooks
83 # $wgDBtype should be checked to specifiy the proper file
84 $wgExtNewTables = array(); // table, dir
85 $wgExtNewFields = array(); // table, column, dir
86 $wgExtPGNewFields = array(); // table, column, column attributes; for PostgreSQL
87 $wgExtPGAlteredFields = array(); // table, column, new type, conversion method; for PostgreSQL
88 $wgExtNewIndexes = array(); // table, index, dir
89 $wgExtModifiedFields = array(); // table, index, dir
93 * Loads LocalSettings.php, if needed, and initialises everything needed for LoadExtensionSchemaUpdates hook
95 private function loadExtensions() {
96 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
97 return; // already loaded
99 $vars = Installer
::getExistingLocalSettings();
101 return; // no LocalSettings found
103 if ( !isset( $vars['wgHooks'] ) && !isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
106 global $wgHooks, $wgAutoloadClasses;
107 $wgHooks['LoadExtensionSchemaUpdates'] = $vars['wgHooks']['LoadExtensionSchemaUpdates'];
108 $wgAutoloadClasses = $wgAutoloadClasses +
$vars['wgAutoloadClasses'];
112 * @throws MWException
113 * @param DatabaseBase $db
114 * @param bool $shared
115 * @param null $maintenance
116 * @return DatabaseUpdater
118 public static function newForDB( &$db, $shared = false, $maintenance = null ) {
119 $type = $db->getType();
120 if( in_array( $type, Installer
::getDBTypes() ) ) {
121 $class = ucfirst( $type ) . 'Updater';
122 return new $class( $db, $shared, $maintenance );
124 throw new MWException( __METHOD__
. ' called for unsupported $wgDBtype' );
129 * Get a database connection to run updates
131 * @return DatabaseBase
133 public function getDB() {
138 * Output some text. If we're running from web, escape the text first.
140 * @param $str String: Text to output
142 public function output( $str ) {
143 if ( $this->maintenance
->isQuiet() ) {
146 global $wgCommandLineMode;
147 if( !$wgCommandLineMode ) {
148 $str = htmlspecialchars( $str );
155 * Add a new update coming from an extension. This should be called by
156 * 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)
172 * @param $tableName String Name of table to create
173 * @param $sqlPath String Full path to the schema file
175 public function addExtensionTable( $tableName, $sqlPath ) {
176 $this->extensionUpdates
[] = array( 'addTable', $tableName, $sqlPath, true );
180 * Add a brand new extension to MediaWiki. Used during the initial install
181 * @param $ext String Name of extension
182 * @param $sqlPath String Full path to the schema file
184 public function addNewExtension( $ext, $sqlPath ) {
185 $this->newExtensions
[ strtolower( $ext ) ] = $sqlPath;
189 * Get the list of extensions that registered a schema with our DB type
192 public function getNewExtensions() {
193 return $this->newExtensions
;
197 * Get the list of extension-defined updates
201 protected function getExtensionUpdates() {
202 return $this->extensionUpdates
;
205 public function getPostDatabaseUpdateMaintenance() {
206 return $this->postDatabaseUpdateMaintenance
;
212 * @param $what Array: what updates to perform
214 public function doUpdates( $what = array( 'core', 'extensions', 'purge' ) ) {
217 $what = array_flip( $what );
218 if ( isset( $what['core'] ) ) {
219 $this->runUpdates( $this->getCoreUpdateList(), false );
221 if ( isset( $what['extensions'] ) ) {
222 $this->runUpdates( $this->getOldGlobalUpdates(), false );
223 $this->runUpdates( $this->getExtensionUpdates(), true );
226 $this->setAppliedUpdates( $wgVersion, $this->updates
);
228 if( isset( $what['purge'] ) ) {
231 if ( isset( $what['core'] ) ) {
237 * Helper function for doUpdates()
239 * @param $updates Array of updates to run
240 * @param $passSelf Boolean: whether to pass this object we calling external
243 private function runUpdates( array $updates, $passSelf ) {
244 foreach ( $updates as $params ) {
245 $func = array_shift( $params );
246 if( !is_array( $func ) && method_exists( $this, $func ) ) {
247 $func = array( $this, $func );
248 } elseif ( $passSelf ) {
249 array_unshift( $params, $this );
251 call_user_func_array( $func, $params );
254 $this->updates
= array_merge( $this->updates
, $updates );
257 protected function setAppliedUpdates( $version, $updates = array() ) {
258 if( !$this->canUseNewUpdatelog() ) {
261 $key = "updatelist-$version-" . time();
262 $this->db
->insert( 'updatelog',
263 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
268 * Helper function: check if the given key is present in the updatelog table.
269 * Obviously, only use this for updates that occur after the updatelog table was
271 * @param $key String Name of the key to check for
273 public function updateRowExists( $key ) {
274 $row = $this->db
->selectRow(
277 array( 'ul_key' => $key ),
284 * Helper function: Add a key to the updatelog table
285 * Obviously, only use this for updates that occur after the updatelog table was
287 * @param $key String Name of key to insert
288 * @param $val String [optional] value to insert along with the key
290 public function insertUpdateRow( $key, $val = null ) {
291 $values = array( 'ul_key' => $key );
292 if( $val && $this->canUseNewUpdatelog() ) {
293 $values['ul_value'] = $val;
295 $this->db
->insert( 'updatelog', $values, __METHOD__
, 'IGNORE' );
299 * Updatelog was changed in 1.17 to have a ul_value column so we can record
300 * more information about what kind of updates we've done (that's what this
301 * class does). Pre-1.17 wikis won't have this column, and really old wikis
302 * might not even have updatelog at all
306 protected function canUseNewUpdatelog() {
307 return $this->db
->tableExists( 'updatelog' ) &&
308 $this->db
->fieldExists( 'updatelog', 'ul_value' );
312 * Before 1.17, we used to handle updates via stuff like
313 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
314 * of this in 1.17 but we want to remain back-compatible for a while. So
315 * load up these old global-based things into our update list.
317 protected function getOldGlobalUpdates() {
318 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
319 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
321 $doUser = $this->shared ?
322 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
323 !$wgSharedDB ||
!in_array( 'user', $wgSharedTables );
327 foreach ( $wgExtNewTables as $tableRecord ) {
329 'addTable', $tableRecord[0], $tableRecord[1], true
333 foreach ( $wgExtNewFields as $fieldRecord ) {
334 if ( $fieldRecord[0] != 'user' ||
$doUser ) {
336 'addField', $fieldRecord[0], $fieldRecord[1],
337 $fieldRecord[2], true
342 foreach ( $wgExtNewIndexes as $fieldRecord ) {
344 'addIndex', $fieldRecord[0], $fieldRecord[1],
345 $fieldRecord[2], true
349 foreach ( $wgExtModifiedFields as $fieldRecord ) {
351 'modifyField', $fieldRecord[0], $fieldRecord[1],
352 $fieldRecord[2], true
360 * Get an array of updates to perform on the database. Should return a
361 * multi-dimensional array. The main key is the MediaWiki version (1.12,
362 * 1.13...) with the values being arrays of updates, identical to how
363 * updaters.inc did it (for now)
367 protected abstract function getCoreUpdateList();
370 * Applies a SQL patch
371 * @param $path String Path to the patch file
372 * @param $isFullPath Boolean Whether to treat $path as a relative or not
374 protected function applyPatch( $path, $isFullPath = false ) {
376 $this->db
->sourceFile( $path );
378 $this->db
->sourceFile( $this->db
->patchPath( $path ) );
383 * Add a new table to the database
384 * @param $name String Name of the new table
385 * @param $patch String Path to the patch file
386 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
388 protected function addTable( $name, $patch, $fullpath = false ) {
389 if ( $this->db
->tableExists( $name ) ) {
390 $this->output( "...$name table already exists.\n" );
392 $this->output( "Creating $name table..." );
393 $this->applyPatch( $patch, $fullpath );
394 $this->output( "ok\n" );
399 * Add a new field to an existing table
400 * @param $table String Name of the table to modify
401 * @param $field String Name of the new field
402 * @param $patch String Path to the patch file
403 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
405 protected function addField( $table, $field, $patch, $fullpath = false ) {
406 if ( !$this->db
->tableExists( $table ) ) {
407 $this->output( "...$table table does not exist, skipping new field patch\n" );
408 } elseif ( $this->db
->fieldExists( $table, $field ) ) {
409 $this->output( "...have $field field in $table table.\n" );
411 $this->output( "Adding $field field to table $table..." );
412 $this->applyPatch( $patch, $fullpath );
413 $this->output( "ok\n" );
418 * Add a new index to an existing table
419 * @param $table String Name of the table to modify
420 * @param $index String Name of the new index
421 * @param $patch String Path to the patch file
422 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
424 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
425 if ( $this->db
->indexExists( $table, $index ) ) {
426 $this->output( "...$index key already set on $table table.\n" );
428 $this->output( "Adding $index key to table $table... " );
429 $this->applyPatch( $patch, $fullpath );
430 $this->output( "ok\n" );
435 * Drop a field from an existing table
437 * @param $table String Name of the table to modify
438 * @param $field String Name of the old field
439 * @param $patch String Path to the patch file
440 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
442 protected function dropField( $table, $field, $patch, $fullpath = false ) {
443 if ( $this->db
->fieldExists( $table, $field ) ) {
444 $this->output( "Table $table contains $field field. Dropping... " );
445 $this->applyPatch( $patch, $fullpath );
446 $this->output( "ok\n" );
448 $this->output( "...$table table does not contain $field field.\n" );
453 * Drop an index from an existing table
455 * @param $table String: Name of the table to modify
456 * @param $index String: Name of the old index
457 * @param $patch String: Path to the patch file
458 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
460 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
461 if ( $this->db
->indexExists( $table, $index ) ) {
462 $this->output( "Dropping $index from table $table... " );
463 $this->applyPatch( $patch, $fullpath );
464 $this->output( "ok\n" );
466 $this->output( "...$index key doesn't exist.\n" );
471 * Modify an existing field
473 * @param $table String: name of the table to which the field belongs
474 * @param $field String: name of the field to modify
475 * @param $patch String: path to the patch file
476 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
478 public function modifyField( $table, $field, $patch, $fullpath = false ) {
479 $updateKey = "$table-$field-$patch";
480 if ( !$this->db
->tableExists( $table ) ) {
481 $this->output( "...$table table does not exist, skipping modify field patch\n" );
482 } elseif ( !$this->db
->fieldExists( $table, $field ) ) {
483 $this->output( "...$field field does not exist in $table table, skipping modify field patch\n" );
484 } elseif( $this->updateRowExists( $updateKey ) ) {
485 $this->output( "...$field in table $table already modified by patch $patch\n" );
487 $this->output( "Modifying $field field of table $table..." );
488 $this->applyPatch( $patch, $fullpath );
489 $this->insertUpdateRow( $updateKey );
490 $this->output( "ok\n" );
495 * Purge the objectcache table
497 protected function purgeCache() {
498 # We can't guarantee that the user will be able to use TRUNCATE,
499 # but we know that DELETE is available to us
500 $this->output( "Purging caches..." );
501 $this->db
->delete( 'objectcache', '*', __METHOD__
);
502 $this->output( "done.\n" );
506 * Check the site_stats table is not properly populated.
508 protected function checkStats() {
509 $this->output( "Checking site_stats row..." );
510 $row = $this->db
->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__
);
511 if ( $row === false ) {
512 $this->output( "data is missing! rebuilding...\n" );
513 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
514 $this->output( "missing ss_total_pages, rebuilding...\n" );
516 $this->output( "done.\n" );
519 SiteStatsInit
::doAllAndCommit( false );
522 # Common updater functions
524 protected function doActiveUsersInit() {
525 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', false, __METHOD__
);
526 if ( $activeUsers == -1 ) {
527 $activeUsers = $this->db
->selectField( 'recentchanges',
528 'COUNT( DISTINCT rc_user_text )',
529 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
531 $this->db
->update( 'site_stats',
532 array( 'ss_active_users' => intval( $activeUsers ) ),
533 array( 'ss_row_id' => 1 ), __METHOD__
, array( 'LIMIT' => 1 )
536 $this->output( "...ss_active_users user count set...\n" );
539 protected function doLogUsertextPopulation() {
540 if ( $this->updateRowExists( 'populate log_usertext' ) ) {
541 $this->output( "...log_user_text field already populated.\n" );
546 "Populating log_user_text field, printing progress markers. For large\n" .
547 "databases, you may want to hit Ctrl-C and do this manually with\n" .
548 "maintenance/populateLogUsertext.php.\n" );
549 $task = $this->maintenance
->runChild( 'PopulateLogUsertext' );
551 $this->output( "Done populating log_user_text field.\n" );
554 protected function doLogSearchPopulation() {
555 if ( $this->updateRowExists( 'populate log_search' ) ) {
556 $this->output( "...log_search table already populated.\n" );
561 "Populating log_search table, printing progress markers. For large\n" .
562 "databases, you may want to hit Ctrl-C and do this manually with\n" .
563 "maintenance/populateLogSearch.php.\n" );
564 $task = $this->maintenance
->runChild( 'PopulateLogSearch' );
566 $this->output( "Done populating log_search table.\n" );
569 protected function doUpdateTranscacheField() {
570 if ( $this->updateRowExists( 'convert transcache field' ) ) {
571 $this->output( "...transcache tc_time already converted.\n" );
575 $this->output( "Converting tc_time from UNIX epoch to MediaWiki timestamp... " );
576 $this->applyPatch( 'patch-tc-timestamp.sql' );
577 $this->output( "ok\n" );
580 protected function doCollationUpdate() {
581 global $wgCategoryCollation;
582 if ( $this->db
->selectField(
585 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
588 $this->output( "...collations up-to-date.\n" );
592 $task = $this->maintenance
->runChild( 'UpdateCollation' );