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