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