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->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 Postgres support, to avoid suppressed fatal error
52 if ( !function_exists( 'pg_connect' ) ) {
53 throw new DBConnectionError( $this, "Postgres 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 $safeuser = $this->quote_ident($wgDBuser);
96 ## Are we connecting as a superuser for the first time?
98 ## Are we really a superuser? Check out our rights
100 CASE WHEN usesuper IS TRUE THEN
101 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
102 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
104 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
105 $rows = $this->numRows($res = $this->doQuery($SQL));
107 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
110 $perms = pg_fetch_result($res, 0, 0);
112 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
113 $rows = $this->numRows($this->doQuery($SQL));
115 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
118 if ($perms != 1 and $perms != 3) {
119 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
120 print 'Please use a different Postgres user.</li>';
123 print "<li>Creating user <b>$wgDBuser</b>...";
124 $safepass = $this->addQuotes($wgDBpass);
125 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
126 $this->doQuery($SQL);
129 ## User now exists, check out the database
130 if ($dbName != $wgDBname) {
131 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
132 $rows = $this->numRows($this->doQuery($SQL));
134 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
138 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
139 print 'Please use a different Postgres user.</li>';
142 print "<li>Creating database <b>$wgDBname</b>...";
143 $safename = $this->quote_ident($wgDBname);
144 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
145 $this->doQuery($SQL);
147 ## Hopefully tsearch2 and plpgsql are in template1...
150 ## Reconnect to check out tsearch2 rights for this user
151 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
152 @$this->mConn
= pg_connect("$hstring dbname=$wgDBname user=$user password=$password");
153 if ( $this->mConn
== false ) {
154 print "<b>FAILED TO CONNECT!</b></li>";
161 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
162 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
163 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
164 print "Please see 'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
165 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
169 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
170 foreach (array('cfg','cfgmap','dict','parser') as $table) {
171 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
172 $this->doQuery($SQL);
177 ## Setup the schema for this user if needed
178 $result = $this->schemaExists($wgDBmwschema);
179 $safeschema = $this->quote_ident($wgDBmwschema);
181 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
182 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
184 print "<b>FAILED</b>.</li>\n";
190 print "<li>Schema already exists, explicitly granting rights...\n";
191 $safeschema2 = $this->addQuotes($wgDBmwschema);
192 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
193 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
194 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
195 "AND p.relkind IN ('r','S','v')\n";
197 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
198 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
199 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
200 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
201 $res = $this->doQuery($SQL);
203 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
206 $this->doQuery("SET search_path = $safeschema");
207 $rows = $this->numRows($res);
210 $this->doQuery(pg_fetch_result($res, $rows, 0));
216 return true; ## Reconnect as regular user
219 if (!defined('POSTGRES_SEARCHPATH')) {
221 ## Do we have the basic tsearch2 table?
222 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
223 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
224 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
225 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
226 print " for instructions.</li>\n";
231 ## Does this user have the rights to the tsearch2 tables?
232 print "<li>Checking tsearch2 permissions...";
233 $SQL = "SELECT 1 FROM $wgDBts2schema.pg_ts_cfg";
234 error_reporting( 0 );
235 $res = $this->doQuery($SQL);
236 error_reporting( E_ALL
);
238 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" has SELECT access to the tsearch2 tables</li>\n";
243 ## Do we have plpgsql installed?
244 print "<li>Checking for Pl/Pgsql ...";
245 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
246 $rows = $this->numRows($this->doQuery($SQL));
248 print "<b>FAILED</b>. Make sure the language plpgsql is installed for the database <tt>$wgDBname</tt></li>";
253 ## Does the schema already exist? Who owns it?
254 $result = $this->schemaExists($wgDBmwschema);
256 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
257 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
259 print "<b>FAILED</b>.</li>\n";
264 else if ($result != $user) {
265 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
268 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
271 ## Fix up the search paths if needed
272 print "<li>Setting the search path for user \"$user\" ...";
273 $path = $this->quote_ident($wgDBmwschema);
274 if ($wgDBts2schema !== $wgDBmwschema)
275 $path .= ", ". $this->quote_ident($wgDBts2schema);
276 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
278 $SQL = "ALTER USER $safeuser SET search_path = $path";
279 $result = pg_query($this->mConn
, $SQL);
281 print "<b>FAILED</b>.</li>\n";
285 ## Set for the rest of this session
286 $SQL = "SET search_path = $path";
287 $result = pg_query($this->mConn
, $SQL);
289 print "<li>Failed to set search_path</li>\n";
292 define( "POSTGRES_SEARCHPATH", $path );
299 * Closes a database connection, if it is open
300 * Returns success, true if already closed
303 $this->mOpened
= false;
304 if ( $this->mConn
) {
305 return pg_close( $this->mConn
);
311 function doQuery( $sql ) {
312 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
315 function queryIgnore( $sql, $fname = '' ) {
316 return $this->query( $sql, $fname, true );
319 function freeResult( $res ) {
320 if ( !@pg_free_result
( $res ) ) {
321 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
325 function fetchObject( $res ) {
326 @$row = pg_fetch_object( $res );
327 # FIXME: HACK HACK HACK HACK debug
330 # hashar : not sure if the following test really trigger if the object
332 if( pg_last_error($this->mConn
) ) {
333 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
338 function fetchRow( $res ) {
339 @$row = pg_fetch_array( $res );
340 if( pg_last_error($this->mConn
) ) {
341 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
346 function numRows( $res ) {
347 @$n = pg_num_rows( $res );
348 if( pg_last_error($this->mConn
) ) {
349 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
353 function numFields( $res ) { return pg_num_fields( $res ); }
354 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
357 * This must be called after nextSequenceVal
359 function insertId() {
360 return $this->mInsertId
;
363 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
364 function lastError() {
365 if ( $this->mConn
) {
366 return pg_last_error();
369 return "No database connection";
372 function lastErrno() {
373 return pg_last_error() ?
1 : 0;
376 function affectedRows() {
377 return pg_affected_rows( $this->mLastResult
);
381 * Returns information about an index
382 * If errors are explicitly ignored, returns NULL on failure
384 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
385 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
386 $res = $this->query( $sql, $fname );
391 while ( $row = $this->fetchObject( $res ) ) {
392 if ( $row->indexname
== $index ) {
399 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
400 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
401 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
402 $res = $this->query( $sql, $fname );
405 while ($row = $this->fetchObject( $res ))
411 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
412 # Postgres doesn't support options
413 # We have a go at faking one of them
414 # TODO: DELAYED, LOW_PRIORITY
416 if ( !is_array($options))
417 $options = array($options);
419 if ( in_array( 'IGNORE', $options ) )
420 $oldIgnore = $this->ignoreErrors( true );
422 # IGNORE is performed using single-row inserts, ignoring errors in each
423 # FIXME: need some way to distiguish between key collision and other types of error
424 $oldIgnore = $this->ignoreErrors( true );
425 if ( !is_array( reset( $a ) ) ) {
428 foreach ( $a as $row ) {
429 parent
::insert( $table, $row, $fname, array() );
431 $this->ignoreErrors( $oldIgnore );
434 if ( in_array( 'IGNORE', $options ) )
435 $this->ignoreErrors( $oldIgnore );
440 function tableName( $name ) {
441 # Replace reserved words with better ones
446 return 'pagecontent';
453 * Return the next in a sequence, save the value for retrieval via insertId()
455 function nextSequenceValue( $seqName ) {
456 $safeseq = preg_replace( "/'/", "''", $seqName );
457 $res = $this->query( "SELECT nextval('$safeseq')" );
458 $row = $this->fetchRow( $res );
459 $this->mInsertId
= $row[0];
460 $this->freeResult( $res );
461 return $this->mInsertId
;
465 * Postgres does not have a "USE INDEX" clause, so return an empty string
467 function useIndexClause( $index ) {
471 # REPLACE query wrapper
472 # Postgres simulates this with a DELETE followed by INSERT
473 # $row is the row to insert, an associative array
474 # $uniqueIndexes is an array of indexes. Each element may be either a
475 # field name or an array of field names
477 # It may be more efficient to leave off unique indexes which are unlikely to collide.
478 # However if you do this, you run the risk of encountering errors which wouldn't have
480 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
481 $table = $this->tableName( $table );
483 if (count($rows)==0) {
488 if ( !is_array( reset( $rows ) ) ) {
489 $rows = array( $rows );
492 foreach( $rows as $row ) {
493 # Delete rows which collide
494 if ( $uniqueIndexes ) {
495 $sql = "DELETE FROM $table WHERE ";
497 foreach ( $uniqueIndexes as $index ) {
504 if ( is_array( $index ) ) {
506 foreach ( $index as $col ) {
512 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
515 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
519 $this->query( $sql, $fname );
523 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
524 $this->makeList( $row, LIST_COMMA
) . ')';
525 $this->query( $sql, $fname );
529 # DELETE where the condition is a join
530 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
532 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
535 $delTable = $this->tableName( $delTable );
536 $joinTable = $this->tableName( $joinTable );
537 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
538 if ( $conds != '*' ) {
539 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
543 $this->query( $sql, $fname );
546 # Returns the size of a text field, or -1 for "unlimited"
547 function textFieldSize( $table, $field ) {
548 $table = $this->tableName( $table );
549 $sql = "SELECT t.typname as ftype,a.atttypmod as size
550 FROM pg_class c, pg_attribute a, pg_type t
551 WHERE relname='$table' AND a.attrelid=c.oid AND
552 a.atttypid=t.oid and a.attname='$field'";
553 $res =$this->query($sql);
554 $row=$this->fetchObject($res);
555 if ($row->ftype
=="varchar") {
560 $this->freeResult( $res );
564 function lowPriorityOption() {
568 function limitResult($sql, $limit,$offset) {
569 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
573 * Returns an SQL expression for a simple conditional.
574 * Uses CASE on Postgres
576 * @param string $cond SQL expression which will result in a boolean value
577 * @param string $trueVal SQL expression to return if true
578 * @param string $falseVal SQL expression to return if false
579 * @return string SQL fragment
581 function conditional( $cond, $trueVal, $falseVal ) {
582 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
585 # FIXME: actually detecting deadlocks might be nice
586 function wasDeadlock() {
590 function timestamp( $ts=0 ) {
591 return wfTimestamp(TS_POSTGRES
,$ts);
595 * Return aggregated value function call
597 function aggregateValue ($valuedata,$valuename='value') {
602 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
603 $message = "A database error has occurred\n" .
605 "Function: $fname\n" .
606 "Error: $errno $error\n";
607 throw new DBUnexpectedError($this, $message);
611 * @return string wikitext of a link to the server software's web site
613 function getSoftwareLink() {
614 return "[http://www.postgresql.org/ PostgreSQL]";
618 * @return string Version information from the database
620 function getServerVersion() {
621 $res = $this->query( "SELECT version()" );
622 $row = $this->fetchRow( $res );
624 $this->freeResult( $res );
630 * Query whether a given table exists (in the given schema, or the default mw one if not given)
632 function tableExists( $table, $schema = false ) {
633 global $wgDBmwschema;
635 $schema = $wgDBmwschema;
636 $etable = preg_replace("/'/", "''", $table);
637 $eschema = preg_replace("/'/", "''", $schema);
638 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
639 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema'";
640 $res = $this->query( $SQL );
641 $count = $res ?
pg_num_rows($res) : 0;
643 $this->freeResult( $res );
649 * Query whether a given schema exists. Returns the name of the owner
651 function schemaExists( $schema ) {
652 $eschema = preg_replace("/'/", "''", $schema);
653 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
654 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
655 $res = $this->query( $SQL );
656 $owner = $res ?
pg_num_rows($res) ?
pg_fetch_result($res, 0, 0) : false : false;
658 $this->freeResult($res);
663 * Query whether a given column exists in the mediawiki schema
665 function fieldExists( $table, $field ) {
666 global $wgDBmwschema;
667 $etable = preg_replace("/'/", "''", $table);
668 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
669 $ecol = preg_replace("/'/", "''", $field);
670 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
671 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
672 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
673 $res = $this->query( $SQL );
674 $count = $res ?
pg_num_rows($res) : 0;
676 $this->freeResult( $res );
680 function fieldInfo( $table, $field ) {
681 $res = $this->query( "SELECT $field FROM $table LIMIT 1" );
682 $type = pg_field_type( $res, 0 );
686 function begin( $fname = 'DatabasePostgrs::begin' ) {
687 $this->query( 'BEGIN', $fname );
688 $this->mTrxLevel
= 1;
690 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
693 function commit( $fname = 'DatabasePostgres::commit' ) {
694 $this->query( 'COMMIT', $fname );
695 $this->mTrxLevel
= 0;
698 /* Not even sure why this is used in the main codebase... */
699 function limitResultForUpdate($sql, $num) {
703 function setup_database() {
704 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport;
706 dbsource( "../maintenance/postgres/tables.sql", $this);
708 ## Update version information
709 $mwv = $this->addQuotes($wgVersion);
710 $pgv = $this->addQuotes($this->getServerVersion());
711 $pgu = $this->addQuotes($this->mUser
);
712 $mws = $this->addQuotes($wgDBmwschema);
713 $tss = $this->addQuotes($wgDBts2schema);
714 $pgp = $this->addQuotes($wgDBport);
715 $dbn = $this->addQuotes($this->mDBname
);
717 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
718 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn ".
719 "WHERE type = 'Creation'";
722 ## Avoid the non-standard "REPLACE INTO" syntax
723 $f = fopen( "../maintenance/interwiki.sql", 'r' );
725 dieout( "<li>Could not find the interwiki.sql file");
727 ## We simply assume it is already empty as we have just created it
728 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
729 while ( ! feof( $f ) ) {
730 $line = fgets($f,1024);
731 if (!preg_match("/^\s*(\(.+?),(\d)\)/", $line, $matches)) {
734 $yesno = $matches[2]; ## ? "'true'" : "'false'";
735 $this->query("$SQL $matches[1],$matches[2])");
737 print " (table interwiki successfully populated)...\n";
740 function encodeBlob($b) {
741 return array('bytea',pg_escape_bytea($b));
743 function decodeBlob($b) {
744 return pg_unescape_bytea( $b );
747 function strencode( $s ) { ## Should not be called by us
748 return pg_escape_string( $s );
751 function addQuotes( $s ) {
752 if ( is_null( $s ) ) {
754 } else if (is_array( $s )) { ## Assume it is bytea data
757 return "'" . pg_escape_string($s) . "'";
758 return "E'" . pg_escape_string($s) . "'";
761 function quote_ident( $s ) {
762 return '"' . preg_replace( '/"/', '""', $s) . '"';