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