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 ## TODO: Move this out of open()
159 if (defined('MEDIAWIKI_INSTALL')) {
160 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBsuperuser, $wgDBmwschema,
163 print "<li>Checking the version of Postgres...";
164 $version = $this->getServerVersion();
166 if ($this->numeric_version
< $PGMINVER) {
167 print "<b>FAILED</b>. Required version is $PGMINVER. You have $this->numeric_version ($version)</li>\n";
170 print "version $this->numeric_version is OK.</li>\n";
172 $safeuser = $this->quote_ident($wgDBuser);
173 ## Are we connecting as a superuser for the first time?
174 if ($wgDBsuperuser) {
175 ## Are we really a superuser? Check out our rights
177 CASE WHEN usesuper IS TRUE THEN
178 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
179 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
181 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
182 $rows = $this->numRows($res = $this->doQuery($SQL));
184 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
187 $perms = pg_fetch_result($res, 0, 0);
189 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
190 $rows = $this->numRows($this->doQuery($SQL));
192 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
195 if ($perms != 1 and $perms != 3) {
196 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
197 print 'Please use a different Postgres user.</li>';
200 print "<li>Creating user <b>$wgDBuser</b>...";
201 $safepass = $this->addQuotes($wgDBpassword);
202 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
203 $this->doQuery($SQL);
206 ## User now exists, check out the database
207 if ($dbName != $wgDBname) {
208 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
209 $rows = $this->numRows($this->doQuery($SQL));
211 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
215 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
216 print 'Please use a different Postgres user.</li>';
219 print "<li>Creating database <b>$wgDBname</b>...";
220 $safename = $this->quote_ident($wgDBname);
221 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
222 $this->doQuery($SQL);
224 ## Hopefully tsearch2 and plpgsql are in template1...
227 ## Reconnect to check out tsearch2 rights for this user
228 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
229 @$this->mConn
= pg_connect("$hstring dbname=$wgDBname user=$user password=$password");
230 if ( $this->mConn
== false ) {
231 print "<b>FAILED TO CONNECT!</b></li>";
238 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
239 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
240 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
241 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
242 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
246 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
247 foreach (array('cfg','cfgmap','dict','parser') as $table) {
248 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
249 $this->doQuery($SQL);
254 ## Setup the schema for this user if needed
255 $result = $this->schemaExists($wgDBmwschema);
256 $safeschema = $this->quote_ident($wgDBmwschema);
258 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
259 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
261 print "<b>FAILED</b>.</li>\n";
267 print "<li>Schema already exists, explicitly granting rights...\n";
268 $safeschema2 = $this->addQuotes($wgDBmwschema);
269 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
270 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
271 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
272 "AND p.relkind IN ('r','S','v')\n";
274 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
275 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
276 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
277 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
278 $res = $this->doQuery($SQL);
280 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
283 $this->doQuery("SET search_path = $safeschema");
284 $rows = $this->numRows($res);
287 $this->doQuery(pg_fetch_result($res, $rows, 0));
293 return true; ## Reconnect as regular user
297 if (!defined('POSTGRES_SEARCHPATH')) {
299 ## Do we have the basic tsearch2 table?
300 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
301 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
302 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
303 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
304 print " for instructions.</li>\n";
309 ## Does this user have the rights to the tsearch2 tables?
310 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
311 print "<li>Checking tsearch2 permissions...";
312 ## Let's check all four, just to be safe
313 error_reporting( 0 );
314 $ts2tables = array('cfg','cfgmap','dict','parser');
315 foreach ( $ts2tables AS $tname ) {
316 $SQL = "SELECT count(*) FROM $wgDBts2schema.pg_ts_$tname";
317 $res = $this->doQuery($SQL);
319 print "<b>FAILED</b> to access pg_ts_$tname. Make sure that the user ".
320 "\"$wgDBuser\" has SELECT access to all four tsearch2 tables</li>\n";
324 $SQL = "SELECT ts_name FROM $wgDBts2schema.pg_ts_cfg WHERE locale = '$ctype'";
325 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
326 $res = $this->doQuery($SQL);
327 error_reporting( E_ALL
);
329 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
334 ## Will the current locale work? Can we force it to?
335 print "<li>Verifying tsearch2 locale with $ctype...";
336 $rows = $this->numRows($res);
339 print "<b>not found</b></li>\n";
340 print "<li>Attempting to set default tsearch2 locale to \"$ctype\"...";
344 $tsname = pg_fetch_result($res, 0, 0);
345 if ($tsname != 'default') {
346 print "<b>not set to default ($tsname)</b>";
347 print "<li>Attempting to change tsearch2 default locale to \"$ctype\"...";
352 $SQL = "UPDATE $wgDBts2schema.pg_ts_cfg SET locale = '$ctype' WHERE ts_name = 'default'";
353 $res = $this->doQuery($SQL);
355 print "<b>FAILED</b>. ";
356 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"$ctype\"</li>\n";
362 ## Final test: try out a simple tsearch2 query
363 $SQL = "SELECT $wgDBts2schema.to_tsvector('default','MediaWiki tsearch2 testing')";
364 $res = $this->doQuery($SQL);
366 print "<b>FAILED</b>. Specifically, \"$SQL\" did not work.</li>";
371 ## Do we have plpgsql installed?
372 print "<li>Checking for Pl/Pgsql ...";
373 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
374 $rows = $this->numRows($this->doQuery($SQL));
376 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
377 print "not installed. Attempting to install Pl/Pgsql ...";
378 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
379 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
380 $rows = $this->numRows($this->doQuery($SQL));
382 $olde = error_reporting(0);
383 error_reporting($olde - E_WARNING
);
384 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
385 error_reporting($olde);
387 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
392 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
398 ## Does the schema already exist? Who owns it?
399 $result = $this->schemaExists($wgDBmwschema);
401 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
402 error_reporting( 0 );
403 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
404 error_reporting( E_ALL
);
406 print "<b>FAILED</b>. The user \"$wgDBuser\" must be able to access the schema. ".
407 "You can try making them the owner of the database, or try creating the schema with a ".
408 "different user, and then grant access to the \"$wgDBuser\" user.</li>\n";
413 else if ($result != $user) {
414 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
417 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
420 ## Always return GMT time to accomodate the existing integer-based timestamp assumption
421 print "<li>Setting the timezone to GMT for user \"$user\" ...";
422 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
423 $result = pg_query($this->mConn
, $SQL);
425 print "<b>FAILED</b>.</li>\n";
429 ## Set for the rest of this session
430 $SQL = "SET timezone = 'GMT'";
431 $result = pg_query($this->mConn
, $SQL);
433 print "<li>Failed to set timezone</li>\n";
437 print "<li>Setting the datestyle to ISO, YMD for user \"$user\" ...";
438 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
439 $result = pg_query($this->mConn
, $SQL);
441 print "<b>FAILED</b>.</li>\n";
445 ## Set for the rest of this session
446 $SQL = "SET datestyle = 'ISO, YMD'";
447 $result = pg_query($this->mConn
, $SQL);
449 print "<li>Failed to set datestyle</li>\n";
453 ## Fix up the search paths if needed
454 print "<li>Setting the search path for user \"$user\" ...";
455 $path = $this->quote_ident($wgDBmwschema);
456 if ($wgDBts2schema !== $wgDBmwschema)
457 $path .= ", ". $this->quote_ident($wgDBts2schema);
458 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
460 $SQL = "ALTER USER $safeuser SET search_path = $path";
461 $result = pg_query($this->mConn
, $SQL);
463 print "<b>FAILED</b>.</li>\n";
467 ## Set for the rest of this session
468 $SQL = "SET search_path = $path";
469 $result = pg_query($this->mConn
, $SQL);
471 print "<li>Failed to set search_path</li>\n";
474 define( "POSTGRES_SEARCHPATH", $path );
477 global $wgCommandLineMode;
478 ## If called from the command-line (e.g. importDump), only show errors
479 if ($wgCommandLineMode) {
480 $this->doQuery("SET client_min_messages = 'ERROR'");
487 * Closes a database connection, if it is open
488 * Returns success, true if already closed
491 $this->mOpened
= false;
492 if ( $this->mConn
) {
493 return pg_close( $this->mConn
);
499 function doQuery( $sql ) {
500 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
503 function queryIgnore( $sql, $fname = '' ) {
504 return $this->query( $sql, $fname, true );
507 function freeResult( $res ) {
508 if ( !@pg_free_result
( $res ) ) {
509 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
513 function fetchObject( $res ) {
514 @$row = pg_fetch_object( $res );
515 # FIXME: HACK HACK HACK HACK debug
518 # hashar : not sure if the following test really trigger if the object
520 if( pg_last_error($this->mConn
) ) {
521 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
526 function fetchRow( $res ) {
527 @$row = pg_fetch_array( $res );
528 if( pg_last_error($this->mConn
) ) {
529 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
534 function numRows( $res ) {
535 @$n = pg_num_rows( $res );
536 if( pg_last_error($this->mConn
) ) {
537 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
541 function numFields( $res ) { return pg_num_fields( $res ); }
542 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
545 * This must be called after nextSequenceVal
547 function insertId() {
548 return $this->mInsertId
;
551 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
552 function lastError() {
553 if ( $this->mConn
) {
554 return pg_last_error();
557 return "No database connection";
560 function lastErrno() {
561 return pg_last_error() ?
1 : 0;
564 function affectedRows() {
565 if( !isset( $this->mLastResult
) or ! $this->mLastResult
)
568 return pg_affected_rows( $this->mLastResult
);
572 * Estimate rows in dataset
573 * Returns estimated count, based on EXPLAIN output
574 * This is not necessarily an accurate estimate, so use sparingly
575 * Returns -1 if count cannot be found
576 * Takes same arguments as Database::select()
579 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
580 $options['EXPLAIN'] = true;
581 $res = $this->select( $table, $vars, $conds, $fname, $options );
584 $row = $this->fetchRow( $res );
586 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
589 $this->freeResult($res);
596 * Returns information about an index
597 * If errors are explicitly ignored, returns NULL on failure
599 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
600 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
601 $res = $this->query( $sql, $fname );
605 while ( $row = $this->fetchObject( $res ) ) {
606 if ( $row->indexname
== $index ) {
613 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
614 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
615 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
616 $res = $this->query( $sql, $fname );
619 while ($row = $this->fetchObject( $res ))
626 * INSERT wrapper, inserts an array into a table
628 * $args may be a single associative array, or an array of these with numeric keys,
629 * for multi-row insert (Postgres version 8.2 and above only).
631 * @param array $table String: Name of the table to insert to.
632 * @param array $args Array: Items to insert into the table.
633 * @param array $fname String: Name of the function, for profiling
634 * @param mixed $options String or Array. Valid options: IGNORE
636 * @return bool Success of insert operation. IGNORE always returns true.
638 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
641 $table = $this->tableName( $table );
642 if (! isset( $wgDBversion ) ) {
643 $this->getServerVersion();
644 $wgDBversion = $this->numeric_version
;
647 if ( !is_array( $options ) )
648 $options = array( $options );
650 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
652 $keys = array_keys( $args[0] );
656 $keys = array_keys( $args );
659 $ignore = in_array( 'IGNORE', $options ) ?
1 : 0;
661 $olde = error_reporting( 0 );
663 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
666 if ( $wgDBversion >= 8.1 ) {
668 foreach ( $args as $row ) {
674 $sql .= '(' . $this->makeList( $row ) . ')';
676 $res = (bool)$this->query( $sql, $fname, $ignore );
681 foreach ( $args as $row ) {
683 $tempsql .= '(' . $this->makeList( $row ) . ')';
684 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
691 $sql .= '(' . $this->makeList( $args ) . ')';
692 $res = (bool)$this->query( $sql, $fname, $ignore );
696 $olde = error_reporting( $olde );
704 function tableName( $name ) {
705 # Replace reserved words with better ones
710 return 'pagecontent';
717 * Return the next in a sequence, save the value for retrieval via insertId()
719 function nextSequenceValue( $seqName ) {
720 $safeseq = preg_replace( "/'/", "''", $seqName );
721 $res = $this->query( "SELECT nextval('$safeseq')" );
722 $row = $this->fetchRow( $res );
723 $this->mInsertId
= $row[0];
724 $this->freeResult( $res );
725 return $this->mInsertId
;
729 * Postgres does not have a "USE INDEX" clause, so return an empty string
731 function useIndexClause( $index ) {
735 # REPLACE query wrapper
736 # Postgres simulates this with a DELETE followed by INSERT
737 # $row is the row to insert, an associative array
738 # $uniqueIndexes is an array of indexes. Each element may be either a
739 # field name or an array of field names
741 # It may be more efficient to leave off unique indexes which are unlikely to collide.
742 # However if you do this, you run the risk of encountering errors which wouldn't have
744 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
745 $table = $this->tableName( $table );
747 if (count($rows)==0) {
752 if ( !is_array( reset( $rows ) ) ) {
753 $rows = array( $rows );
756 foreach( $rows as $row ) {
757 # Delete rows which collide
758 if ( $uniqueIndexes ) {
759 $sql = "DELETE FROM $table WHERE ";
761 foreach ( $uniqueIndexes as $index ) {
768 if ( is_array( $index ) ) {
770 foreach ( $index as $col ) {
776 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
779 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
783 $this->query( $sql, $fname );
787 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
788 $this->makeList( $row, LIST_COMMA
) . ')';
789 $this->query( $sql, $fname );
793 # DELETE where the condition is a join
794 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
796 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
799 $delTable = $this->tableName( $delTable );
800 $joinTable = $this->tableName( $joinTable );
801 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
802 if ( $conds != '*' ) {
803 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
807 $this->query( $sql, $fname );
810 # Returns the size of a text field, or -1 for "unlimited"
811 function textFieldSize( $table, $field ) {
812 $table = $this->tableName( $table );
813 $sql = "SELECT t.typname as ftype,a.atttypmod as size
814 FROM pg_class c, pg_attribute a, pg_type t
815 WHERE relname='$table' AND a.attrelid=c.oid AND
816 a.atttypid=t.oid and a.attname='$field'";
817 $res =$this->query($sql);
818 $row=$this->fetchObject($res);
819 if ($row->ftype
=="varchar") {
824 $this->freeResult( $res );
828 function lowPriorityOption() {
832 function limitResult($sql, $limit,$offset=false) {
833 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
837 * Returns an SQL expression for a simple conditional.
838 * Uses CASE on Postgres
840 * @param string $cond SQL expression which will result in a boolean value
841 * @param string $trueVal SQL expression to return if true
842 * @param string $falseVal SQL expression to return if false
843 * @return string SQL fragment
845 function conditional( $cond, $trueVal, $falseVal ) {
846 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
849 function wasDeadlock() {
850 return $this->lastErrno() == '40P01';
853 function timestamp( $ts=0 ) {
854 return wfTimestamp(TS_POSTGRES
,$ts);
858 * Return aggregated value function call
860 function aggregateValue ($valuedata,$valuename='value') {
865 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
866 # Ignore errors during error handling to avoid infinite recursion
867 $ignore = $this->ignoreErrors( true );
868 ++
$this->mErrorCount
;
870 if ($ignore ||
$tempIgnore) {
871 wfDebug("SQL ERROR (ignored): $error\n");
872 $this->ignoreErrors( $ignore );
875 $message = "A database error has occurred\n" .
877 "Function: $fname\n" .
878 "Error: $errno $error\n";
879 throw new DBUnexpectedError($this, $message);
884 * @return string wikitext of a link to the server software's web site
886 function getSoftwareLink() {
887 return "[http://www.postgresql.org/ PostgreSQL]";
891 * @return string Version information from the database
893 function getServerVersion() {
894 $version = pg_fetch_result($this->doQuery("SELECT version()"),0,0);
896 if (!preg_match('/PostgreSQL (\d+\.\d+)(\S+)/', $version, $thisver)) {
897 die("Could not determine the numeric version from $version!");
899 $this->numeric_version
= $thisver[1];
905 * Query whether a given relation exists (in the given schema, or the
906 * default mw one if not given)
908 function relationExists( $table, $types, $schema = false ) {
909 global $wgDBmwschema;
910 if (!is_array($types))
911 $types = array($types);
913 $schema = $wgDBmwschema;
914 $etable = $this->addQuotes($table);
915 $eschema = $this->addQuotes($schema);
916 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
917 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
918 . "AND c.relkind IN ('" . implode("','", $types) . "')";
919 $res = $this->query( $SQL );
920 $count = $res ?
pg_num_rows($res) : 0;
922 $this->freeResult( $res );
923 return $count ?
true : false;
927 * For backward compatibility, this function checks both tables and
930 function tableExists ($table, $schema = false) {
931 return $this->relationExists($table, array('r', 'v'), $schema);
934 function sequenceExists ($sequence, $schema = false) {
935 return $this->relationExists($sequence, 'S', $schema);
938 function triggerExists($table, $trigger) {
939 global $wgDBmwschema;
942 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
943 WHERE relnamespace=pg_namespace.oid AND relkind='r'
944 AND tgrelid=pg_class.oid
945 AND nspname=%s AND relname=%s AND tgname=%s
947 $res = $this->query(sprintf($q,
948 $this->addQuotes($wgDBmwschema),
949 $this->addQuotes($table),
950 $this->addQuotes($trigger)));
953 $rows = pg_num_rows($res);
954 $this->freeResult($res);
958 function ruleExists($table, $rule) {
959 global $wgDBmwschema;
960 $exists = $this->selectField("pg_rules", "rulename",
961 array( "rulename" => $rule,
962 "tablename" => $table,
963 "schemaname" => $wgDBmwschema));
964 return $exists === $rule;
967 function constraintExists($table, $constraint) {
968 global $wgDBmwschema;
969 $SQL = sprintf("SELECT 1 FROM information_schema.table_constraints ".
970 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
971 $this->addQuotes($wgDBmwschema),
972 $this->addQuotes($table),
973 $this->addQuotes($constraint));
974 $res = $this->query($SQL);
977 $rows = pg_num_rows($res);
978 $this->freeResult($res);
983 * Query whether a given schema exists. Returns the name of the owner
985 function schemaExists( $schema ) {
986 $eschema = preg_replace("/'/", "''", $schema);
987 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
988 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
989 $res = $this->query( $SQL );
990 $owner = $res ?
pg_num_rows($res) ?
pg_fetch_result($res, 0, 0) : false : false;
992 $this->freeResult($res);
997 * Query whether a given column exists in the mediawiki schema
999 function fieldExists( $table, $field, $fname = 'DatabasePostgres::fieldExists' ) {
1000 global $wgDBmwschema;
1001 $etable = preg_replace("/'/", "''", $table);
1002 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
1003 $ecol = preg_replace("/'/", "''", $field);
1004 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
1005 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
1006 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
1007 $res = $this->query( $SQL, $fname );
1008 $count = $res ?
pg_num_rows($res) : 0;
1010 $this->freeResult( $res );
1014 function fieldInfo( $table, $field ) {
1015 return PostgresField
::fromText($this, $table, $field);
1018 function begin( $fname = 'DatabasePostgres::begin' ) {
1019 $this->query( 'BEGIN', $fname );
1020 $this->mTrxLevel
= 1;
1022 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
1025 function commit( $fname = 'DatabasePostgres::commit' ) {
1026 $this->query( 'COMMIT', $fname );
1027 $this->mTrxLevel
= 0;
1030 /* Not even sure why this is used in the main codebase... */
1031 function limitResultForUpdate($sql, $num) {
1035 function setup_database() {
1036 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
1038 ## Make sure that we can write to the correct schema
1039 ## If not, Postgres will happily and silently go to the next search_path item
1040 $ctest = "mw_test_table";
1041 if ($this->tableExists($ctest, $wgDBmwschema)) {
1042 $this->doQuery("DROP TABLE $wgDBmwschema.$ctest");
1044 $SQL = "CREATE TABLE $wgDBmwschema.$ctest(a int)";
1045 $olde = error_reporting( 0 );
1046 $res = $this->doQuery($SQL);
1047 error_reporting( $olde );
1049 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" can write to the schema \"$wgDBmwschema\"</li>\n";
1052 $this->doQuery("DROP TABLE $wgDBmwschema.mw_test_table");
1054 dbsource( "../maintenance/postgres/tables.sql", $this);
1056 ## Version-specific stuff
1057 if ($this->numeric_version
== 8.1) {
1058 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gist(textvector)");
1059 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gist(titlevector)");
1062 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gin(textvector)");
1063 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gin(titlevector)");
1066 ## Update version information
1067 $mwv = $this->addQuotes($wgVersion);
1068 $pgv = $this->addQuotes($this->getServerVersion());
1069 $pgu = $this->addQuotes($this->mUser
);
1070 $mws = $this->addQuotes($wgDBmwschema);
1071 $tss = $this->addQuotes($wgDBts2schema);
1072 $pgp = $this->addQuotes($wgDBport);
1073 $dbn = $this->addQuotes($this->mDBname
);
1074 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
1076 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
1077 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
1078 "ctype = '$ctype' ".
1079 "WHERE type = 'Creation'";
1082 ## Avoid the non-standard "REPLACE INTO" syntax
1083 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1085 dieout( "<li>Could not find the interwiki.sql file");
1087 ## We simply assume it is already empty as we have just created it
1088 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1089 while ( ! feof( $f ) ) {
1090 $line = fgets($f,1024);
1092 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
1095 $this->query("$SQL $matches[1],$matches[2])");
1097 print " (table interwiki successfully populated)...\n";
1099 $this->doQuery("COMMIT");
1102 function encodeBlob( $b ) {
1103 return pg_escape_bytea( $b );
1105 function decodeBlob( $b ) {
1106 return pg_unescape_bytea( $b );
1109 function strencode( $s ) { ## Should not be called by us
1110 return pg_escape_string( $s );
1113 function addQuotes( $s ) {
1114 if ( is_null( $s ) ) {
1116 } else if (is_array( $s )) { ## Assume it is bytea data
1119 return "'" . pg_escape_string($s) . "'";
1120 // Unreachable: return "E'" . pg_escape_string($s) . "'";
1123 function quote_ident( $s ) {
1124 return '"' . preg_replace( '/"/', '""', $s) . '"';
1127 /* For now, does nothing */
1128 function selectDB( $db ) {
1133 * Various select options
1137 * @param array $options an associative array of options to be turned into
1138 * an SQL query, valid keys are listed in the function.
1141 function makeSelectOptions( $options ) {
1142 $preLimitTail = $postLimitTail = '';
1143 $startOpts = $useIndex = '';
1145 $noKeyOptions = array();
1146 foreach ( $options as $key => $option ) {
1147 if ( is_numeric( $key ) ) {
1148 $noKeyOptions[$option] = true;
1152 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY " . $options['GROUP BY'];
1153 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1154 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY " . $options['ORDER BY'];
1156 //if (isset($options['LIMIT'])) {
1157 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1158 // isset($options['OFFSET']) ? $options['OFFSET']
1162 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1163 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1164 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1166 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1169 public function setTimeout( $timeout ) {
1170 // @todo fixme no-op
1174 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
1179 * How lagged is this slave?
1182 public function getLag() {
1183 # Not implemented for PostgreSQL
1187 } // end DatabasePostgres class