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) {
20 CASE WHEN typname = 'int2' THEN 'smallint'
21 WHEN typname = 'int4' THEN 'integer'
22 WHEN typname = 'int8' THEN 'bigint'
23 WHEN typname = 'bpchar' THEN 'char'
24 ELSE typname END AS typname
,
26 FROM pg_class
, pg_namespace
, pg_attribute
, pg_type
27 WHERE relnamespace
=pg_namespace
.oid
29 AND attrelid
=pg_class
.oid
30 AND atttypid
=pg_type
.oid
35 $res = $db->query(sprintf($q,
36 $db->addQuotes($wgDBmwschema),
37 $db->addQuotes($table),
38 $db->addQuotes($field)));
39 $row = $db->fetchObject($res);
42 $n = new PostgresField
;
43 $n->type
= $row->typname
;
44 $n->nullable
= ($row->attnotnull
== 'f');
46 $n->tablename
= $table;
47 $n->max_length
= $row->attlen
;
55 function tableName() {
56 return $this->tablename
;
64 return $this->nullable
;
67 function maxLength() {
68 return $this->max_length
;
73 * @addtogroup Database
75 class DatabasePostgres
extends Database
{
76 var $mInsertId = NULL;
77 var $mLastResult = NULL;
78 var $numeric_version = NULL;
80 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
81 $failFunction = false, $flags = 0 )
85 # Can't get a reference if it hasn't been set yet
86 if ( !isset( $wgOut ) ) {
89 $this->mOut
=& $wgOut;
90 $this->mFailFunction
= $failFunction;
91 $this->mFlags
= $flags;
92 $this->open( $server, $user, $password, $dbName);
96 function cascadingDeletes() {
99 function cleanupTriggers() {
102 function strictIPs() {
105 function realTimestamps() {
108 function implicitGroupby() {
111 function implicitOrderby() {
114 function searchableIPs() {
117 function functionalIndexes() {
121 function hasConstraint( $name ) {
122 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint WHERE conname = '" . pg_escape_string( $name ) . "'";
123 return $this->numRows($res = $this->doQuery($SQL));
126 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
128 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
132 * Usually aborts on failure
133 * If the failFunction is set to a non-zero integer, returns success
135 function open( $server, $user, $password, $dbName ) {
136 # Test for Postgres support, to avoid suppressed fatal error
137 if ( !function_exists( 'pg_connect' ) ) {
138 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" );
143 if (!strlen($user)) { ## e.g. the class is being loaded
148 $this->mServer
= $server;
150 $this->mUser
= $user;
151 $this->mPassword
= $password;
152 $this->mDBname
= $dbName;
155 if ($server!=false && $server!="") {
156 $hstring="host=$server ";
158 if ($port!=false && $port!="") {
159 $hstring .= "port=$port ";
163 error_reporting( E_ALL
);
164 @$this->mConn
= pg_connect("$hstring dbname=$dbName user=$user password=$password");
166 if ( $this->mConn
== false ) {
167 wfDebug( "DB connection error\n" );
168 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
169 wfDebug( $this->lastError()."\n" );
173 $this->mOpened
= true;
174 ## If this is the initial connection, setup the schema stuff and possibly create the user
175 ## TODO: Move this out of open()
176 if (defined('MEDIAWIKI_INSTALL')) {
177 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBsuperuser, $wgDBmwschema,
180 print "<li>Checking the version of Postgres...";
181 $version = $this->getServerVersion();
183 if ($this->numeric_version
< $PGMINVER) {
184 print "<b>FAILED</b>. Required version is $PGMINVER. You have $this->numeric_version ($version)</li>\n";
187 print "version $this->numeric_version is OK.</li>\n";
189 $safeuser = $this->quote_ident($wgDBuser);
190 ## Are we connecting as a superuser for the first time?
191 if ($wgDBsuperuser) {
192 ## Are we really a superuser? Check out our rights
194 CASE WHEN usesuper IS TRUE THEN
195 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
196 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
198 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
199 $rows = $this->numRows($res = $this->doQuery($SQL));
201 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
204 $perms = pg_fetch_result($res, 0, 0);
206 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
207 $rows = $this->numRows($this->doQuery($SQL));
209 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
212 if ($perms != 1 and $perms != 3) {
213 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
214 print 'Please use a different Postgres user.</li>';
217 print "<li>Creating user <b>$wgDBuser</b>...";
218 $safepass = $this->addQuotes($wgDBpassword);
219 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
220 $this->doQuery($SQL);
223 ## User now exists, check out the database
224 if ($dbName != $wgDBname) {
225 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
226 $rows = $this->numRows($this->doQuery($SQL));
228 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
232 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
233 print 'Please use a different Postgres user.</li>';
236 print "<li>Creating database <b>$wgDBname</b>...";
237 $safename = $this->quote_ident($wgDBname);
238 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
239 $this->doQuery($SQL);
241 ## Hopefully tsearch2 and plpgsql are in template1...
244 ## Reconnect to check out tsearch2 rights for this user
245 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
246 @$this->mConn
= pg_connect("$hstring dbname=$wgDBname user=$user password=$password");
247 if ( $this->mConn
== false ) {
248 print "<b>FAILED TO CONNECT!</b></li>";
255 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
256 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
257 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
258 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
259 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
263 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
264 foreach (array('cfg','cfgmap','dict','parser') as $table) {
265 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
266 $this->doQuery($SQL);
271 ## Setup the schema for this user if needed
272 $result = $this->schemaExists($wgDBmwschema);
273 $safeschema = $this->quote_ident($wgDBmwschema);
275 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
276 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
278 print "<b>FAILED</b>.</li>\n";
284 print "<li>Schema already exists, explicitly granting rights...\n";
285 $safeschema2 = $this->addQuotes($wgDBmwschema);
286 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
287 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
288 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
289 "AND p.relkind IN ('r','S','v')\n";
291 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
292 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
293 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
294 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
295 $res = $this->doQuery($SQL);
297 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
300 $this->doQuery("SET search_path = $safeschema");
301 $rows = $this->numRows($res);
304 $this->doQuery(pg_fetch_result($res, $rows, 0));
310 return true; ## Reconnect as regular user
314 if (!defined('POSTGRES_SEARCHPATH')) {
316 ## Do we have the basic tsearch2 table?
317 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
318 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
319 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
320 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
321 print " for instructions.</li>\n";
326 ## Does this user have the rights to the tsearch2 tables?
327 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
328 print "<li>Checking tsearch2 permissions...";
329 ## Let's check all four, just to be safe
330 error_reporting( 0 );
331 $ts2tables = array('cfg','cfgmap','dict','parser');
332 foreach ( $ts2tables AS $tname ) {
333 $SQL = "SELECT count(*) FROM $wgDBts2schema.pg_ts_$tname";
334 $res = $this->doQuery($SQL);
336 print "<b>FAILED</b> to access pg_ts_$tname. Make sure that the user ".
337 "\"$wgDBuser\" has SELECT access to all four tsearch2 tables</li>\n";
341 $SQL = "SELECT ts_name FROM $wgDBts2schema.pg_ts_cfg WHERE locale = '$ctype'";
342 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
343 $res = $this->doQuery($SQL);
344 error_reporting( E_ALL
);
346 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
351 ## Will the current locale work? Can we force it to?
352 print "<li>Verifying tsearch2 locale with $ctype...";
353 $rows = $this->numRows($res);
356 print "<b>not found</b></li>\n";
357 print "<li>Attempting to set default tsearch2 locale to \"$ctype\"...";
361 $tsname = pg_fetch_result($res, 0, 0);
362 if ($tsname != 'default') {
363 print "<b>not set to default ($tsname)</b>";
364 print "<li>Attempting to change tsearch2 default locale to \"$ctype\"...";
369 $SQL = "UPDATE $wgDBts2schema.pg_ts_cfg SET locale = '$ctype' WHERE ts_name = 'default'";
370 $res = $this->doQuery($SQL);
372 print "<b>FAILED</b>. ";
373 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"$ctype\"</li>\n";
379 ## Final test: try out a simple tsearch2 query
380 $SQL = "SELECT $wgDBts2schema.to_tsvector('default','MediaWiki tsearch2 testing')";
381 $res = $this->doQuery($SQL);
383 print "<b>FAILED</b>. Specifically, \"$SQL\" did not work.</li>";
388 ## Do we have plpgsql installed?
389 print "<li>Checking for Pl/Pgsql ...";
390 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
391 $rows = $this->numRows($this->doQuery($SQL));
393 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
394 print "not installed. Attempting to install Pl/Pgsql ...";
395 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
396 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
397 $rows = $this->numRows($this->doQuery($SQL));
399 $olde = error_reporting(0);
400 error_reporting($olde - E_WARNING
);
401 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
402 error_reporting($olde);
404 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
409 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
415 ## Does the schema already exist? Who owns it?
416 $result = $this->schemaExists($wgDBmwschema);
418 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
419 error_reporting( 0 );
420 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
421 error_reporting( E_ALL
);
423 print "<b>FAILED</b>. The user \"$wgDBuser\" must be able to access the schema. ".
424 "You can try making them the owner of the database, or try creating the schema with a ".
425 "different user, and then grant access to the \"$wgDBuser\" user.</li>\n";
430 else if ($result != $user) {
431 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
434 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
437 ## Always return GMT time to accomodate the existing integer-based timestamp assumption
438 print "<li>Setting the timezone to GMT for user \"$user\" ...";
439 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
440 $result = pg_query($this->mConn
, $SQL);
442 print "<b>FAILED</b>.</li>\n";
446 ## Set for the rest of this session
447 $SQL = "SET timezone = 'GMT'";
448 $result = pg_query($this->mConn
, $SQL);
450 print "<li>Failed to set timezone</li>\n";
454 print "<li>Setting the datestyle to ISO, YMD for user \"$user\" ...";
455 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
456 $result = pg_query($this->mConn
, $SQL);
458 print "<b>FAILED</b>.</li>\n";
462 ## Set for the rest of this session
463 $SQL = "SET datestyle = 'ISO, YMD'";
464 $result = pg_query($this->mConn
, $SQL);
466 print "<li>Failed to set datestyle</li>\n";
470 ## Fix up the search paths if needed
471 print "<li>Setting the search path for user \"$user\" ...";
472 $path = $this->quote_ident($wgDBmwschema);
473 if ($wgDBts2schema !== $wgDBmwschema)
474 $path .= ", ". $this->quote_ident($wgDBts2schema);
475 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
477 $SQL = "ALTER USER $safeuser SET search_path = $path";
478 $result = pg_query($this->mConn
, $SQL);
480 print "<b>FAILED</b>.</li>\n";
484 ## Set for the rest of this session
485 $SQL = "SET search_path = $path";
486 $result = pg_query($this->mConn
, $SQL);
488 print "<li>Failed to set search_path</li>\n";
491 define( "POSTGRES_SEARCHPATH", $path );
494 global $wgCommandLineMode;
495 ## If called from the command-line (e.g. importDump), only show errors
496 if ($wgCommandLineMode) {
497 $this->doQuery("SET client_min_messages = 'ERROR'");
500 global $wgDBmwschema, $wgDBts2schema;
501 if (isset( $wgDBmwschema ) && isset( $wgDBts2schema )
502 && $wgDBmwschema !== 'mediawiki'
503 && preg_match( '/^\w+$/', $wgDBmwschema )
504 && preg_match( '/^\w+$/', $wgDBts2schema )
506 $this->doQuery("SET search_path = $wgDBmwschema, $wgDBts2schema, public");
513 * Closes a database connection, if it is open
514 * Returns success, true if already closed
517 $this->mOpened
= false;
518 if ( $this->mConn
) {
519 return pg_close( $this->mConn
);
525 function doQuery( $sql ) {
526 if (function_exists('mb_convert_encoding')) {
527 return $this->mLastResult
=pg_query( $this->mConn
, mb_convert_encoding($sql,'UTF-8') );
529 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
532 function queryIgnore( $sql, $fname = '' ) {
533 return $this->query( $sql, $fname, true );
536 function freeResult( $res ) {
537 if ( $res instanceof ResultWrapper
) {
540 if ( !@pg_free_result
( $res ) ) {
541 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
545 function fetchObject( $res ) {
546 if ( $res instanceof ResultWrapper
) {
549 @$row = pg_fetch_object( $res );
550 # FIXME: HACK HACK HACK HACK debug
553 # hashar : not sure if the following test really trigger if the object
555 if( pg_last_error($this->mConn
) ) {
556 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
561 function fetchRow( $res ) {
562 if ( $res instanceof ResultWrapper
) {
565 @$row = pg_fetch_array( $res );
566 if( pg_last_error($this->mConn
) ) {
567 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
572 function numRows( $res ) {
573 if ( $res instanceof ResultWrapper
) {
576 @$n = pg_num_rows( $res );
577 if( pg_last_error($this->mConn
) ) {
578 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
582 function numFields( $res ) {
583 if ( $res instanceof ResultWrapper
) {
586 return pg_num_fields( $res );
588 function fieldName( $res, $n ) {
589 if ( $res instanceof ResultWrapper
) {
592 return pg_field_name( $res, $n );
596 * This must be called after nextSequenceVal
598 function insertId() {
599 return $this->mInsertId
;
602 function dataSeek( $res, $row ) {
603 if ( $res instanceof ResultWrapper
) {
606 return pg_result_seek( $res, $row );
609 function lastError() {
610 if ( $this->mConn
) {
611 return pg_last_error();
614 return "No database connection";
617 function lastErrno() {
618 return pg_last_error() ?
1 : 0;
621 function affectedRows() {
622 if( !isset( $this->mLastResult
) or ! $this->mLastResult
)
625 return pg_affected_rows( $this->mLastResult
);
629 * Estimate rows in dataset
630 * Returns estimated count, based on EXPLAIN output
631 * This is not necessarily an accurate estimate, so use sparingly
632 * Returns -1 if count cannot be found
633 * Takes same arguments as Database::select()
636 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
637 $options['EXPLAIN'] = true;
638 $res = $this->select( $table, $vars, $conds, $fname, $options );
641 $row = $this->fetchRow( $res );
643 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
646 $this->freeResult($res);
653 * Returns information about an index
654 * If errors are explicitly ignored, returns NULL on failure
656 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
657 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
658 $res = $this->query( $sql, $fname );
662 while ( $row = $this->fetchObject( $res ) ) {
663 if ( $row->indexname
== $index ) {
670 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
671 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
672 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
673 $res = $this->query( $sql, $fname );
676 while ($row = $this->fetchObject( $res ))
683 * INSERT wrapper, inserts an array into a table
685 * $args may be a single associative array, or an array of these with numeric keys,
686 * for multi-row insert (Postgres version 8.2 and above only).
688 * @param array $table String: Name of the table to insert to.
689 * @param array $args Array: Items to insert into the table.
690 * @param array $fname String: Name of the function, for profiling
691 * @param mixed $options String or Array. Valid options: IGNORE
693 * @return bool Success of insert operation. IGNORE always returns true.
695 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
698 $table = $this->tableName( $table );
699 if (! isset( $wgDBversion ) ) {
700 $this->getServerVersion();
701 $wgDBversion = $this->numeric_version
;
704 if ( !is_array( $options ) )
705 $options = array( $options );
707 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
709 $keys = array_keys( $args[0] );
713 $keys = array_keys( $args );
716 $ignore = in_array( 'IGNORE', $options ) ?
1 : 0;
718 $olde = error_reporting( 0 );
720 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
723 if ( $wgDBversion >= 8.2 ) {
725 foreach ( $args as $row ) {
731 $sql .= '(' . $this->makeList( $row ) . ')';
733 $res = (bool)$this->query( $sql, $fname, $ignore );
738 foreach ( $args as $row ) {
740 $tempsql .= '(' . $this->makeList( $row ) . ')';
741 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
748 $sql .= '(' . $this->makeList( $args ) . ')';
749 $res = (bool)$this->query( $sql, $fname, $ignore );
753 $olde = error_reporting( $olde );
761 function tableName( $name ) {
762 # Replace reserved words with better ones
767 return 'pagecontent';
774 * Return the next in a sequence, save the value for retrieval via insertId()
776 function nextSequenceValue( $seqName ) {
777 $safeseq = preg_replace( "/'/", "''", $seqName );
778 $res = $this->query( "SELECT nextval('$safeseq')" );
779 $row = $this->fetchRow( $res );
780 $this->mInsertId
= $row[0];
781 $this->freeResult( $res );
782 return $this->mInsertId
;
786 * Postgres does not have a "USE INDEX" clause, so return an empty string
788 function useIndexClause( $index ) {
792 # REPLACE query wrapper
793 # Postgres simulates this with a DELETE followed by INSERT
794 # $row is the row to insert, an associative array
795 # $uniqueIndexes is an array of indexes. Each element may be either a
796 # field name or an array of field names
798 # It may be more efficient to leave off unique indexes which are unlikely to collide.
799 # However if you do this, you run the risk of encountering errors which wouldn't have
801 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
802 $table = $this->tableName( $table );
804 if (count($rows)==0) {
809 if ( !is_array( reset( $rows ) ) ) {
810 $rows = array( $rows );
813 foreach( $rows as $row ) {
814 # Delete rows which collide
815 if ( $uniqueIndexes ) {
816 $sql = "DELETE FROM $table WHERE ";
818 foreach ( $uniqueIndexes as $index ) {
825 if ( is_array( $index ) ) {
827 foreach ( $index as $col ) {
833 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
836 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
840 $this->query( $sql, $fname );
844 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
845 $this->makeList( $row, LIST_COMMA
) . ')';
846 $this->query( $sql, $fname );
850 # DELETE where the condition is a join
851 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
853 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
856 $delTable = $this->tableName( $delTable );
857 $joinTable = $this->tableName( $joinTable );
858 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
859 if ( $conds != '*' ) {
860 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
864 $this->query( $sql, $fname );
867 # Returns the size of a text field, or -1 for "unlimited"
868 function textFieldSize( $table, $field ) {
869 $table = $this->tableName( $table );
870 $sql = "SELECT t.typname as ftype,a.atttypmod as size
871 FROM pg_class c, pg_attribute a, pg_type t
872 WHERE relname='$table' AND a.attrelid=c.oid AND
873 a.atttypid=t.oid and a.attname='$field'";
874 $res =$this->query($sql);
875 $row=$this->fetchObject($res);
876 if ($row->ftype
=="varchar") {
881 $this->freeResult( $res );
885 function lowPriorityOption() {
889 function limitResult($sql, $limit,$offset=false) {
890 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
894 * Returns an SQL expression for a simple conditional.
895 * Uses CASE on Postgres
897 * @param string $cond SQL expression which will result in a boolean value
898 * @param string $trueVal SQL expression to return if true
899 * @param string $falseVal SQL expression to return if false
900 * @return string SQL fragment
902 function conditional( $cond, $trueVal, $falseVal ) {
903 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
906 function wasDeadlock() {
907 return $this->lastErrno() == '40P01';
910 function timestamp( $ts=0 ) {
911 return wfTimestamp(TS_POSTGRES
,$ts);
915 * Return aggregated value function call
917 function aggregateValue ($valuedata,$valuename='value') {
922 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
923 # Ignore errors during error handling to avoid infinite recursion
924 $ignore = $this->ignoreErrors( true );
925 ++
$this->mErrorCount
;
927 if ($ignore ||
$tempIgnore) {
928 wfDebug("SQL ERROR (ignored): $error\n");
929 $this->ignoreErrors( $ignore );
932 $message = "A database error has occurred\n" .
934 "Function: $fname\n" .
935 "Error: $errno $error\n";
936 throw new DBUnexpectedError($this, $message);
941 * @return string wikitext of a link to the server software's web site
943 function getSoftwareLink() {
944 return "[http://www.postgresql.org/ PostgreSQL]";
948 * @return string Version information from the database
950 function getServerVersion() {
951 $version = pg_fetch_result($this->doQuery("SELECT version()"),0,0);
953 if (!preg_match('/PostgreSQL (\d+\.\d+)(\S+)/', $version, $thisver)) {
954 die("Could not determine the numeric version from $version!");
956 $this->numeric_version
= $thisver[1];
962 * Query whether a given relation exists (in the given schema, or the
963 * default mw one if not given)
965 function relationExists( $table, $types, $schema = false ) {
966 global $wgDBmwschema;
967 if (!is_array($types))
968 $types = array($types);
970 $schema = $wgDBmwschema;
971 $etable = $this->addQuotes($table);
972 $eschema = $this->addQuotes($schema);
973 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
974 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
975 . "AND c.relkind IN ('" . implode("','", $types) . "')";
976 $res = $this->query( $SQL );
977 $count = $res ?
$res->numRows() : 0;
979 $this->freeResult( $res );
980 return $count ?
true : false;
984 * For backward compatibility, this function checks both tables and
987 function tableExists ($table, $schema = false) {
988 return $this->relationExists($table, array('r', 'v'), $schema);
991 function sequenceExists ($sequence, $schema = false) {
992 return $this->relationExists($sequence, 'S', $schema);
995 function triggerExists($table, $trigger) {
996 global $wgDBmwschema;
999 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1000 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1001 AND tgrelid=pg_class.oid
1002 AND nspname=%s AND relname=%s AND tgname=%s
1004 $res = $this->query(sprintf($q,
1005 $this->addQuotes($wgDBmwschema),
1006 $this->addQuotes($table),
1007 $this->addQuotes($trigger)));
1010 $rows = $res->numRows();
1011 $this->freeResult($res);
1015 function ruleExists($table, $rule) {
1016 global $wgDBmwschema;
1017 $exists = $this->selectField("pg_rules", "rulename",
1018 array( "rulename" => $rule,
1019 "tablename" => $table,
1020 "schemaname" => $wgDBmwschema));
1021 return $exists === $rule;
1024 function constraintExists($table, $constraint) {
1025 global $wgDBmwschema;
1026 $SQL = sprintf("SELECT 1 FROM information_schema.table_constraints ".
1027 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1028 $this->addQuotes($wgDBmwschema),
1029 $this->addQuotes($table),
1030 $this->addQuotes($constraint));
1031 $res = $this->query($SQL);
1034 $rows = $res->numRows();
1035 $this->freeResult($res);
1040 * Query whether a given schema exists. Returns the name of the owner
1042 function schemaExists( $schema ) {
1043 $eschema = preg_replace("/'/", "''", $schema);
1044 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1045 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1046 $res = $this->query( $SQL );
1047 if ( $res && $res->numRows() ) {
1048 $row = $res->fetchObject();
1049 $owner = $row->rolname
;
1054 $this->freeResult($res);
1059 * Query whether a given column exists in the mediawiki schema
1061 function fieldExists( $table, $field, $fname = 'DatabasePostgres::fieldExists' ) {
1062 global $wgDBmwschema;
1063 $etable = preg_replace("/'/", "''", $table);
1064 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
1065 $ecol = preg_replace("/'/", "''", $field);
1066 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
1067 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
1068 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
1069 $res = $this->query( $SQL, $fname );
1070 $count = $res ?
$res->numRows() : 0;
1072 $this->freeResult( $res );
1076 function fieldInfo( $table, $field ) {
1077 return PostgresField
::fromText($this, $table, $field);
1080 function begin( $fname = 'DatabasePostgres::begin' ) {
1081 $this->query( 'BEGIN', $fname );
1082 $this->mTrxLevel
= 1;
1084 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
1087 function commit( $fname = 'DatabasePostgres::commit' ) {
1088 $this->query( 'COMMIT', $fname );
1089 $this->mTrxLevel
= 0;
1092 /* Not even sure why this is used in the main codebase... */
1093 function limitResultForUpdate($sql, $num) {
1097 function setup_database() {
1098 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
1100 ## Make sure that we can write to the correct schema
1101 ## If not, Postgres will happily and silently go to the next search_path item
1102 $ctest = "mw_test_table";
1103 if ($this->tableExists($ctest, $wgDBmwschema)) {
1104 $this->doQuery("DROP TABLE $wgDBmwschema.$ctest");
1106 $SQL = "CREATE TABLE $wgDBmwschema.$ctest(a int)";
1107 $olde = error_reporting( 0 );
1108 $res = $this->doQuery($SQL);
1109 error_reporting( $olde );
1111 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" can write to the schema \"$wgDBmwschema\"</li>\n";
1114 $this->doQuery("DROP TABLE $wgDBmwschema.mw_test_table");
1116 dbsource( "../maintenance/postgres/tables.sql", $this);
1118 ## Version-specific stuff
1119 if ($this->numeric_version
== 8.1) {
1120 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gist(textvector)");
1121 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gist(titlevector)");
1124 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gin(textvector)");
1125 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gin(titlevector)");
1128 ## Update version information
1129 $mwv = $this->addQuotes($wgVersion);
1130 $pgv = $this->addQuotes($this->getServerVersion());
1131 $pgu = $this->addQuotes($this->mUser
);
1132 $mws = $this->addQuotes($wgDBmwschema);
1133 $tss = $this->addQuotes($wgDBts2schema);
1134 $pgp = $this->addQuotes($wgDBport);
1135 $dbn = $this->addQuotes($this->mDBname
);
1136 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
1138 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
1139 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
1140 "ctype = '$ctype' ".
1141 "WHERE type = 'Creation'";
1144 ## Avoid the non-standard "REPLACE INTO" syntax
1145 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1147 dieout( "<li>Could not find the interwiki.sql file");
1149 ## We simply assume it is already empty as we have just created it
1150 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1151 while ( ! feof( $f ) ) {
1152 $line = fgets($f,1024);
1154 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
1157 $this->query("$SQL $matches[1],$matches[2])");
1159 print " (table interwiki successfully populated)...\n";
1161 $this->doQuery("COMMIT");
1164 function encodeBlob( $b ) {
1165 return new Blob ( pg_escape_bytea( $b ) ) ;
1168 function decodeBlob( $b ) {
1169 if ($b instanceof Blob
) {
1172 return pg_unescape_bytea( $b );
1175 function strencode( $s ) { ## Should not be called by us
1176 return pg_escape_string( $s );
1179 function addQuotes( $s ) {
1180 if ( is_null( $s ) ) {
1182 } else if ($s instanceof Blob
) {
1183 return "'".$s->fetch($s)."'";
1185 return "'" . pg_escape_string($s) . "'";
1188 function quote_ident( $s ) {
1189 return '"' . preg_replace( '/"/', '""', $s) . '"';
1192 /* For now, does nothing */
1193 function selectDB( $db ) {
1198 * Various select options
1202 * @param array $options an associative array of options to be turned into
1203 * an SQL query, valid keys are listed in the function.
1206 function makeSelectOptions( $options ) {
1207 $preLimitTail = $postLimitTail = '';
1208 $startOpts = $useIndex = '';
1210 $noKeyOptions = array();
1211 foreach ( $options as $key => $option ) {
1212 if ( is_numeric( $key ) ) {
1213 $noKeyOptions[$option] = true;
1217 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY " . $options['GROUP BY'];
1218 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1219 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY " . $options['ORDER BY'];
1221 //if (isset($options['LIMIT'])) {
1222 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1223 // isset($options['OFFSET']) ? $options['OFFSET']
1227 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1228 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1229 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1231 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1234 public function setTimeout( $timeout ) {
1235 // @todo fixme no-op
1239 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
1244 * How lagged is this slave?
1247 public function getLag() {
1248 # Not implemented for PostgreSQL
1252 function buildConcat( $stringList ) {
1253 return implode( ' || ', $stringList );
1256 } // end DatabasePostgres class