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->mCascadingDeletes
= true;
34 $this->mCleanupTriggers
= true;
35 $this->mFlags
= $flags;
36 $this->open( $server, $user, $password, $dbName);
40 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
41 $failFunction = false, $flags = 0)
43 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
47 * Usually aborts on failure
48 * If the failFunction is set to a non-zero integer, returns success
50 function open( $server, $user, $password, $dbName ) {
51 # Test for PostgreSQL support, to avoid suppressed fatal error
52 if ( !function_exists( 'pg_connect' ) ) {
53 throw new DBConnectionError( $this, "PostgreSQL functions missing, have you compiled PHP with the --with-pgsql option?\n" );
60 $this->mServer
= $server;
63 $this->mPassword
= $password;
64 $this->mDBname
= $dbName;
68 if ($server!=false && $server!="") {
69 $hstring="host=$server ";
71 if ($port!=false && $port!="") {
72 $hstring .= "port=$port ";
75 if (!strlen($user)) { ## e.g. the class is being loaded
79 error_reporting( E_ALL
);
80 @$this->mConn
= pg_connect("$hstring dbname=$dbName user=$user password=$password");
82 if ( $this->mConn
== false ) {
83 wfDebug( "DB connection error\n" );
84 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
85 wfDebug( $this->lastError()."\n" );
89 $this->mOpened
= true;
90 ## If this is the initial connection, setup the schema stuff and possibly create the user
91 if (defined('MEDIAWIKI_INSTALL')) {
92 global $wgDBname, $wgDBuser, $wgDBpass, $wgDBsuperuser, $wgDBmwschema, $wgDBts2schema;
95 $safeuser = $this->quote_ident($wgDBuser);
96 ## Are we connecting as a superuser for the first time?
98 ## Are we really a superuser? Check out our rights
100 CASE WHEN usesuper IS TRUE THEN
101 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
102 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
104 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
105 $rows = $this->numRows($res = $this->doQuery($SQL));
107 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
110 $perms = pg_fetch_result($res, 0, 0);
112 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
113 $rows = $this->numRows($this->doQuery($SQL));
115 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
118 if ($perms != 1 and $perms != 3) {
119 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
120 print 'Please use a different Postgres user.</li>';
123 print "<li>Creating user <b>$wgDBuser</b>...";
124 $safepass = $this->addQuotes($wgDBpass);
125 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
126 $this->doQuery($SQL);
129 ## User now exists, check out the database
130 if ($dbName != $wgDBname) {
131 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
132 $rows = $this->numRows($this->doQuery($SQL));
134 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
138 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
139 print 'Please use a different Postgres user.</li>';
142 print "<li>Creating database <b>$wgDBname</b>...";
143 $safename = $this->quote_ident($wgDBname);
144 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
145 $this->doQuery($SQL);
147 ## Hopefully tsearch2 and plpgsql are in template1...
150 ## Reconnect to check out tsearch2 rights for this user
151 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
152 @$this->mConn
= pg_connect("$hstring dbname=$wgDBname user=$user password=$password");
153 if ( $this->mConn
== false ) {
154 print "<b>FAILED TO CONNECT!</b></li>";
161 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
162 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
163 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
164 print "Please see 'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
165 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
169 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
170 foreach (array('cfg','cfgmap','dict','parser') as $table) {
171 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
172 $this->doQuery($SQL);
177 ## Setup the schema for this user if needed
178 $result = $this->schemaExists($wgDBmwschema);
180 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
181 $safeschema = $this->quote_ident($wgDBmwschema);
182 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
184 print "<b>FAILED</b>.</li>\n";
191 return true; ## Reconnect as regular user
194 if (!defined('POSTGRES_SEARCHPATH')) {
196 ## Do we have the basic tsearch2 table?
197 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
198 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
199 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
200 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
201 print " for instructions.</li>\n";
206 ## Does this user have the rights to the tsearch2 tables?
207 print "<li>Checking tsearch2 permissions...";
208 $SQL = "SELECT 1 FROM $wgDBts2schema.pg_ts_cfg";
209 error_reporting( 0 );
210 $res = $this->doQuery($SQL);
211 error_reporting( E_ALL
);
213 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" has SELECT access to the tsearch2 tables</li>\n";
218 ## Do we have plpgsql installed?
219 print "<li>Checking for Pl/Pgsql ...";
220 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
221 $rows = $this->numRows($this->doQuery($SQL));
223 print "<b>FAILED</b>. Make sure the language plpgsql is installed for the database <tt>$wgDBname</tt></li>";
228 ## Does the schema already exist? Who owns it?
229 $result = $this->schemaExists($wgDBmwschema);
231 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
232 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
234 print "<b>FAILED</b>.</li>\n";
239 else if ($result != $user) {
240 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
243 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
246 ## Fix up the search paths if needed
247 print "<li>Setting the search path for user \"$user\" ...";
248 $path = $this->quote_ident($wgDBmwschema);
249 if ($wgDBts2schema !== $wgDBmwschema)
250 $path .= ", ". $this->quote_ident($wgDBts2schema);
251 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
253 $SQL = "ALTER USER $safeuser SET search_path = $path";
254 $result = pg_query($this->mConn
, $SQL);
256 print "<b>FAILED</b>.</li>\n";
260 ## Set for the rest of this session
261 $SQL = "SET search_path = $path";
262 $result = pg_query($this->mConn
, $SQL);
264 print "<li>Failed to set search_path</li>\n";
267 define( "POSTGRES_SEARCHPATH", $path );
274 * Closes a database connection, if it is open
275 * Returns success, true if already closed
278 $this->mOpened
= false;
279 if ( $this->mConn
) {
280 return pg_close( $this->mConn
);
286 function doQuery( $sql ) {
287 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
290 function queryIgnore( $sql, $fname = '' ) {
291 return $this->query( $sql, $fname, true );
294 function freeResult( $res ) {
295 if ( !@pg_free_result
( $res ) ) {
296 throw new DBUnexpectedError($this, "Unable to free PostgreSQL result\n" );
300 function fetchObject( $res ) {
301 @$row = pg_fetch_object( $res );
302 # FIXME: HACK HACK HACK HACK debug
305 # hashar : not sure if the following test really trigger if the object
307 if( pg_last_error($this->mConn
) ) {
308 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
313 function fetchRow( $res ) {
314 @$row = pg_fetch_array( $res );
315 if( pg_last_error($this->mConn
) ) {
316 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
321 function numRows( $res ) {
322 @$n = pg_num_rows( $res );
323 if( pg_last_error($this->mConn
) ) {
324 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
328 function numFields( $res ) { return pg_num_fields( $res ); }
329 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
332 * This must be called after nextSequenceVal
334 function insertId() {
335 return $this->mInsertId
;
338 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
339 function lastError() {
340 if ( $this->mConn
) {
341 return pg_last_error();
344 return "No database connection";
347 function lastErrno() {
348 return pg_last_error() ?
1 : 0;
351 function affectedRows() {
352 return pg_affected_rows( $this->mLastResult
);
356 * Returns information about an index
357 * If errors are explicitly ignored, returns NULL on failure
359 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
360 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
361 $res = $this->query( $sql, $fname );
366 while ( $row = $this->fetchObject( $res ) ) {
367 if ( $row->indexname
== $index ) {
374 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
375 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
376 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
377 $res = $this->query( $sql, $fname );
380 while ($row = $this->fetchObject( $res ))
386 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
387 # PostgreSQL doesn't support options
388 # We have a go at faking one of them
389 # TODO: DELAYED, LOW_PRIORITY
391 if ( !is_array($options))
392 $options = array($options);
394 if ( in_array( 'IGNORE', $options ) )
395 $oldIgnore = $this->ignoreErrors( true );
397 # IGNORE is performed using single-row inserts, ignoring errors in each
398 # FIXME: need some way to distiguish between key collision and other types of error
399 $oldIgnore = $this->ignoreErrors( true );
400 if ( !is_array( reset( $a ) ) ) {
403 foreach ( $a as $row ) {
404 parent
::insert( $table, $row, $fname, array() );
406 $this->ignoreErrors( $oldIgnore );
409 if ( in_array( 'IGNORE', $options ) )
410 $this->ignoreErrors( $oldIgnore );
415 function tableName( $name ) {
416 # Replace reserved words with better ones
421 return 'pagecontent';
428 * Return the next in a sequence, save the value for retrieval via insertId()
430 function nextSequenceValue( $seqName ) {
431 $safeseq = preg_replace( "/'/", "''", $seqName );
432 $res = $this->query( "SELECT nextval('$safeseq')" );
433 $row = $this->fetchRow( $res );
434 $this->mInsertId
= $row[0];
435 $this->freeResult( $res );
436 return $this->mInsertId
;
441 * PostgreSQL doesn't have them and returns ""
443 function useIndexClause( $index ) {
447 # REPLACE query wrapper
448 # PostgreSQL simulates this with a DELETE followed by INSERT
449 # $row is the row to insert, an associative array
450 # $uniqueIndexes is an array of indexes. Each element may be either a
451 # field name or an array of field names
453 # It may be more efficient to leave off unique indexes which are unlikely to collide.
454 # However if you do this, you run the risk of encountering errors which wouldn't have
456 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
457 $table = $this->tableName( $table );
459 if (count($rows)==0) {
464 if ( !is_array( reset( $rows ) ) ) {
465 $rows = array( $rows );
468 foreach( $rows as $row ) {
469 # Delete rows which collide
470 if ( $uniqueIndexes ) {
471 $sql = "DELETE FROM $table WHERE ";
473 foreach ( $uniqueIndexes as $index ) {
480 if ( is_array( $index ) ) {
482 foreach ( $index as $col ) {
488 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
491 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
495 $this->query( $sql, $fname );
499 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
500 $this->makeList( $row, LIST_COMMA
) . ')';
501 $this->query( $sql, $fname );
505 # DELETE where the condition is a join
506 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
508 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
511 $delTable = $this->tableName( $delTable );
512 $joinTable = $this->tableName( $joinTable );
513 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
514 if ( $conds != '*' ) {
515 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
519 $this->query( $sql, $fname );
522 # Returns the size of a text field, or -1 for "unlimited"
523 function textFieldSize( $table, $field ) {
524 $table = $this->tableName( $table );
525 $sql = "SELECT t.typname as ftype,a.atttypmod as size
526 FROM pg_class c, pg_attribute a, pg_type t
527 WHERE relname='$table' AND a.attrelid=c.oid AND
528 a.atttypid=t.oid and a.attname='$field'";
529 $res =$this->query($sql);
530 $row=$this->fetchObject($res);
531 if ($row->ftype
=="varchar") {
536 $this->freeResult( $res );
540 function lowPriorityOption() {
544 function limitResult($sql, $limit,$offset) {
545 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
549 * Returns an SQL expression for a simple conditional.
550 * Uses CASE on PostgreSQL.
552 * @param string $cond SQL expression which will result in a boolean value
553 * @param string $trueVal SQL expression to return if true
554 * @param string $falseVal SQL expression to return if false
555 * @return string SQL fragment
557 function conditional( $cond, $trueVal, $falseVal ) {
558 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
561 # FIXME: actually detecting deadlocks might be nice
562 function wasDeadlock() {
566 function timestamp( $ts=0 ) {
567 return wfTimestamp(TS_POSTGRES
,$ts);
571 * Return aggregated value function call
573 function aggregateValue ($valuedata,$valuename='value') {
578 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
579 $message = "A database error has occurred\n" .
581 "Function: $fname\n" .
582 "Error: $errno $error\n";
583 throw new DBUnexpectedError($this, $message);
587 * @return string wikitext of a link to the server software's web site
589 function getSoftwareLink() {
590 return "[http://www.postgresql.org/ PostgreSQL]";
594 * @return string Version information from the database
596 function getServerVersion() {
597 $res = $this->query( "SELECT version()" );
598 $row = $this->fetchRow( $res );
600 $this->freeResult( $res );
606 * Query whether a given table exists (in the given schema, or the default mw one if not given)
608 function tableExists( $table, $schema = false ) {
609 global $wgDBmwschema;
611 $schema = $wgDBmwschema;
612 $etable = preg_replace("/'/", "''", $table);
613 $eschema = preg_replace("/'/", "''", $schema);
614 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
615 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema'";
616 $res = $this->query( $SQL );
617 $count = $res ?
pg_num_rows($res) : 0;
619 $this->freeResult( $res );
625 * Query whether a given schema exists. Returns the name of the owner
627 function schemaExists( $schema ) {
628 $eschema = preg_replace("/'/", "''", $schema);
629 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
630 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
631 $res = $this->query( $SQL );
632 $owner = $res ?
pg_num_rows($res) ?
pg_fetch_result($res, 0, 0) : false : false;
634 $this->freeResult($res);
639 * Query whether a given column exists in the mediawiki schema
641 function fieldExists( $table, $field ) {
642 global $wgDBmwschema;
643 $etable = preg_replace("/'/", "''", $table);
644 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
645 $ecol = preg_replace("/'/", "''", $field);
646 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
647 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
648 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
649 $res = $this->query( $SQL );
650 $count = $res ?
pg_num_rows($res) : 0;
652 $this->freeResult( $res );
656 function fieldInfo( $table, $field ) {
657 $res = $this->query( "SELECT $field FROM $table LIMIT 1" );
658 $type = pg_field_type( $res, 0 );
662 function begin( $fname = 'DatabasePostgrs::begin' ) {
663 $this->query( 'BEGIN', $fname );
664 $this->mTrxLevel
= 1;
666 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
669 function commit( $fname = 'DatabasePostgres::commit' ) {
670 $this->query( 'COMMIT', $fname );
671 $this->mTrxLevel
= 0;
674 /* Not even sure why this is used in the main codebase... */
675 function limitResultForUpdate($sql, $num) {
679 function setup_database() {
680 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport;
682 dbsource( "../maintenance/postgres/tables.sql", $this);
684 ## Update version information
685 $mwv = $this->addQuotes($wgVersion);
686 $pgv = $this->addQuotes($this->getServerVersion());
687 $pgu = $this->addQuotes($this->mUser
);
688 $mws = $this->addQuotes($wgDBmwschema);
689 $tss = $this->addQuotes($wgDBts2schema);
690 $pgp = $this->addQuotes($wgDBport);
691 $dbn = $this->addQuotes($this->mDBname
);
693 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
694 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn ".
695 "WHERE type = 'Creation'";
698 ## Avoid the non-standard "REPLACE INTO" syntax
699 $f = fopen( "../maintenance/interwiki.sql", 'r' );
701 dieout( "<li>Could not find the interwiki.sql file");
703 ## We simply assume it is already empty as we have just created it
704 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
705 while ( ! feof( $f ) ) {
706 $line = fgets($f,1024);
707 if (!preg_match("/^\s*(\(.+?),(\d)\)/", $line, $matches)) {
710 $yesno = $matches[2]; ## ? "'true'" : "'false'";
711 $this->query("$SQL $matches[1],$matches[2])");
713 print " (table interwiki successfully populated)...\n";
716 function encodeBlob($b) {
717 return array('bytea',pg_escape_bytea($b));
719 function decodeBlob($b) {
720 return pg_unescape_bytea( $b );
723 function strencode( $s ) { ## Should not be called by us
724 return pg_escape_string( $s );
727 function addQuotes( $s ) {
728 if ( is_null( $s ) ) {
730 } else if (is_array( $s )) { ## Assume it is bytea data
733 return "'" . pg_escape_string($s) . "'";
734 return "E'" . pg_escape_string($s) . "'";
737 function quote_ident( $s ) {
738 return '"' . preg_replace( '/"/', '""', $s) . '"';