8 * This is the Postgres database abstraction layer.
10 * As it includes more generic version for DB functions,
11 * than MySQL ones, some of them should be moved to parent
17 private $name, $tablename, $type, $nullable, $max_length;
19 static function fromText($db, $table, $field) {
24 CASE WHEN typname = 'int2' THEN 'smallint'
25 WHEN typname = 'int4' THEN 'integer'
26 WHEN typname = 'int8' THEN 'bigint'
27 WHEN typname = 'bpchar' THEN 'char'
28 ELSE typname END AS typname
,
30 FROM pg_class
, pg_namespace
, pg_attribute
, pg_type
31 WHERE relnamespace
=pg_namespace
.oid
33 AND attrelid
=pg_class
.oid
34 AND atttypid
=pg_type
.oid
39 $res = $db->query(sprintf($q,
40 $db->addQuotes($wgDBmwschema),
41 $db->addQuotes($table),
42 $db->addQuotes($field)));
43 $row = $db->fetchObject($res);
46 $n = new PostgresField
;
47 $n->type
= $row->typname
;
48 $n->nullable
= ($row->attnotnull
== 'f');
50 $n->tablename
= $table;
51 $n->max_length
= $row->attlen
;
59 function tableName() {
60 return $this->tablename
;
68 return $this->nullable
;
71 function maxLength() {
72 return $this->max_length
;
79 class DatabasePostgres
extends Database
{
80 var $mInsertId = NULL;
81 var $mLastResult = NULL;
82 var $numeric_version = NULL;
84 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
85 $failFunction = false, $flags = 0 )
89 # Can't get a reference if it hasn't been set yet
90 if ( !isset( $wgOut ) ) {
93 $this->mOut
=& $wgOut;
94 $this->mFailFunction
= $failFunction;
95 $this->mFlags
= $flags;
96 $this->open( $server, $user, $password, $dbName);
100 function cascadingDeletes() {
103 function cleanupTriggers() {
106 function strictIPs() {
109 function realTimestamps() {
112 function implicitGroupby() {
115 function implicitOrderby() {
118 function searchableIPs() {
121 function functionalIndexes() {
125 function hasConstraint( $name ) {
126 global $wgDBmwschema;
127 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" . pg_escape_string( $name ) . "' AND n.nspname = '" . pg_escape_string($wgDBmwschema) ."'";
128 return $this->numRows($res = $this->doQuery($SQL));
131 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
133 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
137 * Usually aborts on failure
138 * If the failFunction is set to a non-zero integer, returns success
140 function open( $server, $user, $password, $dbName ) {
141 # Test for Postgres support, to avoid suppressed fatal error
142 if ( !function_exists( 'pg_connect' ) ) {
143 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" );
148 if (!strlen($user)) { ## e.g. the class is being loaded
153 $this->mServer
= $server;
154 $this->mPort
= $port = $wgDBport;
155 $this->mUser
= $user;
156 $this->mPassword
= $password;
157 $this->mDBname
= $dbName;
160 if ($server!=false && $server!="") {
161 $hstring="host=$server ";
163 if ($port!=false && $port!="") {
164 $hstring .= "port=$port ";
167 error_reporting( E_ALL
);
168 @$this->mConn
= pg_connect("$hstring dbname=$dbName user=$user password=$password");
170 if ( $this->mConn
== false ) {
171 wfDebug( "DB connection error\n" );
172 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
173 wfDebug( $this->lastError()."\n" );
177 $this->mOpened
= true;
179 global $wgCommandLineMode;
180 ## If called from the command-line (e.g. importDump), only show errors
181 if ($wgCommandLineMode) {
182 $this->doQuery("SET client_min_messages = 'ERROR'");
185 global $wgDBmwschema, $wgDBts2schema;
186 if (isset( $wgDBmwschema ) && isset( $wgDBts2schema )
187 && $wgDBmwschema !== 'mediawiki'
188 && preg_match( '/^\w+$/', $wgDBmwschema )
189 && preg_match( '/^\w+$/', $wgDBts2schema )
191 $safeschema = $this->quote_ident($wgDBmwschema);
192 $safeschema2 = $this->quote_ident($wgDBts2schema);
193 $this->doQuery("SET search_path = $safeschema, $wgDBts2schema, public");
200 function initial_setup($password, $dbName) {
201 // If this is the initial connection, setup the schema stuff and possibly create the user
202 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBsuperuser, $wgDBmwschema, $wgDBts2schema;
204 print "<li>Checking the version of Postgres...";
205 $version = $this->getServerVersion();
207 if ($this->numeric_version
< $PGMINVER) {
208 print "<b>FAILED</b>. Required version is $PGMINVER. You have $this->numeric_version ($version)</li>\n";
211 print "version $this->numeric_version is OK.</li>\n";
213 $safeuser = $this->quote_ident($wgDBuser);
214 // Are we connecting as a superuser for the first time?
215 if ($wgDBsuperuser) {
216 // Are we really a superuser? Check out our rights
218 CASE WHEN usesuper IS TRUE THEN
219 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
220 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
222 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
223 $rows = $this->numRows($res = $this->doQuery($SQL));
225 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
228 $perms = pg_fetch_result($res, 0, 0);
230 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
231 $rows = $this->numRows($this->doQuery($SQL));
233 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
236 if ($perms != 1 and $perms != 3) {
237 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
238 print 'Please use a different Postgres user.</li>';
241 print "<li>Creating user <b>$wgDBuser</b>...";
242 $safepass = $this->addQuotes($wgDBpassword);
243 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
244 $this->doQuery($SQL);
247 // User now exists, check out the database
248 if ($dbName != $wgDBname) {
249 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
250 $rows = $this->numRows($this->doQuery($SQL));
252 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
256 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
257 print 'Please use a different Postgres user.</li>';
260 print "<li>Creating database <b>$wgDBname</b>...";
261 $safename = $this->quote_ident($wgDBname);
262 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
263 $this->doQuery($SQL);
265 // Hopefully tsearch2 and plpgsql are in template1...
268 // Reconnect to check out tsearch2 rights for this user
269 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
272 if ($this->mServer
!=false && $this->mServer
!="") {
273 $hstring="host=$this->mServer ";
275 if ($this->mPort
!=false && $this->mPort
!="") {
276 $hstring .= "port=$this->mPort ";
279 @$this->mConn
= pg_connect("$hstring dbname=$wgDBname user=$wgDBsuperuser password=$password");
280 if ( $this->mConn
== false ) {
281 print "<b>FAILED TO CONNECT!</b></li>";
287 if ($this->numeric_version
< 8.3) {
289 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
290 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
291 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
292 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
293 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
297 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
298 foreach (array('cfg','cfgmap','dict','parser') as $table) {
299 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
300 $this->doQuery($SQL);
305 // Setup the schema for this user if needed
306 $result = $this->schemaExists($wgDBmwschema);
307 $safeschema = $this->quote_ident($wgDBmwschema);
309 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
310 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
312 print "<b>FAILED</b>.</li>\n";
318 print "<li>Schema already exists, explicitly granting rights...\n";
319 $safeschema2 = $this->addQuotes($wgDBmwschema);
320 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
321 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
322 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
323 "AND p.relkind IN ('r','S','v')\n";
325 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
326 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
327 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
328 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
329 $res = $this->doQuery($SQL);
331 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
334 $this->doQuery("SET search_path = $safeschema");
335 $rows = $this->numRows($res);
338 $this->doQuery(pg_fetch_result($res, $rows, 0));
343 // Install plpgsql if needed
344 $this->setup_plpgsql();
347 return true; // Reconnect as regular user
351 if (!defined('POSTGRES_SEARCHPATH')) {
353 if ($this->numeric_version
< 8.3) {
354 // Do we have the basic tsearch2 table?
355 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
356 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
357 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
358 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
359 print " for instructions.</li>\n";
364 // Does this user have the rights to the tsearch2 tables?
365 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
366 print "<li>Checking tsearch2 permissions...";
367 // Let's check all four, just to be safe
368 error_reporting( 0 );
369 $ts2tables = array('cfg','cfgmap','dict','parser');
370 $safetsschema = $this->quote_ident($wgDBts2schema);
371 foreach ( $ts2tables AS $tname ) {
372 $SQL = "SELECT count(*) FROM $safetsschema.pg_ts_$tname";
373 $res = $this->doQuery($SQL);
375 print "<b>FAILED</b> to access pg_ts_$tname. Make sure that the user ".
376 "\"$wgDBuser\" has SELECT access to all four tsearch2 tables</li>\n";
380 $SQL = "SELECT ts_name FROM $safetsschema.pg_ts_cfg WHERE locale = '$ctype'";
381 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
382 $res = $this->doQuery($SQL);
383 error_reporting( E_ALL
);
385 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
390 // Will the current locale work? Can we force it to?
391 print "<li>Verifying tsearch2 locale with $ctype...";
392 $rows = $this->numRows($res);
395 print "<b>not found</b></li>\n";
396 print "<li>Attempting to set default tsearch2 locale to \"$ctype\"...";
400 $tsname = pg_fetch_result($res, 0, 0);
401 if ($tsname != 'default') {
402 print "<b>not set to default ($tsname)</b>";
403 print "<li>Attempting to change tsearch2 default locale to \"$ctype\"...";
408 $SQL = "UPDATE $safetsschema.pg_ts_cfg SET locale = '$ctype' WHERE ts_name = 'default'";
409 $res = $this->doQuery($SQL);
411 print "<b>FAILED</b>. ";
412 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"$ctype\"</li>\n";
418 // Final test: try out a simple tsearch2 query
419 $SQL = "SELECT $safetsschema.to_tsvector('default','MediaWiki tsearch2 testing')";
420 $res = $this->doQuery($SQL);
422 print "<b>FAILED</b>. Specifically, \"$SQL\" did not work.</li>";
428 // Install plpgsql if needed
429 $this->setup_plpgsql();
431 // Does the schema already exist? Who owns it?
432 $result = $this->schemaExists($wgDBmwschema);
434 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
435 error_reporting( 0 );
436 $safeschema = $this->quote_ident($wgDBmwschema);
437 $result = $this->doQuery("CREATE SCHEMA $safeschema");
438 error_reporting( E_ALL
);
440 print "<b>FAILED</b>. The user \"$wgDBuser\" must be able to access the schema. ".
441 "You can try making them the owner of the database, or try creating the schema with a ".
442 "different user, and then grant access to the \"$wgDBuser\" user.</li>\n";
447 else if ($result != $wgDBuser) {
448 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$wgDBuser\". Not ideal.</li>\n";
451 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$wgDBuser\". Excellent.</li>\n";
454 // Always return GMT time to accomodate the existing integer-based timestamp assumption
455 print "<li>Setting the timezone to GMT for user \"$wgDBuser\" ...";
456 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
457 $result = pg_query($this->mConn
, $SQL);
459 print "<b>FAILED</b>.</li>\n";
463 // Set for the rest of this session
464 $SQL = "SET timezone = 'GMT'";
465 $result = pg_query($this->mConn
, $SQL);
467 print "<li>Failed to set timezone</li>\n";
471 print "<li>Setting the datestyle to ISO, YMD for user \"$wgDBuser\" ...";
472 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
473 $result = pg_query($this->mConn
, $SQL);
475 print "<b>FAILED</b>.</li>\n";
479 // Set for the rest of this session
480 $SQL = "SET datestyle = 'ISO, YMD'";
481 $result = pg_query($this->mConn
, $SQL);
483 print "<li>Failed to set datestyle</li>\n";
487 // Fix up the search paths if needed
488 print "<li>Setting the search path for user \"$wgDBuser\" ...";
489 $path = $this->quote_ident($wgDBmwschema);
490 if ($wgDBts2schema !== $wgDBmwschema)
491 $path .= ", ". $this->quote_ident($wgDBts2schema);
492 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
494 $SQL = "ALTER USER $safeuser SET search_path = $path";
495 $result = pg_query($this->mConn
, $SQL);
497 print "<b>FAILED</b>.</li>\n";
501 // Set for the rest of this session
502 $SQL = "SET search_path = $path";
503 $result = pg_query($this->mConn
, $SQL);
505 print "<li>Failed to set search_path</li>\n";
508 define( "POSTGRES_SEARCHPATH", $path );
513 function setup_plpgsql() {
514 print "<li>Checking for Pl/Pgsql ...";
515 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
516 $rows = $this->numRows($this->doQuery($SQL));
518 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
519 print "not installed. Attempting to install Pl/Pgsql ...";
520 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
521 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
522 $rows = $this->numRows($this->doQuery($SQL));
524 $olde = error_reporting(0);
525 error_reporting($olde - E_WARNING
);
526 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
527 error_reporting($olde);
529 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
534 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
543 * Closes a database connection, if it is open
544 * Returns success, true if already closed
547 $this->mOpened
= false;
548 if ( $this->mConn
) {
549 return pg_close( $this->mConn
);
555 function doQuery( $sql ) {
556 if (function_exists('mb_convert_encoding')) {
557 return $this->mLastResult
=pg_query( $this->mConn
, mb_convert_encoding($sql,'UTF-8') );
559 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
562 function queryIgnore( $sql, $fname = '' ) {
563 return $this->query( $sql, $fname, true );
566 function freeResult( $res ) {
567 if ( $res instanceof ResultWrapper
) {
570 if ( !@pg_free_result
( $res ) ) {
571 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
575 function fetchObject( $res ) {
576 if ( $res instanceof ResultWrapper
) {
579 @$row = pg_fetch_object( $res );
580 # FIXME: HACK HACK HACK HACK debug
583 # hashar : not sure if the following test really trigger if the object
585 if( pg_last_error($this->mConn
) ) {
586 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
591 function fetchRow( $res ) {
592 if ( $res instanceof ResultWrapper
) {
595 @$row = pg_fetch_array( $res );
596 if( pg_last_error($this->mConn
) ) {
597 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
602 function numRows( $res ) {
603 if ( $res instanceof ResultWrapper
) {
606 @$n = pg_num_rows( $res );
607 if( pg_last_error($this->mConn
) ) {
608 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
612 function numFields( $res ) {
613 if ( $res instanceof ResultWrapper
) {
616 return pg_num_fields( $res );
618 function fieldName( $res, $n ) {
619 if ( $res instanceof ResultWrapper
) {
622 return pg_field_name( $res, $n );
626 * This must be called after nextSequenceVal
628 function insertId() {
629 return $this->mInsertId
;
632 function dataSeek( $res, $row ) {
633 if ( $res instanceof ResultWrapper
) {
636 return pg_result_seek( $res, $row );
639 function lastError() {
640 if ( $this->mConn
) {
641 return pg_last_error();
644 return "No database connection";
647 function lastErrno() {
648 return pg_last_error() ?
1 : 0;
651 function affectedRows() {
652 if( !isset( $this->mLastResult
) or ! $this->mLastResult
)
655 return pg_affected_rows( $this->mLastResult
);
659 * Estimate rows in dataset
660 * Returns estimated count, based on EXPLAIN output
661 * This is not necessarily an accurate estimate, so use sparingly
662 * Returns -1 if count cannot be found
663 * Takes same arguments as Database::select()
666 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
667 $options['EXPLAIN'] = true;
668 $res = $this->select( $table, $vars, $conds, $fname, $options );
671 $row = $this->fetchRow( $res );
673 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
676 $this->freeResult($res);
683 * Returns information about an index
684 * If errors are explicitly ignored, returns NULL on failure
686 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
687 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
688 $res = $this->query( $sql, $fname );
692 while ( $row = $this->fetchObject( $res ) ) {
693 if ( $row->indexname
== $index ) {
700 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
701 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
702 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
703 $res = $this->query( $sql, $fname );
706 while ($row = $this->fetchObject( $res ))
713 * INSERT wrapper, inserts an array into a table
715 * $args may be a single associative array, or an array of these with numeric keys,
716 * for multi-row insert (Postgres version 8.2 and above only).
718 * @param array $table String: Name of the table to insert to.
719 * @param array $args Array: Items to insert into the table.
720 * @param array $fname String: Name of the function, for profiling
721 * @param mixed $options String or Array. Valid options: IGNORE
723 * @return bool Success of insert operation. IGNORE always returns true.
725 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
728 if ( !count( $args ) ) {
732 $table = $this->tableName( $table );
733 if (! isset( $wgDBversion ) ) {
734 $this->getServerVersion();
735 $wgDBversion = $this->numeric_version
;
738 if ( !is_array( $options ) )
739 $options = array( $options );
741 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
743 $keys = array_keys( $args[0] );
747 $keys = array_keys( $args );
750 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
753 if (! $this->mTrxLevel
) {
757 pg_query($this->mConn
, "SAVEPOINT $ignore");
758 $olde = error_reporting( 0 );
760 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
763 if ( $wgDBversion >= 8.2 ) {
765 foreach ( $args as $row ) {
771 $sql .= '(' . $this->makeList( $row ) . ')';
773 $res = (bool)$this->query( $sql, $fname, $ignore );
778 foreach ( $args as $row ) {
780 $tempsql .= '(' . $this->makeList( $row ) . ')';
781 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
788 $sql .= '(' . $this->makeList( $args ) . ')';
789 $res = (bool)$this->query( $sql, $fname, $ignore );
793 $olde = error_reporting( $olde );
794 $bar = pg_last_error();
795 if ($bar !== FALSE) {
796 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
799 pg_query( $this->mConn
, "RELEASE $ignore" );
804 ## IGNORE always returns true
812 function tableName( $name ) {
813 # Replace reserved words with better ones
818 return 'pagecontent';
825 * Return the next in a sequence, save the value for retrieval via insertId()
827 function nextSequenceValue( $seqName ) {
828 $safeseq = preg_replace( "/'/", "''", $seqName );
829 $res = $this->query( "SELECT nextval('$safeseq')" );
830 $row = $this->fetchRow( $res );
831 $this->mInsertId
= $row[0];
832 $this->freeResult( $res );
833 return $this->mInsertId
;
837 * Return the current value of a sequence. Assumes it has ben nextval'ed in this session.
839 function currentSequenceValue( $seqName ) {
840 $safeseq = preg_replace( "/'/", "''", $seqName );
841 $res = $this->query( "SELECT currval('$safeseq')" );
842 $row = $this->fetchRow( $res );
844 $this->freeResult( $res );
849 * Postgres does not have a "USE INDEX" clause, so return an empty string
851 function useIndexClause( $index ) {
855 # REPLACE query wrapper
856 # Postgres simulates this with a DELETE followed by INSERT
857 # $row is the row to insert, an associative array
858 # $uniqueIndexes is an array of indexes. Each element may be either a
859 # field name or an array of field names
861 # It may be more efficient to leave off unique indexes which are unlikely to collide.
862 # However if you do this, you run the risk of encountering errors which wouldn't have
864 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
865 $table = $this->tableName( $table );
867 if (count($rows)==0) {
872 if ( !is_array( reset( $rows ) ) ) {
873 $rows = array( $rows );
876 foreach( $rows as $row ) {
877 # Delete rows which collide
878 if ( $uniqueIndexes ) {
879 $sql = "DELETE FROM $table WHERE ";
881 foreach ( $uniqueIndexes as $index ) {
888 if ( is_array( $index ) ) {
890 foreach ( $index as $col ) {
896 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
899 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
903 $this->query( $sql, $fname );
907 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
908 $this->makeList( $row, LIST_COMMA
) . ')';
909 $this->query( $sql, $fname );
913 # DELETE where the condition is a join
914 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
916 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
919 $delTable = $this->tableName( $delTable );
920 $joinTable = $this->tableName( $joinTable );
921 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
922 if ( $conds != '*' ) {
923 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
927 $this->query( $sql, $fname );
930 # Returns the size of a text field, or -1 for "unlimited"
931 function textFieldSize( $table, $field ) {
932 $table = $this->tableName( $table );
933 $sql = "SELECT t.typname as ftype,a.atttypmod as size
934 FROM pg_class c, pg_attribute a, pg_type t
935 WHERE relname='$table' AND a.attrelid=c.oid AND
936 a.atttypid=t.oid and a.attname='$field'";
937 $res =$this->query($sql);
938 $row=$this->fetchObject($res);
939 if ($row->ftype
=="varchar") {
944 $this->freeResult( $res );
948 function lowPriorityOption() {
952 function limitResult($sql, $limit, $offset=false) {
953 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
957 * Returns an SQL expression for a simple conditional.
958 * Uses CASE on Postgres
960 * @param string $cond SQL expression which will result in a boolean value
961 * @param string $trueVal SQL expression to return if true
962 * @param string $falseVal SQL expression to return if false
963 * @return string SQL fragment
965 function conditional( $cond, $trueVal, $falseVal ) {
966 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
969 function wasDeadlock() {
970 return $this->lastErrno() == '40P01';
973 function timestamp( $ts=0 ) {
974 return wfTimestamp(TS_POSTGRES
,$ts);
978 * Return aggregated value function call
980 function aggregateValue ($valuedata,$valuename='value') {
985 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
986 // Ignore errors during error handling to avoid infinite recursion
987 $ignore = $this->ignoreErrors( true );
988 $this->mErrorCount++
;
990 if ($ignore ||
$tempIgnore) {
991 wfDebug("SQL ERROR (ignored): $error\n");
992 $this->ignoreErrors( $ignore );
995 $message = "A database error has occurred\n" .
997 "Function: $fname\n" .
998 "Error: $errno $error\n";
999 throw new DBUnexpectedError($this, $message);
1004 * @return string wikitext of a link to the server software's web site
1006 function getSoftwareLink() {
1007 return "[http://www.postgresql.org/ PostgreSQL]";
1011 * @return string Version information from the database
1013 function getServerVersion() {
1014 $version = pg_fetch_result($this->doQuery("SELECT version()"),0,0);
1016 if (!preg_match('/PostgreSQL (\d+\.\d+)(\S+)/', $version, $thisver)) {
1017 die("Could not determine the numeric version from $version!");
1019 $this->numeric_version
= $thisver[1];
1025 * Query whether a given relation exists (in the given schema, or the
1026 * default mw one if not given)
1028 function relationExists( $table, $types, $schema = false ) {
1029 global $wgDBmwschema;
1030 if (!is_array($types))
1031 $types = array($types);
1033 $schema = $wgDBmwschema;
1034 $etable = $this->addQuotes($table);
1035 $eschema = $this->addQuotes($schema);
1036 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1037 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1038 . "AND c.relkind IN ('" . implode("','", $types) . "')";
1039 $res = $this->query( $SQL );
1040 $count = $res ?
$res->numRows() : 0;
1042 $this->freeResult( $res );
1043 return $count ?
true : false;
1047 * For backward compatibility, this function checks both tables and
1050 function tableExists ($table, $schema = false) {
1051 return $this->relationExists($table, array('r', 'v'), $schema);
1054 function sequenceExists ($sequence, $schema = false) {
1055 return $this->relationExists($sequence, 'S', $schema);
1058 function triggerExists($table, $trigger) {
1059 global $wgDBmwschema;
1062 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1063 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1064 AND tgrelid=pg_class.oid
1065 AND nspname=%s AND relname=%s AND tgname=%s
1067 $res = $this->query(sprintf($q,
1068 $this->addQuotes($wgDBmwschema),
1069 $this->addQuotes($table),
1070 $this->addQuotes($trigger)));
1073 $rows = $res->numRows();
1074 $this->freeResult($res);
1078 function ruleExists($table, $rule) {
1079 global $wgDBmwschema;
1080 $exists = $this->selectField("pg_rules", "rulename",
1081 array( "rulename" => $rule,
1082 "tablename" => $table,
1083 "schemaname" => $wgDBmwschema));
1084 return $exists === $rule;
1087 function constraintExists($table, $constraint) {
1088 global $wgDBmwschema;
1089 $SQL = sprintf("SELECT 1 FROM information_schema.table_constraints ".
1090 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1091 $this->addQuotes($wgDBmwschema),
1092 $this->addQuotes($table),
1093 $this->addQuotes($constraint));
1094 $res = $this->query($SQL);
1097 $rows = $res->numRows();
1098 $this->freeResult($res);
1103 * Query whether a given schema exists. Returns the name of the owner
1105 function schemaExists( $schema ) {
1106 $eschema = preg_replace("/'/", "''", $schema);
1107 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1108 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1109 $res = $this->query( $SQL );
1110 if ( $res && $res->numRows() ) {
1111 $row = $res->fetchObject();
1112 $owner = $row->rolname
;
1117 $this->freeResult($res);
1122 * Query whether a given column exists in the mediawiki schema
1124 function fieldExists( $table, $field, $fname = 'DatabasePostgres::fieldExists' ) {
1125 global $wgDBmwschema;
1126 $etable = preg_replace("/'/", "''", $table);
1127 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
1128 $ecol = preg_replace("/'/", "''", $field);
1129 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
1130 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
1131 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
1132 $res = $this->query( $SQL, $fname );
1133 $count = $res ?
$res->numRows() : 0;
1135 $this->freeResult( $res );
1139 function fieldInfo( $table, $field ) {
1140 return PostgresField
::fromText($this, $table, $field);
1143 function begin( $fname = 'DatabasePostgres::begin' ) {
1144 $this->query( 'BEGIN', $fname );
1145 $this->mTrxLevel
= 1;
1147 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
1150 function commit( $fname = 'DatabasePostgres::commit' ) {
1151 $this->query( 'COMMIT', $fname );
1152 $this->mTrxLevel
= 0;
1155 /* Not even sure why this is used in the main codebase... */
1156 function limitResultForUpdate($sql, $num) {
1160 function setup_database() {
1161 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
1163 // Make sure that we can write to the correct schema
1164 // If not, Postgres will happily and silently go to the next search_path item
1165 $ctest = "mediawiki_test_table";
1166 $safeschema = $this->quote_ident($wgDBmwschema);
1167 if ($this->tableExists($ctest, $wgDBmwschema)) {
1168 $this->doQuery("DROP TABLE $safeschema.$ctest");
1170 $SQL = "CREATE TABLE $safeschema.$ctest(a int)";
1171 $olde = error_reporting( 0 );
1172 $res = $this->doQuery($SQL);
1173 error_reporting( $olde );
1175 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" can write to the schema \"$wgDBmwschema\"</li>\n";
1178 $this->doQuery("DROP TABLE $safeschema.$ctest");
1180 $res = dbsource( "../maintenance/postgres/tables.sql", $this);
1182 ## Update version information
1183 $mwv = $this->addQuotes($wgVersion);
1184 $pgv = $this->addQuotes($this->getServerVersion());
1185 $pgu = $this->addQuotes($this->mUser
);
1186 $mws = $this->addQuotes($wgDBmwschema);
1187 $tss = $this->addQuotes($wgDBts2schema);
1188 $pgp = $this->addQuotes($wgDBport);
1189 $dbn = $this->addQuotes($this->mDBname
);
1190 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
1192 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
1193 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
1194 "ctype = '$ctype' ".
1195 "WHERE type = 'Creation'";
1198 ## Avoid the non-standard "REPLACE INTO" syntax
1199 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1201 dieout( "<li>Could not find the interwiki.sql file");
1203 ## We simply assume it is already empty as we have just created it
1204 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1205 while ( ! feof( $f ) ) {
1206 $line = fgets($f,1024);
1208 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
1211 $this->query("$SQL $matches[1],$matches[2])");
1213 print " (table interwiki successfully populated)...\n";
1215 $this->doQuery("COMMIT");
1218 function encodeBlob( $b ) {
1219 return new Blob ( pg_escape_bytea( $b ) ) ;
1222 function decodeBlob( $b ) {
1223 if ($b instanceof Blob
) {
1226 return pg_unescape_bytea( $b );
1229 function strencode( $s ) { ## Should not be called by us
1230 return pg_escape_string( $s );
1233 function addQuotes( $s ) {
1234 if ( is_null( $s ) ) {
1236 } else if ($s instanceof Blob
) {
1237 return "'".$s->fetch($s)."'";
1239 return "'" . pg_escape_string($s) . "'";
1242 function quote_ident( $s ) {
1243 return '"' . preg_replace( '/"/', '""', $s) . '"';
1246 /* For now, does nothing */
1247 function selectDB( $db ) {
1252 * Postgres specific version of replaceVars.
1253 * Calls the parent version in Database.php
1257 * @param string $com SQL string, read from a stream (usually tables.sql)
1259 * @return string SQL string
1261 protected function replaceVars( $ins ) {
1263 $ins = parent
::replaceVars( $ins );
1265 if ($this->numeric_version
>= 8.3) {
1266 // Thanks for not providing backwards-compatibility, 8.3
1267 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1270 if ($this->numeric_version
<= 8.1) { // Our minimum version
1271 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1278 * Various select options
1282 * @param array $options an associative array of options to be turned into
1283 * an SQL query, valid keys are listed in the function.
1286 function makeSelectOptions( $options ) {
1287 $preLimitTail = $postLimitTail = '';
1288 $startOpts = $useIndex = '';
1290 $noKeyOptions = array();
1291 foreach ( $options as $key => $option ) {
1292 if ( is_numeric( $key ) ) {
1293 $noKeyOptions[$option] = true;
1297 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY " . $options['GROUP BY'];
1298 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1299 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY " . $options['ORDER BY'];
1301 //if (isset($options['LIMIT'])) {
1302 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1303 // isset($options['OFFSET']) ? $options['OFFSET']
1307 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1308 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1309 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1311 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1314 public function setTimeout( $timeout ) {
1315 // @todo fixme no-op
1319 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
1324 * How lagged is this slave?
1327 public function getLag() {
1328 # Not implemented for PostgreSQL
1332 function setFakeSlaveLag() {}
1333 function setFakeMaster() {}
1335 function getDBname() {
1336 return $this->mDBname
;
1339 function getServer() {
1340 return $this->mServer
;
1343 function buildConcat( $stringList ) {
1344 return implode( ' || ', $stringList );
1347 /* These are not used yet, but we know we don't want the default version */
1349 public function lock( $lockName, $method ) {
1352 public function unlock( $lockName, $method ) {
1356 } // end DatabasePostgres class