Expand a few comments. One as per Nikerabbit's comment on r59695.
[mediawiki.git] / maintenance / updaters.inc
blobfd3bebd19457f686fe44c5b04e9f48f653f83e0a
1 <?php
2 /**
3  * @file
4  * @ingroup Maintenance
5  */
7 if ( !defined( 'MEDIAWIKI' ) ) {
8         echo "This file is not a valid entry point\n";
9         exit( 1 );
12 require_once 'convertLinks.inc';
13 require_once 'userDupes.inc';
14 # Extension updates
15 require_once( "$IP/includes/Hooks.php" );
17 /**
18  * List of update functions to call for each DB type, in sequence. First item 
19  * is function name, rest are parameters to pass.
20  */
21 $wgUpdates = array(
22         'mysql' => array(
23                 // 1.2
24                 // update_passwords obsolete
25                 array( 'add_field', 'ipblocks',      'ipb_id',           'patch-ipblocks.sql' ),
26                 array( 'add_field', 'ipblocks',      'ipb_expiry',       'patch-ipb_expiry.sql' ),
27                 array( 'do_interwiki_update' ),
28                 array( 'do_index_update' ),
29                 // do_linkscc_update obsolete
30                 array( 'add_table', 'hitcounter',                        'patch-hitcounter.sql' ),
31                 array( 'add_field', 'recentchanges', 'rc_type',          'patch-rc_type.sql' ),
32                 
33                 // 1.3
34                 array( 'add_field', 'user',          'user_real_name',   'patch-user-realname.sql' ),
35                 array( 'add_table', 'querycache',                        'patch-querycache.sql' ),
36                 array( 'add_table', 'objectcache',                       'patch-objectcache.sql' ),
37                 array( 'add_table', 'categorylinks',                     'patch-categorylinks.sql' ),
38                 // do_linkscc_1_3_update obsolete
39                 array( 'do_old_links_update' ),
40                 array( 'fix_ancient_imagelinks' ),
41                 array( 'add_field', 'recentchanges', 'rc_ip',            'patch-rc_ip.sql' ),
42                 
43                 // 1.4
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
56                 
57                 // 1.5
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' ),
81                 
82                 // 1.6
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' ),
98                 
99                 // 1.9
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' ),
107                 
108                 // 1.10
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' ),
120                 
121                 // 1.11
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' ),
131                 // 1.12
132                 array( 'add_table', 'protected_titles',                  'patch-protected_titles.sql' ),
133                 
134                 // 1.13
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                 
147                 // 1.14
148                 array( 'add_field', 'site_stats',    'ss_active_users',  'patch-ss_active_users.sql' ),
149                 array( 'do_active_users_init' ),
150                 array( 'add_field', 'ipblocks',      'ipb_allow_usertalk', 'patch-ipb_allow_usertalk.sql' ),
152                 // 1.15
153                 array( 'do_unique_pl_tl_il' ),
154                 array( 'add_table', 'change_tag',                        'patch-change_tag.sql' ),
155                 array( 'add_table', 'tag_summary',                       'patch-change_tag.sql' ),
156                 array( 'add_table', 'valid_tag',                         'patch-change_tag.sql' ),
158                 // 1.16
159                 array( 'add_table', 'user_properties',                   'patch-user_properties.sql' ),
160                 array( 'add_table', 'log_search',                        'patch-log_search.sql' ),
161                 array( 'do_log_search_population' ),
162                 array( 'add_field', 'logging',       'log_user_text',    'patch-log_user_text.sql' ),
163                 array( 'add_table', 'l10n_cache',                        'patch-l10n_cache.sql' ),
164                 array( 'add_table', 'external_user',                     'patch-external_user.sql' ),
165                 array( 'add_index', 'log_search',    'ls_field_val',     'patch-log_search-rename-index.sql' ),
166                 array( 'add_index', 'change_tag',    'change_tag_rc_tag', 'patch-change_tag-indexes.sql' ),
167                 array( 'add_field', 'redirect',      'rd_interwiki',     'patch-rd_interwiki.sql' ),
168         ),
170         'sqlite' => array(
171                 // 1.14
172                 array( 'add_field', 'site_stats',    'ss_active_users',  'patch-ss_active_users.sql' ),
173                 array( 'do_active_users_init' ),
174                 array( 'add_field', 'ipblocks',      'ipb_allow_usertalk', 'patch-ipb_allow_usertalk.sql' ),
175                 array( 'sqlite_initial_indexes' ),
177                 // 1.15
178                 array( 'add_table', 'change_tag',                        'patch-change_tag.sql' ),
179                 array( 'add_table', 'tag_summary',                       'patch-change_tag.sql' ),
180                 array( 'add_table', 'valid_tag',                         'patch-change_tag.sql' ),
182                 // 1.16
183                 array( 'add_table', 'user_properties',                   'patch-user_properties.sql' ),
184                 array( 'add_table', 'log_search',                        'patch-log_search.sql' ),
185                 array( 'do_log_search_population' ),
186                 array( 'add_field', 'logging',       'log_user_text',    'patch-log_user_text.sql' ),
187                 array( 'add_table', 'l10n_cache',                        'patch-l10n_cache.sql' ),
188                 array( 'add_table', 'external_user',                     'patch-external_user.sql' ),
189                 array( 'add_index', 'log_search',    'ls_field_val',     'patch-log_search-rename-index.sql' ),
190                 array( 'add_index', 'change_tag',    'change_tag_rc_tag', 'patch-change_tag-indexes.sql' ),
191                 array( 'add_field', 'redirect',      'rd_interwiki',     'patch-rd_interwiki.sql' ),
192                 
193                 // version-independent searchindex setup, added in 1.16
194                 array( 'sqlite_setup_searchindex' ),
195         ),
199 # For extensions only, should be populated via hooks
200 # $wgDBtype should be checked to specifiy the proper file
201 $wgExtNewTables = array(); // table, dir
202 $wgExtNewFields = array(); // table, column, dir
203 $wgExtPGNewFields = array(); // table, column, column attributes; for PostgreSQL
204 $wgExtPGAlteredFields = array(); // table, column, new type, conversion method; for PostgreSQL
205 $wgExtNewIndexes = array(); // table, index, dir
206 $wgExtModifiedFields = array(); //table, index, dir
208 # Helper function: check if the given key is present in the updatelog table.
209 # Obviously, only use this for updates that occur after the updatelog table was
210 # created!
211 function update_row_exists( $key ) {
212         $dbr = wfGetDB( DB_SLAVE );
213         $row = $dbr->selectRow(
214                 'updatelog',
215                 '1',
216                 array( 'ul_key' => $key ),
217                 __FUNCTION__
218         );
219         return (bool)$row;
222 function rename_table( $from, $to, $patch ) {
223         global $wgDatabase;
224         if ( $wgDatabase->tableExists( $from ) ) {
225                 if ( $wgDatabase->tableExists( $to ) ) {
226                         wfOut( "...can't move table $from to $to, $to already exists.\n" );
227                 } else {
228                         wfOut( "Moving table $from to $to..." );
229                         $wgDatabase->sourceFile( archive($patch) );
230                         wfOut( "ok\n" );
231                 }
232         } else {
233                 // Source table does not exist
234                 // Renames are done before creations, so this is typical for a new installation
235                 // Ignore silently
236         }
239 function add_table( $name, $patch, $fullpath=false ) {
240         global $wgDatabase;
241         if ( $wgDatabase->tableExists( $name ) ) {
242                 wfOut( "...$name table already exists.\n" );
243         } else {
244                 wfOut( "Creating $name table..." );
245                 if( $fullpath ) {
246                         $wgDatabase->sourceFile( $patch );
247                 } else {
248                         $wgDatabase->sourceFile( archive($patch) );
249                 }
250                 wfOut( "ok\n" );
251         }
254 function modify_field($table, $field, $patch, $fullpath=false){
255         global $wgDatabase;
256         if ( !$wgDatabase->tableExists( $table ) ) {
257                 wfOut( "...$table table does not exist, skipping modify field patch\n" );
258         } elseif (! $wgDatabase->fieldExists( $table, $field ) ) {
259                 wfOut( "...$field field does not exist in $table table, skipping modify field patch\n" );
260         } else {
261                 wfOut( "Modifying $field field of table $table..." );
262                 if( $fullpath ) {
263                         $wgDatabase->sourceFile( $patch );
264                 } else {
265                         $wgDatabase->sourceFile( archive($patch) );
266                 }
267                 wfOut( "ok\n" );
268         }
273 function add_field( $table, $field, $patch, $fullpath=false ) {
274         global $wgDatabase;
275         if ( !$wgDatabase->tableExists( $table ) ) {
276                 wfOut( "...$table table does not exist, skipping new field patch\n" );
277         } elseif ( $wgDatabase->fieldExists( $table, $field ) ) {
278                 wfOut( "...have $field field in $table table.\n" );
279         } else {
280                 wfOut( "Adding $field field to table $table..." );
281                 if( $fullpath ) {
282                         $wgDatabase->sourceFile( $patch );
283                 } else {
284                         $wgDatabase->sourceFile( archive($patch) );
285                 }
286                 wfOut( "ok\n" );
287         }
290 function add_index( $table, $index, $patch, $fullpath=false ) {
291         global $wgDatabase;
292         if( $wgDatabase->indexExists( $table, $index ) ) {
293                 wfOut( "...$index key already set on $table table.\n" );
294         } else {
295                 wfOut( "Adding $index key to table $table... " );
296                 if( $fullpath ) {
297                         $wgDatabase->sourceFile( $patch );
298                 } else {
299                         $wgDatabase->sourceFile( archive($patch) );
300                 }
301                 wfOut( "ok\n" );
302         }
305 function do_interwiki_update() {
306         # Check that interwiki table exists; if it doesn't source it
307         global $wgDatabase, $IP;
308         if( $wgDatabase->tableExists( "interwiki" ) ) {
309                 wfOut( "...already have interwiki table\n" );
310                 return true;
311         }
312         wfOut( "Creating interwiki table: " );
313         $wgDatabase->sourceFile( archive("patch-interwiki.sql") );
314         wfOut( "ok\n" );
315         wfOut( "Adding default interwiki definitions: " );
316         $wgDatabase->sourceFile( "$IP/maintenance/interwiki.sql" );
317         wfOut( "ok\n" );
320 function do_index_update() {
321         # Check that proper indexes are in place
322         global $wgDatabase;
323         $meta = $wgDatabase->fieldInfo( "recentchanges", "rc_timestamp" );
324         if( !$meta->isMultipleKey() ) {
325                 wfOut( "Updating indexes to 20031107: " );
326                 $wgDatabase->sourceFile( archive("patch-indexes.sql") );
327                 wfOut( "ok\n" );
328                 return true;
329         }
330         wfOut( "...indexes seem up to 20031107 standards\n" );
331         return false;
334 function do_image_index_update() {
335         global $wgDatabase;
337         $meta = $wgDatabase->fieldInfo( "image", "img_major_mime" );
338         if( !$meta->isMultipleKey() ) {
339                 wfOut( "Updating indexes to 20050912: " );
340                 $wgDatabase->sourceFile( archive("patch-mimesearch-indexes.sql") );
341                 wfOut( "ok\n" );
342                 return true;
343         }
344         wfOut( "...indexes seem up to 20050912 standards\n" );
345         return false;
348 function do_image_name_unique_update() {
349         global $wgDatabase;
350         if( $wgDatabase->indexExists( 'image', 'PRIMARY' ) ) {
351                 wfOut( "...image primary key already set.\n" );
352         } else {
353                 wfOut( "Making img_name the primary key... " );
354                 $wgDatabase->sourceFile( archive("patch-image_name_primary.sql") );
355                 wfOut( "ok\n" );
356         }
359 function do_logging_timestamp_index() {
360         global $wgDatabase;
361         if( $wgDatabase->indexExists( 'logging', 'times' ) ) {
362                 wfOut( "...timestamp key on logging already exists.\n" );
363         } else {
364                 wfOut( "Adding timestamp key on logging table... " );
365                 $wgDatabase->sourceFile( archive("patch-logging-times-index.sql") );
366                 wfOut( "ok\n" );
367         }
370 function do_archive_user_index() {
371         global $wgDatabase;
372         if( $wgDatabase->indexExists( 'archive', 'usertext_timestamp' ) ) {
373                 wfOut( "...usertext,timestamp key on archive already exists.\n" );
374         } else {
375                 wfOut( "Adding usertext,timestamp key on archive table... " );
376                 $wgDatabase->sourceFile( archive("patch-archive-user-index.sql") );
377                 wfOut( "ok\n" );
378         }
381 function do_image_user_index() {
382         global $wgDatabase;
383         if( $wgDatabase->indexExists( 'image', 'img_usertext_timestamp' ) ) {
384                 wfOut( "...usertext,timestamp key on image already exists.\n" );
385         } else {
386                 wfOut( "Adding usertext,timestamp key on image table... " );
387                 $wgDatabase->sourceFile( archive("patch-image-user-index.sql") );
388                 wfOut( "ok\n" );
389         }
392 function do_oldimage_user_index() {
393         global $wgDatabase;
394         if( $wgDatabase->indexExists( 'oldimage', 'oi_usertext_timestamp' ) ) {
395                 wfOut( "...usertext,timestamp key on oldimage already exists.\n" );
396         } else {
397                 wfOut( "Adding usertext,timestamp key on oldimage table... " );
398                 $wgDatabase->sourceFile( archive("patch-oldimage-user-index.sql") );
399                 wfOut( "ok\n" );
400         }
403 function do_watchlist_update() {
404         global $wgDatabase;
405         $fname = 'do_watchlist_update';
406         if( $wgDatabase->fieldExists( 'watchlist', 'wl_notificationtimestamp' ) ) {
407                 wfOut( "The watchlist table is already set up for email notification.\n" );
408         } else {
409                 wfOut( "Adding wl_notificationtimestamp field for email notification management." );
410                 /* ALTER TABLE watchlist ADD (wl_notificationtimestamp varchar(14) binary NOT NULL default '0'); */
411                 $wgDatabase->sourceFile( archive( 'patch-email-notification.sql' ) );
412                 wfOut( "ok\n" );
413         }
414         # Check if we need to add talk page rows to the watchlist
415         $talk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'wl_namespace & 1', $fname );
416         $nontalk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'NOT (wl_namespace & 1)', $fname );
417         if ( $talk != $nontalk ) {
418                 wfOut( "Adding missing watchlist talk page rows... " );
419                 flush();
421                 $wgDatabase->insertSelect( 'watchlist', 'watchlist', 
422                         array(
423                                 'wl_user' => 'wl_user',
424                                 'wl_namespace' => 'wl_namespace | 1',
425                                 'wl_title' => 'wl_title',
426                                 'wl_notificationtimestamp' => 'wl_notificationtimestamp'
427                         ), array( 'NOT (wl_namespace & 1)' ), $fname, 'IGNORE' );
428                 wfOut( "ok\n" );
429         } else {
430                 wfOut( "...watchlist talk page rows already present\n" );
431         }
434 function do_copy_newtalk_to_watchlist() {
435         global $wgDatabase;
436         global $wgCommandLineMode;      # this needs to be saved while getID() and getName() are called
438         $res = $wgDatabase->safeQuery( 'SELECT user_id, user_ip FROM !',
439                 $wgDatabase->tableName( 'user_newtalk' ) );
440         $num_newtalks=$wgDatabase->numRows($res);
441         wfOut( "Now converting $num_newtalks user_newtalk entries to watchlist table entries ... \n" );
443         $user = new User();
444         for ( $i = 1; $i <= $num_newtalks; $i++ ) {
445                 $wluser = $wgDatabase->fetchObject( $res );
446                 if ($wluser->user_id == 0) { # anonymous users ... have IP numbers as "names"
447                         if ($user->isIP($wluser->user_ip)) { # do only if it really looks like an IP number (double checked)
448                                 $wgDatabase->replace( 'watchlist',
449                                         array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
450                                           array('wl_user'                       => 0,
451                                                 'wl_namespace'                  => NS_USER_TALK,
452                                                 'wl_title'                      => $wluser->user_ip,
453                                                 'wl_notificationtimestamp'      => '19700101000000'
454                                                 ), 'updaters.inc::do_watchlist_update2'
455                                         );
456                         }
457                 } else { # normal users ... have user_ids
458                         $user->setID($wluser->user_id);
459                         $wgDatabase->replace( 'watchlist',
460                                 array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
461                                   array('wl_user'                       => $user->getID(),
462                                         'wl_namespace'                  => NS_USER_TALK,
463                                         'wl_title'                      => $user->getName(),
464                                         'wl_notificationtimestamp'      => '19700101000000'
465                                         ), 'updaters.inc::do_watchlist_update3'
466                                 );
467                 }
468         }
469         wfOut( "Done.\n" );
473 function do_user_update() {
474         global $wgDatabase;
475         if( $wgDatabase->fieldExists( 'user', 'user_emailauthenticationtimestamp' ) ) {
476                 wfOut( "User table contains old email authentication field. Dropping... " );
477                 $wgDatabase->sourceFile( archive( 'patch-email-authentication.sql' ) );
478                 wfOut( "ok\n" );
479         } else {
480                 wfOut( "...user table does not contain old email authentication field.\n" );
481         }
485  * 1.4 betas were missing the 'binary' marker from logging.log_title,
486  * which causes a collation mismatch error on joins in MySQL 4.1.
487  */
488 function check_bin( $table, $field, $patchFile ) {
489         global $wgDatabase, $wgDBtype;
490         if ($wgDBtype != 'mysql')
491                 return;
492         $tableName = $wgDatabase->tableName( $table );
493         $res = $wgDatabase->query( "SELECT $field FROM $tableName LIMIT 0" );
494         $flags = explode( ' ', mysql_field_flags( $res->result, 0 ) );
495         $wgDatabase->freeResult( $res );
497         if( in_array( 'binary', $flags ) ) {
498                 wfOut( "$table table has correct $field encoding.\n" );
499         } else {
500                 wfOut( "Fixing $field encoding on $table table... " );
501                 $wgDatabase->sourceFile( archive( $patchFile ) );
502                 wfOut( "ok\n" );
503         }
506 function do_schema_restructuring() {
507         global $wgDatabase;
508         $fname="do_schema_restructuring";
509         if ( $wgDatabase->tableExists( 'page' ) ) {
510                 wfOut( "...page table already exists.\n" );
511         } else {
512                 wfOut( "...converting from cur/old to page/revision/text DB structure.\n" );
513                 wfOut( wfTimestamp( TS_DB ) );
514                 wfOut( "......checking for duplicate entries.\n" );
516                 list ($cur, $old, $page, $revision, $text) = $wgDatabase->tableNamesN( 'cur', 'old', 'page', 'revision', 'text' );
518                 $rows = $wgDatabase->query( "SELECT cur_title, cur_namespace, COUNT(cur_namespace) AS c
519                                 FROM $cur GROUP BY cur_title, cur_namespace HAVING c>1", $fname );
521                 if ( $wgDatabase->numRows( $rows ) > 0 ) {
522                         wfOut( wfTimestamp( TS_DB ) );
523                         wfOut( "......<b>Found duplicate entries</b>\n" );
524                         wfOut( sprintf( "<b>      %-60s %3s %5s</b>\n", 'Title', 'NS', 'Count' ) );
525                         while ( $row = $wgDatabase->fetchObject( $rows ) ) {
526                                 if ( ! isset( $duplicate[$row->cur_namespace] ) ) {
527                                         $duplicate[$row->cur_namespace] = array();
528                                 }
529                                 $duplicate[$row->cur_namespace][] = $row->cur_title;
530                                 wfOut( sprintf( "      %-60s %3s %5s\n", $row->cur_title, $row->cur_namespace, $row->c ) );
531                         }
532                         $sql = "SELECT cur_title, cur_namespace, cur_id, cur_timestamp FROM $cur WHERE ";
533                         $firstCond = true;
534                         foreach ( $duplicate as $ns => $titles ) {
535                                 if ( $firstCond ) {
536                                         $firstCond = false;
537                                 } else {
538                                         $sql .= ' OR ';
539                                 }
540                                 $sql .= "( cur_namespace = {$ns} AND cur_title in (";
541                                 $first = true;
542                                 foreach ( $titles as $t ) {
543                                         if ( $first ) {
544                                                 $sql .= $wgDatabase->addQuotes( $t );
545                                                 $first = false;
546                                         } else {
547                                                 $sql .= ', ' . $wgDatabase->addQuotes( $t );
548                                         }
549                                 }
550                                 $sql .= ") ) \n";
551                         }
552                         # By sorting descending, the most recent entry will be the first in the list.
553                         # All following entries will be deleted by the next while-loop.
554                         $sql .= 'ORDER BY cur_namespace, cur_title, cur_timestamp DESC';
556                         $rows = $wgDatabase->query( $sql, $fname );
558                         $prev_title = $prev_namespace = false;
559                         $deleteId = array();
561                         while ( $row = $wgDatabase->fetchObject( $rows ) ) {
562                                 if ( $prev_title == $row->cur_title && $prev_namespace == $row->cur_namespace ) {
563                                         $deleteId[] = $row->cur_id;
564                                 }
565                                 $prev_title     = $row->cur_title;
566                                 $prev_namespace = $row->cur_namespace;
567                         }
568                         $sql = "DELETE FROM $cur WHERE cur_id IN ( " . join( ',', $deleteId ) . ')';
569                         $rows = $wgDatabase->query( $sql, $fname );
570                         wfOut( wfTimestamp( TS_DB ) );
571                         wfOut( "......<b>Deleted</b> ".$wgDatabase->affectedRows()." records.\n" );
572                 }
575                 wfOut( wfTimestamp( TS_DB ) );
576                 wfOut( "......Creating tables.\n" );
577                 $wgDatabase->query("CREATE TABLE $page (
578                         page_id int(8) unsigned NOT NULL auto_increment,
579                         page_namespace int NOT NULL,
580                         page_title varchar(255) binary NOT NULL,
581                         page_restrictions tinyblob NOT NULL,
582                         page_counter bigint(20) unsigned NOT NULL default '0',
583                         page_is_redirect tinyint(1) unsigned NOT NULL default '0',
584                         page_is_new tinyint(1) unsigned NOT NULL default '0',
585                         page_random real unsigned NOT NULL,
586                         page_touched char(14) binary NOT NULL default '',
587                         page_latest int(8) unsigned NOT NULL,
588                         page_len int(8) unsigned NOT NULL,
590                         PRIMARY KEY page_id (page_id),
591                         UNIQUE INDEX name_title (page_namespace,page_title),
592                         INDEX (page_random),
593                         INDEX (page_len)
594                         ) ENGINE=InnoDB", $fname );
595                 $wgDatabase->query("CREATE TABLE $revision (
596                         rev_id int(8) unsigned NOT NULL auto_increment,
597                         rev_page int(8) unsigned NOT NULL,
598                         rev_comment tinyblob NOT NULL,
599                         rev_user int(5) unsigned NOT NULL default '0',
600                         rev_user_text varchar(255) binary NOT NULL default '',
601                         rev_timestamp char(14) binary NOT NULL default '',
602                         rev_minor_edit tinyint(1) unsigned NOT NULL default '0',
603                         rev_deleted tinyint(1) unsigned NOT NULL default '0',
604                         rev_len int(8) unsigned,
605                         rev_parent_id int(8) unsigned default NULL,
606                         PRIMARY KEY rev_page_id (rev_page, rev_id),
607                         UNIQUE INDEX rev_id (rev_id),
608                         INDEX rev_timestamp (rev_timestamp),
609                         INDEX page_timestamp (rev_page,rev_timestamp),
610                         INDEX user_timestamp (rev_user,rev_timestamp),
611                         INDEX usertext_timestamp (rev_user_text,rev_timestamp)
612                         ) ENGINE=InnoDB", $fname );
614                 wfOut( wfTimestamp( TS_DB ) );
615                 wfOut( "......Locking tables.\n" );
616                 $wgDatabase->query( "LOCK TABLES $page WRITE, $revision WRITE, $old WRITE, $cur WRITE", $fname );
618                 $maxold = intval( $wgDatabase->selectField( 'old', 'max(old_id)', '', $fname ) );
619                 wfOut( wfTimestamp( TS_DB ) );
620                 wfOut( "......maxold is {$maxold}\n" );
622                 wfOut( wfTimestamp( TS_DB ) );
623                 global $wgLegacySchemaConversion;
624                 if( $wgLegacySchemaConversion ) {
625                         // Create HistoryBlobCurStub entries.
626                         // Text will be pulled from the leftover 'cur' table at runtime.
627                         wfOut( "......Moving metadata from cur; using blob references to text in cur table.\n" );
628                         $cur_text = "concat('O:18:\"historyblobcurstub\":1:{s:6:\"mCurId\";i:',cur_id,';}')";
629                         $cur_flags = "'object'";
630                 } else {
631                         // Copy all cur text in immediately: this may take longer but avoids
632                         // having to keep an extra table around.
633                         wfOut( "......Moving text from cur.\n" );
634                         $cur_text = 'cur_text';
635                         $cur_flags = "''";
636                 }
637                 $wgDatabase->query( "INSERT INTO $old (old_namespace, old_title, old_text, old_comment, old_user, old_user_text,
638                                 old_timestamp, old_minor_edit, old_flags)
639                         SELECT cur_namespace, cur_title, $cur_text, cur_comment, cur_user, cur_user_text, cur_timestamp, cur_minor_edit, $cur_flags
640                         FROM $cur", $fname );
642                 wfOut( wfTimestamp( TS_DB ) );
643                 wfOut( "......Setting up revision table.\n" );
644                 $wgDatabase->query( "INSERT INTO $revision (rev_id, rev_page, rev_comment, rev_user, rev_user_text, rev_timestamp,
645                                 rev_minor_edit)
646                         SELECT old_id, cur_id, old_comment, old_user, old_user_text,
647                                 old_timestamp, old_minor_edit
648                         FROM $old,$cur WHERE old_namespace=cur_namespace AND old_title=cur_title", $fname );
650                 wfOut( wfTimestamp( TS_DB ) );
651                 wfOut( "......Setting up page table.\n" );
652                 $wgDatabase->query( "INSERT INTO $page (page_id, page_namespace, page_title, page_restrictions, page_counter,
653                                 page_is_redirect, page_is_new, page_random, page_touched, page_latest, page_len)
654                         SELECT cur_id, cur_namespace, cur_title, cur_restrictions, cur_counter, cur_is_redirect, cur_is_new,
655                                 cur_random, cur_touched, rev_id, LENGTH(cur_text)
656                         FROM $cur,$revision
657                         WHERE cur_id=rev_page AND rev_timestamp=cur_timestamp AND rev_id > {$maxold}", $fname );
659                 wfOut( wfTimestamp( TS_DB ) );
660                 wfOut( "......Unlocking tables.\n" );
661                 $wgDatabase->query( "UNLOCK TABLES", $fname );
663                 wfOut( wfTimestamp( TS_DB ) );
664                 wfOut( "......Renaming old.\n" );
665                 $wgDatabase->query( "ALTER TABLE $old RENAME TO $text", $fname );
667                 wfOut( wfTimestamp( TS_DB ) );
668                 wfOut( "...done.\n" );
669         }
672 function do_inverse_timestamp() {
673         global $wgDatabase;
674         if( $wgDatabase->fieldExists( 'revision', 'inverse_timestamp' ) ) {
675                 wfOut( "Removing revision.inverse_timestamp and fixing indexes... " );
676                 $wgDatabase->sourceFile( archive( 'patch-inverse_timestamp.sql' ) );
677                 wfOut( "ok\n" );
678         } else {
679                 wfOut( "revision timestamp indexes already up to 2005-03-13\n" );
680         }
683 function do_text_id() {
684         global $wgDatabase;
685         if( $wgDatabase->fieldExists( 'revision', 'rev_text_id' ) ) {
686                 wfOut( "...rev_text_id already in place.\n" );
687         } else {
688                 wfOut( "Adding rev_text_id field... " );
689                 $wgDatabase->sourceFile( archive( 'patch-rev_text_id.sql' ) );
690                 wfOut( "ok\n" );
691         }
694 function do_namespace_size() {
695         $tables = array(
696                 'page'          => 'page',
697                 'archive'       => 'ar',
698                 'recentchanges' => 'rc',
699                 'watchlist'     => 'wl',
700                 'querycache'    => 'qc',
701                 'logging'       => 'log',
702         );
703         foreach( $tables as $table => $prefix ) {
704                 do_namespace_size_on( $table, $prefix );
705                 flush();
706         }
709 function do_namespace_size_on( $table, $prefix ) {
710         global $wgDatabase, $wgDBtype;
711         if ($wgDBtype != 'mysql')
712                 return;
713         $field = $prefix . '_namespace';
715         $tablename = $wgDatabase->tableName( $table );
716         $result = $wgDatabase->query( "SHOW COLUMNS FROM $tablename LIKE '$field'" );
717         $info = $wgDatabase->fetchObject( $result );
718         $wgDatabase->freeResult( $result );
720         if( substr( $info->Type, 0, 3 ) == 'int' ) {
721                 wfOut( "...$field is already a full int ($info->Type).\n" );
722         } else {
723                 wfOut( "Promoting $field from $info->Type to int... " );
725                 $sql = "ALTER TABLE $tablename MODIFY $field int NOT NULL";
726                 $wgDatabase->query( $sql );
728                 wfOut( "ok\n" );
729         }
732 function do_pagelinks_update() {
733         global $wgDatabase;
734         if( $wgDatabase->tableExists( 'pagelinks' ) ) {
735                 wfOut( "...already have pagelinks table.\n" );
736         } else {
737                 wfOut( "Converting links and brokenlinks tables to pagelinks... " );
738                 $wgDatabase->sourceFile( archive( 'patch-pagelinks.sql' ) );
739                 wfOut( "ok\n" );
740                 flush();
742                 global $wgCanonicalNamespaceNames;
743                 foreach( $wgCanonicalNamespaceNames as $ns => $name ) {
744                         if( $ns != 0 ) {
745                                 do_pagelinks_namespace( $ns );
746                         }
747                 }
748         }
751 function do_pagelinks_namespace( $namespace ) {
752         global $wgDatabase, $wgContLang;
754         $ns = intval( $namespace );
755         wfOut( "Cleaning up broken links for namespace $ns... " );
757         $pagelinks = $wgDatabase->tableName( 'pagelinks' );
758         $name = $wgContLang->getNsText( $ns );
759         $prefix = $wgDatabase->strencode( $name );
760         $likeprefix = str_replace( '_', '\\_', $prefix);
762         $sql = "UPDATE $pagelinks
763                    SET pl_namespace=$ns,
764                        pl_title=TRIM(LEADING '$prefix:' FROM pl_title)
765                  WHERE pl_namespace=0
766                    AND pl_title LIKE '$likeprefix:%'";
768         $wgDatabase->query( $sql, 'do_pagelinks_namespace' );
769         wfOut( "ok\n" );
772 function do_drop_img_type() {
773         global $wgDatabase;
775         if( $wgDatabase->fieldExists( 'image', 'img_type' ) ) {
776                 wfOut( "Dropping unused img_type field in image table... " );
777                 $wgDatabase->sourceFile( archive( 'patch-drop_img_type.sql' ) );
778                 wfOut( "ok\n" );
779         } else {
780                 wfOut( "No img_type field in image table; Good.\n" );
781         }
784 function do_old_links_update() {
785         global $wgDatabase;
786         if( $wgDatabase->tableExists( 'pagelinks' ) ) {
787                 wfOut( "Already have pagelinks; skipping old links table updates.\n" );
788         } else {
789                 convertLinks(); flush();
790         }
793 function fix_ancient_imagelinks() {
794         global $wgDatabase;
795         $info = $wgDatabase->fieldInfo( 'imagelinks', 'il_from' );
796         if ( $info && $info->type() === 'string' ) {
797                 wfOut( "Fixing ancient broken imagelinks table.\n" );
798                 wfOut( "NOTE: you will have to run maintenance/refreshLinks.php after this.\n" );
799                 $wgDatabase->sourceFile( archive( 'patch-fix-il_from.sql' ) );
800                 wfOut( "ok\n" );
801         } else {
802                 wfOut( "...il_from OK\n" );
803         }
806 function do_user_unique_update() {
807         global $wgDatabase;
808         $duper = new UserDupes( $wgDatabase );
809         if( $duper->hasUniqueIndex() ) {
810                 wfOut( "Already have unique user_name index.\n" );
811         } else {
812                 if( !$duper->clearDupes() ) {
813                         wfOut( "WARNING: This next step will probably fail due to unfixed duplicates...\n" );
814                 }
815                 wfOut( "Adding unique index on user_name... " );
816                 $wgDatabase->sourceFile( archive( 'patch-user_nameindex.sql' ) );
817                 wfOut( "ok\n" );
818         }
821 function do_user_groups_update() {
822         $fname = 'do_user_groups_update';
823         global $wgDatabase;
825         if( $wgDatabase->tableExists( 'user_groups' ) ) {
826                 wfOut( "...user_groups table already exists.\n" );
827                 return do_user_groups_reformat();
828         }
830         wfOut( "Adding user_groups table... " );
831         $wgDatabase->sourceFile( archive( 'patch-user_groups.sql' ) );
832         wfOut( "ok\n" );
834         if( !$wgDatabase->tableExists( 'user_rights' ) ) {
835                 if( $wgDatabase->fieldExists( 'user', 'user_rights' ) ) {
836                         wfOut( "Upgrading from a 1.3 or older database? Breaking out user_rights for conversion..." );
837                         $wgDatabase->sourceFile( archive( 'patch-user_rights.sql' ) );
838                         wfOut( "ok\n" );
839                 } else {
840                         wfOut( "*** WARNING: couldn't locate user_rights table or field for upgrade.\n" );
841                         wfOut( "*** You may need to manually configure some sysops by manipulating\n" );
842                         wfOut( "*** the user_groups table.\n" );
843                         return;
844                 }
845         }
847         wfOut( "Converting user_rights table to user_groups... " );
848         $result = $wgDatabase->select( 'user_rights',
849                 array( 'ur_user', 'ur_rights' ),
850                 array( "ur_rights != ''" ),
851                 $fname );
853         while( $row = $wgDatabase->fetchObject( $result ) ) {
854                 $groups = array_unique(
855                         array_map( 'trim',
856                                 explode( ',', $row->ur_rights ) ) );
858                 foreach( $groups as $group ) {
859                         $wgDatabase->insert( 'user_groups',
860                                 array(
861                                         'ug_user'  => $row->ur_user,
862                                         'ug_group' => $group ),
863                                 $fname );
864                 }
865         }
866         $wgDatabase->freeResult( $result );
867         wfOut( "ok\n" );
870 function do_user_groups_reformat() {
871         # Check for bogus formats from previous 1.5 alpha code.
872         global $wgDatabase;
873         $info = $wgDatabase->fieldInfo( 'user_groups', 'ug_group' );
875         if( $info->type() == 'int' ) {
876                 $oldug = $wgDatabase->tableName( 'user_groups' );
877                 $newug = $wgDatabase->tableName( 'user_groups_bogus' );
878                 wfOut( "user_groups is in bogus intermediate format. Renaming to $newug... " );
879                 $wgDatabase->query( "ALTER TABLE $oldug RENAME TO $newug" );
880                 wfOut( "ok\n" );
882                 wfOut( "Re-adding fresh user_groups table... " );
883                 $wgDatabase->sourceFile( archive( 'patch-user_groups.sql' ) );
884                 wfOut( "ok\n" );
886                 wfOut( "***\n" );
887                 wfOut( "*** WARNING: You will need to manually fix up user permissions in the user_groups\n" );
888                 wfOut( "*** table. Old 1.5 alpha versions did some pretty funky stuff...\n" );
889                 wfOut( "***\n" );
890         } else {
891                 wfOut( "...user_groups is in current format.\n" );
892         }
896 function do_watchlist_null() {
897         # Make sure wl_notificationtimestamp can be NULL,
898         # and update old broken items.
899         global $wgDatabase;
900         $info = $wgDatabase->fieldInfo( 'watchlist', 'wl_notificationtimestamp' );
902         if( !$info->nullable() ) {
903                 wfOut( "Making wl_notificationtimestamp nullable... " );
904                 $wgDatabase->sourceFile( archive( 'patch-watchlist-null.sql' ) );
905                 wfOut( "ok\n" );
906         } else {
907                 wfOut( "...wl_notificationtimestamp is already nullable.\n" );
908         }
913  * @bug 3946
914  */
915 function do_page_random_update() {
916         global $wgDatabase;
918         wfOut( "Setting page_random to a random value on rows where it equals 0..." );
920         $page = $wgDatabase->tableName( 'page' );
921         $wgDatabase->query( "UPDATE $page SET page_random = RAND() WHERE page_random = 0", 'do_page_random_update' );
922         $rows = $wgDatabase->affectedRows();
924         wfOut( "changed $rows rows\n" );
927 function do_templatelinks_update() {
928         global $wgDatabase, $wgLoadBalancer;
929         $fname = 'do_templatelinks_update';
931         if ( $wgDatabase->tableExists( 'templatelinks' ) ) {
932                 wfOut( "...templatelinks table already exists\n" );
933                 return;
934         }
935         wfOut( "Creating templatelinks table...\n" );
936         $wgDatabase->sourceFile( archive('patch-templatelinks.sql') );
937         wfOut( "Populating...\n" );
938         if ( isset( $wgLoadBalancer ) && $wgLoadBalancer->getServerCount() > 1 ) {
939                 // Slow, replication-friendly update
940                 $res = $wgDatabase->select( 'pagelinks', array( 'pl_from', 'pl_namespace', 'pl_title' ),
941                         array( 'pl_namespace' => NS_TEMPLATE ), $fname );
942                 $count = 0;
943                 while ( $row = $wgDatabase->fetchObject( $res ) ) {
944                         $count = ($count + 1) % 100;
945                         if ( $count == 0 ) {
946                                 if ( function_exists( 'wfWaitForSlaves' ) ) {
947                                         wfWaitForSlaves( 10 );
948                                 } else {
949                                         sleep( 1 );
950                                 }
951                         }
952                         $wgDatabase->insert( 'templatelinks',
953                                 array(
954                                         'tl_from' => $row->pl_from,
955                                         'tl_namespace' => $row->pl_namespace,
956                                         'tl_title' => $row->pl_title,
957                                 ), $fname
958                         );
960                 }
961                 $wgDatabase->freeResult( $res );
962         } else {
963                 // Fast update
964                 $wgDatabase->insertSelect( 'templatelinks', 'pagelinks',
965                         array(
966                                 'tl_from' => 'pl_from',
967                                 'tl_namespace' => 'pl_namespace',
968                                 'tl_title' => 'pl_title'
969                         ), array(
970                                 'pl_namespace' => 10
971                         ), $fname
972                 );
973         }
974         wfOut( "Done. Please run maintenance/refreshLinks.php for a more thorough templatelinks update.\n" );
977 // Add index on ( rc_namespace, rc_user_text ) [Jul. 2006]
978 // Add index on ( rc_user_text, rc_timestamp ) [Nov. 2006]
979 function do_rc_indices_update() {
980         global $wgDatabase;
981         wfOut( "Checking for additional recent changes indices...\n" );
983         $indexes = array(
984                 'rc_ns_usertext' => 'patch-recentchanges-utindex.sql',
985                 'rc_user_text' => 'patch-rc_user_text-index.sql',
986         );
987         
988         foreach( $indexes as $index => $patch ) {
989                 $info = $wgDatabase->indexInfo( 'recentchanges', $index, __METHOD__ );
990                 if( !$info ) {
991                         wfOut( "...index `{$index}` not found; adding..." );
992                         $wgDatabase->sourceFile( archive( $patch ) );
993                         wfOut( "done.\n" );
994                 } else {
995                         wfOut( "...index `{$index}` seems ok.\n" );
996                 }
997         }
1000 function index_has_field($table, $index, $field) {
1001         global $wgDatabase;
1002         wfOut( "Checking if $table index $index includes field $field...\n" );
1003         $info = $wgDatabase->indexInfo( $table, $index, __METHOD__ );
1004         if( $info ) {
1005                 foreach($info as $row) {
1006                         if($row->Column_name == $field) {
1007                                 wfOut( "...index $index on table $table seems to be ok\n" );
1008                                 return true;
1009                         }
1010                 }
1011         }
1012         wfOut( "...index $index on table $table has no field $field; adding\n" );
1013         return false;
1016 function do_backlinking_indices_update() {
1017         global $wgDatabase;
1018         wfOut( "Checking for backlinking indices...\n" );
1019         if (!index_has_field('pagelinks', 'pl_namespace', 'pl_from') ||
1020                 !index_has_field('templatelinks', 'tl_namespace', 'tl_from') ||
1021                 !index_has_field('imagelinks', 'il_to', 'il_from'))
1022         {       
1023                 $wgDatabase->sourceFile( archive( 'patch-backlinkindexes.sql' ) );
1024                 wfOut( "...backlinking indices updated\n" );
1025         }
1028 function do_categorylinks_indices_update() {
1029         global $wgDatabase;
1030         wfOut( "Checking for categorylinks indices...\n" );
1031         if (!index_has_field('categorylinks', 'cl_sortkey', 'cl_from'))
1032         {       
1033                 $wgDatabase->sourceFile( archive( 'patch-categorylinksindex.sql' ) );
1034                 wfOut( "...categorylinks indices updated\n" );
1035         }
1038 function do_filearchive_indices_update() {
1039         global $wgDatabase;
1040         wfOut( "Checking filearchive indices...\n" );
1041         $info = $wgDatabase->indexInfo( 'filearchive', 'fa_user_timestamp', __METHOD__ );
1042         if ( !$info )
1043         {       
1044                 $wgDatabase->sourceFile( archive( 'patch-filearchive-user-index.sql' ) );
1045                 wfOut( "...filearchive indices updated\n" );
1046         }
1049 function maybe_do_profiling_memory_update() {
1050         global $wgDatabase;
1051         if ( !$wgDatabase->tableExists( 'profiling' ) ) {
1052                 // Simply ignore
1053         } elseif ( $wgDatabase->fieldExists( 'profiling', 'pf_memory' ) ) {
1054                 wfOut( "profiling table has pf_memory field.\n" );
1055         } else {
1056                 wfOut( "Adding pf_memory field to table profiling..." );
1057                 $wgDatabase->sourceFile( archive( 'patch-profiling-memory.sql' ) );
1058                 wfOut( "ok\n" );
1059         }
1062 function do_stats_init() {
1063         // Sometimes site_stats table is not properly populated.
1064         global $wgDatabase;
1065         wfOut( "Checking site_stats row..." );
1066         $row = $wgDatabase->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
1067         if( $row === false ) {
1068                 wfOut( "data is missing! rebuilding...\n" );
1069         } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
1070                 wfOut( "missing ss_total_pages, rebuilding...\n" );
1071         } else {
1072                 wfOut( "ok.\n" );
1073                 return;
1074         }
1075         SiteStatsInit::doAllAndCommit( false );
1078 function do_active_users_init() {
1079         global $wgDatabase;
1080         $activeUsers = $wgDatabase->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
1081         if( $activeUsers == -1 ) {
1082                 $activeUsers = $wgDatabase->selectField( 'recentchanges', 
1083                         'COUNT( DISTINCT rc_user_text )',
1084                         array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__ 
1085                 );
1086                 $wgDatabase->update( 'site_stats', 
1087                         array( 'ss_active_users' => intval($activeUsers) ),
1088                         array( 'ss_row_id' => 1 ), __METHOD__, array( 'LIMIT' => 1 )
1089                 );
1090         }
1091         wfOut( "...ss_active_users user count set...\n" );
1094 function purge_cache() {
1095         global $wgDatabase;
1096         # We can't guarantee that the user will be able to use TRUNCATE,
1097         # but we know that DELETE is available to us
1098         wfOut( "Purging caches..." );
1099         $wgDatabase->delete( 'objectcache', '*', __METHOD__ );
1100         wfOut( "done.\n" );
1103 function do_all_updates( $shared = false, $purge = true ) {
1104         global $wgNewTables, $wgExtModifiedFields, $wgNewFields, $wgRenamedTables, $wgSharedDB, $wgSharedTables, $wgDatabase, $wgDBtype, $IP;
1106         wfRunHooks('LoadExtensionSchemaUpdates');
1108         $doUser = $shared ? $wgSharedDB && in_array('user', $wgSharedTables) : !$wgSharedDB || !in_array('user', $wgSharedTables);
1110         if ($wgDBtype === 'postgres') {
1111                 do_postgres_updates();
1112                 return;
1113         }
1114         
1115         # Run core updates in sequence...
1116         global $wgUpdates;
1117         if ( isset( $wgUpdates[$wgDBtype] ) ) {
1118                 foreach( $wgUpdates[$wgDBtype] as $params ) {
1119                         $func = array_shift( $params );
1120                         call_user_func_array( $func, $params );
1121                         flush();
1122                 }
1123         }
1124         
1125         /// @fixme clean up this mess too!
1126         global $wgExtNewTables, $wgExtNewFields, $wgExtNewIndexes;
1127         # Add missing extension tables
1128         foreach ( $wgExtNewTables as $tableRecord ) {
1129                 add_table( $tableRecord[0], $tableRecord[1], true );
1130                 flush();
1131         }
1132         # Add missing extension fields
1133         foreach ( $wgExtNewFields as $fieldRecord ) {
1134                 if ( $fieldRecord[0] != 'user' || $doUser ) {
1135                         add_field( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true );
1136                 }
1137                 flush();
1138         }
1139         # Add missing extension indexes
1140         foreach ( $wgExtNewIndexes as $fieldRecord ) {
1141                 add_index( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true );
1142                 flush();
1143         }
1144         # Add modified extension fields
1145         foreach ( $wgExtModifiedFields as $fieldRecord ) {
1146                 modify_field($fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true);
1147                 flush();
1148         }
1151         wfOut( "Deleting old default messages (this may take a long time!)..." ); 
1152         if( !defined( 'MW_NO_SETUP' ) ) {
1153                 define( 'MW_NO_SETUP', true );
1154         }
1155         require_once 'deleteDefaultMessages.php';
1156         DeleteDefaultMessages::reallyExecute();
1157         wfOut( "Done\n" );
1158         
1159         do_stats_init();
1160         
1161         if( $purge ) {
1162                 purge_cache();
1163         }
1166 function archive($name) {
1167         global $wgDBtype, $IP;
1168         if ( file_exists( "$IP/maintenance/$wgDBtype/archives/$name" ) ) {
1169                 return "$IP/maintenance/$wgDBtype/archives/$name";
1170         } else {
1171                 return "$IP/maintenance/archives/$name";
1172         }
1175 function do_restrictions_update() {
1176         # Adding page_restrictions table, obsoleting page.page_restrictions.
1177         #  Migrating old restrictions to new table
1178         # -- Andrew Garrett, January 2007.
1180         global $wgDatabase;
1182         $name = 'page_restrictions';
1183         $patch = 'patch-page_restrictions.sql';
1184         $patch2 = 'patch-page_restrictions_sortkey.sql';
1186         if ( $wgDatabase->tableExists( $name ) ) {
1187                 wfOut( "...$name table already exists.\n" );
1188         } else {
1189                 wfOut( "Creating $name table..." );
1190                 $wgDatabase->sourceFile( archive($patch) );
1191                 $wgDatabase->sourceFile( archive($patch2) );
1192                 wfOut( "ok\n" );
1194                 wfOut( "Migrating old restrictions to new table..." );
1196                 $res = $wgDatabase->select( 'page', array( 'page_id', 'page_restrictions' ), array("page_restrictions!=''", "page_restrictions!='edit=:move='"), __METHOD__ );
1198                 $count = 0;
1200                 while ($row = $wgDatabase->fetchObject($res) ) {
1201                         $count = ($count + 1) % 100;
1203                         if ($count == 0) {
1204                                 if ( function_exists( 'wfWaitForSlaves' ) ) {
1205                                         wfWaitForSlaves( 10 );
1206                                 } else {
1207                                         sleep( 1 );
1208                                 }
1209                         }
1211                         # Figure out what the restrictions are..
1212                         $id = $row->page_id;
1213                         $flatrestrictions = explode( ':', $row->page_restrictions );
1215                         $restrictions = array ();
1216                         foreach( $flatrestrictions as $restriction ) {
1217                                 $thisrestriction = explode( '=', $restriction, 2 );
1218                                 if( count( $thisrestriction ) == 1 ) {
1219                                         // Compatibility with old protections from before
1220                                         // separate move protection was added.
1221                                         list( $level ) = $thisrestriction;
1222                                         if( $level ) {
1223                                                 $restrictions['edit'] = $level;
1224                                                 $restrictions['move'] = $level;
1225                                         }
1226                                 } else {
1227                                         list( $type, $level ) = $thisrestriction;
1228                                         if( $level ) {
1229                                                 $restrictions[$type] = $level;
1230                                         }
1231                                 }
1233                         $wgDatabase->update( 'page', array ( 'page_restrictions' => ''), array( 'page_id' => $id ), __METHOD__ );
1235                         }
1236                         
1237                         foreach( $restrictions as $type => $level ) {
1238                                 $wgDatabase->insert( 'page_restrictions', array ( 'pr_page' => $id,
1239                                                                                         'pr_type' => $type,
1240                                                                                         'pr_level' => $level,
1241                                                                                         'pr_cascade' => 0,
1242                                                                                         'pr_expiry' => 'infinity' ),
1243                                                                                         __METHOD__ );
1244                         }
1245                 }
1246                 wfOut( "ok\n" );
1247         }
1250 function do_category_population() {
1251         if( update_row_exists( 'populate category' ) ) {
1252                 wfOut( "...category table already populated.\n" );
1253                 return;
1254         }
1255         require_once( 'populateCategory.inc' );
1256         wfOut( "Populating category table, printing progress markers.  " ).
1257 "For large databases, you\n".
1258 "may want to hit Ctrl-C and do this manually with maintenance/\n".
1259 "populateCategory.php.\n";
1260         populateCategory( '', 10, 0, true );
1261         wfOut( "Done populating category table.\n" );
1264 function do_populate_parent_id() {
1265         if( update_row_exists( 'populate rev_parent_id' ) ) {
1266                 wfOut( "...rev_parent_id column already populated.\n" );
1267                 return;
1268         }
1269         require_once( 'populateParentId.inc' );
1270         
1271         global $wgDatabase;
1272         populate_rev_parent_id( $wgDatabase );
1275 function sqlite_initial_indexes() {
1276         global $wgDatabase;
1277         // initial-indexes.sql fails if the indexes are already present, so we perform a quick check if our database is newer.
1278         if ( update_row_exists( 'initial_indexes' ) || $wgDatabase->indexExists( 'user', 'user_name' ) ) {
1279                 wfOut( "...have initial indexes\n" );
1280                 return;
1281         }
1282         wfOut( "Adding initial indexes..." );
1283         $wgDatabase->sourceFile( archive( 'initial-indexes.sql' ) );
1284         wfOut( "done\n" );
1287 function sqlite_setup_searchindex() {
1288         global $wgDatabase;
1289         $module = $wgDatabase->getFulltextSearchModule();
1290         $fts3tTable = update_row_exists( 'fts3' );
1291         if ( $fts3tTable &&  !$module ) {
1292                 wfOut( '...PHP is missing FTS3 support, downgrading tables...' );
1293                 $wgDatabase->sourceFile( archive( 'searchindex-no-fts.sql' ) );
1294                 wfOut( "done\n" );
1295         } elseif ( !$fts3tTable && $module == 'FTS3' ) {
1296                 wfOut( '...adding FTS3 search capabilities...' );
1297                 $wgDatabase->sourceFile( archive( 'searchindex-fts3.sql' ) );
1298                 wfOut( "done\n" );
1299         } else {
1300                 wfOut( "...fulltext search table appears to be in order.\n" );
1301         }
1304 function do_unique_pl_tl_il() {
1305         global $wgDatabase;
1306         $info = $wgDatabase->indexInfo( 'pagelinks', 'pl_namespace' );
1307         if( is_array($info) && !$info[0]->Non_unique ) {
1308                 wfOut( "...pl_namespace, tl_namespace, il_to indices are already UNIQUE.\n" );
1309         } else {
1310                 wfOut( "Making pl_namespace, tl_namespace and il_to indices UNIQUE... " );
1311                 $wgDatabase->sourceFile( archive( 'patch-pl-tl-il-unique.sql' ) );
1312                 wfOut( "ok\n" );
1313         }
1316 function do_log_search_population() {
1317         global $wgDatabase;
1318         if( update_row_exists( 'populate log_search' ) ) {
1319                 wfOut( "...log_search table already populated.\n" );
1320                 return;
1321         }
1322         require_once( 'populateLogSearch.inc' );
1323         wfOut(
1324 "Populating log_search table, printing progress markers. For large\n" .
1325 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1326 "maintenance/populateLogSearch.php.\n" );
1327         migrate_log_params( $wgDatabase );
1328         wfOut( "Done populating log_search table.\n" );
1331 /***********************************************************************
1332  * Start PG stuff
1333  * TODO: merge with above
1334  ***********************************************************************/
1336 function pg_describe_table($table) {
1337         global  $wgDatabase, $wgDBmwschema;
1338         $q = <<<END
1339 SELECT attname, attnum FROM pg_namespace, pg_class, pg_attribute
1340         WHERE pg_class.relnamespace = pg_namespace.oid 
1341           AND attrelid=pg_class.oid AND attnum > 0
1342           AND relname=%s AND nspname=%s
1343 END;
1344         $res = $wgDatabase->query(sprintf($q,
1345                         $wgDatabase->addQuotes($table),
1346                         $wgDatabase->addQuotes($wgDBmwschema)));
1347         if (!$res)
1348                 return null;
1350         $cols = array();
1351         while ($r = $wgDatabase->fetchRow($res)) {
1352                 $cols[] = array(        
1353                                 "name" => $r[0],
1354                                 "ord" => $r[1],
1355                         );
1356         }
1357         return $cols;
1360 function pg_describe_index($idx) {
1361         global  $wgDatabase, $wgDBmwschema;
1363         // first fetch the key (which is a list of columns ords) and
1364         // the table the index applies to (an oid)
1365         $q = <<<END
1366 SELECT indkey, indrelid FROM pg_namespace, pg_class, pg_index
1367         WHERE nspname=%s
1368           AND pg_class.relnamespace = pg_namespace.oid
1369           AND relname=%s
1370           AND indexrelid=pg_class.oid
1371 END;
1372         $res = $wgDatabase->query(sprintf($q,
1373                         $wgDatabase->addQuotes($wgDBmwschema),
1374                         $wgDatabase->addQuotes($idx)));
1375         if (!$res)
1376                 return null;
1377         if (!($r = $wgDatabase->fetchRow($res))) {
1378                 $wgDatabase->freeResult($res);
1379                 return null;
1380         }
1382         $indkey = $r[0];
1383         $relid = intval($r[1]);
1384         $indkeys = explode(" ", $indkey);
1385         $wgDatabase->freeResult($res);
1387         $colnames = array();
1388         foreach ($indkeys as $rid) {
1389                 $query = <<<END
1390 SELECT attname FROM pg_class, pg_attribute
1391         WHERE attrelid=$relid
1392           AND attnum=%d
1393           AND attrelid=pg_class.oid
1394 END;
1395                 $r2 = $wgDatabase->query(sprintf($query, $rid));
1396                 if (!$r2)
1397                         return null;
1398                 if (!($row2 = $wgDatabase->fetchRow($r2))) {
1399                         $wgDatabase->freeResult($r2);
1400                         return null;
1401                 }
1402                 $colnames[] = $row2[0];
1403                 $wgDatabase->freeResult($r2);
1404         }
1406         return $colnames;
1409 function pg_index_exists($table, $index) {
1410         global  $wgDatabase, $wgDBmwschema;
1411         $exists = $wgDatabase->selectField("pg_indexes", "indexname",
1412                         array(  "indexname" => $index,
1413                                 "tablename" => $table,
1414                                 "schemaname" => $wgDBmwschema));
1415         return $exists === $index;
1418 function pg_fkey_deltype($fkey) {
1419         global  $wgDatabase, $wgDBmwschema;
1420         $q = <<<END
1421 SELECT confdeltype FROM pg_constraint, pg_namespace
1422         WHERE connamespace=pg_namespace.oid
1423           AND nspname=%s
1424           AND conname=%s;
1425 END;
1426         $r = $wgDatabase->query(sprintf($q,
1427                 $wgDatabase->addQuotes($wgDBmwschema),
1428                 $wgDatabase->addQuotes($fkey)));
1429         if (!($row = $wgDatabase->fetchRow($r)))
1430                 return null;
1431         return $row[0];
1434 function pg_rule_def($table, $rule) {
1435         global  $wgDatabase, $wgDBmwschema;
1436         $q = <<<END
1437 SELECT definition FROM pg_rules
1438         WHERE schemaname = %s
1439           AND tablename = %s
1440           AND rulename = %s
1441 END;
1442         $r = $wgDatabase->query(sprintf($q,
1443                         $wgDatabase->addQuotes($wgDBmwschema),
1444                         $wgDatabase->addQuotes($table),
1445                         $wgDatabase->addQuotes($rule)));
1446         $row = $wgDatabase->fetchRow($r);
1447         if (!$row)
1448                 return null;
1449         $d = $row[0];
1450         $wgDatabase->freeResult($r);
1451         return $d;
1454 function do_postgres_updates() {
1455         global $wgDatabase, $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgShowExceptionDetails, $wgDBuser;
1457         ## Gather version numbers in case we need them
1458         $version = $wgDatabase->getServerVersion(); ## long string
1459         $numver = $wgDatabase->numeric_version; ## X.Y e.g. 8.3
1461         $wgShowExceptionDetails = 1;
1463         # Just in case their LocalSettings.php does not have this:
1464         if ( !isset( $wgDBmwschema ))
1465                 $wgDBmwschema = 'mediawiki';
1467         # Verify that this user is configured correctly
1468         $safeuser = $wgDatabase->addQuotes($wgDBuser);
1469         $SQL = "SELECT array_to_string(useconfig,'*') FROM pg_catalog.pg_user WHERE usename = $safeuser";
1470         $config = pg_fetch_result( $wgDatabase->doQuery( $SQL ), 0, 0 );
1471         $conf = array();
1472         foreach( explode( '*', $config ) as $c ) {
1473                 list( $x,$y ) = explode( '=', $c );
1474                 $conf[$x] = $y;
1475         }
1476         if( !array_key_exists( 'search_path', $conf ) ) {
1477                 $search_path = '';
1478         }
1479         else {
1480                 $search_path = $conf['search_path'];
1481         }
1482         if( strpos( $search_path, $wgDBmwschema ) === false ) {
1483                 wfOut( "Adding in schema \"$wgDBmwschema\" to search_path for user \"$wgDBuser\"\n" );
1484                 $search_path = "$wgDBmwschema, $search_path";
1485         }
1486         if( strpos( $search_path, $wgDBts2schema ) === false ) {
1487                 wfOut( "Adding in schema \"$wgDBts2schema\" to search_path for user \"$wgDBuser\"\n" );
1488                 $search_path = "$search_path, $wgDBts2schema";
1489         }
1490         $search_path = str_replace( ', ,', ',', $search_path);
1491         if( array_key_exists( 'search_path', $conf ) === false || $search_path != $conf['search_path'] ) {
1492                 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET search_path = $search_path" );
1493                 $wgDatabase->doQuery( "SET search_path = $search_path" );
1494         }
1495         else {
1496                 $path = $conf['search_path'];
1497                 wfOut( "... search_path for user \"$wgDBuser\" looks correct ($path)\n" );
1498         }
1499         $goodconf = array(
1500                 'client_min_messages' => 'error',
1501                 'DateStyle'           => 'ISO, YMD',
1502                 'TimeZone'            => 'GMT'
1503         );
1504         foreach( array_keys( $goodconf ) AS $key ) {
1505                 $value = $goodconf[$key];
1506                 if( !array_key_exists( $key, $conf ) or $conf[$key] !== $value ) {
1507                         wfOut( "Setting $key to '$value' for user \"$wgDBuser\"\n" );
1508                         $wgDatabase->doQuery( "ALTER USER $wgDBuser SET $key = '$value'" );
1509                         $wgDatabase->doQuery( "SET $key = '$value'" );
1510                 }
1511                 else {
1512                         wfOut( "... default value of \"$key\" is correctly set to \"$value\" for user \"$wgDBuser\"\n" );
1513                 }
1514         }
1516         $newsequences = array(
1517                 "logging_log_id_seq",
1518                 "page_restrictions_pr_id_seq",
1519         );
1521         $newtables = array(
1522                 array("category",          "patch-category.sql"),
1523                 array("mediawiki_version", "patch-mediawiki_version.sql"),
1524                 array("mwuser",            "patch-mwuser.sql"),
1525                 array("pagecontent",       "patch-pagecontent.sql"),
1526                 array("querycachetwo",     "patch-querycachetwo.sql"),
1527                 array("page_props",        "patch-page_props.sql"),
1528                 array("page_restrictions", "patch-page_restrictions.sql"),
1529                 array("profiling",         "patch-profiling.sql"),
1530                 array("protected_titles",  "patch-protected_titles.sql"),
1531                 array("redirect",          "patch-redirect.sql"),
1532                 array("updatelog",         "patch-updatelog.sql"),
1533                 array('change_tag',        'patch-change_tag.sql'),
1534                 array('tag_summary',       'patch-change_tag.sql'),
1535                 array('valid_tag',         'patch-change_tag.sql'),
1536                 array('user_properties',   'patch-user_properties.sql'),
1537                 array('log_search',        'patch-log_search.sql'),
1538                 array('l10n_cache',        'patch-l10n_cache.sql'),
1539         );
1541         $newcols = array(
1542                 array("archive",       "ar_deleted",           "SMALLINT NOT NULL DEFAULT 0"),
1543                 array("archive",       "ar_len",               "INTEGER"),
1544                 array("archive",       "ar_page_id",           "INTEGER"),
1545                 array("archive",       "ar_parent_id",         "INTEGER"),
1546                 array("image",         "img_sha1",             "TEXT NOT NULL DEFAULT ''"),
1547                 array("ipblocks",      "ipb_allow_usertalk",   "SMALLINT NOT NULL DEFAULT 0"),
1548                 array("ipblocks",      "ipb_anon_only",        "SMALLINT NOT NULL DEFAULT 0"),
1549                 array("ipblocks",      "ipb_by_text",          "TEXT NOT NULL DEFAULT ''"),
1550                 array("ipblocks",      "ipb_block_email",      "SMALLINT NOT NULL DEFAULT 0"),
1551                 array("ipblocks",      "ipb_create_account",   "SMALLINT NOT NULL DEFAULT 1"),
1552                 array("ipblocks",      "ipb_deleted",          "SMALLINT NOT NULL DEFAULT 0"),
1553                 array("ipblocks",      "ipb_enable_autoblock", "SMALLINT NOT NULL DEFAULT 1"),
1554                 array("filearchive",   "fa_deleted",           "SMALLINT NOT NULL DEFAULT 0"),
1555                 array("logging",       "log_deleted",          "SMALLINT NOT NULL DEFAULT 0"),
1556                 array("logging",       "log_id",               "INTEGER NOT NULL PRIMARY KEY DEFAULT nextval('logging_log_id_seq')"),
1557                 array("logging",       "log_params",           "TEXT"),
1558                 array("mwuser",        "user_editcount",       "INTEGER"),
1559                 array("mwuser",        "user_hidden",          "SMALLINT NOT NULL DEFAULT 0"),
1560                 array("mwuser",        "user_newpass_time",    "TIMESTAMPTZ"),
1561                 array("oldimage",      "oi_deleted",           "SMALLINT NOT NULL DEFAULT 0"),
1562                 array("oldimage",      "oi_major_mime",        "TEXT NOT NULL DEFAULT 'unknown'"),
1563                 array("oldimage",      "oi_media_type",        "TEXT"),
1564                 array("oldimage",      "oi_metadata",          "BYTEA NOT NULL DEFAULT ''"),
1565                 array("oldimage",      "oi_minor_mime",        "TEXT NOT NULL DEFAULT 'unknown'"),
1566                 array("oldimage",      "oi_sha1",              "TEXT NOT NULL DEFAULT ''"),
1567                 array("page_restrictions", "pr_id",            "INTEGER NOT NULL UNIQUE DEFAULT nextval('page_restrictions_pr_id_val')"),
1568                 array("profiling",     "pf_memory",            "NUMERIC(18,10) NOT NULL DEFAULT 0"),
1569                 array("recentchanges", "rc_deleted",           "SMALLINT NOT NULL DEFAULT 0"),
1570                 array("recentchanges", "rc_log_action",        "TEXT"),
1571         array("recentchanges", "rc_log_type",          "TEXT"),
1572         array("recentchanges", "rc_logid",             "INTEGER NOT NULL DEFAULT 0"),
1573                 array("recentchanges", "rc_new_len",           "INTEGER"),
1574                 array("recentchanges", "rc_old_len",           "INTEGER"),
1575                 array("recentchanges", "rc_params",            "TEXT"),
1576                 array("redirect",      "rd_interwiki",         "TEXT NULL"),
1577                 array("redirect",      "rd_fragment",          "TEXT NULL"),
1578                 array("revision",      "rev_deleted",          "SMALLINT NOT NULL DEFAULT 0"),
1579                 array("revision",      "rev_len",              "INTEGER"),
1580                 array("revision",      "rev_parent_id",        "INTEGER DEFAULT NULL"),
1581                 array("site_stats",    "ss_active_users",      "INTEGER DEFAULT '-1'"),
1582                 array("user_newtalk",  "user_last_timestamp",  "TIMESTAMPTZ"),
1583                 array("logging",       "log_user_text",        "TEXT NOT NULL DEFAULT ''"),
1584                 array("logging",       "log_page",             "INTEGER"),
1585         );
1588         # table, column, desired type, USING clause if needed (with new default if needed)
1589         $typechanges = array(
1590                 array("archive",      "ar_deleted",      "smallint", ""),
1591                 array("archive",      "ar_minor_edit",   "smallint", "ar_minor_edit::smallint DEFAULT 0"),
1592                 array("filearchive",  "fa_deleted",      "smallint", ""),
1593                 array("filearchive",  "fa_height",       "integer",  ""),
1594                 array("filearchive",  "fa_metadata",     "bytea",    "decode(fa_metadata,'escape')"),
1595                 array("filearchive",  "fa_size",         "integer",  ""),
1596                 array("filearchive",  "fa_width",        "integer",  ""),
1597                 array("filearchive",  "fa_storage_group","text",     ""),
1598                 array("filearchive",  "fa_storage_key",  "text",     ""),
1599                 array("image",        "img_metadata",    "bytea",    "decode(img_metadata,'escape')"),
1600                 array("image",        "img_size",        "integer",  ""),
1601                 array("image",        "img_width",       "integer",  ""),
1602                 array("image",        "img_height",      "integer",  ""),
1603                 array("interwiki",    "iw_local",        "smallint", "iw_local::smallint DEFAULT 0"),
1604                 array("interwiki",    "iw_trans",        "smallint", "iw_trans::smallint DEFAULT 0"),
1605                 array("ipblocks",     "ipb_auto",        "smallint", "ipb_auto::smallint DEFAULT 0"),
1606                 array("ipblocks",     "ipb_anon_only",   "smallint", "CASE WHEN ipb_anon_only=' ' THEN 0 ELSE ipb_anon_only::smallint END DEFAULT 0"),
1607                 array("ipblocks",     "ipb_create_account", "smallint", "CASE WHEN ipb_create_account=' ' THEN 0 ELSE ipb_create_account::smallint END DEFAULT 1"),
1608                 array("ipblocks",     "ipb_enable_autoblock", "smallint", "CASE WHEN ipb_enable_autoblock=' ' THEN 0 ELSE ipb_enable_autoblock::smallint END DEFAULT 1"),
1609                 array("ipblocks",     "ipb_block_email", "smallint", "CASE WHEN ipb_block_email=' ' THEN 0 ELSE ipb_block_email::smallint END DEFAULT 0"),
1610                 array("ipblocks",     "ipb_address",     "text",     "ipb_address::text"),
1611                 array("ipblocks",     "ipb_deleted",     "smallint", "ipb_deleted::smallint DEFAULT 0"),
1612                 array("math",         "math_inputhash",  "bytea",    "decode(math_inputhash,'escape')"),
1613                 array("math",         "math_outputhash", "bytea",    "decode(math_outputhash,'escape')"),
1614                 array("mwuser",       "user_token",      "text",     ""),
1615                 array("mwuser",       "user_email_token","text",     ""),
1616                 array("objectcache",  "keyname",         "text",     ""),
1617                 array("oldimage",     "oi_height",       "integer",  ""),
1618                 array("oldimage",     "oi_metadata",     "bytea",    "decode(img_metadata,'escape')"),
1619                 array("oldimage",     "oi_size",         "integer",  ""),
1620                 array("oldimage",     "oi_width",        "integer",  ""),
1621                 array("page",         "page_is_redirect","smallint", "page_is_redirect::smallint DEFAULT 0"),
1622                 array("page",         "page_is_new",     "smallint", "page_is_new::smallint DEFAULT 0"),
1623                 array("querycache",   "qc_value",        "integer",  ""),
1624                 array("querycachetwo","qcc_value",       "integer",  ""),
1625                 array("recentchanges","rc_bot",          "smallint", "rc_bot::smallint DEFAULT 0"),
1626                 array("recentchanges","rc_deleted",      "smallint", ""),
1627                 array("recentchanges","rc_minor",        "smallint", "rc_minor::smallint DEFAULT 0"),
1628                 array("recentchanges","rc_new",          "smallint", "rc_new::smallint DEFAULT 0"),
1629                 array("recentchanges","rc_type",         "smallint", "rc_type::smallint DEFAULT 0"),
1630                 array("recentchanges","rc_patrolled",    "smallint", "rc_patrolled::smallint DEFAULT 0"),
1631                 array("revision",     "rev_deleted",     "smallint", "rev_deleted::smallint DEFAULT 0"),
1632                 array("revision",     "rev_minor_edit",  "smallint", "rev_minor_edit::smallint DEFAULT 0"),
1633                 array("templatelinks","tl_namespace",    "smallint", "tl_namespace::smallint"),
1634                 array("user_newtalk", "user_ip",         "text",     "host(user_ip)"),
1635         );
1637         # table, column, nullability
1638         $nullchanges = array(
1639                 array("oldimage", "oi_bits",       "NULL"),
1640                 array("oldimage", "oi_timestamp",  "NULL"),
1641                 array("oldimage", "oi_major_mime", "NULL"),
1642                 array("oldimage", "oi_minor_mime", "NULL"),
1643         );
1645         $newindexes = array(
1646                 array("archive",       "archive_user_text",  "(ar_user_text)"),
1647                 array("image",         "img_sha1",           "(img_sha1)"),
1648                 array("oldimage",      "oi_sha1",            "(oi_sha1)"),
1649                 array("revision",      "rev_text_id_idx",    "(rev_text_id)"),
1650                 array("recentchanges", "rc_timestamp_bot",   "(rc_timestamp) WHERE rc_bot = 0"),
1651                 array("templatelinks", "templatelinks_from", "(tl_from)"),
1652                 array("watchlist",     "wl_user",            "(wl_user)"),
1653                 array("logging",       "logging_user_type_time", "(log_user, log_type, log_timestamp)"),
1654                 array("logging",       "logging_page_id_time",   "(log_page,log_timestamp)"),
1655         );
1657         $newrules = array(
1658         );
1660         #Check new sequences, rename if needed
1661         foreach ($newsequences as $ns) {
1662                 if( $wgDatabase->sequenceExists('pr_id_val') ) {
1663                         wfOut( "Updating sequence names\n" );
1664                         $wgDatabase->sourceFile(archive('patch-update_sequences.sql'));
1665                         continue;
1666                 } elseif ( $wgDatabase->sequenceExists('page_restrictions_pr_id_seq') ) {
1667                         wfOut( "... sequences already updated\n" );
1668                         continue;
1669                 } else {
1670                         wfOut( "Creating sequence \"$ns\"\n" );
1671                         $wgDatabase->query("CREATE SEQUENCE $ns");
1672                 }
1673         }
1675         foreach ($newtables as $nt) {
1676                 if ($wgDatabase->tableExists($nt[0])) {
1677                         wfOut( "... table \"$nt[0]\" already exists\n" );
1678                         continue;
1679                 }
1681                 wfOut( "Creating table \"$nt[0]\"\n" );
1682                 $wgDatabase->sourceFile(archive($nt[1]));
1683         }
1685         ## Needed before newcols
1686         if ($wgDatabase->tableExists("archive2")) {
1687                 wfOut( "Converting \"archive2\" back to normal archive table\n" );
1688                 if ($wgDatabase->ruleExists("archive", "archive_insert")) {
1689                         wfOut( "Dropping rule \"archive_insert\"\n" );
1690                         $wgDatabase->query("DROP RULE archive_insert ON archive");
1691                 }
1692                 if ($wgDatabase->ruleExists("archive", "archive_delete")) {
1693                         wfOut( "Dropping rule \"archive_delete\"\n" );
1694                         $wgDatabase->query("DROP RULE archive_delete ON archive");
1695                 }
1696                 $wgDatabase->sourceFile(archive("patch-remove-archive2.sql"));
1697         }
1698         else
1699                 wfOut( "... obsolete table \"archive2\" does not exist\n" );
1701         foreach ($newcols as $nc) {
1702                 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1703                 if (!is_null($fi)) {
1704                         wfOut( "... column \"$nc[0].$nc[1]\" already exists\n" );
1705                         continue;
1706                 }
1708                 wfOut( "Adding column \"$nc[0].$nc[1]\"\n" );
1709                 $wgDatabase->query("ALTER TABLE $nc[0] ADD $nc[1] $nc[2]");
1710         }
1712         foreach ($typechanges as $tc) {
1713                 $fi = $wgDatabase->fieldInfo($tc[0], $tc[1]);
1714                 if (is_null($fi)) {
1715                         wfOut( "... error: expected column $tc[0].$tc[1] to exist\n" );
1716                         exit(1);
1717                 }
1719                 if ($fi->type() === $tc[2])
1720                         wfOut( "... column \"$tc[0].$tc[1]\" is already of type \"$tc[2]\"\n" );
1721                 else {
1722                         wfOut( "Changing column type of \"$tc[0].$tc[1]\" from \"{$fi->type()}\" to \"$tc[2]\"\n" );
1723                         $sql = "ALTER TABLE $tc[0] ALTER $tc[1] TYPE $tc[2]";
1724                         if (strlen($tc[3])) {
1725                                 $default = array();
1726                                 if (preg_match( '/DEFAULT (.+)/', $tc[3], $default)) {
1727                                         $sqldef = "ALTER TABLE $tc[0] ALTER $tc[1] SET DEFAULT $default[1]";
1728                                         $wgDatabase->query($sqldef);
1729                                         $tc[3] = preg_replace( '/\s*DEFAULT .+/', '', $tc[3]);
1730                                 }
1731                                 $sql .= " USING $tc[3]";
1732                         }
1733                         $sql .= ";\nCOMMIT;\n";
1734                         $wgDatabase->query($sql);
1735                 }
1736         }
1738         foreach ($nullchanges as $nc) {
1739                 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1740                 if (is_null($fi)) {
1741                         wfOut( "... error: expected column $nc[0].$nc[1] to exist\n" );
1742                         exit(1);
1743                 }
1744                 if ($fi->nullable()) {
1745                         ## It's NULL - does it need to be NOT NULL?
1746                         if ('NOT NULL' === $nc[2]) {
1747                                 wfOut( "Changing \"$nc[0].$nc[1]\" to not allow NULLs\n" );
1748                                 $wgDatabase->query( "ALTER TABLE $nc[0] ALTER $nc[1] SET NOT NULL" );
1749                         }
1750                         else {
1751                                 wfOut( "... column \"$nc[0].$nc[1]\" is already set as NULL\n" );
1752                         }
1753                 }
1754                 else {
1755                         ## It's NOT NULL - does it need to be NULL?
1756                         if ('NULL' === $nc[2]) {
1757                                 wfOut( "Changing \"$nc[0].$nc[1]\" to allow NULLs\n" );
1758                                 $wgDatabase->query( "ALTER TABLE $nc[0] ALTER $nc[1] DROP NOT NULL" );
1759                         }
1760                         else {
1761                                 wfOut( "... column \"$nc[0].$nc[1]\" is already set as NOT NULL\n" );
1762                         }
1763                 }
1764         }
1766         if ($wgDatabase->fieldInfo('oldimage','oi_deleted')->type() !== 'smallint') {
1767                 wfOut( "Changing \"oldimage.oi_deleted\" to type \"smallint\"\n" );
1768                 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted DROP DEFAULT" );
1769                 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted TYPE SMALLINT USING (oi_deleted::smallint)" );
1770                 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted SET DEFAULT 0" );
1771         }
1772         else
1773                 wfOut( "... column \"oldimage.oi_deleted\" is already of type \"smallint\"\n" );
1776         foreach ($newindexes as $ni) {
1777                 if (pg_index_exists($ni[0], $ni[1])) {
1778                         wfOut( "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n" );
1779                         continue;
1780                 }
1781                 wfOut( "Creating index \"$ni[1]\" on table \"$ni[0]\" $ni[2]\n" );
1782                 $wgDatabase->query( "CREATE INDEX $ni[1] ON $ni[0] $ni[2]" );
1783         }
1785         foreach ($newrules as $nr) {
1786                 if ($wgDatabase->ruleExists($nr[0], $nr[1])) {
1787                         wfOut( "... rule \"$nr[1]\" on table \"$nr[0]\" already exists\n" );
1788                         continue;
1789                 }
1790                 wfOut( "Adding rule \"$nr[1]\" to table \"$nr[0]\"\n" );
1791                 $wgDatabase->sourceFile(archive($nr[2]));
1792         }
1794         if ($wgDatabase->hasConstraint("oldimage_oi_name_fkey_cascaded")) {
1795                 wfOut( "... table \"oldimage\" has correct cascading delete/update foreign key to image\n" );
1796         }
1797         else {
1798                 if ($wgDatabase->hasConstraint("oldimage_oi_name_fkey")) {
1799                         $wgDatabase->query( "ALTER TABLE oldimage DROP CONSTRAINT oldimage_oi_name_fkey" );
1800                 }
1801                 if ($wgDatabase->hasConstraint("oldimage_oi_name_fkey_cascade")) {
1802                         $wgDatabase->query( "ALTER TABLE oldimage DROP CONSTRAINT oldimage_oi_name_fkey_cascade" );
1803                 }
1804                 wfOut( "Making foreign key on table \"oldimage\" (to image) a cascade delete/update\n" );
1805                 $wgDatabase->query( "ALTER TABLE oldimage ADD CONSTRAINT oldimage_oi_name_fkey_cascaded ".
1806                         "FOREIGN KEY (oi_name) REFERENCES image(img_name) ON DELETE CASCADE ON UPDATE CASCADE" );
1807         }
1809         if (!$wgDatabase->triggerExists("page", "page_deleted")) {
1810                 wfOut( "Adding function and trigger \"page_deleted\" to table \"page\"\n" );
1811                 $wgDatabase->sourceFile(archive('patch-page_deleted.sql'));
1812         }
1813         else
1814                 wfOut( "... table \"page\" has \"page_deleted\" trigger\n" );
1816         $fi = $wgDatabase->fieldInfo("recentchanges", "rc_cur_id");
1817         if (!$fi->nullable()) {
1818                 wfOut( "Removing NOT NULL constraint from \"recentchanges.rc_cur_id\"\n" );
1819                 $wgDatabase->sourceFile(archive('patch-rc_cur_id-not-null.sql'));
1820         }
1821         else
1822                 wfOut( "... column \"recentchanges.rc_cur_id\" has a NOT NULL constraint\n" );
1824         $pu = pg_describe_index("pagelink_unique");
1825         if (!is_null($pu) && ($pu[0] != "pl_from" || $pu[1] != "pl_namespace" || $pu[2] != "pl_title")) {
1826                 wfOut( "Dropping obsolete version of index \"pagelink_unique index\"\n" );
1827                 $wgDatabase->query("DROP INDEX pagelink_unique");
1828                 $pu = null;
1829         }
1830         else
1831                 wfOut( "... obsolete version of index \"pagelink_unique index\" does not exist\n" );
1833         if (is_null($pu)) {
1834                 wfOut( "Creating index \"pagelink_unique index\"\n" );
1835                 $wgDatabase->query("CREATE UNIQUE INDEX pagelink_unique ON pagelinks (pl_from,pl_namespace,pl_title)");
1836         }
1837         else
1838                 wfOut( "... index \"pagelink_unique_index\" already exists\n" );
1840         if (pg_fkey_deltype("revision_rev_user_fkey") == 'r') {
1841                 wfOut( "... constraint \"revision_rev_user_fkey\" is ON DELETE RESTRICT\n" );
1842         }
1843         else {
1844                 wfOut( "Changing constraint \"revision_rev_user_fkey\" to ON DELETE RESTRICT\n" );
1845                 $wgDatabase->sourceFile(archive('patch-revision_rev_user_fkey.sql'));
1846         }
1848         # Fix ipb_address index
1849         if (pg_index_exists('ipblocks', 'ipb_address' )) {
1850                 wfOut( "Removing deprecated index 'ipb_address'...\n" );
1851                 $wgDatabase->query('DROP INDEX ipb_address');
1852         }
1853         if (pg_index_exists('ipblocks', 'ipb_address_unique' )) {
1854                 wfOut( "... have ipb_address_unique\n" );
1855         }
1856         else {
1857                 wfOut( "Adding ipb_address_unique index\n" );
1858                 $wgDatabase->sourceFile(archive('patch-ipb_address_unique.sql'));
1859         }
1861         global $wgExtNewTables, $wgExtPGNewFields, $wgExtPGAlteredFields, $wgExtNewIndexes;
1862         # Add missing extension tables
1863         foreach ( $wgExtNewTables as $nt ) {
1864                 if ($wgDatabase->tableExists($nt[0])) {
1865                         wfOut( "... table \"$nt[0]\" already exists\n" );
1866                         continue;
1867                 }
1868                 wfOut( "Creating table \"$nt[0]\"\n" );
1869                 $wgDatabase->sourceFile($nt[1]);
1870         }
1871         # Add missing extension fields
1872         foreach ( $wgExtPGNewFields as $nc ) {
1873                 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1874                 if (!is_null($fi)) {
1875                         wfOut( "... column \"$nc[0].$nc[1]\" already exists\n" );
1876                         continue;
1877                 }
1878                 wfOut( "Adding column \"$nc[0].$nc[1]\"\n" );
1879                 $wgDatabase->query( "ALTER TABLE $nc[0] ADD $nc[1] $nc[2]" );
1880         }
1881         # Change altered columns
1882         foreach ( $wgExtPGAlteredFields as $nc ) {
1883                 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1884                 if (is_null($fi)) {
1885                         wfOut( "WARNING! Column \"$nc[0].$nc[1]\" does not exist but had an alter request! Please report this.\n" );
1886                         continue;
1887                 }
1888                 $oldtype = $fi->type();
1889                 $newtype = strtolower( $nc[2] );
1890                 if ($oldtype === $newtype) {
1891                         wfOut( "... column \"$nc[0].$nc[1]\" has correct type of \"$newtype\"\n" );
1892                         continue;
1893                 }
1894                 $command = "ALTER TABLE $nc[0] ALTER $nc[1] TYPE $nc[2]";
1895                 if ( isset( $nc[3] ) ) {
1896                         $command .= " USING $nc[3]";
1897                 }
1898                 wfOut( "Altering column \"$nc[0].$nc[1]\" from type \"$oldtype\" to \"$newtype\"\n" );
1899                 $wgDatabase->query( $command );
1900         }
1901         # Add missing extension indexes
1902         foreach ( $wgExtNewIndexes as $ni ) {
1903                 if (pg_index_exists($ni[0], $ni[1])) {
1904                         wfOut( "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n" );
1905                         continue;
1906                 }
1907                 wfOut( "Creating index \"$ni[1]\" on table \"$ni[0]\"\n" );
1908                 if ( preg_match( '/^\(/', $ni[2] ) ) {
1909                         $wgDatabase->query( "CREATE INDEX $ni[1] ON $ni[0] $ni[2]" );
1910                 }
1911                 else {
1912                         $wgDatabase->sourceFile($ni[2]);
1913                 }
1914         }
1916         # Tweak the page_title tsearch2 trigger to filter out slashes
1917         # This is create or replace, so harmless to call if not needed
1918         $wgDatabase->sourceFile(archive('patch-ts2pagetitle.sql'));
1920         ## If the server is 8.3 or higher, rewrite the tsearch2 triggers
1921         ## in case they have the old 'default' versions
1922         if ( $numver >= 8.3 )
1923                 $wgDatabase->sourceFile(archive('patch-tsearch2funcs.sql'));
1925         ## Put a new row in the mediawiki_version table
1926         $wgDatabase->insert( 'mediawiki_version',
1927                 array(
1928                         'type' => 'Update',
1929                         'ctype' => 'U',
1930                         'mw_version' => $wgVersion,
1931                         'pg_version' => $version,
1932                         'sql_version' => '$LastChangedRevision$',
1933                         'sql_date' => '$LastChangedDate$',
1934                 ) );
1935         return;