3 * DBMS-specific updater helper.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 require_once( __DIR__
. '/../../maintenance/Maintenance.php' );
27 * Class for handling database updates. Roughly based off of updaters.inc, with
28 * a few improvements :)
33 abstract class DatabaseUpdater
{
36 * Array of updates to perform on the database
40 protected $updates = array();
43 * Array of updates that were skipped
47 protected $updatesSkipped = array();
50 * List of extension-provided database updates
53 protected $extensionUpdates = array();
56 * Handle to the database subclass
62 protected $shared = false;
65 * Scripts to run after database update
66 * Should be a subclass of LoggedUpdateMaintenance
68 protected $postDatabaseUpdateMaintenance = array(
69 'DeleteDefaultMessages',
70 'PopulateRevisionLength',
71 'PopulateRevisionSha1',
73 'FixExtLinksProtocolRelative',
74 'PopulateFilearchiveSha1',
78 * File handle for SQL output.
82 protected $fileHandle = null;
85 * Flag specifying whether or not to skip schema (e.g. SQL-only) updates.
89 protected $skipSchema = false;
94 * @param $db DatabaseBase object to perform updates on
95 * @param $shared bool Whether to perform updates on shared tables
96 * @param $maintenance Maintenance Maintenance object which created us
98 protected function __construct( DatabaseBase
&$db, $shared, Maintenance
$maintenance = null ) {
100 $this->db
->setFlag( DBO_DDLMODE
); // For Oracle's handling of schema files
101 $this->shared
= $shared;
102 if ( $maintenance ) {
103 $this->maintenance
= $maintenance;
104 $this->fileHandle
= $maintenance->fileHandle
;
106 $this->maintenance
= new FakeMaintenance
;
108 $this->maintenance
->setDB( $db );
109 $this->initOldGlobals();
110 $this->loadExtensions();
111 wfRunHooks( 'LoadExtensionSchemaUpdates', array( $this ) );
115 * Initialize all of the old globals. One day this should all become
116 * something much nicer
118 private function initOldGlobals() {
119 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
120 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
122 # For extensions only, should be populated via hooks
123 # $wgDBtype should be checked to specifiy the proper file
124 $wgExtNewTables = array(); // table, dir
125 $wgExtNewFields = array(); // table, column, dir
126 $wgExtPGNewFields = array(); // table, column, column attributes; for PostgreSQL
127 $wgExtPGAlteredFields = array(); // table, column, new type, conversion method; for PostgreSQL
128 $wgExtNewIndexes = array(); // table, index, dir
129 $wgExtModifiedFields = array(); // table, index, dir
133 * Loads LocalSettings.php, if needed, and initialises everything needed for LoadExtensionSchemaUpdates hook
135 private function loadExtensions() {
136 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
137 return; // already loaded
139 $vars = Installer
::getExistingLocalSettings();
141 return; // no LocalSettings found
143 if ( !isset( $vars['wgHooks'] ) ||
!isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
146 global $wgHooks, $wgAutoloadClasses;
147 $wgHooks['LoadExtensionSchemaUpdates'] = $vars['wgHooks']['LoadExtensionSchemaUpdates'];
148 $wgAutoloadClasses = $wgAutoloadClasses +
$vars['wgAutoloadClasses'];
152 * @throws MWException
153 * @param DatabaseBase $db
154 * @param bool $shared
155 * @param null $maintenance
156 * @return DatabaseUpdater
158 public static function newForDB( &$db, $shared = false, $maintenance = null ) {
159 $type = $db->getType();
160 if( in_array( $type, Installer
::getDBTypes() ) ) {
161 $class = ucfirst( $type ) . 'Updater';
162 return new $class( $db, $shared, $maintenance );
164 throw new MWException( __METHOD__
. ' called for unsupported $wgDBtype' );
169 * Get a database connection to run updates
171 * @return DatabaseBase
173 public function getDB() {
178 * Output some text. If we're running from web, escape the text first.
180 * @param $str String: Text to output
182 public function output( $str ) {
183 if ( $this->maintenance
->isQuiet() ) {
186 global $wgCommandLineMode;
187 if( !$wgCommandLineMode ) {
188 $str = htmlspecialchars( $str );
195 * Add a new update coming from an extension. This should be called by
196 * extensions while executing the LoadExtensionSchemaUpdates hook.
200 * @param $update Array: the update to run. Format is the following:
201 * first item is the callback function, it also can be a
202 * simple string with the name of a function in this class,
203 * following elements are parameters to the function.
204 * Note that callback functions will receive this object as
207 public function addExtensionUpdate( array $update ) {
208 $this->extensionUpdates
[] = $update;
212 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
213 * is the most common usage of updaters in an extension)
217 * @param $tableName String Name of table to create
218 * @param $sqlPath String Full path to the schema file
220 public function addExtensionTable( $tableName, $sqlPath ) {
221 $this->extensionUpdates
[] = array( 'addTable', $tableName, $sqlPath, true );
227 * @param $tableName string
228 * @param $indexName string
229 * @param $sqlPath string
231 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
232 $this->extensionUpdates
[] = array( 'addIndex', $tableName, $indexName, $sqlPath, true );
239 * @param $tableName string
240 * @param $columnName string
241 * @param $sqlPath string
243 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
244 $this->extensionUpdates
[] = array( 'addField', $tableName, $columnName, $sqlPath, true );
251 * @param $tableName string
252 * @param $columnName string
253 * @param $sqlPath string
255 public function dropExtensionField( $tableName, $columnName, $sqlPath ) {
256 $this->extensionUpdates
[] = array( 'dropField', $tableName, $columnName, $sqlPath, true );
263 * @param $tableName string
264 * @param $sqlPath string
266 public function dropExtensionTable( $tableName, $sqlPath ) {
267 $this->extensionUpdates
[] = array( 'dropTable', $tableName, $sqlPath, true );
274 * @param $tableName string
277 public function tableExists( $tableName ) {
278 return ( $this->db
->tableExists( $tableName, __METHOD__
) );
282 * Add a maintenance script to be run after the database updates are complete.
284 * Script should subclass LoggedUpdateMaintenance
288 * @param $class string Name of a Maintenance subclass
290 public function addPostDatabaseUpdateMaintenance( $class ) {
291 $this->postDatabaseUpdateMaintenance
[] = $class;
295 * Get the list of extension-defined updates
299 protected function getExtensionUpdates() {
300 return $this->extensionUpdates
;
308 public function getPostDatabaseUpdateMaintenance() {
309 return $this->postDatabaseUpdateMaintenance
;
315 * Writes the schema updates desired to a file for the DB Admin to run.
317 private function writeSchemaUpdateFile( $schemaUpdate = array() ) {
318 $updates = $this->updatesSkipped
;
319 $this->updatesSkipped
= array();
321 foreach( $updates as $funcList ) {
322 $func = $funcList[0];
324 $origParams = $funcList[2];
325 $ret = call_user_func_array( $func, $arg );
327 $this->updatesSkipped
[] = $origParams;
334 * @param $what Array: what updates to perform
336 public function doUpdates( $what = array( 'core', 'extensions', 'stats' ) ) {
337 global $wgVersion, $wgLocalisationCacheConf;
339 $this->db
->begin( __METHOD__
);
340 $what = array_flip( $what );
341 $this->skipSchema
= isset( $what['noschema'] ) ||
$this->fileHandle
!== null;
342 if ( isset( $what['core'] ) ) {
343 $this->runUpdates( $this->getCoreUpdateList(), false );
345 if ( isset( $what['extensions'] ) ) {
346 $this->runUpdates( $this->getOldGlobalUpdates(), false );
347 $this->runUpdates( $this->getExtensionUpdates(), true );
350 if ( isset( $what['stats'] ) ) {
354 if ( isset( $what['purge'] ) ) {
357 if ( $wgLocalisationCacheConf['manualRecache'] ) {
358 $this->rebuildLocalisationCache();
362 $this->setAppliedUpdates( $wgVersion, $this->updates
);
364 if( $this->fileHandle
) {
365 $this->skipSchema
= false;
366 $this->writeSchemaUpdateFile( );
367 $this->setAppliedUpdates( "$wgVersion-schema", $this->updatesSkipped
);
370 $this->db
->commit( __METHOD__
);
374 * Helper function for doUpdates()
376 * @param $updates Array of updates to run
377 * @param $passSelf Boolean: whether to pass this object we calling external
380 private function runUpdates( array $updates, $passSelf ) {
381 $updatesDone = array();
382 $updatesSkipped = array();
383 foreach ( $updates as $params ) {
384 $origParams = $params;
385 $func = array_shift( $params );
386 if( !is_array( $func ) && method_exists( $this, $func ) ) {
387 $func = array( $this, $func );
388 } elseif ( $passSelf ) {
389 array_unshift( $params, $this );
391 $ret = call_user_func_array( $func, $params );
393 if( $ret !== false ) {
394 $updatesDone[] = $origParams;
396 $updatesSkipped[] = array( $func, $params, $origParams );
399 $this->updatesSkipped
= array_merge( $this->updatesSkipped
, $updatesSkipped );
400 $this->updates
= array_merge( $this->updates
, $updatesDone );
405 * @param $updates array
407 protected function setAppliedUpdates( $version, $updates = array() ) {
408 $this->db
->clearFlag( DBO_DDLMODE
);
409 if( !$this->canUseNewUpdatelog() ) {
412 $key = "updatelist-$version-" . time();
413 $this->db
->insert( 'updatelog',
414 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
416 $this->db
->setFlag( DBO_DDLMODE
);
420 * Helper function: check if the given key is present in the updatelog table.
421 * Obviously, only use this for updates that occur after the updatelog table was
423 * @param $key String Name of the key to check for
427 public function updateRowExists( $key ) {
428 $row = $this->db
->selectRow(
431 array( 'ul_key' => $key ),
438 * Helper function: Add a key to the updatelog table
439 * Obviously, only use this for updates that occur after the updatelog table was
441 * @param $key String Name of key to insert
442 * @param $val String [optional] value to insert along with the key
444 public function insertUpdateRow( $key, $val = null ) {
445 $this->db
->clearFlag( DBO_DDLMODE
);
446 $values = array( 'ul_key' => $key );
447 if( $val && $this->canUseNewUpdatelog() ) {
448 $values['ul_value'] = $val;
450 $this->db
->insert( 'updatelog', $values, __METHOD__
, 'IGNORE' );
451 $this->db
->setFlag( DBO_DDLMODE
);
455 * Updatelog was changed in 1.17 to have a ul_value column so we can record
456 * more information about what kind of updates we've done (that's what this
457 * class does). Pre-1.17 wikis won't have this column, and really old wikis
458 * might not even have updatelog at all
462 protected function canUseNewUpdatelog() {
463 return $this->db
->tableExists( 'updatelog', __METHOD__
) &&
464 $this->db
->fieldExists( 'updatelog', 'ul_value', __METHOD__
);
468 * Before 1.17, we used to handle updates via stuff like
469 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
470 * of this in 1.17 but we want to remain back-compatible for a while. So
471 * load up these old global-based things into our update list.
475 protected function getOldGlobalUpdates() {
476 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
477 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
479 $doUser = $this->shared ?
480 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
481 !$wgSharedDB ||
!in_array( 'user', $wgSharedTables );
485 foreach ( $wgExtNewTables as $tableRecord ) {
487 'addTable', $tableRecord[0], $tableRecord[1], true
491 foreach ( $wgExtNewFields as $fieldRecord ) {
492 if ( $fieldRecord[0] != 'user' ||
$doUser ) {
494 'addField', $fieldRecord[0], $fieldRecord[1],
495 $fieldRecord[2], true
500 foreach ( $wgExtNewIndexes as $fieldRecord ) {
502 'addIndex', $fieldRecord[0], $fieldRecord[1],
503 $fieldRecord[2], true
507 foreach ( $wgExtModifiedFields as $fieldRecord ) {
509 'modifyField', $fieldRecord[0], $fieldRecord[1],
510 $fieldRecord[2], true
518 * Get an array of updates to perform on the database. Should return a
519 * multi-dimensional array. The main key is the MediaWiki version (1.12,
520 * 1.13...) with the values being arrays of updates, identical to how
521 * updaters.inc did it (for now)
525 protected abstract function getCoreUpdateList();
528 * Append an SQL fragment to the open file handle.
530 * @param $filename String: File name to open
532 public function copyFile( $filename ) {
533 $this->db
->sourceFile( $filename, false, false, false,
534 array( $this, 'appendLine' )
539 * Append a line to the open filehandle. The line is assumed to
540 * be a complete SQL statement.
542 * This is used as a callback for for sourceLine().
544 * @param $line String text to append to the file
545 * @return Boolean false to skip actually executing the file
546 * @throws MWException
548 public function appendLine( $line ) {
549 $line = rtrim( $line ) . ";\n";
550 if( fwrite( $this->fileHandle
, $line ) === false ) {
551 throw new MWException( "trouble writing file" );
557 * Applies a SQL patch
558 * @param $path String Path to the patch file
559 * @param $isFullPath Boolean Whether to treat $path as a relative or not
560 * @param $msg String Description of the patch
561 * @return boolean false if patch is skipped.
563 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
564 if ( $msg === null ) {
565 $msg = "Applying $path patch";
567 if ( $this->skipSchema
) {
568 $this->output( "...skipping schema change ($msg).\n" );
572 $this->output( "$msg ..." );
574 if ( !$isFullPath ) {
575 $path = $this->db
->patchPath( $path );
577 if( $this->fileHandle
!== null ) {
578 $this->copyFile( $path );
580 $this->db
->sourceFile( $path );
582 $this->output( "done.\n" );
587 * Add a new table to the database
588 * @param $name String Name of the new table
589 * @param $patch String Path to the patch file
590 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
591 * @return Boolean false if this was skipped because schema changes are skipped
593 protected function addTable( $name, $patch, $fullpath = false ) {
594 if ( $this->db
->tableExists( $name, __METHOD__
) ) {
595 $this->output( "...$name table already exists.\n" );
597 return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
603 * Add a new field to an existing table
604 * @param $table String Name of the table to modify
605 * @param $field String Name of the new field
606 * @param $patch String Path to the patch file
607 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
608 * @return Boolean false if this was skipped because schema changes are skipped
610 protected function addField( $table, $field, $patch, $fullpath = false ) {
611 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
612 $this->output( "...$table table does not exist, skipping new field patch.\n" );
613 } elseif ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
614 $this->output( "...have $field field in $table table.\n" );
616 return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
622 * Add a new index to an existing table
623 * @param $table String Name of the table to modify
624 * @param $index String Name of the new index
625 * @param $patch String Path to the patch file
626 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
627 * @return Boolean false if this was skipped because schema changes are skipped
629 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
630 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
631 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
633 } else if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
634 $this->output( "...index $index already set on $table table.\n" );
636 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
642 * Drop a field from an existing table
644 * @param $table String Name of the table to modify
645 * @param $field String Name of the old field
646 * @param $patch String Path to the patch file
647 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
648 * @return Boolean false if this was skipped because schema changes are skipped
650 protected function dropField( $table, $field, $patch, $fullpath = false ) {
651 if ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
652 return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
654 $this->output( "...$table table does not contain $field field.\n" );
660 * Drop an index from an existing table
662 * @param $table String: Name of the table to modify
663 * @param $index String: Name of the old index
664 * @param $patch String: Path to the patch file
665 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
666 * @return Boolean false if this was skipped because schema changes are skipped
668 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
669 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
670 return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
672 $this->output( "...$index key doesn't exist.\n" );
678 * If the specified table exists, drop it, or execute the
679 * patch if one is provided.
683 * @param $table string
684 * @param $patch string|false
685 * @param $fullpath bool
686 * @return Boolean false if this was skipped because schema changes are skipped
688 public function dropTable( $table, $patch = false, $fullpath = false ) {
689 if ( $this->db
->tableExists( $table, __METHOD__
) ) {
690 $msg = "Dropping table $table";
692 if ( $patch === false ) {
693 $this->output( "$msg ..." );
694 $this->db
->dropTable( $table, __METHOD__
);
695 $this->output( "done.\n" );
698 return $this->applyPatch( $patch, $fullpath, $msg );
701 $this->output( "...$table doesn't exist.\n" );
707 * Modify an existing field
709 * @param $table String: name of the table to which the field belongs
710 * @param $field String: name of the field to modify
711 * @param $patch String: path to the patch file
712 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
713 * @return Boolean false if this was skipped because schema changes are skipped
715 public function modifyField( $table, $field, $patch, $fullpath = false ) {
716 $updateKey = "$table-$field-$patch";
717 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
718 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
719 } elseif ( !$this->db
->fieldExists( $table, $field, __METHOD__
) ) {
720 $this->output( "...$field field does not exist in $table table, skipping modify field patch.\n" );
721 } elseif( $this->updateRowExists( $updateKey ) ) {
722 $this->output( "...$field in table $table already modified by patch $patch.\n" );
724 return $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
725 $this->insertUpdateRow( $updateKey );
731 * Purge the objectcache table
733 public function purgeCache() {
734 global $wgLocalisationCacheConf;
735 # We can't guarantee that the user will be able to use TRUNCATE,
736 # but we know that DELETE is available to us
737 $this->output( "Purging caches..." );
738 $this->db
->delete( 'objectcache', '*', __METHOD__
);
739 if ( $wgLocalisationCacheConf['manualRecache'] ) {
740 $this->rebuildLocalisationCache();
742 $this->output( "done.\n" );
746 * Check the site_stats table is not properly populated.
748 protected function checkStats() {
749 $this->output( "...site_stats is populated..." );
750 $row = $this->db
->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__
);
751 if ( $row === false ) {
752 $this->output( "data is missing! rebuilding...\n" );
753 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
754 $this->output( "missing ss_total_pages, rebuilding...\n" );
756 $this->output( "done.\n" );
759 SiteStatsInit
::doAllAndCommit( $this->db
);
762 # Common updater functions
765 * Sets the number of active users in the site_stats table
767 protected function doActiveUsersInit() {
768 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', false, __METHOD__
);
769 if ( $activeUsers == -1 ) {
770 $activeUsers = $this->db
->selectField( 'recentchanges',
771 'COUNT( DISTINCT rc_user_text )',
772 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
774 $this->db
->update( 'site_stats',
775 array( 'ss_active_users' => intval( $activeUsers ) ),
776 array( 'ss_row_id' => 1 ), __METHOD__
, array( 'LIMIT' => 1 )
779 $this->output( "...ss_active_users user count set...\n" );
783 * Populates the log_user_text field in the logging table
785 protected function doLogUsertextPopulation() {
786 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
788 "Populating log_user_text field, printing progress markers. For large\n" .
789 "databases, you may want to hit Ctrl-C and do this manually with\n" .
790 "maintenance/populateLogUsertext.php.\n" );
792 $task = $this->maintenance
->runChild( 'PopulateLogUsertext' );
794 $this->output( "done.\n" );
799 * Migrate log params to new table and index for searching
801 protected function doLogSearchPopulation() {
802 if ( !$this->updateRowExists( 'populate log_search' ) ) {
804 "Populating log_search table, printing progress markers. For large\n" .
805 "databases, you may want to hit Ctrl-C and do this manually with\n" .
806 "maintenance/populateLogSearch.php.\n" );
808 $task = $this->maintenance
->runChild( 'PopulateLogSearch' );
810 $this->output( "done.\n" );
815 * Updates the timestamps in the transcache table
817 protected function doUpdateTranscacheField() {
818 if ( $this->updateRowExists( 'convert transcache field' ) ) {
819 $this->output( "...transcache tc_time already converted.\n" );
823 return $this->applyPatch( 'patch-tc-timestamp.sql', false,
824 "Converting tc_time from UNIX epoch to MediaWiki timestamp" );
828 * Update CategoryLinks collation
830 protected function doCollationUpdate() {
831 global $wgCategoryCollation;
832 if ( $this->db
->fieldExists( 'categorylinks', 'cl_collation', __METHOD__
) ) {
833 if ( $this->db
->selectField(
836 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
839 $this->output( "...collations up-to-date.\n" );
843 $this->output( "Updating category collations..." );
844 $task = $this->maintenance
->runChild( 'UpdateCollation' );
846 $this->output( "...done.\n" );
851 * Migrates user options from the user table blob to user_properties
853 protected function doMigrateUserOptions() {
854 if( $this->db
->tableExists( 'user_properties' ) ) {
855 $cl = $this->maintenance
->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
857 $this->output( "done.\n" );
862 * Rebuilds the localisation cache
864 protected function rebuildLocalisationCache() {
866 * @var $cl RebuildLocalisationCache
868 $cl = $this->maintenance
->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
869 $this->output( "Rebuilding localisation cache...\n" );
872 $this->output( "done.\n" );