New global config setting $wgMaxTocLevel: Maximum indent level of toc.
[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 class DatabasePgsql extends Database {
18 var $mInsertId = NULL;
19
20 function DatabasePgsql($server = false, $user = false, $password = false, $dbName = false,
21 $failFunction = false, $debug = false, $bufferResults = true, $ignoreErrors = false)
22 {
23 Database::Database( $server, $user, $password, $dbName, $failFunction, $debug,
24 $bufferResults, $ignoreErrors );
25 }
26
27 /* static */ function newFromParams( $server, $user, $password, $dbName,
28 $failFunction = false, $debug = false, $bufferResults = true, $ignoreErrors = false )
29 {
30 return new DatabasePgsql( $server, $user, $password, $dbName, $failFunction, $debug,
31 $bufferResults, $ignoreErrors );
32 }
33
34 # Usually aborts on failure
35 # If the failFunction is set to a non-zero integer, returns success
36 function open( $server, $user, $password, $dbName )
37 {
38 # Test for PostgreSQL support, to avoid suppressed fatal error
39 if ( !function_exists( 'pg_connect' ) ) {
40 die( "PostgreSQL functions missing, have you compiled PHP with the --with-pgsql option?\n" );
41 }
42
43 $this->close();
44 $this->mServer = $server;
45 $this->mUser = $user;
46 $this->mPassword = $password;
47 $this->mDBname = $dbName;
48
49 $success = false;
50
51 if ( "" != $dbName ) {
52 # start a database connection
53 @$this->mConn = pg_connect("host=$server dbname=$dbName user=$user password=$password");
54 if ( $this->mConn == false ) {
55 wfDebug( "DB connection error\n" );
56 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
57 wfDebug( $this->lastError()."\n" );
58 } else {
59 $this->mOpened = true;
60 }
61 }
62 return $this->mConn;
63 }
64
65 # Closes a database connection, if it is open
66 # Returns success, true if already closed
67 function close()
68 {
69 $this->mOpened = false;
70 if ( $this->mConn ) {
71 return pg_close( $this->mConn );
72 } else {
73 return true;
74 }
75 }
76
77 # Usually aborts on failure
78 # If errors are explicitly ignored, returns success
79 function query( $sql, $fname = "", $tempIgnore = false )
80 {
81 global $wgProfiling;
82
83 if ( $wgProfiling ) {
84 # generalizeSQL will probably cut down the query to reasonable
85 # logging size most of the time. The substr is really just a sanity check.
86 $profName = "query: " . substr( Database::generalizeSQL( $sql ), 0, 255 );
87 wfProfileIn( $profName );
88 }
89
90 $this->mLastQuery = $sql;
91
92 if ( $this->mDebug ) {
93 $sqlx = substr( $sql, 0, 500 );
94 $sqlx = wordwrap(strtr($sqlx,"\t\n"," "));
95 wfDebug( "SQL: $sqlx\n" );
96 }
97
98 $ret = pg_query( $this->mConn , $sql);
99 $this->mLastResult = $ret;
100 if ( false == $ret ) {
101 // Ignore errors during error handling to prevent infinite recursion
102 $ignore = $this->setIgnoreErrors( true );
103 $error = pg_last_error( $this->mConn );
104 // TODO FIXME : no error number function in postgre
105 // $errno = mysql_errno( $this->mConn );
106 if( $ignore || $tempIgnore ) {
107 wfDebug("SQL ERROR (ignored): " . $error . "\n");
108 } else {
109 wfDebug("SQL ERROR: " . $error . "\n");
110 if ( $this->mOut ) {
111 // this calls wfAbruptExit()
112 $this->mOut->databaseError( $fname, $sql, $error, 0 );
113 }
114 }
115 $this->setIgnoreErrors( $ignore );
116 }
117
118 if ( $wgProfiling ) {
119 wfProfileOut( $profName );
120 }
121 return $ret;
122 }
123
124 function queryIgnore( $sql, $fname = "" ) {
125 return $this->query( $sql, $fname, true );
126 }
127
128 function freeResult( $res ) {
129 if ( !@pg_free_result( $res ) ) {
130 wfDebugDieBacktrace( "Unable to free PostgreSQL result\n" );
131 }
132 }
133 function fetchObject( $res ) {
134 @$row = pg_fetch_object( $res );
135 # FIXME: HACK HACK HACK HACK debug
136
137 # TODO:
138 # hashar : not sure if the following test really trigger if the object
139 # fetching failled.
140 if( pg_last_error($this->mConn) ) {
141 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( pg_last_error($this->mConn) ) );
142 }
143 return $row;
144 }
145
146 function fetchRow( $res ) {
147 @$row = pg_fetch_array( $res );
148 if( pg_last_error($this->mConn) ) {
149 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( pg_last_error($this->mConn) ) );
150 }
151 return $row;
152 }
153
154 function numRows( $res ) {
155 @$n = pg_num_rows( $res );
156 if( pg_last_error($this->mConn) ) {
157 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( pg_last_error($this->mConn) ) );
158 }
159 return $n;
160 }
161 function numFields( $res ) { return pg_num_fields( $res ); }
162 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
163
164 # This must be called after nextSequenceVal
165 function insertId() {
166 return $this->mInsertId;
167 }
168
169 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
170 function lastError() { return pg_last_error(); }
171 function affectedRows() {
172 return pg_affected_rows( $this->mLastResult );
173 }
174
175 # Returns information about an index
176 # If errors are explicitly ignored, returns NULL on failure
177 function indexInfo( $table, $index, $fname = "Database::indexExists" )
178 {
179 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
180 $res = $this->query( $sql, $fname );
181 if ( !$res ) {
182 return NULL;
183 }
184
185 while ( $row = $this->fetchObject( $res ) ) {
186 if ( $row->Key_name == $index ) {
187 return $row;
188 }
189 }
190 return false;
191 }
192
193 function fieldInfo( $table, $field )
194 {
195 wfDebugDieBacktrace( "Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre" );
196 /*
197 $res = $this->query( "SELECT * FROM '$table' LIMIT 1" );
198 $n = pg_num_fields( $res );
199 for( $i = 0; $i < $n; $i++ ) {
200 // FIXME
201 wfDebugDieBacktrace( "Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre" );
202 $meta = mysql_fetch_field( $res, $i );
203 if( $field == $meta->name ) {
204 return $meta;
205 }
206 }
207 return false;*/
208 }
209
210 function insertArray( $table, $a, $fname = "Database::insertArray", $options = array() ) {
211 # PostgreSQL doesn't support options
212 # We have a go at faking one of them
213 # TODO: DELAYED, LOW_PRIORITY
214
215 # IGNORE is performed using single-row inserts, ignoring errors in each
216 if ( in_array( 'IGNORE', $options ) ) {
217 # FIXME: need some way to distiguish between key collision and other types of error
218 $oldIgnore = $this->setIgnoreErrors( 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->setIgnoreErrors( $oldIgnore );
226 $retVal = true;
227 } else {
228 $retVal = parent::insertArray( $table, $a, $fname, array() );
229 }
230 return $retVal;
231 }
232
233 function startTimer( $timeout )
234 {
235 global $IP;
236 wfDebugDieBacktrace( "Database::startTimer() error : mysql_thread_id() not implemented for postgre" );
237 /*$tid = mysql_thread_id( $this->mConn );
238 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );*/
239 }
240
241 function tableName( $name ) {
242 # First run any transformations from the parent object
243 $name = parent::tableName( $name );
244
245 # Now quote PG reserved keywords
246 switch( $name ) {
247 case 'user':
248 return '"user"';
249 case 'old':
250 return '"old"';
251 default:
252 return $name;
253 }
254 }
255
256 function strencode( $s ) {
257 return pg_escape_string( $s );
258 }
259
260 # Return the next in a sequence, save the value for retrieval via insertId()
261 function nextSequenceValue( $seqName ) {
262 $value = $this->getField(""," nextval('" . $seqName . "')");
263 $this->mInsertId = $value;
264 return $value;
265 }
266
267 # USE INDEX clause
268 # PostgreSQL doesn't have them and returns ""
269 function useIndexClause( $index ) {
270 return '';
271 }
272
273 # REPLACE query wrapper
274 # PostgreSQL simulates this with a DELETE followed by INSERT
275 # $row is the row to insert, an associative array
276 # $uniqueIndexes is an array of indexes. Each element may be either a
277 # field name or an array of field names
278 #
279 # It may be more efficient to leave off unique indexes which are unlikely to collide.
280 # However if you do this, you run the risk of encountering errors which wouldn't have
281 # occurred in MySQL
282 function replace( $table, $uniqueIndexes, $rows, $fname = "Database::replace" ) {
283 $table = $this->tableName( $table );
284
285 # Single row case
286 if ( !is_array( reset( $rows ) ) ) {
287 $rows = array( $rows );
288 }
289
290 foreach( $rows as $row ) {
291 # Delete rows which collide
292 if ( $uniqueIndexes ) {
293 $sql = "DELETE FROM $table WHERE (";
294 $first = true;
295 foreach ( $uniqueIndexes as $index ) {
296 if ( $first ) {
297 $first = false;
298 } else {
299 $sql .= ") OR (";
300 }
301 if ( is_array( $index ) ) {
302 $first2 = true;
303 $sql .= "(";
304 foreach ( $index as $col ) {
305 if ( $first2 ) {
306 $first2 = false;
307 } else {
308 $sql .= " AND ";
309 }
310 $sql .= "$col=" . $this->addQuotes( $row[$col] )
311 }
312 } else {
313 $sql .= "$index=" . $this->addQuotes( $row[$index] );
314 }
315 }
316 $sql .= ")";
317 $this->query( $sql, $fname );
318 }
319
320 # Now insert the row
321 $sql = "INSERT INTO $table (" . $this->makeList( array_flip( $row ) ) .') VALUES (' .
322 $this->makeList( $row, LIST_COMMA ) . ')';
323 $this->query( $sql, $fname );
324 }
325 }
326
327 # DELETE where the condition is a join
328 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
329 if ( !$conds ) {
330 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
331 }
332
333 $delTable = $this->tableName( $delTable );
334 $joinTable = $this->tableName( $joinTable );
335 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
336 if ( $conds != '*' ) {
337 $sql .= "WHERE " . $this->makeList( $conds, LIST_AND );
338 }
339 $sql .= ")";
340
341 $this->query( $sql, $fname );
342 }
343
344 # Returns the size of a text field, or -1 for "unlimited"
345 function textFieldSize( $table, $field ) {
346 $table = $this->tableName( $table );
347 $res = $this->query( "SELECT $field FROM $table LIMIT 1", "Database::textFieldLength" );
348 $size = pg_field_size( $res, 0 );
349 $this->freeResult( $res );
350 return $size;
351 }
352
353 function lowPriorityOption() {
354 return '';
355 }
356
357 function limitResult($limit,$offset) {
358 return " LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
359 }
360
361 # FIXME: actually detecting deadlocks might be nice
362 function wasDeadlock() {
363 return false;
364 }
365 }
366
367 # Just an alias.
368 class DatabasePostgreSQL extends DatabasePgsql {
369 }
370
371 ?>