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 ) ?
1 : 0;
752 $olde = error_reporting( 0 );
754 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
757 if ( $wgDBversion >= 8.2 ) {
759 foreach ( $args as $row ) {
765 $sql .= '(' . $this->makeList( $row ) . ')';
767 $res = (bool)$this->query( $sql, $fname, $ignore );
772 foreach ( $args as $row ) {
774 $tempsql .= '(' . $this->makeList( $row ) . ')';
775 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
782 $sql .= '(' . $this->makeList( $args ) . ')';
783 $res = (bool)$this->query( $sql, $fname, $ignore );
787 $olde = error_reporting( $olde );
795 function tableName( $name ) {
796 # Replace reserved words with better ones
801 return 'pagecontent';
808 * Return the next in a sequence, save the value for retrieval via insertId()
810 function nextSequenceValue( $seqName ) {
811 $safeseq = preg_replace( "/'/", "''", $seqName );
812 $res = $this->query( "SELECT nextval('$safeseq')" );
813 $row = $this->fetchRow( $res );
814 $this->mInsertId
= $row[0];
815 $this->freeResult( $res );
816 return $this->mInsertId
;
820 * Return the current value of a sequence. Assumes it has ben nextval'ed in this session.
822 function currentSequenceValue( $seqName ) {
823 $safeseq = preg_replace( "/'/", "''", $seqName );
824 $res = $this->query( "SELECT currval('$safeseq')" );
825 $row = $this->fetchRow( $res );
827 $this->freeResult( $res );
832 * Postgres does not have a "USE INDEX" clause, so return an empty string
834 function useIndexClause( $index ) {
838 # REPLACE query wrapper
839 # Postgres simulates this with a DELETE followed by INSERT
840 # $row is the row to insert, an associative array
841 # $uniqueIndexes is an array of indexes. Each element may be either a
842 # field name or an array of field names
844 # It may be more efficient to leave off unique indexes which are unlikely to collide.
845 # However if you do this, you run the risk of encountering errors which wouldn't have
847 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
848 $table = $this->tableName( $table );
850 if (count($rows)==0) {
855 if ( !is_array( reset( $rows ) ) ) {
856 $rows = array( $rows );
859 foreach( $rows as $row ) {
860 # Delete rows which collide
861 if ( $uniqueIndexes ) {
862 $sql = "DELETE FROM $table WHERE ";
864 foreach ( $uniqueIndexes as $index ) {
871 if ( is_array( $index ) ) {
873 foreach ( $index as $col ) {
879 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
882 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
886 $this->query( $sql, $fname );
890 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
891 $this->makeList( $row, LIST_COMMA
) . ')';
892 $this->query( $sql, $fname );
896 # DELETE where the condition is a join
897 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
899 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
902 $delTable = $this->tableName( $delTable );
903 $joinTable = $this->tableName( $joinTable );
904 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
905 if ( $conds != '*' ) {
906 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
910 $this->query( $sql, $fname );
913 # Returns the size of a text field, or -1 for "unlimited"
914 function textFieldSize( $table, $field ) {
915 $table = $this->tableName( $table );
916 $sql = "SELECT t.typname as ftype,a.atttypmod as size
917 FROM pg_class c, pg_attribute a, pg_type t
918 WHERE relname='$table' AND a.attrelid=c.oid AND
919 a.atttypid=t.oid and a.attname='$field'";
920 $res =$this->query($sql);
921 $row=$this->fetchObject($res);
922 if ($row->ftype
=="varchar") {
927 $this->freeResult( $res );
931 function lowPriorityOption() {
935 function limitResult($sql, $limit, $offset=false) {
936 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
940 * Returns an SQL expression for a simple conditional.
941 * Uses CASE on Postgres
943 * @param string $cond SQL expression which will result in a boolean value
944 * @param string $trueVal SQL expression to return if true
945 * @param string $falseVal SQL expression to return if false
946 * @return string SQL fragment
948 function conditional( $cond, $trueVal, $falseVal ) {
949 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
952 function wasDeadlock() {
953 return $this->lastErrno() == '40P01';
956 function timestamp( $ts=0 ) {
957 return wfTimestamp(TS_POSTGRES
,$ts);
961 * Return aggregated value function call
963 function aggregateValue ($valuedata,$valuename='value') {
968 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
969 // Ignore errors during error handling to avoid infinite recursion
970 $ignore = $this->ignoreErrors( true );
971 $this->mErrorCount++
;
973 if ($ignore ||
$tempIgnore) {
974 wfDebug("SQL ERROR (ignored): $error\n");
975 $this->ignoreErrors( $ignore );
978 $message = "A database error has occurred\n" .
980 "Function: $fname\n" .
981 "Error: $errno $error\n";
982 throw new DBUnexpectedError($this, $message);
987 * @return string wikitext of a link to the server software's web site
989 function getSoftwareLink() {
990 return "[http://www.postgresql.org/ PostgreSQL]";
994 * @return string Version information from the database
996 function getServerVersion() {
997 $version = pg_fetch_result($this->doQuery("SELECT version()"),0,0);
999 if (!preg_match('/PostgreSQL (\d+\.\d+)(\S+)/', $version, $thisver)) {
1000 die("Could not determine the numeric version from $version!");
1002 $this->numeric_version
= $thisver[1];
1008 * Query whether a given relation exists (in the given schema, or the
1009 * default mw one if not given)
1011 function relationExists( $table, $types, $schema = false ) {
1012 global $wgDBmwschema;
1013 if (!is_array($types))
1014 $types = array($types);
1016 $schema = $wgDBmwschema;
1017 $etable = $this->addQuotes($table);
1018 $eschema = $this->addQuotes($schema);
1019 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1020 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1021 . "AND c.relkind IN ('" . implode("','", $types) . "')";
1022 $res = $this->query( $SQL );
1023 $count = $res ?
$res->numRows() : 0;
1025 $this->freeResult( $res );
1026 return $count ?
true : false;
1030 * For backward compatibility, this function checks both tables and
1033 function tableExists ($table, $schema = false) {
1034 return $this->relationExists($table, array('r', 'v'), $schema);
1037 function sequenceExists ($sequence, $schema = false) {
1038 return $this->relationExists($sequence, 'S', $schema);
1041 function triggerExists($table, $trigger) {
1042 global $wgDBmwschema;
1045 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1046 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1047 AND tgrelid=pg_class.oid
1048 AND nspname=%s AND relname=%s AND tgname=%s
1050 $res = $this->query(sprintf($q,
1051 $this->addQuotes($wgDBmwschema),
1052 $this->addQuotes($table),
1053 $this->addQuotes($trigger)));
1056 $rows = $res->numRows();
1057 $this->freeResult($res);
1061 function ruleExists($table, $rule) {
1062 global $wgDBmwschema;
1063 $exists = $this->selectField("pg_rules", "rulename",
1064 array( "rulename" => $rule,
1065 "tablename" => $table,
1066 "schemaname" => $wgDBmwschema));
1067 return $exists === $rule;
1070 function constraintExists($table, $constraint) {
1071 global $wgDBmwschema;
1072 $SQL = sprintf("SELECT 1 FROM information_schema.table_constraints ".
1073 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1074 $this->addQuotes($wgDBmwschema),
1075 $this->addQuotes($table),
1076 $this->addQuotes($constraint));
1077 $res = $this->query($SQL);
1080 $rows = $res->numRows();
1081 $this->freeResult($res);
1086 * Query whether a given schema exists. Returns the name of the owner
1088 function schemaExists( $schema ) {
1089 $eschema = preg_replace("/'/", "''", $schema);
1090 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1091 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1092 $res = $this->query( $SQL );
1093 if ( $res && $res->numRows() ) {
1094 $row = $res->fetchObject();
1095 $owner = $row->rolname
;
1100 $this->freeResult($res);
1105 * Query whether a given column exists in the mediawiki schema
1107 function fieldExists( $table, $field, $fname = 'DatabasePostgres::fieldExists' ) {
1108 global $wgDBmwschema;
1109 $etable = preg_replace("/'/", "''", $table);
1110 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
1111 $ecol = preg_replace("/'/", "''", $field);
1112 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
1113 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
1114 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
1115 $res = $this->query( $SQL, $fname );
1116 $count = $res ?
$res->numRows() : 0;
1118 $this->freeResult( $res );
1122 function fieldInfo( $table, $field ) {
1123 return PostgresField
::fromText($this, $table, $field);
1126 function begin( $fname = 'DatabasePostgres::begin' ) {
1127 $this->query( 'BEGIN', $fname );
1128 $this->mTrxLevel
= 1;
1130 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
1133 function commit( $fname = 'DatabasePostgres::commit' ) {
1134 $this->query( 'COMMIT', $fname );
1135 $this->mTrxLevel
= 0;
1138 /* Not even sure why this is used in the main codebase... */
1139 function limitResultForUpdate($sql, $num) {
1143 function setup_database() {
1144 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
1146 // Make sure that we can write to the correct schema
1147 // If not, Postgres will happily and silently go to the next search_path item
1148 $ctest = "mediawiki_test_table";
1149 $safeschema = $this->quote_ident($wgDBmwschema);
1150 if ($this->tableExists($ctest, $wgDBmwschema)) {
1151 $this->doQuery("DROP TABLE $safeschema.$ctest");
1153 $SQL = "CREATE TABLE $safeschema.$ctest(a int)";
1154 $olde = error_reporting( 0 );
1155 $res = $this->doQuery($SQL);
1156 error_reporting( $olde );
1158 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" can write to the schema \"$wgDBmwschema\"</li>\n";
1161 $this->doQuery("DROP TABLE $safeschema.$ctest");
1163 $res = dbsource( "../maintenance/postgres/tables.sql", $this);
1165 ## Update version information
1166 $mwv = $this->addQuotes($wgVersion);
1167 $pgv = $this->addQuotes($this->getServerVersion());
1168 $pgu = $this->addQuotes($this->mUser
);
1169 $mws = $this->addQuotes($wgDBmwschema);
1170 $tss = $this->addQuotes($wgDBts2schema);
1171 $pgp = $this->addQuotes($wgDBport);
1172 $dbn = $this->addQuotes($this->mDBname
);
1173 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
1175 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
1176 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
1177 "ctype = '$ctype' ".
1178 "WHERE type = 'Creation'";
1181 ## Avoid the non-standard "REPLACE INTO" syntax
1182 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1184 dieout( "<li>Could not find the interwiki.sql file");
1186 ## We simply assume it is already empty as we have just created it
1187 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1188 while ( ! feof( $f ) ) {
1189 $line = fgets($f,1024);
1191 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
1194 $this->query("$SQL $matches[1],$matches[2])");
1196 print " (table interwiki successfully populated)...\n";
1198 $this->doQuery("COMMIT");
1201 function encodeBlob( $b ) {
1202 return new Blob ( pg_escape_bytea( $b ) ) ;
1205 function decodeBlob( $b ) {
1206 if ($b instanceof Blob
) {
1209 return pg_unescape_bytea( $b );
1212 function strencode( $s ) { ## Should not be called by us
1213 return pg_escape_string( $s );
1216 function addQuotes( $s ) {
1217 if ( is_null( $s ) ) {
1219 } else if ($s instanceof Blob
) {
1220 return "'".$s->fetch($s)."'";
1222 return "'" . pg_escape_string($s) . "'";
1225 function quote_ident( $s ) {
1226 return '"' . preg_replace( '/"/', '""', $s) . '"';
1229 /* For now, does nothing */
1230 function selectDB( $db ) {
1235 * Postgres specific version of replaceVars.
1236 * Calls the parent version in Database.php
1240 * @param string $com SQL string, read from a stream (usually tables.sql)
1242 * @return string SQL string
1244 protected function replaceVars( $ins ) {
1246 $ins = parent
::replaceVars( $ins );
1248 if ($this->numeric_version
>= 8.3) {
1249 // Thanks for not providing backwards-compatibility, 8.3
1250 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1253 if ($this->numeric_version
<= 8.1) { // Our minimum version
1254 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1261 * Various select options
1265 * @param array $options an associative array of options to be turned into
1266 * an SQL query, valid keys are listed in the function.
1269 function makeSelectOptions( $options ) {
1270 $preLimitTail = $postLimitTail = '';
1271 $startOpts = $useIndex = '';
1273 $noKeyOptions = array();
1274 foreach ( $options as $key => $option ) {
1275 if ( is_numeric( $key ) ) {
1276 $noKeyOptions[$option] = true;
1280 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY " . $options['GROUP BY'];
1281 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1282 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY " . $options['ORDER BY'];
1284 //if (isset($options['LIMIT'])) {
1285 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1286 // isset($options['OFFSET']) ? $options['OFFSET']
1290 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1291 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1292 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1294 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1297 public function setTimeout( $timeout ) {
1298 // @todo fixme no-op
1302 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
1307 * How lagged is this slave?
1310 public function getLag() {
1311 # Not implemented for PostgreSQL
1315 function setFakeSlaveLag() {}
1316 function setFakeMaster() {}
1318 function getDBname() {
1319 return $this->mDBname
;
1322 function getServer() {
1323 return $this->mServer
;
1326 function buildConcat( $stringList ) {
1327 return implode( ' || ', $stringList );
1330 } // end DatabasePostgres class