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 );
790 return $res->numRows() > 0;
794 * INSERT wrapper, inserts an array into a table
796 * $args may be a single associative array, or an array of these with numeric keys,
797 * for multi-row insert (Postgres version 8.2 and above only).
799 * @param $table String: Name of the table to insert to.
800 * @param $args Array: Items to insert into the table.
801 * @param $fname String: Name of the function, for profiling
802 * @param string $options or Array. Valid options: IGNORE
804 * @return bool Success of insert operation. IGNORE always returns true.
806 function insert( $table, $args, $fname = __METHOD__, $options = array() ) {
807 if ( !count( $args ) ) {
811 $table = $this->tableName( $table );
812 if ( !isset( $this->numericVersion ) ) {
813 $this->getServerVersion();
816 if ( !is_array( $options ) ) {
817 $options = array( $options );
820 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
822 $keys = array_keys( $args[0] );
825 $keys = array_keys( $args );
828 // If IGNORE is set, we use savepoints to emulate mysql's behavior
830 if ( in_array( 'IGNORE', $options ) ) {
831 $savepoint = new SavepointPostgres( $this, 'mw' );
832 $olde = error_reporting( 0 );
833 // For future use, we may want to track the number of actual inserts
834 // Right now, insert (all writes) simply return true/false
835 $numrowsinserted = 0;
838 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
841 if ( $this->numericVersion >= 8.2 && !$savepoint ) {
843 foreach ( $args as $row ) {
849 $sql .= '(' . $this->makeList( $row ) . ')';
851 $res = (bool)$this->query( $sql, $fname, $savepoint );
855 foreach ( $args as $row ) {
857 $tempsql .= '(' . $this->makeList( $row ) . ')';
860 $savepoint->savepoint();
863 $tempres = (bool)$this->query( $tempsql, $fname, $savepoint );
866 $bar = pg_last_error();
867 if ( $bar != false ) {
868 $savepoint->rollback();
870 $savepoint->release();
875 // If any of them fail, we fail overall for this function call
876 // Note that this will be ignored if IGNORE is set
883 // Not multi, just a lone insert
885 $savepoint->savepoint();
888 $sql .= '(' . $this->makeList( $args ) . ')';
889 $res = (bool)$this->query( $sql, $fname, $savepoint );
891 $bar = pg_last_error();
892 if ( $bar != false ) {
893 $savepoint->rollback();
895 $savepoint->release();
901 error_reporting( $olde );
902 $savepoint->commit();
904 // Set the affected row count for the whole operation
905 $this->mAffectedRows = $numrowsinserted;
907 // IGNORE always returns true
915 * INSERT SELECT wrapper
916 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
917 * Source items may be literals rather then field names, but strings should
918 * be quoted with Database::addQuotes()
919 * $conds may be "*" to copy the whole table
920 * srcTable may be an array of tables.
921 * @todo FIXME: Implement this a little better (seperate select/insert)?
924 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
925 $insertOptions = array(), $selectOptions = array() ) {
926 $destTable = $this->tableName( $destTable );
928 if ( !is_array( $insertOptions ) ) {
929 $insertOptions = array( $insertOptions );
933 * If IGNORE is set, we use savepoints to emulate mysql's behavior
934 * Ignore LOW PRIORITY option, since it is MySQL-specific
937 if ( in_array( 'IGNORE', $insertOptions ) ) {
938 $savepoint = new SavepointPostgres( $this, 'mw' );
939 $olde = error_reporting( 0 );
940 $numrowsinserted = 0;
941 $savepoint->savepoint();
944 if ( !is_array( $selectOptions ) ) {
945 $selectOptions = array( $selectOptions );
947 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
948 if ( is_array( $srcTable ) ) {
949 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
951 $srcTable = $this->tableName( $srcTable );
954 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
955 " SELECT $startOpts " . implode( ',', $varMap ) .
956 " FROM $srcTable $useIndex";
958 if ( $conds != '*' ) {
959 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
962 $sql .= " $tailOpts";
964 $res = (bool)$this->query( $sql, $fname, $savepoint );
966 $bar = pg_last_error();
967 if ( $bar != false ) {
968 $savepoint->rollback();
970 $savepoint->release();
973 error_reporting( $olde );
974 $savepoint->commit();
976 // Set the affected row count for the whole operation
977 $this->mAffectedRows = $numrowsinserted;
979 // IGNORE always returns true
986 function tableName( $name, $format = 'quoted' ) {
987 # Replace reserved words with better ones
990 return $this->realTableName( 'mwuser', $format );
992 return $this->realTableName( 'pagecontent', $format );
994 return $this->realTableName( $name, $format );
998 /* Don't cheat on installer */
999 function realTableName( $name, $format = 'quoted' ) {
1000 return parent::tableName( $name, $format );
1004 * Return the next in a sequence, save the value for retrieval via insertId()
1006 * @param string $seqName
1009 function nextSequenceValue( $seqName ) {
1010 $safeseq = str_replace( "'", "''", $seqName );
1011 $res = $this->query( "SELECT nextval('$safeseq')" );
1012 $row = $this->fetchRow( $res );
1013 $this->mInsertId = $row[0];
1015 return $this->mInsertId;
1019 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
1021 * @param string $seqName
1024 function currentSequenceValue( $seqName ) {
1025 $safeseq = str_replace( "'", "''", $seqName );
1026 $res = $this->query( "SELECT currval('$safeseq')" );
1027 $row = $this->fetchRow( $res );
1033 # Returns the size of a text field, or -1 for "unlimited"
1034 function textFieldSize( $table, $field ) {
1035 $table = $this->tableName( $table );
1036 $sql = "SELECT t.typname as ftype,a.atttypmod as size
1037 FROM pg_class c, pg_attribute a, pg_type t
1038 WHERE relname='$table' AND a.attrelid=c.oid AND
1039 a.atttypid=t.oid and a.attname='$field'";
1040 $res = $this->query( $sql );
1041 $row = $this->fetchObject( $res );
1042 if ( $row->ftype == 'varchar' ) {
1043 $size = $row->size - 4;
1051 function limitResult( $sql, $limit, $offset = false ) {
1052 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
1055 function wasDeadlock() {
1056 return $this->lastErrno() == '40P01';
1059 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
1060 $newName = $this->addIdentifierQuotes( $newName );
1061 $oldName = $this->addIdentifierQuotes( $oldName );
1063 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName " .
1064 "(LIKE $oldName INCLUDING DEFAULTS)", $fname );
1067 function listTables( $prefix = null, $fname = __METHOD__ ) {
1068 $eschema = $this->addQuotes( $this->getCoreSchema() );
1069 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
1070 $endArray = array();
1072 foreach ( $result as $table ) {
1073 $vars = get_object_vars( $table );
1074 $table = array_pop( $vars );
1075 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1076 $endArray[] = $table;
1083 function timestamp( $ts = 0 ) {
1084 return wfTimestamp( TS_POSTGRES, $ts );
1088 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
1089 * to http://www.php.net/manual/en/ref.pgsql.php
1091 * Parsing a postgres array can be a tricky problem, he's my
1092 * take on this, it handles multi-dimensional arrays plus
1093 * escaping using a nasty regexp to determine the limits of each
1096 * This should really be handled by PHP PostgreSQL module
1099 * @param $text string: postgreql array returned in a text form like {a,b}
1100 * @param $output string
1102 * @param $offset int
1105 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
1106 if ( false === $limit ) {
1107 $limit = strlen( $text ) - 1;
1110 if ( '{}' == $text ) {
1114 if ( '{' != $text[$offset] ) {
1115 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
1116 $text, $match, 0, $offset );
1117 $offset += strlen( $match[0] );
1118 $output[] = ( '"' != $match[1][0]
1120 : stripcslashes( substr( $match[1], 1, -1 ) ) );
1121 if ( '},' == $match[3] ) {
1125 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
1127 } while ( $limit > $offset );
1133 * Return aggregated value function call
1135 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1140 * @return string wikitext of a link to the server software's web site
1142 public function getSoftwareLink() {
1143 return '[http://www.postgresql.org/ PostgreSQL]';
1147 * Return current schema (executes SELECT current_schema())
1151 * @return string Default schema for the current session
1153 function getCurrentSchema() {
1154 $res = $this->query( "SELECT current_schema()", __METHOD__ );
1155 $row = $this->fetchRow( $res );
1161 * Return list of schemas which are accessible without schema name
1162 * This is list does not contain magic keywords like "$user"
1165 * @see getSearchPath()
1166 * @see setSearchPath()
1168 * @return array list of actual schemas for the current sesson
1170 function getSchemas() {
1171 $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
1172 $row = $this->fetchRow( $res );
1175 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
1177 return $this->pg_array_parse( $row[0], $schemas );
1181 * Return search patch for schemas
1182 * This is different from getSchemas() since it contain magic keywords
1187 * @return array how to search for table names schemas for the current user
1189 function getSearchPath() {
1190 $res = $this->query( "SHOW search_path", __METHOD__ );
1191 $row = $this->fetchRow( $res );
1193 /* PostgreSQL returns SHOW values as strings */
1195 return explode( ",", $row[0] );
1199 * Update search_path, values should already be sanitized
1200 * Values may contain magic keywords like "$user"
1203 * @param $search_path array list of schemas to be searched by default
1205 function setSearchPath( $search_path ) {
1206 $this->query( "SET search_path = " . implode( ", ", $search_path ) );
1210 * Determine default schema for MediaWiki core
1211 * Adjust this session schema search path if desired schema exists
1212 * and is not alread there.
1214 * We need to have name of the core schema stored to be able
1215 * to query database metadata.
1217 * This will be also called by the installer after the schema is created
1220 * @param $desired_schema string
1222 function determineCoreSchema( $desired_schema ) {
1223 $this->begin( __METHOD__ );
1224 if ( $this->schemaExists( $desired_schema ) ) {
1225 if ( in_array( $desired_schema, $this->getSchemas() ) ) {
1226 $this->mCoreSchema = $desired_schema;
1227 wfDebug( "Schema \"" . $desired_schema . "\" already in the search path\n" );
1230 * Prepend our schema (e.g. 'mediawiki') in front
1231 * of the search path
1234 $search_path = $this->getSearchPath();
1235 array_unshift( $search_path,
1236 $this->addIdentifierQuotes( $desired_schema ) );
1237 $this->setSearchPath( $search_path );
1238 $this->mCoreSchema = $desired_schema;
1239 wfDebug( "Schema \"" . $desired_schema . "\" added to the search path\n" );
1242 $this->mCoreSchema = $this->getCurrentSchema();
1243 wfDebug( "Schema \"" . $desired_schema . "\" not found, using current \"" .
1244 $this->mCoreSchema . "\"\n" );
1246 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1247 $this->commit( __METHOD__ );
1251 * Return schema name fore core MediaWiki tables
1254 * @return string core schema name
1256 function getCoreSchema() {
1257 return $this->mCoreSchema;
1261 * @return string Version information from the database
1263 function getServerVersion() {
1264 if ( !isset( $this->numericVersion ) ) {
1265 $versionInfo = pg_version( $this->mConn );
1266 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1267 // Old client, abort install
1268 $this->numericVersion = '7.3 or earlier';
1269 } elseif ( isset( $versionInfo['server'] ) ) {
1271 $this->numericVersion = $versionInfo['server'];
1273 // Bug 16937: broken pgsql extension from PHP<5.3
1274 $this->numericVersion = pg_parameter_status( $this->mConn, 'server_version' );
1278 return $this->numericVersion;
1282 * Query whether a given relation exists (in the given schema, or the
1283 * default mw one if not given)
1286 function relationExists( $table, $types, $schema = false ) {
1287 if ( !is_array( $types ) ) {
1288 $types = array( $types );
1291 $schema = $this->getCoreSchema();
1293 $table = $this->realTableName( $table, 'raw' );
1294 $etable = $this->addQuotes( $table );
1295 $eschema = $this->addQuotes( $schema );
1296 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1297 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1298 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1299 $res = $this->query( $SQL );
1300 $count = $res ? $res->numRows() : 0;
1302 return (bool)$count;
1306 * For backward compatibility, this function checks both tables and
1310 function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1311 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1314 function sequenceExists( $sequence, $schema = false ) {
1315 return $this->relationExists( $sequence, 'S', $schema );
1318 function triggerExists( $table, $trigger ) {
1320 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1321 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1322 AND tgrelid=pg_class.oid
1323 AND nspname=%s AND relname=%s AND tgname=%s
1325 $res = $this->query(
1328 $this->addQuotes( $this->getCoreSchema() ),
1329 $this->addQuotes( $table ),
1330 $this->addQuotes( $trigger )
1336 $rows = $res->numRows();
1341 function ruleExists( $table, $rule ) {
1342 $exists = $this->selectField( 'pg_rules', 'rulename',
1344 'rulename' => $rule,
1345 'tablename' => $table,
1346 'schemaname' => $this->getCoreSchema()
1350 return $exists === $rule;
1353 function constraintExists( $table, $constraint ) {
1354 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1355 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1356 $this->addQuotes( $this->getCoreSchema() ),
1357 $this->addQuotes( $table ),
1358 $this->addQuotes( $constraint )
1360 $res = $this->query( $SQL );
1364 $rows = $res->numRows();
1370 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1373 function schemaExists( $schema ) {
1374 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1375 array( 'nspname' => $schema ), __METHOD__ );
1377 return (bool)$exists;
1381 * Returns true if a given role (i.e. user) exists, false otherwise.
1384 function roleExists( $roleName ) {
1385 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1386 array( 'rolname' => $roleName ), __METHOD__ );
1388 return (bool)$exists;
1391 function fieldInfo( $table, $field ) {
1392 return PostgresField::fromText( $this, $table, $field );
1396 * pg_field_type() wrapper
1399 function fieldType( $res, $index ) {
1400 if ( $res instanceof ResultWrapper ) {
1401 $res = $res->result;
1404 return pg_field_type( $res, $index );
1411 function encodeBlob( $b ) {
1412 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
1415 function decodeBlob( $b ) {
1416 if ( $b instanceof Blob ) {
1420 return pg_unescape_bytea( $b );
1423 function strencode( $s ) { # Should not be called by us
1424 return pg_escape_string( $this->mConn, $s );
1428 * @param $s null|bool|Blob
1429 * @return int|string
1431 function addQuotes( $s ) {
1432 if ( is_null( $s ) ) {
1434 } elseif ( is_bool( $s ) ) {
1435 return intval( $s );
1436 } elseif ( $s instanceof Blob ) {
1437 return "'" . $s->fetch( $s ) . "'";
1440 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1444 * Postgres specific version of replaceVars.
1445 * Calls the parent version in Database.php
1449 * @param string $ins SQL string, read from a stream (usually tables.sql)
1451 * @return string SQL string
1453 protected function replaceVars( $ins ) {
1454 $ins = parent::replaceVars( $ins );
1456 if ( $this->numericVersion >= 8.3 ) {
1457 // Thanks for not providing backwards-compatibility, 8.3
1458 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1461 if ( $this->numericVersion <= 8.1 ) { // Our minimum version
1462 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1469 * Various select options
1473 * @param array $options an associative array of options to be turned into
1474 * an SQL query, valid keys are listed in the function.
1477 function makeSelectOptions( $options ) {
1478 $preLimitTail = $postLimitTail = '';
1479 $startOpts = $useIndex = '';
1481 $noKeyOptions = array();
1482 foreach ( $options as $key => $option ) {
1483 if ( is_numeric( $key ) ) {
1484 $noKeyOptions[$option] = true;
1488 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1490 $preLimitTail .= $this->makeOrderBy( $options );
1492 //if ( isset( $options['LIMIT'] ) ) {
1493 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1494 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1498 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1499 $postLimitTail .= ' FOR UPDATE';
1501 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1502 $startOpts .= 'DISTINCT';
1505 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1508 function setFakeMaster( $enabled = true ) {
1511 function getDBname() {
1512 return $this->mDBname;
1515 function getServer() {
1516 return $this->mServer;
1519 function buildConcat( $stringList ) {
1520 return implode( ' || ', $stringList );
1523 public function buildGroupConcatField(
1524 $delimiter, $table, $field, $conds = '', $options = array(), $join_conds = array()
1526 $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1528 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
1531 public function getSearchEngine() {
1532 return 'SearchPostgres';
1535 public function streamStatementEnd( &$sql, &$newLine ) {
1536 # Allow dollar quoting for function declarations
1537 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1538 if ( $this->delimiter ) {
1539 $this->delimiter = false;
1541 $this->delimiter = ';';
1545 return parent::streamStatementEnd( $sql, $newLine );
1549 * Check to see if a named lock is available. This is non-blocking.
1550 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1552 * @param string $lockName name of lock to poll
1553 * @param string $method name of method calling us
1557 public function lockIsFree( $lockName, $method ) {
1558 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1559 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1560 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1561 $row = $this->fetchObject( $result );
1563 return ( $row->lockstatus === 't' );
1567 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1568 * @param $lockName string
1569 * @param $method string
1570 * @param $timeout int
1573 public function lock( $lockName, $method, $timeout = 5 ) {
1574 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1575 for ( $attempts = 1; $attempts <= $timeout; ++$attempts ) {
1576 $result = $this->query(
1577 "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1578 $row = $this->fetchObject( $result );
1579 if ( $row->lockstatus === 't' ) {
1585 wfDebug( __METHOD__ . " failed to acquire lock\n" );
1591 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKSFROM
1592 * PG DOCS: http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1593 * @param $lockName string
1594 * @param $method string
1597 public function unlock( $lockName, $method ) {
1598 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1599 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1600 $row = $this->fetchObject( $result );
1602 return ( $row->lockstatus === 't' );
1606 * @param string $lockName
1607 * @return string Integer
1609 private function bigintFromLockName( $lockName ) {
1610 return wfBaseConvert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1612 } // end DatabasePostgres class