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" );
59 $this->mServer
= $server;
61 $this->mPassword
= $password;
62 $this->mDBname
= $dbName;
66 if ( '' != $dbName ) {
67 # start a database connection
69 if ($server!=false && $server!="") {
70 $hstring="host=$server ";
72 @$this->mConn
= pg_connect("$hstring dbname=$dbName user=$user password=$password");
73 if ( $this->mConn
== false ) {
74 wfDebug( "DB connection error\n" );
75 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
76 wfDebug( $this->lastError()."\n" );
78 $this->mOpened
= true;
80 $this->query("SET search_path = $wgDBschema,public");
86 * Closes a database connection, if it is open
87 * Returns success, true if already closed
90 $this->mOpened
= false;
92 return pg_close( $this->mConn
);
98 function doQuery( $sql ) {
99 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
102 function queryIgnore( $sql, $fname = '' ) {
103 return $this->query( $sql, $fname, true );
106 function freeResult( $res ) {
107 if ( !@pg_free_result
( $res ) ) {
108 wfDebugDieBacktrace( "Unable to free PostgreSQL result\n" );
112 function fetchObject( $res ) {
113 @$row = pg_fetch_object( $res );
114 # FIXME: HACK HACK HACK HACK debug
117 # hashar : not sure if the following test really trigger if the object
119 if( pg_last_error($this->mConn
) ) {
120 wfDebugDieBacktrace( 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
125 function fetchRow( $res ) {
126 @$row = pg_fetch_array( $res );
127 if( pg_last_error($this->mConn
) ) {
128 wfDebugDieBacktrace( 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
133 function numRows( $res ) {
134 @$n = pg_num_rows( $res );
135 if( pg_last_error($this->mConn
) ) {
136 wfDebugDieBacktrace( 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
140 function numFields( $res ) { return pg_num_fields( $res ); }
141 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
144 * This must be called after nextSequenceVal
146 function insertId() {
147 return $this->mInsertId
;
150 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
151 function lastError() { return pg_last_error(); }
152 function lastErrno() { return 1; }
154 function affectedRows() {
155 return pg_affected_rows( $this->mLastResult
);
159 * Returns information about an index
160 * If errors are explicitly ignored, returns NULL on failure
162 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
163 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
164 $res = $this->query( $sql, $fname );
169 while ( $row = $this->fetchObject( $res ) ) {
170 if ( $row->Key_name
== $index ) {
177 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
178 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
179 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
180 $res = $this->query( $sql, $fname );
183 while ($row = $this->fetchObject( $res ))
189 function fieldInfo( $table, $field ) {
190 wfDebugDieBacktrace( 'Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre' );
192 $res = $this->query( "SELECT * FROM '$table' LIMIT 1" );
193 $n = pg_num_fields( $res );
194 for( $i = 0; $i < $n; $i++ ) {
196 wfDebugDieBacktrace( "Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre" );
197 $meta = mysql_fetch_field( $res, $i );
198 if( $field == $meta->name ) {
205 function insertArray( $table, $a, $fname = 'Database::insertArray', $options = array() ) {
206 # PostgreSQL doesn't support options
207 # We have a go at faking one of them
208 # TODO: DELAYED, LOW_PRIORITY
210 if ( !is_array($options))
211 $options = array($options);
213 if ( in_array( 'IGNORE', $options ) )
214 $oldIgnore = $this->ignoreErrors( true );
216 # IGNORE is performed using single-row inserts, ignoring errors in each
217 # FIXME: need some way to distiguish between key collision and other types of error
218 $oldIgnore = $this->ignoreErrors( true );
219 if ( !is_array( reset( $a ) ) ) {
222 foreach ( $a as $row ) {
223 parent
::insertArray( $table, $row, $fname, array() );
225 $this->ignoreErrors( $oldIgnore );
228 if ( in_array( 'IGNORE', $options ) )
229 $this->ignoreErrors( $oldIgnore );
234 function startTimer( $timeout )
237 wfDebugDieBacktrace( 'Database::startTimer() error : mysql_thread_id() not implemented for postgre' );
238 /*$tid = mysql_thread_id( $this->mConn );
239 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );*/
242 function tableName( $name ) {
243 # First run any transformations from the parent object
244 $name = parent
::tableName( $name );
246 # Now quote PG reserved keywords
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->getField(''," 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 wfDebugDieBacktrace( '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($limit,$offset) {
376 return " 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 wfDebugDieBacktrace($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 );
441 class DatabasePostgreSQL
extends DatabasePgsql
{