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