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