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 $db DatabaseBase
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
{
139 static $WATCHED = array(
141 "desc" => "%s: Connection state changed from %s -> %s\n",
143 PGSQL_CONNECTION_OK
=> "OK",
144 PGSQL_CONNECTION_BAD
=> "BAD"
148 "desc" => "%s: Transaction state changed from %s -> %s\n",
150 PGSQL_TRANSACTION_IDLE
=> "IDLE",
151 PGSQL_TRANSACTION_ACTIVE
=> "ACTIVE",
152 PGSQL_TRANSACTION_INTRANS
=> "TRANS",
153 PGSQL_TRANSACTION_INERROR
=> "ERROR",
154 PGSQL_TRANSACTION_UNKNOWN
=> "UNKNOWN"
159 public function __construct( $conn ) {
160 $this->mConn
= $conn;
162 $this->mCurrentState
= $this->mNewState
;
165 public function update() {
166 $this->mNewState
= array(
167 pg_connection_status( $this->mConn
),
168 pg_transaction_status( $this->mConn
)
172 public function check() {
173 global $wgDebugDBTransactions;
175 if ( $wgDebugDBTransactions ) {
176 if ( $this->mCurrentState
!== $this->mNewState
) {
177 $old = reset( $this->mCurrentState
);
178 $new = reset( $this->mNewState
);
179 foreach ( self
::$WATCHED as $watched ) {
180 if ( $old !== $new ) {
181 $this->log_changed( $old, $new, $watched );
183 $old = next( $this->mCurrentState
);
184 $new = next( $this->mNewState
);
188 $this->mCurrentState
= $this->mNewState
;
191 protected function describe_changed( $status, $desc_table ) {
192 if ( isset( $desc_table[$status] ) ) {
193 return $desc_table[$status];
195 return "STATUS " . $status;
199 protected function log_changed( $old, $new, $watched ) {
200 wfDebug( sprintf( $watched["desc"],
202 $this->describe_changed( $old, $watched["states"] ),
203 $this->describe_changed( $new, $watched["states"] )
209 * Manage savepoints within a transaction
213 class SavepointPostgres
{
215 * Establish a savepoint within a transaction
221 public function __construct( $dbw, $id ) {
224 $this->didbegin
= false;
225 /* If we are not in a transaction, we need to be for savepoint trickery */
226 if ( !$dbw->trxLevel() ) {
227 $dbw->begin( "FOR SAVEPOINT" );
228 $this->didbegin
= true;
232 public function __destruct() {
233 if ( $this->didbegin
) {
234 $this->dbw
->rollback();
235 $this->didbegin
= false;
239 public function commit() {
240 if ( $this->didbegin
) {
241 $this->dbw
->commit();
242 $this->didbegin
= false;
246 protected function query( $keyword, $msg_ok, $msg_failed ) {
247 global $wgDebugDBTransactions;
248 if ( $this->dbw
->doQuery( $keyword . " " . $this->id
) !== false ) {
249 if ( $wgDebugDBTransactions ) {
250 wfDebug( sprintf( $msg_ok, $this->id
) );
253 wfDebug( sprintf( $msg_failed, $this->id
) );
257 public function savepoint() {
258 $this->query( "SAVEPOINT",
259 "Transaction state: savepoint \"%s\" established.\n",
260 "Transaction state: establishment of savepoint \"%s\" FAILED.\n"
264 public function release() {
265 $this->query( "RELEASE",
266 "Transaction state: savepoint \"%s\" released.\n",
267 "Transaction state: release of savepoint \"%s\" FAILED.\n"
271 public function rollback() {
272 $this->query( "ROLLBACK TO",
273 "Transaction state: savepoint \"%s\" rolled back.\n",
274 "Transaction state: rollback of savepoint \"%s\" FAILED.\n"
278 public function __toString() {
279 return (string)$this->id
;
286 class DatabasePostgres
extends DatabaseBase
{
287 var $mInsertId = null;
288 var $mLastResult = null;
289 var $numeric_version = null;
290 var $mAffectedRows = null;
296 function cascadingDeletes() {
300 function cleanupTriggers() {
304 function strictIPs() {
308 function realTimestamps() {
312 function implicitGroupby() {
316 function implicitOrderby() {
320 function searchableIPs() {
324 function functionalIndexes() {
328 function hasConstraint( $name ) {
329 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
330 "WHERE c.connamespace = n.oid AND conname = '" .
331 pg_escape_string( $this->mConn
, $name ) . "' AND n.nspname = '" .
332 pg_escape_string( $this->mConn
, $this->getCoreSchema() ) . "'";
333 $res = $this->doQuery( $SQL );
335 return $this->numRows( $res );
339 * Usually aborts on failure
340 * @param string $server
341 * @param string $user
342 * @param string $password
343 * @param string $dbName
344 * @throws DBConnectionError
345 * @return DatabaseBase|null
347 function open( $server, $user, $password, $dbName ) {
348 # Test for Postgres support, to avoid suppressed fatal error
349 if ( !function_exists( 'pg_connect' ) ) {
350 throw new DBConnectionError(
352 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
353 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
354 "webserver and database)\n"
360 if ( !strlen( $user ) ) { # e.g. the class is being loaded
364 $this->mServer
= $server;
366 $this->mUser
= $user;
367 $this->mPassword
= $password;
368 $this->mDBname
= $dbName;
370 $connectVars = array(
373 'password' => $password
375 if ( $server != false && $server != '' ) {
376 $connectVars['host'] = $server;
378 if ( $port != false && $port != '' ) {
379 $connectVars['port'] = $port;
381 if ( $this->mFlags
& DBO_SSL
) {
382 $connectVars['sslmode'] = 1;
385 $this->connectString
= $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
387 $this->installErrorHandler();
390 $this->mConn
= pg_connect( $this->connectString
);
391 } catch ( Exception
$ex ) {
392 $this->restoreErrorHandler();
396 $phpError = $this->restoreErrorHandler();
398 if ( !$this->mConn
) {
399 wfDebug( "DB connection error\n" );
400 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " .
401 substr( $password, 0, 3 ) . "...\n" );
402 wfDebug( $this->lastError() . "\n" );
403 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
406 $this->mOpened
= true;
407 $this->mTransactionState
= new PostgresTransactionState( $this->mConn
);
409 global $wgCommandLineMode;
410 # If called from the command-line (e.g. importDump), only show errors
411 if ( $wgCommandLineMode ) {
412 $this->doQuery( "SET client_min_messages = 'ERROR'" );
415 $this->query( "SET client_encoding='UTF8'", __METHOD__
);
416 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__
);
417 $this->query( "SET timezone = 'GMT'", __METHOD__
);
418 $this->query( "SET standard_conforming_strings = on", __METHOD__
);
419 if ( $this->getServerVersion() >= 9.0 ) {
420 $this->query( "SET bytea_output = 'escape'", __METHOD__
); // PHP bug 53127
423 global $wgDBmwschema;
424 $this->determineCoreSchema( $wgDBmwschema );
430 * Postgres doesn't support selectDB in the same way MySQL does. So if the
431 * DB name doesn't match the open connection, open a new one
434 function selectDB( $db ) {
435 if ( $this->mDBname
!== $db ) {
436 return (bool)$this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $db );
442 function makeConnectionString( $vars ) {
444 foreach ( $vars as $name => $value ) {
445 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
452 * Closes a database connection, if it is open
453 * Returns success, true if already closed
456 protected function closeConnection() {
457 return pg_close( $this->mConn
);
460 public function doQuery( $sql ) {
461 if ( function_exists( 'mb_convert_encoding' ) ) {
462 $sql = mb_convert_encoding( $sql, 'UTF-8' );
464 $this->mTransactionState
->check();
465 if ( pg_send_query( $this->mConn
, $sql ) === false ) {
466 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
468 $this->mLastResult
= pg_get_result( $this->mConn
);
469 $this->mTransactionState
->check();
470 $this->mAffectedRows
= null;
471 if ( pg_result_error( $this->mLastResult
) ) {
475 return $this->mLastResult
;
478 protected function dumpError() {
482 PGSQL_DIAG_MESSAGE_PRIMARY
,
483 PGSQL_DIAG_MESSAGE_DETAIL
,
484 PGSQL_DIAG_MESSAGE_HINT
,
485 PGSQL_DIAG_STATEMENT_POSITION
,
486 PGSQL_DIAG_INTERNAL_POSITION
,
487 PGSQL_DIAG_INTERNAL_QUERY
,
489 PGSQL_DIAG_SOURCE_FILE
,
490 PGSQL_DIAG_SOURCE_LINE
,
491 PGSQL_DIAG_SOURCE_FUNCTION
493 foreach ( $diags as $d ) {
494 wfDebug( sprintf( "PgSQL ERROR(%d): %s\n",
495 $d, pg_result_error_field( $this->mLastResult
, $d ) ) );
499 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
500 /* Transaction stays in the ERROR state until rolledback */
502 /* Check for constraint violation */
503 if ( $errno === '23505' ) {
504 parent
::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
509 /* Don't ignore serious errors */
510 $this->rollback( __METHOD__
);
511 parent
::reportQueryError( $error, $errno, $sql, $fname, false );
514 function queryIgnore( $sql, $fname = __METHOD__
) {
515 return $this->query( $sql, $fname, true );
518 function freeResult( $res ) {
519 if ( $res instanceof ResultWrapper
) {
522 wfSuppressWarnings();
523 $ok = pg_free_result( $res );
526 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
530 function fetchObject( $res ) {
531 if ( $res instanceof ResultWrapper
) {
534 wfSuppressWarnings();
535 $row = pg_fetch_object( $res );
537 # @todo FIXME: HACK HACK HACK HACK debug
539 # @todo hashar: not sure if the following test really trigger if the object
541 if ( pg_last_error( $this->mConn
) ) {
542 throw new DBUnexpectedError(
544 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) )
551 function fetchRow( $res ) {
552 if ( $res instanceof ResultWrapper
) {
555 wfSuppressWarnings();
556 $row = pg_fetch_array( $res );
558 if ( pg_last_error( $this->mConn
) ) {
559 throw new DBUnexpectedError(
561 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) )
568 function numRows( $res ) {
569 if ( $res instanceof ResultWrapper
) {
572 wfSuppressWarnings();
573 $n = pg_num_rows( $res );
575 if ( pg_last_error( $this->mConn
) ) {
576 throw new DBUnexpectedError(
578 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) )
585 function numFields( $res ) {
586 if ( $res instanceof ResultWrapper
) {
590 return pg_num_fields( $res );
593 function fieldName( $res, $n ) {
594 if ( $res instanceof ResultWrapper
) {
598 return pg_field_name( $res, $n );
602 * Return the result of the last call to nextSequenceValue();
603 * This must be called after nextSequenceValue().
605 * @return integer|null
607 function insertId() {
608 return $this->mInsertId
;
611 function dataSeek( $res, $row ) {
612 if ( $res instanceof ResultWrapper
) {
616 return pg_result_seek( $res, $row );
619 function lastError() {
620 if ( $this->mConn
) {
621 if ( $this->mLastResult
) {
622 return pg_result_error( $this->mLastResult
);
624 return pg_last_error();
627 return 'No database connection';
631 function lastErrno() {
632 if ( $this->mLastResult
) {
633 return pg_result_error_field( $this->mLastResult
, PGSQL_DIAG_SQLSTATE
);
639 function affectedRows() {
640 if ( !is_null( $this->mAffectedRows
) ) {
641 // Forced result for simulated queries
642 return $this->mAffectedRows
;
644 if ( empty( $this->mLastResult
) ) {
648 return pg_affected_rows( $this->mLastResult
);
652 * Estimate rows in dataset
653 * Returns estimated count, based on EXPLAIN output
654 * This is not necessarily an accurate estimate, so use sparingly
655 * Returns -1 if count cannot be found
656 * Takes same arguments as Database::select()
659 function estimateRowCount( $table, $vars = '*', $conds = '',
660 $fname = __METHOD__
, $options = array()
662 $options['EXPLAIN'] = true;
663 $res = $this->select( $table, $vars, $conds, $fname, $options );
666 $row = $this->fetchRow( $res );
668 if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
677 * Returns information about an index
678 * If errors are explicitly ignored, returns NULL on failure
681 function indexInfo( $table, $index, $fname = __METHOD__
) {
682 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
683 $res = $this->query( $sql, $fname );
687 foreach ( $res as $row ) {
688 if ( $row->indexname
== $this->indexName( $index ) ) {
697 * Returns is of attributes used in index
702 function indexAttributes( $index, $schema = false ) {
703 if ( $schema === false ) {
704 $schema = $this->getCoreSchema();
707 * A subquery would be not needed if we didn't care about the order
708 * of attributes, but we do
710 $sql = <<<__INDEXATTR__
714 i.indoption[s.g] as option,
717 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
721 ON cis.oid=isub.indexrelid
723 ON cis.relnamespace = ns.oid
724 WHERE cis.relname='$index' AND ns.nspname='$schema') AS s,
730 ON ci.oid=i.indexrelid
732 ON ct.oid = i.indrelid
734 ON ci.relnamespace = n.oid
736 ci.relname='$index' AND n.nspname='$schema'
737 AND attrelid = ct.oid
738 AND i.indkey[s.g] = attnum
739 AND i.indclass[s.g] = opcls.oid
740 AND pg_am.oid = opcls.opcmethod
742 $res = $this->query( $sql, __METHOD__ );
745 foreach ( $res as $row ) {
759 function indexUnique( $table, $index, $fname = __METHOD__ ) {
760 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
761 " AND indexdef LIKE 'CREATE UNIQUE%(" .
762 $this->strencode( $this->indexName( $index ) ) .
764 $res = $this->query( $sql, $fname );
768 foreach ( $res as $row ) {
776 * INSERT wrapper, inserts an array into a table
778 * $args may be a single associative array, or an array of these with numeric keys,
779 * for multi-row insert (Postgres version 8.2 and above only).
781 * @param $table String: Name of the table to insert to.
782 * @param $args Array: Items to insert into the table.
783 * @param $fname String: Name of the function, for profiling
784 * @param string $options or Array. Valid options: IGNORE
786 * @return bool Success of insert operation. IGNORE always returns true.
788 function insert( $table, $args, $fname = __METHOD__, $options = array() ) {
789 if ( !count( $args ) ) {
793 $table = $this->tableName( $table );
794 if ( !isset( $this->numeric_version ) ) {
795 $this->getServerVersion();
798 if ( !is_array( $options ) ) {
799 $options = array( $options );
802 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
804 $keys = array_keys( $args[0] );
807 $keys = array_keys( $args );
810 // If IGNORE is set, we use savepoints to emulate mysql's behavior
812 if ( in_array( 'IGNORE', $options ) ) {
813 $savepoint = new SavepointPostgres( $this, 'mw' );
814 $olde = error_reporting( 0 );
815 // For future use, we may want to track the number of actual inserts
816 // Right now, insert (all writes) simply return true/false
817 $numrowsinserted = 0;
820 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
823 if ( $this->numeric_version >= 8.2 && !$savepoint ) {
825 foreach ( $args as $row ) {
831 $sql .= '(' . $this->makeList( $row ) . ')';
833 $res = (bool)$this->query( $sql, $fname, $savepoint );
837 foreach ( $args as $row ) {
839 $tempsql .= '(' . $this->makeList( $row ) . ')';
842 $savepoint->savepoint();
845 $tempres = (bool)$this->query( $tempsql, $fname, $savepoint );
848 $bar = pg_last_error();
849 if ( $bar != false ) {
850 $savepoint->rollback();
852 $savepoint->release();
857 // If any of them fail, we fail overall for this function call
858 // Note that this will be ignored if IGNORE is set
865 // Not multi, just a lone insert
867 $savepoint->savepoint();
870 $sql .= '(' . $this->makeList( $args ) . ')';
871 $res = (bool)$this->query( $sql, $fname, $savepoint );
873 $bar = pg_last_error();
874 if ( $bar != false ) {
875 $savepoint->rollback();
877 $savepoint->release();
883 $olde = error_reporting( $olde );
884 $savepoint->commit();
886 // Set the affected row count for the whole operation
887 $this->mAffectedRows = $numrowsinserted;
889 // IGNORE always returns true
897 * INSERT SELECT wrapper
898 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
899 * Source items may be literals rather then field names, but strings should
900 * be quoted with Database::addQuotes()
901 * $conds may be "*" to copy the whole table
902 * srcTable may be an array of tables.
903 * @todo FIXME: Implement this a little better (seperate select/insert)?
906 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
907 $insertOptions = array(), $selectOptions = array() ) {
908 $destTable = $this->tableName( $destTable );
910 if ( !is_array( $insertOptions ) ) {
911 $insertOptions = array( $insertOptions );
915 * If IGNORE is set, we use savepoints to emulate mysql's behavior
916 * Ignore LOW PRIORITY option, since it is MySQL-specific
919 if ( in_array( 'IGNORE', $insertOptions ) ) {
920 $savepoint = new SavepointPostgres( $this, 'mw' );
921 $olde = error_reporting( 0 );
922 $numrowsinserted = 0;
923 $savepoint->savepoint();
926 if ( !is_array( $selectOptions ) ) {
927 $selectOptions = array( $selectOptions );
929 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
930 if ( is_array( $srcTable ) ) {
931 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
933 $srcTable = $this->tableName( $srcTable );
936 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
937 " SELECT $startOpts " . implode( ',', $varMap ) .
938 " FROM $srcTable $useIndex";
940 if ( $conds != '*' ) {
941 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
944 $sql .= " $tailOpts";
946 $res = (bool)$this->query( $sql, $fname, $savepoint );
948 $bar = pg_last_error();
949 if ( $bar != false ) {
950 $savepoint->rollback();
952 $savepoint->release();
955 $olde = error_reporting( $olde );
956 $savepoint->commit();
958 // Set the affected row count for the whole operation
959 $this->mAffectedRows = $numrowsinserted;
961 // IGNORE always returns true
968 function tableName( $name, $format = 'quoted' ) {
969 # Replace reserved words with better ones
972 return $this->realTableName( 'mwuser', $format );
974 return $this->realTableName( 'pagecontent', $format );
976 return $this->realTableName( $name, $format );
980 /* Don't cheat on installer */
981 function realTableName( $name, $format = 'quoted' ) {
982 return parent::tableName( $name, $format );
986 * Return the next in a sequence, save the value for retrieval via insertId()
989 function nextSequenceValue( $seqName ) {
990 $safeseq = str_replace( "'", "''", $seqName );
991 $res = $this->query( "SELECT nextval('$safeseq')" );
992 $row = $this->fetchRow( $res );
993 $this->mInsertId = $row[0];
995 return $this->mInsertId;
999 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
1002 function currentSequenceValue( $seqName ) {
1003 $safeseq = str_replace( "'", "''", $seqName );
1004 $res = $this->query( "SELECT currval('$safeseq')" );
1005 $row = $this->fetchRow( $res );
1011 # Returns the size of a text field, or -1 for "unlimited"
1012 function textFieldSize( $table, $field ) {
1013 $table = $this->tableName( $table );
1014 $sql = "SELECT t.typname as ftype,a.atttypmod as size
1015 FROM pg_class c, pg_attribute a, pg_type t
1016 WHERE relname='$table' AND a.attrelid=c.oid AND
1017 a.atttypid=t.oid and a.attname='$field'";
1018 $res = $this->query( $sql );
1019 $row = $this->fetchObject( $res );
1020 if ( $row->ftype == 'varchar' ) {
1021 $size = $row->size - 4;
1029 function limitResult( $sql, $limit, $offset = false ) {
1030 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
1033 function wasDeadlock() {
1034 return $this->lastErrno() == '40P01';
1037 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
1038 $newName = $this->addIdentifierQuotes( $newName );
1039 $oldName = $this->addIdentifierQuotes( $oldName );
1041 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName " .
1042 "(LIKE $oldName INCLUDING DEFAULTS)", $fname );
1045 function listTables( $prefix = null, $fname = __METHOD__ ) {
1046 $eschema = $this->addQuotes( $this->getCoreSchema() );
1047 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
1048 $endArray = array();
1050 foreach ( $result as $table ) {
1051 $vars = get_object_vars( $table );
1052 $table = array_pop( $vars );
1053 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1054 $endArray[] = $table;
1061 function timestamp( $ts = 0 ) {
1062 return wfTimestamp( TS_POSTGRES, $ts );
1066 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
1067 * to http://www.php.net/manual/en/ref.pgsql.php
1069 * Parsing a postgres array can be a tricky problem, he's my
1070 * take on this, it handles multi-dimensional arrays plus
1071 * escaping using a nasty regexp to determine the limits of each
1074 * This should really be handled by PHP PostgreSQL module
1077 * @param $text string: postgreql array returned in a text form like {a,b}
1078 * @param $output string
1080 * @param $offset int
1083 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
1084 if ( false === $limit ) {
1085 $limit = strlen( $text ) - 1;
1088 if ( '{}' == $text ) {
1092 if ( '{' != $text[$offset] ) {
1093 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
1094 $text, $match, 0, $offset );
1095 $offset += strlen( $match[0] );
1096 $output[] = ( '"' != $match[1][0]
1098 : stripcslashes( substr( $match[1], 1, -1 ) ) );
1099 if ( '},' == $match[3] ) {
1103 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
1105 } while ( $limit > $offset );
1111 * Return aggregated value function call
1113 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1118 * @return string wikitext of a link to the server software's web site
1120 public function getSoftwareLink() {
1121 return '[http://www.postgresql.org/ PostgreSQL]';
1125 * Return current schema (executes SELECT current_schema())
1129 * @return string return default schema for the current session
1131 function getCurrentSchema() {
1132 $res = $this->query( "SELECT current_schema()", __METHOD__ );
1133 $row = $this->fetchRow( $res );
1139 * Return list of schemas which are accessible without schema name
1140 * This is list does not contain magic keywords like "$user"
1143 * @see getSearchPath()
1144 * @see setSearchPath()
1146 * @return array list of actual schemas for the current sesson
1148 function getSchemas() {
1149 $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
1150 $row = $this->fetchRow( $res );
1153 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
1155 return $this->pg_array_parse( $row[0], $schemas );
1159 * Return search patch for schemas
1160 * This is different from getSchemas() since it contain magic keywords
1165 * @return array how to search for table names schemas for the current user
1167 function getSearchPath() {
1168 $res = $this->query( "SHOW search_path", __METHOD__ );
1169 $row = $this->fetchRow( $res );
1171 /* PostgreSQL returns SHOW values as strings */
1173 return explode( ",", $row[0] );
1177 * Update search_path, values should already be sanitized
1178 * Values may contain magic keywords like "$user"
1181 * @param $search_path array list of schemas to be searched by default
1183 function setSearchPath( $search_path ) {
1184 $this->query( "SET search_path = " . implode( ", ", $search_path ) );
1188 * Determine default schema for MediaWiki core
1189 * Adjust this session schema search path if desired schema exists
1190 * and is not alread there.
1192 * We need to have name of the core schema stored to be able
1193 * to query database metadata.
1195 * This will be also called by the installer after the schema is created
1198 * @param $desired_schema string
1200 function determineCoreSchema( $desired_schema ) {
1201 $this->begin( __METHOD__ );
1202 if ( $this->schemaExists( $desired_schema ) ) {
1203 if ( in_array( $desired_schema, $this->getSchemas() ) ) {
1204 $this->mCoreSchema = $desired_schema;
1205 wfDebug( "Schema \"" . $desired_schema . "\" already in the search path\n" );
1208 * Prepend our schema (e.g. 'mediawiki') in front
1209 * of the search path
1212 $search_path = $this->getSearchPath();
1213 array_unshift( $search_path,
1214 $this->addIdentifierQuotes( $desired_schema ) );
1215 $this->setSearchPath( $search_path );
1216 $this->mCoreSchema = $desired_schema;
1217 wfDebug( "Schema \"" . $desired_schema . "\" added to the search path\n" );
1220 $this->mCoreSchema = $this->getCurrentSchema();
1221 wfDebug( "Schema \"" . $desired_schema . "\" not found, using current \"" .
1222 $this->mCoreSchema . "\"\n" );
1224 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1225 $this->commit( __METHOD__ );
1229 * Return schema name fore core MediaWiki tables
1232 * @return string core schema name
1234 function getCoreSchema() {
1235 return $this->mCoreSchema;
1239 * @return string Version information from the database
1241 function getServerVersion() {
1242 if ( !isset( $this->numeric_version ) ) {
1243 $versionInfo = pg_version( $this->mConn );
1244 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1245 // Old client, abort install
1246 $this->numeric_version = '7.3 or earlier';
1247 } elseif ( isset( $versionInfo['server'] ) ) {
1249 $this->numeric_version = $versionInfo['server'];
1251 // Bug 16937: broken pgsql extension from PHP<5.3
1252 $this->numeric_version = pg_parameter_status( $this->mConn, 'server_version' );
1256 return $this->numeric_version;
1260 * Query whether a given relation exists (in the given schema, or the
1261 * default mw one if not given)
1264 function relationExists( $table, $types, $schema = false ) {
1265 if ( !is_array( $types ) ) {
1266 $types = array( $types );
1269 $schema = $this->getCoreSchema();
1271 $table = $this->realTableName( $table, 'raw' );
1272 $etable = $this->addQuotes( $table );
1273 $eschema = $this->addQuotes( $schema );
1274 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1275 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1276 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1277 $res = $this->query( $SQL );
1278 $count = $res ? $res->numRows() : 0;
1280 return (bool)$count;
1284 * For backward compatibility, this function checks both tables and
1288 function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1289 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1292 function sequenceExists( $sequence, $schema = false ) {
1293 return $this->relationExists( $sequence, 'S', $schema );
1296 function triggerExists( $table, $trigger ) {
1298 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1299 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1300 AND tgrelid=pg_class.oid
1301 AND nspname=%s AND relname=%s AND tgname=%s
1303 $res = $this->query(
1306 $this->addQuotes( $this->getCoreSchema() ),
1307 $this->addQuotes( $table ),
1308 $this->addQuotes( $trigger )
1314 $rows = $res->numRows();
1319 function ruleExists( $table, $rule ) {
1320 $exists = $this->selectField( 'pg_rules', 'rulename',
1322 'rulename' => $rule,
1323 'tablename' => $table,
1324 'schemaname' => $this->getCoreSchema()
1328 return $exists === $rule;
1331 function constraintExists( $table, $constraint ) {
1332 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1333 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1334 $this->addQuotes( $this->getCoreSchema() ),
1335 $this->addQuotes( $table ),
1336 $this->addQuotes( $constraint )
1338 $res = $this->query( $SQL );
1342 $rows = $res->numRows();
1348 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1351 function schemaExists( $schema ) {
1352 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1353 array( 'nspname' => $schema ), __METHOD__ );
1355 return (bool)$exists;
1359 * Returns true if a given role (i.e. user) exists, false otherwise.
1362 function roleExists( $roleName ) {
1363 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1364 array( 'rolname' => $roleName ), __METHOD__ );
1366 return (bool)$exists;
1369 function fieldInfo( $table, $field ) {
1370 return PostgresField::fromText( $this, $table, $field );
1374 * pg_field_type() wrapper
1377 function fieldType( $res, $index ) {
1378 if ( $res instanceof ResultWrapper ) {
1379 $res = $res->result;
1382 return pg_field_type( $res, $index );
1389 function encodeBlob( $b ) {
1390 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
1393 function decodeBlob( $b ) {
1394 if ( $b instanceof Blob ) {
1398 return pg_unescape_bytea( $b );
1401 function strencode( $s ) { # Should not be called by us
1402 return pg_escape_string( $this->mConn, $s );
1406 * @param $s null|bool|Blob
1407 * @return int|string
1409 function addQuotes( $s ) {
1410 if ( is_null( $s ) ) {
1412 } elseif ( is_bool( $s ) ) {
1413 return intval( $s );
1414 } elseif ( $s instanceof Blob ) {
1415 return "'" . $s->fetch( $s ) . "'";
1418 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1422 * Postgres specific version of replaceVars.
1423 * Calls the parent version in Database.php
1427 * @param string $ins SQL string, read from a stream (usually tables.sql)
1429 * @return string SQL string
1431 protected function replaceVars( $ins ) {
1432 $ins = parent::replaceVars( $ins );
1434 if ( $this->numeric_version >= 8.3 ) {
1435 // Thanks for not providing backwards-compatibility, 8.3
1436 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1439 if ( $this->numeric_version <= 8.1 ) { // Our minimum version
1440 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1447 * Various select options
1451 * @param array $options an associative array of options to be turned into
1452 * an SQL query, valid keys are listed in the function.
1455 function makeSelectOptions( $options ) {
1456 $preLimitTail = $postLimitTail = '';
1457 $startOpts = $useIndex = '';
1459 $noKeyOptions = array();
1460 foreach ( $options as $key => $option ) {
1461 if ( is_numeric( $key ) ) {
1462 $noKeyOptions[$option] = true;
1466 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1468 $preLimitTail .= $this->makeOrderBy( $options );
1470 //if ( isset( $options['LIMIT'] ) ) {
1471 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1472 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1476 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1477 $postLimitTail .= ' FOR UPDATE';
1479 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1480 $startOpts .= 'DISTINCT';
1483 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1486 function setFakeMaster( $enabled = true ) {
1489 function getDBname() {
1490 return $this->mDBname;
1493 function getServer() {
1494 return $this->mServer;
1497 function buildConcat( $stringList ) {
1498 return implode( ' || ', $stringList );
1501 public function buildGroupConcatField(
1502 $delimiter, $table, $field, $conds = '', $options = array(), $join_conds = array()
1504 $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1506 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
1509 public function getSearchEngine() {
1510 return 'SearchPostgres';
1513 public function streamStatementEnd( &$sql, &$newLine ) {
1514 # Allow dollar quoting for function declarations
1515 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1516 if ( $this->delimiter ) {
1517 $this->delimiter = false;
1519 $this->delimiter = ';';
1523 return parent::streamStatementEnd( $sql, $newLine );
1527 * Check to see if a named lock is available. This is non-blocking.
1528 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1530 * @param string $lockName name of lock to poll
1531 * @param string $method name of method calling us
1535 public function lockIsFree( $lockName, $method ) {
1536 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1537 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1538 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1539 $row = $this->fetchObject( $result );
1541 return ( $row->lockstatus === 't' );
1545 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1546 * @param $lockName string
1547 * @param $method string
1548 * @param $timeout int
1551 public function lock( $lockName, $method, $timeout = 5 ) {
1552 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1553 for ( $attempts = 1; $attempts <= $timeout; ++$attempts ) {
1554 $result = $this->query(
1555 "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1556 $row = $this->fetchObject( $result );
1557 if ( $row->lockstatus === 't' ) {
1563 wfDebug( __METHOD__ . " failed to acquire lock\n" );
1569 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKSFROM
1570 * PG DOCS: http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1571 * @param $lockName string
1572 * @param $method string
1575 public function unlock( $lockName, $method ) {
1576 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1577 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1578 $row = $this->fetchObject( $result );
1580 return ( $row->lockstatus === 't' );
1584 * @param string $lockName
1585 * @return string Integer
1587 private function bigintFromLockName( $lockName ) {
1588 return wfBaseConvert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1590 } // end DatabasePostgres class