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