3 * This is the Postgres database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 class PostgresField
implements Field
{
25 private $name, $tablename, $type, $nullable, $max_length, $deferred, $deferrable, $conname,
26 $has_default, $default;
29 * @param DatabaseBase $db
30 * @param string $table
31 * @param string $field
32 * @return null|PostgresField
34 static function fromText( $db, $table, $field ) {
37 attnotnull, attlen, conname AS conname,
40 COALESCE(condeferred, 'f') AS deferred,
41 COALESCE(condeferrable, 'f') AS deferrable,
42 CASE WHEN typname = 'int2' THEN 'smallint'
43 WHEN typname = 'int4' THEN 'integer'
44 WHEN typname = 'int8' THEN 'bigint'
45 WHEN typname = 'bpchar' THEN 'char'
46 ELSE typname END AS typname
48 JOIN pg_namespace n ON (n.oid = c.relnamespace)
49 JOIN pg_attribute a ON (a.attrelid = c.oid)
50 JOIN pg_type t ON (t.oid = a.atttypid)
51 LEFT JOIN pg_constraint o ON (o.conrelid = c.oid AND a.attnum = ANY(o.conkey) AND o.contype = 'f')
52 LEFT JOIN pg_attrdef d on c.oid=d.adrelid and a.attnum=d.adnum
59 $table = $db->tableName( $table, 'raw' );
62 $db->addQuotes( $db->getCoreSchema() ),
63 $db->addQuotes( $table ),
64 $db->addQuotes( $field )
67 $row = $db->fetchObject( $res );
71 $n = new PostgresField
;
72 $n->type
= $row->typname
;
73 $n->nullable
= ( $row->attnotnull
== 'f' );
75 $n->tablename
= $table;
76 $n->max_length
= $row->attlen
;
77 $n->deferrable
= ( $row->deferrable
== 't' );
78 $n->deferred
= ( $row->deferred
== 't' );
79 $n->conname
= $row->conname
;
80 $n->has_default
= ( $row->atthasdef
=== 't' );
81 $n->default = $row->adsrc
;
90 function tableName() {
91 return $this->tablename
;
98 function isNullable() {
99 return $this->nullable
;
102 function maxLength() {
103 return $this->max_length
;
106 function is_deferrable() {
107 return $this->deferrable
;
110 function is_deferred() {
111 return $this->deferred
;
115 return $this->conname
;
121 function defaultValue() {
122 if ( $this->has_default
) {
123 return $this->default;
131 * Used to debug transaction processing
132 * Only used if $wgDebugDBTransactions is true
137 class PostgresTransactionState
{
138 private static $WATCHED = array(
140 "desc" => "%s: Connection state changed from %s -> %s\n",
142 PGSQL_CONNECTION_OK
=> "OK",
143 PGSQL_CONNECTION_BAD
=> "BAD"
147 "desc" => "%s: Transaction state changed from %s -> %s\n",
149 PGSQL_TRANSACTION_IDLE
=> "IDLE",
150 PGSQL_TRANSACTION_ACTIVE
=> "ACTIVE",
151 PGSQL_TRANSACTION_INTRANS
=> "TRANS",
152 PGSQL_TRANSACTION_INERROR
=> "ERROR",
153 PGSQL_TRANSACTION_UNKNOWN
=> "UNKNOWN"
162 private $mCurrentState;
164 public function __construct( $conn ) {
165 $this->mConn
= $conn;
167 $this->mCurrentState
= $this->mNewState
;
170 public function update() {
171 $this->mNewState
= array(
172 pg_connection_status( $this->mConn
),
173 pg_transaction_status( $this->mConn
)
177 public function check() {
178 global $wgDebugDBTransactions;
180 if ( $wgDebugDBTransactions ) {
181 if ( $this->mCurrentState
!== $this->mNewState
) {
182 $old = reset( $this->mCurrentState
);
183 $new = reset( $this->mNewState
);
184 foreach ( self
::$WATCHED as $watched ) {
185 if ( $old !== $new ) {
186 $this->log_changed( $old, $new, $watched );
188 $old = next( $this->mCurrentState
);
189 $new = next( $this->mNewState
);
193 $this->mCurrentState
= $this->mNewState
;
196 protected function describe_changed( $status, $desc_table ) {
197 if ( isset( $desc_table[$status] ) ) {
198 return $desc_table[$status];
200 return "STATUS " . $status;
204 protected function log_changed( $old, $new, $watched ) {
205 wfDebug( sprintf( $watched["desc"],
207 $this->describe_changed( $old, $watched["states"] ),
208 $this->describe_changed( $new, $watched["states"] )
214 * Manage savepoints within a transaction
218 class SavepointPostgres
{
219 /** @var DatabaseBase Establish a savepoint within a transaction */
225 * @param DatabaseBase $dbw
228 public function __construct( $dbw, $id ) {
231 $this->didbegin
= false;
232 /* If we are not in a transaction, we need to be for savepoint trickery */
233 if ( !$dbw->trxLevel() ) {
234 $dbw->begin( "FOR SAVEPOINT" );
235 $this->didbegin
= true;
239 public function __destruct() {
240 if ( $this->didbegin
) {
241 $this->dbw
->rollback();
242 $this->didbegin
= false;
246 public function commit() {
247 if ( $this->didbegin
) {
248 $this->dbw
->commit();
249 $this->didbegin
= false;
253 protected function query( $keyword, $msg_ok, $msg_failed ) {
254 global $wgDebugDBTransactions;
255 if ( $this->dbw
->doQuery( $keyword . " " . $this->id
) !== false ) {
256 if ( $wgDebugDBTransactions ) {
257 wfDebug( sprintf( $msg_ok, $this->id
) );
260 wfDebug( sprintf( $msg_failed, $this->id
) );
264 public function savepoint() {
265 $this->query( "SAVEPOINT",
266 "Transaction state: savepoint \"%s\" established.\n",
267 "Transaction state: establishment of savepoint \"%s\" FAILED.\n"
271 public function release() {
272 $this->query( "RELEASE",
273 "Transaction state: savepoint \"%s\" released.\n",
274 "Transaction state: release of savepoint \"%s\" FAILED.\n"
278 public function rollback() {
279 $this->query( "ROLLBACK TO",
280 "Transaction state: savepoint \"%s\" rolled back.\n",
281 "Transaction state: rollback of savepoint \"%s\" FAILED.\n"
285 public function __toString() {
286 return (string)$this->id
;
293 class DatabasePostgres
extends DatabaseBase
{
295 protected $mLastResult = null;
297 /** @var int The number of rows affected as an integer */
298 protected $mAffectedRows = null;
301 private $mInsertId = null;
303 /** @var float|string */
304 private $numericVersion = null;
306 /** @var string Connect string to open a PostgreSQL connection */
307 private $connectString;
309 /** @var PostgresTransactionState */
310 private $mTransactionState;
313 private $mCoreSchema;
319 function cascadingDeletes() {
323 function cleanupTriggers() {
327 function strictIPs() {
331 function realTimestamps() {
335 function implicitGroupby() {
339 function implicitOrderby() {
343 function searchableIPs() {
347 function functionalIndexes() {
351 function hasConstraint( $name ) {
352 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
353 "WHERE c.connamespace = n.oid AND conname = '" .
354 pg_escape_string( $this->mConn
, $name ) . "' AND n.nspname = '" .
355 pg_escape_string( $this->mConn
, $this->getCoreSchema() ) . "'";
356 $res = $this->doQuery( $SQL );
358 return $this->numRows( $res );
362 * Usually aborts on failure
363 * @param string $server
364 * @param string $user
365 * @param string $password
366 * @param string $dbName
367 * @throws DBConnectionError|Exception
368 * @return DatabaseBase|null
370 function open( $server, $user, $password, $dbName ) {
371 # Test for Postgres support, to avoid suppressed fatal error
372 if ( !function_exists( 'pg_connect' ) ) {
373 throw new DBConnectionError(
375 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
376 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
377 "webserver and database)\n"
383 if ( !strlen( $user ) ) { # e.g. the class is being loaded
387 $this->mServer
= $server;
389 $this->mUser
= $user;
390 $this->mPassword
= $password;
391 $this->mDBname
= $dbName;
393 $connectVars = array(
396 'password' => $password
398 if ( $server != false && $server != '' ) {
399 $connectVars['host'] = $server;
401 if ( $port != false && $port != '' ) {
402 $connectVars['port'] = $port;
404 if ( $this->mFlags
& DBO_SSL
) {
405 $connectVars['sslmode'] = 1;
408 $this->connectString
= $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
410 $this->installErrorHandler();
413 $this->mConn
= pg_connect( $this->connectString
);
414 } catch ( Exception
$ex ) {
415 $this->restoreErrorHandler();
419 $phpError = $this->restoreErrorHandler();
421 if ( !$this->mConn
) {
422 wfDebug( "DB connection error\n" );
423 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " .
424 substr( $password, 0, 3 ) . "...\n" );
425 wfDebug( $this->lastError() . "\n" );
426 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
429 $this->mOpened
= true;
430 $this->mTransactionState
= new PostgresTransactionState( $this->mConn
);
432 global $wgCommandLineMode;
433 # If called from the command-line (e.g. importDump), only show errors
434 if ( $wgCommandLineMode ) {
435 $this->doQuery( "SET client_min_messages = 'ERROR'" );
438 $this->query( "SET client_encoding='UTF8'", __METHOD__
);
439 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__
);
440 $this->query( "SET timezone = 'GMT'", __METHOD__
);
441 $this->query( "SET standard_conforming_strings = on", __METHOD__
);
442 if ( $this->getServerVersion() >= 9.0 ) {
443 $this->query( "SET bytea_output = 'escape'", __METHOD__
); // PHP bug 53127
446 global $wgDBmwschema;
447 $this->determineCoreSchema( $wgDBmwschema );
453 * Postgres doesn't support selectDB in the same way MySQL does. So if the
454 * DB name doesn't match the open connection, open a new one
458 function selectDB( $db ) {
459 if ( $this->mDBname
!== $db ) {
460 return (bool)$this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $db );
466 function makeConnectionString( $vars ) {
468 foreach ( $vars as $name => $value ) {
469 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
476 * Closes a database connection, if it is open
477 * Returns success, true if already closed
480 protected function closeConnection() {
481 return pg_close( $this->mConn
);
484 public function doQuery( $sql ) {
485 if ( function_exists( 'mb_convert_encoding' ) ) {
486 $sql = mb_convert_encoding( $sql, 'UTF-8' );
488 $this->mTransactionState
->check();
489 if ( pg_send_query( $this->mConn
, $sql ) === false ) {
490 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
492 $this->mLastResult
= pg_get_result( $this->mConn
);
493 $this->mTransactionState
->check();
494 $this->mAffectedRows
= null;
495 if ( pg_result_error( $this->mLastResult
) ) {
499 return $this->mLastResult
;
502 protected function dumpError() {
506 PGSQL_DIAG_MESSAGE_PRIMARY
,
507 PGSQL_DIAG_MESSAGE_DETAIL
,
508 PGSQL_DIAG_MESSAGE_HINT
,
509 PGSQL_DIAG_STATEMENT_POSITION
,
510 PGSQL_DIAG_INTERNAL_POSITION
,
511 PGSQL_DIAG_INTERNAL_QUERY
,
513 PGSQL_DIAG_SOURCE_FILE
,
514 PGSQL_DIAG_SOURCE_LINE
,
515 PGSQL_DIAG_SOURCE_FUNCTION
517 foreach ( $diags as $d ) {
518 wfDebug( sprintf( "PgSQL ERROR(%d): %s\n",
519 $d, pg_result_error_field( $this->mLastResult
, $d ) ) );
523 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
524 /* Transaction stays in the ERROR state until rolledback */
526 /* Check for constraint violation */
527 if ( $errno === '23505' ) {
528 parent
::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
533 /* Don't ignore serious errors */
534 $this->rollback( __METHOD__
);
535 parent
::reportQueryError( $error, $errno, $sql, $fname, false );
538 function queryIgnore( $sql, $fname = __METHOD__
) {
539 return $this->query( $sql, $fname, true );
543 * @param stdClass|ResultWrapper $res
544 * @throws DBUnexpectedError
546 function freeResult( $res ) {
547 if ( $res instanceof ResultWrapper
) {
550 wfSuppressWarnings();
551 $ok = pg_free_result( $res );
554 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
559 * @param ResultWrapper|stdClass $res
561 * @throws DBUnexpectedError
563 function fetchObject( $res ) {
564 if ( $res instanceof ResultWrapper
) {
567 wfSuppressWarnings();
568 $row = pg_fetch_object( $res );
570 # @todo FIXME: HACK HACK HACK HACK debug
572 # @todo hashar: not sure if the following test really trigger if the object
574 if ( pg_last_error( $this->mConn
) ) {
575 throw new DBUnexpectedError(
577 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) )
584 function fetchRow( $res ) {
585 if ( $res instanceof ResultWrapper
) {
588 wfSuppressWarnings();
589 $row = pg_fetch_array( $res );
591 if ( pg_last_error( $this->mConn
) ) {
592 throw new DBUnexpectedError(
594 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) )
601 function numRows( $res ) {
602 if ( $res instanceof ResultWrapper
) {
605 wfSuppressWarnings();
606 $n = pg_num_rows( $res );
608 if ( pg_last_error( $this->mConn
) ) {
609 throw new DBUnexpectedError(
611 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) )
618 function numFields( $res ) {
619 if ( $res instanceof ResultWrapper
) {
623 return pg_num_fields( $res );
626 function fieldName( $res, $n ) {
627 if ( $res instanceof ResultWrapper
) {
631 return pg_field_name( $res, $n );
635 * Return the result of the last call to nextSequenceValue();
636 * This must be called after nextSequenceValue().
640 function insertId() {
641 return $this->mInsertId
;
649 function dataSeek( $res, $row ) {
650 if ( $res instanceof ResultWrapper
) {
654 return pg_result_seek( $res, $row );
657 function lastError() {
658 if ( $this->mConn
) {
659 if ( $this->mLastResult
) {
660 return pg_result_error( $this->mLastResult
);
662 return pg_last_error();
665 return 'No database connection';
669 function lastErrno() {
670 if ( $this->mLastResult
) {
671 return pg_result_error_field( $this->mLastResult
, PGSQL_DIAG_SQLSTATE
);
677 function affectedRows() {
678 if ( !is_null( $this->mAffectedRows
) ) {
679 // Forced result for simulated queries
680 return $this->mAffectedRows
;
682 if ( empty( $this->mLastResult
) ) {
686 return pg_affected_rows( $this->mLastResult
);
690 * Estimate rows in dataset
691 * Returns estimated count, based on EXPLAIN output
692 * This is not necessarily an accurate estimate, so use sparingly
693 * Returns -1 if count cannot be found
694 * Takes same arguments as Database::select()
696 * @param string $table
697 * @param string $vars
698 * @param string $conds
699 * @param string $fname
700 * @param array $options
703 function estimateRowCount( $table, $vars = '*', $conds = '',
704 $fname = __METHOD__
, $options = array()
706 $options['EXPLAIN'] = true;
707 $res = $this->select( $table, $vars, $conds, $fname, $options );
710 $row = $this->fetchRow( $res );
712 if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
721 * Returns information about an index
722 * If errors are explicitly ignored, returns NULL on failure
724 * @param string $table
725 * @param string $index
726 * @param string $fname
729 function indexInfo( $table, $index, $fname = __METHOD__
) {
730 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
731 $res = $this->query( $sql, $fname );
735 foreach ( $res as $row ) {
736 if ( $row->indexname
== $this->indexName( $index ) ) {
745 * Returns is of attributes used in index
748 * @param string $index
749 * @param bool|string $schema
752 function indexAttributes( $index, $schema = false ) {
753 if ( $schema === false ) {
754 $schema = $this->getCoreSchema();
757 * A subquery would be not needed if we didn't care about the order
758 * of attributes, but we do
760 $sql = <<<__INDEXATTR__
764 i.indoption[s.g] as option,
767 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
771 ON cis.oid=isub.indexrelid
773 ON cis.relnamespace = ns.oid
774 WHERE cis.relname='$index' AND ns.nspname='$schema') AS s,
780 ON ci.oid=i.indexrelid
782 ON ct.oid = i.indrelid
784 ON ci.relnamespace = n.oid
786 ci.relname='$index' AND n.nspname='$schema'
787 AND attrelid = ct.oid
788 AND i.indkey[s.g] = attnum
789 AND i.indclass[s.g] = opcls.oid
790 AND pg_am.oid = opcls.opcmethod
792 $res = $this->query( $sql, __METHOD__ );
795 foreach ( $res as $row ) {
809 function indexUnique( $table, $index, $fname = __METHOD__ ) {
810 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
811 " AND indexdef LIKE 'CREATE UNIQUE%(" .
812 $this->strencode( $this->indexName( $index ) ) .
814 $res = $this->query( $sql, $fname );
819 return $res->numRows() > 0;
823 * Change the FOR UPDATE option as necessary based on the join conditions. Then pass
824 * to the parent function to get the actual SQL text.
826 * In Postgres when using FOR UPDATE, only the main table and tables that are inner joined
827 * can be locked. That means tables in an outer join cannot be FOR UPDATE locked. Trying to do
828 * so causes a DB error. This wrapper checks which tables can be locked and adjusts it accordingly.
830 function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__, $options = array(), $join_conds = array() ) {
831 $forUpdateKey = array_search( 'FOR UPDATE', $options );
832 if ( $forUpdateKey !== false && $join_conds ) {
833 unset( $options[$forUpdateKey] );
835 foreach ( $join_conds as $table => $join_cond ) {
836 if ( 0 === preg_match( '/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_cond[0] ) ) {
837 $options['FOR UPDATE'][] = $table;
842 return parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
846 * INSERT wrapper, inserts an array into a table
848 * $args may be a single associative array, or an array of these with numeric keys,
849 * for multi-row insert (Postgres version 8.2 and above only).
851 * @param string $table Name of the table to insert to.
852 * @param array $args Items to insert into the table.
853 * @param string $fname Name of the function, for profiling
854 * @param array|string $options String or array. Valid options: IGNORE
855 * @return bool Success of insert operation. IGNORE always returns true.
857 function insert( $table, $args, $fname = __METHOD__, $options = array() ) {
858 if ( !count( $args ) ) {
862 $table = $this->tableName( $table );
863 if ( !isset( $this->numericVersion ) ) {
864 $this->getServerVersion();
867 if ( !is_array( $options ) ) {
868 $options = array( $options );
871 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
873 $keys = array_keys( $args[0] );
876 $keys = array_keys( $args );
879 // If IGNORE is set, we use savepoints to emulate mysql's behavior
881 if ( in_array( 'IGNORE', $options ) ) {
882 $savepoint = new SavepointPostgres( $this, 'mw' );
883 $olde = error_reporting( 0 );
884 // For future use, we may want to track the number of actual inserts
885 // Right now, insert (all writes) simply return true/false
886 $numrowsinserted = 0;
889 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
892 if ( $this->numericVersion >= 8.2 && !$savepoint ) {
894 foreach ( $args as $row ) {
900 $sql .= '(' . $this->makeList( $row ) . ')';
902 $res = (bool)$this->query( $sql, $fname, $savepoint );
906 foreach ( $args as $row ) {
908 $tempsql .= '(' . $this->makeList( $row ) . ')';
911 $savepoint->savepoint();
914 $tempres = (bool)$this->query( $tempsql, $fname, $savepoint );
917 $bar = pg_last_error();
918 if ( $bar != false ) {
919 $savepoint->rollback();
921 $savepoint->release();
926 // If any of them fail, we fail overall for this function call
927 // Note that this will be ignored if IGNORE is set
934 // Not multi, just a lone insert
936 $savepoint->savepoint();
939 $sql .= '(' . $this->makeList( $args ) . ')';
940 $res = (bool)$this->query( $sql, $fname, $savepoint );
942 $bar = pg_last_error();
943 if ( $bar != false ) {
944 $savepoint->rollback();
946 $savepoint->release();
952 error_reporting( $olde );
953 $savepoint->commit();
955 // Set the affected row count for the whole operation
956 $this->mAffectedRows = $numrowsinserted;
958 // IGNORE always returns true
966 * INSERT SELECT wrapper
967 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
968 * Source items may be literals rather then field names, but strings should
969 * be quoted with Database::addQuotes()
970 * $conds may be "*" to copy the whole table
971 * srcTable may be an array of tables.
972 * @todo FIXME: Implement this a little better (seperate select/insert)?
974 * @param string $destTable
975 * @param array|string $srcTable
976 * @param array $varMap
977 * @param array $conds
978 * @param string $fname
979 * @param array $insertOptions
980 * @param array $selectOptions
983 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
984 $insertOptions = array(), $selectOptions = array() ) {
985 $destTable = $this->tableName( $destTable );
987 if ( !is_array( $insertOptions ) ) {
988 $insertOptions = array( $insertOptions );
992 * If IGNORE is set, we use savepoints to emulate mysql's behavior
993 * Ignore LOW PRIORITY option, since it is MySQL-specific
996 if ( in_array( 'IGNORE', $insertOptions ) ) {
997 $savepoint = new SavepointPostgres( $this, 'mw' );
998 $olde = error_reporting( 0 );
999 $numrowsinserted = 0;
1000 $savepoint->savepoint();
1003 if ( !is_array( $selectOptions ) ) {
1004 $selectOptions = array( $selectOptions );
1006 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1007 if ( is_array( $srcTable ) ) {
1008 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1010 $srcTable = $this->tableName( $srcTable );
1013 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1014 " SELECT $startOpts " . implode( ',', $varMap ) .
1015 " FROM $srcTable $useIndex";
1017 if ( $conds != '*' ) {
1018 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1021 $sql .= " $tailOpts";
1023 $res = (bool)$this->query( $sql, $fname, $savepoint );
1025 $bar = pg_last_error();
1026 if ( $bar != false ) {
1027 $savepoint->rollback();
1029 $savepoint->release();
1032 error_reporting( $olde );
1033 $savepoint->commit();
1035 // Set the affected row count for the whole operation
1036 $this->mAffectedRows = $numrowsinserted;
1038 // IGNORE always returns true
1045 function tableName( $name, $format = 'quoted' ) {
1046 # Replace reserved words with better ones
1049 return $this->realTableName( 'mwuser', $format );
1051 return $this->realTableName( 'pagecontent', $format );
1053 return $this->realTableName( $name, $format );
1057 /* Don't cheat on installer */
1058 function realTableName( $name, $format = 'quoted' ) {
1059 return parent::tableName( $name, $format );
1063 * Return the next in a sequence, save the value for retrieval via insertId()
1065 * @param string $seqName
1068 function nextSequenceValue( $seqName ) {
1069 $safeseq = str_replace( "'", "''", $seqName );
1070 $res = $this->query( "SELECT nextval('$safeseq')" );
1071 $row = $this->fetchRow( $res );
1072 $this->mInsertId = $row[0];
1074 return $this->mInsertId;
1078 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
1080 * @param string $seqName
1083 function currentSequenceValue( $seqName ) {
1084 $safeseq = str_replace( "'", "''", $seqName );
1085 $res = $this->query( "SELECT currval('$safeseq')" );
1086 $row = $this->fetchRow( $res );
1092 # Returns the size of a text field, or -1 for "unlimited"
1093 function textFieldSize( $table, $field ) {
1094 $table = $this->tableName( $table );
1095 $sql = "SELECT t.typname as ftype,a.atttypmod as size
1096 FROM pg_class c, pg_attribute a, pg_type t
1097 WHERE relname='$table' AND a.attrelid=c.oid AND
1098 a.atttypid=t.oid and a.attname='$field'";
1099 $res = $this->query( $sql );
1100 $row = $this->fetchObject( $res );
1101 if ( $row->ftype == 'varchar' ) {
1102 $size = $row->size - 4;
1110 function limitResult( $sql, $limit, $offset = false ) {
1111 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
1114 function wasDeadlock() {
1115 return $this->lastErrno() == '40P01';
1118 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
1119 $newName = $this->addIdentifierQuotes( $newName );
1120 $oldName = $this->addIdentifierQuotes( $oldName );
1122 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName " .
1123 "(LIKE $oldName INCLUDING DEFAULTS)", $fname );
1126 function listTables( $prefix = null, $fname = __METHOD__ ) {
1127 $eschema = $this->addQuotes( $this->getCoreSchema() );
1128 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
1129 $endArray = array();
1131 foreach ( $result as $table ) {
1132 $vars = get_object_vars( $table );
1133 $table = array_pop( $vars );
1134 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1135 $endArray[] = $table;
1142 function timestamp( $ts = 0 ) {
1143 return wfTimestamp( TS_POSTGRES, $ts );
1147 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
1148 * to http://www.php.net/manual/en/ref.pgsql.php
1150 * Parsing a postgres array can be a tricky problem, he's my
1151 * take on this, it handles multi-dimensional arrays plus
1152 * escaping using a nasty regexp to determine the limits of each
1155 * This should really be handled by PHP PostgreSQL module
1158 * @param string $text Postgreql array returned in a text form like {a,b}
1159 * @param string $output
1161 * @param int $offset
1164 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
1165 if ( false === $limit ) {
1166 $limit = strlen( $text ) - 1;
1169 if ( '{}' == $text ) {
1173 if ( '{' != $text[$offset] ) {
1174 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
1175 $text, $match, 0, $offset );
1176 $offset += strlen( $match[0] );
1177 $output[] = ( '"' != $match[1][0]
1179 : stripcslashes( substr( $match[1], 1, -1 ) ) );
1180 if ( '},' == $match[3] ) {
1184 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
1186 } while ( $limit > $offset );
1192 * Return aggregated value function call
1194 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1199 * @return string Wikitext of a link to the server software's web site
1201 public function getSoftwareLink() {
1202 return '[{{int:version-db-postgres-url}} PostgreSQL]';
1206 * Return current schema (executes SELECT current_schema())
1210 * @return string Default schema for the current session
1212 function getCurrentSchema() {
1213 $res = $this->query( "SELECT current_schema()", __METHOD__ );
1214 $row = $this->fetchRow( $res );
1220 * Return list of schemas which are accessible without schema name
1221 * This is list does not contain magic keywords like "$user"
1224 * @see getSearchPath()
1225 * @see setSearchPath()
1227 * @return array list of actual schemas for the current sesson
1229 function getSchemas() {
1230 $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
1231 $row = $this->fetchRow( $res );
1234 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
1236 return $this->pg_array_parse( $row[0], $schemas );
1240 * Return search patch for schemas
1241 * This is different from getSchemas() since it contain magic keywords
1246 * @return array How to search for table names schemas for the current user
1248 function getSearchPath() {
1249 $res = $this->query( "SHOW search_path", __METHOD__ );
1250 $row = $this->fetchRow( $res );
1252 /* PostgreSQL returns SHOW values as strings */
1254 return explode( ",", $row[0] );
1258 * Update search_path, values should already be sanitized
1259 * Values may contain magic keywords like "$user"
1262 * @param $search_path array list of schemas to be searched by default
1264 function setSearchPath( $search_path ) {
1265 $this->query( "SET search_path = " . implode( ", ", $search_path ) );
1269 * Determine default schema for MediaWiki core
1270 * Adjust this session schema search path if desired schema exists
1271 * and is not alread there.
1273 * We need to have name of the core schema stored to be able
1274 * to query database metadata.
1276 * This will be also called by the installer after the schema is created
1280 * @param string $desiredSchema
1282 function determineCoreSchema( $desiredSchema ) {
1283 $this->begin( __METHOD__ );
1284 if ( $this->schemaExists( $desiredSchema ) ) {
1285 if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
1286 $this->mCoreSchema = $desiredSchema;
1287 wfDebug( "Schema \"" . $desiredSchema . "\" already in the search path\n" );
1290 * Prepend our schema (e.g. 'mediawiki') in front
1291 * of the search path
1294 $search_path = $this->getSearchPath();
1295 array_unshift( $search_path,
1296 $this->addIdentifierQuotes( $desiredSchema ) );
1297 $this->setSearchPath( $search_path );
1298 $this->mCoreSchema = $desiredSchema;
1299 wfDebug( "Schema \"" . $desiredSchema . "\" added to the search path\n" );
1302 $this->mCoreSchema = $this->getCurrentSchema();
1303 wfDebug( "Schema \"" . $desiredSchema . "\" not found, using current \"" .
1304 $this->mCoreSchema . "\"\n" );
1306 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1307 $this->commit( __METHOD__ );
1311 * Return schema name fore core MediaWiki tables
1314 * @return string core schema name
1316 function getCoreSchema() {
1317 return $this->mCoreSchema;
1321 * @return string Version information from the database
1323 function getServerVersion() {
1324 if ( !isset( $this->numericVersion ) ) {
1325 $versionInfo = pg_version( $this->mConn );
1326 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1327 // Old client, abort install
1328 $this->numericVersion = '7.3 or earlier';
1329 } elseif ( isset( $versionInfo['server'] ) ) {
1331 $this->numericVersion = $versionInfo['server'];
1333 // Bug 16937: broken pgsql extension from PHP<5.3
1334 $this->numericVersion = pg_parameter_status( $this->mConn, 'server_version' );
1338 return $this->numericVersion;
1342 * Query whether a given relation exists (in the given schema, or the
1343 * default mw one if not given)
1344 * @param string $table
1345 * @param array|string $types
1346 * @param bool|string $schema
1349 function relationExists( $table, $types, $schema = false ) {
1350 if ( !is_array( $types ) ) {
1351 $types = array( $types );
1354 $schema = $this->getCoreSchema();
1356 $table = $this->realTableName( $table, 'raw' );
1357 $etable = $this->addQuotes( $table );
1358 $eschema = $this->addQuotes( $schema );
1359 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1360 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1361 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1362 $res = $this->query( $SQL );
1363 $count = $res ? $res->numRows() : 0;
1365 return (bool)$count;
1369 * For backward compatibility, this function checks both tables and
1371 * @param string $table
1372 * @param string $fname
1373 * @param bool|string $schema
1376 function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1377 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1380 function sequenceExists( $sequence, $schema = false ) {
1381 return $this->relationExists( $sequence, 'S', $schema );
1384 function triggerExists( $table, $trigger ) {
1386 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1387 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1388 AND tgrelid=pg_class.oid
1389 AND nspname=%s AND relname=%s AND tgname=%s
1391 $res = $this->query(
1394 $this->addQuotes( $this->getCoreSchema() ),
1395 $this->addQuotes( $table ),
1396 $this->addQuotes( $trigger )
1402 $rows = $res->numRows();
1407 function ruleExists( $table, $rule ) {
1408 $exists = $this->selectField( 'pg_rules', 'rulename',
1410 'rulename' => $rule,
1411 'tablename' => $table,
1412 'schemaname' => $this->getCoreSchema()
1416 return $exists === $rule;
1419 function constraintExists( $table, $constraint ) {
1420 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1421 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1422 $this->addQuotes( $this->getCoreSchema() ),
1423 $this->addQuotes( $table ),
1424 $this->addQuotes( $constraint )
1426 $res = $this->query( $SQL );
1430 $rows = $res->numRows();
1436 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1437 * @param string $schema
1440 function schemaExists( $schema ) {
1441 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1442 array( 'nspname' => $schema ), __METHOD__ );
1444 return (bool)$exists;
1448 * Returns true if a given role (i.e. user) exists, false otherwise.
1449 * @param string $roleName
1452 function roleExists( $roleName ) {
1453 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1454 array( 'rolname' => $roleName ), __METHOD__ );
1456 return (bool)$exists;
1459 function fieldInfo( $table, $field ) {
1460 return PostgresField::fromText( $this, $table, $field );
1464 * pg_field_type() wrapper
1465 * @param ResultWrapper|resource $res ResultWrapper or PostgreSQL query result resource
1466 * @param int $index Field number, starting from 0
1469 function fieldType( $res, $index ) {
1470 if ( $res instanceof ResultWrapper ) {
1471 $res = $res->result;
1474 return pg_field_type( $res, $index );
1481 function encodeBlob( $b ) {
1482 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
1485 function decodeBlob( $b ) {
1486 if ( $b instanceof Blob ) {
1490 return pg_unescape_bytea( $b );
1493 function strencode( $s ) { # Should not be called by us
1494 return pg_escape_string( $this->mConn, $s );
1498 * @param null|bool|Blob $s
1499 * @return int|string
1501 function addQuotes( $s ) {
1502 if ( is_null( $s ) ) {
1504 } elseif ( is_bool( $s ) ) {
1505 return intval( $s );
1506 } elseif ( $s instanceof Blob ) {
1507 return "'" . $s->fetch( $s ) . "'";
1510 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1514 * Postgres specific version of replaceVars.
1515 * Calls the parent version in Database.php
1517 * @param string $ins SQL string, read from a stream (usually tables.sql)
1518 * @return string SQL string
1520 protected function replaceVars( $ins ) {
1521 $ins = parent::replaceVars( $ins );
1523 if ( $this->numericVersion >= 8.3 ) {
1524 // Thanks for not providing backwards-compatibility, 8.3
1525 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1528 if ( $this->numericVersion <= 8.1 ) { // Our minimum version
1529 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1536 * Various select options
1538 * @param array $options an associative array of options to be turned into
1539 * an SQL query, valid keys are listed in the function.
1542 function makeSelectOptions( $options ) {
1543 $preLimitTail = $postLimitTail = '';
1544 $startOpts = $useIndex = '';
1546 $noKeyOptions = array();
1547 foreach ( $options as $key => $option ) {
1548 if ( is_numeric( $key ) ) {
1549 $noKeyOptions[$option] = true;
1553 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1555 $preLimitTail .= $this->makeOrderBy( $options );
1557 //if ( isset( $options['LIMIT'] ) ) {
1558 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1559 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1563 if ( isset( $options['FOR UPDATE'] ) ) {
1564 $postLimitTail .= ' FOR UPDATE OF ' . implode( ', ', $options['FOR UPDATE'] );
1565 } else if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1566 $postLimitTail .= ' FOR UPDATE';
1569 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1570 $startOpts .= 'DISTINCT';
1573 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1576 function getDBname() {
1577 return $this->mDBname;
1580 function getServer() {
1581 return $this->mServer;
1584 function buildConcat( $stringList ) {
1585 return implode( ' || ', $stringList );
1588 public function buildGroupConcatField(
1589 $delimiter, $table, $field, $conds = '', $options = array(), $join_conds = array()
1591 $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1593 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
1596 public function getSearchEngine() {
1597 return 'SearchPostgres';
1600 public function streamStatementEnd( &$sql, &$newLine ) {
1601 # Allow dollar quoting for function declarations
1602 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1603 if ( $this->delimiter ) {
1604 $this->delimiter = false;
1606 $this->delimiter = ';';
1610 return parent::streamStatementEnd( $sql, $newLine );
1614 * Check to see if a named lock is available. This is non-blocking.
1615 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1617 * @param string $lockName Name of lock to poll
1618 * @param string $method Name of method calling us
1622 public function lockIsFree( $lockName, $method ) {
1623 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1624 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1625 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1626 $row = $this->fetchObject( $result );
1628 return ( $row->lockstatus === 't' );
1632 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1633 * @param string $lockName
1634 * @param string $method
1635 * @param int $timeout
1638 public function lock( $lockName, $method, $timeout = 5 ) {
1639 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1640 for ( $attempts = 1; $attempts <= $timeout; ++$attempts ) {
1641 $result = $this->query(
1642 "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1643 $row = $this->fetchObject( $result );
1644 if ( $row->lockstatus === 't' ) {
1650 wfDebug( __METHOD__ . " failed to acquire lock\n" );
1656 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKSFROM
1657 * PG DOCS: http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1658 * @param string $lockName
1659 * @param string $method
1662 public function unlock( $lockName, $method ) {
1663 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1664 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1665 $row = $this->fetchObject( $result );
1667 return ( $row->lockstatus === 't' );
1671 * @param string $lockName
1672 * @return string Integer
1674 private function bigintFromLockName( $lockName ) {
1675 return wfBaseConvert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1677 } // end DatabasePostgres class