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
23 namespace Wikimedia\Rdbms
;
25 use Wikimedia\Timestamp\ConvertibleTimestamp
;
26 use Wikimedia\WaitConditionLoop
;
33 class DatabasePostgres
extends Database
{
38 protected $mLastResult = null;
39 /** @var int The number of rows affected as an integer */
40 protected $mAffectedRows = null;
42 /** @var float|string */
43 private $numericVersion = null;
44 /** @var string Connect string to open a PostgreSQL connection */
45 private $connectString;
48 /** @var string[] Map of (reserved table name => alternate table name) */
49 private $keywordTableMap = [];
52 * @see Database::__construct()
53 * @param array $params Additional parameters include:
54 * - keywordTableMap : Map of reserved table names to alternative table names to use
56 public function __construct( array $params ) {
57 $this->port
= isset( $params['port'] ) ?
$params['port'] : false;
58 $this->keywordTableMap
= isset( $params['keywordTableMap'] )
59 ?
$params['keywordTableMap']
62 parent
::__construct( $params );
65 public function getType() {
69 public function implicitGroupby() {
73 public function implicitOrderby() {
77 public function hasConstraint( $name ) {
78 $conn = $this->getBindingHandle();
80 $sql = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
81 "WHERE c.connamespace = n.oid AND conname = '" .
82 pg_escape_string( $conn, $name ) . "' AND n.nspname = '" .
83 pg_escape_string( $conn, $this->getCoreSchema() ) . "'";
84 $res = $this->doQuery( $sql );
86 return $this->numRows( $res );
89 public function open( $server, $user, $password, $dbName ) {
90 # Test for Postgres support, to avoid suppressed fatal error
91 if ( !function_exists( 'pg_connect' ) ) {
92 throw new DBConnectionError(
94 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
95 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
96 "webserver and database)\n"
100 $this->mServer
= $server;
101 $this->mUser
= $user;
102 $this->mPassword
= $password;
103 $this->mDBname
= $dbName;
106 // pg_connect() user $user as the default database. Since a database is *required*,
107 // at least pick a "don't care" database that is more likely to exist. This case
108 // arrises when LoadBalancer::getConnection( $i, [], '' ) is used.
109 'dbname' => strlen( $dbName ) ?
$dbName : 'postgres',
111 'password' => $password
113 if ( $server != false && $server != '' ) {
114 $connectVars['host'] = $server;
116 if ( (int)$this->port
> 0 ) {
117 $connectVars['port'] = (int)$this->port
;
119 if ( $this->mFlags
& self
::DBO_SSL
) {
120 $connectVars['sslmode'] = 1;
123 $this->connectString
= $this->makeConnectionString( $connectVars );
125 $this->installErrorHandler();
128 // Use new connections to let LoadBalancer/LBFactory handle reuse
129 $this->mConn
= pg_connect( $this->connectString
, PGSQL_CONNECT_FORCE_NEW
);
130 } catch ( Exception
$ex ) {
131 $this->restoreErrorHandler();
135 $phpError = $this->restoreErrorHandler();
137 if ( !$this->mConn
) {
138 $this->queryLogger
->debug(
139 "DB connection error\n" .
140 "Server: $server, Database: $dbName, User: $user, Password: " .
141 substr( $password, 0, 3 ) . "...\n"
143 $this->queryLogger
->debug( $this->lastError() . "\n" );
144 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
147 $this->mOpened
= true;
149 # If called from the command-line (e.g. importDump), only show errors
150 if ( $this->cliMode
) {
151 $this->doQuery( "SET client_min_messages = 'ERROR'" );
154 $this->query( "SET client_encoding='UTF8'", __METHOD__
);
155 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__
);
156 $this->query( "SET timezone = 'GMT'", __METHOD__
);
157 $this->query( "SET standard_conforming_strings = on", __METHOD__
);
158 if ( $this->getServerVersion() >= 9.0 ) {
159 $this->query( "SET bytea_output = 'escape'", __METHOD__
); // PHP bug 53127
162 $this->determineCoreSchema( $this->mSchema
);
163 // The schema to be used is now in the search path; no need for explicit qualification
169 public function databasesAreIndependent() {
174 * Postgres doesn't support selectDB in the same way MySQL does. So if the
175 * DB name doesn't match the open connection, open a new one
178 * @throws DBUnexpectedError
180 public function selectDB( $db ) {
181 if ( $this->mDBname
!== $db ) {
182 return (bool)$this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $db );
189 * @param string[] $vars
192 private function makeConnectionString( $vars ) {
194 foreach ( $vars as $name => $value ) {
195 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
201 protected function closeConnection() {
202 return $this->mConn ?
pg_close( $this->mConn
) : true;
205 public function doQuery( $sql ) {
206 $conn = $this->getBindingHandle();
208 $sql = mb_convert_encoding( $sql, 'UTF-8' );
209 // Clear previously left over PQresult
210 while ( $res = pg_get_result( $conn ) ) {
211 pg_free_result( $res );
213 if ( pg_send_query( $conn, $sql ) === false ) {
214 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
216 $this->mLastResult
= pg_get_result( $conn );
217 $this->mAffectedRows
= null;
218 if ( pg_result_error( $this->mLastResult
) ) {
222 return $this->mLastResult
;
225 protected function dumpError() {
229 PGSQL_DIAG_MESSAGE_PRIMARY
,
230 PGSQL_DIAG_MESSAGE_DETAIL
,
231 PGSQL_DIAG_MESSAGE_HINT
,
232 PGSQL_DIAG_STATEMENT_POSITION
,
233 PGSQL_DIAG_INTERNAL_POSITION
,
234 PGSQL_DIAG_INTERNAL_QUERY
,
236 PGSQL_DIAG_SOURCE_FILE
,
237 PGSQL_DIAG_SOURCE_LINE
,
238 PGSQL_DIAG_SOURCE_FUNCTION
240 foreach ( $diags as $d ) {
241 $this->queryLogger
->debug( sprintf( "PgSQL ERROR(%d): %s\n",
242 $d, pg_result_error_field( $this->mLastResult
, $d ) ) );
246 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
248 /* Check for constraint violation */
249 if ( $errno === '23505' ) {
250 parent
::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
255 /* Transaction stays in the ERROR state until rolled back */
256 if ( $this->mTrxLevel
) {
257 // Throw away the transaction state, then raise the error as normal.
258 // Note that if this connection is managed by LBFactory, it's already expected
259 // that the other transactions LBFactory manages will be rolled back.
260 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
262 parent
::reportQueryError( $error, $errno, $sql, $fname, false );
265 public function freeResult( $res ) {
266 if ( $res instanceof ResultWrapper
) {
269 MediaWiki\
suppressWarnings();
270 $ok = pg_free_result( $res );
271 MediaWiki\restoreWarnings
();
273 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
277 public function fetchObject( $res ) {
278 if ( $res instanceof ResultWrapper
) {
281 MediaWiki\
suppressWarnings();
282 $row = pg_fetch_object( $res );
283 MediaWiki\restoreWarnings
();
284 # @todo FIXME: HACK HACK HACK HACK debug
286 # @todo hashar: not sure if the following test really trigger if the object
288 $conn = $this->getBindingHandle();
289 if ( pg_last_error( $conn ) ) {
290 throw new DBUnexpectedError(
292 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
299 public function fetchRow( $res ) {
300 if ( $res instanceof ResultWrapper
) {
303 MediaWiki\
suppressWarnings();
304 $row = pg_fetch_array( $res );
305 MediaWiki\restoreWarnings
();
307 $conn = $this->getBindingHandle();
308 if ( pg_last_error( $conn ) ) {
309 throw new DBUnexpectedError(
311 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
318 public function numRows( $res ) {
319 if ( $res instanceof ResultWrapper
) {
322 MediaWiki\
suppressWarnings();
323 $n = pg_num_rows( $res );
324 MediaWiki\restoreWarnings
();
326 $conn = $this->getBindingHandle();
327 if ( pg_last_error( $conn ) ) {
328 throw new DBUnexpectedError(
330 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
337 public function numFields( $res ) {
338 if ( $res instanceof ResultWrapper
) {
342 return pg_num_fields( $res );
345 public function fieldName( $res, $n ) {
346 if ( $res instanceof ResultWrapper
) {
350 return pg_field_name( $res, $n );
353 public function insertId() {
354 $res = $this->query( "SELECT lastval()" );
355 $row = $this->fetchRow( $res );
356 return is_null( $row[0] ) ?
null : (int)$row[0];
359 public function dataSeek( $res, $row ) {
360 if ( $res instanceof ResultWrapper
) {
364 return pg_result_seek( $res, $row );
367 public function lastError() {
368 if ( $this->mConn
) {
369 if ( $this->mLastResult
) {
370 return pg_result_error( $this->mLastResult
);
372 return pg_last_error();
376 return $this->getLastPHPError() ?
: 'No database connection';
379 public function lastErrno() {
380 if ( $this->mLastResult
) {
381 return pg_result_error_field( $this->mLastResult
, PGSQL_DIAG_SQLSTATE
);
387 public function affectedRows() {
388 if ( !is_null( $this->mAffectedRows
) ) {
389 // Forced result for simulated queries
390 return $this->mAffectedRows
;
392 if ( empty( $this->mLastResult
) ) {
396 return pg_affected_rows( $this->mLastResult
);
400 * Estimate rows in dataset
401 * Returns estimated count, based on EXPLAIN output
402 * This is not necessarily an accurate estimate, so use sparingly
403 * Returns -1 if count cannot be found
404 * Takes same arguments as Database::select()
406 * @param string $table
407 * @param string $vars
408 * @param string $conds
409 * @param string $fname
410 * @param array $options
413 public function estimateRowCount( $table, $vars = '*', $conds = '',
414 $fname = __METHOD__
, $options = []
416 $options['EXPLAIN'] = true;
417 $res = $this->select( $table, $vars, $conds, $fname, $options );
420 $row = $this->fetchRow( $res );
422 if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
423 $rows = (int)$count[1];
430 public function indexInfo( $table, $index, $fname = __METHOD__
) {
431 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
432 $res = $this->query( $sql, $fname );
436 foreach ( $res as $row ) {
437 if ( $row->indexname
== $this->indexName( $index ) ) {
445 public function indexAttributes( $index, $schema = false ) {
446 if ( $schema === false ) {
447 $schema = $this->getCoreSchema();
450 * A subquery would be not needed if we didn't care about the order
451 * of attributes, but we do
453 $sql = <<<__INDEXATTR__
457 i.indoption[s.g] as option,
460 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
464 ON cis.oid=isub.indexrelid
466 ON cis.relnamespace = ns.oid
467 WHERE cis.relname='$index' AND ns.nspname='$schema') AS s,
473 ON ci.oid=i.indexrelid
475 ON ct.oid = i.indrelid
477 ON ci.relnamespace = n.oid
479 ci.relname='$index' AND n.nspname='$schema'
480 AND attrelid = ct.oid
481 AND i.indkey[s.g] = attnum
482 AND i.indclass[s.g] = opcls.oid
483 AND pg_am.oid = opcls.opcmethod
485 $res = $this->query( $sql, __METHOD__ );
488 foreach ( $res as $row ) {
502 public function indexUnique( $table, $index, $fname = __METHOD__ ) {
503 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
504 " AND indexdef LIKE 'CREATE UNIQUE%(" .
505 $this->strencode( $this->indexName( $index ) ) .
507 $res = $this->query( $sql, $fname );
512 return $res->numRows() > 0;
515 public function selectSQLText(
516 $table, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
518 if ( is_string( $options ) ) {
519 $options = [ $options ];
522 // Change the FOR UPDATE option as necessary based on the join conditions. Then pass
523 // to the parent function to get the actual SQL text.
524 // In Postgres when using FOR UPDATE, only the main table and tables that are inner joined
525 // can be locked. That means tables in an outer join cannot be FOR UPDATE locked. Trying to
526 // do so causes a DB error. This wrapper checks which tables can be locked and adjusts it
528 // MySQL uses "ORDER BY NULL" as an optimization hint, but that is illegal in PostgreSQL.
529 if ( is_array( $options ) ) {
530 $forUpdateKey = array_search( 'FOR UPDATE', $options, true );
531 if ( $forUpdateKey !== false && $join_conds ) {
532 unset( $options[$forUpdateKey] );
533 $options['FOR UPDATE'] = [];
535 // All tables not in $join_conds are good
536 foreach ( $table as $alias => $name ) {
537 if ( is_numeric( $alias ) ) {
540 if ( !isset( $join_conds[$alias] ) ) {
541 $options['FOR UPDATE'][] = $alias;
545 foreach ( $join_conds as $table_cond => $join_cond ) {
546 if ( 0 === preg_match( '/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_cond[0] ) ) {
547 $options['FOR UPDATE'][] = $table_cond;
551 // Quote alias names so $this->tableName() won't mangle them
552 $options['FOR UPDATE'] = array_map( function ( $name ) use ( $table ) {
553 return isset( $table[$name] ) ? $this->addIdentifierQuotes( $name ) : $name;
554 }, $options['FOR UPDATE'] );
557 if ( isset( $options['ORDER BY'] ) && $options['ORDER BY'] == 'NULL' ) {
558 unset( $options['ORDER BY'] );
562 return parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
566 * INSERT wrapper, inserts an array into a table
568 * $args may be a single associative array, or an array of these with numeric keys,
569 * for multi-row insert (Postgres version 8.2 and above only).
571 * @param string $table Name of the table to insert to.
572 * @param array $args Items to insert into the table.
573 * @param string $fname Name of the function, for profiling
574 * @param array|string $options String or array. Valid options: IGNORE
575 * @return bool Success of insert operation. IGNORE always returns true.
577 public function insert( $table, $args, $fname = __METHOD__, $options = [] ) {
578 if ( !count( $args ) ) {
582 $table = $this->tableName( $table );
583 if ( !isset( $this->numericVersion ) ) {
584 $this->getServerVersion();
587 if ( !is_array( $options ) ) {
588 $options = [ $options ];
591 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
593 $keys = array_keys( $args[0] );
596 $keys = array_keys( $args );
599 // If IGNORE is set, we use savepoints to emulate mysql's behavior
600 $savepoint = $olde = null;
601 $numrowsinserted = 0;
602 if ( in_array( 'IGNORE', $options ) ) {
603 $savepoint = new SavepointPostgres( $this, 'mw', $this->queryLogger );
604 $olde = error_reporting( 0 );
605 // For future use, we may want to track the number of actual inserts
606 // Right now, insert (all writes) simply return true/false
609 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
612 if ( $this->numericVersion >= 8.2 && !$savepoint ) {
614 foreach ( $args as $row ) {
620 $sql .= '(' . $this->makeList( $row ) . ')';
622 $res = (bool)$this->query( $sql, $fname, $savepoint );
626 foreach ( $args as $row ) {
628 $tempsql .= '(' . $this->makeList( $row ) . ')';
631 $savepoint->savepoint();
634 $tempres = (bool)$this->query( $tempsql, $fname, $savepoint );
637 $bar = pg_result_error( $this->mLastResult );
638 if ( $bar != false ) {
639 $savepoint->rollback();
641 $savepoint->release();
646 // If any of them fail, we fail overall for this function call
647 // Note that this will be ignored if IGNORE is set
654 // Not multi, just a lone insert
656 $savepoint->savepoint();
659 $sql .= '(' . $this->makeList( $args ) . ')';
660 $res = (bool)$this->query( $sql, $fname, $savepoint );
662 $bar = pg_result_error( $this->mLastResult );
663 if ( $bar != false ) {
664 $savepoint->rollback();
666 $savepoint->release();
672 error_reporting( $olde );
673 $savepoint->commit();
675 // Set the affected row count for the whole operation
676 $this->mAffectedRows = $numrowsinserted;
678 // IGNORE always returns true
686 * INSERT SELECT wrapper
687 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
688 * Source items may be literals rather then field names, but strings should
689 * be quoted with Database::addQuotes()
690 * $conds may be "*" to copy the whole table
691 * srcTable may be an array of tables.
692 * @todo FIXME: Implement this a little better (seperate select/insert)?
694 * @param string $destTable
695 * @param array|string $srcTable
696 * @param array $varMap
697 * @param array $conds
698 * @param string $fname
699 * @param array $insertOptions
700 * @param array $selectOptions
701 * @param array $selectJoinConds
704 public function nativeInsertSelect(
705 $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
706 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
708 if ( !is_array( $insertOptions ) ) {
709 $insertOptions = [ $insertOptions ];
713 * If IGNORE is set, we use savepoints to emulate mysql's behavior
714 * Ignore LOW PRIORITY option, since it is MySQL-specific
716 $savepoint = $olde = null;
717 $numrowsinserted = 0;
718 if ( in_array( 'IGNORE', $insertOptions ) ) {
719 $savepoint = new SavepointPostgres( $this, 'mw', $this->queryLogger );
720 $olde = error_reporting( 0 );
721 $savepoint->savepoint();
724 $res = parent::nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname,
725 $insertOptions, $selectOptions, $selectJoinConds );
728 $bar = pg_result_error( $this->mLastResult );
729 if ( $bar != false ) {
730 $savepoint->rollback();
732 $savepoint->release();
735 error_reporting( $olde );
736 $savepoint->commit();
738 // Set the affected row count for the whole operation
739 $this->mAffectedRows = $numrowsinserted;
741 // IGNORE always returns true
748 public function tableName( $name, $format = 'quoted' ) {
749 // Replace reserved words with better ones
750 $name = $this->remappedTableName( $name );
752 return parent::tableName( $name, $format );
756 * @param string $name
757 * @return string Value of $name or remapped name if $name is a reserved keyword
759 public function remappedTableName( $name ) {
760 return isset( $this->keywordTableMap[$name] ) ? $this->keywordTableMap[$name] : $name;
764 * @param string $name
765 * @param string $format
766 * @return string Qualified and encoded (if requested) table name
768 public function realTableName( $name, $format = 'quoted' ) {
769 return parent::tableName( $name, $format );
772 public function nextSequenceValue( $seqName ) {
773 return new NextSequenceValue;
777 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
779 * @param string $seqName
782 public function currentSequenceValue( $seqName ) {
783 $safeseq = str_replace( "'", "''", $seqName );
784 $res = $this->query( "SELECT currval('$safeseq')" );
785 $row = $this->fetchRow( $res );
791 public function textFieldSize( $table, $field ) {
792 $table = $this->tableName( $table );
793 $sql = "SELECT t.typname as ftype,a.atttypmod as size
794 FROM pg_class c, pg_attribute a, pg_type t
795 WHERE relname='$table' AND a.attrelid=c.oid AND
796 a.atttypid=t.oid and a.attname='$field'";
797 $res = $this->query( $sql );
798 $row = $this->fetchObject( $res );
799 if ( $row->ftype == 'varchar' ) {
800 $size = $row->size - 4;
808 public function limitResult( $sql, $limit, $offset = false ) {
809 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
812 public function wasDeadlock() {
813 return $this->lastErrno() == '40P01';
816 public function duplicateTableStructure(
817 $oldName, $newName, $temporary = false, $fname = __METHOD__
819 $newName = $this->addIdentifierQuotes( $newName );
820 $oldName = $this->addIdentifierQuotes( $oldName );
822 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName " .
823 "(LIKE $oldName INCLUDING DEFAULTS INCLUDING INDEXES)", $fname );
826 public function listTables( $prefix = null, $fname = __METHOD__ ) {
827 $eschema = $this->addQuotes( $this->getCoreSchema() );
828 $result = $this->query(
829 "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
832 foreach ( $result as $table ) {
833 $vars = get_object_vars( $table );
834 $table = array_pop( $vars );
835 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
836 $endArray[] = $table;
843 public function timestamp( $ts = 0 ) {
844 $ct = new ConvertibleTimestamp( $ts );
846 return $ct->getTimestamp( TS_POSTGRES );
850 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
851 * to https://secure.php.net/manual/en/ref.pgsql.php
853 * Parsing a postgres array can be a tricky problem, he's my
854 * take on this, it handles multi-dimensional arrays plus
855 * escaping using a nasty regexp to determine the limits of each
858 * This should really be handled by PHP PostgreSQL module
861 * @param string $text Postgreql array returned in a text form like {a,b}
862 * @param string[] $output
863 * @param int|bool $limit
867 private function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
868 if ( false === $limit ) {
869 $limit = strlen( $text ) - 1;
872 if ( '{}' == $text ) {
876 if ( '{' != $text[$offset] ) {
877 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
878 $text, $match, 0, $offset );
879 $offset += strlen( $match[0] );
880 $output[] = ( '"' != $match[1][0]
882 : stripcslashes( substr( $match[1], 1, -1 ) ) );
883 if ( '},' == $match[3] ) {
887 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
889 } while ( $limit > $offset );
894 public function aggregateValue( $valuedata, $valuename = 'value' ) {
898 public function getSoftwareLink() {
899 return '[{{int:version-db-postgres-url}} PostgreSQL]';
903 * Return current schema (executes SELECT current_schema())
907 * @return string Default schema for the current session
909 public function getCurrentSchema() {
910 $res = $this->query( "SELECT current_schema()", __METHOD__ );
911 $row = $this->fetchRow( $res );
917 * Return list of schemas which are accessible without schema name
918 * This is list does not contain magic keywords like "$user"
921 * @see getSearchPath()
922 * @see setSearchPath()
924 * @return array List of actual schemas for the current sesson
926 public function getSchemas() {
927 $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
928 $row = $this->fetchRow( $res );
931 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
933 return $this->pg_array_parse( $row[0], $schemas );
937 * Return search patch for schemas
938 * This is different from getSchemas() since it contain magic keywords
943 * @return array How to search for table names schemas for the current user
945 public function getSearchPath() {
946 $res = $this->query( "SHOW search_path", __METHOD__ );
947 $row = $this->fetchRow( $res );
949 /* PostgreSQL returns SHOW values as strings */
951 return explode( ",", $row[0] );
955 * Update search_path, values should already be sanitized
956 * Values may contain magic keywords like "$user"
959 * @param array $search_path List of schemas to be searched by default
961 private function setSearchPath( $search_path ) {
962 $this->query( "SET search_path = " . implode( ", ", $search_path ) );
966 * Determine default schema for the current application
967 * Adjust this session schema search path if desired schema exists
968 * and is not alread there.
970 * We need to have name of the core schema stored to be able
971 * to query database metadata.
973 * This will be also called by the installer after the schema is created
977 * @param string $desiredSchema
979 public function determineCoreSchema( $desiredSchema ) {
980 $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
981 if ( $this->schemaExists( $desiredSchema ) ) {
982 if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
983 $this->mCoreSchema = $desiredSchema;
984 $this->queryLogger->debug(
985 "Schema \"" . $desiredSchema . "\" already in the search path\n" );
988 * Prepend our schema (e.g. 'mediawiki') in front
992 $search_path = $this->getSearchPath();
993 array_unshift( $search_path,
994 $this->addIdentifierQuotes( $desiredSchema ) );
995 $this->setSearchPath( $search_path );
996 $this->mCoreSchema = $desiredSchema;
997 $this->queryLogger->debug(
998 "Schema \"" . $desiredSchema . "\" added to the search path\n" );
1001 $this->mCoreSchema = $this->getCurrentSchema();
1002 $this->queryLogger->debug(
1003 "Schema \"" . $desiredSchema . "\" not found, using current \"" .
1004 $this->mCoreSchema . "\"\n" );
1006 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1007 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
1011 * Return schema name for core application tables
1014 * @return string Core schema name
1016 public function getCoreSchema() {
1017 return $this->mCoreSchema;
1020 public function getServerVersion() {
1021 if ( !isset( $this->numericVersion ) ) {
1022 $conn = $this->getBindingHandle();
1023 $versionInfo = pg_version( $conn );
1024 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1025 // Old client, abort install
1026 $this->numericVersion = '7.3 or earlier';
1027 } elseif ( isset( $versionInfo['server'] ) ) {
1029 $this->numericVersion = $versionInfo['server'];
1031 // T18937: broken pgsql extension from PHP<5.3
1032 $this->numericVersion = pg_parameter_status( $conn, 'server_version' );
1036 return $this->numericVersion;
1040 * Query whether a given relation exists (in the given schema, or the
1041 * default mw one if not given)
1042 * @param string $table
1043 * @param array|string $types
1044 * @param bool|string $schema
1047 private function relationExists( $table, $types, $schema = false ) {
1048 if ( !is_array( $types ) ) {
1049 $types = [ $types ];
1051 if ( $schema === false ) {
1052 $schema = $this->getCoreSchema();
1054 $table = $this->realTableName( $table, 'raw' );
1055 $etable = $this->addQuotes( $table );
1056 $eschema = $this->addQuotes( $schema );
1057 $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1058 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1059 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1060 $res = $this->query( $sql );
1061 $count = $res ? $res->numRows() : 0;
1063 return (bool)$count;
1067 * For backward compatibility, this function checks both tables and views.
1068 * @param string $table
1069 * @param string $fname
1070 * @param bool|string $schema
1073 public function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1074 return $this->relationExists( $table, [ 'r', 'v' ], $schema );
1077 public function sequenceExists( $sequence, $schema = false ) {
1078 return $this->relationExists( $sequence, 'S', $schema );
1081 public function triggerExists( $table, $trigger ) {
1083 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1084 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1085 AND tgrelid=pg_class.oid
1086 AND nspname=%s AND relname=%s AND tgname=%s
1088 $res = $this->query(
1091 $this->addQuotes( $this->getCoreSchema() ),
1092 $this->addQuotes( $table ),
1093 $this->addQuotes( $trigger )
1099 $rows = $res->numRows();
1104 public function ruleExists( $table, $rule ) {
1105 $exists = $this->selectField( 'pg_rules', 'rulename',
1107 'rulename' => $rule,
1108 'tablename' => $table,
1109 'schemaname' => $this->getCoreSchema()
1113 return $exists === $rule;
1116 public function constraintExists( $table, $constraint ) {
1117 $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1118 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1119 $this->addQuotes( $this->getCoreSchema() ),
1120 $this->addQuotes( $table ),
1121 $this->addQuotes( $constraint )
1123 $res = $this->query( $sql );
1127 $rows = $res->numRows();
1133 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1134 * @param string $schema
1137 public function schemaExists( $schema ) {
1138 if ( !strlen( $schema ) ) {
1139 return false; // short-circuit
1142 $exists = $this->selectField(
1143 '"pg_catalog"."pg_namespace"', 1, [ 'nspname' => $schema ], __METHOD__ );
1145 return (bool)$exists;
1149 * Returns true if a given role (i.e. user) exists, false otherwise.
1150 * @param string $roleName
1153 public function roleExists( $roleName ) {
1154 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1155 [ 'rolname' => $roleName ], __METHOD__ );
1157 return (bool)$exists;
1161 * @param string $table
1162 * @param string $field
1163 * @return PostgresField|null
1165 public function fieldInfo( $table, $field ) {
1166 return PostgresField::fromText( $this, $table, $field );
1170 * pg_field_type() wrapper
1171 * @param ResultWrapper|resource $res ResultWrapper or PostgreSQL query result resource
1172 * @param int $index Field number, starting from 0
1175 public function fieldType( $res, $index ) {
1176 if ( $res instanceof ResultWrapper ) {
1177 $res = $res->result;
1180 return pg_field_type( $res, $index );
1183 public function encodeBlob( $b ) {
1184 return new PostgresBlob( pg_escape_bytea( $b ) );
1187 public function decodeBlob( $b ) {
1188 if ( $b instanceof PostgresBlob ) {
1190 } elseif ( $b instanceof Blob ) {
1194 return pg_unescape_bytea( $b );
1197 public function strencode( $s ) {
1198 // Should not be called by us
1199 return pg_escape_string( $this->getBindingHandle(), $s );
1202 public function addQuotes( $s ) {
1203 $conn = $this->getBindingHandle();
1205 if ( is_null( $s ) ) {
1207 } elseif ( is_bool( $s ) ) {
1208 return intval( $s );
1209 } elseif ( $s instanceof Blob ) {
1210 if ( $s instanceof PostgresBlob ) {
1213 $s = pg_escape_bytea( $conn, $s->fetch() );
1216 } elseif ( $s instanceof NextSequenceValue ) {
1220 return "'" . pg_escape_string( $conn, $s ) . "'";
1224 * Postgres specific version of replaceVars.
1225 * Calls the parent version in Database.php
1227 * @param string $ins SQL string, read from a stream (usually tables.sql)
1228 * @return string SQL string
1230 protected function replaceVars( $ins ) {
1231 $ins = parent::replaceVars( $ins );
1233 if ( $this->numericVersion >= 8.3 ) {
1234 // Thanks for not providing backwards-compatibility, 8.3
1235 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1238 if ( $this->numericVersion <= 8.1 ) { // Our minimum version
1239 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1245 public function makeSelectOptions( $options ) {
1246 $preLimitTail = $postLimitTail = '';
1247 $startOpts = $useIndex = $ignoreIndex = '';
1250 foreach ( $options as $key => $option ) {
1251 if ( is_numeric( $key ) ) {
1252 $noKeyOptions[$option] = true;
1256 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1258 $preLimitTail .= $this->makeOrderBy( $options );
1260 if ( isset( $options['FOR UPDATE'] ) ) {
1261 $postLimitTail .= ' FOR UPDATE OF ' .
1262 implode( ', ', array_map( [ $this, 'tableName' ], $options['FOR UPDATE'] ) );
1263 } elseif ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1264 $postLimitTail .= ' FOR UPDATE';
1267 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1268 $startOpts .= 'DISTINCT';
1271 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1274 public function getDBname() {
1275 return $this->mDBname;
1278 public function getServer() {
1279 return $this->mServer;
1282 public function buildConcat( $stringList ) {
1283 return implode( ' || ', $stringList );
1286 public function buildGroupConcatField(
1287 $delimiter, $table, $field, $conds = '', $options = [], $join_conds = []
1289 $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1291 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1294 public function buildStringCast( $field ) {
1295 return $field . '::text';
1298 public function streamStatementEnd( &$sql, &$newLine ) {
1299 # Allow dollar quoting for function declarations
1300 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1301 if ( $this->delimiter ) {
1302 $this->delimiter = false;
1304 $this->delimiter = ';';
1308 return parent::streamStatementEnd( $sql, $newLine );
1311 public function doLockTables( array $read, array $write, $method ) {
1313 foreach ( $write as $table ) {
1314 $tablesWrite[] = $this->tableName( $table );
1317 foreach ( $read as $table ) {
1318 $tablesRead[] = $this->tableName( $table );
1321 // Acquire locks for the duration of the current transaction...
1322 if ( $tablesWrite ) {
1324 'LOCK TABLE ONLY ' . implode( ',', $tablesWrite ) . ' IN EXCLUSIVE MODE',
1328 if ( $tablesRead ) {
1330 'LOCK TABLE ONLY ' . implode( ',', $tablesRead ) . ' IN SHARE MODE',
1338 public function lockIsFree( $lockName, $method ) {
1339 // http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1340 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1341 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1342 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1343 $row = $this->fetchObject( $result );
1345 return ( $row->lockstatus === 't' );
1348 public function lock( $lockName, $method, $timeout = 5 ) {
1349 // http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1350 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1351 $loop = new WaitConditionLoop(
1352 function () use ( $lockName, $key, $timeout, $method ) {
1353 $res = $this->query( "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1354 $row = $this->fetchObject( $res );
1355 if ( $row->lockstatus === 't' ) {
1356 parent::lock( $lockName, $method, $timeout ); // record
1360 return WaitConditionLoop::CONDITION_CONTINUE;
1365 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1368 public function unlock( $lockName, $method ) {
1369 // http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1370 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1371 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1372 $row = $this->fetchObject( $result );
1374 if ( $row->lockstatus === 't' ) {
1375 parent::unlock( $lockName, $method ); // record
1379 $this->queryLogger->debug( __METHOD__ . " failed to release lock\n" );
1384 public function serverIsReadOnly() {
1385 $res = $this->query( "SHOW default_transaction_read_only", __METHOD__ );
1386 $row = $this->fetchObject( $res );
1388 return $row ? ( strtolower( $row->default_transaction_read_only ) === 'on' ) : false;
1392 * @param string $lockName
1393 * @return string Integer
1395 private function bigintFromLockName( $lockName ) {
1396 return \Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1400 class_alias( DatabasePostgres::class, 'DatabasePostgres' );