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( 'do_unique_pl_tl_il' ),
153 array( 'add_table', 'change_tag', 'patch-change_tag.sql' ),
154 array( 'add_table', 'tag_summary', 'patch-change_tag.sql' ),
155 array( 'add_table', 'valid_tag', 'patch-change_tag.sql' ),
160 array( 'add_field', 'site_stats', 'ss_active_users', 'patch-ss_active_users.sql' ),
161 array( 'do_active_users_init' ),
162 array( 'add_field', 'ipblocks', 'ipb_allow_usertalk', 'patch-ipb_allow_usertalk.sql' ),
163 array( 'sqlite_initial_indexes' ),
168 # For extensions only, should be populated via hooks
169 # $wgDBtype should be checked to specifiy the proper file
170 $wgExtNewTables = array(); // table, dir
171 $wgExtNewFields = array(); // table, column, dir
172 $wgExtPGNewFields = array(); // table, column attributes; for PostgreSQL
173 $wgExtNewIndexes = array(); // table, index, dir
175 # Helper function: check if the given key is present in the updatelog table.
176 # Obviously, only use this for updates that occur after the updatelog table was
178 function update_row_exists( $key ) {
179 $dbr = wfGetDB( DB_SLAVE );
180 $row = $dbr->selectRow(
183 array( 'ul_key' => $key ),
189 function rename_table( $from, $to, $patch ) {
191 if ( $wgDatabase->tableExists( $from ) ) {
192 if ( $wgDatabase->tableExists( $to ) ) {
193 wfOut( "...can't move table $from to $to, $to already exists.\n" );
195 wfOut( "Moving table $from to $to..." );
196 dbsource( archive($patch), $wgDatabase );
200 // Source table does not exist
201 // Renames are done before creations, so this is typical for a new installation
206 function add_table( $name, $patch, $fullpath=false ) {
208 if ( $wgDatabase->tableExists( $name ) ) {
209 wfOut( "...$name table already exists.\n" );
211 wfOut( "Creating $name table..." );
213 dbsource( $patch, $wgDatabase );
215 dbsource( archive($patch), $wgDatabase );
221 function add_field( $table, $field, $patch, $fullpath=false ) {
223 if ( !$wgDatabase->tableExists( $table ) ) {
224 wfOut( "...$table table does not exist, skipping new field patch\n" );
225 } elseif ( $wgDatabase->fieldExists( $table, $field ) ) {
226 wfOut( "...have $field field in $table table.\n" );
228 wfOut( "Adding $field field to table $table..." );
230 dbsource( $patch, $wgDatabase );
232 dbsource( archive($patch), $wgDatabase );
238 function add_index( $table, $index, $patch, $fullpath=false ) {
240 if( $wgDatabase->indexExists( $table, $index ) ) {
241 wfOut( "...$index key already set on $table table.\n" );
243 wfOut( "Adding $index key to table $table... " );
245 dbsource( $patch, $wgDatabase );
247 dbsource( archive($patch), $wgDatabase );
253 function do_revision_updates() {
254 global $wgSoftwareRevision;
255 if ( $wgSoftwareRevision < 1001 ) {
260 function update_passwords() {
261 wfDebugDieBacktrace( "This function needs to be updated or removed.\n" );
264 $fname = "Update script: update_passwords()";
265 wfOut( "\nIt appears that you need to update the user passwords in your\n" .
266 "database. If you have already done this (if you've run this update\n" .
267 "script once before, for example), doing so again will make all your\n" .
268 "user accounts inaccessible, so be sure you only do this once.\n" .
269 "Update user passwords? (yes/no)" );
271 $resp = readconsole();
272 if ( ! ( "Y" == $resp{0} || "y" == $resp{0} ) ) { return; }
274 $sql = "SELECT user_id,user_password FROM user";
275 $source = $wgDatabase->query( $sql, $fname );
277 while ( $row = $wgDatabase->fetchObject( $source ) ) {
279 $oldpass = $row->user_password;
280 $newpass = md5( "{$id}-{$oldpass}" );
282 $sql = "UPDATE user SET user_password='{$newpass}' " .
283 "WHERE user_id={$id}";
284 $wgDatabase->query( $sql, $fname );
288 function do_interwiki_update() {
289 # Check that interwiki table exists; if it doesn't source it
290 global $wgDatabase, $IP;
291 if( $wgDatabase->tableExists( "interwiki" ) ) {
292 wfOut( "...already have interwiki table\n" );
295 wfOut( "Creating interwiki table: " );
296 dbsource( archive("patch-interwiki.sql") );
298 wfOut( "Adding default interwiki definitions: " );
299 dbsource( "$IP/maintenance/interwiki.sql" );
303 function do_index_update() {
304 # Check that proper indexes are in place
306 $meta = $wgDatabase->fieldInfo( "recentchanges", "rc_timestamp" );
307 if( !$meta->isMultipleKey() ) {
308 wfOut( "Updating indexes to 20031107: " );
309 dbsource( archive("patch-indexes.sql") );
313 wfOut( "...indexes seem up to 20031107 standards\n" );
317 function do_image_index_update() {
320 $meta = $wgDatabase->fieldInfo( "image", "img_major_mime" );
321 if( !$meta->isMultipleKey() ) {
322 wfOut( "Updating indexes to 20050912: " );
323 dbsource( archive("patch-mimesearch-indexes.sql") );
327 wfOut( "...indexes seem up to 20050912 standards\n" );
331 function do_image_name_unique_update() {
333 if( $wgDatabase->indexExists( 'image', 'PRIMARY' ) ) {
334 wfOut( "...image primary key already set.\n" );
336 wfOut( "Making img_name the primary key... " );
337 dbsource( archive("patch-image_name_primary.sql"), $wgDatabase );
342 function do_logging_timestamp_index() {
344 if( $wgDatabase->indexExists( 'logging', 'times' ) ) {
345 wfOut( "...timestamp key on logging already exists.\n" );
347 wfOut( "Adding timestamp key on logging table... " );
348 dbsource( archive("patch-logging-times-index.sql"), $wgDatabase );
353 function do_archive_user_index() {
355 if( $wgDatabase->indexExists( 'archive', 'usertext_timestamp' ) ) {
356 wfOut( "...usertext,timestamp key on archive already exists.\n" );
358 wfOut( "Adding usertext,timestamp key on archive table... " );
359 dbsource( archive("patch-archive-user-index.sql"), $wgDatabase );
364 function do_image_user_index() {
366 if( $wgDatabase->indexExists( 'image', 'img_usertext_timestamp' ) ) {
367 wfOut( "...usertext,timestamp key on image already exists.\n" );
369 wfOut( "Adding usertext,timestamp key on image table... " );
370 dbsource( archive("patch-image-user-index.sql"), $wgDatabase );
375 function do_oldimage_user_index() {
377 if( $wgDatabase->indexExists( 'oldimage', 'oi_usertext_timestamp' ) ) {
378 wfOut( "...usertext,timestamp key on oldimage already exists.\n" );
380 wfOut( "Adding usertext,timestamp key on oldimage table... " );
381 dbsource( archive("patch-oldimage-user-index.sql"), $wgDatabase );
386 function do_watchlist_update() {
388 $fname = 'do_watchlist_update';
389 if( $wgDatabase->fieldExists( 'watchlist', 'wl_notificationtimestamp' ) ) {
390 wfOut( "The watchlist table is already set up for email notification.\n" );
392 wfOut( "Adding wl_notificationtimestamp field for email notification management." );
393 /* ALTER TABLE watchlist ADD (wl_notificationtimestamp varchar(14) binary NOT NULL default '0'); */
394 dbsource( archive( 'patch-email-notification.sql' ), $wgDatabase );
397 # Check if we need to add talk page rows to the watchlist
398 $talk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'wl_namespace & 1', $fname );
399 $nontalk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'NOT (wl_namespace & 1)', $fname );
400 if ( $talk != $nontalk ) {
401 wfOut( "Adding missing watchlist talk page rows... " );
404 $wgDatabase->insertSelect( 'watchlist', 'watchlist',
406 'wl_user' => 'wl_user',
407 'wl_namespace' => 'wl_namespace | 1',
408 'wl_title' => 'wl_title',
409 'wl_notificationtimestamp' => 'wl_notificationtimestamp'
410 ), array( 'NOT (wl_namespace & 1)' ), $fname, 'IGNORE' );
413 wfOut( "...watchlist talk page rows already present\n" );
417 function do_copy_newtalk_to_watchlist() {
419 global $wgCommandLineMode; # this needs to be saved while getID() and getName() are called
421 $res = $wgDatabase->safeQuery( 'SELECT user_id, user_ip FROM !',
422 $wgDatabase->tableName( 'user_newtalk' ) );
423 $num_newtalks=$wgDatabase->numRows($res);
424 wfOut( "Now converting $num_newtalks user_newtalk entries to watchlist table entries ... \n" );
427 for ( $i = 1; $i <= $num_newtalks; $i++ ) {
428 $wluser = $wgDatabase->fetchObject( $res );
429 if ($wluser->user_id == 0) { # anonymous users ... have IP numbers as "names"
430 if ($user->isIP($wluser->user_ip)) { # do only if it really looks like an IP number (double checked)
431 $wgDatabase->replace( 'watchlist',
432 array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
433 array('wl_user' => 0,
434 'wl_namespace' => NS_USER_TALK,
435 'wl_title' => $wluser->user_ip,
436 'wl_notificationtimestamp' => '19700101000000'
437 ), 'updaters.inc::do_watchlist_update2'
440 } else { # normal users ... have user_ids
441 $user->setID($wluser->user_id);
442 $wgDatabase->replace( 'watchlist',
443 array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
444 array('wl_user' => $user->getID(),
445 'wl_namespace' => NS_USER_TALK,
446 'wl_title' => $user->getName(),
447 'wl_notificationtimestamp' => '19700101000000'
448 ), 'updaters.inc::do_watchlist_update3'
456 function do_user_update() {
458 if( $wgDatabase->fieldExists( 'user', 'user_emailauthenticationtimestamp' ) ) {
459 wfOut( "User table contains old email authentication field. Dropping... " );
460 dbsource( archive( 'patch-email-authentication.sql' ), $wgDatabase );
463 wfOut( "...user table does not contain old email authentication field.\n" );
468 * 1.4 betas were missing the 'binary' marker from logging.log_title,
469 * which causes a collation mismatch error on joins in MySQL 4.1.
471 function check_bin( $table, $field, $patchFile ) {
472 global $wgDatabase, $wgDBtype;
473 if ($wgDBtype != 'mysql')
475 $tableName = $wgDatabase->tableName( $table );
476 $res = $wgDatabase->query( "SELECT $field FROM $tableName LIMIT 0" );
477 $flags = explode( ' ', mysql_field_flags( $res->result, 0 ) );
478 $wgDatabase->freeResult( $res );
480 if( in_array( 'binary', $flags ) ) {
481 wfOut( "$table table has correct $field encoding.\n" );
483 wfOut( "Fixing $field encoding on $table table... " );
484 dbsource( archive( $patchFile ), $wgDatabase );
489 function do_schema_restructuring() {
491 $fname="do_schema_restructuring";
492 if ( $wgDatabase->tableExists( 'page' ) ) {
493 wfOut( "...page table already exists.\n" );
495 wfOut( "...converting from cur/old to page/revision/text DB structure.\n" );
496 wfOut( wfTimestamp( TS_DB ) );
497 wfOut( "......checking for duplicate entries.\n" );
499 list ($cur, $old, $page, $revision, $text) = $wgDatabase->tableNamesN( 'cur', 'old', 'page', 'revision', 'text' );
501 $rows = $wgDatabase->query( "SELECT cur_title, cur_namespace, COUNT(cur_namespace) AS c
502 FROM $cur GROUP BY cur_title, cur_namespace HAVING c>1", $fname );
504 if ( $wgDatabase->numRows( $rows ) > 0 ) {
505 wfOut( wfTimestamp( TS_DB ) );
506 wfOut( "......<b>Found duplicate entries</b>\n" );
507 wfOut( sprintf( "<b> %-60s %3s %5s</b>\n", 'Title', 'NS', 'Count' ) );
508 while ( $row = $wgDatabase->fetchObject( $rows ) ) {
509 if ( ! isset( $duplicate[$row->cur_namespace] ) ) {
510 $duplicate[$row->cur_namespace] = array();
512 $duplicate[$row->cur_namespace][] = $row->cur_title;
513 wfOut( sprintf( " %-60s %3s %5s\n", $row->cur_title, $row->cur_namespace, $row->c ) );
515 $sql = "SELECT cur_title, cur_namespace, cur_id, cur_timestamp FROM $cur WHERE ";
517 foreach ( $duplicate as $ns => $titles ) {
523 $sql .= "( cur_namespace = {$ns} AND cur_title in (";
525 foreach ( $titles as $t ) {
527 $sql .= $wgDatabase->addQuotes( $t );
530 $sql .= ', ' . $wgDatabase->addQuotes( $t );
535 # By sorting descending, the most recent entry will be the first in the list.
536 # All following entries will be deleted by the next while-loop.
537 $sql .= 'ORDER BY cur_namespace, cur_title, cur_timestamp DESC';
539 $rows = $wgDatabase->query( $sql, $fname );
541 $prev_title = $prev_namespace = false;
544 while ( $row = $wgDatabase->fetchObject( $rows ) ) {
545 if ( $prev_title == $row->cur_title && $prev_namespace == $row->cur_namespace ) {
546 $deleteId[] = $row->cur_id;
548 $prev_title = $row->cur_title;
549 $prev_namespace = $row->cur_namespace;
551 $sql = "DELETE FROM $cur WHERE cur_id IN ( " . join( ',', $deleteId ) . ')';
552 $rows = $wgDatabase->query( $sql, $fname );
553 wfOut( wfTimestamp( TS_DB ) );
554 wfOut( "......<b>Deleted</b> ".$wgDatabase->affectedRows()." records.\n" );
558 wfOut( wfTimestamp( TS_DB ) );
559 wfOut( "......Creating tables.\n" );
560 $wgDatabase->query("CREATE TABLE $page (
561 page_id int(8) unsigned NOT NULL auto_increment,
562 page_namespace int NOT NULL,
563 page_title varchar(255) binary NOT NULL,
564 page_restrictions tinyblob NOT NULL,
565 page_counter bigint(20) unsigned NOT NULL default '0',
566 page_is_redirect tinyint(1) unsigned NOT NULL default '0',
567 page_is_new tinyint(1) unsigned NOT NULL default '0',
568 page_random real unsigned NOT NULL,
569 page_touched char(14) binary NOT NULL default '',
570 page_latest int(8) unsigned NOT NULL,
571 page_len int(8) unsigned NOT NULL,
573 PRIMARY KEY page_id (page_id),
574 UNIQUE INDEX name_title (page_namespace,page_title),
577 ) ENGINE=InnoDB", $fname );
578 $wgDatabase->query("CREATE TABLE $revision (
579 rev_id int(8) unsigned NOT NULL auto_increment,
580 rev_page int(8) unsigned NOT NULL,
581 rev_comment tinyblob NOT NULL,
582 rev_user int(5) unsigned NOT NULL default '0',
583 rev_user_text varchar(255) binary NOT NULL default '',
584 rev_timestamp char(14) binary NOT NULL default '',
585 rev_minor_edit tinyint(1) unsigned NOT NULL default '0',
586 rev_deleted tinyint(1) unsigned NOT NULL default '0',
587 rev_len int(8) unsigned,
588 rev_parent_id int(8) unsigned default NULL,
589 PRIMARY KEY rev_page_id (rev_page, rev_id),
590 UNIQUE INDEX rev_id (rev_id),
591 INDEX rev_timestamp (rev_timestamp),
592 INDEX page_timestamp (rev_page,rev_timestamp),
593 INDEX user_timestamp (rev_user,rev_timestamp),
594 INDEX usertext_timestamp (rev_user_text,rev_timestamp)
595 ) ENGINE=InnoDB", $fname );
597 wfOut( wfTimestamp( TS_DB ) );
598 wfOut( "......Locking tables.\n" );
599 $wgDatabase->query( "LOCK TABLES $page WRITE, $revision WRITE, $old WRITE, $cur WRITE", $fname );
601 $maxold = intval( $wgDatabase->selectField( 'old', 'max(old_id)', '', $fname ) );
602 wfOut( wfTimestamp( TS_DB ) );
603 wfOut( "......maxold is {$maxold}\n" );
605 wfOut( wfTimestamp( TS_DB ) );
606 global $wgLegacySchemaConversion;
607 if( $wgLegacySchemaConversion ) {
608 // Create HistoryBlobCurStub entries.
609 // Text will be pulled from the leftover 'cur' table at runtime.
610 wfOut( "......Moving metadata from cur; using blob references to text in cur table.\n" );
611 $cur_text = "concat('O:18:\"historyblobcurstub\":1:{s:6:\"mCurId\";i:',cur_id,';}')";
612 $cur_flags = "'object'";
614 // Copy all cur text in immediately: this may take longer but avoids
615 // having to keep an extra table around.
616 wfOut( "......Moving text from cur.\n" );
617 $cur_text = 'cur_text';
620 $wgDatabase->query( "INSERT INTO $old (old_namespace, old_title, old_text, old_comment, old_user, old_user_text,
621 old_timestamp, old_minor_edit, old_flags)
622 SELECT cur_namespace, cur_title, $cur_text, cur_comment, cur_user, cur_user_text, cur_timestamp, cur_minor_edit, $cur_flags
623 FROM $cur", $fname );
625 wfOut( wfTimestamp( TS_DB ) );
626 wfOut( "......Setting up revision table.\n" );
627 $wgDatabase->query( "INSERT INTO $revision (rev_id, rev_page, rev_comment, rev_user, rev_user_text, rev_timestamp,
629 SELECT old_id, cur_id, old_comment, old_user, old_user_text,
630 old_timestamp, old_minor_edit
631 FROM $old,$cur WHERE old_namespace=cur_namespace AND old_title=cur_title", $fname );
633 wfOut( wfTimestamp( TS_DB ) );
634 wfOut( "......Setting up page table.\n" );
635 $wgDatabase->query( "INSERT INTO $page (page_id, page_namespace, page_title, page_restrictions, page_counter,
636 page_is_redirect, page_is_new, page_random, page_touched, page_latest, page_len)
637 SELECT cur_id, cur_namespace, cur_title, cur_restrictions, cur_counter, cur_is_redirect, cur_is_new,
638 cur_random, cur_touched, rev_id, LENGTH(cur_text)
640 WHERE cur_id=rev_page AND rev_timestamp=cur_timestamp AND rev_id > {$maxold}", $fname );
642 wfOut( wfTimestamp( TS_DB ) );
643 wfOut( "......Unlocking tables.\n" );
644 $wgDatabase->query( "UNLOCK TABLES", $fname );
646 wfOut( wfTimestamp( TS_DB ) );
647 wfOut( "......Renaming old.\n" );
648 $wgDatabase->query( "ALTER TABLE $old RENAME TO $text", $fname );
650 wfOut( wfTimestamp( TS_DB ) );
651 wfOut( "...done.\n" );
655 function do_inverse_timestamp() {
657 if( $wgDatabase->fieldExists( 'revision', 'inverse_timestamp' ) ) {
658 wfOut( "Removing revision.inverse_timestamp and fixing indexes... " );
659 dbsource( archive( 'patch-inverse_timestamp.sql' ), $wgDatabase );
662 wfOut( "revision timestamp indexes already up to 2005-03-13\n" );
666 function do_text_id() {
668 if( $wgDatabase->fieldExists( 'revision', 'rev_text_id' ) ) {
669 wfOut( "...rev_text_id already in place.\n" );
671 wfOut( "Adding rev_text_id field... " );
672 dbsource( archive( 'patch-rev_text_id.sql' ), $wgDatabase );
677 function do_namespace_size() {
681 'recentchanges' => 'rc',
683 'querycache' => 'qc',
686 foreach( $tables as $table => $prefix ) {
687 do_namespace_size_on( $table, $prefix );
692 function do_namespace_size_on( $table, $prefix ) {
693 global $wgDatabase, $wgDBtype;
694 if ($wgDBtype != 'mysql')
696 $field = $prefix . '_namespace';
698 $tablename = $wgDatabase->tableName( $table );
699 $result = $wgDatabase->query( "SHOW COLUMNS FROM $tablename LIKE '$field'" );
700 $info = $wgDatabase->fetchObject( $result );
701 $wgDatabase->freeResult( $result );
703 if( substr( $info->Type, 0, 3 ) == 'int' ) {
704 wfOut( "...$field is already a full int ($info->Type).\n" );
706 wfOut( "Promoting $field from $info->Type to int... " );
708 $sql = "ALTER TABLE $tablename MODIFY $field int NOT NULL";
709 $wgDatabase->query( $sql );
715 function do_pagelinks_update() {
717 if( $wgDatabase->tableExists( 'pagelinks' ) ) {
718 wfOut( "...already have pagelinks table.\n" );
720 wfOut( "Converting links and brokenlinks tables to pagelinks... " );
721 dbsource( archive( 'patch-pagelinks.sql' ), $wgDatabase );
725 global $wgCanonicalNamespaceNames;
726 foreach( $wgCanonicalNamespaceNames as $ns => $name ) {
728 do_pagelinks_namespace( $ns );
734 function do_pagelinks_namespace( $namespace ) {
735 global $wgDatabase, $wgContLang;
737 $ns = intval( $namespace );
738 wfOut( "Cleaning up broken links for namespace $ns... " );
740 $pagelinks = $wgDatabase->tableName( 'pagelinks' );
741 $name = $wgContLang->getNsText( $ns );
742 $prefix = $wgDatabase->strencode( $name );
743 $likeprefix = str_replace( '_', '\\_', $prefix);
745 $sql = "UPDATE $pagelinks
746 SET pl_namespace=$ns,
747 pl_title=TRIM(LEADING '$prefix:' FROM pl_title)
749 AND pl_title LIKE '$likeprefix:%'";
751 $wgDatabase->query( $sql, 'do_pagelinks_namespace' );
755 function do_drop_img_type() {
758 if( $wgDatabase->fieldExists( 'image', 'img_type' ) ) {
759 wfOut( "Dropping unused img_type field in image table... " );
760 dbsource( archive( 'patch-drop_img_type.sql' ), $wgDatabase );
763 wfOut( "No img_type field in image table; Good.\n" );
767 function do_old_links_update() {
769 if( $wgDatabase->tableExists( 'pagelinks' ) ) {
770 wfOut( "Already have pagelinks; skipping old links table updates.\n" );
772 convertLinks(); flush();
776 function do_user_unique_update() {
778 $duper = new UserDupes( $wgDatabase );
779 if( $duper->hasUniqueIndex() ) {
780 wfOut( "Already have unique user_name index.\n" );
782 if( !$duper->clearDupes() ) {
783 wfOut( "WARNING: This next step will probably fail due to unfixed duplicates...\n" );
785 wfOut( "Adding unique index on user_name... " );
786 dbsource( archive( 'patch-user_nameindex.sql' ), $wgDatabase );
791 function do_user_groups_update() {
792 $fname = 'do_user_groups_update';
795 if( $wgDatabase->tableExists( 'user_groups' ) ) {
796 wfOut( "...user_groups table already exists.\n" );
797 return do_user_groups_reformat();
800 wfOut( "Adding user_groups table... " );
801 dbsource( archive( 'patch-user_groups.sql' ), $wgDatabase );
804 if( !$wgDatabase->tableExists( 'user_rights' ) ) {
805 if( $wgDatabase->fieldExists( 'user', 'user_rights' ) ) {
806 wfOut( "Upgrading from a 1.3 or older database? Breaking out user_rights for conversion..." );
807 dbsource( archive( 'patch-user_rights.sql' ), $wgDatabase );
810 wfOut( "*** WARNING: couldn't locate user_rights table or field for upgrade.\n" );
811 wfOut( "*** You may need to manually configure some sysops by manipulating\n" );
812 wfOut( "*** the user_groups table.\n" );
817 wfOut( "Converting user_rights table to user_groups... " );
818 $result = $wgDatabase->select( 'user_rights',
819 array( 'ur_user', 'ur_rights' ),
820 array( "ur_rights != ''" ),
823 while( $row = $wgDatabase->fetchObject( $result ) ) {
824 $groups = array_unique(
826 explode( ',', $row->ur_rights ) ) );
828 foreach( $groups as $group ) {
829 $wgDatabase->insert( 'user_groups',
831 'ug_user' => $row->ur_user,
832 'ug_group' => $group ),
836 $wgDatabase->freeResult( $result );
840 function do_user_groups_reformat() {
841 # Check for bogus formats from previous 1.5 alpha code.
843 $info = $wgDatabase->fieldInfo( 'user_groups', 'ug_group' );
845 if( $info->type() == 'int' ) {
846 $oldug = $wgDatabase->tableName( 'user_groups' );
847 $newug = $wgDatabase->tableName( 'user_groups_bogus' );
848 wfOut( "user_groups is in bogus intermediate format. Renaming to $newug... " );
849 $wgDatabase->query( "ALTER TABLE $oldug RENAME TO $newug" );
852 wfOut( "Re-adding fresh user_groups table... " );
853 dbsource( archive( 'patch-user_groups.sql' ), $wgDatabase );
857 wfOut( "*** WARNING: You will need to manually fix up user permissions in the user_groups\n" );
858 wfOut( "*** table. Old 1.5 alpha versions did some pretty funky stuff...\n" );
861 wfOut( "...user_groups is in current format.\n" );
866 function do_watchlist_null() {
867 # Make sure wl_notificationtimestamp can be NULL,
868 # and update old broken items.
870 $info = $wgDatabase->fieldInfo( 'watchlist', 'wl_notificationtimestamp' );
872 if( !$info->nullable() ) {
873 wfOut( "Making wl_notificationtimestamp nullable... " );
874 dbsource( archive( 'patch-watchlist-null.sql' ), $wgDatabase );
877 wfOut( "...wl_notificationtimestamp is already nullable.\n" );
885 function do_page_random_update() {
888 wfOut( "Setting page_random to a random value on rows where it equals 0..." );
890 $page = $wgDatabase->tableName( 'page' );
891 $wgDatabase->query( "UPDATE $page SET page_random = RAND() WHERE page_random = 0", 'do_page_random_update' );
892 $rows = $wgDatabase->affectedRows();
894 wfOut( "changed $rows rows\n" );
897 function do_templatelinks_update() {
898 global $wgDatabase, $wgLoadBalancer;
899 $fname = 'do_templatelinks_update';
901 if ( $wgDatabase->tableExists( 'templatelinks' ) ) {
902 wfOut( "...templatelinks table already exists\n" );
905 wfOut( "Creating templatelinks table...\n" );
906 dbsource( archive('patch-templatelinks.sql'), $wgDatabase );
907 wfOut( "Populating...\n" );
908 if ( isset( $wgLoadBalancer ) && $wgLoadBalancer->getServerCount() > 1 ) {
909 // Slow, replication-friendly update
910 $res = $wgDatabase->select( 'pagelinks', array( 'pl_from', 'pl_namespace', 'pl_title' ),
911 array( 'pl_namespace' => NS_TEMPLATE ), $fname );
913 while ( $row = $wgDatabase->fetchObject( $res ) ) {
914 $count = ($count + 1) % 100;
916 if ( function_exists( 'wfWaitForSlaves' ) ) {
917 wfWaitForSlaves( 10 );
922 $wgDatabase->insert( 'templatelinks',
924 'tl_from' => $row->pl_from,
925 'tl_namespace' => $row->pl_namespace,
926 'tl_title' => $row->pl_title,
931 $wgDatabase->freeResult( $res );
934 $wgDatabase->insertSelect( 'templatelinks', 'pagelinks',
936 'tl_from' => 'pl_from',
937 'tl_namespace' => 'pl_namespace',
938 'tl_title' => 'pl_title'
944 wfOut( "Done. Please run maintenance/refreshLinks.php for a more thorough templatelinks update.\n" );
947 // Add index on ( rc_namespace, rc_user_text ) [Jul. 2006]
948 // Add index on ( rc_user_text, rc_timestamp ) [Nov. 2006]
949 function do_rc_indices_update() {
951 wfOut( "Checking for additional recent changes indices...\n" );
954 'rc_ns_usertext' => 'patch-recentchanges-utindex.sql',
955 'rc_user_text' => 'patch-rc_user_text-index.sql',
958 foreach( $indexes as $index => $patch ) {
959 $info = $wgDatabase->indexInfo( 'recentchanges', $index, __METHOD__ );
961 wfOut( "...index `{$index}` not found; adding..." );
962 dbsource( archive( $patch ) );
965 wfOut( "...index `{$index}` seems ok.\n" );
970 function index_has_field($table, $index, $field) {
972 wfOut( "Checking if $table index $index includes field $field...\n" );
973 $info = $wgDatabase->indexInfo( $table, $index, __METHOD__ );
975 foreach($info as $row) {
976 if($row->Column_name == $field) {
977 wfOut( "...index $index on table $table seems to be ok\n" );
982 wfOut( "...index $index on table $table has no field $field; adding\n" );
986 function do_backlinking_indices_update() {
987 wfOut( "Checking for backlinking indices...\n" );
988 if (!index_has_field('pagelinks', 'pl_namespace', 'pl_from') ||
989 !index_has_field('templatelinks', 'tl_namespace', 'tl_from') ||
990 !index_has_field('imagelinks', 'il_to', 'il_from'))
992 dbsource( archive( 'patch-backlinkindexes.sql' ) );
993 wfOut( "...backlinking indices updated\n" );
997 function do_categorylinks_indices_update() {
998 wfOut( "Checking for categorylinks indices...\n" );
999 if (!index_has_field('categorylinks', 'cl_sortkey', 'cl_from'))
1001 dbsource( archive( 'patch-categorylinksindex.sql' ) );
1002 wfOut( "...categorylinks indices updated\n" );
1006 function do_filearchive_indices_update() {
1008 wfOut( "Checking filearchive indices...\n" );
1009 $info = $wgDatabase->indexInfo( 'filearchive', 'fa_user_timestamp', __METHOD__ );
1012 dbsource( archive( 'patch-filearhive-user-index.sql' ) );
1013 wfOut( "...filearchive indices updated\n" );
1017 function maybe_do_profiling_memory_update() {
1019 if ( !$wgDatabase->tableExists( 'profiling' ) ) {
1021 } elseif ( $wgDatabase->fieldExists( 'profiling', 'pf_memory' ) ) {
1022 wfOut( "profiling table has pf_memory field.\n" );
1024 wfOut( "Adding pf_memory field to table profiling..." );
1025 dbsource( archive( 'patch-profiling-memory.sql' ), $wgDatabase );
1030 function do_stats_init() {
1031 // Sometimes site_stats table is not properly populated.
1033 wfOut( "Checking site_stats row..." );
1034 $row = $wgDatabase->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
1035 if( $row === false ) {
1036 wfOut( "data is missing! rebuilding...\n" );
1037 } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
1038 wfOut( "missing ss_total_pages, rebuilding...\n" );
1045 require_once "$IP/maintenance/initStats.inc";
1049 function do_active_users_init() {
1051 $activeUsers = $wgDatabase->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
1052 if( $activeUsers == -1 ) {
1053 $activeUsers = $wgDatabase->selectField( 'recentchanges',
1054 'COUNT( DISTINCT rc_user_text )',
1055 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
1057 $wgDatabase->update( 'site_stats',
1058 array( 'ss_active_users' => intval($activeUsers) ),
1059 array( 'ss_row_id' => 1 ), __METHOD__, array( 'LIMIT' => 1 )
1062 wfOut( "...ss_active_users user count set...\n" );
1065 function purge_cache() {
1067 # We can't guarantee that the user will be able to use TRUNCATE,
1068 # but we know that DELETE is available to us
1069 wfOut( "Purging caches..." );
1070 $wgDatabase->delete( 'objectcache', '*', __METHOD__ );
1074 function do_all_updates( $shared = false, $purge = true ) {
1075 global $wgNewTables, $wgNewFields, $wgRenamedTables, $wgSharedDB, $wgSharedTables, $wgDatabase, $wgDBtype, $IP;
1077 wfRunHooks('LoadExtensionSchemaUpdates');
1079 $doUser = $shared ? $wgSharedDB && in_array('user', $wgSharedTables) : !$wgSharedDB || !in_array('user', $wgSharedTables);
1081 if ($wgDBtype === 'postgres') {
1082 do_postgres_updates();
1086 # Run core updates in sequence...
1088 if ( isset( $wgUpdates[$wgDBtype] ) ) {
1089 foreach( $wgUpdates[$wgDBtype] as $params ) {
1090 $func = array_shift( $params );
1091 call_user_func_array( $func, $params );
1096 /// @fixme clean up this mess too!
1097 global $wgExtNewTables, $wgExtNewFields, $wgExtNewIndexes;
1098 # Add missing extension tables
1099 foreach ( $wgExtNewTables as $tableRecord ) {
1100 add_table( $tableRecord[0], $tableRecord[1], true );
1103 # Add missing extension fields
1104 foreach ( $wgExtNewFields as $fieldRecord ) {
1105 if ( $fieldRecord[0] != 'user' || $doUser ) {
1106 add_field( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true );
1110 # Add missing extension indexes
1111 foreach ( $wgExtNewIndexes as $fieldRecord ) {
1112 add_index( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true );
1117 wfOut( "Deleting old default messages (this may take a long time!)..." );
1118 deleteDefaultMessages();
1128 function archive($name) {
1129 global $wgDBtype, $IP;
1130 if ( file_exists( "$IP/maintenance/$wgDBtype/archives/$name" ) ) {
1131 return "$IP/maintenance/$wgDBtype/archives/$name";
1133 return "$IP/maintenance/archives/$name";
1137 function do_restrictions_update() {
1138 # Adding page_restrictions table, obsoleting page.page_restrictions.
1139 # Migrating old restrictions to new table
1140 # -- Andrew Garrett, January 2007.
1144 $name = 'page_restrictions';
1145 $patch = 'patch-page_restrictions.sql';
1146 $patch2 = 'patch-page_restrictions_sortkey.sql';
1148 if ( $wgDatabase->tableExists( $name ) ) {
1149 wfOut( "...$name table already exists.\n" );
1151 wfOut( "Creating $name table..." );
1152 dbsource( archive($patch), $wgDatabase );
1153 dbsource( archive($patch2), $wgDatabase );
1156 wfOut( "Migrating old restrictions to new table..." );
1158 $res = $wgDatabase->select( 'page', array( 'page_id', 'page_restrictions' ), array("page_restrictions!=''", "page_restrictions!='edit=:move='"), __METHOD__ );
1162 while ($row = $wgDatabase->fetchObject($res) ) {
1163 $count = ($count + 1) % 100;
1166 if ( function_exists( 'wfWaitForSlaves' ) ) {
1167 wfWaitForSlaves( 10 );
1173 # Figure out what the restrictions are..
1174 $id = $row->page_id;
1175 $flatrestrictions = explode( ':', $row->page_restrictions );
1177 $restrictions = array ();
1178 foreach( $flatrestrictions as $restriction ) {
1179 $thisrestriction = explode( '=', $restriction, 2 );
1180 if( count( $thisrestriction ) == 1 ) {
1181 // Compatibility with old protections from before
1182 // separate move protection was added.
1183 list( $level ) = $thisrestriction;
1185 $restrictions['edit'] = $level;
1186 $restrictions['move'] = $level;
1189 list( $type, $level ) = $thisrestriction;
1191 $restrictions[$type] = $level;
1195 $wgDatabase->update( 'page', array ( 'page_restrictions' => ''), array( 'page_id' => $id ), __METHOD__ );
1199 foreach( $restrictions as $type => $level ) {
1200 $wgDatabase->insert( 'page_restrictions', array ( 'pr_page' => $id,
1202 'pr_level' => $level,
1204 'pr_expiry' => 'infinity' ),
1212 function do_category_population() {
1213 if( update_row_exists( 'populate category' ) ) {
1214 wfOut( "...category table already populated.\n" );
1217 require_once( 'populateCategory.inc' );
1218 wfOut( "Populating category table, printing progress markers. " ).
1219 "For large databases, you\n".
1220 "may want to hit Ctrl-C and do this manually with maintenance/\n".
1221 "populateCategory.php.\n";
1222 populateCategory( '', 10, 0, true );
1223 wfOut( "Done populating category table.\n" );
1226 function do_populate_parent_id() {
1227 if( update_row_exists( 'populate rev_parent_id' ) ) {
1228 wfOut( "...rev_parent_id column already populated.\n" );
1231 require_once( 'populateParentId.inc' );
1234 populate_rev_parent_id( $wgDatabase );
1237 function update_password_format() {
1238 if ( update_row_exists( 'password format' ) ) {
1239 wfOut( "...password hash format already changed\n" );
1243 wfOut( "Updating password hash format..." );
1245 global $wgDatabase, $wgPasswordSalt;
1246 $user = $wgDatabase->tableName( 'user' );
1247 if ( $wgPasswordSalt ) {
1248 $sql = "UPDATE $user SET user_password=CONCAT(':B:', user_id, ':', user_password) " .
1249 "WHERE user_password NOT LIKE ':%'";
1251 $sql = "UPDATE $user SET user_password=CONCAT(':A:', user_password) " .
1252 "WHERE user_password NOT LIKE ':%'";
1254 $wgDatabase->query( $sql, __METHOD__ );
1255 $wgDatabase->insert( 'updatelog', array( 'ul_key' => 'password format' ), __METHOD__ );
1260 function sqlite_initial_indexes() {
1262 if ( update_row_exists( 'initial_indexes' ) ) {
1263 wfOut( "...have initial indexes\n" );
1266 wfOut( "Adding initial indexes..." );
1267 $wgDatabase->sourceFile( archive( 'initial-indexes.sql' ) );
1271 function do_unique_pl_tl_il() {
1273 $info = $wgDatabase->indexInfo( 'pagelinks', 'pl_namespace' );
1274 if( is_array($info) && !$info[0]->Non_unique ) {
1275 wfOut( "...pl_namespace, tl_namespace, il_to indices are already UNIQUE.\n" );
1277 wfOut( "Making pl_namespace, tl_namespace and il_to indices UNIQUE... " );
1278 dbsource( archive( 'patch-pl-tl-il-unique.sql' ), $wgDatabase );
1283 /***********************************************************************
1285 * TODO: merge with above
1286 ***********************************************************************/
1289 pg_describe_table($table)
1291 global $wgDatabase, $wgDBmwschema;
1293 SELECT attname, attnum FROM pg_namespace, pg_class, pg_attribute
1294 WHERE pg_class.relnamespace = pg_namespace.oid
1295 AND attrelid=pg_class.oid AND attnum > 0
1296 AND relname=%s AND nspname=%s
1298 $res = $wgDatabase->query(sprintf($q,
1299 $wgDatabase->addQuotes($table),
1300 $wgDatabase->addQuotes($wgDBmwschema)));
1305 while ($r = $wgDatabase->fetchRow($res)) {
1315 pg_describe_index($idx)
1317 global $wgDatabase, $wgDBmwschema;
1319 // first fetch the key (which is a list of columns ords) and
1320 // the table the index applies to (an oid)
1322 SELECT indkey, indrelid FROM pg_namespace, pg_class, pg_index
1324 AND pg_class.relnamespace = pg_namespace.oid
1326 AND indexrelid=pg_class.oid
1328 $res = $wgDatabase->query(sprintf($q,
1329 $wgDatabase->addQuotes($wgDBmwschema),
1330 $wgDatabase->addQuotes($idx)));
1333 if (!($r = $wgDatabase->fetchRow($res))) {
1334 $wgDatabase->freeResult($res);
1339 $relid = intval($r[1]);
1340 $indkeys = explode(" ", $indkey);
1341 $wgDatabase->freeResult($res);
1343 $colnames = array();
1344 foreach ($indkeys as $rid) {
1346 SELECT attname FROM pg_class, pg_attribute
1347 WHERE attrelid=$relid
1349 AND attrelid=pg_class.oid
1351 $r2 = $wgDatabase->query(sprintf($query, $rid));
1354 if (!($row2 = $wgDatabase->fetchRow($r2))) {
1355 $wgDatabase->freeResult($r2);
1358 $colnames[] = $row2[0];
1359 $wgDatabase->freeResult($r2);
1366 pg_index_exists($table, $index)
1368 global $wgDatabase, $wgDBmwschema;
1369 $exists = $wgDatabase->selectField("pg_indexes", "indexname",
1370 array( "indexname" => $index,
1371 "tablename" => $table,
1372 "schemaname" => $wgDBmwschema));
1373 return $exists === $index;
1377 pg_fkey_deltype($fkey)
1379 global $wgDatabase, $wgDBmwschema;
1381 SELECT confdeltype FROM pg_constraint, pg_namespace
1382 WHERE connamespace=pg_namespace.oid
1386 $r = $wgDatabase->query(sprintf($q,
1387 $wgDatabase->addQuotes($wgDBmwschema),
1388 $wgDatabase->addQuotes($fkey)));
1389 if (!($row = $wgDatabase->fetchRow($r)))
1395 pg_rule_def($table, $rule)
1397 global $wgDatabase, $wgDBmwschema;
1399 SELECT definition FROM pg_rules
1400 WHERE schemaname = %s
1404 $r = $wgDatabase->query(sprintf($q,
1405 $wgDatabase->addQuotes($wgDBmwschema),
1406 $wgDatabase->addQuotes($table),
1407 $wgDatabase->addQuotes($rule)));
1408 $row = $wgDatabase->fetchRow($r);
1412 $wgDatabase->freeResult($r);
1416 function do_postgres_updates() {
1417 global $wgDatabase, $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgShowExceptionDetails, $wgDBuser;
1419 ## Gather version numbers in case we need them
1420 $version = $wgDatabase->getServerVersion(); ## long string
1421 $numver = $wgDatabase->numeric_version; ## X.Y e.g. 8.3
1423 $wgShowExceptionDetails = 1;
1425 # Just in case their LocalSettings.php does not have this:
1426 if ( !isset( $wgDBmwschema ))
1427 $wgDBmwschema = 'mediawiki';
1429 # Verify that this user is configured correctly
1430 $safeuser = $wgDatabase->addQuotes($wgDBuser);
1431 $SQL = "SELECT array_to_string(useconfig,'*') FROM pg_catalog.pg_user WHERE usename = $safeuser";
1432 $config = pg_fetch_result( $wgDatabase->doQuery( $SQL ), 0, 0 );
1434 foreach( explode( '*', $config ) as $c ) {
1435 list( $x,$y ) = explode( '=', $c );
1438 if( !array_key_exists( 'search_path', $conf ) ) {
1442 $search_path = $conf['search_path'];
1444 if( strpos( $search_path, $wgDBmwschema ) === false ) {
1445 wfOut( "Adding in schema \"$wgDBmwschema\" to search_path for user \"$wgDBuser\"\n" );
1446 $search_path = "$wgDBmwschema, $search_path";
1448 if( strpos( $search_path, $wgDBts2schema ) === false ) {
1449 wfOut( "Adding in schema \"$wgDBts2schema\" to search_path for user \"$wgDBuser\"\n" );
1450 $search_path = "$search_path, $wgDBts2schema";
1452 $search_path = str_replace( ', ,', ',', $search_path);
1453 if( array_key_exists( 'search_path', $conf ) === false || $search_path != $conf['search_path'] ) {
1454 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET search_path = $search_path" );
1455 $wgDatabase->doQuery( "SET search_path = $search_path" );
1458 $path = $conf['search_path'];
1459 wfOut( "... search_path for user \"$wgDBuser\" looks correct ($path)\n" );
1462 'client_min_messages' => 'error',
1463 'DateStyle' => 'ISO, YMD',
1466 foreach( array_keys( $goodconf ) AS $key ) {
1467 $value = $goodconf[$key];
1468 if( !array_key_exists( $key, $conf ) or $conf[$key] !== $value ) {
1469 wfOut( "Setting $key to '$value' for user \"$wgDBuser\"\n" );
1470 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET $key = '$value'" );
1471 $wgDatabase->doQuery( "SET $key = '$value'" );
1474 wfOut( "... default value of \"$key\" is correctly set to \"$value\" for user \"$wgDBuser\"\n" );
1478 $newsequences = array(
1484 array("category", "patch-category.sql"),
1485 array("mediawiki_version", "patch-mediawiki_version.sql"),
1486 array("mwuser", "patch-mwuser.sql"),
1487 array("pagecontent", "patch-pagecontent.sql"),
1488 array("querycachetwo", "patch-querycachetwo.sql"),
1489 array("page_props", "patch-page_props.sql"),
1490 array("page_restrictions", "patch-page_restrictions.sql"),
1491 array("profiling", "patch-profiling.sql"),
1492 array("protected_titles", "patch-protected_titles.sql"),
1493 array("redirect", "patch-redirect.sql"),
1494 array("updatelog", "patch-updatelog.sql"),
1495 array('change_tag', 'patch-change_tag.sql'),
1496 array('tag_summary', 'patch-change_tag.sql'),
1497 array('valid_tag', 'patch-change_tag.sql'),
1501 array("archive", "ar_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1502 array("archive", "ar_len", "INTEGER"),
1503 array("archive", "ar_page_id", "INTEGER"),
1504 array("archive", "ar_parent_id", "INTEGER"),
1505 array("image", "img_sha1", "TEXT NOT NULL DEFAULT ''"),
1506 array("ipblocks", "ipb_allow_usertalk", "SMALLINT NOT NULL DEFAULT 0"),
1507 array("ipblocks", "ipb_anon_only", "SMALLINT NOT NULL DEFAULT 0"),
1508 array("ipblocks", "ipb_by_text", "TEXT NOT NULL DEFAULT ''"),
1509 array("ipblocks", "ipb_block_email", "SMALLINT NOT NULL DEFAULT 0"),
1510 array("ipblocks", "ipb_create_account", "SMALLINT NOT NULL DEFAULT 1"),
1511 array("ipblocks", "ipb_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1512 array("ipblocks", "ipb_enable_autoblock", "SMALLINT NOT NULL DEFAULT 1"),
1513 array("filearchive", "fa_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1514 array("logging", "log_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1515 array("logging", "log_id", "INTEGER NOT NULL PRIMARY KEY DEFAULT nextval('log_log_id_seq')"),
1516 array("logging", "log_params", "TEXT"),
1517 array("mwuser", "user_editcount", "INTEGER"),
1518 array("mwuser", "user_newpass_time", "TIMESTAMPTZ"),
1519 array("oldimage", "oi_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1520 array("oldimage", "oi_major_mime", "TEXT NOT NULL DEFAULT 'unknown'"),
1521 array("oldimage", "oi_media_type", "TEXT"),
1522 array("oldimage", "oi_metadata", "BYTEA NOT NULL DEFAULT ''"),
1523 array("oldimage", "oi_minor_mime", "TEXT NOT NULL DEFAULT 'unknown'"),
1524 array("oldimage", "oi_sha1", "TEXT NOT NULL DEFAULT ''"),
1525 array("page_restrictions", "pr_id", "INTEGER NOT NULL UNIQUE DEFAULT nextval('pr_id_val')"),
1526 array("profiling", "pf_memory", "NUMERIC(18,10) NOT NULL DEFAULT 0"),
1527 array("recentchanges", "rc_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1528 array("recentchanges", "rc_log_action", "TEXT"),
1529 array("recentchanges", "rc_log_type", "TEXT"),
1530 array("recentchanges", "rc_logid", "INTEGER NOT NULL DEFAULT 0"),
1531 array("recentchanges", "rc_new_len", "INTEGER"),
1532 array("recentchanges", "rc_old_len", "INTEGER"),
1533 array("recentchanges", "rc_params", "TEXT"),
1534 array("revision", "rev_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1535 array("revision", "rev_len", "INTEGER"),
1536 array("revision", "rev_parent_id", "INTEGER DEFAULT NULL"),
1537 array("site_stats", "ss_active_users", "INTEGER DEFAULT '-1'"),
1538 array("user_newtalk", "user_last_timestamp", "TIMESTAMPTZ"),
1542 # table, column, desired type, USING clause if needed (with new default if needed)
1543 $typechanges = array(
1544 array("archive", "ar_deleted", "smallint", ""),
1545 array("archive", "ar_minor_edit", "smallint", "ar_minor_edit::smallint DEFAULT 0"),
1546 array("filearchive", "fa_deleted", "smallint", ""),
1547 array("filearchive", "fa_height", "integer", ""),
1548 array("filearchive", "fa_metadata", "bytea", "decode(fa_metadata,'escape')"),
1549 array("filearchive", "fa_size", "integer", ""),
1550 array("filearchive", "fa_width", "integer", ""),
1551 array("filearchive", "fa_storage_group","text", ""),
1552 array("filearchive", "fa_storage_key", "text", ""),
1553 array("image", "img_metadata", "bytea", "decode(img_metadata,'escape')"),
1554 array("image", "img_size", "integer", ""),
1555 array("image", "img_width", "integer", ""),
1556 array("image", "img_height", "integer", ""),
1557 array("interwiki", "iw_local", "smallint", "iw_local::smallint DEFAULT 0"),
1558 array("interwiki", "iw_trans", "smallint", "iw_trans::smallint DEFAULT 0"),
1559 array("ipblocks", "ipb_auto", "smallint", "ipb_auto::smallint DEFAULT 0"),
1560 array("ipblocks", "ipb_anon_only", "smallint", "CASE WHEN ipb_anon_only=' ' THEN 0 ELSE ipb_anon_only::smallint END DEFAULT 0"),
1561 array("ipblocks", "ipb_create_account", "smallint", "CASE WHEN ipb_create_account=' ' THEN 0 ELSE ipb_create_account::smallint END DEFAULT 1"),
1562 array("ipblocks", "ipb_enable_autoblock", "smallint", "CASE WHEN ipb_enable_autoblock=' ' THEN 0 ELSE ipb_enable_autoblock::smallint END DEFAULT 1"),
1563 array("ipblocks", "ipb_block_email", "smallint", "CASE WHEN ipb_block_email=' ' THEN 0 ELSE ipb_block_email::smallint END DEFAULT 0"),
1564 array("ipblocks", "ipb_address", "text", "ipb_address::text"),
1565 array("ipblocks", "ipb_deleted", "smallint", "ipb_deleted::smallint"),
1566 array("math", "math_inputhash", "bytea", "decode(math_inputhash,'escape')"),
1567 array("math", "math_outputhash", "bytea", "decode(math_outputhash,'escape')"),
1568 array("mwuser", "user_token", "text", ""),
1569 array("mwuser", "user_email_token","text", ""),
1570 array("objectcache", "keyname", "text", ""),
1571 array("oldimage", "oi_height", "integer", ""),
1572 array("oldimage", "oi_metadata", "bytea", "decode(img_metadata,'escape')"),
1573 array("oldimage", "oi_size", "integer", ""),
1574 array("oldimage", "oi_width", "integer", ""),
1575 array("page", "page_is_redirect","smallint", "page_is_redirect::smallint DEFAULT 0"),
1576 array("page", "page_is_new", "smallint", "page_is_new::smallint DEFAULT 0"),
1577 array("querycache", "qc_value", "integer", ""),
1578 array("querycachetwo","qcc_value", "integer", ""),
1579 array("recentchanges","rc_bot", "smallint", "rc_bot::smallint DEFAULT 0"),
1580 array("recentchanges","rc_deleted", "smallint", ""),
1581 array("recentchanges","rc_minor", "smallint", "rc_minor::smallint DEFAULT 0"),
1582 array("recentchanges","rc_new", "smallint", "rc_new::smallint DEFAULT 0"),
1583 array("recentchanges","rc_type", "smallint", "rc_type::smallint DEFAULT 0"),
1584 array("recentchanges","rc_patrolled", "smallint", "rc_patrolled::smallint DEFAULT 0"),
1585 array("revision", "rev_deleted", "smallint", "rev_deleted::smallint DEFAULT 0"),
1586 array("revision", "rev_minor_edit", "smallint", "rev_minor_edit::smallint DEFAULT 0"),
1587 array("templatelinks","tl_namespace", "smallint", "tl_namespace::smallint"),
1588 array("user_newtalk", "user_ip", "text", "host(user_ip)"),
1591 $newindexes = array(
1592 array("archive", "archive_user_text", "(ar_user_text)"),
1593 array("image", "img_sha1", "(img_sha1)"),
1594 array("oldimage", "oi_sha1", "(oi_sha1)"),
1595 array("revision", "rev_text_id_idx", "(rev_text_id)"),
1596 array("recentchanges", "rc_timestamp_nobot", "(rc_timestamp) WHERE rc_bot = 0"),
1597 array("templatelinks", "templatelinks_from", "(tl_from)"),
1598 array("watchlist", "wl_user", "(wl_user)"),
1604 foreach ($newsequences as $ns) {
1605 if ($wgDatabase->sequenceExists($ns)) {
1606 wfOut( "... sequence \"$ns\" already exists\n" );
1610 wfOut( "Creating sequence \"$ns\"\n" );
1611 $wgDatabase->query("CREATE SEQUENCE $ns");
1614 foreach ($newtables as $nt) {
1615 if ($wgDatabase->tableExists($nt[0])) {
1616 wfOut( "... table \"$nt[0]\" already exists\n" );
1620 wfOut( "Creating table \"$nt[0]\"\n" );
1621 dbsource(archive($nt[1]));
1624 ## Needed before newcols
1625 if ($wgDatabase->tableExists("archive2")) {
1626 wfOut( "Converting \"archive2\" back to normal archive table\n" );
1627 if ($wgDatabase->ruleExists("archive", "archive_insert")) {
1628 wfOut( "Dropping rule \"archive_insert\"\n" );
1629 $wgDatabase->query("DROP RULE archive_insert ON archive");
1631 if ($wgDatabase->ruleExists("archive", "archive_delete")) {
1632 wfOut( "Dropping rule \"archive_delete\"\n" );
1633 $wgDatabase->query("DROP RULE archive_delete ON archive");
1635 dbsource(archive("patch-remove-archive2.sql"));
1638 wfOut( "... obsolete table \"archive2\" does not exist\n" );
1640 foreach ($newcols as $nc) {
1641 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1642 if (!is_null($fi)) {
1643 wfOut( "... column \"$nc[0].$nc[1]\" already exists\n" );
1647 wfOut( "Adding column \"$nc[0].$nc[1]\"\n" );
1648 $wgDatabase->query("ALTER TABLE $nc[0] ADD $nc[1] $nc[2]");
1651 foreach ($typechanges as $tc) {
1652 $fi = $wgDatabase->fieldInfo($tc[0], $tc[1]);
1654 wfOut( "... error: expected column $tc[0].$tc[1] to exist\n" );
1658 if ($fi->type() === $tc[2])
1659 wfOut( "... column \"$tc[0].$tc[1]\" is already of type \"$tc[2]\"\n" );
1661 wfOut( "Changing column type of \"$tc[0].$tc[1]\" from \"{$fi->type()}\" to \"$tc[2]\"\n" );
1662 $sql = "ALTER TABLE $tc[0] ALTER $tc[1] TYPE $tc[2]";
1663 if (strlen($tc[3])) {
1665 if (preg_match( '/DEFAULT (.+)/', $tc[3], $default)) {
1666 $sqldef = "ALTER TABLE $tc[0] ALTER $tc[1] SET DEFAULT $default[1]";
1667 $wgDatabase->query($sqldef);
1668 $tc[3] = preg_replace( '/\s*DEFAULT .+/', '', $tc[3]);
1670 $sql .= " USING $tc[3]";
1672 $sql .= ";\nCOMMIT;\n";
1673 $wgDatabase->query($sql);
1677 if ($wgDatabase->fieldInfo('oldimage','oi_deleted')->type() !== 'smallint') {
1678 wfOut( "Changing \"oldimage.oi_deleted\" to type \"smallint\"\n" );
1679 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted DROP DEFAULT" );
1680 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted TYPE SMALLINT USING (oi_deleted::smallint)" );
1681 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted SET DEFAULT 0" );
1684 wfOut( "... column \"oldimage.oi_deleted\" is already of type \"smallint\"\n" );
1687 foreach ($newindexes as $ni) {
1688 if (pg_index_exists($ni[0], $ni[1])) {
1689 wfOut( "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n" );
1692 wfOut( "Creating index \"$ni[1]\" on table \"$ni[0]\" $ni[2]\n" );
1693 $wgDatabase->query( "CREATE INDEX $ni[1] ON $ni[0] $ni[2]" );
1696 foreach ($newrules as $nr) {
1697 if ($wgDatabase->ruleExists($nr[0], $nr[1])) {
1698 wfOut( "... rule \"$nr[1]\" on table \"$nr[0]\" already exists\n" );
1701 wfOut( "Adding rule \"$nr[1]\" to table \"$nr[0]\"\n" );
1702 dbsource(archive($nr[2]));
1705 if ($wgDatabase->hasConstraint("oldimage_oi_name_fkey")) {
1706 wfOut( "Making foriegn key on table \"oldimage\" (to image) a cascade delete\n" );
1707 $wgDatabase->query( "ALTER TABLE oldimage DROP CONSTRAINT oldimage_oi_name_fkey" );
1708 $wgDatabase->query( "ALTER TABLE oldimage ADD CONSTRAINT oldimage_oi_name_fkey_cascade ".
1709 "FOREIGN KEY (oi_name) REFERENCES image(img_name) ON DELETE CASCADE" );
1712 wfOut( "... table \"oldimage\" has correct cascade delete foreign key to image\n" );
1714 if (!$wgDatabase->triggerExists("page", "page_deleted")) {
1715 wfOut( "Adding function and trigger \"page_deleted\" to table \"page\"\n" );
1716 dbsource(archive('patch-page_deleted.sql'));
1719 wfOut( "... table \"page\" has \"page_deleted\" trigger\n" );
1721 $fi = $wgDatabase->fieldInfo("recentchanges", "rc_cur_id");
1722 if (!$fi->nullable()) {
1723 wfOut( "Removing NOT NULL constraint from \"recentchanges.rc_cur_id\"\n" );
1724 dbsource(archive('patch-rc_cur_id-not-null.sql'));
1727 wfOut( "... column \"recentchanges.rc_cur_id\" has a NOT NULL constraint\n" );
1729 $pu = pg_describe_index("pagelink_unique");
1730 if (!is_null($pu) && ($pu[0] != "pl_from" || $pu[1] != "pl_namespace" || $pu[2] != "pl_title")) {
1731 wfOut( "Dropping obsolete version of index \"pagelink_unique index\"\n" );
1732 $wgDatabase->query("DROP INDEX pagelink_unique");
1736 wfOut( "... obsolete version of index \"pagelink_unique index\" does not exist\n" );
1739 wfOut( "Creating index \"pagelink_unique index\"\n" );
1740 $wgDatabase->query("CREATE UNIQUE INDEX pagelink_unique ON pagelinks (pl_from,pl_namespace,pl_title)");
1743 wfOut( "... index \"pagelink_unique_index\" already exists\n" );
1745 if (pg_fkey_deltype("revision_rev_user_fkey") == 'r') {
1746 wfOut( "... constraint \"revision_rev_user_fkey\" is ON DELETE RESTRICT\n" );
1749 wfOut( "Changing constraint \"revision_rev_user_fkey\" to ON DELETE RESTRICT\n" );
1750 dbsource(archive('patch-revision_rev_user_fkey.sql'));
1753 # Fix ipb_address index
1754 if (pg_index_exists('ipblocks', 'ipb_address' )) {
1755 wfOut( "Removing deprecated index 'ipb_address'...\n" );
1756 $wgDatabase->query('DROP INDEX ipb_address');
1758 if (pg_index_exists('ipblocks', 'ipb_address_unique' )) {
1759 wfOut( "... have ipb_address_unique\n" );
1762 wfOut( "Adding ipb_address_unique index\n" );
1763 dbsource(archive('patch-ipb_address_unique.sql'));
1766 global $wgExtNewTables, $wgExtPGNewFields, $wgExtNewIndexes;
1767 # Add missing extension tables
1768 foreach ( $wgExtNewTables as $nt ) {
1769 if ($wgDatabase->tableExists($nt[0])) {
1770 wfOut( "... table \"$nt[0]\" already exists\n" );
1773 wfOut( "Creating table \"$nt[0]\"\n" );
1776 # Add missing extension fields
1777 foreach ( $wgExtPGNewFields as $nc ) {
1778 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1779 if (!is_null($fi)) {
1780 wfOut( "... column \"$nc[0].$nc[1]\" already exists\n" );
1783 wfOut( "Adding column \"$nc[0].$nc[1]\"\n" );
1784 $wgDatabase->query( "ALTER TABLE $nc[0] ADD $nc[1] $nc[2]" );
1786 # Add missing extension indexes
1787 foreach ( $wgExtNewIndexes as $ni ) {
1788 if (pg_index_exists($ni[0], $ni[1])) {
1789 wfOut( "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n" );
1792 wfOut( "Creating index \"$ni[1]\" on table \"$ni[0]\"\n" );
1796 # Tweak the page_title tsearch2 trigger to filter out slashes
1797 # This is create or replace, so harmless to call if not needed
1798 dbsource(archive('patch-ts2pagetitle.sql'));
1800 ## If the server is 8.3 or higher, rewrite the tsearch2 triggers
1801 ## in case they have the old 'default' versions
1802 if ( $numver >= 8.3 )
1803 dbsource(archive('patch-tsearch2funcs.sql'));
1805 ## Put a new row in the mediawiki_version table
1806 $wgDatabase->insert( 'mediawiki_version',
1810 'mw_version' => $wgVersion,
1811 'pg_version' => $version,
1812 'sql_version' => '$LastChangedRevision$',
1813 'sql_date' => '$LastChangedDate$',