5 * This is the Postgres database abstraction layer.
9 private $name, $tablename, $type, $nullable, $max_length, $deferred, $deferrable, $conname;
11 static function fromText($db, $table, $field) {
16 attnotnull, attlen, COALESCE(conname, '') AS conname,
17 COALESCE(condeferred, 'f') AS deferred,
18 COALESCE(condeferrable, 'f') AS deferrable,
19 CASE WHEN typname = 'int2' THEN 'smallint'
20 WHEN typname = 'int4' THEN 'integer'
21 WHEN typname = 'int8' THEN 'bigint'
22 WHEN typname = 'bpchar' THEN 'char'
23 ELSE typname END AS typname
25 JOIN pg_namespace n ON (n.oid = c.relnamespace)
26 JOIN pg_attribute a ON (a.attrelid = c.oid)
27 JOIN pg_type t ON (t.oid = a.atttypid)
28 LEFT JOIN pg_constraint o ON (o.conrelid = c.oid AND a.attnum = ANY(o.conkey) AND o.contype = 'f')
35 $table = $db->tableName( $table );
36 $res = $db->query(sprintf($q,
37 $db->addQuotes($wgDBmwschema),
38 $db->addQuotes($table),
39 $db->addQuotes($field)));
40 $row = $db->fetchObject($res);
43 $n = new PostgresField
;
44 $n->type
= $row->typname
;
45 $n->nullable
= ($row->attnotnull
== 'f');
47 $n->tablename
= $table;
48 $n->max_length
= $row->attlen
;
49 $n->deferrable
= ($row->deferrable
== 't');
50 $n->deferred
= ($row->deferred
== 't');
51 $n->conname
= $row->conname
;
59 function tableName() {
60 return $this->tablename
;
68 return $this->nullable
;
71 function maxLength() {
72 return $this->max_length
;
75 function is_deferrable() {
76 return $this->deferrable
;
79 function is_deferred() {
80 return $this->deferred
;
84 return $this->conname
;
92 class DatabasePostgres
extends DatabaseBase
{
93 var $mInsertId = null;
94 var $mLastResult = null;
95 var $numeric_version = null;
96 var $mAffectedRows = null;
98 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
99 $failFunction = false, $flags = 0 )
102 $this->mFailFunction
= $failFunction;
103 $this->mFlags
= $flags;
104 $this->open( $server, $user, $password, $dbName);
112 function cascadingDeletes() {
115 function cleanupTriggers() {
118 function strictIPs() {
121 function realTimestamps() {
124 function implicitGroupby() {
127 function implicitOrderby() {
130 function searchableIPs() {
133 function functionalIndexes() {
137 function hasConstraint( $name ) {
138 global $wgDBmwschema;
139 $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) ."'";
140 return $this->numRows($res = $this->doQuery($SQL));
143 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
145 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
149 * Usually aborts on failure
150 * If the failFunction is set to a non-zero integer, returns success
152 function open( $server, $user, $password, $dbName ) {
153 # Test for Postgres support, to avoid suppressed fatal error
154 if ( !function_exists( 'pg_connect' ) ) {
155 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" );
160 if (!strlen($user)) { ## e.g. the class is being loaded
164 $this->mServer
= $server;
165 $this->mPort
= $port = $wgDBport;
166 $this->mUser
= $user;
167 $this->mPassword
= $password;
168 $this->mDBname
= $dbName;
170 $connectVars = array(
173 'password' => $password );
174 if ($server!=false && $server!="") {
175 $connectVars['host'] = $server;
177 if ($port!=false && $port!="") {
178 $connectVars['port'] = $port;
180 $connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
182 $this->installErrorHandler();
183 $this->mConn
= pg_connect( $connectString );
184 $phpError = $this->restoreErrorHandler();
186 if ( !$this->mConn
) {
187 wfDebug( "DB connection error\n" );
188 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
189 wfDebug( $this->lastError()."\n" );
190 if ( !$this->mFailFunction
) {
191 throw new DBConnectionError( $this, $phpError );
197 $this->mOpened
= true;
199 global $wgCommandLineMode;
200 ## If called from the command-line (e.g. importDump), only show errors
201 if ($wgCommandLineMode) {
202 $this->doQuery( "SET client_min_messages = 'ERROR'" );
205 $this->doQuery( "SET client_encoding='UTF8'" );
207 global $wgDBmwschema, $wgDBts2schema;
208 if (isset( $wgDBmwschema ) && isset( $wgDBts2schema )
209 && $wgDBmwschema !== 'mediawiki'
210 && preg_match( '/^\w+$/', $wgDBmwschema )
211 && preg_match( '/^\w+$/', $wgDBts2schema )
213 $safeschema = $this->quote_ident($wgDBmwschema);
214 $safeschema2 = $this->quote_ident($wgDBts2schema);
215 $this->doQuery( "SET search_path = $safeschema, $wgDBts2schema, public" );
221 function makeConnectionString( $vars ) {
223 foreach ( $vars as $name => $value ) {
224 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
230 function initial_setup($superuser, $password, $dbName) {
231 // If this is the initial connection, setup the schema stuff and possibly create the user
232 global $wgDBname, $wgDBuser, $wgDBpassword, $superuser, $wgDBmwschema, $wgDBts2schema;
234 print "<li>Checking the version of Postgres...";
235 $version = $this->getServerVersion();
237 if ($version < $PGMINVER) {
238 print "<b>FAILED</b>. Required version is $PGMINVER. You have " . htmlspecialchars( $version ) . "</li>\n";
241 print "version " . htmlspecialchars( $this->numeric_version
) . " is OK.</li>\n";
243 $safeuser = $this->quote_ident($wgDBuser);
244 // Are we connecting as a superuser for the first time?
246 // Are we really a superuser? Check out our rights
248 CASE WHEN usesuper IS TRUE THEN
249 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
250 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
252 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($superuser);
253 $rows = $this->numRows($res = $this->doQuery($SQL));
255 print "<li>ERROR: Could not read permissions for user \"" . htmlspecialchars( $superuser ) . "\"</li>\n";
258 $perms = pg_fetch_result($res, 0, 0);
260 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
261 $rows = $this->numRows($this->doQuery($SQL));
263 print "<li>User \"" . htmlspecialchars( $wgDBuser ) . "\" already exists, skipping account creation.</li>";
266 if ($perms != 1 and $perms != 3) {
267 print "<li>ERROR: the user \"" . htmlspecialchars( $superuser ) . "\" cannot create other users. ";
268 print 'Please use a different Postgres user.</li>';
271 print "<li>Creating user <b>" . htmlspecialchars( $wgDBuser ) . "</b>...";
272 $safepass = $this->addQuotes($wgDBpassword);
273 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
274 $this->doQuery($SQL);
277 // User now exists, check out the database
278 if ($dbName != $wgDBname) {
279 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
280 $rows = $this->numRows($this->doQuery($SQL));
282 print "<li>Database \"" . htmlspecialchars( $wgDBname ) . "\" already exists, skipping database creation.</li>";
286 print "<li>ERROR: the user \"" . htmlspecialchars( $superuser ) . "\" cannot create databases. ";
287 print 'Please use a different Postgres user.</li>';
290 print "<li>Creating database <b>" . htmlspecialchars( $wgDBname ) . "</b>...";
291 $safename = $this->quote_ident($wgDBname);
292 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
293 $this->doQuery($SQL);
295 // Hopefully tsearch2 and plpgsql are in template1...
298 // Reconnect to check out tsearch2 rights for this user
299 print "<li>Connecting to \"" . htmlspecialchars( $wgDBname ) . "\" as superuser \"" .
300 htmlspecialchars( $superuser ) . "\" to check rights...";
302 $connectVars = array();
303 if ($this->mServer
!=false && $this->mServer
!="") {
304 $connectVars['host'] = $this->mServer
;
306 if ($this->mPort
!=false && $this->mPort
!="") {
307 $connectVars['port'] = $this->mPort
;
309 $connectVars['dbname'] = $wgDBname;
310 $connectVars['user'] = $superuser;
311 $connectVars['password'] = $password;
313 @$this->mConn
= pg_connect( $this->makeConnectionString( $connectVars ) );
314 if ( !$this->mConn
) {
315 print "<b>FAILED TO CONNECT!</b></li>";
321 if ($this->numeric_version
< 8.3) {
323 print "<li>Checking that tsearch2 is installed in the database \"" .
324 htmlspecialchars( $wgDBname ) . "\"...";
325 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
326 print "<b>FAILED</b>. tsearch2 must be installed in the database \"" .
327 htmlspecialchars( $wgDBname ) . "\".";
328 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
329 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
333 print "<li>Ensuring that user \"" . htmlspecialchars( $wgDBuser ) .
334 "\" has select rights on the tsearch2 tables...";
335 foreach (array('cfg','cfgmap','dict','parser') as $table) {
336 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
337 $this->doQuery($SQL);
342 // Setup the schema for this user if needed
343 $result = $this->schemaExists($wgDBmwschema);
344 $safeschema = $this->quote_ident($wgDBmwschema);
346 print "<li>Creating schema <b>" . htmlspecialchars( $wgDBmwschema ) . "</b> ...";
347 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
349 print "<b>FAILED</b>.</li>\n";
355 print "<li>Schema already exists, explicitly granting rights...\n";
356 $safeschema2 = $this->addQuotes($wgDBmwschema);
357 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
358 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
359 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
360 "AND p.relkind IN ('r','S','v')\n";
362 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
363 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
364 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
365 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
366 $res = $this->doQuery($SQL);
368 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
371 $this->doQuery("SET search_path = $safeschema");
372 $rows = $this->numRows($res);
375 $this->doQuery(pg_fetch_result($res, $rows, 0));
380 // Install plpgsql if needed
381 $this->setup_plpgsql();
384 return true; // Reconnect as regular user
388 if (!defined('POSTGRES_SEARCHPATH')) {
390 if ($this->numeric_version
< 8.3) {
391 // Do we have the basic tsearch2 table?
392 print "<li>Checking for tsearch2 in the schema \"" . htmlspecialchars( $wgDBts2schema ) . "\"...";
393 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
394 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
395 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
396 print " for instructions.</li>\n";
401 // Does this user have the rights to the tsearch2 tables?
402 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
403 print "<li>Checking tsearch2 permissions...";
404 // Let's check all four, just to be safe
405 error_reporting( 0 );
406 $ts2tables = array('cfg','cfgmap','dict','parser');
407 $safetsschema = $this->quote_ident($wgDBts2schema);
408 foreach ( $ts2tables AS $tname ) {
409 $SQL = "SELECT count(*) FROM $safetsschema.pg_ts_$tname";
410 $res = $this->doQuery($SQL);
412 print "<b>FAILED</b> to access " . htmlspecialchars( "pg_ts_$tname" ) .
413 ". Make sure that the user \"". htmlspecialchars( $wgDBuser ) .
414 "\" has SELECT access to all four tsearch2 tables</li>\n";
418 $SQL = "SELECT ts_name FROM $safetsschema.pg_ts_cfg WHERE locale = " . $this->addQuotes( $ctype ) ;
419 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
420 $res = $this->doQuery($SQL);
421 error_reporting( E_ALL
);
423 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
428 // Will the current locale work? Can we force it to?
429 print "<li>Verifying tsearch2 locale with " . htmlspecialchars( $ctype ) . "...";
430 $rows = $this->numRows($res);
433 print "<b>not found</b></li>\n";
434 print "<li>Attempting to set default tsearch2 locale to \"" . htmlspecialchars( $ctype ) . "\"...";
438 $tsname = pg_fetch_result($res, 0, 0);
439 if ($tsname != 'default') {
440 print "<b>not set to default (" . htmlspecialchars( $tsname ) . ")</b>";
441 print "<li>Attempting to change tsearch2 default locale to \"" .
442 htmlspecialchars( $ctype ) . "\"...";
447 $SQL = "UPDATE $safetsschema.pg_ts_cfg SET locale = " . $this->addQuotes( $ctype ) . " WHERE ts_name = 'default'";
448 $res = $this->doQuery($SQL);
450 print "<b>FAILED</b>. ";
451 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"" .
452 htmlspecialchars( $ctype ) . "\"</li>\n";
458 // Final test: try out a simple tsearch2 query
459 $SQL = "SELECT $safetsschema.to_tsvector('default','MediaWiki tsearch2 testing')";
460 $res = $this->doQuery($SQL);
462 print "<b>FAILED</b>. Specifically, \"" . htmlspecialchars( $SQL ) . "\" did not work.</li>";
468 // Install plpgsql if needed
469 $this->setup_plpgsql();
471 // Does the schema already exist? Who owns it?
472 $result = $this->schemaExists($wgDBmwschema);
474 print "<li>Creating schema <b>" . htmlspecialchars( $wgDBmwschema ) . "</b> ...";
475 error_reporting( 0 );
476 $safeschema = $this->quote_ident($wgDBmwschema);
477 $result = $this->doQuery("CREATE SCHEMA $safeschema");
478 error_reporting( E_ALL
);
480 print "<b>FAILED</b>. The user \"" . htmlspecialchars( $wgDBuser ) .
481 "\" must be able to access the schema. ".
482 "You can try making them the owner of the database, or try creating the schema with a ".
483 "different user, and then grant access to the \"" .
484 htmlspecialchars( $wgDBuser ) . "\" user.</li>\n";
489 else if ($result != $wgDBuser) {
490 print "<li>Schema \"" . htmlspecialchars( $wgDBmwschema ) . "\" exists but is not owned by \"" .
491 htmlspecialchars( $wgDBuser ) . "\". Not ideal.</li>\n";
494 print "<li>Schema \"" . htmlspecialchars( $wgDBmwschema ) . "\" exists and is owned by \"" .
495 htmlspecialchars( $wgDBuser ) . "\". Excellent.</li>\n";
498 // Always return GMT time to accomodate the existing integer-based timestamp assumption
499 print "<li>Setting the timezone to GMT for user \"" . htmlspecialchars( $wgDBuser ) . "\" ...";
500 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
501 $result = pg_query($this->mConn
, $SQL);
503 print "<b>FAILED</b>.</li>\n";
507 // Set for the rest of this session
508 $SQL = "SET timezone = 'GMT'";
509 $result = pg_query($this->mConn
, $SQL);
511 print "<li>Failed to set timezone</li>\n";
515 print "<li>Setting the datestyle to ISO, YMD for user \"" . htmlspecialchars( $wgDBuser ) . "\" ...";
516 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
517 $result = pg_query($this->mConn
, $SQL);
519 print "<b>FAILED</b>.</li>\n";
523 // Set for the rest of this session
524 $SQL = "SET datestyle = 'ISO, YMD'";
525 $result = pg_query($this->mConn
, $SQL);
527 print "<li>Failed to set datestyle</li>\n";
531 // Fix up the search paths if needed
532 print "<li>Setting the search path for user \"" . htmlspecialchars( $wgDBuser ) . "\" ...";
533 $path = $this->quote_ident($wgDBmwschema);
534 if ($wgDBts2schema !== $wgDBmwschema)
535 $path .= ", ". $this->quote_ident($wgDBts2schema);
536 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
538 $SQL = "ALTER USER $safeuser SET search_path = $path";
539 $result = pg_query($this->mConn
, $SQL);
541 print "<b>FAILED</b>.</li>\n";
545 // Set for the rest of this session
546 $SQL = "SET search_path = $path";
547 $result = pg_query($this->mConn
, $SQL);
549 print "<li>Failed to set search_path</li>\n";
552 define( "POSTGRES_SEARCHPATH", $path );
557 function setup_plpgsql() {
558 print "<li>Checking for Pl/Pgsql ...";
559 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
560 $rows = $this->numRows($this->doQuery($SQL));
562 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
563 print "not installed. Attempting to install Pl/Pgsql ...";
564 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
565 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
566 $rows = $this->numRows($this->doQuery($SQL));
569 $olde = error_reporting(0);
570 error_reporting($olde - E_WARNING
);
571 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
572 error_reporting($olde);
574 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>" .
575 htmlspecialchars( $wgDBname ) . "</tt></li>";
580 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>" .
581 htmlspecialchars( $wgDBname ) . "</tt></li>";
590 * Closes a database connection, if it is open
591 * Returns success, true if already closed
594 $this->mOpened
= false;
595 if ( $this->mConn
) {
596 return pg_close( $this->mConn
);
602 function doQuery( $sql ) {
603 if (function_exists('mb_convert_encoding')) {
604 $sql = mb_convert_encoding($sql,'UTF-8');
606 $this->mLastResult
= pg_query( $this->mConn
, $sql);
607 $this->mAffectedRows
= null; // use pg_affected_rows(mLastResult)
608 return $this->mLastResult
;
611 function queryIgnore( $sql, $fname = '' ) {
612 return $this->query( $sql, $fname, true );
615 function freeResult( $res ) {
616 if ( $res instanceof ResultWrapper
) {
619 if ( !@pg_free_result
( $res ) ) {
620 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
624 function fetchObject( $res ) {
625 if ( $res instanceof ResultWrapper
) {
628 @$row = pg_fetch_object( $res );
629 # FIXME: HACK HACK HACK HACK debug
632 # hashar : not sure if the following test really trigger if the object
634 if( pg_last_error($this->mConn
) ) {
635 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
640 function fetchRow( $res ) {
641 if ( $res instanceof ResultWrapper
) {
644 @$row = pg_fetch_array( $res );
645 if( pg_last_error($this->mConn
) ) {
646 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
651 function numRows( $res ) {
652 if ( $res instanceof ResultWrapper
) {
655 @$n = pg_num_rows( $res );
656 if( pg_last_error($this->mConn
) ) {
657 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
661 function numFields( $res ) {
662 if ( $res instanceof ResultWrapper
) {
665 return pg_num_fields( $res );
667 function fieldName( $res, $n ) {
668 if ( $res instanceof ResultWrapper
) {
671 return pg_field_name( $res, $n );
675 * This must be called after nextSequenceVal
677 function insertId() {
678 return $this->mInsertId
;
681 function dataSeek( $res, $row ) {
682 if ( $res instanceof ResultWrapper
) {
685 return pg_result_seek( $res, $row );
688 function lastError() {
689 if ( $this->mConn
) {
690 return pg_last_error();
693 return "No database connection";
696 function lastErrno() {
697 return pg_last_error() ?
1 : 0;
700 function affectedRows() {
701 if ( !is_null( $this->mAffectedRows
) ) {
702 // Forced result for simulated queries
703 return $this->mAffectedRows
;
705 if( empty( $this->mLastResult
) )
707 return pg_affected_rows( $this->mLastResult
);
711 * Estimate rows in dataset
712 * Returns estimated count, based on EXPLAIN output
713 * This is not necessarily an accurate estimate, so use sparingly
714 * Returns -1 if count cannot be found
715 * Takes same arguments as Database::select()
718 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
719 $options['EXPLAIN'] = true;
720 $res = $this->select( $table, $vars, $conds, $fname, $options );
723 $row = $this->fetchRow( $res );
725 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
728 $this->freeResult($res);
735 * Returns information about an index
736 * If errors are explicitly ignored, returns NULL on failure
738 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
739 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
740 $res = $this->query( $sql, $fname );
744 while ( $row = $this->fetchObject( $res ) ) {
745 if ( $row->indexname
== $this->indexName( $index ) ) {
752 function indexUnique ($table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
753 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
754 " AND indexdef LIKE 'CREATE UNIQUE%(" .
755 $this->strencode( $this->indexName( $index ) ) .
757 $res = $this->query( $sql, $fname );
760 while ($row = $this->fetchObject( $res ))
767 * INSERT wrapper, inserts an array into a table
769 * $args may be a single associative array, or an array of these with numeric keys,
770 * for multi-row insert (Postgres version 8.2 and above only).
772 * @param $table String: Name of the table to insert to.
773 * @param $args Array: Items to insert into the table.
774 * @param $fname String: Name of the function, for profiling
775 * @param $options String or Array. Valid options: IGNORE
777 * @return bool Success of insert operation. IGNORE always returns true.
779 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
782 if ( !count( $args ) ) {
786 $table = $this->tableName( $table );
787 if (! isset( $wgDBversion ) ) {
788 $wgDBversion = $this->getServerVersion();
791 if ( !is_array( $options ) )
792 $options = array( $options );
794 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
796 $keys = array_keys( $args[0] );
800 $keys = array_keys( $args );
803 // If IGNORE is set, we use savepoints to emulate mysql's behavior
804 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
806 // If we are not in a transaction, we need to be for savepoint trickery
809 if (! $this->mTrxLevel
) {
813 $olde = error_reporting( 0 );
814 // For future use, we may want to track the number of actual inserts
815 // Right now, insert (all writes) simply return true/false
816 $numrowsinserted = 0;
819 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
822 if ( $wgDBversion >= 8.2 && !$ignore ) {
824 foreach ( $args as $row ) {
830 $sql .= '(' . $this->makeList( $row ) . ')';
832 $res = (bool)$this->query( $sql, $fname, $ignore );
837 foreach ( $args as $row ) {
839 $tempsql .= '(' . $this->makeList( $row ) . ')';
842 pg_query($this->mConn
, "SAVEPOINT $ignore");
845 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
848 $bar = pg_last_error();
850 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
853 pg_query( $this->mConn
, "RELEASE $ignore" );
858 // If any of them fail, we fail overall for this function call
859 // Note that this will be ignored if IGNORE is set
866 // Not multi, just a lone insert
868 pg_query($this->mConn
, "SAVEPOINT $ignore");
871 $sql .= '(' . $this->makeList( $args ) . ')';
872 $res = (bool)$this->query( $sql, $fname, $ignore );
874 $bar = pg_last_error();
876 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
879 pg_query( $this->mConn
, "RELEASE $ignore" );
885 $olde = error_reporting( $olde );
890 // Set the affected row count for the whole operation
891 $this->mAffectedRows
= $numrowsinserted;
893 // IGNORE always returns true
903 * INSERT SELECT wrapper
904 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
905 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
906 * $conds may be "*" to copy the whole table
907 * srcTable may be an array of tables.
908 * @todo FIXME: implement this a little better (seperate select/insert)?
910 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
911 $insertOptions = array(), $selectOptions = array() )
913 $destTable = $this->tableName( $destTable );
915 // If IGNORE is set, we use savepoints to emulate mysql's behavior
916 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
918 if( is_array( $insertOptions ) ) {
919 $insertOptions = implode( ' ', $insertOptions );
921 if( !is_array( $selectOptions ) ) {
922 $selectOptions = array( $selectOptions );
924 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
925 if( is_array( $srcTable ) ) {
926 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
928 $srcTable = $this->tableName( $srcTable );
931 // If we are not in a transaction, we need to be for savepoint trickery
934 if( !$this->mTrxLevel
) {
938 $olde = error_reporting( 0 );
939 $numrowsinserted = 0;
940 pg_query( $this->mConn
, "SAVEPOINT $ignore");
943 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
944 " SELECT $startOpts " . implode( ',', $varMap ) .
945 " FROM $srcTable $useIndex";
947 if ( $conds != '*') {
948 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
951 $sql .= " $tailOpts";
953 $res = (bool)$this->query( $sql, $fname, $ignore );
955 $bar = pg_last_error();
956 if( $bar != false ) {
957 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
959 pg_query( $this->mConn
, "RELEASE $ignore" );
962 $olde = error_reporting( $olde );
967 // Set the affected row count for the whole operation
968 $this->mAffectedRows
= $numrowsinserted;
970 // IGNORE always returns true
977 function tableName( $name ) {
978 # Replace reserved words with better ones
983 return 'pagecontent';
990 * Return the next in a sequence, save the value for retrieval via insertId()
992 function nextSequenceValue( $seqName ) {
993 $safeseq = preg_replace( "/'/", "''", $seqName );
994 $res = $this->query( "SELECT nextval('$safeseq')" );
995 $row = $this->fetchRow( $res );
996 $this->mInsertId
= $row[0];
997 $this->freeResult( $res );
998 return $this->mInsertId
;
1002 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
1004 function currentSequenceValue( $seqName ) {
1005 $safeseq = preg_replace( "/'/", "''", $seqName );
1006 $res = $this->query( "SELECT currval('$safeseq')" );
1007 $row = $this->fetchRow( $res );
1009 $this->freeResult( $res );
1013 # REPLACE query wrapper
1014 # Postgres simulates this with a DELETE followed by INSERT
1015 # $row is the row to insert, an associative array
1016 # $uniqueIndexes is an array of indexes. Each element may be either a
1017 # field name or an array of field names
1019 # It may be more efficient to leave off unique indexes which are unlikely to collide.
1020 # However if you do this, you run the risk of encountering errors which wouldn't have
1022 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
1023 $table = $this->tableName( $table );
1025 if (count($rows)==0) {
1030 if ( !is_array( reset( $rows ) ) ) {
1031 $rows = array( $rows );
1034 foreach( $rows as $row ) {
1035 # Delete rows which collide
1036 if ( $uniqueIndexes ) {
1037 $sql = "DELETE FROM $table WHERE ";
1039 foreach ( $uniqueIndexes as $index ) {
1046 if ( is_array( $index ) ) {
1048 foreach ( $index as $col ) {
1054 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
1057 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1061 $this->query( $sql, $fname );
1064 # Now insert the row
1065 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
1066 $this->makeList( $row, LIST_COMMA
) . ')';
1067 $this->query( $sql, $fname );
1071 # DELETE where the condition is a join
1072 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
1074 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
1077 $delTable = $this->tableName( $delTable );
1078 $joinTable = $this->tableName( $joinTable );
1079 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1080 if ( $conds != '*' ) {
1081 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1085 $this->query( $sql, $fname );
1088 # Returns the size of a text field, or -1 for "unlimited"
1089 function textFieldSize( $table, $field ) {
1090 $table = $this->tableName( $table );
1091 $sql = "SELECT t.typname as ftype,a.atttypmod as size
1092 FROM pg_class c, pg_attribute a, pg_type t
1093 WHERE relname='$table' AND a.attrelid=c.oid AND
1094 a.atttypid=t.oid and a.attname='$field'";
1095 $res =$this->query($sql);
1096 $row=$this->fetchObject($res);
1097 if ($row->ftype
=="varchar") {
1102 $this->freeResult( $res );
1106 function limitResult($sql, $limit, $offset=false) {
1107 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
1110 function wasDeadlock() {
1111 return $this->lastErrno() == '40P01';
1114 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
1115 return $this->query( 'CREATE ' . ( $temporary ?
'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
1118 function timestamp( $ts=0 ) {
1119 return wfTimestamp(TS_POSTGRES
,$ts);
1123 * Return aggregated value function call
1125 function aggregateValue ($valuedata,$valuename='value') {
1130 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1131 // Ignore errors during error handling to avoid infinite recursion
1132 $ignore = $this->ignoreErrors( true );
1133 $this->mErrorCount++
;
1135 if ($ignore ||
$tempIgnore) {
1136 wfDebug("SQL ERROR (ignored): $error\n");
1137 $this->ignoreErrors( $ignore );
1140 $message = "A database error has occurred\n" .
1142 "Function: $fname\n" .
1143 "Error: $errno $error\n";
1144 throw new DBUnexpectedError($this, $message);
1149 * @return string wikitext of a link to the server software's web site
1151 function getSoftwareLink() {
1152 return "[http://www.postgresql.org/ PostgreSQL]";
1156 * @return string Version information from the database
1158 function getServerVersion() {
1159 $versionInfo = pg_version( $this->mConn
);
1160 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1161 // Old client, abort install
1162 $this->numeric_version
= '7.3 or earlier';
1163 } elseif ( isset( $versionInfo['server'] ) ) {
1165 $this->numeric_version
= $versionInfo['server'];
1167 // Bug 16937: broken pgsql extension from PHP<5.3
1168 $this->numeric_version
= pg_parameter_status( $this->mConn
, 'server_version' );
1170 return $this->numeric_version
;
1174 * Query whether a given relation exists (in the given schema, or the
1175 * default mw one if not given)
1177 function relationExists( $table, $types, $schema = false ) {
1178 global $wgDBmwschema;
1179 if ( !is_array( $types ) )
1180 $types = array( $types );
1182 $schema = $wgDBmwschema;
1183 $etable = $this->addQuotes( $table );
1184 $eschema = $this->addQuotes( $schema );
1185 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1186 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1187 . "AND c.relkind IN ('" . implode("','", $types) . "')";
1188 $res = $this->query( $SQL );
1189 $count = $res ?
$res->numRows() : 0;
1191 $this->freeResult( $res );
1192 return $count ?
true : false;
1196 * For backward compatibility, this function checks both tables and
1199 function tableExists( $table, $schema = false ) {
1200 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1203 function sequenceExists( $sequence, $schema = false ) {
1204 return $this->relationExists( $sequence, 'S', $schema );
1207 function triggerExists( $table, $trigger ) {
1208 global $wgDBmwschema;
1211 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1212 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1213 AND tgrelid=pg_class.oid
1214 AND nspname=%s AND relname=%s AND tgname=%s
1216 $res = $this->query(sprintf($q,
1217 $this->addQuotes($wgDBmwschema),
1218 $this->addQuotes($table),
1219 $this->addQuotes($trigger)));
1222 $rows = $res->numRows();
1223 $this->freeResult( $res );
1227 function ruleExists( $table, $rule ) {
1228 global $wgDBmwschema;
1229 $exists = $this->selectField("pg_rules", "rulename",
1230 array( "rulename" => $rule,
1231 "tablename" => $table,
1232 "schemaname" => $wgDBmwschema ) );
1233 return $exists === $rule;
1236 function constraintExists( $table, $constraint ) {
1237 global $wgDBmwschema;
1238 $SQL = sprintf("SELECT 1 FROM information_schema.table_constraints ".
1239 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1240 $this->addQuotes($wgDBmwschema),
1241 $this->addQuotes($table),
1242 $this->addQuotes($constraint));
1243 $res = $this->query($SQL);
1246 $rows = $res->numRows();
1247 $this->freeResult($res);
1252 * Query whether a given schema exists. Returns the name of the owner
1254 function schemaExists( $schema ) {
1255 $eschema = preg_replace("/'/", "''", $schema);
1256 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1257 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1258 $res = $this->query( $SQL );
1259 if ( $res && $res->numRows() ) {
1260 $row = $res->fetchObject();
1261 $owner = $row->rolname
;
1266 $this->freeResult($res);
1270 function fieldInfo( $table, $field ) {
1271 return PostgresField
::fromText($this, $table, $field);
1275 * pg_field_type() wrapper
1277 function fieldType( $res, $index ) {
1278 if ( $res instanceof ResultWrapper
) {
1279 $res = $res->result
;
1281 return pg_field_type( $res, $index );
1284 function begin( $fname = 'DatabasePostgres::begin' ) {
1285 $this->query( 'BEGIN', $fname );
1286 $this->mTrxLevel
= 1;
1289 function commit( $fname = 'DatabasePostgres::commit' ) {
1290 $this->query( 'COMMIT', $fname );
1291 $this->mTrxLevel
= 0;
1294 /* Not even sure why this is used in the main codebase... */
1295 function limitResultForUpdate( $sql, $num ) {
1299 function setup_database() {
1300 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
1302 // Make sure that we can write to the correct schema
1303 // If not, Postgres will happily and silently go to the next search_path item
1304 $ctest = "mediawiki_test_table";
1305 $safeschema = $this->quote_ident($wgDBmwschema);
1306 if ($this->tableExists($ctest, $wgDBmwschema)) {
1307 $this->doQuery("DROP TABLE $safeschema.$ctest");
1309 $SQL = "CREATE TABLE $safeschema.$ctest(a int)";
1310 $olde = error_reporting( 0 );
1311 $res = $this->doQuery($SQL);
1312 error_reporting( $olde );
1314 print "<b>FAILED</b>. Make sure that the user \"" . htmlspecialchars( $wgDBuser ) .
1315 "\" can write to the schema \"" . htmlspecialchars( $wgDBmwschema ) . "\"</li>\n";
1316 dieout(""); # Will close the main list <ul> and finish the page.
1318 $this->doQuery("DROP TABLE $safeschema.$ctest");
1320 $res = $this->sourceFile( "../maintenance/postgres/tables.sql" );
1321 if ($res === true) {
1322 print " done.</li>\n";
1324 print " <b>FAILED</b></li>\n";
1325 dieout( htmlspecialchars( $res ) );
1328 ## Update version information
1329 $mwv = $this->addQuotes($wgVersion);
1330 $pgv = $this->addQuotes($this->getServerVersion());
1331 $pgu = $this->addQuotes($this->mUser
);
1332 $mws = $this->addQuotes($wgDBmwschema);
1333 $tss = $this->addQuotes($wgDBts2schema);
1334 $pgp = $this->addQuotes($wgDBport);
1335 $dbn = $this->addQuotes($this->mDBname
);
1336 $ctype = $this->addQuotes( pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0) );
1338 echo "<li>Populating interwiki table... ";
1339 ## Avoid the non-standard "REPLACE INTO" syntax
1340 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1342 print "<b>FAILED</b></li>";
1343 dieout( "Could not find the interwiki.sql file" );
1345 ## We simply assume it is already empty as we have just created it
1346 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1347 while ( ! feof( $f ) ) {
1348 $line = fgets($f,1024);
1350 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
1353 $this->query("$SQL $matches[1],$matches[2])");
1355 print " successfully populated.</li>\n";
1357 $this->doQuery("COMMIT");
1360 function encodeBlob( $b ) {
1361 return new Blob ( pg_escape_bytea( $b ) ) ;
1364 function decodeBlob( $b ) {
1365 if ($b instanceof Blob
) {
1368 return pg_unescape_bytea( $b );
1371 function strencode( $s ) { ## Should not be called by us
1372 return pg_escape_string( $s );
1375 function addQuotes( $s ) {
1376 if ( is_null( $s ) ) {
1378 } else if ( is_bool( $s ) ) {
1379 return intval( $s );
1380 } else if ($s instanceof Blob
) {
1381 return "'".$s->fetch($s)."'";
1383 return "'" . pg_escape_string($s) . "'";
1386 function quote_ident( $s ) {
1387 return '"' . preg_replace( '/"/', '""', $s) . '"';
1391 * Postgres specific version of replaceVars.
1392 * Calls the parent version in Database.php
1396 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1398 * @return string SQL string
1400 protected function replaceVars( $ins ) {
1402 $ins = parent
::replaceVars( $ins );
1404 if ($this->numeric_version
>= 8.3) {
1405 // Thanks for not providing backwards-compatibility, 8.3
1406 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1409 if ($this->numeric_version
<= 8.1) { // Our minimum version
1410 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1417 * Various select options
1421 * @param $options Array: an associative array of options to be turned into
1422 * an SQL query, valid keys are listed in the function.
1425 function makeSelectOptions( $options ) {
1426 $preLimitTail = $postLimitTail = '';
1427 $startOpts = $useIndex = '';
1429 $noKeyOptions = array();
1430 foreach ( $options as $key => $option ) {
1431 if ( is_numeric( $key ) ) {
1432 $noKeyOptions[$option] = true;
1436 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY " . $options['GROUP BY'];
1437 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1438 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY " . $options['ORDER BY'];
1440 //if (isset($options['LIMIT'])) {
1441 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1442 // isset($options['OFFSET']) ? $options['OFFSET']
1446 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1447 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1448 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1450 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1453 function setFakeMaster( $enabled = true ) {}
1455 function getDBname() {
1456 return $this->mDBname
;
1459 function getServer() {
1460 return $this->mServer
;
1463 function buildConcat( $stringList ) {
1464 return implode( ' || ', $stringList );
1467 public function getSearchEngine() {
1468 return "SearchPostgres";
1470 } // end DatabasePostgres class