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