3 * This is the Postgres database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 class PostgresField
implements Field
{
25 private $name, $tablename, $type, $nullable, $max_length, $deferred, $deferrable, $conname,
26 $has_default, $default;
29 * @param DatabaseBase $db
30 * @param string $table
31 * @param string $field
32 * @return null|PostgresField
34 static function fromText( $db, $table, $field ) {
37 attnotnull, attlen, conname AS conname,
40 COALESCE(condeferred, 'f') AS deferred,
41 COALESCE(condeferrable, 'f') AS deferrable,
42 CASE WHEN typname = 'int2' THEN 'smallint'
43 WHEN typname = 'int4' THEN 'integer'
44 WHEN typname = 'int8' THEN 'bigint'
45 WHEN typname = 'bpchar' THEN 'char'
46 ELSE typname END AS typname
48 JOIN pg_namespace n ON (n.oid = c.relnamespace)
49 JOIN pg_attribute a ON (a.attrelid = c.oid)
50 JOIN pg_type t ON (t.oid = a.atttypid)
51 LEFT JOIN pg_constraint o ON (o.conrelid = c.oid AND a.attnum = ANY(o.conkey) AND o.contype = 'f')
52 LEFT JOIN pg_attrdef d on c.oid=d.adrelid and a.attnum=d.adnum
59 $table = $db->tableName( $table, 'raw' );
62 $db->addQuotes( $db->getCoreSchema() ),
63 $db->addQuotes( $table ),
64 $db->addQuotes( $field )
67 $row = $db->fetchObject( $res );
71 $n = new PostgresField
;
72 $n->type
= $row->typname
;
73 $n->nullable
= ( $row->attnotnull
== 'f' );
75 $n->tablename
= $table;
76 $n->max_length
= $row->attlen
;
77 $n->deferrable
= ( $row->deferrable
== 't' );
78 $n->deferred
= ( $row->deferred
== 't' );
79 $n->conname
= $row->conname
;
80 $n->has_default
= ( $row->atthasdef
=== 't' );
81 $n->default = $row->adsrc
;
90 function tableName() {
91 return $this->tablename
;
98 function isNullable() {
99 return $this->nullable
;
102 function maxLength() {
103 return $this->max_length
;
106 function is_deferrable() {
107 return $this->deferrable
;
110 function is_deferred() {
111 return $this->deferred
;
115 return $this->conname
;
122 function defaultValue() {
123 if ( $this->has_default
) {
124 return $this->default;
132 * Manage savepoints within a transaction
136 class SavepointPostgres
{
137 /** @var DatabasePostgres Establish a savepoint within a transaction */
143 * @param DatabaseBase $dbw
146 public function __construct( $dbw, $id ) {
149 $this->didbegin
= false;
150 /* If we are not in a transaction, we need to be for savepoint trickery */
151 if ( !$dbw->trxLevel() ) {
152 $dbw->begin( "FOR SAVEPOINT" );
153 $this->didbegin
= true;
157 public function __destruct() {
158 if ( $this->didbegin
) {
159 $this->dbw
->rollback();
160 $this->didbegin
= false;
164 public function commit() {
165 if ( $this->didbegin
) {
166 $this->dbw
->commit();
167 $this->didbegin
= false;
171 protected function query( $keyword, $msg_ok, $msg_failed ) {
172 if ( $this->dbw
->doQuery( $keyword . " " . $this->id
) !== false ) {
174 wfDebug( sprintf( $msg_failed, $this->id
) );
178 public function savepoint() {
179 $this->query( "SAVEPOINT",
180 "Transaction state: savepoint \"%s\" established.\n",
181 "Transaction state: establishment of savepoint \"%s\" FAILED.\n"
185 public function release() {
186 $this->query( "RELEASE",
187 "Transaction state: savepoint \"%s\" released.\n",
188 "Transaction state: release of savepoint \"%s\" FAILED.\n"
192 public function rollback() {
193 $this->query( "ROLLBACK TO",
194 "Transaction state: savepoint \"%s\" rolled back.\n",
195 "Transaction state: rollback of savepoint \"%s\" FAILED.\n"
199 public function __toString() {
200 return (string)$this->id
;
207 class DatabasePostgres
extends Database
{
209 protected $mLastResult = null;
211 /** @var int The number of rows affected as an integer */
212 protected $mAffectedRows = null;
215 private $mInsertId = null;
217 /** @var float|string */
218 private $numericVersion = null;
220 /** @var string Connect string to open a PostgreSQL connection */
221 private $connectString;
224 private $mCoreSchema;
230 function cascadingDeletes() {
234 function cleanupTriggers() {
238 function strictIPs() {
242 function realTimestamps() {
246 function implicitGroupby() {
250 function implicitOrderby() {
254 function searchableIPs() {
258 function functionalIndexes() {
262 function hasConstraint( $name ) {
263 $sql = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
264 "WHERE c.connamespace = n.oid AND conname = '" .
265 pg_escape_string( $this->mConn
, $name ) . "' AND n.nspname = '" .
266 pg_escape_string( $this->mConn
, $this->getCoreSchema() ) . "'";
267 $res = $this->doQuery( $sql );
269 return $this->numRows( $res );
273 * Usually aborts on failure
274 * @param string $server
275 * @param string $user
276 * @param string $password
277 * @param string $dbName
278 * @throws DBConnectionError|Exception
279 * @return DatabaseBase|null
281 function open( $server, $user, $password, $dbName ) {
282 # Test for Postgres support, to avoid suppressed fatal error
283 if ( !function_exists( 'pg_connect' ) ) {
284 throw new DBConnectionError(
286 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
287 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
288 "webserver and database)\n"
294 if ( !strlen( $user ) ) { # e.g. the class is being loaded
298 $this->mServer
= $server;
300 $this->mUser
= $user;
301 $this->mPassword
= $password;
302 $this->mDBname
= $dbName;
304 $connectVars = array(
307 'password' => $password
309 if ( $server != false && $server != '' ) {
310 $connectVars['host'] = $server;
312 if ( $port != false && $port != '' ) {
313 $connectVars['port'] = $port;
315 if ( $this->mFlags
& DBO_SSL
) {
316 $connectVars['sslmode'] = 1;
319 $this->connectString
= $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
321 $this->installErrorHandler();
324 $this->mConn
= pg_connect( $this->connectString
);
325 } catch ( Exception
$ex ) {
326 $this->restoreErrorHandler();
330 $phpError = $this->restoreErrorHandler();
332 if ( !$this->mConn
) {
333 wfDebug( "DB connection error\n" );
334 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " .
335 substr( $password, 0, 3 ) . "...\n" );
336 wfDebug( $this->lastError() . "\n" );
337 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
340 $this->mOpened
= true;
342 global $wgCommandLineMode;
343 # If called from the command-line (e.g. importDump), only show errors
344 if ( $wgCommandLineMode ) {
345 $this->doQuery( "SET client_min_messages = 'ERROR'" );
348 $this->query( "SET client_encoding='UTF8'", __METHOD__
);
349 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__
);
350 $this->query( "SET timezone = 'GMT'", __METHOD__
);
351 $this->query( "SET standard_conforming_strings = on", __METHOD__
);
352 if ( $this->getServerVersion() >= 9.0 ) {
353 $this->query( "SET bytea_output = 'escape'", __METHOD__
); // PHP bug 53127
356 global $wgDBmwschema;
357 $this->determineCoreSchema( $wgDBmwschema );
363 * Postgres doesn't support selectDB in the same way MySQL does. So if the
364 * DB name doesn't match the open connection, open a new one
368 function selectDB( $db ) {
369 if ( $this->mDBname
!== $db ) {
370 return (bool)$this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $db );
376 function makeConnectionString( $vars ) {
378 foreach ( $vars as $name => $value ) {
379 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
386 * Closes a database connection, if it is open
387 * Returns success, true if already closed
390 protected function closeConnection() {
391 return pg_close( $this->mConn
);
394 public function doQuery( $sql ) {
395 if ( function_exists( 'mb_convert_encoding' ) ) {
396 $sql = mb_convert_encoding( $sql, 'UTF-8' );
398 // Clear previously left over PQresult
399 while ( $res = pg_get_result( $this->mConn
) )
400 pg_free_result( $res );
401 if ( pg_send_query( $this->mConn
, $sql ) === false ) {
402 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
404 $this->mLastResult
= pg_get_result( $this->mConn
);
405 $this->mAffectedRows
= null;
406 if ( pg_result_error( $this->mLastResult
) ) {
410 return $this->mLastResult
;
413 protected function dumpError() {
417 PGSQL_DIAG_MESSAGE_PRIMARY
,
418 PGSQL_DIAG_MESSAGE_DETAIL
,
419 PGSQL_DIAG_MESSAGE_HINT
,
420 PGSQL_DIAG_STATEMENT_POSITION
,
421 PGSQL_DIAG_INTERNAL_POSITION
,
422 PGSQL_DIAG_INTERNAL_QUERY
,
424 PGSQL_DIAG_SOURCE_FILE
,
425 PGSQL_DIAG_SOURCE_LINE
,
426 PGSQL_DIAG_SOURCE_FUNCTION
428 foreach ( $diags as $d ) {
429 wfDebug( sprintf( "PgSQL ERROR(%d): %s\n",
430 $d, pg_result_error_field( $this->mLastResult
, $d ) ) );
434 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
436 /* Check for constraint violation */
437 if ( $errno === '23505' ) {
438 parent
::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
443 /* Transaction stays in the ERROR state until rolled back */
444 if ( $this->mTrxLevel
) {
445 $ignore = $this->ignoreErrors( true );
446 $this->rollback( __METHOD__
);
447 $this->ignoreErrors( $ignore );
449 parent
::reportQueryError( $error, $errno, $sql, $fname, false );
452 function queryIgnore( $sql, $fname = __METHOD__
) {
453 return $this->query( $sql, $fname, true );
457 * @param stdClass|ResultWrapper $res
458 * @throws DBUnexpectedError
460 function freeResult( $res ) {
461 if ( $res instanceof ResultWrapper
) {
464 MediaWiki\
suppressWarnings();
465 $ok = pg_free_result( $res );
466 MediaWiki\restoreWarnings
();
468 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
473 * @param ResultWrapper|stdClass $res
475 * @throws DBUnexpectedError
477 function fetchObject( $res ) {
478 if ( $res instanceof ResultWrapper
) {
481 MediaWiki\
suppressWarnings();
482 $row = pg_fetch_object( $res );
483 MediaWiki\restoreWarnings
();
484 # @todo FIXME: HACK HACK HACK HACK debug
486 # @todo hashar: not sure if the following test really trigger if the object
488 if ( pg_last_error( $this->mConn
) ) {
489 throw new DBUnexpectedError(
491 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) )
498 function fetchRow( $res ) {
499 if ( $res instanceof ResultWrapper
) {
502 MediaWiki\
suppressWarnings();
503 $row = pg_fetch_array( $res );
504 MediaWiki\restoreWarnings
();
505 if ( pg_last_error( $this->mConn
) ) {
506 throw new DBUnexpectedError(
508 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) )
515 function numRows( $res ) {
516 if ( $res instanceof ResultWrapper
) {
519 MediaWiki\
suppressWarnings();
520 $n = pg_num_rows( $res );
521 MediaWiki\restoreWarnings
();
522 if ( pg_last_error( $this->mConn
) ) {
523 throw new DBUnexpectedError(
525 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) )
532 function numFields( $res ) {
533 if ( $res instanceof ResultWrapper
) {
537 return pg_num_fields( $res );
540 function fieldName( $res, $n ) {
541 if ( $res instanceof ResultWrapper
) {
545 return pg_field_name( $res, $n );
549 * Return the result of the last call to nextSequenceValue();
550 * This must be called after nextSequenceValue().
554 function insertId() {
555 return $this->mInsertId
;
563 function dataSeek( $res, $row ) {
564 if ( $res instanceof ResultWrapper
) {
568 return pg_result_seek( $res, $row );
571 function lastError() {
572 if ( $this->mConn
) {
573 if ( $this->mLastResult
) {
574 return pg_result_error( $this->mLastResult
);
576 return pg_last_error();
579 return 'No database connection';
583 function lastErrno() {
584 if ( $this->mLastResult
) {
585 return pg_result_error_field( $this->mLastResult
, PGSQL_DIAG_SQLSTATE
);
591 function affectedRows() {
592 if ( !is_null( $this->mAffectedRows
) ) {
593 // Forced result for simulated queries
594 return $this->mAffectedRows
;
596 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()
610 * @param string $table
611 * @param string $vars
612 * @param string $conds
613 * @param string $fname
614 * @param array $options
617 function estimateRowCount( $table, $vars = '*', $conds = '',
618 $fname = __METHOD__
, $options = array()
620 $options['EXPLAIN'] = true;
621 $res = $this->select( $table, $vars, $conds, $fname, $options );
624 $row = $this->fetchRow( $res );
626 if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
627 $rows = (int)$count[1];
635 * Returns information about an index
636 * If errors are explicitly ignored, returns NULL on failure
638 * @param string $table
639 * @param string $index
640 * @param string $fname
643 function indexInfo( $table, $index, $fname = __METHOD__
) {
644 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
645 $res = $this->query( $sql, $fname );
649 foreach ( $res as $row ) {
650 if ( $row->indexname
== $this->indexName( $index ) ) {
659 * Returns is of attributes used in index
662 * @param string $index
663 * @param bool|string $schema
666 function indexAttributes( $index, $schema = false ) {
667 if ( $schema === false ) {
668 $schema = $this->getCoreSchema();
671 * A subquery would be not needed if we didn't care about the order
672 * of attributes, but we do
674 $sql = <<<__INDEXATTR__
678 i.indoption[s.g] as option,
681 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
685 ON cis.oid=isub.indexrelid
687 ON cis.relnamespace = ns.oid
688 WHERE cis.relname='$index' AND ns.nspname='$schema') AS s,
694 ON ci.oid=i.indexrelid
696 ON ct.oid = i.indrelid
698 ON ci.relnamespace = n.oid
700 ci.relname='$index' AND n.nspname='$schema'
701 AND attrelid = ct.oid
702 AND i.indkey[s.g] = attnum
703 AND i.indclass[s.g] = opcls.oid
704 AND pg_am.oid = opcls.opcmethod
706 $res = $this->query( $sql, __METHOD__ );
709 foreach ( $res as $row ) {
723 function indexUnique( $table, $index, $fname = __METHOD__ ) {
724 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
725 " AND indexdef LIKE 'CREATE UNIQUE%(" .
726 $this->strencode( $this->indexName( $index ) ) .
728 $res = $this->query( $sql, $fname );
733 return $res->numRows() > 0;
737 * Change the FOR UPDATE option as necessary based on the join conditions. Then pass
738 * to the parent function to get the actual SQL text.
740 * In Postgres when using FOR UPDATE, only the main table and tables that are inner joined
741 * can be locked. That means tables in an outer join cannot be FOR UPDATE locked. Trying to do
742 * so causes a DB error. This wrapper checks which tables can be locked and adjusts it accordingly.
744 * MySQL uses "ORDER BY NULL" as an optimization hint, but that syntax is illegal in PostgreSQL.
745 * @see DatabaseBase::selectSQLText
747 function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
748 $options = array(), $join_conds = array()
750 if ( is_array( $options ) ) {
751 $forUpdateKey = array_search( 'FOR UPDATE', $options, true );
752 if ( $forUpdateKey !== false && $join_conds ) {
753 unset( $options[$forUpdateKey] );
755 foreach ( $join_conds as $table_cond => $join_cond ) {
756 if ( 0 === preg_match( '/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_cond[0] ) ) {
757 $options['FOR UPDATE'][] = $table_cond;
762 if ( isset( $options['ORDER BY'] ) && $options['ORDER BY'] == 'NULL' ) {
763 unset( $options['ORDER BY'] );
767 return parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
771 * INSERT wrapper, inserts an array into a table
773 * $args may be a single associative array, or an array of these with numeric keys,
774 * for multi-row insert (Postgres version 8.2 and above only).
776 * @param string $table Name of the table to insert to.
777 * @param array $args Items to insert into the table.
778 * @param string $fname Name of the function, for profiling
779 * @param array|string $options String or array. Valid options: IGNORE
780 * @return bool Success of insert operation. IGNORE always returns true.
782 function insert( $table, $args, $fname = __METHOD__, $options = array() ) {
783 if ( !count( $args ) ) {
787 $table = $this->tableName( $table );
788 if ( !isset( $this->numericVersion ) ) {
789 $this->getServerVersion();
792 if ( !is_array( $options ) ) {
793 $options = array( $options );
796 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
798 $keys = array_keys( $args[0] );
801 $keys = array_keys( $args );
804 // If IGNORE is set, we use savepoints to emulate mysql's behavior
806 if ( in_array( 'IGNORE', $options ) ) {
807 $savepoint = new SavepointPostgres( $this, 'mw' );
808 $olde = error_reporting( 0 );
809 // For future use, we may want to track the number of actual inserts
810 // Right now, insert (all writes) simply return true/false
811 $numrowsinserted = 0;
814 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
817 if ( $this->numericVersion >= 8.2 && !$savepoint ) {
819 foreach ( $args as $row ) {
825 $sql .= '(' . $this->makeList( $row ) . ')';
827 $res = (bool)$this->query( $sql, $fname, $savepoint );
831 foreach ( $args as $row ) {
833 $tempsql .= '(' . $this->makeList( $row ) . ')';
836 $savepoint->savepoint();
839 $tempres = (bool)$this->query( $tempsql, $fname, $savepoint );
842 $bar = pg_last_error();
843 if ( $bar != false ) {
844 $savepoint->rollback();
846 $savepoint->release();
851 // If any of them fail, we fail overall for this function call
852 // Note that this will be ignored if IGNORE is set
859 // Not multi, just a lone insert
861 $savepoint->savepoint();
864 $sql .= '(' . $this->makeList( $args ) . ')';
865 $res = (bool)$this->query( $sql, $fname, $savepoint );
867 $bar = pg_last_error();
868 if ( $bar != false ) {
869 $savepoint->rollback();
871 $savepoint->release();
877 error_reporting( $olde );
878 $savepoint->commit();
880 // Set the affected row count for the whole operation
881 $this->mAffectedRows = $numrowsinserted;
883 // IGNORE always returns true
891 * INSERT SELECT wrapper
892 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
893 * Source items may be literals rather then field names, but strings should
894 * be quoted with Database::addQuotes()
895 * $conds may be "*" to copy the whole table
896 * srcTable may be an array of tables.
897 * @todo FIXME: Implement this a little better (seperate select/insert)?
899 * @param string $destTable
900 * @param array|string $srcTable
901 * @param array $varMap
902 * @param array $conds
903 * @param string $fname
904 * @param array $insertOptions
905 * @param array $selectOptions
908 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
909 $insertOptions = array(), $selectOptions = array() ) {
910 $destTable = $this->tableName( $destTable );
912 if ( !is_array( $insertOptions ) ) {
913 $insertOptions = array( $insertOptions );
917 * If IGNORE is set, we use savepoints to emulate mysql's behavior
918 * Ignore LOW PRIORITY option, since it is MySQL-specific
921 if ( in_array( 'IGNORE', $insertOptions ) ) {
922 $savepoint = new SavepointPostgres( $this, 'mw' );
923 $olde = error_reporting( 0 );
924 $numrowsinserted = 0;
925 $savepoint->savepoint();
928 if ( !is_array( $selectOptions ) ) {
929 $selectOptions = array( $selectOptions );
931 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
932 if ( is_array( $srcTable ) ) {
933 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
935 $srcTable = $this->tableName( $srcTable );
938 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
939 " SELECT $startOpts " . implode( ',', $varMap ) .
940 " FROM $srcTable $useIndex";
942 if ( $conds != '*' ) {
943 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
946 $sql .= " $tailOpts";
948 $res = (bool)$this->query( $sql, $fname, $savepoint );
950 $bar = pg_last_error();
951 if ( $bar != false ) {
952 $savepoint->rollback();
954 $savepoint->release();
957 error_reporting( $olde );
958 $savepoint->commit();
960 // Set the affected row count for the whole operation
961 $this->mAffectedRows = $numrowsinserted;
963 // IGNORE always returns true
970 function tableName( $name, $format = 'quoted' ) {
971 # Replace reserved words with better ones
974 return $this->realTableName( 'mwuser', $format );
976 return $this->realTableName( 'pagecontent', $format );
978 return $this->realTableName( $name, $format );
982 /* Don't cheat on installer */
983 function realTableName( $name, $format = 'quoted' ) {
984 return parent::tableName( $name, $format );
988 * Return the next in a sequence, save the value for retrieval via insertId()
990 * @param string $seqName
993 function nextSequenceValue( $seqName ) {
994 $safeseq = str_replace( "'", "''", $seqName );
995 $res = $this->query( "SELECT nextval('$safeseq')" );
996 $row = $this->fetchRow( $res );
997 $this->mInsertId = $row[0];
999 return $this->mInsertId;
1003 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
1005 * @param string $seqName
1008 function currentSequenceValue( $seqName ) {
1009 $safeseq = str_replace( "'", "''", $seqName );
1010 $res = $this->query( "SELECT currval('$safeseq')" );
1011 $row = $this->fetchRow( $res );
1017 # Returns the size of a text field, or -1 for "unlimited"
1018 function textFieldSize( $table, $field ) {
1019 $table = $this->tableName( $table );
1020 $sql = "SELECT t.typname as ftype,a.atttypmod as size
1021 FROM pg_class c, pg_attribute a, pg_type t
1022 WHERE relname='$table' AND a.attrelid=c.oid AND
1023 a.atttypid=t.oid and a.attname='$field'";
1024 $res = $this->query( $sql );
1025 $row = $this->fetchObject( $res );
1026 if ( $row->ftype == 'varchar' ) {
1027 $size = $row->size - 4;
1035 function limitResult( $sql, $limit, $offset = false ) {
1036 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
1039 function wasDeadlock() {
1040 return $this->lastErrno() == '40P01';
1043 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
1044 $newName = $this->addIdentifierQuotes( $newName );
1045 $oldName = $this->addIdentifierQuotes( $oldName );
1047 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName " .
1048 "(LIKE $oldName INCLUDING DEFAULTS)", $fname );
1051 function listTables( $prefix = null, $fname = __METHOD__ ) {
1052 $eschema = $this->addQuotes( $this->getCoreSchema() );
1053 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
1054 $endArray = array();
1056 foreach ( $result as $table ) {
1057 $vars = get_object_vars( $table );
1058 $table = array_pop( $vars );
1059 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1060 $endArray[] = $table;
1067 function timestamp( $ts = 0 ) {
1068 return wfTimestamp( TS_POSTGRES, $ts );
1072 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
1073 * to http://www.php.net/manual/en/ref.pgsql.php
1075 * Parsing a postgres array can be a tricky problem, he's my
1076 * take on this, it handles multi-dimensional arrays plus
1077 * escaping using a nasty regexp to determine the limits of each
1080 * This should really be handled by PHP PostgreSQL module
1083 * @param string $text Postgreql array returned in a text form like {a,b}
1084 * @param string $output
1086 * @param int $offset
1089 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
1090 if ( false === $limit ) {
1091 $limit = strlen( $text ) - 1;
1094 if ( '{}' == $text ) {
1098 if ( '{' != $text[$offset] ) {
1099 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
1100 $text, $match, 0, $offset );
1101 $offset += strlen( $match[0] );
1102 $output[] = ( '"' != $match[1][0]
1104 : stripcslashes( substr( $match[1], 1, -1 ) ) );
1105 if ( '},' == $match[3] ) {
1109 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
1111 } while ( $limit > $offset );
1117 * Return aggregated value function call
1118 * @param array $valuedata
1119 * @param string $valuename
1122 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1127 * @return string Wikitext of a link to the server software's web site
1129 public function getSoftwareLink() {
1130 return '[{{int:version-db-postgres-url}} PostgreSQL]';
1134 * Return current schema (executes SELECT current_schema())
1138 * @return string Default schema for the current session
1140 function getCurrentSchema() {
1141 $res = $this->query( "SELECT current_schema()", __METHOD__ );
1142 $row = $this->fetchRow( $res );
1148 * Return list of schemas which are accessible without schema name
1149 * This is list does not contain magic keywords like "$user"
1152 * @see getSearchPath()
1153 * @see setSearchPath()
1155 * @return array List of actual schemas for the current sesson
1157 function getSchemas() {
1158 $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
1159 $row = $this->fetchRow( $res );
1162 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
1164 return $this->pg_array_parse( $row[0], $schemas );
1168 * Return search patch for schemas
1169 * This is different from getSchemas() since it contain magic keywords
1174 * @return array How to search for table names schemas for the current user
1176 function getSearchPath() {
1177 $res = $this->query( "SHOW search_path", __METHOD__ );
1178 $row = $this->fetchRow( $res );
1180 /* PostgreSQL returns SHOW values as strings */
1182 return explode( ",", $row[0] );
1186 * Update search_path, values should already be sanitized
1187 * Values may contain magic keywords like "$user"
1190 * @param array $search_path List of schemas to be searched by default
1192 function setSearchPath( $search_path ) {
1193 $this->query( "SET search_path = " . implode( ", ", $search_path ) );
1197 * Determine default schema for MediaWiki core
1198 * Adjust this session schema search path if desired schema exists
1199 * and is not alread there.
1201 * We need to have name of the core schema stored to be able
1202 * to query database metadata.
1204 * This will be also called by the installer after the schema is created
1208 * @param string $desiredSchema
1210 function determineCoreSchema( $desiredSchema ) {
1211 $this->begin( __METHOD__ );
1212 if ( $this->schemaExists( $desiredSchema ) ) {
1213 if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
1214 $this->mCoreSchema = $desiredSchema;
1215 wfDebug( "Schema \"" . $desiredSchema . "\" already in the search path\n" );
1218 * Prepend our schema (e.g. 'mediawiki') in front
1219 * of the search path
1222 $search_path = $this->getSearchPath();
1223 array_unshift( $search_path,
1224 $this->addIdentifierQuotes( $desiredSchema ) );
1225 $this->setSearchPath( $search_path );
1226 $this->mCoreSchema = $desiredSchema;
1227 wfDebug( "Schema \"" . $desiredSchema . "\" added to the search path\n" );
1230 $this->mCoreSchema = $this->getCurrentSchema();
1231 wfDebug( "Schema \"" . $desiredSchema . "\" not found, using current \"" .
1232 $this->mCoreSchema . "\"\n" );
1234 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1235 $this->commit( __METHOD__ );
1239 * Return schema name fore core MediaWiki tables
1242 * @return string Core schema name
1244 function getCoreSchema() {
1245 return $this->mCoreSchema;
1249 * @return string Version information from the database
1251 function getServerVersion() {
1252 if ( !isset( $this->numericVersion ) ) {
1253 $versionInfo = pg_version( $this->mConn );
1254 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1255 // Old client, abort install
1256 $this->numericVersion = '7.3 or earlier';
1257 } elseif ( isset( $versionInfo['server'] ) ) {
1259 $this->numericVersion = $versionInfo['server'];
1261 // Bug 16937: broken pgsql extension from PHP<5.3
1262 $this->numericVersion = pg_parameter_status( $this->mConn, 'server_version' );
1266 return $this->numericVersion;
1270 * Query whether a given relation exists (in the given schema, or the
1271 * default mw one if not given)
1272 * @param string $table
1273 * @param array|string $types
1274 * @param bool|string $schema
1277 function relationExists( $table, $types, $schema = false ) {
1278 if ( !is_array( $types ) ) {
1279 $types = array( $types );
1282 $schema = $this->getCoreSchema();
1284 $table = $this->realTableName( $table, 'raw' );
1285 $etable = $this->addQuotes( $table );
1286 $eschema = $this->addQuotes( $schema );
1287 $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1288 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1289 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1290 $res = $this->query( $sql );
1291 $count = $res ? $res->numRows() : 0;
1293 return (bool)$count;
1297 * For backward compatibility, this function checks both tables and
1299 * @param string $table
1300 * @param string $fname
1301 * @param bool|string $schema
1304 function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1305 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1308 function sequenceExists( $sequence, $schema = false ) {
1309 return $this->relationExists( $sequence, 'S', $schema );
1312 function triggerExists( $table, $trigger ) {
1314 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1315 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1316 AND tgrelid=pg_class.oid
1317 AND nspname=%s AND relname=%s AND tgname=%s
1319 $res = $this->query(
1322 $this->addQuotes( $this->getCoreSchema() ),
1323 $this->addQuotes( $table ),
1324 $this->addQuotes( $trigger )
1330 $rows = $res->numRows();
1335 function ruleExists( $table, $rule ) {
1336 $exists = $this->selectField( 'pg_rules', 'rulename',
1338 'rulename' => $rule,
1339 'tablename' => $table,
1340 'schemaname' => $this->getCoreSchema()
1344 return $exists === $rule;
1347 function constraintExists( $table, $constraint ) {
1348 $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1349 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1350 $this->addQuotes( $this->getCoreSchema() ),
1351 $this->addQuotes( $table ),
1352 $this->addQuotes( $constraint )
1354 $res = $this->query( $sql );
1358 $rows = $res->numRows();
1364 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1365 * @param string $schema
1368 function schemaExists( $schema ) {
1369 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1370 array( 'nspname' => $schema ), __METHOD__ );
1372 return (bool)$exists;
1376 * Returns true if a given role (i.e. user) exists, false otherwise.
1377 * @param string $roleName
1380 function roleExists( $roleName ) {
1381 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1382 array( 'rolname' => $roleName ), __METHOD__ );
1384 return (bool)$exists;
1387 function fieldInfo( $table, $field ) {
1388 return PostgresField::fromText( $this, $table, $field );
1392 * pg_field_type() wrapper
1393 * @param ResultWrapper|resource $res ResultWrapper or PostgreSQL query result resource
1394 * @param int $index Field number, starting from 0
1397 function fieldType( $res, $index ) {
1398 if ( $res instanceof ResultWrapper ) {
1399 $res = $res->result;
1402 return pg_field_type( $res, $index );
1409 function encodeBlob( $b ) {
1410 return new PostgresBlob( pg_escape_bytea( $b ) );
1413 function decodeBlob( $b ) {
1414 if ( $b instanceof PostgresBlob ) {
1416 } elseif ( $b instanceof Blob ) {
1420 return pg_unescape_bytea( $b );
1423 function strencode( $s ) {
1424 // Should not be called by us
1426 return pg_escape_string( $this->mConn, $s );
1430 * @param null|bool|Blob $s
1431 * @return int|string
1433 function addQuotes( $s ) {
1434 if ( is_null( $s ) ) {
1436 } elseif ( is_bool( $s ) ) {
1437 return intval( $s );
1438 } elseif ( $s instanceof Blob ) {
1439 if ( $s instanceof PostgresBlob ) {
1442 $s = pg_escape_bytea( $this->mConn, $s->fetch() );
1447 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1451 * Postgres specific version of replaceVars.
1452 * Calls the parent version in Database.php
1454 * @param string $ins SQL string, read from a stream (usually tables.sql)
1455 * @return string SQL string
1457 protected function replaceVars( $ins ) {
1458 $ins = parent::replaceVars( $ins );
1460 if ( $this->numericVersion >= 8.3 ) {
1461 // Thanks for not providing backwards-compatibility, 8.3
1462 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1465 if ( $this->numericVersion <= 8.1 ) { // Our minimum version
1466 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1473 * Various select options
1475 * @param array $options An associative array of options to be turned into
1476 * an SQL query, valid keys are listed in the function.
1479 function makeSelectOptions( $options ) {
1480 $preLimitTail = $postLimitTail = '';
1481 $startOpts = $useIndex = '';
1483 $noKeyOptions = array();
1484 foreach ( $options as $key => $option ) {
1485 if ( is_numeric( $key ) ) {
1486 $noKeyOptions[$option] = true;
1490 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1492 $preLimitTail .= $this->makeOrderBy( $options );
1494 // if ( isset( $options['LIMIT'] ) ) {
1495 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1496 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1500 if ( isset( $options['FOR UPDATE'] ) ) {
1501 $postLimitTail .= ' FOR UPDATE OF ' .
1502 implode( ', ', array_map( array( &$this, 'tableName' ), $options['FOR UPDATE'] ) );
1503 } elseif ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1504 $postLimitTail .= ' FOR UPDATE';
1507 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1508 $startOpts .= 'DISTINCT';
1511 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
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 string $lockName
1572 * @param string $method
1573 * @param int $timeout
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 string $lockName
1597 * @param string $method
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
1617 class PostgresBlob extends Blob {