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->initOldGlobals();
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
92 * @param DatabaseBase $db
94 * @param null $maintenance
95 * @return DatabaseUpdater
97 public static function newForDB( &$db, $shared = false, $maintenance = null ) {
98 $type = $db->getType();
99 if( in_array( $type, Installer
::getDBTypes() ) ) {
100 $class = ucfirst( $type ) . 'Updater';
101 return new $class( $db, $shared, $maintenance );
103 throw new MWException( __METHOD__
. ' called for unsupported $wgDBtype' );
108 * Get a database connection to run updates
110 * @return DatabaseBase
112 public function getDB() {
117 * Output some text. If we're running from web, escape the text first.
119 * @param $str String: Text to output
121 public function output( $str ) {
122 if ( $this->maintenance
->isQuiet() ) {
125 global $wgCommandLineMode;
126 if( !$wgCommandLineMode ) {
127 $str = htmlspecialchars( $str );
134 * Add a new update coming from an extension. This should be called by
135 * extensions while executing the LoadExtensionSchemaUpdates hook.
137 * @param $update Array: the update to run. Format is the following:
138 * first item is the callback function, it also can be a
139 * simple string with the name of a function in this class,
140 * following elements are parameters to the function.
141 * Note that callback functions will receive this object as
144 public function addExtensionUpdate( Array $update ) {
145 $this->extensionUpdates
[] = $update;
149 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
150 * is the most common usage of updaters in an extension)
151 * @param $tableName String Name of table to create
152 * @param $sqlPath String Full path to the schema file
154 public function addExtensionTable( $tableName, $sqlPath ) {
155 $this->extensionUpdates
[] = array( 'addTable', $tableName, $sqlPath, true );
159 * Add a brand new extension to MediaWiki. Used during the initial install
160 * @param $ext String Name of extension
161 * @param $sqlPath String Full path to the schema file
163 public function addNewExtension( $ext, $sqlPath ) {
164 $this->newExtensions
[ strtolower( $ext ) ] = $sqlPath;
168 * Get the list of extensions that registered a schema with our DB type
171 public function getNewExtensions() {
172 return $this->newExtensions
;
176 * Get the list of extension-defined updates
180 protected function getExtensionUpdates() {
181 return $this->extensionUpdates
;
184 public function getPostDatabaseUpdateMaintenance() {
185 return $this->postDatabaseUpdateMaintenance
;
191 * @param $what Array: what updates to perform
193 public function doUpdates( $what = array( 'core', 'extensions', 'purge' ) ) {
196 $what = array_flip( $what );
197 if ( isset( $what['core'] ) ) {
198 $this->runUpdates( $this->getCoreUpdateList(), false );
200 if ( isset( $what['extensions'] ) ) {
201 $this->runUpdates( $this->getOldGlobalUpdates(), false );
202 $this->runUpdates( $this->getExtensionUpdates(), true );
205 $this->setAppliedUpdates( $wgVersion, $this->updates
);
207 if( isset( $what['purge'] ) ) {
210 if ( isset( $what['core'] ) ) {
216 * Helper function for doUpdates()
218 * @param $updates Array of updates to run
219 * @param $passSelf Boolean: whether to pass this object we calling external
222 private function runUpdates( array $updates, $passSelf ) {
223 foreach ( $updates as $params ) {
224 $func = array_shift( $params );
225 if( !is_array( $func ) && method_exists( $this, $func ) ) {
226 $func = array( $this, $func );
227 } elseif ( $passSelf ) {
228 array_unshift( $params, $this );
230 call_user_func_array( $func, $params );
233 $this->updates
= array_merge( $this->updates
, $updates );
236 protected function setAppliedUpdates( $version, $updates = array() ) {
237 if( !$this->canUseNewUpdatelog() ) {
240 $key = "updatelist-$version-" . time();
241 $this->db
->insert( 'updatelog',
242 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
247 * Helper function: check if the given key is present in the updatelog table.
248 * Obviously, only use this for updates that occur after the updatelog table was
251 public function updateRowExists( $key ) {
252 $row = $this->db
->selectRow(
255 array( 'ul_key' => $key ),
262 * Updatelog was changed in 1.17 to have a ul_value column so we can record
263 * more information about what kind of updates we've done (that's what this
264 * class does). Pre-1.17 wikis won't have this column, and really old wikis
265 * might not even have updatelog at all
269 protected function canUseNewUpdatelog() {
270 return $this->db
->tableExists( 'updatelog' ) &&
271 $this->db
->fieldExists( 'updatelog', 'ul_value' );
275 * Before 1.17, we used to handle updates via stuff like
276 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
277 * of this in 1.17 but we want to remain back-compatible for a while. So
278 * load up these old global-based things into our update list.
280 protected function getOldGlobalUpdates() {
281 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
282 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
284 $doUser = $this->shared ?
285 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
286 !$wgSharedDB ||
!in_array( 'user', $wgSharedTables );
290 foreach ( $wgExtNewTables as $tableRecord ) {
292 'addTable', $tableRecord[0], $tableRecord[1], true
296 foreach ( $wgExtNewFields as $fieldRecord ) {
297 if ( $fieldRecord[0] != 'user' ||
$doUser ) {
299 'addField', $fieldRecord[0], $fieldRecord[1],
300 $fieldRecord[2], true
305 foreach ( $wgExtNewIndexes as $fieldRecord ) {
307 'addIndex', $fieldRecord[0], $fieldRecord[1],
308 $fieldRecord[2], true
312 foreach ( $wgExtModifiedFields as $fieldRecord ) {
314 'modifyField', $fieldRecord[0], $fieldRecord[1],
315 $fieldRecord[2], true
323 * Get an array of updates to perform on the database. Should return a
324 * multi-dimensional array. The main key is the MediaWiki version (1.12,
325 * 1.13...) with the values being arrays of updates, identical to how
326 * updaters.inc did it (for now)
330 protected abstract function getCoreUpdateList();
333 * Applies a SQL patch
334 * @param $path String Path to the patch file
335 * @param $isFullPath Boolean Whether to treat $path as a relative or not
337 protected function applyPatch( $path, $isFullPath = false ) {
339 $this->db
->sourceFile( $path );
341 $this->db
->sourceFile( $this->db
->patchPath( $path ) );
346 * Add a new table to the database
347 * @param $name String Name of the new table
348 * @param $patch String Path to the patch file
349 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
351 protected function addTable( $name, $patch, $fullpath = false ) {
352 if ( $this->db
->tableExists( $name ) ) {
353 $this->output( "...$name table already exists.\n" );
355 $this->output( "Creating $name table..." );
356 $this->applyPatch( $patch, $fullpath );
357 $this->output( "ok\n" );
362 * Add a new field to an existing table
363 * @param $table String Name of the table to modify
364 * @param $field String Name of the new field
365 * @param $patch String Path to the patch file
366 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
368 protected function addField( $table, $field, $patch, $fullpath = false ) {
369 if ( !$this->db
->tableExists( $table ) ) {
370 $this->output( "...$table table does not exist, skipping new field patch\n" );
371 } elseif ( $this->db
->fieldExists( $table, $field ) ) {
372 $this->output( "...have $field field in $table table.\n" );
374 $this->output( "Adding $field field to table $table..." );
375 $this->applyPatch( $patch, $fullpath );
376 $this->output( "ok\n" );
381 * Add a new index to an existing table
382 * @param $table String Name of the table to modify
383 * @param $index String Name of the new index
384 * @param $patch String Path to the patch file
385 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
387 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
388 if ( $this->db
->indexExists( $table, $index ) ) {
389 $this->output( "...$index key already set on $table table.\n" );
391 $this->output( "Adding $index key to table $table... " );
392 $this->applyPatch( $patch, $fullpath );
393 $this->output( "ok\n" );
398 * Drop a field from an existing table
400 * @param $table String Name of the table to modify
401 * @param $field String Name of the old 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 dropField( $table, $field, $patch, $fullpath = false ) {
406 if ( $this->db
->fieldExists( $table, $field ) ) {
407 $this->output( "Table $table contains $field field. Dropping... " );
408 $this->applyPatch( $patch, $fullpath );
409 $this->output( "ok\n" );
411 $this->output( "...$table table does not contain $field field.\n" );
416 * Drop an index from an existing table
418 * @param $table String: Name of the table to modify
419 * @param $index String: Name of the old index
420 * @param $patch String: Path to the patch file
421 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
423 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
424 if ( $this->db
->indexExists( $table, $index ) ) {
425 $this->output( "Dropping $index from table $table... " );
426 $this->applyPatch( $patch, $fullpath );
427 $this->output( "ok\n" );
429 $this->output( "...$index key doesn't exist.\n" );
434 * Modify an existing field
436 * @param $table String: name of the table to which the field belongs
437 * @param $field String: name of the field to modify
438 * @param $patch String: path to the patch file
439 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
441 public function modifyField( $table, $field, $patch, $fullpath = false ) {
442 if ( !$this->db
->tableExists( $table ) ) {
443 $this->output( "...$table table does not exist, skipping modify field patch\n" );
444 } elseif ( !$this->db
->fieldExists( $table, $field ) ) {
445 $this->output( "...$field field does not exist in $table table, skipping modify field patch\n" );
447 $this->output( "Modifying $field field of table $table..." );
448 $this->applyPatch( $patch, $fullpath );
449 $this->output( "ok\n" );
454 * Purge the objectcache table
456 protected function purgeCache() {
457 # We can't guarantee that the user will be able to use TRUNCATE,
458 # but we know that DELETE is available to us
459 $this->output( "Purging caches..." );
460 $this->db
->delete( 'objectcache', '*', __METHOD__
);
461 $this->output( "done.\n" );
465 * Check the site_stats table is not properly populated.
467 protected function checkStats() {
468 $this->output( "Checking site_stats row..." );
469 $row = $this->db
->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__
);
470 if ( $row === false ) {
471 $this->output( "data is missing! rebuilding...\n" );
472 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
473 $this->output( "missing ss_total_pages, rebuilding...\n" );
475 $this->output( "done.\n" );
478 SiteStatsInit
::doAllAndCommit( false );
481 # Common updater functions
483 protected function doActiveUsersInit() {
484 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', false, __METHOD__
);
485 if ( $activeUsers == -1 ) {
486 $activeUsers = $this->db
->selectField( 'recentchanges',
487 'COUNT( DISTINCT rc_user_text )',
488 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
490 $this->db
->update( 'site_stats',
491 array( 'ss_active_users' => intval( $activeUsers ) ),
492 array( 'ss_row_id' => 1 ), __METHOD__
, array( 'LIMIT' => 1 )
495 $this->output( "...ss_active_users user count set...\n" );
498 protected function doLogUsertextPopulation() {
499 if ( $this->updateRowExists( 'populate log_usertext' ) ) {
500 $this->output( "...log_user_text field already populated.\n" );
505 "Populating log_user_text field, printing progress markers. For large\n" .
506 "databases, you may want to hit Ctrl-C and do this manually with\n" .
507 "maintenance/populateLogUsertext.php.\n" );
508 $task = new PopulateLogUsertext();
510 $this->output( "Done populating log_user_text field.\n" );
513 protected function doLogSearchPopulation() {
514 if ( $this->updateRowExists( 'populate log_search' ) ) {
515 $this->output( "...log_search table already populated.\n" );
520 "Populating log_search table, printing progress markers. For large\n" .
521 "databases, you may want to hit Ctrl-C and do this manually with\n" .
522 "maintenance/populateLogSearch.php.\n" );
523 $task = new PopulateLogSearch();
525 $this->output( "Done populating log_search table.\n" );
528 protected function doUpdateTranscacheField() {
529 if ( $this->updateRowExists( 'convert transcache field' ) ) {
530 $this->output( "...transcache tc_time already converted.\n" );
534 $this->output( "Converting tc_time from UNIX epoch to MediaWiki timestamp... " );
535 $this->applyPatch( 'patch-tc-timestamp.sql' );
536 $this->output( "ok\n" );
539 protected function doCollationUpdate() {
540 global $wgCategoryCollation;
541 if ( $this->db
->selectField(
544 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
547 $this->output( "...collations up-to-date.\n" );
551 $task = new UpdateCollation();