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