Fix PostgreSQL updater to produce 1.19 schema
[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 *
207 * @since 1.20
208 *
209 * @param $tableName string
210 * @param $columnName string
211 * @param $sqlPath string
212 */
213 public function dropExtensionField( $tableName, $columnName, $sqlPath ) {
214 $this->extensionUpdates[] = array( 'dropField', $tableName, $columnName, $sqlPath, true );
215 }
216
217 /**
218 *
219 * @since 1.20
220 *
221 * @param $tableName string
222 * @param $sqlPath string
223 */
224 public function dropExtensionTable( $tableName, $sqlPath ) {
225 $this->extensionUpdates[] = array( 'dropTable', $tableName, $sqlPath, true );
226 }
227
228 /**
229 *
230 * @since 1.20
231 *
232 * @param $tableName string
233 */
234 public function tableExists( $tableName ) {
235 return ( $this->db->tableExists( $tableName, __METHOD__ ) );
236 }
237
238 /**
239 * Add a maintenance script to be run after the database updates are complete.
240 *
241 * @since 1.19
242 *
243 * @param $class string Name of a Maintenance subclass
244 */
245 public function addPostDatabaseUpdateMaintenance( $class ) {
246 $this->postDatabaseUpdateMaintenance[] = $class;
247 }
248
249 /**
250 * Get the list of extension-defined updates
251 *
252 * @return Array
253 */
254 protected function getExtensionUpdates() {
255 return $this->extensionUpdates;
256 }
257
258 /**
259 * @since 1.17
260 *
261 * @return array
262 */
263 public function getPostDatabaseUpdateMaintenance() {
264 return $this->postDatabaseUpdateMaintenance;
265 }
266
267 /**
268 * Do all the updates
269 *
270 * @param $what Array: what updates to perform
271 */
272 public function doUpdates( $what = array( 'core', 'extensions', 'purge', 'stats' ) ) {
273 global $wgLocalisationCacheConf, $wgVersion;
274
275 $this->db->begin( __METHOD__ );
276 $what = array_flip( $what );
277 if ( isset( $what['core'] ) ) {
278 $this->runUpdates( $this->getCoreUpdateList(), false );
279 }
280 if ( isset( $what['extensions'] ) ) {
281 $this->runUpdates( $this->getOldGlobalUpdates(), false );
282 $this->runUpdates( $this->getExtensionUpdates(), true );
283 }
284
285 $this->setAppliedUpdates( $wgVersion, $this->updates );
286
287 if ( isset( $what['stats'] ) ) {
288 $this->checkStats();
289 }
290
291 if ( isset( $what['purge'] ) ) {
292 $this->purgeCache();
293
294 if ( $wgLocalisationCacheConf['manualRecache'] ) {
295 $this->rebuildLocalisationCache();
296 }
297 }
298 $this->db->commit( __METHOD__ );
299 }
300
301 /**
302 * Helper function for doUpdates()
303 *
304 * @param $updates Array of updates to run
305 * @param $passSelf Boolean: whether to pass this object we calling external
306 * functions
307 */
308 private function runUpdates( array $updates, $passSelf ) {
309 foreach ( $updates as $params ) {
310 $func = array_shift( $params );
311 if( !is_array( $func ) && method_exists( $this, $func ) ) {
312 $func = array( $this, $func );
313 } elseif ( $passSelf ) {
314 array_unshift( $params, $this );
315 }
316 call_user_func_array( $func, $params );
317 flush();
318 }
319 $this->updates = array_merge( $this->updates, $updates );
320 }
321
322 /**
323 * @param $version
324 * @param $updates array
325 */
326 protected function setAppliedUpdates( $version, $updates = array() ) {
327 $this->db->clearFlag( DBO_DDLMODE );
328 if( !$this->canUseNewUpdatelog() ) {
329 return;
330 }
331 $key = "updatelist-$version-" . time();
332 $this->db->insert( 'updatelog',
333 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
334 __METHOD__ );
335 $this->db->setFlag( DBO_DDLMODE );
336 }
337
338 /**
339 * Helper function: check if the given key is present in the updatelog table.
340 * Obviously, only use this for updates that occur after the updatelog table was
341 * created!
342 * @param $key String Name of the key to check for
343 *
344 * @return bool
345 */
346 public function updateRowExists( $key ) {
347 $row = $this->db->selectRow(
348 'updatelog',
349 '1',
350 array( 'ul_key' => $key ),
351 __METHOD__
352 );
353 return (bool)$row;
354 }
355
356 /**
357 * Helper function: Add a key to the updatelog table
358 * Obviously, only use this for updates that occur after the updatelog table was
359 * created!
360 * @param $key String Name of key to insert
361 * @param $val String [optional] value to insert along with the key
362 */
363 public function insertUpdateRow( $key, $val = null ) {
364 $this->db->clearFlag( DBO_DDLMODE );
365 $values = array( 'ul_key' => $key );
366 if( $val && $this->canUseNewUpdatelog() ) {
367 $values['ul_value'] = $val;
368 }
369 $this->db->insert( 'updatelog', $values, __METHOD__, 'IGNORE' );
370 $this->db->setFlag( DBO_DDLMODE );
371 }
372
373 /**
374 * Updatelog was changed in 1.17 to have a ul_value column so we can record
375 * more information about what kind of updates we've done (that's what this
376 * class does). Pre-1.17 wikis won't have this column, and really old wikis
377 * might not even have updatelog at all
378 *
379 * @return boolean
380 */
381 protected function canUseNewUpdatelog() {
382 return $this->db->tableExists( 'updatelog', __METHOD__ ) &&
383 $this->db->fieldExists( 'updatelog', 'ul_value', __METHOD__ );
384 }
385
386 /**
387 * Before 1.17, we used to handle updates via stuff like
388 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
389 * of this in 1.17 but we want to remain back-compatible for a while. So
390 * load up these old global-based things into our update list.
391 *
392 * @return array
393 */
394 protected function getOldGlobalUpdates() {
395 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
396 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
397
398 $doUser = $this->shared ?
399 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
400 !$wgSharedDB || !in_array( 'user', $wgSharedTables );
401
402 $updates = array();
403
404 foreach ( $wgExtNewTables as $tableRecord ) {
405 $updates[] = array(
406 'addTable', $tableRecord[0], $tableRecord[1], true
407 );
408 }
409
410 foreach ( $wgExtNewFields as $fieldRecord ) {
411 if ( $fieldRecord[0] != 'user' || $doUser ) {
412 $updates[] = array(
413 'addField', $fieldRecord[0], $fieldRecord[1],
414 $fieldRecord[2], true
415 );
416 }
417 }
418
419 foreach ( $wgExtNewIndexes as $fieldRecord ) {
420 $updates[] = array(
421 'addIndex', $fieldRecord[0], $fieldRecord[1],
422 $fieldRecord[2], true
423 );
424 }
425
426 foreach ( $wgExtModifiedFields as $fieldRecord ) {
427 $updates[] = array(
428 'modifyField', $fieldRecord[0], $fieldRecord[1],
429 $fieldRecord[2], true
430 );
431 }
432
433 return $updates;
434 }
435
436 /**
437 * Get an array of updates to perform on the database. Should return a
438 * multi-dimensional array. The main key is the MediaWiki version (1.12,
439 * 1.13...) with the values being arrays of updates, identical to how
440 * updaters.inc did it (for now)
441 *
442 * @return Array
443 */
444 protected abstract function getCoreUpdateList();
445
446 /**
447 * Applies a SQL patch
448 * @param $path String Path to the patch file
449 * @param $isFullPath Boolean Whether to treat $path as a relative or not
450 */
451 protected function applyPatch( $path, $isFullPath = false ) {
452 if ( $isFullPath ) {
453 $this->db->sourceFile( $path );
454 } else {
455 $this->db->sourceFile( $this->db->patchPath( $path ) );
456 }
457 }
458
459 /**
460 * Add a new table to the database
461 * @param $name String Name of the new table
462 * @param $patch String Path to the patch file
463 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
464 */
465 protected function addTable( $name, $patch, $fullpath = false ) {
466 if ( $this->db->tableExists( $name, __METHOD__ ) ) {
467 $this->output( "...$name table already exists.\n" );
468 } else {
469 $this->output( "Creating $name table..." );
470 $this->applyPatch( $patch, $fullpath );
471 $this->output( "done.\n" );
472 }
473 }
474
475 /**
476 * Add a new field to an existing table
477 * @param $table String Name of the table to modify
478 * @param $field String Name of the new field
479 * @param $patch String Path to the patch file
480 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
481 */
482 protected function addField( $table, $field, $patch, $fullpath = false ) {
483 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
484 $this->output( "...$table table does not exist, skipping new field patch.\n" );
485 } elseif ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
486 $this->output( "...have $field field in $table table.\n" );
487 } else {
488 $this->output( "Adding $field field to table $table..." );
489 $this->applyPatch( $patch, $fullpath );
490 $this->output( "done.\n" );
491 }
492 }
493
494 /**
495 * Add a new index to an existing table
496 * @param $table String Name of the table to modify
497 * @param $index String Name of the new index
498 * @param $patch String Path to the patch file
499 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
500 */
501 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
502 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
503 $this->output( "...index $index already set on $table table.\n" );
504 } else {
505 $this->output( "Adding index $index to table $table... " );
506 $this->applyPatch( $patch, $fullpath );
507 $this->output( "done.\n" );
508 }
509 }
510
511 /**
512 * Drop a field from an existing table
513 *
514 * @param $table String Name of the table to modify
515 * @param $field String Name of the old field
516 * @param $patch String Path to the patch file
517 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
518 */
519 protected function dropField( $table, $field, $patch, $fullpath = false ) {
520 if ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
521 $this->output( "Table $table contains $field field. Dropping... " );
522 $this->applyPatch( $patch, $fullpath );
523 $this->output( "done.\n" );
524 } else {
525 $this->output( "...$table table does not contain $field field.\n" );
526 }
527 }
528
529 /**
530 * Drop an index from an existing table
531 *
532 * @param $table String: Name of the table to modify
533 * @param $index String: Name of the old index
534 * @param $patch String: Path to the patch file
535 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
536 */
537 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
538 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
539 $this->output( "Dropping $index index from table $table... " );
540 $this->applyPatch( $patch, $fullpath );
541 $this->output( "done.\n" );
542 } else {
543 $this->output( "...$index key doesn't exist.\n" );
544 }
545 }
546
547 /**
548 * @param $table string
549 * @param $patch string
550 * @param $fullpath bool
551 */
552 protected function dropTable( $table, $patch, $fullpath = false ) {
553 if ( $this->db->tableExists( $table, __METHOD__ ) ) {
554 $this->output( "Dropping table $table... " );
555 $this->applyPatch( $patch, $fullpath );
556 $this->output( "done.\n" );
557 } else {
558 $this->output( "...$table doesn't exist.\n" );
559 }
560 }
561
562 /**
563 * Modify an existing field
564 *
565 * @param $table String: name of the table to which the field belongs
566 * @param $field String: name of the field to modify
567 * @param $patch String: path to the patch file
568 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
569 */
570 public function modifyField( $table, $field, $patch, $fullpath = false ) {
571 $updateKey = "$table-$field-$patch";
572 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
573 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
574 } elseif ( !$this->db->fieldExists( $table, $field, __METHOD__ ) ) {
575 $this->output( "...$field field does not exist in $table table, skipping modify field patch.\n" );
576 } elseif( $this->updateRowExists( $updateKey ) ) {
577 $this->output( "...$field in table $table already modified by patch $patch.\n" );
578 } else {
579 $this->output( "Modifying $field field of table $table..." );
580 $this->applyPatch( $patch, $fullpath );
581 $this->insertUpdateRow( $updateKey );
582 $this->output( "done.\n" );
583 }
584 }
585
586 /**
587 * Purge the objectcache table
588 */
589 protected function purgeCache() {
590 # We can't guarantee that the user will be able to use TRUNCATE,
591 # but we know that DELETE is available to us
592 $this->output( "Purging caches..." );
593 $this->db->delete( 'objectcache', '*', __METHOD__ );
594 $this->output( "done.\n" );
595 }
596
597 /**
598 * Check the site_stats table is not properly populated.
599 */
600 protected function checkStats() {
601 $this->output( "...site_stats is populated..." );
602 $row = $this->db->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
603 if ( $row === false ) {
604 $this->output( "data is missing! rebuilding...\n" );
605 } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
606 $this->output( "missing ss_total_pages, rebuilding...\n" );
607 } else {
608 $this->output( "done.\n" );
609 return;
610 }
611 SiteStatsInit::doAllAndCommit( $this->db );
612 }
613
614 # Common updater functions
615
616 /**
617 * Sets the number of active users in the site_stats table
618 */
619 protected function doActiveUsersInit() {
620 $activeUsers = $this->db->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
621 if ( $activeUsers == -1 ) {
622 $activeUsers = $this->db->selectField( 'recentchanges',
623 'COUNT( DISTINCT rc_user_text )',
624 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
625 );
626 $this->db->update( 'site_stats',
627 array( 'ss_active_users' => intval( $activeUsers ) ),
628 array( 'ss_row_id' => 1 ), __METHOD__, array( 'LIMIT' => 1 )
629 );
630 }
631 $this->output( "...ss_active_users user count set...\n" );
632 }
633
634 /**
635 * Populates the log_user_text field in the logging table
636 */
637 protected function doLogUsertextPopulation() {
638 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
639 $this->output(
640 "Populating log_user_text field, printing progress markers. For large\n" .
641 "databases, you may want to hit Ctrl-C and do this manually with\n" .
642 "maintenance/populateLogUsertext.php.\n" );
643
644 $task = $this->maintenance->runChild( 'PopulateLogUsertext' );
645 $task->execute();
646 $this->output( "done.\n" );
647 }
648 }
649
650 /**
651 * Migrate log params to new table and index for searching
652 */
653 protected function doLogSearchPopulation() {
654 if ( !$this->updateRowExists( 'populate log_search' ) ) {
655 $this->output(
656 "Populating log_search table, printing progress markers. For large\n" .
657 "databases, you may want to hit Ctrl-C and do this manually with\n" .
658 "maintenance/populateLogSearch.php.\n" );
659
660 $task = $this->maintenance->runChild( 'PopulateLogSearch' );
661 $task->execute();
662 $this->output( "done.\n" );
663 }
664 }
665
666 /**
667 * Updates the timestamps in the transcache table
668 */
669 protected function doUpdateTranscacheField() {
670 if ( $this->updateRowExists( 'convert transcache field' ) ) {
671 $this->output( "...transcache tc_time already converted.\n" );
672 return;
673 }
674
675 $this->output( "Converting tc_time from UNIX epoch to MediaWiki timestamp... " );
676 $this->applyPatch( 'patch-tc-timestamp.sql' );
677 $this->output( "done.\n" );
678 }
679
680 /**
681 * Update CategoryLinks collation
682 */
683 protected function doCollationUpdate() {
684 global $wgCategoryCollation;
685 if ( $this->db->selectField(
686 'categorylinks',
687 'COUNT(*)',
688 'cl_collation != ' . $this->db->addQuotes( $wgCategoryCollation ),
689 __METHOD__
690 ) == 0 ) {
691 $this->output( "...collations up-to-date.\n" );
692 return;
693 }
694
695 $this->output( "Updating category collations..." );
696 $task = $this->maintenance->runChild( 'UpdateCollation' );
697 $task->execute();
698 $this->output( "...done.\n" );
699 }
700
701 /**
702 * Migrates user options from the user table blob to user_properties
703 */
704 protected function doMigrateUserOptions() {
705 $cl = $this->maintenance->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
706 $cl->execute();
707 $this->output( "done.\n" );
708 }
709
710 /**
711 * Rebuilds the localisation cache
712 */
713 protected function rebuildLocalisationCache() {
714 /**
715 * @var $cl RebuildLocalisationCache
716 */
717 $cl = $this->maintenance->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
718 $this->output( "Rebuilding localisation cache...\n" );
719 $cl->setForce();
720 $cl->execute();
721 $this->output( "done.\n" );
722 }
723 }