5ba0d3b5302feedc98f44cbee1207f66e6221127
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;
90 ## Do we have the basic tsearch2 table?
91 print "<li>Checking for tsearch2 ...";
92 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
93 print "FAILED. 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 ## Does the schema already exist? Who owns it?
101 $result = $this->schemaExists($wgDBmwschema);
103 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
104 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
106 print "FAILED.</li>\n";
111 else if ($result != $user) {
112 print "<li>Schema <b>$wgDBmwschema</b> exists but is not owned by <b>$user</b>. Not ideal.</li>\n";
115 print "<li>Schema <b>$wgDBmwschema</b> exists and is owned by <b>$user ($result)</b>. Excellent.</li>\n";
118 ## Fix up the search paths if needed
119 print "<li>Setting the search path for user <b>$user</b> ...";
120 $path = "$wgDBmwschema";
121 if ($wgDBts2schema !== $wgDBmwschema)
122 $path .= ", $wgDBts2schema";
123 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
125 $SQL = "ALTER USER $user SET search_path = $path";
126 $result = pg_query($this->mConn
, $SQL);
128 print "FAILED.</li>\n";
132 ## Set for the rest of this session
133 $SQL = "SET search_path = $path";
134 $result = pg_query($this->mConn
, $SQL);
136 print "<li>Failed to set search_path</li>\n";
139 define( "POSTGRES_SEARCHPATH", $path );
146 * Closes a database connection, if it is open
147 * Returns success, true if already closed
150 $this->mOpened
= false;
151 if ( $this->mConn
) {
152 return pg_close( $this->mConn
);
158 function doQuery( $sql ) {
159 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
162 function queryIgnore( $sql, $fname = '' ) {
163 return $this->query( $sql, $fname, true );
166 function freeResult( $res ) {
167 if ( !@pg_free_result
( $res ) ) {
168 throw new DBUnexpectedError($this, "Unable to free PostgreSQL result\n" );
172 function fetchObject( $res ) {
173 @$row = pg_fetch_object( $res );
174 # FIXME: HACK HACK HACK HACK debug
177 # hashar : not sure if the following test really trigger if the object
179 if( pg_last_error($this->mConn
) ) {
180 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
185 function fetchRow( $res ) {
186 @$row = pg_fetch_array( $res );
187 if( pg_last_error($this->mConn
) ) {
188 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
193 function numRows( $res ) {
194 @$n = pg_num_rows( $res );
195 if( pg_last_error($this->mConn
) ) {
196 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
200 function numFields( $res ) { return pg_num_fields( $res ); }
201 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
204 * This must be called after nextSequenceVal
206 function insertId() {
207 return $this->mInsertId
;
210 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
211 function lastError() {
212 if ( $this->mConn
) {
213 return pg_last_error();
216 return "No database connection";
219 function lastErrno() { return 1; }
221 function affectedRows() {
222 return pg_affected_rows( $this->mLastResult
);
226 * Returns information about an index
227 * If errors are explicitly ignored, returns NULL on failure
229 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
230 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
231 $res = $this->query( $sql, $fname );
236 while ( $row = $this->fetchObject( $res ) ) {
237 if ( $row->indexname
== $index ) {
244 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
245 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
246 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
247 $res = $this->query( $sql, $fname );
250 while ($row = $this->fetchObject( $res ))
256 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
257 # PostgreSQL doesn't support options
258 # We have a go at faking one of them
259 # TODO: DELAYED, LOW_PRIORITY
261 if ( !is_array($options))
262 $options = array($options);
264 if ( in_array( 'IGNORE', $options ) )
265 $oldIgnore = $this->ignoreErrors( true );
267 # IGNORE is performed using single-row inserts, ignoring errors in each
268 # FIXME: need some way to distiguish between key collision and other types of error
269 $oldIgnore = $this->ignoreErrors( true );
270 if ( !is_array( reset( $a ) ) ) {
273 foreach ( $a as $row ) {
274 parent
::insert( $table, $row, $fname, array() );
276 $this->ignoreErrors( $oldIgnore );
279 if ( in_array( 'IGNORE', $options ) )
280 $this->ignoreErrors( $oldIgnore );
285 function tableName( $name ) {
286 # Replace backticks into double quotes
287 $name = strtr($name,'`','"');
289 # Now quote PG reserved keywords
294 return '"' . $name . '"';
301 function strencode( $s ) {
302 return pg_escape_string( $s );
306 * Return the next in a sequence, save the value for retrieval via insertId()
308 function nextSequenceValue( $seqName ) {
309 $value = $this->selectField(''," nextval('" . $seqName . "')");
310 $this->mInsertId
= $value;
316 * PostgreSQL doesn't have them and returns ""
318 function useIndexClause( $index ) {
322 # REPLACE query wrapper
323 # PostgreSQL simulates this with a DELETE followed by INSERT
324 # $row is the row to insert, an associative array
325 # $uniqueIndexes is an array of indexes. Each element may be either a
326 # field name or an array of field names
328 # It may be more efficient to leave off unique indexes which are unlikely to collide.
329 # However if you do this, you run the risk of encountering errors which wouldn't have
331 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
332 $table = $this->tableName( $table );
334 if (count($rows)==0) {
339 if ( !is_array( reset( $rows ) ) ) {
340 $rows = array( $rows );
343 foreach( $rows as $row ) {
344 # Delete rows which collide
345 if ( $uniqueIndexes ) {
346 $sql = "DELETE FROM $table WHERE ";
348 foreach ( $uniqueIndexes as $index ) {
355 if ( is_array( $index ) ) {
357 foreach ( $index as $col ) {
363 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
366 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
370 $this->query( $sql, $fname );
374 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
375 $this->makeList( $row, LIST_COMMA
) . ')';
376 $this->query( $sql, $fname );
380 # DELETE where the condition is a join
381 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
383 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
386 $delTable = $this->tableName( $delTable );
387 $joinTable = $this->tableName( $joinTable );
388 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
389 if ( $conds != '*' ) {
390 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
394 $this->query( $sql, $fname );
397 # Returns the size of a text field, or -1 for "unlimited"
398 function textFieldSize( $table, $field ) {
399 $table = $this->tableName( $table );
400 $sql = "SELECT t.typname as ftype,a.atttypmod as size
401 FROM pg_class c, pg_attribute a, pg_type t
402 WHERE relname='$table' AND a.attrelid=c.oid AND
403 a.atttypid=t.oid and a.attname='$field'";
404 $res =$this->query($sql);
405 $row=$this->fetchObject($res);
406 if ($row->ftype
=="varchar") {
411 $this->freeResult( $res );
415 function lowPriorityOption() {
419 function limitResult($sql, $limit,$offset) {
420 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
424 * Returns an SQL expression for a simple conditional.
425 * Uses CASE on PostgreSQL.
427 * @param string $cond SQL expression which will result in a boolean value
428 * @param string $trueVal SQL expression to return if true
429 * @param string $falseVal SQL expression to return if false
430 * @return string SQL fragment
432 function conditional( $cond, $trueVal, $falseVal ) {
433 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
436 # FIXME: actually detecting deadlocks might be nice
437 function wasDeadlock() {
441 # Return DB-style timestamp used for MySQL schema
442 function timestamp( $ts=0 ) {
443 return wfTimestamp(TS_DB
,$ts);
447 * Return aggregated value function call
449 function aggregateValue ($valuedata,$valuename='value') {
454 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
455 $message = "A database error has occurred\n" .
457 "Function: $fname\n" .
458 "Error: $errno $error\n";
459 throw new DBUnexpectedError($this, $message);
463 * @return string wikitext of a link to the server software's web site
465 function getSoftwareLink() {
466 return "[http://www.postgresql.org/ PostgreSQL]";
470 * @return string Version information from the database
472 function getServerVersion() {
473 $res = $this->query( "SELECT version()" );
474 $row = $this->fetchRow( $res );
476 $this->freeResult( $res );
482 * Query whether a given table exists (in the given schema, or the default mw one if not given)
484 function tableExists( $table, $schema = false ) {
485 global $wgDBmwschema;
487 $schema = $wgDBmwschema;
488 $etable = preg_replace("/'/", "''", $table);
489 $eschema = preg_replace("/'/", "''", $schema);
490 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
491 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema'";
492 $res = $this->query( $SQL );
493 $count = $res ?
pg_num_rows($res) : 0;
495 $this->freeResult( $res );
501 * Query whether a given schema exists. Returns the name of the owner
503 function schemaExists( $schema ) {
504 $eschema = preg_replace("/'/", "''", $schema);
505 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
506 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
507 $res = $this->query( $SQL );
508 $owner = $res ?
pg_num_rows($res) ?
pg_fetch_result($res, 0, 0) : false : false;
510 $this->freeResult($res);
515 * Query whether a given column exists in the mediawiki schema
517 function fieldExists( $table, $field ) {
518 global $wgDBmwschema;
519 $etable = preg_replace("/'/", "''", $table);
520 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
521 $ecol = preg_replace("/'/", "''", $field);
522 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
523 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
524 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
525 $res = $this->query( $SQL );
526 $count = $res ?
pg_num_rows($res) : 0;
528 $this->freeResult( $res );
532 function fieldInfo( $table, $field ) {
533 $res = $this->query( "SELECT $field FROM $table LIMIT 1" );
534 $type = pg_field_type( $res, 0 );
538 function commit( $fname = 'Database::commit' ) {
541 $this->query( 'COMMIT', $fname );
542 $this->mTrxLevel
= 0;
545 /* Not even sure why this is used in the main codebase... */
546 function limitResultForUpdate($sql, $num) {
550 function update_interwiki() {
551 ## Avoid the non-standard "REPLACE INTO" syntax
552 ## Called by config/index.php
553 $f = fopen( "../maintenance/interwiki.sql", 'r' );
555 dieout( "<li>Could not find the interwiki.sql file");
557 ## We simply assume it is already empty as we have just created it
558 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
559 while ( ! feof( $f ) ) {
560 $line = fgets($f,1024);
561 if (!preg_match("/^\s*(\(.+?),(\d)\)/", $line, $matches)) {
564 $yesno = $matches[2]; ## ? "'true'" : "'false'";
565 $this->query("$SQL $matches[1],$matches[2])");
567 print " (table interwiki successfully populated)...\n";