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