4 * This is PostgreSQL database abstraction layer.
6 * As it includes more generic version for DB functions,
7 * than MySQL ones, some of them should be moved to parent
16 require_once( 'Database.php' );
18 class DatabasePostgres
extends Database
{
19 var $mInsertId = NULL;
20 var $mLastResult = NULL;
22 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
23 $failFunction = false, $flags = 0 )
25 Database
::__construct( $server, $user, $password, $dbName, $failFunction, $flags );
28 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
29 $failFunction = false, $flags = 0)
31 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
35 * Usually aborts on failure
36 * If the failFunction is set to a non-zero integer, returns success
38 function open( $server, $user, $password, $dbName ) {
39 # Test for PostgreSQL support, to avoid suppressed fatal error
40 if ( !function_exists( 'pg_connect' ) ) {
41 throw new DBConnectionError( $this, "PostgreSQL functions missing, have you compiled PHP with the --with-pgsql option?\n" );
47 $this->mServer
= $server;
49 $this->mPassword
= $password;
50 $this->mDBname
= $dbName;
51 $this->mSchemas
= array($wgDBschema,'public');
55 if ( '' != $dbName ) {
56 # start a database connection
58 if ($server!=false && $server!="") {
59 $hstring="host=$server ";
62 @$this->mConn
= pg_connect("$hstring dbname=$dbName user=$user password=$password");
63 if ( $this->mConn
== false ) {
64 wfDebug( "DB connection error\n" );
65 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
66 wfDebug( $this->lastError()."\n" );
69 $this->mOpened
= true;
76 * Closes a database connection, if it is open
77 * Returns success, true if already closed
80 $this->mOpened
= false;
82 return pg_close( $this->mConn
);
88 function doQuery( $sql ) {
89 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
92 function queryIgnore( $sql, $fname = '' ) {
93 return $this->query( $sql, $fname, true );
96 function freeResult( $res ) {
97 if ( !@pg_free_result
( $res ) ) {
98 throw new DBUnexpectedError($this, "Unable to free PostgreSQL result\n" );
102 function fetchObject( $res ) {
103 @$row = pg_fetch_object( $res );
104 # FIXME: HACK HACK HACK HACK debug
107 # hashar : not sure if the following test really trigger if the object
109 if( pg_last_error($this->mConn
) ) {
110 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
115 function fetchRow( $res ) {
116 @$row = pg_fetch_array( $res );
117 if( pg_last_error($this->mConn
) ) {
118 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
123 function numRows( $res ) {
124 @$n = pg_num_rows( $res );
125 if( pg_last_error($this->mConn
) ) {
126 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
130 function numFields( $res ) { return pg_num_fields( $res ); }
131 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
134 * This must be called after nextSequenceVal
136 function insertId() {
137 return $this->mInsertId
;
140 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
141 function lastError() {
142 if ( $this->mConn
) {
143 return pg_last_error();
146 return "No database connection";
149 function lastErrno() { return 1; }
151 function affectedRows() {
152 return pg_affected_rows( $this->mLastResult
);
156 * Returns information about an index
157 * If errors are explicitly ignored, returns NULL on failure
159 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
160 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
161 $res = $this->query( $sql, $fname );
166 while ( $row = $this->fetchObject( $res ) ) {
167 if ( $row->Key_name
== $index ) {
174 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
175 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
176 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
177 $res = $this->query( $sql, $fname );
180 while ($row = $this->fetchObject( $res ))
186 function fieldInfo( $table, $field ) {
188 throw new DBUnexpectedError($this, 'Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre' );
190 $res = $this->query( "SELECT * FROM '$table' LIMIT 1" );
191 $n = pg_num_fields( $res );
192 for( $i = 0; $i < $n; $i++ ) {
194 throw new DBUnexpectedError($this, "Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre" );
195 $meta = mysql_fetch_field( $res, $i );
196 if( $field == $meta->name ) {
203 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
204 # PostgreSQL doesn't support options
205 # We have a go at faking one of them
206 # TODO: DELAYED, LOW_PRIORITY
208 if ( !is_array($options))
209 $options = array($options);
211 if ( in_array( 'IGNORE', $options ) )
212 $oldIgnore = $this->ignoreErrors( true );
214 # IGNORE is performed using single-row inserts, ignoring errors in each
215 # FIXME: need some way to distiguish between key collision and other types of error
216 $oldIgnore = $this->ignoreErrors( true );
217 if ( !is_array( reset( $a ) ) ) {
220 foreach ( $a as $row ) {
221 parent
::insert( $table, $row, $fname, array() );
223 $this->ignoreErrors( $oldIgnore );
226 if ( in_array( 'IGNORE', $options ) )
227 $this->ignoreErrors( $oldIgnore );
232 function tableName( $name ) {
233 # First run any transformations from the parent object
234 $name = parent
::tableName( $name );
236 # Replace backticks into double quotes
237 $name = strtr($name,'`','"');
239 # Now quote PG reserved keywords
244 return '"' . $name . '"';
251 function strencode( $s ) {
252 return pg_escape_string( $s );
256 * Return the next in a sequence, save the value for retrieval via insertId()
258 function nextSequenceValue( $seqName ) {
259 $value = $this->selectField(''," nextval('" . $seqName . "')");
260 $this->mInsertId
= $value;
266 * PostgreSQL doesn't have them and returns ""
268 function useIndexClause( $index ) {
272 # REPLACE query wrapper
273 # PostgreSQL simulates this with a DELETE followed by INSERT
274 # $row is the row to insert, an associative array
275 # $uniqueIndexes is an array of indexes. Each element may be either a
276 # field name or an array of field names
278 # It may be more efficient to leave off unique indexes which are unlikely to collide.
279 # However if you do this, you run the risk of encountering errors which wouldn't have
281 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
282 $table = $this->tableName( $table );
284 if (count($rows)==0) {
289 if ( !is_array( reset( $rows ) ) ) {
290 $rows = array( $rows );
293 foreach( $rows as $row ) {
294 # Delete rows which collide
295 if ( $uniqueIndexes ) {
296 $sql = "DELETE FROM $table WHERE ";
298 foreach ( $uniqueIndexes as $index ) {
305 if ( is_array( $index ) ) {
307 foreach ( $index as $col ) {
313 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
316 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
320 $this->query( $sql, $fname );
324 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
325 $this->makeList( $row, LIST_COMMA
) . ')';
326 $this->query( $sql, $fname );
330 # DELETE where the condition is a join
331 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
333 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
336 $delTable = $this->tableName( $delTable );
337 $joinTable = $this->tableName( $joinTable );
338 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
339 if ( $conds != '*' ) {
340 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
344 $this->query( $sql, $fname );
347 # Returns the size of a text field, or -1 for "unlimited"
348 function textFieldSize( $table, $field ) {
349 $table = $this->tableName( $table );
350 $sql = "SELECT t.typname as ftype,a.atttypmod as size
351 FROM pg_class c, pg_attribute a, pg_type t
352 WHERE relname='$table' AND a.attrelid=c.oid AND
353 a.atttypid=t.oid and a.attname='$field'";
354 $res =$this->query($sql);
355 $row=$this->fetchObject($res);
356 if ($row->ftype
=="varchar") {
361 $this->freeResult( $res );
365 function lowPriorityOption() {
369 function limitResult($sql, $limit,$offset) {
370 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
374 * Returns an SQL expression for a simple conditional.
375 * Uses CASE on PostgreSQL.
377 * @param string $cond SQL expression which will result in a boolean value
378 * @param string $trueVal SQL expression to return if true
379 * @param string $falseVal SQL expression to return if false
380 * @return string SQL fragment
382 function conditional( $cond, $trueVal, $falseVal ) {
383 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
386 # FIXME: actually detecting deadlocks might be nice
387 function wasDeadlock() {
391 # Return DB-style timestamp used for MySQL schema
392 function timestamp( $ts=0 ) {
393 return wfTimestamp(TS_DB
,$ts);
397 * Return aggregated value function call
399 function aggregateValue ($valuedata,$valuename='value') {
404 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
405 $message = "A database error has occurred\n" .
407 "Function: $fname\n" .
408 "Error: $errno $error\n";
409 throw new DBUnexpectedError($this, $message);
413 * @return string wikitext of a link to the server software's web site
415 function getSoftwareLink() {
416 return "[http://www.postgresql.org/ PostgreSQL]";
420 * @return string Version information from the database
422 function getServerVersion() {
423 $res = $this->query( "SELECT version()" );
424 $row = $this->fetchRow( $res );
426 $this->freeResult( $res );
430 function setSchema($schema=false) {
431 $schemas=$this->mSchemas
;
432 if ($schema) { array_unshift($schemas,$schema); }
433 $searchpath=$this->makeList($schemas,LIST_NAMES
);
434 $this->query("SET search_path = $searchpath");
438 * Query whether a given table exists
440 function tableExists( $table, $fname = 'DatabasePostgres:tableExists' ) {
442 $stable = preg_replace("/'/", "''", $table);
443 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
444 . "WHERE c.relnamespace = n.oid AND c.relname = '$stable AND n.nspname = '$wgDBschema'";
445 $res = $this->query( $SQL, $fname );
447 $this->freeResult( $res );
454 * Query whether a given column exists
456 function fieldExists( $table, $field, $fname = 'DatabasePostgres::fieldExists' ) {
458 $stable = preg_replace("/'/", "''", $table);
459 $scol = preg_replace("/'/", "''", $field);
460 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
461 . "WHERE c.relnamespace = n.oid AND c.relname = '$stable' AND n.nspname = '$wgDBschema' "
462 . "AND a.attrelid = c.oid AND a.attname = '$safecol'";
463 $res = $this->query( $SQL, $fname );
465 $this->freeResult( $res );