Remove unused initial_setup(), last $wgDBts2schema user. Follow up to r81132
[lhc/web/wiklou.git] / includes / db / DatabasePostgres.php
1 <?php
2 /**
3 * This is the Postgres database abstraction layer.
4 *
5 * @file
6 * @ingroup Database
7 */
8
9 class PostgresField implements Field {
10 private $name, $tablename, $type, $nullable, $max_length, $deferred, $deferrable, $conname;
11
12 static function fromText($db, $table, $field) {
13 global $wgDBmwschema;
14
15 $q = <<<SQL
16 SELECT
17 attnotnull, attlen, COALESCE(conname, '') AS conname,
18 COALESCE(condeferred, 'f') AS deferred,
19 COALESCE(condeferrable, 'f') AS deferrable,
20 CASE WHEN typname = 'int2' THEN 'smallint'
21 WHEN typname = 'int4' THEN 'integer'
22 WHEN typname = 'int8' THEN 'bigint'
23 WHEN typname = 'bpchar' THEN 'char'
24 ELSE typname END AS typname
25 FROM pg_class c
26 JOIN pg_namespace n ON (n.oid = c.relnamespace)
27 JOIN pg_attribute a ON (a.attrelid = c.oid)
28 JOIN pg_type t ON (t.oid = a.atttypid)
29 LEFT JOIN pg_constraint o ON (o.conrelid = c.oid AND a.attnum = ANY(o.conkey) AND o.contype = 'f')
30 WHERE relkind = 'r'
31 AND nspname=%s
32 AND relname=%s
33 AND attname=%s;
34 SQL;
35
36 $table = $db->tableName( $table );
37 $res = $db->query(
38 sprintf( $q,
39 $db->addQuotes( $wgDBmwschema ),
40 $db->addQuotes( $table ),
41 $db->addQuotes( $field )
42 )
43 );
44 $row = $db->fetchObject( $res );
45 if ( !$row ) {
46 return null;
47 }
48 $n = new PostgresField;
49 $n->type = $row->typname;
50 $n->nullable = ( $row->attnotnull == 'f' );
51 $n->name = $field;
52 $n->tablename = $table;
53 $n->max_length = $row->attlen;
54 $n->deferrable = ( $row->deferrable == 't' );
55 $n->deferred = ( $row->deferred == 't' );
56 $n->conname = $row->conname;
57 return $n;
58 }
59
60 function name() {
61 return $this->name;
62 }
63
64 function tableName() {
65 return $this->tablename;
66 }
67
68 function type() {
69 return $this->type;
70 }
71
72 function isNullable() {
73 return $this->nullable;
74 }
75
76 function maxLength() {
77 return $this->max_length;
78 }
79
80 function is_deferrable() {
81 return $this->deferrable;
82 }
83
84 function is_deferred() {
85 return $this->deferred;
86 }
87
88 function conname() {
89 return $this->conname;
90 }
91
92 }
93
94 /**
95 * @ingroup Database
96 */
97 class DatabasePostgres extends DatabaseBase {
98 var $mInsertId = null;
99 var $mLastResult = null;
100 var $numeric_version = null;
101 var $mAffectedRows = null;
102
103 function getType() {
104 return 'postgres';
105 }
106
107 function cascadingDeletes() {
108 return true;
109 }
110 function cleanupTriggers() {
111 return true;
112 }
113 function strictIPs() {
114 return true;
115 }
116 function realTimestamps() {
117 return true;
118 }
119 function implicitGroupby() {
120 return false;
121 }
122 function implicitOrderby() {
123 return false;
124 }
125 function searchableIPs() {
126 return true;
127 }
128 function functionalIndexes() {
129 return true;
130 }
131
132 function hasConstraint( $name ) {
133 global $wgDBmwschema;
134 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" .
135 pg_escape_string( $this->mConn, $name ) . "' AND n.nspname = '" . pg_escape_string( $this->mConn, $wgDBmwschema ) ."'";
136 $res = $this->doQuery( $SQL );
137 return $this->numRows( $res );
138 }
139
140 /**
141 * Usually aborts on failure
142 */
143 function open( $server, $user, $password, $dbName ) {
144 # Test for Postgres support, to avoid suppressed fatal error
145 if ( !function_exists( 'pg_connect' ) ) {
146 throw new DBConnectionError( $this, "Postgres functions missing, have you compiled PHP with the --with-pgsql option?\n (Note: if you recently installed PHP, you may need to restart your webserver and database)\n" );
147 }
148
149 global $wgDBport;
150
151 if ( !strlen( $user ) ) { # e.g. the class is being loaded
152 return;
153 }
154
155 $this->close();
156 $this->mServer = $server;
157 $this->mPort = $port = $wgDBport;
158 $this->mUser = $user;
159 $this->mPassword = $password;
160 $this->mDBname = $dbName;
161
162 $connectVars = array(
163 'dbname' => $dbName,
164 'user' => $user,
165 'password' => $password
166 );
167 if ( $server != false && $server != '' ) {
168 $connectVars['host'] = $server;
169 }
170 if ( $port != false && $port != '' ) {
171 $connectVars['port'] = $port;
172 }
173 $connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW );
174
175 $this->installErrorHandler();
176 $this->mConn = pg_connect( $connectString );
177 $phpError = $this->restoreErrorHandler();
178
179 if ( !$this->mConn ) {
180 wfDebug( "DB connection error\n" );
181 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
182 wfDebug( $this->lastError() . "\n" );
183 throw new DBConnectionError( $this, $phpError );
184 }
185
186 $this->mOpened = true;
187
188 global $wgCommandLineMode;
189 # If called from the command-line (e.g. importDump), only show errors
190 if ( $wgCommandLineMode ) {
191 $this->doQuery( "SET client_min_messages = 'ERROR'" );
192 }
193
194 $this->doQuery( "SET client_encoding='UTF8'" );
195
196 global $wgDBmwschema;
197 if ( isset( $wgDBmwschema )
198 && preg_match( '/^\w+$/', $wgDBmwschema )
199 ) {
200 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
201 $this->doQuery( "SET search_path = $safeschema, public" );
202 }
203
204 return $this->mConn;
205 }
206
207 function makeConnectionString( $vars ) {
208 $s = '';
209 foreach ( $vars as $name => $value ) {
210 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
211 }
212 return $s;
213 }
214
215 /**
216 * Closes a database connection, if it is open
217 * Returns success, true if already closed
218 */
219 function close() {
220 $this->mOpened = false;
221 if ( $this->mConn ) {
222 return pg_close( $this->mConn );
223 } else {
224 return true;
225 }
226 }
227
228 function doQuery( $sql ) {
229 if ( function_exists( 'mb_convert_encoding' ) ) {
230 $sql = mb_convert_encoding( $sql, 'UTF-8' );
231 }
232 $this->mLastResult = pg_query( $this->mConn, $sql );
233 $this->mAffectedRows = null; // use pg_affected_rows(mLastResult)
234 return $this->mLastResult;
235 }
236
237 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
238 return $this->query( $sql, $fname, true );
239 }
240
241 function freeResult( $res ) {
242 if ( $res instanceof ResultWrapper ) {
243 $res = $res->result;
244 }
245 if ( !@pg_free_result( $res ) ) {
246 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
247 }
248 }
249
250 function fetchObject( $res ) {
251 if ( $res instanceof ResultWrapper ) {
252 $res = $res->result;
253 }
254 @$row = pg_fetch_object( $res );
255 # FIXME: HACK HACK HACK HACK debug
256
257 # TODO:
258 # hashar : not sure if the following test really trigger if the object
259 # fetching failed.
260 if( pg_last_error( $this->mConn ) ) {
261 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
262 }
263 return $row;
264 }
265
266 function fetchRow( $res ) {
267 if ( $res instanceof ResultWrapper ) {
268 $res = $res->result;
269 }
270 @$row = pg_fetch_array( $res );
271 if( pg_last_error( $this->mConn ) ) {
272 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
273 }
274 return $row;
275 }
276
277 function numRows( $res ) {
278 if ( $res instanceof ResultWrapper ) {
279 $res = $res->result;
280 }
281 @$n = pg_num_rows( $res );
282 if( pg_last_error( $this->mConn ) ) {
283 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
284 }
285 return $n;
286 }
287
288 function numFields( $res ) {
289 if ( $res instanceof ResultWrapper ) {
290 $res = $res->result;
291 }
292 return pg_num_fields( $res );
293 }
294
295 function fieldName( $res, $n ) {
296 if ( $res instanceof ResultWrapper ) {
297 $res = $res->result;
298 }
299 return pg_field_name( $res, $n );
300 }
301
302 /**
303 * This must be called after nextSequenceVal
304 */
305 function insertId() {
306 return $this->mInsertId;
307 }
308
309 function dataSeek( $res, $row ) {
310 if ( $res instanceof ResultWrapper ) {
311 $res = $res->result;
312 }
313 return pg_result_seek( $res, $row );
314 }
315
316 function lastError() {
317 if ( $this->mConn ) {
318 return pg_last_error();
319 } else {
320 return 'No database connection';
321 }
322 }
323 function lastErrno() {
324 return pg_last_error() ? 1 : 0;
325 }
326
327 function affectedRows() {
328 if ( !is_null( $this->mAffectedRows ) ) {
329 // Forced result for simulated queries
330 return $this->mAffectedRows;
331 }
332 if( empty( $this->mLastResult ) ) {
333 return 0;
334 }
335 return pg_affected_rows( $this->mLastResult );
336 }
337
338 /**
339 * Estimate rows in dataset
340 * Returns estimated count, based on EXPLAIN output
341 * This is not necessarily an accurate estimate, so use sparingly
342 * Returns -1 if count cannot be found
343 * Takes same arguments as Database::select()
344 */
345 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
346 $options['EXPLAIN'] = true;
347 $res = $this->select( $table, $vars, $conds, $fname, $options );
348 $rows = -1;
349 if ( $res ) {
350 $row = $this->fetchRow( $res );
351 $count = array();
352 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
353 $rows = $count[1];
354 }
355 }
356 return $rows;
357 }
358
359 /**
360 * Returns information about an index
361 * If errors are explicitly ignored, returns NULL on failure
362 */
363 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
364 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
365 $res = $this->query( $sql, $fname );
366 if ( !$res ) {
367 return null;
368 }
369 foreach ( $res as $row ) {
370 if ( $row->indexname == $this->indexName( $index ) ) {
371 return $row;
372 }
373 }
374 return false;
375 }
376
377 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
378 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
379 " AND indexdef LIKE 'CREATE UNIQUE%(" .
380 $this->strencode( $this->indexName( $index ) ) .
381 ")'";
382 $res = $this->query( $sql, $fname );
383 if ( !$res ) {
384 return null;
385 }
386 foreach ( $res as $row ) {
387 return true;
388 }
389 return false;
390 }
391
392 /**
393 * INSERT wrapper, inserts an array into a table
394 *
395 * $args may be a single associative array, or an array of these with numeric keys,
396 * for multi-row insert (Postgres version 8.2 and above only).
397 *
398 * @param $table String: Name of the table to insert to.
399 * @param $args Array: Items to insert into the table.
400 * @param $fname String: Name of the function, for profiling
401 * @param $options String or Array. Valid options: IGNORE
402 *
403 * @return bool Success of insert operation. IGNORE always returns true.
404 */
405 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
406 if ( !count( $args ) ) {
407 return true;
408 }
409
410 $table = $this->tableName( $table );
411 if (! isset( $this->numeric_version ) ) {
412 $this->getServerVersion();
413 }
414
415 if ( !is_array( $options ) ) {
416 $options = array( $options );
417 }
418
419 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
420 $multi = true;
421 $keys = array_keys( $args[0] );
422 } else {
423 $multi = false;
424 $keys = array_keys( $args );
425 }
426
427 // If IGNORE is set, we use savepoints to emulate mysql's behavior
428 $ignore = in_array( 'IGNORE', $options ) ? 'mw' : '';
429
430 // If we are not in a transaction, we need to be for savepoint trickery
431 $didbegin = 0;
432 if ( $ignore ) {
433 if ( !$this->mTrxLevel ) {
434 $this->begin();
435 $didbegin = 1;
436 }
437 $olde = error_reporting( 0 );
438 // For future use, we may want to track the number of actual inserts
439 // Right now, insert (all writes) simply return true/false
440 $numrowsinserted = 0;
441 }
442
443 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
444
445 if ( $multi ) {
446 if ( $this->numeric_version >= 8.2 && !$ignore ) {
447 $first = true;
448 foreach ( $args as $row ) {
449 if ( $first ) {
450 $first = false;
451 } else {
452 $sql .= ',';
453 }
454 $sql .= '(' . $this->makeList( $row ) . ')';
455 }
456 $res = (bool)$this->query( $sql, $fname, $ignore );
457 } else {
458 $res = true;
459 $origsql = $sql;
460 foreach ( $args as $row ) {
461 $tempsql = $origsql;
462 $tempsql .= '(' . $this->makeList( $row ) . ')';
463
464 if ( $ignore ) {
465 pg_query( $this->mConn, "SAVEPOINT $ignore" );
466 }
467
468 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
469
470 if ( $ignore ) {
471 $bar = pg_last_error();
472 if ( $bar != false ) {
473 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
474 } else {
475 pg_query( $this->mConn, "RELEASE $ignore" );
476 $numrowsinserted++;
477 }
478 }
479
480 // If any of them fail, we fail overall for this function call
481 // Note that this will be ignored if IGNORE is set
482 if ( !$tempres ) {
483 $res = false;
484 }
485 }
486 }
487 } else {
488 // Not multi, just a lone insert
489 if ( $ignore ) {
490 pg_query($this->mConn, "SAVEPOINT $ignore");
491 }
492
493 $sql .= '(' . $this->makeList( $args ) . ')';
494 $res = (bool)$this->query( $sql, $fname, $ignore );
495 if ( $ignore ) {
496 $bar = pg_last_error();
497 if ( $bar != false ) {
498 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
499 } else {
500 pg_query( $this->mConn, "RELEASE $ignore" );
501 $numrowsinserted++;
502 }
503 }
504 }
505 if ( $ignore ) {
506 $olde = error_reporting( $olde );
507 if ( $didbegin ) {
508 $this->commit();
509 }
510
511 // Set the affected row count for the whole operation
512 $this->mAffectedRows = $numrowsinserted;
513
514 // IGNORE always returns true
515 return true;
516 }
517
518 return $res;
519 }
520
521 /**
522 * INSERT SELECT wrapper
523 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
524 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
525 * $conds may be "*" to copy the whole table
526 * srcTable may be an array of tables.
527 * @todo FIXME: implement this a little better (seperate select/insert)?
528 */
529 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
530 $insertOptions = array(), $selectOptions = array() )
531 {
532 $destTable = $this->tableName( $destTable );
533
534 // If IGNORE is set, we use savepoints to emulate mysql's behavior
535 $ignore = in_array( 'IGNORE', $insertOptions ) ? 'mw' : '';
536
537 if( is_array( $insertOptions ) ) {
538 $insertOptions = implode( ' ', $insertOptions );
539 }
540 if( !is_array( $selectOptions ) ) {
541 $selectOptions = array( $selectOptions );
542 }
543 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
544 if( is_array( $srcTable ) ) {
545 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
546 } else {
547 $srcTable = $this->tableName( $srcTable );
548 }
549
550 // If we are not in a transaction, we need to be for savepoint trickery
551 $didbegin = 0;
552 if ( $ignore ) {
553 if( !$this->mTrxLevel ) {
554 $this->begin();
555 $didbegin = 1;
556 }
557 $olde = error_reporting( 0 );
558 $numrowsinserted = 0;
559 pg_query( $this->mConn, "SAVEPOINT $ignore");
560 }
561
562 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
563 " SELECT $startOpts " . implode( ',', $varMap ) .
564 " FROM $srcTable $useIndex";
565
566 if ( $conds != '*' ) {
567 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
568 }
569
570 $sql .= " $tailOpts";
571
572 $res = (bool)$this->query( $sql, $fname, $ignore );
573 if( $ignore ) {
574 $bar = pg_last_error();
575 if( $bar != false ) {
576 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
577 } else {
578 pg_query( $this->mConn, "RELEASE $ignore" );
579 $numrowsinserted++;
580 }
581 $olde = error_reporting( $olde );
582 if( $didbegin ) {
583 $this->commit();
584 }
585
586 // Set the affected row count for the whole operation
587 $this->mAffectedRows = $numrowsinserted;
588
589 // IGNORE always returns true
590 return true;
591 }
592
593 return $res;
594 }
595
596 function tableName( $name ) {
597 # Replace reserved words with better ones
598 switch( $name ) {
599 case 'user':
600 return 'mwuser';
601 case 'text':
602 return 'pagecontent';
603 default:
604 return $name;
605 }
606 }
607
608 /**
609 * Return the next in a sequence, save the value for retrieval via insertId()
610 */
611 function nextSequenceValue( $seqName ) {
612 $safeseq = str_replace( "'", "''", $seqName );
613 $res = $this->query( "SELECT nextval('$safeseq')" );
614 $row = $this->fetchRow( $res );
615 $this->mInsertId = $row[0];
616 return $this->mInsertId;
617 }
618
619 /**
620 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
621 */
622 function currentSequenceValue( $seqName ) {
623 $safeseq = str_replace( "'", "''", $seqName );
624 $res = $this->query( "SELECT currval('$safeseq')" );
625 $row = $this->fetchRow( $res );
626 $currval = $row[0];
627 return $currval;
628 }
629
630 /**
631 * REPLACE query wrapper
632 * Postgres simulates this with a DELETE followed by INSERT
633 * $row is the row to insert, an associative array
634 * $uniqueIndexes is an array of indexes. Each element may be either a
635 * field name or an array of field names
636 *
637 * It may be more efficient to leave off unique indexes which are unlikely to collide.
638 * However if you do this, you run the risk of encountering errors which wouldn't have
639 * occurred in MySQL
640 */
641 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
642 $table = $this->tableName( $table );
643
644 if ( count( $rows ) == 0 ) {
645 return;
646 }
647
648 # Single row case
649 if ( !is_array( reset( $rows ) ) ) {
650 $rows = array( $rows );
651 }
652
653 foreach( $rows as $row ) {
654 # Delete rows which collide
655 if ( $uniqueIndexes ) {
656 $sql = "DELETE FROM $table WHERE ";
657 $first = true;
658 foreach ( $uniqueIndexes as $index ) {
659 if ( $first ) {
660 $first = false;
661 $sql .= '(';
662 } else {
663 $sql .= ') OR (';
664 }
665 if ( is_array( $index ) ) {
666 $first2 = true;
667 foreach ( $index as $col ) {
668 if ( $first2 ) {
669 $first2 = false;
670 } else {
671 $sql .= ' AND ';
672 }
673 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
674 }
675 } else {
676 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
677 }
678 }
679 $sql .= ')';
680 $this->query( $sql, $fname );
681 }
682
683 # Now insert the row
684 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
685 $this->makeList( $row, LIST_COMMA ) . ')';
686 $this->query( $sql, $fname );
687 }
688 }
689
690 # DELETE where the condition is a join
691 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
692 if ( !$conds ) {
693 throw new DBUnexpectedError( $this, 'DatabasePostgres::deleteJoin() called with empty $conds' );
694 }
695
696 $delTable = $this->tableName( $delTable );
697 $joinTable = $this->tableName( $joinTable );
698 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
699 if ( $conds != '*' ) {
700 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
701 }
702 $sql .= ')';
703
704 $this->query( $sql, $fname );
705 }
706
707 # Returns the size of a text field, or -1 for "unlimited"
708 function textFieldSize( $table, $field ) {
709 $table = $this->tableName( $table );
710 $sql = "SELECT t.typname as ftype,a.atttypmod as size
711 FROM pg_class c, pg_attribute a, pg_type t
712 WHERE relname='$table' AND a.attrelid=c.oid AND
713 a.atttypid=t.oid and a.attname='$field'";
714 $res =$this->query( $sql );
715 $row = $this->fetchObject( $res );
716 if ( $row->ftype == 'varchar' ) {
717 $size = $row->size - 4;
718 } else {
719 $size = $row->size;
720 }
721 return $size;
722 }
723
724 function limitResult( $sql, $limit, $offset = false ) {
725 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
726 }
727
728 function wasDeadlock() {
729 return $this->lastErrno() == '40P01';
730 }
731
732 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
733 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
734 }
735
736 function timestamp( $ts = 0 ) {
737 return wfTimestamp( TS_POSTGRES, $ts );
738 }
739
740 /**
741 * Return aggregated value function call
742 */
743 function aggregateValue( $valuedata, $valuename = 'value' ) {
744 return $valuedata;
745 }
746
747 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
748 // Ignore errors during error handling to avoid infinite recursion
749 $ignore = $this->ignoreErrors( true );
750 $this->mErrorCount++;
751
752 if ( $ignore || $tempIgnore ) {
753 wfDebug( "SQL ERROR (ignored): $error\n" );
754 $this->ignoreErrors( $ignore );
755 } else {
756 $message = "A database error has occurred. Did you forget to run maintenance/update.php after upgrading? See: http://www.mediawiki.org/wiki/Manual:Upgrading#Run_the_update_script\n" .
757 "Query: $sql\n" .
758 "Function: $fname\n" .
759 "Error: $errno $error\n";
760 throw new DBUnexpectedError( $this, $message );
761 }
762 }
763
764 /**
765 * @return string wikitext of a link to the server software's web site
766 */
767 public static function getSoftwareLink() {
768 return '[http://www.postgresql.org/ PostgreSQL]';
769 }
770
771 /**
772 * @return string Version information from the database
773 */
774 function getServerVersion() {
775 if ( !isset( $this->numeric_version ) ) {
776 $versionInfo = pg_version( $this->mConn );
777 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
778 // Old client, abort install
779 $this->numeric_version = '7.3 or earlier';
780 } elseif ( isset( $versionInfo['server'] ) ) {
781 // Normal client
782 $this->numeric_version = $versionInfo['server'];
783 } else {
784 // Bug 16937: broken pgsql extension from PHP<5.3
785 $this->numeric_version = pg_parameter_status( $this->mConn, 'server_version' );
786 }
787 }
788 return $this->numeric_version;
789 }
790
791 /**
792 * Query whether a given relation exists (in the given schema, or the
793 * default mw one if not given)
794 */
795 function relationExists( $table, $types, $schema = false ) {
796 global $wgDBmwschema;
797 if ( !is_array( $types ) ) {
798 $types = array( $types );
799 }
800 if ( !$schema ) {
801 $schema = $wgDBmwschema;
802 }
803 $table = $this->tableName( $table );
804 $etable = $this->addQuotes( $table );
805 $eschema = $this->addQuotes( $schema );
806 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
807 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
808 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
809 $res = $this->query( $SQL );
810 $count = $res ? $res->numRows() : 0;
811 return (bool)$count;
812 }
813
814 /**
815 * For backward compatibility, this function checks both tables and
816 * views.
817 */
818 function tableExists( $table, $schema = false ) {
819 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
820 }
821
822 function sequenceExists( $sequence, $schema = false ) {
823 return $this->relationExists( $sequence, 'S', $schema );
824 }
825
826 function triggerExists( $table, $trigger ) {
827 global $wgDBmwschema;
828
829 $q = <<<SQL
830 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
831 WHERE relnamespace=pg_namespace.oid AND relkind='r'
832 AND tgrelid=pg_class.oid
833 AND nspname=%s AND relname=%s AND tgname=%s
834 SQL;
835 $res = $this->query(
836 sprintf(
837 $q,
838 $this->addQuotes( $wgDBmwschema ),
839 $this->addQuotes( $table ),
840 $this->addQuotes( $trigger )
841 )
842 );
843 if ( !$res ) {
844 return null;
845 }
846 $rows = $res->numRows();
847 return $rows;
848 }
849
850 function ruleExists( $table, $rule ) {
851 global $wgDBmwschema;
852 $exists = $this->selectField( 'pg_rules', 'rulename',
853 array(
854 'rulename' => $rule,
855 'tablename' => $table,
856 'schemaname' => $wgDBmwschema
857 )
858 );
859 return $exists === $rule;
860 }
861
862 function constraintExists( $table, $constraint ) {
863 global $wgDBmwschema;
864 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
865 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
866 $this->addQuotes( $wgDBmwschema ),
867 $this->addQuotes( $table ),
868 $this->addQuotes( $constraint )
869 );
870 $res = $this->query( $SQL );
871 if ( !$res ) {
872 return null;
873 }
874 $rows = $res->numRows();
875 return $rows;
876 }
877
878 /**
879 * Query whether a given schema exists. Returns the name of the owner
880 */
881 function schemaExists( $schema ) {
882 $eschema = str_replace( "'", "''", $schema );
883 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
884 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
885 $res = $this->query( $SQL );
886 if ( $res && $res->numRows() ) {
887 $row = $res->fetchObject();
888 $owner = $row->rolname;
889 } else {
890 $owner = false;
891 }
892 return $owner;
893 }
894
895 function fieldInfo( $table, $field ) {
896 return PostgresField::fromText( $this, $table, $field );
897 }
898
899 /**
900 * pg_field_type() wrapper
901 */
902 function fieldType( $res, $index ) {
903 if ( $res instanceof ResultWrapper ) {
904 $res = $res->result;
905 }
906 return pg_field_type( $res, $index );
907 }
908
909 /* Not even sure why this is used in the main codebase... */
910 function limitResultForUpdate( $sql, $num ) {
911 return $sql;
912 }
913
914 function encodeBlob( $b ) {
915 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
916 }
917
918 function decodeBlob( $b ) {
919 if ( $b instanceof Blob ) {
920 $b = $b->fetch();
921 }
922 return pg_unescape_bytea( $b );
923 }
924
925 function strencode( $s ) { # Should not be called by us
926 return pg_escape_string( $this->mConn, $s );
927 }
928
929 function addQuotes( $s ) {
930 if ( is_null( $s ) ) {
931 return 'NULL';
932 } elseif ( is_bool( $s ) ) {
933 return intval( $s );
934 } elseif ( $s instanceof Blob ) {
935 return "'" . $s->fetch( $s ) . "'";
936 }
937 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
938 }
939
940 /**
941 * Postgres specific version of replaceVars.
942 * Calls the parent version in Database.php
943 *
944 * @private
945 *
946 * @param $ins String: SQL string, read from a stream (usually tables.sql)
947 *
948 * @return string SQL string
949 */
950 protected function replaceVars( $ins ) {
951 $ins = parent::replaceVars( $ins );
952
953 if ( $this->numeric_version >= 8.3 ) {
954 // Thanks for not providing backwards-compatibility, 8.3
955 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
956 }
957
958 if ( $this->numeric_version <= 8.1 ) { // Our minimum version
959 $ins = str_replace( 'USING gin', 'USING gist', $ins );
960 }
961
962 return $ins;
963 }
964
965 /**
966 * Various select options
967 *
968 * @private
969 *
970 * @param $options Array: an associative array of options to be turned into
971 * an SQL query, valid keys are listed in the function.
972 * @return array
973 */
974 function makeSelectOptions( $options ) {
975 $preLimitTail = $postLimitTail = '';
976 $startOpts = $useIndex = '';
977
978 $noKeyOptions = array();
979 foreach ( $options as $key => $option ) {
980 if ( is_numeric( $key ) ) {
981 $noKeyOptions[$option] = true;
982 }
983 }
984
985 if ( isset( $options['GROUP BY'] ) ) {
986 $preLimitTail .= ' GROUP BY ' . $options['GROUP BY'];
987 }
988 if ( isset( $options['HAVING'] ) ) {
989 $preLimitTail .= " HAVING {$options['HAVING']}";
990 }
991 if ( isset( $options['ORDER BY'] ) ) {
992 $preLimitTail .= ' ORDER BY ' . $options['ORDER BY'];
993 }
994
995 //if ( isset( $options['LIMIT'] ) ) {
996 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
997 // isset( $options['OFFSET'] ) ? $options['OFFSET']
998 // : false );
999 //}
1000
1001 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1002 $postLimitTail .= ' FOR UPDATE';
1003 }
1004 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1005 $postLimitTail .= ' LOCK IN SHARE MODE';
1006 }
1007 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1008 $startOpts .= 'DISTINCT';
1009 }
1010
1011 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1012 }
1013
1014 function setFakeMaster( $enabled = true ) {}
1015
1016 function getDBname() {
1017 return $this->mDBname;
1018 }
1019
1020 function getServer() {
1021 return $this->mServer;
1022 }
1023
1024 function buildConcat( $stringList ) {
1025 return implode( ' || ', $stringList );
1026 }
1027
1028 public function getSearchEngine() {
1029 return 'SearchPostgres';
1030 }
1031 } // end DatabasePostgres class