* double quotes to single quotes
[mediawiki.git] / includes / DatabasePostgreSQL.php
blobb3e74ec2f699e67164dfc7d159f6d0e85c59f904
1 <?php
2 # $Id$
4 /**
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
9 * ported.
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."
16 * Hashar
18 * @package MediaWiki
21 /**
22 * Depends on database
24 require_once( 'Database.php' );
26 /**
28 * @package MediaWiki
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 );
46 /**
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" );
56 $this->close();
57 $this->mServer = $server;
58 $this->mUser = $user;
59 $this->mPassword = $password;
60 $this->mDBname = $dbName;
62 $success = false;
64 if ( '' != $dbName ) {
65 # start a database connection
66 $hstring="";
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" );
75 } else {
76 $this->mOpened = true;
79 return $this->mConn;
82 /**
83 * Closes a database connection, if it is open
84 * Returns success, true if already closed
86 function close() {
87 $this->mOpened = false;
88 if ( $this->mConn ) {
89 return pg_close( $this->mConn );
90 } else {
91 return true;
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
113 # TODO:
114 # hashar : not sure if the following test really trigger if the object
115 # fetching failled.
116 if( pg_last_error($this->mConn) ) {
117 wfDebugDieBacktrace( 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
119 return $row;
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) ) );
127 return $row;
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) ) );
135 return $n;
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 );
162 if ( !$res ) {
163 return NULL;
166 while ( $row = $this->fetchObject( $res ) ) {
167 if ( $row->Key_name == $index ) {
168 return $row;
171 return false;
174 function fieldInfo( $table, $field ) {
175 wfDebugDieBacktrace( 'Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre' );
177 $res = $this->query( "SELECT * FROM '$table' LIMIT 1" );
178 $n = pg_num_fields( $res );
179 for( $i = 0; $i < $n; $i++ ) {
180 // FIXME
181 wfDebugDieBacktrace( "Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre" );
182 $meta = mysql_fetch_field( $res, $i );
183 if( $field == $meta->name ) {
184 return $meta;
187 return false;*/
190 function insertArray( $table, $a, $fname = 'Database::insertArray', $options = array() ) {
191 # PostgreSQL doesn't support options
192 # We have a go at faking one of them
193 # TODO: DELAYED, LOW_PRIORITY
195 if ( !is_array($options))
196 $options = array($options);
198 if ( in_array( 'IGNORE', $options ) )
199 $oldIgnore = $this->ignoreErrors( true );
201 # IGNORE is performed using single-row inserts, ignoring errors in each
202 # FIXME: need some way to distiguish between key collision and other types of error
203 $oldIgnore = $this->ignoreErrors( true );
204 if ( !is_array( reset( $a ) ) ) {
205 $a = array( $a );
207 foreach ( $a as $row ) {
208 parent::insertArray( $table, $row, $fname, array() );
210 $this->ignoreErrors( $oldIgnore );
211 $retVal = true;
213 if ( in_array( 'IGNORE', $options ) )
214 $this->ignoreErrors( $oldIgnore );
216 return $retVal;
219 function startTimer( $timeout )
221 global $IP;
222 wfDebugDieBacktrace( 'Database::startTimer() error : mysql_thread_id() not implemented for postgre' );
223 /*$tid = mysql_thread_id( $this->mConn );
224 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );*/
227 function tableName( $name ) {
228 # First run any transformations from the parent object
229 $name = parent::tableName( $name );
231 # Now quote PG reserved keywords
232 switch( $name ) {
233 case 'user':
234 return '"user"';
235 case 'old':
236 return '"old"';
237 default:
238 return $name;
242 function strencode( $s ) {
243 return pg_escape_string( $s );
247 * Return the next in a sequence, save the value for retrieval via insertId()
249 function nextSequenceValue( $seqName ) {
250 $value = $this->getField(''," nextval('" . $seqName . "')");
251 $this->mInsertId = $value;
252 return $value;
256 * USE INDEX clause
257 * PostgreSQL doesn't have them and returns ""
259 function useIndexClause( $index ) {
260 return '';
263 # REPLACE query wrapper
264 # PostgreSQL simulates this with a DELETE followed by INSERT
265 # $row is the row to insert, an associative array
266 # $uniqueIndexes is an array of indexes. Each element may be either a
267 # field name or an array of field names
269 # It may be more efficient to leave off unique indexes which are unlikely to collide.
270 # However if you do this, you run the risk of encountering errors which wouldn't have
271 # occurred in MySQL
272 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
273 $table = $this->tableName( $table );
275 if (count($rows)==0) {
276 return;
279 # Single row case
280 if ( !is_array( reset( $rows ) ) ) {
281 $rows = array( $rows );
284 foreach( $rows as $row ) {
285 # Delete rows which collide
286 if ( $uniqueIndexes ) {
287 $sql = "DELETE FROM $table WHERE ";
288 $first = true;
289 foreach ( $uniqueIndexes as $index ) {
290 if ( $first ) {
291 $first = false;
292 $sql .= "(";
293 } else {
294 $sql .= ') OR (';
296 if ( is_array( $index ) ) {
297 $first2 = true;
298 foreach ( $index as $col ) {
299 if ( $first2 ) {
300 $first2 = false;
301 } else {
302 $sql .= ' AND ';
304 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
306 } else {
307 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
310 $sql .= ')';
311 $this->query( $sql, $fname );
314 # Now insert the row
315 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
316 $this->makeList( $row, LIST_COMMA ) . ')';
317 $this->query( $sql, $fname );
321 # DELETE where the condition is a join
322 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
323 if ( !$conds ) {
324 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
327 $delTable = $this->tableName( $delTable );
328 $joinTable = $this->tableName( $joinTable );
329 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
330 if ( $conds != '*' ) {
331 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
333 $sql .= ')';
335 $this->query( $sql, $fname );
338 # Returns the size of a text field, or -1 for "unlimited"
339 function textFieldSize( $table, $field ) {
340 $table = $this->tableName( $table );
341 $res = $this->query( "SELECT $field FROM $table LIMIT 1", "Database::textFieldLength" );
342 $size = pg_field_size( $res, 0 );
343 $this->freeResult( $res );
344 return $size;
347 function lowPriorityOption() {
348 return '';
351 function limitResult($limit,$offset) {
352 return " LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
355 # FIXME: actually detecting deadlocks might be nice
356 function wasDeadlock() {
357 return false;
360 # Return DB-style timestamp used for MySQL schema
361 function timestamp( $ts=0 ) {
362 return wfTimestamp(TS_DB,$ts);
365 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
366 $message = "A database error has occurred\n" .
367 "Query: $sql\n" .
368 "Function: $fname\n" .
369 "Error: $errno $error\n";
370 wfDebugDieBacktrace($message);
375 * Just an alias.
376 * @package MediaWiki
378 class DatabasePostgreSQL extends DatabasePgsql {