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