4 # DO NOT USE !!! Unless you want to help developping it.
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
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."
17 require_once( "FulltextStoplist.php" );
18 require_once( "CacheManager.php" );
20 define( "DB_READ", -1 );
21 define( "DB_WRITE", -2 );
22 define( "DB_LAST", -3 );
24 define( "LIST_COMMA", 0 );
25 define( "LIST_AND", 1 );
26 define( "LIST_SET", 2 );
30 #------------------------------------------------------------------------------
32 #------------------------------------------------------------------------------
33 /* private */ var $mLastQuery = "";
34 /* private */ var $mBufferResults = true;
35 /* private */ var $mIgnoreErrors = false;
37 /* private */ var $mServer, $mUser, $mPassword, $mConn, $mDBname;
38 /* private */ var $mOut, $mDebug, $mOpened = false;
40 /* private */ var $mFailFunction;
42 #------------------------------------------------------------------------------
44 #------------------------------------------------------------------------------
46 # These set a variable and return the previous state
48 # Fail function, takes a Database as a parameter
49 # Set to false for default, 1 for ignore errors
50 function setFailFunction( $function ) { return wfSetVar( $this->mFailFunction
, $function ); }
52 # Output page, used for reporting errors
53 # FALSE means discard output
54 function &setOutputPage( &$out ) { return wfSetRef( $this->mOut
, $out ); }
56 # Boolean, controls output of large amounts of debug information
57 function setDebug( $debug ) { return wfSetVar( $this->mDebug
, $debug ); }
59 # Turns buffering of SQL result sets on (true) or off (false). Default is
60 # "on" and it should not be changed without good reasons.
61 function setBufferResults( $buffer ) { return wfSetVar( $this->mBufferResults
, $buffer ); }
63 # Turns on (false) or off (true) the automatic generation and sending
64 # of a "we're sorry, but there has been a database error" page on
65 # database errors. Default is on (false). When turned off, the
66 # code should use wfLastErrno() and wfLastError() to handle the
67 # situation as appropriate.
68 function setIgnoreErrors( $ignoreErrors ) { return wfSetVar( $this->mIgnoreErrors
, $ignoreErrors ); }
72 function lastQuery() { return $this->mLastQuery
; }
73 function isOpen() { return $this->mOpened
; }
75 #------------------------------------------------------------------------------
77 #------------------------------------------------------------------------------
82 # Can't get a reference if it hasn't been set yet
83 if ( !isset( $wgOut ) ) {
86 $this->mOut
=& $wgOut;
90 /* static */ function newFromParams( $server, $user, $password, $dbName,
91 $failFunction = false, $debug = false, $bufferResults = true, $ignoreErrors = false )
94 $db->mFailFunction
= $failFunction;
95 $db->mIgnoreErrors
= $ignoreErrors;
97 $db->mBufferResults
= $bufferResults;
98 $db->open( $server, $user, $password, $dbName );
102 # Usually aborts on failure
103 # If the failFunction is set to a non-zero integer, returns success
104 function open( $server, $user, $password, $dbName )
106 global $wgEmergencyContact;
109 $this->mServer
= $server;
110 $this->mUser
= $user;
111 $this->mPassword
= $password;
112 $this->mDBname
= $dbName;
117 if ( "" != $dbName ) {
118 # start a database connection
119 @$this->mConn
= pg_connect("host=$server dbname=$dbName user=$user password=$password");
120 if ( $this->mConn
== false ) {
121 wfDebug( "DB connection error\n" );
122 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
123 wfDebug( $this->lastError()."\n" );
129 # Closes a database connection, if it is open
130 # Returns success, true if already closed
133 $this->mOpened
= false;
134 if ( $this->mConn
) {
135 return pg_close( $this->mConn
);
141 /* private */ function reportConnectionError( $msg = "")
143 if ( $this->mFailFunction
) {
144 if ( !is_int( $this->mFailFunction
) ) {
145 $this->$mFailFunction( $this );
148 wfEmergencyAbort( $this );
152 # Usually aborts on failure
153 # If errors are explicitly ignored, returns success
154 function query( $sql, $fname = "" )
158 if ( $wgProfiling ) {
159 # generalizeSQL will probably cut down the query to reasonable
160 # logging size most of the time. The substr is really just a sanity check.
161 $profName = "query: " . substr( Database
::generalizeSQL( $sql ), 0, 255 );
162 wfProfileIn( $profName );
165 $this->mLastQuery
= $sql;
167 if ( $this->mDebug
) {
168 $sqlx = substr( $sql, 0, 500 );
169 $sqlx = wordwrap(strtr($sqlx,"\t\n"," "));
170 wfDebug( "SQL: $sqlx\n" );
173 $ret = pg_query( $this->mConn
, $sql);
174 if ( false === $ret ) {
175 $error = pg_last_error( $this->mConn
);
176 // TODO FIXME : no error number function in postgre
177 // $errno = mysql_errno( $this->mConn );
178 if( $this->mIgnoreErrors
) {
179 wfDebug("SQL ERROR (ignored): " . $error . "\n");
181 wfDebug("SQL ERROR: " . $error . "\n");
183 // this calls wfAbruptExit()
184 $this->mOut
->databaseError( $fname, $sql, $error, 0 );
189 if ( $wgProfiling ) {
190 wfProfileOut( $profName );
195 function freeResult( $res ) {
196 if ( !@pg_free_result
( $res ) ) {
197 wfDebugDieBacktrace( "Unable to free PostgreSQL result\n" );
200 function fetchObject( $res ) {
201 @$row = pg_fetch_object( $res );
202 # FIXME: HACK HACK HACK HACK debug
205 # hashar : not sure if the following test really trigger if the object
207 if( pg_last_error($this->mConn
) ) {
208 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( pg_last_error($this->mConn
) ) );
213 function fetchRow( $res ) {
214 @$row = pg_fetch_array( $res );
215 if( pg_last_error($this->mConn
) ) {
216 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( pg_last_error($this->mConn
) ) );
221 function numRows( $res ) {
222 @$n = pg_num_rows( $res );
223 if( pg_last_error($this->mConn
) ) {
224 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( pg_last_error($this->mConn
) ) );
228 function numFields( $res ) { return pg_num_fields( $res ); }
229 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
230 // TODO FIXME: need to implement something here
231 function insertId() {
232 //return mysql_insert_id( $this->mConn );
233 wfDebugDieBacktrace( "Database::insertId() error : not implemented for postgre" );
235 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
236 function lastErrno() { return $this->lastError(); }
237 function lastError() { return pg_last_error(); }
238 function affectedRows() { return pg_affected_rows( $this->mConn
); }
240 # Simple UPDATE wrapper
241 # Usually aborts on failure
242 # If errors are explicitly ignored, returns success
243 function set( $table, $var, $value, $cond, $fname = "Database::set" )
245 $sql = "UPDATE \"$table\" SET \"$var\" = '" .
246 wfStrencode( $value ) . "' WHERE ($cond)";
247 return !!$this->query( $sql, DB_WRITE
, $fname );
250 # Simple SELECT wrapper, returns a single field, input must be encoded
251 # Usually aborts on failure
252 # If errors are explicitly ignored, returns FALSE on failure
253 function get( $table, $var, $cond, $fname = "Database::get" )
255 $sql = "SELECT \"$var\" FROM \"$table\" WHERE ($cond)";
256 $result = $this->query( $sql, DB_READ
, $fname );
259 if ( pg_num_rows( $result ) > 0 ) {
260 $s = pg_fetch_object( $result );
262 pg_free_result( $result );
267 # More complex SELECT wrapper, single row only
268 # Aborts or returns FALSE on error
269 # Takes an array of selected variables, and a condition map, which is ANDed
270 # e.g. getArray( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
271 # would return an object where $obj->cur_id is the ID of the Astronomy article
272 function getArray( $table, $vars, $conds, $fname = "Database::getArray" )
274 $vars = implode( ",", $vars );
275 $where = Database
::makeList( $conds, LIST_AND
);
276 $sql = "SELECT \"$vars\" FROM \"$table\" WHERE $where LIMIT 1";
277 $res = $this->query( $sql, $fname );
278 if ( $res === false ||
!$this->numRows( $res ) ) {
281 $obj = $this->fetchObject( $res );
282 $this->freeResult( $res );
286 # Removes most variables from an SQL query and replaces them with X or N for numbers.
287 # It's only slightly flawed. Don't use for anything important.
288 /* static */ function generalizeSQL( $sql )
290 # This does the same as the regexp below would do, but in such a way
291 # as to avoid crashing php on some large strings.
292 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
294 $sql = str_replace ( "\\\\", "", $sql);
295 $sql = str_replace ( "\\'", "", $sql);
296 $sql = str_replace ( "\\\"", "", $sql);
297 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
298 $sql = preg_replace ('/".*"/s', "'X'", $sql);
300 # All newlines, tabs, etc replaced by single space
301 $sql = preg_replace ( "/\s+/", " ", $sql);
304 $sql = preg_replace ('/-?[0-9]+/s', "N", $sql);
309 # Determines whether a field exists in a table
310 # Usually aborts on failure
311 # If errors are explicitly ignored, returns NULL on failure
312 function fieldExists( $table, $field, $fname = "Database::fieldExists" )
314 $res = $this->query( "DESCRIBE '$table'", DB_READ
, $fname );
321 while ( $row = $this->fetchObject( $res ) ) {
322 if ( $row->Field
== $field ) {
330 # Determines whether an index exists
331 # Usually aborts on failure
332 # If errors are explicitly ignored, returns NULL on failure
333 function indexExists( $table, $index, $fname = "Database::indexExists" )
335 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
336 $res = $this->query( $sql, DB_READ
, $fname );
343 while ( $row = $this->fetchObject( $res ) ) {
344 if ( $row->Key_name
== $index ) {
352 function tableExists( $table )
354 $old = $this->mIgnoreErrors
;
355 $this->mIgnoreErrors
= true;
356 $res = $this->query( "SELECT 1 FROM '$table' LIMIT 1" );
357 $this->mIgnoreErrors
= $old;
359 $this->freeResult( $res );
366 function fieldInfo( $table, $field )
368 $res = $this->query( "SELECT * FROM '$table' LIMIT 1" );
369 $n = pg_num_fields( $res );
370 for( $i = 0; $i < $n; $i++
) {
372 wfDebugDieBacktrace( "Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre" );
373 $meta = mysql_fetch_field( $res, $i );
374 if( $field == $meta->name
) {
381 # INSERT wrapper, inserts an array into a table
382 # Keys are field names, values are values
383 # Usually aborts on failure
384 # If errors are explicitly ignored, returns success
385 function insertArray( $table, $a, $fname = "Database::insertArray" )
387 $sql1 = "INSERT INTO '$table' (";
388 $sql2 = "VALUES (" . Database
::makeList( $a );
390 foreach ( $a as $field => $value ) {
397 $sql = "$sql1) $sql2)";
398 return !!$this->query( $sql, $fname );
401 # A cross between insertArray and getArray, takes a condition array and a SET array
402 function updateArray( $table, $values, $conds, $fname = "Database::updateArray" )
404 $sql = "UPDATE '$table' SET " . $this->makeList( $values, LIST_SET
);
405 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
406 $this->query( $sql, $fname );
409 # Makes a wfStrencoded list from an array
410 # $mode: LIST_COMMA - comma separated, no field names
411 # LIST_AND - ANDed WHERE clause (without the WHERE)
412 # LIST_SET - comma separated with field names, like a SET clause
413 /* static */ function makeList( $a, $mode = LIST_COMMA
)
417 foreach ( $a as $field => $value ) {
419 if ( $mode == LIST_AND
) {
427 if ( $mode == LIST_AND ||
$mode == LIST_SET
) {
430 if ( !is_numeric( $value ) ) {
431 $list .= "'" . wfStrencode( $value ) . "'";
439 function startTimer( $timeout )
442 wfDebugDieBacktrace( "Database::startTimer() error : mysql_thread_id() not implemented for postgre" );
443 $tid = mysql_thread_id( $this->mConn
);
444 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );
453 #------------------------------------------------------------------------------
455 #------------------------------------------------------------------------------
457 /* Standard fail function, called by default when a connection cannot be established
458 Displays the file cache if possible */
459 function wfEmergencyAbort( &$conn ) {
460 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
462 header( "Content-type: text/html; charset=$wgOutputEncoding" );
463 $msg = $wgSiteNotice;
464 if($msg == "") $msg = wfMsgNoDB( "noconnect" );
467 if($wgUseFileCache) {
472 $t = Title
::newFromURL( $title );
473 } elseif (@$_REQUEST['search']) {
474 $search = $_REQUEST['search'];
475 echo wfMsgNoDB( "searchdisabled" );
476 echo wfMsgNoDB( "googlesearch", htmlspecialchars( $search ), $wgInputEncoding );
479 $t = Title
::newFromText( wfMsgNoDB( "mainpage" ) );
483 $cache = new CacheManager( $t );
484 if( $cache->isFileCached() ) {
485 $msg = "<p style='color: red'><b>$msg<br />\n" .
486 wfMsgNoDB( "cachederror" ) . "</b></p>\n";
488 $tag = "<div id='article'>";
492 $cache->fetchPageText() );
496 /* Don't cache error pages! They cause no end of trouble... */
497 header( "Cache-control: none" );
498 header( "Pragma: nocache" );
503 function wfStrencode( $s )
505 return pg_escape_string( $s );
508 # Use PostgreSQL timestamp without timezone data type
509 function wfTimestamp2Unix( $ts ) {
510 return gmmktime( ( (int)substr( $ts, 11, 2) ),
511 (int)substr( $ts, 14, 2 ), (int)substr( $ts, 17, 2 ),
512 (int)substr( $ts, 5, 2 ), (int)substr( $ts, 8, 2 ),
513 (int)substr( $ts, 0, 4 ) );
516 function wfUnix2Timestamp( $unixtime ) {
517 return gmdate( "Y-m-d H:i:s", $unixtime );
520 function wfTimestampNow() {
522 return gmdate( "Y-m-d H:i:s" );
525 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
526 function wfInvertTimestamp( $ts ) {