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;
107 function cascadingDeletes() {
110 function cleanupTriggers() {
113 function strictIPs() {
116 function realTimestamps() {
119 function implicitGroupby() {
122 function implicitOrderby() {
125 function searchableIPs() {
128 function functionalIndexes() {
132 function hasConstraint( $name ) {
133 global $wgDBmwschema;
134 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" .
135 pg_escape_string( $this->mConn
, $name ) . "' AND n.nspname = '" . pg_escape_string( $this->mConn
, $wgDBmwschema ) ."'";
136 $res = $this->doQuery( $SQL );
137 return $this->numRows( $res );
141 * Usually aborts on failure
143 function open( $server, $user, $password, $dbName ) {
144 # Test for Postgres support, to avoid suppressed fatal error
145 if ( !function_exists( 'pg_connect' ) ) {
146 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" );
151 if ( !strlen( $user ) ) { # e.g. the class is being loaded
155 $this->mServer
= $server;
156 $this->mPort
= $port = $wgDBport;
157 $this->mUser
= $user;
158 $this->mPassword
= $password;
159 $this->mDBname
= $dbName;
161 $connectVars = array(
164 'password' => $password
166 if ( $server != false && $server != '' ) {
167 $connectVars['host'] = $server;
169 if ( $port != false && $port != '' ) {
170 $connectVars['port'] = $port;
172 $connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
174 $this->installErrorHandler();
175 $this->mConn
= pg_connect( $connectString );
176 $phpError = $this->restoreErrorHandler();
178 if ( !$this->mConn
) {
179 wfDebug( "DB connection error\n" );
180 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
181 wfDebug( $this->lastError() . "\n" );
182 throw new DBConnectionError( $this, $phpError );
185 $this->mOpened
= true;
187 global $wgCommandLineMode;
188 # If called from the command-line (e.g. importDump), only show errors
189 if ( $wgCommandLineMode ) {
190 $this->doQuery( "SET client_min_messages = 'ERROR'" );
193 $this->doQuery( "SET client_encoding='UTF8'" );
195 global $wgDBmwschema, $wgDBts2schema;
196 if ( isset( $wgDBmwschema ) && isset( $wgDBts2schema )
197 && $wgDBmwschema !== 'mediawiki'
198 && preg_match( '/^\w+$/', $wgDBmwschema )
199 && preg_match( '/^\w+$/', $wgDBts2schema )
201 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
202 $this->doQuery( "SET search_path = $safeschema, $wgDBts2schema, public" );
208 function makeConnectionString( $vars ) {
210 foreach ( $vars as $name => $value ) {
211 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
217 function initial_setup( $superuser, $password, $dbName ) {
218 // If this is the initial connection, setup the schema stuff and possibly create the user
219 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBmwschema, $wgDBts2schema;
221 $safeuser = $this->addIdentifierQuotes( $wgDBuser );
222 // Are we connecting as a superuser for the first time?
224 // Are we really a superuser? Check out our rights
226 CASE WHEN usesuper IS TRUE THEN
227 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
228 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
230 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes( $superuser );
231 $rows = $this->numRows( $res = $this->doQuery( $SQL ) );
233 print '<li>ERROR: Could not read permissions for user "' . htmlspecialchars( $superuser ) . "\"</li>\n";
236 $perms = pg_fetch_result( $res, 0, 0 );
238 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes( $wgDBuser );
239 $rows = $this->numRows( $this->doQuery( $SQL ) );
241 print '<li>User "' . htmlspecialchars( $wgDBuser ) . '" already exists, skipping account creation.</li>';
243 if ( $perms != 1 && $perms != 3 ) {
244 print '<li>ERROR: the user "' . htmlspecialchars( $superuser ) . '" cannot create other users. ';
245 print 'Please use a different Postgres user.</li>';
248 print '<li>Creating user <b>' . htmlspecialchars( $wgDBuser ) . '</b>...';
249 $safepass = $this->addQuotes( $wgDBpassword );
250 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
251 $this->doQuery( $SQL );
254 // User now exists, check out the database
255 if ( $dbName != $wgDBname ) {
256 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes( $wgDBname );
257 $rows = $this->numRows( $this->doQuery( $SQL ) );
259 print '<li>Database "' . htmlspecialchars( $wgDBname ) . '" already exists, skipping database creation.</li>';
262 print '<li>ERROR: the user "' . htmlspecialchars( $superuser ) . '" cannot create databases. ';
263 print 'Please use a different Postgres user.</li>';
266 print '<li>Creating database <b>' . htmlspecialchars( $wgDBname ) . '</b>...';
267 $safename = $this->addIdentifierQuotes( $wgDBname );
268 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
269 $this->doQuery( $SQL );
271 // Hopefully tsearch2 and plpgsql are in template1...
274 // Reconnect to check out tsearch2 rights for this user
275 print '<li>Connecting to "' . htmlspecialchars( $wgDBname ) . '" as superuser "' .
276 htmlspecialchars( $superuser ) . '" to check rights...';
278 $connectVars = array();
279 if ( $this->mServer
!= false && $this->mServer
!= '' ) {
280 $connectVars['host'] = $this->mServer
;
282 if ( $this->mPort
!= false && $this->mPort
!= '' ) {
283 $connectVars['port'] = $this->mPort
;
285 $connectVars['dbname'] = $wgDBname;
286 $connectVars['user'] = $superuser;
287 $connectVars['password'] = $password;
289 @$this->mConn
= pg_connect( $this->makeConnectionString( $connectVars ) );
290 if ( !$this->mConn
) {
291 print "<b>FAILED TO CONNECT!</b></li>";
297 if ( $this->numeric_version
< 8.3 ) {
299 print '<li>Checking that tsearch2 is installed in the database "' .
300 htmlspecialchars( $wgDBname ) . '"...';
301 if ( !$this->tableExists( 'pg_ts_cfg', $wgDBts2schema ) ) {
302 print '<b>FAILED</b>. tsearch2 must be installed in the database "' .
303 htmlspecialchars( $wgDBname ) . '".';
304 print 'Please see <a href="http://www.devx.com/opensource/Article/21674/0/page/2">this article</a>';
305 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
309 print '<li>Ensuring that user "' . htmlspecialchars( $wgDBuser ) .
310 '" has select rights on the tsearch2 tables...';
311 foreach ( array( 'cfg', 'cfgmap', 'dict', 'parser' ) as $table ) {
312 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
313 $this->doQuery( $SQL );
318 // Setup the schema for this user if needed
319 $result = $this->schemaExists( $wgDBmwschema );
320 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
322 print '<li>Creating schema <b>' . htmlspecialchars( $wgDBmwschema ) . '</b> ...';
323 $result = $this->doQuery( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
325 print "<b>FAILED</b>.</li>\n";
330 print "<li>Schema already exists, explicitly granting rights...\n";
331 $safeschema2 = $this->addQuotes( $wgDBmwschema );
332 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
333 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
334 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
335 "AND p.relkind IN ('r','S','v')\n";
337 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
338 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
339 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
340 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
341 $res = $this->doQuery( $SQL );
343 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
346 $this->doQuery( "SET search_path = $safeschema" );
347 $rows = $this->numRows( $res );
350 $this->doQuery( pg_fetch_result( $res, $rows, 0 ) );
355 // Install plpgsql if needed
356 $this->setup_plpgsql();
358 return true; // Reconnect as regular user
362 if ( !defined( 'POSTGRES_SEARCHPATH' ) ) {
364 if ( $this->numeric_version
< 8.3 ) {
365 // Do we have the basic tsearch2 table?
366 print '<li>Checking for tsearch2 in the schema "' . htmlspecialchars( $wgDBts2schema ) . '"...';
367 if ( !$this->tableExists( 'pg_ts_dict', $wgDBts2schema ) ) {
368 print '<b>FAILED</b>. Make sure tsearch2 is installed. See <a href="';
369 print 'http://www.devx.com/opensource/Article/21674/0/page/2">this article</a>';
370 print " for instructions.</li>\n";
375 // Does this user have the rights to the tsearch2 tables?
376 $ctype = pg_fetch_result( $this->doQuery( 'SHOW lc_ctype' ), 0, 0 );
377 print '<li>Checking tsearch2 permissions...';
378 // Let's check all four, just to be safe
379 error_reporting( 0 );
380 $ts2tables = array( 'cfg', 'cfgmap', 'dict', 'parser' );
381 $safetsschema = $this->addIdentifierQuotes( $wgDBts2schema );
382 foreach ( $ts2tables as $tname ) {
383 $SQL = "SELECT count(*) FROM $safetsschema.pg_ts_$tname";
384 $res = $this->doQuery( $SQL );
386 print "<b>FAILED</b> to access " . htmlspecialchars( "pg_ts_$tname" ) .
387 ". Make sure that the user \"". htmlspecialchars( $wgDBuser ) .
388 "\" has SELECT access to all four tsearch2 tables</li>\n";
392 $SQL = "SELECT ts_name FROM $safetsschema.pg_ts_cfg WHERE locale = " . $this->addQuotes( $ctype ) ;
393 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
394 $res = $this->doQuery( $SQL );
395 error_reporting( E_ALL
);
397 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
402 // Will the current locale work? Can we force it to?
403 print '<li>Verifying tsearch2 locale with ' . htmlspecialchars( $ctype ) . '...';
404 $rows = $this->numRows( $res );
407 print "<b>not found</b></li>\n";
408 print '<li>Attempting to set default tsearch2 locale to "' . htmlspecialchars( $ctype ) . '"...';
411 $tsname = pg_fetch_result( $res, 0, 0 );
412 if ( $tsname != 'default' ) {
413 print "<b>not set to default (" . htmlspecialchars( $tsname ) . ")</b>";
414 print "<li>Attempting to change tsearch2 default locale to \"" .
415 htmlspecialchars( $ctype ) . "\"...";
419 if ( $resetlocale ) {
420 $SQL = "UPDATE $safetsschema.pg_ts_cfg SET locale = " . $this->addQuotes( $ctype ) . " WHERE ts_name = 'default'";
421 $res = $this->doQuery( $SQL );
423 print '<b>FAILED</b>. ';
424 print 'Please make sure that the locale in pg_ts_cfg for "default" is set to "' .
425 htmlspecialchars( $ctype ) . "\"</li>\n";
431 // Final test: try out a simple tsearch2 query
432 $SQL = "SELECT $safetsschema.to_tsvector('default','MediaWiki tsearch2 testing')";
433 $res = $this->doQuery( $SQL );
435 print '<b>FAILED</b>. Specifically, "' . htmlspecialchars( $SQL ) . '" did not work.</li>';
441 // Install plpgsql if needed
442 $this->setup_plpgsql();
444 // Does the schema already exist? Who owns it?
445 $result = $this->schemaExists( $wgDBmwschema );
447 print '<li>Creating schema <b>' . htmlspecialchars( $wgDBmwschema ) . '</b> ...';
448 error_reporting( 0 );
449 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
450 $result = $this->doQuery( "CREATE SCHEMA $safeschema" );
451 error_reporting( E_ALL
);
453 print '<b>FAILED</b>. The user "' . htmlspecialchars( $wgDBuser ) .
454 '" must be able to access the schema. '.
455 'You can try making them the owner of the database, or try creating the schema with a '.
456 'different user, and then grant access to the "' .
457 htmlspecialchars( $wgDBuser ) . "\" user.</li>\n";
461 } elseif ( $result != $wgDBuser ) {
462 print '<li>Schema "' . htmlspecialchars( $wgDBmwschema ) . '" exists but is not owned by "' .
463 htmlspecialchars( $wgDBuser ) . "\". Not ideal.</li>\n";
465 print '<li>Schema "' . htmlspecialchars( $wgDBmwschema ) . '" exists and is owned by "' .
466 htmlspecialchars( $wgDBuser ) . "\". Excellent.</li>\n";
469 // Always return GMT time to accomodate the existing integer-based timestamp assumption
470 print "<li>Setting the timezone to GMT for user \"" . htmlspecialchars( $wgDBuser ) . '" ...';
471 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
472 $result = pg_query( $this->mConn
, $SQL );
474 print "<b>FAILED</b>.</li>\n";
478 // Set for the rest of this session
479 $SQL = "SET timezone = 'GMT'";
480 $result = pg_query( $this->mConn
, $SQL );
482 print "<li>Failed to set timezone</li>\n";
486 print '<li>Setting the datestyle to ISO, YMD for user "' . htmlspecialchars( $wgDBuser ) . '" ...';
487 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
488 $result = pg_query( $this->mConn
, $SQL );
490 print "<b>FAILED</b>.</li>\n";
494 // Set for the rest of this session
495 $SQL = "SET datestyle = 'ISO, YMD'";
496 $result = pg_query( $this->mConn
, $SQL );
498 print "<li>Failed to set datestyle</li>\n";
502 // Fix up the search paths if needed
503 print '<li>Setting the search path for user "' . htmlspecialchars( $wgDBuser ) . '" ...';
504 $path = $this->addIdentifierQuotes( $wgDBmwschema );
505 if ( $wgDBts2schema !== $wgDBmwschema ) {
506 $path .= ', '. $this->addIdentifierQuotes( $wgDBts2schema );
508 if ( $wgDBmwschema !== 'public' && $wgDBts2schema !== 'public' ) {
511 $SQL = "ALTER USER $safeuser SET search_path = $path";
512 $result = pg_query( $this->mConn
, $SQL );
514 print "<b>FAILED</b>.</li>\n";
518 // Set for the rest of this session
519 $SQL = "SET search_path = $path";
520 $result = pg_query( $this->mConn
, $SQL );
522 print "<li>Failed to set search_path</li>\n";
525 define( 'POSTGRES_SEARCHPATH', $path );
530 * Closes a database connection, if it is open
531 * Returns success, true if already closed
534 $this->mOpened
= false;
535 if ( $this->mConn
) {
536 return pg_close( $this->mConn
);
542 function doQuery( $sql ) {
543 if ( function_exists( 'mb_convert_encoding' ) ) {
544 $sql = mb_convert_encoding( $sql, 'UTF-8' );
546 $this->mLastResult
= pg_query( $this->mConn
, $sql );
547 $this->mAffectedRows
= null; // use pg_affected_rows(mLastResult)
548 return $this->mLastResult
;
551 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
552 return $this->query( $sql, $fname, true );
555 function freeResult( $res ) {
556 if ( $res instanceof ResultWrapper
) {
559 if ( !@pg_free_result
( $res ) ) {
560 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
564 function fetchObject( $res ) {
565 if ( $res instanceof ResultWrapper
) {
568 @$row = pg_fetch_object( $res );
569 # FIXME: HACK HACK HACK HACK debug
572 # hashar : not sure if the following test really trigger if the object
574 if( pg_last_error( $this->mConn
) ) {
575 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
580 function fetchRow( $res ) {
581 if ( $res instanceof ResultWrapper
) {
584 @$row = pg_fetch_array( $res );
585 if( pg_last_error( $this->mConn
) ) {
586 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
591 function numRows( $res ) {
592 if ( $res instanceof ResultWrapper
) {
595 @$n = pg_num_rows( $res );
596 if( pg_last_error( $this->mConn
) ) {
597 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
602 function numFields( $res ) {
603 if ( $res instanceof ResultWrapper
) {
606 return pg_num_fields( $res );
609 function fieldName( $res, $n ) {
610 if ( $res instanceof ResultWrapper
) {
613 return pg_field_name( $res, $n );
617 * This must be called after nextSequenceVal
619 function insertId() {
620 return $this->mInsertId
;
623 function dataSeek( $res, $row ) {
624 if ( $res instanceof ResultWrapper
) {
627 return pg_result_seek( $res, $row );
630 function lastError() {
631 if ( $this->mConn
) {
632 return pg_last_error();
634 return 'No database connection';
637 function lastErrno() {
638 return pg_last_error() ?
1 : 0;
641 function affectedRows() {
642 if ( !is_null( $this->mAffectedRows
) ) {
643 // Forced result for simulated queries
644 return $this->mAffectedRows
;
646 if( empty( $this->mLastResult
) ) {
649 return pg_affected_rows( $this->mLastResult
);
653 * Estimate rows in dataset
654 * Returns estimated count, based on EXPLAIN output
655 * This is not necessarily an accurate estimate, so use sparingly
656 * Returns -1 if count cannot be found
657 * Takes same arguments as Database::select()
659 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
660 $options['EXPLAIN'] = true;
661 $res = $this->select( $table, $vars, $conds, $fname, $options );
664 $row = $this->fetchRow( $res );
666 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
674 * Returns information about an index
675 * If errors are explicitly ignored, returns NULL on failure
677 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
678 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
679 $res = $this->query( $sql, $fname );
683 foreach ( $res as $row ) {
684 if ( $row->indexname
== $this->indexName( $index ) ) {
691 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
692 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
693 " AND indexdef LIKE 'CREATE UNIQUE%(" .
694 $this->strencode( $this->indexName( $index ) ) .
696 $res = $this->query( $sql, $fname );
700 foreach ( $res as $row ) {
707 * INSERT wrapper, inserts an array into a table
709 * $args may be a single associative array, or an array of these with numeric keys,
710 * for multi-row insert (Postgres version 8.2 and above only).
712 * @param $table String: Name of the table to insert to.
713 * @param $args Array: Items to insert into the table.
714 * @param $fname String: Name of the function, for profiling
715 * @param $options String or Array. Valid options: IGNORE
717 * @return bool Success of insert operation. IGNORE always returns true.
719 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
720 if ( !count( $args ) ) {
724 $table = $this->tableName( $table );
725 if (! isset( $this->numeric_version
) ) {
726 $this->getServerVersion();
729 if ( !is_array( $options ) ) {
730 $options = array( $options );
733 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
735 $keys = array_keys( $args[0] );
738 $keys = array_keys( $args );
741 // If IGNORE is set, we use savepoints to emulate mysql's behavior
742 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
744 // If we are not in a transaction, we need to be for savepoint trickery
747 if ( !$this->mTrxLevel
) {
751 $olde = error_reporting( 0 );
752 // For future use, we may want to track the number of actual inserts
753 // Right now, insert (all writes) simply return true/false
754 $numrowsinserted = 0;
757 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
760 if ( $this->numeric_version
>= 8.2 && !$ignore ) {
762 foreach ( $args as $row ) {
768 $sql .= '(' . $this->makeList( $row ) . ')';
770 $res = (bool)$this->query( $sql, $fname, $ignore );
774 foreach ( $args as $row ) {
776 $tempsql .= '(' . $this->makeList( $row ) . ')';
779 pg_query( $this->mConn
, "SAVEPOINT $ignore" );
782 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
785 $bar = pg_last_error();
786 if ( $bar != false ) {
787 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
789 pg_query( $this->mConn
, "RELEASE $ignore" );
794 // If any of them fail, we fail overall for this function call
795 // Note that this will be ignored if IGNORE is set
802 // Not multi, just a lone insert
804 pg_query($this->mConn
, "SAVEPOINT $ignore");
807 $sql .= '(' . $this->makeList( $args ) . ')';
808 $res = (bool)$this->query( $sql, $fname, $ignore );
810 $bar = pg_last_error();
811 if ( $bar != false ) {
812 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
814 pg_query( $this->mConn
, "RELEASE $ignore" );
820 $olde = error_reporting( $olde );
825 // Set the affected row count for the whole operation
826 $this->mAffectedRows
= $numrowsinserted;
828 // IGNORE always returns true
836 * INSERT SELECT wrapper
837 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
838 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
839 * $conds may be "*" to copy the whole table
840 * srcTable may be an array of tables.
841 * @todo FIXME: implement this a little better (seperate select/insert)?
843 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
844 $insertOptions = array(), $selectOptions = array() )
846 $destTable = $this->tableName( $destTable );
848 // If IGNORE is set, we use savepoints to emulate mysql's behavior
849 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
851 if( is_array( $insertOptions ) ) {
852 $insertOptions = implode( ' ', $insertOptions );
854 if( !is_array( $selectOptions ) ) {
855 $selectOptions = array( $selectOptions );
857 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
858 if( is_array( $srcTable ) ) {
859 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
861 $srcTable = $this->tableName( $srcTable );
864 // If we are not in a transaction, we need to be for savepoint trickery
867 if( !$this->mTrxLevel
) {
871 $olde = error_reporting( 0 );
872 $numrowsinserted = 0;
873 pg_query( $this->mConn
, "SAVEPOINT $ignore");
876 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
877 " SELECT $startOpts " . implode( ',', $varMap ) .
878 " FROM $srcTable $useIndex";
880 if ( $conds != '*' ) {
881 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
884 $sql .= " $tailOpts";
886 $res = (bool)$this->query( $sql, $fname, $ignore );
888 $bar = pg_last_error();
889 if( $bar != false ) {
890 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
892 pg_query( $this->mConn
, "RELEASE $ignore" );
895 $olde = error_reporting( $olde );
900 // Set the affected row count for the whole operation
901 $this->mAffectedRows
= $numrowsinserted;
903 // IGNORE always returns true
910 function tableName( $name ) {
911 # Replace reserved words with better ones
916 return 'pagecontent';
923 * Return the next in a sequence, save the value for retrieval via insertId()
925 function nextSequenceValue( $seqName ) {
926 $safeseq = str_replace( "'", "''", $seqName );
927 $res = $this->query( "SELECT nextval('$safeseq')" );
928 $row = $this->fetchRow( $res );
929 $this->mInsertId
= $row[0];
930 return $this->mInsertId
;
934 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
936 function currentSequenceValue( $seqName ) {
937 $safeseq = str_replace( "'", "''", $seqName );
938 $res = $this->query( "SELECT currval('$safeseq')" );
939 $row = $this->fetchRow( $res );
945 * REPLACE query wrapper
946 * Postgres simulates this with a DELETE followed by INSERT
947 * $row is the row to insert, an associative array
948 * $uniqueIndexes is an array of indexes. Each element may be either a
949 * field name or an array of field names
951 * It may be more efficient to leave off unique indexes which are unlikely to collide.
952 * However if you do this, you run the risk of encountering errors which wouldn't have
955 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
956 $table = $this->tableName( $table );
958 if ( count( $rows ) == 0 ) {
963 if ( !is_array( reset( $rows ) ) ) {
964 $rows = array( $rows );
967 foreach( $rows as $row ) {
968 # Delete rows which collide
969 if ( $uniqueIndexes ) {
970 $sql = "DELETE FROM $table WHERE ";
972 foreach ( $uniqueIndexes as $index ) {
979 if ( is_array( $index ) ) {
981 foreach ( $index as $col ) {
987 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
990 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
994 $this->query( $sql, $fname );
998 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
999 $this->makeList( $row, LIST_COMMA
) . ')';
1000 $this->query( $sql, $fname );
1004 # DELETE where the condition is a join
1005 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
1007 throw new DBUnexpectedError( $this, 'DatabasePostgres::deleteJoin() called with empty $conds' );
1010 $delTable = $this->tableName( $delTable );
1011 $joinTable = $this->tableName( $joinTable );
1012 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1013 if ( $conds != '*' ) {
1014 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1018 $this->query( $sql, $fname );
1021 # Returns the size of a text field, or -1 for "unlimited"
1022 function textFieldSize( $table, $field ) {
1023 $table = $this->tableName( $table );
1024 $sql = "SELECT t.typname as ftype,a.atttypmod as size
1025 FROM pg_class c, pg_attribute a, pg_type t
1026 WHERE relname='$table' AND a.attrelid=c.oid AND
1027 a.atttypid=t.oid and a.attname='$field'";
1028 $res =$this->query( $sql );
1029 $row = $this->fetchObject( $res );
1030 if ( $row->ftype
== 'varchar' ) {
1031 $size = $row->size
- 4;
1038 function limitResult( $sql, $limit, $offset = false ) {
1039 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " : '' );
1042 function wasDeadlock() {
1043 return $this->lastErrno() == '40P01';
1046 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
1047 return $this->query( 'CREATE ' . ( $temporary ?
'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
1050 function timestamp( $ts = 0 ) {
1051 return wfTimestamp( TS_POSTGRES
, $ts );
1055 * Return aggregated value function call
1057 function aggregateValue( $valuedata, $valuename = 'value' ) {
1061 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1062 // Ignore errors during error handling to avoid infinite recursion
1063 $ignore = $this->ignoreErrors( true );
1064 $this->mErrorCount++
;
1066 if ( $ignore ||
$tempIgnore ) {
1067 wfDebug( "SQL ERROR (ignored): $error\n" );
1068 $this->ignoreErrors( $ignore );
1070 $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" .
1072 "Function: $fname\n" .
1073 "Error: $errno $error\n";
1074 throw new DBUnexpectedError( $this, $message );
1079 * @return string wikitext of a link to the server software's web site
1081 public static function getSoftwareLink() {
1082 return '[http://www.postgresql.org/ PostgreSQL]';
1086 * @return string Version information from the database
1088 function getServerVersion() {
1089 if ( !isset( $this->numeric_version
) ) {
1090 $versionInfo = pg_version( $this->mConn
);
1091 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1092 // Old client, abort install
1093 $this->numeric_version
= '7.3 or earlier';
1094 } elseif ( isset( $versionInfo['server'] ) ) {
1096 $this->numeric_version
= $versionInfo['server'];
1098 // Bug 16937: broken pgsql extension from PHP<5.3
1099 $this->numeric_version
= pg_parameter_status( $this->mConn
, 'server_version' );
1102 return $this->numeric_version
;
1106 * Query whether a given relation exists (in the given schema, or the
1107 * default mw one if not given)
1109 function relationExists( $table, $types, $schema = false ) {
1110 global $wgDBmwschema;
1111 if ( !is_array( $types ) ) {
1112 $types = array( $types );
1115 $schema = $wgDBmwschema;
1117 $etable = $this->addQuotes( $table );
1118 $eschema = $this->addQuotes( $schema );
1119 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1120 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1121 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1122 $res = $this->query( $SQL );
1123 $count = $res ?
$res->numRows() : 0;
1124 return (bool)$count;
1128 * For backward compatibility, this function checks both tables and
1131 function tableExists( $table, $schema = false ) {
1132 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1135 function sequenceExists( $sequence, $schema = false ) {
1136 return $this->relationExists( $sequence, 'S', $schema );
1139 function triggerExists( $table, $trigger ) {
1140 global $wgDBmwschema;
1143 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1144 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1145 AND tgrelid=pg_class.oid
1146 AND nspname=%s AND relname=%s AND tgname=%s
1148 $res = $this->query(
1151 $this->addQuotes( $wgDBmwschema ),
1152 $this->addQuotes( $table ),
1153 $this->addQuotes( $trigger )
1159 $rows = $res->numRows();
1163 function ruleExists( $table, $rule ) {
1164 global $wgDBmwschema;
1165 $exists = $this->selectField( 'pg_rules', 'rulename',
1167 'rulename' => $rule,
1168 'tablename' => $table,
1169 'schemaname' => $wgDBmwschema
1172 return $exists === $rule;
1175 function constraintExists( $table, $constraint ) {
1176 global $wgDBmwschema;
1177 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
1178 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1179 $this->addQuotes( $wgDBmwschema ),
1180 $this->addQuotes( $table ),
1181 $this->addQuotes( $constraint )
1183 $res = $this->query( $SQL );
1187 $rows = $res->numRows();
1192 * Query whether a given schema exists. Returns the name of the owner
1194 function schemaExists( $schema ) {
1195 $eschema = str_replace( "'", "''", $schema );
1196 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1197 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1198 $res = $this->query( $SQL );
1199 if ( $res && $res->numRows() ) {
1200 $row = $res->fetchObject();
1201 $owner = $row->rolname
;
1208 function fieldInfo( $table, $field ) {
1209 return PostgresField
::fromText( $this, $table, $field );
1213 * pg_field_type() wrapper
1215 function fieldType( $res, $index ) {
1216 if ( $res instanceof ResultWrapper
) {
1217 $res = $res->result
;
1219 return pg_field_type( $res, $index );
1222 /* Not even sure why this is used in the main codebase... */
1223 function limitResultForUpdate( $sql, $num ) {
1227 function encodeBlob( $b ) {
1228 return new Blob( pg_escape_bytea( $this->mConn
, $b ) );
1231 function decodeBlob( $b ) {
1232 if ( $b instanceof Blob
) {
1235 return pg_unescape_bytea( $b );
1238 function strencode( $s ) { # Should not be called by us
1239 return pg_escape_string( $this->mConn
, $s );
1242 function addQuotes( $s ) {
1243 if ( is_null( $s ) ) {
1245 } elseif ( is_bool( $s ) ) {
1246 return intval( $s );
1247 } elseif ( $s instanceof Blob
) {
1248 return "'" . $s->fetch( $s ) . "'";
1250 return "'" . pg_escape_string( $this->mConn
, $s ) . "'";
1254 * Postgres specific version of replaceVars.
1255 * Calls the parent version in Database.php
1259 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1261 * @return string SQL string
1263 protected function replaceVars( $ins ) {
1264 $ins = parent
::replaceVars( $ins );
1266 if ( $this->numeric_version
>= 8.3 ) {
1267 // Thanks for not providing backwards-compatibility, 8.3
1268 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1271 if ( $this->numeric_version
<= 8.1 ) { // Our minimum version
1272 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1279 * Various select options
1283 * @param $options Array: an associative array of options to be turned into
1284 * an SQL query, valid keys are listed in the function.
1287 function makeSelectOptions( $options ) {
1288 $preLimitTail = $postLimitTail = '';
1289 $startOpts = $useIndex = '';
1291 $noKeyOptions = array();
1292 foreach ( $options as $key => $option ) {
1293 if ( is_numeric( $key ) ) {
1294 $noKeyOptions[$option] = true;
1298 if ( isset( $options['GROUP BY'] ) ) {
1299 $preLimitTail .= ' GROUP BY ' . $options['GROUP BY'];
1301 if ( isset( $options['HAVING'] ) ) {
1302 $preLimitTail .= " HAVING {$options['HAVING']}";
1304 if ( isset( $options['ORDER BY'] ) ) {
1305 $preLimitTail .= ' ORDER BY ' . $options['ORDER BY'];
1308 //if ( isset( $options['LIMIT'] ) ) {
1309 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1310 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1314 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1315 $postLimitTail .= ' FOR UPDATE';
1317 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1318 $postLimitTail .= ' LOCK IN SHARE MODE';
1320 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1321 $startOpts .= 'DISTINCT';
1324 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1327 function setFakeMaster( $enabled = true ) {}
1329 function getDBname() {
1330 return $this->mDBname
;
1333 function getServer() {
1334 return $this->mServer
;
1337 function buildConcat( $stringList ) {
1338 return implode( ' || ', $stringList );
1341 public function getSearchEngine() {
1342 return 'SearchPostgres';
1344 } // end DatabasePostgres class