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
{
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
{
220 * Establish a savepoint within a transaction
226 public function __construct( $dbw, $id ) {
229 $this->didbegin
= false;
230 /* If we are not in a transaction, we need to be for savepoint trickery */
231 if ( !$dbw->trxLevel() ) {
232 $dbw->begin( "FOR SAVEPOINT" );
233 $this->didbegin
= true;
237 public function __destruct() {
238 if ( $this->didbegin
) {
239 $this->dbw
->rollback();
240 $this->didbegin
= false;
244 public function commit() {
245 if ( $this->didbegin
) {
246 $this->dbw
->commit();
247 $this->didbegin
= false;
251 protected function query( $keyword, $msg_ok, $msg_failed ) {
252 global $wgDebugDBTransactions;
253 if ( $this->dbw
->doQuery( $keyword . " " . $this->id
) !== false ) {
254 if ( $wgDebugDBTransactions ) {
255 wfDebug( sprintf( $msg_ok, $this->id
) );
258 wfDebug( sprintf( $msg_failed, $this->id
) );
262 public function savepoint() {
263 $this->query( "SAVEPOINT",
264 "Transaction state: savepoint \"%s\" established.\n",
265 "Transaction state: establishment of savepoint \"%s\" FAILED.\n"
269 public function release() {
270 $this->query( "RELEASE",
271 "Transaction state: savepoint \"%s\" released.\n",
272 "Transaction state: release of savepoint \"%s\" FAILED.\n"
276 public function rollback() {
277 $this->query( "ROLLBACK TO",
278 "Transaction state: savepoint \"%s\" rolled back.\n",
279 "Transaction state: rollback of savepoint \"%s\" FAILED.\n"
283 public function __toString() {
284 return (string)$this->id
;
291 class DatabasePostgres
extends DatabaseBase
{
293 protected $mLastResult = null;
295 /** @var int The number of rows affected as an integer */
296 protected $mAffectedRows = null;
299 private $mInsertId = null;
301 /** @var float|string */
302 private $numericVersion = null;
304 /** @var string Connect string to open a PostgreSQL connection */
305 private $connectString;
307 /** @var PostgresTransactionState */
308 private $mTransactionState;
311 private $mCoreSchema;
317 function cascadingDeletes() {
321 function cleanupTriggers() {
325 function strictIPs() {
329 function realTimestamps() {
333 function implicitGroupby() {
337 function implicitOrderby() {
341 function searchableIPs() {
345 function functionalIndexes() {
349 function hasConstraint( $name ) {
350 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
351 "WHERE c.connamespace = n.oid AND conname = '" .
352 pg_escape_string( $this->mConn
, $name ) . "' AND n.nspname = '" .
353 pg_escape_string( $this->mConn
, $this->getCoreSchema() ) . "'";
354 $res = $this->doQuery( $SQL );
356 return $this->numRows( $res );
360 * Usually aborts on failure
361 * @param string $server
362 * @param string $user
363 * @param string $password
364 * @param string $dbName
365 * @throws DBConnectionError
366 * @return DatabaseBase|null
368 function open( $server, $user, $password, $dbName ) {
369 # Test for Postgres support, to avoid suppressed fatal error
370 if ( !function_exists( 'pg_connect' ) ) {
371 throw new DBConnectionError(
373 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
374 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
375 "webserver and database)\n"
381 if ( !strlen( $user ) ) { # e.g. the class is being loaded
385 $this->mServer
= $server;
387 $this->mUser
= $user;
388 $this->mPassword
= $password;
389 $this->mDBname
= $dbName;
391 $connectVars = array(
394 'password' => $password
396 if ( $server != false && $server != '' ) {
397 $connectVars['host'] = $server;
399 if ( $port != false && $port != '' ) {
400 $connectVars['port'] = $port;
402 if ( $this->mFlags
& DBO_SSL
) {
403 $connectVars['sslmode'] = 1;
406 $this->connectString
= $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
408 $this->installErrorHandler();
411 $this->mConn
= pg_connect( $this->connectString
);
412 } catch ( Exception
$ex ) {
413 $this->restoreErrorHandler();
417 $phpError = $this->restoreErrorHandler();
419 if ( !$this->mConn
) {
420 wfDebug( "DB connection error\n" );
421 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " .
422 substr( $password, 0, 3 ) . "...\n" );
423 wfDebug( $this->lastError() . "\n" );
424 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
427 $this->mOpened
= true;
428 $this->mTransactionState
= new PostgresTransactionState( $this->mConn
);
430 global $wgCommandLineMode;
431 # If called from the command-line (e.g. importDump), only show errors
432 if ( $wgCommandLineMode ) {
433 $this->doQuery( "SET client_min_messages = 'ERROR'" );
436 $this->query( "SET client_encoding='UTF8'", __METHOD__
);
437 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__
);
438 $this->query( "SET timezone = 'GMT'", __METHOD__
);
439 $this->query( "SET standard_conforming_strings = on", __METHOD__
);
440 if ( $this->getServerVersion() >= 9.0 ) {
441 $this->query( "SET bytea_output = 'escape'", __METHOD__
); // PHP bug 53127
444 global $wgDBmwschema;
445 $this->determineCoreSchema( $wgDBmwschema );
451 * Postgres doesn't support selectDB in the same way MySQL does. So if the
452 * DB name doesn't match the open connection, open a new one
455 function selectDB( $db ) {
456 if ( $this->mDBname
!== $db ) {
457 return (bool)$this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $db );
463 function makeConnectionString( $vars ) {
465 foreach ( $vars as $name => $value ) {
466 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
473 * Closes a database connection, if it is open
474 * Returns success, true if already closed
477 protected function closeConnection() {
478 return pg_close( $this->mConn
);
481 public function doQuery( $sql ) {
482 if ( function_exists( 'mb_convert_encoding' ) ) {
483 $sql = mb_convert_encoding( $sql, 'UTF-8' );
485 $this->mTransactionState
->check();
486 if ( pg_send_query( $this->mConn
, $sql ) === false ) {
487 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
489 $this->mLastResult
= pg_get_result( $this->mConn
);
490 $this->mTransactionState
->check();
491 $this->mAffectedRows
= null;
492 if ( pg_result_error( $this->mLastResult
) ) {
496 return $this->mLastResult
;
499 protected function dumpError() {
503 PGSQL_DIAG_MESSAGE_PRIMARY
,
504 PGSQL_DIAG_MESSAGE_DETAIL
,
505 PGSQL_DIAG_MESSAGE_HINT
,
506 PGSQL_DIAG_STATEMENT_POSITION
,
507 PGSQL_DIAG_INTERNAL_POSITION
,
508 PGSQL_DIAG_INTERNAL_QUERY
,
510 PGSQL_DIAG_SOURCE_FILE
,
511 PGSQL_DIAG_SOURCE_LINE
,
512 PGSQL_DIAG_SOURCE_FUNCTION
514 foreach ( $diags as $d ) {
515 wfDebug( sprintf( "PgSQL ERROR(%d): %s\n",
516 $d, pg_result_error_field( $this->mLastResult
, $d ) ) );
520 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
521 /* Transaction stays in the ERROR state until rolledback */
523 /* Check for constraint violation */
524 if ( $errno === '23505' ) {
525 parent
::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
530 /* Don't ignore serious errors */
531 $this->rollback( __METHOD__
);
532 parent
::reportQueryError( $error, $errno, $sql, $fname, false );
535 function queryIgnore( $sql, $fname = __METHOD__
) {
536 return $this->query( $sql, $fname, true );
539 function freeResult( $res ) {
540 if ( $res instanceof ResultWrapper
) {
543 wfSuppressWarnings();
544 $ok = pg_free_result( $res );
547 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
551 function fetchObject( $res ) {
552 if ( $res instanceof ResultWrapper
) {
555 wfSuppressWarnings();
556 $row = pg_fetch_object( $res );
558 # @todo FIXME: HACK HACK HACK HACK debug
560 # @todo hashar: not sure if the following test really trigger if the object
562 if ( pg_last_error( $this->mConn
) ) {
563 throw new DBUnexpectedError(
565 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) )
572 function fetchRow( $res ) {
573 if ( $res instanceof ResultWrapper
) {
576 wfSuppressWarnings();
577 $row = pg_fetch_array( $res );
579 if ( pg_last_error( $this->mConn
) ) {
580 throw new DBUnexpectedError(
582 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) )
589 function numRows( $res ) {
590 if ( $res instanceof ResultWrapper
) {
593 wfSuppressWarnings();
594 $n = pg_num_rows( $res );
596 if ( pg_last_error( $this->mConn
) ) {
597 throw new DBUnexpectedError(
599 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) )
606 function numFields( $res ) {
607 if ( $res instanceof ResultWrapper
) {
611 return pg_num_fields( $res );
614 function fieldName( $res, $n ) {
615 if ( $res instanceof ResultWrapper
) {
619 return pg_field_name( $res, $n );
623 * Return the result of the last call to nextSequenceValue();
624 * This must be called after nextSequenceValue().
628 function insertId() {
629 return $this->mInsertId
;
632 function dataSeek( $res, $row ) {
633 if ( $res instanceof ResultWrapper
) {
637 return pg_result_seek( $res, $row );
640 function lastError() {
641 if ( $this->mConn
) {
642 if ( $this->mLastResult
) {
643 return pg_result_error( $this->mLastResult
);
645 return pg_last_error();
648 return 'No database connection';
652 function lastErrno() {
653 if ( $this->mLastResult
) {
654 return pg_result_error_field( $this->mLastResult
, PGSQL_DIAG_SQLSTATE
);
660 function affectedRows() {
661 if ( !is_null( $this->mAffectedRows
) ) {
662 // Forced result for simulated queries
663 return $this->mAffectedRows
;
665 if ( empty( $this->mLastResult
) ) {
669 return pg_affected_rows( $this->mLastResult
);
673 * Estimate rows in dataset
674 * Returns estimated count, based on EXPLAIN output
675 * This is not necessarily an accurate estimate, so use sparingly
676 * Returns -1 if count cannot be found
677 * Takes same arguments as Database::select()
680 function estimateRowCount( $table, $vars = '*', $conds = '',
681 $fname = __METHOD__
, $options = array()
683 $options['EXPLAIN'] = true;
684 $res = $this->select( $table, $vars, $conds, $fname, $options );
687 $row = $this->fetchRow( $res );
689 if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
698 * Returns information about an index
699 * If errors are explicitly ignored, returns NULL on failure
702 function indexInfo( $table, $index, $fname = __METHOD__
) {
703 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
704 $res = $this->query( $sql, $fname );
708 foreach ( $res as $row ) {
709 if ( $row->indexname
== $this->indexName( $index ) ) {
718 * Returns is of attributes used in index
723 function indexAttributes( $index, $schema = false ) {
724 if ( $schema === false ) {
725 $schema = $this->getCoreSchema();
728 * A subquery would be not needed if we didn't care about the order
729 * of attributes, but we do
731 $sql = <<<__INDEXATTR__
735 i.indoption[s.g] as option,
738 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
742 ON cis.oid=isub.indexrelid
744 ON cis.relnamespace = ns.oid
745 WHERE cis.relname='$index' AND ns.nspname='$schema') AS s,
751 ON ci.oid=i.indexrelid
753 ON ct.oid = i.indrelid
755 ON ci.relnamespace = n.oid
757 ci.relname='$index' AND n.nspname='$schema'
758 AND attrelid = ct.oid
759 AND i.indkey[s.g] = attnum
760 AND i.indclass[s.g] = opcls.oid
761 AND pg_am.oid = opcls.opcmethod
763 $res = $this->query( $sql, __METHOD__ );
766 foreach ( $res as $row ) {
780 function indexUnique( $table, $index, $fname = __METHOD__ ) {
781 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
782 " AND indexdef LIKE 'CREATE UNIQUE%(" .
783 $this->strencode( $this->indexName( $index ) ) .
785 $res = $this->query( $sql, $fname );
789 foreach ( $res as $row ) {
797 * INSERT wrapper, inserts an array into a table
799 * $args may be a single associative array, or an array of these with numeric keys,
800 * for multi-row insert (Postgres version 8.2 and above only).
802 * @param $table String: Name of the table to insert to.
803 * @param $args Array: Items to insert into the table.
804 * @param $fname String: Name of the function, for profiling
805 * @param string $options or Array. Valid options: IGNORE
807 * @return bool Success of insert operation. IGNORE always returns true.
809 function insert( $table, $args, $fname = __METHOD__, $options = array() ) {
810 if ( !count( $args ) ) {
814 $table = $this->tableName( $table );
815 if ( !isset( $this->numericVersion ) ) {
816 $this->getServerVersion();
819 if ( !is_array( $options ) ) {
820 $options = array( $options );
823 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
825 $keys = array_keys( $args[0] );
828 $keys = array_keys( $args );
831 // If IGNORE is set, we use savepoints to emulate mysql's behavior
833 if ( in_array( 'IGNORE', $options ) ) {
834 $savepoint = new SavepointPostgres( $this, 'mw' );
835 $olde = error_reporting( 0 );
836 // For future use, we may want to track the number of actual inserts
837 // Right now, insert (all writes) simply return true/false
838 $numrowsinserted = 0;
841 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
844 if ( $this->numericVersion >= 8.2 && !$savepoint ) {
846 foreach ( $args as $row ) {
852 $sql .= '(' . $this->makeList( $row ) . ')';
854 $res = (bool)$this->query( $sql, $fname, $savepoint );
858 foreach ( $args as $row ) {
860 $tempsql .= '(' . $this->makeList( $row ) . ')';
863 $savepoint->savepoint();
866 $tempres = (bool)$this->query( $tempsql, $fname, $savepoint );
869 $bar = pg_last_error();
870 if ( $bar != false ) {
871 $savepoint->rollback();
873 $savepoint->release();
878 // If any of them fail, we fail overall for this function call
879 // Note that this will be ignored if IGNORE is set
886 // Not multi, just a lone insert
888 $savepoint->savepoint();
891 $sql .= '(' . $this->makeList( $args ) . ')';
892 $res = (bool)$this->query( $sql, $fname, $savepoint );
894 $bar = pg_last_error();
895 if ( $bar != false ) {
896 $savepoint->rollback();
898 $savepoint->release();
904 $olde = error_reporting( $olde );
905 $savepoint->commit();
907 // Set the affected row count for the whole operation
908 $this->mAffectedRows = $numrowsinserted;
910 // IGNORE always returns true
918 * INSERT SELECT wrapper
919 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
920 * Source items may be literals rather then field names, but strings should
921 * be quoted with Database::addQuotes()
922 * $conds may be "*" to copy the whole table
923 * srcTable may be an array of tables.
924 * @todo FIXME: Implement this a little better (seperate select/insert)?
927 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
928 $insertOptions = array(), $selectOptions = array() ) {
929 $destTable = $this->tableName( $destTable );
931 if ( !is_array( $insertOptions ) ) {
932 $insertOptions = array( $insertOptions );
936 * If IGNORE is set, we use savepoints to emulate mysql's behavior
937 * Ignore LOW PRIORITY option, since it is MySQL-specific
940 if ( in_array( 'IGNORE', $insertOptions ) ) {
941 $savepoint = new SavepointPostgres( $this, 'mw' );
942 $olde = error_reporting( 0 );
943 $numrowsinserted = 0;
944 $savepoint->savepoint();
947 if ( !is_array( $selectOptions ) ) {
948 $selectOptions = array( $selectOptions );
950 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
951 if ( is_array( $srcTable ) ) {
952 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
954 $srcTable = $this->tableName( $srcTable );
957 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
958 " SELECT $startOpts " . implode( ',', $varMap ) .
959 " FROM $srcTable $useIndex";
961 if ( $conds != '*' ) {
962 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
965 $sql .= " $tailOpts";
967 $res = (bool)$this->query( $sql, $fname, $savepoint );
969 $bar = pg_last_error();
970 if ( $bar != false ) {
971 $savepoint->rollback();
973 $savepoint->release();
976 $olde = error_reporting( $olde );
977 $savepoint->commit();
979 // Set the affected row count for the whole operation
980 $this->mAffectedRows = $numrowsinserted;
982 // IGNORE always returns true
989 function tableName( $name, $format = 'quoted' ) {
990 # Replace reserved words with better ones
993 return $this->realTableName( 'mwuser', $format );
995 return $this->realTableName( 'pagecontent', $format );
997 return $this->realTableName( $name, $format );
1001 /* Don't cheat on installer */
1002 function realTableName( $name, $format = 'quoted' ) {
1003 return parent::tableName( $name, $format );
1007 * Return the next in a sequence, save the value for retrieval via insertId()
1009 * @param string $seqName
1012 function nextSequenceValue( $seqName ) {
1013 $safeseq = str_replace( "'", "''", $seqName );
1014 $res = $this->query( "SELECT nextval('$safeseq')" );
1015 $row = $this->fetchRow( $res );
1016 $this->mInsertId = $row[0];
1018 return $this->mInsertId;
1022 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
1024 * @param string $seqName
1027 function currentSequenceValue( $seqName ) {
1028 $safeseq = str_replace( "'", "''", $seqName );
1029 $res = $this->query( "SELECT currval('$safeseq')" );
1030 $row = $this->fetchRow( $res );
1036 # Returns the size of a text field, or -1 for "unlimited"
1037 function textFieldSize( $table, $field ) {
1038 $table = $this->tableName( $table );
1039 $sql = "SELECT t.typname as ftype,a.atttypmod as size
1040 FROM pg_class c, pg_attribute a, pg_type t
1041 WHERE relname='$table' AND a.attrelid=c.oid AND
1042 a.atttypid=t.oid and a.attname='$field'";
1043 $res = $this->query( $sql );
1044 $row = $this->fetchObject( $res );
1045 if ( $row->ftype == 'varchar' ) {
1046 $size = $row->size - 4;
1054 function limitResult( $sql, $limit, $offset = false ) {
1055 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
1058 function wasDeadlock() {
1059 return $this->lastErrno() == '40P01';
1062 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
1063 $newName = $this->addIdentifierQuotes( $newName );
1064 $oldName = $this->addIdentifierQuotes( $oldName );
1066 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName " .
1067 "(LIKE $oldName INCLUDING DEFAULTS)", $fname );
1070 function listTables( $prefix = null, $fname = __METHOD__ ) {
1071 $eschema = $this->addQuotes( $this->getCoreSchema() );
1072 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
1073 $endArray = array();
1075 foreach ( $result as $table ) {
1076 $vars = get_object_vars( $table );
1077 $table = array_pop( $vars );
1078 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1079 $endArray[] = $table;
1086 function timestamp( $ts = 0 ) {
1087 return wfTimestamp( TS_POSTGRES, $ts );
1091 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
1092 * to http://www.php.net/manual/en/ref.pgsql.php
1094 * Parsing a postgres array can be a tricky problem, he's my
1095 * take on this, it handles multi-dimensional arrays plus
1096 * escaping using a nasty regexp to determine the limits of each
1099 * This should really be handled by PHP PostgreSQL module
1102 * @param $text string: postgreql array returned in a text form like {a,b}
1103 * @param $output string
1105 * @param $offset int
1108 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
1109 if ( false === $limit ) {
1110 $limit = strlen( $text ) - 1;
1113 if ( '{}' == $text ) {
1117 if ( '{' != $text[$offset] ) {
1118 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
1119 $text, $match, 0, $offset );
1120 $offset += strlen( $match[0] );
1121 $output[] = ( '"' != $match[1][0]
1123 : stripcslashes( substr( $match[1], 1, -1 ) ) );
1124 if ( '},' == $match[3] ) {
1128 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
1130 } while ( $limit > $offset );
1136 * Return aggregated value function call
1138 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1143 * @return string wikitext of a link to the server software's web site
1145 public function getSoftwareLink() {
1146 return '[http://www.postgresql.org/ PostgreSQL]';
1150 * Return current schema (executes SELECT current_schema())
1154 * @return string Default schema for the current session
1156 function getCurrentSchema() {
1157 $res = $this->query( "SELECT current_schema()", __METHOD__ );
1158 $row = $this->fetchRow( $res );
1164 * Return list of schemas which are accessible without schema name
1165 * This is list does not contain magic keywords like "$user"
1168 * @see getSearchPath()
1169 * @see setSearchPath()
1171 * @return array list of actual schemas for the current sesson
1173 function getSchemas() {
1174 $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
1175 $row = $this->fetchRow( $res );
1178 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
1180 return $this->pg_array_parse( $row[0], $schemas );
1184 * Return search patch for schemas
1185 * This is different from getSchemas() since it contain magic keywords
1190 * @return array how to search for table names schemas for the current user
1192 function getSearchPath() {
1193 $res = $this->query( "SHOW search_path", __METHOD__ );
1194 $row = $this->fetchRow( $res );
1196 /* PostgreSQL returns SHOW values as strings */
1198 return explode( ",", $row[0] );
1202 * Update search_path, values should already be sanitized
1203 * Values may contain magic keywords like "$user"
1206 * @param $search_path array list of schemas to be searched by default
1208 function setSearchPath( $search_path ) {
1209 $this->query( "SET search_path = " . implode( ", ", $search_path ) );
1213 * Determine default schema for MediaWiki core
1214 * Adjust this session schema search path if desired schema exists
1215 * and is not alread there.
1217 * We need to have name of the core schema stored to be able
1218 * to query database metadata.
1220 * This will be also called by the installer after the schema is created
1223 * @param $desired_schema string
1225 function determineCoreSchema( $desired_schema ) {
1226 $this->begin( __METHOD__ );
1227 if ( $this->schemaExists( $desired_schema ) ) {
1228 if ( in_array( $desired_schema, $this->getSchemas() ) ) {
1229 $this->mCoreSchema = $desired_schema;
1230 wfDebug( "Schema \"" . $desired_schema . "\" already in the search path\n" );
1233 * Prepend our schema (e.g. 'mediawiki') in front
1234 * of the search path
1237 $search_path = $this->getSearchPath();
1238 array_unshift( $search_path,
1239 $this->addIdentifierQuotes( $desired_schema ) );
1240 $this->setSearchPath( $search_path );
1241 $this->mCoreSchema = $desired_schema;
1242 wfDebug( "Schema \"" . $desired_schema . "\" added to the search path\n" );
1245 $this->mCoreSchema = $this->getCurrentSchema();
1246 wfDebug( "Schema \"" . $desired_schema . "\" not found, using current \"" .
1247 $this->mCoreSchema . "\"\n" );
1249 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1250 $this->commit( __METHOD__ );
1254 * Return schema name fore core MediaWiki tables
1257 * @return string core schema name
1259 function getCoreSchema() {
1260 return $this->mCoreSchema;
1264 * @return string Version information from the database
1266 function getServerVersion() {
1267 if ( !isset( $this->numericVersion ) ) {
1268 $versionInfo = pg_version( $this->mConn );
1269 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1270 // Old client, abort install
1271 $this->numericVersion = '7.3 or earlier';
1272 } elseif ( isset( $versionInfo['server'] ) ) {
1274 $this->numericVersion = $versionInfo['server'];
1276 // Bug 16937: broken pgsql extension from PHP<5.3
1277 $this->numericVersion = pg_parameter_status( $this->mConn, 'server_version' );
1281 return $this->numericVersion;
1285 * Query whether a given relation exists (in the given schema, or the
1286 * default mw one if not given)
1289 function relationExists( $table, $types, $schema = false ) {
1290 if ( !is_array( $types ) ) {
1291 $types = array( $types );
1294 $schema = $this->getCoreSchema();
1296 $table = $this->realTableName( $table, 'raw' );
1297 $etable = $this->addQuotes( $table );
1298 $eschema = $this->addQuotes( $schema );
1299 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1300 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1301 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1302 $res = $this->query( $SQL );
1303 $count = $res ? $res->numRows() : 0;
1305 return (bool)$count;
1309 * For backward compatibility, this function checks both tables and
1313 function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1314 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1317 function sequenceExists( $sequence, $schema = false ) {
1318 return $this->relationExists( $sequence, 'S', $schema );
1321 function triggerExists( $table, $trigger ) {
1323 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1324 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1325 AND tgrelid=pg_class.oid
1326 AND nspname=%s AND relname=%s AND tgname=%s
1328 $res = $this->query(
1331 $this->addQuotes( $this->getCoreSchema() ),
1332 $this->addQuotes( $table ),
1333 $this->addQuotes( $trigger )
1339 $rows = $res->numRows();
1344 function ruleExists( $table, $rule ) {
1345 $exists = $this->selectField( 'pg_rules', 'rulename',
1347 'rulename' => $rule,
1348 'tablename' => $table,
1349 'schemaname' => $this->getCoreSchema()
1353 return $exists === $rule;
1356 function constraintExists( $table, $constraint ) {
1357 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1358 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1359 $this->addQuotes( $this->getCoreSchema() ),
1360 $this->addQuotes( $table ),
1361 $this->addQuotes( $constraint )
1363 $res = $this->query( $SQL );
1367 $rows = $res->numRows();
1373 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1376 function schemaExists( $schema ) {
1377 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1378 array( 'nspname' => $schema ), __METHOD__ );
1380 return (bool)$exists;
1384 * Returns true if a given role (i.e. user) exists, false otherwise.
1387 function roleExists( $roleName ) {
1388 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1389 array( 'rolname' => $roleName ), __METHOD__ );
1391 return (bool)$exists;
1394 function fieldInfo( $table, $field ) {
1395 return PostgresField::fromText( $this, $table, $field );
1399 * pg_field_type() wrapper
1402 function fieldType( $res, $index ) {
1403 if ( $res instanceof ResultWrapper ) {
1404 $res = $res->result;
1407 return pg_field_type( $res, $index );
1414 function encodeBlob( $b ) {
1415 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
1418 function decodeBlob( $b ) {
1419 if ( $b instanceof Blob ) {
1423 return pg_unescape_bytea( $b );
1426 function strencode( $s ) { # Should not be called by us
1427 return pg_escape_string( $this->mConn, $s );
1431 * @param $s null|bool|Blob
1432 * @return int|string
1434 function addQuotes( $s ) {
1435 if ( is_null( $s ) ) {
1437 } elseif ( is_bool( $s ) ) {
1438 return intval( $s );
1439 } elseif ( $s instanceof Blob ) {
1440 return "'" . $s->fetch( $s ) . "'";
1443 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1447 * Postgres specific version of replaceVars.
1448 * Calls the parent version in Database.php
1452 * @param string $ins SQL string, read from a stream (usually tables.sql)
1454 * @return string SQL string
1456 protected function replaceVars( $ins ) {
1457 $ins = parent::replaceVars( $ins );
1459 if ( $this->numericVersion >= 8.3 ) {
1460 // Thanks for not providing backwards-compatibility, 8.3
1461 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1464 if ( $this->numericVersion <= 8.1 ) { // Our minimum version
1465 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1472 * Various select options
1476 * @param array $options an associative array of options to be turned into
1477 * an SQL query, valid keys are listed in the function.
1480 function makeSelectOptions( $options ) {
1481 $preLimitTail = $postLimitTail = '';
1482 $startOpts = $useIndex = '';
1484 $noKeyOptions = array();
1485 foreach ( $options as $key => $option ) {
1486 if ( is_numeric( $key ) ) {
1487 $noKeyOptions[$option] = true;
1491 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1493 $preLimitTail .= $this->makeOrderBy( $options );
1495 //if ( isset( $options['LIMIT'] ) ) {
1496 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1497 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1501 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1502 $postLimitTail .= ' FOR UPDATE';
1504 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1505 $startOpts .= 'DISTINCT';
1508 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1511 function setFakeMaster( $enabled = true ) {
1514 function getDBname() {
1515 return $this->mDBname;
1518 function getServer() {
1519 return $this->mServer;
1522 function buildConcat( $stringList ) {
1523 return implode( ' || ', $stringList );
1526 public function buildGroupConcatField(
1527 $delimiter, $table, $field, $conds = '', $options = array(), $join_conds = array()
1529 $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1531 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
1534 public function getSearchEngine() {
1535 return 'SearchPostgres';
1538 public function streamStatementEnd( &$sql, &$newLine ) {
1539 # Allow dollar quoting for function declarations
1540 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1541 if ( $this->delimiter ) {
1542 $this->delimiter = false;
1544 $this->delimiter = ';';
1548 return parent::streamStatementEnd( $sql, $newLine );
1552 * Check to see if a named lock is available. This is non-blocking.
1553 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1555 * @param string $lockName name of lock to poll
1556 * @param string $method name of method calling us
1560 public function lockIsFree( $lockName, $method ) {
1561 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1562 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1563 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1564 $row = $this->fetchObject( $result );
1566 return ( $row->lockstatus === 't' );
1570 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1571 * @param $lockName string
1572 * @param $method string
1573 * @param $timeout int
1576 public function lock( $lockName, $method, $timeout = 5 ) {
1577 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1578 for ( $attempts = 1; $attempts <= $timeout; ++$attempts ) {
1579 $result = $this->query(
1580 "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1581 $row = $this->fetchObject( $result );
1582 if ( $row->lockstatus === 't' ) {
1588 wfDebug( __METHOD__ . " failed to acquire lock\n" );
1594 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKSFROM
1595 * PG DOCS: http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1596 * @param $lockName string
1597 * @param $method string
1600 public function unlock( $lockName, $method ) {
1601 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1602 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1603 $row = $this->fetchObject( $result );
1605 return ( $row->lockstatus === 't' );
1609 * @param string $lockName
1610 * @return string Integer
1612 private function bigintFromLockName( $lockName ) {
1613 return wfBaseConvert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1615 } // end DatabasePostgres class