3 * This is the Postgres database abstraction layer.
9 class PostgresField
implements Field
{
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
;
72 function isNullable() {
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,
106 $this->mFlags
= $flags;
107 $this->open( $server, $user, $password, $dbName );
114 function cascadingDeletes() {
117 function cleanupTriggers() {
120 function strictIPs() {
123 function realTimestamps() {
126 function implicitGroupby() {
129 function implicitOrderby() {
132 function searchableIPs() {
135 function functionalIndexes() {
139 function hasConstraint( $name ) {
140 global $wgDBmwschema;
141 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" .
142 pg_escape_string( $this->mConn
, $name ) . "' AND n.nspname = '" . pg_escape_string( $this->mConn
, $wgDBmwschema ) ."'";
143 $res = $this->doQuery( $SQL );
144 return $this->numRows( $res );
148 * Usually aborts on failure
150 function open( $server, $user, $password, $dbName ) {
151 # Test for Postgres support, to avoid suppressed fatal error
152 if ( !function_exists( 'pg_connect' ) ) {
153 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" );
158 if ( !strlen( $user ) ) { # e.g. the class is being loaded
162 $this->mServer
= $server;
163 $this->mPort
= $port = $wgDBport;
164 $this->mUser
= $user;
165 $this->mPassword
= $password;
166 $this->mDBname
= $dbName;
168 $connectVars = array(
171 'password' => $password
173 if ( $server != false && $server != '' ) {
174 $connectVars['host'] = $server;
176 if ( $port != false && $port != '' ) {
177 $connectVars['port'] = $port;
179 $connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
181 $this->installErrorHandler();
182 $this->mConn
= pg_connect( $connectString );
183 $phpError = $this->restoreErrorHandler();
185 if ( !$this->mConn
) {
186 wfDebug( "DB connection error\n" );
187 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
188 wfDebug( $this->lastError() . "\n" );
189 throw new DBConnectionError( $this, $phpError );
192 $this->mOpened
= true;
194 global $wgCommandLineMode;
195 # If called from the command-line (e.g. importDump), only show errors
196 if ( $wgCommandLineMode ) {
197 $this->doQuery( "SET client_min_messages = 'ERROR'" );
200 $this->doQuery( "SET client_encoding='UTF8'" );
202 global $wgDBmwschema, $wgDBts2schema;
203 if ( isset( $wgDBmwschema ) && isset( $wgDBts2schema )
204 && $wgDBmwschema !== 'mediawiki'
205 && preg_match( '/^\w+$/', $wgDBmwschema )
206 && preg_match( '/^\w+$/', $wgDBts2schema )
208 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
209 $this->doQuery( "SET search_path = $safeschema, $wgDBts2schema, public" );
215 function makeConnectionString( $vars ) {
217 foreach ( $vars as $name => $value ) {
218 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
224 function initial_setup( $superuser, $password, $dbName ) {
225 // If this is the initial connection, setup the schema stuff and possibly create the user
226 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBmwschema, $wgDBts2schema;
228 $safeuser = $this->addIdentifierQuotes( $wgDBuser );
229 // Are we connecting as a superuser for the first time?
231 // Are we really a superuser? Check out our rights
233 CASE WHEN usesuper IS TRUE THEN
234 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
235 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
237 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes( $superuser );
238 $rows = $this->numRows( $res = $this->doQuery( $SQL ) );
240 print '<li>ERROR: Could not read permissions for user "' . htmlspecialchars( $superuser ) . "\"</li>\n";
243 $perms = pg_fetch_result( $res, 0, 0 );
245 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes( $wgDBuser );
246 $rows = $this->numRows( $this->doQuery( $SQL ) );
248 print '<li>User "' . htmlspecialchars( $wgDBuser ) . '" already exists, skipping account creation.</li>';
250 if ( $perms != 1 && $perms != 3 ) {
251 print '<li>ERROR: the user "' . htmlspecialchars( $superuser ) . '" cannot create other users. ';
252 print 'Please use a different Postgres user.</li>';
255 print '<li>Creating user <b>' . htmlspecialchars( $wgDBuser ) . '</b>...';
256 $safepass = $this->addQuotes( $wgDBpassword );
257 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
258 $this->doQuery( $SQL );
261 // User now exists, check out the database
262 if ( $dbName != $wgDBname ) {
263 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes( $wgDBname );
264 $rows = $this->numRows( $this->doQuery( $SQL ) );
266 print '<li>Database "' . htmlspecialchars( $wgDBname ) . '" already exists, skipping database creation.</li>';
269 print '<li>ERROR: the user "' . htmlspecialchars( $superuser ) . '" cannot create databases. ';
270 print 'Please use a different Postgres user.</li>';
273 print '<li>Creating database <b>' . htmlspecialchars( $wgDBname ) . '</b>...';
274 $safename = $this->addIdentifierQuotes( $wgDBname );
275 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
276 $this->doQuery( $SQL );
278 // Hopefully tsearch2 and plpgsql are in template1...
281 // Reconnect to check out tsearch2 rights for this user
282 print '<li>Connecting to "' . htmlspecialchars( $wgDBname ) . '" as superuser "' .
283 htmlspecialchars( $superuser ) . '" to check rights...';
285 $connectVars = array();
286 if ( $this->mServer
!= false && $this->mServer
!= '' ) {
287 $connectVars['host'] = $this->mServer
;
289 if ( $this->mPort
!= false && $this->mPort
!= '' ) {
290 $connectVars['port'] = $this->mPort
;
292 $connectVars['dbname'] = $wgDBname;
293 $connectVars['user'] = $superuser;
294 $connectVars['password'] = $password;
296 @$this->mConn
= pg_connect( $this->makeConnectionString( $connectVars ) );
297 if ( !$this->mConn
) {
298 print "<b>FAILED TO CONNECT!</b></li>";
304 if ( $this->numeric_version
< 8.3 ) {
306 print '<li>Checking that tsearch2 is installed in the database "' .
307 htmlspecialchars( $wgDBname ) . '"...';
308 if ( !$this->tableExists( 'pg_ts_cfg', $wgDBts2schema ) ) {
309 print '<b>FAILED</b>. tsearch2 must be installed in the database "' .
310 htmlspecialchars( $wgDBname ) . '".';
311 print 'Please see <a href="http://www.devx.com/opensource/Article/21674/0/page/2">this article</a>';
312 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
316 print '<li>Ensuring that user "' . htmlspecialchars( $wgDBuser ) .
317 '" has select rights on the tsearch2 tables...';
318 foreach ( array( 'cfg', 'cfgmap', 'dict', 'parser' ) as $table ) {
319 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
320 $this->doQuery( $SQL );
325 // Setup the schema for this user if needed
326 $result = $this->schemaExists( $wgDBmwschema );
327 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
329 print '<li>Creating schema <b>' . htmlspecialchars( $wgDBmwschema ) . '</b> ...';
330 $result = $this->doQuery( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
332 print "<b>FAILED</b>.</li>\n";
337 print "<li>Schema already exists, explicitly granting rights...\n";
338 $safeschema2 = $this->addQuotes( $wgDBmwschema );
339 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
340 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
341 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
342 "AND p.relkind IN ('r','S','v')\n";
344 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
345 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
346 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
347 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
348 $res = $this->doQuery( $SQL );
350 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
353 $this->doQuery( "SET search_path = $safeschema" );
354 $rows = $this->numRows( $res );
357 $this->doQuery( pg_fetch_result( $res, $rows, 0 ) );
362 // Install plpgsql if needed
363 $this->setup_plpgsql();
365 return true; // Reconnect as regular user
369 if ( !defined( 'POSTGRES_SEARCHPATH' ) ) {
371 if ( $this->numeric_version
< 8.3 ) {
372 // Do we have the basic tsearch2 table?
373 print '<li>Checking for tsearch2 in the schema "' . htmlspecialchars( $wgDBts2schema ) . '"...';
374 if ( !$this->tableExists( 'pg_ts_dict', $wgDBts2schema ) ) {
375 print '<b>FAILED</b>. Make sure tsearch2 is installed. See <a href="';
376 print 'http://www.devx.com/opensource/Article/21674/0/page/2">this article</a>';
377 print " for instructions.</li>\n";
382 // Does this user have the rights to the tsearch2 tables?
383 $ctype = pg_fetch_result( $this->doQuery( 'SHOW lc_ctype' ), 0, 0 );
384 print '<li>Checking tsearch2 permissions...';
385 // Let's check all four, just to be safe
386 error_reporting( 0 );
387 $ts2tables = array( 'cfg', 'cfgmap', 'dict', 'parser' );
388 $safetsschema = $this->addIdentifierQuotes( $wgDBts2schema );
389 foreach ( $ts2tables as $tname ) {
390 $SQL = "SELECT count(*) FROM $safetsschema.pg_ts_$tname";
391 $res = $this->doQuery( $SQL );
393 print "<b>FAILED</b> to access " . htmlspecialchars( "pg_ts_$tname" ) .
394 ". Make sure that the user \"". htmlspecialchars( $wgDBuser ) .
395 "\" has SELECT access to all four tsearch2 tables</li>\n";
399 $SQL = "SELECT ts_name FROM $safetsschema.pg_ts_cfg WHERE locale = " . $this->addQuotes( $ctype ) ;
400 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
401 $res = $this->doQuery( $SQL );
402 error_reporting( E_ALL
);
404 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
409 // Will the current locale work? Can we force it to?
410 print '<li>Verifying tsearch2 locale with ' . htmlspecialchars( $ctype ) . '...';
411 $rows = $this->numRows( $res );
414 print "<b>not found</b></li>\n";
415 print '<li>Attempting to set default tsearch2 locale to "' . htmlspecialchars( $ctype ) . '"...';
418 $tsname = pg_fetch_result( $res, 0, 0 );
419 if ( $tsname != 'default' ) {
420 print "<b>not set to default (" . htmlspecialchars( $tsname ) . ")</b>";
421 print "<li>Attempting to change tsearch2 default locale to \"" .
422 htmlspecialchars( $ctype ) . "\"...";
426 if ( $resetlocale ) {
427 $SQL = "UPDATE $safetsschema.pg_ts_cfg SET locale = " . $this->addQuotes( $ctype ) . " WHERE ts_name = 'default'";
428 $res = $this->doQuery( $SQL );
430 print '<b>FAILED</b>. ';
431 print 'Please make sure that the locale in pg_ts_cfg for "default" is set to "' .
432 htmlspecialchars( $ctype ) . "\"</li>\n";
438 // Final test: try out a simple tsearch2 query
439 $SQL = "SELECT $safetsschema.to_tsvector('default','MediaWiki tsearch2 testing')";
440 $res = $this->doQuery( $SQL );
442 print '<b>FAILED</b>. Specifically, "' . htmlspecialchars( $SQL ) . '" did not work.</li>';
448 // Install plpgsql if needed
449 $this->setup_plpgsql();
451 // Does the schema already exist? Who owns it?
452 $result = $this->schemaExists( $wgDBmwschema );
454 print '<li>Creating schema <b>' . htmlspecialchars( $wgDBmwschema ) . '</b> ...';
455 error_reporting( 0 );
456 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
457 $result = $this->doQuery( "CREATE SCHEMA $safeschema" );
458 error_reporting( E_ALL
);
460 print '<b>FAILED</b>. The user "' . htmlspecialchars( $wgDBuser ) .
461 '" must be able to access the schema. '.
462 'You can try making them the owner of the database, or try creating the schema with a '.
463 'different user, and then grant access to the "' .
464 htmlspecialchars( $wgDBuser ) . "\" user.</li>\n";
468 } elseif ( $result != $wgDBuser ) {
469 print '<li>Schema "' . htmlspecialchars( $wgDBmwschema ) . '" exists but is not owned by "' .
470 htmlspecialchars( $wgDBuser ) . "\". Not ideal.</li>\n";
472 print '<li>Schema "' . htmlspecialchars( $wgDBmwschema ) . '" exists and is owned by "' .
473 htmlspecialchars( $wgDBuser ) . "\". Excellent.</li>\n";
476 // Always return GMT time to accomodate the existing integer-based timestamp assumption
477 print "<li>Setting the timezone to GMT for user \"" . htmlspecialchars( $wgDBuser ) . '" ...';
478 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
479 $result = pg_query( $this->mConn
, $SQL );
481 print "<b>FAILED</b>.</li>\n";
485 // Set for the rest of this session
486 $SQL = "SET timezone = 'GMT'";
487 $result = pg_query( $this->mConn
, $SQL );
489 print "<li>Failed to set timezone</li>\n";
493 print '<li>Setting the datestyle to ISO, YMD for user "' . htmlspecialchars( $wgDBuser ) . '" ...';
494 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
495 $result = pg_query( $this->mConn
, $SQL );
497 print "<b>FAILED</b>.</li>\n";
501 // Set for the rest of this session
502 $SQL = "SET datestyle = 'ISO, YMD'";
503 $result = pg_query( $this->mConn
, $SQL );
505 print "<li>Failed to set datestyle</li>\n";
509 // Fix up the search paths if needed
510 print '<li>Setting the search path for user "' . htmlspecialchars( $wgDBuser ) . '" ...';
511 $path = $this->addIdentifierQuotes( $wgDBmwschema );
512 if ( $wgDBts2schema !== $wgDBmwschema ) {
513 $path .= ', '. $this->addIdentifierQuotes( $wgDBts2schema );
515 if ( $wgDBmwschema !== 'public' && $wgDBts2schema !== 'public' ) {
518 $SQL = "ALTER USER $safeuser SET search_path = $path";
519 $result = pg_query( $this->mConn
, $SQL );
521 print "<b>FAILED</b>.</li>\n";
525 // Set for the rest of this session
526 $SQL = "SET search_path = $path";
527 $result = pg_query( $this->mConn
, $SQL );
529 print "<li>Failed to set search_path</li>\n";
532 define( 'POSTGRES_SEARCHPATH', $path );
537 * Closes a database connection, if it is open
538 * Returns success, true if already closed
541 $this->mOpened
= false;
542 if ( $this->mConn
) {
543 return pg_close( $this->mConn
);
549 function doQuery( $sql ) {
550 if ( function_exists( 'mb_convert_encoding' ) ) {
551 $sql = mb_convert_encoding( $sql, 'UTF-8' );
553 $this->mLastResult
= pg_query( $this->mConn
, $sql );
554 $this->mAffectedRows
= null; // use pg_affected_rows(mLastResult)
555 return $this->mLastResult
;
558 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
559 return $this->query( $sql, $fname, true );
562 function freeResult( $res ) {
563 if ( $res instanceof ResultWrapper
) {
566 if ( !@pg_free_result
( $res ) ) {
567 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
571 function fetchObject( $res ) {
572 if ( $res instanceof ResultWrapper
) {
575 @$row = pg_fetch_object( $res );
576 # FIXME: HACK HACK HACK HACK debug
579 # hashar : not sure if the following test really trigger if the object
581 if( pg_last_error( $this->mConn
) ) {
582 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
587 function fetchRow( $res ) {
588 if ( $res instanceof ResultWrapper
) {
591 @$row = pg_fetch_array( $res );
592 if( pg_last_error( $this->mConn
) ) {
593 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
598 function numRows( $res ) {
599 if ( $res instanceof ResultWrapper
) {
602 @$n = pg_num_rows( $res );
603 if( pg_last_error( $this->mConn
) ) {
604 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
609 function numFields( $res ) {
610 if ( $res instanceof ResultWrapper
) {
613 return pg_num_fields( $res );
616 function fieldName( $res, $n ) {
617 if ( $res instanceof ResultWrapper
) {
620 return pg_field_name( $res, $n );
624 * This must be called after nextSequenceVal
626 function insertId() {
627 return $this->mInsertId
;
630 function dataSeek( $res, $row ) {
631 if ( $res instanceof ResultWrapper
) {
634 return pg_result_seek( $res, $row );
637 function lastError() {
638 if ( $this->mConn
) {
639 return pg_last_error();
641 return 'No database connection';
644 function lastErrno() {
645 return pg_last_error() ?
1 : 0;
648 function affectedRows() {
649 if ( !is_null( $this->mAffectedRows
) ) {
650 // Forced result for simulated queries
651 return $this->mAffectedRows
;
653 if( empty( $this->mLastResult
) ) {
656 return pg_affected_rows( $this->mLastResult
);
660 * Estimate rows in dataset
661 * Returns estimated count, based on EXPLAIN output
662 * This is not necessarily an accurate estimate, so use sparingly
663 * Returns -1 if count cannot be found
664 * Takes same arguments as Database::select()
666 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
667 $options['EXPLAIN'] = true;
668 $res = $this->select( $table, $vars, $conds, $fname, $options );
671 $row = $this->fetchRow( $res );
673 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
681 * Returns information about an index
682 * If errors are explicitly ignored, returns NULL on failure
684 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
685 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
686 $res = $this->query( $sql, $fname );
690 foreach ( $res as $row ) {
691 if ( $row->indexname
== $this->indexName( $index ) ) {
698 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
699 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
700 " AND indexdef LIKE 'CREATE UNIQUE%(" .
701 $this->strencode( $this->indexName( $index ) ) .
703 $res = $this->query( $sql, $fname );
707 foreach ( $res as $row ) {
714 * INSERT wrapper, inserts an array into a table
716 * $args may be a single associative array, or an array of these with numeric keys,
717 * for multi-row insert (Postgres version 8.2 and above only).
719 * @param $table String: Name of the table to insert to.
720 * @param $args Array: Items to insert into the table.
721 * @param $fname String: Name of the function, for profiling
722 * @param $options String or Array. Valid options: IGNORE
724 * @return bool Success of insert operation. IGNORE always returns true.
726 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
727 if ( !count( $args ) ) {
731 $table = $this->tableName( $table );
732 if (! isset( $this->numeric_version
) ) {
733 $this->getServerVersion();
736 if ( !is_array( $options ) ) {
737 $options = array( $options );
740 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
742 $keys = array_keys( $args[0] );
745 $keys = array_keys( $args );
748 // If IGNORE is set, we use savepoints to emulate mysql's behavior
749 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
751 // If we are not in a transaction, we need to be for savepoint trickery
754 if ( !$this->mTrxLevel
) {
758 $olde = error_reporting( 0 );
759 // For future use, we may want to track the number of actual inserts
760 // Right now, insert (all writes) simply return true/false
761 $numrowsinserted = 0;
764 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
767 if ( $this->numeric_version
>= 8.2 && !$ignore ) {
769 foreach ( $args as $row ) {
775 $sql .= '(' . $this->makeList( $row ) . ')';
777 $res = (bool)$this->query( $sql, $fname, $ignore );
781 foreach ( $args as $row ) {
783 $tempsql .= '(' . $this->makeList( $row ) . ')';
786 pg_query( $this->mConn
, "SAVEPOINT $ignore" );
789 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
792 $bar = pg_last_error();
793 if ( $bar != false ) {
794 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
796 pg_query( $this->mConn
, "RELEASE $ignore" );
801 // If any of them fail, we fail overall for this function call
802 // Note that this will be ignored if IGNORE is set
809 // Not multi, just a lone insert
811 pg_query($this->mConn
, "SAVEPOINT $ignore");
814 $sql .= '(' . $this->makeList( $args ) . ')';
815 $res = (bool)$this->query( $sql, $fname, $ignore );
817 $bar = pg_last_error();
818 if ( $bar != false ) {
819 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
821 pg_query( $this->mConn
, "RELEASE $ignore" );
827 $olde = error_reporting( $olde );
832 // Set the affected row count for the whole operation
833 $this->mAffectedRows
= $numrowsinserted;
835 // IGNORE always returns true
843 * INSERT SELECT wrapper
844 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
845 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
846 * $conds may be "*" to copy the whole table
847 * srcTable may be an array of tables.
848 * @todo FIXME: implement this a little better (seperate select/insert)?
850 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
851 $insertOptions = array(), $selectOptions = array() )
853 $destTable = $this->tableName( $destTable );
855 // If IGNORE is set, we use savepoints to emulate mysql's behavior
856 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
858 if( is_array( $insertOptions ) ) {
859 $insertOptions = implode( ' ', $insertOptions );
861 if( !is_array( $selectOptions ) ) {
862 $selectOptions = array( $selectOptions );
864 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
865 if( is_array( $srcTable ) ) {
866 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
868 $srcTable = $this->tableName( $srcTable );
871 // If we are not in a transaction, we need to be for savepoint trickery
874 if( !$this->mTrxLevel
) {
878 $olde = error_reporting( 0 );
879 $numrowsinserted = 0;
880 pg_query( $this->mConn
, "SAVEPOINT $ignore");
883 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
884 " SELECT $startOpts " . implode( ',', $varMap ) .
885 " FROM $srcTable $useIndex";
887 if ( $conds != '*' ) {
888 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
891 $sql .= " $tailOpts";
893 $res = (bool)$this->query( $sql, $fname, $ignore );
895 $bar = pg_last_error();
896 if( $bar != false ) {
897 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
899 pg_query( $this->mConn
, "RELEASE $ignore" );
902 $olde = error_reporting( $olde );
907 // Set the affected row count for the whole operation
908 $this->mAffectedRows
= $numrowsinserted;
910 // IGNORE always returns true
917 function tableName( $name ) {
918 # Replace reserved words with better ones
923 return 'pagecontent';
930 * Return the next in a sequence, save the value for retrieval via insertId()
932 function nextSequenceValue( $seqName ) {
933 $safeseq = str_replace( "'", "''", $seqName );
934 $res = $this->query( "SELECT nextval('$safeseq')" );
935 $row = $this->fetchRow( $res );
936 $this->mInsertId
= $row[0];
937 return $this->mInsertId
;
941 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
943 function currentSequenceValue( $seqName ) {
944 $safeseq = str_replace( "'", "''", $seqName );
945 $res = $this->query( "SELECT currval('$safeseq')" );
946 $row = $this->fetchRow( $res );
952 * REPLACE query wrapper
953 * Postgres simulates this with a DELETE followed by INSERT
954 * $row is the row to insert, an associative array
955 * $uniqueIndexes is an array of indexes. Each element may be either a
956 * field name or an array of field names
958 * It may be more efficient to leave off unique indexes which are unlikely to collide.
959 * However if you do this, you run the risk of encountering errors which wouldn't have
962 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
963 $table = $this->tableName( $table );
965 if ( count( $rows ) == 0 ) {
970 if ( !is_array( reset( $rows ) ) ) {
971 $rows = array( $rows );
974 foreach( $rows as $row ) {
975 # Delete rows which collide
976 if ( $uniqueIndexes ) {
977 $sql = "DELETE FROM $table WHERE ";
979 foreach ( $uniqueIndexes as $index ) {
986 if ( is_array( $index ) ) {
988 foreach ( $index as $col ) {
994 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
997 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1001 $this->query( $sql, $fname );
1004 # Now insert the row
1005 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
1006 $this->makeList( $row, LIST_COMMA
) . ')';
1007 $this->query( $sql, $fname );
1011 # DELETE where the condition is a join
1012 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
1014 throw new DBUnexpectedError( $this, 'DatabasePostgres::deleteJoin() called with empty $conds' );
1017 $delTable = $this->tableName( $delTable );
1018 $joinTable = $this->tableName( $joinTable );
1019 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1020 if ( $conds != '*' ) {
1021 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1025 $this->query( $sql, $fname );
1028 # Returns the size of a text field, or -1 for "unlimited"
1029 function textFieldSize( $table, $field ) {
1030 $table = $this->tableName( $table );
1031 $sql = "SELECT t.typname as ftype,a.atttypmod as size
1032 FROM pg_class c, pg_attribute a, pg_type t
1033 WHERE relname='$table' AND a.attrelid=c.oid AND
1034 a.atttypid=t.oid and a.attname='$field'";
1035 $res =$this->query( $sql );
1036 $row = $this->fetchObject( $res );
1037 if ( $row->ftype
== 'varchar' ) {
1038 $size = $row->size
- 4;
1045 function limitResult( $sql, $limit, $offset = false ) {
1046 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " : '' );
1049 function wasDeadlock() {
1050 return $this->lastErrno() == '40P01';
1053 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
1054 return $this->query( 'CREATE ' . ( $temporary ?
'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
1057 function timestamp( $ts = 0 ) {
1058 return wfTimestamp( TS_POSTGRES
, $ts );
1062 * Return aggregated value function call
1064 function aggregateValue( $valuedata, $valuename = 'value' ) {
1068 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1069 // Ignore errors during error handling to avoid infinite recursion
1070 $ignore = $this->ignoreErrors( true );
1071 $this->mErrorCount++
;
1073 if ( $ignore ||
$tempIgnore ) {
1074 wfDebug( "SQL ERROR (ignored): $error\n" );
1075 $this->ignoreErrors( $ignore );
1077 $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" .
1079 "Function: $fname\n" .
1080 "Error: $errno $error\n";
1081 throw new DBUnexpectedError( $this, $message );
1086 * @return string wikitext of a link to the server software's web site
1088 public static function getSoftwareLink() {
1089 return '[http://www.postgresql.org/ PostgreSQL]';
1093 * @return string Version information from the database
1095 function getServerVersion() {
1096 if ( !isset( $this->numeric_version
) ) {
1097 $versionInfo = pg_version( $this->mConn
);
1098 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1099 // Old client, abort install
1100 $this->numeric_version
= '7.3 or earlier';
1101 } elseif ( isset( $versionInfo['server'] ) ) {
1103 $this->numeric_version
= $versionInfo['server'];
1105 // Bug 16937: broken pgsql extension from PHP<5.3
1106 $this->numeric_version
= pg_parameter_status( $this->mConn
, 'server_version' );
1109 return $this->numeric_version
;
1113 * Query whether a given relation exists (in the given schema, or the
1114 * default mw one if not given)
1116 function relationExists( $table, $types, $schema = false ) {
1117 global $wgDBmwschema;
1118 if ( !is_array( $types ) ) {
1119 $types = array( $types );
1122 $schema = $wgDBmwschema;
1124 $etable = $this->addQuotes( $table );
1125 $eschema = $this->addQuotes( $schema );
1126 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1127 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1128 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1129 $res = $this->query( $SQL );
1130 $count = $res ?
$res->numRows() : 0;
1131 return (bool)$count;
1135 * For backward compatibility, this function checks both tables and
1138 function tableExists( $table, $schema = false ) {
1139 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1142 function sequenceExists( $sequence, $schema = false ) {
1143 return $this->relationExists( $sequence, 'S', $schema );
1146 function triggerExists( $table, $trigger ) {
1147 global $wgDBmwschema;
1150 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1151 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1152 AND tgrelid=pg_class.oid
1153 AND nspname=%s AND relname=%s AND tgname=%s
1155 $res = $this->query(
1158 $this->addQuotes( $wgDBmwschema ),
1159 $this->addQuotes( $table ),
1160 $this->addQuotes( $trigger )
1166 $rows = $res->numRows();
1170 function ruleExists( $table, $rule ) {
1171 global $wgDBmwschema;
1172 $exists = $this->selectField( 'pg_rules', 'rulename',
1174 'rulename' => $rule,
1175 'tablename' => $table,
1176 'schemaname' => $wgDBmwschema
1179 return $exists === $rule;
1182 function constraintExists( $table, $constraint ) {
1183 global $wgDBmwschema;
1184 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
1185 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1186 $this->addQuotes( $wgDBmwschema ),
1187 $this->addQuotes( $table ),
1188 $this->addQuotes( $constraint )
1190 $res = $this->query( $SQL );
1194 $rows = $res->numRows();
1199 * Query whether a given schema exists. Returns the name of the owner
1201 function schemaExists( $schema ) {
1202 $eschema = str_replace( "'", "''", $schema );
1203 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1204 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1205 $res = $this->query( $SQL );
1206 if ( $res && $res->numRows() ) {
1207 $row = $res->fetchObject();
1208 $owner = $row->rolname
;
1215 function fieldInfo( $table, $field ) {
1216 return PostgresField
::fromText( $this, $table, $field );
1220 * pg_field_type() wrapper
1222 function fieldType( $res, $index ) {
1223 if ( $res instanceof ResultWrapper
) {
1224 $res = $res->result
;
1226 return pg_field_type( $res, $index );
1229 /* Not even sure why this is used in the main codebase... */
1230 function limitResultForUpdate( $sql, $num ) {
1234 function encodeBlob( $b ) {
1235 return new Blob( pg_escape_bytea( $this->mConn
, $b ) );
1238 function decodeBlob( $b ) {
1239 if ( $b instanceof Blob
) {
1242 return pg_unescape_bytea( $b );
1245 function strencode( $s ) { # Should not be called by us
1246 return pg_escape_string( $this->mConn
, $s );
1249 function addQuotes( $s ) {
1250 if ( is_null( $s ) ) {
1252 } elseif ( is_bool( $s ) ) {
1253 return intval( $s );
1254 } elseif ( $s instanceof Blob
) {
1255 return "'" . $s->fetch( $s ) . "'";
1257 return "'" . pg_escape_string( $this->mConn
, $s ) . "'";
1261 * Postgres specific version of replaceVars.
1262 * Calls the parent version in Database.php
1266 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1268 * @return string SQL string
1270 protected function replaceVars( $ins ) {
1271 $ins = parent
::replaceVars( $ins );
1273 if ( $this->numeric_version
>= 8.3 ) {
1274 // Thanks for not providing backwards-compatibility, 8.3
1275 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1278 if ( $this->numeric_version
<= 8.1 ) { // Our minimum version
1279 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1286 * Various select options
1290 * @param $options Array: an associative array of options to be turned into
1291 * an SQL query, valid keys are listed in the function.
1294 function makeSelectOptions( $options ) {
1295 $preLimitTail = $postLimitTail = '';
1296 $startOpts = $useIndex = '';
1298 $noKeyOptions = array();
1299 foreach ( $options as $key => $option ) {
1300 if ( is_numeric( $key ) ) {
1301 $noKeyOptions[$option] = true;
1305 if ( isset( $options['GROUP BY'] ) ) {
1306 $preLimitTail .= ' GROUP BY ' . $options['GROUP BY'];
1308 if ( isset( $options['HAVING'] ) ) {
1309 $preLimitTail .= " HAVING {$options['HAVING']}";
1311 if ( isset( $options['ORDER BY'] ) ) {
1312 $preLimitTail .= ' ORDER BY ' . $options['ORDER BY'];
1315 //if ( isset( $options['LIMIT'] ) ) {
1316 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1317 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1321 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1322 $postLimitTail .= ' FOR UPDATE';
1324 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1325 $postLimitTail .= ' LOCK IN SHARE MODE';
1327 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1328 $startOpts .= 'DISTINCT';
1331 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1334 function setFakeMaster( $enabled = true ) {}
1336 function getDBname() {
1337 return $this->mDBname
;
1340 function getServer() {
1341 return $this->mServer
;
1344 function buildConcat( $stringList ) {
1345 return implode( ' || ', $stringList );
1348 public function getSearchEngine() {
1349 return 'SearchPostgres';
1351 } // end DatabasePostgres class