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->mCascadingDeletes
= true;
34 $this->mCleanupTriggers
= true;
35 $this->mFlags
= $flags;
36 $this->open( $server, $user, $password, $dbName);
40 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
41 $failFunction = false, $flags = 0)
43 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
47 * Usually aborts on failure
48 * If the failFunction is set to a non-zero integer, returns success
50 function open( $server, $user, $password, $dbName ) {
51 # Test for PostgreSQL support, to avoid suppressed fatal error
52 if ( !function_exists( 'pg_connect' ) ) {
53 throw new DBConnectionError( $this, "PostgreSQL functions missing, have you compiled PHP with the --with-pgsql option?\n" );
60 $this->mServer
= $server;
63 $this->mPassword
= $password;
64 $this->mDBname
= $dbName;
68 if ($server!=false && $server!="") {
69 $hstring="host=$server ";
71 if ($port!=false && $port!="") {
72 $hstring .= "port=$port ";
75 if (!strlen($user)) { ## e.g. the class is being loaded
79 error_reporting( E_ALL
);
80 @$this->mConn
= pg_connect("$hstring dbname=$dbName user=$user password=$password");
82 if ( $this->mConn
== false ) {
83 wfDebug( "DB connection error\n" );
84 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
85 wfDebug( $this->lastError()."\n" );
89 $this->mOpened
= true;
90 ## If this is the initial connection, setup the schema stuff and possibly create the user
91 if (defined('MEDIAWIKI_INSTALL')) {
92 global $wgDBname, $wgDBuser, $wgDBpass, $wgDBsuperuser, $wgDBmwschema, $wgDBts2schema;
95 ## Are we connecting as a superuser for the first time?
97 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
98 $rows = $this->numRows($this->doQuery($SQL));
100 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
103 ## Can we create users?
104 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usesuper IS TRUE AND ".
105 "usename = " . $this->addQuotes($wgDBsuperuser);
106 $rows = $this->numRows($this->doQuery($SQL));
108 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
109 print 'Please use a different Postgres user.</li>';
112 print "<li>Creating user <b>$wgDBuser</b>...";
113 $safepass = $this->addQuotes($wgDBpass);
114 $SQL = "CREATE USER \"$wgDBuser\" NOCREATEDB PASSWORD $safepass";
115 $this->doQuery($SQL);
118 ## User now exists, check out the database
119 $safename = $this->addQuotes($wgDBname);
120 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = $safename";
121 $rows = $this->numRows($this->doQuery($SQL));
123 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
126 print "<li>Creating database <b>$wgDBname</b>...";
127 $SQL = "CREATE DATABASE \"$wgDBname\" OWNER \"$wgDBuser\" ";
128 $this->doQuery($SQL);
130 ## Hopefully tsearch2 and plpgsql are in template1...
133 ## Reconnect to check out tsearch2 rights for this user
134 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
135 @$this->mConn
= pg_connect("$hstring dbname=$wgDBname user=$user password=$password");
136 if ( $this->mConn
== false ) {
137 print "<b>FAILED TO CONNECT!</b></li>";
141 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
142 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
143 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
144 print "Please see 'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
145 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
149 print "Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
150 foreach (array('cfg','cfgmap','dict','parser') as $table) {
151 $SQL = "GRANT SELECT ON pg_ts_$table TO \"$wgDBuser\"";
152 $this->doQuery($SQL);
156 return true; ## Reconnect as regular user
159 if (!defined('POSTGRES_SEARCHPATH')) {
161 ## Do we have the basic tsearch2 table?
162 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
163 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
164 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
165 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
166 print " for instructions.</li>\n";
171 ## Does this user have the rights to the tsearch2 tables?
172 print "<li>Checking tsearch2 permissions...";
173 $SQL = "SELECT 1 FROM $wgDBts2schema.pg_ts_cfg";
174 error_reporting( 0 );
175 $res = $this->doQuery($SQL);
176 error_reporting( E_ALL
);
178 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" has SELECT access to the tsearch2 tables</li>\n";
183 ## Do we have plpgsql installed?
184 print "<li>Checking for plpgsql ...";
185 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
186 $rows = $this->numRows($this->doQuery($SQL));
188 print "<b>FAILED</b>. Make sure the language plpgsql is installed for the database <tt>$wgDBname</tt></li>";
193 ## Does the schema already exist? Who owns it?
194 $result = $this->schemaExists($wgDBmwschema);
196 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
197 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
199 print "<b>FAILED</b>.</li>\n";
204 else if ($result != $user) {
205 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
208 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
211 ## Fix up the search paths if needed
212 print "<li>Setting the search path for user \"$user\" ...";
213 $path = "$wgDBmwschema";
214 if ($wgDBts2schema !== $wgDBmwschema)
215 $path .= ", $wgDBts2schema";
216 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
218 $SQL = "ALTER USER $user SET search_path = $path";
219 $result = pg_query($this->mConn
, $SQL);
221 print "<b>FAILED</b>.</li>\n";
225 ## Set for the rest of this session
226 $SQL = "SET search_path = $path";
227 $result = pg_query($this->mConn
, $SQL);
229 print "<li>Failed to set search_path</li>\n";
232 define( "POSTGRES_SEARCHPATH", $path );
239 * Closes a database connection, if it is open
240 * Returns success, true if already closed
243 $this->mOpened
= false;
244 if ( $this->mConn
) {
245 return pg_close( $this->mConn
);
251 function doQuery( $sql ) {
252 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
255 function queryIgnore( $sql, $fname = '' ) {
256 return $this->query( $sql, $fname, true );
259 function freeResult( $res ) {
260 if ( !@pg_free_result
( $res ) ) {
261 throw new DBUnexpectedError($this, "Unable to free PostgreSQL result\n" );
265 function fetchObject( $res ) {
266 @$row = pg_fetch_object( $res );
267 # FIXME: HACK HACK HACK HACK debug
270 # hashar : not sure if the following test really trigger if the object
272 if( pg_last_error($this->mConn
) ) {
273 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
278 function fetchRow( $res ) {
279 @$row = pg_fetch_array( $res );
280 if( pg_last_error($this->mConn
) ) {
281 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
286 function numRows( $res ) {
287 @$n = pg_num_rows( $res );
288 if( pg_last_error($this->mConn
) ) {
289 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
293 function numFields( $res ) { return pg_num_fields( $res ); }
294 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
297 * This must be called after nextSequenceVal
299 function insertId() {
300 return $this->mInsertId
;
303 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
304 function lastError() {
305 if ( $this->mConn
) {
306 return pg_last_error();
309 return "No database connection";
312 function lastErrno() {
313 return pg_last_error() ?
1 : 0;
316 function affectedRows() {
317 return pg_affected_rows( $this->mLastResult
);
321 * Returns information about an index
322 * If errors are explicitly ignored, returns NULL on failure
324 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
325 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
326 $res = $this->query( $sql, $fname );
331 while ( $row = $this->fetchObject( $res ) ) {
332 if ( $row->indexname
== $index ) {
339 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
340 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
341 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
342 $res = $this->query( $sql, $fname );
345 while ($row = $this->fetchObject( $res ))
351 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
352 # PostgreSQL doesn't support options
353 # We have a go at faking one of them
354 # TODO: DELAYED, LOW_PRIORITY
356 if ( !is_array($options))
357 $options = array($options);
359 if ( in_array( 'IGNORE', $options ) )
360 $oldIgnore = $this->ignoreErrors( true );
362 # IGNORE is performed using single-row inserts, ignoring errors in each
363 # FIXME: need some way to distiguish between key collision and other types of error
364 $oldIgnore = $this->ignoreErrors( true );
365 if ( !is_array( reset( $a ) ) ) {
368 foreach ( $a as $row ) {
369 parent
::insert( $table, $row, $fname, array() );
371 $this->ignoreErrors( $oldIgnore );
374 if ( in_array( 'IGNORE', $options ) )
375 $this->ignoreErrors( $oldIgnore );
380 function tableName( $name ) {
381 # Replace backticks into double quotes
382 $name = strtr($name,'`','"');
384 # Now quote PG reserved keywords
389 return '"' . $name . '"';
397 * Return the next in a sequence, save the value for retrieval via insertId()
399 function nextSequenceValue( $seqName ) {
400 $safeseq = preg_replace( "/'/", "''", $seqName );
401 $res = $this->query( "SELECT nextval('$safeseq')" );
402 $row = $this->fetchRow( $res );
403 $this->mInsertId
= $row[0];
404 $this->freeResult( $res );
405 return $this->mInsertId
;
410 * PostgreSQL doesn't have them and returns ""
412 function useIndexClause( $index ) {
416 # REPLACE query wrapper
417 # PostgreSQL simulates this with a DELETE followed by INSERT
418 # $row is the row to insert, an associative array
419 # $uniqueIndexes is an array of indexes. Each element may be either a
420 # field name or an array of field names
422 # It may be more efficient to leave off unique indexes which are unlikely to collide.
423 # However if you do this, you run the risk of encountering errors which wouldn't have
425 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
426 $table = $this->tableName( $table );
428 if (count($rows)==0) {
433 if ( !is_array( reset( $rows ) ) ) {
434 $rows = array( $rows );
437 foreach( $rows as $row ) {
438 # Delete rows which collide
439 if ( $uniqueIndexes ) {
440 $sql = "DELETE FROM $table WHERE ";
442 foreach ( $uniqueIndexes as $index ) {
449 if ( is_array( $index ) ) {
451 foreach ( $index as $col ) {
457 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
460 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
464 $this->query( $sql, $fname );
468 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
469 $this->makeList( $row, LIST_COMMA
) . ')';
470 $this->query( $sql, $fname );
474 # DELETE where the condition is a join
475 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
477 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
480 $delTable = $this->tableName( $delTable );
481 $joinTable = $this->tableName( $joinTable );
482 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
483 if ( $conds != '*' ) {
484 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
488 $this->query( $sql, $fname );
491 # Returns the size of a text field, or -1 for "unlimited"
492 function textFieldSize( $table, $field ) {
493 $table = $this->tableName( $table );
494 $sql = "SELECT t.typname as ftype,a.atttypmod as size
495 FROM pg_class c, pg_attribute a, pg_type t
496 WHERE relname='$table' AND a.attrelid=c.oid AND
497 a.atttypid=t.oid and a.attname='$field'";
498 $res =$this->query($sql);
499 $row=$this->fetchObject($res);
500 if ($row->ftype
=="varchar") {
505 $this->freeResult( $res );
509 function lowPriorityOption() {
513 function limitResult($sql, $limit,$offset) {
514 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
518 * Returns an SQL expression for a simple conditional.
519 * Uses CASE on PostgreSQL.
521 * @param string $cond SQL expression which will result in a boolean value
522 * @param string $trueVal SQL expression to return if true
523 * @param string $falseVal SQL expression to return if false
524 * @return string SQL fragment
526 function conditional( $cond, $trueVal, $falseVal ) {
527 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
530 # FIXME: actually detecting deadlocks might be nice
531 function wasDeadlock() {
535 function timestamp( $ts=0 ) {
536 return wfTimestamp(TS_POSTGRES
,$ts);
540 * Return aggregated value function call
542 function aggregateValue ($valuedata,$valuename='value') {
547 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
548 $message = "A database error has occurred\n" .
550 "Function: $fname\n" .
551 "Error: $errno $error\n";
552 throw new DBUnexpectedError($this, $message);
556 * @return string wikitext of a link to the server software's web site
558 function getSoftwareLink() {
559 return "[http://www.postgresql.org/ PostgreSQL]";
563 * @return string Version information from the database
565 function getServerVersion() {
566 $res = $this->query( "SELECT version()" );
567 $row = $this->fetchRow( $res );
569 $this->freeResult( $res );
575 * Query whether a given table exists (in the given schema, or the default mw one if not given)
577 function tableExists( $table, $schema = false ) {
578 global $wgDBmwschema;
580 $schema = $wgDBmwschema;
581 $etable = preg_replace("/'/", "''", $table);
582 $eschema = preg_replace("/'/", "''", $schema);
583 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
584 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema'";
585 $res = $this->query( $SQL );
586 $count = $res ?
pg_num_rows($res) : 0;
588 $this->freeResult( $res );
594 * Query whether a given schema exists. Returns the name of the owner
596 function schemaExists( $schema ) {
597 $eschema = preg_replace("/'/", "''", $schema);
598 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
599 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
600 $res = $this->query( $SQL );
601 $owner = $res ?
pg_num_rows($res) ?
pg_fetch_result($res, 0, 0) : false : false;
603 $this->freeResult($res);
608 * Query whether a given column exists in the mediawiki schema
610 function fieldExists( $table, $field ) {
611 global $wgDBmwschema;
612 $etable = preg_replace("/'/", "''", $table);
613 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
614 $ecol = preg_replace("/'/", "''", $field);
615 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
616 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
617 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
618 $res = $this->query( $SQL );
619 $count = $res ?
pg_num_rows($res) : 0;
621 $this->freeResult( $res );
625 function fieldInfo( $table, $field ) {
626 $res = $this->query( "SELECT $field FROM $table LIMIT 1" );
627 $type = pg_field_type( $res, 0 );
631 function begin( $fname = 'DatabasePostgrs::begin' ) {
632 $this->query( 'BEGIN', $fname );
633 $this->mTrxLevel
= 1;
635 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
638 function commit( $fname = 'DatabasePostgres::commit' ) {
639 $this->query( 'COMMIT', $fname );
640 $this->mTrxLevel
= 0;
643 /* Not even sure why this is used in the main codebase... */
644 function limitResultForUpdate($sql, $num) {
648 function setup_database() {
649 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport;
651 dbsource( "../maintenance/postgres/tables.sql", $this);
653 ## Update version information
654 $mwv = $this->addQuotes($wgVersion);
655 $pgv = $this->addQuotes($this->getServerVersion());
656 $pgu = $this->addQuotes($this->mUser
);
657 $mws = $this->addQuotes($wgDBmwschema);
658 $tss = $this->addQuotes($wgDBts2schema);
659 $pgp = $this->addQuotes($wgDBport);
660 $dbn = $this->addQuotes($this->mDBname
);
662 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
663 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn ".
664 "WHERE type = 'Creation'";
667 ## Avoid the non-standard "REPLACE INTO" syntax
668 $f = fopen( "../maintenance/interwiki.sql", 'r' );
670 dieout( "<li>Could not find the interwiki.sql file");
672 ## We simply assume it is already empty as we have just created it
673 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
674 while ( ! feof( $f ) ) {
675 $line = fgets($f,1024);
676 if (!preg_match("/^\s*(\(.+?),(\d)\)/", $line, $matches)) {
679 $yesno = $matches[2]; ## ? "'true'" : "'false'";
680 $this->query("$SQL $matches[1],$matches[2])");
682 print " (table interwiki successfully populated)...\n";
685 function encodeBlob($b) {
686 return array('bytea',pg_escape_bytea($b));
688 function decodeBlob($b) {
689 return pg_unescape_bytea( $b );
692 function strencode( $s ) { ## Should not be called by us
693 return pg_escape_string( $s );
696 function addQuotes( $s ) {
697 if ( is_null( $s ) ) {
699 } else if (is_array( $s )) { ## Assume it is bytea data
702 return "'" . pg_escape_string($s) . "'";
703 return "E'" . pg_escape_string($s) . "'";