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" );
58 $this->mServer
= $server;
61 $this->mPassword
= $password;
62 $this->mDBname
= $dbName;
67 if ($server!=false && $server!="") {
68 $hstring="host=$server ";
70 if ($port!=false && $port!="") {
71 $hstring .= "port=$port ";
74 error_reporting( E_ALL
);
76 @$this->mConn
= pg_connect("$hstring dbname=$dbName user=$user password=$password");
78 if ( $this->mConn
== false ) {
79 wfDebug( "DB connection error\n" );
80 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
81 wfDebug( $this->lastError()."\n" );
85 $this->mOpened
= true;
86 ## If this is the initial connection, setup the schema stuff
87 if (defined('MEDIAWIKI_INSTALL') and !defined('POSTGRES_SEARCHPATH')) {
88 global $wgDBmwschema, $wgDBts2schema, $wgDBname;
90 ## Do we have the basic tsearch2 table?
91 print "<li>Checking for tsearch2 ...";
92 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
93 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
94 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
95 print " for instructions.</li>\n";
100 ## Do we have plpgsql installed?
101 print "<li>Checking for plpgsql ...";
102 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
103 $res = $this->doQuery($SQL);
104 $rows = $this->numRows($this->doQuery($SQL));
106 print "<b>FAILED</b>. Make sure the language plpgsql is installed for the database <tt>$wgDBname</tt>t</li>";
112 ## Does the schema already exist? Who owns it?
113 $result = $this->schemaExists($wgDBmwschema);
115 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
116 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
118 print "FAILED.</li>\n";
123 else if ($result != $user) {
124 print "<li>Schema <b>$wgDBmwschema</b> exists but is not owned by <b>$user</b>. Not ideal.</li>\n";
127 print "<li>Schema <b>$wgDBmwschema</b> exists and is owned by <b>$user ($result)</b>. Excellent.</li>\n";
130 ## Fix up the search paths if needed
131 print "<li>Setting the search path for user <b>$user</b> ...";
132 $path = "$wgDBmwschema";
133 if ($wgDBts2schema !== $wgDBmwschema)
134 $path .= ", $wgDBts2schema";
135 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
137 $SQL = "ALTER USER $user SET search_path = $path";
138 $result = pg_query($this->mConn
, $SQL);
140 print "FAILED.</li>\n";
144 ## Set for the rest of this session
145 $SQL = "SET search_path = $path";
146 $result = pg_query($this->mConn
, $SQL);
148 print "<li>Failed to set search_path</li>\n";
151 define( "POSTGRES_SEARCHPATH", $path );
158 * Closes a database connection, if it is open
159 * Returns success, true if already closed
162 $this->mOpened
= false;
163 if ( $this->mConn
) {
164 return pg_close( $this->mConn
);
170 function doQuery( $sql ) {
171 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
174 function queryIgnore( $sql, $fname = '' ) {
175 return $this->query( $sql, $fname, true );
178 function freeResult( $res ) {
179 if ( !@pg_free_result
( $res ) ) {
180 throw new DBUnexpectedError($this, "Unable to free PostgreSQL result\n" );
184 function fetchObject( $res ) {
185 @$row = pg_fetch_object( $res );
186 # FIXME: HACK HACK HACK HACK debug
189 # hashar : not sure if the following test really trigger if the object
191 if( pg_last_error($this->mConn
) ) {
192 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
197 function fetchRow( $res ) {
198 @$row = pg_fetch_array( $res );
199 if( pg_last_error($this->mConn
) ) {
200 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
205 function numRows( $res ) {
206 @$n = pg_num_rows( $res );
207 if( pg_last_error($this->mConn
) ) {
208 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
212 function numFields( $res ) { return pg_num_fields( $res ); }
213 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
216 * This must be called after nextSequenceVal
218 function insertId() {
219 return $this->mInsertId
;
222 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
223 function lastError() {
224 if ( $this->mConn
) {
225 return pg_last_error();
228 return "No database connection";
231 function lastErrno() { return 1; }
233 function affectedRows() {
234 return pg_affected_rows( $this->mLastResult
);
238 * Returns information about an index
239 * If errors are explicitly ignored, returns NULL on failure
241 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
242 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
243 $res = $this->query( $sql, $fname );
248 while ( $row = $this->fetchObject( $res ) ) {
249 if ( $row->indexname
== $index ) {
256 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
257 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
258 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
259 $res = $this->query( $sql, $fname );
262 while ($row = $this->fetchObject( $res ))
268 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
269 # PostgreSQL doesn't support options
270 # We have a go at faking one of them
271 # TODO: DELAYED, LOW_PRIORITY
273 if ( !is_array($options))
274 $options = array($options);
276 if ( in_array( 'IGNORE', $options ) )
277 $oldIgnore = $this->ignoreErrors( true );
279 # IGNORE is performed using single-row inserts, ignoring errors in each
280 # FIXME: need some way to distiguish between key collision and other types of error
281 $oldIgnore = $this->ignoreErrors( true );
282 if ( !is_array( reset( $a ) ) ) {
285 foreach ( $a as $row ) {
286 parent
::insert( $table, $row, $fname, array() );
288 $this->ignoreErrors( $oldIgnore );
291 if ( in_array( 'IGNORE', $options ) )
292 $this->ignoreErrors( $oldIgnore );
297 function tableName( $name ) {
298 # Replace backticks into double quotes
299 $name = strtr($name,'`','"');
301 # Now quote PG reserved keywords
306 return '"' . $name . '"';
314 * Return the next in a sequence, save the value for retrieval via insertId()
316 function nextSequenceValue( $seqName ) {
317 $safeseq = preg_replace( "/'/", "''", $seqName );
318 $res = $this->query( "SELECT nextval('$safeseq')" );
319 $row = $this->fetchRow( $res );
320 $this->mInsertId
= $row[0];
321 $this->freeResult( $res );
322 return $this->mInsertId
;
327 * PostgreSQL doesn't have them and returns ""
329 function useIndexClause( $index ) {
333 # REPLACE query wrapper
334 # PostgreSQL simulates this with a DELETE followed by INSERT
335 # $row is the row to insert, an associative array
336 # $uniqueIndexes is an array of indexes. Each element may be either a
337 # field name or an array of field names
339 # It may be more efficient to leave off unique indexes which are unlikely to collide.
340 # However if you do this, you run the risk of encountering errors which wouldn't have
342 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
343 $table = $this->tableName( $table );
345 if (count($rows)==0) {
350 if ( !is_array( reset( $rows ) ) ) {
351 $rows = array( $rows );
354 foreach( $rows as $row ) {
355 # Delete rows which collide
356 if ( $uniqueIndexes ) {
357 $sql = "DELETE FROM $table WHERE ";
359 foreach ( $uniqueIndexes as $index ) {
366 if ( is_array( $index ) ) {
368 foreach ( $index as $col ) {
374 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
377 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
381 $this->query( $sql, $fname );
385 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
386 $this->makeList( $row, LIST_COMMA
) . ')';
387 $this->query( $sql, $fname );
391 # DELETE where the condition is a join
392 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
394 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
397 $delTable = $this->tableName( $delTable );
398 $joinTable = $this->tableName( $joinTable );
399 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
400 if ( $conds != '*' ) {
401 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
405 $this->query( $sql, $fname );
408 # Returns the size of a text field, or -1 for "unlimited"
409 function textFieldSize( $table, $field ) {
410 $table = $this->tableName( $table );
411 $sql = "SELECT t.typname as ftype,a.atttypmod as size
412 FROM pg_class c, pg_attribute a, pg_type t
413 WHERE relname='$table' AND a.attrelid=c.oid AND
414 a.atttypid=t.oid and a.attname='$field'";
415 $res =$this->query($sql);
416 $row=$this->fetchObject($res);
417 if ($row->ftype
=="varchar") {
422 $this->freeResult( $res );
426 function lowPriorityOption() {
430 function limitResult($sql, $limit,$offset) {
431 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
435 * Returns an SQL expression for a simple conditional.
436 * Uses CASE on PostgreSQL.
438 * @param string $cond SQL expression which will result in a boolean value
439 * @param string $trueVal SQL expression to return if true
440 * @param string $falseVal SQL expression to return if false
441 * @return string SQL fragment
443 function conditional( $cond, $trueVal, $falseVal ) {
444 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
447 # FIXME: actually detecting deadlocks might be nice
448 function wasDeadlock() {
452 # Return DB-style timestamp used for MySQL schema
453 function timestamp( $ts=0 ) {
454 return wfTimestamp(TS_DB
,$ts);
458 * Return aggregated value function call
460 function aggregateValue ($valuedata,$valuename='value') {
465 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
466 $message = "A database error has occurred\n" .
468 "Function: $fname\n" .
469 "Error: $errno $error\n";
470 throw new DBUnexpectedError($this, $message);
474 * @return string wikitext of a link to the server software's web site
476 function getSoftwareLink() {
477 return "[http://www.postgresql.org/ PostgreSQL]";
481 * @return string Version information from the database
483 function getServerVersion() {
484 $res = $this->query( "SELECT version()" );
485 $row = $this->fetchRow( $res );
487 $this->freeResult( $res );
493 * Query whether a given table exists (in the given schema, or the default mw one if not given)
495 function tableExists( $table, $schema = false ) {
496 global $wgDBmwschema;
498 $schema = $wgDBmwschema;
499 $etable = preg_replace("/'/", "''", $table);
500 $eschema = preg_replace("/'/", "''", $schema);
501 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
502 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema'";
503 $res = $this->query( $SQL );
504 $count = $res ?
pg_num_rows($res) : 0;
506 $this->freeResult( $res );
512 * Query whether a given schema exists. Returns the name of the owner
514 function schemaExists( $schema ) {
515 $eschema = preg_replace("/'/", "''", $schema);
516 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
517 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
518 $res = $this->query( $SQL );
519 $owner = $res ?
pg_num_rows($res) ?
pg_fetch_result($res, 0, 0) : false : false;
521 $this->freeResult($res);
526 * Query whether a given column exists in the mediawiki schema
528 function fieldExists( $table, $field ) {
529 global $wgDBmwschema;
530 $etable = preg_replace("/'/", "''", $table);
531 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
532 $ecol = preg_replace("/'/", "''", $field);
533 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
534 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
535 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
536 $res = $this->query( $SQL );
537 $count = $res ?
pg_num_rows($res) : 0;
539 $this->freeResult( $res );
543 function fieldInfo( $table, $field ) {
544 $res = $this->query( "SELECT $field FROM $table LIMIT 1" );
545 $type = pg_field_type( $res, 0 );
549 function commit( $fname = 'Database::commit' ) {
550 $this->query( 'COMMIT', $fname );
551 $this->mTrxLevel
= 0;
554 /* Not even sure why this is used in the main codebase... */
555 function limitResultForUpdate($sql, $num) {
559 function update_interwiki() {
560 ## Avoid the non-standard "REPLACE INTO" syntax
561 ## Called by config/index.php
562 $f = fopen( "../maintenance/interwiki.sql", 'r' );
564 dieout( "<li>Could not find the interwiki.sql file");
566 ## We simply assume it is already empty as we have just created it
567 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
568 while ( ! feof( $f ) ) {
569 $line = fgets($f,1024);
570 if (!preg_match("/^\s*(\(.+?),(\d)\)/", $line, $matches)) {
573 $yesno = $matches[2]; ## ? "'true'" : "'false'";
574 $this->query("$SQL $matches[1],$matches[2])");
576 print " (table interwiki successfully populated)...\n";
579 function encodeBlob($b) {
580 return array('bytea',pg_escape_bytea($b));
582 function decodeBlob($b) {
583 return pg_unescape_bytea( $b );
586 function strencode( $s ) { ## Should not be called by us
587 return pg_escape_string( $s );
590 function addQuotes( $s ) {
591 if ( is_null( $s ) ) {
593 } else if (is_array( $s )) { ## Assume it is bytea data
596 return "'" . pg_escape_string($s) . "'";
597 return "E'" . pg_escape_string($s) . "'";