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