Allow user to always preview text on editing ( implement http://bugzilla.wikipedia...
[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
64 $success = false;
65
66 if ( '' != $dbName ) {
67 # start a database connection
68 $hstring="";
69 if ($server!=false && $server!="") {
70 $hstring="host=$server ";
71 }
72 @$this->mConn = pg_connect("$hstring dbname=$dbName user=$user password=$password");
73 if ( $this->mConn == false ) {
74 wfDebug( "DB connection error\n" );
75 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
76 wfDebug( $this->lastError()."\n" );
77 } else {
78 $this->mOpened = true;
79 }
80 $this->query("SET search_path = $wgDBschema,public");
81 }
82 return $this->mConn;
83 }
84
85 /**
86 * Closes a database connection, if it is open
87 * Returns success, true if already closed
88 */
89 function close() {
90 $this->mOpened = false;
91 if ( $this->mConn ) {
92 return pg_close( $this->mConn );
93 } else {
94 return true;
95 }
96 }
97
98 function doQuery( $sql ) {
99 return $this->mLastResult=pg_query( $this->mConn , $sql);
100 }
101
102 function queryIgnore( $sql, $fname = '' ) {
103 return $this->query( $sql, $fname, true );
104 }
105
106 function freeResult( $res ) {
107 if ( !@pg_free_result( $res ) ) {
108 wfDebugDieBacktrace( "Unable to free PostgreSQL result\n" );
109 }
110 }
111
112 function fetchObject( $res ) {
113 @$row = pg_fetch_object( $res );
114 # FIXME: HACK HACK HACK HACK debug
115
116 # TODO:
117 # hashar : not sure if the following test really trigger if the object
118 # fetching failled.
119 if( pg_last_error($this->mConn) ) {
120 wfDebugDieBacktrace( 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
121 }
122 return $row;
123 }
124
125 function fetchRow( $res ) {
126 @$row = pg_fetch_array( $res );
127 if( pg_last_error($this->mConn) ) {
128 wfDebugDieBacktrace( 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
129 }
130 return $row;
131 }
132
133 function numRows( $res ) {
134 @$n = pg_num_rows( $res );
135 if( pg_last_error($this->mConn) ) {
136 wfDebugDieBacktrace( 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
137 }
138 return $n;
139 }
140 function numFields( $res ) { return pg_num_fields( $res ); }
141 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
142
143 /**
144 * This must be called after nextSequenceVal
145 */
146 function insertId() {
147 return $this->mInsertId;
148 }
149
150 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
151 function lastError() { return pg_last_error(); }
152 function lastErrno() { return 1; }
153
154 function affectedRows() {
155 return pg_affected_rows( $this->mLastResult );
156 }
157
158 /**
159 * Returns information about an index
160 * If errors are explicitly ignored, returns NULL on failure
161 */
162 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
163 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
164 $res = $this->query( $sql, $fname );
165 if ( !$res ) {
166 return NULL;
167 }
168
169 while ( $row = $this->fetchObject( $res ) ) {
170 if ( $row->Key_name == $index ) {
171 return $row;
172 }
173 }
174 return false;
175 }
176
177 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
178 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
179 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
180 $res = $this->query( $sql, $fname );
181 if ( !$res )
182 return NULL;
183 while ($row = $this->fetchObject( $res ))
184 return true;
185 return false;
186
187 }
188
189 function fieldInfo( $table, $field ) {
190 wfDebugDieBacktrace( 'Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre' );
191 /*
192 $res = $this->query( "SELECT * FROM '$table' LIMIT 1" );
193 $n = pg_num_fields( $res );
194 for( $i = 0; $i < $n; $i++ ) {
195 // FIXME
196 wfDebugDieBacktrace( "Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre" );
197 $meta = mysql_fetch_field( $res, $i );
198 if( $field == $meta->name ) {
199 return $meta;
200 }
201 }
202 return false;*/
203 }
204
205 function insertArray( $table, $a, $fname = 'Database::insertArray', $options = array() ) {
206 # PostgreSQL doesn't support options
207 # We have a go at faking one of them
208 # TODO: DELAYED, LOW_PRIORITY
209
210 if ( !is_array($options))
211 $options = array($options);
212
213 if ( in_array( 'IGNORE', $options ) )
214 $oldIgnore = $this->ignoreErrors( true );
215
216 # IGNORE is performed using single-row inserts, ignoring errors in each
217 # FIXME: need some way to distiguish between key collision and other types of error
218 $oldIgnore = $this->ignoreErrors( true );
219 if ( !is_array( reset( $a ) ) ) {
220 $a = array( $a );
221 }
222 foreach ( $a as $row ) {
223 parent::insertArray( $table, $row, $fname, array() );
224 }
225 $this->ignoreErrors( $oldIgnore );
226 $retVal = true;
227
228 if ( in_array( 'IGNORE', $options ) )
229 $this->ignoreErrors( $oldIgnore );
230
231 return $retVal;
232 }
233
234 function startTimer( $timeout )
235 {
236 global $IP;
237 wfDebugDieBacktrace( 'Database::startTimer() error : mysql_thread_id() not implemented for postgre' );
238 /*$tid = mysql_thread_id( $this->mConn );
239 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );*/
240 }
241
242 function tableName( $name ) {
243 # First run any transformations from the parent object
244 $name = parent::tableName( $name );
245
246 # Now quote PG reserved keywords
247 switch( $name ) {
248 case 'user':
249 return '"user"';
250 case 'old':
251 return '"old"';
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->getField(''," 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
437 /**
438 * Just an alias.
439 * @package MediaWiki
440 */
441 class DatabasePostgreSQL extends DatabasePgsql {
442 }
443
444 ?>