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