4 * This is the 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
10 * @addtogroup Database
13 private $name, $tablename, $type, $nullable, $max_length;
15 static function fromText($db, $table, $field) {
19 SELECT typname, attnotnull, attlen
20 FROM pg_class, pg_namespace, pg_attribute, pg_type
21 WHERE relnamespace=pg_namespace.oid
23 AND attrelid=pg_class.oid
24 AND atttypid=pg_type.oid
29 $res = $db->query(sprintf($q,
30 $db->addQuotes($wgDBmwschema),
31 $db->addQuotes($table),
32 $db->addQuotes($field)));
33 $row = $db->fetchObject($res);
36 $n = new PostgresField
;
37 $n->type
= $row->typname
;
38 $n->nullable
= ($row->attnotnull
== 'f');
40 $n->tablename
= $table;
41 $n->max_length
= $row->attlen
;
49 function tableName() {
50 return $this->tablename
;
58 return $this->nullable
;
61 function maxLength() {
62 return $this->max_length
;
67 * @addtogroup Database
69 class DatabasePostgres
extends Database
{
70 var $mInsertId = NULL;
71 var $mLastResult = NULL;
72 var $numeric_version = NULL;
74 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
75 $failFunction = false, $flags = 0 )
79 # Can't get a reference if it hasn't been set yet
80 if ( !isset( $wgOut ) ) {
83 $this->mOut
=& $wgOut;
84 $this->mFailFunction
= $failFunction;
85 $this->mFlags
= $flags;
86 $this->open( $server, $user, $password, $dbName);
90 function cascadingDeletes() {
93 function cleanupTriggers() {
96 function strictIPs() {
99 function realTimestamps() {
102 function implicitGroupby() {
105 function searchableIPs() {
109 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
111 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
115 * Usually aborts on failure
116 * If the failFunction is set to a non-zero integer, returns success
118 function open( $server, $user, $password, $dbName ) {
119 # Test for Postgres support, to avoid suppressed fatal error
120 if ( !function_exists( 'pg_connect' ) ) {
121 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" );
126 if (!strlen($user)) { ## e.g. the class is being loaded
131 $this->mServer
= $server;
133 $this->mUser
= $user;
134 $this->mPassword
= $password;
135 $this->mDBname
= $dbName;
138 if ($server!=false && $server!="") {
139 $hstring="host=$server ";
141 if ($port!=false && $port!="") {
142 $hstring .= "port=$port ";
146 error_reporting( E_ALL
);
147 @$this->mConn
= pg_connect("$hstring dbname=$dbName user=$user password=$password");
149 if ( $this->mConn
== false ) {
150 wfDebug( "DB connection error\n" );
151 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
152 wfDebug( $this->lastError()."\n" );
156 $this->mOpened
= true;
157 ## If this is the initial connection, setup the schema stuff and possibly create the user
158 if (defined('MEDIAWIKI_INSTALL')) {
159 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBsuperuser, $wgDBmwschema,
162 print "<li>Checking the version of Postgres...";
163 $version = $this->getServerVersion();
165 if ($this->numeric_version
< $PGMINVER) {
166 print "<b>FAILED</b>. Required version is $PGMINVER. You have $this->numeric_version ($version)</li>\n";
169 print "version $this->numeric_version is OK.</li>\n";
171 $safeuser = $this->quote_ident($wgDBuser);
172 ## Are we connecting as a superuser for the first time?
173 if ($wgDBsuperuser) {
174 ## Are we really a superuser? Check out our rights
176 CASE WHEN usesuper IS TRUE THEN
177 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
178 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
180 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
181 $rows = $this->numRows($res = $this->doQuery($SQL));
183 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
186 $perms = pg_fetch_result($res, 0, 0);
188 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
189 $rows = $this->numRows($this->doQuery($SQL));
191 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
194 if ($perms != 1 and $perms != 3) {
195 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
196 print 'Please use a different Postgres user.</li>';
199 print "<li>Creating user <b>$wgDBuser</b>...";
200 $safepass = $this->addQuotes($wgDBpassword);
201 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
202 $this->doQuery($SQL);
205 ## User now exists, check out the database
206 if ($dbName != $wgDBname) {
207 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
208 $rows = $this->numRows($this->doQuery($SQL));
210 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
214 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
215 print 'Please use a different Postgres user.</li>';
218 print "<li>Creating database <b>$wgDBname</b>...";
219 $safename = $this->quote_ident($wgDBname);
220 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
221 $this->doQuery($SQL);
223 ## Hopefully tsearch2 and plpgsql are in template1...
226 ## Reconnect to check out tsearch2 rights for this user
227 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
228 @$this->mConn
= pg_connect("$hstring dbname=$wgDBname user=$user password=$password");
229 if ( $this->mConn
== false ) {
230 print "<b>FAILED TO CONNECT!</b></li>";
237 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
238 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
239 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
240 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
241 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
245 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
246 foreach (array('cfg','cfgmap','dict','parser') as $table) {
247 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
248 $this->doQuery($SQL);
253 ## Setup the schema for this user if needed
254 $result = $this->schemaExists($wgDBmwschema);
255 $safeschema = $this->quote_ident($wgDBmwschema);
257 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
258 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
260 print "<b>FAILED</b>.</li>\n";
266 print "<li>Schema already exists, explicitly granting rights...\n";
267 $safeschema2 = $this->addQuotes($wgDBmwschema);
268 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
269 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
270 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
271 "AND p.relkind IN ('r','S','v')\n";
273 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
274 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
275 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
276 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
277 $res = $this->doQuery($SQL);
279 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
282 $this->doQuery("SET search_path = $safeschema");
283 $rows = $this->numRows($res);
286 $this->doQuery(pg_fetch_result($res, $rows, 0));
292 return true; ## Reconnect as regular user
296 if (!defined('POSTGRES_SEARCHPATH')) {
298 ## Do we have the basic tsearch2 table?
299 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
300 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
301 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
302 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
303 print " for instructions.</li>\n";
308 ## Does this user have the rights to the tsearch2 tables?
309 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
310 print "<li>Checking tsearch2 permissions...";
311 ## Let's check all four, just to be safe
312 error_reporting( 0 );
313 $ts2tables = array('cfg','cfgmap','dict','parser');
314 foreach ( $ts2tables AS $tname ) {
315 $SQL = "SELECT count(*) FROM $wgDBts2schema.pg_ts_$tname";
316 $res = $this->doQuery($SQL);
318 print "<b>FAILED</b> to access pg_ts_$tname. Make sure that the user ".
319 "\"$wgDBuser\" has SELECT access to all four tsearch2 tables</li>\n";
323 $SQL = "SELECT ts_name FROM $wgDBts2schema.pg_ts_cfg WHERE locale = '$ctype'";
324 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
325 $res = $this->doQuery($SQL);
326 error_reporting( E_ALL
);
328 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
333 ## Will the current locale work? Can we force it to?
334 print "<li>Verifying tsearch2 locale with $ctype...";
335 $rows = $this->numRows($res);
338 print "<b>not found</b></li>\n";
339 print "<li>Attempting to set default tsearch2 locale to \"$ctype\"...";
343 $tsname = pg_fetch_result($res, 0, 0);
344 if ($tsname != 'default') {
345 print "<b>not set to default ($tsname)</b>";
346 print "<li>Attempting to change tsearch2 default locale to \"$ctype\"...";
351 $SQL = "UPDATE $wgDBts2schema.pg_ts_cfg SET locale = '$ctype' WHERE ts_name = 'default'";
352 $res = $this->doQuery($SQL);
354 print "<b>FAILED</b>. ";
355 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"$ctype\"</li>\n";
361 ## Final test: try out a simple tsearch2 query
362 $SQL = "SELECT $wgDBts2schema.to_tsvector('default','MediaWiki tsearch2 testing')";
363 $res = $this->doQuery($SQL);
365 print "<b>FAILED</b>. Specifically, \"$SQL\" did not work.</li>";
370 ## Do we have plpgsql installed?
371 print "<li>Checking for Pl/Pgsql ...";
372 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
373 $rows = $this->numRows($this->doQuery($SQL));
375 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
376 print "not installed. Attempting to install Pl/Pgsql ...";
377 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
378 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
379 $rows = $this->numRows($this->doQuery($SQL));
381 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
383 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
388 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
394 ## Does the schema already exist? Who owns it?
395 $result = $this->schemaExists($wgDBmwschema);
397 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
398 error_reporting( 0 );
399 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
400 error_reporting( E_ALL
);
402 print "<b>FAILED</b>. The user \"$wgDBuser\" must be able to access the schema. ".
403 "You can try making them the owner of the database, or try creating the schema with a ".
404 "different user, and then grant access to the \"$wgDBuser\" user.</li>\n";
409 else if ($result != $user) {
410 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
413 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
416 ## Always return GMT time to accomodate the existing integer-based timestamp assumption
417 print "<li>Setting the timezone to GMT for user \"$user\" ...";
418 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
419 $result = pg_query($this->mConn
, $SQL);
421 print "<b>FAILED</b>.</li>\n";
425 ## Set for the rest of this session
426 $SQL = "SET timezone = 'GMT'";
427 $result = pg_query($this->mConn
, $SQL);
429 print "<li>Failed to set timezone</li>\n";
433 print "<li>Setting the datestyle to ISO, YMD for user \"$user\" ...";
434 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
435 $result = pg_query($this->mConn
, $SQL);
437 print "<b>FAILED</b>.</li>\n";
441 ## Set for the rest of this session
442 $SQL = "SET datestyle = 'ISO, YMD'";
443 $result = pg_query($this->mConn
, $SQL);
445 print "<li>Failed to set datestyle</li>\n";
449 ## Fix up the search paths if needed
450 print "<li>Setting the search path for user \"$user\" ...";
451 $path = $this->quote_ident($wgDBmwschema);
452 if ($wgDBts2schema !== $wgDBmwschema)
453 $path .= ", ". $this->quote_ident($wgDBts2schema);
454 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
456 $SQL = "ALTER USER $safeuser SET search_path = $path";
457 $result = pg_query($this->mConn
, $SQL);
459 print "<b>FAILED</b>.</li>\n";
463 ## Set for the rest of this session
464 $SQL = "SET search_path = $path";
465 $result = pg_query($this->mConn
, $SQL);
467 print "<li>Failed to set search_path</li>\n";
470 define( "POSTGRES_SEARCHPATH", $path );
473 global $wgCommandLineMode;
474 ## If called from the command-line (e.g. importDump), only show errors
475 if ($wgCommandLineMode) {
476 $this->doQuery("SET client_min_messages = 'ERROR'");
483 * Closes a database connection, if it is open
484 * Returns success, true if already closed
487 $this->mOpened
= false;
488 if ( $this->mConn
) {
489 return pg_close( $this->mConn
);
495 function doQuery( $sql ) {
496 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
499 function queryIgnore( $sql, $fname = '' ) {
500 return $this->query( $sql, $fname, true );
503 function freeResult( $res ) {
504 if ( !@pg_free_result
( $res ) ) {
505 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
509 function fetchObject( $res ) {
510 @$row = pg_fetch_object( $res );
511 # FIXME: HACK HACK HACK HACK debug
514 # hashar : not sure if the following test really trigger if the object
516 if( pg_last_error($this->mConn
) ) {
517 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
522 function fetchRow( $res ) {
523 @$row = pg_fetch_array( $res );
524 if( pg_last_error($this->mConn
) ) {
525 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
530 function numRows( $res ) {
531 @$n = pg_num_rows( $res );
532 if( pg_last_error($this->mConn
) ) {
533 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
537 function numFields( $res ) { return pg_num_fields( $res ); }
538 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
541 * This must be called after nextSequenceVal
543 function insertId() {
544 return $this->mInsertId
;
547 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
548 function lastError() {
549 if ( $this->mConn
) {
550 return pg_last_error();
553 return "No database connection";
556 function lastErrno() {
557 return pg_last_error() ?
1 : 0;
560 function affectedRows() {
561 return pg_affected_rows( $this->mLastResult
);
565 * Estimate rows in dataset
566 * Returns estimated count, based on EXPLAIN output
567 * This is not necessarily an accurate estimate, so use sparingly
568 * Returns -1 if count cannot be found
569 * Takes same arguments as Database::select()
572 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
573 $options['EXPLAIN'] = true;
574 $res = $this->select( $table, $vars, $conds, $fname, $options );
577 $row = $this->fetchRow( $res );
579 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
582 $this->freeResult($res);
589 * Returns information about an index
590 * If errors are explicitly ignored, returns NULL on failure
592 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
593 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
594 $res = $this->query( $sql, $fname );
599 while ( $row = $this->fetchObject( $res ) ) {
600 if ( $row->indexname
== $index ) {
603 // BUG: !!!! This code needs to be synced up with database.php
610 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
611 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
612 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
613 $res = $this->query( $sql, $fname );
616 while ($row = $this->fetchObject( $res ))
622 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
623 # Postgres doesn't support options
624 # We have a go at faking one of them
625 # TODO: DELAYED, LOW_PRIORITY
627 if ( !is_array($options))
628 $options = array($options);
630 if ( in_array( 'IGNORE', $options ) )
631 $oldIgnore = $this->ignoreErrors( true );
633 # IGNORE is performed using single-row inserts, ignoring errors in each
634 # FIXME: need some way to distiguish between key collision and other types of error
635 $oldIgnore = $this->ignoreErrors( true );
636 if ( !is_array( reset( $a ) ) ) {
639 foreach ( $a as $row ) {
640 parent
::insert( $table, $row, $fname, array() );
642 $this->ignoreErrors( $oldIgnore );
645 if ( in_array( 'IGNORE', $options ) )
646 $this->ignoreErrors( $oldIgnore );
651 function tableName( $name ) {
652 # Replace reserved words with better ones
657 return 'pagecontent';
664 * Return the next in a sequence, save the value for retrieval via insertId()
666 function nextSequenceValue( $seqName ) {
667 $safeseq = preg_replace( "/'/", "''", $seqName );
668 $res = $this->query( "SELECT nextval('$safeseq')" );
669 $row = $this->fetchRow( $res );
670 $this->mInsertId
= $row[0];
671 $this->freeResult( $res );
672 return $this->mInsertId
;
676 * Postgres does not have a "USE INDEX" clause, so return an empty string
678 function useIndexClause( $index ) {
682 # REPLACE query wrapper
683 # Postgres simulates this with a DELETE followed by INSERT
684 # $row is the row to insert, an associative array
685 # $uniqueIndexes is an array of indexes. Each element may be either a
686 # field name or an array of field names
688 # It may be more efficient to leave off unique indexes which are unlikely to collide.
689 # However if you do this, you run the risk of encountering errors which wouldn't have
691 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
692 $table = $this->tableName( $table );
694 if (count($rows)==0) {
699 if ( !is_array( reset( $rows ) ) ) {
700 $rows = array( $rows );
703 foreach( $rows as $row ) {
704 # Delete rows which collide
705 if ( $uniqueIndexes ) {
706 $sql = "DELETE FROM $table WHERE ";
708 foreach ( $uniqueIndexes as $index ) {
715 if ( is_array( $index ) ) {
717 foreach ( $index as $col ) {
723 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
726 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
730 $this->query( $sql, $fname );
734 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
735 $this->makeList( $row, LIST_COMMA
) . ')';
736 $this->query( $sql, $fname );
740 # DELETE where the condition is a join
741 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
743 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
746 $delTable = $this->tableName( $delTable );
747 $joinTable = $this->tableName( $joinTable );
748 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
749 if ( $conds != '*' ) {
750 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
754 $this->query( $sql, $fname );
757 # Returns the size of a text field, or -1 for "unlimited"
758 function textFieldSize( $table, $field ) {
759 $table = $this->tableName( $table );
760 $sql = "SELECT t.typname as ftype,a.atttypmod as size
761 FROM pg_class c, pg_attribute a, pg_type t
762 WHERE relname='$table' AND a.attrelid=c.oid AND
763 a.atttypid=t.oid and a.attname='$field'";
764 $res =$this->query($sql);
765 $row=$this->fetchObject($res);
766 if ($row->ftype
=="varchar") {
771 $this->freeResult( $res );
775 function lowPriorityOption() {
779 function limitResult($sql, $limit,$offset=false) {
780 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
784 * Returns an SQL expression for a simple conditional.
785 * Uses CASE on Postgres
787 * @param string $cond SQL expression which will result in a boolean value
788 * @param string $trueVal SQL expression to return if true
789 * @param string $falseVal SQL expression to return if false
790 * @return string SQL fragment
792 function conditional( $cond, $trueVal, $falseVal ) {
793 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
796 function wasDeadlock() {
797 return $this->lastErrno() == '40P01';
800 function timestamp( $ts=0 ) {
801 return wfTimestamp(TS_POSTGRES
,$ts);
805 * Return aggregated value function call
807 function aggregateValue ($valuedata,$valuename='value') {
812 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
813 # Ignore errors during error handling to avoid infinite recursion
814 $ignore = $this->ignoreErrors( true );
815 ++
$this->mErrorCount
;
817 if ($ignore ||
$tempIgnore) {
818 wfDebug("SQL ERROR (ignored): $error\n");
819 $this->ignoreErrors( $ignore );
822 $message = "A database error has occurred\n" .
824 "Function: $fname\n" .
825 "Error: $errno $error\n";
826 throw new DBUnexpectedError($this, $message);
831 * @return string wikitext of a link to the server software's web site
833 function getSoftwareLink() {
834 return "[http://www.postgresql.org/ PostgreSQL]";
838 * @return string Version information from the database
840 function getServerVersion() {
841 $version = pg_fetch_result($this->doQuery("SELECT version()"),0,0);
843 if (!preg_match('/PostgreSQL (\d+\.\d+)(\S+)/', $version, $thisver)) {
844 die("Could not determine the numeric version from $version!");
846 $this->numeric_version
= $thisver[1];
852 * Query whether a given relation exists (in the given schema, or the
853 * default mw one if not given)
855 function relationExists( $table, $types, $schema = false ) {
856 global $wgDBmwschema;
857 if (!is_array($types))
858 $types = array($types);
860 $schema = $wgDBmwschema;
861 $etable = $this->addQuotes($table);
862 $eschema = $this->addQuotes($schema);
863 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
864 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
865 . "AND c.relkind IN ('" . implode("','", $types) . "')";
866 $res = $this->query( $SQL );
867 $count = $res ?
pg_num_rows($res) : 0;
869 $this->freeResult( $res );
874 * For backward compatibility, this function checks both tables and
877 function tableExists ($table, $schema = false) {
878 return $this->relationExists($table, array('r', 'v'), $schema);
881 function sequenceExists ($sequence, $schema = false) {
882 return $this->relationExists($sequence, 'S', $schema);
885 function triggerExists($table, $trigger) {
886 global $wgDBmwschema;
889 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
890 WHERE relnamespace=pg_namespace.oid AND relkind='r'
891 AND tgrelid=pg_class.oid
892 AND nspname=%s AND relname=%s AND tgname=%s
894 $res = $this->query(sprintf($q,
895 $this->addQuotes($wgDBmwschema),
896 $this->addQuotes($table),
897 $this->addQuotes($trigger)));
900 $rows = pg_num_rows($res);
901 $this->freeResult($res);
905 function ruleExists($table, $rule) {
906 global $wgDBmwschema;
907 $exists = $this->selectField("pg_rules", "rulename",
908 array( "rulename" => $rule,
909 "tablename" => $table,
910 "schemaname" => $wgDBmwschema));
911 return $exists === $rule;
914 function constraintExists($table, $constraint) {
915 global $wgDBmwschema;
916 $SQL = sprintf("SELECT 1 FROM information_schema.table_constraints ".
917 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
918 $this->addQuotes($wgDBmwschema),
919 $this->addQuotes($table),
920 $this->addQuotes($constraint));
921 $res = $this->query($SQL);
924 $rows = pg_num_rows($res);
925 $this->freeResult($res);
930 * Query whether a given schema exists. Returns the name of the owner
932 function schemaExists( $schema ) {
933 $eschema = preg_replace("/'/", "''", $schema);
934 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
935 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
936 $res = $this->query( $SQL );
937 $owner = $res ?
pg_num_rows($res) ?
pg_fetch_result($res, 0, 0) : false : false;
939 $this->freeResult($res);
944 * Query whether a given column exists in the mediawiki schema
946 function fieldExists( $table, $field, $fname = 'DatabasePostgres::fieldExists' ) {
947 global $wgDBmwschema;
948 $etable = preg_replace("/'/", "''", $table);
949 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
950 $ecol = preg_replace("/'/", "''", $field);
951 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
952 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
953 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
954 $res = $this->query( $SQL, $fname );
955 $count = $res ?
pg_num_rows($res) : 0;
957 $this->freeResult( $res );
961 function fieldInfo( $table, $field ) {
962 return PostgresField
::fromText($this, $table, $field);
965 function begin( $fname = 'DatabasePostgres::begin' ) {
966 $this->query( 'BEGIN', $fname );
967 $this->mTrxLevel
= 1;
969 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
972 function commit( $fname = 'DatabasePostgres::commit' ) {
973 $this->query( 'COMMIT', $fname );
974 $this->mTrxLevel
= 0;
977 /* Not even sure why this is used in the main codebase... */
978 function limitResultForUpdate($sql, $num) {
982 function setup_database() {
983 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
985 ## Make sure that we can write to the correct schema
986 ## If not, Postgres will happily and silently go to the next search_path item
987 $ctest = "mw_test_table";
988 if ($this->tableExists($ctest, $wgDBmwschema)) {
989 $this->doQuery("DROP TABLE $wgDBmwschema.$ctest");
991 $SQL = "CREATE TABLE $wgDBmwschema.$ctest(a int)";
992 error_reporting( 0 );
993 $res = $this->doQuery($SQL);
994 error_reporting( E_ALL
);
996 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" can write to the schema \"$wgDBmwschema\"</li>\n";
999 $this->doQuery("DROP TABLE $wgDBmwschema.mw_test_table");
1001 dbsource( "../maintenance/postgres/tables.sql", $this);
1003 ## Version-specific stuff
1004 if ($this->numeric_version
== 8.1) {
1005 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gist(textvector)");
1006 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gist(titlevector)");
1009 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gin(textvector)");
1010 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gin(titlevector)");
1013 ## Update version information
1014 $mwv = $this->addQuotes($wgVersion);
1015 $pgv = $this->addQuotes($this->getServerVersion());
1016 $pgu = $this->addQuotes($this->mUser
);
1017 $mws = $this->addQuotes($wgDBmwschema);
1018 $tss = $this->addQuotes($wgDBts2schema);
1019 $pgp = $this->addQuotes($wgDBport);
1020 $dbn = $this->addQuotes($this->mDBname
);
1021 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
1023 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
1024 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
1025 "ctype = '$ctype' ".
1026 "WHERE type = 'Creation'";
1029 ## Avoid the non-standard "REPLACE INTO" syntax
1030 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1032 dieout( "<li>Could not find the interwiki.sql file");
1034 ## We simply assume it is already empty as we have just created it
1035 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1036 while ( ! feof( $f ) ) {
1037 $line = fgets($f,1024);
1039 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
1042 $this->query("$SQL $matches[1],$matches[2])");
1044 print " (table interwiki successfully populated)...\n";
1046 $this->doQuery("COMMIT");
1049 function encodeBlob($b) {
1050 return array('bytea',pg_escape_bytea($b));
1052 function decodeBlob($b) {
1053 return pg_unescape_bytea( $b );
1056 function strencode( $s ) { ## Should not be called by us
1057 return pg_escape_string( $s );
1060 function addQuotes( $s ) {
1061 if ( is_null( $s ) ) {
1063 } else if (is_array( $s )) { ## Assume it is bytea data
1066 return "'" . pg_escape_string($s) . "'";
1067 // Unreachable: return "E'" . pg_escape_string($s) . "'";
1070 function quote_ident( $s ) {
1071 return '"' . preg_replace( '/"/', '""', $s) . '"';
1074 /* For now, does nothing */
1075 function selectDB( $db ) {
1080 * Various select options
1084 * @param array $options an associative array of options to be turned into
1085 * an SQL query, valid keys are listed in the function.
1088 function makeSelectOptions( $options ) {
1089 $preLimitTail = $postLimitTail = '';
1090 $startOpts = $useIndex = '';
1092 $noKeyOptions = array();
1093 foreach ( $options as $key => $option ) {
1094 if ( is_numeric( $key ) ) {
1095 $noKeyOptions[$option] = true;
1099 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY " . $options['GROUP BY'];
1100 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1101 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY " . $options['ORDER BY'];
1103 //if (isset($options['LIMIT'])) {
1104 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1105 // isset($options['OFFSET']) ? $options['OFFSET']
1109 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1110 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1111 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1113 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1116 public function setTimeout( $timeout ) {
1117 // @todo fixme no-op
1121 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
1126 } // end DatabasePostgres class