4 * DO NOT USE !!! Unless you want to help developping it.
6 * This file is an attempt to port the mysql database layer to postgreSQL. The
7 * only thing done so far is s/mysql/pg/ and dieing if function haven't been
10 * As said brion 07/06/2004 :
11 * "table definitions need to be changed. fulltext index needs to work differently
12 * things that use the last insert id need to be changed. Probably other things
13 * need to be changed. various semantics may be different."
23 require_once( 'Database.php' );
29 class DatabasePgsql
extends Database
{
30 var $mInsertId = NULL;
31 var $mLastResult = NULL;
33 function DatabasePgsql($server = false, $user = false, $password = false, $dbName = false,
34 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
36 Database
::Database( $server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix );
39 /* static */ function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
40 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
42 return new DatabasePgsql( $server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix );
46 * Usually aborts on failure
47 * If the failFunction is set to a non-zero integer, returns success
49 function open( $server, $user, $password, $dbName ) {
50 # Test for PostgreSQL support, to avoid suppressed fatal error
51 if ( !function_exists( 'pg_connect' ) ) {
52 die( "PostgreSQL functions missing, have you compiled PHP with the --with-pgsql option?\n" );
58 $this->mServer
= $server;
60 $this->mPassword
= $password;
61 $this->mDBname
= $dbName;
62 $this->mSchemas
= array($wgDBschema,'public');
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" );
79 $this->mOpened
= true;
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 insert( $table, $a, $fname = 'Database::insert', $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
::insert( $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 # Replace backticks into double quotes
247 $name = strtr($name,'`','"');
249 # Now quote PG reserved keywords
254 return '"' . $name . '"';
261 function strencode( $s ) {
262 return addslashes( $s );
266 * Return the next in a sequence, save the value for retrieval via insertId()
268 function nextSequenceValue( $seqName ) {
269 $value = $this->selectField(''," nextval('" . $seqName . "')");
270 $this->mInsertId
= $value;
276 * PostgreSQL doesn't have them and returns ""
278 function useIndexClause( $index ) {
282 # REPLACE query wrapper
283 # PostgreSQL simulates this with a DELETE followed by INSERT
284 # $row is the row to insert, an associative array
285 # $uniqueIndexes is an array of indexes. Each element may be either a
286 # field name or an array of field names
288 # It may be more efficient to leave off unique indexes which are unlikely to collide.
289 # However if you do this, you run the risk of encountering errors which wouldn't have
291 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
292 $table = $this->tableName( $table );
294 if (count($rows)==0) {
299 if ( !is_array( reset( $rows ) ) ) {
300 $rows = array( $rows );
303 foreach( $rows as $row ) {
304 # Delete rows which collide
305 if ( $uniqueIndexes ) {
306 $sql = "DELETE FROM $table WHERE ";
308 foreach ( $uniqueIndexes as $index ) {
315 if ( is_array( $index ) ) {
317 foreach ( $index as $col ) {
323 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
326 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
330 $this->query( $sql, $fname );
334 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
335 $this->makeList( $row, LIST_COMMA
) . ')';
336 $this->query( $sql, $fname );
340 # DELETE where the condition is a join
341 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
343 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
346 $delTable = $this->tableName( $delTable );
347 $joinTable = $this->tableName( $joinTable );
348 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
349 if ( $conds != '*' ) {
350 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
354 $this->query( $sql, $fname );
357 # Returns the size of a text field, or -1 for "unlimited"
358 function textFieldSize( $table, $field ) {
359 $table = $this->tableName( $table );
360 $sql = "SELECT t.typname as ftype,a.atttypmod as size
361 FROM pg_class c, pg_attribute a, pg_type t
362 WHERE relname='$table' AND a.attrelid=c.oid AND
363 a.atttypid=t.oid and a.attname='$field'";
364 $res =$this->query($sql);
365 $row=$this->fetchObject($res);
366 if ($row->ftype
=="varchar") {
371 $this->freeResult( $res );
375 function lowPriorityOption() {
379 function limitResult($limit,$offset) {
380 return " LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
384 * Returns an SQL expression for a simple conditional.
385 * Uses CASE on PostgreSQL.
387 * @param string $cond SQL expression which will result in a boolean value
388 * @param string $trueVal SQL expression to return if true
389 * @param string $falseVal SQL expression to return if false
390 * @return string SQL fragment
392 function conditional( $cond, $trueVal, $falseVal ) {
393 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
396 # FIXME: actually detecting deadlocks might be nice
397 function wasDeadlock() {
401 # Return DB-style timestamp used for MySQL schema
402 function timestamp( $ts=0 ) {
403 return wfTimestamp(TS_DB
,$ts);
407 * Return aggregated value function call
409 function aggregateValue ($valuedata,$valuename='value') {
414 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
415 $message = "A database error has occurred\n" .
417 "Function: $fname\n" .
418 "Error: $errno $error\n";
419 wfDebugDieBacktrace($message);
423 * @return string wikitext of a link to the server software's web site
425 function getSoftwareLink() {
426 return "[http://www.postgresql.org/ PostgreSQL]";
430 * @return string Version information from the database
432 function getServerVersion() {
433 $res = $this->query( "SELECT version()" );
434 $row = $this->fetchRow( $res );
436 $this->freeResult( $res );
440 function setSchema($schema=false) {
441 $schemas=$this->mSchemas
;
442 if ($schema) { array_unshift($schemas,$schema); }
443 $searchpath=$this->makeList($schemas,LIST_NAMES
);
444 $this->query("SET search_path = $searchpath");
452 class DatabasePostgreSQL
extends DatabasePgsql
{