Revert to r15092; massive breakage, unable to connect to MySQL at all
[lhc/web/wiklou.git] / includes / DatabasePostgres.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 DatabasePostgres extends Database {
26 var $mInsertId = NULL;
27 var $mLastResult = NULL;
28
29 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
30 $failFunction = false, $flags = 0 )
31 {
32 Database::__construct( $server, $user, $password, $dbName, $failFunction, $flags );
33 }
34
35 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
36 $failFunction = false, $flags = 0)
37 {
38 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
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 throw new DBConnectionError( $this, "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
69 @$this->mConn = pg_connect("$hstring dbname=$dbName user=$user password=$password");
70 if ( $this->mConn == false ) {
71 wfDebug( "DB connection error\n" );
72 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
73 wfDebug( $this->lastError()."\n" );
74 } else {
75 $this->setSchema();
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 throw new DBUnexpectedError($this, "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 throw new DBUnexpectedError($this, '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 throw new DBUnexpectedError($this, '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 throw new DBUnexpectedError($this, '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() {
149 if ( $this->mConn ) {
150 return pg_last_error();
151 }
152 else {
153 return "No database connection";
154 }
155 }
156 function lastErrno() { return 1; }
157
158 function affectedRows() {
159 return pg_affected_rows( $this->mLastResult );
160 }
161
162 /**
163 * Returns information about an index
164 * If errors are explicitly ignored, returns NULL on failure
165 */
166 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
167 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
168 $res = $this->query( $sql, $fname );
169 if ( !$res ) {
170 return NULL;
171 }
172
173 while ( $row = $this->fetchObject( $res ) ) {
174 if ( $row->Key_name == $index ) {
175 return $row;
176 }
177 }
178 return false;
179 }
180
181 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
182 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
183 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
184 $res = $this->query( $sql, $fname );
185 if ( !$res )
186 return NULL;
187 while ($row = $this->fetchObject( $res ))
188 return true;
189 return false;
190
191 }
192
193 function fieldInfo( $table, $field ) {
194 throw new DBUnexpectedError($this, 'Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre' );
195 /*
196 $res = $this->query( "SELECT * FROM '$table' LIMIT 1" );
197 $n = pg_num_fields( $res );
198 for( $i = 0; $i < $n; $i++ ) {
199 // FIXME
200 throw new DBUnexpectedError($this, "Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre" );
201 $meta = mysql_fetch_field( $res, $i );
202 if( $field == $meta->name ) {
203 return $meta;
204 }
205 }
206 return false;*/
207 }
208
209 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
210 # PostgreSQL doesn't support options
211 # We have a go at faking one of them
212 # TODO: DELAYED, LOW_PRIORITY
213
214 if ( !is_array($options))
215 $options = array($options);
216
217 if ( in_array( 'IGNORE', $options ) )
218 $oldIgnore = $this->ignoreErrors( true );
219
220 # IGNORE is performed using single-row inserts, ignoring errors in each
221 # FIXME: need some way to distiguish between key collision and other types of error
222 $oldIgnore = $this->ignoreErrors( true );
223 if ( !is_array( reset( $a ) ) ) {
224 $a = array( $a );
225 }
226 foreach ( $a as $row ) {
227 parent::insert( $table, $row, $fname, array() );
228 }
229 $this->ignoreErrors( $oldIgnore );
230 $retVal = true;
231
232 if ( in_array( 'IGNORE', $options ) )
233 $this->ignoreErrors( $oldIgnore );
234
235 return $retVal;
236 }
237
238 function tableName( $name ) {
239 # First run any transformations from the parent object
240 $name = parent::tableName( $name );
241
242 # Replace backticks into double quotes
243 $name = strtr($name,'`','"');
244
245 # Now quote PG reserved keywords
246 switch( $name ) {
247 case 'user':
248 case 'old':
249 case 'group':
250 return '"' . $name . '"';
251
252 default:
253 return $name;
254 }
255 }
256
257 function strencode( $s ) {
258 return pg_escape_string( $s );
259 }
260
261 /**
262 * Return the next in a sequence, save the value for retrieval via insertId()
263 */
264 function nextSequenceValue( $seqName ) {
265 $value = $this->selectField(''," nextval('" . $seqName . "')");
266 $this->mInsertId = $value;
267 return $value;
268 }
269
270 /**
271 * USE INDEX clause
272 * PostgreSQL doesn't have them and returns ""
273 */
274 function useIndexClause( $index ) {
275 return '';
276 }
277
278 # REPLACE query wrapper
279 # PostgreSQL simulates this with a DELETE followed by INSERT
280 # $row is the row to insert, an associative array
281 # $uniqueIndexes is an array of indexes. Each element may be either a
282 # field name or an array of field names
283 #
284 # It may be more efficient to leave off unique indexes which are unlikely to collide.
285 # However if you do this, you run the risk of encountering errors which wouldn't have
286 # occurred in MySQL
287 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
288 $table = $this->tableName( $table );
289
290 if (count($rows)==0) {
291 return;
292 }
293
294 # Single row case
295 if ( !is_array( reset( $rows ) ) ) {
296 $rows = array( $rows );
297 }
298
299 foreach( $rows as $row ) {
300 # Delete rows which collide
301 if ( $uniqueIndexes ) {
302 $sql = "DELETE FROM $table WHERE ";
303 $first = true;
304 foreach ( $uniqueIndexes as $index ) {
305 if ( $first ) {
306 $first = false;
307 $sql .= "(";
308 } else {
309 $sql .= ') OR (';
310 }
311 if ( is_array( $index ) ) {
312 $first2 = true;
313 foreach ( $index as $col ) {
314 if ( $first2 ) {
315 $first2 = false;
316 } else {
317 $sql .= ' AND ';
318 }
319 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
320 }
321 } else {
322 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
323 }
324 }
325 $sql .= ')';
326 $this->query( $sql, $fname );
327 }
328
329 # Now insert the row
330 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
331 $this->makeList( $row, LIST_COMMA ) . ')';
332 $this->query( $sql, $fname );
333 }
334 }
335
336 # DELETE where the condition is a join
337 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
338 if ( !$conds ) {
339 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
340 }
341
342 $delTable = $this->tableName( $delTable );
343 $joinTable = $this->tableName( $joinTable );
344 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
345 if ( $conds != '*' ) {
346 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
347 }
348 $sql .= ')';
349
350 $this->query( $sql, $fname );
351 }
352
353 # Returns the size of a text field, or -1 for "unlimited"
354 function textFieldSize( $table, $field ) {
355 $table = $this->tableName( $table );
356 $sql = "SELECT t.typname as ftype,a.atttypmod as size
357 FROM pg_class c, pg_attribute a, pg_type t
358 WHERE relname='$table' AND a.attrelid=c.oid AND
359 a.atttypid=t.oid and a.attname='$field'";
360 $res =$this->query($sql);
361 $row=$this->fetchObject($res);
362 if ($row->ftype=="varchar") {
363 $size=$row->size-4;
364 } else {
365 $size=$row->size;
366 }
367 $this->freeResult( $res );
368 return $size;
369 }
370
371 function lowPriorityOption() {
372 return '';
373 }
374
375 function limitResult($sql, $limit,$offset) {
376 return "$sql LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
377 }
378
379 /**
380 * Returns an SQL expression for a simple conditional.
381 * Uses CASE on PostgreSQL.
382 *
383 * @param string $cond SQL expression which will result in a boolean value
384 * @param string $trueVal SQL expression to return if true
385 * @param string $falseVal SQL expression to return if false
386 * @return string SQL fragment
387 */
388 function conditional( $cond, $trueVal, $falseVal ) {
389 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
390 }
391
392 # FIXME: actually detecting deadlocks might be nice
393 function wasDeadlock() {
394 return false;
395 }
396
397 # Return DB-style timestamp used for MySQL schema
398 function timestamp( $ts=0 ) {
399 return wfTimestamp(TS_DB,$ts);
400 }
401
402 /**
403 * Return aggregated value function call
404 */
405 function aggregateValue ($valuedata,$valuename='value') {
406 return $valuedata;
407 }
408
409
410 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
411 $message = "A database error has occurred\n" .
412 "Query: $sql\n" .
413 "Function: $fname\n" .
414 "Error: $errno $error\n";
415 throw new DBUnexpectedError($this, $message);
416 }
417
418 /**
419 * @return string wikitext of a link to the server software's web site
420 */
421 function getSoftwareLink() {
422 return "[http://www.postgresql.org/ PostgreSQL]";
423 }
424
425 /**
426 * @return string Version information from the database
427 */
428 function getServerVersion() {
429 $res = $this->query( "SELECT version()" );
430 $row = $this->fetchRow( $res );
431 $version = $row[0];
432 $this->freeResult( $res );
433 return $version;
434 }
435
436 function setSchema($schema=false) {
437 $schemas=$this->mSchemas;
438 if ($schema) { array_unshift($schemas,$schema); }
439 $searchpath=$this->makeList($schemas,LIST_NAMES);
440 $this->query("SET search_path = $searchpath");
441 }
442 }
443
444 ?>