4 * This is PostgreSQL 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
16 require_once( 'Database.php' );
18 class DatabasePostgres
extends Database
{
19 var $mInsertId = NULL;
20 var $mLastResult = NULL;
22 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
23 $failFunction = false, $flags = 0 )
26 global $wgOut, $wgDBprefix, $wgCommandLineMode;
27 # Can't get a reference if it hasn't been set yet
28 if ( !isset( $wgOut ) ) {
31 $this->mOut
=& $wgOut;
32 $this->mFailFunction
= $failFunction;
33 $this->mFlags
= $flags;
35 $this->open( $server, $user, $password, $dbName);
39 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
40 $failFunction = false, $flags = 0)
42 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
46 * Usually aborts on failure
47 * If the failFunction is set to a non-zero integer, returns success
49 function open( $server, $user, $password, $dbName ) {
50 # Test for PostgreSQL support, to avoid suppressed fatal error
51 if ( !function_exists( 'pg_connect' ) ) {
52 throw new DBConnectionError( $this, "PostgreSQL functions missing, have you compiled PHP with the --with-pgsql option?\n" );
59 $this->mServer
= $server;
62 $this->mPassword
= $password;
63 $this->mDBname
= $dbName;
67 if ($server!=false && $server!="") {
68 $hstring="host=$server ";
70 if ($port!=false && $port!="") {
71 $hstring .= "port=$port ";
74 if (!strlen($user)) { ## e.g. the class is being loaded
78 error_reporting( E_ALL
);
79 @$this->mConn
= pg_connect("$hstring dbname=$dbName user=$user password=$password");
81 if ( $this->mConn
== false ) {
82 wfDebug( "DB connection error\n" );
83 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
84 wfDebug( $this->lastError()."\n" );
88 $this->mOpened
= true;
89 ## If this is the initial connection, setup the schema stuff and possibly create the user
90 if (defined('MEDIAWIKI_INSTALL')) {
91 global $wgDBname, $wgDBuser, $wgDBpass, $wgDBsuperuser, $wgDBmwschema, $wgDBts2schema;
94 ## Are we connecting as a superuser for the first time?
96 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
97 $rows = $this->numRows($this->doQuery($SQL));
99 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
102 ## Can we create users?
103 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usesuper IS TRUE AND ".
104 "usename = " . $this->addQuotes($wgDBsuperuser);
105 $rows = $this->numRows($this->doQuery($SQL));
107 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
108 print 'Please use a different Postgres user.</li>';
111 print "<li>Creating user <b>$wgDBuser</b>...";
112 $safepass = $this->addQuotes($wgDBpass);
113 $SQL = "CREATE USER \"$wgDBuser\" NOCREATEDB PASSWORD $safepass";
114 $this->doQuery($SQL);
117 ## User now exists, check out the database
118 $safename = $this->addQuotes($wgDBname);
119 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = $safename";
120 $rows = $this->numRows($this->doQuery($SQL));
122 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
125 print "<li>Creating database <b>$wgDBname</b>...";
126 $SQL = "CREATE DATABASE \"$wgDBname\" OWNER \"$wgDBuser\" ";
127 $this->doQuery($SQL);
129 ## Hopefully tsearch2 and plpgsql are in template1...
132 ## Reconnect to check out tsearch2 rights for this user
133 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
134 @$this->mConn
= pg_connect("$hstring dbname=$wgDBname user=$user password=$password");
135 if ( $this->mConn
== false ) {
136 print "<b>FAILED TO CONNECT!</b></li>";
140 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
141 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
142 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
143 print "Please see 'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
144 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
148 print "Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
149 foreach (array('cfg','cfgmap','dict','parser') as $table) {
150 $SQL = "GRANT SELECT ON pg_ts_$table TO \"$wgDBuser\"";
151 $this->doQuery($SQL);
155 return true; ## Reconnect as regular user
158 if (!defined('POSTGRES_SEARCHPATH')) {
160 ## Do we have the basic tsearch2 table?
161 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
162 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
163 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
164 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
165 print " for instructions.</li>\n";
170 ## Does this user have the rights to the tsearch2 tables?
171 print "<li>Checking tsearch2 permissions...";
172 $SQL = "SELECT 1 FROM $wgDBts2schema.pg_ts_cfg";
173 error_reporting( 0 );
174 $res = $this->doQuery($SQL);
175 error_reporting( E_ALL
);
177 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" has SELECT access to the tsearch2 tables</li>\n";
182 ## Do we have plpgsql installed?
183 print "<li>Checking for plpgsql ...";
184 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
185 $rows = $this->numRows($this->doQuery($SQL));
187 print "<b>FAILED</b>. Make sure the language plpgsql is installed for the database <tt>$wgDBname</tt></li>";
192 ## Does the schema already exist? Who owns it?
193 $result = $this->schemaExists($wgDBmwschema);
195 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
196 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
198 print "<b>FAILED</b>.</li>\n";
203 else if ($result != $user) {
204 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
207 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
210 ## Fix up the search paths if needed
211 print "<li>Setting the search path for user \"$user\" ...";
212 $path = "$wgDBmwschema";
213 if ($wgDBts2schema !== $wgDBmwschema)
214 $path .= ", $wgDBts2schema";
215 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
217 $SQL = "ALTER USER $user SET search_path = $path";
218 $result = pg_query($this->mConn
, $SQL);
220 print "<b>FAILED</b>.</li>\n";
224 ## Set for the rest of this session
225 $SQL = "SET search_path = $path";
226 $result = pg_query($this->mConn
, $SQL);
228 print "<li>Failed to set search_path</li>\n";
231 define( "POSTGRES_SEARCHPATH", $path );
238 * Closes a database connection, if it is open
239 * Returns success, true if already closed
242 $this->mOpened
= false;
243 if ( $this->mConn
) {
244 return pg_close( $this->mConn
);
250 function doQuery( $sql ) {
251 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
254 function queryIgnore( $sql, $fname = '' ) {
255 return $this->query( $sql, $fname, true );
258 function freeResult( $res ) {
259 if ( !@pg_free_result
( $res ) ) {
260 throw new DBUnexpectedError($this, "Unable to free PostgreSQL result\n" );
264 function fetchObject( $res ) {
265 @$row = pg_fetch_object( $res );
266 # FIXME: HACK HACK HACK HACK debug
269 # hashar : not sure if the following test really trigger if the object
271 if( pg_last_error($this->mConn
) ) {
272 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
277 function fetchRow( $res ) {
278 @$row = pg_fetch_array( $res );
279 if( pg_last_error($this->mConn
) ) {
280 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
285 function numRows( $res ) {
286 @$n = pg_num_rows( $res );
287 if( pg_last_error($this->mConn
) ) {
288 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
292 function numFields( $res ) { return pg_num_fields( $res ); }
293 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
296 * This must be called after nextSequenceVal
298 function insertId() {
299 return $this->mInsertId
;
302 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
303 function lastError() {
304 if ( $this->mConn
) {
305 return pg_last_error();
308 return "No database connection";
311 function lastErrno() { return 1; }
313 function affectedRows() {
314 return pg_affected_rows( $this->mLastResult
);
318 * Returns information about an index
319 * If errors are explicitly ignored, returns NULL on failure
321 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
322 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
323 $res = $this->query( $sql, $fname );
328 while ( $row = $this->fetchObject( $res ) ) {
329 if ( $row->indexname
== $index ) {
336 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
337 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
338 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
339 $res = $this->query( $sql, $fname );
342 while ($row = $this->fetchObject( $res ))
348 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
349 # PostgreSQL doesn't support options
350 # We have a go at faking one of them
351 # TODO: DELAYED, LOW_PRIORITY
353 if ( !is_array($options))
354 $options = array($options);
356 if ( in_array( 'IGNORE', $options ) )
357 $oldIgnore = $this->ignoreErrors( true );
359 # IGNORE is performed using single-row inserts, ignoring errors in each
360 # FIXME: need some way to distiguish between key collision and other types of error
361 $oldIgnore = $this->ignoreErrors( true );
362 if ( !is_array( reset( $a ) ) ) {
365 foreach ( $a as $row ) {
366 parent
::insert( $table, $row, $fname, array() );
368 $this->ignoreErrors( $oldIgnore );
371 if ( in_array( 'IGNORE', $options ) )
372 $this->ignoreErrors( $oldIgnore );
377 function tableName( $name ) {
378 # Replace backticks into double quotes
379 $name = strtr($name,'`','"');
381 # Now quote PG reserved keywords
386 return '"' . $name . '"';
394 * Return the next in a sequence, save the value for retrieval via insertId()
396 function nextSequenceValue( $seqName ) {
397 $safeseq = preg_replace( "/'/", "''", $seqName );
398 $res = $this->query( "SELECT nextval('$safeseq')" );
399 $row = $this->fetchRow( $res );
400 $this->mInsertId
= $row[0];
401 $this->freeResult( $res );
402 return $this->mInsertId
;
407 * PostgreSQL doesn't have them and returns ""
409 function useIndexClause( $index ) {
413 # REPLACE query wrapper
414 # PostgreSQL simulates this with a DELETE followed by INSERT
415 # $row is the row to insert, an associative array
416 # $uniqueIndexes is an array of indexes. Each element may be either a
417 # field name or an array of field names
419 # It may be more efficient to leave off unique indexes which are unlikely to collide.
420 # However if you do this, you run the risk of encountering errors which wouldn't have
422 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
423 $table = $this->tableName( $table );
425 if (count($rows)==0) {
430 if ( !is_array( reset( $rows ) ) ) {
431 $rows = array( $rows );
434 foreach( $rows as $row ) {
435 # Delete rows which collide
436 if ( $uniqueIndexes ) {
437 $sql = "DELETE FROM $table WHERE ";
439 foreach ( $uniqueIndexes as $index ) {
446 if ( is_array( $index ) ) {
448 foreach ( $index as $col ) {
454 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
457 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
461 $this->query( $sql, $fname );
465 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
466 $this->makeList( $row, LIST_COMMA
) . ')';
467 $this->query( $sql, $fname );
471 # DELETE where the condition is a join
472 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
474 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
477 $delTable = $this->tableName( $delTable );
478 $joinTable = $this->tableName( $joinTable );
479 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
480 if ( $conds != '*' ) {
481 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
485 $this->query( $sql, $fname );
488 # Returns the size of a text field, or -1 for "unlimited"
489 function textFieldSize( $table, $field ) {
490 $table = $this->tableName( $table );
491 $sql = "SELECT t.typname as ftype,a.atttypmod as size
492 FROM pg_class c, pg_attribute a, pg_type t
493 WHERE relname='$table' AND a.attrelid=c.oid AND
494 a.atttypid=t.oid and a.attname='$field'";
495 $res =$this->query($sql);
496 $row=$this->fetchObject($res);
497 if ($row->ftype
=="varchar") {
502 $this->freeResult( $res );
506 function lowPriorityOption() {
510 function limitResult($sql, $limit,$offset) {
511 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
515 * Returns an SQL expression for a simple conditional.
516 * Uses CASE on PostgreSQL.
518 * @param string $cond SQL expression which will result in a boolean value
519 * @param string $trueVal SQL expression to return if true
520 * @param string $falseVal SQL expression to return if false
521 * @return string SQL fragment
523 function conditional( $cond, $trueVal, $falseVal ) {
524 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
527 # FIXME: actually detecting deadlocks might be nice
528 function wasDeadlock() {
532 # Return DB-style timestamp used for MySQL schema
533 function timestamp( $ts=0 ) {
534 return wfTimestamp(TS_DB
,$ts);
538 * Return aggregated value function call
540 function aggregateValue ($valuedata,$valuename='value') {
545 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
546 $message = "A database error has occurred\n" .
548 "Function: $fname\n" .
549 "Error: $errno $error\n";
550 throw new DBUnexpectedError($this, $message);
554 * @return string wikitext of a link to the server software's web site
556 function getSoftwareLink() {
557 return "[http://www.postgresql.org/ PostgreSQL]";
561 * @return string Version information from the database
563 function getServerVersion() {
564 $res = $this->query( "SELECT version()" );
565 $row = $this->fetchRow( $res );
567 $this->freeResult( $res );
573 * Query whether a given table exists (in the given schema, or the default mw one if not given)
575 function tableExists( $table, $schema = false ) {
576 global $wgDBmwschema;
578 $schema = $wgDBmwschema;
579 $etable = preg_replace("/'/", "''", $table);
580 $eschema = preg_replace("/'/", "''", $schema);
581 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
582 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema'";
583 $res = $this->query( $SQL );
584 $count = $res ?
pg_num_rows($res) : 0;
586 $this->freeResult( $res );
592 * Query whether a given schema exists. Returns the name of the owner
594 function schemaExists( $schema ) {
595 $eschema = preg_replace("/'/", "''", $schema);
596 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
597 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
598 $res = $this->query( $SQL );
599 $owner = $res ?
pg_num_rows($res) ?
pg_fetch_result($res, 0, 0) : false : false;
601 $this->freeResult($res);
606 * Query whether a given column exists in the mediawiki schema
608 function fieldExists( $table, $field ) {
609 global $wgDBmwschema;
610 $etable = preg_replace("/'/", "''", $table);
611 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
612 $ecol = preg_replace("/'/", "''", $field);
613 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
614 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
615 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
616 $res = $this->query( $SQL );
617 $count = $res ?
pg_num_rows($res) : 0;
619 $this->freeResult( $res );
623 function fieldInfo( $table, $field ) {
624 $res = $this->query( "SELECT $field FROM $table LIMIT 1" );
625 $type = pg_field_type( $res, 0 );
629 function begin( $fname = 'DatabasePostgrs::begin' ) {
630 $this->query( 'BEGIN', $fname );
631 $this->mTrxLevel
= 1;
633 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
636 function commit( $fname = 'DatabasePostgres::commit' ) {
637 $this->query( 'COMMIT', $fname );
638 $this->mTrxLevel
= 0;
641 /* Not even sure why this is used in the main codebase... */
642 function limitResultForUpdate($sql, $num) {
646 function setup_database() {
647 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport;
649 dbsource( "../maintenance/postgres/tables.sql", $this);
651 ## Update version information
652 $mwv = $this->addQuotes($wgVersion);
653 $pgv = $this->addQuotes($this->getServerVersion());
654 $pgu = $this->addQuotes($this->mUser
);
655 $mws = $this->addQuotes($wgDBmwschema);
656 $tss = $this->addQuotes($wgDBts2schema);
657 $pgp = $this->addQuotes($wgDBport);
658 $dbn = $this->addQuotes($this->mDBname
);
660 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
661 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn ".
662 "WHERE type = 'Creation'";
665 ## Avoid the non-standard "REPLACE INTO" syntax
666 $f = fopen( "../maintenance/interwiki.sql", 'r' );
668 dieout( "<li>Could not find the interwiki.sql file");
670 ## We simply assume it is already empty as we have just created it
671 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
672 while ( ! feof( $f ) ) {
673 $line = fgets($f,1024);
674 if (!preg_match("/^\s*(\(.+?),(\d)\)/", $line, $matches)) {
677 $yesno = $matches[2]; ## ? "'true'" : "'false'";
678 $this->query("$SQL $matches[1],$matches[2])");
680 print " (table interwiki successfully populated)...\n";
683 function encodeBlob($b) {
684 return array('bytea',pg_escape_bytea($b));
686 function decodeBlob($b) {
687 return pg_unescape_bytea( $b );
690 function strencode( $s ) { ## Should not be called by us
691 return pg_escape_string( $s );
694 function addQuotes( $s ) {
695 if ( is_null( $s ) ) {
697 } else if (is_array( $s )) { ## Assume it is bytea data
700 return "'" . pg_escape_string($s) . "'";
701 return "E'" . pg_escape_string($s) . "'";