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 = '" .
143 pg_escape_string( $this->mConn
, $name ) . "' AND n.nspname = '" . pg_escape_string( $this->mConn
, $wgDBmwschema ) ."'";
144 $res = $this->doQuery( $SQL );
145 return $this->numRows( $res );
148 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 ) {
149 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
153 * Usually aborts on failure
154 * If the failFunction is set to a non-zero integer, returns success
156 function open( $server, $user, $password, $dbName ) {
157 # Test for Postgres support, to avoid suppressed fatal error
158 if ( !function_exists( 'pg_connect' ) ) {
159 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" );
164 if ( !strlen( $user ) ) { # e.g. the class is being loaded
168 $this->mServer
= $server;
169 $this->mPort
= $port = $wgDBport;
170 $this->mUser
= $user;
171 $this->mPassword
= $password;
172 $this->mDBname
= $dbName;
174 $connectVars = array(
177 'password' => $password
179 if ( $server != false && $server != '' ) {
180 $connectVars['host'] = $server;
182 if ( $port != false && $port != '' ) {
183 $connectVars['port'] = $port;
185 $connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
187 $this->installErrorHandler();
188 $this->mConn
= pg_connect( $connectString );
189 $phpError = $this->restoreErrorHandler();
191 if ( !$this->mConn
) {
192 wfDebug( "DB connection error\n" );
193 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
194 wfDebug( $this->lastError() . "\n" );
195 if ( !$this->mFailFunction
) {
196 throw new DBConnectionError( $this, $phpError );
202 $this->mOpened
= true;
204 global $wgCommandLineMode;
205 # If called from the command-line (e.g. importDump), only show errors
206 if ( $wgCommandLineMode ) {
207 $this->doQuery( "SET client_min_messages = 'ERROR'" );
210 $this->doQuery( "SET client_encoding='UTF8'" );
212 global $wgDBmwschema, $wgDBts2schema;
213 if ( isset( $wgDBmwschema ) && isset( $wgDBts2schema )
214 && $wgDBmwschema !== 'mediawiki'
215 && preg_match( '/^\w+$/', $wgDBmwschema )
216 && preg_match( '/^\w+$/', $wgDBts2schema )
218 $safeschema = $this->quote_ident( $wgDBmwschema );
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();
384 return true; // Reconnect as regular user
388 if ( !defined( 'POSTGRES_SEARCHPATH' ) ) {
390 if ( $this->numeric_version
< 8.3 ) {
391 // Do we have the basic tsearch2 table?
392 print '<li>Checking for tsearch2 in the schema "' . htmlspecialchars( $wgDBts2schema ) . '"...';
393 if ( !$this->tableExists( 'pg_ts_dict', $wgDBts2schema ) ) {
394 print '<b>FAILED</b>. Make sure tsearch2 is installed. See <a href="';
395 print 'http://www.devx.com/opensource/Article/21674/0/page/2">this article</a>';
396 print " for instructions.</li>\n";
401 // Does this user have the rights to the tsearch2 tables?
402 $ctype = pg_fetch_result( $this->doQuery( 'SHOW lc_ctype' ), 0, 0 );
403 print '<li>Checking tsearch2 permissions...';
404 // Let's check all four, just to be safe
405 error_reporting( 0 );
406 $ts2tables = array( 'cfg', 'cfgmap', 'dict', 'parser' );
407 $safetsschema = $this->quote_ident( $wgDBts2schema );
408 foreach ( $ts2tables as $tname ) {
409 $SQL = "SELECT count(*) FROM $safetsschema.pg_ts_$tname";
410 $res = $this->doQuery( $SQL );
412 print "<b>FAILED</b> to access " . htmlspecialchars( "pg_ts_$tname" ) .
413 ". Make sure that the user \"". htmlspecialchars( $wgDBuser ) .
414 "\" has SELECT access to all four tsearch2 tables</li>\n";
418 $SQL = "SELECT ts_name FROM $safetsschema.pg_ts_cfg WHERE locale = " . $this->addQuotes( $ctype ) ;
419 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
420 $res = $this->doQuery( $SQL );
421 error_reporting( E_ALL
);
423 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
428 // Will the current locale work? Can we force it to?
429 print '<li>Verifying tsearch2 locale with ' . htmlspecialchars( $ctype ) . '...';
430 $rows = $this->numRows( $res );
433 print "<b>not found</b></li>\n";
434 print '<li>Attempting to set default tsearch2 locale to "' . htmlspecialchars( $ctype ) . '"...';
437 $tsname = pg_fetch_result( $res, 0, 0 );
438 if ( $tsname != 'default' ) {
439 print "<b>not set to default (" . htmlspecialchars( $tsname ) . ")</b>";
440 print "<li>Attempting to change tsearch2 default locale to \"" .
441 htmlspecialchars( $ctype ) . "\"...";
445 if ( $resetlocale ) {
446 $SQL = "UPDATE $safetsschema.pg_ts_cfg SET locale = " . $this->addQuotes( $ctype ) . " WHERE ts_name = 'default'";
447 $res = $this->doQuery( $SQL );
449 print '<b>FAILED</b>. ';
450 print 'Please make sure that the locale in pg_ts_cfg for "default" is set to "' .
451 htmlspecialchars( $ctype ) . "\"</li>\n";
457 // Final test: try out a simple tsearch2 query
458 $SQL = "SELECT $safetsschema.to_tsvector('default','MediaWiki tsearch2 testing')";
459 $res = $this->doQuery( $SQL );
461 print '<b>FAILED</b>. Specifically, "' . htmlspecialchars( $SQL ) . '" did not work.</li>';
467 // Install plpgsql if needed
468 $this->setup_plpgsql();
470 // Does the schema already exist? Who owns it?
471 $result = $this->schemaExists( $wgDBmwschema );
473 print '<li>Creating schema <b>' . htmlspecialchars( $wgDBmwschema ) . '</b> ...';
474 error_reporting( 0 );
475 $safeschema = $this->quote_ident( $wgDBmwschema );
476 $result = $this->doQuery( "CREATE SCHEMA $safeschema" );
477 error_reporting( E_ALL
);
479 print '<b>FAILED</b>. The user "' . htmlspecialchars( $wgDBuser ) .
480 '" must be able to access the schema. '.
481 'You can try making them the owner of the database, or try creating the schema with a '.
482 'different user, and then grant access to the "' .
483 htmlspecialchars( $wgDBuser ) . "\" user.</li>\n";
487 } elseif ( $result != $wgDBuser ) {
488 print '<li>Schema "' . htmlspecialchars( $wgDBmwschema ) . '" exists but is not owned by "' .
489 htmlspecialchars( $wgDBuser ) . "\". Not ideal.</li>\n";
491 print '<li>Schema "' . htmlspecialchars( $wgDBmwschema ) . '" exists and is owned by "' .
492 htmlspecialchars( $wgDBuser ) . "\". Excellent.</li>\n";
495 // Always return GMT time to accomodate the existing integer-based timestamp assumption
496 print "<li>Setting the timezone to GMT for user \"" . htmlspecialchars( $wgDBuser ) . '" ...';
497 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
498 $result = pg_query( $this->mConn
, $SQL );
500 print "<b>FAILED</b>.</li>\n";
504 // Set for the rest of this session
505 $SQL = "SET timezone = 'GMT'";
506 $result = pg_query( $this->mConn
, $SQL );
508 print "<li>Failed to set timezone</li>\n";
512 print '<li>Setting the datestyle to ISO, YMD for user "' . htmlspecialchars( $wgDBuser ) . '" ...';
513 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
514 $result = pg_query( $this->mConn
, $SQL );
516 print "<b>FAILED</b>.</li>\n";
520 // Set for the rest of this session
521 $SQL = "SET datestyle = 'ISO, YMD'";
522 $result = pg_query( $this->mConn
, $SQL );
524 print "<li>Failed to set datestyle</li>\n";
528 // Fix up the search paths if needed
529 print '<li>Setting the search path for user "' . htmlspecialchars( $wgDBuser ) . '" ...';
530 $path = $this->quote_ident( $wgDBmwschema );
531 if ( $wgDBts2schema !== $wgDBmwschema ) {
532 $path .= ', '. $this->quote_ident( $wgDBts2schema );
534 if ( $wgDBmwschema !== 'public' && $wgDBts2schema !== 'public' ) {
537 $SQL = "ALTER USER $safeuser SET search_path = $path";
538 $result = pg_query( $this->mConn
, $SQL );
540 print "<b>FAILED</b>.</li>\n";
544 // Set for the rest of this session
545 $SQL = "SET search_path = $path";
546 $result = pg_query( $this->mConn
, $SQL );
548 print "<li>Failed to set search_path</li>\n";
551 define( 'POSTGRES_SEARCHPATH', $path );
555 function setup_plpgsql() {
556 print '<li>Checking for PL/pgSQL ...';
557 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
558 $rows = $this->numRows( $this->doQuery( $SQL ) );
560 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
561 print 'not installed. Attempting to install PL/pgSQL ...';
562 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
563 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
564 $rows = $this->numRows( $this->doQuery( $SQL ) );
567 $olde = error_reporting( 0 );
568 error_reporting( $olde - E_WARNING
);
569 $result = $this->doQuery( 'CREATE LANGUAGE plpgsql' );
570 error_reporting( $olde );
572 print '<b>FAILED</b>. You need to install the language PL/pgSQL in the database <tt>' .
573 htmlspecialchars( $wgDBname ) . '</tt></li>';
577 print '<b>FAILED</b>. You need to install the language PL/pgSQL in the database <tt>' .
578 htmlspecialchars( $wgDBname ) . '</tt></li>';
586 * Closes a database connection, if it is open
587 * Returns success, true if already closed
590 $this->mOpened
= false;
591 if ( $this->mConn
) {
592 return pg_close( $this->mConn
);
598 function doQuery( $sql ) {
599 if ( function_exists( 'mb_convert_encoding' ) ) {
600 $sql = mb_convert_encoding( $sql, 'UTF-8' );
602 $this->mLastResult
= pg_query( $this->mConn
, $sql );
603 $this->mAffectedRows
= null; // use pg_affected_rows(mLastResult)
604 return $this->mLastResult
;
607 function queryIgnore( $sql, $fname = '' ) {
608 return $this->query( $sql, $fname, true );
611 function freeResult( $res ) {
612 if ( $res instanceof ResultWrapper
) {
615 if ( !@pg_free_result
( $res ) ) {
616 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
620 function fetchObject( $res ) {
621 if ( $res instanceof ResultWrapper
) {
624 @$row = pg_fetch_object( $res );
625 # FIXME: HACK HACK HACK HACK debug
628 # hashar : not sure if the following test really trigger if the object
630 if( pg_last_error( $this->mConn
) ) {
631 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
636 function fetchRow( $res ) {
637 if ( $res instanceof ResultWrapper
) {
640 @$row = pg_fetch_array( $res );
641 if( pg_last_error( $this->mConn
) ) {
642 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
647 function numRows( $res ) {
648 if ( $res instanceof ResultWrapper
) {
651 @$n = pg_num_rows( $res );
652 if( pg_last_error( $this->mConn
) ) {
653 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
658 function numFields( $res ) {
659 if ( $res instanceof ResultWrapper
) {
662 return pg_num_fields( $res );
665 function fieldName( $res, $n ) {
666 if ( $res instanceof ResultWrapper
) {
669 return pg_field_name( $res, $n );
673 * This must be called after nextSequenceVal
675 function insertId() {
676 return $this->mInsertId
;
679 function dataSeek( $res, $row ) {
680 if ( $res instanceof ResultWrapper
) {
683 return pg_result_seek( $res, $row );
686 function lastError() {
687 if ( $this->mConn
) {
688 return pg_last_error();
690 return 'No database connection';
693 function lastErrno() {
694 return pg_last_error() ?
1 : 0;
697 function affectedRows() {
698 if ( !is_null( $this->mAffectedRows
) ) {
699 // Forced result for simulated queries
700 return $this->mAffectedRows
;
702 if( empty( $this->mLastResult
) ) {
705 return pg_affected_rows( $this->mLastResult
);
709 * Estimate rows in dataset
710 * Returns estimated count, based on EXPLAIN output
711 * This is not necessarily an accurate estimate, so use sparingly
712 * Returns -1 if count cannot be found
713 * Takes same arguments as Database::select()
715 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
716 $options['EXPLAIN'] = true;
717 $res = $this->select( $table, $vars, $conds, $fname, $options );
720 $row = $this->fetchRow( $res );
722 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
730 * Returns information about an index
731 * If errors are explicitly ignored, returns NULL on failure
733 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
734 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
735 $res = $this->query( $sql, $fname );
739 foreach ( $res as $row ) {
740 if ( $row->indexname
== $this->indexName( $index ) ) {
747 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
748 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
749 " AND indexdef LIKE 'CREATE UNIQUE%(" .
750 $this->strencode( $this->indexName( $index ) ) .
752 $res = $this->query( $sql, $fname );
756 foreach ( $res as $row ) {
764 * INSERT wrapper, inserts an array into a table
766 * $args may be a single associative array, or an array of these with numeric keys,
767 * for multi-row insert (Postgres version 8.2 and above only).
769 * @param $table String: Name of the table to insert to.
770 * @param $args Array: Items to insert into the table.
771 * @param $fname String: Name of the function, for profiling
772 * @param $options String or Array. Valid options: IGNORE
774 * @return bool Success of insert operation. IGNORE always returns true.
776 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
777 if ( !count( $args ) ) {
781 $table = $this->tableName( $table );
782 if (! isset( $this->numeric_version
) ) {
783 $this->getServerVersion();
786 if ( !is_array( $options ) ) {
787 $options = array( $options );
790 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
792 $keys = array_keys( $args[0] );
795 $keys = array_keys( $args );
798 // If IGNORE is set, we use savepoints to emulate mysql's behavior
799 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
801 // If we are not in a transaction, we need to be for savepoint trickery
804 if ( !$this->mTrxLevel
) {
808 $olde = error_reporting( 0 );
809 // For future use, we may want to track the number of actual inserts
810 // Right now, insert (all writes) simply return true/false
811 $numrowsinserted = 0;
814 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
817 if ( $this->numeric_version
>= 8.2 && !$ignore ) {
819 foreach ( $args as $row ) {
825 $sql .= '(' . $this->makeList( $row ) . ')';
827 $res = (bool)$this->query( $sql, $fname, $ignore );
831 foreach ( $args as $row ) {
833 $tempsql .= '(' . $this->makeList( $row ) . ')';
836 pg_query( $this->mConn
, "SAVEPOINT $ignore" );
839 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
842 $bar = pg_last_error();
843 if ( $bar != false ) {
844 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
846 pg_query( $this->mConn
, "RELEASE $ignore" );
851 // If any of them fail, we fail overall for this function call
852 // Note that this will be ignored if IGNORE is set
859 // Not multi, just a lone insert
861 pg_query($this->mConn
, "SAVEPOINT $ignore");
864 $sql .= '(' . $this->makeList( $args ) . ')';
865 $res = (bool)$this->query( $sql, $fname, $ignore );
867 $bar = pg_last_error();
868 if ( $bar != false ) {
869 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
871 pg_query( $this->mConn
, "RELEASE $ignore" );
877 $olde = error_reporting( $olde );
882 // Set the affected row count for the whole operation
883 $this->mAffectedRows
= $numrowsinserted;
885 // IGNORE always returns true
893 * INSERT SELECT wrapper
894 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
895 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
896 * $conds may be "*" to copy the whole table
897 * srcTable may be an array of tables.
898 * @todo FIXME: implement this a little better (seperate select/insert)?
900 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
901 $insertOptions = array(), $selectOptions = array() )
903 $destTable = $this->tableName( $destTable );
905 // If IGNORE is set, we use savepoints to emulate mysql's behavior
906 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
908 if( is_array( $insertOptions ) ) {
909 $insertOptions = implode( ' ', $insertOptions );
911 if( !is_array( $selectOptions ) ) {
912 $selectOptions = array( $selectOptions );
914 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
915 if( is_array( $srcTable ) ) {
916 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
918 $srcTable = $this->tableName( $srcTable );
921 // If we are not in a transaction, we need to be for savepoint trickery
924 if( !$this->mTrxLevel
) {
928 $olde = error_reporting( 0 );
929 $numrowsinserted = 0;
930 pg_query( $this->mConn
, "SAVEPOINT $ignore");
933 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
934 " SELECT $startOpts " . implode( ',', $varMap ) .
935 " FROM $srcTable $useIndex";
937 if ( $conds != '*' ) {
938 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
941 $sql .= " $tailOpts";
943 $res = (bool)$this->query( $sql, $fname, $ignore );
945 $bar = pg_last_error();
946 if( $bar != false ) {
947 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
949 pg_query( $this->mConn
, "RELEASE $ignore" );
952 $olde = error_reporting( $olde );
957 // Set the affected row count for the whole operation
958 $this->mAffectedRows
= $numrowsinserted;
960 // IGNORE always returns true
967 function tableName( $name ) {
968 # Replace reserved words with better ones
973 return 'pagecontent';
980 * Return the next in a sequence, save the value for retrieval via insertId()
982 function nextSequenceValue( $seqName ) {
983 $safeseq = preg_replace( "/'/", "''", $seqName );
984 $res = $this->query( "SELECT nextval('$safeseq')" );
985 $row = $this->fetchRow( $res );
986 $this->mInsertId
= $row[0];
987 return $this->mInsertId
;
991 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
993 function currentSequenceValue( $seqName ) {
994 $safeseq = preg_replace( "/'/", "''", $seqName );
995 $res = $this->query( "SELECT currval('$safeseq')" );
996 $row = $this->fetchRow( $res );
1002 * REPLACE query wrapper
1003 * Postgres simulates this with a DELETE followed by INSERT
1004 * $row is the row to insert, an associative array
1005 * $uniqueIndexes is an array of indexes. Each element may be either a
1006 * field name or an array of field names
1008 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1009 * However if you do this, you run the risk of encountering errors which wouldn't have
1012 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
1013 $table = $this->tableName( $table );
1015 if ( count( $rows ) == 0 ) {
1020 if ( !is_array( reset( $rows ) ) ) {
1021 $rows = array( $rows );
1024 foreach( $rows as $row ) {
1025 # Delete rows which collide
1026 if ( $uniqueIndexes ) {
1027 $sql = "DELETE FROM $table WHERE ";
1029 foreach ( $uniqueIndexes as $index ) {
1036 if ( is_array( $index ) ) {
1038 foreach ( $index as $col ) {
1044 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
1047 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1051 $this->query( $sql, $fname );
1054 # Now insert the row
1055 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
1056 $this->makeList( $row, LIST_COMMA
) . ')';
1057 $this->query( $sql, $fname );
1061 # DELETE where the condition is a join
1062 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
1064 throw new DBUnexpectedError( $this, 'DatabasePostgres::deleteJoin() called with empty $conds' );
1067 $delTable = $this->tableName( $delTable );
1068 $joinTable = $this->tableName( $joinTable );
1069 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1070 if ( $conds != '*' ) {
1071 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1075 $this->query( $sql, $fname );
1078 # Returns the size of a text field, or -1 for "unlimited"
1079 function textFieldSize( $table, $field ) {
1080 $table = $this->tableName( $table );
1081 $sql = "SELECT t.typname as ftype,a.atttypmod as size
1082 FROM pg_class c, pg_attribute a, pg_type t
1083 WHERE relname='$table' AND a.attrelid=c.oid AND
1084 a.atttypid=t.oid and a.attname='$field'";
1085 $res =$this->query( $sql );
1086 $row = $this->fetchObject( $res );
1087 if ( $row->ftype
== 'varchar' ) {
1088 $size = $row->size
- 4;
1095 function limitResult( $sql, $limit, $offset = false ) {
1096 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " : '' );
1099 function wasDeadlock() {
1100 return $this->lastErrno() == '40P01';
1103 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
1104 return $this->query( 'CREATE ' . ( $temporary ?
'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
1107 function timestamp( $ts = 0 ) {
1108 return wfTimestamp( TS_POSTGRES
, $ts );
1112 * Return aggregated value function call
1114 function aggregateValue( $valuedata, $valuename = 'value' ) {
1118 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1119 // Ignore errors during error handling to avoid infinite recursion
1120 $ignore = $this->ignoreErrors( true );
1121 $this->mErrorCount++
;
1123 if ( $ignore ||
$tempIgnore ) {
1124 wfDebug( "SQL ERROR (ignored): $error\n" );
1125 $this->ignoreErrors( $ignore );
1127 $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" .
1129 "Function: $fname\n" .
1130 "Error: $errno $error\n";
1131 throw new DBUnexpectedError( $this, $message );
1136 * @return string wikitext of a link to the server software's web site
1138 public static function getSoftwareLink() {
1139 return '[http://www.postgresql.org/ PostgreSQL]';
1143 * @return string Version information from the database
1145 function getServerVersion() {
1146 if ( !isset( $this->numeric_version
) ) {
1147 $versionInfo = pg_version( $this->mConn
);
1148 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1149 // Old client, abort install
1150 $this->numeric_version
= '7.3 or earlier';
1151 } elseif ( isset( $versionInfo['server'] ) ) {
1153 $this->numeric_version
= $versionInfo['server'];
1155 // Bug 16937: broken pgsql extension from PHP<5.3
1156 $this->numeric_version
= pg_parameter_status( $this->mConn
, 'server_version' );
1159 return $this->numeric_version
;
1163 * Query whether a given relation exists (in the given schema, or the
1164 * default mw one if not given)
1166 function relationExists( $table, $types, $schema = false ) {
1167 global $wgDBmwschema;
1168 if ( !is_array( $types ) ) {
1169 $types = array( $types );
1172 $schema = $wgDBmwschema;
1174 $etable = $this->addQuotes( $table );
1175 $eschema = $this->addQuotes( $schema );
1176 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1177 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1178 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1179 $res = $this->query( $SQL );
1180 $count = $res ?
$res->numRows() : 0;
1181 return (bool)$count;
1185 * For backward compatibility, this function checks both tables and
1188 function tableExists( $table, $schema = false ) {
1189 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1192 function sequenceExists( $sequence, $schema = false ) {
1193 return $this->relationExists( $sequence, 'S', $schema );
1196 function triggerExists( $table, $trigger ) {
1197 global $wgDBmwschema;
1200 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1201 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1202 AND tgrelid=pg_class.oid
1203 AND nspname=%s AND relname=%s AND tgname=%s
1205 $res = $this->query(
1208 $this->addQuotes( $wgDBmwschema ),
1209 $this->addQuotes( $table ),
1210 $this->addQuotes( $trigger )
1216 $rows = $res->numRows();
1220 function ruleExists( $table, $rule ) {
1221 global $wgDBmwschema;
1222 $exists = $this->selectField( 'pg_rules', 'rulename',
1224 'rulename' => $rule,
1225 'tablename' => $table,
1226 'schemaname' => $wgDBmwschema
1229 return $exists === $rule;
1232 function constraintExists( $table, $constraint ) {
1233 global $wgDBmwschema;
1234 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
1235 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1236 $this->addQuotes( $wgDBmwschema ),
1237 $this->addQuotes( $table ),
1238 $this->addQuotes( $constraint )
1240 $res = $this->query( $SQL );
1244 $rows = $res->numRows();
1249 * Query whether a given schema exists. Returns the name of the owner
1251 function schemaExists( $schema ) {
1252 $eschema = preg_replace( "/'/", "''", $schema );
1253 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1254 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1255 $res = $this->query( $SQL );
1256 if ( $res && $res->numRows() ) {
1257 $row = $res->fetchObject();
1258 $owner = $row->rolname
;
1265 function fieldInfo( $table, $field ) {
1266 return PostgresField
::fromText( $this, $table, $field );
1270 * pg_field_type() wrapper
1272 function fieldType( $res, $index ) {
1273 if ( $res instanceof ResultWrapper
) {
1274 $res = $res->result
;
1276 return pg_field_type( $res, $index );
1279 /* Not even sure why this is used in the main codebase... */
1280 function limitResultForUpdate( $sql, $num ) {
1284 function setup_database() {
1285 global $wgDBmwschema, $wgDBuser;
1287 // Make sure that we can write to the correct schema
1288 // If not, Postgres will happily and silently go to the next search_path item
1289 $ctest = 'mediawiki_test_table';
1290 $safeschema = $this->quote_ident( $wgDBmwschema );
1291 if ( $this->tableExists( $ctest, $wgDBmwschema ) ) {
1292 $this->doQuery( "DROP TABLE $safeschema.$ctest" );
1294 $SQL = "CREATE TABLE $safeschema.$ctest(a int)";
1295 $olde = error_reporting( 0 );
1296 $res = $this->doQuery( $SQL );
1297 error_reporting( $olde );
1299 print '<b>FAILED</b>. Make sure that the user "' . htmlspecialchars( $wgDBuser ) .
1300 '" can write to the schema "' . htmlspecialchars( $wgDBmwschema ) . "\"</li>\n";
1301 dieout( '' ); # Will close the main list <ul> and finish the page.
1303 $this->doQuery( "DROP TABLE $safeschema.$ctest" );
1305 $res = $this->sourceFile( "../maintenance/postgres/tables.sql" );
1306 if ( $res === true ) {
1307 print " done.</li>\n";
1309 print " <b>FAILED</b></li>\n";
1310 dieout( htmlspecialchars( $res ) );
1313 echo '<li>Populating interwiki table... ';
1314 # Avoid the non-standard "REPLACE INTO" syntax
1315 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1317 print '<b>FAILED</b></li>';
1318 dieout( 'Could not find the interwiki.sql file' );
1320 # We simply assume it is already empty as we have just created it
1321 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1322 while ( !feof( $f ) ) {
1323 $line = fgets( $f, 1024 );
1325 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) {
1328 $this->query( "$SQL $matches[1],$matches[2])" );
1330 print " successfully populated.</li>\n";
1332 $this->doQuery( 'COMMIT' );
1335 function encodeBlob( $b ) {
1336 return new Blob( pg_escape_bytea( $this->mConn
, $b ) );
1339 function decodeBlob( $b ) {
1340 if ( $b instanceof Blob
) {
1343 return pg_unescape_bytea( $b );
1346 function strencode( $s ) { # Should not be called by us
1347 return pg_escape_string( $this->mConn
, $s );
1350 function addQuotes( $s ) {
1351 if ( is_null( $s ) ) {
1353 } elseif ( is_bool( $s ) ) {
1354 return intval( $s );
1355 } elseif ( $s instanceof Blob
) {
1356 return "'" . $s->fetch( $s ) . "'";
1358 return "'" . pg_escape_string( $this->mConn
, $s ) . "'";
1361 function quote_ident( $s ) {
1362 return '"' . preg_replace( '/"/', '""', $s ) . '"';
1366 * Postgres specific version of replaceVars.
1367 * Calls the parent version in Database.php
1371 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1373 * @return string SQL string
1375 protected function replaceVars( $ins ) {
1376 $ins = parent
::replaceVars( $ins );
1378 if ( $this->numeric_version
>= 8.3 ) {
1379 // Thanks for not providing backwards-compatibility, 8.3
1380 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1383 if ( $this->numeric_version
<= 8.1 ) { // Our minimum version
1384 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1391 * Various select options
1395 * @param $options Array: an associative array of options to be turned into
1396 * an SQL query, valid keys are listed in the function.
1399 function makeSelectOptions( $options ) {
1400 $preLimitTail = $postLimitTail = '';
1401 $startOpts = $useIndex = '';
1403 $noKeyOptions = array();
1404 foreach ( $options as $key => $option ) {
1405 if ( is_numeric( $key ) ) {
1406 $noKeyOptions[$option] = true;
1410 if ( isset( $options['GROUP BY'] ) ) {
1411 $preLimitTail .= ' GROUP BY ' . $options['GROUP BY'];
1413 if ( isset( $options['HAVING'] ) ) {
1414 $preLimitTail .= " HAVING {$options['HAVING']}";
1416 if ( isset( $options['ORDER BY'] ) ) {
1417 $preLimitTail .= ' ORDER BY ' . $options['ORDER BY'];
1420 //if ( isset( $options['LIMIT'] ) ) {
1421 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1422 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1426 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1427 $postLimitTail .= ' FOR UPDATE';
1429 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1430 $postLimitTail .= ' LOCK IN SHARE MODE';
1432 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1433 $startOpts .= 'DISTINCT';
1436 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1439 function setFakeMaster( $enabled = true ) {}
1441 function getDBname() {
1442 return $this->mDBname
;
1445 function getServer() {
1446 return $this->mServer
;
1449 function buildConcat( $stringList ) {
1450 return implode( ' || ', $stringList );
1453 public function getSearchEngine() {
1454 return 'SearchPostgres';
1456 } // end DatabasePostgres class