Move page tweaks:
[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 global $wgDBschema;
57
58 $this->close();
59 $this->mServer = $server;
60 $this->mUser = $user;
61 $this->mPassword = $password;
62 $this->mDBname = $dbName;
63 $this->mSchemas = array($wgDBschema,'public');
64
65 $success = false;
66
67 if ( '' != $dbName ) {
68 # start a database connection
69 $hstring="";
70 if ($server!=false && $server!="") {
71 $hstring="host=$server ";
72 }
73 @$this->mConn = pg_connect("$hstring dbname=$dbName user=$user password=$password");
74 if ( $this->mConn == false ) {
75 wfDebug( "DB connection error\n" );
76 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
77 wfDebug( $this->lastError()."\n" );
78 } else {
79 $this->setSchema();
80 $this->mOpened = true;
81 }
82 }
83 return $this->mConn;
84 }
85
86 /**
87 * Closes a database connection, if it is open
88 * Returns success, true if already closed
89 */
90 function close() {
91 $this->mOpened = false;
92 if ( $this->mConn ) {
93 return pg_close( $this->mConn );
94 } else {
95 return true;
96 }
97 }
98
99 function doQuery( $sql ) {
100 return $this->mLastResult=pg_query( $this->mConn , $sql);
101 }
102
103 function queryIgnore( $sql, $fname = '' ) {
104 return $this->query( $sql, $fname, true );
105 }
106
107 function freeResult( $res ) {
108 if ( !@pg_free_result( $res ) ) {
109 wfDebugDieBacktrace( "Unable to free PostgreSQL result\n" );
110 }
111 }
112
113 function fetchObject( $res ) {
114 @$row = pg_fetch_object( $res );
115 # FIXME: HACK HACK HACK HACK debug
116
117 # TODO:
118 # hashar : not sure if the following test really trigger if the object
119 # fetching failled.
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 fetchRow( $res ) {
127 @$row = pg_fetch_array( $res );
128 if( pg_last_error($this->mConn) ) {
129 wfDebugDieBacktrace( 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
130 }
131 return $row;
132 }
133
134 function numRows( $res ) {
135 @$n = pg_num_rows( $res );
136 if( pg_last_error($this->mConn) ) {
137 wfDebugDieBacktrace( 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
138 }
139 return $n;
140 }
141 function numFields( $res ) { return pg_num_fields( $res ); }
142 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
143
144 /**
145 * This must be called after nextSequenceVal
146 */
147 function insertId() {
148 return $this->mInsertId;
149 }
150
151 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
152 function lastError() { return pg_last_error(); }
153 function lastErrno() { return 1; }
154
155 function affectedRows() {
156 return pg_affected_rows( $this->mLastResult );
157 }
158
159 /**
160 * Returns information about an index
161 * If errors are explicitly ignored, returns NULL on failure
162 */
163 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
164 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
165 $res = $this->query( $sql, $fname );
166 if ( !$res ) {
167 return NULL;
168 }
169
170 while ( $row = $this->fetchObject( $res ) ) {
171 if ( $row->Key_name == $index ) {
172 return $row;
173 }
174 }
175 return false;
176 }
177
178 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
179 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
180 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
181 $res = $this->query( $sql, $fname );
182 if ( !$res )
183 return NULL;
184 while ($row = $this->fetchObject( $res ))
185 return true;
186 return false;
187
188 }
189
190 function fieldInfo( $table, $field ) {
191 wfDebugDieBacktrace( 'Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre' );
192 /*
193 $res = $this->query( "SELECT * FROM '$table' LIMIT 1" );
194 $n = pg_num_fields( $res );
195 for( $i = 0; $i < $n; $i++ ) {
196 // FIXME
197 wfDebugDieBacktrace( "Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre" );
198 $meta = mysql_fetch_field( $res, $i );
199 if( $field == $meta->name ) {
200 return $meta;
201 }
202 }
203 return false;*/
204 }
205
206 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
207 # PostgreSQL doesn't support options
208 # We have a go at faking one of them
209 # TODO: DELAYED, LOW_PRIORITY
210
211 if ( !is_array($options))
212 $options = array($options);
213
214 if ( in_array( 'IGNORE', $options ) )
215 $oldIgnore = $this->ignoreErrors( true );
216
217 # IGNORE is performed using single-row inserts, ignoring errors in each
218 # FIXME: need some way to distiguish between key collision and other types of error
219 $oldIgnore = $this->ignoreErrors( true );
220 if ( !is_array( reset( $a ) ) ) {
221 $a = array( $a );
222 }
223 foreach ( $a as $row ) {
224 parent::insert( $table, $row, $fname, array() );
225 }
226 $this->ignoreErrors( $oldIgnore );
227 $retVal = true;
228
229 if ( in_array( 'IGNORE', $options ) )
230 $this->ignoreErrors( $oldIgnore );
231
232 return $retVal;
233 }
234
235 function startTimer( $timeout )
236 {
237 global $IP;
238 wfDebugDieBacktrace( 'Database::startTimer() error : mysql_thread_id() not implemented for postgre' );
239 /*$tid = mysql_thread_id( $this->mConn );
240 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );*/
241 }
242
243 function tableName( $name ) {
244 # First run any transformations from the parent object
245 $name = parent::tableName( $name );
246
247 # Now quote PG reserved keywords
248 switch( $name ) {
249 case 'user':
250 case 'old':
251 case 'group':
252 return '"' . $name . '"';
253
254 default:
255 return $name;
256 }
257 }
258
259 function strencode( $s ) {
260 return addslashes( $s );
261 }
262
263 /**
264 * Return the next in a sequence, save the value for retrieval via insertId()
265 */
266 function nextSequenceValue( $seqName ) {
267 $value = $this->selectField(''," nextval('" . $seqName . "')");
268 $this->mInsertId = $value;
269 return $value;
270 }
271
272 /**
273 * USE INDEX clause
274 * PostgreSQL doesn't have them and returns ""
275 */
276 function useIndexClause( $index ) {
277 return '';
278 }
279
280 # REPLACE query wrapper
281 # PostgreSQL simulates this with a DELETE followed by INSERT
282 # $row is the row to insert, an associative array
283 # $uniqueIndexes is an array of indexes. Each element may be either a
284 # field name or an array of field names
285 #
286 # It may be more efficient to leave off unique indexes which are unlikely to collide.
287 # However if you do this, you run the risk of encountering errors which wouldn't have
288 # occurred in MySQL
289 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
290 $table = $this->tableName( $table );
291
292 if (count($rows)==0) {
293 return;
294 }
295
296 # Single row case
297 if ( !is_array( reset( $rows ) ) ) {
298 $rows = array( $rows );
299 }
300
301 foreach( $rows as $row ) {
302 # Delete rows which collide
303 if ( $uniqueIndexes ) {
304 $sql = "DELETE FROM $table WHERE ";
305 $first = true;
306 foreach ( $uniqueIndexes as $index ) {
307 if ( $first ) {
308 $first = false;
309 $sql .= "(";
310 } else {
311 $sql .= ') OR (';
312 }
313 if ( is_array( $index ) ) {
314 $first2 = true;
315 foreach ( $index as $col ) {
316 if ( $first2 ) {
317 $first2 = false;
318 } else {
319 $sql .= ' AND ';
320 }
321 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
322 }
323 } else {
324 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
325 }
326 }
327 $sql .= ')';
328 $this->query( $sql, $fname );
329 }
330
331 # Now insert the row
332 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
333 $this->makeList( $row, LIST_COMMA ) . ')';
334 $this->query( $sql, $fname );
335 }
336 }
337
338 # DELETE where the condition is a join
339 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
340 if ( !$conds ) {
341 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
342 }
343
344 $delTable = $this->tableName( $delTable );
345 $joinTable = $this->tableName( $joinTable );
346 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
347 if ( $conds != '*' ) {
348 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
349 }
350 $sql .= ')';
351
352 $this->query( $sql, $fname );
353 }
354
355 # Returns the size of a text field, or -1 for "unlimited"
356 function textFieldSize( $table, $field ) {
357 $table = $this->tableName( $table );
358 $sql = "SELECT t.typname as ftype,a.atttypmod as size
359 FROM pg_class c, pg_attribute a, pg_type t
360 WHERE relname='$table' AND a.attrelid=c.oid AND
361 a.atttypid=t.oid and a.attname='$field'";
362 $res =$this->query($sql);
363 $row=$this->fetchObject($res);
364 if ($row->ftype=="varchar") {
365 $size=$row->size-4;
366 } else {
367 $size=$row->size;
368 }
369 $this->freeResult( $res );
370 return $size;
371 }
372
373 function lowPriorityOption() {
374 return '';
375 }
376
377 function limitResult($limit,$offset) {
378 return " LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
379 }
380
381 /**
382 * Returns an SQL expression for a simple conditional.
383 * Uses CASE on PostgreSQL.
384 *
385 * @param string $cond SQL expression which will result in a boolean value
386 * @param string $trueVal SQL expression to return if true
387 * @param string $falseVal SQL expression to return if false
388 * @return string SQL fragment
389 */
390 function conditional( $cond, $trueVal, $falseVal ) {
391 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
392 }
393
394 # FIXME: actually detecting deadlocks might be nice
395 function wasDeadlock() {
396 return false;
397 }
398
399 # Return DB-style timestamp used for MySQL schema
400 function timestamp( $ts=0 ) {
401 return wfTimestamp(TS_DB,$ts);
402 }
403
404 /**
405 * Return aggregated value function call
406 */
407 function aggregateValue ($valuedata,$valuename='value') {
408 return $valuedata;
409 }
410
411
412 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
413 $message = "A database error has occurred\n" .
414 "Query: $sql\n" .
415 "Function: $fname\n" .
416 "Error: $errno $error\n";
417 wfDebugDieBacktrace($message);
418 }
419
420 /**
421 * @return string wikitext of a link to the server software's web site
422 */
423 function getSoftwareLink() {
424 return "[http://www.postgresql.org/ PostgreSQL]";
425 }
426
427 /**
428 * @return string Version information from the database
429 */
430 function getServerVersion() {
431 $res = $this->query( "SELECT version()" );
432 $row = $this->fetchRow( $res );
433 $version = $row[0];
434 $this->freeResult( $res );
435 return $version;
436 }
437
438 function setSchema($schema=false) {
439 $schemas=$this->mSchemas;
440 if ($schema) { array_unshift($schemas,$schema); }
441 $searchpath=$this->makeList($schemas,LIST_NAMES);
442 $this->query("SET search_path = $searchpath");
443 }
444 }
445
446 /**
447 * Just an alias.
448 * @package MediaWiki
449 */
450 class DatabasePostgreSQL extends DatabasePgsql {
451 }
452
453 ?>