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
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
;
66 class DatabasePostgres
extends Database
{
67 var $mInsertId = NULL;
68 var $mLastResult = NULL;
69 var $numeric_version = NULL;
71 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
72 $failFunction = false, $flags = 0 )
76 # Can't get a reference if it hasn't been set yet
77 if ( !isset( $wgOut ) ) {
80 $this->mOut
=& $wgOut;
81 $this->mFailFunction
= $failFunction;
82 $this->mFlags
= $flags;
83 $this->open( $server, $user, $password, $dbName);
87 function cascadingDeletes() {
90 function cleanupTriggers() {
93 function strictIPs() {
96 function realTimestamps() {
99 function implicitGroupby() {
102 function searchableIPs() {
106 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
108 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
112 * Usually aborts on failure
113 * If the failFunction is set to a non-zero integer, returns success
115 function open( $server, $user, $password, $dbName ) {
116 # Test for Postgres support, to avoid suppressed fatal error
117 if ( !function_exists( 'pg_connect' ) ) {
118 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" );
123 if (!strlen($user)) { ## e.g. the class is being loaded
128 $this->mServer
= $server;
130 $this->mUser
= $user;
131 $this->mPassword
= $password;
132 $this->mDBname
= $dbName;
135 if ($server!=false && $server!="") {
136 $hstring="host=$server ";
138 if ($port!=false && $port!="") {
139 $hstring .= "port=$port ";
143 error_reporting( E_ALL
);
144 @$this->mConn
= pg_connect("$hstring dbname=$dbName user=$user password=$password");
146 if ( $this->mConn
== false ) {
147 wfDebug( "DB connection error\n" );
148 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
149 wfDebug( $this->lastError()."\n" );
153 $this->mOpened
= true;
154 ## If this is the initial connection, setup the schema stuff and possibly create the user
155 if (defined('MEDIAWIKI_INSTALL')) {
156 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBsuperuser, $wgDBmwschema,
159 print "<li>Checking the version of Postgres...";
160 $version = $this->getServerVersion();
162 if ($this->numeric_version
< $PGMINVER) {
163 print "<b>FAILED</b>. Required version is $PGMINVER. You have $this->numeric_version ($version)</li>\n";
166 print "version $this->numeric_version is OK.</li>\n";
168 $safeuser = $this->quote_ident($wgDBuser);
169 ## Are we connecting as a superuser for the first time?
170 if ($wgDBsuperuser) {
171 ## Are we really a superuser? Check out our rights
173 CASE WHEN usesuper IS TRUE THEN
174 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
175 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
177 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
178 $rows = $this->numRows($res = $this->doQuery($SQL));
180 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
183 $perms = pg_fetch_result($res, 0, 0);
185 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
186 $rows = $this->numRows($this->doQuery($SQL));
188 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
191 if ($perms != 1 and $perms != 3) {
192 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
193 print 'Please use a different Postgres user.</li>';
196 print "<li>Creating user <b>$wgDBuser</b>...";
197 $safepass = $this->addQuotes($wgDBpassword);
198 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
199 $this->doQuery($SQL);
202 ## User now exists, check out the database
203 if ($dbName != $wgDBname) {
204 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
205 $rows = $this->numRows($this->doQuery($SQL));
207 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
211 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
212 print 'Please use a different Postgres user.</li>';
215 print "<li>Creating database <b>$wgDBname</b>...";
216 $safename = $this->quote_ident($wgDBname);
217 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
218 $this->doQuery($SQL);
220 ## Hopefully tsearch2 and plpgsql are in template1...
223 ## Reconnect to check out tsearch2 rights for this user
224 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
225 @$this->mConn
= pg_connect("$hstring dbname=$wgDBname user=$user password=$password");
226 if ( $this->mConn
== false ) {
227 print "<b>FAILED TO CONNECT!</b></li>";
234 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
235 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
236 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
237 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
238 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
242 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
243 foreach (array('cfg','cfgmap','dict','parser') as $table) {
244 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
245 $this->doQuery($SQL);
250 ## Setup the schema for this user if needed
251 $result = $this->schemaExists($wgDBmwschema);
252 $safeschema = $this->quote_ident($wgDBmwschema);
254 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
255 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
257 print "<b>FAILED</b>.</li>\n";
263 print "<li>Schema already exists, explicitly granting rights...\n";
264 $safeschema2 = $this->addQuotes($wgDBmwschema);
265 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
266 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
267 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
268 "AND p.relkind IN ('r','S','v')\n";
270 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
271 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
272 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
273 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
274 $res = $this->doQuery($SQL);
276 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
279 $this->doQuery("SET search_path = $safeschema");
280 $rows = $this->numRows($res);
283 $this->doQuery(pg_fetch_result($res, $rows, 0));
289 return true; ## Reconnect as regular user
293 if (!defined('POSTGRES_SEARCHPATH')) {
295 ## Do we have the basic tsearch2 table?
296 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
297 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
298 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
299 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
300 print " for instructions.</li>\n";
305 ## Does this user have the rights to the tsearch2 tables?
306 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
307 print "<li>Checking tsearch2 permissions...";
308 ## Let's check all four, just to be safe
309 error_reporting( 0 );
310 $ts2tables = array('cfg','cfgmap','dict','parser');
311 foreach ( $ts2tables AS $tname ) {
312 $SQL = "SELECT count(*) FROM $wgDBts2schema.pg_ts_$tname";
313 $res = $this->doQuery($SQL);
315 print "<b>FAILED</b> to access pg_ts_$tname. Make sure that the user ".
316 "\"$wgDBuser\" has SELECT access to all four tsearch2 tables</li>\n";
320 $SQL = "SELECT ts_name FROM $wgDBts2schema.pg_ts_cfg WHERE locale = '$ctype'";
321 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
322 $res = $this->doQuery($SQL);
323 error_reporting( E_ALL
);
325 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
330 ## Will the current locale work? Can we force it to?
331 print "<li>Verifying tsearch2 locale with $ctype...";
332 $rows = $this->numRows($res);
335 print "<b>not found</b></li>\n";
336 print "<li>Attempting to set default tsearch2 locale to \"$ctype\"...";
340 $tsname = pg_fetch_result($res, 0, 0);
341 if ($tsname != 'default') {
342 print "<b>not set to default ($tsname)</b>";
343 print "<li>Attempting to change tsearch2 default locale to \"$ctype\"...";
348 $SQL = "UPDATE $wgDBts2schema.pg_ts_cfg SET locale = '$ctype' WHERE ts_name = 'default'";
349 $res = $this->doQuery($SQL);
351 print "<b>FAILED</b>. ";
352 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"$ctype\"</li>\n";
358 ## Final test: try out a simple tsearch2 query
359 $SQL = "SELECT $wgDBts2schema.to_tsvector('default','MediaWiki tsearch2 testing')";
360 $res = $this->doQuery($SQL);
362 print "<b>FAILED</b>. Specifically, \"$SQL\" did not work.</li>";
367 ## Do we have plpgsql installed?
368 print "<li>Checking for Pl/Pgsql ...";
369 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
370 $rows = $this->numRows($this->doQuery($SQL));
372 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
373 print "not installed. Attempting to install Pl/Pgsql ...";
374 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
375 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
376 $rows = $this->numRows($this->doQuery($SQL));
378 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
380 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
385 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
391 ## Does the schema already exist? Who owns it?
392 $result = $this->schemaExists($wgDBmwschema);
394 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
395 error_reporting( 0 );
396 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
397 error_reporting( E_ALL
);
399 print "<b>FAILED</b>. The user \"$wgDBuser\" must be able to access the schema. ".
400 "You can try making them the owner of the database, or try creating the schema with a ".
401 "different user, and then grant access to the \"$wgDBuser\" user.</li>\n";
406 else if ($result != $user) {
407 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
410 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
413 ## Always return GMT time to accomodate the existing integer-based timestamp assumption
414 print "<li>Setting the timezone to GMT for user \"$user\" ...";
415 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
416 $result = pg_query($this->mConn
, $SQL);
418 print "<b>FAILED</b>.</li>\n";
422 ## Set for the rest of this session
423 $SQL = "SET timezone = 'GMT'";
424 $result = pg_query($this->mConn
, $SQL);
426 print "<li>Failed to set timezone</li>\n";
430 print "<li>Setting the datestyle to ISO, YMD for user \"$user\" ...";
431 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
432 $result = pg_query($this->mConn
, $SQL);
434 print "<b>FAILED</b>.</li>\n";
438 ## Set for the rest of this session
439 $SQL = "SET datestyle = 'ISO, YMD'";
440 $result = pg_query($this->mConn
, $SQL);
442 print "<li>Failed to set datestyle</li>\n";
446 ## Fix up the search paths if needed
447 print "<li>Setting the search path for user \"$user\" ...";
448 $path = $this->quote_ident($wgDBmwschema);
449 if ($wgDBts2schema !== $wgDBmwschema)
450 $path .= ", ". $this->quote_ident($wgDBts2schema);
451 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
453 $SQL = "ALTER USER $safeuser SET search_path = $path";
454 $result = pg_query($this->mConn
, $SQL);
456 print "<b>FAILED</b>.</li>\n";
460 ## Set for the rest of this session
461 $SQL = "SET search_path = $path";
462 $result = pg_query($this->mConn
, $SQL);
464 print "<li>Failed to set search_path</li>\n";
467 define( "POSTGRES_SEARCHPATH", $path );
470 global $wgCommandLineMode;
471 ## If called from the command-line (e.g. importDump), only show errors
472 if ($wgCommandLineMode) {
473 $this->doQuery("SET client_min_messages = 'ERROR'");
480 * Closes a database connection, if it is open
481 * Returns success, true if already closed
484 $this->mOpened
= false;
485 if ( $this->mConn
) {
486 return pg_close( $this->mConn
);
492 function doQuery( $sql ) {
493 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
496 function queryIgnore( $sql, $fname = '' ) {
497 return $this->query( $sql, $fname, true );
500 function freeResult( $res ) {
501 if ( !@pg_free_result
( $res ) ) {
502 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
506 function fetchObject( $res ) {
507 @$row = pg_fetch_object( $res );
508 # FIXME: HACK HACK HACK HACK debug
511 # hashar : not sure if the following test really trigger if the object
513 if( pg_last_error($this->mConn
) ) {
514 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
519 function fetchRow( $res ) {
520 @$row = pg_fetch_array( $res );
521 if( pg_last_error($this->mConn
) ) {
522 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
527 function numRows( $res ) {
528 @$n = pg_num_rows( $res );
529 if( pg_last_error($this->mConn
) ) {
530 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
534 function numFields( $res ) { return pg_num_fields( $res ); }
535 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
538 * This must be called after nextSequenceVal
540 function insertId() {
541 return $this->mInsertId
;
544 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
545 function lastError() {
546 if ( $this->mConn
) {
547 return pg_last_error();
550 return "No database connection";
553 function lastErrno() {
554 return pg_last_error() ?
1 : 0;
557 function affectedRows() {
558 return pg_affected_rows( $this->mLastResult
);
562 * Estimate rows in dataset
563 * Returns estimated count, based on EXPLAIN output
564 * This is not necessarily an accurate estimate, so use sparingly
565 * Returns -1 if count cannot be found
566 * Takes same arguments as Database::select()
569 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
570 $options['EXPLAIN'] = true;
571 $res = $this->select( $table, $vars, $conds, $fname, $options );
574 $row = $this->fetchRow( $res );
576 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
579 $this->freeResult($res);
586 * Returns information about an index
587 * If errors are explicitly ignored, returns NULL on failure
589 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
590 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
591 $res = $this->query( $sql, $fname );
596 while ( $row = $this->fetchObject( $res ) ) {
597 if ( $row->indexname
== $index ) {
600 // BUG: !!!! This code needs to be synced up with database.php
607 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
608 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
609 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
610 $res = $this->query( $sql, $fname );
613 while ($row = $this->fetchObject( $res ))
619 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
620 # Postgres doesn't support options
621 # We have a go at faking one of them
622 # TODO: DELAYED, LOW_PRIORITY
624 if ( !is_array($options))
625 $options = array($options);
627 if ( in_array( 'IGNORE', $options ) )
628 $oldIgnore = $this->ignoreErrors( true );
630 # IGNORE is performed using single-row inserts, ignoring errors in each
631 # FIXME: need some way to distiguish between key collision and other types of error
632 $oldIgnore = $this->ignoreErrors( true );
633 if ( !is_array( reset( $a ) ) ) {
636 foreach ( $a as $row ) {
637 parent
::insert( $table, $row, $fname, array() );
639 $this->ignoreErrors( $oldIgnore );
642 if ( in_array( 'IGNORE', $options ) )
643 $this->ignoreErrors( $oldIgnore );
648 function tableName( $name ) {
649 # Replace reserved words with better ones
654 return 'pagecontent';
661 * Return the next in a sequence, save the value for retrieval via insertId()
663 function nextSequenceValue( $seqName ) {
664 $safeseq = preg_replace( "/'/", "''", $seqName );
665 $res = $this->query( "SELECT nextval('$safeseq')" );
666 $row = $this->fetchRow( $res );
667 $this->mInsertId
= $row[0];
668 $this->freeResult( $res );
669 return $this->mInsertId
;
673 * Postgres does not have a "USE INDEX" clause, so return an empty string
675 function useIndexClause( $index ) {
679 # REPLACE query wrapper
680 # Postgres simulates this with a DELETE followed by INSERT
681 # $row is the row to insert, an associative array
682 # $uniqueIndexes is an array of indexes. Each element may be either a
683 # field name or an array of field names
685 # It may be more efficient to leave off unique indexes which are unlikely to collide.
686 # However if you do this, you run the risk of encountering errors which wouldn't have
688 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
689 $table = $this->tableName( $table );
691 if (count($rows)==0) {
696 if ( !is_array( reset( $rows ) ) ) {
697 $rows = array( $rows );
700 foreach( $rows as $row ) {
701 # Delete rows which collide
702 if ( $uniqueIndexes ) {
703 $sql = "DELETE FROM $table WHERE ";
705 foreach ( $uniqueIndexes as $index ) {
712 if ( is_array( $index ) ) {
714 foreach ( $index as $col ) {
720 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
723 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
727 $this->query( $sql, $fname );
731 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
732 $this->makeList( $row, LIST_COMMA
) . ')';
733 $this->query( $sql, $fname );
737 # DELETE where the condition is a join
738 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
740 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
743 $delTable = $this->tableName( $delTable );
744 $joinTable = $this->tableName( $joinTable );
745 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
746 if ( $conds != '*' ) {
747 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
751 $this->query( $sql, $fname );
754 # Returns the size of a text field, or -1 for "unlimited"
755 function textFieldSize( $table, $field ) {
756 $table = $this->tableName( $table );
757 $sql = "SELECT t.typname as ftype,a.atttypmod as size
758 FROM pg_class c, pg_attribute a, pg_type t
759 WHERE relname='$table' AND a.attrelid=c.oid AND
760 a.atttypid=t.oid and a.attname='$field'";
761 $res =$this->query($sql);
762 $row=$this->fetchObject($res);
763 if ($row->ftype
=="varchar") {
768 $this->freeResult( $res );
772 function lowPriorityOption() {
776 function limitResult($sql, $limit,$offset=false) {
777 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
781 * Returns an SQL expression for a simple conditional.
782 * Uses CASE on Postgres
784 * @param string $cond SQL expression which will result in a boolean value
785 * @param string $trueVal SQL expression to return if true
786 * @param string $falseVal SQL expression to return if false
787 * @return string SQL fragment
789 function conditional( $cond, $trueVal, $falseVal ) {
790 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
793 function wasDeadlock() {
794 return $this->lastErrno() == '40P01';
797 function timestamp( $ts=0 ) {
798 return wfTimestamp(TS_POSTGRES
,$ts);
802 * Return aggregated value function call
804 function aggregateValue ($valuedata,$valuename='value') {
809 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
810 # Ignore errors during error handling to avoid infinite recursion
811 $ignore = $this->ignoreErrors( true );
812 ++
$this->mErrorCount
;
814 if ($ignore ||
$tempIgnore) {
815 wfDebug("SQL ERROR (ignored): $error\n");
816 $this->ignoreErrors( $ignore );
819 $message = "A database error has occurred\n" .
821 "Function: $fname\n" .
822 "Error: $errno $error\n";
823 throw new DBUnexpectedError($this, $message);
828 * @return string wikitext of a link to the server software's web site
830 function getSoftwareLink() {
831 return "[http://www.postgresql.org/ PostgreSQL]";
835 * @return string Version information from the database
837 function getServerVersion() {
838 $version = pg_fetch_result($this->doQuery("SELECT version()"),0,0);
840 if (!preg_match('/PostgreSQL (\d+\.\d+)(\S+)/', $version, $thisver)) {
841 die("Could not determine the numeric version from $version!");
843 $this->numeric_version
= $thisver[1];
849 * Query whether a given relation exists (in the given schema, or the
850 * default mw one if not given)
852 function relationExists( $table, $types, $schema = false ) {
853 global $wgDBmwschema;
854 if (!is_array($types))
855 $types = array($types);
857 $schema = $wgDBmwschema;
858 $etable = $this->addQuotes($table);
859 $eschema = $this->addQuotes($schema);
860 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
861 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
862 . "AND c.relkind IN ('" . implode("','", $types) . "')";
863 $res = $this->query( $SQL );
864 $count = $res ?
pg_num_rows($res) : 0;
866 $this->freeResult( $res );
871 * For backward compatibility, this function checks both tables and
874 function tableExists ($table, $schema = false) {
875 return $this->relationExists($table, array('r', 'v'), $schema);
878 function sequenceExists ($sequence, $schema = false) {
879 return $this->relationExists($sequence, 'S', $schema);
882 function triggerExists($table, $trigger) {
883 global $wgDBmwschema;
886 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
887 WHERE relnamespace=pg_namespace.oid AND relkind='r'
888 AND tgrelid=pg_class.oid
889 AND nspname=%s AND relname=%s AND tgname=%s
891 $res = $this->query(sprintf($q,
892 $this->addQuotes($wgDBmwschema),
893 $this->addQuotes($table),
894 $this->addQuotes($trigger)));
895 $row = $this->fetchRow($res);
897 $this->freeResult($res);
901 function ruleExists($table, $rule) {
902 global $wgDBmwschema;
903 $exists = $this->selectField("pg_rules", "rulename",
904 array( "rulename" => $rule,
905 "tablename" => $table,
906 "schemaname" => $wgDBmwschema));
907 return $exists === $rule;
911 * Query whether a given schema exists. Returns the name of the owner
913 function schemaExists( $schema ) {
914 $eschema = preg_replace("/'/", "''", $schema);
915 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
916 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
917 $res = $this->query( $SQL );
918 $owner = $res ?
pg_num_rows($res) ?
pg_fetch_result($res, 0, 0) : false : false;
920 $this->freeResult($res);
925 * Query whether a given column exists in the mediawiki schema
927 function fieldExists( $table, $field, $fname = 'DatabasePostgres::fieldExists' ) {
928 global $wgDBmwschema;
929 $etable = preg_replace("/'/", "''", $table);
930 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
931 $ecol = preg_replace("/'/", "''", $field);
932 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
933 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
934 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
935 $res = $this->query( $SQL, $fname );
936 $count = $res ?
pg_num_rows($res) : 0;
938 $this->freeResult( $res );
942 function fieldInfo( $table, $field ) {
943 return PostgresField
::fromText($this, $table, $field);
946 function begin( $fname = 'DatabasePostgres::begin' ) {
947 $this->query( 'BEGIN', $fname );
948 $this->mTrxLevel
= 1;
950 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
953 function commit( $fname = 'DatabasePostgres::commit' ) {
954 $this->query( 'COMMIT', $fname );
955 $this->mTrxLevel
= 0;
958 /* Not even sure why this is used in the main codebase... */
959 function limitResultForUpdate($sql, $num) {
963 function setup_database() {
964 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
966 ## Make sure that we can write to the correct schema
967 ## If not, Postgres will happily and silently go to the next search_path item
968 $ctest = "mw_test_table";
969 if ($this->tableExists($ctest, $wgDBmwschema)) {
970 $this->doQuery("DROP TABLE $wgDBmwschema.$ctest");
972 $SQL = "CREATE TABLE $wgDBmwschema.$ctest(a int)";
973 error_reporting( 0 );
974 $res = $this->doQuery($SQL);
975 error_reporting( E_ALL
);
977 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" can write to the schema \"$wgDBmwschema\"</li>\n";
980 $this->doQuery("DROP TABLE $wgDBmwschema.mw_test_table");
982 dbsource( "../maintenance/postgres/tables.sql", $this);
984 ## Version-specific stuff
985 if ($this->numeric_version
== 8.1) {
986 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gist(textvector)");
987 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gist(titlevector)");
990 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gin(textvector)");
991 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gin(titlevector)");
994 ## Update version information
995 $mwv = $this->addQuotes($wgVersion);
996 $pgv = $this->addQuotes($this->getServerVersion());
997 $pgu = $this->addQuotes($this->mUser
);
998 $mws = $this->addQuotes($wgDBmwschema);
999 $tss = $this->addQuotes($wgDBts2schema);
1000 $pgp = $this->addQuotes($wgDBport);
1001 $dbn = $this->addQuotes($this->mDBname
);
1002 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
1004 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
1005 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
1006 "ctype = '$ctype' ".
1007 "WHERE type = 'Creation'";
1010 ## Avoid the non-standard "REPLACE INTO" syntax
1011 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1013 dieout( "<li>Could not find the interwiki.sql file");
1015 ## We simply assume it is already empty as we have just created it
1016 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1017 while ( ! feof( $f ) ) {
1018 $line = fgets($f,1024);
1020 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
1023 $this->query("$SQL $matches[1],$matches[2])");
1025 print " (table interwiki successfully populated)...\n";
1027 $this->doQuery("COMMIT");
1030 function encodeBlob($b) {
1031 return array('bytea',pg_escape_bytea($b));
1033 function decodeBlob($b) {
1034 return pg_unescape_bytea( $b );
1037 function strencode( $s ) { ## Should not be called by us
1038 return pg_escape_string( $s );
1041 function addQuotes( $s ) {
1042 if ( is_null( $s ) ) {
1044 } else if (is_array( $s )) { ## Assume it is bytea data
1047 return "'" . pg_escape_string($s) . "'";
1048 // Unreachable: return "E'" . pg_escape_string($s) . "'";
1051 function quote_ident( $s ) {
1052 return '"' . preg_replace( '/"/', '""', $s) . '"';
1055 /* For now, does nothing */
1056 function selectDB( $db ) {
1061 * Returns an optional USE INDEX clause to go after the table, and a
1062 * string to go at the end of the query
1066 * @param array $options an associative array of options to be turned into
1067 * an SQL query, valid keys are listed in the function.
1070 function makeSelectOptions( $options ) {
1071 $preLimitTail = $postLimitTail = '';
1074 $noKeyOptions = array();
1075 foreach ( $options as $key => $option ) {
1076 if ( is_numeric( $key ) ) {
1077 $noKeyOptions[$option] = true;
1081 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY " . $options['GROUP BY'];
1082 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY " . $options['ORDER BY'];
1084 //if (isset($options['LIMIT'])) {
1085 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1086 // isset($options['OFFSET']) ? $options['OFFSET']
1090 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1091 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1092 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1094 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1095 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1100 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1103 public function setTimeout( $timeout ) {
1108 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
1113 } // end DatabasePostgres class