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