BUG#76 For categories, don't use the Category:-prefix for the sortkey.
[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 $hstring="";
67 if ($server!=false && $server!="") {
68 $hstring="host=$server ";
69 }
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;
77 }
78 }
79 return $this->mConn;
80 }
81
82 /**
83 * Closes a database connection, if it is open
84 * Returns success, true if already closed
85 */
86 function close() {
87 $this->mOpened = false;
88 if ( $this->mConn ) {
89 return pg_close( $this->mConn );
90 } else {
91 return true;
92 }
93 }
94
95 function doQuery( $sql ) {
96 return $this->mLastResult=pg_query( $this->mConn , $sql);
97 }
98
99 function queryIgnore( $sql, $fname = '' ) {
100 return $this->query( $sql, $fname, true );
101 }
102
103 function freeResult( $res ) {
104 if ( !@pg_free_result( $res ) ) {
105 wfDebugDieBacktrace( "Unable to free PostgreSQL result\n" );
106 }
107 }
108
109 function fetchObject( $res ) {
110 @$row = pg_fetch_object( $res );
111 # FIXME: HACK HACK HACK HACK debug
112
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) ) );
118 }
119 return $row;
120 }
121
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) ) );
126 }
127 return $row;
128 }
129
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) ) );
134 }
135 return $n;
136 }
137 function numFields( $res ) { return pg_num_fields( $res ); }
138 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
139
140 /**
141 * This must be called after nextSequenceVal
142 */
143 function insertId() {
144 return $this->mInsertId;
145 }
146
147 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
148 function lastError() { return pg_last_error(); }
149 function lastErrno() { return 1; }
150
151 function affectedRows() {
152 return pg_affected_rows( $this->mLastResult );
153 }
154
155 /**
156 * Returns information about an index
157 * If errors are explicitly ignored, returns NULL on failure
158 */
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;
164 }
165
166 while ( $row = $this->fetchObject( $res ) ) {
167 if ( $row->Key_name == $index ) {
168 return $row;
169 }
170 }
171 return false;
172 }
173
174 function fieldInfo( $table, $field ) {
175 wfDebugDieBacktrace( 'Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre' );
176 /*
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;
185 }
186 }
187 return false;*/
188 }
189
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
194
195 if ( !is_array($options))
196 $options = array($options);
197
198 if ( in_array( 'IGNORE', $options ) )
199 $oldIgnore = $this->ignoreErrors( true );
200
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 );
206 }
207 foreach ( $a as $row ) {
208 parent::insertArray( $table, $row, $fname, array() );
209 }
210 $this->ignoreErrors( $oldIgnore );
211 $retVal = true;
212
213 if ( in_array( 'IGNORE', $options ) )
214 $this->ignoreErrors( $oldIgnore );
215
216 return $retVal;
217 }
218
219 function startTimer( $timeout )
220 {
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 &" );*/
225 }
226
227 function tableName( $name ) {
228 # First run any transformations from the parent object
229 $name = parent::tableName( $name );
230
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;
239 }
240 }
241
242 function strencode( $s ) {
243 return pg_escape_string( $s );
244 }
245
246 /**
247 * Return the next in a sequence, save the value for retrieval via insertId()
248 */
249 function nextSequenceValue( $seqName ) {
250 $value = $this->getField(''," nextval('" . $seqName . "')");
251 $this->mInsertId = $value;
252 return $value;
253 }
254
255 /**
256 * USE INDEX clause
257 * PostgreSQL doesn't have them and returns ""
258 */
259 function useIndexClause( $index ) {
260 return '';
261 }
262
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
268 #
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 );
274
275 if (count($rows)==0) {
276 return;
277 }
278
279 # Single row case
280 if ( !is_array( reset( $rows ) ) ) {
281 $rows = array( $rows );
282 }
283
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 (';
295 }
296 if ( is_array( $index ) ) {
297 $first2 = true;
298 foreach ( $index as $col ) {
299 if ( $first2 ) {
300 $first2 = false;
301 } else {
302 $sql .= ' AND ';
303 }
304 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
305 }
306 } else {
307 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
308 }
309 }
310 $sql .= ')';
311 $this->query( $sql, $fname );
312 }
313
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 );
318 }
319 }
320
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' );
325 }
326
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 );
332 }
333 $sql .= ')';
334
335 $this->query( $sql, $fname );
336 }
337
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;
345 }
346
347 function lowPriorityOption() {
348 return '';
349 }
350
351 function limitResult($limit,$offset) {
352 return " LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
353 }
354
355 # FIXME: actually detecting deadlocks might be nice
356 function wasDeadlock() {
357 return false;
358 }
359
360 # Return DB-style timestamp used for MySQL schema
361 function timestamp( $ts=0 ) {
362 return wfTimestamp(TS_DB,$ts);
363 }
364
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);
371 }
372 }
373
374 /**
375 * Just an alias.
376 * @package MediaWiki
377 */
378 class DatabasePostgreSQL extends DatabasePgsql {
379 }
380
381 ?>