5 * This is the Postgres database abstraction layer.
9 private $name, $tablename, $type, $nullable, $max_length;
11 static function fromText($db, $table, $field) {
16 CASE WHEN typname = 'int2' THEN 'smallint'
17 WHEN typname = 'int4' THEN 'integer'
18 WHEN typname = 'int8' THEN 'bigint'
19 WHEN typname = 'bpchar' THEN 'char'
20 ELSE typname END AS typname,
22 FROM pg_class, pg_namespace, pg_attribute, pg_type
23 WHERE relnamespace=pg_namespace.oid
25 AND attrelid=pg_class.oid
26 AND atttypid=pg_type.oid
31 $res = $db->query(sprintf($q,
32 $db->addQuotes($wgDBmwschema),
33 $db->addQuotes($table),
34 $db->addQuotes($field)));
35 $row = $db->fetchObject($res);
38 $n = new PostgresField
;
39 $n->type
= $row->typname
;
40 $n->nullable
= ($row->attnotnull
== 'f');
42 $n->tablename
= $table;
43 $n->max_length
= $row->attlen
;
51 function tableName() {
52 return $this->tablename
;
60 return $this->nullable
;
63 function maxLength() {
64 return $this->max_length
;
71 class DatabasePostgres
extends DatabaseBase
{
72 var $mInsertId = null;
73 var $mLastResult = null;
74 var $numeric_version = null;
75 var $mAffectedRows = null;
77 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
78 $failFunction = false, $flags = 0 )
81 $this->mFailFunction
= $failFunction;
82 $this->mFlags
= $flags;
83 $this->open( $server, $user, $password, $dbName);
91 function cascadingDeletes() {
94 function cleanupTriggers() {
97 function strictIPs() {
100 function realTimestamps() {
103 function implicitGroupby() {
106 function implicitOrderby() {
109 function searchableIPs() {
112 function functionalIndexes() {
116 function hasConstraint( $name ) {
117 global $wgDBmwschema;
118 $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) ."'";
119 return $this->numRows($res = $this->doQuery($SQL));
122 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
124 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
128 * Usually aborts on failure
129 * If the failFunction is set to a non-zero integer, returns success
131 function open( $server, $user, $password, $dbName ) {
132 # Test for Postgres support, to avoid suppressed fatal error
133 if ( !function_exists( 'pg_connect' ) ) {
134 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" );
139 if (!strlen($user)) { ## e.g. the class is being loaded
143 $this->mServer
= $server;
144 $this->mPort
= $port = $wgDBport;
145 $this->mUser
= $user;
146 $this->mPassword
= $password;
147 $this->mDBname
= $dbName;
149 $connectVars = array(
152 'password' => $password );
153 if ($server!=false && $server!="") {
154 $connectVars['host'] = $server;
156 if ($port!=false && $port!="") {
157 $connectVars['port'] = $port;
159 $connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
161 $this->installErrorHandler();
162 $this->mConn
= pg_connect( $connectString );
163 $phpError = $this->restoreErrorHandler();
165 if ( $this->mConn
== false ) {
166 wfDebug( "DB connection error\n" );
167 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
168 wfDebug( $this->lastError()."\n" );
169 if ( !$this->mFailFunction
) {
170 throw new DBConnectionError( $this, $phpError );
176 $this->mOpened
= true;
178 global $wgCommandLineMode;
179 ## If called from the command-line (e.g. importDump), only show errors
180 if ($wgCommandLineMode) {
181 $this->doQuery( "SET client_min_messages = 'ERROR'" );
184 $this->doQuery( "SET client_encoding='UTF8'" );
186 global $wgDBmwschema, $wgDBts2schema;
187 if (isset( $wgDBmwschema ) && isset( $wgDBts2schema )
188 && $wgDBmwschema !== 'mediawiki'
189 && preg_match( '/^\w+$/', $wgDBmwschema )
190 && preg_match( '/^\w+$/', $wgDBts2schema )
192 $safeschema = $this->quote_ident($wgDBmwschema);
193 $safeschema2 = $this->quote_ident($wgDBts2schema);
194 $this->doQuery( "SET search_path = $safeschema, $wgDBts2schema, public" );
200 function makeConnectionString( $vars ) {
202 foreach ( $vars as $name => $value ) {
203 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
209 function initial_setup($password, $dbName) {
210 // If this is the initial connection, setup the schema stuff and possibly create the user
211 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBsuperuser, $wgDBmwschema, $wgDBts2schema;
213 print "<li>Checking the version of Postgres...";
214 $version = $this->getServerVersion();
216 if ($version < $PGMINVER) {
217 print "<b>FAILED</b>. Required version is $PGMINVER. You have " . htmlspecialchars( $version ) . "</li>\n";
220 print "version " . htmlspecialchars( $this->numeric_version
) . " is OK.</li>\n";
222 $safeuser = $this->quote_ident($wgDBuser);
223 // Are we connecting as a superuser for the first time?
224 if ($wgDBsuperuser) {
225 // Are we really a superuser? Check out our rights
227 CASE WHEN usesuper IS TRUE THEN
228 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
229 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
231 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
232 $rows = $this->numRows($res = $this->doQuery($SQL));
234 print "<li>ERROR: Could not read permissions for user \"" . htmlspecialchars( $wgDBsuperuser ) . "\"</li>\n";
237 $perms = pg_fetch_result($res, 0, 0);
239 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
240 $rows = $this->numRows($this->doQuery($SQL));
242 print "<li>User \"" . htmlspecialchars( $wgDBuser ) . "\" already exists, skipping account creation.</li>";
245 if ($perms != 1 and $perms != 3) {
246 print "<li>ERROR: the user \"" . htmlspecialchars( $wgDBsuperuser ) . "\" cannot create other users. ";
247 print 'Please use a different Postgres user.</li>';
250 print "<li>Creating user <b>" . htmlspecialchars( $wgDBuser ) . "</b>...";
251 $safepass = $this->addQuotes($wgDBpassword);
252 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
253 $this->doQuery($SQL);
256 // User now exists, check out the database
257 if ($dbName != $wgDBname) {
258 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
259 $rows = $this->numRows($this->doQuery($SQL));
261 print "<li>Database \"" . htmlspecialchars( $wgDBname ) . "\" already exists, skipping database creation.</li>";
265 print "<li>ERROR: the user \"" . htmlspecialchars( $wgDBsuperuser ) . "\" cannot create databases. ";
266 print 'Please use a different Postgres user.</li>';
269 print "<li>Creating database <b>" . htmlspecialchars( $wgDBname ) . "</b>...";
270 $safename = $this->quote_ident($wgDBname);
271 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
272 $this->doQuery($SQL);
274 // Hopefully tsearch2 and plpgsql are in template1...
277 // Reconnect to check out tsearch2 rights for this user
278 print "<li>Connecting to \"" . htmlspecialchars( $wgDBname ) . "\" as superuser \"" .
279 htmlspecialchars( $wgDBsuperuser ) . "\" to check rights...";
281 $connectVars = array();
282 if ($this->mServer
!=false && $this->mServer
!="") {
283 $connectVars['host'] = $this->mServer
;
285 if ($this->mPort
!=false && $this->mPort
!="") {
286 $connectVars['port'] = $this->mPort
;
288 $connectVars['dbname'] = $wgDBname;
289 $connectVars['user'] = $wgDBsuperuser;
290 $connectVars['password'] = $password;
292 @$this->mConn
= pg_connect( $this->makeConnectionString( $connectVars ) );
293 if ( $this->mConn
== false ) {
294 print "<b>FAILED TO CONNECT!</b></li>";
300 if ($this->numeric_version
< 8.3) {
302 print "<li>Checking that tsearch2 is installed in the database \"" .
303 htmlspecialchars( $wgDBname ) . "\"...";
304 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
305 print "<b>FAILED</b>. tsearch2 must be installed in the database \"" .
306 htmlspecialchars( $wgDBname ) . "\".";
307 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
308 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
312 print "<li>Ensuring that user \"" . htmlspecialchars( $wgDBuser ) .
313 "\" has select rights on the tsearch2 tables...";
314 foreach (array('cfg','cfgmap','dict','parser') as $table) {
315 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
316 $this->doQuery($SQL);
321 // Setup the schema for this user if needed
322 $result = $this->schemaExists($wgDBmwschema);
323 $safeschema = $this->quote_ident($wgDBmwschema);
325 print "<li>Creating schema <b>" . htmlspecialchars( $wgDBmwschema ) . "</b> ...";
326 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
328 print "<b>FAILED</b>.</li>\n";
334 print "<li>Schema already exists, explicitly granting rights...\n";
335 $safeschema2 = $this->addQuotes($wgDBmwschema);
336 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
337 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
338 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
339 "AND p.relkind IN ('r','S','v')\n";
341 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
342 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
343 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
344 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
345 $res = $this->doQuery($SQL);
347 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
350 $this->doQuery("SET search_path = $safeschema");
351 $rows = $this->numRows($res);
354 $this->doQuery(pg_fetch_result($res, $rows, 0));
359 // Install plpgsql if needed
360 $this->setup_plpgsql();
363 return true; // Reconnect as regular user
367 if (!defined('POSTGRES_SEARCHPATH')) {
369 if ($this->numeric_version
< 8.3) {
370 // Do we have the basic tsearch2 table?
371 print "<li>Checking for tsearch2 in the schema \"" . htmlspecialchars( $wgDBts2schema ) . "\"...";
372 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
373 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
374 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
375 print " for instructions.</li>\n";
380 // Does this user have the rights to the tsearch2 tables?
381 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
382 print "<li>Checking tsearch2 permissions...";
383 // Let's check all four, just to be safe
384 error_reporting( 0 );
385 $ts2tables = array('cfg','cfgmap','dict','parser');
386 $safetsschema = $this->quote_ident($wgDBts2schema);
387 foreach ( $ts2tables AS $tname ) {
388 $SQL = "SELECT count(*) FROM $safetsschema.pg_ts_$tname";
389 $res = $this->doQuery($SQL);
391 print "<b>FAILED</b> to access " . htmlspecialchars( "pg_ts_$tname" ) .
392 ". Make sure that the user \"". htmlspecialchars( $wgDBuser ) .
393 "\" has SELECT access to all four tsearch2 tables</li>\n";
397 $SQL = "SELECT ts_name FROM $safetsschema.pg_ts_cfg WHERE locale = " . $this->addQuotes( $ctype ) ;
398 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
399 $res = $this->doQuery($SQL);
400 error_reporting( E_ALL
);
402 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
407 // Will the current locale work? Can we force it to?
408 print "<li>Verifying tsearch2 locale with " . htmlspecialchars( $ctype ) . "...";
409 $rows = $this->numRows($res);
412 print "<b>not found</b></li>\n";
413 print "<li>Attempting to set default tsearch2 locale to \"" . htmlspecialchars( $ctype ) . "\"...";
417 $tsname = pg_fetch_result($res, 0, 0);
418 if ($tsname != 'default') {
419 print "<b>not set to default (" . htmlspecialchars( $tsname ) . ")</b>";
420 print "<li>Attempting to change tsearch2 default locale to \"" .
421 htmlspecialchars( $ctype ) . "\"...";
426 $SQL = "UPDATE $safetsschema.pg_ts_cfg SET locale = " . $this->addQuotes( $ctype ) . " WHERE ts_name = 'default'";
427 $res = $this->doQuery($SQL);
429 print "<b>FAILED</b>. ";
430 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"" .
431 htmlspecialchars( $ctype ) . "\"</li>\n";
437 // Final test: try out a simple tsearch2 query
438 $SQL = "SELECT $safetsschema.to_tsvector('default','MediaWiki tsearch2 testing')";
439 $res = $this->doQuery($SQL);
441 print "<b>FAILED</b>. Specifically, \"" . htmlspecialchars( $SQL ) . "\" did not work.</li>";
447 // Install plpgsql if needed
448 $this->setup_plpgsql();
450 // Does the schema already exist? Who owns it?
451 $result = $this->schemaExists($wgDBmwschema);
453 print "<li>Creating schema <b>" . htmlspecialchars( $wgDBmwschema ) . "</b> ...";
454 error_reporting( 0 );
455 $safeschema = $this->quote_ident($wgDBmwschema);
456 $result = $this->doQuery("CREATE SCHEMA $safeschema");
457 error_reporting( E_ALL
);
459 print "<b>FAILED</b>. The user \"" . htmlspecialchars( $wgDBuser ) .
460 "\" must be able to access the schema. ".
461 "You can try making them the owner of the database, or try creating the schema with a ".
462 "different user, and then grant access to the \"" .
463 htmlspecialchars( $wgDBuser ) . "\" user.</li>\n";
468 else if ($result != $wgDBuser) {
469 print "<li>Schema \"" . htmlspecialchars( $wgDBmwschema ) . "\" exists but is not owned by \"" .
470 htmlspecialchars( $wgDBuser ) . "\". Not ideal.</li>\n";
473 print "<li>Schema \"" . htmlspecialchars( $wgDBmwschema ) . "\" exists and is owned by \"" .
474 htmlspecialchars( $wgDBuser ) . "\". Excellent.</li>\n";
477 // Always return GMT time to accomodate the existing integer-based timestamp assumption
478 print "<li>Setting the timezone to GMT for user \"" . htmlspecialchars( $wgDBuser ) . "\" ...";
479 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
480 $result = pg_query($this->mConn
, $SQL);
482 print "<b>FAILED</b>.</li>\n";
486 // Set for the rest of this session
487 $SQL = "SET timezone = 'GMT'";
488 $result = pg_query($this->mConn
, $SQL);
490 print "<li>Failed to set timezone</li>\n";
494 print "<li>Setting the datestyle to ISO, YMD for user \"" . htmlspecialchars( $wgDBuser ) . "\" ...";
495 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
496 $result = pg_query($this->mConn
, $SQL);
498 print "<b>FAILED</b>.</li>\n";
502 // Set for the rest of this session
503 $SQL = "SET datestyle = 'ISO, YMD'";
504 $result = pg_query($this->mConn
, $SQL);
506 print "<li>Failed to set datestyle</li>\n";
510 // Fix up the search paths if needed
511 print "<li>Setting the search path for user \"" . htmlspecialchars( $wgDBuser ) . "\" ...";
512 $path = $this->quote_ident($wgDBmwschema);
513 if ($wgDBts2schema !== $wgDBmwschema)
514 $path .= ", ". $this->quote_ident($wgDBts2schema);
515 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
517 $SQL = "ALTER USER $safeuser SET search_path = $path";
518 $result = pg_query($this->mConn
, $SQL);
520 print "<b>FAILED</b>.</li>\n";
524 // Set for the rest of this session
525 $SQL = "SET search_path = $path";
526 $result = pg_query($this->mConn
, $SQL);
528 print "<li>Failed to set search_path</li>\n";
531 define( "POSTGRES_SEARCHPATH", $path );
536 function setup_plpgsql() {
537 print "<li>Checking for Pl/Pgsql ...";
538 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
539 $rows = $this->numRows($this->doQuery($SQL));
541 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
542 print "not installed. Attempting to install Pl/Pgsql ...";
543 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
544 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
545 $rows = $this->numRows($this->doQuery($SQL));
547 $olde = error_reporting(0);
548 error_reporting($olde - E_WARNING
);
549 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
550 error_reporting($olde);
552 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>" .
553 htmlspecialchars( $wgDBname ) . "</tt></li>";
558 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>" .
559 htmlspecialchars( $wgDBname ) . "</tt></li>";
568 * Closes a database connection, if it is open
569 * Returns success, true if already closed
572 $this->mOpened
= false;
573 if ( $this->mConn
) {
574 return pg_close( $this->mConn
);
580 function doQuery( $sql ) {
581 if (function_exists('mb_convert_encoding')) {
582 $sql = mb_convert_encoding($sql,'UTF-8');
584 $this->mLastResult
= pg_query( $this->mConn
, $sql);
585 $this->mAffectedRows
= null; // use pg_affected_rows(mLastResult)
586 return $this->mLastResult
;
589 function queryIgnore( $sql, $fname = '' ) {
590 return $this->query( $sql, $fname, true );
593 function freeResult( $res ) {
594 if ( $res instanceof ResultWrapper
) {
597 if ( !@pg_free_result
( $res ) ) {
598 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
602 function fetchObject( $res ) {
603 if ( $res instanceof ResultWrapper
) {
606 @$row = pg_fetch_object( $res );
607 # FIXME: HACK HACK HACK HACK debug
610 # hashar : not sure if the following test really trigger if the object
612 if( pg_last_error($this->mConn
) ) {
613 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
618 function fetchRow( $res ) {
619 if ( $res instanceof ResultWrapper
) {
622 @$row = pg_fetch_array( $res );
623 if( pg_last_error($this->mConn
) ) {
624 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
629 function numRows( $res ) {
630 if ( $res instanceof ResultWrapper
) {
633 @$n = pg_num_rows( $res );
634 if( pg_last_error($this->mConn
) ) {
635 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
639 function numFields( $res ) {
640 if ( $res instanceof ResultWrapper
) {
643 return pg_num_fields( $res );
645 function fieldName( $res, $n ) {
646 if ( $res instanceof ResultWrapper
) {
649 return pg_field_name( $res, $n );
653 * This must be called after nextSequenceVal
655 function insertId() {
656 return $this->mInsertId
;
659 function dataSeek( $res, $row ) {
660 if ( $res instanceof ResultWrapper
) {
663 return pg_result_seek( $res, $row );
666 function lastError() {
667 if ( $this->mConn
) {
668 return pg_last_error();
671 return "No database connection";
674 function lastErrno() {
675 return pg_last_error() ?
1 : 0;
678 function affectedRows() {
679 if ( !is_null( $this->mAffectedRows
) ) {
680 // Forced result for simulated queries
681 return $this->mAffectedRows
;
683 if( empty( $this->mLastResult
) )
685 return pg_affected_rows( $this->mLastResult
);
689 * Estimate rows in dataset
690 * Returns estimated count, based on EXPLAIN output
691 * This is not necessarily an accurate estimate, so use sparingly
692 * Returns -1 if count cannot be found
693 * Takes same arguments as Database::select()
696 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
697 $options['EXPLAIN'] = true;
698 $res = $this->select( $table, $vars, $conds, $fname, $options );
701 $row = $this->fetchRow( $res );
703 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
706 $this->freeResult($res);
713 * Returns information about an index
714 * If errors are explicitly ignored, returns NULL on failure
716 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
717 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
718 $res = $this->query( $sql, $fname );
722 while ( $row = $this->fetchObject( $res ) ) {
723 if ( $row->indexname
== $this->indexName( $index ) ) {
730 function indexUnique ($table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
731 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
732 " AND indexdef LIKE 'CREATE UNIQUE%(" .
733 $this->strencode( $this->indexName( $index ) ) .
735 $res = $this->query( $sql, $fname );
738 while ($row = $this->fetchObject( $res ))
745 * INSERT wrapper, inserts an array into a table
747 * $args may be a single associative array, or an array of these with numeric keys,
748 * for multi-row insert (Postgres version 8.2 and above only).
750 * @param $table String: Name of the table to insert to.
751 * @param $args Array: Items to insert into the table.
752 * @param $fname String: Name of the function, for profiling
753 * @param $options String or Array. Valid options: IGNORE
755 * @return bool Success of insert operation. IGNORE always returns true.
757 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
760 if ( !count( $args ) ) {
764 $table = $this->tableName( $table );
765 if (! isset( $wgDBversion ) ) {
766 $wgDBversion = $this->getServerVersion();
769 if ( !is_array( $options ) )
770 $options = array( $options );
772 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
774 $keys = array_keys( $args[0] );
778 $keys = array_keys( $args );
781 // If IGNORE is set, we use savepoints to emulate mysql's behavior
782 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
784 // If we are not in a transaction, we need to be for savepoint trickery
787 if (! $this->mTrxLevel
) {
791 $olde = error_reporting( 0 );
792 // For future use, we may want to track the number of actual inserts
793 // Right now, insert (all writes) simply return true/false
794 $numrowsinserted = 0;
797 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
800 if ( $wgDBversion >= 8.2 && !$ignore ) {
802 foreach ( $args as $row ) {
808 $sql .= '(' . $this->makeList( $row ) . ')';
810 $res = (bool)$this->query( $sql, $fname, $ignore );
815 foreach ( $args as $row ) {
817 $tempsql .= '(' . $this->makeList( $row ) . ')';
820 pg_query($this->mConn
, "SAVEPOINT $ignore");
823 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
826 $bar = pg_last_error();
828 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
831 pg_query( $this->mConn
, "RELEASE $ignore" );
836 // If any of them fail, we fail overall for this function call
837 // Note that this will be ignored if IGNORE is set
844 // Not multi, just a lone insert
846 pg_query($this->mConn
, "SAVEPOINT $ignore");
849 $sql .= '(' . $this->makeList( $args ) . ')';
850 $res = (bool)$this->query( $sql, $fname, $ignore );
852 $bar = pg_last_error();
854 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
857 pg_query( $this->mConn
, "RELEASE $ignore" );
863 $olde = error_reporting( $olde );
868 // Set the affected row count for the whole operation
869 $this->mAffectedRows
= $numrowsinserted;
871 // IGNORE always returns true
881 * INSERT SELECT wrapper
882 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
883 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
884 * $conds may be "*" to copy the whole table
885 * srcTable may be an array of tables.
886 * @todo FIXME: implement this a little better (seperate select/insert)?
888 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
889 $insertOptions = array(), $selectOptions = array() )
891 $destTable = $this->tableName( $destTable );
893 // If IGNORE is set, we use savepoints to emulate mysql's behavior
894 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
896 if( is_array( $insertOptions ) ) {
897 $insertOptions = implode( ' ', $insertOptions );
899 if( !is_array( $selectOptions ) ) {
900 $selectOptions = array( $selectOptions );
902 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
903 if( is_array( $srcTable ) ) {
904 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
906 $srcTable = $this->tableName( $srcTable );
909 // If we are not in a transaction, we need to be for savepoint trickery
912 if( !$this->mTrxLevel
) {
916 $olde = error_reporting( 0 );
917 $numrowsinserted = 0;
918 pg_query( $this->mConn
, "SAVEPOINT $ignore");
921 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
922 " SELECT $startOpts " . implode( ',', $varMap ) .
923 " FROM $srcTable $useIndex";
925 if ( $conds != '*') {
926 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
929 $sql .= " $tailOpts";
931 $res = (bool)$this->query( $sql, $fname, $ignore );
933 $bar = pg_last_error();
934 if( $bar != false ) {
935 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
937 pg_query( $this->mConn
, "RELEASE $ignore" );
940 $olde = error_reporting( $olde );
945 // Set the affected row count for the whole operation
946 $this->mAffectedRows
= $numrowsinserted;
948 // IGNORE always returns true
955 function tableName( $name ) {
956 # Replace reserved words with better ones
961 return 'pagecontent';
968 * Return the next in a sequence, save the value for retrieval via insertId()
970 function nextSequenceValue( $seqName ) {
971 $safeseq = preg_replace( "/'/", "''", $seqName );
972 $res = $this->query( "SELECT nextval('$safeseq')" );
973 $row = $this->fetchRow( $res );
974 $this->mInsertId
= $row[0];
975 $this->freeResult( $res );
976 return $this->mInsertId
;
980 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
982 function currentSequenceValue( $seqName ) {
983 $safeseq = preg_replace( "/'/", "''", $seqName );
984 $res = $this->query( "SELECT currval('$safeseq')" );
985 $row = $this->fetchRow( $res );
987 $this->freeResult( $res );
991 # REPLACE query wrapper
992 # Postgres simulates this with a DELETE followed by INSERT
993 # $row is the row to insert, an associative array
994 # $uniqueIndexes is an array of indexes. Each element may be either a
995 # field name or an array of field names
997 # It may be more efficient to leave off unique indexes which are unlikely to collide.
998 # However if you do this, you run the risk of encountering errors which wouldn't have
1000 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
1001 $table = $this->tableName( $table );
1003 if (count($rows)==0) {
1008 if ( !is_array( reset( $rows ) ) ) {
1009 $rows = array( $rows );
1012 foreach( $rows as $row ) {
1013 # Delete rows which collide
1014 if ( $uniqueIndexes ) {
1015 $sql = "DELETE FROM $table WHERE ";
1017 foreach ( $uniqueIndexes as $index ) {
1024 if ( is_array( $index ) ) {
1026 foreach ( $index as $col ) {
1032 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
1035 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1039 $this->query( $sql, $fname );
1042 # Now insert the row
1043 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
1044 $this->makeList( $row, LIST_COMMA
) . ')';
1045 $this->query( $sql, $fname );
1049 # DELETE where the condition is a join
1050 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
1052 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
1055 $delTable = $this->tableName( $delTable );
1056 $joinTable = $this->tableName( $joinTable );
1057 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1058 if ( $conds != '*' ) {
1059 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1063 $this->query( $sql, $fname );
1066 # Returns the size of a text field, or -1 for "unlimited"
1067 function textFieldSize( $table, $field ) {
1068 $table = $this->tableName( $table );
1069 $sql = "SELECT t.typname as ftype,a.atttypmod as size
1070 FROM pg_class c, pg_attribute a, pg_type t
1071 WHERE relname='$table' AND a.attrelid=c.oid AND
1072 a.atttypid=t.oid and a.attname='$field'";
1073 $res =$this->query($sql);
1074 $row=$this->fetchObject($res);
1075 if ($row->ftype
=="varchar") {
1080 $this->freeResult( $res );
1084 function limitResult($sql, $limit, $offset=false) {
1085 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
1088 function wasDeadlock() {
1089 return $this->lastErrno() == '40P01';
1092 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
1093 return $this->query( 'CREATE ' . ( $temporary ?
'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
1096 function timestamp( $ts=0 ) {
1097 return wfTimestamp(TS_POSTGRES
,$ts);
1101 * Return aggregated value function call
1103 function aggregateValue ($valuedata,$valuename='value') {
1108 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1109 // Ignore errors during error handling to avoid infinite recursion
1110 $ignore = $this->ignoreErrors( true );
1111 $this->mErrorCount++
;
1113 if ($ignore ||
$tempIgnore) {
1114 wfDebug("SQL ERROR (ignored): $error\n");
1115 $this->ignoreErrors( $ignore );
1118 $message = "A database error has occurred\n" .
1120 "Function: $fname\n" .
1121 "Error: $errno $error\n";
1122 throw new DBUnexpectedError($this, $message);
1127 * @return string wikitext of a link to the server software's web site
1129 function getSoftwareLink() {
1130 return "[http://www.postgresql.org/ PostgreSQL]";
1134 * @return string Version information from the database
1136 function getServerVersion() {
1137 $versionInfo = pg_version( $this->mConn
);
1138 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1139 // Old client, abort install
1140 $this->numeric_version
= '7.3 or earlier';
1141 } elseif ( isset( $versionInfo['server'] ) ) {
1143 $this->numeric_version
= $versionInfo['server'];
1145 // Bug 16937: broken pgsql extension from PHP<5.3
1146 $this->numeric_version
= pg_parameter_status( $this->mConn
, 'server_version' );
1148 return $this->numeric_version
;
1152 * Query whether a given relation exists (in the given schema, or the
1153 * default mw one if not given)
1155 function relationExists( $table, $types, $schema = false ) {
1156 global $wgDBmwschema;
1157 if ( !is_array( $types ) )
1158 $types = array( $types );
1160 $schema = $wgDBmwschema;
1161 $etable = $this->addQuotes( $table );
1162 $eschema = $this->addQuotes( $schema );
1163 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1164 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1165 . "AND c.relkind IN ('" . implode("','", $types) . "')";
1166 $res = $this->query( $SQL );
1167 $count = $res ?
$res->numRows() : 0;
1169 $this->freeResult( $res );
1170 return $count ?
true : false;
1174 * For backward compatibility, this function checks both tables and
1177 function tableExists( $table, $schema = false ) {
1178 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1181 function sequenceExists( $sequence, $schema = false ) {
1182 return $this->relationExists( $sequence, 'S', $schema );
1185 function triggerExists( $table, $trigger ) {
1186 global $wgDBmwschema;
1189 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1190 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1191 AND tgrelid=pg_class.oid
1192 AND nspname=%s AND relname=%s AND tgname=%s
1194 $res = $this->query(sprintf($q,
1195 $this->addQuotes($wgDBmwschema),
1196 $this->addQuotes($table),
1197 $this->addQuotes($trigger)));
1200 $rows = $res->numRows();
1201 $this->freeResult( $res );
1205 function ruleExists( $table, $rule ) {
1206 global $wgDBmwschema;
1207 $exists = $this->selectField("pg_rules", "rulename",
1208 array( "rulename" => $rule,
1209 "tablename" => $table,
1210 "schemaname" => $wgDBmwschema ) );
1211 return $exists === $rule;
1214 function constraintExists( $table, $constraint ) {
1215 global $wgDBmwschema;
1216 $SQL = sprintf("SELECT 1 FROM information_schema.table_constraints ".
1217 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1218 $this->addQuotes($wgDBmwschema),
1219 $this->addQuotes($table),
1220 $this->addQuotes($constraint));
1221 $res = $this->query($SQL);
1224 $rows = $res->numRows();
1225 $this->freeResult($res);
1230 * Query whether a given schema exists. Returns the name of the owner
1232 function schemaExists( $schema ) {
1233 $eschema = preg_replace("/'/", "''", $schema);
1234 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1235 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1236 $res = $this->query( $SQL );
1237 if ( $res && $res->numRows() ) {
1238 $row = $res->fetchObject();
1239 $owner = $row->rolname
;
1244 $this->freeResult($res);
1249 * Query whether a given column exists in the mediawiki schema
1251 function fieldExists( $table, $field, $fname = 'DatabasePostgres::fieldExists' ) {
1252 global $wgDBmwschema;
1253 $etable = preg_replace("/'/", "''", $table);
1254 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
1255 $ecol = preg_replace("/'/", "''", $field);
1256 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
1257 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
1258 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
1259 $res = $this->query( $SQL, $fname );
1260 $count = $res ?
$res->numRows() : 0;
1262 $this->freeResult( $res );
1266 function fieldInfo( $table, $field ) {
1267 return PostgresField
::fromText($this, $table, $field);
1271 * pg_field_type() wrapper
1273 function fieldType( $res, $index ) {
1274 if ( $res instanceof ResultWrapper
) {
1275 $res = $res->result
;
1277 return pg_field_type( $res, $index );
1280 function begin( $fname = 'DatabasePostgres::begin' ) {
1281 $this->query( 'BEGIN', $fname );
1282 $this->mTrxLevel
= 1;
1284 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
1287 function commit( $fname = 'DatabasePostgres::commit' ) {
1288 $this->query( 'COMMIT', $fname );
1289 $this->mTrxLevel
= 0;
1292 /* Not even sure why this is used in the main codebase... */
1293 function limitResultForUpdate( $sql, $num ) {
1297 function setup_database() {
1298 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
1300 // Make sure that we can write to the correct schema
1301 // If not, Postgres will happily and silently go to the next search_path item
1302 $ctest = "mediawiki_test_table";
1303 $safeschema = $this->quote_ident($wgDBmwschema);
1304 if ($this->tableExists($ctest, $wgDBmwschema)) {
1305 $this->doQuery("DROP TABLE $safeschema.$ctest");
1307 $SQL = "CREATE TABLE $safeschema.$ctest(a int)";
1308 $olde = error_reporting( 0 );
1309 $res = $this->doQuery($SQL);
1310 error_reporting( $olde );
1312 print "<b>FAILED</b>. Make sure that the user \"" . htmlspecialchars( $wgDBuser ) .
1313 "\" can write to the schema \"" . htmlspecialchars( $wgDBmwschema ) . "\"</li>\n";
1316 $this->doQuery("DROP TABLE $safeschema.$ctest");
1318 $res = $this->sourceFile( "../maintenance/postgres/tables.sql" );
1320 ## Update version information
1321 $mwv = $this->addQuotes($wgVersion);
1322 $pgv = $this->addQuotes($this->getServerVersion());
1323 $pgu = $this->addQuotes($this->mUser
);
1324 $mws = $this->addQuotes($wgDBmwschema);
1325 $tss = $this->addQuotes($wgDBts2schema);
1326 $pgp = $this->addQuotes($wgDBport);
1327 $dbn = $this->addQuotes($this->mDBname
);
1328 $ctype = $this->addQuotes( pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0) );
1330 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
1331 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
1333 "WHERE type = 'Creation'";
1336 ## Avoid the non-standard "REPLACE INTO" syntax
1337 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1339 dieout( "<li>Could not find the interwiki.sql file");
1341 ## We simply assume it is already empty as we have just created it
1342 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1343 while ( ! feof( $f ) ) {
1344 $line = fgets($f,1024);
1346 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
1349 $this->query("$SQL $matches[1],$matches[2])");
1351 print " (table interwiki successfully populated)...\n";
1353 $this->doQuery("COMMIT");
1356 function encodeBlob( $b ) {
1357 return new Blob ( pg_escape_bytea( $b ) ) ;
1360 function decodeBlob( $b ) {
1361 if ($b instanceof Blob
) {
1364 return pg_unescape_bytea( $b );
1367 function strencode( $s ) { ## Should not be called by us
1368 return pg_escape_string( $s );
1371 function addQuotes( $s ) {
1372 if ( is_null( $s ) ) {
1374 } else if ( is_bool( $s ) ) {
1375 return intval( $s );
1376 } else if ($s instanceof Blob
) {
1377 return "'".$s->fetch($s)."'";
1379 return "'" . pg_escape_string($s) . "'";
1382 function quote_ident( $s ) {
1383 return '"' . preg_replace( '/"/', '""', $s) . '"';
1387 * Postgres specific version of replaceVars.
1388 * Calls the parent version in Database.php
1392 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1394 * @return string SQL string
1396 protected function replaceVars( $ins ) {
1398 $ins = parent
::replaceVars( $ins );
1400 if ($this->numeric_version
>= 8.3) {
1401 // Thanks for not providing backwards-compatibility, 8.3
1402 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1405 if ($this->numeric_version
<= 8.1) { // Our minimum version
1406 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1413 * Various select options
1417 * @param $options Array: an associative array of options to be turned into
1418 * an SQL query, valid keys are listed in the function.
1421 function makeSelectOptions( $options ) {
1422 $preLimitTail = $postLimitTail = '';
1423 $startOpts = $useIndex = '';
1425 $noKeyOptions = array();
1426 foreach ( $options as $key => $option ) {
1427 if ( is_numeric( $key ) ) {
1428 $noKeyOptions[$option] = true;
1432 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY " . $options['GROUP BY'];
1433 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1434 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY " . $options['ORDER BY'];
1436 //if (isset($options['LIMIT'])) {
1437 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1438 // isset($options['OFFSET']) ? $options['OFFSET']
1442 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1443 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1444 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1446 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1450 * How lagged is this slave?
1453 public function getLag() {
1454 # Not implemented for PostgreSQL
1458 function setFakeSlaveLag( $lag ) {}
1459 function setFakeMaster( $enabled = true ) {}
1461 function getDBname() {
1462 return $this->mDBname
;
1465 function getServer() {
1466 return $this->mServer
;
1469 function buildConcat( $stringList ) {
1470 return implode( ' || ', $stringList );
1473 public function getSearchEngine() {
1474 return "SearchPostgres";
1476 } // end DatabasePostgres class