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