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 );
39 $db->addQuotes( $wgDBmwschema ),
40 $db->addQuotes( $table ),
41 $db->addQuotes( $field )
44 $row = $db->fetchObject( $res );
48 $n = new PostgresField
;
49 $n->type
= $row->typname
;
50 $n->nullable
= ( $row->attnotnull
== 'f' );
52 $n->tablename
= $table;
53 $n->max_length
= $row->attlen
;
54 $n->deferrable
= ( $row->deferrable
== 't' );
55 $n->deferred
= ( $row->deferred
== 't' );
56 $n->conname
= $row->conname
;
64 function tableName() {
65 return $this->tablename
;
73 return $this->nullable
;
76 function maxLength() {
77 return $this->max_length
;
80 function is_deferrable() {
81 return $this->deferrable
;
84 function is_deferred() {
85 return $this->deferred
;
89 return $this->conname
;
97 class DatabasePostgres
extends DatabaseBase
{
98 var $mInsertId = null;
99 var $mLastResult = null;
100 var $numeric_version = null;
101 var $mAffectedRows = null;
103 function __construct( $server = false, $user = false, $password = false, $dbName = false,
104 $failFunction = false, $flags = 0 )
106 $this->mFailFunction
= $failFunction;
107 $this->mFlags
= $flags;
108 $this->open( $server, $user, $password, $dbName );
115 function cascadingDeletes() {
118 function cleanupTriggers() {
121 function strictIPs() {
124 function realTimestamps() {
127 function implicitGroupby() {
130 function implicitOrderby() {
133 function searchableIPs() {
136 function functionalIndexes() {
140 function hasConstraint( $name ) {
141 global $wgDBmwschema;
142 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" . pg_escape_string( $this->mConn
, $name ) . "' AND n.nspname = '" . pg_escape_string( $this->mConn
, $wgDBmwschema ) ."'";
143 return $this->numRows( $res = $this->doQuery( $SQL ) );
146 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
148 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
152 * Usually aborts on failure
153 * If the failFunction is set to a non-zero integer, returns success
155 function open( $server, $user, $password, $dbName ) {
156 # Test for Postgres support, to avoid suppressed fatal error
157 if ( !function_exists( 'pg_connect' ) ) {
158 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" );
163 if ( !strlen( $user ) ) { # e.g. the class is being loaded
167 $this->mServer
= $server;
168 $this->mPort
= $port = $wgDBport;
169 $this->mUser
= $user;
170 $this->mPassword
= $password;
171 $this->mDBname
= $dbName;
173 $connectVars = array(
176 'password' => $password
178 if ( $server != false && $server != '' ) {
179 $connectVars['host'] = $server;
181 if ( $port != false && $port != '' ) {
182 $connectVars['port'] = $port;
184 $connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
186 $this->installErrorHandler();
187 $this->mConn
= pg_connect( $connectString );
188 $phpError = $this->restoreErrorHandler();
190 if ( !$this->mConn
) {
191 wfDebug( "DB connection error\n" );
192 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
193 wfDebug( $this->lastError() . "\n" );
194 if ( !$this->mFailFunction
) {
195 throw new DBConnectionError( $this, $phpError );
201 $this->mOpened
= true;
203 global $wgCommandLineMode;
204 # If called from the command-line (e.g. importDump), only show errors
205 if ( $wgCommandLineMode ) {
206 $this->doQuery( "SET client_min_messages = 'ERROR'" );
209 $this->doQuery( "SET client_encoding='UTF8'" );
211 global $wgDBmwschema, $wgDBts2schema;
212 if ( isset( $wgDBmwschema ) && isset( $wgDBts2schema )
213 && $wgDBmwschema !== 'mediawiki'
214 && preg_match( '/^\w+$/', $wgDBmwschema )
215 && preg_match( '/^\w+$/', $wgDBts2schema )
217 $safeschema = $this->quote_ident( $wgDBmwschema );
218 $safeschema2 = $this->quote_ident( $wgDBts2schema );
219 $this->doQuery( "SET search_path = $safeschema, $wgDBts2schema, public" );
225 function makeConnectionString( $vars ) {
227 foreach ( $vars as $name => $value ) {
228 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
234 function initial_setup( $superuser, $password, $dbName ) {
235 // If this is the initial connection, setup the schema stuff and possibly create the user
236 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBmwschema, $wgDBts2schema;
238 print '<li>Checking the version of Postgres...';
239 $version = $this->getServerVersion();
241 if ( $version < $PGMINVER ) {
242 print "<b>FAILED</b>. Required version is $PGMINVER. You have " . htmlspecialchars( $version ) . "</li>\n";
245 print 'version ' . htmlspecialchars( $this->numeric_version
) . " is OK.</li>\n";
247 $safeuser = $this->quote_ident( $wgDBuser );
248 // Are we connecting as a superuser for the first time?
250 // Are we really a superuser? Check out our rights
252 CASE WHEN usesuper IS TRUE THEN
253 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
254 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
256 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes( $superuser );
257 $rows = $this->numRows( $res = $this->doQuery( $SQL ) );
259 print '<li>ERROR: Could not read permissions for user "' . htmlspecialchars( $superuser ) . "\"</li>\n";
262 $perms = pg_fetch_result( $res, 0, 0 );
264 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes( $wgDBuser );
265 $rows = $this->numRows( $this->doQuery( $SQL ) );
267 print '<li>User "' . htmlspecialchars( $wgDBuser ) . '" already exists, skipping account creation.</li>';
269 if ( $perms != 1 && $perms != 3 ) {
270 print '<li>ERROR: the user "' . htmlspecialchars( $superuser ) . '" cannot create other users. ';
271 print 'Please use a different Postgres user.</li>';
274 print '<li>Creating user <b>' . htmlspecialchars( $wgDBuser ) . '</b>...';
275 $safepass = $this->addQuotes( $wgDBpassword );
276 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
277 $this->doQuery( $SQL );
280 // User now exists, check out the database
281 if ( $dbName != $wgDBname ) {
282 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes( $wgDBname );
283 $rows = $this->numRows( $this->doQuery( $SQL ) );
285 print '<li>Database "' . htmlspecialchars( $wgDBname ) . '" already exists, skipping database creation.</li>';
288 print '<li>ERROR: the user "' . htmlspecialchars( $superuser ) . '" cannot create databases. ';
289 print 'Please use a different Postgres user.</li>';
292 print '<li>Creating database <b>' . htmlspecialchars( $wgDBname ) . '</b>...';
293 $safename = $this->quote_ident( $wgDBname );
294 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
295 $this->doQuery( $SQL );
297 // Hopefully tsearch2 and plpgsql are in template1...
300 // Reconnect to check out tsearch2 rights for this user
301 print '<li>Connecting to "' . htmlspecialchars( $wgDBname ) . '" as superuser "' .
302 htmlspecialchars( $superuser ) . '" to check rights...';
304 $connectVars = array();
305 if ( $this->mServer
!= false && $this->mServer
!= '' ) {
306 $connectVars['host'] = $this->mServer
;
308 if ( $this->mPort
!= false && $this->mPort
!= '' ) {
309 $connectVars['port'] = $this->mPort
;
311 $connectVars['dbname'] = $wgDBname;
312 $connectVars['user'] = $superuser;
313 $connectVars['password'] = $password;
315 @$this->mConn
= pg_connect( $this->makeConnectionString( $connectVars ) );
316 if ( !$this->mConn
) {
317 print "<b>FAILED TO CONNECT!</b></li>";
323 if ( $this->numeric_version
< 8.3 ) {
325 print '<li>Checking that tsearch2 is installed in the database "' .
326 htmlspecialchars( $wgDBname ) . '"...';
327 if ( !$this->tableExists( 'pg_ts_cfg', $wgDBts2schema ) ) {
328 print '<b>FAILED</b>. tsearch2 must be installed in the database "' .
329 htmlspecialchars( $wgDBname ) . '".';
330 print 'Please see <a href="http://www.devx.com/opensource/Article/21674/0/page/2">this article</a>';
331 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
335 print '<li>Ensuring that user "' . htmlspecialchars( $wgDBuser ) .
336 '" has select rights on the tsearch2 tables...';
337 foreach ( array( 'cfg', 'cfgmap', 'dict', 'parser' ) as $table ) {
338 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
339 $this->doQuery( $SQL );
344 // Setup the schema for this user if needed
345 $result = $this->schemaExists( $wgDBmwschema );
346 $safeschema = $this->quote_ident( $wgDBmwschema );
348 print '<li>Creating schema <b>' . htmlspecialchars( $wgDBmwschema ) . '</b> ...';
349 $result = $this->doQuery( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
351 print "<b>FAILED</b>.</li>\n";
356 print "<li>Schema already exists, explicitly granting rights...\n";
357 $safeschema2 = $this->addQuotes( $wgDBmwschema );
358 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
359 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
360 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
361 "AND p.relkind IN ('r','S','v')\n";
363 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
364 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
365 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
366 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
367 $res = $this->doQuery( $SQL );
369 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
372 $this->doQuery( "SET search_path = $safeschema" );
373 $rows = $this->numRows( $res );
376 $this->doQuery( pg_fetch_result( $res, $rows, 0 ) );
381 // Install plpgsql if needed
382 $this->setup_plpgsql();
385 return true; // Reconnect as regular user
389 if ( !defined( 'POSTGRES_SEARCHPATH' ) ) {
391 if ( $this->numeric_version
< 8.3 ) {
392 // Do we have the basic tsearch2 table?
393 print '<li>Checking for tsearch2 in the schema "' . htmlspecialchars( $wgDBts2schema ) . '"...';
394 if ( !$this->tableExists( 'pg_ts_dict', $wgDBts2schema ) ) {
395 print '<b>FAILED</b>. Make sure tsearch2 is installed. See <a href="';
396 print 'http://www.devx.com/opensource/Article/21674/0/page/2">this article</a>';
397 print " for instructions.</li>\n";
402 // Does this user have the rights to the tsearch2 tables?
403 $ctype = pg_fetch_result( $this->doQuery( 'SHOW lc_ctype' ), 0, 0 );
404 print '<li>Checking tsearch2 permissions...';
405 // Let's check all four, just to be safe
406 error_reporting( 0 );
407 $ts2tables = array( 'cfg', 'cfgmap', 'dict', 'parser' );
408 $safetsschema = $this->quote_ident( $wgDBts2schema );
409 foreach ( $ts2tables as $tname ) {
410 $SQL = "SELECT count(*) FROM $safetsschema.pg_ts_$tname";
411 $res = $this->doQuery( $SQL );
413 print "<b>FAILED</b> to access " . htmlspecialchars( "pg_ts_$tname" ) .
414 ". Make sure that the user \"". htmlspecialchars( $wgDBuser ) .
415 "\" has SELECT access to all four tsearch2 tables</li>\n";
419 $SQL = "SELECT ts_name FROM $safetsschema.pg_ts_cfg WHERE locale = " . $this->addQuotes( $ctype ) ;
420 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
421 $res = $this->doQuery( $SQL );
422 error_reporting( E_ALL
);
424 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
429 // Will the current locale work? Can we force it to?
430 print '<li>Verifying tsearch2 locale with ' . htmlspecialchars( $ctype ) . '...';
431 $rows = $this->numRows( $res );
434 print "<b>not found</b></li>\n";
435 print '<li>Attempting to set default tsearch2 locale to "' . htmlspecialchars( $ctype ) . '"...';
438 $tsname = pg_fetch_result( $res, 0, 0 );
439 if ( $tsname != 'default' ) {
440 print "<b>not set to default (" . htmlspecialchars( $tsname ) . ")</b>";
441 print "<li>Attempting to change tsearch2 default locale to \"" .
442 htmlspecialchars( $ctype ) . "\"...";
446 if ( $resetlocale ) {
447 $SQL = "UPDATE $safetsschema.pg_ts_cfg SET locale = " . $this->addQuotes( $ctype ) . " WHERE ts_name = 'default'";
448 $res = $this->doQuery( $SQL );
450 print '<b>FAILED</b>. ';
451 print 'Please make sure that the locale in pg_ts_cfg for "default" is set to "' .
452 htmlspecialchars( $ctype ) . "\"</li>\n";
458 // Final test: try out a simple tsearch2 query
459 $SQL = "SELECT $safetsschema.to_tsvector('default','MediaWiki tsearch2 testing')";
460 $res = $this->doQuery( $SQL );
462 print '<b>FAILED</b>. Specifically, "' . htmlspecialchars( $SQL ) . '" did not work.</li>';
468 // Install plpgsql if needed
469 $this->setup_plpgsql();
471 // Does the schema already exist? Who owns it?
472 $result = $this->schemaExists( $wgDBmwschema );
474 print '<li>Creating schema <b>' . htmlspecialchars( $wgDBmwschema ) . '</b> ...';
475 error_reporting( 0 );
476 $safeschema = $this->quote_ident( $wgDBmwschema );
477 $result = $this->doQuery( "CREATE SCHEMA $safeschema" );
478 error_reporting( E_ALL
);
480 print '<b>FAILED</b>. The user "' . htmlspecialchars( $wgDBuser ) .
481 '" must be able to access the schema. '.
482 'You can try making them the owner of the database, or try creating the schema with a '.
483 'different user, and then grant access to the "' .
484 htmlspecialchars( $wgDBuser ) . "\" user.</li>\n";
488 } elseif ( $result != $wgDBuser ) {
489 print '<li>Schema "' . htmlspecialchars( $wgDBmwschema ) . '" exists but is not owned by "' .
490 htmlspecialchars( $wgDBuser ) . "\". Not ideal.</li>\n";
492 print '<li>Schema "' . htmlspecialchars( $wgDBmwschema ) . '" exists and is owned by "' .
493 htmlspecialchars( $wgDBuser ) . "\". Excellent.</li>\n";
496 // Always return GMT time to accomodate the existing integer-based timestamp assumption
497 print "<li>Setting the timezone to GMT for user \"" . htmlspecialchars( $wgDBuser ) . '" ...';
498 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
499 $result = pg_query( $this->mConn
, $SQL );
501 print "<b>FAILED</b>.</li>\n";
505 // Set for the rest of this session
506 $SQL = "SET timezone = 'GMT'";
507 $result = pg_query( $this->mConn
, $SQL );
509 print "<li>Failed to set timezone</li>\n";
513 print '<li>Setting the datestyle to ISO, YMD for user "' . htmlspecialchars( $wgDBuser ) . '" ...';
514 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
515 $result = pg_query( $this->mConn
, $SQL );
517 print "<b>FAILED</b>.</li>\n";
521 // Set for the rest of this session
522 $SQL = "SET datestyle = 'ISO, YMD'";
523 $result = pg_query( $this->mConn
, $SQL );
525 print "<li>Failed to set datestyle</li>\n";
529 // Fix up the search paths if needed
530 print '<li>Setting the search path for user "' . htmlspecialchars( $wgDBuser ) . '" ...';
531 $path = $this->quote_ident( $wgDBmwschema );
532 if ( $wgDBts2schema !== $wgDBmwschema ) {
533 $path .= ', '. $this->quote_ident( $wgDBts2schema );
535 if ( $wgDBmwschema !== 'public' && $wgDBts2schema !== 'public' ) {
538 $SQL = "ALTER USER $safeuser SET search_path = $path";
539 $result = pg_query( $this->mConn
, $SQL );
541 print "<b>FAILED</b>.</li>\n";
545 // Set for the rest of this session
546 $SQL = "SET search_path = $path";
547 $result = pg_query( $this->mConn
, $SQL );
549 print "<li>Failed to set search_path</li>\n";
552 define( 'POSTGRES_SEARCHPATH', $path );
556 function setup_plpgsql() {
557 print '<li>Checking for PL/pgSQL ...';
558 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
559 $rows = $this->numRows( $this->doQuery( $SQL ) );
561 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
562 print 'not installed. Attempting to install PL/pgSQL ...';
563 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
564 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
565 $rows = $this->numRows( $this->doQuery( $SQL ) );
568 $olde = error_reporting( 0 );
569 error_reporting( $olde - E_WARNING
);
570 $result = $this->doQuery( 'CREATE LANGUAGE plpgsql' );
571 error_reporting( $olde );
573 print '<b>FAILED</b>. You need to install the language PL/pgSQL in the database <tt>' .
574 htmlspecialchars( $wgDBname ) . '</tt></li>';
578 print '<b>FAILED</b>. You need to install the language PL/pgSQL in the database <tt>' .
579 htmlspecialchars( $wgDBname ) . '</tt></li>';
587 * Closes a database connection, if it is open
588 * Returns success, true if already closed
591 $this->mOpened
= false;
592 if ( $this->mConn
) {
593 return pg_close( $this->mConn
);
599 function doQuery( $sql ) {
600 if ( function_exists( 'mb_convert_encoding' ) ) {
601 $sql = mb_convert_encoding( $sql, 'UTF-8' );
603 $this->mLastResult
= pg_query( $this->mConn
, $sql );
604 $this->mAffectedRows
= null; // use pg_affected_rows(mLastResult)
605 return $this->mLastResult
;
608 function queryIgnore( $sql, $fname = '' ) {
609 return $this->query( $sql, $fname, true );
612 function freeResult( $res ) {
613 if ( $res instanceof ResultWrapper
) {
616 if ( !@pg_free_result
( $res ) ) {
617 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
621 function fetchObject( $res ) {
622 if ( $res instanceof ResultWrapper
) {
625 @$row = pg_fetch_object( $res );
626 # FIXME: HACK HACK HACK HACK debug
629 # hashar : not sure if the following test really trigger if the object
631 if( pg_last_error( $this->mConn
) ) {
632 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
637 function fetchRow( $res ) {
638 if ( $res instanceof ResultWrapper
) {
641 @$row = pg_fetch_array( $res );
642 if( pg_last_error( $this->mConn
) ) {
643 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
648 function numRows( $res ) {
649 if ( $res instanceof ResultWrapper
) {
652 @$n = pg_num_rows( $res );
653 if( pg_last_error( $this->mConn
) ) {
654 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
659 function numFields( $res ) {
660 if ( $res instanceof ResultWrapper
) {
663 return pg_num_fields( $res );
666 function fieldName( $res, $n ) {
667 if ( $res instanceof ResultWrapper
) {
670 return pg_field_name( $res, $n );
674 * This must be called after nextSequenceVal
676 function insertId() {
677 return $this->mInsertId
;
680 function dataSeek( $res, $row ) {
681 if ( $res instanceof ResultWrapper
) {
684 return pg_result_seek( $res, $row );
687 function lastError() {
688 if ( $this->mConn
) {
689 return pg_last_error();
691 return 'No database connection';
694 function lastErrno() {
695 return pg_last_error() ?
1 : 0;
698 function affectedRows() {
699 if ( !is_null( $this->mAffectedRows
) ) {
700 // Forced result for simulated queries
701 return $this->mAffectedRows
;
703 if( empty( $this->mLastResult
) ) {
706 return pg_affected_rows( $this->mLastResult
);
710 * Estimate rows in dataset
711 * Returns estimated count, based on EXPLAIN output
712 * This is not necessarily an accurate estimate, so use sparingly
713 * Returns -1 if count cannot be found
714 * Takes same arguments as Database::select()
716 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
717 $options['EXPLAIN'] = true;
718 $res = $this->select( $table, $vars, $conds, $fname, $options );
721 $row = $this->fetchRow( $res );
723 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
731 * Returns information about an index
732 * If errors are explicitly ignored, returns NULL on failure
734 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
735 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
736 $res = $this->query( $sql, $fname );
740 foreach ( $res as $row ) {
741 if ( $row->indexname
== $this->indexName( $index ) ) {
748 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
749 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
750 " AND indexdef LIKE 'CREATE UNIQUE%(" .
751 $this->strencode( $this->indexName( $index ) ) .
753 $res = $this->query( $sql, $fname );
757 foreach ( $res as $row ) {
765 * INSERT wrapper, inserts an array into a table
767 * $args may be a single associative array, or an array of these with numeric keys,
768 * for multi-row insert (Postgres version 8.2 and above only).
770 * @param $table String: Name of the table to insert to.
771 * @param $args Array: Items to insert into the table.
772 * @param $fname String: Name of the function, for profiling
773 * @param $options String or Array. Valid options: IGNORE
775 * @return bool Success of insert operation. IGNORE always returns true.
777 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
778 if ( !count( $args ) ) {
782 $table = $this->tableName( $table );
783 if (! isset( $this->numeric_version
) ) {
784 $this->getServerVersion();
787 if ( !is_array( $options ) ) {
788 $options = array( $options );
791 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
793 $keys = array_keys( $args[0] );
796 $keys = array_keys( $args );
799 // If IGNORE is set, we use savepoints to emulate mysql's behavior
800 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
802 // If we are not in a transaction, we need to be for savepoint trickery
805 if ( !$this->mTrxLevel
) {
809 $olde = error_reporting( 0 );
810 // For future use, we may want to track the number of actual inserts
811 // Right now, insert (all writes) simply return true/false
812 $numrowsinserted = 0;
815 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
818 if ( $this->numeric_version
>= 8.2 && !$ignore ) {
820 foreach ( $args as $row ) {
826 $sql .= '(' . $this->makeList( $row ) . ')';
828 $res = (bool)$this->query( $sql, $fname, $ignore );
832 foreach ( $args as $row ) {
834 $tempsql .= '(' . $this->makeList( $row ) . ')';
837 pg_query( $this->mConn
, "SAVEPOINT $ignore" );
840 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
843 $bar = pg_last_error();
844 if ( $bar != false ) {
845 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
847 pg_query( $this->mConn
, "RELEASE $ignore" );
852 // If any of them fail, we fail overall for this function call
853 // Note that this will be ignored if IGNORE is set
860 // Not multi, just a lone insert
862 pg_query($this->mConn
, "SAVEPOINT $ignore");
865 $sql .= '(' . $this->makeList( $args ) . ')';
866 $res = (bool)$this->query( $sql, $fname, $ignore );
868 $bar = pg_last_error();
869 if ( $bar != false ) {
870 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
872 pg_query( $this->mConn
, "RELEASE $ignore" );
878 $olde = error_reporting( $olde );
883 // Set the affected row count for the whole operation
884 $this->mAffectedRows
= $numrowsinserted;
886 // IGNORE always returns true
894 * INSERT SELECT wrapper
895 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
896 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
897 * $conds may be "*" to copy the whole table
898 * srcTable may be an array of tables.
899 * @todo FIXME: implement this a little better (seperate select/insert)?
901 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
902 $insertOptions = array(), $selectOptions = array() )
904 $destTable = $this->tableName( $destTable );
906 // If IGNORE is set, we use savepoints to emulate mysql's behavior
907 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
909 if( is_array( $insertOptions ) ) {
910 $insertOptions = implode( ' ', $insertOptions );
912 if( !is_array( $selectOptions ) ) {
913 $selectOptions = array( $selectOptions );
915 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
916 if( is_array( $srcTable ) ) {
917 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
919 $srcTable = $this->tableName( $srcTable );
922 // If we are not in a transaction, we need to be for savepoint trickery
925 if( !$this->mTrxLevel
) {
929 $olde = error_reporting( 0 );
930 $numrowsinserted = 0;
931 pg_query( $this->mConn
, "SAVEPOINT $ignore");
934 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
935 " SELECT $startOpts " . implode( ',', $varMap ) .
936 " FROM $srcTable $useIndex";
938 if ( $conds != '*' ) {
939 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
942 $sql .= " $tailOpts";
944 $res = (bool)$this->query( $sql, $fname, $ignore );
946 $bar = pg_last_error();
947 if( $bar != false ) {
948 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
950 pg_query( $this->mConn
, "RELEASE $ignore" );
953 $olde = error_reporting( $olde );
958 // Set the affected row count for the whole operation
959 $this->mAffectedRows
= $numrowsinserted;
961 // IGNORE always returns true
968 function tableName( $name ) {
969 # Replace reserved words with better ones
974 return 'pagecontent';
981 * Return the next in a sequence, save the value for retrieval via insertId()
983 function nextSequenceValue( $seqName ) {
984 $safeseq = preg_replace( "/'/", "''", $seqName );
985 $res = $this->query( "SELECT nextval('$safeseq')" );
986 $row = $this->fetchRow( $res );
987 $this->mInsertId
= $row[0];
988 return $this->mInsertId
;
992 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
994 function currentSequenceValue( $seqName ) {
995 $safeseq = preg_replace( "/'/", "''", $seqName );
996 $res = $this->query( "SELECT currval('$safeseq')" );
997 $row = $this->fetchRow( $res );
1003 * REPLACE query wrapper
1004 * Postgres simulates this with a DELETE followed by INSERT
1005 * $row is the row to insert, an associative array
1006 * $uniqueIndexes is an array of indexes. Each element may be either a
1007 * field name or an array of field names
1009 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1010 * However if you do this, you run the risk of encountering errors which wouldn't have
1013 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
1014 $table = $this->tableName( $table );
1016 if ( count( $rows ) == 0 ) {
1021 if ( !is_array( reset( $rows ) ) ) {
1022 $rows = array( $rows );
1025 foreach( $rows as $row ) {
1026 # Delete rows which collide
1027 if ( $uniqueIndexes ) {
1028 $sql = "DELETE FROM $table WHERE ";
1030 foreach ( $uniqueIndexes as $index ) {
1037 if ( is_array( $index ) ) {
1039 foreach ( $index as $col ) {
1045 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
1048 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1052 $this->query( $sql, $fname );
1055 # Now insert the row
1056 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
1057 $this->makeList( $row, LIST_COMMA
) . ')';
1058 $this->query( $sql, $fname );
1062 # DELETE where the condition is a join
1063 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
1065 throw new DBUnexpectedError( $this, 'DatabasePostgres::deleteJoin() called with empty $conds' );
1068 $delTable = $this->tableName( $delTable );
1069 $joinTable = $this->tableName( $joinTable );
1070 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1071 if ( $conds != '*' ) {
1072 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1076 $this->query( $sql, $fname );
1079 # Returns the size of a text field, or -1 for "unlimited"
1080 function textFieldSize( $table, $field ) {
1081 $table = $this->tableName( $table );
1082 $sql = "SELECT t.typname as ftype,a.atttypmod as size
1083 FROM pg_class c, pg_attribute a, pg_type t
1084 WHERE relname='$table' AND a.attrelid=c.oid AND
1085 a.atttypid=t.oid and a.attname='$field'";
1086 $res =$this->query( $sql );
1087 $row = $this->fetchObject( $res );
1088 if ( $row->ftype
== 'varchar' ) {
1089 $size = $row->size
- 4;
1096 function limitResult( $sql, $limit, $offset = false ) {
1097 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " : '' );
1100 function wasDeadlock() {
1101 return $this->lastErrno() == '40P01';
1104 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
1105 return $this->query( 'CREATE ' . ( $temporary ?
'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
1108 function timestamp( $ts = 0 ) {
1109 return wfTimestamp( TS_POSTGRES
, $ts );
1113 * Return aggregated value function call
1115 function aggregateValue( $valuedata, $valuename = 'value' ) {
1119 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1120 // Ignore errors during error handling to avoid infinite recursion
1121 $ignore = $this->ignoreErrors( true );
1122 $this->mErrorCount++
;
1124 if ( $ignore ||
$tempIgnore ) {
1125 wfDebug( "SQL ERROR (ignored): $error\n" );
1126 $this->ignoreErrors( $ignore );
1128 $message = "A database error has occurred. Did you forget to run maintenance/update.php after upgrading? See: http://www.mediawiki.org/wiki/Manual:Upgrading#Run_the_update_script\n" .
1130 "Function: $fname\n" .
1131 "Error: $errno $error\n";
1132 throw new DBUnexpectedError( $this, $message );
1137 * @return string wikitext of a link to the server software's web site
1139 public static function getSoftwareLink() {
1140 return '[http://www.postgresql.org/ PostgreSQL]';
1144 * @return string Version information from the database
1146 function getServerVersion() {
1147 if ( !isset( $this->numeric_version
) ) {
1148 $versionInfo = pg_version( $this->mConn
);
1149 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1150 // Old client, abort install
1151 $this->numeric_version
= '7.3 or earlier';
1152 } elseif ( isset( $versionInfo['server'] ) ) {
1154 $this->numeric_version
= $versionInfo['server'];
1156 // Bug 16937: broken pgsql extension from PHP<5.3
1157 $this->numeric_version
= pg_parameter_status( $this->mConn
, 'server_version' );
1160 return $this->numeric_version
;
1164 * Query whether a given relation exists (in the given schema, or the
1165 * default mw one if not given)
1167 function relationExists( $table, $types, $schema = false ) {
1168 global $wgDBmwschema;
1169 if ( !is_array( $types ) ) {
1170 $types = array( $types );
1173 $schema = $wgDBmwschema;
1175 $etable = $this->addQuotes( $table );
1176 $eschema = $this->addQuotes( $schema );
1177 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1178 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1179 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1180 $res = $this->query( $SQL );
1181 $count = $res ?
$res->numRows() : 0;
1182 return (bool)$count;
1186 * For backward compatibility, this function checks both tables and
1189 function tableExists( $table, $schema = false ) {
1190 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1193 function sequenceExists( $sequence, $schema = false ) {
1194 return $this->relationExists( $sequence, 'S', $schema );
1197 function triggerExists( $table, $trigger ) {
1198 global $wgDBmwschema;
1201 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1202 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1203 AND tgrelid=pg_class.oid
1204 AND nspname=%s AND relname=%s AND tgname=%s
1206 $res = $this->query(
1209 $this->addQuotes( $wgDBmwschema ),
1210 $this->addQuotes( $table ),
1211 $this->addQuotes( $trigger )
1217 $rows = $res->numRows();
1221 function ruleExists( $table, $rule ) {
1222 global $wgDBmwschema;
1223 $exists = $this->selectField( 'pg_rules', 'rulename',
1225 'rulename' => $rule,
1226 'tablename' => $table,
1227 'schemaname' => $wgDBmwschema
1230 return $exists === $rule;
1233 function constraintExists( $table, $constraint ) {
1234 global $wgDBmwschema;
1235 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
1236 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1237 $this->addQuotes( $wgDBmwschema ),
1238 $this->addQuotes( $table ),
1239 $this->addQuotes( $constraint )
1241 $res = $this->query( $SQL );
1245 $rows = $res->numRows();
1250 * Query whether a given schema exists. Returns the name of the owner
1252 function schemaExists( $schema ) {
1253 $eschema = preg_replace( "/'/", "''", $schema );
1254 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1255 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1256 $res = $this->query( $SQL );
1257 if ( $res && $res->numRows() ) {
1258 $row = $res->fetchObject();
1259 $owner = $row->rolname
;
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 /* Not even sure why this is used in the main codebase... */
1281 function limitResultForUpdate( $sql, $num ) {
1285 function setup_database() {
1286 global $wgDBmwschema, $wgDBuser;
1288 // Make sure that we can write to the correct schema
1289 // If not, Postgres will happily and silently go to the next search_path item
1290 $ctest = 'mediawiki_test_table';
1291 $safeschema = $this->quote_ident( $wgDBmwschema );
1292 if ( $this->tableExists( $ctest, $wgDBmwschema ) ) {
1293 $this->doQuery( "DROP TABLE $safeschema.$ctest" );
1295 $SQL = "CREATE TABLE $safeschema.$ctest(a int)";
1296 $olde = error_reporting( 0 );
1297 $res = $this->doQuery( $SQL );
1298 error_reporting( $olde );
1300 print '<b>FAILED</b>. Make sure that the user "' . htmlspecialchars( $wgDBuser ) .
1301 '" can write to the schema "' . htmlspecialchars( $wgDBmwschema ) . "\"</li>\n";
1302 dieout( '' ); # Will close the main list <ul> and finish the page.
1304 $this->doQuery( "DROP TABLE $safeschema.$ctest" );
1306 $res = $this->sourceFile( "../maintenance/postgres/tables.sql" );
1307 if ( $res === true ) {
1308 print " done.</li>\n";
1310 print " <b>FAILED</b></li>\n";
1311 dieout( htmlspecialchars( $res ) );
1314 echo '<li>Populating interwiki table... ';
1315 # Avoid the non-standard "REPLACE INTO" syntax
1316 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1318 print '<b>FAILED</b></li>';
1319 dieout( 'Could not find the interwiki.sql file' );
1321 # We simply assume it is already empty as we have just created it
1322 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1323 while ( !feof( $f ) ) {
1324 $line = fgets( $f, 1024 );
1326 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) {
1329 $this->query( "$SQL $matches[1],$matches[2])" );
1331 print " successfully populated.</li>\n";
1333 $this->doQuery( 'COMMIT' );
1336 function encodeBlob( $b ) {
1337 return new Blob( pg_escape_bytea( $this->mConn
, $b ) );
1340 function decodeBlob( $b ) {
1341 if ( $b instanceof Blob
) {
1344 return pg_unescape_bytea( $b );
1347 function strencode( $s ) { # Should not be called by us
1348 return pg_escape_string( $this->mConn
, $s );
1351 function addQuotes( $s ) {
1352 if ( is_null( $s ) ) {
1354 } elseif ( is_bool( $s ) ) {
1355 return intval( $s );
1356 } elseif ( $s instanceof Blob
) {
1357 return "'" . $s->fetch( $s ) . "'";
1359 return "'" . pg_escape_string( $this->mConn
, $s ) . "'";
1362 function quote_ident( $s ) {
1363 return '"' . preg_replace( '/"/', '""', $s ) . '"';
1367 * Postgres specific version of replaceVars.
1368 * Calls the parent version in Database.php
1372 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1374 * @return string SQL string
1376 protected function replaceVars( $ins ) {
1377 $ins = parent
::replaceVars( $ins );
1379 if ( $this->numeric_version
>= 8.3 ) {
1380 // Thanks for not providing backwards-compatibility, 8.3
1381 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1384 if ( $this->numeric_version
<= 8.1 ) { // Our minimum version
1385 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1392 * Various select options
1396 * @param $options Array: an associative array of options to be turned into
1397 * an SQL query, valid keys are listed in the function.
1400 function makeSelectOptions( $options ) {
1401 $preLimitTail = $postLimitTail = '';
1402 $startOpts = $useIndex = '';
1404 $noKeyOptions = array();
1405 foreach ( $options as $key => $option ) {
1406 if ( is_numeric( $key ) ) {
1407 $noKeyOptions[$option] = true;
1411 if ( isset( $options['GROUP BY'] ) ) {
1412 $preLimitTail .= ' GROUP BY ' . $options['GROUP BY'];
1414 if ( isset( $options['HAVING'] ) ) {
1415 $preLimitTail .= " HAVING {$options['HAVING']}";
1417 if ( isset( $options['ORDER BY'] ) ) {
1418 $preLimitTail .= ' ORDER BY ' . $options['ORDER BY'];
1421 //if ( isset( $options['LIMIT'] ) ) {
1422 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1423 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1427 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1428 $postLimitTail .= ' FOR UPDATE';
1430 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1431 $postLimitTail .= ' LOCK IN SHARE MODE';
1433 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1434 $startOpts .= 'DISTINCT';
1437 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1440 function setFakeMaster( $enabled = true ) {}
1442 function getDBname() {
1443 return $this->mDBname
;
1446 function getServer() {
1447 return $this->mServer
;
1450 function buildConcat( $stringList ) {
1451 return implode( ' || ', $stringList );
1454 public function getSearchEngine() {
1455 return 'SearchPostgres';
1457 } // end DatabasePostgres class