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