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();
27 protected $extensionUpdates = array();
30 * Handle to the database subclass
36 protected $shared = false;
38 protected $postDatabaseUpdateMaintenance = array(
39 'DeleteDefaultMessages'
45 * @param $db DatabaseBase object to perform updates on
46 * @param $shared bool Whether to perform updates on shared tables
47 * @param $maintenance Maintenance Maintenance object which created us
49 protected function __construct( DatabaseBase
&$db, $shared, Maintenance
$maintenance = null ) {
51 $this->shared
= $shared;
53 $this->maintenance
= $maintenance;
55 $this->maintenance
= new FakeMaintenance
;
57 $this->initOldGlobals();
58 wfRunHooks( 'LoadExtensionSchemaUpdates', array( $this ) );
62 * Initialize all of the old globals. One day this should all become
63 * something much nicer
65 private function initOldGlobals() {
66 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
67 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
69 # For extensions only, should be populated via hooks
70 # $wgDBtype should be checked to specifiy the proper file
71 $wgExtNewTables = array(); // table, dir
72 $wgExtNewFields = array(); // table, column, dir
73 $wgExtPGNewFields = array(); // table, column, column attributes; for PostgreSQL
74 $wgExtPGAlteredFields = array(); // table, column, new type, conversion method; for PostgreSQL
75 $wgExtNewIndexes = array(); // table, index, dir
76 $wgExtModifiedFields = array(); // table, index, dir
82 * @param DatabaseBase $db
84 * @param null $maintenance
87 public static function newForDB( &$db, $shared = false, $maintenance = null ) {
88 $type = $db->getType();
89 if( in_array( $type, Installer
::getDBTypes() ) ) {
90 $class = ucfirst( $type ) . 'Updater';
91 return new $class( $db, $shared, $maintenance );
93 throw new MWException( __METHOD__
. ' called for unsupported $wgDBtype' );
98 * Get a database connection to run updates
100 * @return DatabaseBase object
102 public function getDB() {
107 * Output some text. If we're running from web, escape the text first.
109 * @param $str String: Text to output
111 public function output( $str ) {
112 if ( $this->maintenance
->isQuiet() ) {
115 global $wgCommandLineMode;
116 if( !$wgCommandLineMode ) {
117 $str = htmlspecialchars( $str );
124 * Add a new update coming from an extension. This should be called by
125 * extensions while executing the LoadExtensionSchemaUpdates hook.
127 * @param $update Array: the update to run. Format is the following:
128 * first item is the callback function, it also can be a
129 * simple string with the name of a function in this class,
130 * following elements are parameters to the function.
131 * Note that callback functions will recieve this object as
134 public function addExtensionUpdate( Array $update ) {
135 $this->extensionUpdates
[] = $update;
139 * Get the list of extension-defined updates
143 protected function getExtensionUpdates() {
144 return $this->extensionUpdates
;
147 public function getPostDatabaseUpdateMaintenance() {
148 return $this->postDatabaseUpdateMaintenance
;
154 * @param $purge Boolean: whether to clear the objectcache table after updates
156 public function doUpdates( $purge = true ) {
159 if ( !defined( 'MW_NO_SETUP' ) ) {
160 define( 'MW_NO_SETUP', true );
163 $this->runUpdates( $this->getCoreUpdateList(), false );
164 $this->runUpdates( $this->getOldGlobalUpdates(), false );
165 $this->runUpdates( $this->getExtensionUpdates(), true );
167 $this->setAppliedUpdates( $wgVersion, $this->updates
);
176 * Helper function for doUpdates()
178 * @param $updates Array of updates to run
179 * @param $passSelf Boolean: whether to pass this object we calling external
182 private function runUpdates( array $updates, $passSelf ) {
183 foreach ( $updates as $params ) {
184 $func = array_shift( $params );
185 if( !is_array( $func ) && method_exists( $this, $func ) ) {
186 $func = array( $this, $func );
187 } elseif ( $passSelf ) {
188 array_unshift( $params, $this );
190 call_user_func_array( $func, $params );
193 $this->updates
= array_merge( $this->updates
, $updates );
196 protected function setAppliedUpdates( $version, $updates = array() ) {
197 if( !$this->canUseNewUpdatelog() ) {
200 $key = "updatelist-$version-" . time();
201 $this->db
->insert( 'updatelog',
202 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
207 * Helper function: check if the given key is present in the updatelog table.
208 * Obviously, only use this for updates that occur after the updatelog table was
211 public function updateRowExists( $key ) {
212 $row = $this->db
->selectRow(
215 array( 'ul_key' => $key ),
222 * Updatelog was changed in 1.17 to have a ul_value column so we can record
223 * more information about what kind of updates we've done (that's what this
224 * class does). Pre-1.17 wikis won't have this column, and really old wikis
225 * might not even have updatelog at all
229 protected function canUseNewUpdatelog() {
230 return $this->db
->tableExists( 'updatelog' ) &&
231 $this->db
->fieldExists( 'updatelog', 'ul_value' );
235 * Before 1.17, we used to handle updates via stuff like
236 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
237 * of this in 1.17 but we want to remain back-compatible for a while. So
238 * load up these old global-based things into our update list.
240 protected function getOldGlobalUpdates() {
241 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
242 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
244 $doUser = $this->shared ?
245 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
246 !$wgSharedDB ||
!in_array( 'user', $wgSharedTables );
250 foreach ( $wgExtNewTables as $tableRecord ) {
252 'addTable', $tableRecord[0], $tableRecord[1], true
256 foreach ( $wgExtNewFields as $fieldRecord ) {
257 if ( $fieldRecord[0] != 'user' ||
$doUser ) {
259 'addField', $fieldRecord[0], $fieldRecord[1],
260 $fieldRecord[2], true
265 foreach ( $wgExtNewIndexes as $fieldRecord ) {
267 'addIndex', $fieldRecord[0], $fieldRecord[1],
268 $fieldRecord[2], true
272 foreach ( $wgExtModifiedFields as $fieldRecord ) {
274 'modifyField', $fieldRecord[0], $fieldRecord[1],
275 $fieldRecord[2], true
283 * Get an array of updates to perform on the database. Should return a
284 * multi-dimensional array. The main key is the MediaWiki version (1.12,
285 * 1.13...) with the values being arrays of updates, identical to how
286 * updaters.inc did it (for now)
290 protected abstract function getCoreUpdateList();
293 * Applies a SQL patch
294 * @param $path String Path to the patch file
295 * @param $isFullPath Boolean Whether to treat $path as a relative or not
297 protected function applyPatch( $path, $isFullPath = false ) {
299 $this->db
->sourceFile( $path );
301 $this->db
->sourceFile( $this->db
->patchPath( $path ) );
306 * Add a new table to the database
307 * @param $name String Name of the new table
308 * @param $patch String Path to the patch file
309 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
311 protected function addTable( $name, $patch, $fullpath = false ) {
312 if ( $this->db
->tableExists( $name ) ) {
313 $this->output( "...$name table already exists.\n" );
315 $this->output( "Creating $name table..." );
316 $this->applyPatch( $patch, $fullpath );
317 $this->output( "ok\n" );
322 * Add a new field to an existing table
323 * @param $table String Name of the table to modify
324 * @param $field String Name of the new field
325 * @param $patch String Path to the patch file
326 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
328 protected function addField( $table, $field, $patch, $fullpath = false ) {
329 if ( !$this->db
->tableExists( $table ) ) {
330 $this->output( "...$table table does not exist, skipping new field patch\n" );
331 } elseif ( $this->db
->fieldExists( $table, $field ) ) {
332 $this->output( "...have $field field in $table table.\n" );
334 $this->output( "Adding $field field to table $table..." );
335 $this->applyPatch( $patch, $fullpath );
336 $this->output( "ok\n" );
341 * Add a new index to an existing table
342 * @param $table String Name of the table to modify
343 * @param $index String Name of the new index
344 * @param $patch String Path to the patch file
345 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
347 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
348 if ( $this->db
->indexExists( $table, $index ) ) {
349 $this->output( "...$index key already set on $table table.\n" );
351 $this->output( "Adding $index key to table $table... " );
352 $this->applyPatch( $patch, $fullpath );
353 $this->output( "ok\n" );
358 * Drop a field from an existing table
360 * @param $table String Name of the table to modify
361 * @param $field String Name of the old field
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 dropField( $table, $field, $patch, $fullpath = false ) {
366 if ( $this->db
->fieldExists( $table, $field ) ) {
367 $this->output( "Table $table contains $field field. Dropping... " );
368 $this->applyPatch( $patch, $fullpath );
369 $this->output( "ok\n" );
371 $this->output( "...$table table does not contain $field field.\n" );
376 * Drop an index from an existing table
378 * @param $table String: Name of the table to modify
379 * @param $index String: Name of the old index
380 * @param $patch String: Path to the patch file
381 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
383 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
384 if ( $this->db
->indexExists( $table, $index ) ) {
385 $this->output( "Dropping $index from table $table... " );
386 $this->applyPatch( $patch, $fullpath );
387 $this->output( "ok\n" );
389 $this->output( "...$index key doesn't exist.\n" );
394 * Modify an existing field
396 * @param $table String: name of the table to which the field belongs
397 * @param $field String: name of the field to modify
398 * @param $patch String: path to the patch file
399 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
401 public function modifyField( $table, $field, $patch, $fullpath = false ) {
402 if ( !$this->db
->tableExists( $table ) ) {
403 $this->output( "...$table table does not exist, skipping modify field patch\n" );
404 } elseif ( !$this->db
->fieldExists( $table, $field ) ) {
405 $this->output( "...$field field does not exist in $table table, skipping modify field patch\n" );
407 $this->output( "Modifying $field field of table $table..." );
408 $this->applyPatch( $patch, $fullpath );
409 $this->output( "ok\n" );
414 * Purge the objectcache table
416 protected function purgeCache() {
417 # We can't guarantee that the user will be able to use TRUNCATE,
418 # but we know that DELETE is available to us
419 $this->output( "Purging caches..." );
420 $this->db
->delete( 'objectcache', '*', __METHOD__
);
421 $this->output( "done.\n" );
425 * Check the site_stats table is not properly populated.
427 protected function checkStats() {
428 $this->output( "Checking site_stats row..." );
429 $row = $this->db
->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__
);
430 if ( $row === false ) {
431 $this->output( "data is missing! rebuilding...\n" );
432 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
433 $this->output( "missing ss_total_pages, rebuilding...\n" );
435 $this->output( "done.\n" );
438 SiteStatsInit
::doAllAndCommit( false );
441 # Common updater functions
443 protected function doActiveUsersInit() {
444 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', false, __METHOD__
);
445 if ( $activeUsers == -1 ) {
446 $activeUsers = $this->db
->selectField( 'recentchanges',
447 'COUNT( DISTINCT rc_user_text )',
448 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
450 $this->db
->update( 'site_stats',
451 array( 'ss_active_users' => intval( $activeUsers ) ),
452 array( 'ss_row_id' => 1 ), __METHOD__
, array( 'LIMIT' => 1 )
455 $this->output( "...ss_active_users user count set...\n" );
458 protected function doLogSearchPopulation() {
459 if ( $this->updateRowExists( 'populate log_search' ) ) {
460 $this->output( "...log_search table already populated.\n" );
465 "Populating log_search table, printing progress markers. For large\n" .
466 "databases, you may want to hit Ctrl-C and do this manually with\n" .
467 "maintenance/populateLogSearch.php.\n" );
468 $task = new PopulateLogSearch();
470 $this->output( "Done populating log_search table.\n" );
473 protected function doUpdateTranscacheField() {
474 if ( $this->updateRowExists( 'convert transcache field' ) ) {
475 $this->output( "...transcache tc_time already converted.\n" );
479 $this->output( "Converting tc_time from UNIX epoch to MediaWiki timestamp... " );
480 $this->applyPatch( 'patch-tc-timestamp.sql' );
481 $this->output( "ok\n" );
484 protected function doCollationUpdate() {
485 global $wgCategoryCollation;
486 if ( $this->db
->selectField(
489 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
492 $this->output( "...collations up-to-date.\n" );
496 $task = new UpdateCollation();