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