* Oracle schema update to latest (tested with phpunit)
[lhc/web/wiklou.git] / includes / installer / DatabaseUpdater.php
1 <?php
2 /**
3 * DBMS-specific updater helper.
4 *
5 * @file
6 * @ingroup Deployment
7 */
8
9 require_once( dirname(__FILE__) . '/../../maintenance/Maintenance.php' );
10
11 /**
12 * Class for handling database updates. Roughly based off of updaters.inc, with
13 * a few improvements :)
14 *
15 * @ingroup Deployment
16 * @since 1.17
17 */
18 abstract class DatabaseUpdater {
19
20 /**
21 * Array of updates to perform on the database
22 *
23 * @var array
24 */
25 protected $updates = array();
26
27 /**
28 * List of extension-provided database updates
29 * @var array
30 */
31 protected $extensionUpdates = array();
32
33 /**
34 * Handle to the database subclass
35 *
36 * @var DatabaseBase
37 */
38 protected $db;
39
40 protected $shared = false;
41
42 protected $postDatabaseUpdateMaintenance = array(
43 'DeleteDefaultMessages',
44 'PopulateRevisionLength',
45 'PopulateRevisionSha1',
46 'PopulateImageSha1',
47 'FixExtLinksProtocolRelative',
48 );
49
50 /**
51 * Constructor
52 *
53 * @param $db DatabaseBase object to perform updates on
54 * @param $shared bool Whether to perform updates on shared tables
55 * @param $maintenance Maintenance Maintenance object which created us
56 */
57 protected function __construct( DatabaseBase &$db, $shared, Maintenance $maintenance = null ) {
58 $this->db = $db;
59 $this->db->setFlag( DBO_DDLMODE ); // For Oracle's handling of schema files
60 $this->shared = $shared;
61 if ( $maintenance ) {
62 $this->maintenance = $maintenance;
63 } else {
64 $this->maintenance = new FakeMaintenance;
65 }
66 $this->maintenance->setDB( $db );
67 $this->initOldGlobals();
68 $this->loadExtensions();
69 wfRunHooks( 'LoadExtensionSchemaUpdates', array( $this ) );
70 }
71
72 /**
73 * Initialize all of the old globals. One day this should all become
74 * something much nicer
75 */
76 private function initOldGlobals() {
77 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
78 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
79
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
88 }
89
90 /**
91 * Loads LocalSettings.php, if needed, and initialises everything needed for LoadExtensionSchemaUpdates hook
92 */
93 private function loadExtensions() {
94 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
95 return; // already loaded
96 }
97 $vars = Installer::getExistingLocalSettings();
98 if ( !$vars ) {
99 return; // no LocalSettings found
100 }
101 if ( !isset( $vars['wgHooks'] ) || !isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
102 return;
103 }
104 global $wgHooks, $wgAutoloadClasses;
105 $wgHooks['LoadExtensionSchemaUpdates'] = $vars['wgHooks']['LoadExtensionSchemaUpdates'];
106 $wgAutoloadClasses = $wgAutoloadClasses + $vars['wgAutoloadClasses'];
107 }
108
109 /**
110 * @throws MWException
111 * @param DatabaseBase $db
112 * @param bool $shared
113 * @param null $maintenance
114 * @return DatabaseUpdater
115 */
116 public static function newForDB( &$db, $shared = false, $maintenance = null ) {
117 $type = $db->getType();
118 if( in_array( $type, Installer::getDBTypes() ) ) {
119 $class = ucfirst( $type ) . 'Updater';
120 return new $class( $db, $shared, $maintenance );
121 } else {
122 throw new MWException( __METHOD__ . ' called for unsupported $wgDBtype' );
123 }
124 }
125
126 /**
127 * Get a database connection to run updates
128 *
129 * @return DatabaseBase
130 */
131 public function getDB() {
132 return $this->db;
133 }
134
135 /**
136 * Output some text. If we're running from web, escape the text first.
137 *
138 * @param $str String: Text to output
139 */
140 public function output( $str ) {
141 if ( $this->maintenance->isQuiet() ) {
142 return;
143 }
144 global $wgCommandLineMode;
145 if( !$wgCommandLineMode ) {
146 $str = htmlspecialchars( $str );
147 }
148 echo $str;
149 flush();
150 }
151
152 /**
153 * Add a new update coming from an extension. This should be called by
154 * extensions while executing the LoadExtensionSchemaUpdates hook.
155 *
156 * @since 1.17
157 *
158 * @param $update Array: the update to run. Format is the following:
159 * first item is the callback function, it also can be a
160 * simple string with the name of a function in this class,
161 * following elements are parameters to the function.
162 * Note that callback functions will receive this object as
163 * first parameter.
164 */
165 public function addExtensionUpdate( Array $update ) {
166 $this->extensionUpdates[] = $update;
167 }
168
169 /**
170 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
171 * is the most common usage of updaters in an extension)
172 *
173 * @since 1.18
174 *
175 * @param $tableName String Name of table to create
176 * @param $sqlPath String Full path to the schema file
177 */
178 public function addExtensionTable( $tableName, $sqlPath ) {
179 $this->extensionUpdates[] = array( 'addTable', $tableName, $sqlPath, true );
180 }
181
182 /**
183 * @since 1.19
184 *
185 * @param $tableName string
186 * @param $indexName string
187 * @param $sqlPath string
188 */
189 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
190 $this->extensionUpdates[] = array( 'addIndex', $tableName, $indexName, $sqlPath, true );
191 }
192
193 /**
194 *
195 * @since 1.19
196 *
197 * @param $tableName string
198 * @param $columnName string
199 * @param $sqlPath string
200 */
201 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
202 $this->extensionUpdates[] = array( 'addField', $tableName, $columnName, $sqlPath, true );
203 }
204
205 /**
206 * Add a maintenance script to be run after the database updates are complete.
207 *
208 * @since 1.19
209 *
210 * @param $class string Name of a Maintenance subclass
211 */
212 public function addPostDatabaseUpdateMaintenance( $class ) {
213 $this->postDatabaseUpdateMaintenance[] = $class;
214 }
215
216 /**
217 * Get the list of extension-defined updates
218 *
219 * @return Array
220 */
221 protected function getExtensionUpdates() {
222 return $this->extensionUpdates;
223 }
224
225 /**
226 * @since 1.17
227 *
228 * @return array
229 */
230 public function getPostDatabaseUpdateMaintenance() {
231 return $this->postDatabaseUpdateMaintenance;
232 }
233
234 /**
235 * Do all the updates
236 *
237 * @param $what Array: what updates to perform
238 */
239 public function doUpdates( $what = array( 'core', 'extensions', 'purge', 'stats' ) ) {
240 global $wgLocalisationCacheConf, $wgVersion;
241
242 $what = array_flip( $what );
243 if ( isset( $what['core'] ) ) {
244 $this->runUpdates( $this->getCoreUpdateList(), false );
245 }
246 if ( isset( $what['extensions'] ) ) {
247 $this->runUpdates( $this->getOldGlobalUpdates(), false );
248 $this->runUpdates( $this->getExtensionUpdates(), true );
249 }
250
251 $this->setAppliedUpdates( $wgVersion, $this->updates );
252
253 if ( isset( $what['stats'] ) ) {
254 $this->checkStats();
255 }
256
257 if ( isset( $what['purge'] ) ) {
258 $this->purgeCache();
259
260 if ( $wgLocalisationCacheConf['manualRecache'] ) {
261 $this->rebuildLocalisationCache();
262 }
263 }
264 }
265
266 /**
267 * Helper function for doUpdates()
268 *
269 * @param $updates Array of updates to run
270 * @param $passSelf Boolean: whether to pass this object we calling external
271 * functions
272 */
273 private function runUpdates( array $updates, $passSelf ) {
274 foreach ( $updates as $params ) {
275 $func = array_shift( $params );
276 if( !is_array( $func ) && method_exists( $this, $func ) ) {
277 $func = array( $this, $func );
278 } elseif ( $passSelf ) {
279 array_unshift( $params, $this );
280 }
281 call_user_func_array( $func, $params );
282 flush();
283 }
284 $this->updates = array_merge( $this->updates, $updates );
285 }
286
287 /**
288 * @param $version
289 * @param $updates array
290 */
291 protected function setAppliedUpdates( $version, $updates = array() ) {
292 $this->db->clearFlag( DBO_DDLMODE );
293 if( !$this->canUseNewUpdatelog() ) {
294 return;
295 }
296 $key = "updatelist-$version-" . time();
297 $this->db->insert( 'updatelog',
298 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
299 __METHOD__ );
300 $this->db->setFlag( DBO_DDLMODE );
301 }
302
303 /**
304 * Helper function: check if the given key is present in the updatelog table.
305 * Obviously, only use this for updates that occur after the updatelog table was
306 * created!
307 * @param $key String Name of the key to check for
308 *
309 * @return bool
310 */
311 public function updateRowExists( $key ) {
312 $row = $this->db->selectRow(
313 'updatelog',
314 '1',
315 array( 'ul_key' => $key ),
316 __METHOD__
317 );
318 return (bool)$row;
319 }
320
321 /**
322 * Helper function: Add a key to the updatelog table
323 * Obviously, only use this for updates that occur after the updatelog table was
324 * created!
325 * @param $key String Name of key to insert
326 * @param $val String [optional] value to insert along with the key
327 */
328 public function insertUpdateRow( $key, $val = null ) {
329 $this->db->clearFlag( DBO_DDLMODE );
330 $values = array( 'ul_key' => $key );
331 if( $val && $this->canUseNewUpdatelog() ) {
332 $values['ul_value'] = $val;
333 }
334 $this->db->insert( 'updatelog', $values, __METHOD__, 'IGNORE' );
335 $this->db->setFlag( DBO_DDLMODE );
336 }
337
338 /**
339 * Updatelog was changed in 1.17 to have a ul_value column so we can record
340 * more information about what kind of updates we've done (that's what this
341 * class does). Pre-1.17 wikis won't have this column, and really old wikis
342 * might not even have updatelog at all
343 *
344 * @return boolean
345 */
346 protected function canUseNewUpdatelog() {
347 return $this->db->tableExists( 'updatelog', __METHOD__ ) &&
348 $this->db->fieldExists( 'updatelog', 'ul_value', __METHOD__ );
349 }
350
351 /**
352 * Before 1.17, we used to handle updates via stuff like
353 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
354 * of this in 1.17 but we want to remain back-compatible for a while. So
355 * load up these old global-based things into our update list.
356 *
357 * @return array
358 */
359 protected function getOldGlobalUpdates() {
360 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
361 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
362
363 $doUser = $this->shared ?
364 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
365 !$wgSharedDB || !in_array( 'user', $wgSharedTables );
366
367 $updates = array();
368
369 foreach ( $wgExtNewTables as $tableRecord ) {
370 $updates[] = array(
371 'addTable', $tableRecord[0], $tableRecord[1], true
372 );
373 }
374
375 foreach ( $wgExtNewFields as $fieldRecord ) {
376 if ( $fieldRecord[0] != 'user' || $doUser ) {
377 $updates[] = array(
378 'addField', $fieldRecord[0], $fieldRecord[1],
379 $fieldRecord[2], true
380 );
381 }
382 }
383
384 foreach ( $wgExtNewIndexes as $fieldRecord ) {
385 $updates[] = array(
386 'addIndex', $fieldRecord[0], $fieldRecord[1],
387 $fieldRecord[2], true
388 );
389 }
390
391 foreach ( $wgExtModifiedFields as $fieldRecord ) {
392 $updates[] = array(
393 'modifyField', $fieldRecord[0], $fieldRecord[1],
394 $fieldRecord[2], true
395 );
396 }
397
398 return $updates;
399 }
400
401 /**
402 * Get an array of updates to perform on the database. Should return a
403 * multi-dimensional array. The main key is the MediaWiki version (1.12,
404 * 1.13...) with the values being arrays of updates, identical to how
405 * updaters.inc did it (for now)
406 *
407 * @return Array
408 */
409 protected abstract function getCoreUpdateList();
410
411 /**
412 * Applies a SQL patch
413 * @param $path String Path to the patch file
414 * @param $isFullPath Boolean Whether to treat $path as a relative or not
415 */
416 protected function applyPatch( $path, $isFullPath = false ) {
417 if ( $isFullPath ) {
418 $this->db->sourceFile( $path );
419 } else {
420 $this->db->sourceFile( $this->db->patchPath( $path ) );
421 }
422 }
423
424 /**
425 * Add a new table to the database
426 * @param $name String Name of the new table
427 * @param $patch String Path to the patch file
428 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
429 */
430 protected function addTable( $name, $patch, $fullpath = false ) {
431 if ( $this->db->tableExists( $name, __METHOD__ ) ) {
432 $this->output( "...$name table already exists.\n" );
433 } else {
434 $this->output( "Creating $name table..." );
435 $this->applyPatch( $patch, $fullpath );
436 $this->output( "done.\n" );
437 }
438 }
439
440 /**
441 * Add a new field to an existing table
442 * @param $table String Name of the table to modify
443 * @param $field String Name of the new field
444 * @param $patch String Path to the patch file
445 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
446 */
447 protected function addField( $table, $field, $patch, $fullpath = false ) {
448 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
449 $this->output( "...$table table does not exist, skipping new field patch.\n" );
450 } elseif ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
451 $this->output( "...have $field field in $table table.\n" );
452 } else {
453 $this->output( "Adding $field field to table $table..." );
454 $this->applyPatch( $patch, $fullpath );
455 $this->output( "done.\n" );
456 }
457 }
458
459 /**
460 * Add a new index to an existing table
461 * @param $table String Name of the table to modify
462 * @param $index String Name of the new index
463 * @param $patch String Path to the patch file
464 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
465 */
466 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
467 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
468 $this->output( "...index $index already set on $table table.\n" );
469 } else {
470 $this->output( "Adding index $index to table $table... " );
471 $this->applyPatch( $patch, $fullpath );
472 $this->output( "done.\n" );
473 }
474 }
475
476 /**
477 * Drop a field from an existing table
478 *
479 * @param $table String Name of the table to modify
480 * @param $field String Name of the old field
481 * @param $patch String Path to the patch file
482 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
483 */
484 protected function dropField( $table, $field, $patch, $fullpath = false ) {
485 if ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
486 $this->output( "Table $table contains $field field. Dropping... " );
487 $this->applyPatch( $patch, $fullpath );
488 $this->output( "done.\n" );
489 } else {
490 $this->output( "...$table table does not contain $field field.\n" );
491 }
492 }
493
494 /**
495 * Drop an index from an existing table
496 *
497 * @param $table String: Name of the table to modify
498 * @param $index String: Name of the old index
499 * @param $patch String: Path to the patch file
500 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
501 */
502 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
503 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
504 $this->output( "Dropping $index index from table $table... " );
505 $this->applyPatch( $patch, $fullpath );
506 $this->output( "done.\n" );
507 } else {
508 $this->output( "...$index key doesn't exist.\n" );
509 }
510 }
511
512 /**
513 * @param $table string
514 * @param $patch string
515 * @param $fullpath bool
516 */
517 protected function dropTable( $table, $patch, $fullpath = false ) {
518 if ( $this->db->tableExists( $table, __METHOD__ ) ) {
519 $this->output( "Dropping table $table... " );
520 $this->applyPatch( $patch, $fullpath );
521 $this->output( "done.\n" );
522 } else {
523 $this->output( "...$table doesn't exist.\n" );
524 }
525 }
526
527 /**
528 * Modify an existing field
529 *
530 * @param $table String: name of the table to which the field belongs
531 * @param $field String: name of the field to modify
532 * @param $patch String: path to the patch file
533 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
534 */
535 public function modifyField( $table, $field, $patch, $fullpath = false ) {
536 $updateKey = "$table-$field-$patch";
537 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
538 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
539 } elseif ( !$this->db->fieldExists( $table, $field, __METHOD__ ) ) {
540 $this->output( "...$field field does not exist in $table table, skipping modify field patch.\n" );
541 } elseif( $this->updateRowExists( $updateKey ) ) {
542 $this->output( "...$field in table $table already modified by patch $patch.\n" );
543 } else {
544 $this->output( "Modifying $field field of table $table..." );
545 $this->applyPatch( $patch, $fullpath );
546 $this->insertUpdateRow( $updateKey );
547 $this->output( "done.\n" );
548 }
549 }
550
551 /**
552 * Purge the objectcache table
553 */
554 protected function purgeCache() {
555 # We can't guarantee that the user will be able to use TRUNCATE,
556 # but we know that DELETE is available to us
557 $this->output( "Purging caches..." );
558 $this->db->delete( 'objectcache', '*', __METHOD__ );
559 $this->output( "done.\n" );
560 }
561
562 /**
563 * Check the site_stats table is not properly populated.
564 */
565 protected function checkStats() {
566 $this->output( "...site_stats is populated..." );
567 $row = $this->db->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
568 if ( $row === false ) {
569 $this->output( "data is missing! rebuilding...\n" );
570 } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
571 $this->output( "missing ss_total_pages, rebuilding...\n" );
572 } else {
573 $this->output( "done.\n" );
574 return;
575 }
576 SiteStatsInit::doAllAndCommit( $this->db );
577 }
578
579 # Common updater functions
580
581 /**
582 * Sets the number of active users in the site_stats table
583 */
584 protected function doActiveUsersInit() {
585 $activeUsers = $this->db->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
586 if ( $activeUsers == -1 ) {
587 $activeUsers = $this->db->selectField( 'recentchanges',
588 'COUNT( DISTINCT rc_user_text )',
589 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
590 );
591 $this->db->update( 'site_stats',
592 array( 'ss_active_users' => intval( $activeUsers ) ),
593 array( 'ss_row_id' => 1 ), __METHOD__, array( 'LIMIT' => 1 )
594 );
595 }
596 $this->output( "...ss_active_users user count set...\n" );
597 }
598
599 /**
600 * Populates the log_user_text field in the logging table
601 */
602 protected function doLogUsertextPopulation() {
603 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
604 $this->output(
605 "Populating log_user_text field, printing progress markers. For large\n" .
606 "databases, you may want to hit Ctrl-C and do this manually with\n" .
607 "maintenance/populateLogUsertext.php.\n" );
608
609 $task = $this->maintenance->runChild( 'PopulateLogUsertext' );
610 $task->execute();
611 $this->output( "done.\n" );
612 }
613 }
614
615 /**
616 * Migrate log params to new table and index for searching
617 */
618 protected function doLogSearchPopulation() {
619 if ( !$this->updateRowExists( 'populate log_search' ) ) {
620 $this->output(
621 "Populating log_search table, printing progress markers. For large\n" .
622 "databases, you may want to hit Ctrl-C and do this manually with\n" .
623 "maintenance/populateLogSearch.php.\n" );
624
625 $task = $this->maintenance->runChild( 'PopulateLogSearch' );
626 $task->execute();
627 $this->output( "done.\n" );
628 }
629 }
630
631 /**
632 * Updates the timestamps in the transcache table
633 */
634 protected function doUpdateTranscacheField() {
635 if ( $this->updateRowExists( 'convert transcache field' ) ) {
636 $this->output( "...transcache tc_time already converted.\n" );
637 return;
638 }
639
640 $this->output( "Converting tc_time from UNIX epoch to MediaWiki timestamp... " );
641 $this->applyPatch( 'patch-tc-timestamp.sql' );
642 $this->output( "done.\n" );
643 }
644
645 /**
646 * Update CategoryLinks collation
647 */
648 protected function doCollationUpdate() {
649 global $wgCategoryCollation;
650 if ( $this->db->selectField(
651 'categorylinks',
652 'COUNT(*)',
653 'cl_collation != ' . $this->db->addQuotes( $wgCategoryCollation ),
654 __METHOD__
655 ) == 0 ) {
656 $this->output( "...collations up-to-date.\n" );
657 return;
658 }
659
660 $this->output( "Updating category collations..." );
661 $task = $this->maintenance->runChild( 'UpdateCollation' );
662 $task->execute();
663 $this->output( "...done.\n" );
664 }
665
666 /**
667 * Migrates user options from the user table blob to user_properties
668 */
669 protected function doMigrateUserOptions() {
670 $cl = $this->maintenance->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
671 $cl->execute();
672 $this->output( "done.\n" );
673 }
674
675 /**
676 * Rebuilds the localisation cache
677 */
678 protected function rebuildLocalisationCache() {
679 /**
680 * @var $cl RebuildLocalisationCache
681 */
682 $cl = $this->maintenance->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
683 $this->output( "Rebuilding localisation cache...\n" );
684 $cl->setForce();
685 $cl->execute();
686 $this->output( "done.\n" );
687 }
688 }