Fix bug 2642 : watchdetails message using HTML instead of wiki syntax. Patch by zigge...
[lhc/web/wiklou.git] / includes / DatabasePostgreSQL.php
1 <?php
2
3 /**
4 * This is PostgreSQL database abstraction layer.
5 *
6 * As it includes more generic version for DB functions,
7 * than MySQL ones, some of them should be moved to parent
8 * Database class.
9 *
10 * STATUS: Working PG implementation of MediaWiki
11 * TODO: Installer support
12 *
13 * @package MediaWiki
14 */
15
16 /**
17 * Depends on database
18 */
19 require_once( 'Database.php' );
20
21 /**
22 *
23 * @package MediaWiki
24 */
25 class DatabasePgsql extends Database {
26 var $mInsertId = NULL;
27 var $mLastResult = NULL;
28
29 function DatabasePgsql($server = false, $user = false, $password = false, $dbName = false,
30 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
31 {
32 Database::Database( $server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix );
33 }
34
35 /* static */ function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
36 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
37 {
38 return new DatabasePgsql( $server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix );
39 }
40
41 /**
42 * Usually aborts on failure
43 * If the failFunction is set to a non-zero integer, returns success
44 */
45 function open( $server, $user, $password, $dbName ) {
46 # Test for PostgreSQL support, to avoid suppressed fatal error
47 if ( !function_exists( 'pg_connect' ) ) {
48 die( "PostgreSQL functions missing, have you compiled PHP with the --with-pgsql option?\n" );
49 }
50
51 global $wgDBschema;
52
53 $this->close();
54 $this->mServer = $server;
55 $this->mUser = $user;
56 $this->mPassword = $password;
57 $this->mDBname = $dbName;
58 $this->mSchemas = array($wgDBschema,'public');
59
60 $success = false;
61
62 if ( '' != $dbName ) {
63 # start a database connection
64 $hstring="";
65 if ($server!=false && $server!="") {
66 $hstring="host=$server ";
67 }
68 @$this->mConn = pg_connect("$hstring dbname=$dbName user=$user password=$password");
69 if ( $this->mConn == false ) {
70 wfDebug( "DB connection error\n" );
71 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
72 wfDebug( $this->lastError()."\n" );
73 } else {
74 $this->setSchema();
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 indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
174 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
175 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
176 $res = $this->query( $sql, $fname );
177 if ( !$res )
178 return NULL;
179 while ($row = $this->fetchObject( $res ))
180 return true;
181 return false;
182
183 }
184
185 function fieldInfo( $table, $field ) {
186 wfDebugDieBacktrace( 'Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre' );
187 /*
188 $res = $this->query( "SELECT * FROM '$table' LIMIT 1" );
189 $n = pg_num_fields( $res );
190 for( $i = 0; $i < $n; $i++ ) {
191 // FIXME
192 wfDebugDieBacktrace( "Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre" );
193 $meta = mysql_fetch_field( $res, $i );
194 if( $field == $meta->name ) {
195 return $meta;
196 }
197 }
198 return false;*/
199 }
200
201 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
202 # PostgreSQL doesn't support options
203 # We have a go at faking one of them
204 # TODO: DELAYED, LOW_PRIORITY
205
206 if ( !is_array($options))
207 $options = array($options);
208
209 if ( in_array( 'IGNORE', $options ) )
210 $oldIgnore = $this->ignoreErrors( true );
211
212 # IGNORE is performed using single-row inserts, ignoring errors in each
213 # FIXME: need some way to distiguish between key collision and other types of error
214 $oldIgnore = $this->ignoreErrors( true );
215 if ( !is_array( reset( $a ) ) ) {
216 $a = array( $a );
217 }
218 foreach ( $a as $row ) {
219 parent::insert( $table, $row, $fname, array() );
220 }
221 $this->ignoreErrors( $oldIgnore );
222 $retVal = true;
223
224 if ( in_array( 'IGNORE', $options ) )
225 $this->ignoreErrors( $oldIgnore );
226
227 return $retVal;
228 }
229
230 function startTimer( $timeout )
231 {
232 global $IP;
233 wfDebugDieBacktrace( 'Database::startTimer() error : mysql_thread_id() not implemented for postgre' );
234 /*$tid = mysql_thread_id( $this->mConn );
235 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );*/
236 }
237
238 function tableName( $name ) {
239 # First run any transformations from the parent object
240 $name = parent::tableName( $name );
241
242 # Replace backticks into double quotes
243 $name = strtr($name,'`','"');
244
245 # Now quote PG reserved keywords
246 switch( $name ) {
247 case 'user':
248 case 'old':
249 case 'group':
250 return '"' . $name . '"';
251
252 default:
253 return $name;
254 }
255 }
256
257 function strencode( $s ) {
258 return pg_escape_string( $s );
259 }
260
261 /**
262 * Return the next in a sequence, save the value for retrieval via insertId()
263 */
264 function nextSequenceValue( $seqName ) {
265 $value = $this->selectField(''," nextval('" . $seqName . "')");
266 $this->mInsertId = $value;
267 return $value;
268 }
269
270 /**
271 * USE INDEX clause
272 * PostgreSQL doesn't have them and returns ""
273 */
274 function useIndexClause( $index ) {
275 return '';
276 }
277
278 # REPLACE query wrapper
279 # PostgreSQL simulates this with a DELETE followed by INSERT
280 # $row is the row to insert, an associative array
281 # $uniqueIndexes is an array of indexes. Each element may be either a
282 # field name or an array of field names
283 #
284 # It may be more efficient to leave off unique indexes which are unlikely to collide.
285 # However if you do this, you run the risk of encountering errors which wouldn't have
286 # occurred in MySQL
287 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
288 $table = $this->tableName( $table );
289
290 if (count($rows)==0) {
291 return;
292 }
293
294 # Single row case
295 if ( !is_array( reset( $rows ) ) ) {
296 $rows = array( $rows );
297 }
298
299 foreach( $rows as $row ) {
300 # Delete rows which collide
301 if ( $uniqueIndexes ) {
302 $sql = "DELETE FROM $table WHERE ";
303 $first = true;
304 foreach ( $uniqueIndexes as $index ) {
305 if ( $first ) {
306 $first = false;
307 $sql .= "(";
308 } else {
309 $sql .= ') OR (';
310 }
311 if ( is_array( $index ) ) {
312 $first2 = true;
313 foreach ( $index as $col ) {
314 if ( $first2 ) {
315 $first2 = false;
316 } else {
317 $sql .= ' AND ';
318 }
319 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
320 }
321 } else {
322 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
323 }
324 }
325 $sql .= ')';
326 $this->query( $sql, $fname );
327 }
328
329 # Now insert the row
330 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
331 $this->makeList( $row, LIST_COMMA ) . ')';
332 $this->query( $sql, $fname );
333 }
334 }
335
336 # DELETE where the condition is a join
337 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
338 if ( !$conds ) {
339 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
340 }
341
342 $delTable = $this->tableName( $delTable );
343 $joinTable = $this->tableName( $joinTable );
344 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
345 if ( $conds != '*' ) {
346 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
347 }
348 $sql .= ')';
349
350 $this->query( $sql, $fname );
351 }
352
353 # Returns the size of a text field, or -1 for "unlimited"
354 function textFieldSize( $table, $field ) {
355 $table = $this->tableName( $table );
356 $sql = "SELECT t.typname as ftype,a.atttypmod as size
357 FROM pg_class c, pg_attribute a, pg_type t
358 WHERE relname='$table' AND a.attrelid=c.oid AND
359 a.atttypid=t.oid and a.attname='$field'";
360 $res =$this->query($sql);
361 $row=$this->fetchObject($res);
362 if ($row->ftype=="varchar") {
363 $size=$row->size-4;
364 } else {
365 $size=$row->size;
366 }
367 $this->freeResult( $res );
368 return $size;
369 }
370
371 function lowPriorityOption() {
372 return '';
373 }
374
375 function limitResult($limit,$offset) {
376 return " LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
377 }
378
379 /**
380 * Returns an SQL expression for a simple conditional.
381 * Uses CASE on PostgreSQL.
382 *
383 * @param string $cond SQL expression which will result in a boolean value
384 * @param string $trueVal SQL expression to return if true
385 * @param string $falseVal SQL expression to return if false
386 * @return string SQL fragment
387 */
388 function conditional( $cond, $trueVal, $falseVal ) {
389 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
390 }
391
392 # FIXME: actually detecting deadlocks might be nice
393 function wasDeadlock() {
394 return false;
395 }
396
397 # Return DB-style timestamp used for MySQL schema
398 function timestamp( $ts=0 ) {
399 return wfTimestamp(TS_DB,$ts);
400 }
401
402 /**
403 * Return aggregated value function call
404 */
405 function aggregateValue ($valuedata,$valuename='value') {
406 return $valuedata;
407 }
408
409
410 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
411 $message = "A database error has occurred\n" .
412 "Query: $sql\n" .
413 "Function: $fname\n" .
414 "Error: $errno $error\n";
415 wfDebugDieBacktrace($message);
416 }
417
418 /**
419 * @return string wikitext of a link to the server software's web site
420 */
421 function getSoftwareLink() {
422 return "[http://www.postgresql.org/ PostgreSQL]";
423 }
424
425 /**
426 * @return string Version information from the database
427 */
428 function getServerVersion() {
429 $res = $this->query( "SELECT version()" );
430 $row = $this->fetchRow( $res );
431 $version = $row[0];
432 $this->freeResult( $res );
433 return $version;
434 }
435
436 function setSchema($schema=false) {
437 $schemas=$this->mSchemas;
438 if ($schema) { array_unshift($schemas,$schema); }
439 $searchpath=$this->makeList($schemas,LIST_NAMES);
440 $this->query("SET search_path = $searchpath");
441 }
442 }
443
444 /**
445 * Just an alias.
446 * @package MediaWiki
447 */
448 class DatabasePostgreSQL extends DatabasePgsql {
449 }
450
451 ?>