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