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