4 * This is PostgreSQL database abstraction layer.
6 * As it includes more generic version for DB functions,
7 * than MySQL ones, some of them should be moved to parent
16 require_once( 'Database.php' );
18 class DatabasePostgres
extends Database
{
19 var $mInsertId = NULL;
20 var $mLastResult = NULL;
22 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
23 $failFunction = false, $flags = 0 )
26 global $wgOut, $wgDBprefix, $wgCommandLineMode;
27 # Can't get a reference if it hasn't been set yet
28 if ( !isset( $wgOut ) ) {
31 $this->mOut
=& $wgOut;
32 $this->mFailFunction
= $failFunction;
33 $this->mFlags
= $flags;
35 $this->open( $server, $user, $password, $dbName);
39 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
40 $failFunction = false, $flags = 0)
42 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
46 * Usually aborts on failure
47 * If the failFunction is set to a non-zero integer, returns success
49 function open( $server, $user, $password, $dbName ) {
50 # Test for PostgreSQL support, to avoid suppressed fatal error
51 if ( !function_exists( 'pg_connect' ) ) {
52 throw new DBConnectionError( $this, "PostgreSQL functions missing, have you compiled PHP with the --with-pgsql option?\n" );
55 global $wgDBschema, $wgDBport;
58 $this->mServer
= $server;
61 $this->mPassword
= $password;
62 $this->mDBname
= $dbName;
63 $schema = $wgDBschema;
68 if ($server!=false && $server!="") {
69 $hstring="host=$server ";
71 if ($port!=false && $port!="") {
72 $hstring .= "port=$port ";
75 error_reporting( E_ALL
);
77 @$this->mConn
= pg_connect("$hstring dbname=$dbName user=$user password=$password");
79 if ( $this->mConn
== false ) {
80 wfDebug( "DB connection error\n" );
81 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
82 wfDebug( $this->lastError()."\n" );
86 $this->mOpened
= true;
87 ## If this is the initial connection, setup the schema stuff
88 if (defined('MEDIAWIKI_INSTALL')) {
89 ## Does the schema already exist? Who owns it?
90 $result = $this->schemaExists($schema);
92 print "<li>Creating schema <b>$schema</b> ...";
93 $result = $this->doQuery("CREATE SCHEMA $schema");
95 print "FAILED.</li>\n";
100 else if ($result != $user) {
101 print "<li>Schema <b>$schema</b> exists but is not owned by <b>$user</b>. Not ideal.</li>\n";
104 print "<li>Schema <b>$schema</b> exists and is owned by <b>$user ($result)</b>. Excellent.</li>\n";
107 ## Fix up the search paths if needed
108 print "<li>Setting the search path for user <b>$user</b> ...";
109 $SQL = "ALTER USER $user SET search_path = $schema, public";
110 $result = pg_query($this->mConn
, $SQL);
112 print "FAILED.</li>\n";
116 ## Set for the rest of this session
117 $SQL = "SET search_path = $schema, public";
118 $result = pg_query($this->mConn
, $SQL);
120 print "<li>Failed to set search_path</li>\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 function doQuery( $sql ) {
142 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
145 function queryIgnore( $sql, $fname = '' ) {
146 return $this->query( $sql, $fname, true );
149 function freeResult( $res ) {
150 if ( !@pg_free_result
( $res ) ) {
151 throw new DBUnexpectedError($this, "Unable to free PostgreSQL result\n" );
155 function fetchObject( $res ) {
156 @$row = pg_fetch_object( $res );
157 # FIXME: HACK HACK HACK HACK debug
160 # hashar : not sure if the following test really trigger if the object
162 if( pg_last_error($this->mConn
) ) {
163 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
168 function fetchRow( $res ) {
169 @$row = pg_fetch_array( $res );
170 if( pg_last_error($this->mConn
) ) {
171 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
176 function numRows( $res ) {
177 @$n = pg_num_rows( $res );
178 if( pg_last_error($this->mConn
) ) {
179 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
183 function numFields( $res ) { return pg_num_fields( $res ); }
184 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
187 * This must be called after nextSequenceVal
189 function insertId() {
190 return $this->mInsertId
;
193 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
194 function lastError() {
195 if ( $this->mConn
) {
196 return pg_last_error();
199 return "No database connection";
202 function lastErrno() { return 1; }
204 function affectedRows() {
205 return pg_affected_rows( $this->mLastResult
);
209 * Returns information about an index
210 * If errors are explicitly ignored, returns NULL on failure
212 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
213 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
214 $res = $this->query( $sql, $fname );
219 while ( $row = $this->fetchObject( $res ) ) {
220 if ( $row->indexname
== $index ) {
227 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
228 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
229 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
230 $res = $this->query( $sql, $fname );
233 while ($row = $this->fetchObject( $res ))
239 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
240 # PostgreSQL doesn't support options
241 # We have a go at faking one of them
242 # TODO: DELAYED, LOW_PRIORITY
244 if ( !is_array($options))
245 $options = array($options);
247 if ( in_array( 'IGNORE', $options ) )
248 $oldIgnore = $this->ignoreErrors( true );
250 # IGNORE is performed using single-row inserts, ignoring errors in each
251 # FIXME: need some way to distiguish between key collision and other types of error
252 $oldIgnore = $this->ignoreErrors( true );
253 if ( !is_array( reset( $a ) ) ) {
256 foreach ( $a as $row ) {
257 parent
::insert( $table, $row, $fname, array() );
259 $this->ignoreErrors( $oldIgnore );
262 if ( in_array( 'IGNORE', $options ) )
263 $this->ignoreErrors( $oldIgnore );
268 function tableName( $name ) {
269 # Replace backticks into double quotes
270 $name = strtr($name,'`','"');
272 # Now quote PG reserved keywords
277 return '"' . $name . '"';
284 function strencode( $s ) {
285 return pg_escape_string( $s );
289 * Return the next in a sequence, save the value for retrieval via insertId()
291 function nextSequenceValue( $seqName ) {
292 $value = $this->selectField(''," nextval('" . $seqName . "')");
293 $this->mInsertId
= $value;
299 * PostgreSQL doesn't have them and returns ""
301 function useIndexClause( $index ) {
305 # REPLACE query wrapper
306 # PostgreSQL simulates this with a DELETE followed by INSERT
307 # $row is the row to insert, an associative array
308 # $uniqueIndexes is an array of indexes. Each element may be either a
309 # field name or an array of field names
311 # It may be more efficient to leave off unique indexes which are unlikely to collide.
312 # However if you do this, you run the risk of encountering errors which wouldn't have
314 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
315 $table = $this->tableName( $table );
317 if (count($rows)==0) {
322 if ( !is_array( reset( $rows ) ) ) {
323 $rows = array( $rows );
326 foreach( $rows as $row ) {
327 # Delete rows which collide
328 if ( $uniqueIndexes ) {
329 $sql = "DELETE FROM $table WHERE ";
331 foreach ( $uniqueIndexes as $index ) {
338 if ( is_array( $index ) ) {
340 foreach ( $index as $col ) {
346 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
349 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
353 $this->query( $sql, $fname );
357 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
358 $this->makeList( $row, LIST_COMMA
) . ')';
359 $this->query( $sql, $fname );
363 # DELETE where the condition is a join
364 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
366 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
369 $delTable = $this->tableName( $delTable );
370 $joinTable = $this->tableName( $joinTable );
371 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
372 if ( $conds != '*' ) {
373 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
377 $this->query( $sql, $fname );
380 # Returns the size of a text field, or -1 for "unlimited"
381 function textFieldSize( $table, $field ) {
382 $table = $this->tableName( $table );
383 $sql = "SELECT t.typname as ftype,a.atttypmod as size
384 FROM pg_class c, pg_attribute a, pg_type t
385 WHERE relname='$table' AND a.attrelid=c.oid AND
386 a.atttypid=t.oid and a.attname='$field'";
387 $res =$this->query($sql);
388 $row=$this->fetchObject($res);
389 if ($row->ftype
=="varchar") {
394 $this->freeResult( $res );
398 function lowPriorityOption() {
402 function limitResult($sql, $limit,$offset) {
403 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
407 * Returns an SQL expression for a simple conditional.
408 * Uses CASE on PostgreSQL.
410 * @param string $cond SQL expression which will result in a boolean value
411 * @param string $trueVal SQL expression to return if true
412 * @param string $falseVal SQL expression to return if false
413 * @return string SQL fragment
415 function conditional( $cond, $trueVal, $falseVal ) {
416 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
419 # FIXME: actually detecting deadlocks might be nice
420 function wasDeadlock() {
424 # Return DB-style timestamp used for MySQL schema
425 function timestamp( $ts=0 ) {
426 return wfTimestamp(TS_DB
,$ts);
430 * Return aggregated value function call
432 function aggregateValue ($valuedata,$valuename='value') {
437 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
438 $message = "A database error has occurred\n" .
440 "Function: $fname\n" .
441 "Error: $errno $error\n";
442 throw new DBUnexpectedError($this, $message);
446 * @return string wikitext of a link to the server software's web site
448 function getSoftwareLink() {
449 return "[http://www.postgresql.org/ PostgreSQL]";
453 * @return string Version information from the database
455 function getServerVersion() {
456 $res = $this->query( "SELECT version()" );
457 $row = $this->fetchRow( $res );
459 $this->freeResult( $res );
465 * Query whether a given table exists (in the default schema)
467 function tableExists( $table, $fname = 'DatabasePostgres:tableExists' ) {
469 $stable = preg_replace("/'/", "''", $table);
470 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
471 . "WHERE c.relnamespace = n.oid AND c.relname = '$stable' AND n.nspname = '$wgDBschema'";
472 $res = $this->query( $SQL, $fname );
473 $count = $res ?
pg_num_rows($res) : 0;
475 $this->freeResult( $res );
480 * Query whether a given schema exists. Returns the name of the owner
482 function schemaExists( $schema, $fname = 'DatabasePostgres:schemaExists' ) {
483 $sschema = preg_replace("/'/", "''", $schema);
484 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
485 ."WHERE n.nspowner=r.oid AND n.nspname = '$sschema'";
486 $res = $this->query($SQL, $fname);
487 $res = $this->query( $SQL, $fname );
488 $owner = $res ?
pg_num_rows($res) ?
pg_fetch_result($res, 0, 0) : false : false;
490 $this->freeResult($res);
495 * Query whether a given column exists
497 function fieldExists( $table, $field, $fname = 'DatabasePostgres::fieldExists' ) {
499 $stable = preg_replace("/'/", "''", $table);
500 $scol = preg_replace("/'/", "''", $field);
501 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
502 . "WHERE c.relnamespace = n.oid AND c.relname = '$stable' AND n.nspname = '$wgDBschema' "
503 . "AND a.attrelid = c.oid AND a.attname = '$scol'";
504 $res = $this->query( $SQL, $fname );
505 $count = $res ?
pg_num_rows($res) : 0;
507 $this->freeResult( $res );
511 function fieldInfo( $table, $field ) {
512 $res = $this->query( "SELECT $field FROM $table LIMIT 1" );
513 $type = pg_field_type( $res, 0 );