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