5 * This is the Postgres database abstraction layer.
9 private $name, $tablename, $type, $nullable, $max_length;
11 static function fromText($db, $table, $field) {
16 CASE WHEN typname = 'int2' THEN 'smallint'
17 WHEN typname = 'int4' THEN 'integer'
18 WHEN typname = 'int8' THEN 'bigint'
19 WHEN typname = 'bpchar' THEN 'char'
20 ELSE typname END AS typname,
22 FROM pg_class, pg_namespace, pg_attribute, pg_type
23 WHERE relnamespace=pg_namespace.oid
25 AND attrelid=pg_class.oid
26 AND atttypid=pg_type.oid
31 $res = $db->query(sprintf($q,
32 $db->addQuotes($wgDBmwschema),
33 $db->addQuotes($table),
34 $db->addQuotes($field)));
35 $row = $db->fetchObject($res);
38 $n = new PostgresField
;
39 $n->type
= $row->typname
;
40 $n->nullable
= ($row->attnotnull
== 'f');
42 $n->tablename
= $table;
43 $n->max_length
= $row->attlen
;
51 function tableName() {
52 return $this->tablename
;
60 return $this->nullable
;
63 function maxLength() {
64 return $this->max_length
;
71 class DatabasePostgres
extends DatabaseBase
{
72 var $mInsertId = null;
73 var $mLastResult = null;
74 var $numeric_version = null;
75 var $mAffectedRows = null;
77 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
78 $failFunction = false, $flags = 0 )
81 $this->mFailFunction
= $failFunction;
82 $this->mFlags
= $flags;
83 $this->open( $server, $user, $password, $dbName);
87 function cascadingDeletes() {
90 function cleanupTriggers() {
93 function strictIPs() {
96 function realTimestamps() {
99 function implicitGroupby() {
102 function implicitOrderby() {
105 function searchableIPs() {
108 function functionalIndexes() {
112 function hasConstraint( $name ) {
113 global $wgDBmwschema;
114 $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) ."'";
115 return $this->numRows($res = $this->doQuery($SQL));
118 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
120 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
124 * Usually aborts on failure
125 * If the failFunction is set to a non-zero integer, returns success
127 function open( $server, $user, $password, $dbName ) {
128 # Test for Postgres support, to avoid suppressed fatal error
129 if ( !function_exists( 'pg_connect' ) ) {
130 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" );
135 if (!strlen($user)) { ## e.g. the class is being loaded
139 $this->mServer
= $server;
140 $this->mPort
= $port = $wgDBport;
141 $this->mUser
= $user;
142 $this->mPassword
= $password;
143 $this->mDBname
= $dbName;
145 $connectVars = array(
148 'password' => $password );
149 if ($server!=false && $server!="") {
150 $connectVars['host'] = $server;
152 if ($port!=false && $port!="") {
153 $connectVars['port'] = $port;
155 $connectString = $this->makeConnectionString( $connectVars );
157 $this->installErrorHandler();
158 $this->mConn
= pg_connect( $connectString );
159 $phpError = $this->restoreErrorHandler();
161 if ( $this->mConn
== false ) {
162 wfDebug( "DB connection error\n" );
163 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
164 wfDebug( $this->lastError()."\n" );
165 if ( !$this->mFailFunction
) {
166 throw new DBConnectionError( $this, $phpError );
172 $this->mOpened
= true;
174 global $wgCommandLineMode;
175 ## If called from the command-line (e.g. importDump), only show errors
176 if ($wgCommandLineMode) {
177 $this->doQuery( "SET client_min_messages = 'ERROR'" );
180 $this->doQuery( "SET client_encoding='UTF8'" );
182 global $wgDBmwschema, $wgDBts2schema;
183 if (isset( $wgDBmwschema ) && isset( $wgDBts2schema )
184 && $wgDBmwschema !== 'mediawiki'
185 && preg_match( '/^\w+$/', $wgDBmwschema )
186 && preg_match( '/^\w+$/', $wgDBts2schema )
188 $safeschema = $this->quote_ident($wgDBmwschema);
189 $safeschema2 = $this->quote_ident($wgDBts2schema);
190 $this->doQuery( "SET search_path = $safeschema, $wgDBts2schema, public" );
196 function makeConnectionString( $vars ) {
198 foreach ( $vars as $name => $value ) {
199 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
205 function initial_setup($password, $dbName) {
206 // If this is the initial connection, setup the schema stuff and possibly create the user
207 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBsuperuser, $wgDBmwschema, $wgDBts2schema;
209 print "<li>Checking the version of Postgres...";
210 $version = $this->getServerVersion();
212 if ($version < $PGMINVER) {
213 print "<b>FAILED</b>. Required version is $PGMINVER. You have " . htmlspecialchars( $version ) . "</li>\n";
216 print "version " . htmlspecialchars( $this->numeric_version
) . " is OK.</li>\n";
218 $safeuser = $this->quote_ident($wgDBuser);
219 // Are we connecting as a superuser for the first time?
220 if ($wgDBsuperuser) {
221 // Are we really a superuser? Check out our rights
223 CASE WHEN usesuper IS TRUE THEN
224 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
225 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
227 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
228 $rows = $this->numRows($res = $this->doQuery($SQL));
230 print "<li>ERROR: Could not read permissions for user \"" . htmlspecialchars( $wgDBsuperuser ) . "\"</li>\n";
233 $perms = pg_fetch_result($res, 0, 0);
235 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
236 $rows = $this->numRows($this->doQuery($SQL));
238 print "<li>User \"" . htmlspecialchars( $wgDBuser ) . "\" already exists, skipping account creation.</li>";
241 if ($perms != 1 and $perms != 3) {
242 print "<li>ERROR: the user \"" . htmlspecialchars( $wgDBsuperuser ) . "\" cannot create other users. ";
243 print 'Please use a different Postgres user.</li>';
246 print "<li>Creating user <b>" . htmlspecialchars( $wgDBuser ) . "</b>...";
247 $safepass = $this->addQuotes($wgDBpassword);
248 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
249 $this->doQuery($SQL);
252 // User now exists, check out the database
253 if ($dbName != $wgDBname) {
254 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
255 $rows = $this->numRows($this->doQuery($SQL));
257 print "<li>Database \"" . htmlspecialchars( $wgDBname ) . "\" already exists, skipping database creation.</li>";
261 print "<li>ERROR: the user \"" . htmlspecialchars( $wgDBsuperuser ) . "\" cannot create databases. ";
262 print 'Please use a different Postgres user.</li>';
265 print "<li>Creating database <b>" . htmlspecialchars( $wgDBname ) . "</b>...";
266 $safename = $this->quote_ident($wgDBname);
267 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
268 $this->doQuery($SQL);
270 // Hopefully tsearch2 and plpgsql are in template1...
273 // Reconnect to check out tsearch2 rights for this user
274 print "<li>Connecting to \"" . htmlspecialchars( $wgDBname ) . "\" as superuser \"" .
275 htmlspecialchars( $wgDBsuperuser ) . "\" to check rights...";
277 $connectVars = array();
278 if ($this->mServer
!=false && $this->mServer
!="") {
279 $connectVars['host'] = $this->mServer
;
281 if ($this->mPort
!=false && $this->mPort
!="") {
282 $connectVars['port'] = $this->mPort
;
284 $connectVars['dbname'] = $wgDBname;
285 $connectVars['user'] = $wgDBsuperuser;
286 $connectVars['password'] = $password;
288 @$this->mConn
= pg_connect( $this->makeConnectionString( $connectVars ) );
289 if ( $this->mConn
== false ) {
290 print "<b>FAILED TO CONNECT!</b></li>";
296 if ($this->numeric_version
< 8.3) {
298 print "<li>Checking that tsearch2 is installed in the database \"" .
299 htmlspecialchars( $wgDBname ) . "\"...";
300 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
301 print "<b>FAILED</b>. tsearch2 must be installed in the database \"" .
302 htmlspecialchars( $wgDBname ) . "\".";
303 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
304 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
308 print "<li>Ensuring that user \"" . htmlspecialchars( $wgDBuser ) .
309 "\" has select rights on the tsearch2 tables...";
310 foreach (array('cfg','cfgmap','dict','parser') as $table) {
311 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
312 $this->doQuery($SQL);
317 // Setup the schema for this user if needed
318 $result = $this->schemaExists($wgDBmwschema);
319 $safeschema = $this->quote_ident($wgDBmwschema);
321 print "<li>Creating schema <b>" . htmlspecialchars( $wgDBmwschema ) . "</b> ...";
322 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
324 print "<b>FAILED</b>.</li>\n";
330 print "<li>Schema already exists, explicitly granting rights...\n";
331 $safeschema2 = $this->addQuotes($wgDBmwschema);
332 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
333 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
334 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
335 "AND p.relkind IN ('r','S','v')\n";
337 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
338 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
339 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
340 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
341 $res = $this->doQuery($SQL);
343 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
346 $this->doQuery("SET search_path = $safeschema");
347 $rows = $this->numRows($res);
350 $this->doQuery(pg_fetch_result($res, $rows, 0));
355 // Install plpgsql if needed
356 $this->setup_plpgsql();
359 return true; // Reconnect as regular user
363 if (!defined('POSTGRES_SEARCHPATH')) {
365 if ($this->numeric_version
< 8.3) {
366 // Do we have the basic tsearch2 table?
367 print "<li>Checking for tsearch2 in the schema \"" . htmlspecialchars( $wgDBts2schema ) . "\"...";
368 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
369 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
370 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
371 print " for instructions.</li>\n";
376 // Does this user have the rights to the tsearch2 tables?
377 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
378 print "<li>Checking tsearch2 permissions...";
379 // Let's check all four, just to be safe
380 error_reporting( 0 );
381 $ts2tables = array('cfg','cfgmap','dict','parser');
382 $safetsschema = $this->quote_ident($wgDBts2schema);
383 foreach ( $ts2tables AS $tname ) {
384 $SQL = "SELECT count(*) FROM $safetsschema.pg_ts_$tname";
385 $res = $this->doQuery($SQL);
387 print "<b>FAILED</b> to access " . htmlspecialchars( "pg_ts_$tname" ) .
388 ". Make sure that the user \"". htmlspecialchars( $wgDBuser ) .
389 "\" has SELECT access to all four tsearch2 tables</li>\n";
393 $SQL = "SELECT ts_name FROM $safetsschema.pg_ts_cfg WHERE locale = " . $this->addQuotes( $ctype ) ;
394 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
395 $res = $this->doQuery($SQL);
396 error_reporting( E_ALL
);
398 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
403 // Will the current locale work? Can we force it to?
404 print "<li>Verifying tsearch2 locale with " . htmlspecialchars( $ctype ) . "...";
405 $rows = $this->numRows($res);
408 print "<b>not found</b></li>\n";
409 print "<li>Attempting to set default tsearch2 locale to \"" . htmlspecialchars( $ctype ) . "\"...";
413 $tsname = pg_fetch_result($res, 0, 0);
414 if ($tsname != 'default') {
415 print "<b>not set to default (" . htmlspecialchars( $tsname ) . ")</b>";
416 print "<li>Attempting to change tsearch2 default locale to \"" .
417 htmlspecialchars( $ctype ) . "\"...";
422 $SQL = "UPDATE $safetsschema.pg_ts_cfg SET locale = " . $this->addQuotes( $ctype ) . " WHERE ts_name = 'default'";
423 $res = $this->doQuery($SQL);
425 print "<b>FAILED</b>. ";
426 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"" .
427 htmlspecialchars( $ctype ) . "\"</li>\n";
433 // Final test: try out a simple tsearch2 query
434 $SQL = "SELECT $safetsschema.to_tsvector('default','MediaWiki tsearch2 testing')";
435 $res = $this->doQuery($SQL);
437 print "<b>FAILED</b>. Specifically, \"" . htmlspecialchars( $SQL ) . "\" did not work.</li>";
443 // Install plpgsql if needed
444 $this->setup_plpgsql();
446 // Does the schema already exist? Who owns it?
447 $result = $this->schemaExists($wgDBmwschema);
449 print "<li>Creating schema <b>" . htmlspecialchars( $wgDBmwschema ) . "</b> ...";
450 error_reporting( 0 );
451 $safeschema = $this->quote_ident($wgDBmwschema);
452 $result = $this->doQuery("CREATE SCHEMA $safeschema");
453 error_reporting( E_ALL
);
455 print "<b>FAILED</b>. The user \"" . htmlspecialchars( $wgDBuser ) .
456 "\" must be able to access the schema. ".
457 "You can try making them the owner of the database, or try creating the schema with a ".
458 "different user, and then grant access to the \"" .
459 htmlspecialchars( $wgDBuser ) . "\" user.</li>\n";
464 else if ($result != $wgDBuser) {
465 print "<li>Schema \"" . htmlspecialchars( $wgDBmwschema ) . "\" exists but is not owned by \"" .
466 htmlspecialchars( $wgDBuser ) . "\". Not ideal.</li>\n";
469 print "<li>Schema \"" . htmlspecialchars( $wgDBmwschema ) . "\" exists and is owned by \"" .
470 htmlspecialchars( $wgDBuser ) . "\". Excellent.</li>\n";
473 // Always return GMT time to accomodate the existing integer-based timestamp assumption
474 print "<li>Setting the timezone to GMT for user \"" . htmlspecialchars( $wgDBuser ) . "\" ...";
475 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
476 $result = pg_query($this->mConn
, $SQL);
478 print "<b>FAILED</b>.</li>\n";
482 // Set for the rest of this session
483 $SQL = "SET timezone = 'GMT'";
484 $result = pg_query($this->mConn
, $SQL);
486 print "<li>Failed to set timezone</li>\n";
490 print "<li>Setting the datestyle to ISO, YMD for user \"" . htmlspecialchars( $wgDBuser ) . "\" ...";
491 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
492 $result = pg_query($this->mConn
, $SQL);
494 print "<b>FAILED</b>.</li>\n";
498 // Set for the rest of this session
499 $SQL = "SET datestyle = 'ISO, YMD'";
500 $result = pg_query($this->mConn
, $SQL);
502 print "<li>Failed to set datestyle</li>\n";
506 // Fix up the search paths if needed
507 print "<li>Setting the search path for user \"" . htmlspecialchars( $wgDBuser ) . "\" ...";
508 $path = $this->quote_ident($wgDBmwschema);
509 if ($wgDBts2schema !== $wgDBmwschema)
510 $path .= ", ". $this->quote_ident($wgDBts2schema);
511 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
513 $SQL = "ALTER USER $safeuser SET search_path = $path";
514 $result = pg_query($this->mConn
, $SQL);
516 print "<b>FAILED</b>.</li>\n";
520 // Set for the rest of this session
521 $SQL = "SET search_path = $path";
522 $result = pg_query($this->mConn
, $SQL);
524 print "<li>Failed to set search_path</li>\n";
527 define( "POSTGRES_SEARCHPATH", $path );
532 function setup_plpgsql() {
533 print "<li>Checking for Pl/Pgsql ...";
534 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
535 $rows = $this->numRows($this->doQuery($SQL));
537 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
538 print "not installed. Attempting to install Pl/Pgsql ...";
539 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
540 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
541 $rows = $this->numRows($this->doQuery($SQL));
543 $olde = error_reporting(0);
544 error_reporting($olde - E_WARNING
);
545 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
546 error_reporting($olde);
548 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>" .
549 htmlspecialchars( $wgDBname ) . "</tt></li>";
554 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>" .
555 htmlspecialchars( $wgDBname ) . "</tt></li>";
564 * Closes a database connection, if it is open
565 * Returns success, true if already closed
568 $this->mOpened
= false;
569 if ( $this->mConn
) {
570 return pg_close( $this->mConn
);
576 function doQuery( $sql ) {
577 if (function_exists('mb_convert_encoding')) {
578 $sql = mb_convert_encoding($sql,'UTF-8');
580 $this->mLastResult
= pg_query( $this->mConn
, $sql);
581 $this->mAffectedRows
= null; // use pg_affected_rows(mLastResult)
582 return $this->mLastResult
;
585 function queryIgnore( $sql, $fname = '' ) {
586 return $this->query( $sql, $fname, true );
589 function freeResult( $res ) {
590 if ( $res instanceof ResultWrapper
) {
593 if ( !@pg_free_result
( $res ) ) {
594 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
598 function fetchObject( $res ) {
599 if ( $res instanceof ResultWrapper
) {
602 @$row = pg_fetch_object( $res );
603 # FIXME: HACK HACK HACK HACK debug
606 # hashar : not sure if the following test really trigger if the object
608 if( pg_last_error($this->mConn
) ) {
609 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
614 function fetchRow( $res ) {
615 if ( $res instanceof ResultWrapper
) {
618 @$row = pg_fetch_array( $res );
619 if( pg_last_error($this->mConn
) ) {
620 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
625 function numRows( $res ) {
626 if ( $res instanceof ResultWrapper
) {
629 @$n = pg_num_rows( $res );
630 if( pg_last_error($this->mConn
) ) {
631 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
635 function numFields( $res ) {
636 if ( $res instanceof ResultWrapper
) {
639 return pg_num_fields( $res );
641 function fieldName( $res, $n ) {
642 if ( $res instanceof ResultWrapper
) {
645 return pg_field_name( $res, $n );
649 * This must be called after nextSequenceVal
651 function insertId() {
652 return $this->mInsertId
;
655 function dataSeek( $res, $row ) {
656 if ( $res instanceof ResultWrapper
) {
659 return pg_result_seek( $res, $row );
662 function lastError() {
663 if ( $this->mConn
) {
664 return pg_last_error();
667 return "No database connection";
670 function lastErrno() {
671 return pg_last_error() ?
1 : 0;
674 function affectedRows() {
675 if ( !is_null( $this->mAffectedRows
) ) {
676 // Forced result for simulated queries
677 return $this->mAffectedRows
;
679 if( empty( $this->mLastResult
) )
681 return pg_affected_rows( $this->mLastResult
);
685 * Estimate rows in dataset
686 * Returns estimated count, based on EXPLAIN output
687 * This is not necessarily an accurate estimate, so use sparingly
688 * Returns -1 if count cannot be found
689 * Takes same arguments as Database::select()
692 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
693 $options['EXPLAIN'] = true;
694 $res = $this->select( $table, $vars, $conds, $fname, $options );
697 $row = $this->fetchRow( $res );
699 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
702 $this->freeResult($res);
709 * Returns information about an index
710 * If errors are explicitly ignored, returns NULL on failure
712 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
713 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
714 $res = $this->query( $sql, $fname );
718 while ( $row = $this->fetchObject( $res ) ) {
719 if ( $row->indexname
== $this->indexName( $index ) ) {
726 function indexUnique ($table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
727 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
728 " AND indexdef LIKE 'CREATE UNIQUE%(" .
729 $this->strencode( $this->indexName( $index ) ) .
731 $res = $this->query( $sql, $fname );
734 while ($row = $this->fetchObject( $res ))
741 * INSERT wrapper, inserts an array into a table
743 * $args may be a single associative array, or an array of these with numeric keys,
744 * for multi-row insert (Postgres version 8.2 and above only).
746 * @param $table String: Name of the table to insert to.
747 * @param $args Array: Items to insert into the table.
748 * @param $fname String: Name of the function, for profiling
749 * @param $options String or Array. Valid options: IGNORE
751 * @return bool Success of insert operation. IGNORE always returns true.
753 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
756 if ( !count( $args ) ) {
760 $table = $this->tableName( $table );
761 if (! isset( $wgDBversion ) ) {
762 $wgDBversion = $this->getServerVersion();
765 if ( !is_array( $options ) )
766 $options = array( $options );
768 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
770 $keys = array_keys( $args[0] );
774 $keys = array_keys( $args );
777 // If IGNORE is set, we use savepoints to emulate mysql's behavior
778 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
780 // If we are not in a transaction, we need to be for savepoint trickery
783 if (! $this->mTrxLevel
) {
787 $olde = error_reporting( 0 );
788 // For future use, we may want to track the number of actual inserts
789 // Right now, insert (all writes) simply return true/false
790 $numrowsinserted = 0;
793 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
796 if ( $wgDBversion >= 8.2 && !$ignore ) {
798 foreach ( $args as $row ) {
804 $sql .= '(' . $this->makeList( $row ) . ')';
806 $res = (bool)$this->query( $sql, $fname, $ignore );
811 foreach ( $args as $row ) {
813 $tempsql .= '(' . $this->makeList( $row ) . ')';
816 pg_query($this->mConn
, "SAVEPOINT $ignore");
819 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
822 $bar = pg_last_error();
824 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
827 pg_query( $this->mConn
, "RELEASE $ignore" );
832 // If any of them fail, we fail overall for this function call
833 // Note that this will be ignored if IGNORE is set
840 // Not multi, just a lone insert
842 pg_query($this->mConn
, "SAVEPOINT $ignore");
845 $sql .= '(' . $this->makeList( $args ) . ')';
846 $res = (bool)$this->query( $sql, $fname, $ignore );
848 $bar = pg_last_error();
850 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
853 pg_query( $this->mConn
, "RELEASE $ignore" );
859 $olde = error_reporting( $olde );
864 // Set the affected row count for the whole operation
865 $this->mAffectedRows
= $numrowsinserted;
867 // IGNORE always returns true
877 * INSERT SELECT wrapper
878 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
879 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
880 * $conds may be "*" to copy the whole table
881 * srcTable may be an array of tables.
882 * @todo FIXME: implement this a little better (seperate select/insert)?
884 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
885 $insertOptions = array(), $selectOptions = array() )
887 $destTable = $this->tableName( $destTable );
889 // If IGNORE is set, we use savepoints to emulate mysql's behavior
890 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
892 if( is_array( $insertOptions ) ) {
893 $insertOptions = implode( ' ', $insertOptions );
895 if( !is_array( $selectOptions ) ) {
896 $selectOptions = array( $selectOptions );
898 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
899 if( is_array( $srcTable ) ) {
900 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
902 $srcTable = $this->tableName( $srcTable );
905 // If we are not in a transaction, we need to be for savepoint trickery
908 if( !$this->mTrxLevel
) {
912 $olde = error_reporting( 0 );
913 $numrowsinserted = 0;
914 pg_query( $this->mConn
, "SAVEPOINT $ignore");
917 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
918 " SELECT $startOpts " . implode( ',', $varMap ) .
919 " FROM $srcTable $useIndex";
921 if ( $conds != '*') {
922 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
925 $sql .= " $tailOpts";
927 $res = (bool)$this->query( $sql, $fname, $ignore );
929 $bar = pg_last_error();
930 if( $bar != false ) {
931 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
933 pg_query( $this->mConn
, "RELEASE $ignore" );
936 $olde = error_reporting( $olde );
941 // Set the affected row count for the whole operation
942 $this->mAffectedRows
= $numrowsinserted;
944 // IGNORE always returns true
951 function tableName( $name ) {
952 # Replace reserved words with better ones
957 return 'pagecontent';
964 * Return the next in a sequence, save the value for retrieval via insertId()
966 function nextSequenceValue( $seqName ) {
967 $safeseq = preg_replace( "/'/", "''", $seqName );
968 $res = $this->query( "SELECT nextval('$safeseq')" );
969 $row = $this->fetchRow( $res );
970 $this->mInsertId
= $row[0];
971 $this->freeResult( $res );
972 return $this->mInsertId
;
976 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
978 function currentSequenceValue( $seqName ) {
979 $safeseq = preg_replace( "/'/", "''", $seqName );
980 $res = $this->query( "SELECT currval('$safeseq')" );
981 $row = $this->fetchRow( $res );
983 $this->freeResult( $res );
987 # REPLACE query wrapper
988 # Postgres simulates this with a DELETE followed by INSERT
989 # $row is the row to insert, an associative array
990 # $uniqueIndexes is an array of indexes. Each element may be either a
991 # field name or an array of field names
993 # It may be more efficient to leave off unique indexes which are unlikely to collide.
994 # However if you do this, you run the risk of encountering errors which wouldn't have
996 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
997 $table = $this->tableName( $table );
999 if (count($rows)==0) {
1004 if ( !is_array( reset( $rows ) ) ) {
1005 $rows = array( $rows );
1008 foreach( $rows as $row ) {
1009 # Delete rows which collide
1010 if ( $uniqueIndexes ) {
1011 $sql = "DELETE FROM $table WHERE ";
1013 foreach ( $uniqueIndexes as $index ) {
1020 if ( is_array( $index ) ) {
1022 foreach ( $index as $col ) {
1028 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
1031 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1035 $this->query( $sql, $fname );
1038 # Now insert the row
1039 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
1040 $this->makeList( $row, LIST_COMMA
) . ')';
1041 $this->query( $sql, $fname );
1045 # DELETE where the condition is a join
1046 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
1048 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
1051 $delTable = $this->tableName( $delTable );
1052 $joinTable = $this->tableName( $joinTable );
1053 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1054 if ( $conds != '*' ) {
1055 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1059 $this->query( $sql, $fname );
1062 # Returns the size of a text field, or -1 for "unlimited"
1063 function textFieldSize( $table, $field ) {
1064 $table = $this->tableName( $table );
1065 $sql = "SELECT t.typname as ftype,a.atttypmod as size
1066 FROM pg_class c, pg_attribute a, pg_type t
1067 WHERE relname='$table' AND a.attrelid=c.oid AND
1068 a.atttypid=t.oid and a.attname='$field'";
1069 $res =$this->query($sql);
1070 $row=$this->fetchObject($res);
1071 if ($row->ftype
=="varchar") {
1076 $this->freeResult( $res );
1080 function limitResult($sql, $limit, $offset=false) {
1081 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
1084 function wasDeadlock() {
1085 return $this->lastErrno() == '40P01';
1088 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
1089 return $this->query( 'CREATE ' . ( $temporary ?
'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
1092 function timestamp( $ts=0 ) {
1093 return wfTimestamp(TS_POSTGRES
,$ts);
1097 * Return aggregated value function call
1099 function aggregateValue ($valuedata,$valuename='value') {
1104 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1105 // Ignore errors during error handling to avoid infinite recursion
1106 $ignore = $this->ignoreErrors( true );
1107 $this->mErrorCount++
;
1109 if ($ignore ||
$tempIgnore) {
1110 wfDebug("SQL ERROR (ignored): $error\n");
1111 $this->ignoreErrors( $ignore );
1114 $message = "A database error has occurred\n" .
1116 "Function: $fname\n" .
1117 "Error: $errno $error\n";
1118 throw new DBUnexpectedError($this, $message);
1123 * @return string wikitext of a link to the server software's web site
1125 function getSoftwareLink() {
1126 return "[http://www.postgresql.org/ PostgreSQL]";
1130 * @return string Version information from the database
1132 function getServerVersion() {
1133 $versionInfo = pg_version( $this->mConn
);
1134 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1135 // Old client, abort install
1136 $this->numeric_version
= '7.3 or earlier';
1137 } elseif ( isset( $versionInfo['server'] ) ) {
1139 $this->numeric_version
= $versionInfo['server'];
1141 // Bug 16937: broken pgsql extension from PHP<5.3
1142 $this->numeric_version
= pg_parameter_status( $this->mConn
, 'server_version' );
1144 return $this->numeric_version
;
1148 * Query whether a given relation exists (in the given schema, or the
1149 * default mw one if not given)
1151 function relationExists( $table, $types, $schema = false ) {
1152 global $wgDBmwschema;
1153 if ( !is_array( $types ) )
1154 $types = array( $types );
1156 $schema = $wgDBmwschema;
1157 $etable = $this->addQuotes( $table );
1158 $eschema = $this->addQuotes( $schema );
1159 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1160 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1161 . "AND c.relkind IN ('" . implode("','", $types) . "')";
1162 $res = $this->query( $SQL );
1163 $count = $res ?
$res->numRows() : 0;
1165 $this->freeResult( $res );
1166 return $count ?
true : false;
1170 * For backward compatibility, this function checks both tables and
1173 function tableExists( $table, $schema = false ) {
1174 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1177 function sequenceExists( $sequence, $schema = false ) {
1178 return $this->relationExists( $sequence, 'S', $schema );
1181 function triggerExists( $table, $trigger ) {
1182 global $wgDBmwschema;
1185 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1186 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1187 AND tgrelid=pg_class.oid
1188 AND nspname=%s AND relname=%s AND tgname=%s
1190 $res = $this->query(sprintf($q,
1191 $this->addQuotes($wgDBmwschema),
1192 $this->addQuotes($table),
1193 $this->addQuotes($trigger)));
1196 $rows = $res->numRows();
1197 $this->freeResult( $res );
1201 function ruleExists( $table, $rule ) {
1202 global $wgDBmwschema;
1203 $exists = $this->selectField("pg_rules", "rulename",
1204 array( "rulename" => $rule,
1205 "tablename" => $table,
1206 "schemaname" => $wgDBmwschema ) );
1207 return $exists === $rule;
1210 function constraintExists( $table, $constraint ) {
1211 global $wgDBmwschema;
1212 $SQL = sprintf("SELECT 1 FROM information_schema.table_constraints ".
1213 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1214 $this->addQuotes($wgDBmwschema),
1215 $this->addQuotes($table),
1216 $this->addQuotes($constraint));
1217 $res = $this->query($SQL);
1220 $rows = $res->numRows();
1221 $this->freeResult($res);
1226 * Query whether a given schema exists. Returns the name of the owner
1228 function schemaExists( $schema ) {
1229 $eschema = preg_replace("/'/", "''", $schema);
1230 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1231 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1232 $res = $this->query( $SQL );
1233 if ( $res && $res->numRows() ) {
1234 $row = $res->fetchObject();
1235 $owner = $row->rolname
;
1240 $this->freeResult($res);
1245 * Query whether a given column exists in the mediawiki schema
1247 function fieldExists( $table, $field, $fname = 'DatabasePostgres::fieldExists' ) {
1248 global $wgDBmwschema;
1249 $etable = preg_replace("/'/", "''", $table);
1250 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
1251 $ecol = preg_replace("/'/", "''", $field);
1252 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
1253 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
1254 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
1255 $res = $this->query( $SQL, $fname );
1256 $count = $res ?
$res->numRows() : 0;
1258 $this->freeResult( $res );
1262 function fieldInfo( $table, $field ) {
1263 return PostgresField
::fromText($this, $table, $field);
1267 * pg_field_type() wrapper
1269 function fieldType( $res, $index ) {
1270 if ( $res instanceof ResultWrapper
) {
1271 $res = $res->result
;
1273 return pg_field_type( $res, $index );
1276 function begin( $fname = 'DatabasePostgres::begin' ) {
1277 $this->query( 'BEGIN', $fname );
1278 $this->mTrxLevel
= 1;
1280 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
1283 function commit( $fname = 'DatabasePostgres::commit' ) {
1284 $this->query( 'COMMIT', $fname );
1285 $this->mTrxLevel
= 0;
1288 /* Not even sure why this is used in the main codebase... */
1289 function limitResultForUpdate( $sql, $num ) {
1293 function setup_database() {
1294 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
1296 // Make sure that we can write to the correct schema
1297 // If not, Postgres will happily and silently go to the next search_path item
1298 $ctest = "mediawiki_test_table";
1299 $safeschema = $this->quote_ident($wgDBmwschema);
1300 if ($this->tableExists($ctest, $wgDBmwschema)) {
1301 $this->doQuery("DROP TABLE $safeschema.$ctest");
1303 $SQL = "CREATE TABLE $safeschema.$ctest(a int)";
1304 $olde = error_reporting( 0 );
1305 $res = $this->doQuery($SQL);
1306 error_reporting( $olde );
1308 print "<b>FAILED</b>. Make sure that the user \"" . htmlspecialchars( $wgDBuser ) .
1309 "\" can write to the schema \"" . htmlspecialchars( $wgDBmwschema ) . "\"</li>\n";
1312 $this->doQuery("DROP TABLE $safeschema.$ctest");
1314 $res = $this->sourceFile( "../maintenance/postgres/tables.sql" );
1316 ## Update version information
1317 $mwv = $this->addQuotes($wgVersion);
1318 $pgv = $this->addQuotes($this->getServerVersion());
1319 $pgu = $this->addQuotes($this->mUser
);
1320 $mws = $this->addQuotes($wgDBmwschema);
1321 $tss = $this->addQuotes($wgDBts2schema);
1322 $pgp = $this->addQuotes($wgDBport);
1323 $dbn = $this->addQuotes($this->mDBname
);
1324 $ctype = $this->addQuotes( pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0) );
1326 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
1327 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
1329 "WHERE type = 'Creation'";
1332 ## Avoid the non-standard "REPLACE INTO" syntax
1333 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1335 dieout( "<li>Could not find the interwiki.sql file");
1337 ## We simply assume it is already empty as we have just created it
1338 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1339 while ( ! feof( $f ) ) {
1340 $line = fgets($f,1024);
1342 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
1345 $this->query("$SQL $matches[1],$matches[2])");
1347 print " (table interwiki successfully populated)...\n";
1349 $this->doQuery("COMMIT");
1352 function encodeBlob( $b ) {
1353 return new Blob ( pg_escape_bytea( $b ) ) ;
1356 function decodeBlob( $b ) {
1357 if ($b instanceof Blob
) {
1360 return pg_unescape_bytea( $b );
1363 function strencode( $s ) { ## Should not be called by us
1364 return pg_escape_string( $s );
1367 function addQuotes( $s ) {
1368 if ( is_null( $s ) ) {
1370 } else if ( is_bool( $s ) ) {
1371 return intval( $s );
1372 } else if ($s instanceof Blob
) {
1373 return "'".$s->fetch($s)."'";
1375 return "'" . pg_escape_string($s) . "'";
1378 function quote_ident( $s ) {
1379 return '"' . preg_replace( '/"/', '""', $s) . '"';
1383 * Postgres specific version of replaceVars.
1384 * Calls the parent version in Database.php
1388 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1390 * @return string SQL string
1392 protected function replaceVars( $ins ) {
1394 $ins = parent
::replaceVars( $ins );
1396 if ($this->numeric_version
>= 8.3) {
1397 // Thanks for not providing backwards-compatibility, 8.3
1398 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1401 if ($this->numeric_version
<= 8.1) { // Our minimum version
1402 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1409 * Various select options
1413 * @param $options Array: an associative array of options to be turned into
1414 * an SQL query, valid keys are listed in the function.
1417 function makeSelectOptions( $options ) {
1418 $preLimitTail = $postLimitTail = '';
1419 $startOpts = $useIndex = '';
1421 $noKeyOptions = array();
1422 foreach ( $options as $key => $option ) {
1423 if ( is_numeric( $key ) ) {
1424 $noKeyOptions[$option] = true;
1428 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY " . $options['GROUP BY'];
1429 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1430 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY " . $options['ORDER BY'];
1432 //if (isset($options['LIMIT'])) {
1433 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1434 // isset($options['OFFSET']) ? $options['OFFSET']
1438 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1439 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1440 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1442 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1446 * How lagged is this slave?
1449 public function getLag() {
1450 # Not implemented for PostgreSQL
1454 function setFakeSlaveLag( $lag ) {}
1455 function setFakeMaster( $enabled = true ) {}
1457 function getDBname() {
1458 return $this->mDBname
;
1461 function getServer() {
1462 return $this->mServer
;
1465 function buildConcat( $stringList ) {
1466 return implode( ' || ', $stringList );
1469 public function getSearchEngine() {
1470 return "SearchPostgres";
1472 } // end DatabasePostgres class