Merge "Added DatabaseBase::startAtomic and endAtomic"
[lhc/web/wiklou.git] / includes / installer / DatabaseUpdater.php
1 <?php
2 /**
3 * DBMS-specific updater helper.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Deployment
22 */
23
24 require_once __DIR__ . '/../../maintenance/Maintenance.php';
25
26 /**
27 * Class for handling database updates. Roughly based off of updaters.inc, with
28 * a few improvements :)
29 *
30 * @ingroup Deployment
31 * @since 1.17
32 */
33 abstract class DatabaseUpdater {
34
35 /**
36 * Array of updates to perform on the database
37 *
38 * @var array
39 */
40 protected $updates = array();
41
42 /**
43 * Array of updates that were skipped
44 *
45 * @var array
46 */
47 protected $updatesSkipped = array();
48
49 /**
50 * List of extension-provided database updates
51 * @var array
52 */
53 protected $extensionUpdates = array();
54
55 /**
56 * Handle to the database subclass
57 *
58 * @var DatabaseBase
59 */
60 protected $db;
61
62 protected $shared = false;
63
64 /**
65 * Scripts to run after database update
66 * Should be a subclass of LoggedUpdateMaintenance
67 */
68 protected $postDatabaseUpdateMaintenance = array(
69 'DeleteDefaultMessages',
70 'PopulateRevisionLength',
71 'PopulateRevisionSha1',
72 'PopulateImageSha1',
73 'FixExtLinksProtocolRelative',
74 'PopulateFilearchiveSha1',
75 );
76
77 /**
78 * File handle for SQL output.
79 *
80 * @var Filehandle
81 */
82 protected $fileHandle = null;
83
84 /**
85 * Flag specifying whether or not to skip schema (e.g. SQL-only) updates.
86 *
87 * @var bool
88 */
89 protected $skipSchema = false;
90
91 /**
92 * Hold the value of $wgContentHandlerUseDB during the upgrade.
93 */
94 protected $holdContentHandlerUseDB = true;
95
96 /**
97 * Constructor
98 *
99 * @param $db DatabaseBase object to perform updates on
100 * @param bool $shared Whether to perform updates on shared tables
101 * @param $maintenance Maintenance Maintenance object which created us
102 */
103 protected function __construct( DatabaseBase &$db, $shared, Maintenance $maintenance = null ) {
104 $this->db = $db;
105 $this->db->setFlag( DBO_DDLMODE ); // For Oracle's handling of schema files
106 $this->shared = $shared;
107 if ( $maintenance ) {
108 $this->maintenance = $maintenance;
109 $this->fileHandle = $maintenance->fileHandle;
110 } else {
111 $this->maintenance = new FakeMaintenance;
112 }
113 $this->maintenance->setDB( $db );
114 $this->initOldGlobals();
115 $this->loadExtensions();
116 wfRunHooks( 'LoadExtensionSchemaUpdates', array( $this ) );
117 }
118
119 /**
120 * Initialize all of the old globals. One day this should all become
121 * something much nicer
122 */
123 private function initOldGlobals() {
124 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
125 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
126
127 # For extensions only, should be populated via hooks
128 # $wgDBtype should be checked to specifiy the proper file
129 $wgExtNewTables = array(); // table, dir
130 $wgExtNewFields = array(); // table, column, dir
131 $wgExtPGNewFields = array(); // table, column, column attributes; for PostgreSQL
132 $wgExtPGAlteredFields = array(); // table, column, new type, conversion method; for PostgreSQL
133 $wgExtNewIndexes = array(); // table, index, dir
134 $wgExtModifiedFields = array(); // table, index, dir
135 }
136
137 /**
138 * Loads LocalSettings.php, if needed, and initialises everything needed for
139 * LoadExtensionSchemaUpdates hook.
140 */
141 private function loadExtensions() {
142 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
143 return; // already loaded
144 }
145 $vars = Installer::getExistingLocalSettings();
146 if ( !$vars ) {
147 return; // no LocalSettings found
148 }
149 if ( !isset( $vars['wgHooks'] ) || !isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
150 return;
151 }
152 global $wgHooks, $wgAutoloadClasses;
153 $wgHooks['LoadExtensionSchemaUpdates'] = $vars['wgHooks']['LoadExtensionSchemaUpdates'];
154 $wgAutoloadClasses = $wgAutoloadClasses + $vars['wgAutoloadClasses'];
155 }
156
157 /**
158 * @throws MWException
159 * @param DatabaseBase $db
160 * @param bool $shared
161 * @param null $maintenance
162 * @return DatabaseUpdater
163 */
164 public static function newForDB( &$db, $shared = false, $maintenance = null ) {
165 $type = $db->getType();
166 if ( in_array( $type, Installer::getDBTypes() ) ) {
167 $class = ucfirst( $type ) . 'Updater';
168
169 return new $class( $db, $shared, $maintenance );
170 } else {
171 throw new MWException( __METHOD__ . ' called for unsupported $wgDBtype' );
172 }
173 }
174
175 /**
176 * Get a database connection to run updates
177 *
178 * @return DatabaseBase
179 */
180 public function getDB() {
181 return $this->db;
182 }
183
184 /**
185 * Output some text. If we're running from web, escape the text first.
186 *
187 * @param string $str Text to output
188 */
189 public function output( $str ) {
190 if ( $this->maintenance->isQuiet() ) {
191 return;
192 }
193 global $wgCommandLineMode;
194 if ( !$wgCommandLineMode ) {
195 $str = htmlspecialchars( $str );
196 }
197 echo $str;
198 flush();
199 }
200
201 /**
202 * Add a new update coming from an extension. This should be called by
203 * extensions while executing the LoadExtensionSchemaUpdates hook.
204 *
205 * @since 1.17
206 *
207 * @param array $update the update to run. Format is the following:
208 * first item is the callback function, it also can be a
209 * simple string with the name of a function in this class,
210 * following elements are parameters to the function.
211 * Note that callback functions will receive this object as
212 * first parameter.
213 */
214 public function addExtensionUpdate( array $update ) {
215 $this->extensionUpdates[] = $update;
216 }
217
218 /**
219 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
220 * is the most common usage of updaters in an extension)
221 *
222 * @since 1.18
223 *
224 * @param string $tableName Name of table to create
225 * @param string $sqlPath Full path to the schema file
226 */
227 public function addExtensionTable( $tableName, $sqlPath ) {
228 $this->extensionUpdates[] = array( 'addTable', $tableName, $sqlPath, true );
229 }
230
231 /**
232 * @since 1.19
233 *
234 * @param $tableName string
235 * @param $indexName string
236 * @param $sqlPath string
237 */
238 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
239 $this->extensionUpdates[] = array( 'addIndex', $tableName, $indexName, $sqlPath, true );
240 }
241
242 /**
243 *
244 * @since 1.19
245 *
246 * @param $tableName string
247 * @param $columnName string
248 * @param $sqlPath string
249 */
250 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
251 $this->extensionUpdates[] = array( 'addField', $tableName, $columnName, $sqlPath, true );
252 }
253
254 /**
255 *
256 * @since 1.20
257 *
258 * @param $tableName string
259 * @param $columnName string
260 * @param $sqlPath string
261 */
262 public function dropExtensionField( $tableName, $columnName, $sqlPath ) {
263 $this->extensionUpdates[] = array( 'dropField', $tableName, $columnName, $sqlPath, true );
264 }
265
266 /**
267 * Drop an index from an extension table
268 *
269 * @since 1.21
270 *
271 * @param string $tableName The table name
272 * @param string $indexName The index name
273 * @param string $sqlPath The path to the SQL change path
274 */
275 public function dropExtensionIndex( $tableName, $indexName, $sqlPath ) {
276 $this->extensionUpdates[] = array( 'dropIndex', $tableName, $indexName, $sqlPath, true );
277 }
278
279 /**
280 *
281 * @since 1.20
282 *
283 * @param $tableName string
284 * @param $sqlPath string
285 */
286 public function dropExtensionTable( $tableName, $sqlPath ) {
287 $this->extensionUpdates[] = array( 'dropTable', $tableName, $sqlPath, true );
288 }
289
290 /**
291 * Rename an index on an extension table
292 *
293 * @since 1.21
294 *
295 * @param string $tableName The table name
296 * @param string $oldIndexName The old index name
297 * @param string $newIndexName The new index name
298 * @param $skipBothIndexExistWarning Boolean: Whether to warn if both the old
299 * and the new indexes exist. [facultative; by default, false]
300 * @param string $sqlPath The path to the SQL change path
301 */
302 public function renameExtensionIndex( $tableName, $oldIndexName, $newIndexName,
303 $sqlPath, $skipBothIndexExistWarning = false
304 ) {
305 $this->extensionUpdates[] = array(
306 'renameIndex',
307 $tableName,
308 $oldIndexName,
309 $newIndexName,
310 $skipBothIndexExistWarning,
311 $sqlPath,
312 true
313 );
314 }
315
316 /**
317 * @since 1.21
318 *
319 * @param string $tableName The table name
320 * @param string $fieldName The field to be modified
321 * @param string $sqlPath The path to the SQL change path
322 */
323 public function modifyExtensionField( $tableName, $fieldName, $sqlPath ) {
324 $this->extensionUpdates[] = array( 'modifyField', $tableName, $fieldName, $sqlPath, true );
325 }
326
327 /**
328 *
329 * @since 1.20
330 *
331 * @param $tableName string
332 * @return bool
333 */
334 public function tableExists( $tableName ) {
335 return ( $this->db->tableExists( $tableName, __METHOD__ ) );
336 }
337
338 /**
339 * Add a maintenance script to be run after the database updates are complete.
340 *
341 * Script should subclass LoggedUpdateMaintenance
342 *
343 * @since 1.19
344 *
345 * @param string $class Name of a Maintenance subclass
346 */
347 public function addPostDatabaseUpdateMaintenance( $class ) {
348 $this->postDatabaseUpdateMaintenance[] = $class;
349 }
350
351 /**
352 * Get the list of extension-defined updates
353 *
354 * @return Array
355 */
356 protected function getExtensionUpdates() {
357 return $this->extensionUpdates;
358 }
359
360 /**
361 * @since 1.17
362 *
363 * @return array
364 */
365 public function getPostDatabaseUpdateMaintenance() {
366 return $this->postDatabaseUpdateMaintenance;
367 }
368
369 /**
370 * @since 1.21
371 *
372 * Writes the schema updates desired to a file for the DB Admin to run.
373 */
374 private function writeSchemaUpdateFile( $schemaUpdate = array() ) {
375 $updates = $this->updatesSkipped;
376 $this->updatesSkipped = array();
377
378 foreach ( $updates as $funcList ) {
379 $func = $funcList[0];
380 $arg = $funcList[1];
381 $origParams = $funcList[2];
382 call_user_func_array( $func, $arg );
383 flush();
384 $this->updatesSkipped[] = $origParams;
385 }
386 }
387
388 /**
389 * Do all the updates
390 *
391 * @param array $what what updates to perform
392 */
393 public function doUpdates( $what = array( 'core', 'extensions', 'stats' ) ) {
394 global $wgVersion;
395
396 $this->db->begin( __METHOD__ );
397 $what = array_flip( $what );
398 $this->skipSchema = isset( $what['noschema'] ) || $this->fileHandle !== null;
399 if ( isset( $what['core'] ) ) {
400 $this->runUpdates( $this->getCoreUpdateList(), false );
401 }
402 if ( isset( $what['extensions'] ) ) {
403 $this->runUpdates( $this->getOldGlobalUpdates(), false );
404 $this->runUpdates( $this->getExtensionUpdates(), true );
405 }
406
407 if ( isset( $what['stats'] ) ) {
408 $this->checkStats();
409 }
410
411 $this->setAppliedUpdates( $wgVersion, $this->updates );
412
413 if ( $this->fileHandle ) {
414 $this->skipSchema = false;
415 $this->writeSchemaUpdateFile();
416 $this->setAppliedUpdates( "$wgVersion-schema", $this->updatesSkipped );
417 }
418
419 $this->db->commit( __METHOD__ );
420 }
421
422 /**
423 * Helper function for doUpdates()
424 *
425 * @param array $updates of updates to run
426 * @param $passSelf Boolean: whether to pass this object we calling external
427 * functions
428 */
429 private function runUpdates( array $updates, $passSelf ) {
430 $updatesDone = array();
431 $updatesSkipped = array();
432 foreach ( $updates as $params ) {
433 $origParams = $params;
434 $func = array_shift( $params );
435 if ( !is_array( $func ) && method_exists( $this, $func ) ) {
436 $func = array( $this, $func );
437 } elseif ( $passSelf ) {
438 array_unshift( $params, $this );
439 }
440 $ret = call_user_func_array( $func, $params );
441 flush();
442 if ( $ret !== false ) {
443 $updatesDone[] = $origParams;
444 } else {
445 $updatesSkipped[] = array( $func, $params, $origParams );
446 }
447 }
448 $this->updatesSkipped = array_merge( $this->updatesSkipped, $updatesSkipped );
449 $this->updates = array_merge( $this->updates, $updatesDone );
450 }
451
452 /**
453 * @param $version
454 * @param $updates array
455 */
456 protected function setAppliedUpdates( $version, $updates = array() ) {
457 $this->db->clearFlag( DBO_DDLMODE );
458 if ( !$this->canUseNewUpdatelog() ) {
459 return;
460 }
461 $key = "updatelist-$version-" . time();
462 $this->db->insert( 'updatelog',
463 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
464 __METHOD__ );
465 $this->db->setFlag( DBO_DDLMODE );
466 }
467
468 /**
469 * Helper function: check if the given key is present in the updatelog table.
470 * Obviously, only use this for updates that occur after the updatelog table was
471 * created!
472 * @param string $key Name of the key to check for
473 *
474 * @return bool
475 */
476 public function updateRowExists( $key ) {
477 $row = $this->db->selectRow(
478 'updatelog',
479 '1',
480 array( 'ul_key' => $key ),
481 __METHOD__
482 );
483
484 return (bool)$row;
485 }
486
487 /**
488 * Helper function: Add a key to the updatelog table
489 * Obviously, only use this for updates that occur after the updatelog table was
490 * created!
491 * @param string $key Name of key to insert
492 * @param string $val [optional] value to insert along with the key
493 */
494 public function insertUpdateRow( $key, $val = null ) {
495 $this->db->clearFlag( DBO_DDLMODE );
496 $values = array( 'ul_key' => $key );
497 if ( $val && $this->canUseNewUpdatelog() ) {
498 $values['ul_value'] = $val;
499 }
500 $this->db->insert( 'updatelog', $values, __METHOD__, 'IGNORE' );
501 $this->db->setFlag( DBO_DDLMODE );
502 }
503
504 /**
505 * Updatelog was changed in 1.17 to have a ul_value column so we can record
506 * more information about what kind of updates we've done (that's what this
507 * class does). Pre-1.17 wikis won't have this column, and really old wikis
508 * might not even have updatelog at all
509 *
510 * @return boolean
511 */
512 protected function canUseNewUpdatelog() {
513 return $this->db->tableExists( 'updatelog', __METHOD__ ) &&
514 $this->db->fieldExists( 'updatelog', 'ul_value', __METHOD__ );
515 }
516
517 /**
518 * Returns whether updates should be executed on the database table $name.
519 * Updates will be prevented if the table is a shared table and it is not
520 * specified to run updates on shared tables.
521 *
522 * @param string $name table name
523 * @return bool
524 */
525 protected function doTable( $name ) {
526 global $wgSharedDB, $wgSharedTables;
527
528 // Don't bother to check $wgSharedTables if there isn't a shared database
529 // or the user actually also wants to do updates on the shared database.
530 if ( $wgSharedDB === null || $this->shared ) {
531 return true;
532 }
533
534 return !in_array( $name, $wgSharedTables );
535 }
536
537 /**
538 * Before 1.17, we used to handle updates via stuff like
539 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
540 * of this in 1.17 but we want to remain back-compatible for a while. So
541 * load up these old global-based things into our update list.
542 *
543 * @return array
544 */
545 protected function getOldGlobalUpdates() {
546 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
547 $wgExtNewIndexes;
548
549 $updates = array();
550
551 foreach ( $wgExtNewTables as $tableRecord ) {
552 $updates[] = array(
553 'addTable', $tableRecord[0], $tableRecord[1], true
554 );
555 }
556
557 foreach ( $wgExtNewFields as $fieldRecord ) {
558 $updates[] = array(
559 'addField', $fieldRecord[0], $fieldRecord[1],
560 $fieldRecord[2], true
561 );
562 }
563
564 foreach ( $wgExtNewIndexes as $fieldRecord ) {
565 $updates[] = array(
566 'addIndex', $fieldRecord[0], $fieldRecord[1],
567 $fieldRecord[2], true
568 );
569 }
570
571 foreach ( $wgExtModifiedFields as $fieldRecord ) {
572 $updates[] = array(
573 'modifyField', $fieldRecord[0], $fieldRecord[1],
574 $fieldRecord[2], true
575 );
576 }
577
578 return $updates;
579 }
580
581 /**
582 * Get an array of updates to perform on the database. Should return a
583 * multi-dimensional array. The main key is the MediaWiki version (1.12,
584 * 1.13...) with the values being arrays of updates, identical to how
585 * updaters.inc did it (for now)
586 *
587 * @return Array
588 */
589 abstract protected function getCoreUpdateList();
590
591 /**
592 * Append an SQL fragment to the open file handle.
593 *
594 * @param string $filename File name to open
595 */
596 public function copyFile( $filename ) {
597 $this->db->sourceFile( $filename, false, false, false,
598 array( $this, 'appendLine' )
599 );
600 }
601
602 /**
603 * Append a line to the open filehandle. The line is assumed to
604 * be a complete SQL statement.
605 *
606 * This is used as a callback for for sourceLine().
607 *
608 * @param string $line text to append to the file
609 * @return Boolean false to skip actually executing the file
610 * @throws MWException
611 */
612 public function appendLine( $line ) {
613 $line = rtrim( $line ) . ";\n";
614 if ( fwrite( $this->fileHandle, $line ) === false ) {
615 throw new MWException( "trouble writing file" );
616 }
617
618 return false;
619 }
620
621 /**
622 * Applies a SQL patch
623 *
624 * @param string $path Path to the patch file
625 * @param $isFullPath Boolean Whether to treat $path as a relative or not
626 * @param string $msg Description of the patch
627 * @return boolean false if patch is skipped.
628 */
629 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
630 if ( $msg === null ) {
631 $msg = "Applying $path patch";
632 }
633 if ( $this->skipSchema ) {
634 $this->output( "...skipping schema change ($msg).\n" );
635
636 return false;
637 }
638
639 $this->output( "$msg ..." );
640
641 if ( !$isFullPath ) {
642 $path = $this->db->patchPath( $path );
643 }
644 if ( $this->fileHandle !== null ) {
645 $this->copyFile( $path );
646 } else {
647 $this->db->sourceFile( $path );
648 }
649 $this->output( "done.\n" );
650
651 return true;
652 }
653
654 /**
655 * Add a new table to the database
656 *
657 * @param string $name Name of the new table
658 * @param string $patch Path to the patch file
659 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
660 * @return Boolean false if this was skipped because schema changes are skipped
661 */
662 protected function addTable( $name, $patch, $fullpath = false ) {
663 if ( !$this->doTable( $name ) ) {
664 return true;
665 }
666
667 if ( $this->db->tableExists( $name, __METHOD__ ) ) {
668 $this->output( "...$name table already exists.\n" );
669 } else {
670 return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
671 }
672
673 return true;
674 }
675
676 /**
677 * Add a new field to an existing table
678 *
679 * @param string $table Name of the table to modify
680 * @param string $field Name of the new field
681 * @param string $patch Path to the patch file
682 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
683 * @return Boolean false if this was skipped because schema changes are skipped
684 */
685 protected function addField( $table, $field, $patch, $fullpath = false ) {
686 if ( !$this->doTable( $table ) ) {
687 return true;
688 }
689
690 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
691 $this->output( "...$table table does not exist, skipping new field patch.\n" );
692 } elseif ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
693 $this->output( "...have $field field in $table table.\n" );
694 } else {
695 return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
696 }
697
698 return true;
699 }
700
701 /**
702 * Add a new index to an existing table
703 *
704 * @param string $table Name of the table to modify
705 * @param string $index Name of the new index
706 * @param string $patch Path to the patch file
707 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
708 * @return Boolean false if this was skipped because schema changes are skipped
709 */
710 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
711 if ( !$this->doTable( $table ) ) {
712 return true;
713 }
714
715 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
716 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
717 } elseif ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
718 $this->output( "...index $index already set on $table table.\n" );
719 } else {
720 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
721 }
722
723 return true;
724 }
725
726 /**
727 * Drop a field from an existing table
728 *
729 * @param string $table Name of the table to modify
730 * @param string $field Name of the old field
731 * @param string $patch Path to the patch file
732 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
733 * @return Boolean false if this was skipped because schema changes are skipped
734 */
735 protected function dropField( $table, $field, $patch, $fullpath = false ) {
736 if ( !$this->doTable( $table ) ) {
737 return true;
738 }
739
740 if ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
741 return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
742 } else {
743 $this->output( "...$table table does not contain $field field.\n" );
744 }
745
746 return true;
747 }
748
749 /**
750 * Drop an index from an existing table
751 *
752 * @param string $table Name of the table to modify
753 * @param string $index Name of the index
754 * @param string $patch Path to the patch file
755 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
756 * @return Boolean false if this was skipped because schema changes are skipped
757 */
758 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
759 if ( !$this->doTable( $table ) ) {
760 return true;
761 }
762
763 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
764 return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
765 } else {
766 $this->output( "...$index key doesn't exist.\n" );
767 }
768
769 return true;
770 }
771
772 /**
773 * Rename an index from an existing table
774 *
775 * @param string $table Name of the table to modify
776 * @param string $oldIndex Old name of the index
777 * @param string $newIndex New name of the index
778 * @param $skipBothIndexExistWarning Boolean: Whether to warn if both the
779 * old and the new indexes exist.
780 * @param string $patch Path to the patch file
781 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
782 * @return Boolean false if this was skipped because schema changes are skipped
783 */
784 protected function renameIndex( $table, $oldIndex, $newIndex,
785 $skipBothIndexExistWarning, $patch, $fullpath = false
786 ) {
787 if ( !$this->doTable( $table ) ) {
788 return true;
789 }
790
791 // First requirement: the table must exist
792 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
793 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
794
795 return true;
796 }
797
798 // Second requirement: the new index must be missing
799 if ( $this->db->indexExists( $table, $newIndex, __METHOD__ ) ) {
800 $this->output( "...index $newIndex already set on $table table.\n" );
801 if ( !$skipBothIndexExistWarning &&
802 $this->db->indexExists( $table, $oldIndex, __METHOD__ )
803 ) {
804 $this->output( "...WARNING: $oldIndex still exists, despite it has " .
805 "been renamed into $newIndex (which also exists).\n" .
806 " $oldIndex should be manually removed if not needed anymore.\n" );
807 }
808
809 return true;
810 }
811
812 // Third requirement: the old index must exist
813 if ( !$this->db->indexExists( $table, $oldIndex, __METHOD__ ) ) {
814 $this->output( "...skipping: index $oldIndex doesn't exist.\n" );
815
816 return true;
817 }
818
819 // Requirements have been satisfied, patch can be applied
820 return $this->applyPatch(
821 $patch,
822 $fullpath,
823 "Renaming index $oldIndex into $newIndex to table $table"
824 );
825 }
826
827 /**
828 * If the specified table exists, drop it, or execute the
829 * patch if one is provided.
830 *
831 * Public @since 1.20
832 *
833 * @param $table string
834 * @param $patch string|false
835 * @param $fullpath bool
836 * @return Boolean false if this was skipped because schema changes are skipped
837 */
838 public function dropTable( $table, $patch = false, $fullpath = false ) {
839 if ( !$this->doTable( $table ) ) {
840 return true;
841 }
842
843 if ( $this->db->tableExists( $table, __METHOD__ ) ) {
844 $msg = "Dropping table $table";
845
846 if ( $patch === false ) {
847 $this->output( "$msg ..." );
848 $this->db->dropTable( $table, __METHOD__ );
849 $this->output( "done.\n" );
850 } else {
851 return $this->applyPatch( $patch, $fullpath, $msg );
852 }
853 } else {
854 $this->output( "...$table doesn't exist.\n" );
855 }
856
857 return true;
858 }
859
860 /**
861 * Modify an existing field
862 *
863 * @param string $table name of the table to which the field belongs
864 * @param string $field name of the field to modify
865 * @param string $patch path to the patch file
866 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
867 * @return Boolean false if this was skipped because schema changes are skipped
868 */
869 public function modifyField( $table, $field, $patch, $fullpath = false ) {
870 if ( !$this->doTable( $table ) ) {
871 return true;
872 }
873
874 $updateKey = "$table-$field-$patch";
875 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
876 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
877 } elseif ( !$this->db->fieldExists( $table, $field, __METHOD__ ) ) {
878 $this->output( "...$field field does not exist in $table table, " .
879 "skipping modify field patch.\n" );
880 } elseif ( $this->updateRowExists( $updateKey ) ) {
881 $this->output( "...$field in table $table already modified by patch $patch.\n" );
882 } else {
883 $this->insertUpdateRow( $updateKey );
884
885 return $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
886 }
887
888 return true;
889 }
890
891 /**
892 * Purge the objectcache table
893 */
894 public function purgeCache() {
895 global $wgLocalisationCacheConf;
896 # We can't guarantee that the user will be able to use TRUNCATE,
897 # but we know that DELETE is available to us
898 $this->output( "Purging caches..." );
899 $this->db->delete( 'objectcache', '*', __METHOD__ );
900 if ( $wgLocalisationCacheConf['manualRecache'] ) {
901 $this->rebuildLocalisationCache();
902 }
903 MessageBlobStore::clear();
904 $this->output( "done.\n" );
905 }
906
907 /**
908 * Check the site_stats table is not properly populated.
909 */
910 protected function checkStats() {
911 $this->output( "...site_stats is populated..." );
912 $row = $this->db->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
913 if ( $row === false ) {
914 $this->output( "data is missing! rebuilding...\n" );
915 } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
916 $this->output( "missing ss_total_pages, rebuilding...\n" );
917 } else {
918 $this->output( "done.\n" );
919
920 return;
921 }
922 SiteStatsInit::doAllAndCommit( $this->db );
923 }
924
925 # Common updater functions
926
927 /**
928 * Sets the number of active users in the site_stats table
929 */
930 protected function doActiveUsersInit() {
931 $activeUsers = $this->db->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
932 if ( $activeUsers == -1 ) {
933 $activeUsers = $this->db->selectField( 'recentchanges',
934 'COUNT( DISTINCT rc_user_text )',
935 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
936 );
937 $this->db->update( 'site_stats',
938 array( 'ss_active_users' => intval( $activeUsers ) ),
939 array( 'ss_row_id' => 1 ), __METHOD__, array( 'LIMIT' => 1 )
940 );
941 }
942 $this->output( "...ss_active_users user count set...\n" );
943 }
944
945 /**
946 * Populates the log_user_text field in the logging table
947 */
948 protected function doLogUsertextPopulation() {
949 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
950 $this->output(
951 "Populating log_user_text field, printing progress markers. For large\n" .
952 "databases, you may want to hit Ctrl-C and do this manually with\n" .
953 "maintenance/populateLogUsertext.php.\n"
954 );
955
956 $task = $this->maintenance->runChild( 'PopulateLogUsertext' );
957 $task->execute();
958 $this->output( "done.\n" );
959 }
960 }
961
962 /**
963 * Migrate log params to new table and index for searching
964 */
965 protected function doLogSearchPopulation() {
966 if ( !$this->updateRowExists( 'populate log_search' ) ) {
967 $this->output(
968 "Populating log_search table, printing progress markers. For large\n" .
969 "databases, you may want to hit Ctrl-C and do this manually with\n" .
970 "maintenance/populateLogSearch.php.\n" );
971
972 $task = $this->maintenance->runChild( 'PopulateLogSearch' );
973 $task->execute();
974 $this->output( "done.\n" );
975 }
976 }
977
978 /**
979 * Updates the timestamps in the transcache table
980 */
981 protected function doUpdateTranscacheField() {
982 if ( $this->updateRowExists( 'convert transcache field' ) ) {
983 $this->output( "...transcache tc_time already converted.\n" );
984
985 return true;
986 }
987
988 return $this->applyPatch( 'patch-tc-timestamp.sql', false,
989 "Converting tc_time from UNIX epoch to MediaWiki timestamp" );
990 }
991
992 /**
993 * Update CategoryLinks collation
994 */
995 protected function doCollationUpdate() {
996 global $wgCategoryCollation;
997 if ( $this->db->fieldExists( 'categorylinks', 'cl_collation', __METHOD__ ) ) {
998 if ( $this->db->selectField(
999 'categorylinks',
1000 'COUNT(*)',
1001 'cl_collation != ' . $this->db->addQuotes( $wgCategoryCollation ),
1002 __METHOD__
1003 ) == 0
1004 ) {
1005 $this->output( "...collations up-to-date.\n" );
1006
1007 return;
1008 }
1009
1010 $this->output( "Updating category collations..." );
1011 $task = $this->maintenance->runChild( 'UpdateCollation' );
1012 $task->execute();
1013 $this->output( "...done.\n" );
1014 }
1015 }
1016
1017 /**
1018 * Migrates user options from the user table blob to user_properties
1019 */
1020 protected function doMigrateUserOptions() {
1021 if ( $this->db->tableExists( 'user_properties' ) ) {
1022 $cl = $this->maintenance->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
1023 $cl->execute();
1024 $this->output( "done.\n" );
1025 }
1026 }
1027
1028 /**
1029 * Rebuilds the localisation cache
1030 */
1031 protected function rebuildLocalisationCache() {
1032 /**
1033 * @var $cl RebuildLocalisationCache
1034 */
1035 $cl = $this->maintenance->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
1036 $this->output( "Rebuilding localisation cache...\n" );
1037 $cl->setForce();
1038 $cl->execute();
1039 $this->output( "done.\n" );
1040 }
1041
1042 /**
1043 * Turns off content handler fields during parts of the upgrade
1044 * where they aren't available.
1045 */
1046 protected function disableContentHandlerUseDB() {
1047 global $wgContentHandlerUseDB;
1048
1049 if( $wgContentHandlerUseDB ) {
1050 $this->output( "Turning off Content Handler DB fields for this part of upgrade.\n" );
1051 $this->holdContentHandlerUseDB = $wgContentHandlerUseDB;
1052 $wgContentHandlerUseDB = false;
1053 }
1054 }
1055
1056 /**
1057 * Turns content handler fields back on.
1058 */
1059 protected function enableContentHandlerUseDB() {
1060 global $wgContentHandlerUseDB;
1061
1062 if( $this->holdContentHandlerUseDB ) {
1063 $this->output( "Content Handler DB fields should be usable now.\n" );
1064 $wgContentHandlerUseDB = $this->holdContentHandlerUseDB;
1065 }
1066 }
1067 }