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 );
147 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
148 return new DatabasePostgres( $server, $user, $password, $dbName, $flags );
152 * Usually aborts on failure
154 function open( $server, $user, $password, $dbName ) {
155 # Test for Postgres support, to avoid suppressed fatal error
156 if ( !function_exists( 'pg_connect' ) ) {
157 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" );
162 if ( !strlen( $user ) ) { # e.g. the class is being loaded
166 $this->mServer
= $server;
167 $this->mPort
= $port = $wgDBport;
168 $this->mUser
= $user;
169 $this->mPassword
= $password;
170 $this->mDBname
= $dbName;
172 $connectVars = array(
175 'password' => $password
177 if ( $server != false && $server != '' ) {
178 $connectVars['host'] = $server;
180 if ( $port != false && $port != '' ) {
181 $connectVars['port'] = $port;
183 $connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
185 $this->installErrorHandler();
186 $this->mConn
= pg_connect( $connectString );
187 $phpError = $this->restoreErrorHandler();
189 if ( !$this->mConn
) {
190 wfDebug( "DB connection error\n" );
191 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
192 wfDebug( $this->lastError() . "\n" );
193 throw new DBConnectionError( $this, $phpError );
196 $this->mOpened
= true;
198 global $wgCommandLineMode;
199 # If called from the command-line (e.g. importDump), only show errors
200 if ( $wgCommandLineMode ) {
201 $this->doQuery( "SET client_min_messages = 'ERROR'" );
204 $this->doQuery( "SET client_encoding='UTF8'" );
206 global $wgDBmwschema, $wgDBts2schema;
207 if ( isset( $wgDBmwschema ) && isset( $wgDBts2schema )
208 && $wgDBmwschema !== 'mediawiki'
209 && preg_match( '/^\w+$/', $wgDBmwschema )
210 && preg_match( '/^\w+$/', $wgDBts2schema )
212 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
213 $this->doQuery( "SET search_path = $safeschema, $wgDBts2schema, public" );
219 function makeConnectionString( $vars ) {
221 foreach ( $vars as $name => $value ) {
222 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
228 function initial_setup( $superuser, $password, $dbName ) {
229 // If this is the initial connection, setup the schema stuff and possibly create the user
230 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBmwschema, $wgDBts2schema;
232 $safeuser = $this->addIdentifierQuotes( $wgDBuser );
233 // Are we connecting as a superuser for the first time?
235 // Are we really a superuser? Check out our rights
237 CASE WHEN usesuper IS TRUE THEN
238 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
239 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
241 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes( $superuser );
242 $rows = $this->numRows( $res = $this->doQuery( $SQL ) );
244 print '<li>ERROR: Could not read permissions for user "' . htmlspecialchars( $superuser ) . "\"</li>\n";
247 $perms = pg_fetch_result( $res, 0, 0 );
249 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes( $wgDBuser );
250 $rows = $this->numRows( $this->doQuery( $SQL ) );
252 print '<li>User "' . htmlspecialchars( $wgDBuser ) . '" already exists, skipping account creation.</li>';
254 if ( $perms != 1 && $perms != 3 ) {
255 print '<li>ERROR: the user "' . htmlspecialchars( $superuser ) . '" cannot create other users. ';
256 print 'Please use a different Postgres user.</li>';
259 print '<li>Creating user <b>' . htmlspecialchars( $wgDBuser ) . '</b>...';
260 $safepass = $this->addQuotes( $wgDBpassword );
261 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
262 $this->doQuery( $SQL );
265 // User now exists, check out the database
266 if ( $dbName != $wgDBname ) {
267 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes( $wgDBname );
268 $rows = $this->numRows( $this->doQuery( $SQL ) );
270 print '<li>Database "' . htmlspecialchars( $wgDBname ) . '" already exists, skipping database creation.</li>';
273 print '<li>ERROR: the user "' . htmlspecialchars( $superuser ) . '" cannot create databases. ';
274 print 'Please use a different Postgres user.</li>';
277 print '<li>Creating database <b>' . htmlspecialchars( $wgDBname ) . '</b>...';
278 $safename = $this->addIdentifierQuotes( $wgDBname );
279 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
280 $this->doQuery( $SQL );
282 // Hopefully tsearch2 and plpgsql are in template1...
285 // Reconnect to check out tsearch2 rights for this user
286 print '<li>Connecting to "' . htmlspecialchars( $wgDBname ) . '" as superuser "' .
287 htmlspecialchars( $superuser ) . '" to check rights...';
289 $connectVars = array();
290 if ( $this->mServer
!= false && $this->mServer
!= '' ) {
291 $connectVars['host'] = $this->mServer
;
293 if ( $this->mPort
!= false && $this->mPort
!= '' ) {
294 $connectVars['port'] = $this->mPort
;
296 $connectVars['dbname'] = $wgDBname;
297 $connectVars['user'] = $superuser;
298 $connectVars['password'] = $password;
300 @$this->mConn
= pg_connect( $this->makeConnectionString( $connectVars ) );
301 if ( !$this->mConn
) {
302 print "<b>FAILED TO CONNECT!</b></li>";
308 if ( $this->numeric_version
< 8.3 ) {
310 print '<li>Checking that tsearch2 is installed in the database "' .
311 htmlspecialchars( $wgDBname ) . '"...';
312 if ( !$this->tableExists( 'pg_ts_cfg', $wgDBts2schema ) ) {
313 print '<b>FAILED</b>. tsearch2 must be installed in the database "' .
314 htmlspecialchars( $wgDBname ) . '".';
315 print 'Please see <a href="http://www.devx.com/opensource/Article/21674/0/page/2">this article</a>';
316 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
320 print '<li>Ensuring that user "' . htmlspecialchars( $wgDBuser ) .
321 '" has select rights on the tsearch2 tables...';
322 foreach ( array( 'cfg', 'cfgmap', 'dict', 'parser' ) as $table ) {
323 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
324 $this->doQuery( $SQL );
329 // Setup the schema for this user if needed
330 $result = $this->schemaExists( $wgDBmwschema );
331 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
333 print '<li>Creating schema <b>' . htmlspecialchars( $wgDBmwschema ) . '</b> ...';
334 $result = $this->doQuery( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
336 print "<b>FAILED</b>.</li>\n";
341 print "<li>Schema already exists, explicitly granting rights...\n";
342 $safeschema2 = $this->addQuotes( $wgDBmwschema );
343 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
344 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
345 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
346 "AND p.relkind IN ('r','S','v')\n";
348 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
349 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
350 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
351 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
352 $res = $this->doQuery( $SQL );
354 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
357 $this->doQuery( "SET search_path = $safeschema" );
358 $rows = $this->numRows( $res );
361 $this->doQuery( pg_fetch_result( $res, $rows, 0 ) );
366 // Install plpgsql if needed
367 $this->setup_plpgsql();
369 return true; // Reconnect as regular user
373 if ( !defined( 'POSTGRES_SEARCHPATH' ) ) {
375 if ( $this->numeric_version
< 8.3 ) {
376 // Do we have the basic tsearch2 table?
377 print '<li>Checking for tsearch2 in the schema "' . htmlspecialchars( $wgDBts2schema ) . '"...';
378 if ( !$this->tableExists( 'pg_ts_dict', $wgDBts2schema ) ) {
379 print '<b>FAILED</b>. Make sure tsearch2 is installed. See <a href="';
380 print 'http://www.devx.com/opensource/Article/21674/0/page/2">this article</a>';
381 print " for instructions.</li>\n";
386 // Does this user have the rights to the tsearch2 tables?
387 $ctype = pg_fetch_result( $this->doQuery( 'SHOW lc_ctype' ), 0, 0 );
388 print '<li>Checking tsearch2 permissions...';
389 // Let's check all four, just to be safe
390 error_reporting( 0 );
391 $ts2tables = array( 'cfg', 'cfgmap', 'dict', 'parser' );
392 $safetsschema = $this->addIdentifierQuotes( $wgDBts2schema );
393 foreach ( $ts2tables as $tname ) {
394 $SQL = "SELECT count(*) FROM $safetsschema.pg_ts_$tname";
395 $res = $this->doQuery( $SQL );
397 print "<b>FAILED</b> to access " . htmlspecialchars( "pg_ts_$tname" ) .
398 ". Make sure that the user \"". htmlspecialchars( $wgDBuser ) .
399 "\" has SELECT access to all four tsearch2 tables</li>\n";
403 $SQL = "SELECT ts_name FROM $safetsschema.pg_ts_cfg WHERE locale = " . $this->addQuotes( $ctype ) ;
404 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
405 $res = $this->doQuery( $SQL );
406 error_reporting( E_ALL
);
408 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
413 // Will the current locale work? Can we force it to?
414 print '<li>Verifying tsearch2 locale with ' . htmlspecialchars( $ctype ) . '...';
415 $rows = $this->numRows( $res );
418 print "<b>not found</b></li>\n";
419 print '<li>Attempting to set default tsearch2 locale to "' . htmlspecialchars( $ctype ) . '"...';
422 $tsname = pg_fetch_result( $res, 0, 0 );
423 if ( $tsname != 'default' ) {
424 print "<b>not set to default (" . htmlspecialchars( $tsname ) . ")</b>";
425 print "<li>Attempting to change tsearch2 default locale to \"" .
426 htmlspecialchars( $ctype ) . "\"...";
430 if ( $resetlocale ) {
431 $SQL = "UPDATE $safetsschema.pg_ts_cfg SET locale = " . $this->addQuotes( $ctype ) . " WHERE ts_name = 'default'";
432 $res = $this->doQuery( $SQL );
434 print '<b>FAILED</b>. ';
435 print 'Please make sure that the locale in pg_ts_cfg for "default" is set to "' .
436 htmlspecialchars( $ctype ) . "\"</li>\n";
442 // Final test: try out a simple tsearch2 query
443 $SQL = "SELECT $safetsschema.to_tsvector('default','MediaWiki tsearch2 testing')";
444 $res = $this->doQuery( $SQL );
446 print '<b>FAILED</b>. Specifically, "' . htmlspecialchars( $SQL ) . '" did not work.</li>';
452 // Install plpgsql if needed
453 $this->setup_plpgsql();
455 // Does the schema already exist? Who owns it?
456 $result = $this->schemaExists( $wgDBmwschema );
458 print '<li>Creating schema <b>' . htmlspecialchars( $wgDBmwschema ) . '</b> ...';
459 error_reporting( 0 );
460 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
461 $result = $this->doQuery( "CREATE SCHEMA $safeschema" );
462 error_reporting( E_ALL
);
464 print '<b>FAILED</b>. The user "' . htmlspecialchars( $wgDBuser ) .
465 '" must be able to access the schema. '.
466 'You can try making them the owner of the database, or try creating the schema with a '.
467 'different user, and then grant access to the "' .
468 htmlspecialchars( $wgDBuser ) . "\" user.</li>\n";
472 } elseif ( $result != $wgDBuser ) {
473 print '<li>Schema "' . htmlspecialchars( $wgDBmwschema ) . '" exists but is not owned by "' .
474 htmlspecialchars( $wgDBuser ) . "\". Not ideal.</li>\n";
476 print '<li>Schema "' . htmlspecialchars( $wgDBmwschema ) . '" exists and is owned by "' .
477 htmlspecialchars( $wgDBuser ) . "\". Excellent.</li>\n";
480 // Always return GMT time to accomodate the existing integer-based timestamp assumption
481 print "<li>Setting the timezone to GMT for user \"" . htmlspecialchars( $wgDBuser ) . '" ...';
482 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
483 $result = pg_query( $this->mConn
, $SQL );
485 print "<b>FAILED</b>.</li>\n";
489 // Set for the rest of this session
490 $SQL = "SET timezone = 'GMT'";
491 $result = pg_query( $this->mConn
, $SQL );
493 print "<li>Failed to set timezone</li>\n";
497 print '<li>Setting the datestyle to ISO, YMD for user "' . htmlspecialchars( $wgDBuser ) . '" ...';
498 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
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 datestyle = 'ISO, YMD'";
507 $result = pg_query( $this->mConn
, $SQL );
509 print "<li>Failed to set datestyle</li>\n";
513 // Fix up the search paths if needed
514 print '<li>Setting the search path for user "' . htmlspecialchars( $wgDBuser ) . '" ...';
515 $path = $this->addIdentifierQuotes( $wgDBmwschema );
516 if ( $wgDBts2schema !== $wgDBmwschema ) {
517 $path .= ', '. $this->addIdentifierQuotes( $wgDBts2schema );
519 if ( $wgDBmwschema !== 'public' && $wgDBts2schema !== 'public' ) {
522 $SQL = "ALTER USER $safeuser SET search_path = $path";
523 $result = pg_query( $this->mConn
, $SQL );
525 print "<b>FAILED</b>.</li>\n";
529 // Set for the rest of this session
530 $SQL = "SET search_path = $path";
531 $result = pg_query( $this->mConn
, $SQL );
533 print "<li>Failed to set search_path</li>\n";
536 define( 'POSTGRES_SEARCHPATH', $path );
541 * Closes a database connection, if it is open
542 * Returns success, true if already closed
545 $this->mOpened
= false;
546 if ( $this->mConn
) {
547 return pg_close( $this->mConn
);
553 function doQuery( $sql ) {
554 if ( function_exists( 'mb_convert_encoding' ) ) {
555 $sql = mb_convert_encoding( $sql, 'UTF-8' );
557 $this->mLastResult
= pg_query( $this->mConn
, $sql );
558 $this->mAffectedRows
= null; // use pg_affected_rows(mLastResult)
559 return $this->mLastResult
;
562 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
563 return $this->query( $sql, $fname, true );
566 function freeResult( $res ) {
567 if ( $res instanceof ResultWrapper
) {
570 if ( !@pg_free_result
( $res ) ) {
571 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
575 function fetchObject( $res ) {
576 if ( $res instanceof ResultWrapper
) {
579 @$row = pg_fetch_object( $res );
580 # FIXME: HACK HACK HACK HACK debug
583 # hashar : not sure if the following test really trigger if the object
585 if( pg_last_error( $this->mConn
) ) {
586 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
591 function fetchRow( $res ) {
592 if ( $res instanceof ResultWrapper
) {
595 @$row = pg_fetch_array( $res );
596 if( pg_last_error( $this->mConn
) ) {
597 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
602 function numRows( $res ) {
603 if ( $res instanceof ResultWrapper
) {
606 @$n = pg_num_rows( $res );
607 if( pg_last_error( $this->mConn
) ) {
608 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
613 function numFields( $res ) {
614 if ( $res instanceof ResultWrapper
) {
617 return pg_num_fields( $res );
620 function fieldName( $res, $n ) {
621 if ( $res instanceof ResultWrapper
) {
624 return pg_field_name( $res, $n );
628 * This must be called after nextSequenceVal
630 function insertId() {
631 return $this->mInsertId
;
634 function dataSeek( $res, $row ) {
635 if ( $res instanceof ResultWrapper
) {
638 return pg_result_seek( $res, $row );
641 function lastError() {
642 if ( $this->mConn
) {
643 return pg_last_error();
645 return 'No database connection';
648 function lastErrno() {
649 return pg_last_error() ?
1 : 0;
652 function affectedRows() {
653 if ( !is_null( $this->mAffectedRows
) ) {
654 // Forced result for simulated queries
655 return $this->mAffectedRows
;
657 if( empty( $this->mLastResult
) ) {
660 return pg_affected_rows( $this->mLastResult
);
664 * Estimate rows in dataset
665 * Returns estimated count, based on EXPLAIN output
666 * This is not necessarily an accurate estimate, so use sparingly
667 * Returns -1 if count cannot be found
668 * Takes same arguments as Database::select()
670 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
671 $options['EXPLAIN'] = true;
672 $res = $this->select( $table, $vars, $conds, $fname, $options );
675 $row = $this->fetchRow( $res );
677 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
685 * Returns information about an index
686 * If errors are explicitly ignored, returns NULL on failure
688 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
689 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
690 $res = $this->query( $sql, $fname );
694 foreach ( $res as $row ) {
695 if ( $row->indexname
== $this->indexName( $index ) ) {
702 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
703 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
704 " AND indexdef LIKE 'CREATE UNIQUE%(" .
705 $this->strencode( $this->indexName( $index ) ) .
707 $res = $this->query( $sql, $fname );
711 foreach ( $res as $row ) {
718 * INSERT wrapper, inserts an array into a table
720 * $args may be a single associative array, or an array of these with numeric keys,
721 * for multi-row insert (Postgres version 8.2 and above only).
723 * @param $table String: Name of the table to insert to.
724 * @param $args Array: Items to insert into the table.
725 * @param $fname String: Name of the function, for profiling
726 * @param $options String or Array. Valid options: IGNORE
728 * @return bool Success of insert operation. IGNORE always returns true.
730 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
731 if ( !count( $args ) ) {
735 $table = $this->tableName( $table );
736 if (! isset( $this->numeric_version
) ) {
737 $this->getServerVersion();
740 if ( !is_array( $options ) ) {
741 $options = array( $options );
744 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
746 $keys = array_keys( $args[0] );
749 $keys = array_keys( $args );
752 // If IGNORE is set, we use savepoints to emulate mysql's behavior
753 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
755 // If we are not in a transaction, we need to be for savepoint trickery
758 if ( !$this->mTrxLevel
) {
762 $olde = error_reporting( 0 );
763 // For future use, we may want to track the number of actual inserts
764 // Right now, insert (all writes) simply return true/false
765 $numrowsinserted = 0;
768 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
771 if ( $this->numeric_version
>= 8.2 && !$ignore ) {
773 foreach ( $args as $row ) {
779 $sql .= '(' . $this->makeList( $row ) . ')';
781 $res = (bool)$this->query( $sql, $fname, $ignore );
785 foreach ( $args as $row ) {
787 $tempsql .= '(' . $this->makeList( $row ) . ')';
790 pg_query( $this->mConn
, "SAVEPOINT $ignore" );
793 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
796 $bar = pg_last_error();
797 if ( $bar != false ) {
798 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
800 pg_query( $this->mConn
, "RELEASE $ignore" );
805 // If any of them fail, we fail overall for this function call
806 // Note that this will be ignored if IGNORE is set
813 // Not multi, just a lone insert
815 pg_query($this->mConn
, "SAVEPOINT $ignore");
818 $sql .= '(' . $this->makeList( $args ) . ')';
819 $res = (bool)$this->query( $sql, $fname, $ignore );
821 $bar = pg_last_error();
822 if ( $bar != false ) {
823 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
825 pg_query( $this->mConn
, "RELEASE $ignore" );
831 $olde = error_reporting( $olde );
836 // Set the affected row count for the whole operation
837 $this->mAffectedRows
= $numrowsinserted;
839 // IGNORE always returns true
847 * INSERT SELECT wrapper
848 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
849 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
850 * $conds may be "*" to copy the whole table
851 * srcTable may be an array of tables.
852 * @todo FIXME: implement this a little better (seperate select/insert)?
854 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
855 $insertOptions = array(), $selectOptions = array() )
857 $destTable = $this->tableName( $destTable );
859 // If IGNORE is set, we use savepoints to emulate mysql's behavior
860 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
862 if( is_array( $insertOptions ) ) {
863 $insertOptions = implode( ' ', $insertOptions );
865 if( !is_array( $selectOptions ) ) {
866 $selectOptions = array( $selectOptions );
868 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
869 if( is_array( $srcTable ) ) {
870 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
872 $srcTable = $this->tableName( $srcTable );
875 // If we are not in a transaction, we need to be for savepoint trickery
878 if( !$this->mTrxLevel
) {
882 $olde = error_reporting( 0 );
883 $numrowsinserted = 0;
884 pg_query( $this->mConn
, "SAVEPOINT $ignore");
887 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
888 " SELECT $startOpts " . implode( ',', $varMap ) .
889 " FROM $srcTable $useIndex";
891 if ( $conds != '*' ) {
892 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
895 $sql .= " $tailOpts";
897 $res = (bool)$this->query( $sql, $fname, $ignore );
899 $bar = pg_last_error();
900 if( $bar != false ) {
901 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
903 pg_query( $this->mConn
, "RELEASE $ignore" );
906 $olde = error_reporting( $olde );
911 // Set the affected row count for the whole operation
912 $this->mAffectedRows
= $numrowsinserted;
914 // IGNORE always returns true
921 function tableName( $name ) {
922 # Replace reserved words with better ones
927 return 'pagecontent';
934 * Return the next in a sequence, save the value for retrieval via insertId()
936 function nextSequenceValue( $seqName ) {
937 $safeseq = str_replace( "'", "''", $seqName );
938 $res = $this->query( "SELECT nextval('$safeseq')" );
939 $row = $this->fetchRow( $res );
940 $this->mInsertId
= $row[0];
941 return $this->mInsertId
;
945 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
947 function currentSequenceValue( $seqName ) {
948 $safeseq = str_replace( "'", "''", $seqName );
949 $res = $this->query( "SELECT currval('$safeseq')" );
950 $row = $this->fetchRow( $res );
956 * REPLACE query wrapper
957 * Postgres simulates this with a DELETE followed by INSERT
958 * $row is the row to insert, an associative array
959 * $uniqueIndexes is an array of indexes. Each element may be either a
960 * field name or an array of field names
962 * It may be more efficient to leave off unique indexes which are unlikely to collide.
963 * However if you do this, you run the risk of encountering errors which wouldn't have
966 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
967 $table = $this->tableName( $table );
969 if ( count( $rows ) == 0 ) {
974 if ( !is_array( reset( $rows ) ) ) {
975 $rows = array( $rows );
978 foreach( $rows as $row ) {
979 # Delete rows which collide
980 if ( $uniqueIndexes ) {
981 $sql = "DELETE FROM $table WHERE ";
983 foreach ( $uniqueIndexes as $index ) {
990 if ( is_array( $index ) ) {
992 foreach ( $index as $col ) {
998 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
1001 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1005 $this->query( $sql, $fname );
1008 # Now insert the row
1009 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
1010 $this->makeList( $row, LIST_COMMA
) . ')';
1011 $this->query( $sql, $fname );
1015 # DELETE where the condition is a join
1016 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
1018 throw new DBUnexpectedError( $this, 'DatabasePostgres::deleteJoin() called with empty $conds' );
1021 $delTable = $this->tableName( $delTable );
1022 $joinTable = $this->tableName( $joinTable );
1023 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1024 if ( $conds != '*' ) {
1025 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1029 $this->query( $sql, $fname );
1032 # Returns the size of a text field, or -1 for "unlimited"
1033 function textFieldSize( $table, $field ) {
1034 $table = $this->tableName( $table );
1035 $sql = "SELECT t.typname as ftype,a.atttypmod as size
1036 FROM pg_class c, pg_attribute a, pg_type t
1037 WHERE relname='$table' AND a.attrelid=c.oid AND
1038 a.atttypid=t.oid and a.attname='$field'";
1039 $res =$this->query( $sql );
1040 $row = $this->fetchObject( $res );
1041 if ( $row->ftype
== 'varchar' ) {
1042 $size = $row->size
- 4;
1049 function limitResult( $sql, $limit, $offset = false ) {
1050 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " : '' );
1053 function wasDeadlock() {
1054 return $this->lastErrno() == '40P01';
1057 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
1058 return $this->query( 'CREATE ' . ( $temporary ?
'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
1061 function timestamp( $ts = 0 ) {
1062 return wfTimestamp( TS_POSTGRES
, $ts );
1066 * Return aggregated value function call
1068 function aggregateValue( $valuedata, $valuename = 'value' ) {
1072 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1073 // Ignore errors during error handling to avoid infinite recursion
1074 $ignore = $this->ignoreErrors( true );
1075 $this->mErrorCount++
;
1077 if ( $ignore ||
$tempIgnore ) {
1078 wfDebug( "SQL ERROR (ignored): $error\n" );
1079 $this->ignoreErrors( $ignore );
1081 $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" .
1083 "Function: $fname\n" .
1084 "Error: $errno $error\n";
1085 throw new DBUnexpectedError( $this, $message );
1090 * @return string wikitext of a link to the server software's web site
1092 public static function getSoftwareLink() {
1093 return '[http://www.postgresql.org/ PostgreSQL]';
1097 * @return string Version information from the database
1099 function getServerVersion() {
1100 if ( !isset( $this->numeric_version
) ) {
1101 $versionInfo = pg_version( $this->mConn
);
1102 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1103 // Old client, abort install
1104 $this->numeric_version
= '7.3 or earlier';
1105 } elseif ( isset( $versionInfo['server'] ) ) {
1107 $this->numeric_version
= $versionInfo['server'];
1109 // Bug 16937: broken pgsql extension from PHP<5.3
1110 $this->numeric_version
= pg_parameter_status( $this->mConn
, 'server_version' );
1113 return $this->numeric_version
;
1117 * Query whether a given relation exists (in the given schema, or the
1118 * default mw one if not given)
1120 function relationExists( $table, $types, $schema = false ) {
1121 global $wgDBmwschema;
1122 if ( !is_array( $types ) ) {
1123 $types = array( $types );
1126 $schema = $wgDBmwschema;
1128 $etable = $this->addQuotes( $table );
1129 $eschema = $this->addQuotes( $schema );
1130 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1131 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1132 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1133 $res = $this->query( $SQL );
1134 $count = $res ?
$res->numRows() : 0;
1135 return (bool)$count;
1139 * For backward compatibility, this function checks both tables and
1142 function tableExists( $table, $schema = false ) {
1143 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1146 function sequenceExists( $sequence, $schema = false ) {
1147 return $this->relationExists( $sequence, 'S', $schema );
1150 function triggerExists( $table, $trigger ) {
1151 global $wgDBmwschema;
1154 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1155 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1156 AND tgrelid=pg_class.oid
1157 AND nspname=%s AND relname=%s AND tgname=%s
1159 $res = $this->query(
1162 $this->addQuotes( $wgDBmwschema ),
1163 $this->addQuotes( $table ),
1164 $this->addQuotes( $trigger )
1170 $rows = $res->numRows();
1174 function ruleExists( $table, $rule ) {
1175 global $wgDBmwschema;
1176 $exists = $this->selectField( 'pg_rules', 'rulename',
1178 'rulename' => $rule,
1179 'tablename' => $table,
1180 'schemaname' => $wgDBmwschema
1183 return $exists === $rule;
1186 function constraintExists( $table, $constraint ) {
1187 global $wgDBmwschema;
1188 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
1189 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1190 $this->addQuotes( $wgDBmwschema ),
1191 $this->addQuotes( $table ),
1192 $this->addQuotes( $constraint )
1194 $res = $this->query( $SQL );
1198 $rows = $res->numRows();
1203 * Query whether a given schema exists. Returns the name of the owner
1205 function schemaExists( $schema ) {
1206 $eschema = str_replace( "'", "''", $schema );
1207 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1208 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1209 $res = $this->query( $SQL );
1210 if ( $res && $res->numRows() ) {
1211 $row = $res->fetchObject();
1212 $owner = $row->rolname
;
1219 function fieldInfo( $table, $field ) {
1220 return PostgresField
::fromText( $this, $table, $field );
1224 * pg_field_type() wrapper
1226 function fieldType( $res, $index ) {
1227 if ( $res instanceof ResultWrapper
) {
1228 $res = $res->result
;
1230 return pg_field_type( $res, $index );
1233 /* Not even sure why this is used in the main codebase... */
1234 function limitResultForUpdate( $sql, $num ) {
1238 function encodeBlob( $b ) {
1239 return new Blob( pg_escape_bytea( $this->mConn
, $b ) );
1242 function decodeBlob( $b ) {
1243 if ( $b instanceof Blob
) {
1246 return pg_unescape_bytea( $b );
1249 function strencode( $s ) { # Should not be called by us
1250 return pg_escape_string( $this->mConn
, $s );
1253 function addQuotes( $s ) {
1254 if ( is_null( $s ) ) {
1256 } elseif ( is_bool( $s ) ) {
1257 return intval( $s );
1258 } elseif ( $s instanceof Blob
) {
1259 return "'" . $s->fetch( $s ) . "'";
1261 return "'" . pg_escape_string( $this->mConn
, $s ) . "'";
1265 * Postgres specific version of replaceVars.
1266 * Calls the parent version in Database.php
1270 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1272 * @return string SQL string
1274 protected function replaceVars( $ins ) {
1275 $ins = parent
::replaceVars( $ins );
1277 if ( $this->numeric_version
>= 8.3 ) {
1278 // Thanks for not providing backwards-compatibility, 8.3
1279 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1282 if ( $this->numeric_version
<= 8.1 ) { // Our minimum version
1283 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1290 * Various select options
1294 * @param $options Array: an associative array of options to be turned into
1295 * an SQL query, valid keys are listed in the function.
1298 function makeSelectOptions( $options ) {
1299 $preLimitTail = $postLimitTail = '';
1300 $startOpts = $useIndex = '';
1302 $noKeyOptions = array();
1303 foreach ( $options as $key => $option ) {
1304 if ( is_numeric( $key ) ) {
1305 $noKeyOptions[$option] = true;
1309 if ( isset( $options['GROUP BY'] ) ) {
1310 $preLimitTail .= ' GROUP BY ' . $options['GROUP BY'];
1312 if ( isset( $options['HAVING'] ) ) {
1313 $preLimitTail .= " HAVING {$options['HAVING']}";
1315 if ( isset( $options['ORDER BY'] ) ) {
1316 $preLimitTail .= ' ORDER BY ' . $options['ORDER BY'];
1319 //if ( isset( $options['LIMIT'] ) ) {
1320 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1321 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1325 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1326 $postLimitTail .= ' FOR UPDATE';
1328 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1329 $postLimitTail .= ' LOCK IN SHARE MODE';
1331 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1332 $startOpts .= 'DISTINCT';
1335 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1338 function setFakeMaster( $enabled = true ) {}
1340 function getDBname() {
1341 return $this->mDBname
;
1344 function getServer() {
1345 return $this->mServer
;
1348 function buildConcat( $stringList ) {
1349 return implode( ' || ', $stringList );
1352 public function getSearchEngine() {
1353 return 'SearchPostgres';
1355 } // end DatabasePostgres class