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