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
93 * @param DatabaseBase $db
95 * @param null $maintenance
96 * @return DatabaseUpdater
98 public static function newForDB( &$db, $shared = false, $maintenance = null ) {
99 $type = $db->getType();
100 if( in_array( $type, Installer
::getDBTypes() ) ) {
101 $class = ucfirst( $type ) . 'Updater';
102 return new $class( $db, $shared, $maintenance );
104 throw new MWException( __METHOD__
. ' called for unsupported $wgDBtype' );
109 * Get a database connection to run updates
111 * @return DatabaseBase
113 public function getDB() {
118 * Output some text. If we're running from web, escape the text first.
120 * @param $str String: Text to output
122 public function output( $str ) {
123 if ( $this->maintenance
->isQuiet() ) {
126 global $wgCommandLineMode;
127 if( !$wgCommandLineMode ) {
128 $str = htmlspecialchars( $str );
135 * Add a new update coming from an extension. This should be called by
136 * extensions while executing the LoadExtensionSchemaUpdates hook.
138 * @param $update Array: the update to run. Format is the following:
139 * first item is the callback function, it also can be a
140 * simple string with the name of a function in this class,
141 * following elements are parameters to the function.
142 * Note that callback functions will receive this object as
145 public function addExtensionUpdate( Array $update ) {
146 $this->extensionUpdates
[] = $update;
150 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
151 * is the most common usage of updaters in an extension)
152 * @param $tableName String Name of table to create
153 * @param $sqlPath String Full path to the schema file
155 public function addExtensionTable( $tableName, $sqlPath ) {
156 $this->extensionUpdates
[] = array( 'addTable', $tableName, $sqlPath, true );
160 * Add a brand new extension to MediaWiki. Used during the initial install
161 * @param $ext String Name of extension
162 * @param $sqlPath String Full path to the schema file
164 public function addNewExtension( $ext, $sqlPath ) {
165 $this->newExtensions
[ strtolower( $ext ) ] = $sqlPath;
169 * Get the list of extensions that registered a schema with our DB type
172 public function getNewExtensions() {
173 return $this->newExtensions
;
177 * Get the list of extension-defined updates
181 protected function getExtensionUpdates() {
182 return $this->extensionUpdates
;
185 public function getPostDatabaseUpdateMaintenance() {
186 return $this->postDatabaseUpdateMaintenance
;
192 * @param $what Array: what updates to perform
194 public function doUpdates( $what = array( 'core', 'extensions', 'purge' ) ) {
197 $what = array_flip( $what );
198 if ( isset( $what['core'] ) ) {
199 $this->runUpdates( $this->getCoreUpdateList(), false );
201 if ( isset( $what['extensions'] ) ) {
202 $this->runUpdates( $this->getOldGlobalUpdates(), false );
203 $this->runUpdates( $this->getExtensionUpdates(), true );
206 $this->setAppliedUpdates( $wgVersion, $this->updates
);
208 if( isset( $what['purge'] ) ) {
211 if ( isset( $what['core'] ) ) {
217 * Helper function for doUpdates()
219 * @param $updates Array of updates to run
220 * @param $passSelf Boolean: whether to pass this object we calling external
223 private function runUpdates( array $updates, $passSelf ) {
224 foreach ( $updates as $params ) {
225 $func = array_shift( $params );
226 if( !is_array( $func ) && method_exists( $this, $func ) ) {
227 $func = array( $this, $func );
228 } elseif ( $passSelf ) {
229 array_unshift( $params, $this );
231 call_user_func_array( $func, $params );
234 $this->updates
= array_merge( $this->updates
, $updates );
237 protected function setAppliedUpdates( $version, $updates = array() ) {
238 if( !$this->canUseNewUpdatelog() ) {
241 $key = "updatelist-$version-" . time();
242 $this->db
->insert( 'updatelog',
243 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
248 * Helper function: check if the given key is present in the updatelog table.
249 * Obviously, only use this for updates that occur after the updatelog table was
252 public function updateRowExists( $key ) {
253 $row = $this->db
->selectRow(
256 array( 'ul_key' => $key ),
263 * Updatelog was changed in 1.17 to have a ul_value column so we can record
264 * more information about what kind of updates we've done (that's what this
265 * class does). Pre-1.17 wikis won't have this column, and really old wikis
266 * might not even have updatelog at all
270 protected function canUseNewUpdatelog() {
271 return $this->db
->tableExists( 'updatelog' ) &&
272 $this->db
->fieldExists( 'updatelog', 'ul_value' );
276 * Before 1.17, we used to handle updates via stuff like
277 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
278 * of this in 1.17 but we want to remain back-compatible for a while. So
279 * load up these old global-based things into our update list.
281 protected function getOldGlobalUpdates() {
282 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
283 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
285 $doUser = $this->shared ?
286 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
287 !$wgSharedDB ||
!in_array( 'user', $wgSharedTables );
291 foreach ( $wgExtNewTables as $tableRecord ) {
293 'addTable', $tableRecord[0], $tableRecord[1], true
297 foreach ( $wgExtNewFields as $fieldRecord ) {
298 if ( $fieldRecord[0] != 'user' ||
$doUser ) {
300 'addField', $fieldRecord[0], $fieldRecord[1],
301 $fieldRecord[2], true
306 foreach ( $wgExtNewIndexes as $fieldRecord ) {
308 'addIndex', $fieldRecord[0], $fieldRecord[1],
309 $fieldRecord[2], true
313 foreach ( $wgExtModifiedFields as $fieldRecord ) {
315 'modifyField', $fieldRecord[0], $fieldRecord[1],
316 $fieldRecord[2], true
324 * Get an array of updates to perform on the database. Should return a
325 * multi-dimensional array. The main key is the MediaWiki version (1.12,
326 * 1.13...) with the values being arrays of updates, identical to how
327 * updaters.inc did it (for now)
331 protected abstract function getCoreUpdateList();
334 * Applies a SQL patch
335 * @param $path String Path to the patch file
336 * @param $isFullPath Boolean Whether to treat $path as a relative or not
338 protected function applyPatch( $path, $isFullPath = false ) {
340 $this->db
->sourceFile( $path );
342 $this->db
->sourceFile( $this->db
->patchPath( $path ) );
347 * Add a new table to the database
348 * @param $name String Name of the new table
349 * @param $patch String Path to the patch file
350 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
352 protected function addTable( $name, $patch, $fullpath = false ) {
353 if ( $this->db
->tableExists( $name ) ) {
354 $this->output( "...$name table already exists.\n" );
356 $this->output( "Creating $name table..." );
357 $this->applyPatch( $patch, $fullpath );
358 $this->output( "ok\n" );
363 * Add a new field to an existing table
364 * @param $table String Name of the table to modify
365 * @param $field String Name of the new field
366 * @param $patch String Path to the patch file
367 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
369 protected function addField( $table, $field, $patch, $fullpath = false ) {
370 if ( !$this->db
->tableExists( $table ) ) {
371 $this->output( "...$table table does not exist, skipping new field patch\n" );
372 } elseif ( $this->db
->fieldExists( $table, $field ) ) {
373 $this->output( "...have $field field in $table table.\n" );
375 $this->output( "Adding $field field to table $table..." );
376 $this->applyPatch( $patch, $fullpath );
377 $this->output( "ok\n" );
382 * Add a new index to an existing table
383 * @param $table String Name of the table to modify
384 * @param $index String Name of the new index
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 addIndex( $table, $index, $patch, $fullpath = false ) {
389 if ( $this->db
->indexExists( $table, $index ) ) {
390 $this->output( "...$index key already set on $table table.\n" );
392 $this->output( "Adding $index key to table $table... " );
393 $this->applyPatch( $patch, $fullpath );
394 $this->output( "ok\n" );
399 * Drop a field from an existing table
401 * @param $table String Name of the table to modify
402 * @param $field String Name of the old field
403 * @param $patch String Path to the patch file
404 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
406 protected function dropField( $table, $field, $patch, $fullpath = false ) {
407 if ( $this->db
->fieldExists( $table, $field ) ) {
408 $this->output( "Table $table contains $field field. Dropping... " );
409 $this->applyPatch( $patch, $fullpath );
410 $this->output( "ok\n" );
412 $this->output( "...$table table does not contain $field field.\n" );
417 * Drop an index from an existing table
419 * @param $table String: Name of the table to modify
420 * @param $index String: Name of the old 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 dropIndex( $table, $index, $patch, $fullpath = false ) {
425 if ( $this->db
->indexExists( $table, $index ) ) {
426 $this->output( "Dropping $index from table $table... " );
427 $this->applyPatch( $patch, $fullpath );
428 $this->output( "ok\n" );
430 $this->output( "...$index key doesn't exist.\n" );
435 * Modify an existing field
437 * @param $table String: name of the table to which the field belongs
438 * @param $field String: name of the field to modify
439 * @param $patch String: path to the patch file
440 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
442 public function modifyField( $table, $field, $patch, $fullpath = false ) {
443 if ( !$this->db
->tableExists( $table ) ) {
444 $this->output( "...$table table does not exist, skipping modify field patch\n" );
445 } elseif ( !$this->db
->fieldExists( $table, $field ) ) {
446 $this->output( "...$field field does not exist in $table table, skipping modify field patch\n" );
448 $this->output( "Modifying $field field of table $table..." );
449 $this->applyPatch( $patch, $fullpath );
450 $this->output( "ok\n" );
455 * Purge the objectcache table
457 protected function purgeCache() {
458 # We can't guarantee that the user will be able to use TRUNCATE,
459 # but we know that DELETE is available to us
460 $this->output( "Purging caches..." );
461 $this->db
->delete( 'objectcache', '*', __METHOD__
);
462 $this->output( "done.\n" );
466 * Check the site_stats table is not properly populated.
468 protected function checkStats() {
469 $this->output( "Checking site_stats row..." );
470 $row = $this->db
->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__
);
471 if ( $row === false ) {
472 $this->output( "data is missing! rebuilding...\n" );
473 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
474 $this->output( "missing ss_total_pages, rebuilding...\n" );
476 $this->output( "done.\n" );
479 SiteStatsInit
::doAllAndCommit( false );
482 # Common updater functions
484 protected function doActiveUsersInit() {
485 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', false, __METHOD__
);
486 if ( $activeUsers == -1 ) {
487 $activeUsers = $this->db
->selectField( 'recentchanges',
488 'COUNT( DISTINCT rc_user_text )',
489 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
491 $this->db
->update( 'site_stats',
492 array( 'ss_active_users' => intval( $activeUsers ) ),
493 array( 'ss_row_id' => 1 ), __METHOD__
, array( 'LIMIT' => 1 )
496 $this->output( "...ss_active_users user count set...\n" );
499 protected function doLogUsertextPopulation() {
500 if ( $this->updateRowExists( 'populate log_usertext' ) ) {
501 $this->output( "...log_user_text field already populated.\n" );
506 "Populating log_user_text field, printing progress markers. For large\n" .
507 "databases, you may want to hit Ctrl-C and do this manually with\n" .
508 "maintenance/populateLogUsertext.php.\n" );
509 $task = new PopulateLogUsertext();
511 $this->output( "Done populating log_user_text field.\n" );
514 protected function doLogSearchPopulation() {
515 if ( $this->updateRowExists( 'populate log_search' ) ) {
516 $this->output( "...log_search table already populated.\n" );
521 "Populating log_search table, printing progress markers. For large\n" .
522 "databases, you may want to hit Ctrl-C and do this manually with\n" .
523 "maintenance/populateLogSearch.php.\n" );
524 $task = new PopulateLogSearch();
526 $this->output( "Done populating log_search table.\n" );
529 protected function doUpdateTranscacheField() {
530 if ( $this->updateRowExists( 'convert transcache field' ) ) {
531 $this->output( "...transcache tc_time already converted.\n" );
535 $this->output( "Converting tc_time from UNIX epoch to MediaWiki timestamp... " );
536 $this->applyPatch( 'patch-tc-timestamp.sql' );
537 $this->output( "ok\n" );
540 protected function doCollationUpdate() {
541 global $wgCategoryCollation;
542 if ( $this->db
->selectField(
545 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
548 $this->output( "...collations up-to-date.\n" );
552 $task = new UpdateCollation();