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