3 * @addtogroup Maintenance
8 if ( !defined( 'MEDIAWIKI' ) ) {
9 echo "This file is not a valid entry point\n";
13 require_once 'convertLinks.inc';
14 require_once 'userDupes.inc';
15 require_once 'deleteDefaultMessages.php';
17 require_once( "$IP/includes/Hooks.php" );
20 * List of update functions to call on a MySQL-based MediaWiki installation,
21 * in sequence. First item is function name, rest are parameters to pass.
23 $wgMysqlUpdates = array(
25 // update_passwords obsolete
26 array( 'add_field', 'ipblocks', 'ipb_id', 'patch-ipblocks.sql' ),
27 array( 'add_field', 'ipblocks', 'ipb_expiry', 'patch-ipb_expiry.sql' ),
28 array( 'do_interwiki_update' ),
29 array( 'do_index_update' ),
30 // do_linkscc_update obsolete
31 array( 'add_table', 'hitcounter', 'patch-hitcounter.sql' ),
32 array( 'add_field', 'recentchanges', 'rc_type', 'patch-rc_type.sql' ),
35 array( 'add_field', 'user', 'user_real_name', 'patch-user-realname.sql' ),
36 array( 'add_table', 'querycache', 'patch-querycache.sql' ),
37 array( 'add_table', 'objectcache', 'patch-objectcache.sql' ),
38 array( 'add_table', 'categorylinks', 'patch-categorylinks.sql' ),
39 // do_linkscc_1_3_update obsolete
40 array( 'do_old_links_update' ),
41 array( 'add_field', 'recentchanges', 'rc_ip', 'patch-rc_ip.sql' ),
44 array( 'do_image_name_unique_update' ),
45 array( 'add_field', 'recentchanges', 'rc_id', 'patch-rc_id.sql' ),
46 array( 'add_field', 'recentchanges', 'rc_patrolled', 'patch-rc-patrol.sql' ),
47 array( 'add_table', 'logging', 'patch-logging.sql' ),
48 // do_user_rights_update obsolete
49 array( 'add_field', 'user', 'user_token', 'patch-user_token.sql' ),
50 // old, old_articleid, patch-remove-old-title-namespace.sql obsolete
51 // user_groups, patch-userlevels.sql obsolete
52 // do_group_update() obsolete
53 array( 'do_watchlist_update' ),
54 array( 'do_user_update' ),
55 // do_copy_newtalk_to_watchlist obsolete
58 array( 'do_schema_restructuring' ),
59 array( 'add_field', 'logging', 'log_params', 'patch-log_params.sql' ),
60 array( 'do_logging_encoding' ),
61 array( 'add_field', 'archive', 'ar_rev_id', 'patch-archive-rev_id.sql' ),
62 array( 'add_field', 'page', 'page_len', 'patch-page_len.sql' ),
63 array( 'do_inverse_timestamp' ),
64 array( 'do_text_id' ),
65 array( 'add_field', 'revision', 'rev_deleted', 'patch-rev_deleted.sql' ),
66 array( 'add_field', 'image', 'img_width', 'patch-img_width.sql' ),
67 array( 'add_field', 'image', 'img_metadata', 'patch-img_metadata.sql' ),
68 array( 'add_field', 'user', 'user_email_token', 'patch-user_email_token.sql' ),
69 array( 'add_field', 'archive', 'ar_text_id', 'patch-archive-text_id.sql' ),
70 array( 'do_namespace_size' ),
71 array( 'add_field', 'image', 'img_media_type', 'patch-img_media_type.sql' ),
72 array( 'do_pagelinks_update' ),
73 array( 'do_drop_img_type' ),
74 array( 'do_user_unique_update' ),
75 array( 'do_user_groups_update' ),
76 array( 'add_field', 'site_stats', 'ss_total_pages', 'patch-ss_total_articles.sql' ),
77 array( 'add_table', 'user_newtalk', 'patch-usernewtalk2.sql' ),
78 array( 'add_table', 'transcache', 'patch-transcache.sql' ),
79 array( 'add_field', 'interwiki', 'iw_trans', 'patch-interwiki-trans.sql' ),
80 array( 'add_table', 'trackbacks', 'patch-trackbacks.sql' ),
83 array( 'do_watchlist_null' ),
84 // do_image_index_update obsolete
85 array( 'do_logging_timestamp_index' ),
86 array( 'add_field', 'ipblocks', 'ipb_range_start', 'patch-ipb_range_start.sql' ),
87 array( 'do_page_random_update' ),
88 array( 'add_field', 'user', 'user_registration','patch-user_registration.sql' ),
89 array( 'do_templatelinks_update' ),
90 array( 'add_table', 'externallinks', 'patch-externallinks.sql' ),
91 array( 'add_table', 'job', 'patch-job.sql' ),
92 array( 'add_field', 'site_stats', 'ss_images', 'patch-ss_images.sql' ),
93 array( 'add_table', 'langlinks', 'patch-langlinks.sql' ),
94 array( 'add_table', 'querycache_info', 'patch-querycacheinfo.sql' ),
95 array( 'add_table', 'filearchive', 'patch-filearchive.sql' ),
96 array( 'add_field', 'ipblocks', 'ipb_anon_only', 'patch-ipb_anon_only.sql' ),
97 array( 'do_rc_indices_update' ),
100 array( 'add_field', 'user', 'user_newpass_time', 'patch-user_newpass_time.sql' ),
101 array( 'add_table', 'redirect', 'patch-redirect.sql' ),
102 array( 'add_table', 'querycachetwo', 'patch-querycachetwo.sql' ),
103 array( 'add_field', 'ipblocks', 'ipb_enable_autoblock', 'patch-ipb_optional_autoblock.sql' ),
104 array( 'do_backlinking_indices_update' ),
105 array( 'add_field', 'recentchanges', 'rc_old_len', 'patch-rc_len.sql' ),
106 array( 'add_field', 'user', 'user_editcount', 'patch-user_editcount.sql' ),
109 array( 'do_restrictions_update' ),
110 array( 'add_field', 'logging', 'log_id', 'patch-log_id.sql' ),
111 array( 'add_field', 'revision', 'rev_parent_id', 'patch-rev_parent_id.sql' ),
112 array( 'add_field', 'page_restrictions', 'pr_id', 'patch-page_restrictions_sortkey.sql' ),
113 array( 'add_field', 'revision', 'rev_len', 'patch-rev_len.sql' ),
114 array( 'add_field', 'recentchanges', 'rc_deleted', 'patch-rc_deleted.sql' ),
115 array( 'add_field', 'logging', 'log_deleted', 'patch-log_deleted.sql' ),
116 array( 'add_field', 'archive', 'ar_deleted', 'patch-ar_deleted.sql' ),
117 array( 'add_field', 'ipblocks', 'ipb_deleted', 'patch-ipb_deleted.sql' ),
118 array( 'add_field', 'filearchive', 'fa_deleted', 'patch-fa_deleted.sql' ),
119 array( 'add_field', 'archive', 'ar_len', 'patch-ar_len.sql' ),
122 array( 'add_field', 'ipblocks', 'ipb_block_email', 'patch-ipb_emailban.sql' ),
123 array( 'do_categorylinks_indices_update' ),
124 array( 'add_field', 'oldimage', 'oi_metadata', 'patch-oi_metadata.sql'),
125 array( 'do_archive_user_index' ),
126 array( 'do_image_user_index' ),
127 array( 'do_oldimage_user_index' ),
128 array( 'add_field', 'archive', 'ar_page_id', 'patch-archive-page_id.sql'),
129 array( 'add_field', 'image', 'img_sha1', 'patch-img_sha1.sql' ),
132 array( 'add_table', 'protected_titles', 'patch-protected_titles.sql' ),
135 array( 'add_field', 'ipblocks', 'ipb_by_text', 'patch-ipb_by_text.sql' ),
136 array( 'add_table', 'page_props', 'patch-page_props.sql' ),
137 array( 'add_table', 'updatelog', 'patch-updatelog.sql' ),
138 array( 'add_table', 'category', 'patch-category.sql' ),
139 array( 'do_category_population' ),
140 array( 'add_field', 'archive', 'ar_parent_id', 'patch-ar_parent_id.sql'),
141 array( 'do_populate_parent_id' ),
145 # For extensions only, should be populated via hooks
146 # $wgDBtype should be checked to specifiy the proper file
147 $wgExtNewTables = array(); // table, dir
148 $wgExtNewFields = array(); // table, column, dir
149 $wgExtPGNewFields = array(); // table, column attributes; for PostgreSQL
150 $wgExtNewIndexes = array(); // table, index, dir
152 # Helper function: check if the given key is present in the updatelog table.
153 # Obviously, only use this for updates that occur after the updatelog table was
155 function update_row_exists( $key ) {
156 $dbr = wfGetDB( DB_SLAVE );
157 $row = $dbr->selectRow(
160 array( 'ul_key' => $key ),
166 function rename_table( $from, $to, $patch ) {
168 if ( $wgDatabase->tableExists( $from ) ) {
169 if ( $wgDatabase->tableExists( $to ) ) {
170 echo "...can't move table $from to $to, $to already exists.\n";
172 echo "Moving table $from to $to...";
173 dbsource( archive($patch), $wgDatabase );
177 // Source table does not exist
178 // Renames are done before creations, so this is typical for a new installation
183 function add_table( $name, $patch, $fullpath=false ) {
185 if ( $wgDatabase->tableExists( $name ) ) {
186 echo "...$name table already exists.\n";
188 echo "Creating $name table...";
190 dbsource( $patch, $wgDatabase );
192 dbsource( archive($patch), $wgDatabase );
198 function add_field( $table, $field, $patch, $fullpath=false ) {
200 if ( !$wgDatabase->tableExists( $table ) ) {
201 echo "...$table table does not exist, skipping new field patch\n";
202 } elseif ( $wgDatabase->fieldExists( $table, $field ) ) {
203 echo "...have $field field in $table table.\n";
205 echo "Adding $field field to table $table...";
207 dbsource( $patch, $wgDatabase );
209 dbsource( archive($patch), $wgDatabase );
215 function add_index( $table, $index, $patch, $fullpath=false ) {
217 if( $wgDatabase->indexExists( $table, $index ) ) {
218 echo "...$index key already set on $table table.\n";
220 echo "Adding $index key to table $table... ";
222 dbsource( $patch, $wgDatabase );
224 dbsource( archive($patch), $wgDatabase );
230 function do_revision_updates() {
231 global $wgSoftwareRevision;
232 if ( $wgSoftwareRevision < 1001 ) {
237 function update_passwords() {
238 wfDebugDieBacktrace( "This function needs to be updated or removed.\n" );
241 $fname = "Update script: update_passwords()";
242 print "\nIt appears that you need to update the user passwords in your\n" .
243 "database. If you have already done this (if you've run this update\n" .
244 "script once before, for example), doing so again will make all your\n" .
245 "user accounts inaccessible, so be sure you only do this once.\n" .
246 "Update user passwords? (yes/no)";
248 $resp = readconsole();
249 if ( ! ( "Y" == $resp{0} || "y" == $resp{0} ) ) { return; }
251 $sql = "SELECT user_id,user_password FROM user";
252 $source = $wgDatabase->query( $sql, $fname );
254 while ( $row = $wgDatabase->fetchObject( $source ) ) {
256 $oldpass = $row->user_password;
257 $newpass = md5( "{$id}-{$oldpass}" );
259 $sql = "UPDATE user SET user_password='{$newpass}' " .
260 "WHERE user_id={$id}";
261 $wgDatabase->query( $sql, $fname );
265 function do_interwiki_update() {
266 # Check that interwiki table exists; if it doesn't source it
267 global $wgDatabase, $IP;
268 if( $wgDatabase->tableExists( "interwiki" ) ) {
269 echo "...already have interwiki table\n";
272 echo "Creating interwiki table: ";
273 dbsource( archive("patch-interwiki.sql") );
275 echo "Adding default interwiki definitions: ";
276 dbsource( "$IP/maintenance/interwiki.sql" );
280 function do_index_update() {
281 # Check that proper indexes are in place
283 $meta = $wgDatabase->fieldInfo( "recentchanges", "rc_timestamp" );
284 if( !$meta->isMultipleKey() ) {
285 echo "Updating indexes to 20031107: ";
286 dbsource( archive("patch-indexes.sql") );
290 echo "...indexes seem up to 20031107 standards\n";
294 function do_image_index_update() {
297 $meta = $wgDatabase->fieldInfo( "image", "img_major_mime" );
298 if( !$meta->isMultipleKey() ) {
299 echo "Updating indexes to 20050912: ";
300 dbsource( archive("patch-mimesearch-indexes.sql") );
304 echo "...indexes seem up to 20050912 standards\n";
308 function do_image_name_unique_update() {
310 if( $wgDatabase->indexExists( 'image', 'PRIMARY' ) ) {
311 echo "...image primary key already set.\n";
313 echo "Making img_name the primary key... ";
314 dbsource( archive("patch-image_name_primary.sql"), $wgDatabase );
319 function do_logging_timestamp_index() {
321 if( $wgDatabase->indexExists( 'logging', 'times' ) ) {
322 echo "...timestamp key on logging already exists.\n";
324 echo "Adding timestamp key on logging table... ";
325 dbsource( archive("patch-logging-times-index.sql"), $wgDatabase );
330 function do_archive_user_index() {
332 if( $wgDatabase->indexExists( 'archive', 'usertext_timestamp' ) ) {
333 echo "...usertext,timestamp key on archive already exists.\n";
335 echo "Adding usertext,timestamp key on archive table... ";
336 dbsource( archive("patch-archive-user-index.sql"), $wgDatabase );
341 function do_image_user_index() {
343 if( $wgDatabase->indexExists( 'image', 'img_usertext_timestamp' ) ) {
344 echo "...usertext,timestamp key on image already exists.\n";
346 echo "Adding usertext,timestamp key on image table... ";
347 dbsource( archive("patch-image-user-index.sql"), $wgDatabase );
352 function do_oldimage_user_index() {
354 if( $wgDatabase->indexExists( 'oldimage', 'oi_usertext_timestamp' ) ) {
355 echo "...usertext,timestamp key on oldimage already exists.\n";
357 echo "Adding usertext,timestamp key on oldimage table... ";
358 dbsource( archive("patch-oldimage-user-index.sql"), $wgDatabase );
363 function do_watchlist_update() {
365 $fname = 'do_watchlist_update';
366 if( $wgDatabase->fieldExists( 'watchlist', 'wl_notificationtimestamp' ) ) {
367 echo "The watchlist table is already set up for email notification.\n";
369 echo "Adding wl_notificationtimestamp field for email notification management.";
370 /* ALTER TABLE watchlist ADD (wl_notificationtimestamp varchar(14) binary NOT NULL default '0'); */
371 dbsource( archive( 'patch-email-notification.sql' ), $wgDatabase );
374 # Check if we need to add talk page rows to the watchlist
375 $talk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'wl_namespace & 1', $fname );
376 $nontalk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'NOT (wl_namespace & 1)', $fname );
377 if ( $talk != $nontalk ) {
378 echo "Adding missing watchlist talk page rows... ";
381 $wgDatabase->insertSelect( 'watchlist', 'watchlist',
383 'wl_user' => 'wl_user',
384 'wl_namespace' => 'wl_namespace | 1',
385 'wl_title' => 'wl_title',
386 'wl_notificationtimestamp' => 'wl_notificationtimestamp'
387 ), array( 'NOT (wl_namespace & 1)' ), $fname, 'IGNORE' );
390 echo "...watchlist talk page rows already present\n";
394 function do_copy_newtalk_to_watchlist() {
396 global $wgCommandLineMode; # this needs to be saved while getID() and getName() are called
398 $res = $wgDatabase->safeQuery( 'SELECT user_id, user_ip FROM !',
399 $wgDatabase->tableName( 'user_newtalk' ) );
400 $num_newtalks=$wgDatabase->numRows($res);
401 echo "Now converting ".$num_newtalks." user_newtalk entries to watchlist table entries ... \n";
404 for ( $i = 1; $i <= $num_newtalks; $i++ ) {
405 $wluser = $wgDatabase->fetchObject( $res );
406 if ($wluser->user_id == 0) { # anonymous users ... have IP numbers as "names"
407 if ($user->isIP($wluser->user_ip)) { # do only if it really looks like an IP number (double checked)
408 $wgDatabase->replace( 'watchlist',
409 array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
410 array('wl_user' => 0,
411 'wl_namespace' => NS_USER_TALK,
412 'wl_title' => $wluser->user_ip,
413 'wl_notificationtimestamp' => '19700101000000'
414 ), 'updaters.inc::do_watchlist_update2'
417 } else { # normal users ... have user_ids
418 $user->setID($wluser->user_id);
419 $wgDatabase->replace( 'watchlist',
420 array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
421 array('wl_user' => $user->getID(),
422 'wl_namespace' => NS_USER_TALK,
423 'wl_title' => $user->getName(),
424 'wl_notificationtimestamp' => '19700101000000'
425 ), 'updaters.inc::do_watchlist_update3'
433 function do_user_update() {
435 if( $wgDatabase->fieldExists( 'user', 'user_emailauthenticationtimestamp' ) ) {
436 echo "User table contains old email authentication field. Dropping... ";
437 dbsource( archive( 'patch-email-authentication.sql' ), $wgDatabase );
440 echo "...user table does not contain old email authentication field.\n";
445 * 1.4 betas were missing the 'binary' marker from logging.log_title,
446 * which causes a collation mismatch error on joins in MySQL 4.1.
448 function do_logging_encoding() {
449 global $wgDatabase, $wgDBtype;
450 if ($wgDBtype != 'mysql')
452 $logging = $wgDatabase->tableName( 'logging' );
453 $res = $wgDatabase->query( "SELECT log_title FROM $logging LIMIT 0" );
454 $flags = explode( ' ', mysql_field_flags( $res->result, 0 ) );
455 $wgDatabase->freeResult( $res );
457 if( in_array( 'binary', $flags ) ) {
458 echo "Logging table has correct title encoding.\n";
460 echo "Fixing title encoding on logging table... ";
461 dbsource( archive( 'patch-logging-title.sql' ), $wgDatabase );
466 function do_schema_restructuring() {
468 $fname="do_schema_restructuring";
469 if ( $wgDatabase->tableExists( 'page' ) ) {
470 echo "...page table already exists.\n";
472 echo "...converting from cur/old to page/revision/text DB structure.\n"; flush();
473 echo wfTimestamp( TS_DB );
474 echo "......checking for duplicate entries.\n"; flush();
476 list ($cur, $old, $page, $revision, $text) = $wgDatabase->tableNamesN( 'cur', 'old', 'page', 'revision', 'text' );
478 $rows = $wgDatabase->query( "SELECT cur_title, cur_namespace, COUNT(cur_namespace) AS c
479 FROM $cur GROUP BY cur_title, cur_namespace HAVING c>1", $fname );
481 if ( $wgDatabase->numRows( $rows ) > 0 ) {
482 echo wfTimestamp( TS_DB );
483 echo "......<b>Found duplicate entries</b>\n";
484 echo ( sprintf( "<b> %-60s %3s %5s</b>\n", 'Title', 'NS', 'Count' ) );
485 while ( $row = $wgDatabase->fetchObject( $rows ) ) {
486 if ( ! isset( $duplicate[$row->cur_namespace] ) ) {
487 $duplicate[$row->cur_namespace] = array();
489 $duplicate[$row->cur_namespace][] = $row->cur_title;
490 echo ( sprintf( " %-60s %3s %5s\n", $row->cur_title, $row->cur_namespace, $row->c ) );
492 $sql = "SELECT cur_title, cur_namespace, cur_id, cur_timestamp FROM $cur WHERE ";
494 foreach ( $duplicate as $ns => $titles ) {
500 $sql .= "( cur_namespace = {$ns} AND cur_title in (";
502 foreach ( $titles as $t ) {
504 $sql .= $wgDatabase->addQuotes( $t );
507 $sql .= ', ' . $wgDatabase->addQuotes( $t );
512 # By sorting descending, the most recent entry will be the first in the list.
513 # All following entries will be deleted by the next while-loop.
514 $sql .= 'ORDER BY cur_namespace, cur_title, cur_timestamp DESC';
516 $rows = $wgDatabase->query( $sql, $fname );
518 $prev_title = $prev_namespace = false;
521 while ( $row = $wgDatabase->fetchObject( $rows ) ) {
522 if ( $prev_title == $row->cur_title && $prev_namespace == $row->cur_namespace ) {
523 $deleteId[] = $row->cur_id;
525 $prev_title = $row->cur_title;
526 $prev_namespace = $row->cur_namespace;
528 $sql = "DELETE FROM $cur WHERE cur_id IN ( " . join( ',', $deleteId ) . ')';
529 $rows = $wgDatabase->query( $sql, $fname );
530 echo wfTimestamp( TS_DB );
531 echo "......<b>Deleted</b> ".$wgDatabase->affectedRows()." records.\n";
535 echo wfTimestamp( TS_DB );
536 echo "......Creating tables.\n";
537 $wgDatabase->query("CREATE TABLE $page (
538 page_id int(8) unsigned NOT NULL auto_increment,
539 page_namespace int NOT NULL,
540 page_title varchar(255) binary NOT NULL,
541 page_restrictions tinyblob NOT NULL,
542 page_counter bigint(20) unsigned NOT NULL default '0',
543 page_is_redirect tinyint(1) unsigned NOT NULL default '0',
544 page_is_new tinyint(1) unsigned NOT NULL default '0',
545 page_random real unsigned NOT NULL,
546 page_touched char(14) binary NOT NULL default '',
547 page_latest int(8) unsigned NOT NULL,
548 page_len int(8) unsigned NOT NULL,
550 PRIMARY KEY page_id (page_id),
551 UNIQUE INDEX name_title (page_namespace,page_title),
554 ) TYPE=InnoDB", $fname );
555 $wgDatabase->query("CREATE TABLE $revision (
556 rev_id int(8) unsigned NOT NULL auto_increment,
557 rev_page int(8) unsigned NOT NULL,
558 rev_comment tinyblob NOT NULL,
559 rev_user int(5) unsigned NOT NULL default '0',
560 rev_user_text varchar(255) binary NOT NULL default '',
561 rev_timestamp char(14) binary NOT NULL default '',
562 rev_minor_edit tinyint(1) unsigned NOT NULL default '0',
563 rev_deleted tinyint(1) unsigned NOT NULL default '0',
564 rev_len int(8) unsigned,
565 rev_parent_id int(8) unsigned default NULL,
566 PRIMARY KEY rev_page_id (rev_page, rev_id),
567 UNIQUE INDEX rev_id (rev_id),
568 INDEX rev_timestamp (rev_timestamp),
569 INDEX page_timestamp (rev_page,rev_timestamp),
570 INDEX user_timestamp (rev_user,rev_timestamp),
571 INDEX usertext_timestamp (rev_user_text,rev_timestamp)
572 ) TYPE=InnoDB", $fname );
574 echo wfTimestamp( TS_DB );
575 echo "......Locking tables.\n";
576 $wgDatabase->query( "LOCK TABLES $page WRITE, $revision WRITE, $old WRITE, $cur WRITE", $fname );
578 $maxold = intval( $wgDatabase->selectField( 'old', 'max(old_id)', '', $fname ) );
579 echo wfTimestamp( TS_DB );
580 echo "......maxold is {$maxold}\n";
582 echo wfTimestamp( TS_DB );
583 global $wgLegacySchemaConversion;
584 if( $wgLegacySchemaConversion ) {
585 // Create HistoryBlobCurStub entries.
586 // Text will be pulled from the leftover 'cur' table at runtime.
587 echo "......Moving metadata from cur; using blob references to text in cur table.\n";
588 $cur_text = "concat('O:18:\"historyblobcurstub\":1:{s:6:\"mCurId\";i:',cur_id,';}')";
589 $cur_flags = "'object'";
591 // Copy all cur text in immediately: this may take longer but avoids
592 // having to keep an extra table around.
593 echo "......Moving text from cur.\n";
594 $cur_text = 'cur_text';
597 $wgDatabase->query( "INSERT INTO $old (old_namespace, old_title, old_text, old_comment, old_user, old_user_text,
598 old_timestamp, old_minor_edit, old_flags)
599 SELECT cur_namespace, cur_title, $cur_text, cur_comment, cur_user, cur_user_text, cur_timestamp, cur_minor_edit, $cur_flags
600 FROM $cur", $fname );
602 echo wfTimestamp( TS_DB );
603 echo "......Setting up revision table.\n";
604 $wgDatabase->query( "INSERT INTO $revision (rev_id, rev_page, rev_comment, rev_user, rev_user_text, rev_timestamp,
606 SELECT old_id, cur_id, old_comment, old_user, old_user_text,
607 old_timestamp, old_minor_edit
608 FROM $old,$cur WHERE old_namespace=cur_namespace AND old_title=cur_title", $fname );
610 echo wfTimestamp( TS_DB );
611 echo "......Setting up page table.\n";
612 $wgDatabase->query( "INSERT INTO $page (page_id, page_namespace, page_title, page_restrictions, page_counter,
613 page_is_redirect, page_is_new, page_random, page_touched, page_latest, page_len)
614 SELECT cur_id, cur_namespace, cur_title, cur_restrictions, cur_counter, cur_is_redirect, cur_is_new,
615 cur_random, cur_touched, rev_id, LENGTH(cur_text)
617 WHERE cur_id=rev_page AND rev_timestamp=cur_timestamp AND rev_id > {$maxold}", $fname );
619 echo wfTimestamp( TS_DB );
620 echo "......Unlocking tables.\n";
621 $wgDatabase->query( "UNLOCK TABLES", $fname );
623 echo wfTimestamp( TS_DB );
624 echo "......Renaming old.\n";
625 $wgDatabase->query( "ALTER TABLE $old RENAME TO $text", $fname );
627 echo wfTimestamp( TS_DB );
632 function do_inverse_timestamp() {
634 if( $wgDatabase->fieldExists( 'revision', 'inverse_timestamp' ) ) {
635 echo "Removing revision.inverse_timestamp and fixing indexes... ";
636 dbsource( archive( 'patch-inverse_timestamp.sql' ), $wgDatabase );
639 echo "revision timestamp indexes already up to 2005-03-13\n";
643 function do_text_id() {
645 if( $wgDatabase->fieldExists( 'revision', 'rev_text_id' ) ) {
646 echo "...rev_text_id already in place.\n";
648 echo "Adding rev_text_id field... ";
649 dbsource( archive( 'patch-rev_text_id.sql' ), $wgDatabase );
654 function do_namespace_size() {
658 'recentchanges' => 'rc',
660 'querycache' => 'qc',
663 foreach( $tables as $table => $prefix ) {
664 do_namespace_size_on( $table, $prefix );
669 function do_namespace_size_on( $table, $prefix ) {
670 global $wgDatabase, $wgDBtype;
671 if ($wgDBtype != 'mysql')
673 $field = $prefix . '_namespace';
675 $tablename = $wgDatabase->tableName( $table );
676 $result = $wgDatabase->query( "SHOW COLUMNS FROM $tablename LIKE '$field'" );
677 $info = $wgDatabase->fetchObject( $result );
678 $wgDatabase->freeResult( $result );
680 if( substr( $info->Type, 0, 3 ) == 'int' ) {
681 echo "...$field is already a full int ($info->Type).\n";
683 echo "Promoting $field from $info->Type to int... ";
685 $sql = "ALTER TABLE $tablename MODIFY $field int NOT NULL";
686 $wgDatabase->query( $sql );
692 function do_pagelinks_update() {
694 if( $wgDatabase->tableExists( 'pagelinks' ) ) {
695 echo "...already have pagelinks table.\n";
697 echo "Converting links and brokenlinks tables to pagelinks... ";
698 dbsource( archive( 'patch-pagelinks.sql' ), $wgDatabase );
702 global $wgCanonicalNamespaceNames;
703 foreach( $wgCanonicalNamespaceNames as $ns => $name ) {
705 do_pagelinks_namespace( $ns );
711 function do_pagelinks_namespace( $namespace ) {
712 global $wgDatabase, $wgContLang;
714 $ns = intval( $namespace );
715 echo "Cleaning up broken links for namespace $ns... ";
717 $pagelinks = $wgDatabase->tableName( 'pagelinks' );
718 $name = $wgContLang->getNsText( $ns );
719 $prefix = $wgDatabase->strencode( $name );
720 $likeprefix = str_replace( '_', '\\_', $prefix);
722 $sql = "UPDATE $pagelinks
723 SET pl_namespace=$ns,
724 pl_title=TRIM(LEADING '$prefix:' FROM pl_title)
726 AND pl_title LIKE '$likeprefix:%'";
728 $wgDatabase->query( $sql, 'do_pagelinks_namespace' );
732 function do_drop_img_type() {
735 if( $wgDatabase->fieldExists( 'image', 'img_type' ) ) {
736 echo "Dropping unused img_type field in image table... ";
737 dbsource( archive( 'patch-drop_img_type.sql' ), $wgDatabase );
740 echo "No img_type field in image table; Good.\n";
744 function do_old_links_update() {
746 if( $wgDatabase->tableExists( 'pagelinks' ) ) {
747 echo "Already have pagelinks; skipping old links table updates.\n";
749 convertLinks(); flush();
753 function do_user_unique_update() {
755 $duper = new UserDupes( $wgDatabase );
756 if( $duper->hasUniqueIndex() ) {
757 echo "Already have unique user_name index.\n";
759 if( !$duper->clearDupes() ) {
760 echo "WARNING: This next step will probably fail due to unfixed duplicates...\n";
762 echo "Adding unique index on user_name... ";
763 dbsource( archive( 'patch-user_nameindex.sql' ), $wgDatabase );
768 function do_user_groups_update() {
769 $fname = 'do_user_groups_update';
772 if( $wgDatabase->tableExists( 'user_groups' ) ) {
773 echo "...user_groups table already exists.\n";
774 return do_user_groups_reformat();
777 echo "Adding user_groups table... ";
778 dbsource( archive( 'patch-user_groups.sql' ), $wgDatabase );
781 if( !$wgDatabase->tableExists( 'user_rights' ) ) {
782 if( $wgDatabase->fieldExists( 'user', 'user_rights' ) ) {
783 echo "Upgrading from a 1.3 or older database? Breaking out user_rights for conversion...";
784 dbsource( archive( 'patch-user_rights.sql' ), $wgDatabase );
787 echo "*** WARNING: couldn't locate user_rights table or field for upgrade.\n";
788 echo "*** You may need to manually configure some sysops by manipulating\n";
789 echo "*** the user_groups table.\n";
794 echo "Converting user_rights table to user_groups... ";
795 $result = $wgDatabase->select( 'user_rights',
796 array( 'ur_user', 'ur_rights' ),
797 array( "ur_rights != ''" ),
800 while( $row = $wgDatabase->fetchObject( $result ) ) {
801 $groups = array_unique(
803 explode( ',', $row->ur_rights ) ) );
805 foreach( $groups as $group ) {
806 $wgDatabase->insert( 'user_groups',
808 'ug_user' => $row->ur_user,
809 'ug_group' => $group ),
813 $wgDatabase->freeResult( $result );
817 function do_user_groups_reformat() {
818 # Check for bogus formats from previous 1.5 alpha code.
820 $info = $wgDatabase->fieldInfo( 'user_groups', 'ug_group' );
822 if( $info->type() == 'int' ) {
823 $oldug = $wgDatabase->tableName( 'user_groups' );
824 $newug = $wgDatabase->tableName( 'user_groups_bogus' );
825 echo "user_groups is in bogus intermediate format. Renaming to $newug... ";
826 $wgDatabase->query( "ALTER TABLE $oldug RENAME TO $newug" );
829 echo "Re-adding fresh user_groups table... ";
830 dbsource( archive( 'patch-user_groups.sql' ), $wgDatabase );
834 echo "*** WARNING: You will need to manually fix up user permissions in the user_groups\n";
835 echo "*** table. Old 1.5 alpha versions did some pretty funky stuff...\n";
838 echo "...user_groups is in current format.\n";
843 function do_watchlist_null() {
844 # Make sure wl_notificationtimestamp can be NULL,
845 # and update old broken items.
847 $info = $wgDatabase->fieldInfo( 'watchlist', 'wl_notificationtimestamp' );
849 if( !$info->nullable() ) {
850 echo "Making wl_notificationtimestamp nullable... ";
851 dbsource( archive( 'patch-watchlist-null.sql' ), $wgDatabase );
854 echo "...wl_notificationtimestamp is already nullable.\n";
862 function do_page_random_update() {
865 echo "Setting page_random to a random value on rows where it equals 0...";
867 $page = $wgDatabase->tableName( 'page' );
868 $wgDatabase->query( "UPDATE $page SET page_random = RAND() WHERE page_random = 0", 'do_page_random_update' );
869 $rows = $wgDatabase->affectedRows();
871 echo "changed $rows rows\n";
874 function do_templatelinks_update() {
875 global $wgDatabase, $wgLoadBalancer;
876 $fname = 'do_templatelinks_update';
878 if ( $wgDatabase->tableExists( 'templatelinks' ) ) {
879 echo "...templatelinks table already exists\n";
882 echo "Creating templatelinks table...\n";
883 dbsource( archive('patch-templatelinks.sql'), $wgDatabase );
884 echo "Populating...\n";
885 if ( isset( $wgLoadBalancer ) && $wgLoadBalancer->getServerCount() > 1 ) {
886 // Slow, replication-friendly update
887 $res = $wgDatabase->select( 'pagelinks', array( 'pl_from', 'pl_namespace', 'pl_title' ),
888 array( 'pl_namespace' => NS_TEMPLATE ), $fname );
890 while ( $row = $wgDatabase->fetchObject( $res ) ) {
891 $count = ($count + 1) % 100;
893 if ( function_exists( 'wfWaitForSlaves' ) ) {
894 wfWaitForSlaves( 10 );
899 $wgDatabase->insert( 'templatelinks',
901 'tl_from' => $row->pl_from,
902 'tl_namespace' => $row->pl_namespace,
903 'tl_title' => $row->pl_title,
908 $wgDatabase->freeResult( $res );
911 $wgDatabase->insertSelect( 'templatelinks', 'pagelinks',
913 'tl_from' => 'pl_from',
914 'tl_namespace' => 'pl_namespace',
915 'tl_title' => 'pl_title'
921 echo "Done. Please run maintenance/refreshLinks.php for a more thorough templatelinks update.\n";
924 // Add index on ( rc_namespace, rc_user_text ) [Jul. 2006]
925 // Add index on ( rc_user_text, rc_timestamp ) [Nov. 2006]
926 function do_rc_indices_update() {
928 echo( "Checking for additional recent changes indices...\n" );
931 'rc_ns_usertext' => 'patch-recentchanges-utindex.sql',
932 'rc_user_text' => 'patch-rc_user_text-index.sql',
935 foreach( $indexes as $index => $patch ) {
936 $info = $wgDatabase->indexInfo( 'recentchanges', $index, __METHOD__ );
938 echo( "...index `{$index}` not found; adding..." );
939 dbsource( archive( $patch ) );
942 echo( "...index `{$index}` seems ok.\n" );
947 function index_has_field($table, $index, $field) {
949 echo( "Checking if $table index $index includes field $field...\n" );
950 $info = $wgDatabase->indexInfo( $table, $index, __METHOD__ );
952 foreach($info as $row) {
953 if($row->Column_name == $field) {
954 echo( "...index $index on table $table seems to be ok\n" );
959 echo( "...index $index on table $table has no field $field; adding\n" );
963 function do_backlinking_indices_update() {
964 echo( "Checking for backlinking indices...\n" );
965 if (!index_has_field('pagelinks', 'pl_namespace', 'pl_from') ||
966 !index_has_field('templatelinks', 'tl_namespace', 'tl_from') ||
967 !index_has_field('imagelinks', 'il_to', 'il_from'))
969 dbsource( archive( 'patch-backlinkindexes.sql' ) );
973 function do_categorylinks_indices_update() {
974 echo( "Checking for categorylinks indices...\n" );
975 if (!index_has_field('categorylinks', 'cl_sortkey', 'cl_from'))
977 dbsource( archive( 'patch-categorylinksindex.sql' ) );
981 function do_stats_init() {
982 // Sometimes site_stats table is not properly populated.
984 echo "Checking site_stats row...";
985 $row = $wgDatabase->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
986 if( $row === false ) {
987 echo "data is missing! rebuilding...\n";
990 require_once "$IP/maintenance/initStats.inc";
997 function purge_cache() {
999 # We can't guarantee that the user will be able to use TRUNCATE,
1000 # but we know that DELETE is available to us
1001 echo( "Purging caches..." );
1002 $wgDatabase->delete( 'objectcache', '*', __METHOD__ );
1006 function do_all_updates( $shared = false, $purge = true ) {
1007 global $wgNewTables, $wgNewFields, $wgRenamedTables, $wgSharedDB, $wgDatabase, $wgDBtype, $IP;
1009 wfRunHooks('LoadExtensionSchemaUpdates');
1011 $doUser = !$wgSharedDB || $shared;
1013 if ($wgDBtype === 'postgres') {
1014 do_postgres_updates();
1018 # Run core updates in sequence...
1019 global $wgMysqlUpdates;
1020 foreach( $wgMysqlUpdates as $params ) {
1021 $func = array_shift( $params );
1022 call_user_func_array( $func, $params );
1026 /// @fixme clean up this mess too!
1027 global $wgExtNewTables, $wgExtNewFields, $wgExtNewIndexes;
1028 # Add missing extension tables
1029 foreach ( $wgExtNewTables as $tableRecord ) {
1030 add_table( $tableRecord[0], $tableRecord[1], true );
1033 # Add missing extension fields
1034 foreach ( $wgExtNewFields as $fieldRecord ) {
1035 if ( $fieldRecord[0] != 'user' || $doUser ) {
1036 add_field( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true );
1040 # Add missing extension indexes
1041 foreach ( $wgExtNewIndexes as $fieldRecord ) {
1042 add_index( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true );
1047 echo "Deleting old default messages (this may take a long time!)..."; flush();
1048 deleteDefaultMessages();
1049 echo "Done\n"; flush();
1051 do_stats_init(); flush();
1059 function archive($name) {
1060 global $wgDBtype, $IP;
1061 switch ($wgDBtype) {
1063 return "$IP/maintenance/postgres/archives/$name";
1065 return "$IP/maintenance/archives/$name";
1069 function do_restrictions_update() {
1070 # Adding page_restrictions table, obsoleting page.page_restrictions.
1071 # Migrating old restrictions to new table
1072 # -- Andrew Garrett, January 2007.
1076 $name = 'page_restrictions';
1077 $patch = 'patch-page_restrictions.sql';
1078 $patch2 = 'patch-page_restrictions_sortkey.sql';
1080 if ( $wgDatabase->tableExists( $name ) ) {
1081 echo "...$name table already exists.\n";
1083 echo "Creating $name table...";
1084 dbsource( archive($patch), $wgDatabase );
1085 dbsource( archive($patch2), $wgDatabase );
1088 echo "Migrating old restrictions to new table...";
1090 $res = $wgDatabase->select( 'page', array( 'page_id', 'page_restrictions' ), array("page_restrictions!=''", "page_restrictions!='edit=:move='"), __METHOD__ );
1094 while ($row = $wgDatabase->fetchObject($res) ) {
1095 $count = ($count + 1) % 100;
1098 if ( function_exists( 'wfWaitForSlaves' ) ) {
1099 wfWaitForSlaves( 10 );
1105 # Figure out what the restrictions are..
1106 $id = $row->page_id;
1107 $flatrestrictions = explode( ':', $row->page_restrictions );
1109 $restrictions = array ();
1110 foreach( $flatrestrictions as $restriction ) {
1111 $thisrestriction = explode( '=', $restriction, 2 );
1112 if( count( $thisrestriction ) == 1 ) {
1113 // Compatibility with old protections from before
1114 // separate move protection was added.
1115 list( $level ) = $thisrestriction;
1117 $restrictions['edit'] = $level;
1118 $restrictions['move'] = $level;
1121 list( $type, $level ) = $thisrestriction;
1123 $restrictions[$type] = $level;
1127 $wgDatabase->update( 'page', array ( 'page_restrictions' => ''), array( 'page_id' => $id ), __METHOD__ );
1131 foreach( $restrictions as $type => $level ) {
1132 $wgDatabase->insert( 'page_restrictions', array ( 'pr_page' => $id,
1134 'pr_level' => $level,
1136 'pr_expiry' => 'infinity' ),
1144 function do_category_population() {
1145 if( update_row_exists( 'populate category' ) ) {
1146 echo "...category table already populated.\n";
1149 require_once( 'populateCategory.inc' );
1150 echo "Populating category table, printing progress markers. ".
1151 "For large databases, you\n".
1152 "may want to hit Ctrl-C and do this manually with maintenance/\n".
1153 "populateCategory.php.\n";
1154 populateCategory( '', 10, 0, true );
1155 echo "Done populating category table.\n";
1158 function do_populate_parent_id() {
1159 if( update_row_exists( 'populate rev_parent_id' ) ) {
1160 echo "...rev_parent_id column already populated.\n";
1163 require_once( 'populateParentId.php' );
1167 pg_describe_table($table)
1169 global $wgDatabase, $wgDBmwschema;
1171 SELECT attname, attnum FROM pg_namespace, pg_class, pg_attribute
1172 WHERE pg_class.relnamespace = pg_namespace.oid
1173 AND attrelid=pg_class.oid AND attnum > 0
1174 AND relname=%s AND nspname=%s
1176 $res = $wgDatabase->query(sprintf($q,
1177 $wgDatabase->addQuotes($table),
1178 $wgDatabase->addQuotes($wgDBmwschema)));
1183 while ($r = $wgDatabase->fetchRow($res)) {
1193 pg_describe_index($idx)
1195 global $wgDatabase, $wgDBmwschema;
1197 // first fetch the key (which is a list of columns ords) and
1198 // the table the index applies to (an oid)
1200 SELECT indkey, indrelid FROM pg_namespace, pg_class, pg_index
1202 AND pg_class.relnamespace = pg_namespace.oid
1204 AND indexrelid=pg_class.oid
1206 $res = $wgDatabase->query(sprintf($q,
1207 $wgDatabase->addQuotes($wgDBmwschema),
1208 $wgDatabase->addQuotes($idx)));
1211 if (!($r = $wgDatabase->fetchRow($res))) {
1212 $wgDatabase->freeResult($res);
1217 $relid = intval($r[1]);
1218 $indkeys = explode(" ", $indkey);
1219 $wgDatabase->freeResult($res);
1221 $colnames = array();
1222 foreach ($indkeys as $rid) {
1224 SELECT attname FROM pg_class, pg_attribute
1225 WHERE attrelid=$relid
1227 AND attrelid=pg_class.oid
1229 $r2 = $wgDatabase->query(sprintf($query, $rid));
1232 if (!($row2 = $wgDatabase->fetchRow($r2))) {
1233 $wgDatabase->freeResult($r2);
1236 $colnames[] = $row2[0];
1237 $wgDatabase->freeResult($r2);
1244 pg_index_exists($table, $index)
1246 global $wgDatabase, $wgDBmwschema;
1247 $exists = $wgDatabase->selectField("pg_indexes", "indexname",
1248 array( "indexname" => $index,
1249 "tablename" => $table,
1250 "schemaname" => $wgDBmwschema));
1251 return $exists === $index;
1255 pg_fkey_deltype($fkey)
1257 global $wgDatabase, $wgDBmwschema;
1259 SELECT confdeltype FROM pg_constraint, pg_namespace
1260 WHERE connamespace=pg_namespace.oid
1264 $r = $wgDatabase->query(sprintf($q,
1265 $wgDatabase->addQuotes($wgDBmwschema),
1266 $wgDatabase->addQuotes($fkey)));
1267 if (!($row = $wgDatabase->fetchRow($r)))
1273 pg_rule_def($table, $rule)
1275 global $wgDatabase, $wgDBmwschema;
1277 SELECT definition FROM pg_rules
1278 WHERE schemaname = %s
1282 $r = $wgDatabase->query(sprintf($q,
1283 $wgDatabase->addQuotes($wgDBmwschema),
1284 $wgDatabase->addQuotes($table),
1285 $wgDatabase->addQuotes($rule)));
1286 $row = $wgDatabase->fetchRow($r);
1290 $wgDatabase->freeResult($r);
1294 function do_postgres_updates() {
1295 global $wgDatabase, $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgShowExceptionDetails, $wgDBuser;
1297 ## Gather version numbers in case we need them
1298 $version = $wgDatabase->getServerVersion(); ## long string
1299 $numver = $wgDatabase->numeric_version; ## X.Y e.g. 8.3
1301 $wgShowExceptionDetails = 1;
1303 # Just in case their LocalSettings.php does not have this:
1304 if ( !isset( $wgDBmwschema ))
1305 $wgDBmwschema = 'mediawiki';
1307 # Verify that this user is configured correctly
1308 $safeuser = $wgDatabase->addQuotes($wgDBuser);
1309 $SQL = "SELECT array_to_string(useconfig,'*') FROM pg_catalog.pg_user WHERE usename = $safeuser";
1310 $config = pg_fetch_result( $wgDatabase->doQuery( $SQL ), 0, 0 );
1312 foreach( explode( '*', $config ) as $c ) {
1313 list( $x,$y ) = explode( '=', $c );
1316 if( !array_key_exists( 'search_path', $conf ) ) {
1320 $search_path = $conf['search_path'];
1322 if( strpos( $search_path, $wgDBmwschema ) === false ) {
1323 echo "Adding in schema \"$wgDBmwschema\" to search_path for user \"$wgDBuser\"\n";
1324 $search_path = "$wgDBmwschema, $search_path";
1326 if( strpos( $search_path, $wgDBts2schema ) === false ) {
1327 echo "Adding in schema \"$wgDBts2schema\" to search_path for user \"$wgDBuser\"\n";
1328 $search_path = "$search_path, $wgDBts2schema";
1330 if( array_key_exists( 'search_path', $conf ) === false || $search_path != $conf['search_path'] ) {
1331 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET search_path = $search_path" );
1332 $wgDatabase->doQuery( "SET search_path = $search_path" );
1335 $path = $conf['search_path'];
1336 echo "... search_path for user \"$wgDBuser\" looks correct ($path)\n";
1339 'client_min_messages' => 'error',
1340 'DateStyle' => 'ISO, YMD',
1343 foreach( array_keys( $goodconf ) AS $key ) {
1344 $value = $goodconf[$key];
1345 if( !array_key_exists( $key, $conf ) or $conf[$key] !== $value ) {
1346 echo "Setting $key to '$value' for user \"$wgDBuser\"\n";
1347 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET $key = '$value'" );
1348 $wgDatabase->doQuery( "SET $key = '$value'" );
1351 echo "... default value of \"$key\" is correctly set to \"$value\" for user \"$wgDBuser\"\n";
1355 $newsequences = array(
1361 array("category", "patch-category.sql"),
1362 array("mediawiki_version", "patch-mediawiki_version.sql"),
1363 array("mwuser", "patch-mwuser.sql"),
1364 array("pagecontent", "patch-pagecontent.sql"),
1365 array("querycachetwo", "patch-querycachetwo.sql"),
1366 array("page_props", "patch-page_props.sql"),
1367 array("page_restrictions", "patch-page_restrictions.sql"),
1368 array("profiling", "patch-profiling.sql"),
1369 array("protected_titles", "patch-protected_titles.sql"),
1370 array("redirect", "patch-redirect.sql"),
1371 array("updatelog", "patch-updatelog.sql"),
1375 array("archive", "ar_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1376 array("archive", "ar_len", "INTEGER"),
1377 array("archive", "ar_page_id", "INTEGER"),
1378 array("archive", "ar_parent_id", "INTEGER"),
1379 array("image", "img_sha1", "TEXT NOT NULL DEFAULT ''"),
1380 array("ipblocks", "ipb_anon_only", "CHAR NOT NULL DEFAULT '0'"),
1381 array("ipblocks", "ipb_by_text", "TEXT NOT NULL DEFAULT ''"),
1382 array("ipblocks", "ipb_block_email", "CHAR NOT NULL DEFAULT '0'"),
1383 array("ipblocks", "ipb_create_account", "CHAR NOT NULL DEFAULT '1'"),
1384 array("ipblocks", "ipb_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1385 array("ipblocks", "ipb_enable_autoblock", "CHAR NOT NULL DEFAULT '1'"),
1386 array("filearchive", "fa_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1387 array("logging", "log_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1388 array("logging", "log_id", "INTEGER NOT NULL PRIMARY KEY DEFAULT nextval('log_log_id_seq')"),
1389 array("logging", "log_params", "TEXT"),
1390 array("mwuser", "user_editcount", "INTEGER"),
1391 array("mwuser", "user_newpass_time", "TIMESTAMPTZ"),
1392 array("oldimage", "oi_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1393 array("oldimage", "oi_metadata", "BYTEA NOT NULL DEFAULT ''"),
1394 array("oldimage", "oi_media_type", "TEXT"),
1395 array("oldimage", "oi_major_mime", "TEXT NOT NULL DEFAULT 'unknown'"),
1396 array("oldimage", "oi_minor_mime", "TEXT NOT NULL DEFAULT 'unknown'"),
1397 array("oldimage", "oi_sha1", "TEXT NOT NULL DEFAULT ''"),
1398 array("page_restrictions", "pr_id", "INTEGER NOT NULL UNIQUE DEFAULT nextval('pr_id_val')"),
1399 array("recentchanges", "rc_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1400 array("recentchanges", "rc_log_action", "TEXT"),
1401 array("recentchanges", "rc_log_type", "TEXT"),
1402 array("recentchanges", "rc_logid", "INTEGER NOT NULL DEFAULT 0"),
1403 array("recentchanges", "rc_new_len", "INTEGER"),
1404 array("recentchanges", "rc_old_len", "INTEGER"),
1405 array("recentchanges", "rc_params", "TEXT"),
1406 array("revision", "rev_len", "INTEGER"),
1407 array("revision", "rev_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1411 # table, column, desired type, USING clause if needed (with new default if needed)
1412 $typechanges = array(
1413 array("archive", "ar_deleted", "smallint", ""),
1414 array("archive", "ar_minor_edit", "smallint", "ar_minor_edit::smallint DEFAULT 0"),
1415 array("filearchive", "fa_deleted", "smallint", ""),
1416 array("filearchive", "fa_height", "integer", ""),
1417 array("filearchive", "fa_metadata", "bytea", "decode(fa_metadata,'escape')"),
1418 array("filearchive", "fa_size", "integer", ""),
1419 array("filearchive", "fa_width", "integer", ""),
1420 array("filearchive", "fa_storage_group","text", ""),
1421 array("filearchive", "fa_storage_key", "text", ""),
1422 array("image", "img_metadata", "bytea", "decode(img_metadata,'escape')"),
1423 array("image", "img_size", "integer", ""),
1424 array("image", "img_width", "integer", ""),
1425 array("image", "img_height", "integer", ""),
1426 array("interwiki", "iw_local", "smallint", "iw_local::smallint DEFAULT 0"),
1427 array("interwiki", "iw_trans", "smallint", "iw_trans::smallint DEFAULT 0"),
1428 array("ipblocks", "ipb_auto", "smallint", "ipb_auto::smallint DEFAULT 0"),
1429 array("ipblocks", "ipb_anon_only", "smallint", "ipb_anon_only::smallint DEFAULT 0"),
1430 array("ipblocks", "ipb_create_account", "smallint", "ipb_create_account::smallint DEFAULT 1"),
1431 array("ipblocks", "ipb_enable_autoblock", "smallint", "ipb_enable_autoblock::smallint DEFAULT 1"),
1432 array("ipblocks", "ipb_block_email", "smallint", "ipb_block_email::smallint DEFAULT 0"),
1433 array("ipblocks", "ipb_address", "text", "ipb_address::text"),
1434 array("ipblocks", "ipb_deleted", "smallint", "ipb_deleted::smallint"),
1435 array("math", "math_inputhash", "bytea", "decode(math_inputhash,'escape')"),
1436 array("math", "math_outputhash", "bytea", "decode(math_outputhash,'escape')"),
1437 array("mwuser", "user_token", "text", ""),
1438 array("mwuser", "user_email_token","text", ""),
1439 array("objectcache", "keyname", "text", ""),
1440 array("oldimage", "oi_height", "integer", ""),
1441 array("oldimage", "oi_size", "integer", ""),
1442 array("oldimage", "oi_width", "integer", ""),
1443 array("page", "page_is_redirect","smallint", "page_is_redirect::smallint DEFAULT 0"),
1444 array("page", "page_is_new", "smallint", "page_is_new::smallint DEFAULT 0"),
1445 array("querycache", "qc_value", "integer", ""),
1446 array("querycachetwo","qcc_value", "integer", ""),
1447 array("recentchanges","rc_bot", "smallint", "rc_bot::smallint DEFAULT 0"),
1448 array("recentchanges","rc_deleted", "smallint", ""),
1449 array("recentchanges","rc_minor", "smallint", "rc_minor::smallint DEFAULT 0"),
1450 array("recentchanges","rc_new", "smallint", "rc_new::smallint DEFAULT 0"),
1451 array("recentchanges","rc_type", "smallint", "rc_type::smallint DEFAULT 0"),
1452 array("recentchanges","rc_patrolled", "smallint", "rc_patrolled::smallint DEFAULT 0"),
1453 array("revision", "rev_minor_edit", "smallint", "rev_minor_edit::smallint DEFAULT 0"),
1454 array("templatelinks","tl_namespace", "smallint", "tl_namespace::smallint"),
1455 array("user_newtalk", "user_ip", "text", "host(user_ip)"),
1458 $newindexes = array(
1459 array("archive", "archive_user_text", "(ar_user_text)"),
1460 array("image", "img_sha1", "(img_sha1)"),
1461 array("oldimage", "oi_sha1", "(oi_sha1)"),
1462 array("revision", "rev_text_id_idx", "(rev_text_id)"),
1468 foreach ($newsequences as $ns) {
1469 if ($wgDatabase->sequenceExists($ns)) {
1470 echo "... sequence \"$ns\" already exists\n";
1474 echo "Creating sequence \"$ns\"\n";
1475 $wgDatabase->query("CREATE SEQUENCE $ns");
1478 foreach ($newtables as $nt) {
1479 if ($wgDatabase->tableExists($nt[0])) {
1480 echo "... table \"$nt[0]\" already exists\n";
1484 echo "Creating table \"$nt[0]\"\n";
1485 dbsource(archive($nt[1]));
1488 ## Needed before newcols
1489 if ($wgDatabase->tableExists("archive2")) {
1490 echo "Converting \"archive2\" back to normal archive table\n";
1491 if ($wgDatabase->ruleExists("archive", "archive_insert")) {
1492 echo "Dropping rule \"archive_insert\"\n";
1493 $wgDatabase->query("DROP RULE archive_insert ON archive");
1495 if ($wgDatabase->ruleExists("archive", "archive_delete")) {
1496 echo "Dropping rule \"archive_delete\"\n";
1497 $wgDatabase->query("DROP RULE archive_delete ON archive");
1499 dbsource(archive("patch-remove-archive2.sql"));
1502 echo "... obsolete table \"archive2\" does not exist\n";
1504 foreach ($newcols as $nc) {
1505 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1506 if (!is_null($fi)) {
1507 echo "... column \"$nc[0].$nc[1]\" already exists\n";
1511 echo "Adding column \"$nc[0].$nc[1]\"\n";
1512 $wgDatabase->query("ALTER TABLE $nc[0] ADD $nc[1] $nc[2]");
1515 foreach ($typechanges as $tc) {
1516 $fi = $wgDatabase->fieldInfo($tc[0], $tc[1]);
1518 echo "... error: expected column $tc[0].$tc[1] to exist\n";
1522 if ($fi->type() === $tc[2])
1523 echo "... column \"$tc[0].$tc[1]\" is already of type \"$tc[2]\"\n";
1525 echo "Changing column type of \"$tc[0].$tc[1]\" from \"{$fi->type()}\" to \"$tc[2]\"\n";
1526 $sql = "ALTER TABLE $tc[0] ALTER $tc[1] TYPE $tc[2]";
1527 if (strlen($tc[3])) {
1529 if (preg_match( '/DEFAULT (.+)/', $tc[3], $default)) {
1530 $sqldef = "ALTER TABLE $tc[0] ALTER $tc[1] SET DEFAULT $default[1]";
1531 $wgDatabase->query($sqldef);
1532 $tc[3] = preg_replace( '/\s*DEFAULT .+/', '', $tc[3]);
1534 $sql .= " USING $tc[3]";
1536 $sql .= ";\nCOMMIT;\n";
1537 $wgDatabase->query($sql);
1541 if ($wgDatabase->fieldInfo('oldimage','oi_deleted')->type() !== 'smallint') {
1542 echo "Changing \"oldimage.oi_deleted\" to type \"smallint\"\n";
1543 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted DROP DEFAULT" );
1544 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted TYPE SMALLINT USING (oi_deleted::smallint)" );
1545 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted SET DEFAULT 0" );
1548 echo "... column \"oldimage.oi_deleted\" is already of type \"smallint\"\n";
1551 foreach ($newindexes as $ni) {
1552 if (pg_index_exists($ni[0], $ni[1])) {
1553 echo "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n";
1556 echo "Creating index \"$ni[1]\" on table \"$ni[0]\" $ni[2]\n";
1557 $wgDatabase->query( "CREATE INDEX $ni[1] ON $ni[0] $ni[2]" );
1560 foreach ($newrules as $nr) {
1561 if ($wgDatabase->ruleExists($nr[0], $nr[1])) {
1562 echo "... rule \"$nr[1]\" on table \"$nr[0]\" already exists\n";
1565 echo "Adding rule \"$nr[1]\" to table \"$nr[0]\"\n";
1566 dbsource(archive($nr[2]));
1569 if ($wgDatabase->hasConstraint("oldimage_oi_name_fkey")) {
1570 echo "Making foriegn key on table \"oldimage\" (to image) a cascade delete\n";
1571 $wgDatabase->query( "ALTER TABLE oldimage DROP CONSTRAINT oldimage_oi_name_fkey" );
1572 $wgDatabase->query( "ALTER TABLE oldimage ADD CONSTRAINT oldimage_oi_name_fkey_cascade ".
1573 "FOREIGN KEY (oi_name) REFERENCES image(img_name) ON DELETE CASCADE" );
1576 echo "... table \"oldimage\" has correct cascade delete foreign key to image\n";
1578 if (!$wgDatabase->triggerExists("page", "page_deleted")) {
1579 echo "Adding function and trigger \"page_deleted\" to table \"page\"\n";
1580 dbsource(archive('patch-page_deleted.sql'));
1583 echo "... table \"page\" has \"page_deleted\" trigger\n";
1585 $fi = $wgDatabase->fieldInfo("recentchanges", "rc_cur_id");
1586 if (!$fi->nullable()) {
1587 echo "Removing NOT NULL constraint from \"recentchanges.rc_cur_id\"\n";
1588 dbsource(archive('patch-rc_cur_id-not-null.sql'));
1591 echo "... column \"recentchanges.rc_cur_id\" has a NOT NULL constraint\n";
1593 $pu = pg_describe_index("pagelink_unique");
1594 if (!is_null($pu) && ($pu[0] != "pl_from" || $pu[1] != "pl_namespace" || $pu[2] != "pl_title")) {
1595 echo "Dropping obsolete version of index \"pagelink_unique index\"\n";
1596 $wgDatabase->query("DROP INDEX pagelink_unique");
1600 echo "... obsolete version of index \"pagelink_unique index\" does not exist\n";
1603 echo "Creating index \"pagelink_unique index\"\n";
1604 $wgDatabase->query("CREATE UNIQUE INDEX pagelink_unique ON pagelinks (pl_from,pl_namespace,pl_title)");
1607 echo "... index \"pagelink_unique_index\" aready exists\n";
1609 if (pg_fkey_deltype("revision_rev_user_fkey") == 'r') {
1610 echo "... constraint \"revision_rev_user_fkey\" is ON DELETE RESTRICT\n";
1613 echo "Changing constraint \"revision_rev_user_fkey\" to ON DELETE RESTRICT\n";
1614 dbsource(archive('patch-revision_rev_user_fkey.sql'));
1617 global $wgExtNewTables, $wgExtPGNewFields, $wgExtNewIndexes;
1618 # Add missing extension tables
1619 foreach ( $wgExtNewTables as $nt ) {
1620 if ($wgDatabase->tableExists($nt[0])) {
1621 echo "... table \"$nt[0]\" already exists\n";
1624 echo "Creating table \"$nt[0]\"\n";
1627 # Add missing extension fields
1628 foreach ( $wgExtPGNewFields as $nc ) {
1629 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1630 if (!is_null($fi)) {
1631 echo "... column \"$nc[0].$nc[1]\" already exists\n";
1634 echo "Adding column \"$nc[0].$nc[1]\"\n";
1635 $wgDatabase->query( "ALTER TABLE $nc[0] ADD $nc[1] $nc[2]" );
1637 # Add missing extension indexes
1638 foreach ( $wgExtNewIndexes as $ni ) {
1639 if (pg_index_exists($ni[0], $ni[1])) {
1640 echo "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n";
1643 echo "Creating index \"$ni[1]\" on table \"$ni[0]\"\n";
1647 # Tweak the page_title tsearch2 trigger to filter out slashes
1648 # This is create or replace, so harmless to call if not needed
1649 dbsource(archive('patch-ts2pagetitle.sql'));
1651 ## If the server is 8.3 or higher, rewrite teh tsearch2 triggers
1652 ## in case they have the old 'default' versions
1653 if ( $numver >= 8.3 )
1654 dbsource(archive('patch-tsearch2funcs.sql'));