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
;
89 function tableName() {
90 return $this->tablename
;
97 function isNullable() {
98 return $this->nullable
;
101 function maxLength() {
102 return $this->max_length
;
105 function is_deferrable() {
106 return $this->deferrable
;
109 function is_deferred() {
110 return $this->deferred
;
114 return $this->conname
;
119 function defaultValue() {
120 if( $this->has_default
) {
121 return $this->default;
130 * Used to debug transaction processing
131 * Only used if $wgDebugDBTransactions is true
136 class PostgresTransactionState
{
138 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"
158 public function __construct( $conn ) {
159 $this->mConn
= $conn;
161 $this->mCurrentState
= $this->mNewState
;
164 public function update() {
165 $this->mNewState
= array(
166 pg_connection_status( $this->mConn
),
167 pg_transaction_status( $this->mConn
)
171 public function check() {
172 global $wgDebugDBTransactions;
174 if ( $wgDebugDBTransactions ) {
175 if ( $this->mCurrentState
!== $this->mNewState
) {
176 $old = reset( $this->mCurrentState
);
177 $new = reset( $this->mNewState
);
178 foreach ( self
::$WATCHED as $watched ) {
179 if ( $old !== $new ) {
180 $this->log_changed( $old, $new, $watched );
182 $old = next( $this->mCurrentState
);
183 $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() {
299 function cleanupTriggers() {
302 function strictIPs() {
305 function realTimestamps() {
308 function implicitGroupby() {
311 function implicitOrderby() {
314 function searchableIPs() {
317 function functionalIndexes() {
321 function hasConstraint( $name ) {
322 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" .
323 pg_escape_string( $this->mConn
, $name ) . "' AND n.nspname = '" . pg_escape_string( $this->mConn
, $this->getCoreSchema() ) ."'";
324 $res = $this->doQuery( $SQL );
325 return $this->numRows( $res );
329 * Usually aborts on failure
330 * @param string $server
331 * @param string $user
332 * @param string $password
333 * @param string $dbName
334 * @throws DBConnectionError
335 * @return DatabaseBase|null
337 function open( $server, $user, $password, $dbName ) {
338 # Test for Postgres support, to avoid suppressed fatal error
339 if ( !function_exists( 'pg_connect' ) ) {
340 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" );
345 if ( !strlen( $user ) ) { # e.g. the class is being loaded
349 $this->mServer
= $server;
351 $this->mUser
= $user;
352 $this->mPassword
= $password;
353 $this->mDBname
= $dbName;
355 $connectVars = array(
358 'password' => $password
360 if ( $server != false && $server != '' ) {
361 $connectVars['host'] = $server;
363 if ( $port != false && $port != '' ) {
364 $connectVars['port'] = $port;
366 if ( $this->mFlags
& DBO_SSL
) {
367 $connectVars['sslmode'] = 1;
370 $this->connectString
= $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
372 $this->installErrorHandler();
373 $this->mConn
= pg_connect( $this->connectString
);
374 $phpError = $this->restoreErrorHandler();
376 if ( !$this->mConn
) {
377 wfDebug( "DB connection error\n" );
378 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
379 wfDebug( $this->lastError() . "\n" );
380 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
383 $this->mOpened
= true;
384 $this->mTransactionState
= new PostgresTransactionState( $this->mConn
);
386 global $wgCommandLineMode;
387 # If called from the command-line (e.g. importDump), only show errors
388 if ( $wgCommandLineMode ) {
389 $this->doQuery( "SET client_min_messages = 'ERROR'" );
392 $this->query( "SET client_encoding='UTF8'", __METHOD__
);
393 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__
);
394 $this->query( "SET timezone = 'GMT'", __METHOD__
);
395 $this->query( "SET standard_conforming_strings = on", __METHOD__
);
396 if ( $this->getServerVersion() >= 9.0 ) {
397 $this->query( "SET bytea_output = 'escape'", __METHOD__
); // PHP bug 53127
400 global $wgDBmwschema;
401 $this->determineCoreSchema( $wgDBmwschema );
407 * Postgres doesn't support selectDB in the same way MySQL does. So if the
408 * DB name doesn't match the open connection, open a new one
411 function selectDB( $db ) {
412 if ( $this->mDBname
!== $db ) {
413 return (bool)$this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $db );
419 function makeConnectionString( $vars ) {
421 foreach ( $vars as $name => $value ) {
422 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
428 * Closes a database connection, if it is open
429 * Returns success, true if already closed
432 protected function closeConnection() {
433 return pg_close( $this->mConn
);
436 public function doQuery( $sql ) {
437 if ( function_exists( 'mb_convert_encoding' ) ) {
438 $sql = mb_convert_encoding( $sql, 'UTF-8' );
440 $this->mTransactionState
->check();
441 if( pg_send_query( $this->mConn
, $sql ) === false ) {
442 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
444 $this->mLastResult
= pg_get_result( $this->mConn
);
445 $this->mTransactionState
->check();
446 $this->mAffectedRows
= null;
447 if ( pg_result_error( $this->mLastResult
) ) {
450 return $this->mLastResult
;
453 protected function dumpError () {
454 $diags = array( PGSQL_DIAG_SEVERITY
,
456 PGSQL_DIAG_MESSAGE_PRIMARY
,
457 PGSQL_DIAG_MESSAGE_DETAIL
,
458 PGSQL_DIAG_MESSAGE_HINT
,
459 PGSQL_DIAG_STATEMENT_POSITION
,
460 PGSQL_DIAG_INTERNAL_POSITION
,
461 PGSQL_DIAG_INTERNAL_QUERY
,
463 PGSQL_DIAG_SOURCE_FILE
,
464 PGSQL_DIAG_SOURCE_LINE
,
465 PGSQL_DIAG_SOURCE_FUNCTION
);
466 foreach ( $diags as $d ) {
467 wfDebug( sprintf("PgSQL ERROR(%d): %s\n", $d, pg_result_error_field( $this->mLastResult
, $d ) ) );
471 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
472 /* Transaction stays in the ERROR state until rolledback */
474 /* Check for constraint violation */
475 if ( $errno === '23505' ) {
476 parent
::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
480 /* Don't ignore serious errors */
481 $this->rollback( __METHOD__
);
482 parent
::reportQueryError( $error, $errno, $sql, $fname, false );
485 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
486 return $this->query( $sql, $fname, true );
489 function freeResult( $res ) {
490 if ( $res instanceof ResultWrapper
) {
493 wfSuppressWarnings();
494 $ok = pg_free_result( $res );
497 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
501 function fetchObject( $res ) {
502 if ( $res instanceof ResultWrapper
) {
505 wfSuppressWarnings();
506 $row = pg_fetch_object( $res );
508 # @todo FIXME: HACK HACK HACK HACK debug
510 # @todo hashar: not sure if the following test really trigger if the object
512 if( pg_last_error( $this->mConn
) ) {
513 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
518 function fetchRow( $res ) {
519 if ( $res instanceof ResultWrapper
) {
522 wfSuppressWarnings();
523 $row = pg_fetch_array( $res );
525 if( pg_last_error( $this->mConn
) ) {
526 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
531 function numRows( $res ) {
532 if ( $res instanceof ResultWrapper
) {
535 wfSuppressWarnings();
536 $n = pg_num_rows( $res );
538 if( pg_last_error( $this->mConn
) ) {
539 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
544 function numFields( $res ) {
545 if ( $res instanceof ResultWrapper
) {
548 return pg_num_fields( $res );
551 function fieldName( $res, $n ) {
552 if ( $res instanceof ResultWrapper
) {
555 return pg_field_name( $res, $n );
559 * This must be called after nextSequenceVal
562 function insertId() {
563 return $this->mInsertId
;
566 function dataSeek( $res, $row ) {
567 if ( $res instanceof ResultWrapper
) {
570 return pg_result_seek( $res, $row );
573 function lastError() {
574 if ( $this->mConn
) {
575 if ( $this->mLastResult
) {
576 return pg_result_error( $this->mLastResult
);
578 return pg_last_error();
581 return 'No database connection';
584 function lastErrno() {
585 if ( $this->mLastResult
) {
586 return pg_result_error_field( $this->mLastResult
, PGSQL_DIAG_SQLSTATE
);
592 function affectedRows() {
593 if ( !is_null( $this->mAffectedRows
) ) {
594 // Forced result for simulated queries
595 return $this->mAffectedRows
;
597 if( empty( $this->mLastResult
) ) {
600 return pg_affected_rows( $this->mLastResult
);
604 * Estimate rows in dataset
605 * Returns estimated count, based on EXPLAIN output
606 * This is not necessarily an accurate estimate, so use sparingly
607 * Returns -1 if count cannot be found
608 * Takes same arguments as Database::select()
611 function estimateRowCount( $table, $vars = '*', $conds = '', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
612 $options['EXPLAIN'] = true;
613 $res = $this->select( $table, $vars, $conds, $fname, $options );
616 $row = $this->fetchRow( $res );
618 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
626 * Returns information about an index
627 * If errors are explicitly ignored, returns NULL on failure
630 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
631 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
632 $res = $this->query( $sql, $fname );
636 foreach ( $res as $row ) {
637 if ( $row->indexname
== $this->indexName( $index ) ) {
645 * Returns is of attributes used in index
650 function indexAttributes ( $index, $schema = false ) {
651 if ( $schema === false )
652 $schema = $this->getCoreSchema();
654 * A subquery would be not needed if we didn't care about the order
655 * of attributes, but we do
657 $sql = <<<__INDEXATTR__
661 i.indoption[s.g] as option,
664 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
668 ON cis.oid=isub.indexrelid
670 ON cis.relnamespace = ns.oid
671 WHERE cis.relname='$index' AND ns.nspname='$schema') AS s,
677 ON ci.oid=i.indexrelid
679 ON ct.oid = i.indrelid
681 ON ci.relnamespace = n.oid
683 ci.relname='$index' AND n.nspname='$schema'
684 AND attrelid = ct.oid
685 AND i.indkey[s.g] = attnum
686 AND i.indclass[s.g] = opcls.oid
687 AND pg_am.oid = opcls.opcmethod
689 $res = $this->query( $sql, __METHOD__ );
692 foreach ( $res as $row ) {
705 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
706 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
707 " AND indexdef LIKE 'CREATE UNIQUE%(" .
708 $this->strencode( $this->indexName( $index ) ) .
710 $res = $this->query( $sql, $fname );
714 foreach ( $res as $row ) {
721 * INSERT wrapper, inserts an array into a table
723 * $args may be a single associative array, or an array of these with numeric keys,
724 * for multi-row insert (Postgres version 8.2 and above only).
726 * @param $table String: Name of the table to insert to.
727 * @param $args Array: Items to insert into the table.
728 * @param $fname String: Name of the function, for profiling
729 * @param string $options or Array. Valid options: IGNORE
731 * @return bool Success of insert operation. IGNORE always returns true.
733 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
734 if ( !count( $args ) ) {
738 $table = $this->tableName( $table );
739 if ( !isset( $this->numeric_version ) ) {
740 $this->getServerVersion();
743 if ( !is_array( $options ) ) {
744 $options = array( $options );
747 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
749 $keys = array_keys( $args[0] );
752 $keys = array_keys( $args );
755 // If IGNORE is set, we use savepoints to emulate mysql's behavior
757 if ( in_array( 'IGNORE', $options ) ) {
758 $savepoint = new SavepointPostgres( $this, 'mw' );
759 $olde = error_reporting( 0 );
760 // For future use, we may want to track the number of actual inserts
761 // Right now, insert (all writes) simply return true/false
762 $numrowsinserted = 0;
765 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
768 if ( $this->numeric_version >= 8.2 && !$savepoint ) {
770 foreach ( $args as $row ) {
776 $sql .= '(' . $this->makeList( $row ) . ')';
778 $res = (bool)$this->query( $sql, $fname, $savepoint );
782 foreach ( $args as $row ) {
784 $tempsql .= '(' . $this->makeList( $row ) . ')';
787 $savepoint->savepoint();
790 $tempres = (bool)$this->query( $tempsql, $fname, $savepoint );
793 $bar = pg_last_error();
794 if ( $bar != false ) {
795 $savepoint->rollback();
797 $savepoint->release();
802 // If any of them fail, we fail overall for this function call
803 // Note that this will be ignored if IGNORE is set
810 // Not multi, just a lone insert
812 $savepoint->savepoint();
815 $sql .= '(' . $this->makeList( $args ) . ')';
816 $res = (bool)$this->query( $sql, $fname, $savepoint );
818 $bar = pg_last_error();
819 if ( $bar != false ) {
820 $savepoint->rollback();
822 $savepoint->release();
828 $olde = error_reporting( $olde );
829 $savepoint->commit();
831 // Set the affected row count for the whole operation
832 $this->mAffectedRows = $numrowsinserted;
834 // IGNORE always returns true
842 * INSERT SELECT wrapper
843 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
844 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
845 * $conds may be "*" to copy the whole table
846 * srcTable may be an array of tables.
847 * @todo FIXME: Implement this a little better (seperate select/insert)?
850 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
851 $insertOptions = array(), $selectOptions = array() )
853 $destTable = $this->tableName( $destTable );
855 if( !is_array( $insertOptions ) ) {
856 $insertOptions = array( $insertOptions );
860 * If IGNORE is set, we use savepoints to emulate mysql's behavior
861 * Ignore LOW PRIORITY option, since it is MySQL-specific
864 if ( in_array( 'IGNORE', $insertOptions ) ) {
865 $savepoint = new SavepointPostgres( $this, 'mw' );
866 $olde = error_reporting( 0 );
867 $numrowsinserted = 0;
868 $savepoint->savepoint();
871 if( !is_array( $selectOptions ) ) {
872 $selectOptions = array( $selectOptions );
874 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
875 if( is_array( $srcTable ) ) {
876 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
878 $srcTable = $this->tableName( $srcTable );
881 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
882 " SELECT $startOpts " . implode( ',', $varMap ) .
883 " FROM $srcTable $useIndex";
885 if ( $conds != '*' ) {
886 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
889 $sql .= " $tailOpts";
891 $res = (bool)$this->query( $sql, $fname, $savepoint );
893 $bar = pg_last_error();
894 if( $bar != false ) {
895 $savepoint->rollback();
897 $savepoint->release();
900 $olde = error_reporting( $olde );
901 $savepoint->commit();
903 // Set the affected row count for the whole operation
904 $this->mAffectedRows = $numrowsinserted;
906 // IGNORE always returns true
913 function tableName( $name, $format = 'quoted' ) {
914 # Replace reserved words with better ones
917 return $this->realTableName( 'mwuser', $format );
919 return $this->realTableName( 'pagecontent', $format );
921 return $this->realTableName( $name, $format );
925 /* Don't cheat on installer */
926 function realTableName( $name, $format = 'quoted' ) {
927 return parent::tableName( $name, $format );
931 * Return the next in a sequence, save the value for retrieval via insertId()
934 function nextSequenceValue( $seqName ) {
935 $safeseq = str_replace( "'", "''", $seqName );
936 $res = $this->query( "SELECT nextval('$safeseq')" );
937 $row = $this->fetchRow( $res );
938 $this->mInsertId = $row[0];
939 return $this->mInsertId;
943 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
946 function currentSequenceValue( $seqName ) {
947 $safeseq = str_replace( "'", "''", $seqName );
948 $res = $this->query( "SELECT currval('$safeseq')" );
949 $row = $this->fetchRow( $res );
954 # Returns the size of a text field, or -1 for "unlimited"
955 function textFieldSize( $table, $field ) {
956 $table = $this->tableName( $table );
957 $sql = "SELECT t.typname as ftype,a.atttypmod as size
958 FROM pg_class c, pg_attribute a, pg_type t
959 WHERE relname='$table' AND a.attrelid=c.oid AND
960 a.atttypid=t.oid and a.attname='$field'";
961 $res =$this->query( $sql );
962 $row = $this->fetchObject( $res );
963 if ( $row->ftype == 'varchar' ) {
964 $size = $row->size - 4;
971 function limitResult( $sql, $limit, $offset = false ) {
972 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
975 function wasDeadlock() {
976 return $this->lastErrno() == '40P01';
979 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
980 $newName = $this->addIdentifierQuotes( $newName );
981 $oldName = $this->addIdentifierQuotes( $oldName );
982 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
985 function listTables( $prefix = null, $fname = 'DatabasePostgres::listTables' ) {
986 $eschema = $this->addQuotes( $this->getCoreSchema() );
987 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
990 foreach( $result as $table ) {
991 $vars = get_object_vars( $table );
992 $table = array_pop( $vars );
993 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
994 $endArray[] = $table;
1001 function timestamp( $ts = 0 ) {
1002 return wfTimestamp( TS_POSTGRES, $ts );
1006 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
1007 * to http://www.php.net/manual/en/ref.pgsql.php
1009 * Parsing a postgres array can be a tricky problem, he's my
1010 * take on this, it handles multi-dimensional arrays plus
1011 * escaping using a nasty regexp to determine the limits of each
1014 * This should really be handled by PHP PostgreSQL module
1017 * @param $text string: postgreql array returned in a text form like {a,b}
1018 * @param $output string
1020 * @param $offset int
1023 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
1024 if( false === $limit ) {
1025 $limit = strlen( $text )-1;
1028 if( '{}' == $text ) {
1032 if ( '{' != $text{$offset} ) {
1033 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
1034 $text, $match, 0, $offset );
1035 $offset += strlen( $match[0] );
1036 $output[] = ( '"' != $match[1]{0}
1038 : stripcslashes( substr( $match[1], 1, -1 ) ) );
1039 if ( '},' == $match[3] ) {
1043 $offset = $this->pg_array_parse( $text, $output, $limit, $offset+1 );
1045 } while ( $limit > $offset );
1050 * Return aggregated value function call
1052 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1057 * @return string wikitext of a link to the server software's web site
1059 public static function getSoftwareLink() {
1060 return '[http://www.postgresql.org/ PostgreSQL]';
1064 * Return current schema (executes SELECT current_schema())
1068 * @return string return default schema for the current session
1070 function getCurrentSchema() {
1071 $res = $this->query( "SELECT current_schema()", __METHOD__ );
1072 $row = $this->fetchRow( $res );
1077 * Return list of schemas which are accessible without schema name
1078 * This is list does not contain magic keywords like "$user"
1081 * @see getSearchPath()
1082 * @see setSearchPath()
1084 * @return array list of actual schemas for the current sesson
1086 function getSchemas() {
1087 $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
1088 $row = $this->fetchRow( $res );
1090 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
1091 return $this->pg_array_parse( $row[0], $schemas );
1095 * Return search patch for schemas
1096 * This is different from getSchemas() since it contain magic keywords
1101 * @return array how to search for table names schemas for the current user
1103 function getSearchPath() {
1104 $res = $this->query( "SHOW search_path", __METHOD__ );
1105 $row = $this->fetchRow( $res );
1106 /* PostgreSQL returns SHOW values as strings */
1107 return explode( ",", $row[0] );
1111 * Update search_path, values should already be sanitized
1112 * Values may contain magic keywords like "$user"
1115 * @param $search_path array list of schemas to be searched by default
1117 function setSearchPath( $search_path ) {
1118 $this->query( "SET search_path = " . implode( ", ", $search_path ) );
1122 * Determine default schema for MediaWiki core
1123 * Adjust this session schema search path if desired schema exists
1124 * and is not alread there.
1126 * We need to have name of the core schema stored to be able
1127 * to query database metadata.
1129 * This will be also called by the installer after the schema is created
1132 * @param $desired_schema string
1134 function determineCoreSchema( $desired_schema ) {
1135 $this->begin( __METHOD__ );
1136 if ( $this->schemaExists( $desired_schema ) ) {
1137 if ( in_array( $desired_schema, $this->getSchemas() ) ) {
1138 $this->mCoreSchema = $desired_schema;
1139 wfDebug( "Schema \"" . $desired_schema . "\" already in the search path\n" );
1142 * Prepend our schema (e.g. 'mediawiki') in front
1143 * of the search path
1146 $search_path = $this->getSearchPath();
1147 array_unshift( $search_path,
1148 $this->addIdentifierQuotes( $desired_schema ));
1149 $this->setSearchPath( $search_path );
1150 $this->mCoreSchema = $desired_schema;
1151 wfDebug( "Schema \"" . $desired_schema . "\" added to the search path\n" );
1154 $this->mCoreSchema = $this->getCurrentSchema();
1155 wfDebug( "Schema \"" . $desired_schema . "\" not found, using current \"" . $this->mCoreSchema . "\"\n" );
1157 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1158 $this->commit( __METHOD__ );
1162 * Return schema name fore core MediaWiki tables
1165 * @return string core schema name
1167 function getCoreSchema() {
1168 return $this->mCoreSchema;
1172 * @return string Version information from the database
1174 function getServerVersion() {
1175 if ( !isset( $this->numeric_version ) ) {
1176 $versionInfo = pg_version( $this->mConn );
1177 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1178 // Old client, abort install
1179 $this->numeric_version = '7.3 or earlier';
1180 } elseif ( isset( $versionInfo['server'] ) ) {
1182 $this->numeric_version = $versionInfo['server'];
1184 // Bug 16937: broken pgsql extension from PHP<5.3
1185 $this->numeric_version = pg_parameter_status( $this->mConn, 'server_version' );
1188 return $this->numeric_version;
1192 * Query whether a given relation exists (in the given schema, or the
1193 * default mw one if not given)
1196 function relationExists( $table, $types, $schema = false ) {
1197 if ( !is_array( $types ) ) {
1198 $types = array( $types );
1201 $schema = $this->getCoreSchema();
1203 $table = $this->realTableName( $table, 'raw' );
1204 $etable = $this->addQuotes( $table );
1205 $eschema = $this->addQuotes( $schema );
1206 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1207 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1208 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1209 $res = $this->query( $SQL );
1210 $count = $res ? $res->numRows() : 0;
1211 return (bool)$count;
1215 * For backward compatibility, this function checks both tables and
1219 function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1220 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1223 function sequenceExists( $sequence, $schema = false ) {
1224 return $this->relationExists( $sequence, 'S', $schema );
1227 function triggerExists( $table, $trigger ) {
1229 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1230 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1231 AND tgrelid=pg_class.oid
1232 AND nspname=%s AND relname=%s AND tgname=%s
1234 $res = $this->query(
1237 $this->addQuotes( $this->getCoreSchema() ),
1238 $this->addQuotes( $table ),
1239 $this->addQuotes( $trigger )
1245 $rows = $res->numRows();
1249 function ruleExists( $table, $rule ) {
1250 $exists = $this->selectField( 'pg_rules', 'rulename',
1252 'rulename' => $rule,
1253 'tablename' => $table,
1254 'schemaname' => $this->getCoreSchema()
1257 return $exists === $rule;
1260 function constraintExists( $table, $constraint ) {
1261 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1262 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1263 $this->addQuotes( $this->getCoreSchema() ),
1264 $this->addQuotes( $table ),
1265 $this->addQuotes( $constraint )
1267 $res = $this->query( $SQL );
1271 $rows = $res->numRows();
1276 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1279 function schemaExists( $schema ) {
1280 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1281 array( 'nspname' => $schema ), __METHOD__ );
1282 return (bool)$exists;
1286 * Returns true if a given role (i.e. user) exists, false otherwise.
1289 function roleExists( $roleName ) {
1290 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1291 array( 'rolname' => $roleName ), __METHOD__ );
1292 return (bool)$exists;
1295 function fieldInfo( $table, $field ) {
1296 return PostgresField::fromText( $this, $table, $field );
1300 * pg_field_type() wrapper
1303 function fieldType( $res, $index ) {
1304 if ( $res instanceof ResultWrapper ) {
1305 $res = $res->result;
1307 return pg_field_type( $res, $index );
1314 function encodeBlob( $b ) {
1315 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
1318 function decodeBlob( $b ) {
1319 if ( $b instanceof Blob ) {
1322 return pg_unescape_bytea( $b );
1325 function strencode( $s ) { # Should not be called by us
1326 return pg_escape_string( $this->mConn, $s );
1330 * @param $s null|bool|Blob
1331 * @return int|string
1333 function addQuotes( $s ) {
1334 if ( is_null( $s ) ) {
1336 } elseif ( is_bool( $s ) ) {
1337 return intval( $s );
1338 } elseif ( $s instanceof Blob ) {
1339 return "'" . $s->fetch( $s ) . "'";
1341 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1345 * Postgres specific version of replaceVars.
1346 * Calls the parent version in Database.php
1350 * @param string $ins SQL string, read from a stream (usually tables.sql)
1352 * @return string SQL string
1354 protected function replaceVars( $ins ) {
1355 $ins = parent::replaceVars( $ins );
1357 if ( $this->numeric_version >= 8.3 ) {
1358 // Thanks for not providing backwards-compatibility, 8.3
1359 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1362 if ( $this->numeric_version <= 8.1 ) { // Our minimum version
1363 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1370 * Various select options
1374 * @param array $options an associative array of options to be turned into
1375 * an SQL query, valid keys are listed in the function.
1378 function makeSelectOptions( $options ) {
1379 $preLimitTail = $postLimitTail = '';
1380 $startOpts = $useIndex = '';
1382 $noKeyOptions = array();
1383 foreach ( $options as $key => $option ) {
1384 if ( is_numeric( $key ) ) {
1385 $noKeyOptions[$option] = true;
1389 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1391 $preLimitTail .= $this->makeOrderBy( $options );
1393 //if ( isset( $options['LIMIT'] ) ) {
1394 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1395 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1399 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1400 $postLimitTail .= ' FOR UPDATE';
1402 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1403 $startOpts .= 'DISTINCT';
1406 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1409 function setFakeMaster( $enabled = true ) {}
1411 function getDBname() {
1412 return $this->mDBname;
1415 function getServer() {
1416 return $this->mServer;
1419 function buildConcat( $stringList ) {
1420 return implode( ' || ', $stringList );
1423 public function getSearchEngine() {
1424 return 'SearchPostgres';
1427 public function streamStatementEnd( &$sql, &$newLine ) {
1428 # Allow dollar quoting for function declarations
1429 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1430 if ( $this->delimiter ) {
1431 $this->delimiter = false;
1434 $this->delimiter = ';';
1437 return parent::streamStatementEnd( $sql, $newLine );
1441 * Check to see if a named lock is available. This is non-blocking.
1442 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1444 * @param string $lockName name of lock to poll
1445 * @param string $method name of method calling us
1449 public function lockIsFree( $lockName, $method ) {
1450 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1451 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1452 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1453 $row = $this->fetchObject( $result );
1454 return ( $row->lockstatus === 't' );
1458 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1459 * @param $lockName string
1460 * @param $method string
1461 * @param $timeout int
1464 public function lock( $lockName, $method, $timeout = 5 ) {
1465 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1466 for ( $attempts = 1; $attempts <= $timeout; ++$attempts ) {
1467 $result = $this->query(
1468 "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1469 $row = $this->fetchObject( $result );
1470 if ( $row->lockstatus === 't' ) {
1476 wfDebug( __METHOD__." failed to acquire lock\n" );
1481 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKSFROM PG DOCS: http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1482 * @param $lockName string
1483 * @param $method string
1486 public function unlock( $lockName, $method ) {
1487 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1488 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1489 $row = $this->fetchObject( $result );
1490 return ( $row->lockstatus === 't' );
1494 * @param string $lockName
1495 * @return string Integer
1497 private function bigintFromLockName( $lockName ) {
1498 return wfBaseConvert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1500 } // end DatabasePostgres class