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
10 * STATUS: Working PG implementation of MediaWiki
11 * TODO: Installer support
19 require_once( 'Database.php' );
25 class DatabasePostgres
extends Database
{
26 var $mInsertId = NULL;
27 var $mLastResult = NULL;
29 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
30 $failFunction = false, $flags = 0 )
32 Database
::__construct( $server, $user, $password, $dbName, $failFunction, $flags );
35 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
36 $failFunction = false, $flags = 0)
38 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
42 * Usually aborts on failure
43 * If the failFunction is set to a non-zero integer, returns success
45 function open( $server, $user, $password, $dbName ) {
46 # Test for PostgreSQL support, to avoid suppressed fatal error
47 if ( !function_exists( 'pg_connect' ) ) {
48 throw new DBConnectionError( $this, "PostgreSQL functions missing, have you compiled PHP with the --with-pgsql option?\n" );
54 $this->mServer
= $server;
56 $this->mPassword
= $password;
57 $this->mDBname
= $dbName;
58 $this->mSchemas
= array($wgDBschema,'public');
62 if ( '' != $dbName ) {
63 # start a database connection
65 if ($server!=false && $server!="") {
66 $hstring="host=$server ";
69 @$this->mConn
= pg_connect("$hstring dbname=$dbName user=$user password=$password");
70 if ( $this->mConn
== false ) {
71 wfDebug( "DB connection error\n" );
72 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
73 wfDebug( $this->lastError()."\n" );
76 $this->mOpened
= true;
83 * Closes a database connection, if it is open
84 * Returns success, true if already closed
87 $this->mOpened
= false;
89 return pg_close( $this->mConn
);
95 function doQuery( $sql ) {
96 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
99 function queryIgnore( $sql, $fname = '' ) {
100 return $this->query( $sql, $fname, true );
103 function freeResult( $res ) {
104 if ( !@pg_free_result
( $res ) ) {
105 throw new DBUnexpectedError($this, "Unable to free PostgreSQL result\n" );
109 function fetchObject( $res ) {
110 @$row = pg_fetch_object( $res );
111 # FIXME: HACK HACK HACK HACK debug
114 # hashar : not sure if the following test really trigger if the object
116 if( pg_last_error($this->mConn
) ) {
117 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
122 function fetchRow( $res ) {
123 @$row = pg_fetch_array( $res );
124 if( pg_last_error($this->mConn
) ) {
125 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
130 function numRows( $res ) {
131 @$n = pg_num_rows( $res );
132 if( pg_last_error($this->mConn
) ) {
133 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
137 function numFields( $res ) { return pg_num_fields( $res ); }
138 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
141 * This must be called after nextSequenceVal
143 function insertId() {
144 return $this->mInsertId
;
147 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
148 function lastError() {
149 if ( $this->mConn
) {
150 return pg_last_error();
153 return "No database connection";
156 function lastErrno() { return 1; }
158 function affectedRows() {
159 return pg_affected_rows( $this->mLastResult
);
163 * Returns information about an index
164 * If errors are explicitly ignored, returns NULL on failure
166 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
167 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
168 $res = $this->query( $sql, $fname );
173 while ( $row = $this->fetchObject( $res ) ) {
174 if ( $row->Key_name
== $index ) {
181 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
182 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
183 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
184 $res = $this->query( $sql, $fname );
187 while ($row = $this->fetchObject( $res ))
193 function fieldInfo( $table, $field ) {
194 throw new DBUnexpectedError($this, 'Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre' );
196 $res = $this->query( "SELECT * FROM '$table' LIMIT 1" );
197 $n = pg_num_fields( $res );
198 for( $i = 0; $i < $n; $i++ ) {
200 throw new DBUnexpectedError($this, "Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre" );
201 $meta = mysql_fetch_field( $res, $i );
202 if( $field == $meta->name ) {
209 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
210 # PostgreSQL doesn't support options
211 # We have a go at faking one of them
212 # TODO: DELAYED, LOW_PRIORITY
214 if ( !is_array($options))
215 $options = array($options);
217 if ( in_array( 'IGNORE', $options ) )
218 $oldIgnore = $this->ignoreErrors( true );
220 # IGNORE is performed using single-row inserts, ignoring errors in each
221 # FIXME: need some way to distiguish between key collision and other types of error
222 $oldIgnore = $this->ignoreErrors( true );
223 if ( !is_array( reset( $a ) ) ) {
226 foreach ( $a as $row ) {
227 parent
::insert( $table, $row, $fname, array() );
229 $this->ignoreErrors( $oldIgnore );
232 if ( in_array( 'IGNORE', $options ) )
233 $this->ignoreErrors( $oldIgnore );
238 function tableName( $name ) {
239 # First run any transformations from the parent object
240 $name = parent
::tableName( $name );
242 # Replace backticks into double quotes
243 $name = strtr($name,'`','"');
245 # Now quote PG reserved keywords
250 return '"' . $name . '"';
257 function strencode( $s ) {
258 return pg_escape_string( $s );
262 * Return the next in a sequence, save the value for retrieval via insertId()
264 function nextSequenceValue( $seqName ) {
265 $value = $this->selectField(''," nextval('" . $seqName . "')");
266 $this->mInsertId
= $value;
272 * PostgreSQL doesn't have them and returns ""
274 function useIndexClause( $index ) {
278 # REPLACE query wrapper
279 # PostgreSQL simulates this with a DELETE followed by INSERT
280 # $row is the row to insert, an associative array
281 # $uniqueIndexes is an array of indexes. Each element may be either a
282 # field name or an array of field names
284 # It may be more efficient to leave off unique indexes which are unlikely to collide.
285 # However if you do this, you run the risk of encountering errors which wouldn't have
287 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
288 $table = $this->tableName( $table );
290 if (count($rows)==0) {
295 if ( !is_array( reset( $rows ) ) ) {
296 $rows = array( $rows );
299 foreach( $rows as $row ) {
300 # Delete rows which collide
301 if ( $uniqueIndexes ) {
302 $sql = "DELETE FROM $table WHERE ";
304 foreach ( $uniqueIndexes as $index ) {
311 if ( is_array( $index ) ) {
313 foreach ( $index as $col ) {
319 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
322 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
326 $this->query( $sql, $fname );
330 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
331 $this->makeList( $row, LIST_COMMA
) . ')';
332 $this->query( $sql, $fname );
336 # DELETE where the condition is a join
337 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
339 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
342 $delTable = $this->tableName( $delTable );
343 $joinTable = $this->tableName( $joinTable );
344 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
345 if ( $conds != '*' ) {
346 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
350 $this->query( $sql, $fname );
353 # Returns the size of a text field, or -1 for "unlimited"
354 function textFieldSize( $table, $field ) {
355 $table = $this->tableName( $table );
356 $sql = "SELECT t.typname as ftype,a.atttypmod as size
357 FROM pg_class c, pg_attribute a, pg_type t
358 WHERE relname='$table' AND a.attrelid=c.oid AND
359 a.atttypid=t.oid and a.attname='$field'";
360 $res =$this->query($sql);
361 $row=$this->fetchObject($res);
362 if ($row->ftype
=="varchar") {
367 $this->freeResult( $res );
371 function lowPriorityOption() {
375 function limitResult($sql, $limit,$offset) {
376 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
380 * Returns an SQL expression for a simple conditional.
381 * Uses CASE on PostgreSQL.
383 * @param string $cond SQL expression which will result in a boolean value
384 * @param string $trueVal SQL expression to return if true
385 * @param string $falseVal SQL expression to return if false
386 * @return string SQL fragment
388 function conditional( $cond, $trueVal, $falseVal ) {
389 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
392 # FIXME: actually detecting deadlocks might be nice
393 function wasDeadlock() {
397 # Return DB-style timestamp used for MySQL schema
398 function timestamp( $ts=0 ) {
399 return wfTimestamp(TS_DB
,$ts);
403 * Return aggregated value function call
405 function aggregateValue ($valuedata,$valuename='value') {
410 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
411 $message = "A database error has occurred\n" .
413 "Function: $fname\n" .
414 "Error: $errno $error\n";
415 throw new DBUnexpectedError($this, $message);
419 * @return string wikitext of a link to the server software's web site
421 function getSoftwareLink() {
422 return "[http://www.postgresql.org/ PostgreSQL]";
426 * @return string Version information from the database
428 function getServerVersion() {
429 $res = $this->query( "SELECT version()" );
430 $row = $this->fetchRow( $res );
432 $this->freeResult( $res );
436 function setSchema($schema=false) {
437 $schemas=$this->mSchemas
;
438 if ($schema) { array_unshift($schemas,$schema); }
439 $searchpath=$this->makeList($schemas,LIST_NAMES
);
440 $this->query("SET search_path = $searchpath");