commit in resource efficient textFieldSize() (uses PG internal schema)
[lhc/web/wiklou.git] / includes / DatabasePostgreSQL.php
1 <?php
2 # $Id$
3
4 /**
5 * DO NOT USE !!! Unless you want to help developping it.
6 *
7 * This file is an attempt to port the mysql database layer to postgreSQL. The
8 * only thing done so far is s/mysql/pg/ and dieing if function haven't been
9 * ported.
10 *
11 * As said brion 07/06/2004 :
12 * "table definitions need to be changed. fulltext index needs to work differently
13 * things that use the last insert id need to be changed. Probably other things
14 * need to be changed. various semantics may be different."
15 *
16 * Hashar
17 *
18 * @package MediaWiki
19 */
20
21 /**
22 * Depends on database
23 */
24 require_once( 'Database.php' );
25
26 /**
27 *
28 * @package MediaWiki
29 */
30 class DatabasePgsql extends Database {
31 var $mInsertId = NULL;
32 var $mLastResult = NULL;
33
34 function DatabasePgsql($server = false, $user = false, $password = false, $dbName = false,
35 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
36 {
37 Database::Database( $server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix );
38 }
39
40 /* static */ function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
41 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
42 {
43 return new DatabasePgsql( $server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix );
44 }
45
46 /**
47 * Usually aborts on failure
48 * If the failFunction is set to a non-zero integer, returns success
49 */
50 function open( $server, $user, $password, $dbName ) {
51 # Test for PostgreSQL support, to avoid suppressed fatal error
52 if ( !function_exists( 'pg_connect' ) ) {
53 die( "PostgreSQL functions missing, have you compiled PHP with the --with-pgsql option?\n" );
54 }
55
56 $this->close();
57 $this->mServer = $server;
58 $this->mUser = $user;
59 $this->mPassword = $password;
60 $this->mDBname = $dbName;
61
62 $success = false;
63
64 if ( '' != $dbName ) {
65 # start a database connection
66 $hstring="";
67 if ($server!=false && $server!="") {
68 $hstring="host=$server ";
69 }
70 @$this->mConn = pg_connect("$hstring dbname=$dbName user=$user password=$password");
71 if ( $this->mConn == false ) {
72 wfDebug( "DB connection error\n" );
73 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
74 wfDebug( $this->lastError()."\n" );
75 } else {
76 $this->mOpened = true;
77 }
78 }
79 return $this->mConn;
80 }
81
82 /**
83 * Closes a database connection, if it is open
84 * Returns success, true if already closed
85 */
86 function close() {
87 $this->mOpened = false;
88 if ( $this->mConn ) {
89 return pg_close( $this->mConn );
90 } else {
91 return true;
92 }
93 }
94
95 function doQuery( $sql ) {
96 return $this->mLastResult=pg_query( $this->mConn , $sql);
97 }
98
99 function queryIgnore( $sql, $fname = '' ) {
100 return $this->query( $sql, $fname, true );
101 }
102
103 function freeResult( $res ) {
104 if ( !@pg_free_result( $res ) ) {
105 wfDebugDieBacktrace( "Unable to free PostgreSQL result\n" );
106 }
107 }
108
109 function fetchObject( $res ) {
110 @$row = pg_fetch_object( $res );
111 # FIXME: HACK HACK HACK HACK debug
112
113 # TODO:
114 # hashar : not sure if the following test really trigger if the object
115 # fetching failled.
116 if( pg_last_error($this->mConn) ) {
117 wfDebugDieBacktrace( 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
118 }
119 return $row;
120 }
121
122 function fetchRow( $res ) {
123 @$row = pg_fetch_array( $res );
124 if( pg_last_error($this->mConn) ) {
125 wfDebugDieBacktrace( 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
126 }
127 return $row;
128 }
129
130 function numRows( $res ) {
131 @$n = pg_num_rows( $res );
132 if( pg_last_error($this->mConn) ) {
133 wfDebugDieBacktrace( 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
134 }
135 return $n;
136 }
137 function numFields( $res ) { return pg_num_fields( $res ); }
138 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
139
140 /**
141 * This must be called after nextSequenceVal
142 */
143 function insertId() {
144 return $this->mInsertId;
145 }
146
147 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
148 function lastError() { return pg_last_error(); }
149 function lastErrno() { return 1; }
150
151 function affectedRows() {
152 return pg_affected_rows( $this->mLastResult );
153 }
154
155 /**
156 * Returns information about an index
157 * If errors are explicitly ignored, returns NULL on failure
158 */
159 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
160 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
161 $res = $this->query( $sql, $fname );
162 if ( !$res ) {
163 return NULL;
164 }
165
166 while ( $row = $this->fetchObject( $res ) ) {
167 if ( $row->Key_name == $index ) {
168 return $row;
169 }
170 }
171 return false;
172 }
173
174 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
175 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
176 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
177 $res = $this->query( $sql, $fname );
178 if ( !$res )
179 return NULL;
180 while ($row = $this->fetchObject( $res ))
181 return true;
182 return false;
183
184 }
185
186 function fieldInfo( $table, $field ) {
187 wfDebugDieBacktrace( 'Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre' );
188 /*
189 $res = $this->query( "SELECT * FROM '$table' LIMIT 1" );
190 $n = pg_num_fields( $res );
191 for( $i = 0; $i < $n; $i++ ) {
192 // FIXME
193 wfDebugDieBacktrace( "Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre" );
194 $meta = mysql_fetch_field( $res, $i );
195 if( $field == $meta->name ) {
196 return $meta;
197 }
198 }
199 return false;*/
200 }
201
202 function insertArray( $table, $a, $fname = 'Database::insertArray', $options = array() ) {
203 # PostgreSQL doesn't support options
204 # We have a go at faking one of them
205 # TODO: DELAYED, LOW_PRIORITY
206
207 if ( !is_array($options))
208 $options = array($options);
209
210 if ( in_array( 'IGNORE', $options ) )
211 $oldIgnore = $this->ignoreErrors( true );
212
213 # IGNORE is performed using single-row inserts, ignoring errors in each
214 # FIXME: need some way to distiguish between key collision and other types of error
215 $oldIgnore = $this->ignoreErrors( true );
216 if ( !is_array( reset( $a ) ) ) {
217 $a = array( $a );
218 }
219 foreach ( $a as $row ) {
220 parent::insertArray( $table, $row, $fname, array() );
221 }
222 $this->ignoreErrors( $oldIgnore );
223 $retVal = true;
224
225 if ( in_array( 'IGNORE', $options ) )
226 $this->ignoreErrors( $oldIgnore );
227
228 return $retVal;
229 }
230
231 function startTimer( $timeout )
232 {
233 global $IP;
234 wfDebugDieBacktrace( 'Database::startTimer() error : mysql_thread_id() not implemented for postgre' );
235 /*$tid = mysql_thread_id( $this->mConn );
236 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );*/
237 }
238
239 function tableName( $name ) {
240 # First run any transformations from the parent object
241 $name = parent::tableName( $name );
242
243 # Now quote PG reserved keywords
244 switch( $name ) {
245 case 'user':
246 return '"user"';
247 case 'old':
248 return '"old"';
249 default:
250 return $name;
251 }
252 }
253
254 function strencode( $s ) {
255 return pg_escape_string( $s );
256 }
257
258 /**
259 * Return the next in a sequence, save the value for retrieval via insertId()
260 */
261 function nextSequenceValue( $seqName ) {
262 $value = $this->getField(''," nextval('" . $seqName . "')");
263 $this->mInsertId = $value;
264 return $value;
265 }
266
267 /**
268 * USE INDEX clause
269 * PostgreSQL doesn't have them and returns ""
270 */
271 function useIndexClause( $index ) {
272 return '';
273 }
274
275 # REPLACE query wrapper
276 # PostgreSQL simulates this with a DELETE followed by INSERT
277 # $row is the row to insert, an associative array
278 # $uniqueIndexes is an array of indexes. Each element may be either a
279 # field name or an array of field names
280 #
281 # It may be more efficient to leave off unique indexes which are unlikely to collide.
282 # However if you do this, you run the risk of encountering errors which wouldn't have
283 # occurred in MySQL
284 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
285 $table = $this->tableName( $table );
286
287 if (count($rows)==0) {
288 return;
289 }
290
291 # Single row case
292 if ( !is_array( reset( $rows ) ) ) {
293 $rows = array( $rows );
294 }
295
296 foreach( $rows as $row ) {
297 # Delete rows which collide
298 if ( $uniqueIndexes ) {
299 $sql = "DELETE FROM $table WHERE ";
300 $first = true;
301 foreach ( $uniqueIndexes as $index ) {
302 if ( $first ) {
303 $first = false;
304 $sql .= "(";
305 } else {
306 $sql .= ') OR (';
307 }
308 if ( is_array( $index ) ) {
309 $first2 = true;
310 foreach ( $index as $col ) {
311 if ( $first2 ) {
312 $first2 = false;
313 } else {
314 $sql .= ' AND ';
315 }
316 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
317 }
318 } else {
319 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
320 }
321 }
322 $sql .= ')';
323 $this->query( $sql, $fname );
324 }
325
326 # Now insert the row
327 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
328 $this->makeList( $row, LIST_COMMA ) . ')';
329 $this->query( $sql, $fname );
330 }
331 }
332
333 # DELETE where the condition is a join
334 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
335 if ( !$conds ) {
336 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
337 }
338
339 $delTable = $this->tableName( $delTable );
340 $joinTable = $this->tableName( $joinTable );
341 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
342 if ( $conds != '*' ) {
343 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
344 }
345 $sql .= ')';
346
347 $this->query( $sql, $fname );
348 }
349
350 # Returns the size of a text field, or -1 for "unlimited"
351 function textFieldSize( $table, $field ) {
352 $table = $this->tableName( $table );
353 $sql = "SELECT t.typname as ftype,a.atttypmod as size
354 FROM pg_class c, pg_attribute a, pg_type t
355 WHERE relname='$table' AND a.attrelid=c.oid AND
356 a.atttypid=t.oid and a.attname='$field'";
357 $res =$this->query($sql);
358 $row=$this->fetchObject($res);
359 if ($row->ftype=="varchar") {
360 $size=$row->size-4;
361 } else {
362 $size=$row->size;
363 }
364 $this->freeResult( $res );
365 return $size;
366 }
367
368 function lowPriorityOption() {
369 return '';
370 }
371
372 function limitResult($limit,$offset) {
373 return " LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
374 }
375
376 /**
377 * Returns an SQL expression for a simple conditional.
378 * Uses CASE on PostgreSQL.
379 *
380 * @param string $cond SQL expression which will result in a boolean value
381 * @param string $trueVal SQL expression to return if true
382 * @param string $falseVal SQL expression to return if false
383 * @return string SQL fragment
384 */
385 function conditional( $cond, $trueVal, $falseVal ) {
386 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
387 }
388
389 # FIXME: actually detecting deadlocks might be nice
390 function wasDeadlock() {
391 return false;
392 }
393
394 # Return DB-style timestamp used for MySQL schema
395 function timestamp( $ts=0 ) {
396 return wfTimestamp(TS_DB,$ts);
397 }
398
399 /**
400 * Return aggregated value function call
401 */
402 function aggregateValue ($valuedata,$valuename='value') {
403 return $valuedata;
404 }
405
406
407 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
408 $message = "A database error has occurred\n" .
409 "Query: $sql\n" .
410 "Function: $fname\n" .
411 "Error: $errno $error\n";
412 wfDebugDieBacktrace($message);
413 }
414
415 /**
416 * @return string wikitext of a link to the server software's web site
417 */
418 function getSoftwareLink() {
419 return "[http://www.postgresql.org/ PostgreSQL]";
420 }
421
422 /**
423 * @return string Version information from the database
424 */
425 function getServerVersion() {
426 $res = $this->query( "SELECT version()" );
427 $row = $this->fetchRow( $res );
428 $version = $row[0];
429 $this->freeResult( $res );
430 return $version;
431 }
432 }
433
434 /**
435 * Just an alias.
436 * @package MediaWiki
437 */
438 class DatabasePostgreSQL extends DatabasePgsql {
439 }
440
441 ?>