more cssification of diff rendering, some " -> ' in diff engine
[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 ) { return wfSetRef( $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 }
126 }
127 return $this->mConn;
128 }
129
130 # Closes a database connection, if it is open
131 # Returns success, true if already closed
132 function close()
133 {
134 $this->mOpened = false;
135 if ( $this->mConn ) {
136 return pg_close( $this->mConn );
137 } else {
138 return true;
139 }
140 }
141
142 /* private */ function reportConnectionError( $msg = "")
143 {
144 if ( $this->mFailFunction ) {
145 if ( !is_int( $this->mFailFunction ) ) {
146 $this->$mFailFunction( $this );
147 }
148 } else {
149 wfEmergencyAbort( $this );
150 }
151 }
152
153 # Usually aborts on failure
154 # If errors are explicitly ignored, returns success
155 function query( $sql, $fname = "" )
156 {
157 global $wgProfiling;
158
159 if ( $wgProfiling ) {
160 # generalizeSQL will probably cut down the query to reasonable
161 # logging size most of the time. The substr is really just a sanity check.
162 $profName = "query: " . substr( Database::generalizeSQL( $sql ), 0, 255 );
163 wfProfileIn( $profName );
164 }
165
166 $this->mLastQuery = $sql;
167
168 if ( $this->mDebug ) {
169 $sqlx = substr( $sql, 0, 500 );
170 $sqlx = wordwrap(strtr($sqlx,"\t\n"," "));
171 wfDebug( "SQL: $sqlx\n" );
172 }
173
174 $ret = pg_query( $this->mConn , $sql);
175 $this->mLastResult = $ret;
176 if ( false == $ret ) {
177 $error = pg_last_error( $this->mConn );
178 // TODO FIXME : no error number function in postgre
179 // $errno = mysql_errno( $this->mConn );
180 if( $this->mIgnoreErrors ) {
181 wfDebug("SQL ERROR (ignored): " . $error . "\n");
182 } else {
183 wfDebug("SQL ERROR: " . $error . "\n");
184 if ( $this->mOut ) {
185 // this calls wfAbruptExit()
186 $this->mOut->databaseError( $fname, $sql, $error, 0 );
187 }
188 }
189 }
190
191 if ( $wgProfiling ) {
192 wfProfileOut( $profName );
193 }
194 return $ret;
195 }
196
197 function freeResult( $res ) {
198 if ( !@pg_free_result( $res ) ) {
199 wfDebugDieBacktrace( "Unable to free PostgreSQL result\n" );
200 }
201 }
202 function fetchObject( $res ) {
203 @$row = pg_fetch_object( $res );
204 # FIXME: HACK HACK HACK HACK debug
205
206 # TODO:
207 # hashar : not sure if the following test really trigger if the object
208 # fetching failled.
209 if( pg_last_error($this->mConn) ) {
210 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( pg_last_error($this->mConn) ) );
211 }
212 return $row;
213 }
214
215 function fetchRow( $res ) {
216 @$row = pg_fetch_array( $res );
217 if( pg_last_error($this->mConn) ) {
218 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( pg_last_error($this->mConn) ) );
219 }
220 return $row;
221 }
222
223 function numRows( $res ) {
224 @$n = pg_num_rows( $res );
225 if( pg_last_error($this->mConn) ) {
226 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( pg_last_error($this->mConn) ) );
227 }
228 return $n;
229 }
230 function numFields( $res ) { return pg_num_fields( $res ); }
231 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
232 // TODO FIXME: need to implement something here
233 function insertId() {
234 //return mysql_insert_id( $this->mConn );
235 wfDebugDieBacktrace( "Database::insertId() error : not implemented for postgre, use sequences" );
236 }
237 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
238 function lastErrno() { return $this->lastError(); }
239 function lastError() { return pg_last_error(); }
240 function affectedRows() {
241 return pg_affected_rows( $this->mLastResult );
242 }
243
244 # Simple UPDATE wrapper
245 # Usually aborts on failure
246 # If errors are explicitly ignored, returns success
247 function set( $table, $var, $value, $cond, $fname = "Database::set" )
248 {
249 $sql = "UPDATE \"$table\" SET \"$var\" = '" .
250 wfStrencode( $value ) . "' WHERE ($cond)";
251 return !!$this->query( $sql, DB_WRITE, $fname );
252 }
253
254 # Simple SELECT wrapper, returns a single field, input must be encoded
255 # Usually aborts on failure
256 # If errors are explicitly ignored, returns FALSE on failure
257 function get( $table, $var, $cond, $fname = "Database::get" )
258 {
259 $from=$table?" FROM \"$table\" ":"";
260 $where=$cond?" WHERE ($cond)":"";
261
262 $sql = "SELECT $var $from $where";
263
264 $result = $this->query( $sql, DB_READ, $fname );
265
266 $ret = "";
267 if ( pg_num_rows( $result ) > 0 ) {
268 $s = pg_fetch_array( $result );
269 $ret = $s[0];
270 pg_free_result( $result );
271 }
272 return $ret;
273 }
274
275 # More complex SELECT wrapper, single row only
276 # Aborts or returns FALSE on error
277 # Takes an array of selected variables, and a condition map, which is ANDed
278 # e.g. getArray( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
279 # would return an object where $obj->cur_id is the ID of the Astronomy article
280 function getArray( $table, $vars, $conds, $fname = "Database::getArray" )
281 {
282 $vars = implode( ",", $vars );
283 $where = Database::makeList( $conds, LIST_AND );
284 $sql = "SELECT \"$vars\" FROM \"$table\" WHERE $where LIMIT 1";
285 $res = $this->query( $sql, $fname );
286 if ( $res === false || !$this->numRows( $res ) ) {
287 return false;
288 }
289 $obj = $this->fetchObject( $res );
290 $this->freeResult( $res );
291 return $obj;
292 }
293
294 # Removes most variables from an SQL query and replaces them with X or N for numbers.
295 # It's only slightly flawed. Don't use for anything important.
296 /* static */ function generalizeSQL( $sql )
297 {
298 # This does the same as the regexp below would do, but in such a way
299 # as to avoid crashing php on some large strings.
300 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
301
302 $sql = str_replace ( "\\\\", "", $sql);
303 $sql = str_replace ( "\\'", "", $sql);
304 $sql = str_replace ( "\\\"", "", $sql);
305 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
306 $sql = preg_replace ('/".*"/s', "'X'", $sql);
307
308 # All newlines, tabs, etc replaced by single space
309 $sql = preg_replace ( "/\s+/", " ", $sql);
310
311 # All numbers => N
312 $sql = preg_replace ('/-?[0-9]+/s', "N", $sql);
313
314 return $sql;
315 }
316
317 # Determines whether a field exists in a table
318 # Usually aborts on failure
319 # If errors are explicitly ignored, returns NULL on failure
320 function fieldExists( $table, $field, $fname = "Database::fieldExists" )
321 {
322 $res = $this->query( "DESCRIBE '$table'", DB_READ, $fname );
323 if ( !$res ) {
324 return NULL;
325 }
326
327 $found = false;
328
329 while ( $row = $this->fetchObject( $res ) ) {
330 if ( $row->Field == $field ) {
331 $found = true;
332 break;
333 }
334 }
335 return $found;
336 }
337
338 # Determines whether an index exists
339 # Usually aborts on failure
340 # If errors are explicitly ignored, returns NULL on failure
341 function indexExists( $table, $index, $fname = "Database::indexExists" )
342 {
343 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
344 $res = $this->query( $sql, DB_READ, $fname );
345 if ( !$res ) {
346 return NULL;
347 }
348
349 $found = false;
350
351 while ( $row = $this->fetchObject( $res ) ) {
352 if ( $row->Key_name == $index ) {
353 $found = true;
354 break;
355 }
356 }
357 return $found;
358 }
359
360 function tableExists( $table )
361 {
362 $old = $this->mIgnoreErrors;
363 $this->mIgnoreErrors = true;
364 $res = $this->query( "SELECT 1 FROM '$table' LIMIT 1" );
365 $this->mIgnoreErrors = $old;
366 if( $res ) {
367 $this->freeResult( $res );
368 return true;
369 } else {
370 return false;
371 }
372 }
373
374 function fieldInfo( $table, $field )
375 {
376 $res = $this->query( "SELECT * FROM '$table' LIMIT 1" );
377 $n = pg_num_fields( $res );
378 for( $i = 0; $i < $n; $i++ ) {
379 // FIXME
380 wfDebugDieBacktrace( "Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre" );
381 $meta = mysql_fetch_field( $res, $i );
382 if( $field == $meta->name ) {
383 return $meta;
384 }
385 }
386 return false;
387 }
388
389 # INSERT wrapper, inserts an array into a table
390 # Keys are field names, values are values
391 # Usually aborts on failure
392 # If errors are explicitly ignored, returns success
393 function insertArray( $table, $a, $fname = "Database::insertArray" )
394 {
395 $sql1 = "INSERT INTO \"$table\" (";
396 $sql2 = "VALUES (" . Database::makeList( $a );
397 $first = true;
398 foreach ( $a as $field => $value ) {
399 if ( !$first ) {
400 $sql1 .= ",";
401 }
402 $first = false;
403 $sql1 .= $field;
404 }
405 $sql = "$sql1) $sql2)";
406 return !!$this->query( $sql, $fname );
407 }
408
409 # A cross between insertArray and getArray, takes a condition array and a SET array
410 function updateArray( $table, $values, $conds, $fname = "Database::updateArray" )
411 {
412 $sql = "UPDATE '$table' SET " . $this->makeList( $values, LIST_SET );
413 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
414 $this->query( $sql, $fname );
415 }
416
417 # Makes a wfStrencoded list from an array
418 # $mode: LIST_COMMA - comma separated, no field names
419 # LIST_AND - ANDed WHERE clause (without the WHERE)
420 # LIST_SET - comma separated with field names, like a SET clause
421 /* static */ function makeList( $a, $mode = LIST_COMMA )
422 {
423 $first = true;
424 $list = "";
425 foreach ( $a as $field => $value ) {
426 if ( !$first ) {
427 if ( $mode == LIST_AND ) {
428 $list .= " AND ";
429 } else {
430 $list .= ",";
431 }
432 } else {
433 $first = false;
434 }
435 if ( $mode == LIST_AND || $mode == LIST_SET ) {
436 $list .= "$field=";
437 }
438 if ( !is_numeric( $value ) ) {
439 $list .= "'" . wfStrencode( $value ) . "'";
440 } else {
441 $list .= $value;
442 }
443 }
444 return $list;
445 }
446
447 function startTimer( $timeout )
448 {
449 global $IP;
450 wfDebugDieBacktrace( "Database::startTimer() error : mysql_thread_id() not implemented for postgre" );
451 $tid = mysql_thread_id( $this->mConn );
452 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );
453 }
454
455 function stopTimer()
456 {
457 }
458
459 }
460
461 #------------------------------------------------------------------------------
462 # Global functions
463 #------------------------------------------------------------------------------
464
465 /* Standard fail function, called by default when a connection cannot be established
466 Displays the file cache if possible */
467 function wfEmergencyAbort( &$conn ) {
468 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
469
470 header( "Content-type: text/html; charset=$wgOutputEncoding" );
471 $msg = $wgSiteNotice;
472 if($msg == "") $msg = wfMsgNoDB( "noconnect" );
473 $text = $msg;
474
475 if($wgUseFileCache) {
476 if($wgTitle) {
477 $t =& $wgTitle;
478 } else {
479 if($title) {
480 $t = Title::newFromURL( $title );
481 } elseif (@$_REQUEST['search']) {
482 $search = $_REQUEST['search'];
483 echo wfMsgNoDB( "searchdisabled" );
484 echo wfMsgNoDB( "googlesearch", htmlspecialchars( $search ), $wgInputEncoding );
485 wfAbruptExit();
486 } else {
487 $t = Title::newFromText( wfMsgNoDB( "mainpage" ) );
488 }
489 }
490
491 $cache = new CacheManager( $t );
492 if( $cache->isFileCached() ) {
493 $msg = "<p style='color: red'><b>$msg<br />\n" .
494 wfMsgNoDB( "cachederror" ) . "</b></p>\n";
495
496 $tag = "<div id='article'>";
497 $text = str_replace(
498 $tag,
499 $tag . $msg,
500 $cache->fetchPageText() );
501 }
502 }
503
504 /* Don't cache error pages! They cause no end of trouble... */
505 header( "Cache-control: none" );
506 header( "Pragma: nocache" );
507 echo $text;
508 wfAbruptExit();
509 }
510
511 function wfStrencode( $s )
512 {
513 return pg_escape_string( $s );
514 }
515
516 # Use PostgreSQL timestamp without timezone data type
517 function wfTimestamp2Unix( $ts ) {
518 return gmmktime( ( (int)substr( $ts, 11, 2) ),
519 (int)substr( $ts, 14, 2 ), (int)substr( $ts, 17, 2 ),
520 (int)substr( $ts, 5, 2 ), (int)substr( $ts, 8, 2 ),
521 (int)substr( $ts, 0, 4 ) );
522 }
523
524 function wfUnix2Timestamp( $unixtime ) {
525 return gmdate( "Y-m-d H:i:s", $unixtime );
526 }
527
528 function wfTimestampNow() {
529 # return NOW
530 return gmdate( "Y-m-d H:i:s" );
531 }
532
533 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
534 function wfInvertTimestamp( $ts ) {
535 $ts=preg_replace("/\D/","",$ts);
536 return strtr(
537 $ts,
538 "0123456789",
539 "9876543210"
540 );
541 }
542
543 function wfLimitResult( $limit, $offset ) {
544 return " LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
545 }
546
547 ?>