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