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 * List of extension-provided database updaters
37 protected $extensionUpdaters = array();
40 * Used to hold schema files during installation process
43 protected $newExtensions = array();
46 * Handle to the database subclass
52 protected $shared = false;
54 protected $postDatabaseUpdateMaintenance = array(
55 'DeleteDefaultMessages'
61 * @param $db DatabaseBase object to perform updates on
62 * @param $shared bool Whether to perform updates on shared tables
63 * @param $maintenance Maintenance Maintenance object which created us
65 protected function __construct( DatabaseBase
&$db, $shared, Maintenance
$maintenance = null ) {
67 $this->db
->setFlag( DBO_DDLMODE
); // For Oracle's handling of schema files
68 $this->shared
= $shared;
70 $this->maintenance
= $maintenance;
72 $this->maintenance
= new FakeMaintenance
;
74 $this->maintenance
->setDB( $db );
75 $this->initOldGlobals();
76 $this->initIncludedExtensions();
77 wfRunHooks( 'LoadExtensionSchemaUpdates', array( $this ) );
81 * Initialize all of the old globals. One day this should all become
82 * something much nicer
84 private function initOldGlobals() {
85 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
86 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
88 # For extensions only, should be populated via hooks
89 # $wgDBtype should be checked to specifiy the proper file
90 $wgExtNewTables = array(); // table, dir
91 $wgExtNewFields = array(); // table, column, dir
92 $wgExtPGNewFields = array(); // table, column, column attributes; for PostgreSQL
93 $wgExtPGAlteredFields = array(); // table, column, new type, conversion method; for PostgreSQL
94 $wgExtNewIndexes = array(); // table, index, dir
95 $wgExtModifiedFields = array(); // table, index, dir
99 * Try to include extensions from LocalSettings so their LocalExtensionSchemaChanges hooks can be run
101 private function initIncludedExtensions() {
102 global $IP, $wgHooks, $wgAutoloadClasses;
103 $ls = file_get_contents( "$IP/LocalSettings.php" );
104 if ( $ls === false ) return;
106 preg_match_all( '/[[:blank:]]*(?:require|include){1}(?:_once)?[[:blank:]]*\([[:blank:]]*"\$IP\/extensions\/([^\/].*)\/\1\.php"[[:blank:]]*\);[[:blank:]]*/i',
107 $ls, $matches, PREG_SET_ORDER
);
110 if ( !isset( $wgHooks ) )
112 if ( !isset( $wgAutoloadClasses ) )
113 $wgAutoloadClasses = array();
115 foreach ( $matches as $match ) {
116 include_once ( "$IP/extensions/{$match[1]}/{$match[1]}.php" );
121 * @throws MWException
122 * @param DatabaseBase $db
123 * @param bool $shared
124 * @param null $maintenance
125 * @return DatabaseUpdater
127 public static function newForDB( &$db, $shared = false, $maintenance = null ) {
128 $type = $db->getType();
129 if( in_array( $type, Installer
::getDBTypes() ) ) {
130 $class = ucfirst( $type ) . 'Updater';
131 return new $class( $db, $shared, $maintenance );
133 throw new MWException( __METHOD__
. ' called for unsupported $wgDBtype' );
138 * Get a database connection to run updates
140 * @return DatabaseBase
142 public function getDB() {
147 * Output some text. If we're running from web, escape the text first.
149 * @param $str String: Text to output
151 public function output( $str ) {
152 if ( $this->maintenance
->isQuiet() ) {
155 global $wgCommandLineMode;
156 if( !$wgCommandLineMode ) {
157 $str = htmlspecialchars( $str );
164 * Add a new update coming from an extension. This should be called by
165 * extensions while executing the LoadExtensionSchemaUpdates hook.
167 * @param $update Array: the update to run. Format is the following:
168 * first item is the callback function, it also can be a
169 * simple string with the name of a function in this class,
170 * following elements are parameters to the function.
171 * Note that callback functions will receive this object as
174 public function addExtensionUpdate( Array $update ) {
175 $this->extensionUpdates
[] = $update;
179 * Add a updater class that will handle extensions DB install/update.
180 * This should be called by extensions while executing the
181 * LoadExtensionSchemaUpdates hook.
183 * @param $updater (string) classname (extends DatabaseUpdater).
185 public function addExtensionUpdater( $updater ) {
186 $this->extensionUpdaters
[] = $updater;
190 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
191 * is the most common usage of updaters in an extension)
192 * @param $tableName String Name of table to create
193 * @param $sqlPath String Full path to the schema file
195 public function addExtensionTable( $tableName, $sqlPath ) {
196 $this->extensionUpdates
[] = array( 'addTable', $tableName, $sqlPath, true );
200 * Add a brand new extension to MediaWiki. Used during the initial install
201 * @param $ext String Name of extension
202 * @param $sqlPath String Full path to the schema file
204 public function addNewExtension( $ext, $sqlPath ) {
205 $this->newExtensions
[ strtolower( $ext ) ] = $sqlPath;
209 * Get the list of extensions that registered a schema with our DB type
212 public function getNewExtensions() {
213 return $this->newExtensions
;
217 * Get the list of extension-defined updates
221 protected function getExtensionUpdates() {
222 return $this->extensionUpdates
;
226 * Get the list of extension-defined updaters
230 protected function getExtensionUpdaters() {
231 return $this->extensionUpdaters
;
234 public function getPostDatabaseUpdateMaintenance() {
235 return $this->postDatabaseUpdateMaintenance
;
241 * @param $what Array: what updates to perform
243 public function doUpdates( $what = array( 'core', 'extensions', 'purge' ) ) {
246 $what = array_flip( $what );
247 if ( isset( $what['core'] ) ) {
248 $this->runUpdates( $this->getCoreUpdateList(), false );
250 if ( isset( $what['extensions'] ) ) {
251 $this->runUpdates( $this->getOldGlobalUpdates(), false );
252 $this->runUpdates( $this->getExtensionUpdates(), true );
253 foreach ( $this->getExtensionUpdaters() as $updaterClass ) {
254 $eupdater = new $updaterClass(this
);
255 $eupdater->doUpdates();
259 $this->setAppliedUpdates( $wgVersion, $this->updates
);
261 if( isset( $what['purge'] ) ) {
264 if ( isset( $what['core'] ) ) {
270 * Helper function for doUpdates()
272 * @param $updates Array of updates to run
273 * @param $passSelf Boolean: whether to pass this object we calling external
276 private function runUpdates( array $updates, $passSelf ) {
277 foreach ( $updates as $params ) {
278 $func = array_shift( $params );
279 if( !is_array( $func ) && method_exists( $this, $func ) ) {
280 $func = array( $this, $func );
281 } elseif ( $passSelf ) {
282 array_unshift( $params, $this );
284 call_user_func_array( $func, $params );
287 $this->updates
= array_merge( $this->updates
, $updates );
290 protected function setAppliedUpdates( $version, $updates = array() ) {
291 if( !$this->canUseNewUpdatelog() ) {
294 $key = "updatelist-$version-" . time();
295 $this->db
->insert( 'updatelog',
296 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
301 * Helper function: check if the given key is present in the updatelog table.
302 * Obviously, only use this for updates that occur after the updatelog table was
304 * @param $key String Name of the key to check for
306 public function updateRowExists( $key ) {
307 $row = $this->db
->selectRow(
310 array( 'ul_key' => $key ),
317 * Helper function: Add a key to the updatelog table
318 * Obviously, only use this for updates that occur after the updatelog table was
320 * @param $key String Name of key to insert
321 * @param $val String [optional] value to insert along with the key
323 public function insertUpdateRow( $key, $val = null ) {
324 $values = array( 'ul_key' => $key );
325 if( $val && $this->canUseNewUpdatelog() ) {
326 $values['ul_value'] = $val;
328 $this->db
->insert( 'updatelog', $values, __METHOD__
, 'IGNORE' );
332 * Updatelog was changed in 1.17 to have a ul_value column so we can record
333 * more information about what kind of updates we've done (that's what this
334 * class does). Pre-1.17 wikis won't have this column, and really old wikis
335 * might not even have updatelog at all
339 protected function canUseNewUpdatelog() {
340 return $this->db
->tableExists( 'updatelog' ) &&
341 $this->db
->fieldExists( 'updatelog', 'ul_value' );
345 * Before 1.17, we used to handle updates via stuff like
346 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
347 * of this in 1.17 but we want to remain back-compatible for a while. So
348 * load up these old global-based things into our update list.
350 protected function getOldGlobalUpdates() {
351 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
352 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
354 $doUser = $this->shared ?
355 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
356 !$wgSharedDB ||
!in_array( 'user', $wgSharedTables );
360 foreach ( $wgExtNewTables as $tableRecord ) {
362 'addTable', $tableRecord[0], $tableRecord[1], true
366 foreach ( $wgExtNewFields as $fieldRecord ) {
367 if ( $fieldRecord[0] != 'user' ||
$doUser ) {
369 'addField', $fieldRecord[0], $fieldRecord[1],
370 $fieldRecord[2], true
375 foreach ( $wgExtNewIndexes as $fieldRecord ) {
377 'addIndex', $fieldRecord[0], $fieldRecord[1],
378 $fieldRecord[2], true
382 foreach ( $wgExtModifiedFields as $fieldRecord ) {
384 'modifyField', $fieldRecord[0], $fieldRecord[1],
385 $fieldRecord[2], true
393 * Get an array of updates to perform on the database. Should return a
394 * multi-dimensional array. The main key is the MediaWiki version (1.12,
395 * 1.13...) with the values being arrays of updates, identical to how
396 * updaters.inc did it (for now)
400 protected abstract function getCoreUpdateList();
403 * Applies a SQL patch
404 * @param $path String Path to the patch file
405 * @param $isFullPath Boolean Whether to treat $path as a relative or not
407 protected function applyPatch( $path, $isFullPath = false ) {
409 $this->db
->sourceFile( $path );
411 $this->db
->sourceFile( $this->db
->patchPath( $path ) );
416 * Add a new table to the database
417 * @param $name String Name of the new table
418 * @param $patch String Path to the patch file
419 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
421 protected function addTable( $name, $patch, $fullpath = false ) {
422 if ( $this->db
->tableExists( $name ) ) {
423 $this->output( "...$name table already exists.\n" );
425 $this->output( "Creating $name table..." );
426 $this->applyPatch( $patch, $fullpath );
427 $this->output( "ok\n" );
432 * Add a new field to an existing table
433 * @param $table String Name of the table to modify
434 * @param $field String Name of the new field
435 * @param $patch String Path to the patch file
436 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
438 protected function addField( $table, $field, $patch, $fullpath = false ) {
439 if ( !$this->db
->tableExists( $table ) ) {
440 $this->output( "...$table table does not exist, skipping new field patch\n" );
441 } elseif ( $this->db
->fieldExists( $table, $field ) ) {
442 $this->output( "...have $field field in $table table.\n" );
444 $this->output( "Adding $field field to table $table..." );
445 $this->applyPatch( $patch, $fullpath );
446 $this->output( "ok\n" );
451 * Add a new index to an existing table
452 * @param $table String Name of the table to modify
453 * @param $index String Name of the new index
454 * @param $patch String Path to the patch file
455 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
457 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
458 if ( $this->db
->indexExists( $table, $index ) ) {
459 $this->output( "...$index key already set on $table table.\n" );
461 $this->output( "Adding $index key to table $table... " );
462 $this->applyPatch( $patch, $fullpath );
463 $this->output( "ok\n" );
468 * Drop a field from an existing table
470 * @param $table String Name of the table to modify
471 * @param $field String Name of the old field
472 * @param $patch String Path to the patch file
473 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
475 protected function dropField( $table, $field, $patch, $fullpath = false ) {
476 if ( $this->db
->fieldExists( $table, $field ) ) {
477 $this->output( "Table $table contains $field field. Dropping... " );
478 $this->applyPatch( $patch, $fullpath );
479 $this->output( "ok\n" );
481 $this->output( "...$table table does not contain $field field.\n" );
486 * Drop an index from an existing table
488 * @param $table String: Name of the table to modify
489 * @param $index String: Name of the old index
490 * @param $patch String: Path to the patch file
491 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
493 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
494 if ( $this->db
->indexExists( $table, $index ) ) {
495 $this->output( "Dropping $index from table $table... " );
496 $this->applyPatch( $patch, $fullpath );
497 $this->output( "ok\n" );
499 $this->output( "...$index key doesn't exist.\n" );
504 * Modify an existing field
506 * @param $table String: name of the table to which the field belongs
507 * @param $field String: name of the field to modify
508 * @param $patch String: path to the patch file
509 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
511 public function modifyField( $table, $field, $patch, $fullpath = false ) {
512 $updateKey = "$table-$field-$patch";
513 if ( !$this->db
->tableExists( $table ) ) {
514 $this->output( "...$table table does not exist, skipping modify field patch\n" );
515 } elseif ( !$this->db
->fieldExists( $table, $field ) ) {
516 $this->output( "...$field field does not exist in $table table, skipping modify field patch\n" );
517 } elseif( $this->updateRowExists( $updateKey ) ) {
518 $this->output( "...$field in table $table already modified by patch $patch\n" );
520 $this->output( "Modifying $field field of table $table..." );
521 $this->applyPatch( $patch, $fullpath );
522 $this->insertUpdateRow( $updateKey );
523 $this->output( "ok\n" );
528 * Purge the objectcache table
530 protected function purgeCache() {
531 # We can't guarantee that the user will be able to use TRUNCATE,
532 # but we know that DELETE is available to us
533 $this->output( "Purging caches..." );
534 $this->db
->delete( 'objectcache', '*', __METHOD__
);
535 $this->output( "done.\n" );
539 * Check the site_stats table is not properly populated.
541 protected function checkStats() {
542 $this->output( "Checking site_stats row..." );
543 $row = $this->db
->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__
);
544 if ( $row === false ) {
545 $this->output( "data is missing! rebuilding...\n" );
546 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
547 $this->output( "missing ss_total_pages, rebuilding...\n" );
549 $this->output( "done.\n" );
552 SiteStatsInit
::doAllAndCommit( false );
555 # Common updater functions
557 protected function doActiveUsersInit() {
558 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', false, __METHOD__
);
559 if ( $activeUsers == -1 ) {
560 $activeUsers = $this->db
->selectField( 'recentchanges',
561 'COUNT( DISTINCT rc_user_text )',
562 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
564 $this->db
->update( 'site_stats',
565 array( 'ss_active_users' => intval( $activeUsers ) ),
566 array( 'ss_row_id' => 1 ), __METHOD__
, array( 'LIMIT' => 1 )
569 $this->output( "...ss_active_users user count set...\n" );
572 protected function doLogUsertextPopulation() {
573 if ( $this->updateRowExists( 'populate log_usertext' ) ) {
574 $this->output( "...log_user_text field already populated.\n" );
579 "Populating log_user_text field, printing progress markers. For large\n" .
580 "databases, you may want to hit Ctrl-C and do this manually with\n" .
581 "maintenance/populateLogUsertext.php.\n" );
582 $task = $this->maintenance
->runChild( 'PopulateLogUsertext' );
584 $this->output( "Done populating log_user_text field.\n" );
587 protected function doLogSearchPopulation() {
588 if ( $this->updateRowExists( 'populate log_search' ) ) {
589 $this->output( "...log_search table already populated.\n" );
594 "Populating log_search table, printing progress markers. For large\n" .
595 "databases, you may want to hit Ctrl-C and do this manually with\n" .
596 "maintenance/populateLogSearch.php.\n" );
597 $task = $this->maintenance
->runChild( 'PopulateLogSearch' );
599 $this->output( "Done populating log_search table.\n" );
602 protected function doUpdateTranscacheField() {
603 if ( $this->updateRowExists( 'convert transcache field' ) ) {
604 $this->output( "...transcache tc_time already converted.\n" );
608 $this->output( "Converting tc_time from UNIX epoch to MediaWiki timestamp... " );
609 $this->applyPatch( 'patch-tc-timestamp.sql' );
610 $this->output( "ok\n" );
613 protected function doCollationUpdate() {
614 global $wgCategoryCollation;
615 if ( $this->db
->selectField(
618 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
621 $this->output( "...collations up-to-date.\n" );
625 $task = $this->maintenance
->runChild( 'UpdateCollation' );