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;
40 /** @var float|string */
41 private $numericVersion = null;
42 /** @var string Connect string to open a PostgreSQL connection */
43 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
= $params['port'] ??
false;
58 $this->keywordTableMap
= $params['keywordTableMap'] ??
[];
60 parent
::__construct( $params );
63 public function getType() {
67 public function implicitGroupby() {
71 public function implicitOrderby() {
75 public function hasConstraint( $name ) {
76 foreach ( $this->getCoreSchemas() as $schema ) {
77 $sql = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
78 "WHERE c.connamespace = n.oid AND conname = " .
79 $this->addQuotes( $name ) . " AND n.nspname = " .
80 $this->addQuotes( $schema );
81 $res = $this->doQuery( $sql );
82 if ( $res && $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 $this->query( "SET bytea_output = 'escape'", __METHOD__
); // PHP bug 53127
160 $this->determineCoreSchema( $this->schema
);
161 // The schema to be used is now in the search path; no need for explicit qualification
167 public function databasesAreIndependent() {
172 * Postgres doesn't support selectDB in the same way MySQL does. So if the
173 * DB name doesn't match the open connection, open a new one
176 * @throws DBUnexpectedError
178 public function selectDB( $db ) {
179 if ( $this->dbName
!== $db ) {
180 return (bool)$this->open( $this->server
, $this->user
, $this->password
, $db );
187 * @param string[] $vars
190 private function makeConnectionString( $vars ) {
192 foreach ( $vars as $name => $value ) {
193 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
199 protected function closeConnection() {
200 return $this->conn ?
pg_close( $this->conn
) : true;
203 protected function isTransactableQuery( $sql ) {
204 return parent
::isTransactableQuery( $sql ) &&
205 !preg_match( '/^SELECT\s+pg_(try_|)advisory_\w+\(/', $sql );
208 public function doQuery( $sql ) {
209 $conn = $this->getBindingHandle();
211 $sql = mb_convert_encoding( $sql, 'UTF-8' );
212 // Clear previously left over PQresult
213 while ( $res = pg_get_result( $conn ) ) {
214 pg_free_result( $res );
216 if ( pg_send_query( $conn, $sql ) === false ) {
217 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
219 $this->lastResultHandle
= pg_get_result( $conn );
220 if ( pg_result_error( $this->lastResultHandle
) ) {
224 return $this->lastResultHandle
;
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->lastResultHandle
, $d ) ) );
248 public function freeResult( $res ) {
249 if ( $res instanceof ResultWrapper
) {
252 Wikimedia\
suppressWarnings();
253 $ok = pg_free_result( $res );
254 Wikimedia\restoreWarnings
();
256 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
260 public function fetchObject( $res ) {
261 if ( $res instanceof ResultWrapper
) {
264 Wikimedia\
suppressWarnings();
265 $row = pg_fetch_object( $res );
266 Wikimedia\restoreWarnings
();
267 # @todo FIXME: HACK HACK HACK HACK debug
269 # @todo hashar: not sure if the following test really trigger if the object
271 $conn = $this->getBindingHandle();
272 if ( pg_last_error( $conn ) ) {
273 throw new DBUnexpectedError(
275 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
282 public function fetchRow( $res ) {
283 if ( $res instanceof ResultWrapper
) {
286 Wikimedia\
suppressWarnings();
287 $row = pg_fetch_array( $res );
288 Wikimedia\restoreWarnings
();
290 $conn = $this->getBindingHandle();
291 if ( pg_last_error( $conn ) ) {
292 throw new DBUnexpectedError(
294 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
301 public function numRows( $res ) {
302 if ( $res === false ) {
306 if ( $res instanceof ResultWrapper
) {
309 Wikimedia\
suppressWarnings();
310 $n = pg_num_rows( $res );
311 Wikimedia\restoreWarnings
();
313 $conn = $this->getBindingHandle();
314 if ( pg_last_error( $conn ) ) {
315 throw new DBUnexpectedError(
317 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
324 public function numFields( $res ) {
325 if ( $res instanceof ResultWrapper
) {
329 return pg_num_fields( $res );
332 public function fieldName( $res, $n ) {
333 if ( $res instanceof ResultWrapper
) {
337 return pg_field_name( $res, $n );
340 public function insertId() {
341 $res = $this->query( "SELECT lastval()" );
342 $row = $this->fetchRow( $res );
343 return is_null( $row[0] ) ?
null : (int)$row[0];
346 public function dataSeek( $res, $row ) {
347 if ( $res instanceof ResultWrapper
) {
351 return pg_result_seek( $res, $row );
354 public function lastError() {
356 if ( $this->lastResultHandle
) {
357 return pg_result_error( $this->lastResultHandle
);
359 return pg_last_error();
363 return $this->getLastPHPError() ?
: 'No database connection';
366 public function lastErrno() {
367 if ( $this->lastResultHandle
) {
368 return pg_result_error_field( $this->lastResultHandle
, PGSQL_DIAG_SQLSTATE
);
374 protected function fetchAffectedRowCount() {
375 if ( !$this->lastResultHandle
) {
379 return pg_affected_rows( $this->lastResultHandle
);
383 * Estimate rows in dataset
384 * Returns estimated count, based on EXPLAIN output
385 * This is not necessarily an accurate estimate, so use sparingly
386 * Returns -1 if count cannot be found
387 * Takes same arguments as Database::select()
389 * @param string $table
391 * @param string $conds
392 * @param string $fname
393 * @param array $options
394 * @param array $join_conds
397 public function estimateRowCount( $table, $var = '*', $conds = '',
398 $fname = __METHOD__
, $options = [], $join_conds = []
400 $conds = $this->normalizeConditions( $conds, $fname );
401 $column = $this->extractSingleFieldFromList( $var );
402 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
403 $conds[] = "$column IS NOT NULL";
406 $options['EXPLAIN'] = true;
407 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
410 $row = $this->fetchRow( $res );
412 if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
413 $rows = (int)$count[1];
420 public function indexInfo( $table, $index, $fname = __METHOD__
) {
421 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
422 $res = $this->query( $sql, $fname );
426 foreach ( $res as $row ) {
427 if ( $row->indexname
== $this->indexName( $index ) ) {
435 public function indexAttributes( $index, $schema = false ) {
436 if ( $schema === false ) {
437 $schemas = $this->getCoreSchemas();
439 $schemas = [ $schema ];
442 $eindex = $this->addQuotes( $index );
444 foreach ( $schemas as $schema ) {
445 $eschema = $this->addQuotes( $schema );
447 * A subquery would be not needed if we didn't care about the order
448 * of attributes, but we do
450 $sql = <<<__INDEXATTR__
454 i.indoption[s.g] as option,
457 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
461 ON cis.oid=isub.indexrelid
463 ON cis.relnamespace = ns.oid
464 WHERE cis.relname=$eindex AND ns.nspname=$eschema) AS s,
470 ON ci.oid=i.indexrelid
472 ON ct.oid = i.indrelid
474 ON ci.relnamespace = n.oid
476 ci.relname=$eindex AND n.nspname=$eschema
477 AND attrelid = ct.oid
478 AND i.indkey[s.g] = attnum
479 AND i.indclass[s.g] = opcls.oid
480 AND pg_am.oid = opcls.opcmethod
482 $res = $this->query( $sql, __METHOD__ );
485 foreach ( $res as $row ) {
498 public function indexUnique( $table, $index, $fname = __METHOD__ ) {
499 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
500 " AND indexdef LIKE 'CREATE UNIQUE%(" .
501 $this->strencode( $this->indexName( $index ) ) .
503 $res = $this->query( $sql, $fname );
508 return $res->numRows() > 0;
511 public function selectSQLText(
512 $table, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
514 if ( is_string( $options ) ) {
515 $options = [ $options ];
518 // Change the FOR UPDATE option as necessary based on the join conditions. Then pass
519 // to the parent function to get the actual SQL text.
520 // In Postgres when using FOR UPDATE, only the main table and tables that are inner joined
521 // can be locked. That means tables in an outer join cannot be FOR UPDATE locked. Trying to
522 // do so causes a DB error. This wrapper checks which tables can be locked and adjusts it
524 // MySQL uses "ORDER BY NULL" as an optimization hint, but that is illegal in PostgreSQL.
525 if ( is_array( $options ) ) {
526 $forUpdateKey = array_search( 'FOR UPDATE', $options, true );
527 if ( $forUpdateKey !== false && $join_conds ) {
528 unset( $options[$forUpdateKey] );
529 $options['FOR UPDATE'] = [];
534 $alias = key( $toCheck );
535 $name = $toCheck[$alias];
536 unset( $toCheck[$alias] );
538 $hasAlias = !is_numeric( $alias );
539 if ( !$hasAlias && is_string( $name ) ) {
543 if ( !isset( $join_conds[$alias] ) ||
544 !preg_match( '/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_conds[$alias][0] )
546 if ( is_array( $name ) ) {
547 // It's a parenthesized group, process all the tables inside the group.
548 $toCheck = array_merge( $toCheck, $name );
550 // Quote alias names so $this->tableName() won't mangle them
551 $options['FOR UPDATE'][] = $hasAlias ? $this->addIdentifierQuotes( $alias ) : $alias;
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 public function insert( $table, $args, $fname = __METHOD__, $options = [] ) {
567 if ( !count( $args ) ) {
571 $table = $this->tableName( $table );
572 if ( !isset( $this->numericVersion ) ) {
573 $this->getServerVersion();
576 if ( !is_array( $options ) ) {
577 $options = [ $options ];
580 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
582 $keys = array_keys( $args[0] );
585 $keys = array_keys( $args );
588 $ignore = in_array( 'IGNORE', $options );
590 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
592 if ( $this->numericVersion >= 9.5 || !$ignore ) {
593 // No IGNORE or our PG has "ON CONFLICT DO NOTHING"
595 foreach ( $rows as $row ) {
601 $sql .= '(' . $this->makeList( $row ) . ')';
604 $sql .= ' ON CONFLICT DO NOTHING';
606 $this->query( $sql, $fname );
608 // Emulate IGNORE by doing each row individually, with savepoints
609 // to roll back as necessary.
610 $numrowsinserted = 0;
612 $tok = $this->startAtomic( "$fname (outer)", self::ATOMIC_CANCELABLE );
614 foreach ( $rows as $row ) {
616 $tempsql .= '(' . $this->makeList( $row ) . ')';
618 $this->startAtomic( "$fname (inner)", self::ATOMIC_CANCELABLE );
620 $this->query( $tempsql, $fname );
621 $this->endAtomic( "$fname (inner)" );
623 } catch ( DBQueryError $e ) {
624 $this->cancelAtomic( "$fname (inner)" );
625 // Our IGNORE is supposed to ignore duplicate key errors, but not others.
626 // (even though MySQL's version apparently ignores all errors)
627 if ( $e->errno !== '23505' ) {
632 } catch ( Exception $e ) {
633 $this->cancelAtomic( "$fname (outer)", $tok );
636 $this->endAtomic( "$fname (outer)" );
638 // Set the affected row count for the whole operation
639 $this->affectedRowCount = $numrowsinserted;
646 * INSERT SELECT wrapper
647 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
648 * Source items may be literals rather then field names, but strings should
649 * be quoted with Database::addQuotes()
650 * $conds may be "*" to copy the whole table
651 * srcTable may be an array of tables.
652 * @todo FIXME: Implement this a little better (separate select/insert)?
654 * @param string $destTable
655 * @param array|string $srcTable
656 * @param array $varMap
657 * @param array $conds
658 * @param string $fname
659 * @param array $insertOptions
660 * @param array $selectOptions
661 * @param array $selectJoinConds
664 public function nativeInsertSelect(
665 $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
666 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
668 if ( !is_array( $insertOptions ) ) {
669 $insertOptions = [ $insertOptions ];
672 if ( in_array( 'IGNORE', $insertOptions ) ) {
673 if ( $this->getServerVersion() >= 9.5 ) {
674 // Use ON CONFLICT DO NOTHING if we have it for IGNORE
675 $destTable = $this->tableName( $destTable );
677 $selectSql = $this->selectSQLText(
679 array_values( $varMap ),
686 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
687 $selectSql . ' ON CONFLICT DO NOTHING';
689 return $this->query( $sql, $fname );
691 // IGNORE and we don't have ON CONFLICT DO NOTHING, so just use the non-native version
692 return $this->nonNativeInsertSelect(
693 $destTable, $srcTable, $varMap, $conds, $fname,
694 $insertOptions, $selectOptions, $selectJoinConds
699 return parent::nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname,
700 $insertOptions, $selectOptions, $selectJoinConds );
703 public function tableName( $name, $format = 'quoted' ) {
704 // Replace reserved words with better ones
705 $name = $this->remappedTableName( $name );
707 return parent::tableName( $name, $format );
711 * @param string $name
712 * @return string Value of $name or remapped name if $name is a reserved keyword
714 public function remappedTableName( $name ) {
715 return $this->keywordTableMap[$name] ?? $name;
719 * @param string $name
720 * @param string $format
721 * @return string Qualified and encoded (if requested) table name
723 public function realTableName( $name, $format = 'quoted' ) {
724 return parent::tableName( $name, $format );
727 public function nextSequenceValue( $seqName ) {
728 return new NextSequenceValue;
732 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
734 * @param string $seqName
737 public function currentSequenceValue( $seqName ) {
738 $safeseq = str_replace( "'", "''", $seqName );
739 $res = $this->query( "SELECT currval('$safeseq')" );
740 $row = $this->fetchRow( $res );
746 public function textFieldSize( $table, $field ) {
747 $table = $this->tableName( $table );
748 $sql = "SELECT t.typname as ftype,a.atttypmod as size
749 FROM pg_class c, pg_attribute a, pg_type t
750 WHERE relname='$table' AND a.attrelid=c.oid AND
751 a.atttypid=t.oid and a.attname='$field'";
752 $res = $this->query( $sql );
753 $row = $this->fetchObject( $res );
754 if ( $row->ftype == 'varchar' ) {
755 $size = $row->size - 4;
763 public function limitResult( $sql, $limit, $offset = false ) {
764 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
767 public function wasDeadlock() {
768 // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
769 return $this->lastErrno() === '40P01';
772 public function wasLockTimeout() {
773 // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
774 return $this->lastErrno() === '55P03';
777 public function wasConnectionError( $errno ) {
778 // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
779 static $codes = [ '08000', '08003', '08006', '08001', '08004', '57P01', '57P03', '53300' ];
781 return in_array( $errno, $codes, true );
784 protected function wasKnownStatementRollbackError() {
785 return false; // transaction has to be rolled-back from error state
788 public function duplicateTableStructure(
789 $oldName, $newName, $temporary = false, $fname = __METHOD__
791 $newNameE = $this->addIdentifierQuotes( $newName );
792 $oldNameE = $this->addIdentifierQuotes( $oldName );
794 $temporary = $temporary ? 'TEMPORARY' : '';
796 $ret = $this->query( "CREATE $temporary TABLE $newNameE " .
797 "(LIKE $oldNameE INCLUDING DEFAULTS INCLUDING INDEXES)", $fname );
802 $res = $this->query( 'SELECT attname FROM pg_class c'
803 . ' JOIN pg_namespace n ON (n.oid = c.relnamespace)'
804 . ' JOIN pg_attribute a ON (a.attrelid = c.oid)'
805 . ' JOIN pg_attrdef d ON (c.oid=d.adrelid and a.attnum=d.adnum)'
806 . ' WHERE relkind = \'r\''
807 . ' AND nspname = ' . $this->addQuotes( $this->getCoreSchema() )
808 . ' AND relname = ' . $this->addQuotes( $oldName )
809 . ' AND adsrc LIKE \'nextval(%\'',
812 $row = $this->fetchObject( $res );
814 $field = $row->attname;
815 $newSeq = "{$newName}_{$field}_seq";
816 $fieldE = $this->addIdentifierQuotes( $field );
817 $newSeqE = $this->addIdentifierQuotes( $newSeq );
818 $newSeqQ = $this->addQuotes( $newSeq );
819 $this->query( "CREATE $temporary SEQUENCE $newSeqE OWNED BY $newNameE.$fieldE", $fname );
821 "ALTER TABLE $newNameE ALTER COLUMN $fieldE SET DEFAULT nextval({$newSeqQ}::regclass)",
829 public function resetSequenceForTable( $table, $fname = __METHOD__ ) {
830 $table = $this->tableName( $table, 'raw' );
831 foreach ( $this->getCoreSchemas() as $schema ) {
833 'SELECT c.oid FROM pg_class c JOIN pg_namespace n ON (n.oid = c.relnamespace)'
834 . ' WHERE relkind = \'r\''
835 . ' AND nspname = ' . $this->addQuotes( $schema )
836 . ' AND relname = ' . $this->addQuotes( $table ),
839 if ( !$res || !$this->numRows( $res ) ) {
843 $oid = $this->fetchObject( $res )->oid;
844 $res = $this->query( 'SELECT adsrc FROM pg_attribute a'
845 . ' JOIN pg_attrdef d ON (a.attrelid=d.adrelid and a.attnum=d.adnum)'
846 . " WHERE a.attrelid = $oid"
847 . ' AND adsrc LIKE \'nextval(%\'',
850 $row = $this->fetchObject( $res );
853 'SELECT ' . preg_replace( '/^nextval\((.+)\)$/', 'setval($1,1,false)', $row->adsrc ),
864 public function listTables( $prefix = null, $fname = __METHOD__ ) {
865 $eschemas = implode( ',', array_map( [ $this, 'addQuotes' ], $this->getCoreSchemas() ) );
866 $result = $this->query(
867 "SELECT DISTINCT tablename FROM pg_tables WHERE schemaname IN ($eschemas)", $fname );
870 foreach ( $result as $table ) {
871 $vars = get_object_vars( $table );
872 $table = array_pop( $vars );
873 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
874 $endArray[] = $table;
881 public function timestamp( $ts = 0 ) {
882 $ct = new ConvertibleTimestamp( $ts );
884 return $ct->getTimestamp( TS_POSTGRES );
888 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
889 * to https://secure.php.net/manual/en/ref.pgsql.php
891 * Parsing a postgres array can be a tricky problem, he's my
892 * take on this, it handles multi-dimensional arrays plus
893 * escaping using a nasty regexp to determine the limits of each
896 * This should really be handled by PHP PostgreSQL module
899 * @param string $text Postgreql array returned in a text form like {a,b}
900 * @param string[] $output
901 * @param int|bool $limit
905 private function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
906 if ( false === $limit ) {
907 $limit = strlen( $text ) - 1;
910 if ( '{}' == $text ) {
914 if ( '{' != $text[$offset] ) {
915 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
916 $text, $match, 0, $offset );
917 $offset += strlen( $match[0] );
918 $output[] = ( '"' != $match[1][0]
920 : stripcslashes( substr( $match[1], 1, -1 ) ) );
921 if ( '},' == $match[3] ) {
925 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
927 } while ( $limit > $offset );
932 public function aggregateValue( $valuedata, $valuename = 'value' ) {
936 public function getSoftwareLink() {
937 return '[{{int:version-db-postgres-url}} PostgreSQL]';
941 * Return current schema (executes SELECT current_schema())
945 * @return string Default schema for the current session
947 public function getCurrentSchema() {
948 $res = $this->query( "SELECT current_schema()", __METHOD__ );
949 $row = $this->fetchRow( $res );
955 * Return list of schemas which are accessible without schema name
956 * This is list does not contain magic keywords like "$user"
959 * @see getSearchPath()
960 * @see setSearchPath()
962 * @return array List of actual schemas for the current sesson
964 public function getSchemas() {
965 $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
966 $row = $this->fetchRow( $res );
969 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
971 return $this->pg_array_parse( $row[0], $schemas );
975 * Return search patch for schemas
976 * This is different from getSchemas() since it contain magic keywords
981 * @return array How to search for table names schemas for the current user
983 public function getSearchPath() {
984 $res = $this->query( "SHOW search_path", __METHOD__ );
985 $row = $this->fetchRow( $res );
987 /* PostgreSQL returns SHOW values as strings */
989 return explode( ",", $row[0] );
993 * Update search_path, values should already be sanitized
994 * Values may contain magic keywords like "$user"
997 * @param array $search_path List of schemas to be searched by default
999 private function setSearchPath( $search_path ) {
1000 $this->query( "SET search_path = " . implode( ", ", $search_path ) );
1004 * Determine default schema for the current application
1005 * Adjust this session schema search path if desired schema exists
1006 * and is not alread there.
1008 * We need to have name of the core schema stored to be able
1009 * to query database metadata.
1011 * This will be also called by the installer after the schema is created
1015 * @param string $desiredSchema
1017 public function determineCoreSchema( $desiredSchema ) {
1018 $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
1019 if ( $this->schemaExists( $desiredSchema ) ) {
1020 if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
1021 $this->coreSchema = $desiredSchema;
1022 $this->queryLogger->debug(
1023 "Schema \"" . $desiredSchema . "\" already in the search path\n" );
1026 * Prepend our schema (e.g. 'mediawiki') in front
1027 * of the search path
1030 $search_path = $this->getSearchPath();
1031 array_unshift( $search_path,
1032 $this->addIdentifierQuotes( $desiredSchema ) );
1033 $this->setSearchPath( $search_path );
1034 $this->coreSchema = $desiredSchema;
1035 $this->queryLogger->debug(
1036 "Schema \"" . $desiredSchema . "\" added to the search path\n" );
1039 $this->coreSchema = $this->getCurrentSchema();
1040 $this->queryLogger->debug(
1041 "Schema \"" . $desiredSchema . "\" not found, using current \"" .
1042 $this->coreSchema . "\"\n" );
1044 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1045 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
1049 * Return schema name for core application tables
1052 * @return string Core schema name
1054 public function getCoreSchema() {
1055 return $this->coreSchema;
1059 * Return schema names for temporary tables and core application tables
1062 * @return string[] schema names
1064 public function getCoreSchemas() {
1065 if ( $this->tempSchema ) {
1066 return [ $this->tempSchema, $this->getCoreSchema() ];
1069 $res = $this->query(
1070 "SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = pg_my_temp_schema()", __METHOD__
1072 $row = $this->fetchObject( $res );
1074 $this->tempSchema = $row->nspname;
1075 return [ $this->tempSchema, $this->getCoreSchema() ];
1078 return [ $this->getCoreSchema() ];
1081 public function getServerVersion() {
1082 if ( !isset( $this->numericVersion ) ) {
1083 $conn = $this->getBindingHandle();
1084 $versionInfo = pg_version( $conn );
1085 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1086 // Old client, abort install
1087 $this->numericVersion = '7.3 or earlier';
1088 } elseif ( isset( $versionInfo['server'] ) ) {
1090 $this->numericVersion = $versionInfo['server'];
1092 // T18937: broken pgsql extension from PHP<5.3
1093 $this->numericVersion = pg_parameter_status( $conn, 'server_version' );
1097 return $this->numericVersion;
1101 * Query whether a given relation exists (in the given schema, or the
1102 * default mw one if not given)
1103 * @param string $table
1104 * @param array|string $types
1105 * @param bool|string $schema
1108 private function relationExists( $table, $types, $schema = false ) {
1109 if ( !is_array( $types ) ) {
1110 $types = [ $types ];
1112 if ( $schema === false ) {
1113 $schemas = $this->getCoreSchemas();
1115 $schemas = [ $schema ];
1117 $table = $this->realTableName( $table, 'raw' );
1118 $etable = $this->addQuotes( $table );
1119 foreach ( $schemas as $schema ) {
1120 $eschema = $this->addQuotes( $schema );
1121 $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1122 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1123 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1124 $res = $this->query( $sql );
1125 if ( $res && $res->numRows() ) {
1134 * For backward compatibility, this function checks both tables and views.
1135 * @param string $table
1136 * @param string $fname
1137 * @param bool|string $schema
1140 public function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1141 return $this->relationExists( $table, [ 'r', 'v' ], $schema );
1144 public function sequenceExists( $sequence, $schema = false ) {
1145 return $this->relationExists( $sequence, 'S', $schema );
1148 public function triggerExists( $table, $trigger ) {
1150 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1151 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1152 AND tgrelid=pg_class.oid
1153 AND nspname=%s AND relname=%s AND tgname=%s
1155 foreach ( $this->getCoreSchemas() as $schema ) {
1156 $res = $this->query(
1159 $this->addQuotes( $schema ),
1160 $this->addQuotes( $table ),
1161 $this->addQuotes( $trigger )
1164 if ( $res && $res->numRows() ) {
1172 public function ruleExists( $table, $rule ) {
1173 $exists = $this->selectField( 'pg_rules', 'rulename',
1175 'rulename' => $rule,
1176 'tablename' => $table,
1177 'schemaname' => $this->getCoreSchemas()
1181 return $exists === $rule;
1184 public function constraintExists( $table, $constraint ) {
1185 foreach ( $this->getCoreSchemas() as $schema ) {
1186 $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1187 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1188 $this->addQuotes( $schema ),
1189 $this->addQuotes( $table ),
1190 $this->addQuotes( $constraint )
1192 $res = $this->query( $sql );
1193 if ( $res && $res->numRows() ) {
1201 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1202 * @param string $schema
1205 public function schemaExists( $schema ) {
1206 if ( !strlen( $schema ) ) {
1207 return false; // short-circuit
1210 $exists = $this->selectField(
1211 '"pg_catalog"."pg_namespace"', 1, [ 'nspname' => $schema ], __METHOD__ );
1213 return (bool)$exists;
1217 * Returns true if a given role (i.e. user) exists, false otherwise.
1218 * @param string $roleName
1221 public function roleExists( $roleName ) {
1222 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1223 [ 'rolname' => $roleName ], __METHOD__ );
1225 return (bool)$exists;
1229 * @param string $table
1230 * @param string $field
1231 * @return PostgresField|null
1233 public function fieldInfo( $table, $field ) {
1234 return PostgresField::fromText( $this, $table, $field );
1238 * pg_field_type() wrapper
1239 * @param ResultWrapper|resource $res ResultWrapper or PostgreSQL query result resource
1240 * @param int $index Field number, starting from 0
1243 public function fieldType( $res, $index ) {
1244 if ( $res instanceof ResultWrapper ) {
1245 $res = $res->result;
1248 return pg_field_type( $res, $index );
1251 public function encodeBlob( $b ) {
1252 return new PostgresBlob( pg_escape_bytea( $b ) );
1255 public function decodeBlob( $b ) {
1256 if ( $b instanceof PostgresBlob ) {
1258 } elseif ( $b instanceof Blob ) {
1262 return pg_unescape_bytea( $b );
1265 public function strencode( $s ) {
1266 // Should not be called by us
1267 return pg_escape_string( $this->getBindingHandle(), (string)$s );
1270 public function addQuotes( $s ) {
1271 $conn = $this->getBindingHandle();
1273 if ( is_null( $s ) ) {
1275 } elseif ( is_bool( $s ) ) {
1276 return intval( $s );
1277 } elseif ( $s instanceof Blob ) {
1278 if ( $s instanceof PostgresBlob ) {
1281 $s = pg_escape_bytea( $conn, $s->fetch() );
1284 } elseif ( $s instanceof NextSequenceValue ) {
1288 return "'" . pg_escape_string( $conn, (string)$s ) . "'";
1291 public function makeSelectOptions( $options ) {
1292 $preLimitTail = $postLimitTail = '';
1293 $startOpts = $useIndex = $ignoreIndex = '';
1296 foreach ( $options as $key => $option ) {
1297 if ( is_numeric( $key ) ) {
1298 $noKeyOptions[$option] = true;
1302 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1304 $preLimitTail .= $this->makeOrderBy( $options );
1306 if ( isset( $options['FOR UPDATE'] ) ) {
1307 $postLimitTail .= ' FOR UPDATE OF ' .
1308 implode( ', ', array_map( [ $this, 'tableName' ], $options['FOR UPDATE'] ) );
1309 } elseif ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1310 $postLimitTail .= ' FOR UPDATE';
1313 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1314 $startOpts .= 'DISTINCT';
1317 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1320 public function getDBname() {
1321 return $this->dbName;
1324 public function getServer() {
1325 return $this->server;
1328 public function buildConcat( $stringList ) {
1329 return implode( ' || ', $stringList );
1332 public function buildGroupConcatField(
1333 $delimiter, $table, $field, $conds = '', $options = [], $join_conds = []
1335 $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1337 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1340 public function buildStringCast( $field ) {
1341 return $field . '::text';
1344 public function streamStatementEnd( &$sql, &$newLine ) {
1345 # Allow dollar quoting for function declarations
1346 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1347 if ( $this->delimiter ) {
1348 $this->delimiter = false;
1350 $this->delimiter = ';';
1354 return parent::streamStatementEnd( $sql, $newLine );
1357 public function doLockTables( array $read, array $write, $method ) {
1359 foreach ( $write as $table ) {
1360 $tablesWrite[] = $this->tableName( $table );
1363 foreach ( $read as $table ) {
1364 $tablesRead[] = $this->tableName( $table );
1367 // Acquire locks for the duration of the current transaction...
1368 if ( $tablesWrite ) {
1370 'LOCK TABLE ONLY ' . implode( ',', $tablesWrite ) . ' IN EXCLUSIVE MODE',
1374 if ( $tablesRead ) {
1376 'LOCK TABLE ONLY ' . implode( ',', $tablesRead ) . ' IN SHARE MODE',
1384 public function lockIsFree( $lockName, $method ) {
1385 if ( !parent::lockIsFree( $lockName, $method ) ) {
1386 return false; // already held
1388 // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1389 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1390 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1391 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1392 $row = $this->fetchObject( $result );
1394 return ( $row->lockstatus === 't' );
1397 public function lock( $lockName, $method, $timeout = 5 ) {
1398 // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1399 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1400 $loop = new WaitConditionLoop(
1401 function () use ( $lockName, $key, $timeout, $method ) {
1402 $res = $this->query( "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1403 $row = $this->fetchObject( $res );
1404 if ( $row->lockstatus === 't' ) {
1405 parent::lock( $lockName, $method, $timeout ); // record
1409 return WaitConditionLoop::CONDITION_CONTINUE;
1414 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1417 public function unlock( $lockName, $method ) {
1418 // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1419 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1420 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1421 $row = $this->fetchObject( $result );
1423 if ( $row->lockstatus === 't' ) {
1424 parent::unlock( $lockName, $method ); // record
1428 $this->queryLogger->debug( __METHOD__ . " failed to release lock\n" );
1433 public function serverIsReadOnly() {
1434 $res = $this->query( "SHOW default_transaction_read_only", __METHOD__ );
1435 $row = $this->fetchObject( $res );
1437 return $row ? ( strtolower( $row->default_transaction_read_only ) === 'on' ) : false;
1441 * @param string $lockName
1442 * @return string Integer
1444 private function bigintFromLockName( $lockName ) {
1445 return \Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1450 * @deprecated since 1.29
1452 class_alias( DatabasePostgres::class, 'DatabasePostgres' );