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