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;
63 $this->mSchemas
= array($wgDBschema,'public');
67 if ( '' != $dbName ) {
68 # start a database connection
70 if ($server!=false && $server!="") {
71 $hstring="host=$server ";
73 @$this->mConn
= pg_connect("$hstring dbname=$dbName user=$user password=$password");
74 if ( $this->mConn
== false ) {
75 wfDebug( "DB connection error\n" );
76 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
77 wfDebug( $this->lastError()."\n" );
80 $this->mOpened
= true;
87 * Closes a database connection, if it is open
88 * Returns success, true if already closed
91 $this->mOpened
= false;
93 return pg_close( $this->mConn
);
99 function doQuery( $sql ) {
100 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
103 function queryIgnore( $sql, $fname = '' ) {
104 return $this->query( $sql, $fname, true );
107 function freeResult( $res ) {
108 if ( !@pg_free_result
( $res ) ) {
109 wfDebugDieBacktrace( "Unable to free PostgreSQL result\n" );
113 function fetchObject( $res ) {
114 @$row = pg_fetch_object( $res );
115 # FIXME: HACK HACK HACK HACK debug
118 # hashar : not sure if the following test really trigger if the object
120 if( pg_last_error($this->mConn
) ) {
121 wfDebugDieBacktrace( 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
126 function fetchRow( $res ) {
127 @$row = pg_fetch_array( $res );
128 if( pg_last_error($this->mConn
) ) {
129 wfDebugDieBacktrace( 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
134 function numRows( $res ) {
135 @$n = pg_num_rows( $res );
136 if( pg_last_error($this->mConn
) ) {
137 wfDebugDieBacktrace( 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
141 function numFields( $res ) { return pg_num_fields( $res ); }
142 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
145 * This must be called after nextSequenceVal
147 function insertId() {
148 return $this->mInsertId
;
151 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
152 function lastError() { return pg_last_error(); }
153 function lastErrno() { return 1; }
155 function affectedRows() {
156 return pg_affected_rows( $this->mLastResult
);
160 * Returns information about an index
161 * If errors are explicitly ignored, returns NULL on failure
163 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
164 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
165 $res = $this->query( $sql, $fname );
170 while ( $row = $this->fetchObject( $res ) ) {
171 if ( $row->Key_name
== $index ) {
178 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
179 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
180 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
181 $res = $this->query( $sql, $fname );
184 while ($row = $this->fetchObject( $res ))
190 function fieldInfo( $table, $field ) {
191 wfDebugDieBacktrace( 'Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre' );
193 $res = $this->query( "SELECT * FROM '$table' LIMIT 1" );
194 $n = pg_num_fields( $res );
195 for( $i = 0; $i < $n; $i++ ) {
197 wfDebugDieBacktrace( "Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre" );
198 $meta = mysql_fetch_field( $res, $i );
199 if( $field == $meta->name ) {
206 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
207 # PostgreSQL doesn't support options
208 # We have a go at faking one of them
209 # TODO: DELAYED, LOW_PRIORITY
211 if ( !is_array($options))
212 $options = array($options);
214 if ( in_array( 'IGNORE', $options ) )
215 $oldIgnore = $this->ignoreErrors( true );
217 # IGNORE is performed using single-row inserts, ignoring errors in each
218 # FIXME: need some way to distiguish between key collision and other types of error
219 $oldIgnore = $this->ignoreErrors( true );
220 if ( !is_array( reset( $a ) ) ) {
223 foreach ( $a as $row ) {
224 parent
::insert( $table, $row, $fname, array() );
226 $this->ignoreErrors( $oldIgnore );
229 if ( in_array( 'IGNORE', $options ) )
230 $this->ignoreErrors( $oldIgnore );
235 function startTimer( $timeout )
238 wfDebugDieBacktrace( 'Database::startTimer() error : mysql_thread_id() not implemented for postgre' );
239 /*$tid = mysql_thread_id( $this->mConn );
240 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );*/
243 function tableName( $name ) {
244 # First run any transformations from the parent object
245 $name = parent
::tableName( $name );
247 # Replace backticks into double quotes
248 $name = strtr($name,'`','"');
250 # Now quote PG reserved keywords
255 return '"' . $name . '"';
262 function strencode( $s ) {
263 return addslashes( $s );
267 * Return the next in a sequence, save the value for retrieval via insertId()
269 function nextSequenceValue( $seqName ) {
270 $value = $this->selectField(''," nextval('" . $seqName . "')");
271 $this->mInsertId
= $value;
277 * PostgreSQL doesn't have them and returns ""
279 function useIndexClause( $index ) {
283 # REPLACE query wrapper
284 # PostgreSQL simulates this with a DELETE followed by INSERT
285 # $row is the row to insert, an associative array
286 # $uniqueIndexes is an array of indexes. Each element may be either a
287 # field name or an array of field names
289 # It may be more efficient to leave off unique indexes which are unlikely to collide.
290 # However if you do this, you run the risk of encountering errors which wouldn't have
292 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
293 $table = $this->tableName( $table );
295 if (count($rows)==0) {
300 if ( !is_array( reset( $rows ) ) ) {
301 $rows = array( $rows );
304 foreach( $rows as $row ) {
305 # Delete rows which collide
306 if ( $uniqueIndexes ) {
307 $sql = "DELETE FROM $table WHERE ";
309 foreach ( $uniqueIndexes as $index ) {
316 if ( is_array( $index ) ) {
318 foreach ( $index as $col ) {
324 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
327 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
331 $this->query( $sql, $fname );
335 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
336 $this->makeList( $row, LIST_COMMA
) . ')';
337 $this->query( $sql, $fname );
341 # DELETE where the condition is a join
342 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
344 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
347 $delTable = $this->tableName( $delTable );
348 $joinTable = $this->tableName( $joinTable );
349 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
350 if ( $conds != '*' ) {
351 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
355 $this->query( $sql, $fname );
358 # Returns the size of a text field, or -1 for "unlimited"
359 function textFieldSize( $table, $field ) {
360 $table = $this->tableName( $table );
361 $sql = "SELECT t.typname as ftype,a.atttypmod as size
362 FROM pg_class c, pg_attribute a, pg_type t
363 WHERE relname='$table' AND a.attrelid=c.oid AND
364 a.atttypid=t.oid and a.attname='$field'";
365 $res =$this->query($sql);
366 $row=$this->fetchObject($res);
367 if ($row->ftype
=="varchar") {
372 $this->freeResult( $res );
376 function lowPriorityOption() {
380 function limitResult($limit,$offset) {
381 return " LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
385 * Returns an SQL expression for a simple conditional.
386 * Uses CASE on PostgreSQL.
388 * @param string $cond SQL expression which will result in a boolean value
389 * @param string $trueVal SQL expression to return if true
390 * @param string $falseVal SQL expression to return if false
391 * @return string SQL fragment
393 function conditional( $cond, $trueVal, $falseVal ) {
394 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
397 # FIXME: actually detecting deadlocks might be nice
398 function wasDeadlock() {
402 # Return DB-style timestamp used for MySQL schema
403 function timestamp( $ts=0 ) {
404 return wfTimestamp(TS_DB
,$ts);
408 * Return aggregated value function call
410 function aggregateValue ($valuedata,$valuename='value') {
415 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
416 $message = "A database error has occurred\n" .
418 "Function: $fname\n" .
419 "Error: $errno $error\n";
420 wfDebugDieBacktrace($message);
424 * @return string wikitext of a link to the server software's web site
426 function getSoftwareLink() {
427 return "[http://www.postgresql.org/ PostgreSQL]";
431 * @return string Version information from the database
433 function getServerVersion() {
434 $res = $this->query( "SELECT version()" );
435 $row = $this->fetchRow( $res );
437 $this->freeResult( $res );
441 function setSchema($schema=false) {
442 $schemas=$this->mSchemas
;
443 if ($schema) { array_unshift($schemas,$schema); }
444 $searchpath=$this->makeList($schemas,LIST_NAMES
);
445 $this->query("SET search_path = $searchpath");
453 class DatabasePostgreSQL
extends DatabasePgsql
{