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