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 Database
{
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 = 'Database::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 = 'Database::indexExists' ) {
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 = 'Database::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
876 function tableName( $name ) {
877 # Replace reserved words with better ones
882 return 'pagecontent';
889 * Return the next in a sequence, save the value for retrieval via insertId()
891 function nextSequenceValue( $seqName ) {
892 $safeseq = preg_replace( "/'/", "''", $seqName );
893 $res = $this->query( "SELECT nextval('$safeseq')" );
894 $row = $this->fetchRow( $res );
895 $this->mInsertId
= $row[0];
896 $this->freeResult( $res );
897 return $this->mInsertId
;
901 * Return the current value of a sequence. Assumes it has ben nextval'ed in this session.
903 function currentSequenceValue( $seqName ) {
904 $safeseq = preg_replace( "/'/", "''", $seqName );
905 $res = $this->query( "SELECT currval('$safeseq')" );
906 $row = $this->fetchRow( $res );
908 $this->freeResult( $res );
913 * Postgres does not have a "USE INDEX" clause, so return an empty string
915 function useIndexClause( $index ) {
919 # REPLACE query wrapper
920 # Postgres simulates this with a DELETE followed by INSERT
921 # $row is the row to insert, an associative array
922 # $uniqueIndexes is an array of indexes. Each element may be either a
923 # field name or an array of field names
925 # It may be more efficient to leave off unique indexes which are unlikely to collide.
926 # However if you do this, you run the risk of encountering errors which wouldn't have
928 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
929 $table = $this->tableName( $table );
931 if (count($rows)==0) {
936 if ( !is_array( reset( $rows ) ) ) {
937 $rows = array( $rows );
940 foreach( $rows as $row ) {
941 # Delete rows which collide
942 if ( $uniqueIndexes ) {
943 $sql = "DELETE FROM $table WHERE ";
945 foreach ( $uniqueIndexes as $index ) {
952 if ( is_array( $index ) ) {
954 foreach ( $index as $col ) {
960 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
963 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
967 $this->query( $sql, $fname );
971 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
972 $this->makeList( $row, LIST_COMMA
) . ')';
973 $this->query( $sql, $fname );
977 # DELETE where the condition is a join
978 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
980 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
983 $delTable = $this->tableName( $delTable );
984 $joinTable = $this->tableName( $joinTable );
985 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
986 if ( $conds != '*' ) {
987 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
991 $this->query( $sql, $fname );
994 # Returns the size of a text field, or -1 for "unlimited"
995 function textFieldSize( $table, $field ) {
996 $table = $this->tableName( $table );
997 $sql = "SELECT t.typname as ftype,a.atttypmod as size
998 FROM pg_class c, pg_attribute a, pg_type t
999 WHERE relname='$table' AND a.attrelid=c.oid AND
1000 a.atttypid=t.oid and a.attname='$field'";
1001 $res =$this->query($sql);
1002 $row=$this->fetchObject($res);
1003 if ($row->ftype
=="varchar") {
1008 $this->freeResult( $res );
1012 function lowPriorityOption() {
1016 function limitResult($sql, $limit, $offset=false) {
1017 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
1021 * Returns an SQL expression for a simple conditional.
1022 * Uses CASE on Postgres
1024 * @param $cond String: SQL expression which will result in a boolean value
1025 * @param $trueVal String: SQL expression to return if true
1026 * @param $falseVal String: SQL expression to return if false
1027 * @return String: SQL fragment
1029 function conditional( $cond, $trueVal, $falseVal ) {
1030 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
1033 function wasDeadlock() {
1034 return $this->lastErrno() == '40P01';
1037 function timestamp( $ts=0 ) {
1038 return wfTimestamp(TS_POSTGRES
,$ts);
1042 * Return aggregated value function call
1044 function aggregateValue ($valuedata,$valuename='value') {
1049 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1050 // Ignore errors during error handling to avoid infinite recursion
1051 $ignore = $this->ignoreErrors( true );
1052 $this->mErrorCount++
;
1054 if ($ignore ||
$tempIgnore) {
1055 wfDebug("SQL ERROR (ignored): $error\n");
1056 $this->ignoreErrors( $ignore );
1059 $message = "A database error has occurred\n" .
1061 "Function: $fname\n" .
1062 "Error: $errno $error\n";
1063 throw new DBUnexpectedError($this, $message);
1068 * @return string wikitext of a link to the server software's web site
1070 function getSoftwareLink() {
1071 return "[http://www.postgresql.org/ PostgreSQL]";
1075 * @return string Version information from the database
1077 function getServerVersion() {
1078 $versionInfo = pg_version( $this->mConn
);
1079 if ( isset( $versionInfo['server'] ) ) {
1080 $this->numeric_version
= $versionInfo['server'];
1082 // There's no way to identify the precise version before 7.4, but
1083 // it doesn't matter anyway since we're just going to give an error.
1084 $this->numeric_version
= '7.3 or earlier';
1086 return $this->numeric_version
;
1090 * Query whether a given relation exists (in the given schema, or the
1091 * default mw one if not given)
1093 function relationExists( $table, $types, $schema = false ) {
1094 global $wgDBmwschema;
1095 if (!is_array($types))
1096 $types = array($types);
1098 $schema = $wgDBmwschema;
1099 $etable = $this->addQuotes($table);
1100 $eschema = $this->addQuotes($schema);
1101 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1102 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1103 . "AND c.relkind IN ('" . implode("','", $types) . "')";
1104 $res = $this->query( $SQL );
1105 $count = $res ?
$res->numRows() : 0;
1107 $this->freeResult( $res );
1108 return $count ?
true : false;
1112 * For backward compatibility, this function checks both tables and
1115 function tableExists ($table, $schema = false) {
1116 return $this->relationExists($table, array('r', 'v'), $schema);
1119 function sequenceExists ($sequence, $schema = false) {
1120 return $this->relationExists($sequence, 'S', $schema);
1123 function triggerExists($table, $trigger) {
1124 global $wgDBmwschema;
1127 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1128 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1129 AND tgrelid=pg_class.oid
1130 AND nspname=%s AND relname=%s AND tgname=%s
1132 $res = $this->query(sprintf($q,
1133 $this->addQuotes($wgDBmwschema),
1134 $this->addQuotes($table),
1135 $this->addQuotes($trigger)));
1138 $rows = $res->numRows();
1139 $this->freeResult($res);
1143 function ruleExists($table, $rule) {
1144 global $wgDBmwschema;
1145 $exists = $this->selectField("pg_rules", "rulename",
1146 array( "rulename" => $rule,
1147 "tablename" => $table,
1148 "schemaname" => $wgDBmwschema));
1149 return $exists === $rule;
1152 function constraintExists($table, $constraint) {
1153 global $wgDBmwschema;
1154 $SQL = sprintf("SELECT 1 FROM information_schema.table_constraints ".
1155 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1156 $this->addQuotes($wgDBmwschema),
1157 $this->addQuotes($table),
1158 $this->addQuotes($constraint));
1159 $res = $this->query($SQL);
1162 $rows = $res->numRows();
1163 $this->freeResult($res);
1168 * Query whether a given schema exists. Returns the name of the owner
1170 function schemaExists( $schema ) {
1171 $eschema = preg_replace("/'/", "''", $schema);
1172 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1173 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1174 $res = $this->query( $SQL );
1175 if ( $res && $res->numRows() ) {
1176 $row = $res->fetchObject();
1177 $owner = $row->rolname
;
1182 $this->freeResult($res);
1187 * Query whether a given column exists in the mediawiki schema
1189 function fieldExists( $table, $field, $fname = 'DatabasePostgres::fieldExists' ) {
1190 global $wgDBmwschema;
1191 $etable = preg_replace("/'/", "''", $table);
1192 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
1193 $ecol = preg_replace("/'/", "''", $field);
1194 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
1195 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
1196 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
1197 $res = $this->query( $SQL, $fname );
1198 $count = $res ?
$res->numRows() : 0;
1200 $this->freeResult( $res );
1204 function fieldInfo( $table, $field ) {
1205 return PostgresField
::fromText($this, $table, $field);
1209 * pg_field_type() wrapper
1211 function fieldType( $res, $index ) {
1212 if ( $res instanceof ResultWrapper
) {
1213 $res = $res->result
;
1215 return pg_field_type( $res, $index );
1218 function begin( $fname = 'DatabasePostgres::begin' ) {
1219 $this->query( 'BEGIN', $fname );
1220 $this->mTrxLevel
= 1;
1222 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
1225 function commit( $fname = 'DatabasePostgres::commit' ) {
1226 $this->query( 'COMMIT', $fname );
1227 $this->mTrxLevel
= 0;
1230 /* Not even sure why this is used in the main codebase... */
1231 function limitResultForUpdate($sql, $num) {
1235 function setup_database() {
1236 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
1238 // Make sure that we can write to the correct schema
1239 // If not, Postgres will happily and silently go to the next search_path item
1240 $ctest = "mediawiki_test_table";
1241 $safeschema = $this->quote_ident($wgDBmwschema);
1242 if ($this->tableExists($ctest, $wgDBmwschema)) {
1243 $this->doQuery("DROP TABLE $safeschema.$ctest");
1245 $SQL = "CREATE TABLE $safeschema.$ctest(a int)";
1246 $olde = error_reporting( 0 );
1247 $res = $this->doQuery($SQL);
1248 error_reporting( $olde );
1250 print "<b>FAILED</b>. Make sure that the user \"" . htmlspecialchars( $wgDBuser ) .
1251 "\" can write to the schema \"" . htmlspecialchars( $wgDBmwschema ) . "\"</li>\n";
1254 $this->doQuery("DROP TABLE $safeschema.$ctest");
1256 $res = dbsource( "../maintenance/postgres/tables.sql", $this);
1258 ## Update version information
1259 $mwv = $this->addQuotes($wgVersion);
1260 $pgv = $this->addQuotes($this->getServerVersion());
1261 $pgu = $this->addQuotes($this->mUser
);
1262 $mws = $this->addQuotes($wgDBmwschema);
1263 $tss = $this->addQuotes($wgDBts2schema);
1264 $pgp = $this->addQuotes($wgDBport);
1265 $dbn = $this->addQuotes($this->mDBname
);
1266 $ctype = $this->addQuotes( pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0) );
1268 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
1269 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
1271 "WHERE type = 'Creation'";
1274 ## Avoid the non-standard "REPLACE INTO" syntax
1275 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1277 dieout( "<li>Could not find the interwiki.sql file");
1279 ## We simply assume it is already empty as we have just created it
1280 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1281 while ( ! feof( $f ) ) {
1282 $line = fgets($f,1024);
1284 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
1287 $this->query("$SQL $matches[1],$matches[2])");
1289 print " (table interwiki successfully populated)...\n";
1291 $this->doQuery("COMMIT");
1294 function encodeBlob( $b ) {
1295 return new Blob ( pg_escape_bytea( $b ) ) ;
1298 function decodeBlob( $b ) {
1299 if ($b instanceof Blob
) {
1302 return pg_unescape_bytea( $b );
1305 function strencode( $s ) { ## Should not be called by us
1306 return pg_escape_string( $s );
1309 function addQuotes( $s ) {
1310 if ( is_null( $s ) ) {
1312 } else if ( is_bool( $s ) ) {
1313 return intval( $s );
1314 } else if ($s instanceof Blob
) {
1315 return "'".$s->fetch($s)."'";
1317 return "'" . pg_escape_string($s) . "'";
1320 function quote_ident( $s ) {
1321 return '"' . preg_replace( '/"/', '""', $s) . '"';
1324 /* For now, does nothing */
1325 function selectDB( $db ) {
1330 * Postgres specific version of replaceVars.
1331 * Calls the parent version in Database.php
1335 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1337 * @return string SQL string
1339 protected function replaceVars( $ins ) {
1341 $ins = parent
::replaceVars( $ins );
1343 if ($this->numeric_version
>= 8.3) {
1344 // Thanks for not providing backwards-compatibility, 8.3
1345 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1348 if ($this->numeric_version
<= 8.1) { // Our minimum version
1349 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1356 * Various select options
1360 * @param $options Array: an associative array of options to be turned into
1361 * an SQL query, valid keys are listed in the function.
1364 function makeSelectOptions( $options ) {
1365 $preLimitTail = $postLimitTail = '';
1366 $startOpts = $useIndex = '';
1368 $noKeyOptions = array();
1369 foreach ( $options as $key => $option ) {
1370 if ( is_numeric( $key ) ) {
1371 $noKeyOptions[$option] = true;
1375 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY " . $options['GROUP BY'];
1376 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1377 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY " . $options['ORDER BY'];
1379 //if (isset($options['LIMIT'])) {
1380 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1381 // isset($options['OFFSET']) ? $options['OFFSET']
1385 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1386 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1387 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1389 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1392 public function setTimeout( $timeout ) {
1393 // @todo fixme no-op
1397 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
1402 * How lagged is this slave?
1405 public function getLag() {
1406 # Not implemented for PostgreSQL
1410 function setFakeSlaveLag( $lag ) {}
1411 function setFakeMaster( $enabled = true ) {}
1413 function getDBname() {
1414 return $this->mDBname
;
1417 function getServer() {
1418 return $this->mServer
;
1421 function buildConcat( $stringList ) {
1422 return implode( ' || ', $stringList );
1425 /* These are not used yet, but we know we don't want the default version */
1427 public function lock( $lockName, $method ) {
1430 public function unlock( $lockName, $method ) {
1434 public function getSearchEngine() {
1435 return "SearchPostgres";
1438 } // end DatabasePostgres class