2fe2c79a6898b49f801078b7789eea4be940bded
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 ## Are we connecting as a superuser for the first time?
97 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
98 $rows = $this->numRows($this->doQuery($SQL));
100 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
103 ## Can we create users?
104 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usesuper IS TRUE AND ".
105 "usename = " . $this->addQuotes($wgDBsuperuser);
106 $rows = $this->numRows($this->doQuery($SQL));
108 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
109 print 'Please use a different Postgres user.</li>';
112 print "<li>Creating user <b>$wgDBuser</b>...";
113 $safepass = $this->addQuotes($wgDBpass);
114 $SQL = "CREATE USER \"$wgDBuser\" NOCREATEDB PASSWORD $safepass";
115 $this->doQuery($SQL);
118 ## User now exists, check out the database
119 $safename = $this->addQuotes($wgDBname);
120 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = $safename";
121 $rows = $this->numRows($this->doQuery($SQL));
123 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
126 print "<li>Creating database <b>$wgDBname</b>...";
127 $SQL = "CREATE DATABASE \"$wgDBname\" OWNER \"$wgDBuser\" ";
128 $this->doQuery($SQL);
130 ## Hopefully tsearch2 and plpgsql are in template1...
133 ## Reconnect to check out tsearch2 rights for this user
134 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
135 @$this->mConn
= pg_connect("$hstring dbname=$wgDBname user=$user password=$password");
136 if ( $this->mConn
== false ) {
137 print "<b>FAILED TO CONNECT!</b></li>";
141 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
142 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
143 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
144 print "Please see 'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
145 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
149 print "Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
150 foreach (array('cfg','cfgmap','dict','parser') as $table) {
151 $SQL = "GRANT SELECT ON pg_ts_$table TO \"$wgDBuser\"";
152 $this->doQuery($SQL);
156 return true; ## Reconnect as regular user
159 if (!defined('POSTGRES_SEARCHPATH')) {
161 ## Do we have the basic tsearch2 table?
162 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
163 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
164 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
165 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
166 print " for instructions.</li>\n";
171 ## Does this user have the rights to the tsearch2 tables?
172 print "<li>Checking tsearch2 permissions...";
173 $SQL = "SELECT 1 FROM $wgDBts2schema.pg_ts_cfg";
174 error_reporting( 0 );
175 $res = $this->doQuery($SQL);
176 error_reporting( E_ALL
);
178 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" has SELECT access to the tsearch2 tables</li>\n";
183 ## Do we have plpgsql installed?
184 print "<li>Checking for plpgsql ...";
185 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
186 $rows = $this->numRows($this->doQuery($SQL));
188 print "<b>FAILED</b>. Make sure the language plpgsql is installed for the database <tt>$wgDBname</tt></li>";
193 ## Does the schema already exist? Who owns it?
194 $result = $this->schemaExists($wgDBmwschema);
196 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
197 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
199 print "<b>FAILED</b>.</li>\n";
204 else if ($result != $user) {
205 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
208 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
211 ## Fix up the search paths if needed
212 print "<li>Setting the search path for user \"$user\" ...";
213 $path = "$wgDBmwschema";
214 if ($wgDBts2schema !== $wgDBmwschema)
215 $path .= ", $wgDBts2schema";
216 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
218 $SQL = "ALTER USER $user SET search_path = $path";
219 $result = pg_query($this->mConn
, $SQL);
221 print "<b>FAILED</b>.</li>\n";
225 ## Set for the rest of this session
226 $SQL = "SET search_path = $path";
227 $result = pg_query($this->mConn
, $SQL);
229 print "<li>Failed to set search_path</li>\n";
232 define( "POSTGRES_SEARCHPATH", $path );
239 * Closes a database connection, if it is open
240 * Returns success, true if already closed
243 $this->mOpened
= false;
244 if ( $this->mConn
) {
245 return pg_close( $this->mConn
);
251 function doQuery( $sql ) {
252 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
255 function queryIgnore( $sql, $fname = '' ) {
256 return $this->query( $sql, $fname, true );
259 function freeResult( $res ) {
260 if ( !@pg_free_result
( $res ) ) {
261 throw new DBUnexpectedError($this, "Unable to free PostgreSQL result\n" );
265 function fetchObject( $res ) {
266 @$row = pg_fetch_object( $res );
267 # FIXME: HACK HACK HACK HACK debug
270 # hashar : not sure if the following test really trigger if the object
272 if( pg_last_error($this->mConn
) ) {
273 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
278 function fetchRow( $res ) {
279 @$row = pg_fetch_array( $res );
280 if( pg_last_error($this->mConn
) ) {
281 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
286 function numRows( $res ) {
287 @$n = pg_num_rows( $res );
288 if( pg_last_error($this->mConn
) ) {
289 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
293 function numFields( $res ) { return pg_num_fields( $res ); }
294 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
297 * This must be called after nextSequenceVal
299 function insertId() {
300 return $this->mInsertId
;
303 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
304 function lastError() {
305 if ( $this->mConn
) {
306 return pg_last_error();
309 return "No database connection";
312 function lastErrno() {
313 return pg_last_error() ?
1 : 0;
316 function affectedRows() {
317 return pg_affected_rows( $this->mLastResult
);
321 * Returns information about an index
322 * If errors are explicitly ignored, returns NULL on failure
324 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
325 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
326 $res = $this->query( $sql, $fname );
331 while ( $row = $this->fetchObject( $res ) ) {
332 if ( $row->indexname
== $index ) {
339 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
340 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
341 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
342 $res = $this->query( $sql, $fname );
345 while ($row = $this->fetchObject( $res ))
351 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
352 # PostgreSQL doesn't support options
353 # We have a go at faking one of them
354 # TODO: DELAYED, LOW_PRIORITY
356 if ( !is_array($options))
357 $options = array($options);
359 if ( in_array( 'IGNORE', $options ) )
360 $oldIgnore = $this->ignoreErrors( true );
362 # IGNORE is performed using single-row inserts, ignoring errors in each
363 # FIXME: need some way to distiguish between key collision and other types of error
364 $oldIgnore = $this->ignoreErrors( true );
365 if ( !is_array( reset( $a ) ) ) {
368 foreach ( $a as $row ) {
369 parent
::insert( $table, $row, $fname, array() );
371 $this->ignoreErrors( $oldIgnore );
374 if ( in_array( 'IGNORE', $options ) )
375 $this->ignoreErrors( $oldIgnore );
380 function tableName( $name ) {
381 # Replace reserved words with better ones
386 return 'pagecontent';
393 * Return the next in a sequence, save the value for retrieval via insertId()
395 function nextSequenceValue( $seqName ) {
396 $safeseq = preg_replace( "/'/", "''", $seqName );
397 $res = $this->query( "SELECT nextval('$safeseq')" );
398 $row = $this->fetchRow( $res );
399 $this->mInsertId
= $row[0];
400 $this->freeResult( $res );
401 return $this->mInsertId
;
406 * PostgreSQL doesn't have them and returns ""
408 function useIndexClause( $index ) {
412 # REPLACE query wrapper
413 # PostgreSQL simulates this with a DELETE followed by INSERT
414 # $row is the row to insert, an associative array
415 # $uniqueIndexes is an array of indexes. Each element may be either a
416 # field name or an array of field names
418 # It may be more efficient to leave off unique indexes which are unlikely to collide.
419 # However if you do this, you run the risk of encountering errors which wouldn't have
421 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
422 $table = $this->tableName( $table );
424 if (count($rows)==0) {
429 if ( !is_array( reset( $rows ) ) ) {
430 $rows = array( $rows );
433 foreach( $rows as $row ) {
434 # Delete rows which collide
435 if ( $uniqueIndexes ) {
436 $sql = "DELETE FROM $table WHERE ";
438 foreach ( $uniqueIndexes as $index ) {
445 if ( is_array( $index ) ) {
447 foreach ( $index as $col ) {
453 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
456 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
460 $this->query( $sql, $fname );
464 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
465 $this->makeList( $row, LIST_COMMA
) . ')';
466 $this->query( $sql, $fname );
470 # DELETE where the condition is a join
471 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
473 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
476 $delTable = $this->tableName( $delTable );
477 $joinTable = $this->tableName( $joinTable );
478 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
479 if ( $conds != '*' ) {
480 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
484 $this->query( $sql, $fname );
487 # Returns the size of a text field, or -1 for "unlimited"
488 function textFieldSize( $table, $field ) {
489 $table = $this->tableName( $table );
490 $sql = "SELECT t.typname as ftype,a.atttypmod as size
491 FROM pg_class c, pg_attribute a, pg_type t
492 WHERE relname='$table' AND a.attrelid=c.oid AND
493 a.atttypid=t.oid and a.attname='$field'";
494 $res =$this->query($sql);
495 $row=$this->fetchObject($res);
496 if ($row->ftype
=="varchar") {
501 $this->freeResult( $res );
505 function lowPriorityOption() {
509 function limitResult($sql, $limit,$offset) {
510 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
514 * Returns an SQL expression for a simple conditional.
515 * Uses CASE on PostgreSQL.
517 * @param string $cond SQL expression which will result in a boolean value
518 * @param string $trueVal SQL expression to return if true
519 * @param string $falseVal SQL expression to return if false
520 * @return string SQL fragment
522 function conditional( $cond, $trueVal, $falseVal ) {
523 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
526 # FIXME: actually detecting deadlocks might be nice
527 function wasDeadlock() {
531 function timestamp( $ts=0 ) {
532 return wfTimestamp(TS_POSTGRES
,$ts);
536 * Return aggregated value function call
538 function aggregateValue ($valuedata,$valuename='value') {
543 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
544 $message = "A database error has occurred\n" .
546 "Function: $fname\n" .
547 "Error: $errno $error\n";
548 throw new DBUnexpectedError($this, $message);
552 * @return string wikitext of a link to the server software's web site
554 function getSoftwareLink() {
555 return "[http://www.postgresql.org/ PostgreSQL]";
559 * @return string Version information from the database
561 function getServerVersion() {
562 $res = $this->query( "SELECT version()" );
563 $row = $this->fetchRow( $res );
565 $this->freeResult( $res );
571 * Query whether a given table exists (in the given schema, or the default mw one if not given)
573 function tableExists( $table, $schema = false ) {
574 global $wgDBmwschema;
576 $schema = $wgDBmwschema;
577 $etable = preg_replace("/'/", "''", $table);
578 $eschema = preg_replace("/'/", "''", $schema);
579 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
580 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema'";
581 $res = $this->query( $SQL );
582 $count = $res ?
pg_num_rows($res) : 0;
584 $this->freeResult( $res );
590 * Query whether a given schema exists. Returns the name of the owner
592 function schemaExists( $schema ) {
593 $eschema = preg_replace("/'/", "''", $schema);
594 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
595 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
596 $res = $this->query( $SQL );
597 $owner = $res ?
pg_num_rows($res) ?
pg_fetch_result($res, 0, 0) : false : false;
599 $this->freeResult($res);
604 * Query whether a given column exists in the mediawiki schema
606 function fieldExists( $table, $field ) {
607 global $wgDBmwschema;
608 $etable = preg_replace("/'/", "''", $table);
609 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
610 $ecol = preg_replace("/'/", "''", $field);
611 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
612 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
613 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
614 $res = $this->query( $SQL );
615 $count = $res ?
pg_num_rows($res) : 0;
617 $this->freeResult( $res );
621 function fieldInfo( $table, $field ) {
622 $res = $this->query( "SELECT $field FROM $table LIMIT 1" );
623 $type = pg_field_type( $res, 0 );
627 function begin( $fname = 'DatabasePostgrs::begin' ) {
628 $this->query( 'BEGIN', $fname );
629 $this->mTrxLevel
= 1;
631 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
634 function commit( $fname = 'DatabasePostgres::commit' ) {
635 $this->query( 'COMMIT', $fname );
636 $this->mTrxLevel
= 0;
639 /* Not even sure why this is used in the main codebase... */
640 function limitResultForUpdate($sql, $num) {
644 function setup_database() {
645 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport;
647 dbsource( "../maintenance/postgres/tables.sql", $this);
649 ## Update version information
650 $mwv = $this->addQuotes($wgVersion);
651 $pgv = $this->addQuotes($this->getServerVersion());
652 $pgu = $this->addQuotes($this->mUser
);
653 $mws = $this->addQuotes($wgDBmwschema);
654 $tss = $this->addQuotes($wgDBts2schema);
655 $pgp = $this->addQuotes($wgDBport);
656 $dbn = $this->addQuotes($this->mDBname
);
658 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
659 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn ".
660 "WHERE type = 'Creation'";
663 ## Avoid the non-standard "REPLACE INTO" syntax
664 $f = fopen( "../maintenance/interwiki.sql", 'r' );
666 dieout( "<li>Could not find the interwiki.sql file");
668 ## We simply assume it is already empty as we have just created it
669 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
670 while ( ! feof( $f ) ) {
671 $line = fgets($f,1024);
672 if (!preg_match("/^\s*(\(.+?),(\d)\)/", $line, $matches)) {
675 $yesno = $matches[2]; ## ? "'true'" : "'false'";
676 $this->query("$SQL $matches[1],$matches[2])");
678 print " (table interwiki successfully populated)...\n";
681 function encodeBlob($b) {
682 return array('bytea',pg_escape_bytea($b));
684 function decodeBlob($b) {
685 return pg_unescape_bytea( $b );
688 function strencode( $s ) { ## Should not be called by us
689 return pg_escape_string( $s );
692 function addQuotes( $s ) {
693 if ( is_null( $s ) ) {
695 } else if (is_array( $s )) { ## Assume it is bytea data
698 return "'" . pg_escape_string($s) . "'";
699 return "E'" . pg_escape_string($s) . "'";