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 $lastResultHandle = null;
39 /** @var int The number of rows affected as an integer */
40 protected $lastAffectedRowCount = 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->server
= $server;
102 $this->password
= $password;
103 $this->dbName
= $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->flags
& 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->conn
= pg_connect( $this->connectString
, PGSQL_CONNECT_FORCE_NEW
);
130 } catch ( Exception
$ex ) {
131 $this->restoreErrorHandler();
135 $phpError = $this->restoreErrorHandler();
137 if ( !$this->conn
) {
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->opened
= 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->schema
);
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->dbName
!== $db ) {
182 return (bool)$this->open( $this->server
, $this->user
, $this->password
, $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->conn ?
pg_close( $this->conn
) : true;
205 protected function isTransactableQuery( $sql ) {
206 return parent
::isTransactableQuery( $sql ) &&
207 !preg_match( '/^SELECT\s+pg_(try_|)advisory_\w+\(/', $sql );
210 public function doQuery( $sql ) {
211 $conn = $this->getBindingHandle();
213 $sql = mb_convert_encoding( $sql, 'UTF-8' );
214 // Clear previously left over PQresult
215 while ( $res = pg_get_result( $conn ) ) {
216 pg_free_result( $res );
218 if ( pg_send_query( $conn, $sql ) === false ) {
219 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
221 $this->lastResultHandle
= pg_get_result( $conn );
222 $this->lastAffectedRowCount
= null;
223 if ( pg_result_error( $this->lastResultHandle
) ) {
227 return $this->lastResultHandle
;
230 protected function dumpError() {
234 PGSQL_DIAG_MESSAGE_PRIMARY
,
235 PGSQL_DIAG_MESSAGE_DETAIL
,
236 PGSQL_DIAG_MESSAGE_HINT
,
237 PGSQL_DIAG_STATEMENT_POSITION
,
238 PGSQL_DIAG_INTERNAL_POSITION
,
239 PGSQL_DIAG_INTERNAL_QUERY
,
241 PGSQL_DIAG_SOURCE_FILE
,
242 PGSQL_DIAG_SOURCE_LINE
,
243 PGSQL_DIAG_SOURCE_FUNCTION
245 foreach ( $diags as $d ) {
246 $this->queryLogger
->debug( sprintf( "PgSQL ERROR(%d): %s\n",
247 $d, pg_result_error_field( $this->lastResultHandle
, $d ) ) );
251 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
253 /* Check for constraint violation */
254 if ( $errno === '23505' ) {
255 parent
::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
260 /* Transaction stays in the ERROR state until rolled back */
261 if ( $this->trxLevel
) {
262 // Throw away the transaction state, then raise the error as normal.
263 // Note that if this connection is managed by LBFactory, it's already expected
264 // that the other transactions LBFactory manages will be rolled back.
265 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
267 parent
::reportQueryError( $error, $errno, $sql, $fname, false );
270 public function freeResult( $res ) {
271 if ( $res instanceof ResultWrapper
) {
274 Wikimedia\
suppressWarnings();
275 $ok = pg_free_result( $res );
276 Wikimedia\restoreWarnings
();
278 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
282 public function fetchObject( $res ) {
283 if ( $res instanceof ResultWrapper
) {
286 Wikimedia\
suppressWarnings();
287 $row = pg_fetch_object( $res );
288 Wikimedia\restoreWarnings
();
289 # @todo FIXME: HACK HACK HACK HACK debug
291 # @todo hashar: not sure if the following test really trigger if the object
293 $conn = $this->getBindingHandle();
294 if ( pg_last_error( $conn ) ) {
295 throw new DBUnexpectedError(
297 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
304 public function fetchRow( $res ) {
305 if ( $res instanceof ResultWrapper
) {
308 Wikimedia\
suppressWarnings();
309 $row = pg_fetch_array( $res );
310 Wikimedia\restoreWarnings
();
312 $conn = $this->getBindingHandle();
313 if ( pg_last_error( $conn ) ) {
314 throw new DBUnexpectedError(
316 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
323 public function numRows( $res ) {
324 if ( $res instanceof ResultWrapper
) {
327 Wikimedia\
suppressWarnings();
328 $n = pg_num_rows( $res );
329 Wikimedia\restoreWarnings
();
331 $conn = $this->getBindingHandle();
332 if ( pg_last_error( $conn ) ) {
333 throw new DBUnexpectedError(
335 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
342 public function numFields( $res ) {
343 if ( $res instanceof ResultWrapper
) {
347 return pg_num_fields( $res );
350 public function fieldName( $res, $n ) {
351 if ( $res instanceof ResultWrapper
) {
355 return pg_field_name( $res, $n );
358 public function insertId() {
359 $res = $this->query( "SELECT lastval()" );
360 $row = $this->fetchRow( $res );
361 return is_null( $row[0] ) ?
null : (int)$row[0];
364 public function dataSeek( $res, $row ) {
365 if ( $res instanceof ResultWrapper
) {
369 return pg_result_seek( $res, $row );
372 public function lastError() {
374 if ( $this->lastResultHandle
) {
375 return pg_result_error( $this->lastResultHandle
);
377 return pg_last_error();
381 return $this->getLastPHPError() ?
: 'No database connection';
384 public function lastErrno() {
385 if ( $this->lastResultHandle
) {
386 return pg_result_error_field( $this->lastResultHandle
, PGSQL_DIAG_SQLSTATE
);
392 protected function fetchAffectedRowCount() {
393 if ( !is_null( $this->lastAffectedRowCount
) ) {
394 // Forced result for simulated queries
395 return $this->lastAffectedRowCount
;
397 if ( !$this->lastResultHandle
) {
401 return pg_affected_rows( $this->lastResultHandle
);
405 * Estimate rows in dataset
406 * Returns estimated count, based on EXPLAIN output
407 * This is not necessarily an accurate estimate, so use sparingly
408 * Returns -1 if count cannot be found
409 * Takes same arguments as Database::select()
411 * @param string $table
413 * @param string $conds
414 * @param string $fname
415 * @param array $options
416 * @param array $join_conds
419 public function estimateRowCount( $table, $var = '*', $conds = '',
420 $fname = __METHOD__
, $options = [], $join_conds = []
422 $conds = $this->normalizeConditions( $conds, $fname );
423 $column = $this->extractSingleFieldFromList( $var );
424 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
425 $conds[] = "$column IS NOT NULL";
428 $options['EXPLAIN'] = true;
429 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
432 $row = $this->fetchRow( $res );
434 if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
435 $rows = (int)$count[1];
442 public function indexInfo( $table, $index, $fname = __METHOD__
) {
443 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
444 $res = $this->query( $sql, $fname );
448 foreach ( $res as $row ) {
449 if ( $row->indexname
== $this->indexName( $index ) ) {
457 public function indexAttributes( $index, $schema = false ) {
458 if ( $schema === false ) {
459 $schema = $this->getCoreSchema();
462 * A subquery would be not needed if we didn't care about the order
463 * of attributes, but we do
465 $sql = <<<__INDEXATTR__
469 i.indoption[s.g] as option,
472 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
476 ON cis.oid=isub.indexrelid
478 ON cis.relnamespace = ns.oid
479 WHERE cis.relname='$index' AND ns.nspname='$schema') AS s,
485 ON ci.oid=i.indexrelid
487 ON ct.oid = i.indrelid
489 ON ci.relnamespace = n.oid
491 ci.relname='$index' AND n.nspname='$schema'
492 AND attrelid = ct.oid
493 AND i.indkey[s.g] = attnum
494 AND i.indclass[s.g] = opcls.oid
495 AND pg_am.oid = opcls.opcmethod
497 $res = $this->query( $sql, __METHOD__ );
500 foreach ( $res as $row ) {
514 public function indexUnique( $table, $index, $fname = __METHOD__ ) {
515 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
516 " AND indexdef LIKE 'CREATE UNIQUE%(" .
517 $this->strencode( $this->indexName( $index ) ) .
519 $res = $this->query( $sql, $fname );
524 return $res->numRows() > 0;
527 public function selectSQLText(
528 $table, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
530 if ( is_string( $options ) ) {
531 $options = [ $options ];
534 // Change the FOR UPDATE option as necessary based on the join conditions. Then pass
535 // to the parent function to get the actual SQL text.
536 // In Postgres when using FOR UPDATE, only the main table and tables that are inner joined
537 // can be locked. That means tables in an outer join cannot be FOR UPDATE locked. Trying to
538 // do so causes a DB error. This wrapper checks which tables can be locked and adjusts it
540 // MySQL uses "ORDER BY NULL" as an optimization hint, but that is illegal in PostgreSQL.
541 if ( is_array( $options ) ) {
542 $forUpdateKey = array_search( 'FOR UPDATE', $options, true );
543 if ( $forUpdateKey !== false && $join_conds ) {
544 unset( $options[$forUpdateKey] );
545 $options['FOR UPDATE'] = [];
550 $alias = key( $toCheck );
551 $name = $toCheck[$alias];
552 unset( $toCheck[$alias] );
554 $hasAlias = !is_numeric( $alias );
555 if ( !$hasAlias && is_string( $name ) ) {
559 if ( !isset( $join_conds[$alias] ) ||
560 !preg_match( '/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_conds[$alias][0] )
562 if ( is_array( $name ) ) {
563 // It's a parenthesized group, process all the tables inside the group.
564 $toCheck = array_merge( $toCheck, $name );
566 // Quote alias names so $this->tableName() won't mangle them
567 $options['FOR UPDATE'][] = $hasAlias ? $this->addIdentifierQuotes( $alias ) : $alias;
573 if ( isset( $options['ORDER BY'] ) && $options['ORDER BY'] == 'NULL' ) {
574 unset( $options['ORDER BY'] );
578 return parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
582 * INSERT wrapper, inserts an array into a table
584 * $args may be a single associative array, or an array of these with numeric keys,
585 * for multi-row insert (Postgres version 8.2 and above only).
587 * @param string $table Name of the table to insert to.
588 * @param array $args Items to insert into the table.
589 * @param string $fname Name of the function, for profiling
590 * @param array|string $options String or array. Valid options: IGNORE
591 * @return bool Success of insert operation. IGNORE always returns true.
593 public function insert( $table, $args, $fname = __METHOD__, $options = [] ) {
594 if ( !count( $args ) ) {
598 $table = $this->tableName( $table );
599 if ( !isset( $this->numericVersion ) ) {
600 $this->getServerVersion();
603 if ( !is_array( $options ) ) {
604 $options = [ $options ];
607 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
609 $keys = array_keys( $args[0] );
612 $keys = array_keys( $args );
615 // If IGNORE is set, we use savepoints to emulate mysql's behavior
616 // @todo If PostgreSQL 9.5+, we could use ON CONFLICT DO NOTHING instead
617 $savepoint = $olde = null;
618 $numrowsinserted = 0;
619 if ( in_array( 'IGNORE', $options ) ) {
620 $savepoint = new SavepointPostgres( $this, 'mw', $this->queryLogger );
621 $olde = error_reporting( 0 );
622 // For future use, we may want to track the number of actual inserts
623 // Right now, insert (all writes) simply return true/false
626 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
629 if ( $this->numericVersion >= 8.2 && !$savepoint ) {
631 foreach ( $args as $row ) {
637 $sql .= '(' . $this->makeList( $row ) . ')';
639 $res = (bool)$this->query( $sql, $fname, $savepoint );
643 foreach ( $args as $row ) {
645 $tempsql .= '(' . $this->makeList( $row ) . ')';
648 $savepoint->savepoint();
651 $tempres = (bool)$this->query( $tempsql, $fname, $savepoint );
654 $bar = pg_result_error( $this->lastResultHandle );
655 if ( $bar != false ) {
656 $savepoint->rollback();
658 $savepoint->release();
663 // If any of them fail, we fail overall for this function call
664 // Note that this will be ignored if IGNORE is set
671 // Not multi, just a lone insert
673 $savepoint->savepoint();
676 $sql .= '(' . $this->makeList( $args ) . ')';
677 $res = (bool)$this->query( $sql, $fname, $savepoint );
679 $bar = pg_result_error( $this->lastResultHandle );
680 if ( $bar != false ) {
681 $savepoint->rollback();
683 $savepoint->release();
689 error_reporting( $olde );
690 $savepoint->commit();
692 // Set the affected row count for the whole operation
693 $this->lastAffectedRowCount = $numrowsinserted;
695 // IGNORE always returns true
703 * INSERT SELECT wrapper
704 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
705 * Source items may be literals rather then field names, but strings should
706 * be quoted with Database::addQuotes()
707 * $conds may be "*" to copy the whole table
708 * srcTable may be an array of tables.
709 * @todo FIXME: Implement this a little better (seperate select/insert)?
711 * @param string $destTable
712 * @param array|string $srcTable
713 * @param array $varMap
714 * @param array $conds
715 * @param string $fname
716 * @param array $insertOptions
717 * @param array $selectOptions
718 * @param array $selectJoinConds
721 public function nativeInsertSelect(
722 $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
723 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
725 if ( !is_array( $insertOptions ) ) {
726 $insertOptions = [ $insertOptions ];
730 * If IGNORE is set, use the non-native version.
731 * @todo If PostgreSQL 9.5+, we could use ON CONFLICT DO NOTHING
733 if ( in_array( 'IGNORE', $insertOptions ) ) {
734 return $this->nonNativeInsertSelect(
735 $destTable, $srcTable, $varMap, $conds, $fname, $insertOptions, $selectOptions, $selectJoinConds
739 return parent::nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname,
740 $insertOptions, $selectOptions, $selectJoinConds );
743 public function tableName( $name, $format = 'quoted' ) {
744 // Replace reserved words with better ones
745 $name = $this->remappedTableName( $name );
747 return parent::tableName( $name, $format );
751 * @param string $name
752 * @return string Value of $name or remapped name if $name is a reserved keyword
754 public function remappedTableName( $name ) {
755 return isset( $this->keywordTableMap[$name] ) ? $this->keywordTableMap[$name] : $name;
759 * @param string $name
760 * @param string $format
761 * @return string Qualified and encoded (if requested) table name
763 public function realTableName( $name, $format = 'quoted' ) {
764 return parent::tableName( $name, $format );
767 public function nextSequenceValue( $seqName ) {
768 return new NextSequenceValue;
772 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
774 * @param string $seqName
777 public function currentSequenceValue( $seqName ) {
778 $safeseq = str_replace( "'", "''", $seqName );
779 $res = $this->query( "SELECT currval('$safeseq')" );
780 $row = $this->fetchRow( $res );
786 public function textFieldSize( $table, $field ) {
787 $table = $this->tableName( $table );
788 $sql = "SELECT t.typname as ftype,a.atttypmod as size
789 FROM pg_class c, pg_attribute a, pg_type t
790 WHERE relname='$table' AND a.attrelid=c.oid AND
791 a.atttypid=t.oid and a.attname='$field'";
792 $res = $this->query( $sql );
793 $row = $this->fetchObject( $res );
794 if ( $row->ftype == 'varchar' ) {
795 $size = $row->size - 4;
803 public function limitResult( $sql, $limit, $offset = false ) {
804 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
807 public function wasDeadlock() {
808 // https://www.postgresql.org/docs/8.2/static/errcodes-appendix.html
809 return $this->lastErrno() === '40P01';
812 public function wasLockTimeout() {
813 // https://www.postgresql.org/docs/8.2/static/errcodes-appendix.html
814 return $this->lastErrno() === '55P03';
817 public function duplicateTableStructure(
818 $oldName, $newName, $temporary = false, $fname = __METHOD__
820 $newName = $this->addIdentifierQuotes( $newName );
821 $oldName = $this->addIdentifierQuotes( $oldName );
823 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName " .
824 "(LIKE $oldName INCLUDING DEFAULTS INCLUDING INDEXES)", $fname );
827 public function listTables( $prefix = null, $fname = __METHOD__ ) {
828 $eschema = $this->addQuotes( $this->getCoreSchema() );
829 $result = $this->query(
830 "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
833 foreach ( $result as $table ) {
834 $vars = get_object_vars( $table );
835 $table = array_pop( $vars );
836 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
837 $endArray[] = $table;
844 public function timestamp( $ts = 0 ) {
845 $ct = new ConvertibleTimestamp( $ts );
847 return $ct->getTimestamp( TS_POSTGRES );
851 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
852 * to https://secure.php.net/manual/en/ref.pgsql.php
854 * Parsing a postgres array can be a tricky problem, he's my
855 * take on this, it handles multi-dimensional arrays plus
856 * escaping using a nasty regexp to determine the limits of each
859 * This should really be handled by PHP PostgreSQL module
862 * @param string $text Postgreql array returned in a text form like {a,b}
863 * @param string[] $output
864 * @param int|bool $limit
868 private function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
869 if ( false === $limit ) {
870 $limit = strlen( $text ) - 1;
873 if ( '{}' == $text ) {
877 if ( '{' != $text[$offset] ) {
878 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
879 $text, $match, 0, $offset );
880 $offset += strlen( $match[0] );
881 $output[] = ( '"' != $match[1][0]
883 : stripcslashes( substr( $match[1], 1, -1 ) ) );
884 if ( '},' == $match[3] ) {
888 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
890 } while ( $limit > $offset );
895 public function aggregateValue( $valuedata, $valuename = 'value' ) {
899 public function getSoftwareLink() {
900 return '[{{int:version-db-postgres-url}} PostgreSQL]';
904 * Return current schema (executes SELECT current_schema())
908 * @return string Default schema for the current session
910 public function getCurrentSchema() {
911 $res = $this->query( "SELECT current_schema()", __METHOD__ );
912 $row = $this->fetchRow( $res );
918 * Return list of schemas which are accessible without schema name
919 * This is list does not contain magic keywords like "$user"
922 * @see getSearchPath()
923 * @see setSearchPath()
925 * @return array List of actual schemas for the current sesson
927 public function getSchemas() {
928 $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
929 $row = $this->fetchRow( $res );
932 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
934 return $this->pg_array_parse( $row[0], $schemas );
938 * Return search patch for schemas
939 * This is different from getSchemas() since it contain magic keywords
944 * @return array How to search for table names schemas for the current user
946 public function getSearchPath() {
947 $res = $this->query( "SHOW search_path", __METHOD__ );
948 $row = $this->fetchRow( $res );
950 /* PostgreSQL returns SHOW values as strings */
952 return explode( ",", $row[0] );
956 * Update search_path, values should already be sanitized
957 * Values may contain magic keywords like "$user"
960 * @param array $search_path List of schemas to be searched by default
962 private function setSearchPath( $search_path ) {
963 $this->query( "SET search_path = " . implode( ", ", $search_path ) );
967 * Determine default schema for the current application
968 * Adjust this session schema search path if desired schema exists
969 * and is not alread there.
971 * We need to have name of the core schema stored to be able
972 * to query database metadata.
974 * This will be also called by the installer after the schema is created
978 * @param string $desiredSchema
980 public function determineCoreSchema( $desiredSchema ) {
981 $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
982 if ( $this->schemaExists( $desiredSchema ) ) {
983 if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
984 $this->coreSchema = $desiredSchema;
985 $this->queryLogger->debug(
986 "Schema \"" . $desiredSchema . "\" already in the search path\n" );
989 * Prepend our schema (e.g. 'mediawiki') in front
993 $search_path = $this->getSearchPath();
994 array_unshift( $search_path,
995 $this->addIdentifierQuotes( $desiredSchema ) );
996 $this->setSearchPath( $search_path );
997 $this->coreSchema = $desiredSchema;
998 $this->queryLogger->debug(
999 "Schema \"" . $desiredSchema . "\" added to the search path\n" );
1002 $this->coreSchema = $this->getCurrentSchema();
1003 $this->queryLogger->debug(
1004 "Schema \"" . $desiredSchema . "\" not found, using current \"" .
1005 $this->coreSchema . "\"\n" );
1007 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1008 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
1012 * Return schema name for core application tables
1015 * @return string Core schema name
1017 public function getCoreSchema() {
1018 return $this->coreSchema;
1021 public function getServerVersion() {
1022 if ( !isset( $this->numericVersion ) ) {
1023 $conn = $this->getBindingHandle();
1024 $versionInfo = pg_version( $conn );
1025 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1026 // Old client, abort install
1027 $this->numericVersion = '7.3 or earlier';
1028 } elseif ( isset( $versionInfo['server'] ) ) {
1030 $this->numericVersion = $versionInfo['server'];
1032 // T18937: broken pgsql extension from PHP<5.3
1033 $this->numericVersion = pg_parameter_status( $conn, 'server_version' );
1037 return $this->numericVersion;
1041 * Query whether a given relation exists (in the given schema, or the
1042 * default mw one if not given)
1043 * @param string $table
1044 * @param array|string $types
1045 * @param bool|string $schema
1048 private function relationExists( $table, $types, $schema = false ) {
1049 if ( !is_array( $types ) ) {
1050 $types = [ $types ];
1052 if ( $schema === false ) {
1053 $schema = $this->getCoreSchema();
1055 $table = $this->realTableName( $table, 'raw' );
1056 $etable = $this->addQuotes( $table );
1057 $eschema = $this->addQuotes( $schema );
1058 $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1059 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1060 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1061 $res = $this->query( $sql );
1062 $count = $res ? $res->numRows() : 0;
1064 return (bool)$count;
1068 * For backward compatibility, this function checks both tables and views.
1069 * @param string $table
1070 * @param string $fname
1071 * @param bool|string $schema
1074 public function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1075 return $this->relationExists( $table, [ 'r', 'v' ], $schema );
1078 public function sequenceExists( $sequence, $schema = false ) {
1079 return $this->relationExists( $sequence, 'S', $schema );
1082 public function triggerExists( $table, $trigger ) {
1084 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1085 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1086 AND tgrelid=pg_class.oid
1087 AND nspname=%s AND relname=%s AND tgname=%s
1089 $res = $this->query(
1092 $this->addQuotes( $this->getCoreSchema() ),
1093 $this->addQuotes( $table ),
1094 $this->addQuotes( $trigger )
1100 $rows = $res->numRows();
1105 public function ruleExists( $table, $rule ) {
1106 $exists = $this->selectField( 'pg_rules', 'rulename',
1108 'rulename' => $rule,
1109 'tablename' => $table,
1110 'schemaname' => $this->getCoreSchema()
1114 return $exists === $rule;
1117 public function constraintExists( $table, $constraint ) {
1118 $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1119 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1120 $this->addQuotes( $this->getCoreSchema() ),
1121 $this->addQuotes( $table ),
1122 $this->addQuotes( $constraint )
1124 $res = $this->query( $sql );
1128 $rows = $res->numRows();
1134 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1135 * @param string $schema
1138 public function schemaExists( $schema ) {
1139 if ( !strlen( $schema ) ) {
1140 return false; // short-circuit
1143 $exists = $this->selectField(
1144 '"pg_catalog"."pg_namespace"', 1, [ 'nspname' => $schema ], __METHOD__ );
1146 return (bool)$exists;
1150 * Returns true if a given role (i.e. user) exists, false otherwise.
1151 * @param string $roleName
1154 public function roleExists( $roleName ) {
1155 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1156 [ 'rolname' => $roleName ], __METHOD__ );
1158 return (bool)$exists;
1162 * @param string $table
1163 * @param string $field
1164 * @return PostgresField|null
1166 public function fieldInfo( $table, $field ) {
1167 return PostgresField::fromText( $this, $table, $field );
1171 * pg_field_type() wrapper
1172 * @param ResultWrapper|resource $res ResultWrapper or PostgreSQL query result resource
1173 * @param int $index Field number, starting from 0
1176 public function fieldType( $res, $index ) {
1177 if ( $res instanceof ResultWrapper ) {
1178 $res = $res->result;
1181 return pg_field_type( $res, $index );
1184 public function encodeBlob( $b ) {
1185 return new PostgresBlob( pg_escape_bytea( $b ) );
1188 public function decodeBlob( $b ) {
1189 if ( $b instanceof PostgresBlob ) {
1191 } elseif ( $b instanceof Blob ) {
1195 return pg_unescape_bytea( $b );
1198 public function strencode( $s ) {
1199 // Should not be called by us
1200 return pg_escape_string( $this->getBindingHandle(), (string)$s );
1203 public function addQuotes( $s ) {
1204 $conn = $this->getBindingHandle();
1206 if ( is_null( $s ) ) {
1208 } elseif ( is_bool( $s ) ) {
1209 return intval( $s );
1210 } elseif ( $s instanceof Blob ) {
1211 if ( $s instanceof PostgresBlob ) {
1214 $s = pg_escape_bytea( $conn, $s->fetch() );
1217 } elseif ( $s instanceof NextSequenceValue ) {
1221 return "'" . pg_escape_string( $conn, (string)$s ) . "'";
1225 * Postgres specific version of replaceVars.
1226 * Calls the parent version in Database.php
1228 * @param string $ins SQL string, read from a stream (usually tables.sql)
1229 * @return string SQL string
1231 protected function replaceVars( $ins ) {
1232 $ins = parent::replaceVars( $ins );
1234 if ( $this->numericVersion >= 8.3 ) {
1235 // Thanks for not providing backwards-compatibility, 8.3
1236 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1239 if ( $this->numericVersion <= 8.1 ) { // Our minimum version
1240 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1246 public function makeSelectOptions( $options ) {
1247 $preLimitTail = $postLimitTail = '';
1248 $startOpts = $useIndex = $ignoreIndex = '';
1251 foreach ( $options as $key => $option ) {
1252 if ( is_numeric( $key ) ) {
1253 $noKeyOptions[$option] = true;
1257 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1259 $preLimitTail .= $this->makeOrderBy( $options );
1261 if ( isset( $options['FOR UPDATE'] ) ) {
1262 $postLimitTail .= ' FOR UPDATE OF ' .
1263 implode( ', ', array_map( [ $this, 'tableName' ], $options['FOR UPDATE'] ) );
1264 } elseif ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1265 $postLimitTail .= ' FOR UPDATE';
1268 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1269 $startOpts .= 'DISTINCT';
1272 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1275 public function getDBname() {
1276 return $this->dbName;
1279 public function getServer() {
1280 return $this->server;
1283 public function buildConcat( $stringList ) {
1284 return implode( ' || ', $stringList );
1287 public function buildGroupConcatField(
1288 $delimiter, $table, $field, $conds = '', $options = [], $join_conds = []
1290 $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1292 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1295 public function buildStringCast( $field ) {
1296 return $field . '::text';
1299 public function streamStatementEnd( &$sql, &$newLine ) {
1300 # Allow dollar quoting for function declarations
1301 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1302 if ( $this->delimiter ) {
1303 $this->delimiter = false;
1305 $this->delimiter = ';';
1309 return parent::streamStatementEnd( $sql, $newLine );
1312 public function doLockTables( array $read, array $write, $method ) {
1314 foreach ( $write as $table ) {
1315 $tablesWrite[] = $this->tableName( $table );
1318 foreach ( $read as $table ) {
1319 $tablesRead[] = $this->tableName( $table );
1322 // Acquire locks for the duration of the current transaction...
1323 if ( $tablesWrite ) {
1325 'LOCK TABLE ONLY ' . implode( ',', $tablesWrite ) . ' IN EXCLUSIVE MODE',
1329 if ( $tablesRead ) {
1331 'LOCK TABLE ONLY ' . implode( ',', $tablesRead ) . ' IN SHARE MODE',
1339 public function lockIsFree( $lockName, $method ) {
1340 if ( !parent::lockIsFree( $lockName, $method ) ) {
1341 return false; // already held
1343 // http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1344 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1345 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1346 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1347 $row = $this->fetchObject( $result );
1349 return ( $row->lockstatus === 't' );
1352 public function lock( $lockName, $method, $timeout = 5 ) {
1353 // http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1354 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1355 $loop = new WaitConditionLoop(
1356 function () use ( $lockName, $key, $timeout, $method ) {
1357 $res = $this->query( "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1358 $row = $this->fetchObject( $res );
1359 if ( $row->lockstatus === 't' ) {
1360 parent::lock( $lockName, $method, $timeout ); // record
1364 return WaitConditionLoop::CONDITION_CONTINUE;
1369 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1372 public function unlock( $lockName, $method ) {
1373 // http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1374 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1375 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1376 $row = $this->fetchObject( $result );
1378 if ( $row->lockstatus === 't' ) {
1379 parent::unlock( $lockName, $method ); // record
1383 $this->queryLogger->debug( __METHOD__ . " failed to release lock\n" );
1388 public function serverIsReadOnly() {
1389 $res = $this->query( "SHOW default_transaction_read_only", __METHOD__ );
1390 $row = $this->fetchObject( $res );
1392 return $row ? ( strtolower( $row->default_transaction_read_only ) === 'on' ) : false;
1396 * @param string $lockName
1397 * @return string Integer
1399 private function bigintFromLockName( $lockName ) {
1400 return \Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1404 class_alias( DatabasePostgres::class, 'DatabasePostgres' );