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'
50 * @param $db DatabaseBase object to perform updates on
51 * @param $shared bool Whether to perform updates on shared tables
52 * @param $maintenance Maintenance Maintenance object which created us
54 protected function __construct( DatabaseBase
&$db, $shared, Maintenance
$maintenance = null ) {
56 $this->db
->setFlag( DBO_DDLMODE
); // For Oracle's handling of schema files
57 $this->shared
= $shared;
59 $this->maintenance
= $maintenance;
61 $this->maintenance
= new FakeMaintenance
;
63 $this->maintenance
->setDB( $db );
64 $this->initOldGlobals();
65 $this->loadExtensions();
66 wfRunHooks( 'LoadExtensionSchemaUpdates', array( $this ) );
70 * Initialize all of the old globals. One day this should all become
71 * something much nicer
73 private function initOldGlobals() {
74 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
75 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
77 # For extensions only, should be populated via hooks
78 # $wgDBtype should be checked to specifiy the proper file
79 $wgExtNewTables = array(); // table, dir
80 $wgExtNewFields = array(); // table, column, dir
81 $wgExtPGNewFields = array(); // table, column, column attributes; for PostgreSQL
82 $wgExtPGAlteredFields = array(); // table, column, new type, conversion method; for PostgreSQL
83 $wgExtNewIndexes = array(); // table, index, dir
84 $wgExtModifiedFields = array(); // table, index, dir
88 * Loads LocalSettings.php, if needed, and initialises everything needed for LoadExtensionSchemaUpdates hook
90 private function loadExtensions() {
91 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
92 return; // already loaded
94 $vars = Installer
::getExistingLocalSettings();
96 return; // no LocalSettings found
98 if ( !isset( $vars['wgHooks'] ) ||
!isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
101 global $wgHooks, $wgAutoloadClasses;
102 $wgHooks['LoadExtensionSchemaUpdates'] = $vars['wgHooks']['LoadExtensionSchemaUpdates'];
103 $wgAutoloadClasses = $wgAutoloadClasses +
$vars['wgAutoloadClasses'];
107 * @throws MWException
108 * @param DatabaseBase $db
109 * @param bool $shared
110 * @param null $maintenance
111 * @return DatabaseUpdater
113 public static function newForDB( &$db, $shared = false, $maintenance = null ) {
114 $type = $db->getType();
115 if( in_array( $type, Installer
::getDBTypes() ) ) {
116 $class = ucfirst( $type ) . 'Updater';
117 return new $class( $db, $shared, $maintenance );
119 throw new MWException( __METHOD__
. ' called for unsupported $wgDBtype' );
124 * Get a database connection to run updates
126 * @return DatabaseBase
128 public function getDB() {
133 * Output some text. If we're running from web, escape the text first.
135 * @param $str String: Text to output
137 public function output( $str ) {
138 if ( $this->maintenance
->isQuiet() ) {
141 global $wgCommandLineMode;
142 if( !$wgCommandLineMode ) {
143 $str = htmlspecialchars( $str );
150 * Add a new update coming from an extension. This should be called by
151 * extensions while executing the LoadExtensionSchemaUpdates hook.
153 * @param $update Array: the update to run. Format is the following:
154 * first item is the callback function, it also can be a
155 * simple string with the name of a function in this class,
156 * following elements are parameters to the function.
157 * Note that callback functions will receive this object as
160 public function addExtensionUpdate( Array $update ) {
161 $this->extensionUpdates
[] = $update;
165 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
166 * is the most common usage of updaters in an extension)
167 * @param $tableName String Name of table to create
168 * @param $sqlPath String Full path to the schema file
170 public function addExtensionTable( $tableName, $sqlPath ) {
171 $this->extensionUpdates
[] = array( 'addTable', $tableName, $sqlPath, true );
175 * @param $tableName string
176 * @param $indexName string
177 * @param $sqlPath string
179 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
180 $this->extensionUpdates
[] = array( 'addIndex', $tableName, $indexName, $sqlPath, true );
184 * @param $tableName string
185 * @param $columnName string
186 * @param $sqlPath string
188 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
189 $this->extensionUpdates
[] = array( 'addField', $tableName, $columnName, $sqlPath );
193 * Get the list of extension-defined updates
197 protected function getExtensionUpdates() {
198 return $this->extensionUpdates
;
204 public function getPostDatabaseUpdateMaintenance() {
205 return $this->postDatabaseUpdateMaintenance
;
211 * @param $what Array: what updates to perform
213 public function doUpdates( $what = array( 'core', 'extensions', 'purge', 'stats' ) ) {
216 $what = array_flip( $what );
217 if ( isset( $what['core'] ) ) {
218 $this->runUpdates( $this->getCoreUpdateList(), false );
220 if ( isset( $what['extensions'] ) ) {
221 $this->runUpdates( $this->getOldGlobalUpdates(), false );
222 $this->runUpdates( $this->getExtensionUpdates(), true );
225 $this->setAppliedUpdates( $wgVersion, $this->updates
);
227 if( isset( $what['purge'] ) ) {
230 if ( isset( $what['stats'] ) ) {
236 * Helper function for doUpdates()
238 * @param $updates Array of updates to run
239 * @param $passSelf Boolean: whether to pass this object we calling external
242 private function runUpdates( array $updates, $passSelf ) {
243 foreach ( $updates as $params ) {
244 $func = array_shift( $params );
245 if( !is_array( $func ) && method_exists( $this, $func ) ) {
246 $func = array( $this, $func );
247 } elseif ( $passSelf ) {
248 array_unshift( $params, $this );
250 call_user_func_array( $func, $params );
253 $this->updates
= array_merge( $this->updates
, $updates );
258 * @param $updates array
260 protected function setAppliedUpdates( $version, $updates = array() ) {
261 $this->db
->clearFlag( DBO_DDLMODE
);
262 if( !$this->canUseNewUpdatelog() ) {
265 $key = "updatelist-$version-" . time();
266 $this->db
->insert( 'updatelog',
267 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
269 $this->db
->setFlag( DBO_DDLMODE
);
273 * Helper function: check if the given key is present in the updatelog table.
274 * Obviously, only use this for updates that occur after the updatelog table was
276 * @param $key String Name of the key to check for
280 public function updateRowExists( $key ) {
281 $row = $this->db
->selectRow(
284 array( 'ul_key' => $key ),
291 * Helper function: Add a key to the updatelog table
292 * Obviously, only use this for updates that occur after the updatelog table was
294 * @param $key String Name of key to insert
295 * @param $val String [optional] value to insert along with the key
297 public function insertUpdateRow( $key, $val = null ) {
298 $this->db
->clearFlag( DBO_DDLMODE
);
299 $values = array( 'ul_key' => $key );
300 if( $val && $this->canUseNewUpdatelog() ) {
301 $values['ul_value'] = $val;
303 $this->db
->insert( 'updatelog', $values, __METHOD__
, 'IGNORE' );
304 $this->db
->setFlag( DBO_DDLMODE
);
308 * Updatelog was changed in 1.17 to have a ul_value column so we can record
309 * more information about what kind of updates we've done (that's what this
310 * class does). Pre-1.17 wikis won't have this column, and really old wikis
311 * might not even have updatelog at all
315 protected function canUseNewUpdatelog() {
316 return $this->db
->tableExists( 'updatelog' ) &&
317 $this->db
->fieldExists( 'updatelog', 'ul_value' );
321 * Before 1.17, we used to handle updates via stuff like
322 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
323 * of this in 1.17 but we want to remain back-compatible for a while. So
324 * load up these old global-based things into our update list.
328 protected function getOldGlobalUpdates() {
329 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
330 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
332 $doUser = $this->shared ?
333 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
334 !$wgSharedDB ||
!in_array( 'user', $wgSharedTables );
338 foreach ( $wgExtNewTables as $tableRecord ) {
340 'addTable', $tableRecord[0], $tableRecord[1], true
344 foreach ( $wgExtNewFields as $fieldRecord ) {
345 if ( $fieldRecord[0] != 'user' ||
$doUser ) {
347 'addField', $fieldRecord[0], $fieldRecord[1],
348 $fieldRecord[2], true
353 foreach ( $wgExtNewIndexes as $fieldRecord ) {
355 'addIndex', $fieldRecord[0], $fieldRecord[1],
356 $fieldRecord[2], true
360 foreach ( $wgExtModifiedFields as $fieldRecord ) {
362 'modifyField', $fieldRecord[0], $fieldRecord[1],
363 $fieldRecord[2], true
371 * Get an array of updates to perform on the database. Should return a
372 * multi-dimensional array. The main key is the MediaWiki version (1.12,
373 * 1.13...) with the values being arrays of updates, identical to how
374 * updaters.inc did it (for now)
378 protected abstract function getCoreUpdateList();
381 * Applies a SQL patch
382 * @param $path String Path to the patch file
383 * @param $isFullPath Boolean Whether to treat $path as a relative or not
385 protected function applyPatch( $path, $isFullPath = false ) {
387 $this->db
->sourceFile( $path );
389 $this->db
->sourceFile( $this->db
->patchPath( $path ) );
394 * Add a new table to the database
395 * @param $name String Name of the new table
396 * @param $patch String Path to the patch file
397 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
399 protected function addTable( $name, $patch, $fullpath = false ) {
400 if ( $this->db
->tableExists( $name ) ) {
401 $this->output( "...$name table already exists.\n" );
403 $this->output( "Creating $name table..." );
404 $this->applyPatch( $patch, $fullpath );
405 $this->output( "ok\n" );
410 * Add a new field to an existing table
411 * @param $table String Name of the table to modify
412 * @param $field String Name of the new field
413 * @param $patch String Path to the patch file
414 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
416 protected function addField( $table, $field, $patch, $fullpath = false ) {
417 if ( !$this->db
->tableExists( $table ) ) {
418 $this->output( "...$table table does not exist, skipping new field patch\n" );
419 } elseif ( $this->db
->fieldExists( $table, $field ) ) {
420 $this->output( "...have $field field in $table table.\n" );
422 $this->output( "Adding $field field to table $table..." );
423 $this->applyPatch( $patch, $fullpath );
424 $this->output( "ok\n" );
429 * Add a new index to an existing table
430 * @param $table String Name of the table to modify
431 * @param $index String Name of the new index
432 * @param $patch String Path to the patch file
433 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
435 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
436 if ( $this->db
->indexExists( $table, $index ) ) {
437 $this->output( "...$index key already set on $table table.\n" );
439 $this->output( "Adding $index key to table $table... " );
440 $this->applyPatch( $patch, $fullpath );
441 $this->output( "ok\n" );
446 * Drop a field from an existing table
448 * @param $table String Name of the table to modify
449 * @param $field String Name of the old field
450 * @param $patch String Path to the patch file
451 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
453 protected function dropField( $table, $field, $patch, $fullpath = false ) {
454 if ( $this->db
->fieldExists( $table, $field ) ) {
455 $this->output( "Table $table contains $field field. Dropping... " );
456 $this->applyPatch( $patch, $fullpath );
457 $this->output( "ok\n" );
459 $this->output( "...$table table does not contain $field field.\n" );
464 * Drop an index from an existing table
466 * @param $table String: Name of the table to modify
467 * @param $index String: Name of the old index
468 * @param $patch String: Path to the patch file
469 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
471 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
472 if ( $this->db
->indexExists( $table, $index ) ) {
473 $this->output( "Dropping $index from table $table... " );
474 $this->applyPatch( $patch, $fullpath );
475 $this->output( "ok\n" );
477 $this->output( "...$index key doesn't exist.\n" );
482 * Modify an existing field
484 * @param $table String: name of the table to which the field belongs
485 * @param $field String: name of the field to modify
486 * @param $patch String: path to the patch file
487 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
489 public function modifyField( $table, $field, $patch, $fullpath = false ) {
490 $updateKey = "$table-$field-$patch";
491 if ( !$this->db
->tableExists( $table ) ) {
492 $this->output( "...$table table does not exist, skipping modify field patch\n" );
493 } elseif ( !$this->db
->fieldExists( $table, $field ) ) {
494 $this->output( "...$field field does not exist in $table table, skipping modify field patch\n" );
495 } elseif( $this->updateRowExists( $updateKey ) ) {
496 $this->output( "...$field in table $table already modified by patch $patch\n" );
498 $this->output( "Modifying $field field of table $table..." );
499 $this->applyPatch( $patch, $fullpath );
500 $this->insertUpdateRow( $updateKey );
501 $this->output( "ok\n" );
506 * Purge the objectcache table
508 protected function purgeCache() {
509 # We can't guarantee that the user will be able to use TRUNCATE,
510 # but we know that DELETE is available to us
511 $this->output( "Purging caches..." );
512 $this->db
->delete( 'objectcache', '*', __METHOD__
);
513 $this->output( "done.\n" );
517 * Check the site_stats table is not properly populated.
519 protected function checkStats() {
520 $this->output( "Checking site_stats row..." );
521 $row = $this->db
->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__
);
522 if ( $row === false ) {
523 $this->output( "data is missing! rebuilding...\n" );
524 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
525 $this->output( "missing ss_total_pages, rebuilding...\n" );
527 $this->output( "done.\n" );
530 SiteStatsInit
::doAllAndCommit( $this->db
);
533 # Common updater functions
535 protected function doActiveUsersInit() {
536 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', false, __METHOD__
);
537 if ( $activeUsers == -1 ) {
538 $activeUsers = $this->db
->selectField( 'recentchanges',
539 'COUNT( DISTINCT rc_user_text )',
540 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
542 $this->db
->update( 'site_stats',
543 array( 'ss_active_users' => intval( $activeUsers ) ),
544 array( 'ss_row_id' => 1 ), __METHOD__
, array( 'LIMIT' => 1 )
547 $this->output( "...ss_active_users user count set...\n" );
550 protected function doLogUsertextPopulation() {
551 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
553 "Populating log_user_text field, printing progress markers. For large\n" .
554 "databases, you may want to hit Ctrl-C and do this manually with\n" .
555 "maintenance/populateLogUsertext.php.\n" );
557 $task = $this->maintenance
->runChild( 'PopulateLogUsertext' );
561 protected function doLogSearchPopulation() {
562 if ( !$this->updateRowExists( 'populate log_search' ) ) {
564 "Populating log_search table, printing progress markers. For large\n" .
565 "databases, you may want to hit Ctrl-C and do this manually with\n" .
566 "maintenance/populateLogSearch.php.\n" );
568 $task = $this->maintenance
->runChild( 'PopulateLogSearch' );
572 protected function doUpdateTranscacheField() {
573 if ( $this->updateRowExists( 'convert transcache field' ) ) {
574 $this->output( "...transcache tc_time already converted.\n" );
578 $this->output( "Converting tc_time from UNIX epoch to MediaWiki timestamp... " );
579 $this->applyPatch( 'patch-tc-timestamp.sql' );
580 $this->output( "ok\n" );
583 protected function doCollationUpdate() {
584 global $wgCategoryCollation;
585 if ( $this->db
->selectField(
588 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
591 $this->output( "...collations up-to-date.\n" );
595 $task = $this->maintenance
->runChild( 'UpdateCollation' );
599 protected function doMigrateUserOptions() {
600 $cl = $this->maintenance
->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
601 $this->output( "Migrating remaining user_options... " );
603 $this->output( "done.\n" );