Split files and classes in different packages for phpdocumentor. I probably changed...
[lhc/web/wiklou.git] / includes / DatabasePostgreSQL.php
1 <?php
2 # $Id$
3
4 /**
5 * DO NOT USE !!! Unless you want to help developping it.
6 *
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.
10 *
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."
15 *
16 * Hashar
17 *
18 * @package MediaWiki
19 */
20
21 /**
22 * Depends on database
23 */
24 require_once( 'Database.php' );
25
26 /**
27 *
28 * @package MediaWiki
29 */
30 class DatabasePgsql extends Database {
31 var $mInsertId = NULL;
32 var $mLastResult = NULL;
33
34 function DatabasePgsql($server = false, $user = false, $password = false, $dbName = false,
35 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
36 {
37 Database::Database( $server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix );
38 }
39
40 /* static */ function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
41 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
42 {
43 return new DatabasePgsql( $server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix );
44 }
45
46 /**
47 * Usually aborts on failure
48 * If the failFunction is set to a non-zero integer, returns success
49 */
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" );
54 }
55
56 $this->close();
57 $this->mServer = $server;
58 $this->mUser = $user;
59 $this->mPassword = $password;
60 $this->mDBname = $dbName;
61
62 $success = false;
63
64 if ( '' != $dbName ) {
65 # start a database connection
66 @$this->mConn = pg_connect("host=$server dbname=$dbName user=$user password=$password");
67 if ( $this->mConn == false ) {
68 wfDebug( "DB connection error\n" );
69 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
70 wfDebug( $this->lastError()."\n" );
71 } else {
72 $this->mOpened = true;
73 }
74 }
75 return $this->mConn;
76 }
77
78 /**
79 * Closes a database connection, if it is open
80 * Returns success, true if already closed
81 */
82 function close() {
83 $this->mOpened = false;
84 if ( $this->mConn ) {
85 return pg_close( $this->mConn );
86 } else {
87 return true;
88 }
89 }
90
91 function doQuery( $sql ) {
92 return $this->mLastResult=pg_query( $this->mConn , $sql);
93 }
94
95 function queryIgnore( $sql, $fname = '' ) {
96 return $this->query( $sql, $fname, true );
97 }
98
99 function freeResult( $res ) {
100 if ( !@pg_free_result( $res ) ) {
101 wfDebugDieBacktrace( "Unable to free PostgreSQL result\n" );
102 }
103 }
104
105 function fetchObject( $res ) {
106 @$row = pg_fetch_object( $res );
107 # FIXME: HACK HACK HACK HACK debug
108
109 # TODO:
110 # hashar : not sure if the following test really trigger if the object
111 # fetching failled.
112 if( pg_last_error($this->mConn) ) {
113 wfDebugDieBacktrace( 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
114 }
115 return $row;
116 }
117
118 function fetchRow( $res ) {
119 @$row = pg_fetch_array( $res );
120 if( pg_last_error($this->mConn) ) {
121 wfDebugDieBacktrace( 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
122 }
123 return $row;
124 }
125
126 function numRows( $res ) {
127 @$n = pg_num_rows( $res );
128 if( pg_last_error($this->mConn) ) {
129 wfDebugDieBacktrace( 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
130 }
131 return $n;
132 }
133 function numFields( $res ) { return pg_num_fields( $res ); }
134 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
135
136 /**
137 * This must be called after nextSequenceVal
138 */
139 function insertId() {
140 return $this->mInsertId;
141 }
142
143 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
144 function lastError() { return pg_last_error(); }
145 function lastErrno() { return 1; }
146
147 function affectedRows() {
148 return pg_affected_rows( $this->mLastResult );
149 }
150
151 /**
152 * Returns information about an index
153 * If errors are explicitly ignored, returns NULL on failure
154 */
155 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
156 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
157 $res = $this->query( $sql, $fname );
158 if ( !$res ) {
159 return NULL;
160 }
161
162 while ( $row = $this->fetchObject( $res ) ) {
163 if ( $row->Key_name == $index ) {
164 return $row;
165 }
166 }
167 return false;
168 }
169
170 function fieldInfo( $table, $field ) {
171 wfDebugDieBacktrace( 'Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre' );
172 /*
173 $res = $this->query( "SELECT * FROM '$table' LIMIT 1" );
174 $n = pg_num_fields( $res );
175 for( $i = 0; $i < $n; $i++ ) {
176 // FIXME
177 wfDebugDieBacktrace( "Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre" );
178 $meta = mysql_fetch_field( $res, $i );
179 if( $field == $meta->name ) {
180 return $meta;
181 }
182 }
183 return false;*/
184 }
185
186 function insertArray( $table, $a, $fname = 'Database::insertArray', $options = array() ) {
187 # PostgreSQL doesn't support options
188 # We have a go at faking one of them
189 # TODO: DELAYED, LOW_PRIORITY
190
191 if ( !is_array($options))
192 $options = array($options);
193
194 if ( in_array( 'IGNORE', $options ) )
195 $oldIgnore = $this->ignoreErrors( true );
196
197 # IGNORE is performed using single-row inserts, ignoring errors in each
198 # FIXME: need some way to distiguish between key collision and other types of error
199 $oldIgnore = $this->ignoreErrors( true );
200 if ( !is_array( reset( $a ) ) ) {
201 $a = array( $a );
202 }
203 foreach ( $a as $row ) {
204 parent::insertArray( $table, $row, $fname, array() );
205 }
206 $this->ignoreErrors( $oldIgnore );
207 $retVal = true;
208
209 if ( in_array( 'IGNORE', $options ) )
210 $this->ignoreErrors( $oldIgnore );
211
212 return $retVal;
213 }
214
215 function startTimer( $timeout )
216 {
217 global $IP;
218 wfDebugDieBacktrace( 'Database::startTimer() error : mysql_thread_id() not implemented for postgre' );
219 /*$tid = mysql_thread_id( $this->mConn );
220 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );*/
221 }
222
223 function tableName( $name ) {
224 # First run any transformations from the parent object
225 $name = parent::tableName( $name );
226
227 # Now quote PG reserved keywords
228 switch( $name ) {
229 case 'user':
230 return '"user"';
231 case 'old':
232 return '"old"';
233 default:
234 return $name;
235 }
236 }
237
238 function strencode( $s ) {
239 return pg_escape_string( $s );
240 }
241
242 /**
243 * Return the next in a sequence, save the value for retrieval via insertId()
244 */
245 function nextSequenceValue( $seqName ) {
246 $value = $this->getField(''," nextval('" . $seqName . "')");
247 $this->mInsertId = $value;
248 return $value;
249 }
250
251 /**
252 * USE INDEX clause
253 * PostgreSQL doesn't have them and returns ""
254 */
255 function useIndexClause( $index ) {
256 return '';
257 }
258
259 # REPLACE query wrapper
260 # PostgreSQL simulates this with a DELETE followed by INSERT
261 # $row is the row to insert, an associative array
262 # $uniqueIndexes is an array of indexes. Each element may be either a
263 # field name or an array of field names
264 #
265 # It may be more efficient to leave off unique indexes which are unlikely to collide.
266 # However if you do this, you run the risk of encountering errors which wouldn't have
267 # occurred in MySQL
268 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
269 $table = $this->tableName( $table );
270
271 # Single row case
272 if ( !is_array( reset( $rows ) ) ) {
273 $rows = array( $rows );
274 }
275
276 foreach( $rows as $row ) {
277 # Delete rows which collide
278 if ( $uniqueIndexes ) {
279 $sql = "DELETE FROM $table WHERE (";
280 $first = true;
281 foreach ( $uniqueIndexes as $index ) {
282 if ( $first ) {
283 $first = false;
284 } else {
285 $sql .= ') OR (';
286 }
287 if ( is_array( $index ) ) {
288 $first2 = true;
289 $sql .= "(";
290 foreach ( $index as $col ) {
291 if ( $first2 ) {
292 $first2 = false;
293 } else {
294 $sql .= ' AND ';
295 }
296 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
297 }
298 } else {
299 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
300 }
301 }
302 $sql .= ')';
303 $this->query( $sql, $fname );
304 }
305
306 # Now insert the row
307 $sql = "INSERT INTO $table (" . $this->makeList( array_flip( $row ) ) .') VALUES (' .
308 $this->makeList( $row, LIST_COMMA ) . ')';
309 $this->query( $sql, $fname );
310 }
311 }
312
313 # DELETE where the condition is a join
314 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
315 if ( !$conds ) {
316 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
317 }
318
319 $delTable = $this->tableName( $delTable );
320 $joinTable = $this->tableName( $joinTable );
321 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
322 if ( $conds != '*' ) {
323 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
324 }
325 $sql .= ')';
326
327 $this->query( $sql, $fname );
328 }
329
330 # Returns the size of a text field, or -1 for "unlimited"
331 function textFieldSize( $table, $field ) {
332 $table = $this->tableName( $table );
333 $res = $this->query( "SELECT $field FROM $table LIMIT 1", "Database::textFieldLength" );
334 $size = pg_field_size( $res, 0 );
335 $this->freeResult( $res );
336 return $size;
337 }
338
339 function lowPriorityOption() {
340 return '';
341 }
342
343 function limitResult($limit,$offset) {
344 return " LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
345 }
346
347 # FIXME: actually detecting deadlocks might be nice
348 function wasDeadlock() {
349 return false;
350 }
351
352 # Return DB-style timestamp used for MySQL schema
353 function timestamp( $ts=0 ) {
354 return wfTimestamp(TS_DB,$ts);
355 }
356
357 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
358 $message = "A database error has occurred\n" .
359 "Query: $sql\n" .
360 "Function: $fname\n" .
361 "Error: $errno $error\n";
362 wfDebugDieBacktrace($message);
363 }
364 }
365
366 /**
367 * Just an alias.
368 * @package MediaWiki
369 */
370 class DatabasePostgreSQL extends DatabasePgsql {
371 }
372
373 ?>