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 for each DB type, in sequence. First item
20 * is function name, rest are parameters to pass.
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( 'check_bin', 'logging', 'log_title', 'patch-logging-title.sql', ),
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( 'add_field', 'user_newtalk', 'user_last_timestamp', 'patch-user_last_timestamp.sql'),
142 array( 'do_populate_parent_id' ),
143 array( 'check_bin', 'protected_titles', 'pt_title', 'patch-pt_title-encoding.sql', ),
144 array( 'maybe_do_profiling_memory_update' ),
145 array( 'do_filearchive_indices_update' ),
146 array( 'update_password_format' ),
149 array( 'add_field', 'site_stats', 'ss_active_users', 'patch-ss_active_users.sql' ),
150 array( 'do_active_users_init' ),
151 array( 'add_field', 'ipblocks', 'ipb_allow_usertalk', 'patch-ipb_allow_usertalk.sql' ),
152 array( 'add_index', 'user_newtalk', 'un_user_id', 'patch-index-renames.sql' ),
153 array( 'do_unique_pl_tl_il' ),
158 array( 'add_field', 'site_stats', 'ss_active_users', 'patch-ss_active_users.sql' ),
159 array( 'do_active_users_init' ),
160 array( 'add_field', 'ipblocks', 'ipb_allow_usertalk', 'patch-ipb_allow_usertalk.sql' ),
161 array( 'sqlite_initial_indexes' ),
166 # For extensions only, should be populated via hooks
167 # $wgDBtype should be checked to specifiy the proper file
168 $wgExtNewTables = array(); // table, dir
169 $wgExtNewFields = array(); // table, column, dir
170 $wgExtPGNewFields = array(); // table, column attributes; for PostgreSQL
171 $wgExtNewIndexes = array(); // table, index, dir
173 # Helper function: check if the given key is present in the updatelog table.
174 # Obviously, only use this for updates that occur after the updatelog table was
176 function update_row_exists( $key ) {
177 $dbr = wfGetDB( DB_SLAVE );
178 $row = $dbr->selectRow(
181 array( 'ul_key' => $key ),
187 function rename_table( $from, $to, $patch ) {
189 if ( $wgDatabase->tableExists( $from ) ) {
190 if ( $wgDatabase->tableExists( $to ) ) {
191 echo "...can't move table $from to $to, $to already exists.\n";
193 echo "Moving table $from to $to...";
194 dbsource( archive($patch), $wgDatabase );
198 // Source table does not exist
199 // Renames are done before creations, so this is typical for a new installation
204 function add_table( $name, $patch, $fullpath=false ) {
206 if ( $wgDatabase->tableExists( $name ) ) {
207 echo "...$name table already exists.\n";
209 echo "Creating $name table...";
211 dbsource( $patch, $wgDatabase );
213 dbsource( archive($patch), $wgDatabase );
219 function add_field( $table, $field, $patch, $fullpath=false ) {
221 if ( !$wgDatabase->tableExists( $table ) ) {
222 echo "...$table table does not exist, skipping new field patch\n";
223 } elseif ( $wgDatabase->fieldExists( $table, $field ) ) {
224 echo "...have $field field in $table table.\n";
226 echo "Adding $field field to table $table...";
228 dbsource( $patch, $wgDatabase );
230 dbsource( archive($patch), $wgDatabase );
236 function add_index( $table, $index, $patch, $fullpath=false ) {
238 if( $wgDatabase->indexExists( $table, $index ) ) {
239 echo "...$index key already set on $table table.\n";
241 echo "Adding $index key to table $table... ";
243 dbsource( $patch, $wgDatabase );
245 dbsource( archive($patch), $wgDatabase );
251 function do_revision_updates() {
252 global $wgSoftwareRevision;
253 if ( $wgSoftwareRevision < 1001 ) {
258 function update_passwords() {
259 wfDebugDieBacktrace( "This function needs to be updated or removed.\n" );
262 $fname = "Update script: update_passwords()";
263 print "\nIt appears that you need to update the user passwords in your\n" .
264 "database. If you have already done this (if you've run this update\n" .
265 "script once before, for example), doing so again will make all your\n" .
266 "user accounts inaccessible, so be sure you only do this once.\n" .
267 "Update user passwords? (yes/no)";
269 $resp = readconsole();
270 if ( ! ( "Y" == $resp{0} || "y" == $resp{0} ) ) { return; }
272 $sql = "SELECT user_id,user_password FROM user";
273 $source = $wgDatabase->query( $sql, $fname );
275 while ( $row = $wgDatabase->fetchObject( $source ) ) {
277 $oldpass = $row->user_password;
278 $newpass = md5( "{$id}-{$oldpass}" );
280 $sql = "UPDATE user SET user_password='{$newpass}' " .
281 "WHERE user_id={$id}";
282 $wgDatabase->query( $sql, $fname );
286 function do_interwiki_update() {
287 # Check that interwiki table exists; if it doesn't source it
288 global $wgDatabase, $IP;
289 if( $wgDatabase->tableExists( "interwiki" ) ) {
290 echo "...already have interwiki table\n";
293 echo "Creating interwiki table: ";
294 dbsource( archive("patch-interwiki.sql") );
296 echo "Adding default interwiki definitions: ";
297 dbsource( "$IP/maintenance/interwiki.sql" );
301 function do_index_update() {
302 # Check that proper indexes are in place
304 $meta = $wgDatabase->fieldInfo( "recentchanges", "rc_timestamp" );
305 if( !$meta->isMultipleKey() ) {
306 echo "Updating indexes to 20031107: ";
307 dbsource( archive("patch-indexes.sql") );
311 echo "...indexes seem up to 20031107 standards\n";
315 function do_image_index_update() {
318 $meta = $wgDatabase->fieldInfo( "image", "img_major_mime" );
319 if( !$meta->isMultipleKey() ) {
320 echo "Updating indexes to 20050912: ";
321 dbsource( archive("patch-mimesearch-indexes.sql") );
325 echo "...indexes seem up to 20050912 standards\n";
329 function do_image_name_unique_update() {
331 if( $wgDatabase->indexExists( 'image', 'PRIMARY' ) ) {
332 echo "...image primary key already set.\n";
334 echo "Making img_name the primary key... ";
335 dbsource( archive("patch-image_name_primary.sql"), $wgDatabase );
340 function do_logging_timestamp_index() {
342 if( $wgDatabase->indexExists( 'logging', 'times' ) ) {
343 echo "...timestamp key on logging already exists.\n";
345 echo "Adding timestamp key on logging table... ";
346 dbsource( archive("patch-logging-times-index.sql"), $wgDatabase );
351 function do_archive_user_index() {
353 if( $wgDatabase->indexExists( 'archive', 'usertext_timestamp' ) ) {
354 echo "...usertext,timestamp key on archive already exists.\n";
356 echo "Adding usertext,timestamp key on archive table... ";
357 dbsource( archive("patch-archive-user-index.sql"), $wgDatabase );
362 function do_image_user_index() {
364 if( $wgDatabase->indexExists( 'image', 'img_usertext_timestamp' ) ) {
365 echo "...usertext,timestamp key on image already exists.\n";
367 echo "Adding usertext,timestamp key on image table... ";
368 dbsource( archive("patch-image-user-index.sql"), $wgDatabase );
373 function do_oldimage_user_index() {
375 if( $wgDatabase->indexExists( 'oldimage', 'oi_usertext_timestamp' ) ) {
376 echo "...usertext,timestamp key on oldimage already exists.\n";
378 echo "Adding usertext,timestamp key on oldimage table... ";
379 dbsource( archive("patch-oldimage-user-index.sql"), $wgDatabase );
384 function do_watchlist_update() {
386 $fname = 'do_watchlist_update';
387 if( $wgDatabase->fieldExists( 'watchlist', 'wl_notificationtimestamp' ) ) {
388 echo "The watchlist table is already set up for email notification.\n";
390 echo "Adding wl_notificationtimestamp field for email notification management.";
391 /* ALTER TABLE watchlist ADD (wl_notificationtimestamp varchar(14) binary NOT NULL default '0'); */
392 dbsource( archive( 'patch-email-notification.sql' ), $wgDatabase );
395 # Check if we need to add talk page rows to the watchlist
396 $talk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'wl_namespace & 1', $fname );
397 $nontalk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'NOT (wl_namespace & 1)', $fname );
398 if ( $talk != $nontalk ) {
399 echo "Adding missing watchlist talk page rows... ";
402 $wgDatabase->insertSelect( 'watchlist', 'watchlist',
404 'wl_user' => 'wl_user',
405 'wl_namespace' => 'wl_namespace | 1',
406 'wl_title' => 'wl_title',
407 'wl_notificationtimestamp' => 'wl_notificationtimestamp'
408 ), array( 'NOT (wl_namespace & 1)' ), $fname, 'IGNORE' );
411 echo "...watchlist talk page rows already present\n";
415 function do_copy_newtalk_to_watchlist() {
417 global $wgCommandLineMode; # this needs to be saved while getID() and getName() are called
419 $res = $wgDatabase->safeQuery( 'SELECT user_id, user_ip FROM !',
420 $wgDatabase->tableName( 'user_newtalk' ) );
421 $num_newtalks=$wgDatabase->numRows($res);
422 echo "Now converting ".$num_newtalks." user_newtalk entries to watchlist table entries ... \n";
425 for ( $i = 1; $i <= $num_newtalks; $i++ ) {
426 $wluser = $wgDatabase->fetchObject( $res );
427 if ($wluser->user_id == 0) { # anonymous users ... have IP numbers as "names"
428 if ($user->isIP($wluser->user_ip)) { # do only if it really looks like an IP number (double checked)
429 $wgDatabase->replace( 'watchlist',
430 array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
431 array('wl_user' => 0,
432 'wl_namespace' => NS_USER_TALK,
433 'wl_title' => $wluser->user_ip,
434 'wl_notificationtimestamp' => '19700101000000'
435 ), 'updaters.inc::do_watchlist_update2'
438 } else { # normal users ... have user_ids
439 $user->setID($wluser->user_id);
440 $wgDatabase->replace( 'watchlist',
441 array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
442 array('wl_user' => $user->getID(),
443 'wl_namespace' => NS_USER_TALK,
444 'wl_title' => $user->getName(),
445 'wl_notificationtimestamp' => '19700101000000'
446 ), 'updaters.inc::do_watchlist_update3'
454 function do_user_update() {
456 if( $wgDatabase->fieldExists( 'user', 'user_emailauthenticationtimestamp' ) ) {
457 echo "User table contains old email authentication field. Dropping... ";
458 dbsource( archive( 'patch-email-authentication.sql' ), $wgDatabase );
461 echo "...user table does not contain old email authentication field.\n";
466 * 1.4 betas were missing the 'binary' marker from logging.log_title,
467 * which causes a collation mismatch error on joins in MySQL 4.1.
469 function check_bin( $table, $field, $patchFile ) {
470 global $wgDatabase, $wgDBtype;
471 if ($wgDBtype != 'mysql')
473 $tableName = $wgDatabase->tableName( $table );
474 $res = $wgDatabase->query( "SELECT $field FROM $tableName LIMIT 0" );
475 $flags = explode( ' ', mysql_field_flags( $res->result, 0 ) );
476 $wgDatabase->freeResult( $res );
478 if( in_array( 'binary', $flags ) ) {
479 echo "$table table has correct $field encoding.\n";
481 echo "Fixing $field encoding on $table table... ";
482 dbsource( archive( $patchFile ), $wgDatabase );
487 function do_schema_restructuring() {
489 $fname="do_schema_restructuring";
490 if ( $wgDatabase->tableExists( 'page' ) ) {
491 echo "...page table already exists.\n";
493 echo "...converting from cur/old to page/revision/text DB structure.\n"; flush();
494 echo wfTimestamp( TS_DB );
495 echo "......checking for duplicate entries.\n"; flush();
497 list ($cur, $old, $page, $revision, $text) = $wgDatabase->tableNamesN( 'cur', 'old', 'page', 'revision', 'text' );
499 $rows = $wgDatabase->query( "SELECT cur_title, cur_namespace, COUNT(cur_namespace) AS c
500 FROM $cur GROUP BY cur_title, cur_namespace HAVING c>1", $fname );
502 if ( $wgDatabase->numRows( $rows ) > 0 ) {
503 echo wfTimestamp( TS_DB );
504 echo "......<b>Found duplicate entries</b>\n";
505 echo ( sprintf( "<b> %-60s %3s %5s</b>\n", 'Title', 'NS', 'Count' ) );
506 while ( $row = $wgDatabase->fetchObject( $rows ) ) {
507 if ( ! isset( $duplicate[$row->cur_namespace] ) ) {
508 $duplicate[$row->cur_namespace] = array();
510 $duplicate[$row->cur_namespace][] = $row->cur_title;
511 echo ( sprintf( " %-60s %3s %5s\n", $row->cur_title, $row->cur_namespace, $row->c ) );
513 $sql = "SELECT cur_title, cur_namespace, cur_id, cur_timestamp FROM $cur WHERE ";
515 foreach ( $duplicate as $ns => $titles ) {
521 $sql .= "( cur_namespace = {$ns} AND cur_title in (";
523 foreach ( $titles as $t ) {
525 $sql .= $wgDatabase->addQuotes( $t );
528 $sql .= ', ' . $wgDatabase->addQuotes( $t );
533 # By sorting descending, the most recent entry will be the first in the list.
534 # All following entries will be deleted by the next while-loop.
535 $sql .= 'ORDER BY cur_namespace, cur_title, cur_timestamp DESC';
537 $rows = $wgDatabase->query( $sql, $fname );
539 $prev_title = $prev_namespace = false;
542 while ( $row = $wgDatabase->fetchObject( $rows ) ) {
543 if ( $prev_title == $row->cur_title && $prev_namespace == $row->cur_namespace ) {
544 $deleteId[] = $row->cur_id;
546 $prev_title = $row->cur_title;
547 $prev_namespace = $row->cur_namespace;
549 $sql = "DELETE FROM $cur WHERE cur_id IN ( " . join( ',', $deleteId ) . ')';
550 $rows = $wgDatabase->query( $sql, $fname );
551 echo wfTimestamp( TS_DB );
552 echo "......<b>Deleted</b> ".$wgDatabase->affectedRows()." records.\n";
556 echo wfTimestamp( TS_DB );
557 echo "......Creating tables.\n";
558 $wgDatabase->query("CREATE TABLE $page (
559 page_id int(8) unsigned NOT NULL auto_increment,
560 page_namespace int NOT NULL,
561 page_title varchar(255) binary NOT NULL,
562 page_restrictions tinyblob NOT NULL,
563 page_counter bigint(20) unsigned NOT NULL default '0',
564 page_is_redirect tinyint(1) unsigned NOT NULL default '0',
565 page_is_new tinyint(1) unsigned NOT NULL default '0',
566 page_random real unsigned NOT NULL,
567 page_touched char(14) binary NOT NULL default '',
568 page_latest int(8) unsigned NOT NULL,
569 page_len int(8) unsigned NOT NULL,
571 PRIMARY KEY page_id (page_id),
572 UNIQUE INDEX name_title (page_namespace,page_title),
575 ) ENGINE=InnoDB", $fname );
576 $wgDatabase->query("CREATE TABLE $revision (
577 rev_id int(8) unsigned NOT NULL auto_increment,
578 rev_page int(8) unsigned NOT NULL,
579 rev_comment tinyblob NOT NULL,
580 rev_user int(5) unsigned NOT NULL default '0',
581 rev_user_text varchar(255) binary NOT NULL default '',
582 rev_timestamp char(14) binary NOT NULL default '',
583 rev_minor_edit tinyint(1) unsigned NOT NULL default '0',
584 rev_deleted tinyint(1) unsigned NOT NULL default '0',
585 rev_len int(8) unsigned,
586 rev_parent_id int(8) unsigned default NULL,
587 PRIMARY KEY rev_page_id (rev_page, rev_id),
588 UNIQUE INDEX rev_id (rev_id),
589 INDEX rev_timestamp (rev_timestamp),
590 INDEX page_timestamp (rev_page,rev_timestamp),
591 INDEX user_timestamp (rev_user,rev_timestamp),
592 INDEX usertext_timestamp (rev_user_text,rev_timestamp)
593 ) ENGINE=InnoDB", $fname );
595 echo wfTimestamp( TS_DB );
596 echo "......Locking tables.\n";
597 $wgDatabase->query( "LOCK TABLES $page WRITE, $revision WRITE, $old WRITE, $cur WRITE", $fname );
599 $maxold = intval( $wgDatabase->selectField( 'old', 'max(old_id)', '', $fname ) );
600 echo wfTimestamp( TS_DB );
601 echo "......maxold is {$maxold}\n";
603 echo wfTimestamp( TS_DB );
604 global $wgLegacySchemaConversion;
605 if( $wgLegacySchemaConversion ) {
606 // Create HistoryBlobCurStub entries.
607 // Text will be pulled from the leftover 'cur' table at runtime.
608 echo "......Moving metadata from cur; using blob references to text in cur table.\n";
609 $cur_text = "concat('O:18:\"historyblobcurstub\":1:{s:6:\"mCurId\";i:',cur_id,';}')";
610 $cur_flags = "'object'";
612 // Copy all cur text in immediately: this may take longer but avoids
613 // having to keep an extra table around.
614 echo "......Moving text from cur.\n";
615 $cur_text = 'cur_text';
618 $wgDatabase->query( "INSERT INTO $old (old_namespace, old_title, old_text, old_comment, old_user, old_user_text,
619 old_timestamp, old_minor_edit, old_flags)
620 SELECT cur_namespace, cur_title, $cur_text, cur_comment, cur_user, cur_user_text, cur_timestamp, cur_minor_edit, $cur_flags
621 FROM $cur", $fname );
623 echo wfTimestamp( TS_DB );
624 echo "......Setting up revision table.\n";
625 $wgDatabase->query( "INSERT INTO $revision (rev_id, rev_page, rev_comment, rev_user, rev_user_text, rev_timestamp,
627 SELECT old_id, cur_id, old_comment, old_user, old_user_text,
628 old_timestamp, old_minor_edit
629 FROM $old,$cur WHERE old_namespace=cur_namespace AND old_title=cur_title", $fname );
631 echo wfTimestamp( TS_DB );
632 echo "......Setting up page table.\n";
633 $wgDatabase->query( "INSERT INTO $page (page_id, page_namespace, page_title, page_restrictions, page_counter,
634 page_is_redirect, page_is_new, page_random, page_touched, page_latest, page_len)
635 SELECT cur_id, cur_namespace, cur_title, cur_restrictions, cur_counter, cur_is_redirect, cur_is_new,
636 cur_random, cur_touched, rev_id, LENGTH(cur_text)
638 WHERE cur_id=rev_page AND rev_timestamp=cur_timestamp AND rev_id > {$maxold}", $fname );
640 echo wfTimestamp( TS_DB );
641 echo "......Unlocking tables.\n";
642 $wgDatabase->query( "UNLOCK TABLES", $fname );
644 echo wfTimestamp( TS_DB );
645 echo "......Renaming old.\n";
646 $wgDatabase->query( "ALTER TABLE $old RENAME TO $text", $fname );
648 echo wfTimestamp( TS_DB );
653 function do_inverse_timestamp() {
655 if( $wgDatabase->fieldExists( 'revision', 'inverse_timestamp' ) ) {
656 echo "Removing revision.inverse_timestamp and fixing indexes... ";
657 dbsource( archive( 'patch-inverse_timestamp.sql' ), $wgDatabase );
660 echo "revision timestamp indexes already up to 2005-03-13\n";
664 function do_text_id() {
666 if( $wgDatabase->fieldExists( 'revision', 'rev_text_id' ) ) {
667 echo "...rev_text_id already in place.\n";
669 echo "Adding rev_text_id field... ";
670 dbsource( archive( 'patch-rev_text_id.sql' ), $wgDatabase );
675 function do_namespace_size() {
679 'recentchanges' => 'rc',
681 'querycache' => 'qc',
684 foreach( $tables as $table => $prefix ) {
685 do_namespace_size_on( $table, $prefix );
690 function do_namespace_size_on( $table, $prefix ) {
691 global $wgDatabase, $wgDBtype;
692 if ($wgDBtype != 'mysql')
694 $field = $prefix . '_namespace';
696 $tablename = $wgDatabase->tableName( $table );
697 $result = $wgDatabase->query( "SHOW COLUMNS FROM $tablename LIKE '$field'" );
698 $info = $wgDatabase->fetchObject( $result );
699 $wgDatabase->freeResult( $result );
701 if( substr( $info->Type, 0, 3 ) == 'int' ) {
702 echo "...$field is already a full int ($info->Type).\n";
704 echo "Promoting $field from $info->Type to int... ";
706 $sql = "ALTER TABLE $tablename MODIFY $field int NOT NULL";
707 $wgDatabase->query( $sql );
713 function do_pagelinks_update() {
715 if( $wgDatabase->tableExists( 'pagelinks' ) ) {
716 echo "...already have pagelinks table.\n";
718 echo "Converting links and brokenlinks tables to pagelinks... ";
719 dbsource( archive( 'patch-pagelinks.sql' ), $wgDatabase );
723 global $wgCanonicalNamespaceNames;
724 foreach( $wgCanonicalNamespaceNames as $ns => $name ) {
726 do_pagelinks_namespace( $ns );
732 function do_pagelinks_namespace( $namespace ) {
733 global $wgDatabase, $wgContLang;
735 $ns = intval( $namespace );
736 echo "Cleaning up broken links for namespace $ns... ";
738 $pagelinks = $wgDatabase->tableName( 'pagelinks' );
739 $name = $wgContLang->getNsText( $ns );
740 $prefix = $wgDatabase->strencode( $name );
741 $likeprefix = str_replace( '_', '\\_', $prefix);
743 $sql = "UPDATE $pagelinks
744 SET pl_namespace=$ns,
745 pl_title=TRIM(LEADING '$prefix:' FROM pl_title)
747 AND pl_title LIKE '$likeprefix:%'";
749 $wgDatabase->query( $sql, 'do_pagelinks_namespace' );
753 function do_drop_img_type() {
756 if( $wgDatabase->fieldExists( 'image', 'img_type' ) ) {
757 echo "Dropping unused img_type field in image table... ";
758 dbsource( archive( 'patch-drop_img_type.sql' ), $wgDatabase );
761 echo "No img_type field in image table; Good.\n";
765 function do_old_links_update() {
767 if( $wgDatabase->tableExists( 'pagelinks' ) ) {
768 echo "Already have pagelinks; skipping old links table updates.\n";
770 convertLinks(); flush();
774 function do_user_unique_update() {
776 $duper = new UserDupes( $wgDatabase );
777 if( $duper->hasUniqueIndex() ) {
778 echo "Already have unique user_name index.\n";
780 if( !$duper->clearDupes() ) {
781 echo "WARNING: This next step will probably fail due to unfixed duplicates...\n";
783 echo "Adding unique index on user_name... ";
784 dbsource( archive( 'patch-user_nameindex.sql' ), $wgDatabase );
789 function do_user_groups_update() {
790 $fname = 'do_user_groups_update';
793 if( $wgDatabase->tableExists( 'user_groups' ) ) {
794 echo "...user_groups table already exists.\n";
795 return do_user_groups_reformat();
798 echo "Adding user_groups table... ";
799 dbsource( archive( 'patch-user_groups.sql' ), $wgDatabase );
802 if( !$wgDatabase->tableExists( 'user_rights' ) ) {
803 if( $wgDatabase->fieldExists( 'user', 'user_rights' ) ) {
804 echo "Upgrading from a 1.3 or older database? Breaking out user_rights for conversion...";
805 dbsource( archive( 'patch-user_rights.sql' ), $wgDatabase );
808 echo "*** WARNING: couldn't locate user_rights table or field for upgrade.\n";
809 echo "*** You may need to manually configure some sysops by manipulating\n";
810 echo "*** the user_groups table.\n";
815 echo "Converting user_rights table to user_groups... ";
816 $result = $wgDatabase->select( 'user_rights',
817 array( 'ur_user', 'ur_rights' ),
818 array( "ur_rights != ''" ),
821 while( $row = $wgDatabase->fetchObject( $result ) ) {
822 $groups = array_unique(
824 explode( ',', $row->ur_rights ) ) );
826 foreach( $groups as $group ) {
827 $wgDatabase->insert( 'user_groups',
829 'ug_user' => $row->ur_user,
830 'ug_group' => $group ),
834 $wgDatabase->freeResult( $result );
838 function do_user_groups_reformat() {
839 # Check for bogus formats from previous 1.5 alpha code.
841 $info = $wgDatabase->fieldInfo( 'user_groups', 'ug_group' );
843 if( $info->type() == 'int' ) {
844 $oldug = $wgDatabase->tableName( 'user_groups' );
845 $newug = $wgDatabase->tableName( 'user_groups_bogus' );
846 echo "user_groups is in bogus intermediate format. Renaming to $newug... ";
847 $wgDatabase->query( "ALTER TABLE $oldug RENAME TO $newug" );
850 echo "Re-adding fresh user_groups table... ";
851 dbsource( archive( 'patch-user_groups.sql' ), $wgDatabase );
855 echo "*** WARNING: You will need to manually fix up user permissions in the user_groups\n";
856 echo "*** table. Old 1.5 alpha versions did some pretty funky stuff...\n";
859 echo "...user_groups is in current format.\n";
864 function do_watchlist_null() {
865 # Make sure wl_notificationtimestamp can be NULL,
866 # and update old broken items.
868 $info = $wgDatabase->fieldInfo( 'watchlist', 'wl_notificationtimestamp' );
870 if( !$info->nullable() ) {
871 echo "Making wl_notificationtimestamp nullable... ";
872 dbsource( archive( 'patch-watchlist-null.sql' ), $wgDatabase );
875 echo "...wl_notificationtimestamp is already nullable.\n";
883 function do_page_random_update() {
886 echo "Setting page_random to a random value on rows where it equals 0...";
888 $page = $wgDatabase->tableName( 'page' );
889 $wgDatabase->query( "UPDATE $page SET page_random = RAND() WHERE page_random = 0", 'do_page_random_update' );
890 $rows = $wgDatabase->affectedRows();
892 echo "changed $rows rows\n";
895 function do_templatelinks_update() {
896 global $wgDatabase, $wgLoadBalancer;
897 $fname = 'do_templatelinks_update';
899 if ( $wgDatabase->tableExists( 'templatelinks' ) ) {
900 echo "...templatelinks table already exists\n";
903 echo "Creating templatelinks table...\n";
904 dbsource( archive('patch-templatelinks.sql'), $wgDatabase );
905 echo "Populating...\n";
906 if ( isset( $wgLoadBalancer ) && $wgLoadBalancer->getServerCount() > 1 ) {
907 // Slow, replication-friendly update
908 $res = $wgDatabase->select( 'pagelinks', array( 'pl_from', 'pl_namespace', 'pl_title' ),
909 array( 'pl_namespace' => NS_TEMPLATE ), $fname );
911 while ( $row = $wgDatabase->fetchObject( $res ) ) {
912 $count = ($count + 1) % 100;
914 if ( function_exists( 'wfWaitForSlaves' ) ) {
915 wfWaitForSlaves( 10 );
920 $wgDatabase->insert( 'templatelinks',
922 'tl_from' => $row->pl_from,
923 'tl_namespace' => $row->pl_namespace,
924 'tl_title' => $row->pl_title,
929 $wgDatabase->freeResult( $res );
932 $wgDatabase->insertSelect( 'templatelinks', 'pagelinks',
934 'tl_from' => 'pl_from',
935 'tl_namespace' => 'pl_namespace',
936 'tl_title' => 'pl_title'
942 echo "Done. Please run maintenance/refreshLinks.php for a more thorough templatelinks update.\n";
945 // Add index on ( rc_namespace, rc_user_text ) [Jul. 2006]
946 // Add index on ( rc_user_text, rc_timestamp ) [Nov. 2006]
947 function do_rc_indices_update() {
949 echo( "Checking for additional recent changes indices...\n" );
952 'rc_ns_usertext' => 'patch-recentchanges-utindex.sql',
953 'rc_user_text' => 'patch-rc_user_text-index.sql',
956 foreach( $indexes as $index => $patch ) {
957 $info = $wgDatabase->indexInfo( 'recentchanges', $index, __METHOD__ );
959 echo( "...index `{$index}` not found; adding..." );
960 dbsource( archive( $patch ) );
963 echo( "...index `{$index}` seems ok.\n" );
968 function index_has_field($table, $index, $field) {
970 echo( "Checking if $table index $index includes field $field...\n" );
971 $info = $wgDatabase->indexInfo( $table, $index, __METHOD__ );
973 foreach($info as $row) {
974 if($row->Column_name == $field) {
975 echo( "...index $index on table $table seems to be ok\n" );
980 echo( "...index $index on table $table has no field $field; adding\n" );
984 function do_backlinking_indices_update() {
985 echo( "Checking for backlinking indices...\n" );
986 if (!index_has_field('pagelinks', 'pl_namespace', 'pl_from') ||
987 !index_has_field('templatelinks', 'tl_namespace', 'tl_from') ||
988 !index_has_field('imagelinks', 'il_to', 'il_from'))
990 dbsource( archive( 'patch-backlinkindexes.sql' ) );
991 echo( "...backlinking indices updated\n" );
995 function do_categorylinks_indices_update() {
996 echo( "Checking for categorylinks indices...\n" );
997 if (!index_has_field('categorylinks', 'cl_sortkey', 'cl_from'))
999 dbsource( archive( 'patch-categorylinksindex.sql' ) );
1000 echo( "...categorylinks indices updated\n" );
1004 function do_filearchive_indices_update() {
1006 echo( "Checking filearchive indices...\n" );
1007 $info = $wgDatabase->indexInfo( 'filearchive', 'fa_user_timestamp', __METHOD__ );
1010 dbsource( archive( 'patch-filearhive-user-index.sql' ) );
1011 echo( "...filearchive indices updated\n" );
1015 function maybe_do_profiling_memory_update() {
1017 if ( !$wgDatabase->tableExists( 'profiling' ) ) {
1019 } elseif ( $wgDatabase->fieldExists( 'profiling', 'pf_memory' ) ) {
1020 echo "profiling table has pf_memory field.\n";
1022 echo "Adding pf_memory field to table profiling...";
1023 dbsource( archive( 'patch-profiling-memory.sql' ), $wgDatabase );
1028 function do_stats_init() {
1029 // Sometimes site_stats table is not properly populated.
1031 echo "Checking site_stats row...";
1032 $row = $wgDatabase->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
1033 if( $row === false ) {
1034 echo "data is missing! rebuilding...\n";
1035 } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
1036 echo "missing ss_total_pages, rebuilding...\n";
1043 require_once "$IP/maintenance/initStats.inc";
1047 function do_active_users_init() {
1049 $activeUsers = $wgDatabase->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
1050 if( $activeUsers == -1 ) {
1051 $activeUsers = $wgDatabase->selectField( 'recentchanges',
1052 'COUNT( DISTINCT rc_user_text )',
1053 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
1055 $wgDatabase->update( 'site_stats',
1056 array( 'ss_active_users' => intval($activeUsers) ),
1057 array( 'ss_row_id' => 1 ), __METHOD__, array( 'LIMIT' => 1 )
1060 echo( "...ss_active_users user count set...\n" );
1063 function purge_cache() {
1065 # We can't guarantee that the user will be able to use TRUNCATE,
1066 # but we know that DELETE is available to us
1067 echo( "Purging caches..." );
1068 $wgDatabase->delete( 'objectcache', '*', __METHOD__ );
1072 function do_all_updates( $shared = false, $purge = true ) {
1073 global $wgNewTables, $wgNewFields, $wgRenamedTables, $wgSharedDB, $wgSharedTables, $wgDatabase, $wgDBtype, $IP;
1075 wfRunHooks('LoadExtensionSchemaUpdates');
1077 $doUser = $shared ? $wgSharedDB && in_array('user', $wgSharedTables) : !$wgSharedDB || !in_array('user', $wgSharedTables);
1079 if ($wgDBtype === 'postgres') {
1080 do_postgres_updates();
1084 # Run core updates in sequence...
1086 if ( isset( $wgUpdates[$wgDBtype] ) ) {
1087 foreach( $wgUpdates[$wgDBtype] as $params ) {
1088 $func = array_shift( $params );
1089 call_user_func_array( $func, $params );
1094 /// @fixme clean up this mess too!
1095 global $wgExtNewTables, $wgExtNewFields, $wgExtNewIndexes;
1096 # Add missing extension tables
1097 foreach ( $wgExtNewTables as $tableRecord ) {
1098 add_table( $tableRecord[0], $tableRecord[1], true );
1101 # Add missing extension fields
1102 foreach ( $wgExtNewFields as $fieldRecord ) {
1103 if ( $fieldRecord[0] != 'user' || $doUser ) {
1104 add_field( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true );
1108 # Add missing extension indexes
1109 foreach ( $wgExtNewIndexes as $fieldRecord ) {
1110 add_index( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true );
1115 echo "Deleting old default messages (this may take a long time!)..."; flush();
1116 deleteDefaultMessages();
1117 echo "Done\n"; flush();
1119 do_stats_init(); flush();
1127 function archive($name) {
1128 global $wgDBtype, $IP;
1129 if ( file_exists( "$IP/maintenance/$wgDBtype/archives/$name" ) ) {
1130 return "$IP/maintenance/$wgDBtype/archives/$name";
1132 return "$IP/maintenance/archives/$name";
1136 function do_restrictions_update() {
1137 # Adding page_restrictions table, obsoleting page.page_restrictions.
1138 # Migrating old restrictions to new table
1139 # -- Andrew Garrett, January 2007.
1143 $name = 'page_restrictions';
1144 $patch = 'patch-page_restrictions.sql';
1145 $patch2 = 'patch-page_restrictions_sortkey.sql';
1147 if ( $wgDatabase->tableExists( $name ) ) {
1148 echo "...$name table already exists.\n";
1150 echo "Creating $name table...";
1151 dbsource( archive($patch), $wgDatabase );
1152 dbsource( archive($patch2), $wgDatabase );
1155 echo "Migrating old restrictions to new table...";
1157 $res = $wgDatabase->select( 'page', array( 'page_id', 'page_restrictions' ), array("page_restrictions!=''", "page_restrictions!='edit=:move='"), __METHOD__ );
1161 while ($row = $wgDatabase->fetchObject($res) ) {
1162 $count = ($count + 1) % 100;
1165 if ( function_exists( 'wfWaitForSlaves' ) ) {
1166 wfWaitForSlaves( 10 );
1172 # Figure out what the restrictions are..
1173 $id = $row->page_id;
1174 $flatrestrictions = explode( ':', $row->page_restrictions );
1176 $restrictions = array ();
1177 foreach( $flatrestrictions as $restriction ) {
1178 $thisrestriction = explode( '=', $restriction, 2 );
1179 if( count( $thisrestriction ) == 1 ) {
1180 // Compatibility with old protections from before
1181 // separate move protection was added.
1182 list( $level ) = $thisrestriction;
1184 $restrictions['edit'] = $level;
1185 $restrictions['move'] = $level;
1188 list( $type, $level ) = $thisrestriction;
1190 $restrictions[$type] = $level;
1194 $wgDatabase->update( 'page', array ( 'page_restrictions' => ''), array( 'page_id' => $id ), __METHOD__ );
1198 foreach( $restrictions as $type => $level ) {
1199 $wgDatabase->insert( 'page_restrictions', array ( 'pr_page' => $id,
1201 'pr_level' => $level,
1203 'pr_expiry' => 'infinity' ),
1211 function do_category_population() {
1212 if( update_row_exists( 'populate category' ) ) {
1213 echo "...category table already populated.\n";
1216 require_once( 'populateCategory.inc' );
1217 echo "Populating category table, printing progress markers. ".
1218 "For large databases, you\n".
1219 "may want to hit Ctrl-C and do this manually with maintenance/\n".
1220 "populateCategory.php.\n";
1221 populateCategory( '', 10, 0, true );
1222 echo "Done populating category table.\n";
1225 function do_populate_parent_id() {
1226 if( update_row_exists( 'populate rev_parent_id' ) ) {
1227 echo "...rev_parent_id column already populated.\n";
1230 require_once( 'populateParentId.inc' );
1233 populate_rev_parent_id( $wgDatabase );
1236 function update_password_format() {
1237 if ( update_row_exists( 'password format' ) ) {
1238 echo "...password hash format already changed\n";
1242 echo "Updating password hash format...";
1244 global $wgDatabase, $wgPasswordSalt;
1245 $user = $wgDatabase->tableName( 'user' );
1246 if ( $wgPasswordSalt ) {
1247 $sql = "UPDATE $user SET user_password=CONCAT(':B:', user_id, ':', user_password) " .
1248 "WHERE user_password NOT LIKE ':%'";
1250 $sql = "UPDATE $user SET user_password=CONCAT(':A:', user_password) " .
1251 "WHERE user_password NOT LIKE ':%'";
1253 $wgDatabase->query( $sql, __METHOD__ );
1254 $wgDatabase->insert( 'updatelog', array( 'ul_key' => 'password format' ), __METHOD__ );
1259 function sqlite_initial_indexes() {
1261 if ( update_row_exists( 'initial_indexes' ) ) {
1262 echo "...have initial indexes\n";
1265 echo "Adding initial indexes...";
1266 $wgDatabase->sourceFile( archive( 'initial-indexes.sql' ) );
1270 function do_unique_pl_tl_il() {
1272 $info = $wgDatabase->indexInfo( 'pagelinks', 'pl_namespace' );
1273 if( !$info->Non_unique ) {
1274 echo "...pl_namespace, tl_namespace, il_to indices are already UNIQUE.\n";
1276 echo "Making pl_namespace, tl_namespace and il_to indices UNIQUE... ";
1277 dbsource( archive( 'patch-pl-tl-il-unique.sql' ), $wgDatabase );
1282 /***********************************************************************
1284 * TODO: merge with above
1285 ***********************************************************************/
1288 pg_describe_table($table)
1290 global $wgDatabase, $wgDBmwschema;
1292 SELECT attname, attnum FROM pg_namespace, pg_class, pg_attribute
1293 WHERE pg_class.relnamespace = pg_namespace.oid
1294 AND attrelid=pg_class.oid AND attnum > 0
1295 AND relname=%s AND nspname=%s
1297 $res = $wgDatabase->query(sprintf($q,
1298 $wgDatabase->addQuotes($table),
1299 $wgDatabase->addQuotes($wgDBmwschema)));
1304 while ($r = $wgDatabase->fetchRow($res)) {
1314 pg_describe_index($idx)
1316 global $wgDatabase, $wgDBmwschema;
1318 // first fetch the key (which is a list of columns ords) and
1319 // the table the index applies to (an oid)
1321 SELECT indkey, indrelid FROM pg_namespace, pg_class, pg_index
1323 AND pg_class.relnamespace = pg_namespace.oid
1325 AND indexrelid=pg_class.oid
1327 $res = $wgDatabase->query(sprintf($q,
1328 $wgDatabase->addQuotes($wgDBmwschema),
1329 $wgDatabase->addQuotes($idx)));
1332 if (!($r = $wgDatabase->fetchRow($res))) {
1333 $wgDatabase->freeResult($res);
1338 $relid = intval($r[1]);
1339 $indkeys = explode(" ", $indkey);
1340 $wgDatabase->freeResult($res);
1342 $colnames = array();
1343 foreach ($indkeys as $rid) {
1345 SELECT attname FROM pg_class, pg_attribute
1346 WHERE attrelid=$relid
1348 AND attrelid=pg_class.oid
1350 $r2 = $wgDatabase->query(sprintf($query, $rid));
1353 if (!($row2 = $wgDatabase->fetchRow($r2))) {
1354 $wgDatabase->freeResult($r2);
1357 $colnames[] = $row2[0];
1358 $wgDatabase->freeResult($r2);
1365 pg_index_exists($table, $index)
1367 global $wgDatabase, $wgDBmwschema;
1368 $exists = $wgDatabase->selectField("pg_indexes", "indexname",
1369 array( "indexname" => $index,
1370 "tablename" => $table,
1371 "schemaname" => $wgDBmwschema));
1372 return $exists === $index;
1376 pg_fkey_deltype($fkey)
1378 global $wgDatabase, $wgDBmwschema;
1380 SELECT confdeltype FROM pg_constraint, pg_namespace
1381 WHERE connamespace=pg_namespace.oid
1385 $r = $wgDatabase->query(sprintf($q,
1386 $wgDatabase->addQuotes($wgDBmwschema),
1387 $wgDatabase->addQuotes($fkey)));
1388 if (!($row = $wgDatabase->fetchRow($r)))
1394 pg_rule_def($table, $rule)
1396 global $wgDatabase, $wgDBmwschema;
1398 SELECT definition FROM pg_rules
1399 WHERE schemaname = %s
1403 $r = $wgDatabase->query(sprintf($q,
1404 $wgDatabase->addQuotes($wgDBmwschema),
1405 $wgDatabase->addQuotes($table),
1406 $wgDatabase->addQuotes($rule)));
1407 $row = $wgDatabase->fetchRow($r);
1411 $wgDatabase->freeResult($r);
1415 function do_postgres_updates() {
1416 global $wgDatabase, $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgShowExceptionDetails, $wgDBuser;
1418 ## Gather version numbers in case we need them
1419 $version = $wgDatabase->getServerVersion(); ## long string
1420 $numver = $wgDatabase->numeric_version; ## X.Y e.g. 8.3
1422 $wgShowExceptionDetails = 1;
1424 # Just in case their LocalSettings.php does not have this:
1425 if ( !isset( $wgDBmwschema ))
1426 $wgDBmwschema = 'mediawiki';
1428 # Verify that this user is configured correctly
1429 $safeuser = $wgDatabase->addQuotes($wgDBuser);
1430 $SQL = "SELECT array_to_string(useconfig,'*') FROM pg_catalog.pg_user WHERE usename = $safeuser";
1431 $config = pg_fetch_result( $wgDatabase->doQuery( $SQL ), 0, 0 );
1433 foreach( explode( '*', $config ) as $c ) {
1434 list( $x,$y ) = explode( '=', $c );
1437 if( !array_key_exists( 'search_path', $conf ) ) {
1441 $search_path = $conf['search_path'];
1443 if( strpos( $search_path, $wgDBmwschema ) === false ) {
1444 echo "Adding in schema \"$wgDBmwschema\" to search_path for user \"$wgDBuser\"\n";
1445 $search_path = "$wgDBmwschema, $search_path";
1447 if( strpos( $search_path, $wgDBts2schema ) === false ) {
1448 echo "Adding in schema \"$wgDBts2schema\" to search_path for user \"$wgDBuser\"\n";
1449 $search_path = "$search_path, $wgDBts2schema";
1451 if( array_key_exists( 'search_path', $conf ) === false || $search_path != $conf['search_path'] ) {
1452 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET search_path = $search_path" );
1453 $wgDatabase->doQuery( "SET search_path = $search_path" );
1456 $path = $conf['search_path'];
1457 echo "... search_path for user \"$wgDBuser\" looks correct ($path)\n";
1460 'client_min_messages' => 'error',
1461 'DateStyle' => 'ISO, YMD',
1464 foreach( array_keys( $goodconf ) AS $key ) {
1465 $value = $goodconf[$key];
1466 if( !array_key_exists( $key, $conf ) or $conf[$key] !== $value ) {
1467 echo "Setting $key to '$value' for user \"$wgDBuser\"\n";
1468 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET $key = '$value'" );
1469 $wgDatabase->doQuery( "SET $key = '$value'" );
1472 echo "... default value of \"$key\" is correctly set to \"$value\" for user \"$wgDBuser\"\n";
1476 $newsequences = array(
1482 array("category", "patch-category.sql"),
1483 array("mediawiki_version", "patch-mediawiki_version.sql"),
1484 array("mwuser", "patch-mwuser.sql"),
1485 array("pagecontent", "patch-pagecontent.sql"),
1486 array("querycachetwo", "patch-querycachetwo.sql"),
1487 array("page_props", "patch-page_props.sql"),
1488 array("page_restrictions", "patch-page_restrictions.sql"),
1489 array("profiling", "patch-profiling.sql"),
1490 array("protected_titles", "patch-protected_titles.sql"),
1491 array("redirect", "patch-redirect.sql"),
1492 array("updatelog", "patch-updatelog.sql"),
1496 array("archive", "ar_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1497 array("archive", "ar_len", "INTEGER"),
1498 array("archive", "ar_page_id", "INTEGER"),
1499 array("archive", "ar_parent_id", "INTEGER"),
1500 array("image", "img_sha1", "TEXT NOT NULL DEFAULT ''"),
1501 array("ipblocks", "ipb_anon_only", "SMALLINT NOT NULL DEFAULT 0"),
1502 array("ipblocks", "ipb_by_text", "TEXT NOT NULL DEFAULT ''"),
1503 array("ipblocks", "ipb_block_email", "SMALLINT NOT NULL DEFAULT 0"),
1504 array("ipblocks", "ipb_create_account", "SMALLINT NOT NULL DEFAULT 1"),
1505 array("ipblocks", "ipb_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1506 array("ipblocks", "ipb_enable_autoblock", "SMALLINT NOT NULL DEFAULT 1"),
1507 array("ipblocks", "ipb_allow_usertalk", "SMALLINT NOT NULL DEFAULT 0"),
1508 array("filearchive", "fa_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1509 array("logging", "log_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1510 array("logging", "log_id", "INTEGER NOT NULL PRIMARY KEY DEFAULT nextval('log_log_id_seq')"),
1511 array("logging", "log_params", "TEXT"),
1512 array("mwuser", "user_editcount", "INTEGER"),
1513 array("mwuser", "user_newpass_time", "TIMESTAMPTZ"),
1514 array("oldimage", "oi_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1515 array("oldimage", "oi_metadata", "BYTEA NOT NULL DEFAULT ''"),
1516 array("oldimage", "oi_media_type", "TEXT"),
1517 array("oldimage", "oi_major_mime", "TEXT NOT NULL DEFAULT 'unknown'"),
1518 array("oldimage", "oi_minor_mime", "TEXT NOT NULL DEFAULT 'unknown'"),
1519 array("oldimage", "oi_sha1", "TEXT NOT NULL DEFAULT ''"),
1520 array("page_restrictions", "pr_id", "INTEGER NOT NULL UNIQUE DEFAULT nextval('pr_id_val')"),
1521 array("profiling", "pf_memory", "NUMERIC(18,10) NOT NULL DEFAULT 0"),
1522 array("recentchanges", "rc_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1523 array("recentchanges", "rc_log_action", "TEXT"),
1524 array("recentchanges", "rc_log_type", "TEXT"),
1525 array("recentchanges", "rc_logid", "INTEGER NOT NULL DEFAULT 0"),
1526 array("recentchanges", "rc_new_len", "INTEGER"),
1527 array("recentchanges", "rc_old_len", "INTEGER"),
1528 array("recentchanges", "rc_params", "TEXT"),
1529 array("revision", "rev_len", "INTEGER"),
1530 array("revision", "rev_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1531 array("user_newtalk", "user_last_timestamp", "TIMESTAMPTZ"),
1532 array("site_stats", "ss_active_users", "INTEGER DEFAULT '-1'"),
1533 array("revision", "rev_parent_id", "INTEGER DEFAULT NULL"),
1537 # table, column, desired type, USING clause if needed (with new default if needed)
1538 $typechanges = array(
1539 array("archive", "ar_deleted", "smallint", ""),
1540 array("archive", "ar_minor_edit", "smallint", "ar_minor_edit::smallint DEFAULT 0"),
1541 array("filearchive", "fa_deleted", "smallint", ""),
1542 array("filearchive", "fa_height", "integer", ""),
1543 array("filearchive", "fa_metadata", "bytea", "decode(fa_metadata,'escape')"),
1544 array("filearchive", "fa_size", "integer", ""),
1545 array("filearchive", "fa_width", "integer", ""),
1546 array("filearchive", "fa_storage_group","text", ""),
1547 array("filearchive", "fa_storage_key", "text", ""),
1548 array("image", "img_metadata", "bytea", "decode(img_metadata,'escape')"),
1549 array("image", "img_size", "integer", ""),
1550 array("image", "img_width", "integer", ""),
1551 array("image", "img_height", "integer", ""),
1552 array("interwiki", "iw_local", "smallint", "iw_local::smallint DEFAULT 0"),
1553 array("interwiki", "iw_trans", "smallint", "iw_trans::smallint DEFAULT 0"),
1554 array("ipblocks", "ipb_auto", "smallint", "ipb_auto::smallint DEFAULT 0"),
1555 array("ipblocks", "ipb_anon_only", "smallint", "CASE WHEN ipb_anon_only=' ' THEN 0 ELSE ipb_anon_only::smallint END DEFAULT 0"),
1556 array("ipblocks", "ipb_create_account", "smallint", "CASE WHEN ipb_create_account=' ' THEN 0 ELSE ipb_create_account::smallint END DEFAULT 1"),
1557 array("ipblocks", "ipb_enable_autoblock", "smallint", "CASE WHEN ipb_enable_autoblock=' ' THEN 0 ELSE ipb_enable_autoblock::smallint END DEFAULT 1"),
1558 array("ipblocks", "ipb_block_email", "smallint", "CASE WHEN ipb_block_email=' ' THEN 0 ELSE ipb_block_email::smallint END DEFAULT 0"),
1559 array("ipblocks", "ipb_address", "text", "ipb_address::text"),
1560 array("ipblocks", "ipb_deleted", "smallint", "ipb_deleted::smallint"),
1561 array("math", "math_inputhash", "bytea", "decode(math_inputhash,'escape')"),
1562 array("math", "math_outputhash", "bytea", "decode(math_outputhash,'escape')"),
1563 array("mwuser", "user_token", "text", ""),
1564 array("mwuser", "user_email_token","text", ""),
1565 array("objectcache", "keyname", "text", ""),
1566 array("oldimage", "oi_height", "integer", ""),
1567 array("oldimage", "oi_metadata", "bytea", "decode(img_metadata,'escape')"),
1568 array("oldimage", "oi_size", "integer", ""),
1569 array("oldimage", "oi_width", "integer", ""),
1570 array("page", "page_is_redirect","smallint", "page_is_redirect::smallint DEFAULT 0"),
1571 array("page", "page_is_new", "smallint", "page_is_new::smallint DEFAULT 0"),
1572 array("querycache", "qc_value", "integer", ""),
1573 array("querycachetwo","qcc_value", "integer", ""),
1574 array("recentchanges","rc_bot", "smallint", "rc_bot::smallint DEFAULT 0"),
1575 array("recentchanges","rc_deleted", "smallint", ""),
1576 array("recentchanges","rc_minor", "smallint", "rc_minor::smallint DEFAULT 0"),
1577 array("recentchanges","rc_new", "smallint", "rc_new::smallint DEFAULT 0"),
1578 array("recentchanges","rc_type", "smallint", "rc_type::smallint DEFAULT 0"),
1579 array("recentchanges","rc_patrolled", "smallint", "rc_patrolled::smallint DEFAULT 0"),
1580 array("revision", "rev_deleted", "smallint", "rev_deleted::smallint DEFAULT 0"),
1581 array("revision", "rev_minor_edit", "smallint", "rev_minor_edit::smallint DEFAULT 0"),
1582 array("templatelinks","tl_namespace", "smallint", "tl_namespace::smallint"),
1583 array("user_newtalk", "user_ip", "text", "host(user_ip)"),
1586 $newindexes = array(
1587 array("archive", "archive_user_text", "(ar_user_text)"),
1588 array("image", "img_sha1", "(img_sha1)"),
1589 array("oldimage", "oi_sha1", "(oi_sha1)"),
1590 array("revision", "rev_text_id_idx", "(rev_text_id)"),
1591 array("recentchanges", "rc_timestamp_nobot", "(rc_timestamp) WHERE rc_bot = 0"),
1592 array("templatelinks", "templatelinks_from", "(tl_from)"),
1593 array("watchlist", "wl_user", "(wl_user)"),
1599 foreach ($newsequences as $ns) {
1600 if ($wgDatabase->sequenceExists($ns)) {
1601 echo "... sequence \"$ns\" already exists\n";
1605 echo "Creating sequence \"$ns\"\n";
1606 $wgDatabase->query("CREATE SEQUENCE $ns");
1609 foreach ($newtables as $nt) {
1610 if ($wgDatabase->tableExists($nt[0])) {
1611 echo "... table \"$nt[0]\" already exists\n";
1615 echo "Creating table \"$nt[0]\"\n";
1616 dbsource(archive($nt[1]));
1619 ## Needed before newcols
1620 if ($wgDatabase->tableExists("archive2")) {
1621 echo "Converting \"archive2\" back to normal archive table\n";
1622 if ($wgDatabase->ruleExists("archive", "archive_insert")) {
1623 echo "Dropping rule \"archive_insert\"\n";
1624 $wgDatabase->query("DROP RULE archive_insert ON archive");
1626 if ($wgDatabase->ruleExists("archive", "archive_delete")) {
1627 echo "Dropping rule \"archive_delete\"\n";
1628 $wgDatabase->query("DROP RULE archive_delete ON archive");
1630 dbsource(archive("patch-remove-archive2.sql"));
1633 echo "... obsolete table \"archive2\" does not exist\n";
1635 foreach ($newcols as $nc) {
1636 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1637 if (!is_null($fi)) {
1638 echo "... column \"$nc[0].$nc[1]\" already exists\n";
1642 echo "Adding column \"$nc[0].$nc[1]\"\n";
1643 $wgDatabase->query("ALTER TABLE $nc[0] ADD $nc[1] $nc[2]");
1646 foreach ($typechanges as $tc) {
1647 $fi = $wgDatabase->fieldInfo($tc[0], $tc[1]);
1649 echo "... error: expected column $tc[0].$tc[1] to exist\n";
1653 if ($fi->type() === $tc[2])
1654 echo "... column \"$tc[0].$tc[1]\" is already of type \"$tc[2]\"\n";
1656 echo "Changing column type of \"$tc[0].$tc[1]\" from \"{$fi->type()}\" to \"$tc[2]\"\n";
1657 $sql = "ALTER TABLE $tc[0] ALTER $tc[1] TYPE $tc[2]";
1658 if (strlen($tc[3])) {
1660 if (preg_match( '/DEFAULT (.+)/', $tc[3], $default)) {
1661 $sqldef = "ALTER TABLE $tc[0] ALTER $tc[1] SET DEFAULT $default[1]";
1662 $wgDatabase->query($sqldef);
1663 $tc[3] = preg_replace( '/\s*DEFAULT .+/', '', $tc[3]);
1665 $sql .= " USING $tc[3]";
1667 $sql .= ";\nCOMMIT;\n";
1668 $wgDatabase->query($sql);
1672 if ($wgDatabase->fieldInfo('oldimage','oi_deleted')->type() !== 'smallint') {
1673 echo "Changing \"oldimage.oi_deleted\" to type \"smallint\"\n";
1674 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted DROP DEFAULT" );
1675 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted TYPE SMALLINT USING (oi_deleted::smallint)" );
1676 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted SET DEFAULT 0" );
1679 echo "... column \"oldimage.oi_deleted\" is already of type \"smallint\"\n";
1682 foreach ($newindexes as $ni) {
1683 if (pg_index_exists($ni[0], $ni[1])) {
1684 echo "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n";
1687 echo "Creating index \"$ni[1]\" on table \"$ni[0]\" $ni[2]\n";
1688 $wgDatabase->query( "CREATE INDEX $ni[1] ON $ni[0] $ni[2]" );
1691 foreach ($newrules as $nr) {
1692 if ($wgDatabase->ruleExists($nr[0], $nr[1])) {
1693 echo "... rule \"$nr[1]\" on table \"$nr[0]\" already exists\n";
1696 echo "Adding rule \"$nr[1]\" to table \"$nr[0]\"\n";
1697 dbsource(archive($nr[2]));
1700 if ($wgDatabase->hasConstraint("oldimage_oi_name_fkey")) {
1701 echo "Making foriegn key on table \"oldimage\" (to image) a cascade delete\n";
1702 $wgDatabase->query( "ALTER TABLE oldimage DROP CONSTRAINT oldimage_oi_name_fkey" );
1703 $wgDatabase->query( "ALTER TABLE oldimage ADD CONSTRAINT oldimage_oi_name_fkey_cascade ".
1704 "FOREIGN KEY (oi_name) REFERENCES image(img_name) ON DELETE CASCADE" );
1707 echo "... table \"oldimage\" has correct cascade delete foreign key to image\n";
1709 if (!$wgDatabase->triggerExists("page", "page_deleted")) {
1710 echo "Adding function and trigger \"page_deleted\" to table \"page\"\n";
1711 dbsource(archive('patch-page_deleted.sql'));
1714 echo "... table \"page\" has \"page_deleted\" trigger\n";
1716 $fi = $wgDatabase->fieldInfo("recentchanges", "rc_cur_id");
1717 if (!$fi->nullable()) {
1718 echo "Removing NOT NULL constraint from \"recentchanges.rc_cur_id\"\n";
1719 dbsource(archive('patch-rc_cur_id-not-null.sql'));
1722 echo "... column \"recentchanges.rc_cur_id\" has a NOT NULL constraint\n";
1724 $pu = pg_describe_index("pagelink_unique");
1725 if (!is_null($pu) && ($pu[0] != "pl_from" || $pu[1] != "pl_namespace" || $pu[2] != "pl_title")) {
1726 echo "Dropping obsolete version of index \"pagelink_unique index\"\n";
1727 $wgDatabase->query("DROP INDEX pagelink_unique");
1731 echo "... obsolete version of index \"pagelink_unique index\" does not exist\n";
1734 echo "Creating index \"pagelink_unique index\"\n";
1735 $wgDatabase->query("CREATE UNIQUE INDEX pagelink_unique ON pagelinks (pl_from,pl_namespace,pl_title)");
1738 echo "... index \"pagelink_unique_index\" already exists\n";
1740 if (pg_fkey_deltype("revision_rev_user_fkey") == 'r') {
1741 echo "... constraint \"revision_rev_user_fkey\" is ON DELETE RESTRICT\n";
1744 echo "Changing constraint \"revision_rev_user_fkey\" to ON DELETE RESTRICT\n";
1745 dbsource(archive('patch-revision_rev_user_fkey.sql'));
1748 # Fix ipb_address index
1749 if (pg_index_exists('ipblocks', 'ipb_address' )) {
1750 echo "Removing deprecated index 'ipb_address'...\n";
1751 $wgDatabase->query('DROP INDEX ipb_address');
1753 if (pg_index_exists('ipblocks', 'ipb_address_unique' )) {
1754 echo "... have ipb_address_unique\n";
1757 echo "Adding ipb_address_unique index\n";
1758 dbsource(archive('patch-ipb_address_unique.sql'));
1761 global $wgExtNewTables, $wgExtPGNewFields, $wgExtNewIndexes;
1762 # Add missing extension tables
1763 foreach ( $wgExtNewTables as $nt ) {
1764 if ($wgDatabase->tableExists($nt[0])) {
1765 echo "... table \"$nt[0]\" already exists\n";
1768 echo "Creating table \"$nt[0]\"\n";
1771 # Add missing extension fields
1772 foreach ( $wgExtPGNewFields as $nc ) {
1773 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1774 if (!is_null($fi)) {
1775 echo "... column \"$nc[0].$nc[1]\" already exists\n";
1778 echo "Adding column \"$nc[0].$nc[1]\"\n";
1779 $wgDatabase->query( "ALTER TABLE $nc[0] ADD $nc[1] $nc[2]" );
1781 # Add missing extension indexes
1782 foreach ( $wgExtNewIndexes as $ni ) {
1783 if (pg_index_exists($ni[0], $ni[1])) {
1784 echo "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n";
1787 echo "Creating index \"$ni[1]\" on table \"$ni[0]\"\n";
1791 # Tweak the page_title tsearch2 trigger to filter out slashes
1792 # This is create or replace, so harmless to call if not needed
1793 dbsource(archive('patch-ts2pagetitle.sql'));
1795 ## If the server is 8.3 or higher, rewrite the tsearch2 triggers
1796 ## in case they have the old 'default' versions
1797 if ( $numver >= 8.3 )
1798 dbsource(archive('patch-tsearch2funcs.sql'));
1800 ## Put a new row in the mediawiki_version table
1801 $wgDatabase->insert( 'mediawiki_version',
1805 'mw_version' => $wgVersion,
1806 'pg_version' => $version,
1807 'sql_version' => '$LastChangedRevision$',
1808 'sql_date' => '$LastChangedDate$',