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