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