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