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'
49 * @param $db DatabaseBase object to perform updates on
50 * @param $shared bool Whether to perform updates on shared tables
51 * @param $maintenance Maintenance Maintenance object which created us
53 protected function __construct( DatabaseBase
&$db, $shared, Maintenance
$maintenance = null ) {
55 $this->db
->setFlag( DBO_DDLMODE
); // For Oracle's handling of schema files
56 $this->shared
= $shared;
58 $this->maintenance
= $maintenance;
60 $this->maintenance
= new FakeMaintenance
;
62 $this->maintenance
->setDB( $db );
63 $this->initOldGlobals();
64 $this->loadExtensions();
65 wfRunHooks( 'LoadExtensionSchemaUpdates', array( $this ) );
69 * Initialize all of the old globals. One day this should all become
70 * something much nicer
72 private function initOldGlobals() {
73 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
74 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
76 # For extensions only, should be populated via hooks
77 # $wgDBtype should be checked to specifiy the proper file
78 $wgExtNewTables = array(); // table, dir
79 $wgExtNewFields = array(); // table, column, dir
80 $wgExtPGNewFields = array(); // table, column, column attributes; for PostgreSQL
81 $wgExtPGAlteredFields = array(); // table, column, new type, conversion method; for PostgreSQL
82 $wgExtNewIndexes = array(); // table, index, dir
83 $wgExtModifiedFields = array(); // table, index, dir
87 * Loads LocalSettings.php, if needed, and initialises everything needed for LoadExtensionSchemaUpdates hook
89 private function loadExtensions() {
90 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
91 return; // already loaded
93 $vars = Installer
::getExistingLocalSettings();
95 return; // no LocalSettings found
97 if ( !isset( $vars['wgHooks'] ) && !isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
100 global $wgHooks, $wgAutoloadClasses;
101 $wgHooks['LoadExtensionSchemaUpdates'] = $vars['wgHooks']['LoadExtensionSchemaUpdates'];
102 $wgAutoloadClasses = $wgAutoloadClasses +
$vars['wgAutoloadClasses'];
106 * @throws MWException
107 * @param DatabaseBase $db
108 * @param bool $shared
109 * @param null $maintenance
110 * @return DatabaseUpdater
112 public static function newForDB( &$db, $shared = false, $maintenance = null ) {
113 $type = $db->getType();
114 if( in_array( $type, Installer
::getDBTypes() ) ) {
115 $class = ucfirst( $type ) . 'Updater';
116 return new $class( $db, $shared, $maintenance );
118 throw new MWException( __METHOD__
. ' called for unsupported $wgDBtype' );
123 * Get a database connection to run updates
125 * @return DatabaseBase
127 public function getDB() {
132 * Output some text. If we're running from web, escape the text first.
134 * @param $str String: Text to output
136 public function output( $str ) {
137 if ( $this->maintenance
->isQuiet() ) {
140 global $wgCommandLineMode;
141 if( !$wgCommandLineMode ) {
142 $str = htmlspecialchars( $str );
149 * Add a new update coming from an extension. This should be called by
150 * extensions while executing the LoadExtensionSchemaUpdates hook.
152 * @param $update Array: the update to run. Format is the following:
153 * first item is the callback function, it also can be a
154 * simple string with the name of a function in this class,
155 * following elements are parameters to the function.
156 * Note that callback functions will receive this object as
159 public function addExtensionUpdate( Array $update ) {
160 $this->extensionUpdates
[] = $update;
164 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
165 * is the most common usage of updaters in an extension)
166 * @param $tableName String Name of table to create
167 * @param $sqlPath String Full path to the schema file
169 public function addExtensionTable( $tableName, $sqlPath ) {
170 $this->extensionUpdates
[] = array( 'addTable', $tableName, $sqlPath, true );
174 * Get the list of extension-defined updates
178 protected function getExtensionUpdates() {
179 return $this->extensionUpdates
;
182 public function getPostDatabaseUpdateMaintenance() {
183 return $this->postDatabaseUpdateMaintenance
;
189 * @param $what Array: what updates to perform
191 public function doUpdates( $what = array( 'core', 'extensions', 'purge' ) ) {
194 $what = array_flip( $what );
195 if ( isset( $what['core'] ) ) {
196 $this->runUpdates( $this->getCoreUpdateList(), false );
198 if ( isset( $what['extensions'] ) ) {
199 $this->runUpdates( $this->getOldGlobalUpdates(), false );
200 $this->runUpdates( $this->getExtensionUpdates(), true );
203 $this->setAppliedUpdates( $wgVersion, $this->updates
);
205 if( isset( $what['purge'] ) ) {
208 if ( isset( $what['core'] ) ) {
214 * Helper function for doUpdates()
216 * @param $updates Array of updates to run
217 * @param $passSelf Boolean: whether to pass this object we calling external
220 private function runUpdates( array $updates, $passSelf ) {
221 foreach ( $updates as $params ) {
222 $func = array_shift( $params );
223 if( !is_array( $func ) && method_exists( $this, $func ) ) {
224 $func = array( $this, $func );
225 } elseif ( $passSelf ) {
226 array_unshift( $params, $this );
228 call_user_func_array( $func, $params );
231 $this->updates
= array_merge( $this->updates
, $updates );
234 protected function setAppliedUpdates( $version, $updates = array() ) {
235 if( !$this->canUseNewUpdatelog() ) {
238 $key = "updatelist-$version-" . time();
239 $this->db
->insert( 'updatelog',
240 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
245 * Helper function: check if the given key is present in the updatelog table.
246 * Obviously, only use this for updates that occur after the updatelog table was
248 * @param $key String Name of the key to check for
250 public function updateRowExists( $key ) {
251 $row = $this->db
->selectRow(
254 array( 'ul_key' => $key ),
261 * Helper function: Add a key to the updatelog table
262 * Obviously, only use this for updates that occur after the updatelog table was
264 * @param $key String Name of key to insert
265 * @param $val String [optional] value to insert along with the key
267 public function insertUpdateRow( $key, $val = null ) {
268 $values = array( 'ul_key' => $key );
269 if( $val && $this->canUseNewUpdatelog() ) {
270 $values['ul_value'] = $val;
272 $this->db
->insert( 'updatelog', $values, __METHOD__
, 'IGNORE' );
276 * Updatelog was changed in 1.17 to have a ul_value column so we can record
277 * more information about what kind of updates we've done (that's what this
278 * class does). Pre-1.17 wikis won't have this column, and really old wikis
279 * might not even have updatelog at all
283 protected function canUseNewUpdatelog() {
284 return $this->db
->tableExists( 'updatelog' ) &&
285 $this->db
->fieldExists( 'updatelog', 'ul_value' );
289 * Before 1.17, we used to handle updates via stuff like
290 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
291 * of this in 1.17 but we want to remain back-compatible for a while. So
292 * load up these old global-based things into our update list.
294 protected function getOldGlobalUpdates() {
295 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
296 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
298 $doUser = $this->shared ?
299 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
300 !$wgSharedDB ||
!in_array( 'user', $wgSharedTables );
304 foreach ( $wgExtNewTables as $tableRecord ) {
306 'addTable', $tableRecord[0], $tableRecord[1], true
310 foreach ( $wgExtNewFields as $fieldRecord ) {
311 if ( $fieldRecord[0] != 'user' ||
$doUser ) {
313 'addField', $fieldRecord[0], $fieldRecord[1],
314 $fieldRecord[2], true
319 foreach ( $wgExtNewIndexes as $fieldRecord ) {
321 'addIndex', $fieldRecord[0], $fieldRecord[1],
322 $fieldRecord[2], true
326 foreach ( $wgExtModifiedFields as $fieldRecord ) {
328 'modifyField', $fieldRecord[0], $fieldRecord[1],
329 $fieldRecord[2], true
337 * Get an array of updates to perform on the database. Should return a
338 * multi-dimensional array. The main key is the MediaWiki version (1.12,
339 * 1.13...) with the values being arrays of updates, identical to how
340 * updaters.inc did it (for now)
344 protected abstract function getCoreUpdateList();
347 * Applies a SQL patch
348 * @param $path String Path to the patch file
349 * @param $isFullPath Boolean Whether to treat $path as a relative or not
351 protected function applyPatch( $path, $isFullPath = false ) {
353 $this->db
->sourceFile( $path );
355 $this->db
->sourceFile( $this->db
->patchPath( $path ) );
360 * Add a new table to the database
361 * @param $name String Name of the new table
362 * @param $patch String Path to the patch file
363 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
365 protected function addTable( $name, $patch, $fullpath = false ) {
366 if ( $this->db
->tableExists( $name ) ) {
367 $this->output( "...$name table already exists.\n" );
369 $this->output( "Creating $name table..." );
370 $this->applyPatch( $patch, $fullpath );
371 $this->output( "ok\n" );
376 * Add a new field to an existing table
377 * @param $table String Name of the table to modify
378 * @param $field String Name of the new field
379 * @param $patch String Path to the patch file
380 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
382 protected function addField( $table, $field, $patch, $fullpath = false ) {
383 if ( !$this->db
->tableExists( $table ) ) {
384 $this->output( "...$table table does not exist, skipping new field patch\n" );
385 } elseif ( $this->db
->fieldExists( $table, $field ) ) {
386 $this->output( "...have $field field in $table table.\n" );
388 $this->output( "Adding $field field to table $table..." );
389 $this->applyPatch( $patch, $fullpath );
390 $this->output( "ok\n" );
395 * Add a new index to an existing table
396 * @param $table String Name of the table to modify
397 * @param $index String Name of the new index
398 * @param $patch String Path to the patch file
399 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
401 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
402 if ( $this->db
->indexExists( $table, $index ) ) {
403 $this->output( "...$index key already set on $table table.\n" );
405 $this->output( "Adding $index key to table $table... " );
406 $this->applyPatch( $patch, $fullpath );
407 $this->output( "ok\n" );
412 * Drop a field from an existing table
414 * @param $table String Name of the table to modify
415 * @param $field String Name of the old field
416 * @param $patch String Path to the patch file
417 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
419 protected function dropField( $table, $field, $patch, $fullpath = false ) {
420 if ( $this->db
->fieldExists( $table, $field ) ) {
421 $this->output( "Table $table contains $field field. Dropping... " );
422 $this->applyPatch( $patch, $fullpath );
423 $this->output( "ok\n" );
425 $this->output( "...$table table does not contain $field field.\n" );
430 * Drop an index from an existing table
432 * @param $table String: Name of the table to modify
433 * @param $index String: Name of the old index
434 * @param $patch String: Path to the patch file
435 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
437 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
438 if ( $this->db
->indexExists( $table, $index ) ) {
439 $this->output( "Dropping $index from table $table... " );
440 $this->applyPatch( $patch, $fullpath );
441 $this->output( "ok\n" );
443 $this->output( "...$index key doesn't exist.\n" );
448 * Modify an existing field
450 * @param $table String: name of the table to which the field belongs
451 * @param $field String: name of the field to modify
452 * @param $patch String: path to the patch file
453 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
455 public function modifyField( $table, $field, $patch, $fullpath = false ) {
456 $updateKey = "$table-$field-$patch";
457 if ( !$this->db
->tableExists( $table ) ) {
458 $this->output( "...$table table does not exist, skipping modify field patch\n" );
459 } elseif ( !$this->db
->fieldExists( $table, $field ) ) {
460 $this->output( "...$field field does not exist in $table table, skipping modify field patch\n" );
461 } elseif( $this->updateRowExists( $updateKey ) ) {
462 $this->output( "...$field in table $table already modified by patch $patch\n" );
464 $this->output( "Modifying $field field of table $table..." );
465 $this->applyPatch( $patch, $fullpath );
466 $this->insertUpdateRow( $updateKey );
467 $this->output( "ok\n" );
472 * Purge the objectcache table
474 protected function purgeCache() {
475 # We can't guarantee that the user will be able to use TRUNCATE,
476 # but we know that DELETE is available to us
477 $this->output( "Purging caches..." );
478 $this->db
->delete( 'objectcache', '*', __METHOD__
);
479 $this->output( "done.\n" );
483 * Check the site_stats table is not properly populated.
485 protected function checkStats() {
486 $this->output( "Checking site_stats row..." );
487 $row = $this->db
->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__
);
488 if ( $row === false ) {
489 $this->output( "data is missing! rebuilding...\n" );
490 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
491 $this->output( "missing ss_total_pages, rebuilding...\n" );
493 $this->output( "done.\n" );
496 SiteStatsInit
::doAllAndCommit( false );
499 # Common updater functions
501 protected function doActiveUsersInit() {
502 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', false, __METHOD__
);
503 if ( $activeUsers == -1 ) {
504 $activeUsers = $this->db
->selectField( 'recentchanges',
505 'COUNT( DISTINCT rc_user_text )',
506 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
508 $this->db
->update( 'site_stats',
509 array( 'ss_active_users' => intval( $activeUsers ) ),
510 array( 'ss_row_id' => 1 ), __METHOD__
, array( 'LIMIT' => 1 )
513 $this->output( "...ss_active_users user count set...\n" );
516 protected function doLogUsertextPopulation() {
517 if ( $this->updateRowExists( 'populate log_usertext' ) ) {
518 $this->output( "...log_user_text field already populated.\n" );
523 "Populating log_user_text field, printing progress markers. For large\n" .
524 "databases, you may want to hit Ctrl-C and do this manually with\n" .
525 "maintenance/populateLogUsertext.php.\n" );
526 $task = $this->maintenance
->runChild( 'PopulateLogUsertext' );
528 $this->output( "Done populating log_user_text field.\n" );
531 protected function doLogSearchPopulation() {
532 if ( $this->updateRowExists( 'populate log_search' ) ) {
533 $this->output( "...log_search table already populated.\n" );
538 "Populating log_search table, printing progress markers. For large\n" .
539 "databases, you may want to hit Ctrl-C and do this manually with\n" .
540 "maintenance/populateLogSearch.php.\n" );
541 $task = $this->maintenance
->runChild( 'PopulateLogSearch' );
543 $this->output( "Done populating log_search table.\n" );
546 protected function doUpdateTranscacheField() {
547 if ( $this->updateRowExists( 'convert transcache field' ) ) {
548 $this->output( "...transcache tc_time already converted.\n" );
552 $this->output( "Converting tc_time from UNIX epoch to MediaWiki timestamp... " );
553 $this->applyPatch( 'patch-tc-timestamp.sql' );
554 $this->output( "ok\n" );
557 protected function doCollationUpdate() {
558 global $wgCategoryCollation;
559 if ( $this->db
->selectField(
562 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
565 $this->output( "...collations up-to-date.\n" );
569 $task = $this->maintenance
->runChild( 'UpdateCollation' );