5 * DO NOT USE !!! Unless you want to help developping it.
7 * This file is an attempt to port the mysql database layer to postgreSQL. The
8 * only thing done so far is s/mysql/pg/ and dieing if function haven't been
11 * As said brion 07/06/2004 :
12 * "table definitions need to be changed. fulltext index needs to work differently
13 * things that use the last insert id need to be changed. Probably other things
14 * need to be changed. various semantics may be different."
24 require_once( 'Database.php' );
30 class DatabasePgsql
extends Database
{
31 var $mInsertId = NULL;
32 var $mLastResult = NULL;
34 function DatabasePgsql($server = false, $user = false, $password = false, $dbName = false,
35 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
37 Database
::Database( $server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix );
40 /* static */ function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
41 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
43 return new DatabasePgsql( $server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix );
47 * Usually aborts on failure
48 * If the failFunction is set to a non-zero integer, returns success
50 function open( $server, $user, $password, $dbName ) {
51 # Test for PostgreSQL support, to avoid suppressed fatal error
52 if ( !function_exists( 'pg_connect' ) ) {
53 die( "PostgreSQL functions missing, have you compiled PHP with the --with-pgsql option?\n" );
57 $this->mServer
= $server;
59 $this->mPassword
= $password;
60 $this->mDBname
= $dbName;
64 if ( '' != $dbName ) {
65 # start a database connection
67 if ($server!=false && $server!="") {
68 $hstring="host=$server ";
70 @$this->mConn
= pg_connect("$hstring dbname=$dbName user=$user password=$password");
71 if ( $this->mConn
== false ) {
72 wfDebug( "DB connection error\n" );
73 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
74 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 wfDebugDieBacktrace( "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 wfDebugDieBacktrace( '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 wfDebugDieBacktrace( '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 wfDebugDieBacktrace( '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() { return pg_last_error(); }
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 ) {
187 wfDebugDieBacktrace( 'Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre' );
189 $res = $this->query( "SELECT * FROM '$table' LIMIT 1" );
190 $n = pg_num_fields( $res );
191 for( $i = 0; $i < $n; $i++ ) {
193 wfDebugDieBacktrace( "Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre" );
194 $meta = mysql_fetch_field( $res, $i );
195 if( $field == $meta->name ) {
202 function insertArray( $table, $a, $fname = 'Database::insertArray', $options = array() ) {
203 # PostgreSQL doesn't support options
204 # We have a go at faking one of them
205 # TODO: DELAYED, LOW_PRIORITY
207 if ( !is_array($options))
208 $options = array($options);
210 if ( in_array( 'IGNORE', $options ) )
211 $oldIgnore = $this->ignoreErrors( true );
213 # IGNORE is performed using single-row inserts, ignoring errors in each
214 # FIXME: need some way to distiguish between key collision and other types of error
215 $oldIgnore = $this->ignoreErrors( true );
216 if ( !is_array( reset( $a ) ) ) {
219 foreach ( $a as $row ) {
220 parent
::insertArray( $table, $row, $fname, array() );
222 $this->ignoreErrors( $oldIgnore );
225 if ( in_array( 'IGNORE', $options ) )
226 $this->ignoreErrors( $oldIgnore );
231 function startTimer( $timeout )
234 wfDebugDieBacktrace( 'Database::startTimer() error : mysql_thread_id() not implemented for postgre' );
235 /*$tid = mysql_thread_id( $this->mConn );
236 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );*/
239 function tableName( $name ) {
240 # First run any transformations from the parent object
241 $name = parent
::tableName( $name );
243 # Now quote PG reserved keywords
254 function strencode( $s ) {
255 return pg_escape_string( $s );
259 * Return the next in a sequence, save the value for retrieval via insertId()
261 function nextSequenceValue( $seqName ) {
262 $value = $this->getField(''," nextval('" . $seqName . "')");
263 $this->mInsertId
= $value;
269 * PostgreSQL doesn't have them and returns ""
271 function useIndexClause( $index ) {
275 # REPLACE query wrapper
276 # PostgreSQL simulates this with a DELETE followed by INSERT
277 # $row is the row to insert, an associative array
278 # $uniqueIndexes is an array of indexes. Each element may be either a
279 # field name or an array of field names
281 # It may be more efficient to leave off unique indexes which are unlikely to collide.
282 # However if you do this, you run the risk of encountering errors which wouldn't have
284 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
285 $table = $this->tableName( $table );
287 if (count($rows)==0) {
292 if ( !is_array( reset( $rows ) ) ) {
293 $rows = array( $rows );
296 foreach( $rows as $row ) {
297 # Delete rows which collide
298 if ( $uniqueIndexes ) {
299 $sql = "DELETE FROM $table WHERE ";
301 foreach ( $uniqueIndexes as $index ) {
308 if ( is_array( $index ) ) {
310 foreach ( $index as $col ) {
316 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
319 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
323 $this->query( $sql, $fname );
327 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
328 $this->makeList( $row, LIST_COMMA
) . ')';
329 $this->query( $sql, $fname );
333 # DELETE where the condition is a join
334 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
336 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
339 $delTable = $this->tableName( $delTable );
340 $joinTable = $this->tableName( $joinTable );
341 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
342 if ( $conds != '*' ) {
343 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
347 $this->query( $sql, $fname );
350 # Returns the size of a text field, or -1 for "unlimited"
351 function textFieldSize( $table, $field ) {
352 $table = $this->tableName( $table );
353 $sql = "SELECT t.typname as ftype,a.atttypmod as size
354 FROM pg_class c, pg_attribute a, pg_type t
355 WHERE relname='$table' AND a.attrelid=c.oid AND
356 a.atttypid=t.oid and a.attname='$field'";
357 $res =$this->query($sql);
358 $row=$this->fetchObject($res);
359 if ($row->ftype
=="varchar") {
364 $this->freeResult( $res );
368 function lowPriorityOption() {
372 function limitResult($limit,$offset) {
373 return " LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
377 * Returns an SQL expression for a simple conditional.
378 * Uses CASE on PostgreSQL.
380 * @param string $cond SQL expression which will result in a boolean value
381 * @param string $trueVal SQL expression to return if true
382 * @param string $falseVal SQL expression to return if false
383 * @return string SQL fragment
385 function conditional( $cond, $trueVal, $falseVal ) {
386 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
389 # FIXME: actually detecting deadlocks might be nice
390 function wasDeadlock() {
394 # Return DB-style timestamp used for MySQL schema
395 function timestamp( $ts=0 ) {
396 return wfTimestamp(TS_DB
,$ts);
400 * Return aggregated value function call
402 function aggregateValue ($valuedata,$valuename='value') {
407 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
408 $message = "A database error has occurred\n" .
410 "Function: $fname\n" .
411 "Error: $errno $error\n";
412 wfDebugDieBacktrace($message);
416 * @return string wikitext of a link to the server software's web site
418 function getSoftwareLink() {
419 return "[http://www.postgresql.org/ PostgreSQL]";
423 * @return string Version information from the database
425 function getServerVersion() {
426 $res = $this->query( "SELECT version()" );
427 $row = $this->fetchRow( $res );
429 $this->freeResult( $res );
438 class DatabasePostgreSQL
extends DatabasePgsql
{