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 FROM pg_class, pg_namespace, pg_attribute, pg_type
20 WHERE relnamespace=pg_namespace.oid AND relkind='r'
21 AND attrelid=pg_class.oid AND atttypid=pg_type.oid
22 AND nspname=%s AND relname=%s AND attname=%s;
24 $res = $db->query(sprintf($q,
25 $db->addQuotes($wgDBmwschema),
26 $db->addQuotes($table),
27 $db->addQuotes($field)));
28 $row = $db->fetchObject($res);
31 $n = new PostgresField
;
32 $n->type
= $row->typname
;
33 $n->nullable
= ($row->attnotnull
== 'f');
35 $n->tablename
= $table;
36 $n->max_length
= $row->attlen
;
44 function tableName() {
45 return $this->tablename
;
53 return $this->nullable
;
56 function maxLength() {
57 return $this->max_length
;
61 class DatabasePostgres
extends Database
{
62 var $mInsertId = NULL;
63 var $mLastResult = NULL;
64 var $numeric_version = NULL;
66 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
67 $failFunction = false, $flags = 0 )
71 # Can't get a reference if it hasn't been set yet
72 if ( !isset( $wgOut ) ) {
75 $this->mOut
=& $wgOut;
76 $this->mFailFunction
= $failFunction;
77 $this->mCascadingDeletes
= true;
78 $this->mCleanupTriggers
= true;
79 $this->mStrictIPs
= true;
80 $this->mFlags
= $flags;
81 $this->open( $server, $user, $password, $dbName);
85 function realTimestamps() {
89 function implicitGroupby() {
93 function searchableIPs() {
97 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
99 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
103 * Usually aborts on failure
104 * If the failFunction is set to a non-zero integer, returns success
106 function open( $server, $user, $password, $dbName ) {
107 # Test for Postgres support, to avoid suppressed fatal error
108 if ( !function_exists( 'pg_connect' ) ) {
109 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" );
114 if (!strlen($user)) { ## e.g. the class is being loaded
119 $this->mServer
= $server;
121 $this->mUser
= $user;
122 $this->mPassword
= $password;
123 $this->mDBname
= $dbName;
126 if ($server!=false && $server!="") {
127 $hstring="host=$server ";
129 if ($port!=false && $port!="") {
130 $hstring .= "port=$port ";
134 error_reporting( E_ALL
);
135 @$this->mConn
= pg_connect("$hstring dbname=$dbName user=$user password=$password");
137 if ( $this->mConn
== false ) {
138 wfDebug( "DB connection error\n" );
139 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
140 wfDebug( $this->lastError()."\n" );
144 $this->mOpened
= true;
145 ## If this is the initial connection, setup the schema stuff and possibly create the user
146 if (defined('MEDIAWIKI_INSTALL')) {
147 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBsuperuser, $wgDBmwschema,
150 print "<li>Checking the version of Postgres...";
151 $version = $this->getServerVersion();
153 if ($this->numeric_version
< $PGMINVER) {
154 print "<b>FAILED</b>. Required version is $PGMINVER. You have $this->numeric_version ($version)</li>\n";
157 print "version $this->numeric_version is OK.</li>\n";
159 $safeuser = $this->quote_ident($wgDBuser);
160 ## Are we connecting as a superuser for the first time?
161 if ($wgDBsuperuser) {
162 ## Are we really a superuser? Check out our rights
164 CASE WHEN usesuper IS TRUE THEN
165 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
166 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
168 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
169 $rows = $this->numRows($res = $this->doQuery($SQL));
171 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
174 $perms = pg_fetch_result($res, 0, 0);
176 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
177 $rows = $this->numRows($this->doQuery($SQL));
179 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
182 if ($perms != 1 and $perms != 3) {
183 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
184 print 'Please use a different Postgres user.</li>';
187 print "<li>Creating user <b>$wgDBuser</b>...";
188 $safepass = $this->addQuotes($wgDBpassword);
189 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
190 $this->doQuery($SQL);
193 ## User now exists, check out the database
194 if ($dbName != $wgDBname) {
195 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
196 $rows = $this->numRows($this->doQuery($SQL));
198 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
202 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
203 print 'Please use a different Postgres user.</li>';
206 print "<li>Creating database <b>$wgDBname</b>...";
207 $safename = $this->quote_ident($wgDBname);
208 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
209 $this->doQuery($SQL);
211 ## Hopefully tsearch2 and plpgsql are in template1...
214 ## Reconnect to check out tsearch2 rights for this user
215 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
216 @$this->mConn
= pg_connect("$hstring dbname=$wgDBname user=$user password=$password");
217 if ( $this->mConn
== false ) {
218 print "<b>FAILED TO CONNECT!</b></li>";
225 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
226 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
227 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
228 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
229 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
233 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
234 foreach (array('cfg','cfgmap','dict','parser') as $table) {
235 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
236 $this->doQuery($SQL);
241 ## Setup the schema for this user if needed
242 $result = $this->schemaExists($wgDBmwschema);
243 $safeschema = $this->quote_ident($wgDBmwschema);
245 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
246 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
248 print "<b>FAILED</b>.</li>\n";
254 print "<li>Schema already exists, explicitly granting rights...\n";
255 $safeschema2 = $this->addQuotes($wgDBmwschema);
256 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
257 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
258 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
259 "AND p.relkind IN ('r','S','v')\n";
261 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
262 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
263 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
264 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
265 $res = $this->doQuery($SQL);
267 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
270 $this->doQuery("SET search_path = $safeschema");
271 $rows = $this->numRows($res);
274 $this->doQuery(pg_fetch_result($res, $rows, 0));
280 return true; ## Reconnect as regular user
284 if (!defined('POSTGRES_SEARCHPATH')) {
286 ## Do we have the basic tsearch2 table?
287 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
288 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
289 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
290 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
291 print " for instructions.</li>\n";
296 ## Does this user have the rights to the tsearch2 tables?
297 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
298 print "<li>Checking tsearch2 permissions...";
299 ## Let's check all four, just to be safe
300 error_reporting( 0 );
301 $ts2tables = array('cfg','cfgmap','dict','parser');
302 foreach ( $ts2tables AS $tname ) {
303 $SQL = "SELECT count(*) FROM $wgDBts2schema.pg_ts_$tname";
304 $res = $this->doQuery($SQL);
306 print "<b>FAILED</b> to access pg_ts_$tname. Make sure that the user ".
307 "\"$wgDBuser\" has SELECT access to all four tsearch2 tables</li>\n";
311 $SQL = "SELECT ts_name FROM $wgDBts2schema.pg_ts_cfg WHERE locale = '$ctype'";
312 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
313 $res = $this->doQuery($SQL);
314 error_reporting( E_ALL
);
316 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
321 ## Will the current locale work? Can we force it to?
322 print "<li>Verifying tsearch2 locale with $ctype...";
323 $rows = $this->numRows($res);
326 print "<b>not found</b></li>\n";
327 print "<li>Attempting to set default tsearch2 locale to \"$ctype\"...";
331 $tsname = pg_fetch_result($res, 0, 0);
332 if ($tsname != 'default') {
333 print "<b>not set to default ($tsname)</b>";
334 print "<li>Attempting to change tsearch2 default locale to \"$ctype\"...";
339 $SQL = "UPDATE $wgDBts2schema.pg_ts_cfg SET locale = '$ctype' WHERE ts_name = 'default'";
340 $res = $this->doQuery($SQL);
342 print "<b>FAILED</b>. ";
343 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"$ctype\"</li>\n";
349 ## Final test: try out a simple tsearch2 query
350 $SQL = "SELECT $wgDBts2schema.to_tsvector('default','MediaWiki tsearch2 testing')";
351 $res = $this->doQuery($SQL);
353 print "<b>FAILED</b>. Specifically, \"$SQL\" did not work.</li>";
358 ## Do we have plpgsql installed?
359 print "<li>Checking for Pl/Pgsql ...";
360 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
361 $rows = $this->numRows($this->doQuery($SQL));
363 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
364 print "not installed. Attempting to install Pl/Pgsql ...";
365 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
366 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
367 $rows = $this->numRows($this->doQuery($SQL));
369 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
371 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
376 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
382 ## Does the schema already exist? Who owns it?
383 $result = $this->schemaExists($wgDBmwschema);
385 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
386 error_reporting( 0 );
387 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
388 error_reporting( E_ALL
);
390 print "<b>FAILED</b>. The user \"$wgDBuser\" must be able to access the schema. ".
391 "You can try making them the owner of the database, or try creating the schema with a ".
392 "different user, and then grant access to the \"$wgDBuser\" user.</li>\n";
397 else if ($result != $user) {
398 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
401 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
404 ## Fix up the search paths if needed
405 print "<li>Setting the search path for user \"$user\" ...";
406 $path = $this->quote_ident($wgDBmwschema);
407 if ($wgDBts2schema !== $wgDBmwschema)
408 $path .= ", ". $this->quote_ident($wgDBts2schema);
409 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
411 $SQL = "ALTER USER $safeuser SET search_path = $path";
412 $result = pg_query($this->mConn
, $SQL);
414 print "<b>FAILED</b>.</li>\n";
418 ## Set for the rest of this session
419 $SQL = "SET search_path = $path";
420 $result = pg_query($this->mConn
, $SQL);
422 print "<li>Failed to set search_path</li>\n";
425 define( "POSTGRES_SEARCHPATH", $path );
428 global $wgCommandLineMode;
429 ## If called from the command-line (e.g. importDump), only show errors
430 if ($wgCommandLineMode) {
431 $this->doQuery("SET client_min_messages = 'ERROR'");
438 * Closes a database connection, if it is open
439 * Returns success, true if already closed
442 $this->mOpened
= false;
443 if ( $this->mConn
) {
444 return pg_close( $this->mConn
);
450 function doQuery( $sql ) {
451 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
454 function queryIgnore( $sql, $fname = '' ) {
455 return $this->query( $sql, $fname, true );
458 function freeResult( $res ) {
459 if ( !@pg_free_result
( $res ) ) {
460 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
464 function fetchObject( $res ) {
465 @$row = pg_fetch_object( $res );
466 # FIXME: HACK HACK HACK HACK debug
469 # hashar : not sure if the following test really trigger if the object
471 if( pg_last_error($this->mConn
) ) {
472 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
477 function fetchRow( $res ) {
478 @$row = pg_fetch_array( $res );
479 if( pg_last_error($this->mConn
) ) {
480 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
485 function numRows( $res ) {
486 @$n = pg_num_rows( $res );
487 if( pg_last_error($this->mConn
) ) {
488 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
492 function numFields( $res ) { return pg_num_fields( $res ); }
493 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
496 * This must be called after nextSequenceVal
498 function insertId() {
499 return $this->mInsertId
;
502 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
503 function lastError() {
504 if ( $this->mConn
) {
505 return pg_last_error();
508 return "No database connection";
511 function lastErrno() {
512 return pg_last_error() ?
1 : 0;
515 function affectedRows() {
516 return pg_affected_rows( $this->mLastResult
);
520 * Returns information about an index
521 * If errors are explicitly ignored, returns NULL on failure
523 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
524 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
525 $res = $this->query( $sql, $fname );
530 while ( $row = $this->fetchObject( $res ) ) {
531 if ( $row->indexname
== $index ) {
534 // BUG: !!!! This code needs to be synced up with database.php
541 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
542 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
543 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
544 $res = $this->query( $sql, $fname );
547 while ($row = $this->fetchObject( $res ))
553 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
554 # Postgres doesn't support options
555 # We have a go at faking one of them
556 # TODO: DELAYED, LOW_PRIORITY
558 if ( !is_array($options))
559 $options = array($options);
561 if ( in_array( 'IGNORE', $options ) )
562 $oldIgnore = $this->ignoreErrors( true );
564 # IGNORE is performed using single-row inserts, ignoring errors in each
565 # FIXME: need some way to distiguish between key collision and other types of error
566 $oldIgnore = $this->ignoreErrors( true );
567 if ( !is_array( reset( $a ) ) ) {
570 foreach ( $a as $row ) {
571 parent
::insert( $table, $row, $fname, array() );
573 $this->ignoreErrors( $oldIgnore );
576 if ( in_array( 'IGNORE', $options ) )
577 $this->ignoreErrors( $oldIgnore );
582 function tableName( $name ) {
583 # Replace reserved words with better ones
588 return 'pagecontent';
595 * Return the next in a sequence, save the value for retrieval via insertId()
597 function nextSequenceValue( $seqName ) {
598 $safeseq = preg_replace( "/'/", "''", $seqName );
599 $res = $this->query( "SELECT nextval('$safeseq')" );
600 $row = $this->fetchRow( $res );
601 $this->mInsertId
= $row[0];
602 $this->freeResult( $res );
603 return $this->mInsertId
;
607 * Postgres does not have a "USE INDEX" clause, so return an empty string
609 function useIndexClause( $index ) {
613 # REPLACE query wrapper
614 # Postgres simulates this with a DELETE followed by INSERT
615 # $row is the row to insert, an associative array
616 # $uniqueIndexes is an array of indexes. Each element may be either a
617 # field name or an array of field names
619 # It may be more efficient to leave off unique indexes which are unlikely to collide.
620 # However if you do this, you run the risk of encountering errors which wouldn't have
622 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
623 $table = $this->tableName( $table );
625 if (count($rows)==0) {
630 if ( !is_array( reset( $rows ) ) ) {
631 $rows = array( $rows );
634 foreach( $rows as $row ) {
635 # Delete rows which collide
636 if ( $uniqueIndexes ) {
637 $sql = "DELETE FROM $table WHERE ";
639 foreach ( $uniqueIndexes as $index ) {
646 if ( is_array( $index ) ) {
648 foreach ( $index as $col ) {
654 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
657 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
661 $this->query( $sql, $fname );
665 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
666 $this->makeList( $row, LIST_COMMA
) . ')';
667 $this->query( $sql, $fname );
671 # DELETE where the condition is a join
672 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
674 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
677 $delTable = $this->tableName( $delTable );
678 $joinTable = $this->tableName( $joinTable );
679 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
680 if ( $conds != '*' ) {
681 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
685 $this->query( $sql, $fname );
688 # Returns the size of a text field, or -1 for "unlimited"
689 function textFieldSize( $table, $field ) {
690 $table = $this->tableName( $table );
691 $sql = "SELECT t.typname as ftype,a.atttypmod as size
692 FROM pg_class c, pg_attribute a, pg_type t
693 WHERE relname='$table' AND a.attrelid=c.oid AND
694 a.atttypid=t.oid and a.attname='$field'";
695 $res =$this->query($sql);
696 $row=$this->fetchObject($res);
697 if ($row->ftype
=="varchar") {
702 $this->freeResult( $res );
706 function lowPriorityOption() {
710 function limitResult($sql, $limit,$offset=false) {
711 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
715 * Returns an SQL expression for a simple conditional.
716 * Uses CASE on Postgres
718 * @param string $cond SQL expression which will result in a boolean value
719 * @param string $trueVal SQL expression to return if true
720 * @param string $falseVal SQL expression to return if false
721 * @return string SQL fragment
723 function conditional( $cond, $trueVal, $falseVal ) {
724 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
727 function wasDeadlock() {
728 return $this->lastErrno() == '40P01';
731 function timestamp( $ts=0 ) {
732 return wfTimestamp(TS_POSTGRES
,$ts);
736 * Return aggregated value function call
738 function aggregateValue ($valuedata,$valuename='value') {
743 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
744 # Ignore errors during error handling to avoid infinite recursion
745 $ignore = $this->ignoreErrors( true );
746 ++
$this->mErrorCount
;
748 if ($ignore ||
$tempIgnore) {
749 wfDebug("SQL ERROR (ignored): $error\n");
750 $this->ignoreErrors( $ignore );
753 $message = "A database error has occurred\n" .
755 "Function: $fname\n" .
756 "Error: $errno $error\n";
757 throw new DBUnexpectedError($this, $message);
762 * @return string wikitext of a link to the server software's web site
764 function getSoftwareLink() {
765 return "[http://www.postgresql.org/ PostgreSQL]";
769 * @return string Version information from the database
771 function getServerVersion() {
772 $version = pg_fetch_result($this->doQuery("SELECT version()"),0,0);
774 if (!preg_match('/PostgreSQL (\d+\.\d+)(\S+)/', $version, $thisver)) {
775 die("Could not determine the numeric version from $version!");
777 $this->numeric_version
= $thisver[1];
783 * Query whether a given relation exists (in the given schema, or the
784 * default mw one if not given)
786 function relationExists( $table, $types, $schema = false ) {
787 global $wgDBmwschema;
788 if (!is_array($types))
789 $types = array($types);
791 $schema = $wgDBmwschema;
792 $etable = $this->addQuotes($table);
793 $eschema = $this->addQuotes($schema);
794 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
795 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
796 . "AND c.relkind IN ('" . implode("','", $types) . "')";
797 $res = $this->query( $SQL );
798 $count = $res ?
pg_num_rows($res) : 0;
800 $this->freeResult( $res );
805 * For backward compatibility, this function checks both tables and
808 function tableExists ($table, $schema = false) {
809 return $this->relationExists($table, array('r', 'v'), $schema);
812 function sequenceExists ($sequence, $schema = false) {
813 return $this->relationExists($sequence, 'S', $schema);
816 function triggerExists($table, $trigger) {
817 global $wgDBmwschema;
820 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
821 WHERE relnamespace=pg_namespace.oid AND relkind='r'
822 AND tgrelid=pg_class.oid
823 AND nspname=%s AND relname=%s AND tgname=%s
825 $res = $this->query(sprintf($q,
826 $this->addQuotes($wgDBmwschema),
827 $this->addQuotes($table),
828 $this->addQuotes($trigger)));
829 $row = $this->fetchRow($res);
831 $this->freeResult($res);
835 function ruleExists($table, $rule) {
836 global $wgDBmwschema;
837 $exists = $this->selectField("pg_rules", "rulename",
838 array( "rulename" => $rule,
839 "tablename" => $table,
840 "schemaname" => $wgDBmwschema));
841 return $exists === $rule;
845 * Query whether a given schema exists. Returns the name of the owner
847 function schemaExists( $schema ) {
848 $eschema = preg_replace("/'/", "''", $schema);
849 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
850 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
851 $res = $this->query( $SQL );
852 $owner = $res ?
pg_num_rows($res) ?
pg_fetch_result($res, 0, 0) : false : false;
854 $this->freeResult($res);
859 * Query whether a given column exists in the mediawiki schema
861 function fieldExists( $table, $field, $fname = 'DatabasePostgres::fieldExists' ) {
862 global $wgDBmwschema;
863 $etable = preg_replace("/'/", "''", $table);
864 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
865 $ecol = preg_replace("/'/", "''", $field);
866 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
867 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
868 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
869 $res = $this->query( $SQL, $fname );
870 $count = $res ?
pg_num_rows($res) : 0;
872 $this->freeResult( $res );
876 function fieldInfo( $table, $field ) {
877 return PostgresField
::fromText($this, $table, $field);
880 function begin( $fname = 'DatabasePostgres::begin' ) {
881 $this->query( 'BEGIN', $fname );
882 $this->mTrxLevel
= 1;
884 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
887 function commit( $fname = 'DatabasePostgres::commit' ) {
888 $this->query( 'COMMIT', $fname );
889 $this->mTrxLevel
= 0;
892 /* Not even sure why this is used in the main codebase... */
893 function limitResultForUpdate($sql, $num) {
897 function setup_database() {
898 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
900 ## Make sure that we can write to the correct schema
901 ## If not, Postgres will happily and silently go to the next search_path item
902 $SQL = "CREATE TABLE $wgDBmwschema.mw_test_table(a int)";
903 error_reporting( 0 );
904 $res = $this->doQuery($SQL);
905 error_reporting( E_ALL
);
907 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" can write to the schema \"wgDBmwschema\"</li>\n";
911 dbsource( "../maintenance/postgres/tables.sql", $this);
913 ## Version-specific stuff
914 if ($this->numeric_version
== 8.1) {
915 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gist(textvector)");
916 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gist(titlevector)");
919 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gin(textvector)");
920 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gin(titlevector)");
923 ## Update version information
924 $mwv = $this->addQuotes($wgVersion);
925 $pgv = $this->addQuotes($this->getServerVersion());
926 $pgu = $this->addQuotes($this->mUser
);
927 $mws = $this->addQuotes($wgDBmwschema);
928 $tss = $this->addQuotes($wgDBts2schema);
929 $pgp = $this->addQuotes($wgDBport);
930 $dbn = $this->addQuotes($this->mDBname
);
931 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
933 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
934 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
936 "WHERE type = 'Creation'";
939 ## Avoid the non-standard "REPLACE INTO" syntax
940 $f = fopen( "../maintenance/interwiki.sql", 'r' );
942 dieout( "<li>Could not find the interwiki.sql file");
944 ## We simply assume it is already empty as we have just created it
945 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
946 while ( ! feof( $f ) ) {
947 $line = fgets($f,1024);
949 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
952 $this->query("$SQL $matches[1],$matches[2])");
954 print " (table interwiki successfully populated)...\n";
957 function encodeBlob($b) {
958 return array('bytea',pg_escape_bytea($b));
960 function decodeBlob($b) {
961 return pg_unescape_bytea( $b );
964 function strencode( $s ) { ## Should not be called by us
965 return pg_escape_string( $s );
968 function addQuotes( $s ) {
969 if ( is_null( $s ) ) {
971 } else if (is_array( $s )) { ## Assume it is bytea data
974 return "'" . pg_escape_string($s) . "'";
975 // Unreachable: return "E'" . pg_escape_string($s) . "'";
978 function quote_ident( $s ) {
979 return '"' . preg_replace( '/"/', '""', $s) . '"';
982 /* For now, does nothing */
983 function selectDB( $db ) {
988 * Returns an optional USE INDEX clause to go after the table, and a
989 * string to go at the end of the query
993 * @param array $options an associative array of options to be turned into
994 * an SQL query, valid keys are listed in the function.
997 function makeSelectOptions( $options ) {
998 $preLimitTail = $postLimitTail = '';
1001 $noKeyOptions = array();
1002 foreach ( $options as $key => $option ) {
1003 if ( is_numeric( $key ) ) {
1004 $noKeyOptions[$option] = true;
1008 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY " . $options['GROUP BY'];
1009 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY " . $options['ORDER BY'];
1011 //if (isset($options['LIMIT'])) {
1012 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1013 // isset($options['OFFSET']) ? $options['OFFSET']
1017 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1018 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1019 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1021 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1022 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1027 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1030 public function setTimeout( $timeout ) {
1035 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
1040 } // end DatabasePostgres class