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 '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 print "<b>FAILED</b>. Make sure the language plpgsql is installed for the database <tt>$wgDBname</tt></li>";
254 ## Does the schema already exist? Who owns it?
255 $result = $this->schemaExists($wgDBmwschema);
257 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
258 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
260 print "<b>FAILED</b>.</li>\n";
265 else if ($result != $user) {
266 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
269 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
272 ## Fix up the search paths if needed
273 print "<li>Setting the search path for user \"$user\" ...";
274 $path = $this->quote_ident($wgDBmwschema);
275 if ($wgDBts2schema !== $wgDBmwschema)
276 $path .= ", ". $this->quote_ident($wgDBts2schema);
277 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
279 $SQL = "ALTER USER $safeuser SET search_path = $path";
280 $result = pg_query($this->mConn
, $SQL);
282 print "<b>FAILED</b>.</li>\n";
286 ## Set for the rest of this session
287 $SQL = "SET search_path = $path";
288 $result = pg_query($this->mConn
, $SQL);
290 print "<li>Failed to set search_path</li>\n";
293 define( "POSTGRES_SEARCHPATH", $path );
296 global $wgCommandLineMode;
297 ## If called from the command-line (e.g. importDump), only show errors
298 if ($wgCommandLineMode) {
299 $this->doQuery("SET client_min_messages = 'ERROR'");
306 * Closes a database connection, if it is open
307 * Returns success, true if already closed
310 $this->mOpened
= false;
311 if ( $this->mConn
) {
312 return pg_close( $this->mConn
);
318 function doQuery( $sql ) {
319 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
322 function queryIgnore( $sql, $fname = '' ) {
323 return $this->query( $sql, $fname, true );
326 function freeResult( $res ) {
327 if ( !@pg_free_result
( $res ) ) {
328 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
332 function fetchObject( $res ) {
333 @$row = pg_fetch_object( $res );
334 # FIXME: HACK HACK HACK HACK debug
337 # hashar : not sure if the following test really trigger if the object
339 if( pg_last_error($this->mConn
) ) {
340 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
345 function fetchRow( $res ) {
346 @$row = pg_fetch_array( $res );
347 if( pg_last_error($this->mConn
) ) {
348 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
353 function numRows( $res ) {
354 @$n = pg_num_rows( $res );
355 if( pg_last_error($this->mConn
) ) {
356 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
360 function numFields( $res ) { return pg_num_fields( $res ); }
361 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
364 * This must be called after nextSequenceVal
366 function insertId() {
367 return $this->mInsertId
;
370 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
371 function lastError() {
372 if ( $this->mConn
) {
373 return pg_last_error();
376 return "No database connection";
379 function lastErrno() {
380 return pg_last_error() ?
1 : 0;
383 function affectedRows() {
384 return pg_affected_rows( $this->mLastResult
);
388 * Returns information about an index
389 * If errors are explicitly ignored, returns NULL on failure
391 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
392 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
393 $res = $this->query( $sql, $fname );
398 while ( $row = $this->fetchObject( $res ) ) {
399 if ( $row->indexname
== $index ) {
406 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
407 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
408 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
409 $res = $this->query( $sql, $fname );
412 while ($row = $this->fetchObject( $res ))
418 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
419 # Postgres doesn't support options
420 # We have a go at faking one of them
421 # TODO: DELAYED, LOW_PRIORITY
423 if ( !is_array($options))
424 $options = array($options);
426 if ( in_array( 'IGNORE', $options ) )
427 $oldIgnore = $this->ignoreErrors( true );
429 # IGNORE is performed using single-row inserts, ignoring errors in each
430 # FIXME: need some way to distiguish between key collision and other types of error
431 $oldIgnore = $this->ignoreErrors( true );
432 if ( !is_array( reset( $a ) ) ) {
435 foreach ( $a as $row ) {
436 parent
::insert( $table, $row, $fname, array() );
438 $this->ignoreErrors( $oldIgnore );
441 if ( in_array( 'IGNORE', $options ) )
442 $this->ignoreErrors( $oldIgnore );
447 function tableName( $name ) {
448 # Replace reserved words with better ones
453 return 'pagecontent';
460 * Return the next in a sequence, save the value for retrieval via insertId()
462 function nextSequenceValue( $seqName ) {
463 $safeseq = preg_replace( "/'/", "''", $seqName );
464 $res = $this->query( "SELECT nextval('$safeseq')" );
465 $row = $this->fetchRow( $res );
466 $this->mInsertId
= $row[0];
467 $this->freeResult( $res );
468 return $this->mInsertId
;
472 * Postgres does not have a "USE INDEX" clause, so return an empty string
474 function useIndexClause( $index ) {
478 # REPLACE query wrapper
479 # Postgres simulates this with a DELETE followed by INSERT
480 # $row is the row to insert, an associative array
481 # $uniqueIndexes is an array of indexes. Each element may be either a
482 # field name or an array of field names
484 # It may be more efficient to leave off unique indexes which are unlikely to collide.
485 # However if you do this, you run the risk of encountering errors which wouldn't have
487 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
488 $table = $this->tableName( $table );
490 if (count($rows)==0) {
495 if ( !is_array( reset( $rows ) ) ) {
496 $rows = array( $rows );
499 foreach( $rows as $row ) {
500 # Delete rows which collide
501 if ( $uniqueIndexes ) {
502 $sql = "DELETE FROM $table WHERE ";
504 foreach ( $uniqueIndexes as $index ) {
511 if ( is_array( $index ) ) {
513 foreach ( $index as $col ) {
519 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
522 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
526 $this->query( $sql, $fname );
530 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
531 $this->makeList( $row, LIST_COMMA
) . ')';
532 $this->query( $sql, $fname );
536 # DELETE where the condition is a join
537 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
539 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
542 $delTable = $this->tableName( $delTable );
543 $joinTable = $this->tableName( $joinTable );
544 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
545 if ( $conds != '*' ) {
546 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
550 $this->query( $sql, $fname );
553 # Returns the size of a text field, or -1 for "unlimited"
554 function textFieldSize( $table, $field ) {
555 $table = $this->tableName( $table );
556 $sql = "SELECT t.typname as ftype,a.atttypmod as size
557 FROM pg_class c, pg_attribute a, pg_type t
558 WHERE relname='$table' AND a.attrelid=c.oid AND
559 a.atttypid=t.oid and a.attname='$field'";
560 $res =$this->query($sql);
561 $row=$this->fetchObject($res);
562 if ($row->ftype
=="varchar") {
567 $this->freeResult( $res );
571 function lowPriorityOption() {
575 function limitResult($sql, $limit,$offset) {
576 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
580 * Returns an SQL expression for a simple conditional.
581 * Uses CASE on Postgres
583 * @param string $cond SQL expression which will result in a boolean value
584 * @param string $trueVal SQL expression to return if true
585 * @param string $falseVal SQL expression to return if false
586 * @return string SQL fragment
588 function conditional( $cond, $trueVal, $falseVal ) {
589 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
592 # FIXME: actually detecting deadlocks might be nice
593 function wasDeadlock() {
597 function timestamp( $ts=0 ) {
598 return wfTimestamp(TS_POSTGRES
,$ts);
602 * Return aggregated value function call
604 function aggregateValue ($valuedata,$valuename='value') {
609 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
610 $message = "A database error has occurred\n" .
612 "Function: $fname\n" .
613 "Error: $errno $error\n";
614 throw new DBUnexpectedError($this, $message);
618 * @return string wikitext of a link to the server software's web site
620 function getSoftwareLink() {
621 return "[http://www.postgresql.org/ PostgreSQL]";
625 * @return string Version information from the database
627 function getServerVersion() {
628 $res = $this->query( "SELECT version()" );
629 $row = $this->fetchRow( $res );
631 $this->freeResult( $res );
637 * Query whether a given table exists (in the given schema, or the default mw one if not given)
639 function tableExists( $table, $schema = false ) {
640 global $wgDBmwschema;
642 $schema = $wgDBmwschema;
643 $etable = preg_replace("/'/", "''", $table);
644 $eschema = preg_replace("/'/", "''", $schema);
645 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
646 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema'";
647 $res = $this->query( $SQL );
648 $count = $res ?
pg_num_rows($res) : 0;
650 $this->freeResult( $res );
656 * Query whether a given schema exists. Returns the name of the owner
658 function schemaExists( $schema ) {
659 $eschema = preg_replace("/'/", "''", $schema);
660 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
661 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
662 $res = $this->query( $SQL );
663 $owner = $res ?
pg_num_rows($res) ?
pg_fetch_result($res, 0, 0) : false : false;
665 $this->freeResult($res);
670 * Query whether a given column exists in the mediawiki schema
672 function fieldExists( $table, $field ) {
673 global $wgDBmwschema;
674 $etable = preg_replace("/'/", "''", $table);
675 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
676 $ecol = preg_replace("/'/", "''", $field);
677 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
678 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
679 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
680 $res = $this->query( $SQL );
681 $count = $res ?
pg_num_rows($res) : 0;
683 $this->freeResult( $res );
687 function fieldInfo( $table, $field ) {
688 $res = $this->query( "SELECT $field FROM $table LIMIT 1" );
689 $type = pg_field_type( $res, 0 );
693 function begin( $fname = 'DatabasePostgrs::begin' ) {
694 $this->query( 'BEGIN', $fname );
695 $this->mTrxLevel
= 1;
697 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
700 function commit( $fname = 'DatabasePostgres::commit' ) {
701 $this->query( 'COMMIT', $fname );
702 $this->mTrxLevel
= 0;
705 /* Not even sure why this is used in the main codebase... */
706 function limitResultForUpdate($sql, $num) {
710 function setup_database() {
711 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport;
713 dbsource( "../maintenance/postgres/tables.sql", $this);
715 ## Update version information
716 $mwv = $this->addQuotes($wgVersion);
717 $pgv = $this->addQuotes($this->getServerVersion());
718 $pgu = $this->addQuotes($this->mUser
);
719 $mws = $this->addQuotes($wgDBmwschema);
720 $tss = $this->addQuotes($wgDBts2schema);
721 $pgp = $this->addQuotes($wgDBport);
722 $dbn = $this->addQuotes($this->mDBname
);
724 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
725 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn ".
726 "WHERE type = 'Creation'";
729 ## Avoid the non-standard "REPLACE INTO" syntax
730 $f = fopen( "../maintenance/interwiki.sql", 'r' );
732 dieout( "<li>Could not find the interwiki.sql file");
734 ## We simply assume it is already empty as we have just created it
735 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
736 while ( ! feof( $f ) ) {
737 $line = fgets($f,1024);
738 if (!preg_match("/^\s*(\(.+?),(\d)\)/", $line, $matches)) {
741 $yesno = $matches[2]; ## ? "'true'" : "'false'";
742 $this->query("$SQL $matches[1],$matches[2])");
744 print " (table interwiki successfully populated)...\n";
747 function encodeBlob($b) {
748 return array('bytea',pg_escape_bytea($b));
750 function decodeBlob($b) {
751 return pg_unescape_bytea( $b );
754 function strencode( $s ) { ## Should not be called by us
755 return pg_escape_string( $s );
758 function addQuotes( $s ) {
759 if ( is_null( $s ) ) {
761 } else if (is_array( $s )) { ## Assume it is bytea data
764 return "'" . pg_escape_string($s) . "'";
765 return "E'" . pg_escape_string($s) . "'";
768 function quote_ident( $s ) {
769 return '"' . preg_replace( '/"/', '""', $s) . '"';