DB error log
[lhc/web/wiklou.git] / includes / DatabasePostgreSQL.php
1 <?php
2 # $Id$
3 #
4 # DO NOT USE !!! Unless you want to help developping it.
5 #
6 # This file is an attempt to port the mysql database layer to postgreSQL. The
7 # only thing done so far is s/mysql/pg/ and dieing if function haven't been
8 # ported.
9 #
10 # As said brion 07/06/2004 :
11 # "table definitions need to be changed. fulltext index needs to work differently
12 # things that use the last insert id need to be changed. Probably other things
13 # need to be changed. various semantics may be different."
14 #
15 # Hashar
16
17 require_once( "FulltextStoplist.php" );
18 require_once( "CacheManager.php" );
19
20 define( "DB_READ", -1 );
21 define( "DB_WRITE", -2 );
22 define( "DB_LAST", -3 );
23
24 define( "LIST_COMMA", 0 );
25 define( "LIST_AND", 1 );
26 define( "LIST_SET", 2 );
27
28 class Database {
29
30 #------------------------------------------------------------------------------
31 # Variables
32 #------------------------------------------------------------------------------
33 /* private */ var $mLastQuery = "";
34 /* private */ var $mBufferResults = true;
35 /* private */ var $mIgnoreErrors = false;
36
37 /* private */ var $mServer, $mUser, $mPassword, $mConn, $mDBname;
38 /* private */ var $mOut, $mDebug, $mOpened = false;
39
40 /* private */ var $mFailFunction;
41 /* private */ var $mLastResult;
42
43 #------------------------------------------------------------------------------
44 # Accessors
45 #------------------------------------------------------------------------------
46 # Set functions
47 # These set a variable and return the previous state
48
49 # Fail function, takes a Database as a parameter
50 # Set to false for default, 1 for ignore errors
51 function setFailFunction( $function ) { return wfSetVar( $this->mFailFunction, $function ); }
52
53 # Output page, used for reporting errors
54 # FALSE means discard output
55 function &setOutputPage( &$out ) { $this->mOut =& $out; }
56
57 # Boolean, controls output of large amounts of debug information
58 function setDebug( $debug ) { return wfSetVar( $this->mDebug, $debug ); }
59
60 # Turns buffering of SQL result sets on (true) or off (false). Default is
61 # "on" and it should not be changed without good reasons.
62 function setBufferResults( $buffer ) { return wfSetVar( $this->mBufferResults, $buffer ); }
63
64 # Turns on (false) or off (true) the automatic generation and sending
65 # of a "we're sorry, but there has been a database error" page on
66 # database errors. Default is on (false). When turned off, the
67 # code should use wfLastErrno() and wfLastError() to handle the
68 # situation as appropriate.
69 function setIgnoreErrors( $ignoreErrors ) { return wfSetVar( $this->mIgnoreErrors, $ignoreErrors ); }
70
71 # Get functions
72
73 function lastQuery() { return $this->mLastQuery; }
74 function isOpen() { return $this->mOpened; }
75
76 #------------------------------------------------------------------------------
77 # Other functions
78 #------------------------------------------------------------------------------
79
80 function Database()
81 {
82 global $wgOut;
83 # Can't get a reference if it hasn't been set yet
84 if ( !isset( $wgOut ) ) {
85 $wgOut = NULL;
86 }
87 $this->mOut =& $wgOut;
88
89 }
90
91 /* static */ function newFromParams( $server, $user, $password, $dbName,
92 $failFunction = false, $debug = false, $bufferResults = true, $ignoreErrors = false )
93 {
94 $db = new Database;
95 $db->mFailFunction = $failFunction;
96 $db->mIgnoreErrors = $ignoreErrors;
97 $db->mDebug = $debug;
98 $db->mBufferResults = $bufferResults;
99 $db->open( $server, $user, $password, $dbName );
100 return $db;
101 }
102
103 # Usually aborts on failure
104 # If the failFunction is set to a non-zero integer, returns success
105 function open( $server, $user, $password, $dbName )
106 {
107 global $wgEmergencyContact;
108
109 $this->close();
110 $this->mServer = $server;
111 $this->mUser = $user;
112 $this->mPassword = $password;
113 $this->mDBname = $dbName;
114
115 $success = false;
116
117
118 if ( "" != $dbName ) {
119 # start a database connection
120 @$this->mConn = pg_connect("host=$server dbname=$dbName user=$user password=$password");
121 if ( $this->mConn == false ) {
122 wfDebug( "DB connection error\n" );
123 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
124 wfDebug( $this->lastError()."\n" );
125 } else {
126 $this->mOpened = true;
127 }
128 }
129 return $this->mConn;
130 }
131
132 # Closes a database connection, if it is open
133 # Returns success, true if already closed
134 function close()
135 {
136 $this->mOpened = false;
137 if ( $this->mConn ) {
138 return pg_close( $this->mConn );
139 } else {
140 return true;
141 }
142 }
143
144 /* private */ function reportConnectionError( $msg = "")
145 {
146 if ( $this->mFailFunction ) {
147 if ( !is_int( $this->mFailFunction ) ) {
148 $this->$mFailFunction( $this );
149 }
150 } else {
151 wfEmergencyAbort( $this );
152 }
153 }
154
155 # Usually aborts on failure
156 # If errors are explicitly ignored, returns success
157 function query( $sql, $fname = "" )
158 {
159 global $wgProfiling;
160
161 if ( $wgProfiling ) {
162 # generalizeSQL will probably cut down the query to reasonable
163 # logging size most of the time. The substr is really just a sanity check.
164 $profName = "query: " . substr( Database::generalizeSQL( $sql ), 0, 255 );
165 wfProfileIn( $profName );
166 }
167
168 $this->mLastQuery = $sql;
169
170 if ( $this->mDebug ) {
171 $sqlx = substr( $sql, 0, 500 );
172 $sqlx = wordwrap(strtr($sqlx,"\t\n"," "));
173 wfDebug( "SQL: $sqlx\n" );
174 }
175
176 $ret = pg_query( $this->mConn , $sql);
177 $this->mLastResult = $ret;
178 if ( false == $ret ) {
179 $error = pg_last_error( $this->mConn );
180 // TODO FIXME : no error number function in postgre
181 // $errno = mysql_errno( $this->mConn );
182 if( $this->mIgnoreErrors ) {
183 wfDebug("SQL ERROR (ignored): " . $error . "\n");
184 } else {
185 wfDebug("SQL ERROR: " . $error . "\n");
186 if ( $this->mOut ) {
187 // this calls wfAbruptExit()
188 $this->mOut->databaseError( $fname, $sql, $error, 0 );
189 }
190 }
191 }
192
193 if ( $wgProfiling ) {
194 wfProfileOut( $profName );
195 }
196 return $ret;
197 }
198
199 function freeResult( $res ) {
200 if ( !@pg_free_result( $res ) ) {
201 wfDebugDieBacktrace( "Unable to free PostgreSQL result\n" );
202 }
203 }
204 function fetchObject( $res ) {
205 @$row = pg_fetch_object( $res );
206 # FIXME: HACK HACK HACK HACK debug
207
208 # TODO:
209 # hashar : not sure if the following test really trigger if the object
210 # fetching failled.
211 if( pg_last_error($this->mConn) ) {
212 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( pg_last_error($this->mConn) ) );
213 }
214 return $row;
215 }
216
217 function fetchRow( $res ) {
218 @$row = pg_fetch_array( $res );
219 if( pg_last_error($this->mConn) ) {
220 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( pg_last_error($this->mConn) ) );
221 }
222 return $row;
223 }
224
225 function numRows( $res ) {
226 @$n = pg_num_rows( $res );
227 if( pg_last_error($this->mConn) ) {
228 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( pg_last_error($this->mConn) ) );
229 }
230 return $n;
231 }
232 function numFields( $res ) { return pg_num_fields( $res ); }
233 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
234 // TODO FIXME: need to implement something here
235 function insertId() {
236 //return mysql_insert_id( $this->mConn );
237 wfDebugDieBacktrace( "Database::insertId() error : not implemented for postgre, use sequences" );
238 }
239 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
240 function lastErrno() { return $this->lastError(); }
241 function lastError() { return pg_last_error(); }
242 function affectedRows() {
243 return pg_affected_rows( $this->mLastResult );
244 }
245
246 # Simple UPDATE wrapper
247 # Usually aborts on failure
248 # If errors are explicitly ignored, returns success
249 function set( $table, $var, $value, $cond, $fname = "Database::set" )
250 {
251 $sql = "UPDATE \"$table\" SET \"$var\" = '" .
252 wfStrencode( $value ) . "' WHERE ($cond)";
253 return !!$this->query( $sql, DB_WRITE, $fname );
254 }
255
256 # Simple SELECT wrapper, returns a single field, input must be encoded
257 # Usually aborts on failure
258 # If errors are explicitly ignored, returns FALSE on failure
259 function get( $table, $var, $cond, $fname = "Database::get" )
260 {
261 $from=$table?" FROM \"$table\" ":"";
262 $where=$cond?" WHERE ($cond)":"";
263
264 $sql = "SELECT $var $from $where";
265
266 $result = $this->query( $sql, DB_READ, $fname );
267
268 $ret = "";
269 if ( pg_num_rows( $result ) > 0 ) {
270 $s = pg_fetch_array( $result );
271 $ret = $s[0];
272 pg_free_result( $result );
273 }
274 return $ret;
275 }
276
277 # More complex SELECT wrapper, single row only
278 # Aborts or returns FALSE on error
279 # Takes an array of selected variables, and a condition map, which is ANDed
280 # e.g. getArray( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
281 # would return an object where $obj->cur_id is the ID of the Astronomy article
282 function getArray( $table, $vars, $conds, $fname = "Database::getArray" )
283 {
284 $vars = implode( ",", $vars );
285 $where = Database::makeList( $conds, LIST_AND );
286 $sql = "SELECT \"$vars\" FROM \"$table\" WHERE $where LIMIT 1";
287 $res = $this->query( $sql, $fname );
288 if ( $res === false || !$this->numRows( $res ) ) {
289 return false;
290 }
291 $obj = $this->fetchObject( $res );
292 $this->freeResult( $res );
293 return $obj;
294 }
295
296 # Removes most variables from an SQL query and replaces them with X or N for numbers.
297 # It's only slightly flawed. Don't use for anything important.
298 /* static */ function generalizeSQL( $sql )
299 {
300 # This does the same as the regexp below would do, but in such a way
301 # as to avoid crashing php on some large strings.
302 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
303
304 $sql = str_replace ( "\\\\", "", $sql);
305 $sql = str_replace ( "\\'", "", $sql);
306 $sql = str_replace ( "\\\"", "", $sql);
307 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
308 $sql = preg_replace ('/".*"/s', "'X'", $sql);
309
310 # All newlines, tabs, etc replaced by single space
311 $sql = preg_replace ( "/\s+/", " ", $sql);
312
313 # All numbers => N
314 $sql = preg_replace ('/-?[0-9]+/s', "N", $sql);
315
316 return $sql;
317 }
318
319 # Determines whether a field exists in a table
320 # Usually aborts on failure
321 # If errors are explicitly ignored, returns NULL on failure
322 function fieldExists( $table, $field, $fname = "Database::fieldExists" )
323 {
324 $res = $this->query( "DESCRIBE '$table'", DB_READ, $fname );
325 if ( !$res ) {
326 return NULL;
327 }
328
329 $found = false;
330
331 while ( $row = $this->fetchObject( $res ) ) {
332 if ( $row->Field == $field ) {
333 $found = true;
334 break;
335 }
336 }
337 return $found;
338 }
339
340 # Determines whether an index exists
341 # Usually aborts on failure
342 # If errors are explicitly ignored, returns NULL on failure
343 function indexExists( $table, $index, $fname = "Database::indexExists" )
344 {
345 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
346 $res = $this->query( $sql, DB_READ, $fname );
347 if ( !$res ) {
348 return NULL;
349 }
350
351 $found = false;
352
353 while ( $row = $this->fetchObject( $res ) ) {
354 if ( $row->Key_name == $index ) {
355 $found = true;
356 break;
357 }
358 }
359 return $found;
360 }
361
362 function tableExists( $table )
363 {
364 $old = $this->mIgnoreErrors;
365 $this->mIgnoreErrors = true;
366 $res = $this->query( "SELECT 1 FROM '$table' LIMIT 1" );
367 $this->mIgnoreErrors = $old;
368 if( $res ) {
369 $this->freeResult( $res );
370 return true;
371 } else {
372 return false;
373 }
374 }
375
376 function fieldInfo( $table, $field )
377 {
378 $res = $this->query( "SELECT * FROM '$table' LIMIT 1" );
379 $n = pg_num_fields( $res );
380 for( $i = 0; $i < $n; $i++ ) {
381 // FIXME
382 wfDebugDieBacktrace( "Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre" );
383 $meta = mysql_fetch_field( $res, $i );
384 if( $field == $meta->name ) {
385 return $meta;
386 }
387 }
388 return false;
389 }
390
391 # INSERT wrapper, inserts an array into a table
392 # Keys are field names, values are values
393 # Usually aborts on failure
394 # If errors are explicitly ignored, returns success
395 function insertArray( $table, $a, $fname = "Database::insertArray" )
396 {
397 $sql1 = "INSERT INTO \"$table\" (";
398 $sql2 = "VALUES (" . Database::makeList( $a );
399 $first = true;
400 foreach ( $a as $field => $value ) {
401 if ( !$first ) {
402 $sql1 .= ",";
403 }
404 $first = false;
405 $sql1 .= $field;
406 }
407 $sql = "$sql1) $sql2)";
408 return !!$this->query( $sql, $fname );
409 }
410
411 # A cross between insertArray and getArray, takes a condition array and a SET array
412 function updateArray( $table, $values, $conds, $fname = "Database::updateArray" )
413 {
414 $sql = "UPDATE '$table' SET " . $this->makeList( $values, LIST_SET );
415 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
416 $this->query( $sql, $fname );
417 }
418
419 # Makes a wfStrencoded list from an array
420 # $mode: LIST_COMMA - comma separated, no field names
421 # LIST_AND - ANDed WHERE clause (without the WHERE)
422 # LIST_SET - comma separated with field names, like a SET clause
423 /* static */ function makeList( $a, $mode = LIST_COMMA )
424 {
425 $first = true;
426 $list = "";
427 foreach ( $a as $field => $value ) {
428 if ( !$first ) {
429 if ( $mode == LIST_AND ) {
430 $list .= " AND ";
431 } else {
432 $list .= ",";
433 }
434 } else {
435 $first = false;
436 }
437 if ( $mode == LIST_AND || $mode == LIST_SET ) {
438 $list .= "$field=";
439 }
440 if ( !is_numeric( $value ) ) {
441 $list .= "'" . wfStrencode( $value ) . "'";
442 } else {
443 $list .= $value;
444 }
445 }
446 return $list;
447 }
448
449 function startTimer( $timeout )
450 {
451 global $IP;
452 wfDebugDieBacktrace( "Database::startTimer() error : mysql_thread_id() not implemented for postgre" );
453 $tid = mysql_thread_id( $this->mConn );
454 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );
455 }
456
457 function stopTimer()
458 {
459 }
460
461 }
462
463 #------------------------------------------------------------------------------
464 # Global functions
465 #------------------------------------------------------------------------------
466
467 /* Standard fail function, called by default when a connection cannot be established
468 Displays the file cache if possible */
469 function wfEmergencyAbort( &$conn ) {
470 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
471
472 header( "Content-type: text/html; charset=$wgOutputEncoding" );
473 $msg = $wgSiteNotice;
474 if($msg == "") $msg = wfMsgNoDB( "noconnect" );
475 $text = $msg;
476
477 if($wgUseFileCache) {
478 if($wgTitle) {
479 $t =& $wgTitle;
480 } else {
481 if($title) {
482 $t = Title::newFromURL( $title );
483 } elseif (@$_REQUEST['search']) {
484 $search = $_REQUEST['search'];
485 echo wfMsgNoDB( "searchdisabled" );
486 echo wfMsgNoDB( "googlesearch", htmlspecialchars( $search ), $wgInputEncoding );
487 wfAbruptExit();
488 } else {
489 $t = Title::newFromText( wfMsgNoDB( "mainpage" ) );
490 }
491 }
492
493 $cache = new CacheManager( $t );
494 if( $cache->isFileCached() ) {
495 $msg = "<p style='color: red'><b>$msg<br />\n" .
496 wfMsgNoDB( "cachederror" ) . "</b></p>\n";
497
498 $tag = "<div id='article'>";
499 $text = str_replace(
500 $tag,
501 $tag . $msg,
502 $cache->fetchPageText() );
503 }
504 }
505
506 /* Don't cache error pages! They cause no end of trouble... */
507 header( "Cache-control: none" );
508 header( "Pragma: nocache" );
509 echo $text;
510 wfAbruptExit();
511 }
512
513 function wfStrencode( $s )
514 {
515 return pg_escape_string( $s );
516 }
517
518 # Use PostgreSQL timestamp without timezone data type
519 function wfTimestamp2Unix( $ts ) {
520 return gmmktime( ( (int)substr( $ts, 11, 2) ),
521 (int)substr( $ts, 14, 2 ), (int)substr( $ts, 17, 2 ),
522 (int)substr( $ts, 5, 2 ), (int)substr( $ts, 8, 2 ),
523 (int)substr( $ts, 0, 4 ) );
524 }
525
526 function wfUnix2Timestamp( $unixtime ) {
527 return gmdate( "Y-m-d H:i:s", $unixtime );
528 }
529
530 function wfTimestampNow() {
531 # return NOW
532 return gmdate( "Y-m-d H:i:s" );
533 }
534
535 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
536 function wfInvertTimestamp( $ts ) {
537 $ts=preg_replace("/\D/","",$ts);
538 return strtr(
539 $ts,
540 "0123456789",
541 "9876543210"
542 );
543 }
544
545 function wfLimitResult( $limit, $offset ) {
546 return " LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
547 }
548
549 ?>