7 if ( !defined( 'MEDIAWIKI' ) ) {
8 echo "This file is not a valid entry point\n";
12 require_once 'convertLinks.inc';
13 require_once 'userDupes.inc';
14 require_once 'deleteDefaultMessages.php';
16 require_once( "$IP/includes/Hooks.php" );
19 * List of update functions to call on a MySQL-based MediaWiki installation,
20 * in sequence. First item is function name, rest are parameters to pass.
22 $wgMysqlUpdates = array(
24 // update_passwords obsolete
25 array( 'add_field', 'ipblocks', 'ipb_id', 'patch-ipblocks.sql' ),
26 array( 'add_field', 'ipblocks', 'ipb_expiry', 'patch-ipb_expiry.sql' ),
27 array( 'do_interwiki_update' ),
28 array( 'do_index_update' ),
29 // do_linkscc_update obsolete
30 array( 'add_table', 'hitcounter', 'patch-hitcounter.sql' ),
31 array( 'add_field', 'recentchanges', 'rc_type', 'patch-rc_type.sql' ),
34 array( 'add_field', 'user', 'user_real_name', 'patch-user-realname.sql' ),
35 array( 'add_table', 'querycache', 'patch-querycache.sql' ),
36 array( 'add_table', 'objectcache', 'patch-objectcache.sql' ),
37 array( 'add_table', 'categorylinks', 'patch-categorylinks.sql' ),
38 // do_linkscc_1_3_update obsolete
39 array( 'do_old_links_update' ),
40 array( 'add_field', 'recentchanges', 'rc_ip', 'patch-rc_ip.sql' ),
43 array( 'do_image_name_unique_update' ),
44 array( 'add_field', 'recentchanges', 'rc_id', 'patch-rc_id.sql' ),
45 array( 'add_field', 'recentchanges', 'rc_patrolled', 'patch-rc-patrol.sql' ),
46 array( 'add_table', 'logging', 'patch-logging.sql' ),
47 // do_user_rights_update obsolete
48 array( 'add_field', 'user', 'user_token', 'patch-user_token.sql' ),
49 // old, old_articleid, patch-remove-old-title-namespace.sql obsolete
50 // user_groups, patch-userlevels.sql obsolete
51 // do_group_update() obsolete
52 array( 'do_watchlist_update' ),
53 array( 'do_user_update' ),
54 // do_copy_newtalk_to_watchlist obsolete
57 array( 'do_schema_restructuring' ),
58 array( 'add_field', 'logging', 'log_params', 'patch-log_params.sql' ),
59 array( 'check_bin', 'logging', 'log_title', 'patch-logging-title.sql', ),
60 array( 'add_field', 'archive', 'ar_rev_id', 'patch-archive-rev_id.sql' ),
61 array( 'add_field', 'page', 'page_len', 'patch-page_len.sql' ),
62 array( 'do_inverse_timestamp' ),
63 array( 'do_text_id' ),
64 array( 'add_field', 'revision', 'rev_deleted', 'patch-rev_deleted.sql' ),
65 array( 'add_field', 'image', 'img_width', 'patch-img_width.sql' ),
66 array( 'add_field', 'image', 'img_metadata', 'patch-img_metadata.sql' ),
67 array( 'add_field', 'user', 'user_email_token', 'patch-user_email_token.sql' ),
68 array( 'add_field', 'archive', 'ar_text_id', 'patch-archive-text_id.sql' ),
69 array( 'do_namespace_size' ),
70 array( 'add_field', 'image', 'img_media_type', 'patch-img_media_type.sql' ),
71 array( 'do_pagelinks_update' ),
72 array( 'do_drop_img_type' ),
73 array( 'do_user_unique_update' ),
74 array( 'do_user_groups_update' ),
75 array( 'add_field', 'site_stats', 'ss_total_pages', 'patch-ss_total_articles.sql' ),
76 array( 'add_table', 'user_newtalk', 'patch-usernewtalk2.sql' ),
77 array( 'add_table', 'transcache', 'patch-transcache.sql' ),
78 array( 'add_field', 'interwiki', 'iw_trans', 'patch-interwiki-trans.sql' ),
79 array( 'add_table', 'trackbacks', 'patch-trackbacks.sql' ),
82 array( 'do_watchlist_null' ),
83 // do_image_index_update obsolete
84 array( 'do_logging_timestamp_index' ),
85 array( 'add_field', 'ipblocks', 'ipb_range_start', 'patch-ipb_range_start.sql' ),
86 array( 'do_page_random_update' ),
87 array( 'add_field', 'user', 'user_registration','patch-user_registration.sql' ),
88 array( 'do_templatelinks_update' ),
89 array( 'add_table', 'externallinks', 'patch-externallinks.sql' ),
90 array( 'add_table', 'job', 'patch-job.sql' ),
91 array( 'add_field', 'site_stats', 'ss_images', 'patch-ss_images.sql' ),
92 array( 'add_table', 'langlinks', 'patch-langlinks.sql' ),
93 array( 'add_table', 'querycache_info', 'patch-querycacheinfo.sql' ),
94 array( 'add_table', 'filearchive', 'patch-filearchive.sql' ),
95 array( 'add_field', 'ipblocks', 'ipb_anon_only', 'patch-ipb_anon_only.sql' ),
96 array( 'do_rc_indices_update' ),
99 array( 'add_field', 'user', 'user_newpass_time', 'patch-user_newpass_time.sql' ),
100 array( 'add_table', 'redirect', 'patch-redirect.sql' ),
101 array( 'add_table', 'querycachetwo', 'patch-querycachetwo.sql' ),
102 array( 'add_field', 'ipblocks', 'ipb_enable_autoblock', 'patch-ipb_optional_autoblock.sql' ),
103 array( 'do_backlinking_indices_update' ),
104 array( 'add_field', 'recentchanges', 'rc_old_len', 'patch-rc_len.sql' ),
105 array( 'add_field', 'user', 'user_editcount', 'patch-user_editcount.sql' ),
108 array( 'do_restrictions_update' ),
109 array( 'add_field', 'logging', 'log_id', 'patch-log_id.sql' ),
110 array( 'add_field', 'revision', 'rev_parent_id', 'patch-rev_parent_id.sql' ),
111 array( 'add_field', 'page_restrictions', 'pr_id', 'patch-page_restrictions_sortkey.sql' ),
112 array( 'add_field', 'revision', 'rev_len', 'patch-rev_len.sql' ),
113 array( 'add_field', 'recentchanges', 'rc_deleted', 'patch-rc_deleted.sql' ),
114 array( 'add_field', 'logging', 'log_deleted', 'patch-log_deleted.sql' ),
115 array( 'add_field', 'archive', 'ar_deleted', 'patch-ar_deleted.sql' ),
116 array( 'add_field', 'ipblocks', 'ipb_deleted', 'patch-ipb_deleted.sql' ),
117 array( 'add_field', 'filearchive', 'fa_deleted', 'patch-fa_deleted.sql' ),
118 array( 'add_field', 'archive', 'ar_len', 'patch-ar_len.sql' ),
121 array( 'add_field', 'ipblocks', 'ipb_block_email', 'patch-ipb_emailban.sql' ),
122 array( 'do_categorylinks_indices_update' ),
123 array( 'add_field', 'oldimage', 'oi_metadata', 'patch-oi_metadata.sql'),
124 array( 'do_archive_user_index' ),
125 array( 'do_image_user_index' ),
126 array( 'do_oldimage_user_index' ),
127 array( 'add_field', 'archive', 'ar_page_id', 'patch-archive-page_id.sql'),
128 array( 'add_field', 'image', 'img_sha1', 'patch-img_sha1.sql' ),
131 array( 'add_table', 'protected_titles', 'patch-protected_titles.sql' ),
134 array( 'add_field', 'ipblocks', 'ipb_by_text', 'patch-ipb_by_text.sql' ),
135 array( 'add_table', 'page_props', 'patch-page_props.sql' ),
136 array( 'add_table', 'updatelog', 'patch-updatelog.sql' ),
137 array( 'add_table', 'category', 'patch-category.sql' ),
138 array( 'do_category_population' ),
139 array( 'add_field', 'archive', 'ar_parent_id', 'patch-ar_parent_id.sql'),
140 array( 'add_field', 'user_newtalk', 'user_last_timestamp', 'patch-user_last_timestamp.sql'),
141 array( 'do_populate_parent_id' ),
142 array( 'check_bin', 'protected_titles', 'pt_title', 'patch-pt_title-encoding.sql', ),
143 array( 'maybe_do_profiling_memory_update' ),
144 array( 'do_filearchive_indices_update' ),
148 # For extensions only, should be populated via hooks
149 # $wgDBtype should be checked to specifiy the proper file
150 $wgExtNewTables = array(); // table, dir
151 $wgExtNewFields = array(); // table, column, dir
152 $wgExtPGNewFields = array(); // table, column attributes; for PostgreSQL
153 $wgExtNewIndexes = array(); // table, index, dir
155 # Helper function: check if the given key is present in the updatelog table.
156 # Obviously, only use this for updates that occur after the updatelog table was
158 function update_row_exists( $key ) {
159 $dbr = wfGetDB( DB_SLAVE );
160 $row = $dbr->selectRow(
163 array( 'ul_key' => $key ),
169 function rename_table( $from, $to, $patch ) {
171 if ( $wgDatabase->tableExists( $from ) ) {
172 if ( $wgDatabase->tableExists( $to ) ) {
173 echo "...can't move table $from to $to, $to already exists.\n";
175 echo "Moving table $from to $to...";
176 dbsource( archive($patch), $wgDatabase );
180 // Source table does not exist
181 // Renames are done before creations, so this is typical for a new installation
186 function add_table( $name, $patch, $fullpath=false ) {
188 if ( $wgDatabase->tableExists( $name ) ) {
189 echo "...$name table already exists.\n";
191 echo "Creating $name table...";
193 dbsource( $patch, $wgDatabase );
195 dbsource( archive($patch), $wgDatabase );
201 function add_field( $table, $field, $patch, $fullpath=false ) {
203 if ( !$wgDatabase->tableExists( $table ) ) {
204 echo "...$table table does not exist, skipping new field patch\n";
205 } elseif ( $wgDatabase->fieldExists( $table, $field ) ) {
206 echo "...have $field field in $table table.\n";
208 echo "Adding $field field to table $table...";
210 dbsource( $patch, $wgDatabase );
212 dbsource( archive($patch), $wgDatabase );
218 function add_index( $table, $index, $patch, $fullpath=false ) {
220 if( $wgDatabase->indexExists( $table, $index ) ) {
221 echo "...$index key already set on $table table.\n";
223 echo "Adding $index key to table $table... ";
225 dbsource( $patch, $wgDatabase );
227 dbsource( archive($patch), $wgDatabase );
233 function do_revision_updates() {
234 global $wgSoftwareRevision;
235 if ( $wgSoftwareRevision < 1001 ) {
240 function update_passwords() {
241 wfDebugDieBacktrace( "This function needs to be updated or removed.\n" );
244 $fname = "Update script: update_passwords()";
245 print "\nIt appears that you need to update the user passwords in your\n" .
246 "database. If you have already done this (if you've run this update\n" .
247 "script once before, for example), doing so again will make all your\n" .
248 "user accounts inaccessible, so be sure you only do this once.\n" .
249 "Update user passwords? (yes/no)";
251 $resp = readconsole();
252 if ( ! ( "Y" == $resp{0} || "y" == $resp{0} ) ) { return; }
254 $sql = "SELECT user_id,user_password FROM user";
255 $source = $wgDatabase->query( $sql, $fname );
257 while ( $row = $wgDatabase->fetchObject( $source ) ) {
259 $oldpass = $row->user_password;
260 $newpass = md5( "{$id}-{$oldpass}" );
262 $sql = "UPDATE user SET user_password='{$newpass}' " .
263 "WHERE user_id={$id}";
264 $wgDatabase->query( $sql, $fname );
268 function do_interwiki_update() {
269 # Check that interwiki table exists; if it doesn't source it
270 global $wgDatabase, $IP;
271 if( $wgDatabase->tableExists( "interwiki" ) ) {
272 echo "...already have interwiki table\n";
275 echo "Creating interwiki table: ";
276 dbsource( archive("patch-interwiki.sql") );
278 echo "Adding default interwiki definitions: ";
279 dbsource( "$IP/maintenance/interwiki.sql" );
283 function do_index_update() {
284 # Check that proper indexes are in place
286 $meta = $wgDatabase->fieldInfo( "recentchanges", "rc_timestamp" );
287 if( !$meta->isMultipleKey() ) {
288 echo "Updating indexes to 20031107: ";
289 dbsource( archive("patch-indexes.sql") );
293 echo "...indexes seem up to 20031107 standards\n";
297 function do_image_index_update() {
300 $meta = $wgDatabase->fieldInfo( "image", "img_major_mime" );
301 if( !$meta->isMultipleKey() ) {
302 echo "Updating indexes to 20050912: ";
303 dbsource( archive("patch-mimesearch-indexes.sql") );
307 echo "...indexes seem up to 20050912 standards\n";
311 function do_image_name_unique_update() {
313 if( $wgDatabase->indexExists( 'image', 'PRIMARY' ) ) {
314 echo "...image primary key already set.\n";
316 echo "Making img_name the primary key... ";
317 dbsource( archive("patch-image_name_primary.sql"), $wgDatabase );
322 function do_logging_timestamp_index() {
324 if( $wgDatabase->indexExists( 'logging', 'times' ) ) {
325 echo "...timestamp key on logging already exists.\n";
327 echo "Adding timestamp key on logging table... ";
328 dbsource( archive("patch-logging-times-index.sql"), $wgDatabase );
333 function do_archive_user_index() {
335 if( $wgDatabase->indexExists( 'archive', 'usertext_timestamp' ) ) {
336 echo "...usertext,timestamp key on archive already exists.\n";
338 echo "Adding usertext,timestamp key on archive table... ";
339 dbsource( archive("patch-archive-user-index.sql"), $wgDatabase );
344 function do_image_user_index() {
346 if( $wgDatabase->indexExists( 'image', 'img_usertext_timestamp' ) ) {
347 echo "...usertext,timestamp key on image already exists.\n";
349 echo "Adding usertext,timestamp key on image table... ";
350 dbsource( archive("patch-image-user-index.sql"), $wgDatabase );
355 function do_oldimage_user_index() {
357 if( $wgDatabase->indexExists( 'oldimage', 'oi_usertext_timestamp' ) ) {
358 echo "...usertext,timestamp key on oldimage already exists.\n";
360 echo "Adding usertext,timestamp key on oldimage table... ";
361 dbsource( archive("patch-oldimage-user-index.sql"), $wgDatabase );
366 function do_watchlist_update() {
368 $fname = 'do_watchlist_update';
369 if( $wgDatabase->fieldExists( 'watchlist', 'wl_notificationtimestamp' ) ) {
370 echo "The watchlist table is already set up for email notification.\n";
372 echo "Adding wl_notificationtimestamp field for email notification management.";
373 /* ALTER TABLE watchlist ADD (wl_notificationtimestamp varchar(14) binary NOT NULL default '0'); */
374 dbsource( archive( 'patch-email-notification.sql' ), $wgDatabase );
377 # Check if we need to add talk page rows to the watchlist
378 $talk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'wl_namespace & 1', $fname );
379 $nontalk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'NOT (wl_namespace & 1)', $fname );
380 if ( $talk != $nontalk ) {
381 echo "Adding missing watchlist talk page rows... ";
384 $wgDatabase->insertSelect( 'watchlist', 'watchlist',
386 'wl_user' => 'wl_user',
387 'wl_namespace' => 'wl_namespace | 1',
388 'wl_title' => 'wl_title',
389 'wl_notificationtimestamp' => 'wl_notificationtimestamp'
390 ), array( 'NOT (wl_namespace & 1)' ), $fname, 'IGNORE' );
393 echo "...watchlist talk page rows already present\n";
397 function do_copy_newtalk_to_watchlist() {
399 global $wgCommandLineMode; # this needs to be saved while getID() and getName() are called
401 $res = $wgDatabase->safeQuery( 'SELECT user_id, user_ip FROM !',
402 $wgDatabase->tableName( 'user_newtalk' ) );
403 $num_newtalks=$wgDatabase->numRows($res);
404 echo "Now converting ".$num_newtalks." user_newtalk entries to watchlist table entries ... \n";
407 for ( $i = 1; $i <= $num_newtalks; $i++ ) {
408 $wluser = $wgDatabase->fetchObject( $res );
409 if ($wluser->user_id == 0) { # anonymous users ... have IP numbers as "names"
410 if ($user->isIP($wluser->user_ip)) { # do only if it really looks like an IP number (double checked)
411 $wgDatabase->replace( 'watchlist',
412 array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
413 array('wl_user' => 0,
414 'wl_namespace' => NS_USER_TALK,
415 'wl_title' => $wluser->user_ip,
416 'wl_notificationtimestamp' => '19700101000000'
417 ), 'updaters.inc::do_watchlist_update2'
420 } else { # normal users ... have user_ids
421 $user->setID($wluser->user_id);
422 $wgDatabase->replace( 'watchlist',
423 array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
424 array('wl_user' => $user->getID(),
425 'wl_namespace' => NS_USER_TALK,
426 'wl_title' => $user->getName(),
427 'wl_notificationtimestamp' => '19700101000000'
428 ), 'updaters.inc::do_watchlist_update3'
436 function do_user_update() {
438 if( $wgDatabase->fieldExists( 'user', 'user_emailauthenticationtimestamp' ) ) {
439 echo "User table contains old email authentication field. Dropping... ";
440 dbsource( archive( 'patch-email-authentication.sql' ), $wgDatabase );
443 echo "...user table does not contain old email authentication field.\n";
448 * 1.4 betas were missing the 'binary' marker from logging.log_title,
449 * which causes a collation mismatch error on joins in MySQL 4.1.
451 function check_bin( $table, $field, $patchFile ) {
452 global $wgDatabase, $wgDBtype;
453 if ($wgDBtype != 'mysql')
455 $tableName = $wgDatabase->tableName( $table );
456 $res = $wgDatabase->query( "SELECT $field FROM $tableName LIMIT 0" );
457 $flags = explode( ' ', mysql_field_flags( $res->result, 0 ) );
458 $wgDatabase->freeResult( $res );
460 if( in_array( 'binary', $flags ) ) {
461 echo "$table table has correct $field encoding.\n";
463 echo "Fixing $field encoding on $table table... ";
464 dbsource( archive( $patchFile ), $wgDatabase );
469 function do_schema_restructuring() {
471 $fname="do_schema_restructuring";
472 if ( $wgDatabase->tableExists( 'page' ) ) {
473 echo "...page table already exists.\n";
475 echo "...converting from cur/old to page/revision/text DB structure.\n"; flush();
476 echo wfTimestamp( TS_DB );
477 echo "......checking for duplicate entries.\n"; flush();
479 list ($cur, $old, $page, $revision, $text) = $wgDatabase->tableNamesN( 'cur', 'old', 'page', 'revision', 'text' );
481 $rows = $wgDatabase->query( "SELECT cur_title, cur_namespace, COUNT(cur_namespace) AS c
482 FROM $cur GROUP BY cur_title, cur_namespace HAVING c>1", $fname );
484 if ( $wgDatabase->numRows( $rows ) > 0 ) {
485 echo wfTimestamp( TS_DB );
486 echo "......<b>Found duplicate entries</b>\n";
487 echo ( sprintf( "<b> %-60s %3s %5s</b>\n", 'Title', 'NS', 'Count' ) );
488 while ( $row = $wgDatabase->fetchObject( $rows ) ) {
489 if ( ! isset( $duplicate[$row->cur_namespace] ) ) {
490 $duplicate[$row->cur_namespace] = array();
492 $duplicate[$row->cur_namespace][] = $row->cur_title;
493 echo ( sprintf( " %-60s %3s %5s\n", $row->cur_title, $row->cur_namespace, $row->c ) );
495 $sql = "SELECT cur_title, cur_namespace, cur_id, cur_timestamp FROM $cur WHERE ";
497 foreach ( $duplicate as $ns => $titles ) {
503 $sql .= "( cur_namespace = {$ns} AND cur_title in (";
505 foreach ( $titles as $t ) {
507 $sql .= $wgDatabase->addQuotes( $t );
510 $sql .= ', ' . $wgDatabase->addQuotes( $t );
515 # By sorting descending, the most recent entry will be the first in the list.
516 # All following entries will be deleted by the next while-loop.
517 $sql .= 'ORDER BY cur_namespace, cur_title, cur_timestamp DESC';
519 $rows = $wgDatabase->query( $sql, $fname );
521 $prev_title = $prev_namespace = false;
524 while ( $row = $wgDatabase->fetchObject( $rows ) ) {
525 if ( $prev_title == $row->cur_title && $prev_namespace == $row->cur_namespace ) {
526 $deleteId[] = $row->cur_id;
528 $prev_title = $row->cur_title;
529 $prev_namespace = $row->cur_namespace;
531 $sql = "DELETE FROM $cur WHERE cur_id IN ( " . join( ',', $deleteId ) . ')';
532 $rows = $wgDatabase->query( $sql, $fname );
533 echo wfTimestamp( TS_DB );
534 echo "......<b>Deleted</b> ".$wgDatabase->affectedRows()." records.\n";
538 echo wfTimestamp( TS_DB );
539 echo "......Creating tables.\n";
540 $wgDatabase->query("CREATE TABLE $page (
541 page_id int(8) unsigned NOT NULL auto_increment,
542 page_namespace int NOT NULL,
543 page_title varchar(255) binary NOT NULL,
544 page_restrictions tinyblob NOT NULL,
545 page_counter bigint(20) unsigned NOT NULL default '0',
546 page_is_redirect tinyint(1) unsigned NOT NULL default '0',
547 page_is_new tinyint(1) unsigned NOT NULL default '0',
548 page_random real unsigned NOT NULL,
549 page_touched char(14) binary NOT NULL default '',
550 page_latest int(8) unsigned NOT NULL,
551 page_len int(8) unsigned NOT NULL,
553 PRIMARY KEY page_id (page_id),
554 UNIQUE INDEX name_title (page_namespace,page_title),
557 ) TYPE=InnoDB", $fname );
558 $wgDatabase->query("CREATE TABLE $revision (
559 rev_id int(8) unsigned NOT NULL auto_increment,
560 rev_page int(8) unsigned NOT NULL,
561 rev_comment tinyblob NOT NULL,
562 rev_user int(5) unsigned NOT NULL default '0',
563 rev_user_text varchar(255) binary NOT NULL default '',
564 rev_timestamp char(14) binary NOT NULL default '',
565 rev_minor_edit tinyint(1) unsigned NOT NULL default '0',
566 rev_deleted tinyint(1) unsigned NOT NULL default '0',
567 rev_len int(8) unsigned,
568 rev_parent_id int(8) unsigned default NULL,
569 PRIMARY KEY rev_page_id (rev_page, rev_id),
570 UNIQUE INDEX rev_id (rev_id),
571 INDEX rev_timestamp (rev_timestamp),
572 INDEX page_timestamp (rev_page,rev_timestamp),
573 INDEX user_timestamp (rev_user,rev_timestamp),
574 INDEX usertext_timestamp (rev_user_text,rev_timestamp)
575 ) TYPE=InnoDB", $fname );
577 echo wfTimestamp( TS_DB );
578 echo "......Locking tables.\n";
579 $wgDatabase->query( "LOCK TABLES $page WRITE, $revision WRITE, $old WRITE, $cur WRITE", $fname );
581 $maxold = intval( $wgDatabase->selectField( 'old', 'max(old_id)', '', $fname ) );
582 echo wfTimestamp( TS_DB );
583 echo "......maxold is {$maxold}\n";
585 echo wfTimestamp( TS_DB );
586 global $wgLegacySchemaConversion;
587 if( $wgLegacySchemaConversion ) {
588 // Create HistoryBlobCurStub entries.
589 // Text will be pulled from the leftover 'cur' table at runtime.
590 echo "......Moving metadata from cur; using blob references to text in cur table.\n";
591 $cur_text = "concat('O:18:\"historyblobcurstub\":1:{s:6:\"mCurId\";i:',cur_id,';}')";
592 $cur_flags = "'object'";
594 // Copy all cur text in immediately: this may take longer but avoids
595 // having to keep an extra table around.
596 echo "......Moving text from cur.\n";
597 $cur_text = 'cur_text';
600 $wgDatabase->query( "INSERT INTO $old (old_namespace, old_title, old_text, old_comment, old_user, old_user_text,
601 old_timestamp, old_minor_edit, old_flags)
602 SELECT cur_namespace, cur_title, $cur_text, cur_comment, cur_user, cur_user_text, cur_timestamp, cur_minor_edit, $cur_flags
603 FROM $cur", $fname );
605 echo wfTimestamp( TS_DB );
606 echo "......Setting up revision table.\n";
607 $wgDatabase->query( "INSERT INTO $revision (rev_id, rev_page, rev_comment, rev_user, rev_user_text, rev_timestamp,
609 SELECT old_id, cur_id, old_comment, old_user, old_user_text,
610 old_timestamp, old_minor_edit
611 FROM $old,$cur WHERE old_namespace=cur_namespace AND old_title=cur_title", $fname );
613 echo wfTimestamp( TS_DB );
614 echo "......Setting up page table.\n";
615 $wgDatabase->query( "INSERT INTO $page (page_id, page_namespace, page_title, page_restrictions, page_counter,
616 page_is_redirect, page_is_new, page_random, page_touched, page_latest, page_len)
617 SELECT cur_id, cur_namespace, cur_title, cur_restrictions, cur_counter, cur_is_redirect, cur_is_new,
618 cur_random, cur_touched, rev_id, LENGTH(cur_text)
620 WHERE cur_id=rev_page AND rev_timestamp=cur_timestamp AND rev_id > {$maxold}", $fname );
622 echo wfTimestamp( TS_DB );
623 echo "......Unlocking tables.\n";
624 $wgDatabase->query( "UNLOCK TABLES", $fname );
626 echo wfTimestamp( TS_DB );
627 echo "......Renaming old.\n";
628 $wgDatabase->query( "ALTER TABLE $old RENAME TO $text", $fname );
630 echo wfTimestamp( TS_DB );
635 function do_inverse_timestamp() {
637 if( $wgDatabase->fieldExists( 'revision', 'inverse_timestamp' ) ) {
638 echo "Removing revision.inverse_timestamp and fixing indexes... ";
639 dbsource( archive( 'patch-inverse_timestamp.sql' ), $wgDatabase );
642 echo "revision timestamp indexes already up to 2005-03-13\n";
646 function do_text_id() {
648 if( $wgDatabase->fieldExists( 'revision', 'rev_text_id' ) ) {
649 echo "...rev_text_id already in place.\n";
651 echo "Adding rev_text_id field... ";
652 dbsource( archive( 'patch-rev_text_id.sql' ), $wgDatabase );
657 function do_namespace_size() {
661 'recentchanges' => 'rc',
663 'querycache' => 'qc',
666 foreach( $tables as $table => $prefix ) {
667 do_namespace_size_on( $table, $prefix );
672 function do_namespace_size_on( $table, $prefix ) {
673 global $wgDatabase, $wgDBtype;
674 if ($wgDBtype != 'mysql')
676 $field = $prefix . '_namespace';
678 $tablename = $wgDatabase->tableName( $table );
679 $result = $wgDatabase->query( "SHOW COLUMNS FROM $tablename LIKE '$field'" );
680 $info = $wgDatabase->fetchObject( $result );
681 $wgDatabase->freeResult( $result );
683 if( substr( $info->Type, 0, 3 ) == 'int' ) {
684 echo "...$field is already a full int ($info->Type).\n";
686 echo "Promoting $field from $info->Type to int... ";
688 $sql = "ALTER TABLE $tablename MODIFY $field int NOT NULL";
689 $wgDatabase->query( $sql );
695 function do_pagelinks_update() {
697 if( $wgDatabase->tableExists( 'pagelinks' ) ) {
698 echo "...already have pagelinks table.\n";
700 echo "Converting links and brokenlinks tables to pagelinks... ";
701 dbsource( archive( 'patch-pagelinks.sql' ), $wgDatabase );
705 global $wgCanonicalNamespaceNames;
706 foreach( $wgCanonicalNamespaceNames as $ns => $name ) {
708 do_pagelinks_namespace( $ns );
714 function do_pagelinks_namespace( $namespace ) {
715 global $wgDatabase, $wgContLang;
717 $ns = intval( $namespace );
718 echo "Cleaning up broken links for namespace $ns... ";
720 $pagelinks = $wgDatabase->tableName( 'pagelinks' );
721 $name = $wgContLang->getNsText( $ns );
722 $prefix = $wgDatabase->strencode( $name );
723 $likeprefix = str_replace( '_', '\\_', $prefix);
725 $sql = "UPDATE $pagelinks
726 SET pl_namespace=$ns,
727 pl_title=TRIM(LEADING '$prefix:' FROM pl_title)
729 AND pl_title LIKE '$likeprefix:%'";
731 $wgDatabase->query( $sql, 'do_pagelinks_namespace' );
735 function do_drop_img_type() {
738 if( $wgDatabase->fieldExists( 'image', 'img_type' ) ) {
739 echo "Dropping unused img_type field in image table... ";
740 dbsource( archive( 'patch-drop_img_type.sql' ), $wgDatabase );
743 echo "No img_type field in image table; Good.\n";
747 function do_old_links_update() {
749 if( $wgDatabase->tableExists( 'pagelinks' ) ) {
750 echo "Already have pagelinks; skipping old links table updates.\n";
752 convertLinks(); flush();
756 function do_user_unique_update() {
758 $duper = new UserDupes( $wgDatabase );
759 if( $duper->hasUniqueIndex() ) {
760 echo "Already have unique user_name index.\n";
762 if( !$duper->clearDupes() ) {
763 echo "WARNING: This next step will probably fail due to unfixed duplicates...\n";
765 echo "Adding unique index on user_name... ";
766 dbsource( archive( 'patch-user_nameindex.sql' ), $wgDatabase );
771 function do_user_groups_update() {
772 $fname = 'do_user_groups_update';
775 if( $wgDatabase->tableExists( 'user_groups' ) ) {
776 echo "...user_groups table already exists.\n";
777 return do_user_groups_reformat();
780 echo "Adding user_groups table... ";
781 dbsource( archive( 'patch-user_groups.sql' ), $wgDatabase );
784 if( !$wgDatabase->tableExists( 'user_rights' ) ) {
785 if( $wgDatabase->fieldExists( 'user', 'user_rights' ) ) {
786 echo "Upgrading from a 1.3 or older database? Breaking out user_rights for conversion...";
787 dbsource( archive( 'patch-user_rights.sql' ), $wgDatabase );
790 echo "*** WARNING: couldn't locate user_rights table or field for upgrade.\n";
791 echo "*** You may need to manually configure some sysops by manipulating\n";
792 echo "*** the user_groups table.\n";
797 echo "Converting user_rights table to user_groups... ";
798 $result = $wgDatabase->select( 'user_rights',
799 array( 'ur_user', 'ur_rights' ),
800 array( "ur_rights != ''" ),
803 while( $row = $wgDatabase->fetchObject( $result ) ) {
804 $groups = array_unique(
806 explode( ',', $row->ur_rights ) ) );
808 foreach( $groups as $group ) {
809 $wgDatabase->insert( 'user_groups',
811 'ug_user' => $row->ur_user,
812 'ug_group' => $group ),
816 $wgDatabase->freeResult( $result );
820 function do_user_groups_reformat() {
821 # Check for bogus formats from previous 1.5 alpha code.
823 $info = $wgDatabase->fieldInfo( 'user_groups', 'ug_group' );
825 if( $info->type() == 'int' ) {
826 $oldug = $wgDatabase->tableName( 'user_groups' );
827 $newug = $wgDatabase->tableName( 'user_groups_bogus' );
828 echo "user_groups is in bogus intermediate format. Renaming to $newug... ";
829 $wgDatabase->query( "ALTER TABLE $oldug RENAME TO $newug" );
832 echo "Re-adding fresh user_groups table... ";
833 dbsource( archive( 'patch-user_groups.sql' ), $wgDatabase );
837 echo "*** WARNING: You will need to manually fix up user permissions in the user_groups\n";
838 echo "*** table. Old 1.5 alpha versions did some pretty funky stuff...\n";
841 echo "...user_groups is in current format.\n";
846 function do_watchlist_null() {
847 # Make sure wl_notificationtimestamp can be NULL,
848 # and update old broken items.
850 $info = $wgDatabase->fieldInfo( 'watchlist', 'wl_notificationtimestamp' );
852 if( !$info->nullable() ) {
853 echo "Making wl_notificationtimestamp nullable... ";
854 dbsource( archive( 'patch-watchlist-null.sql' ), $wgDatabase );
857 echo "...wl_notificationtimestamp is already nullable.\n";
865 function do_page_random_update() {
868 echo "Setting page_random to a random value on rows where it equals 0...";
870 $page = $wgDatabase->tableName( 'page' );
871 $wgDatabase->query( "UPDATE $page SET page_random = RAND() WHERE page_random = 0", 'do_page_random_update' );
872 $rows = $wgDatabase->affectedRows();
874 echo "changed $rows rows\n";
877 function do_templatelinks_update() {
878 global $wgDatabase, $wgLoadBalancer;
879 $fname = 'do_templatelinks_update';
881 if ( $wgDatabase->tableExists( 'templatelinks' ) ) {
882 echo "...templatelinks table already exists\n";
885 echo "Creating templatelinks table...\n";
886 dbsource( archive('patch-templatelinks.sql'), $wgDatabase );
887 echo "Populating...\n";
888 if ( isset( $wgLoadBalancer ) && $wgLoadBalancer->getServerCount() > 1 ) {
889 // Slow, replication-friendly update
890 $res = $wgDatabase->select( 'pagelinks', array( 'pl_from', 'pl_namespace', 'pl_title' ),
891 array( 'pl_namespace' => NS_TEMPLATE ), $fname );
893 while ( $row = $wgDatabase->fetchObject( $res ) ) {
894 $count = ($count + 1) % 100;
896 if ( function_exists( 'wfWaitForSlaves' ) ) {
897 wfWaitForSlaves( 10 );
902 $wgDatabase->insert( 'templatelinks',
904 'tl_from' => $row->pl_from,
905 'tl_namespace' => $row->pl_namespace,
906 'tl_title' => $row->pl_title,
911 $wgDatabase->freeResult( $res );
914 $wgDatabase->insertSelect( 'templatelinks', 'pagelinks',
916 'tl_from' => 'pl_from',
917 'tl_namespace' => 'pl_namespace',
918 'tl_title' => 'pl_title'
924 echo "Done. Please run maintenance/refreshLinks.php for a more thorough templatelinks update.\n";
927 // Add index on ( rc_namespace, rc_user_text ) [Jul. 2006]
928 // Add index on ( rc_user_text, rc_timestamp ) [Nov. 2006]
929 function do_rc_indices_update() {
931 echo( "Checking for additional recent changes indices...\n" );
934 'rc_ns_usertext' => 'patch-recentchanges-utindex.sql',
935 'rc_user_text' => 'patch-rc_user_text-index.sql',
938 foreach( $indexes as $index => $patch ) {
939 $info = $wgDatabase->indexInfo( 'recentchanges', $index, __METHOD__ );
941 echo( "...index `{$index}` not found; adding..." );
942 dbsource( archive( $patch ) );
945 echo( "...index `{$index}` seems ok.\n" );
950 function index_has_field($table, $index, $field) {
952 echo( "Checking if $table index $index includes field $field...\n" );
953 $info = $wgDatabase->indexInfo( $table, $index, __METHOD__ );
955 foreach($info as $row) {
956 if($row->Column_name == $field) {
957 echo( "...index $index on table $table seems to be ok\n" );
962 echo( "...index $index on table $table has no field $field; adding\n" );
966 function do_backlinking_indices_update() {
967 echo( "Checking for backlinking indices...\n" );
968 if (!index_has_field('pagelinks', 'pl_namespace', 'pl_from') ||
969 !index_has_field('templatelinks', 'tl_namespace', 'tl_from') ||
970 !index_has_field('imagelinks', 'il_to', 'il_from'))
972 dbsource( archive( 'patch-backlinkindexes.sql' ) );
973 echo( "...backlinking indices updated\n" );
977 function do_categorylinks_indices_update() {
978 echo( "Checking for categorylinks indices...\n" );
979 if (!index_has_field('categorylinks', 'cl_sortkey', 'cl_from'))
981 dbsource( archive( 'patch-categorylinksindex.sql' ) );
982 echo( "...categorylinks indices updated\n" );
986 function do_filearchive_indices_update() {
988 echo( "Checking filearchive indices...\n" );
989 $info = $wgDatabase->indexInfo( 'filearchive', 'fa_user_timestamp', __METHOD__ );
992 dbsource( archive( 'patch-filearhive-user-index.sql' ) );
993 echo( "...filearchive indices updated\n" );
997 function maybe_do_profiling_memory_update() {
999 if ( !$wgDatabase->tableExists( 'profiling' ) ) {
1001 } elseif ( $wgDatabase->fieldExists( 'profiling', 'pf_memory' ) ) {
1002 echo "profiling table has pf_memory field.\n";
1004 echo "Adding pf_memory field to table profiling...";
1005 dbsource( archive( 'patch-profiling-memory.sql' ), $wgDatabase );
1010 function do_stats_init() {
1011 // Sometimes site_stats table is not properly populated.
1013 echo "Checking site_stats row...";
1014 $row = $wgDatabase->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
1015 if( $row === false ) {
1016 echo "data is missing! rebuilding...\n";
1019 require_once "$IP/maintenance/initStats.inc";
1026 function purge_cache() {
1028 # We can't guarantee that the user will be able to use TRUNCATE,
1029 # but we know that DELETE is available to us
1030 echo( "Purging caches..." );
1031 $wgDatabase->delete( 'objectcache', '*', __METHOD__ );
1035 function do_all_updates( $shared = false, $purge = true ) {
1036 global $wgNewTables, $wgNewFields, $wgRenamedTables, $wgSharedDB, $wgDatabase, $wgDBtype, $IP;
1038 wfRunHooks('LoadExtensionSchemaUpdates');
1040 $doUser = !$wgSharedDB || $shared;
1042 if ($wgDBtype === 'postgres') {
1043 do_postgres_updates();
1047 # Run core updates in sequence...
1048 global $wgMysqlUpdates;
1049 foreach( $wgMysqlUpdates as $params ) {
1050 $func = array_shift( $params );
1051 call_user_func_array( $func, $params );
1055 /// @fixme clean up this mess too!
1056 global $wgExtNewTables, $wgExtNewFields, $wgExtNewIndexes;
1057 # Add missing extension tables
1058 foreach ( $wgExtNewTables as $tableRecord ) {
1059 add_table( $tableRecord[0], $tableRecord[1], true );
1062 # Add missing extension fields
1063 foreach ( $wgExtNewFields as $fieldRecord ) {
1064 if ( $fieldRecord[0] != 'user' || $doUser ) {
1065 add_field( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true );
1069 # Add missing extension indexes
1070 foreach ( $wgExtNewIndexes as $fieldRecord ) {
1071 add_index( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true );
1076 echo "Deleting old default messages (this may take a long time!)..."; flush();
1077 deleteDefaultMessages();
1078 echo "Done\n"; flush();
1080 do_stats_init(); flush();
1088 function archive($name) {
1089 global $wgDBtype, $IP;
1090 switch ($wgDBtype) {
1092 return "$IP/maintenance/postgres/archives/$name";
1094 return "$IP/maintenance/archives/$name";
1098 function do_restrictions_update() {
1099 # Adding page_restrictions table, obsoleting page.page_restrictions.
1100 # Migrating old restrictions to new table
1101 # -- Andrew Garrett, January 2007.
1105 $name = 'page_restrictions';
1106 $patch = 'patch-page_restrictions.sql';
1107 $patch2 = 'patch-page_restrictions_sortkey.sql';
1109 if ( $wgDatabase->tableExists( $name ) ) {
1110 echo "...$name table already exists.\n";
1112 echo "Creating $name table...";
1113 dbsource( archive($patch), $wgDatabase );
1114 dbsource( archive($patch2), $wgDatabase );
1117 echo "Migrating old restrictions to new table...";
1119 $res = $wgDatabase->select( 'page', array( 'page_id', 'page_restrictions' ), array("page_restrictions!=''", "page_restrictions!='edit=:move='"), __METHOD__ );
1123 while ($row = $wgDatabase->fetchObject($res) ) {
1124 $count = ($count + 1) % 100;
1127 if ( function_exists( 'wfWaitForSlaves' ) ) {
1128 wfWaitForSlaves( 10 );
1134 # Figure out what the restrictions are..
1135 $id = $row->page_id;
1136 $flatrestrictions = explode( ':', $row->page_restrictions );
1138 $restrictions = array ();
1139 foreach( $flatrestrictions as $restriction ) {
1140 $thisrestriction = explode( '=', $restriction, 2 );
1141 if( count( $thisrestriction ) == 1 ) {
1142 // Compatibility with old protections from before
1143 // separate move protection was added.
1144 list( $level ) = $thisrestriction;
1146 $restrictions['edit'] = $level;
1147 $restrictions['move'] = $level;
1150 list( $type, $level ) = $thisrestriction;
1152 $restrictions[$type] = $level;
1156 $wgDatabase->update( 'page', array ( 'page_restrictions' => ''), array( 'page_id' => $id ), __METHOD__ );
1160 foreach( $restrictions as $type => $level ) {
1161 $wgDatabase->insert( 'page_restrictions', array ( 'pr_page' => $id,
1163 'pr_level' => $level,
1165 'pr_expiry' => 'infinity' ),
1173 function do_category_population() {
1174 if( update_row_exists( 'populate category' ) ) {
1175 echo "...category table already populated.\n";
1178 require_once( 'populateCategory.inc' );
1179 echo "Populating category table, printing progress markers. ".
1180 "For large databases, you\n".
1181 "may want to hit Ctrl-C and do this manually with maintenance/\n".
1182 "populateCategory.php.\n";
1183 populateCategory( '', 10, 0, true );
1184 echo "Done populating category table.\n";
1187 function do_populate_parent_id() {
1188 if( update_row_exists( 'populate rev_parent_id' ) ) {
1189 echo "...rev_parent_id column already populated.\n";
1192 require_once( 'populateParentId.inc' );
1195 populate_rev_parent_id( $wgDatabase );
1199 pg_describe_table($table)
1201 global $wgDatabase, $wgDBmwschema;
1203 SELECT attname, attnum FROM pg_namespace, pg_class, pg_attribute
1204 WHERE pg_class.relnamespace = pg_namespace.oid
1205 AND attrelid=pg_class.oid AND attnum > 0
1206 AND relname=%s AND nspname=%s
1208 $res = $wgDatabase->query(sprintf($q,
1209 $wgDatabase->addQuotes($table),
1210 $wgDatabase->addQuotes($wgDBmwschema)));
1215 while ($r = $wgDatabase->fetchRow($res)) {
1225 pg_describe_index($idx)
1227 global $wgDatabase, $wgDBmwschema;
1229 // first fetch the key (which is a list of columns ords) and
1230 // the table the index applies to (an oid)
1232 SELECT indkey, indrelid FROM pg_namespace, pg_class, pg_index
1234 AND pg_class.relnamespace = pg_namespace.oid
1236 AND indexrelid=pg_class.oid
1238 $res = $wgDatabase->query(sprintf($q,
1239 $wgDatabase->addQuotes($wgDBmwschema),
1240 $wgDatabase->addQuotes($idx)));
1243 if (!($r = $wgDatabase->fetchRow($res))) {
1244 $wgDatabase->freeResult($res);
1249 $relid = intval($r[1]);
1250 $indkeys = explode(" ", $indkey);
1251 $wgDatabase->freeResult($res);
1253 $colnames = array();
1254 foreach ($indkeys as $rid) {
1256 SELECT attname FROM pg_class, pg_attribute
1257 WHERE attrelid=$relid
1259 AND attrelid=pg_class.oid
1261 $r2 = $wgDatabase->query(sprintf($query, $rid));
1264 if (!($row2 = $wgDatabase->fetchRow($r2))) {
1265 $wgDatabase->freeResult($r2);
1268 $colnames[] = $row2[0];
1269 $wgDatabase->freeResult($r2);
1276 pg_index_exists($table, $index)
1278 global $wgDatabase, $wgDBmwschema;
1279 $exists = $wgDatabase->selectField("pg_indexes", "indexname",
1280 array( "indexname" => $index,
1281 "tablename" => $table,
1282 "schemaname" => $wgDBmwschema));
1283 return $exists === $index;
1287 pg_fkey_deltype($fkey)
1289 global $wgDatabase, $wgDBmwschema;
1291 SELECT confdeltype FROM pg_constraint, pg_namespace
1292 WHERE connamespace=pg_namespace.oid
1296 $r = $wgDatabase->query(sprintf($q,
1297 $wgDatabase->addQuotes($wgDBmwschema),
1298 $wgDatabase->addQuotes($fkey)));
1299 if (!($row = $wgDatabase->fetchRow($r)))
1305 pg_rule_def($table, $rule)
1307 global $wgDatabase, $wgDBmwschema;
1309 SELECT definition FROM pg_rules
1310 WHERE schemaname = %s
1314 $r = $wgDatabase->query(sprintf($q,
1315 $wgDatabase->addQuotes($wgDBmwschema),
1316 $wgDatabase->addQuotes($table),
1317 $wgDatabase->addQuotes($rule)));
1318 $row = $wgDatabase->fetchRow($r);
1322 $wgDatabase->freeResult($r);
1326 function do_postgres_updates() {
1327 global $wgDatabase, $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgShowExceptionDetails, $wgDBuser;
1329 ## Gather version numbers in case we need them
1330 $version = $wgDatabase->getServerVersion(); ## long string
1331 $numver = $wgDatabase->numeric_version; ## X.Y e.g. 8.3
1333 $wgShowExceptionDetails = 1;
1335 # Just in case their LocalSettings.php does not have this:
1336 if ( !isset( $wgDBmwschema ))
1337 $wgDBmwschema = 'mediawiki';
1339 # Verify that this user is configured correctly
1340 $safeuser = $wgDatabase->addQuotes($wgDBuser);
1341 $SQL = "SELECT array_to_string(useconfig,'*') FROM pg_catalog.pg_user WHERE usename = $safeuser";
1342 $config = pg_fetch_result( $wgDatabase->doQuery( $SQL ), 0, 0 );
1344 foreach( explode( '*', $config ) as $c ) {
1345 list( $x,$y ) = explode( '=', $c );
1348 if( !array_key_exists( 'search_path', $conf ) ) {
1352 $search_path = $conf['search_path'];
1354 if( strpos( $search_path, $wgDBmwschema ) === false ) {
1355 echo "Adding in schema \"$wgDBmwschema\" to search_path for user \"$wgDBuser\"\n";
1356 $search_path = "$wgDBmwschema, $search_path";
1358 if( strpos( $search_path, $wgDBts2schema ) === false ) {
1359 echo "Adding in schema \"$wgDBts2schema\" to search_path for user \"$wgDBuser\"\n";
1360 $search_path = "$search_path, $wgDBts2schema";
1362 if( array_key_exists( 'search_path', $conf ) === false || $search_path != $conf['search_path'] ) {
1363 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET search_path = $search_path" );
1364 $wgDatabase->doQuery( "SET search_path = $search_path" );
1367 $path = $conf['search_path'];
1368 echo "... search_path for user \"$wgDBuser\" looks correct ($path)\n";
1371 'client_min_messages' => 'error',
1372 'DateStyle' => 'ISO, YMD',
1375 foreach( array_keys( $goodconf ) AS $key ) {
1376 $value = $goodconf[$key];
1377 if( !array_key_exists( $key, $conf ) or $conf[$key] !== $value ) {
1378 echo "Setting $key to '$value' for user \"$wgDBuser\"\n";
1379 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET $key = '$value'" );
1380 $wgDatabase->doQuery( "SET $key = '$value'" );
1383 echo "... default value of \"$key\" is correctly set to \"$value\" for user \"$wgDBuser\"\n";
1387 $newsequences = array(
1393 array("category", "patch-category.sql"),
1394 array("mediawiki_version", "patch-mediawiki_version.sql"),
1395 array("mwuser", "patch-mwuser.sql"),
1396 array("pagecontent", "patch-pagecontent.sql"),
1397 array("querycachetwo", "patch-querycachetwo.sql"),
1398 array("page_props", "patch-page_props.sql"),
1399 array("page_restrictions", "patch-page_restrictions.sql"),
1400 array("profiling", "patch-profiling.sql"),
1401 array("protected_titles", "patch-protected_titles.sql"),
1402 array("redirect", "patch-redirect.sql"),
1403 array("updatelog", "patch-updatelog.sql"),
1407 array("archive", "ar_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1408 array("archive", "ar_len", "INTEGER"),
1409 array("archive", "ar_page_id", "INTEGER"),
1410 array("archive", "ar_parent_id", "INTEGER"),
1411 array("image", "img_sha1", "TEXT NOT NULL DEFAULT ''"),
1412 array("ipblocks", "ipb_anon_only", "CHAR NOT NULL DEFAULT '0'"),
1413 array("ipblocks", "ipb_by_text", "TEXT NOT NULL DEFAULT ''"),
1414 array("ipblocks", "ipb_block_email", "CHAR NOT NULL DEFAULT '0'"),
1415 array("ipblocks", "ipb_create_account", "CHAR NOT NULL DEFAULT '1'"),
1416 array("ipblocks", "ipb_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1417 array("ipblocks", "ipb_enable_autoblock", "CHAR NOT NULL DEFAULT '1'"),
1418 array("filearchive", "fa_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1419 array("logging", "log_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1420 array("logging", "log_id", "INTEGER NOT NULL PRIMARY KEY DEFAULT nextval('log_log_id_seq')"),
1421 array("logging", "log_params", "TEXT"),
1422 array("mwuser", "user_editcount", "INTEGER"),
1423 array("mwuser", "user_newpass_time", "TIMESTAMPTZ"),
1424 array("oldimage", "oi_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1425 array("oldimage", "oi_metadata", "BYTEA NOT NULL DEFAULT ''"),
1426 array("oldimage", "oi_media_type", "TEXT"),
1427 array("oldimage", "oi_major_mime", "TEXT NOT NULL DEFAULT 'unknown'"),
1428 array("oldimage", "oi_minor_mime", "TEXT NOT NULL DEFAULT 'unknown'"),
1429 array("oldimage", "oi_sha1", "TEXT NOT NULL DEFAULT ''"),
1430 array("page_restrictions", "pr_id", "INTEGER NOT NULL UNIQUE DEFAULT nextval('pr_id_val')"),
1431 array("profiling", "pf_memory", "NUMERIC(18,10) NOT NULL DEFAULT 0"),
1432 array("recentchanges", "rc_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1433 array("recentchanges", "rc_log_action", "TEXT"),
1434 array("recentchanges", "rc_log_type", "TEXT"),
1435 array("recentchanges", "rc_logid", "INTEGER NOT NULL DEFAULT 0"),
1436 array("recentchanges", "rc_new_len", "INTEGER"),
1437 array("recentchanges", "rc_old_len", "INTEGER"),
1438 array("recentchanges", "rc_params", "TEXT"),
1439 array("revision", "rev_len", "INTEGER"),
1440 array("revision", "rev_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1441 array("user_newtalk", "user_last_timestamp", "TIMESTAMPTZ"),
1445 # table, column, desired type, USING clause if needed (with new default if needed)
1446 $typechanges = array(
1447 array("archive", "ar_deleted", "smallint", ""),
1448 array("archive", "ar_minor_edit", "smallint", "ar_minor_edit::smallint DEFAULT 0"),
1449 array("filearchive", "fa_deleted", "smallint", ""),
1450 array("filearchive", "fa_height", "integer", ""),
1451 array("filearchive", "fa_metadata", "bytea", "decode(fa_metadata,'escape')"),
1452 array("filearchive", "fa_size", "integer", ""),
1453 array("filearchive", "fa_width", "integer", ""),
1454 array("filearchive", "fa_storage_group","text", ""),
1455 array("filearchive", "fa_storage_key", "text", ""),
1456 array("image", "img_metadata", "bytea", "decode(img_metadata,'escape')"),
1457 array("image", "img_size", "integer", ""),
1458 array("image", "img_width", "integer", ""),
1459 array("image", "img_height", "integer", ""),
1460 array("interwiki", "iw_local", "smallint", "iw_local::smallint DEFAULT 0"),
1461 array("interwiki", "iw_trans", "smallint", "iw_trans::smallint DEFAULT 0"),
1462 array("ipblocks", "ipb_auto", "smallint", "ipb_auto::smallint DEFAULT 0"),
1463 array("ipblocks", "ipb_anon_only", "smallint", "ipb_anon_only::smallint DEFAULT 0"),
1464 array("ipblocks", "ipb_create_account", "smallint", "ipb_create_account::smallint DEFAULT 1"),
1465 array("ipblocks", "ipb_enable_autoblock", "smallint", "ipb_enable_autoblock::smallint DEFAULT 1"),
1466 array("ipblocks", "ipb_block_email", "smallint", "ipb_block_email::smallint DEFAULT 0"),
1467 array("ipblocks", "ipb_address", "text", "ipb_address::text"),
1468 array("ipblocks", "ipb_deleted", "smallint", "ipb_deleted::smallint"),
1469 array("math", "math_inputhash", "bytea", "decode(math_inputhash,'escape')"),
1470 array("math", "math_outputhash", "bytea", "decode(math_outputhash,'escape')"),
1471 array("mwuser", "user_token", "text", ""),
1472 array("mwuser", "user_email_token","text", ""),
1473 array("objectcache", "keyname", "text", ""),
1474 array("oldimage", "oi_height", "integer", ""),
1475 array("oldimage", "oi_size", "integer", ""),
1476 array("oldimage", "oi_width", "integer", ""),
1477 array("page", "page_is_redirect","smallint", "page_is_redirect::smallint DEFAULT 0"),
1478 array("page", "page_is_new", "smallint", "page_is_new::smallint DEFAULT 0"),
1479 array("querycache", "qc_value", "integer", ""),
1480 array("querycachetwo","qcc_value", "integer", ""),
1481 array("recentchanges","rc_bot", "smallint", "rc_bot::smallint DEFAULT 0"),
1482 array("recentchanges","rc_deleted", "smallint", ""),
1483 array("recentchanges","rc_minor", "smallint", "rc_minor::smallint DEFAULT 0"),
1484 array("recentchanges","rc_new", "smallint", "rc_new::smallint DEFAULT 0"),
1485 array("recentchanges","rc_type", "smallint", "rc_type::smallint DEFAULT 0"),
1486 array("recentchanges","rc_patrolled", "smallint", "rc_patrolled::smallint DEFAULT 0"),
1487 array("revision", "rev_deleted", "smallint", "rev_deleted::smallint DEFAULT 0"),
1488 array("revision", "rev_minor_edit", "smallint", "rev_minor_edit::smallint DEFAULT 0"),
1489 array("templatelinks","tl_namespace", "smallint", "tl_namespace::smallint"),
1490 array("user_newtalk", "user_ip", "text", "host(user_ip)"),
1493 $newindexes = array(
1494 array("archive", "archive_user_text", "(ar_user_text)"),
1495 array("image", "img_sha1", "(img_sha1)"),
1496 array("oldimage", "oi_sha1", "(oi_sha1)"),
1497 array("revision", "rev_text_id_idx", "(rev_text_id)"),
1503 foreach ($newsequences as $ns) {
1504 if ($wgDatabase->sequenceExists($ns)) {
1505 echo "... sequence \"$ns\" already exists\n";
1509 echo "Creating sequence \"$ns\"\n";
1510 $wgDatabase->query("CREATE SEQUENCE $ns");
1513 foreach ($newtables as $nt) {
1514 if ($wgDatabase->tableExists($nt[0])) {
1515 echo "... table \"$nt[0]\" already exists\n";
1519 echo "Creating table \"$nt[0]\"\n";
1520 dbsource(archive($nt[1]));
1523 ## Needed before newcols
1524 if ($wgDatabase->tableExists("archive2")) {
1525 echo "Converting \"archive2\" back to normal archive table\n";
1526 if ($wgDatabase->ruleExists("archive", "archive_insert")) {
1527 echo "Dropping rule \"archive_insert\"\n";
1528 $wgDatabase->query("DROP RULE archive_insert ON archive");
1530 if ($wgDatabase->ruleExists("archive", "archive_delete")) {
1531 echo "Dropping rule \"archive_delete\"\n";
1532 $wgDatabase->query("DROP RULE archive_delete ON archive");
1534 dbsource(archive("patch-remove-archive2.sql"));
1537 echo "... obsolete table \"archive2\" does not exist\n";
1539 foreach ($newcols as $nc) {
1540 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1541 if (!is_null($fi)) {
1542 echo "... column \"$nc[0].$nc[1]\" already exists\n";
1546 echo "Adding column \"$nc[0].$nc[1]\"\n";
1547 $wgDatabase->query("ALTER TABLE $nc[0] ADD $nc[1] $nc[2]");
1550 foreach ($typechanges as $tc) {
1551 $fi = $wgDatabase->fieldInfo($tc[0], $tc[1]);
1553 echo "... error: expected column $tc[0].$tc[1] to exist\n";
1557 if ($fi->type() === $tc[2])
1558 echo "... column \"$tc[0].$tc[1]\" is already of type \"$tc[2]\"\n";
1560 echo "Changing column type of \"$tc[0].$tc[1]\" from \"{$fi->type()}\" to \"$tc[2]\"\n";
1561 $sql = "ALTER TABLE $tc[0] ALTER $tc[1] TYPE $tc[2]";
1562 if (strlen($tc[3])) {
1564 if (preg_match( '/DEFAULT (.+)/', $tc[3], $default)) {
1565 $sqldef = "ALTER TABLE $tc[0] ALTER $tc[1] SET DEFAULT $default[1]";
1566 $wgDatabase->query($sqldef);
1567 $tc[3] = preg_replace( '/\s*DEFAULT .+/', '', $tc[3]);
1569 $sql .= " USING $tc[3]";
1571 $sql .= ";\nCOMMIT;\n";
1572 $wgDatabase->query($sql);
1576 if ($wgDatabase->fieldInfo('oldimage','oi_deleted')->type() !== 'smallint') {
1577 echo "Changing \"oldimage.oi_deleted\" to type \"smallint\"\n";
1578 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted DROP DEFAULT" );
1579 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted TYPE SMALLINT USING (oi_deleted::smallint)" );
1580 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted SET DEFAULT 0" );
1583 echo "... column \"oldimage.oi_deleted\" is already of type \"smallint\"\n";
1586 foreach ($newindexes as $ni) {
1587 if (pg_index_exists($ni[0], $ni[1])) {
1588 echo "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n";
1591 echo "Creating index \"$ni[1]\" on table \"$ni[0]\" $ni[2]\n";
1592 $wgDatabase->query( "CREATE INDEX $ni[1] ON $ni[0] $ni[2]" );
1595 foreach ($newrules as $nr) {
1596 if ($wgDatabase->ruleExists($nr[0], $nr[1])) {
1597 echo "... rule \"$nr[1]\" on table \"$nr[0]\" already exists\n";
1600 echo "Adding rule \"$nr[1]\" to table \"$nr[0]\"\n";
1601 dbsource(archive($nr[2]));
1604 if ($wgDatabase->hasConstraint("oldimage_oi_name_fkey")) {
1605 echo "Making foriegn key on table \"oldimage\" (to image) a cascade delete\n";
1606 $wgDatabase->query( "ALTER TABLE oldimage DROP CONSTRAINT oldimage_oi_name_fkey" );
1607 $wgDatabase->query( "ALTER TABLE oldimage ADD CONSTRAINT oldimage_oi_name_fkey_cascade ".
1608 "FOREIGN KEY (oi_name) REFERENCES image(img_name) ON DELETE CASCADE" );
1611 echo "... table \"oldimage\" has correct cascade delete foreign key to image\n";
1613 if (!$wgDatabase->triggerExists("page", "page_deleted")) {
1614 echo "Adding function and trigger \"page_deleted\" to table \"page\"\n";
1615 dbsource(archive('patch-page_deleted.sql'));
1618 echo "... table \"page\" has \"page_deleted\" trigger\n";
1620 $fi = $wgDatabase->fieldInfo("recentchanges", "rc_cur_id");
1621 if (!$fi->nullable()) {
1622 echo "Removing NOT NULL constraint from \"recentchanges.rc_cur_id\"\n";
1623 dbsource(archive('patch-rc_cur_id-not-null.sql'));
1626 echo "... column \"recentchanges.rc_cur_id\" has a NOT NULL constraint\n";
1628 $pu = pg_describe_index("pagelink_unique");
1629 if (!is_null($pu) && ($pu[0] != "pl_from" || $pu[1] != "pl_namespace" || $pu[2] != "pl_title")) {
1630 echo "Dropping obsolete version of index \"pagelink_unique index\"\n";
1631 $wgDatabase->query("DROP INDEX pagelink_unique");
1635 echo "... obsolete version of index \"pagelink_unique index\" does not exist\n";
1638 echo "Creating index \"pagelink_unique index\"\n";
1639 $wgDatabase->query("CREATE UNIQUE INDEX pagelink_unique ON pagelinks (pl_from,pl_namespace,pl_title)");
1642 echo "... index \"pagelink_unique_index\" aready exists\n";
1644 if (pg_fkey_deltype("revision_rev_user_fkey") == 'r') {
1645 echo "... constraint \"revision_rev_user_fkey\" is ON DELETE RESTRICT\n";
1648 echo "Changing constraint \"revision_rev_user_fkey\" to ON DELETE RESTRICT\n";
1649 dbsource(archive('patch-revision_rev_user_fkey.sql'));
1652 global $wgExtNewTables, $wgExtPGNewFields, $wgExtNewIndexes;
1653 # Add missing extension tables
1654 foreach ( $wgExtNewTables as $nt ) {
1655 if ($wgDatabase->tableExists($nt[0])) {
1656 echo "... table \"$nt[0]\" already exists\n";
1659 echo "Creating table \"$nt[0]\"\n";
1662 # Add missing extension fields
1663 foreach ( $wgExtPGNewFields as $nc ) {
1664 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1665 if (!is_null($fi)) {
1666 echo "... column \"$nc[0].$nc[1]\" already exists\n";
1669 echo "Adding column \"$nc[0].$nc[1]\"\n";
1670 $wgDatabase->query( "ALTER TABLE $nc[0] ADD $nc[1] $nc[2]" );
1672 # Add missing extension indexes
1673 foreach ( $wgExtNewIndexes as $ni ) {
1674 if (pg_index_exists($ni[0], $ni[1])) {
1675 echo "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n";
1678 echo "Creating index \"$ni[1]\" on table \"$ni[0]\"\n";
1682 # Tweak the page_title tsearch2 trigger to filter out slashes
1683 # This is create or replace, so harmless to call if not needed
1684 dbsource(archive('patch-ts2pagetitle.sql'));
1686 ## If the server is 8.3 or higher, rewrite teh tsearch2 triggers
1687 ## in case they have the old 'default' versions
1688 if ( $numver >= 8.3 )
1689 dbsource(archive('patch-tsearch2funcs.sql'));