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;
43 private $mInsertId = null;
44 /** @var float|string */
45 private $numericVersion = null;
46 /** @var string Connect string to open a PostgreSQL connection */
47 private $connectString;
50 /** @var string[] Map of (reserved table name => alternate table name) */
51 private $keywordTableMap = [];
54 * @see Database::__construct()
55 * @param array $params Additional parameters include:
56 * - keywordTableMap : Map of reserved table names to alternative table names to use
58 public function __construct( array $params ) {
59 $this->port
= isset( $params['port'] ) ?
$params['port'] : false;
60 $this->keywordTableMap
= isset( $params['keywordTableMap'] )
61 ?
$params['keywordTableMap']
64 parent
::__construct( $params );
67 public function getType() {
71 public function implicitGroupby() {
75 public function implicitOrderby() {
79 public function hasConstraint( $name ) {
80 $conn = $this->getBindingHandle();
82 $sql = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
83 "WHERE c.connamespace = n.oid AND conname = '" .
84 pg_escape_string( $conn, $name ) . "' AND n.nspname = '" .
85 pg_escape_string( $conn, $this->getCoreSchema() ) . "'";
86 $res = $this->doQuery( $sql );
88 return $this->numRows( $res );
91 public function open( $server, $user, $password, $dbName ) {
92 # Test for Postgres support, to avoid suppressed fatal error
93 if ( !function_exists( 'pg_connect' ) ) {
94 throw new DBConnectionError(
96 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
97 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
98 "webserver and database)\n"
102 $this->mServer
= $server;
103 $this->mUser
= $user;
104 $this->mPassword
= $password;
105 $this->mDBname
= $dbName;
108 // pg_connect() user $user as the default database. Since a database is *required*,
109 // at least pick a "don't care" database that is more likely to exist. This case
110 // arrises when LoadBalancer::getConnection( $i, [], '' ) is used.
111 'dbname' => strlen( $dbName ) ?
$dbName : 'postgres',
113 'password' => $password
115 if ( $server != false && $server != '' ) {
116 $connectVars['host'] = $server;
118 if ( (int)$this->port
> 0 ) {
119 $connectVars['port'] = (int)$this->port
;
121 if ( $this->mFlags
& self
::DBO_SSL
) {
122 $connectVars['sslmode'] = 1;
125 $this->connectString
= $this->makeConnectionString( $connectVars );
127 $this->installErrorHandler();
130 // Use new connections to let LoadBalancer/LBFactory handle reuse
131 $this->mConn
= pg_connect( $this->connectString
, PGSQL_CONNECT_FORCE_NEW
);
132 } catch ( Exception
$ex ) {
133 $this->restoreErrorHandler();
137 $phpError = $this->restoreErrorHandler();
139 if ( !$this->mConn
) {
140 $this->queryLogger
->debug(
141 "DB connection error\n" .
142 "Server: $server, Database: $dbName, User: $user, Password: " .
143 substr( $password, 0, 3 ) . "...\n"
145 $this->queryLogger
->debug( $this->lastError() . "\n" );
146 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
149 $this->mOpened
= true;
151 # If called from the command-line (e.g. importDump), only show errors
152 if ( $this->cliMode
) {
153 $this->doQuery( "SET client_min_messages = 'ERROR'" );
156 $this->query( "SET client_encoding='UTF8'", __METHOD__
);
157 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__
);
158 $this->query( "SET timezone = 'GMT'", __METHOD__
);
159 $this->query( "SET standard_conforming_strings = on", __METHOD__
);
160 if ( $this->getServerVersion() >= 9.0 ) {
161 $this->query( "SET bytea_output = 'escape'", __METHOD__
); // PHP bug 53127
164 $this->determineCoreSchema( $this->mSchema
);
165 // The schema to be used is now in the search path; no need for explicit qualification
171 public function databasesAreIndependent() {
176 * Postgres doesn't support selectDB in the same way MySQL does. So if the
177 * DB name doesn't match the open connection, open a new one
180 * @throws DBUnexpectedError
182 public function selectDB( $db ) {
183 if ( $this->mDBname
!== $db ) {
184 return (bool)$this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $db );
191 * @param string[] $vars
194 private function makeConnectionString( $vars ) {
196 foreach ( $vars as $name => $value ) {
197 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
203 protected function closeConnection() {
204 return $this->mConn ?
pg_close( $this->mConn
) : true;
207 public function doQuery( $sql ) {
208 $conn = $this->getBindingHandle();
210 $sql = mb_convert_encoding( $sql, 'UTF-8' );
211 // Clear previously left over PQresult
212 while ( $res = pg_get_result( $conn ) ) {
213 pg_free_result( $res );
215 if ( pg_send_query( $conn, $sql ) === false ) {
216 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
218 $this->mLastResult
= pg_get_result( $conn );
219 $this->mAffectedRows
= null;
220 if ( pg_result_error( $this->mLastResult
) ) {
224 return $this->mLastResult
;
227 protected function dumpError() {
231 PGSQL_DIAG_MESSAGE_PRIMARY
,
232 PGSQL_DIAG_MESSAGE_DETAIL
,
233 PGSQL_DIAG_MESSAGE_HINT
,
234 PGSQL_DIAG_STATEMENT_POSITION
,
235 PGSQL_DIAG_INTERNAL_POSITION
,
236 PGSQL_DIAG_INTERNAL_QUERY
,
238 PGSQL_DIAG_SOURCE_FILE
,
239 PGSQL_DIAG_SOURCE_LINE
,
240 PGSQL_DIAG_SOURCE_FUNCTION
242 foreach ( $diags as $d ) {
243 $this->queryLogger
->debug( sprintf( "PgSQL ERROR(%d): %s\n",
244 $d, pg_result_error_field( $this->mLastResult
, $d ) ) );
248 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
250 /* Check for constraint violation */
251 if ( $errno === '23505' ) {
252 parent
::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
257 /* Transaction stays in the ERROR state until rolled back */
258 if ( $this->mTrxLevel
) {
259 $this->rollback( __METHOD__
);
261 parent
::reportQueryError( $error, $errno, $sql, $fname, false );
264 public function freeResult( $res ) {
265 if ( $res instanceof ResultWrapper
) {
268 MediaWiki\
suppressWarnings();
269 $ok = pg_free_result( $res );
270 MediaWiki\restoreWarnings
();
272 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
276 public function fetchObject( $res ) {
277 if ( $res instanceof ResultWrapper
) {
280 MediaWiki\
suppressWarnings();
281 $row = pg_fetch_object( $res );
282 MediaWiki\restoreWarnings
();
283 # @todo FIXME: HACK HACK HACK HACK debug
285 # @todo hashar: not sure if the following test really trigger if the object
287 $conn = $this->getBindingHandle();
288 if ( pg_last_error( $conn ) ) {
289 throw new DBUnexpectedError(
291 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
298 public function fetchRow( $res ) {
299 if ( $res instanceof ResultWrapper
) {
302 MediaWiki\
suppressWarnings();
303 $row = pg_fetch_array( $res );
304 MediaWiki\restoreWarnings
();
306 $conn = $this->getBindingHandle();
307 if ( pg_last_error( $conn ) ) {
308 throw new DBUnexpectedError(
310 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
317 public function numRows( $res ) {
318 if ( $res instanceof ResultWrapper
) {
321 MediaWiki\
suppressWarnings();
322 $n = pg_num_rows( $res );
323 MediaWiki\restoreWarnings
();
325 $conn = $this->getBindingHandle();
326 if ( pg_last_error( $conn ) ) {
327 throw new DBUnexpectedError(
329 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
336 public function numFields( $res ) {
337 if ( $res instanceof ResultWrapper
) {
341 return pg_num_fields( $res );
344 public function fieldName( $res, $n ) {
345 if ( $res instanceof ResultWrapper
) {
349 return pg_field_name( $res, $n );
353 * Return the result of the last call to nextSequenceValue();
354 * This must be called after nextSequenceValue().
358 public function insertId() {
359 return $this->mInsertId
;
362 public function dataSeek( $res, $row ) {
363 if ( $res instanceof ResultWrapper
) {
367 return pg_result_seek( $res, $row );
370 public function lastError() {
371 if ( $this->mConn
) {
372 if ( $this->mLastResult
) {
373 return pg_result_error( $this->mLastResult
);
375 return pg_last_error();
379 return $this->getLastPHPError() ?
: 'No database connection';
382 public function lastErrno() {
383 if ( $this->mLastResult
) {
384 return pg_result_error_field( $this->mLastResult
, PGSQL_DIAG_SQLSTATE
);
390 public function affectedRows() {
391 if ( !is_null( $this->mAffectedRows
) ) {
392 // Forced result for simulated queries
393 return $this->mAffectedRows
;
395 if ( empty( $this->mLastResult
) ) {
399 return pg_affected_rows( $this->mLastResult
);
403 * Estimate rows in dataset
404 * Returns estimated count, based on EXPLAIN output
405 * This is not necessarily an accurate estimate, so use sparingly
406 * Returns -1 if count cannot be found
407 * Takes same arguments as Database::select()
409 * @param string $table
410 * @param string $vars
411 * @param string $conds
412 * @param string $fname
413 * @param array $options
416 public function estimateRowCount( $table, $vars = '*', $conds = '',
417 $fname = __METHOD__
, $options = []
419 $options['EXPLAIN'] = true;
420 $res = $this->select( $table, $vars, $conds, $fname, $options );
423 $row = $this->fetchRow( $res );
425 if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
426 $rows = (int)$count[1];
433 public function indexInfo( $table, $index, $fname = __METHOD__
) {
434 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
435 $res = $this->query( $sql, $fname );
439 foreach ( $res as $row ) {
440 if ( $row->indexname
== $this->indexName( $index ) ) {
448 public function indexAttributes( $index, $schema = false ) {
449 if ( $schema === false ) {
450 $schema = $this->getCoreSchema();
453 * A subquery would be not needed if we didn't care about the order
454 * of attributes, but we do
456 $sql = <<<__INDEXATTR__
460 i.indoption[s.g] as option,
463 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
467 ON cis.oid=isub.indexrelid
469 ON cis.relnamespace = ns.oid
470 WHERE cis.relname='$index' AND ns.nspname='$schema') AS s,
476 ON ci.oid=i.indexrelid
478 ON ct.oid = i.indrelid
480 ON ci.relnamespace = n.oid
482 ci.relname='$index' AND n.nspname='$schema'
483 AND attrelid = ct.oid
484 AND i.indkey[s.g] = attnum
485 AND i.indclass[s.g] = opcls.oid
486 AND pg_am.oid = opcls.opcmethod
488 $res = $this->query( $sql, __METHOD__ );
491 foreach ( $res as $row ) {
505 public function indexUnique( $table, $index, $fname = __METHOD__ ) {
506 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
507 " AND indexdef LIKE 'CREATE UNIQUE%(" .
508 $this->strencode( $this->indexName( $index ) ) .
510 $res = $this->query( $sql, $fname );
515 return $res->numRows() > 0;
518 public function selectSQLText(
519 $table, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
521 // Change the FOR UPDATE option as necessary based on the join conditions. Then pass
522 // to the parent function to get the actual SQL text.
523 // In Postgres when using FOR UPDATE, only the main table and tables that are inner joined
524 // can be locked. That means tables in an outer join cannot be FOR UPDATE locked. Trying to
525 // do so causes a DB error. This wrapper checks which tables can be locked and adjusts it
527 // MySQL uses "ORDER BY NULL" as an optimization hint, but that is illegal in PostgreSQL.
528 if ( is_array( $options ) ) {
529 $forUpdateKey = array_search( 'FOR UPDATE', $options, true );
530 if ( $forUpdateKey !== false && $join_conds ) {
531 unset( $options[$forUpdateKey] );
533 foreach ( $join_conds as $table_cond => $join_cond ) {
534 if ( 0 === preg_match( '/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_cond[0] ) ) {
535 $options['FOR UPDATE'][] = $table_cond;
540 if ( isset( $options['ORDER BY'] ) && $options['ORDER BY'] == 'NULL' ) {
541 unset( $options['ORDER BY'] );
545 return parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
549 * INSERT wrapper, inserts an array into a table
551 * $args may be a single associative array, or an array of these with numeric keys,
552 * for multi-row insert (Postgres version 8.2 and above only).
554 * @param string $table Name of the table to insert to.
555 * @param array $args Items to insert into the table.
556 * @param string $fname Name of the function, for profiling
557 * @param array|string $options String or array. Valid options: IGNORE
558 * @return bool Success of insert operation. IGNORE always returns true.
560 public function insert( $table, $args, $fname = __METHOD__, $options = [] ) {
561 if ( !count( $args ) ) {
565 $table = $this->tableName( $table );
566 if ( !isset( $this->numericVersion ) ) {
567 $this->getServerVersion();
570 if ( !is_array( $options ) ) {
571 $options = [ $options ];
574 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
576 $keys = array_keys( $args[0] );
579 $keys = array_keys( $args );
582 // If IGNORE is set, we use savepoints to emulate mysql's behavior
583 $savepoint = $olde = null;
584 $numrowsinserted = 0;
585 if ( in_array( 'IGNORE', $options ) ) {
586 $savepoint = new SavepointPostgres( $this, 'mw', $this->queryLogger );
587 $olde = error_reporting( 0 );
588 // For future use, we may want to track the number of actual inserts
589 // Right now, insert (all writes) simply return true/false
592 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
595 if ( $this->numericVersion >= 8.2 && !$savepoint ) {
597 foreach ( $args as $row ) {
603 $sql .= '(' . $this->makeList( $row ) . ')';
605 $res = (bool)$this->query( $sql, $fname, $savepoint );
609 foreach ( $args as $row ) {
611 $tempsql .= '(' . $this->makeList( $row ) . ')';
614 $savepoint->savepoint();
617 $tempres = (bool)$this->query( $tempsql, $fname, $savepoint );
620 $bar = pg_result_error( $this->mLastResult );
621 if ( $bar != false ) {
622 $savepoint->rollback();
624 $savepoint->release();
629 // If any of them fail, we fail overall for this function call
630 // Note that this will be ignored if IGNORE is set
637 // Not multi, just a lone insert
639 $savepoint->savepoint();
642 $sql .= '(' . $this->makeList( $args ) . ')';
643 $res = (bool)$this->query( $sql, $fname, $savepoint );
645 $bar = pg_result_error( $this->mLastResult );
646 if ( $bar != false ) {
647 $savepoint->rollback();
649 $savepoint->release();
655 error_reporting( $olde );
656 $savepoint->commit();
658 // Set the affected row count for the whole operation
659 $this->mAffectedRows = $numrowsinserted;
661 // IGNORE always returns true
669 * INSERT SELECT wrapper
670 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
671 * Source items may be literals rather then field names, but strings should
672 * be quoted with Database::addQuotes()
673 * $conds may be "*" to copy the whole table
674 * srcTable may be an array of tables.
675 * @todo FIXME: Implement this a little better (seperate select/insert)?
677 * @param string $destTable
678 * @param array|string $srcTable
679 * @param array $varMap
680 * @param array $conds
681 * @param string $fname
682 * @param array $insertOptions
683 * @param array $selectOptions
684 * @param array $selectJoinConds
687 public function nativeInsertSelect(
688 $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
689 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
691 if ( !is_array( $insertOptions ) ) {
692 $insertOptions = [ $insertOptions ];
696 * If IGNORE is set, we use savepoints to emulate mysql's behavior
697 * Ignore LOW PRIORITY option, since it is MySQL-specific
699 $savepoint = $olde = null;
700 $numrowsinserted = 0;
701 if ( in_array( 'IGNORE', $insertOptions ) ) {
702 $savepoint = new SavepointPostgres( $this, 'mw', $this->queryLogger );
703 $olde = error_reporting( 0 );
704 $savepoint->savepoint();
707 $res = parent::nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname,
708 $insertOptions, $selectOptions, $selectJoinConds );
711 $bar = pg_result_error( $this->mLastResult );
712 if ( $bar != false ) {
713 $savepoint->rollback();
715 $savepoint->release();
718 error_reporting( $olde );
719 $savepoint->commit();
721 // Set the affected row count for the whole operation
722 $this->mAffectedRows = $numrowsinserted;
724 // IGNORE always returns true
731 public function tableName( $name, $format = 'quoted' ) {
732 // Replace reserved words with better ones
733 $name = $this->remappedTableName( $name );
735 return parent::tableName( $name, $format );
739 * @param string $name
740 * @return string Value of $name or remapped name if $name is a reserved keyword
742 public function remappedTableName( $name ) {
743 return isset( $this->keywordTableMap[$name] ) ? $this->keywordTableMap[$name] : $name;
747 * @param string $name
748 * @param string $format
749 * @return string Qualified and encoded (if requested) table name
751 public function realTableName( $name, $format = 'quoted' ) {
752 return parent::tableName( $name, $format );
755 public function nextSequenceValue( $seqName ) {
756 $safeseq = str_replace( "'", "''", $seqName );
757 $res = $this->query( "SELECT nextval('$safeseq')" );
758 $row = $this->fetchRow( $res );
759 $this->mInsertId = is_null( $row[0] ) ? null : (int)$row[0];
761 return $this->mInsertId;
765 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
767 * @param string $seqName
770 public function currentSequenceValue( $seqName ) {
771 $safeseq = str_replace( "'", "''", $seqName );
772 $res = $this->query( "SELECT currval('$safeseq')" );
773 $row = $this->fetchRow( $res );
779 public function textFieldSize( $table, $field ) {
780 $table = $this->tableName( $table );
781 $sql = "SELECT t.typname as ftype,a.atttypmod as size
782 FROM pg_class c, pg_attribute a, pg_type t
783 WHERE relname='$table' AND a.attrelid=c.oid AND
784 a.atttypid=t.oid and a.attname='$field'";
785 $res = $this->query( $sql );
786 $row = $this->fetchObject( $res );
787 if ( $row->ftype == 'varchar' ) {
788 $size = $row->size - 4;
796 public function limitResult( $sql, $limit, $offset = false ) {
797 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
800 public function wasDeadlock() {
801 return $this->lastErrno() == '40P01';
804 public function duplicateTableStructure(
805 $oldName, $newName, $temporary = false, $fname = __METHOD__
807 $newName = $this->addIdentifierQuotes( $newName );
808 $oldName = $this->addIdentifierQuotes( $oldName );
810 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName " .
811 "(LIKE $oldName INCLUDING DEFAULTS INCLUDING INDEXES)", $fname );
814 public function listTables( $prefix = null, $fname = __METHOD__ ) {
815 $eschema = $this->addQuotes( $this->getCoreSchema() );
816 $result = $this->query(
817 "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
820 foreach ( $result as $table ) {
821 $vars = get_object_vars( $table );
822 $table = array_pop( $vars );
823 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
824 $endArray[] = $table;
831 public function timestamp( $ts = 0 ) {
832 $ct = new ConvertibleTimestamp( $ts );
834 return $ct->getTimestamp( TS_POSTGRES );
838 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
839 * to https://secure.php.net/manual/en/ref.pgsql.php
841 * Parsing a postgres array can be a tricky problem, he's my
842 * take on this, it handles multi-dimensional arrays plus
843 * escaping using a nasty regexp to determine the limits of each
846 * This should really be handled by PHP PostgreSQL module
849 * @param string $text Postgreql array returned in a text form like {a,b}
850 * @param string[] $output
851 * @param int|bool $limit
855 private function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
856 if ( false === $limit ) {
857 $limit = strlen( $text ) - 1;
860 if ( '{}' == $text ) {
864 if ( '{' != $text[$offset] ) {
865 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
866 $text, $match, 0, $offset );
867 $offset += strlen( $match[0] );
868 $output[] = ( '"' != $match[1][0]
870 : stripcslashes( substr( $match[1], 1, -1 ) ) );
871 if ( '},' == $match[3] ) {
875 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
877 } while ( $limit > $offset );
882 public function aggregateValue( $valuedata, $valuename = 'value' ) {
886 public function getSoftwareLink() {
887 return '[{{int:version-db-postgres-url}} PostgreSQL]';
891 * Return current schema (executes SELECT current_schema())
895 * @return string Default schema for the current session
897 public function getCurrentSchema() {
898 $res = $this->query( "SELECT current_schema()", __METHOD__ );
899 $row = $this->fetchRow( $res );
905 * Return list of schemas which are accessible without schema name
906 * This is list does not contain magic keywords like "$user"
909 * @see getSearchPath()
910 * @see setSearchPath()
912 * @return array List of actual schemas for the current sesson
914 public function getSchemas() {
915 $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
916 $row = $this->fetchRow( $res );
919 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
921 return $this->pg_array_parse( $row[0], $schemas );
925 * Return search patch for schemas
926 * This is different from getSchemas() since it contain magic keywords
931 * @return array How to search for table names schemas for the current user
933 public function getSearchPath() {
934 $res = $this->query( "SHOW search_path", __METHOD__ );
935 $row = $this->fetchRow( $res );
937 /* PostgreSQL returns SHOW values as strings */
939 return explode( ",", $row[0] );
943 * Update search_path, values should already be sanitized
944 * Values may contain magic keywords like "$user"
947 * @param array $search_path List of schemas to be searched by default
949 private function setSearchPath( $search_path ) {
950 $this->query( "SET search_path = " . implode( ", ", $search_path ) );
954 * Determine default schema for the current application
955 * Adjust this session schema search path if desired schema exists
956 * and is not alread there.
958 * We need to have name of the core schema stored to be able
959 * to query database metadata.
961 * This will be also called by the installer after the schema is created
965 * @param string $desiredSchema
967 public function determineCoreSchema( $desiredSchema ) {
968 $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
969 if ( $this->schemaExists( $desiredSchema ) ) {
970 if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
971 $this->mCoreSchema = $desiredSchema;
972 $this->queryLogger->debug(
973 "Schema \"" . $desiredSchema . "\" already in the search path\n" );
976 * Prepend our schema (e.g. 'mediawiki') in front
980 $search_path = $this->getSearchPath();
981 array_unshift( $search_path,
982 $this->addIdentifierQuotes( $desiredSchema ) );
983 $this->setSearchPath( $search_path );
984 $this->mCoreSchema = $desiredSchema;
985 $this->queryLogger->debug(
986 "Schema \"" . $desiredSchema . "\" added to the search path\n" );
989 $this->mCoreSchema = $this->getCurrentSchema();
990 $this->queryLogger->debug(
991 "Schema \"" . $desiredSchema . "\" not found, using current \"" .
992 $this->mCoreSchema . "\"\n" );
994 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
995 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
999 * Return schema name for core application tables
1002 * @return string Core schema name
1004 public function getCoreSchema() {
1005 return $this->mCoreSchema;
1008 public function getServerVersion() {
1009 if ( !isset( $this->numericVersion ) ) {
1010 $conn = $this->getBindingHandle();
1011 $versionInfo = pg_version( $conn );
1012 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1013 // Old client, abort install
1014 $this->numericVersion = '7.3 or earlier';
1015 } elseif ( isset( $versionInfo['server'] ) ) {
1017 $this->numericVersion = $versionInfo['server'];
1019 // T18937: broken pgsql extension from PHP<5.3
1020 $this->numericVersion = pg_parameter_status( $conn, 'server_version' );
1024 return $this->numericVersion;
1028 * Query whether a given relation exists (in the given schema, or the
1029 * default mw one if not given)
1030 * @param string $table
1031 * @param array|string $types
1032 * @param bool|string $schema
1035 private function relationExists( $table, $types, $schema = false ) {
1036 if ( !is_array( $types ) ) {
1037 $types = [ $types ];
1039 if ( $schema === false ) {
1040 $schema = $this->getCoreSchema();
1042 $etable = $this->addQuotes( $table );
1043 $eschema = $this->addQuotes( $schema );
1044 $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1045 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1046 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1047 $res = $this->query( $sql );
1048 $count = $res ? $res->numRows() : 0;
1050 return (bool)$count;
1054 * For backward compatibility, this function checks both tables and views.
1055 * @param string $table
1056 * @param string $fname
1057 * @param bool|string $schema
1060 public function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1061 return $this->relationExists( $table, [ 'r', 'v' ], $schema );
1064 public function sequenceExists( $sequence, $schema = false ) {
1065 return $this->relationExists( $sequence, 'S', $schema );
1068 public function triggerExists( $table, $trigger ) {
1070 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1071 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1072 AND tgrelid=pg_class.oid
1073 AND nspname=%s AND relname=%s AND tgname=%s
1075 $res = $this->query(
1078 $this->addQuotes( $this->getCoreSchema() ),
1079 $this->addQuotes( $table ),
1080 $this->addQuotes( $trigger )
1086 $rows = $res->numRows();
1091 public function ruleExists( $table, $rule ) {
1092 $exists = $this->selectField( 'pg_rules', 'rulename',
1094 'rulename' => $rule,
1095 'tablename' => $table,
1096 'schemaname' => $this->getCoreSchema()
1100 return $exists === $rule;
1103 public function constraintExists( $table, $constraint ) {
1104 $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1105 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1106 $this->addQuotes( $this->getCoreSchema() ),
1107 $this->addQuotes( $table ),
1108 $this->addQuotes( $constraint )
1110 $res = $this->query( $sql );
1114 $rows = $res->numRows();
1120 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1121 * @param string $schema
1124 public function schemaExists( $schema ) {
1125 if ( !strlen( $schema ) ) {
1126 return false; // short-circuit
1129 $exists = $this->selectField(
1130 '"pg_catalog"."pg_namespace"', 1, [ 'nspname' => $schema ], __METHOD__ );
1132 return (bool)$exists;
1136 * Returns true if a given role (i.e. user) exists, false otherwise.
1137 * @param string $roleName
1140 public function roleExists( $roleName ) {
1141 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1142 [ 'rolname' => $roleName ], __METHOD__ );
1144 return (bool)$exists;
1148 * @var string $table
1149 * @var string $field
1150 * @return PostgresField|null
1152 public function fieldInfo( $table, $field ) {
1153 return PostgresField::fromText( $this, $table, $field );
1157 * pg_field_type() wrapper
1158 * @param ResultWrapper|resource $res ResultWrapper or PostgreSQL query result resource
1159 * @param int $index Field number, starting from 0
1162 public function fieldType( $res, $index ) {
1163 if ( $res instanceof ResultWrapper ) {
1164 $res = $res->result;
1167 return pg_field_type( $res, $index );
1170 public function encodeBlob( $b ) {
1171 return new PostgresBlob( pg_escape_bytea( $b ) );
1174 public function decodeBlob( $b ) {
1175 if ( $b instanceof PostgresBlob ) {
1177 } elseif ( $b instanceof Blob ) {
1181 return pg_unescape_bytea( $b );
1184 public function strencode( $s ) {
1185 // Should not be called by us
1186 return pg_escape_string( $this->getBindingHandle(), $s );
1189 public function addQuotes( $s ) {
1190 $conn = $this->getBindingHandle();
1192 if ( is_null( $s ) ) {
1194 } elseif ( is_bool( $s ) ) {
1195 return intval( $s );
1196 } elseif ( $s instanceof Blob ) {
1197 if ( $s instanceof PostgresBlob ) {
1200 $s = pg_escape_bytea( $conn, $s->fetch() );
1205 return "'" . pg_escape_string( $conn, $s ) . "'";
1209 * Postgres specific version of replaceVars.
1210 * Calls the parent version in Database.php
1212 * @param string $ins SQL string, read from a stream (usually tables.sql)
1213 * @return string SQL string
1215 protected function replaceVars( $ins ) {
1216 $ins = parent::replaceVars( $ins );
1218 if ( $this->numericVersion >= 8.3 ) {
1219 // Thanks for not providing backwards-compatibility, 8.3
1220 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1223 if ( $this->numericVersion <= 8.1 ) { // Our minimum version
1224 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1230 public function makeSelectOptions( $options ) {
1231 $preLimitTail = $postLimitTail = '';
1232 $startOpts = $useIndex = $ignoreIndex = '';
1235 foreach ( $options as $key => $option ) {
1236 if ( is_numeric( $key ) ) {
1237 $noKeyOptions[$option] = true;
1241 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1243 $preLimitTail .= $this->makeOrderBy( $options );
1245 if ( isset( $options['FOR UPDATE'] ) ) {
1246 $postLimitTail .= ' FOR UPDATE OF ' .
1247 implode( ', ', array_map( [ $this, 'tableName' ], $options['FOR UPDATE'] ) );
1248 } elseif ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1249 $postLimitTail .= ' FOR UPDATE';
1252 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1253 $startOpts .= 'DISTINCT';
1256 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1259 public function getDBname() {
1260 return $this->mDBname;
1263 public function getServer() {
1264 return $this->mServer;
1267 public function buildConcat( $stringList ) {
1268 return implode( ' || ', $stringList );
1271 public function buildGroupConcatField(
1272 $delimiter, $table, $field, $conds = '', $options = [], $join_conds = []
1274 $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1276 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1279 public function buildStringCast( $field ) {
1280 return $field . '::text';
1283 public function streamStatementEnd( &$sql, &$newLine ) {
1284 # Allow dollar quoting for function declarations
1285 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1286 if ( $this->delimiter ) {
1287 $this->delimiter = false;
1289 $this->delimiter = ';';
1293 return parent::streamStatementEnd( $sql, $newLine );
1296 public function doLockTables( array $read, array $write, $method ) {
1298 foreach ( $write as $table ) {
1299 $tablesWrite[] = $this->tableName( $table );
1302 foreach ( $read as $table ) {
1303 $tablesRead[] = $this->tableName( $table );
1306 // Acquire locks for the duration of the current transaction...
1307 if ( $tablesWrite ) {
1309 'LOCK TABLE ONLY ' . implode( ',', $tablesWrite ) . ' IN EXCLUSIVE MODE',
1313 if ( $tablesRead ) {
1315 'LOCK TABLE ONLY ' . implode( ',', $tablesRead ) . ' IN SHARE MODE',
1323 public function lockIsFree( $lockName, $method ) {
1324 // http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1325 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1326 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1327 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1328 $row = $this->fetchObject( $result );
1330 return ( $row->lockstatus === 't' );
1333 public function lock( $lockName, $method, $timeout = 5 ) {
1334 // http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1335 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1336 $loop = new WaitConditionLoop(
1337 function () use ( $lockName, $key, $timeout, $method ) {
1338 $res = $this->query( "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1339 $row = $this->fetchObject( $res );
1340 if ( $row->lockstatus === 't' ) {
1341 parent::lock( $lockName, $method, $timeout ); // record
1345 return WaitConditionLoop::CONDITION_CONTINUE;
1350 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1353 public function unlock( $lockName, $method ) {
1354 // http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1355 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1356 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1357 $row = $this->fetchObject( $result );
1359 if ( $row->lockstatus === 't' ) {
1360 parent::unlock( $lockName, $method ); // record
1364 $this->queryLogger->debug( __METHOD__ . " failed to release lock\n" );
1370 * @param string $lockName
1371 * @return string Integer
1373 private function bigintFromLockName( $lockName ) {
1374 return \Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1378 class_alias( DatabasePostgres::class, 'DatabasePostgres' );