3 * This is the Postgres database abstraction layer.
10 private $name, $tablename, $type, $nullable, $max_length, $deferred, $deferrable, $conname;
12 static function fromText($db, $table, $field) {
17 attnotnull, attlen, COALESCE(conname, '') AS conname,
18 COALESCE(condeferred, 'f') AS deferred,
19 COALESCE(condeferrable, 'f') AS deferrable,
20 CASE WHEN typname = 'int2' THEN 'smallint'
21 WHEN typname = 'int4' THEN 'integer'
22 WHEN typname = 'int8' THEN 'bigint'
23 WHEN typname = 'bpchar' THEN 'char'
24 ELSE typname END AS typname
26 JOIN pg_namespace n ON (n.oid = c.relnamespace)
27 JOIN pg_attribute a ON (a.attrelid = c.oid)
28 JOIN pg_type t ON (t.oid = a.atttypid)
29 LEFT JOIN pg_constraint o ON (o.conrelid = c.oid AND a.attnum = ANY(o.conkey) AND o.contype = 'f')
36 $table = $db->tableName( $table );
37 $res = $db->query(sprintf($q,
38 $db->addQuotes($wgDBmwschema),
39 $db->addQuotes($table),
40 $db->addQuotes($field)));
41 $row = $db->fetchObject($res);
44 $n = new PostgresField
;
45 $n->type
= $row->typname
;
46 $n->nullable
= ($row->attnotnull
== 'f');
48 $n->tablename
= $table;
49 $n->max_length
= $row->attlen
;
50 $n->deferrable
= ($row->deferrable
== 't');
51 $n->deferred
= ($row->deferred
== 't');
52 $n->conname
= $row->conname
;
60 function tableName() {
61 return $this->tablename
;
69 return $this->nullable
;
72 function maxLength() {
73 return $this->max_length
;
76 function is_deferrable() {
77 return $this->deferrable
;
80 function is_deferred() {
81 return $this->deferred
;
85 return $this->conname
;
93 class DatabasePostgres
extends DatabaseBase
{
94 var $mInsertId = null;
95 var $mLastResult = null;
96 var $numeric_version = null;
97 var $mAffectedRows = null;
99 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
102 $this->mFlags
= $flags;
103 $this->open( $server, $user, $password, $dbName);
110 function cascadingDeletes() {
113 function cleanupTriggers() {
116 function strictIPs() {
119 function realTimestamps() {
122 function implicitGroupby() {
125 function implicitOrderby() {
128 function searchableIPs() {
131 function functionalIndexes() {
135 function hasConstraint( $name ) {
136 global $wgDBmwschema;
137 $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) ."'";
138 return $this->numRows($res = $this->doQuery($SQL));
141 static function newFromParams( $server, $user, $password, $dbName, $flags = 0) {
142 return new DatabasePostgres( $server, $user, $password, $dbName, $flags );
146 * Usually aborts on failure
148 function open( $server, $user, $password, $dbName ) {
149 # Test for Postgres support, to avoid suppressed fatal error
150 if ( !function_exists( 'pg_connect' ) ) {
151 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" );
156 if (!strlen($user)) { ## e.g. the class is being loaded
160 $this->mServer
= $server;
161 $this->mPort
= $port = $wgDBport;
162 $this->mUser
= $user;
163 $this->mPassword
= $password;
164 $this->mDBname
= $dbName;
166 $connectVars = array(
169 'password' => $password );
170 if ($server!=false && $server!="") {
171 $connectVars['host'] = $server;
173 if ($port!=false && $port!="") {
174 $connectVars['port'] = $port;
176 $connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
178 $this->installErrorHandler();
179 $this->mConn
= pg_connect( $connectString );
180 $phpError = $this->restoreErrorHandler();
182 if ( !$this->mConn
) {
183 wfDebug( "DB connection error\n" );
184 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
185 wfDebug( $this->lastError()."\n" );
186 throw new DBConnectionError( $this, $phpError );
189 $this->mOpened
= true;
191 global $wgCommandLineMode;
192 ## If called from the command-line (e.g. importDump), only show errors
193 if ($wgCommandLineMode) {
194 $this->doQuery( "SET client_min_messages = 'ERROR'" );
197 $this->doQuery( "SET client_encoding='UTF8'" );
199 global $wgDBmwschema, $wgDBts2schema;
200 if (isset( $wgDBmwschema ) && isset( $wgDBts2schema )
201 && $wgDBmwschema !== 'mediawiki'
202 && preg_match( '/^\w+$/', $wgDBmwschema )
203 && preg_match( '/^\w+$/', $wgDBts2schema )
205 $safeschema = $this->quote_ident($wgDBmwschema);
206 $safeschema2 = $this->quote_ident($wgDBts2schema);
207 $this->doQuery( "SET search_path = $safeschema, $wgDBts2schema, public" );
213 function makeConnectionString( $vars ) {
215 foreach ( $vars as $name => $value ) {
216 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
222 function initial_setup($superuser, $password, $dbName) {
223 // If this is the initial connection, setup the schema stuff and possibly create the user
224 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBmwschema, $wgDBts2schema;
226 print "<li>Checking the version of Postgres...";
227 $version = $this->getServerVersion();
229 if ($version < $PGMINVER) {
230 print "<b>FAILED</b>. Required version is $PGMINVER. You have " . htmlspecialchars( $version ) . "</li>\n";
233 print "version " . htmlspecialchars( $this->numeric_version
) . " is OK.</li>\n";
235 $safeuser = $this->quote_ident($wgDBuser);
236 // Are we connecting as a superuser for the first time?
238 // Are we really a superuser? Check out our rights
240 CASE WHEN usesuper IS TRUE THEN
241 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
242 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
244 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($superuser);
245 $rows = $this->numRows($res = $this->doQuery($SQL));
247 print "<li>ERROR: Could not read permissions for user \"" . htmlspecialchars( $superuser ) . "\"</li>\n";
250 $perms = pg_fetch_result($res, 0, 0);
252 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
253 $rows = $this->numRows($this->doQuery($SQL));
255 print "<li>User \"" . htmlspecialchars( $wgDBuser ) . "\" already exists, skipping account creation.</li>";
258 if ($perms != 1 and $perms != 3) {
259 print "<li>ERROR: the user \"" . htmlspecialchars( $superuser ) . "\" cannot create other users. ";
260 print 'Please use a different Postgres user.</li>';
263 print "<li>Creating user <b>" . htmlspecialchars( $wgDBuser ) . "</b>...";
264 $safepass = $this->addQuotes($wgDBpassword);
265 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
266 $this->doQuery($SQL);
269 // User now exists, check out the database
270 if ($dbName != $wgDBname) {
271 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
272 $rows = $this->numRows($this->doQuery($SQL));
274 print "<li>Database \"" . htmlspecialchars( $wgDBname ) . "\" already exists, skipping database creation.</li>";
278 print "<li>ERROR: the user \"" . htmlspecialchars( $superuser ) . "\" cannot create databases. ";
279 print 'Please use a different Postgres user.</li>';
282 print "<li>Creating database <b>" . htmlspecialchars( $wgDBname ) . "</b>...";
283 $safename = $this->quote_ident($wgDBname);
284 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
285 $this->doQuery($SQL);
287 // Hopefully tsearch2 and plpgsql are in template1...
290 // Reconnect to check out tsearch2 rights for this user
291 print "<li>Connecting to \"" . htmlspecialchars( $wgDBname ) . "\" as superuser \"" .
292 htmlspecialchars( $superuser ) . "\" to check rights...";
294 $connectVars = array();
295 if ($this->mServer
!=false && $this->mServer
!="") {
296 $connectVars['host'] = $this->mServer
;
298 if ($this->mPort
!=false && $this->mPort
!="") {
299 $connectVars['port'] = $this->mPort
;
301 $connectVars['dbname'] = $wgDBname;
302 $connectVars['user'] = $superuser;
303 $connectVars['password'] = $password;
305 @$this->mConn
= pg_connect( $this->makeConnectionString( $connectVars ) );
306 if ( !$this->mConn
) {
307 print "<b>FAILED TO CONNECT!</b></li>";
313 if ($this->numeric_version
< 8.3) {
315 print "<li>Checking that tsearch2 is installed in the database \"" .
316 htmlspecialchars( $wgDBname ) . "\"...";
317 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
318 print "<b>FAILED</b>. tsearch2 must be installed in the database \"" .
319 htmlspecialchars( $wgDBname ) . "\".";
320 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
321 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
325 print "<li>Ensuring that user \"" . htmlspecialchars( $wgDBuser ) .
326 "\" has select rights on the tsearch2 tables...";
327 foreach (array('cfg','cfgmap','dict','parser') as $table) {
328 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
329 $this->doQuery($SQL);
334 // Setup the schema for this user if needed
335 $result = $this->schemaExists($wgDBmwschema);
336 $safeschema = $this->quote_ident($wgDBmwschema);
338 print "<li>Creating schema <b>" . htmlspecialchars( $wgDBmwschema ) . "</b> ...";
339 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
341 print "<b>FAILED</b>.</li>\n";
347 print "<li>Schema already exists, explicitly granting rights...\n";
348 $safeschema2 = $this->addQuotes($wgDBmwschema);
349 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
350 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
351 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
352 "AND p.relkind IN ('r','S','v')\n";
354 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
355 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
356 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
357 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
358 $res = $this->doQuery($SQL);
360 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
363 $this->doQuery("SET search_path = $safeschema");
364 $rows = $this->numRows($res);
367 $this->doQuery(pg_fetch_result($res, $rows, 0));
372 // Install plpgsql if needed
373 $this->setup_plpgsql();
376 return true; // Reconnect as regular user
380 if (!defined('POSTGRES_SEARCHPATH')) {
382 if ($this->numeric_version
< 8.3) {
383 // Do we have the basic tsearch2 table?
384 print "<li>Checking for tsearch2 in the schema \"" . htmlspecialchars( $wgDBts2schema ) . "\"...";
385 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
386 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
387 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
388 print " for instructions.</li>\n";
393 // Does this user have the rights to the tsearch2 tables?
394 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
395 print "<li>Checking tsearch2 permissions...";
396 // Let's check all four, just to be safe
397 error_reporting( 0 );
398 $ts2tables = array('cfg','cfgmap','dict','parser');
399 $safetsschema = $this->quote_ident($wgDBts2schema);
400 foreach ( $ts2tables AS $tname ) {
401 $SQL = "SELECT count(*) FROM $safetsschema.pg_ts_$tname";
402 $res = $this->doQuery($SQL);
404 print "<b>FAILED</b> to access " . htmlspecialchars( "pg_ts_$tname" ) .
405 ". Make sure that the user \"". htmlspecialchars( $wgDBuser ) .
406 "\" has SELECT access to all four tsearch2 tables</li>\n";
410 $SQL = "SELECT ts_name FROM $safetsschema.pg_ts_cfg WHERE locale = " . $this->addQuotes( $ctype ) ;
411 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
412 $res = $this->doQuery($SQL);
413 error_reporting( E_ALL
);
415 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
420 // Will the current locale work? Can we force it to?
421 print "<li>Verifying tsearch2 locale with " . htmlspecialchars( $ctype ) . "...";
422 $rows = $this->numRows($res);
425 print "<b>not found</b></li>\n";
426 print "<li>Attempting to set default tsearch2 locale to \"" . htmlspecialchars( $ctype ) . "\"...";
430 $tsname = pg_fetch_result($res, 0, 0);
431 if ($tsname != 'default') {
432 print "<b>not set to default (" . htmlspecialchars( $tsname ) . ")</b>";
433 print "<li>Attempting to change tsearch2 default locale to \"" .
434 htmlspecialchars( $ctype ) . "\"...";
439 $SQL = "UPDATE $safetsschema.pg_ts_cfg SET locale = " . $this->addQuotes( $ctype ) . " WHERE ts_name = 'default'";
440 $res = $this->doQuery($SQL);
442 print "<b>FAILED</b>. ";
443 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"" .
444 htmlspecialchars( $ctype ) . "\"</li>\n";
450 // Final test: try out a simple tsearch2 query
451 $SQL = "SELECT $safetsschema.to_tsvector('default','MediaWiki tsearch2 testing')";
452 $res = $this->doQuery($SQL);
454 print "<b>FAILED</b>. Specifically, \"" . htmlspecialchars( $SQL ) . "\" did not work.</li>";
460 // Install plpgsql if needed
461 $this->setup_plpgsql();
463 // Does the schema already exist? Who owns it?
464 $result = $this->schemaExists($wgDBmwschema);
466 print "<li>Creating schema <b>" . htmlspecialchars( $wgDBmwschema ) . "</b> ...";
467 error_reporting( 0 );
468 $safeschema = $this->quote_ident($wgDBmwschema);
469 $result = $this->doQuery("CREATE SCHEMA $safeschema");
470 error_reporting( E_ALL
);
472 print "<b>FAILED</b>. The user \"" . htmlspecialchars( $wgDBuser ) .
473 "\" must be able to access the schema. ".
474 "You can try making them the owner of the database, or try creating the schema with a ".
475 "different user, and then grant access to the \"" .
476 htmlspecialchars( $wgDBuser ) . "\" user.</li>\n";
481 else if ($result != $wgDBuser) {
482 print "<li>Schema \"" . htmlspecialchars( $wgDBmwschema ) . "\" exists but is not owned by \"" .
483 htmlspecialchars( $wgDBuser ) . "\". Not ideal.</li>\n";
486 print "<li>Schema \"" . htmlspecialchars( $wgDBmwschema ) . "\" exists and is owned by \"" .
487 htmlspecialchars( $wgDBuser ) . "\". Excellent.</li>\n";
490 // Always return GMT time to accomodate the existing integer-based timestamp assumption
491 print "<li>Setting the timezone to GMT for user \"" . htmlspecialchars( $wgDBuser ) . "\" ...";
492 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
493 $result = pg_query($this->mConn
, $SQL);
495 print "<b>FAILED</b>.</li>\n";
499 // Set for the rest of this session
500 $SQL = "SET timezone = 'GMT'";
501 $result = pg_query($this->mConn
, $SQL);
503 print "<li>Failed to set timezone</li>\n";
507 print "<li>Setting the datestyle to ISO, YMD for user \"" . htmlspecialchars( $wgDBuser ) . "\" ...";
508 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
509 $result = pg_query($this->mConn
, $SQL);
511 print "<b>FAILED</b>.</li>\n";
515 // Set for the rest of this session
516 $SQL = "SET datestyle = 'ISO, YMD'";
517 $result = pg_query($this->mConn
, $SQL);
519 print "<li>Failed to set datestyle</li>\n";
523 // Fix up the search paths if needed
524 print "<li>Setting the search path for user \"" . htmlspecialchars( $wgDBuser ) . "\" ...";
525 $path = $this->quote_ident($wgDBmwschema);
526 if ($wgDBts2schema !== $wgDBmwschema)
527 $path .= ", ". $this->quote_ident($wgDBts2schema);
528 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
530 $SQL = "ALTER USER $safeuser SET search_path = $path";
531 $result = pg_query($this->mConn
, $SQL);
533 print "<b>FAILED</b>.</li>\n";
537 // Set for the rest of this session
538 $SQL = "SET search_path = $path";
539 $result = pg_query($this->mConn
, $SQL);
541 print "<li>Failed to set search_path</li>\n";
544 define( "POSTGRES_SEARCHPATH", $path );
549 function setup_plpgsql() {
550 print "<li>Checking for PL/pgSQL ...";
551 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
552 $rows = $this->numRows($this->doQuery($SQL));
554 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
555 print "not installed. Attempting to install PL/pgSQL ...";
556 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
557 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
558 $rows = $this->numRows($this->doQuery($SQL));
561 $olde = error_reporting(0);
562 error_reporting($olde - E_WARNING
);
563 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
564 error_reporting($olde);
566 print "<b>FAILED</b>. You need to install the language PL/pgSQL in the database <tt>" .
567 htmlspecialchars( $wgDBname ) . "</tt></li>";
572 print "<b>FAILED</b>. You need to install the language PL/pgSQL in the database <tt>" .
573 htmlspecialchars( $wgDBname ) . "</tt></li>";
582 * Closes a database connection, if it is open
583 * Returns success, true if already closed
586 $this->mOpened
= false;
587 if ( $this->mConn
) {
588 return pg_close( $this->mConn
);
594 function doQuery( $sql ) {
595 if (function_exists('mb_convert_encoding')) {
596 $sql = mb_convert_encoding($sql,'UTF-8');
598 $this->mLastResult
= pg_query( $this->mConn
, $sql);
599 $this->mAffectedRows
= null; // use pg_affected_rows(mLastResult)
600 return $this->mLastResult
;
603 function queryIgnore( $sql, $fname = '' ) {
604 return $this->query( $sql, $fname, true );
607 function freeResult( $res ) {
608 if ( $res instanceof ResultWrapper
) {
611 if ( !@pg_free_result
( $res ) ) {
612 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
616 function fetchObject( $res ) {
617 if ( $res instanceof ResultWrapper
) {
620 @$row = pg_fetch_object( $res );
621 # FIXME: HACK HACK HACK HACK debug
624 # hashar : not sure if the following test really trigger if the object
626 if( pg_last_error($this->mConn
) ) {
627 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
632 function fetchRow( $res ) {
633 if ( $res instanceof ResultWrapper
) {
636 @$row = pg_fetch_array( $res );
637 if( pg_last_error($this->mConn
) ) {
638 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
643 function numRows( $res ) {
644 if ( $res instanceof ResultWrapper
) {
647 @$n = pg_num_rows( $res );
648 if( pg_last_error($this->mConn
) ) {
649 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
653 function numFields( $res ) {
654 if ( $res instanceof ResultWrapper
) {
657 return pg_num_fields( $res );
659 function fieldName( $res, $n ) {
660 if ( $res instanceof ResultWrapper
) {
663 return pg_field_name( $res, $n );
667 * This must be called after nextSequenceVal
669 function insertId() {
670 return $this->mInsertId
;
673 function dataSeek( $res, $row ) {
674 if ( $res instanceof ResultWrapper
) {
677 return pg_result_seek( $res, $row );
680 function lastError() {
681 if ( $this->mConn
) {
682 return pg_last_error();
685 return "No database connection";
688 function lastErrno() {
689 return pg_last_error() ?
1 : 0;
692 function affectedRows() {
693 if ( !is_null( $this->mAffectedRows
) ) {
694 // Forced result for simulated queries
695 return $this->mAffectedRows
;
697 if( empty( $this->mLastResult
) )
699 return pg_affected_rows( $this->mLastResult
);
703 * Estimate rows in dataset
704 * Returns estimated count, based on EXPLAIN output
705 * This is not necessarily an accurate estimate, so use sparingly
706 * Returns -1 if count cannot be found
707 * Takes same arguments as Database::select()
710 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
711 $options['EXPLAIN'] = true;
712 $res = $this->select( $table, $vars, $conds, $fname, $options );
715 $row = $this->fetchRow( $res );
717 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
726 * Returns information about an index
727 * If errors are explicitly ignored, returns NULL on failure
729 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
730 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
731 $res = $this->query( $sql, $fname );
735 while ( $row = $this->fetchObject( $res ) ) {
736 if ( $row->indexname
== $this->indexName( $index ) ) {
743 function indexUnique ($table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
744 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
745 " AND indexdef LIKE 'CREATE UNIQUE%(" .
746 $this->strencode( $this->indexName( $index ) ) .
748 $res = $this->query( $sql, $fname );
751 while ($row = $this->fetchObject( $res ))
758 * INSERT wrapper, inserts an array into a table
760 * $args may be a single associative array, or an array of these with numeric keys,
761 * for multi-row insert (Postgres version 8.2 and above only).
763 * @param $table String: Name of the table to insert to.
764 * @param $args Array: Items to insert into the table.
765 * @param $fname String: Name of the function, for profiling
766 * @param $options String or Array. Valid options: IGNORE
768 * @return bool Success of insert operation. IGNORE always returns true.
770 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
771 if ( !count( $args ) ) {
775 $table = $this->tableName( $table );
776 if (! isset( $this->numeric_version
) ) {
777 $this->getServerVersion();
780 if ( !is_array( $options ) )
781 $options = array( $options );
783 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
785 $keys = array_keys( $args[0] );
789 $keys = array_keys( $args );
792 // If IGNORE is set, we use savepoints to emulate mysql's behavior
793 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
795 // If we are not in a transaction, we need to be for savepoint trickery
798 if (! $this->mTrxLevel
) {
802 $olde = error_reporting( 0 );
803 // For future use, we may want to track the number of actual inserts
804 // Right now, insert (all writes) simply return true/false
805 $numrowsinserted = 0;
808 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
811 if ( $this->numeric_version
>= 8.2 && !$ignore ) {
813 foreach ( $args as $row ) {
819 $sql .= '(' . $this->makeList( $row ) . ')';
821 $res = (bool)$this->query( $sql, $fname, $ignore );
826 foreach ( $args as $row ) {
828 $tempsql .= '(' . $this->makeList( $row ) . ')';
831 pg_query($this->mConn
, "SAVEPOINT $ignore");
834 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
837 $bar = pg_last_error();
839 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
842 pg_query( $this->mConn
, "RELEASE $ignore" );
847 // If any of them fail, we fail overall for this function call
848 // Note that this will be ignored if IGNORE is set
855 // Not multi, just a lone insert
857 pg_query($this->mConn
, "SAVEPOINT $ignore");
860 $sql .= '(' . $this->makeList( $args ) . ')';
861 $res = (bool)$this->query( $sql, $fname, $ignore );
863 $bar = pg_last_error();
865 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
868 pg_query( $this->mConn
, "RELEASE $ignore" );
874 $olde = error_reporting( $olde );
879 // Set the affected row count for the whole operation
880 $this->mAffectedRows
= $numrowsinserted;
882 // IGNORE always returns true
892 * INSERT SELECT wrapper
893 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
894 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
895 * $conds may be "*" to copy the whole table
896 * srcTable may be an array of tables.
897 * @todo FIXME: implement this a little better (seperate select/insert)?
899 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
900 $insertOptions = array(), $selectOptions = array() )
902 $destTable = $this->tableName( $destTable );
904 // If IGNORE is set, we use savepoints to emulate mysql's behavior
905 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
907 if( is_array( $insertOptions ) ) {
908 $insertOptions = implode( ' ', $insertOptions );
910 if( !is_array( $selectOptions ) ) {
911 $selectOptions = array( $selectOptions );
913 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
914 if( is_array( $srcTable ) ) {
915 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
917 $srcTable = $this->tableName( $srcTable );
920 // If we are not in a transaction, we need to be for savepoint trickery
923 if( !$this->mTrxLevel
) {
927 $olde = error_reporting( 0 );
928 $numrowsinserted = 0;
929 pg_query( $this->mConn
, "SAVEPOINT $ignore");
932 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
933 " SELECT $startOpts " . implode( ',', $varMap ) .
934 " FROM $srcTable $useIndex";
936 if ( $conds != '*') {
937 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
940 $sql .= " $tailOpts";
942 $res = (bool)$this->query( $sql, $fname, $ignore );
944 $bar = pg_last_error();
945 if( $bar != false ) {
946 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
948 pg_query( $this->mConn
, "RELEASE $ignore" );
951 $olde = error_reporting( $olde );
956 // Set the affected row count for the whole operation
957 $this->mAffectedRows
= $numrowsinserted;
959 // IGNORE always returns true
966 function tableName( $name ) {
967 # Replace reserved words with better ones
972 return 'pagecontent';
979 * Return the next in a sequence, save the value for retrieval via insertId()
981 function nextSequenceValue( $seqName ) {
982 $safeseq = preg_replace( "/'/", "''", $seqName );
983 $res = $this->query( "SELECT nextval('$safeseq')" );
984 $row = $this->fetchRow( $res );
985 $this->mInsertId
= $row[0];
986 return $this->mInsertId
;
990 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
992 function currentSequenceValue( $seqName ) {
993 $safeseq = preg_replace( "/'/", "''", $seqName );
994 $res = $this->query( "SELECT currval('$safeseq')" );
995 $row = $this->fetchRow( $res );
1000 # REPLACE query wrapper
1001 # Postgres simulates this with a DELETE followed by INSERT
1002 # $row is the row to insert, an associative array
1003 # $uniqueIndexes is an array of indexes. Each element may be either a
1004 # field name or an array of field names
1006 # It may be more efficient to leave off unique indexes which are unlikely to collide.
1007 # However if you do this, you run the risk of encountering errors which wouldn't have
1009 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
1010 $table = $this->tableName( $table );
1012 if (count($rows)==0) {
1017 if ( !is_array( reset( $rows ) ) ) {
1018 $rows = array( $rows );
1021 foreach( $rows as $row ) {
1022 # Delete rows which collide
1023 if ( $uniqueIndexes ) {
1024 $sql = "DELETE FROM $table WHERE ";
1026 foreach ( $uniqueIndexes as $index ) {
1033 if ( is_array( $index ) ) {
1035 foreach ( $index as $col ) {
1041 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
1044 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1048 $this->query( $sql, $fname );
1051 # Now insert the row
1052 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
1053 $this->makeList( $row, LIST_COMMA
) . ')';
1054 $this->query( $sql, $fname );
1058 # DELETE where the condition is a join
1059 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
1061 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
1064 $delTable = $this->tableName( $delTable );
1065 $joinTable = $this->tableName( $joinTable );
1066 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1067 if ( $conds != '*' ) {
1068 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1072 $this->query( $sql, $fname );
1075 # Returns the size of a text field, or -1 for "unlimited"
1076 function textFieldSize( $table, $field ) {
1077 $table = $this->tableName( $table );
1078 $sql = "SELECT t.typname as ftype,a.atttypmod as size
1079 FROM pg_class c, pg_attribute a, pg_type t
1080 WHERE relname='$table' AND a.attrelid=c.oid AND
1081 a.atttypid=t.oid and a.attname='$field'";
1082 $res =$this->query($sql);
1083 $row=$this->fetchObject($res);
1084 if ($row->ftype
=="varchar") {
1092 function limitResult($sql, $limit, $offset=false) {
1093 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
1096 function wasDeadlock() {
1097 return $this->lastErrno() == '40P01';
1100 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
1101 return $this->query( 'CREATE ' . ( $temporary ?
'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
1104 function timestamp( $ts=0 ) {
1105 return wfTimestamp(TS_POSTGRES
,$ts);
1109 * Return aggregated value function call
1111 function aggregateValue ($valuedata,$valuename='value') {
1116 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1117 // Ignore errors during error handling to avoid infinite recursion
1118 $ignore = $this->ignoreErrors( true );
1119 $this->mErrorCount++
;
1121 if ($ignore ||
$tempIgnore) {
1122 wfDebug("SQL ERROR (ignored): $error\n");
1123 $this->ignoreErrors( $ignore );
1126 $message = "A database error has occurred\n" .
1128 "Function: $fname\n" .
1129 "Error: $errno $error\n";
1130 throw new DBUnexpectedError($this, $message);
1135 * @return string wikitext of a link to the server software's web site
1137 function getSoftwareLink() {
1138 return "[http://www.postgresql.org/ PostgreSQL]";
1142 * @return string Version information from the database
1144 function getServerVersion() {
1145 if ( !isset( $this->numeric_version
) ) {
1146 $versionInfo = pg_version( $this->mConn
);
1147 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1148 // Old client, abort install
1149 $this->numeric_version
= '7.3 or earlier';
1150 } elseif ( isset( $versionInfo['server'] ) ) {
1152 $this->numeric_version
= $versionInfo['server'];
1154 // Bug 16937: broken pgsql extension from PHP<5.3
1155 $this->numeric_version
= pg_parameter_status( $this->mConn
, 'server_version' );
1158 return $this->numeric_version
;
1162 * Query whether a given relation exists (in the given schema, or the
1163 * default mw one if not given)
1165 function relationExists( $table, $types, $schema = false ) {
1166 global $wgDBmwschema;
1167 if ( !is_array( $types ) )
1168 $types = array( $types );
1170 $schema = $wgDBmwschema;
1171 $etable = $this->addQuotes( $table );
1172 $eschema = $this->addQuotes( $schema );
1173 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1174 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1175 . "AND c.relkind IN ('" . implode("','", $types) . "')";
1176 $res = $this->query( $SQL );
1177 $count = $res ?
$res->numRows() : 0;
1178 return $count ?
true : false;
1182 * For backward compatibility, this function checks both tables and
1185 function tableExists( $table, $schema = false ) {
1186 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1189 function sequenceExists( $sequence, $schema = false ) {
1190 return $this->relationExists( $sequence, 'S', $schema );
1193 function triggerExists( $table, $trigger ) {
1194 global $wgDBmwschema;
1197 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1198 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1199 AND tgrelid=pg_class.oid
1200 AND nspname=%s AND relname=%s AND tgname=%s
1202 $res = $this->query(sprintf($q,
1203 $this->addQuotes($wgDBmwschema),
1204 $this->addQuotes($table),
1205 $this->addQuotes($trigger)));
1208 $rows = $res->numRows();
1212 function ruleExists( $table, $rule ) {
1213 global $wgDBmwschema;
1214 $exists = $this->selectField("pg_rules", "rulename",
1215 array( "rulename" => $rule,
1216 "tablename" => $table,
1217 "schemaname" => $wgDBmwschema ) );
1218 return $exists === $rule;
1221 function constraintExists( $table, $constraint ) {
1222 global $wgDBmwschema;
1223 $SQL = sprintf("SELECT 1 FROM information_schema.table_constraints ".
1224 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1225 $this->addQuotes($wgDBmwschema),
1226 $this->addQuotes($table),
1227 $this->addQuotes($constraint));
1228 $res = $this->query($SQL);
1231 $rows = $res->numRows();
1236 * Query whether a given schema exists. Returns the name of the owner
1238 function schemaExists( $schema ) {
1239 $eschema = preg_replace("/'/", "''", $schema);
1240 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1241 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1242 $res = $this->query( $SQL );
1243 if ( $res && $res->numRows() ) {
1244 $row = $res->fetchObject();
1245 $owner = $row->rolname
;
1252 function fieldInfo( $table, $field ) {
1253 return PostgresField
::fromText($this, $table, $field);
1257 * pg_field_type() wrapper
1259 function fieldType( $res, $index ) {
1260 if ( $res instanceof ResultWrapper
) {
1261 $res = $res->result
;
1263 return pg_field_type( $res, $index );
1266 /* Not even sure why this is used in the main codebase... */
1267 function limitResultForUpdate( $sql, $num ) {
1271 function setup_database() {
1272 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
1274 // Make sure that we can write to the correct schema
1275 // If not, Postgres will happily and silently go to the next search_path item
1276 $ctest = "mediawiki_test_table";
1277 $safeschema = $this->quote_ident($wgDBmwschema);
1278 if ($this->tableExists($ctest, $wgDBmwschema)) {
1279 $this->doQuery("DROP TABLE $safeschema.$ctest");
1281 $SQL = "CREATE TABLE $safeschema.$ctest(a int)";
1282 $olde = error_reporting( 0 );
1283 $res = $this->doQuery($SQL);
1284 error_reporting( $olde );
1286 print "<b>FAILED</b>. Make sure that the user \"" . htmlspecialchars( $wgDBuser ) .
1287 "\" can write to the schema \"" . htmlspecialchars( $wgDBmwschema ) . "\"</li>\n";
1288 dieout(""); # Will close the main list <ul> and finish the page.
1290 $this->doQuery("DROP TABLE $safeschema.$ctest");
1292 $res = $this->sourceFile( "../maintenance/postgres/tables.sql" );
1293 if ($res === true) {
1294 print " done.</li>\n";
1296 print " <b>FAILED</b></li>\n";
1297 dieout( htmlspecialchars( $res ) );
1300 ## Update version information
1301 $mwv = $this->addQuotes($wgVersion);
1302 $pgv = $this->addQuotes($this->getServerVersion());
1303 $pgu = $this->addQuotes($this->mUser
);
1304 $mws = $this->addQuotes($wgDBmwschema);
1305 $tss = $this->addQuotes($wgDBts2schema);
1306 $pgp = $this->addQuotes($wgDBport);
1307 $dbn = $this->addQuotes($this->mDBname
);
1308 $ctype = $this->addQuotes( pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0) );
1310 echo "<li>Populating interwiki table... ";
1311 ## Avoid the non-standard "REPLACE INTO" syntax
1312 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1314 print "<b>FAILED</b></li>";
1315 dieout( "Could not find the interwiki.sql file" );
1317 ## We simply assume it is already empty as we have just created it
1318 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1319 while ( ! feof( $f ) ) {
1320 $line = fgets($f,1024);
1322 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
1325 $this->query("$SQL $matches[1],$matches[2])");
1327 print " successfully populated.</li>\n";
1329 $this->doQuery("COMMIT");
1332 function encodeBlob( $b ) {
1333 return new Blob ( pg_escape_bytea( $b ) ) ;
1336 function decodeBlob( $b ) {
1337 if ($b instanceof Blob
) {
1340 return pg_unescape_bytea( $b );
1343 function strencode( $s ) { ## Should not be called by us
1344 return pg_escape_string( $s );
1347 function addQuotes( $s ) {
1348 if ( is_null( $s ) ) {
1350 } else if ( is_bool( $s ) ) {
1351 return intval( $s );
1352 } else if ($s instanceof Blob
) {
1353 return "'".$s->fetch($s)."'";
1355 return "'" . pg_escape_string($s) . "'";
1358 function quote_ident( $s ) {
1359 return '"' . preg_replace( '/"/', '""', $s) . '"';
1363 * Postgres specific version of replaceVars.
1364 * Calls the parent version in Database.php
1368 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1370 * @return string SQL string
1372 protected function replaceVars( $ins ) {
1374 $ins = parent
::replaceVars( $ins );
1376 if ($this->numeric_version
>= 8.3) {
1377 // Thanks for not providing backwards-compatibility, 8.3
1378 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1381 if ($this->numeric_version
<= 8.1) { // Our minimum version
1382 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1389 * Various select options
1393 * @param $options Array: an associative array of options to be turned into
1394 * an SQL query, valid keys are listed in the function.
1397 function makeSelectOptions( $options ) {
1398 $preLimitTail = $postLimitTail = '';
1399 $startOpts = $useIndex = '';
1401 $noKeyOptions = array();
1402 foreach ( $options as $key => $option ) {
1403 if ( is_numeric( $key ) ) {
1404 $noKeyOptions[$option] = true;
1408 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY " . $options['GROUP BY'];
1409 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1410 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY " . $options['ORDER BY'];
1412 //if (isset($options['LIMIT'])) {
1413 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1414 // isset($options['OFFSET']) ? $options['OFFSET']
1418 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1419 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1420 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1422 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1425 function setFakeMaster( $enabled = true ) {}
1427 function getDBname() {
1428 return $this->mDBname
;
1431 function getServer() {
1432 return $this->mServer
;
1435 function buildConcat( $stringList ) {
1436 return implode( ' || ', $stringList );
1439 public function getSearchEngine() {
1440 return "SearchPostgres";
1442 } // end DatabasePostgres class