Fixes for r75545: don't use MEDIAWIKI_INSTALL in the updaters classes, it's not what...
[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 if ( !defined( 'MW_NO_SETUP' ) ) {
171 define( 'MW_NO_SETUP', true );
172 }
173
174 $this->runUpdates( $this->getCoreUpdateList(), false );
175 $this->runUpdates( $this->getOldGlobalUpdates(), false );
176 $this->runUpdates( $this->getExtensionUpdates(), true );
177
178 $this->setAppliedUpdates( $wgVersion, $this->updates );
179
180 if( $purge ) {
181 $this->purgeCache();
182 }
183 $this->checkStats();
184 }
185
186 /**
187 * Helper function for doUpdates()
188 *
189 * @param $updates Array of updates to run
190 * @param $passSelf Boolean: whether to pass this object we calling external
191 * functions
192 */
193 private function runUpdates( array $updates, $passSelf ) {
194 foreach ( $updates as $params ) {
195 $func = array_shift( $params );
196 if( !is_array( $func ) && method_exists( $this, $func ) ) {
197 $func = array( $this, $func );
198 } elseif ( $passSelf ) {
199 array_unshift( $params, $this );
200 }
201 call_user_func_array( $func, $params );
202 flush();
203 }
204 $this->updates = array_merge( $this->updates, $updates );
205 }
206
207 protected function setAppliedUpdates( $version, $updates = array() ) {
208 if( !$this->canUseNewUpdatelog() ) {
209 return;
210 }
211 $key = "updatelist-$version-" . time();
212 $this->db->insert( 'updatelog',
213 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
214 __METHOD__ );
215 }
216
217 /**
218 * Helper function: check if the given key is present in the updatelog table.
219 * Obviously, only use this for updates that occur after the updatelog table was
220 * created!
221 */
222 public function updateRowExists( $key ) {
223 $row = $this->db->selectRow(
224 'updatelog',
225 '1',
226 array( 'ul_key' => $key ),
227 __METHOD__
228 );
229 return (bool)$row;
230 }
231
232 /**
233 * Updatelog was changed in 1.17 to have a ul_value column so we can record
234 * more information about what kind of updates we've done (that's what this
235 * class does). Pre-1.17 wikis won't have this column, and really old wikis
236 * might not even have updatelog at all
237 *
238 * @return boolean
239 */
240 protected function canUseNewUpdatelog() {
241 return $this->db->tableExists( 'updatelog' ) &&
242 $this->db->fieldExists( 'updatelog', 'ul_value' );
243 }
244
245 /**
246 * Before 1.17, we used to handle updates via stuff like
247 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
248 * of this in 1.17 but we want to remain back-compatible for a while. So
249 * load up these old global-based things into our update list.
250 */
251 protected function getOldGlobalUpdates() {
252 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
253 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
254
255 $doUser = $this->shared ?
256 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
257 !$wgSharedDB || !in_array( 'user', $wgSharedTables );
258
259 $updates = array();
260
261 foreach ( $wgExtNewTables as $tableRecord ) {
262 $updates[] = array(
263 'addTable', $tableRecord[0], $tableRecord[1], true
264 );
265 }
266
267 foreach ( $wgExtNewFields as $fieldRecord ) {
268 if ( $fieldRecord[0] != 'user' || $doUser ) {
269 $updates[] = array(
270 'addField', $fieldRecord[0], $fieldRecord[1],
271 $fieldRecord[2], true
272 );
273 }
274 }
275
276 foreach ( $wgExtNewIndexes as $fieldRecord ) {
277 $updates[] = array(
278 'addIndex', $fieldRecord[0], $fieldRecord[1],
279 $fieldRecord[2], true
280 );
281 }
282
283 foreach ( $wgExtModifiedFields as $fieldRecord ) {
284 $updates[] = array(
285 'modifyField', $fieldRecord[0], $fieldRecord[1],
286 $fieldRecord[2], true
287 );
288 }
289
290 return $updates;
291 }
292
293 /**
294 * Get an array of updates to perform on the database. Should return a
295 * multi-dimensional array. The main key is the MediaWiki version (1.12,
296 * 1.13...) with the values being arrays of updates, identical to how
297 * updaters.inc did it (for now)
298 *
299 * @return Array
300 */
301 protected abstract function getCoreUpdateList();
302
303 /**
304 * Applies a SQL patch
305 * @param $path String Path to the patch file
306 * @param $isFullPath Boolean Whether to treat $path as a relative or not
307 */
308 protected function applyPatch( $path, $isFullPath = false ) {
309 if ( $isFullPath ) {
310 $this->db->sourceFile( $path );
311 } else {
312 $this->db->sourceFile( $this->db->patchPath( $path ) );
313 }
314 }
315
316 /**
317 * Add a new table to the database
318 * @param $name String Name of the new table
319 * @param $patch String Path to the patch file
320 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
321 */
322 protected function addTable( $name, $patch, $fullpath = false ) {
323 if ( $this->db->tableExists( $name ) ) {
324 $this->output( "...$name table already exists.\n" );
325 } else {
326 $this->output( "Creating $name table..." );
327 $this->applyPatch( $patch, $fullpath );
328 $this->output( "ok\n" );
329 }
330 }
331
332 /**
333 * Add a new field to an existing table
334 * @param $table String Name of the table to modify
335 * @param $field String Name of the new field
336 * @param $patch String Path to the patch file
337 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
338 */
339 protected function addField( $table, $field, $patch, $fullpath = false ) {
340 if ( !$this->db->tableExists( $table ) ) {
341 $this->output( "...$table table does not exist, skipping new field patch\n" );
342 } elseif ( $this->db->fieldExists( $table, $field ) ) {
343 $this->output( "...have $field field in $table table.\n" );
344 } else {
345 $this->output( "Adding $field field to table $table..." );
346 $this->applyPatch( $patch, $fullpath );
347 $this->output( "ok\n" );
348 }
349 }
350
351 /**
352 * Add a new index to an existing table
353 * @param $table String Name of the table to modify
354 * @param $index String Name of the new index
355 * @param $patch String Path to the patch file
356 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
357 */
358 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
359 if ( $this->db->indexExists( $table, $index ) ) {
360 $this->output( "...$index key already set on $table table.\n" );
361 } else {
362 $this->output( "Adding $index key to table $table... " );
363 $this->applyPatch( $patch, $fullpath );
364 $this->output( "ok\n" );
365 }
366 }
367
368 /**
369 * Drop a field from an existing table
370 *
371 * @param $table String Name of the table to modify
372 * @param $field String Name of the old field
373 * @param $patch String Path to the patch file
374 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
375 */
376 protected function dropField( $table, $field, $patch, $fullpath = false ) {
377 if ( $this->db->fieldExists( $table, $field ) ) {
378 $this->output( "Table $table contains $field field. Dropping... " );
379 $this->applyPatch( $patch, $fullpath );
380 $this->output( "ok\n" );
381 } else {
382 $this->output( "...$table table does not contain $field field.\n" );
383 }
384 }
385
386 /**
387 * Drop an index from an existing table
388 *
389 * @param $table String: Name of the table to modify
390 * @param $index String: Name of the old index
391 * @param $patch String: Path to the patch file
392 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
393 */
394 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
395 if ( $this->db->indexExists( $table, $index ) ) {
396 $this->output( "Dropping $index from table $table... " );
397 $this->applyPatch( $patch, $fullpath );
398 $this->output( "ok\n" );
399 } else {
400 $this->output( "...$index key doesn't exist.\n" );
401 }
402 }
403
404 /**
405 * Modify an existing field
406 *
407 * @param $table String: name of the table to which the field belongs
408 * @param $field String: name of the field to modify
409 * @param $patch String: path to the patch file
410 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
411 */
412 public function modifyField( $table, $field, $patch, $fullpath = false ) {
413 if ( !$this->db->tableExists( $table ) ) {
414 $this->output( "...$table table does not exist, skipping modify field patch\n" );
415 } elseif ( !$this->db->fieldExists( $table, $field ) ) {
416 $this->output( "...$field field does not exist in $table table, skipping modify field patch\n" );
417 } else {
418 $this->output( "Modifying $field field of table $table..." );
419 $this->applyPatch( $patch, $fullpath );
420 $this->output( "ok\n" );
421 }
422 }
423
424 /**
425 * Purge the objectcache table
426 */
427 protected function purgeCache() {
428 # We can't guarantee that the user will be able to use TRUNCATE,
429 # but we know that DELETE is available to us
430 $this->output( "Purging caches..." );
431 $this->db->delete( 'objectcache', '*', __METHOD__ );
432 $this->output( "done.\n" );
433 }
434
435 /**
436 * Check the site_stats table is not properly populated.
437 */
438 protected function checkStats() {
439 $this->output( "Checking site_stats row..." );
440 $row = $this->db->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
441 if ( $row === false ) {
442 $this->output( "data is missing! rebuilding...\n" );
443 } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
444 $this->output( "missing ss_total_pages, rebuilding...\n" );
445 } else {
446 $this->output( "done.\n" );
447 return;
448 }
449 SiteStatsInit::doAllAndCommit( false );
450 }
451
452 # Common updater functions
453
454 protected function doActiveUsersInit() {
455 $activeUsers = $this->db->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
456 if ( $activeUsers == -1 ) {
457 $activeUsers = $this->db->selectField( 'recentchanges',
458 'COUNT( DISTINCT rc_user_text )',
459 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
460 );
461 $this->db->update( 'site_stats',
462 array( 'ss_active_users' => intval( $activeUsers ) ),
463 array( 'ss_row_id' => 1 ), __METHOD__, array( 'LIMIT' => 1 )
464 );
465 }
466 $this->output( "...ss_active_users user count set...\n" );
467 }
468
469 protected function doLogSearchPopulation() {
470 if ( $this->updateRowExists( 'populate log_search' ) ) {
471 $this->output( "...log_search table already populated.\n" );
472 return;
473 }
474
475 $this->output(
476 "Populating log_search table, printing progress markers. For large\n" .
477 "databases, you may want to hit Ctrl-C and do this manually with\n" .
478 "maintenance/populateLogSearch.php.\n" );
479 $task = new PopulateLogSearch();
480 $task->execute();
481 $this->output( "Done populating log_search table.\n" );
482 }
483
484 protected function doUpdateTranscacheField() {
485 if ( $this->updateRowExists( 'convert transcache field' ) ) {
486 $this->output( "...transcache tc_time already converted.\n" );
487 return;
488 }
489
490 $this->output( "Converting tc_time from UNIX epoch to MediaWiki timestamp... " );
491 $this->applyPatch( 'patch-tc-timestamp.sql' );
492 $this->output( "ok\n" );
493 }
494
495 protected function doCollationUpdate() {
496 global $wgCategoryCollation;
497 if ( $this->db->selectField(
498 'categorylinks',
499 'COUNT(*)',
500 'cl_collation != ' . $this->db->addQuotes( $wgCategoryCollation ),
501 __METHOD__
502 ) == 0 ) {
503 $this->output( "...collations up-to-date.\n" );
504 return;
505 }
506
507 $task = new UpdateCollation();
508 $task->execute();
509 }
510 }