38bbd42a7cf31ba282950bbb28336fe26d7a6844
[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 * Get the list of extension-defined updates
176 *
177 * @return Array
178 */
179 protected function getExtensionUpdates() {
180 return $this->extensionUpdates;
181 }
182
183 public function getPostDatabaseUpdateMaintenance() {
184 return $this->postDatabaseUpdateMaintenance;
185 }
186
187 /**
188 * Do all the updates
189 *
190 * @param $what Array: what updates to perform
191 */
192 public function doUpdates( $what = array( 'core', 'extensions', 'purge', 'stats' ) ) {
193 global $wgVersion;
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( $wgVersion, $this->updates );
205
206 if( isset( $what['purge'] ) ) {
207 $this->purgeCache();
208 }
209 if ( isset( $what['stats'] ) ) {
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 $this->db->clearFlag( DBO_DDLMODE );
237 if( !$this->canUseNewUpdatelog() ) {
238 return;
239 }
240 $key = "updatelist-$version-" . time();
241 $this->db->insert( 'updatelog',
242 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
243 __METHOD__ );
244 $this->db->setFlag( DBO_DDLMODE );
245 }
246
247 /**
248 * Helper function: check if the given key is present in the updatelog table.
249 * Obviously, only use this for updates that occur after the updatelog table was
250 * created!
251 * @param $key String Name of the key to check for
252 */
253 public function updateRowExists( $key ) {
254 $row = $this->db->selectRow(
255 'updatelog',
256 '1',
257 array( 'ul_key' => $key ),
258 __METHOD__
259 );
260 return (bool)$row;
261 }
262
263 /**
264 * Helper function: Add a key to the updatelog table
265 * Obviously, only use this for updates that occur after the updatelog table was
266 * created!
267 * @param $key String Name of key to insert
268 * @param $val String [optional] value to insert along with the key
269 */
270 public function insertUpdateRow( $key, $val = null ) {
271 $this->db->clearFlag( DBO_DDLMODE );
272 $values = array( 'ul_key' => $key );
273 if( $val && $this->canUseNewUpdatelog() ) {
274 $values['ul_value'] = $val;
275 }
276 $this->db->insert( 'updatelog', $values, __METHOD__, 'IGNORE' );
277 $this->db->setFlag( DBO_DDLMODE );
278 }
279
280 /**
281 * Updatelog was changed in 1.17 to have a ul_value column so we can record
282 * more information about what kind of updates we've done (that's what this
283 * class does). Pre-1.17 wikis won't have this column, and really old wikis
284 * might not even have updatelog at all
285 *
286 * @return boolean
287 */
288 protected function canUseNewUpdatelog() {
289 return $this->db->tableExists( 'updatelog' ) &&
290 $this->db->fieldExists( 'updatelog', 'ul_value' );
291 }
292
293 /**
294 * Before 1.17, we used to handle updates via stuff like
295 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
296 * of this in 1.17 but we want to remain back-compatible for a while. So
297 * load up these old global-based things into our update list.
298 */
299 protected function getOldGlobalUpdates() {
300 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
301 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
302
303 $doUser = $this->shared ?
304 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
305 !$wgSharedDB || !in_array( 'user', $wgSharedTables );
306
307 $updates = array();
308
309 foreach ( $wgExtNewTables as $tableRecord ) {
310 $updates[] = array(
311 'addTable', $tableRecord[0], $tableRecord[1], true
312 );
313 }
314
315 foreach ( $wgExtNewFields as $fieldRecord ) {
316 if ( $fieldRecord[0] != 'user' || $doUser ) {
317 $updates[] = array(
318 'addField', $fieldRecord[0], $fieldRecord[1],
319 $fieldRecord[2], true
320 );
321 }
322 }
323
324 foreach ( $wgExtNewIndexes as $fieldRecord ) {
325 $updates[] = array(
326 'addIndex', $fieldRecord[0], $fieldRecord[1],
327 $fieldRecord[2], true
328 );
329 }
330
331 foreach ( $wgExtModifiedFields as $fieldRecord ) {
332 $updates[] = array(
333 'modifyField', $fieldRecord[0], $fieldRecord[1],
334 $fieldRecord[2], true
335 );
336 }
337
338 return $updates;
339 }
340
341 /**
342 * Get an array of updates to perform on the database. Should return a
343 * multi-dimensional array. The main key is the MediaWiki version (1.12,
344 * 1.13...) with the values being arrays of updates, identical to how
345 * updaters.inc did it (for now)
346 *
347 * @return Array
348 */
349 protected abstract function getCoreUpdateList();
350
351 /**
352 * Applies a SQL patch
353 * @param $path String Path to the patch file
354 * @param $isFullPath Boolean Whether to treat $path as a relative or not
355 */
356 protected function applyPatch( $path, $isFullPath = false ) {
357 if ( $isFullPath ) {
358 $this->db->sourceFile( $path );
359 } else {
360 $this->db->sourceFile( $this->db->patchPath( $path ) );
361 }
362 }
363
364 /**
365 * Add a new table to the database
366 * @param $name String Name of the new table
367 * @param $patch String Path to the patch file
368 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
369 */
370 protected function addTable( $name, $patch, $fullpath = false ) {
371 if ( $this->db->tableExists( $name ) ) {
372 $this->output( "...$name table already exists.\n" );
373 } else {
374 $this->output( "Creating $name table..." );
375 $this->applyPatch( $patch, $fullpath );
376 $this->output( "ok\n" );
377 }
378 }
379
380 /**
381 * Add a new field to an existing table
382 * @param $table String Name of the table to modify
383 * @param $field String Name of the new field
384 * @param $patch String Path to the patch file
385 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
386 */
387 protected function addField( $table, $field, $patch, $fullpath = false ) {
388 if ( !$this->db->tableExists( $table ) ) {
389 $this->output( "...$table table does not exist, skipping new field patch\n" );
390 } elseif ( $this->db->fieldExists( $table, $field ) ) {
391 $this->output( "...have $field field in $table table.\n" );
392 } else {
393 $this->output( "Adding $field field to table $table..." );
394 $this->applyPatch( $patch, $fullpath );
395 $this->output( "ok\n" );
396 }
397 }
398
399 /**
400 * Add a new index to an existing table
401 * @param $table String Name of the table to modify
402 * @param $index String Name of the new index
403 * @param $patch String Path to the patch file
404 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
405 */
406 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
407 if ( $this->db->indexExists( $table, $index ) ) {
408 $this->output( "...$index key already set on $table table.\n" );
409 } else {
410 $this->output( "Adding $index key to table $table... " );
411 $this->applyPatch( $patch, $fullpath );
412 $this->output( "ok\n" );
413 }
414 }
415
416 /**
417 * Drop a field from an existing table
418 *
419 * @param $table String Name of the table to modify
420 * @param $field String Name of the old field
421 * @param $patch String Path to the patch file
422 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
423 */
424 protected function dropField( $table, $field, $patch, $fullpath = false ) {
425 if ( $this->db->fieldExists( $table, $field ) ) {
426 $this->output( "Table $table contains $field field. Dropping... " );
427 $this->applyPatch( $patch, $fullpath );
428 $this->output( "ok\n" );
429 } else {
430 $this->output( "...$table table does not contain $field field.\n" );
431 }
432 }
433
434 /**
435 * Drop an index from an existing table
436 *
437 * @param $table String: Name of the table to modify
438 * @param $index String: Name of the old index
439 * @param $patch String: Path to the patch file
440 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
441 */
442 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
443 if ( $this->db->indexExists( $table, $index ) ) {
444 $this->output( "Dropping $index from table $table... " );
445 $this->applyPatch( $patch, $fullpath );
446 $this->output( "ok\n" );
447 } else {
448 $this->output( "...$index key doesn't exist.\n" );
449 }
450 }
451
452 /**
453 * Modify an existing field
454 *
455 * @param $table String: name of the table to which the field belongs
456 * @param $field String: name of the field to modify
457 * @param $patch String: path to the patch file
458 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
459 */
460 public function modifyField( $table, $field, $patch, $fullpath = false ) {
461 $updateKey = "$table-$field-$patch";
462 if ( !$this->db->tableExists( $table ) ) {
463 $this->output( "...$table table does not exist, skipping modify field patch\n" );
464 } elseif ( !$this->db->fieldExists( $table, $field ) ) {
465 $this->output( "...$field field does not exist in $table table, skipping modify field patch\n" );
466 } elseif( $this->updateRowExists( $updateKey ) ) {
467 $this->output( "...$field in table $table already modified by patch $patch\n" );
468 } else {
469 $this->output( "Modifying $field field of table $table..." );
470 $this->applyPatch( $patch, $fullpath );
471 $this->insertUpdateRow( $updateKey );
472 $this->output( "ok\n" );
473 }
474 }
475
476 /**
477 * Purge the objectcache table
478 */
479 protected function purgeCache() {
480 # We can't guarantee that the user will be able to use TRUNCATE,
481 # but we know that DELETE is available to us
482 $this->output( "Purging caches..." );
483 $this->db->delete( 'objectcache', '*', __METHOD__ );
484 $this->output( "done.\n" );
485 }
486
487 /**
488 * Check the site_stats table is not properly populated.
489 */
490 protected function checkStats() {
491 $this->output( "Checking site_stats row..." );
492 $row = $this->db->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
493 if ( $row === false ) {
494 $this->output( "data is missing! rebuilding...\n" );
495 } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
496 $this->output( "missing ss_total_pages, rebuilding...\n" );
497 } else {
498 $this->output( "done.\n" );
499 return;
500 }
501 SiteStatsInit::doAllAndCommit( $this->db );
502 }
503
504 # Common updater functions
505
506 protected function doActiveUsersInit() {
507 $activeUsers = $this->db->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
508 if ( $activeUsers == -1 ) {
509 $activeUsers = $this->db->selectField( 'recentchanges',
510 'COUNT( DISTINCT rc_user_text )',
511 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
512 );
513 $this->db->update( 'site_stats',
514 array( 'ss_active_users' => intval( $activeUsers ) ),
515 array( 'ss_row_id' => 1 ), __METHOD__, array( 'LIMIT' => 1 )
516 );
517 }
518 $this->output( "...ss_active_users user count set...\n" );
519 }
520
521 protected function doLogUsertextPopulation() {
522 if ( $this->updateRowExists( 'populate log_usertext' ) ) {
523 $this->output( "...log_user_text field already populated.\n" );
524 return;
525 }
526
527 $this->output(
528 "Populating log_user_text field, printing progress markers. For large\n" .
529 "databases, you may want to hit Ctrl-C and do this manually with\n" .
530 "maintenance/populateLogUsertext.php.\n" );
531 $task = $this->maintenance->runChild( 'PopulateLogUsertext' );
532 $task->execute();
533 $this->output( "Done populating log_user_text field.\n" );
534 }
535
536 protected function doLogSearchPopulation() {
537 if ( $this->updateRowExists( 'populate log_search' ) ) {
538 $this->output( "...log_search table already populated.\n" );
539 return;
540 }
541
542 $this->output(
543 "Populating log_search table, printing progress markers. For large\n" .
544 "databases, you may want to hit Ctrl-C and do this manually with\n" .
545 "maintenance/populateLogSearch.php.\n" );
546 $task = $this->maintenance->runChild( 'PopulateLogSearch' );
547 $task->execute();
548 $this->output( "Done populating log_search table.\n" );
549 }
550
551 protected function doUpdateTranscacheField() {
552 if ( $this->updateRowExists( 'convert transcache field' ) ) {
553 $this->output( "...transcache tc_time already converted.\n" );
554 return;
555 }
556
557 $this->output( "Converting tc_time from UNIX epoch to MediaWiki timestamp... " );
558 $this->applyPatch( 'patch-tc-timestamp.sql' );
559 $this->output( "ok\n" );
560 }
561
562 protected function doCollationUpdate() {
563 global $wgCategoryCollation;
564 if ( $this->db->selectField(
565 'categorylinks',
566 'COUNT(*)',
567 'cl_collation != ' . $this->db->addQuotes( $wgCategoryCollation ),
568 __METHOD__
569 ) == 0 ) {
570 $this->output( "...collations up-to-date.\n" );
571 return;
572 }
573
574 $task = $this->maintenance->runChild( 'UpdateCollation' );
575 $task->execute();
576 }
577 }