4 * This is Postgres database abstraction layer.
6 * As it includes more generic version for DB functions,
7 * than MySQL ones, some of them should be moved to parent
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->mStrictIPs
= true;
36 $this->mFlags
= $flags;
37 $this->open( $server, $user, $password, $dbName);
41 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
42 $failFunction = false, $flags = 0)
44 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
48 * Usually aborts on failure
49 * If the failFunction is set to a non-zero integer, returns success
51 function open( $server, $user, $password, $dbName ) {
52 # Test for Postgres support, to avoid suppressed fatal error
53 if ( !function_exists( 'pg_connect' ) ) {
54 throw new DBConnectionError( $this, "Postgres functions missing, have you compiled PHP with the --with-pgsql option?\n" );
61 $this->mServer
= $server;
64 $this->mPassword
= $password;
65 $this->mDBname
= $dbName;
69 if ($server!=false && $server!="") {
70 $hstring="host=$server ";
72 if ($port!=false && $port!="") {
73 $hstring .= "port=$port ";
76 if (!strlen($user)) { ## e.g. the class is being loaded
80 error_reporting( E_ALL
);
81 @$this->mConn
= pg_connect("$hstring dbname=$dbName user=$user password=$password");
83 if ( $this->mConn
== false ) {
84 wfDebug( "DB connection error\n" );
85 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
86 wfDebug( $this->lastError()."\n" );
90 $this->mOpened
= true;
91 ## If this is the initial connection, setup the schema stuff and possibly create the user
92 if (defined('MEDIAWIKI_INSTALL')) {
93 global $wgDBname, $wgDBuser, $wgDBpass, $wgDBsuperuser, $wgDBmwschema, $wgDBts2schema;
96 $safeuser = $this->quote_ident($wgDBuser);
97 ## Are we connecting as a superuser for the first time?
99 ## Are we really a superuser? Check out our rights
101 CASE WHEN usesuper IS TRUE THEN
102 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
103 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
105 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
106 $rows = $this->numRows($res = $this->doQuery($SQL));
108 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
111 $perms = pg_fetch_result($res, 0, 0);
113 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
114 $rows = $this->numRows($this->doQuery($SQL));
116 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
119 if ($perms != 1 and $perms != 3) {
120 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
121 print 'Please use a different Postgres user.</li>';
124 print "<li>Creating user <b>$wgDBuser</b>...";
125 $safepass = $this->addQuotes($wgDBpass);
126 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
127 $this->doQuery($SQL);
130 ## User now exists, check out the database
131 if ($dbName != $wgDBname) {
132 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
133 $rows = $this->numRows($this->doQuery($SQL));
135 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
139 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
140 print 'Please use a different Postgres user.</li>';
143 print "<li>Creating database <b>$wgDBname</b>...";
144 $safename = $this->quote_ident($wgDBname);
145 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
146 $this->doQuery($SQL);
148 ## Hopefully tsearch2 and plpgsql are in template1...
151 ## Reconnect to check out tsearch2 rights for this user
152 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
153 @$this->mConn
= pg_connect("$hstring dbname=$wgDBname user=$user password=$password");
154 if ( $this->mConn
== false ) {
155 print "<b>FAILED TO CONNECT!</b></li>";
162 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
163 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
164 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
165 print "Please see 'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
166 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
170 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
171 foreach (array('cfg','cfgmap','dict','parser') as $table) {
172 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
173 $this->doQuery($SQL);
178 ## Setup the schema for this user if needed
179 $result = $this->schemaExists($wgDBmwschema);
180 $safeschema = $this->quote_ident($wgDBmwschema);
182 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
183 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
185 print "<b>FAILED</b>.</li>\n";
191 print "<li>Schema already exists, explicitly granting rights...\n";
192 $safeschema2 = $this->addQuotes($wgDBmwschema);
193 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
194 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
195 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
196 "AND p.relkind IN ('r','S','v')\n";
198 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
199 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
200 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
201 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
202 $res = $this->doQuery($SQL);
204 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
207 $this->doQuery("SET search_path = $safeschema");
208 $rows = $this->numRows($res);
211 $this->doQuery(pg_fetch_result($res, $rows, 0));
217 return true; ## Reconnect as regular user
220 if (!defined('POSTGRES_SEARCHPATH')) {
222 ## Do we have the basic tsearch2 table?
223 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
224 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
225 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
226 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
227 print " for instructions.</li>\n";
232 ## Does this user have the rights to the tsearch2 tables?
233 print "<li>Checking tsearch2 permissions...";
234 $SQL = "SELECT 1 FROM $wgDBts2schema.pg_ts_cfg";
235 error_reporting( 0 );
236 $res = $this->doQuery($SQL);
237 error_reporting( E_ALL
);
239 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" has SELECT access to the tsearch2 tables</li>\n";
244 ## Do we have plpgsql installed?
245 print "<li>Checking for Pl/Pgsql ...";
246 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
247 $rows = $this->numRows($this->doQuery($SQL));
249 print "<b>FAILED</b>. Make sure the language plpgsql is installed for the database <tt>$wgDBname</tt></li>";
254 ## Does the schema already exist? Who owns it?
255 $result = $this->schemaExists($wgDBmwschema);
257 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
258 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
260 print "<b>FAILED</b>.</li>\n";
265 else if ($result != $user) {
266 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
269 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
272 ## Fix up the search paths if needed
273 print "<li>Setting the search path for user \"$user\" ...";
274 $path = $this->quote_ident($wgDBmwschema);
275 if ($wgDBts2schema !== $wgDBmwschema)
276 $path .= ", ". $this->quote_ident($wgDBts2schema);
277 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
279 $SQL = "ALTER USER $safeuser SET search_path = $path";
280 $result = pg_query($this->mConn
, $SQL);
282 print "<b>FAILED</b>.</li>\n";
286 ## Set for the rest of this session
287 $SQL = "SET search_path = $path";
288 $result = pg_query($this->mConn
, $SQL);
290 print "<li>Failed to set search_path</li>\n";
293 define( "POSTGRES_SEARCHPATH", $path );
300 * Closes a database connection, if it is open
301 * Returns success, true if already closed
304 $this->mOpened
= false;
305 if ( $this->mConn
) {
306 return pg_close( $this->mConn
);
312 function doQuery( $sql ) {
313 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
316 function queryIgnore( $sql, $fname = '' ) {
317 return $this->query( $sql, $fname, true );
320 function freeResult( $res ) {
321 if ( !@pg_free_result
( $res ) ) {
322 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
326 function fetchObject( $res ) {
327 @$row = pg_fetch_object( $res );
328 # FIXME: HACK HACK HACK HACK debug
331 # hashar : not sure if the following test really trigger if the object
333 if( pg_last_error($this->mConn
) ) {
334 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
339 function fetchRow( $res ) {
340 @$row = pg_fetch_array( $res );
341 if( pg_last_error($this->mConn
) ) {
342 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
347 function numRows( $res ) {
348 @$n = pg_num_rows( $res );
349 if( pg_last_error($this->mConn
) ) {
350 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
354 function numFields( $res ) { return pg_num_fields( $res ); }
355 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
358 * This must be called after nextSequenceVal
360 function insertId() {
361 return $this->mInsertId
;
364 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
365 function lastError() {
366 if ( $this->mConn
) {
367 return pg_last_error();
370 return "No database connection";
373 function lastErrno() {
374 return pg_last_error() ?
1 : 0;
377 function affectedRows() {
378 return pg_affected_rows( $this->mLastResult
);
382 * Returns information about an index
383 * If errors are explicitly ignored, returns NULL on failure
385 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
386 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
387 $res = $this->query( $sql, $fname );
392 while ( $row = $this->fetchObject( $res ) ) {
393 if ( $row->indexname
== $index ) {
400 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
401 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
402 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
403 $res = $this->query( $sql, $fname );
406 while ($row = $this->fetchObject( $res ))
412 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
413 # Postgres doesn't support options
414 # We have a go at faking one of them
415 # TODO: DELAYED, LOW_PRIORITY
417 if ( !is_array($options))
418 $options = array($options);
420 if ( in_array( 'IGNORE', $options ) )
421 $oldIgnore = $this->ignoreErrors( true );
423 # IGNORE is performed using single-row inserts, ignoring errors in each
424 # FIXME: need some way to distiguish between key collision and other types of error
425 $oldIgnore = $this->ignoreErrors( true );
426 if ( !is_array( reset( $a ) ) ) {
429 foreach ( $a as $row ) {
430 parent
::insert( $table, $row, $fname, array() );
432 $this->ignoreErrors( $oldIgnore );
435 if ( in_array( 'IGNORE', $options ) )
436 $this->ignoreErrors( $oldIgnore );
441 function tableName( $name ) {
442 # Replace reserved words with better ones
447 return 'pagecontent';
454 * Return the next in a sequence, save the value for retrieval via insertId()
456 function nextSequenceValue( $seqName ) {
457 $safeseq = preg_replace( "/'/", "''", $seqName );
458 $res = $this->query( "SELECT nextval('$safeseq')" );
459 $row = $this->fetchRow( $res );
460 $this->mInsertId
= $row[0];
461 $this->freeResult( $res );
462 return $this->mInsertId
;
466 * Postgres does not have a "USE INDEX" clause, so return an empty string
468 function useIndexClause( $index ) {
472 # REPLACE query wrapper
473 # Postgres simulates this with a DELETE followed by INSERT
474 # $row is the row to insert, an associative array
475 # $uniqueIndexes is an array of indexes. Each element may be either a
476 # field name or an array of field names
478 # It may be more efficient to leave off unique indexes which are unlikely to collide.
479 # However if you do this, you run the risk of encountering errors which wouldn't have
481 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
482 $table = $this->tableName( $table );
484 if (count($rows)==0) {
489 if ( !is_array( reset( $rows ) ) ) {
490 $rows = array( $rows );
493 foreach( $rows as $row ) {
494 # Delete rows which collide
495 if ( $uniqueIndexes ) {
496 $sql = "DELETE FROM $table WHERE ";
498 foreach ( $uniqueIndexes as $index ) {
505 if ( is_array( $index ) ) {
507 foreach ( $index as $col ) {
513 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
516 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
520 $this->query( $sql, $fname );
524 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
525 $this->makeList( $row, LIST_COMMA
) . ')';
526 $this->query( $sql, $fname );
530 # DELETE where the condition is a join
531 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
533 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
536 $delTable = $this->tableName( $delTable );
537 $joinTable = $this->tableName( $joinTable );
538 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
539 if ( $conds != '*' ) {
540 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
544 $this->query( $sql, $fname );
547 # Returns the size of a text field, or -1 for "unlimited"
548 function textFieldSize( $table, $field ) {
549 $table = $this->tableName( $table );
550 $sql = "SELECT t.typname as ftype,a.atttypmod as size
551 FROM pg_class c, pg_attribute a, pg_type t
552 WHERE relname='$table' AND a.attrelid=c.oid AND
553 a.atttypid=t.oid and a.attname='$field'";
554 $res =$this->query($sql);
555 $row=$this->fetchObject($res);
556 if ($row->ftype
=="varchar") {
561 $this->freeResult( $res );
565 function lowPriorityOption() {
569 function limitResult($sql, $limit,$offset) {
570 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
574 * Returns an SQL expression for a simple conditional.
575 * Uses CASE on Postgres
577 * @param string $cond SQL expression which will result in a boolean value
578 * @param string $trueVal SQL expression to return if true
579 * @param string $falseVal SQL expression to return if false
580 * @return string SQL fragment
582 function conditional( $cond, $trueVal, $falseVal ) {
583 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
586 # FIXME: actually detecting deadlocks might be nice
587 function wasDeadlock() {
591 function timestamp( $ts=0 ) {
592 return wfTimestamp(TS_POSTGRES
,$ts);
596 * Return aggregated value function call
598 function aggregateValue ($valuedata,$valuename='value') {
603 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
604 $message = "A database error has occurred\n" .
606 "Function: $fname\n" .
607 "Error: $errno $error\n";
608 throw new DBUnexpectedError($this, $message);
612 * @return string wikitext of a link to the server software's web site
614 function getSoftwareLink() {
615 return "[http://www.postgresql.org/ PostgreSQL]";
619 * @return string Version information from the database
621 function getServerVersion() {
622 $res = $this->query( "SELECT version()" );
623 $row = $this->fetchRow( $res );
625 $this->freeResult( $res );
631 * Query whether a given table exists (in the given schema, or the default mw one if not given)
633 function tableExists( $table, $schema = false ) {
634 global $wgDBmwschema;
636 $schema = $wgDBmwschema;
637 $etable = preg_replace("/'/", "''", $table);
638 $eschema = preg_replace("/'/", "''", $schema);
639 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
640 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema'";
641 $res = $this->query( $SQL );
642 $count = $res ?
pg_num_rows($res) : 0;
644 $this->freeResult( $res );
650 * Query whether a given schema exists. Returns the name of the owner
652 function schemaExists( $schema ) {
653 $eschema = preg_replace("/'/", "''", $schema);
654 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
655 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
656 $res = $this->query( $SQL );
657 $owner = $res ?
pg_num_rows($res) ?
pg_fetch_result($res, 0, 0) : false : false;
659 $this->freeResult($res);
664 * Query whether a given column exists in the mediawiki schema
666 function fieldExists( $table, $field ) {
667 global $wgDBmwschema;
668 $etable = preg_replace("/'/", "''", $table);
669 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
670 $ecol = preg_replace("/'/", "''", $field);
671 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
672 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
673 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
674 $res = $this->query( $SQL );
675 $count = $res ?
pg_num_rows($res) : 0;
677 $this->freeResult( $res );
681 function fieldInfo( $table, $field ) {
682 $res = $this->query( "SELECT $field FROM $table LIMIT 1" );
683 $type = pg_field_type( $res, 0 );
687 function begin( $fname = 'DatabasePostgrs::begin' ) {
688 $this->query( 'BEGIN', $fname );
689 $this->mTrxLevel
= 1;
691 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
694 function commit( $fname = 'DatabasePostgres::commit' ) {
695 $this->query( 'COMMIT', $fname );
696 $this->mTrxLevel
= 0;
699 /* Not even sure why this is used in the main codebase... */
700 function limitResultForUpdate($sql, $num) {
704 function setup_database() {
705 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport;
707 dbsource( "../maintenance/postgres/tables.sql", $this);
709 ## Update version information
710 $mwv = $this->addQuotes($wgVersion);
711 $pgv = $this->addQuotes($this->getServerVersion());
712 $pgu = $this->addQuotes($this->mUser
);
713 $mws = $this->addQuotes($wgDBmwschema);
714 $tss = $this->addQuotes($wgDBts2schema);
715 $pgp = $this->addQuotes($wgDBport);
716 $dbn = $this->addQuotes($this->mDBname
);
718 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
719 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn ".
720 "WHERE type = 'Creation'";
723 ## Avoid the non-standard "REPLACE INTO" syntax
724 $f = fopen( "../maintenance/interwiki.sql", 'r' );
726 dieout( "<li>Could not find the interwiki.sql file");
728 ## We simply assume it is already empty as we have just created it
729 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
730 while ( ! feof( $f ) ) {
731 $line = fgets($f,1024);
732 if (!preg_match("/^\s*(\(.+?),(\d)\)/", $line, $matches)) {
735 $yesno = $matches[2]; ## ? "'true'" : "'false'";
736 $this->query("$SQL $matches[1],$matches[2])");
738 print " (table interwiki successfully populated)...\n";
741 function encodeBlob($b) {
742 return array('bytea',pg_escape_bytea($b));
744 function decodeBlob($b) {
745 return pg_unescape_bytea( $b );
748 function strencode( $s ) { ## Should not be called by us
749 return pg_escape_string( $s );
752 function addQuotes( $s ) {
753 if ( is_null( $s ) ) {
755 } else if (is_array( $s )) { ## Assume it is bytea data
758 return "'" . pg_escape_string($s) . "'";
759 return "E'" . pg_escape_string($s) . "'";
762 function quote_ident( $s ) {
763 return '"' . preg_replace( '/"/', '""', $s) . '"';