4 * This is Postgres 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->mStrictIPs
= true;
36 $this->mFlags
= $flags;
37 $this->open( $server, $user, $password, $dbName);
41 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
42 $failFunction = false, $flags = 0)
44 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
48 * Usually aborts on failure
49 * If the failFunction is set to a non-zero integer, returns success
51 function open( $server, $user, $password, $dbName ) {
52 # Test for Postgres support, to avoid suppressed fatal error
53 if ( !function_exists( 'pg_connect' ) ) {
54 throw new DBConnectionError( $this, "Postgres functions missing, have you compiled PHP with the --with-pgsql option?\n (Note: if you recently installed PHP, you may need to restart your webserver and database)\n" );
61 $this->mServer
= $server;
64 $this->mPassword
= $password;
65 $this->mDBname
= $dbName;
69 if ($server!=false && $server!="") {
70 $hstring="host=$server ";
72 if ($port!=false && $port!="") {
73 $hstring .= "port=$port ";
76 if (!strlen($user)) { ## e.g. the class is being loaded
80 error_reporting( E_ALL
);
81 @$this->mConn
= pg_connect("$hstring dbname=$dbName user=$user password=$password");
83 if ( $this->mConn
== false ) {
84 wfDebug( "DB connection error\n" );
85 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
86 wfDebug( $this->lastError()."\n" );
90 $this->mOpened
= true;
91 ## If this is the initial connection, setup the schema stuff and possibly create the user
92 if (defined('MEDIAWIKI_INSTALL')) {
93 global $wgDBname, $wgDBuser, $wgDBpass, $wgDBsuperuser, $wgDBmwschema, $wgDBts2schema;
96 $safeuser = $this->quote_ident($wgDBuser);
97 ## Are we connecting as a superuser for the first time?
99 ## Are we really a superuser? Check out our rights
101 CASE WHEN usesuper IS TRUE THEN
102 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
103 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
105 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
106 $rows = $this->numRows($res = $this->doQuery($SQL));
108 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
111 $perms = pg_fetch_result($res, 0, 0);
113 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
114 $rows = $this->numRows($this->doQuery($SQL));
116 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
119 if ($perms != 1 and $perms != 3) {
120 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
121 print 'Please use a different Postgres user.</li>';
124 print "<li>Creating user <b>$wgDBuser</b>...";
125 $safepass = $this->addQuotes($wgDBpass);
126 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
127 $this->doQuery($SQL);
130 ## User now exists, check out the database
131 if ($dbName != $wgDBname) {
132 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
133 $rows = $this->numRows($this->doQuery($SQL));
135 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
139 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
140 print 'Please use a different Postgres user.</li>';
143 print "<li>Creating database <b>$wgDBname</b>...";
144 $safename = $this->quote_ident($wgDBname);
145 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
146 $this->doQuery($SQL);
148 ## Hopefully tsearch2 and plpgsql are in template1...
151 ## Reconnect to check out tsearch2 rights for this user
152 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
153 @$this->mConn
= pg_connect("$hstring dbname=$wgDBname user=$user password=$password");
154 if ( $this->mConn
== false ) {
155 print "<b>FAILED TO CONNECT!</b></li>";
162 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
163 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
164 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
165 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
166 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
170 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
171 foreach (array('cfg','cfgmap','dict','parser') as $table) {
172 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
173 $this->doQuery($SQL);
178 ## Setup the schema for this user if needed
179 $result = $this->schemaExists($wgDBmwschema);
180 $safeschema = $this->quote_ident($wgDBmwschema);
182 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
183 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
185 print "<b>FAILED</b>.</li>\n";
191 print "<li>Schema already exists, explicitly granting rights...\n";
192 $safeschema2 = $this->addQuotes($wgDBmwschema);
193 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
194 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
195 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
196 "AND p.relkind IN ('r','S','v')\n";
198 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
199 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
200 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
201 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
202 $res = $this->doQuery($SQL);
204 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
207 $this->doQuery("SET search_path = $safeschema");
208 $rows = $this->numRows($res);
211 $this->doQuery(pg_fetch_result($res, $rows, 0));
217 return true; ## Reconnect as regular user
220 if (!defined('POSTGRES_SEARCHPATH')) {
222 ## Do we have the basic tsearch2 table?
223 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
224 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
225 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
226 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
227 print " for instructions.</li>\n";
232 ## Does this user have the rights to the tsearch2 tables?
233 print "<li>Checking tsearch2 permissions...";
234 $SQL = "SELECT 1 FROM $wgDBts2schema.pg_ts_cfg";
235 error_reporting( 0 );
236 $res = $this->doQuery($SQL);
237 error_reporting( E_ALL
);
239 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" has SELECT access to the tsearch2 tables</li>\n";
244 ## Do we have plpgsql installed?
245 print "<li>Checking for Pl/Pgsql ...";
246 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
247 $rows = $this->numRows($this->doQuery($SQL));
249 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
250 print "not installed. Attempting to install Pl/Pgsql ...";
251 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
252 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
253 $rows = $this->numRows($this->doQuery($SQL));
255 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
257 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
262 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
268 ## Does the schema already exist? Who owns it?
269 $result = $this->schemaExists($wgDBmwschema);
271 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
272 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
274 print "<b>FAILED</b>.</li>\n";
279 else if ($result != $user) {
280 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
283 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
286 ## Fix up the search paths if needed
287 print "<li>Setting the search path for user \"$user\" ...";
288 $path = $this->quote_ident($wgDBmwschema);
289 if ($wgDBts2schema !== $wgDBmwschema)
290 $path .= ", ". $this->quote_ident($wgDBts2schema);
291 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
293 $SQL = "ALTER USER $safeuser SET search_path = $path";
294 $result = pg_query($this->mConn
, $SQL);
296 print "<b>FAILED</b>.</li>\n";
300 ## Set for the rest of this session
301 $SQL = "SET search_path = $path";
302 $result = pg_query($this->mConn
, $SQL);
304 print "<li>Failed to set search_path</li>\n";
307 define( "POSTGRES_SEARCHPATH", $path );
310 global $wgCommandLineMode;
311 ## If called from the command-line (e.g. importDump), only show errors
312 if ($wgCommandLineMode) {
313 $this->doQuery("SET client_min_messages = 'ERROR'");
320 * Closes a database connection, if it is open
321 * Returns success, true if already closed
324 $this->mOpened
= false;
325 if ( $this->mConn
) {
326 return pg_close( $this->mConn
);
332 function doQuery( $sql ) {
333 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
336 function queryIgnore( $sql, $fname = '' ) {
337 return $this->query( $sql, $fname, true );
340 function freeResult( $res ) {
341 if ( !@pg_free_result
( $res ) ) {
342 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
346 function fetchObject( $res ) {
347 @$row = pg_fetch_object( $res );
348 # FIXME: HACK HACK HACK HACK debug
351 # hashar : not sure if the following test really trigger if the object
353 if( pg_last_error($this->mConn
) ) {
354 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
359 function fetchRow( $res ) {
360 @$row = pg_fetch_array( $res );
361 if( pg_last_error($this->mConn
) ) {
362 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
367 function numRows( $res ) {
368 @$n = pg_num_rows( $res );
369 if( pg_last_error($this->mConn
) ) {
370 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
374 function numFields( $res ) { return pg_num_fields( $res ); }
375 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
378 * This must be called after nextSequenceVal
380 function insertId() {
381 return $this->mInsertId
;
384 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
385 function lastError() {
386 if ( $this->mConn
) {
387 return pg_last_error();
390 return "No database connection";
393 function lastErrno() {
394 return pg_last_error() ?
1 : 0;
397 function affectedRows() {
398 return pg_affected_rows( $this->mLastResult
);
402 * Returns information about an index
403 * If errors are explicitly ignored, returns NULL on failure
405 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
406 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
407 $res = $this->query( $sql, $fname );
412 while ( $row = $this->fetchObject( $res ) ) {
413 if ( $row->indexname
== $index ) {
420 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
421 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
422 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
423 $res = $this->query( $sql, $fname );
426 while ($row = $this->fetchObject( $res ))
432 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
433 # Postgres doesn't support options
434 # We have a go at faking one of them
435 # TODO: DELAYED, LOW_PRIORITY
437 if ( !is_array($options))
438 $options = array($options);
440 if ( in_array( 'IGNORE', $options ) )
441 $oldIgnore = $this->ignoreErrors( true );
443 # IGNORE is performed using single-row inserts, ignoring errors in each
444 # FIXME: need some way to distiguish between key collision and other types of error
445 $oldIgnore = $this->ignoreErrors( true );
446 if ( !is_array( reset( $a ) ) ) {
449 foreach ( $a as $row ) {
450 parent
::insert( $table, $row, $fname, array() );
452 $this->ignoreErrors( $oldIgnore );
455 if ( in_array( 'IGNORE', $options ) )
456 $this->ignoreErrors( $oldIgnore );
461 function tableName( $name ) {
462 # Replace reserved words with better ones
467 return 'pagecontent';
474 * Return the next in a sequence, save the value for retrieval via insertId()
476 function nextSequenceValue( $seqName ) {
477 $safeseq = preg_replace( "/'/", "''", $seqName );
478 $res = $this->query( "SELECT nextval('$safeseq')" );
479 $row = $this->fetchRow( $res );
480 $this->mInsertId
= $row[0];
481 $this->freeResult( $res );
482 return $this->mInsertId
;
486 * Postgres does not have a "USE INDEX" clause, so return an empty string
488 function useIndexClause( $index ) {
492 # REPLACE query wrapper
493 # Postgres simulates this with a DELETE followed by INSERT
494 # $row is the row to insert, an associative array
495 # $uniqueIndexes is an array of indexes. Each element may be either a
496 # field name or an array of field names
498 # It may be more efficient to leave off unique indexes which are unlikely to collide.
499 # However if you do this, you run the risk of encountering errors which wouldn't have
501 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
502 $table = $this->tableName( $table );
504 if (count($rows)==0) {
509 if ( !is_array( reset( $rows ) ) ) {
510 $rows = array( $rows );
513 foreach( $rows as $row ) {
514 # Delete rows which collide
515 if ( $uniqueIndexes ) {
516 $sql = "DELETE FROM $table WHERE ";
518 foreach ( $uniqueIndexes as $index ) {
525 if ( is_array( $index ) ) {
527 foreach ( $index as $col ) {
533 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
536 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
540 $this->query( $sql, $fname );
544 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
545 $this->makeList( $row, LIST_COMMA
) . ')';
546 $this->query( $sql, $fname );
550 # DELETE where the condition is a join
551 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
553 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
556 $delTable = $this->tableName( $delTable );
557 $joinTable = $this->tableName( $joinTable );
558 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
559 if ( $conds != '*' ) {
560 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
564 $this->query( $sql, $fname );
567 # Returns the size of a text field, or -1 for "unlimited"
568 function textFieldSize( $table, $field ) {
569 $table = $this->tableName( $table );
570 $sql = "SELECT t.typname as ftype,a.atttypmod as size
571 FROM pg_class c, pg_attribute a, pg_type t
572 WHERE relname='$table' AND a.attrelid=c.oid AND
573 a.atttypid=t.oid and a.attname='$field'";
574 $res =$this->query($sql);
575 $row=$this->fetchObject($res);
576 if ($row->ftype
=="varchar") {
581 $this->freeResult( $res );
585 function lowPriorityOption() {
589 function limitResult($sql, $limit,$offset) {
590 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
594 * Returns an SQL expression for a simple conditional.
595 * Uses CASE on Postgres
597 * @param string $cond SQL expression which will result in a boolean value
598 * @param string $trueVal SQL expression to return if true
599 * @param string $falseVal SQL expression to return if false
600 * @return string SQL fragment
602 function conditional( $cond, $trueVal, $falseVal ) {
603 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
606 # FIXME: actually detecting deadlocks might be nice
607 function wasDeadlock() {
611 function timestamp( $ts=0 ) {
612 return wfTimestamp(TS_POSTGRES
,$ts);
616 * Return aggregated value function call
618 function aggregateValue ($valuedata,$valuename='value') {
623 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
624 $message = "A database error has occurred\n" .
626 "Function: $fname\n" .
627 "Error: $errno $error\n";
628 throw new DBUnexpectedError($this, $message);
632 * @return string wikitext of a link to the server software's web site
634 function getSoftwareLink() {
635 return "[http://www.postgresql.org/ PostgreSQL]";
639 * @return string Version information from the database
641 function getServerVersion() {
642 $res = $this->query( "SELECT version()" );
643 $row = $this->fetchRow( $res );
645 $this->freeResult( $res );
651 * Query whether a given table exists (in the given schema, or the default mw one if not given)
653 function tableExists( $table, $schema = false ) {
654 global $wgDBmwschema;
656 $schema = $wgDBmwschema;
657 $etable = preg_replace("/'/", "''", $table);
658 $eschema = preg_replace("/'/", "''", $schema);
659 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
660 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
661 . "AND c.relkind IN ('r','v')";
662 $res = $this->query( $SQL );
663 $count = $res ?
pg_num_rows($res) : 0;
665 $this->freeResult( $res );
671 * Query whether a given schema exists. Returns the name of the owner
673 function schemaExists( $schema ) {
674 $eschema = preg_replace("/'/", "''", $schema);
675 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
676 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
677 $res = $this->query( $SQL );
678 $owner = $res ?
pg_num_rows($res) ?
pg_fetch_result($res, 0, 0) : false : false;
680 $this->freeResult($res);
685 * Query whether a given column exists in the mediawiki schema
687 function fieldExists( $table, $field ) {
688 global $wgDBmwschema;
689 $etable = preg_replace("/'/", "''", $table);
690 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
691 $ecol = preg_replace("/'/", "''", $field);
692 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
693 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
694 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
695 $res = $this->query( $SQL );
696 $count = $res ?
pg_num_rows($res) : 0;
698 $this->freeResult( $res );
702 function fieldInfo( $table, $field ) {
703 $res = $this->query( "SELECT $field FROM $table LIMIT 1" );
704 $type = pg_field_type( $res, 0 );
708 function begin( $fname = 'DatabasePostgrs::begin' ) {
709 $this->query( 'BEGIN', $fname );
710 $this->mTrxLevel
= 1;
712 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
715 function commit( $fname = 'DatabasePostgres::commit' ) {
716 $this->query( 'COMMIT', $fname );
717 $this->mTrxLevel
= 0;
720 /* Not even sure why this is used in the main codebase... */
721 function limitResultForUpdate($sql, $num) {
725 function setup_database() {
726 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport;
728 dbsource( "../maintenance/postgres/tables.sql", $this);
730 ## Update version information
731 $mwv = $this->addQuotes($wgVersion);
732 $pgv = $this->addQuotes($this->getServerVersion());
733 $pgu = $this->addQuotes($this->mUser
);
734 $mws = $this->addQuotes($wgDBmwschema);
735 $tss = $this->addQuotes($wgDBts2schema);
736 $pgp = $this->addQuotes($wgDBport);
737 $dbn = $this->addQuotes($this->mDBname
);
739 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
740 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn ".
741 "WHERE type = 'Creation'";
744 ## Avoid the non-standard "REPLACE INTO" syntax
745 $f = fopen( "../maintenance/interwiki.sql", 'r' );
747 dieout( "<li>Could not find the interwiki.sql file");
749 ## We simply assume it is already empty as we have just created it
750 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
751 while ( ! feof( $f ) ) {
752 $line = fgets($f,1024);
753 if (!preg_match("/^\s*(\(.+?),(\d)\)/", $line, $matches)) {
756 $yesno = $matches[2]; ## ? "'true'" : "'false'";
757 $this->query("$SQL $matches[1],$matches[2])");
759 print " (table interwiki successfully populated)...\n";
762 function encodeBlob($b) {
763 return array('bytea',pg_escape_bytea($b));
765 function decodeBlob($b) {
766 return pg_unescape_bytea( $b );
769 function strencode( $s ) { ## Should not be called by us
770 return pg_escape_string( $s );
773 function addQuotes( $s ) {
774 if ( is_null( $s ) ) {
776 } else if (is_array( $s )) { ## Assume it is bytea data
779 return "'" . pg_escape_string($s) . "'";
780 return "E'" . pg_escape_string($s) . "'";
783 function quote_ident( $s ) {
784 return '"' . preg_replace( '/"/', '""', $s) . '"';