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