226803fb57da00b66387f96b71b09f47749f91a9
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($password, $dbName) {
231 // If this is the initial connection, setup the schema stuff and possibly create the user
232 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBsuperuser, $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?
245 if ($wgDBsuperuser) {
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($wgDBsuperuser);
253 $rows = $this->numRows($res = $this->doQuery($SQL));
255 print "<li>ERROR: Could not read permissions for user \"" . htmlspecialchars( $wgDBsuperuser ) . "\"</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( $wgDBsuperuser ) . "\" 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( $wgDBsuperuser ) . "\" 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( $wgDBsuperuser ) . "\" 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'] = $wgDBsuperuser;
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));
568 $olde = error_reporting(0);
569 error_reporting($olde - E_WARNING
);
570 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
571 error_reporting($olde);
573 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>" .
574 htmlspecialchars( $wgDBname ) . "</tt></li>";
579 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>" .
580 htmlspecialchars( $wgDBname ) . "</tt></li>";
589 * Closes a database connection, if it is open
590 * Returns success, true if already closed
593 $this->mOpened
= false;
594 if ( $this->mConn
) {
595 return pg_close( $this->mConn
);
601 function doQuery( $sql ) {
602 if (function_exists('mb_convert_encoding')) {
603 $sql = mb_convert_encoding($sql,'UTF-8');
605 $this->mLastResult
= pg_query( $this->mConn
, $sql);
606 $this->mAffectedRows
= null; // use pg_affected_rows(mLastResult)
607 return $this->mLastResult
;
610 function queryIgnore( $sql, $fname = '' ) {
611 return $this->query( $sql, $fname, true );
614 function freeResult( $res ) {
615 if ( $res instanceof ResultWrapper
) {
618 if ( !@pg_free_result
( $res ) ) {
619 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
623 function fetchObject( $res ) {
624 if ( $res instanceof ResultWrapper
) {
627 @$row = pg_fetch_object( $res );
628 # FIXME: HACK HACK HACK HACK debug
631 # hashar : not sure if the following test really trigger if the object
633 if( pg_last_error($this->mConn
) ) {
634 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
639 function fetchRow( $res ) {
640 if ( $res instanceof ResultWrapper
) {
643 @$row = pg_fetch_array( $res );
644 if( pg_last_error($this->mConn
) ) {
645 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
650 function numRows( $res ) {
651 if ( $res instanceof ResultWrapper
) {
654 @$n = pg_num_rows( $res );
655 if( pg_last_error($this->mConn
) ) {
656 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
660 function numFields( $res ) {
661 if ( $res instanceof ResultWrapper
) {
664 return pg_num_fields( $res );
666 function fieldName( $res, $n ) {
667 if ( $res instanceof ResultWrapper
) {
670 return pg_field_name( $res, $n );
674 * This must be called after nextSequenceVal
676 function insertId() {
677 return $this->mInsertId
;
680 function dataSeek( $res, $row ) {
681 if ( $res instanceof ResultWrapper
) {
684 return pg_result_seek( $res, $row );
687 function lastError() {
688 if ( $this->mConn
) {
689 return pg_last_error();
692 return "No database connection";
695 function lastErrno() {
696 return pg_last_error() ?
1 : 0;
699 function affectedRows() {
700 if ( !is_null( $this->mAffectedRows
) ) {
701 // Forced result for simulated queries
702 return $this->mAffectedRows
;
704 if( empty( $this->mLastResult
) )
706 return pg_affected_rows( $this->mLastResult
);
710 * Estimate rows in dataset
711 * Returns estimated count, based on EXPLAIN output
712 * This is not necessarily an accurate estimate, so use sparingly
713 * Returns -1 if count cannot be found
714 * Takes same arguments as Database::select()
717 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
718 $options['EXPLAIN'] = true;
719 $res = $this->select( $table, $vars, $conds, $fname, $options );
722 $row = $this->fetchRow( $res );
724 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
727 $this->freeResult($res);
734 * Returns information about an index
735 * If errors are explicitly ignored, returns NULL on failure
737 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
738 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
739 $res = $this->query( $sql, $fname );
743 while ( $row = $this->fetchObject( $res ) ) {
744 if ( $row->indexname
== $this->indexName( $index ) ) {
751 function indexUnique ($table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
752 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
753 " AND indexdef LIKE 'CREATE UNIQUE%(" .
754 $this->strencode( $this->indexName( $index ) ) .
756 $res = $this->query( $sql, $fname );
759 while ($row = $this->fetchObject( $res ))
766 * INSERT wrapper, inserts an array into a table
768 * $args may be a single associative array, or an array of these with numeric keys,
769 * for multi-row insert (Postgres version 8.2 and above only).
771 * @param $table String: Name of the table to insert to.
772 * @param $args Array: Items to insert into the table.
773 * @param $fname String: Name of the function, for profiling
774 * @param $options String or Array. Valid options: IGNORE
776 * @return bool Success of insert operation. IGNORE always returns true.
778 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
781 if ( !count( $args ) ) {
785 $table = $this->tableName( $table );
786 if (! isset( $wgDBversion ) ) {
787 $wgDBversion = $this->getServerVersion();
790 if ( !is_array( $options ) )
791 $options = array( $options );
793 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
795 $keys = array_keys( $args[0] );
799 $keys = array_keys( $args );
802 // If IGNORE is set, we use savepoints to emulate mysql's behavior
803 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
805 // If we are not in a transaction, we need to be for savepoint trickery
808 if (! $this->mTrxLevel
) {
812 $olde = error_reporting( 0 );
813 // For future use, we may want to track the number of actual inserts
814 // Right now, insert (all writes) simply return true/false
815 $numrowsinserted = 0;
818 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
821 if ( $wgDBversion >= 8.2 && !$ignore ) {
823 foreach ( $args as $row ) {
829 $sql .= '(' . $this->makeList( $row ) . ')';
831 $res = (bool)$this->query( $sql, $fname, $ignore );
836 foreach ( $args as $row ) {
838 $tempsql .= '(' . $this->makeList( $row ) . ')';
841 pg_query($this->mConn
, "SAVEPOINT $ignore");
844 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
847 $bar = pg_last_error();
849 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
852 pg_query( $this->mConn
, "RELEASE $ignore" );
857 // If any of them fail, we fail overall for this function call
858 // Note that this will be ignored if IGNORE is set
865 // Not multi, just a lone insert
867 pg_query($this->mConn
, "SAVEPOINT $ignore");
870 $sql .= '(' . $this->makeList( $args ) . ')';
871 $res = (bool)$this->query( $sql, $fname, $ignore );
873 $bar = pg_last_error();
875 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
878 pg_query( $this->mConn
, "RELEASE $ignore" );
884 $olde = error_reporting( $olde );
889 // Set the affected row count for the whole operation
890 $this->mAffectedRows
= $numrowsinserted;
892 // IGNORE always returns true
902 * INSERT SELECT wrapper
903 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
904 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
905 * $conds may be "*" to copy the whole table
906 * srcTable may be an array of tables.
907 * @todo FIXME: implement this a little better (seperate select/insert)?
909 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
910 $insertOptions = array(), $selectOptions = array() )
912 $destTable = $this->tableName( $destTable );
914 // If IGNORE is set, we use savepoints to emulate mysql's behavior
915 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
917 if( is_array( $insertOptions ) ) {
918 $insertOptions = implode( ' ', $insertOptions );
920 if( !is_array( $selectOptions ) ) {
921 $selectOptions = array( $selectOptions );
923 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
924 if( is_array( $srcTable ) ) {
925 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
927 $srcTable = $this->tableName( $srcTable );
930 // If we are not in a transaction, we need to be for savepoint trickery
933 if( !$this->mTrxLevel
) {
937 $olde = error_reporting( 0 );
938 $numrowsinserted = 0;
939 pg_query( $this->mConn
, "SAVEPOINT $ignore");
942 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
943 " SELECT $startOpts " . implode( ',', $varMap ) .
944 " FROM $srcTable $useIndex";
946 if ( $conds != '*') {
947 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
950 $sql .= " $tailOpts";
952 $res = (bool)$this->query( $sql, $fname, $ignore );
954 $bar = pg_last_error();
955 if( $bar != false ) {
956 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
958 pg_query( $this->mConn
, "RELEASE $ignore" );
961 $olde = error_reporting( $olde );
966 // Set the affected row count for the whole operation
967 $this->mAffectedRows
= $numrowsinserted;
969 // IGNORE always returns true
976 function tableName( $name ) {
977 # Replace reserved words with better ones
982 return 'pagecontent';
989 * Return the next in a sequence, save the value for retrieval via insertId()
991 function nextSequenceValue( $seqName ) {
992 $safeseq = preg_replace( "/'/", "''", $seqName );
993 $res = $this->query( "SELECT nextval('$safeseq')" );
994 $row = $this->fetchRow( $res );
995 $this->mInsertId
= $row[0];
996 $this->freeResult( $res );
997 return $this->mInsertId
;
1001 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
1003 function currentSequenceValue( $seqName ) {
1004 $safeseq = preg_replace( "/'/", "''", $seqName );
1005 $res = $this->query( "SELECT currval('$safeseq')" );
1006 $row = $this->fetchRow( $res );
1008 $this->freeResult( $res );
1012 # REPLACE query wrapper
1013 # Postgres simulates this with a DELETE followed by INSERT
1014 # $row is the row to insert, an associative array
1015 # $uniqueIndexes is an array of indexes. Each element may be either a
1016 # field name or an array of field names
1018 # It may be more efficient to leave off unique indexes which are unlikely to collide.
1019 # However if you do this, you run the risk of encountering errors which wouldn't have
1021 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
1022 $table = $this->tableName( $table );
1024 if (count($rows)==0) {
1029 if ( !is_array( reset( $rows ) ) ) {
1030 $rows = array( $rows );
1033 foreach( $rows as $row ) {
1034 # Delete rows which collide
1035 if ( $uniqueIndexes ) {
1036 $sql = "DELETE FROM $table WHERE ";
1038 foreach ( $uniqueIndexes as $index ) {
1045 if ( is_array( $index ) ) {
1047 foreach ( $index as $col ) {
1053 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
1056 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1060 $this->query( $sql, $fname );
1063 # Now insert the row
1064 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
1065 $this->makeList( $row, LIST_COMMA
) . ')';
1066 $this->query( $sql, $fname );
1070 # DELETE where the condition is a join
1071 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
1073 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
1076 $delTable = $this->tableName( $delTable );
1077 $joinTable = $this->tableName( $joinTable );
1078 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1079 if ( $conds != '*' ) {
1080 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1084 $this->query( $sql, $fname );
1087 # Returns the size of a text field, or -1 for "unlimited"
1088 function textFieldSize( $table, $field ) {
1089 $table = $this->tableName( $table );
1090 $sql = "SELECT t.typname as ftype,a.atttypmod as size
1091 FROM pg_class c, pg_attribute a, pg_type t
1092 WHERE relname='$table' AND a.attrelid=c.oid AND
1093 a.atttypid=t.oid and a.attname='$field'";
1094 $res =$this->query($sql);
1095 $row=$this->fetchObject($res);
1096 if ($row->ftype
=="varchar") {
1101 $this->freeResult( $res );
1105 function limitResult($sql, $limit, $offset=false) {
1106 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
1109 function wasDeadlock() {
1110 return $this->lastErrno() == '40P01';
1113 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
1114 return $this->query( 'CREATE ' . ( $temporary ?
'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
1117 function timestamp( $ts=0 ) {
1118 return wfTimestamp(TS_POSTGRES
,$ts);
1122 * Return aggregated value function call
1124 function aggregateValue ($valuedata,$valuename='value') {
1129 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1130 // Ignore errors during error handling to avoid infinite recursion
1131 $ignore = $this->ignoreErrors( true );
1132 $this->mErrorCount++
;
1134 if ($ignore ||
$tempIgnore) {
1135 wfDebug("SQL ERROR (ignored): $error\n");
1136 $this->ignoreErrors( $ignore );
1139 $message = "A database error has occurred\n" .
1141 "Function: $fname\n" .
1142 "Error: $errno $error\n";
1143 throw new DBUnexpectedError($this, $message);
1148 * @return string wikitext of a link to the server software's web site
1150 function getSoftwareLink() {
1151 return "[http://www.postgresql.org/ PostgreSQL]";
1155 * @return string Version information from the database
1157 function getServerVersion() {
1158 $versionInfo = pg_version( $this->mConn
);
1159 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1160 // Old client, abort install
1161 $this->numeric_version
= '7.3 or earlier';
1162 } elseif ( isset( $versionInfo['server'] ) ) {
1164 $this->numeric_version
= $versionInfo['server'];
1166 // Bug 16937: broken pgsql extension from PHP<5.3
1167 $this->numeric_version
= pg_parameter_status( $this->mConn
, 'server_version' );
1169 return $this->numeric_version
;
1173 * Query whether a given relation exists (in the given schema, or the
1174 * default mw one if not given)
1176 function relationExists( $table, $types, $schema = false ) {
1177 global $wgDBmwschema;
1178 if ( !is_array( $types ) )
1179 $types = array( $types );
1181 $schema = $wgDBmwschema;
1182 $etable = $this->addQuotes( $table );
1183 $eschema = $this->addQuotes( $schema );
1184 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1185 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1186 . "AND c.relkind IN ('" . implode("','", $types) . "')";
1187 $res = $this->query( $SQL );
1188 $count = $res ?
$res->numRows() : 0;
1190 $this->freeResult( $res );
1191 return $count ?
true : false;
1195 * For backward compatibility, this function checks both tables and
1198 function tableExists( $table, $schema = false ) {
1199 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1202 function sequenceExists( $sequence, $schema = false ) {
1203 return $this->relationExists( $sequence, 'S', $schema );
1206 function triggerExists( $table, $trigger ) {
1207 global $wgDBmwschema;
1210 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1211 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1212 AND tgrelid=pg_class.oid
1213 AND nspname=%s AND relname=%s AND tgname=%s
1215 $res = $this->query(sprintf($q,
1216 $this->addQuotes($wgDBmwschema),
1217 $this->addQuotes($table),
1218 $this->addQuotes($trigger)));
1221 $rows = $res->numRows();
1222 $this->freeResult( $res );
1226 function ruleExists( $table, $rule ) {
1227 global $wgDBmwschema;
1228 $exists = $this->selectField("pg_rules", "rulename",
1229 array( "rulename" => $rule,
1230 "tablename" => $table,
1231 "schemaname" => $wgDBmwschema ) );
1232 return $exists === $rule;
1235 function constraintExists( $table, $constraint ) {
1236 global $wgDBmwschema;
1237 $SQL = sprintf("SELECT 1 FROM information_schema.table_constraints ".
1238 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1239 $this->addQuotes($wgDBmwschema),
1240 $this->addQuotes($table),
1241 $this->addQuotes($constraint));
1242 $res = $this->query($SQL);
1245 $rows = $res->numRows();
1246 $this->freeResult($res);
1251 * Query whether a given schema exists. Returns the name of the owner
1253 function schemaExists( $schema ) {
1254 $eschema = preg_replace("/'/", "''", $schema);
1255 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1256 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1257 $res = $this->query( $SQL );
1258 if ( $res && $res->numRows() ) {
1259 $row = $res->fetchObject();
1260 $owner = $row->rolname
;
1265 $this->freeResult($res);
1269 function fieldInfo( $table, $field ) {
1270 return PostgresField
::fromText($this, $table, $field);
1274 * pg_field_type() wrapper
1276 function fieldType( $res, $index ) {
1277 if ( $res instanceof ResultWrapper
) {
1278 $res = $res->result
;
1280 return pg_field_type( $res, $index );
1283 function begin( $fname = 'DatabasePostgres::begin' ) {
1284 $this->query( 'BEGIN', $fname );
1285 $this->mTrxLevel
= 1;
1288 function commit( $fname = 'DatabasePostgres::commit' ) {
1289 $this->query( 'COMMIT', $fname );
1290 $this->mTrxLevel
= 0;
1293 /* Not even sure why this is used in the main codebase... */
1294 function limitResultForUpdate( $sql, $num ) {
1298 function setup_database() {
1299 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
1301 // Make sure that we can write to the correct schema
1302 // If not, Postgres will happily and silently go to the next search_path item
1303 $ctest = "mediawiki_test_table";
1304 $safeschema = $this->quote_ident($wgDBmwschema);
1305 if ($this->tableExists($ctest, $wgDBmwschema)) {
1306 $this->doQuery("DROP TABLE $safeschema.$ctest");
1308 $SQL = "CREATE TABLE $safeschema.$ctest(a int)";
1309 $olde = error_reporting( 0 );
1310 $res = $this->doQuery($SQL);
1311 error_reporting( $olde );
1313 print "<b>FAILED</b>. Make sure that the user \"" . htmlspecialchars( $wgDBuser ) .
1314 "\" can write to the schema \"" . htmlspecialchars( $wgDBmwschema ) . "\"</li>\n";
1315 dieout(""); # Will close the main list <ul> and finish the page.
1317 $this->doQuery("DROP TABLE $safeschema.$ctest");
1319 $res = $this->sourceFile( "../maintenance/postgres/tables.sql" );
1320 if ($res === true) {
1321 print " done.</li>\n";
1323 print " <b>FAILED</b></li>\n";
1324 dieout( htmlspecialchars( $res ) );
1327 ## Update version information
1328 $mwv = $this->addQuotes($wgVersion);
1329 $pgv = $this->addQuotes($this->getServerVersion());
1330 $pgu = $this->addQuotes($this->mUser
);
1331 $mws = $this->addQuotes($wgDBmwschema);
1332 $tss = $this->addQuotes($wgDBts2schema);
1333 $pgp = $this->addQuotes($wgDBport);
1334 $dbn = $this->addQuotes($this->mDBname
);
1335 $ctype = $this->addQuotes( pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0) );
1337 echo "<li>Populating interwiki table... ";
1338 ## Avoid the non-standard "REPLACE INTO" syntax
1339 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1341 print "<b>FAILED</b></li>";
1342 dieout( "Could not find the interwiki.sql file" );
1344 ## We simply assume it is already empty as we have just created it
1345 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1346 while ( ! feof( $f ) ) {
1347 $line = fgets($f,1024);
1349 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
1352 $this->query("$SQL $matches[1],$matches[2])");
1354 print " successfully populated.</li>\n";
1356 $this->doQuery("COMMIT");
1359 function encodeBlob( $b ) {
1360 return new Blob ( pg_escape_bytea( $b ) ) ;
1363 function decodeBlob( $b ) {
1364 if ($b instanceof Blob
) {
1367 return pg_unescape_bytea( $b );
1370 function strencode( $s ) { ## Should not be called by us
1371 return pg_escape_string( $s );
1374 function addQuotes( $s ) {
1375 if ( is_null( $s ) ) {
1377 } else if ( is_bool( $s ) ) {
1378 return intval( $s );
1379 } else if ($s instanceof Blob
) {
1380 return "'".$s->fetch($s)."'";
1382 return "'" . pg_escape_string($s) . "'";
1385 function quote_ident( $s ) {
1386 return '"' . preg_replace( '/"/', '""', $s) . '"';
1390 * Postgres specific version of replaceVars.
1391 * Calls the parent version in Database.php
1395 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1397 * @return string SQL string
1399 protected function replaceVars( $ins ) {
1401 $ins = parent
::replaceVars( $ins );
1403 if ($this->numeric_version
>= 8.3) {
1404 // Thanks for not providing backwards-compatibility, 8.3
1405 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1408 if ($this->numeric_version
<= 8.1) { // Our minimum version
1409 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1416 * Various select options
1420 * @param $options Array: an associative array of options to be turned into
1421 * an SQL query, valid keys are listed in the function.
1424 function makeSelectOptions( $options ) {
1425 $preLimitTail = $postLimitTail = '';
1426 $startOpts = $useIndex = '';
1428 $noKeyOptions = array();
1429 foreach ( $options as $key => $option ) {
1430 if ( is_numeric( $key ) ) {
1431 $noKeyOptions[$option] = true;
1435 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY " . $options['GROUP BY'];
1436 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1437 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY " . $options['ORDER BY'];
1439 //if (isset($options['LIMIT'])) {
1440 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1441 // isset($options['OFFSET']) ? $options['OFFSET']
1445 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1446 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1447 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1449 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1452 function setFakeMaster( $enabled = true ) {}
1454 function getDBname() {
1455 return $this->mDBname
;
1458 function getServer() {
1459 return $this->mServer
;
1462 function buildConcat( $stringList ) {
1463 return implode( ' || ', $stringList );
1466 public function getSearchEngine() {
1467 return "SearchPostgres";
1469 } // end DatabasePostgres class