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
= 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 foreach ( $this->getCoreSchemas() as $schema ) {
79 $sql = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
80 "WHERE c.connamespace = n.oid AND conname = " .
81 $this->addQuotes( $name ) . " AND n.nspname = " .
82 $this->addQuotes( $schema );
83 $res = $this->doQuery( $sql );
84 if ( $res && $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->server
= $server;
104 $this->password
= $password;
105 $this->dbName
= $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->flags
& 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->conn
= pg_connect( $this->connectString
, PGSQL_CONNECT_FORCE_NEW
);
132 } catch ( Exception
$ex ) {
133 $this->restoreErrorHandler();
137 $phpError = $this->restoreErrorHandler();
139 if ( !$this->conn
) {
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->opened
= 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 $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 if ( pg_result_error( $this->lastResultHandle
) ) {
226 return $this->lastResultHandle
;
229 protected function dumpError() {
233 PGSQL_DIAG_MESSAGE_PRIMARY
,
234 PGSQL_DIAG_MESSAGE_DETAIL
,
235 PGSQL_DIAG_MESSAGE_HINT
,
236 PGSQL_DIAG_STATEMENT_POSITION
,
237 PGSQL_DIAG_INTERNAL_POSITION
,
238 PGSQL_DIAG_INTERNAL_QUERY
,
240 PGSQL_DIAG_SOURCE_FILE
,
241 PGSQL_DIAG_SOURCE_LINE
,
242 PGSQL_DIAG_SOURCE_FUNCTION
244 foreach ( $diags as $d ) {
245 $this->queryLogger
->debug( sprintf( "PgSQL ERROR(%d): %s\n",
246 $d, pg_result_error_field( $this->lastResultHandle
, $d ) ) );
250 public function freeResult( $res ) {
251 if ( $res instanceof ResultWrapper
) {
254 Wikimedia\
suppressWarnings();
255 $ok = pg_free_result( $res );
256 Wikimedia\restoreWarnings
();
258 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
262 public function fetchObject( $res ) {
263 if ( $res instanceof ResultWrapper
) {
266 Wikimedia\
suppressWarnings();
267 $row = pg_fetch_object( $res );
268 Wikimedia\restoreWarnings
();
269 # @todo FIXME: HACK HACK HACK HACK debug
271 # @todo hashar: not sure if the following test really trigger if the object
273 $conn = $this->getBindingHandle();
274 if ( pg_last_error( $conn ) ) {
275 throw new DBUnexpectedError(
277 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
284 public function fetchRow( $res ) {
285 if ( $res instanceof ResultWrapper
) {
288 Wikimedia\
suppressWarnings();
289 $row = pg_fetch_array( $res );
290 Wikimedia\restoreWarnings
();
292 $conn = $this->getBindingHandle();
293 if ( pg_last_error( $conn ) ) {
294 throw new DBUnexpectedError(
296 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
303 public function numRows( $res ) {
304 if ( $res instanceof ResultWrapper
) {
307 Wikimedia\
suppressWarnings();
308 $n = pg_num_rows( $res );
309 Wikimedia\restoreWarnings
();
311 $conn = $this->getBindingHandle();
312 if ( pg_last_error( $conn ) ) {
313 throw new DBUnexpectedError(
315 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
322 public function numFields( $res ) {
323 if ( $res instanceof ResultWrapper
) {
327 return pg_num_fields( $res );
330 public function fieldName( $res, $n ) {
331 if ( $res instanceof ResultWrapper
) {
335 return pg_field_name( $res, $n );
338 public function insertId() {
339 $res = $this->query( "SELECT lastval()" );
340 $row = $this->fetchRow( $res );
341 return is_null( $row[0] ) ?
null : (int)$row[0];
344 public function dataSeek( $res, $row ) {
345 if ( $res instanceof ResultWrapper
) {
349 return pg_result_seek( $res, $row );
352 public function lastError() {
354 if ( $this->lastResultHandle
) {
355 return pg_result_error( $this->lastResultHandle
);
357 return pg_last_error();
361 return $this->getLastPHPError() ?
: 'No database connection';
364 public function lastErrno() {
365 if ( $this->lastResultHandle
) {
366 return pg_result_error_field( $this->lastResultHandle
, PGSQL_DIAG_SQLSTATE
);
372 protected function fetchAffectedRowCount() {
373 if ( !$this->lastResultHandle
) {
377 return pg_affected_rows( $this->lastResultHandle
);
381 * Estimate rows in dataset
382 * Returns estimated count, based on EXPLAIN output
383 * This is not necessarily an accurate estimate, so use sparingly
384 * Returns -1 if count cannot be found
385 * Takes same arguments as Database::select()
387 * @param string $table
389 * @param string $conds
390 * @param string $fname
391 * @param array $options
392 * @param array $join_conds
395 public function estimateRowCount( $table, $var = '*', $conds = '',
396 $fname = __METHOD__
, $options = [], $join_conds = []
398 $conds = $this->normalizeConditions( $conds, $fname );
399 $column = $this->extractSingleFieldFromList( $var );
400 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
401 $conds[] = "$column IS NOT NULL";
404 $options['EXPLAIN'] = true;
405 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
408 $row = $this->fetchRow( $res );
410 if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
411 $rows = (int)$count[1];
418 public function indexInfo( $table, $index, $fname = __METHOD__
) {
419 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
420 $res = $this->query( $sql, $fname );
424 foreach ( $res as $row ) {
425 if ( $row->indexname
== $this->indexName( $index ) ) {
433 public function indexAttributes( $index, $schema = false ) {
434 if ( $schema === false ) {
435 $schemas = $this->getCoreSchemas();
437 $schemas = [ $schema ];
440 $eindex = $this->addQuotes( $index );
442 foreach ( $schemas as $schema ) {
443 $eschema = $this->addQuotes( $schema );
445 * A subquery would be not needed if we didn't care about the order
446 * of attributes, but we do
448 $sql = <<<__INDEXATTR__
452 i.indoption[s.g] as option,
455 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
459 ON cis.oid=isub.indexrelid
461 ON cis.relnamespace = ns.oid
462 WHERE cis.relname=$eindex AND ns.nspname=$eschema) AS s,
468 ON ci.oid=i.indexrelid
470 ON ct.oid = i.indrelid
472 ON ci.relnamespace = n.oid
474 ci.relname=$eindex AND n.nspname=$eschema
475 AND attrelid = ct.oid
476 AND i.indkey[s.g] = attnum
477 AND i.indclass[s.g] = opcls.oid
478 AND pg_am.oid = opcls.opcmethod
480 $res = $this->query( $sql, __METHOD__ );
483 foreach ( $res as $row ) {
496 public function indexUnique( $table, $index, $fname = __METHOD__ ) {
497 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
498 " AND indexdef LIKE 'CREATE UNIQUE%(" .
499 $this->strencode( $this->indexName( $index ) ) .
501 $res = $this->query( $sql, $fname );
506 return $res->numRows() > 0;
509 public function selectSQLText(
510 $table, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
512 if ( is_string( $options ) ) {
513 $options = [ $options ];
516 // Change the FOR UPDATE option as necessary based on the join conditions. Then pass
517 // to the parent function to get the actual SQL text.
518 // In Postgres when using FOR UPDATE, only the main table and tables that are inner joined
519 // can be locked. That means tables in an outer join cannot be FOR UPDATE locked. Trying to
520 // do so causes a DB error. This wrapper checks which tables can be locked and adjusts it
522 // MySQL uses "ORDER BY NULL" as an optimization hint, but that is illegal in PostgreSQL.
523 if ( is_array( $options ) ) {
524 $forUpdateKey = array_search( 'FOR UPDATE', $options, true );
525 if ( $forUpdateKey !== false && $join_conds ) {
526 unset( $options[$forUpdateKey] );
527 $options['FOR UPDATE'] = [];
532 $alias = key( $toCheck );
533 $name = $toCheck[$alias];
534 unset( $toCheck[$alias] );
536 $hasAlias = !is_numeric( $alias );
537 if ( !$hasAlias && is_string( $name ) ) {
541 if ( !isset( $join_conds[$alias] ) ||
542 !preg_match( '/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_conds[$alias][0] )
544 if ( is_array( $name ) ) {
545 // It's a parenthesized group, process all the tables inside the group.
546 $toCheck = array_merge( $toCheck, $name );
548 // Quote alias names so $this->tableName() won't mangle them
549 $options['FOR UPDATE'][] = $hasAlias ? $this->addIdentifierQuotes( $alias ) : $alias;
555 if ( isset( $options['ORDER BY'] ) && $options['ORDER BY'] == 'NULL' ) {
556 unset( $options['ORDER BY'] );
560 return parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
564 public function insert( $table, $args, $fname = __METHOD__, $options = [] ) {
565 if ( !count( $args ) ) {
569 $table = $this->tableName( $table );
570 if ( !isset( $this->numericVersion ) ) {
571 $this->getServerVersion();
574 if ( !is_array( $options ) ) {
575 $options = [ $options ];
578 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
580 $keys = array_keys( $args[0] );
583 $keys = array_keys( $args );
586 $ignore = in_array( 'IGNORE', $options );
588 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
590 if ( $this->numericVersion >= 9.5 || !$ignore ) {
591 // No IGNORE or our PG has "ON CONFLICT DO NOTHING"
593 foreach ( $rows as $row ) {
599 $sql .= '(' . $this->makeList( $row ) . ')';
602 $sql .= ' ON CONFLICT DO NOTHING';
604 $this->query( $sql, $fname );
606 // Emulate IGNORE by doing each row individually, with savepoints
607 // to roll back as necessary.
608 $numrowsinserted = 0;
610 $tok = $this->startAtomic( "$fname (outer)", self::ATOMIC_CANCELABLE );
612 foreach ( $rows as $row ) {
614 $tempsql .= '(' . $this->makeList( $row ) . ')';
616 $this->startAtomic( "$fname (inner)", self::ATOMIC_CANCELABLE );
618 $this->query( $tempsql, $fname );
619 $this->endAtomic( "$fname (inner)" );
621 } catch ( DBQueryError $e ) {
622 $this->cancelAtomic( "$fname (inner)" );
623 // Our IGNORE is supposed to ignore duplicate key errors, but not others.
624 // (even though MySQL's version apparently ignores all errors)
625 if ( $e->errno !== '23505' ) {
630 } catch ( Exception $e ) {
631 $this->cancelAtomic( "$fname (outer)", $tok );
634 $this->endAtomic( "$fname (outer)" );
636 // Set the affected row count for the whole operation
637 $this->affectedRowCount = $numrowsinserted;
644 * INSERT SELECT wrapper
645 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
646 * Source items may be literals rather then field names, but strings should
647 * be quoted with Database::addQuotes()
648 * $conds may be "*" to copy the whole table
649 * srcTable may be an array of tables.
650 * @todo FIXME: Implement this a little better (seperate select/insert)?
652 * @param string $destTable
653 * @param array|string $srcTable
654 * @param array $varMap
655 * @param array $conds
656 * @param string $fname
657 * @param array $insertOptions
658 * @param array $selectOptions
659 * @param array $selectJoinConds
662 public function nativeInsertSelect(
663 $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
664 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
666 if ( !is_array( $insertOptions ) ) {
667 $insertOptions = [ $insertOptions ];
670 if ( in_array( 'IGNORE', $insertOptions ) ) {
671 if ( $this->getServerVersion() >= 9.5 ) {
672 // Use ON CONFLICT DO NOTHING if we have it for IGNORE
673 $destTable = $this->tableName( $destTable );
675 $selectSql = $this->selectSQLText(
677 array_values( $varMap ),
684 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
685 $selectSql . ' ON CONFLICT DO NOTHING';
687 return $this->query( $sql, $fname );
689 // IGNORE and we don't have ON CONFLICT DO NOTHING, so just use the non-native version
690 return $this->nonNativeInsertSelect(
691 $destTable, $srcTable, $varMap, $conds, $fname,
692 $insertOptions, $selectOptions, $selectJoinConds
697 return parent::nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname,
698 $insertOptions, $selectOptions, $selectJoinConds );
701 public function tableName( $name, $format = 'quoted' ) {
702 // Replace reserved words with better ones
703 $name = $this->remappedTableName( $name );
705 return parent::tableName( $name, $format );
709 * @param string $name
710 * @return string Value of $name or remapped name if $name is a reserved keyword
712 public function remappedTableName( $name ) {
713 return isset( $this->keywordTableMap[$name] ) ? $this->keywordTableMap[$name] : $name;
717 * @param string $name
718 * @param string $format
719 * @return string Qualified and encoded (if requested) table name
721 public function realTableName( $name, $format = 'quoted' ) {
722 return parent::tableName( $name, $format );
725 public function nextSequenceValue( $seqName ) {
726 return new NextSequenceValue;
730 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
732 * @param string $seqName
735 public function currentSequenceValue( $seqName ) {
736 $safeseq = str_replace( "'", "''", $seqName );
737 $res = $this->query( "SELECT currval('$safeseq')" );
738 $row = $this->fetchRow( $res );
744 public function textFieldSize( $table, $field ) {
745 $table = $this->tableName( $table );
746 $sql = "SELECT t.typname as ftype,a.atttypmod as size
747 FROM pg_class c, pg_attribute a, pg_type t
748 WHERE relname='$table' AND a.attrelid=c.oid AND
749 a.atttypid=t.oid and a.attname='$field'";
750 $res = $this->query( $sql );
751 $row = $this->fetchObject( $res );
752 if ( $row->ftype == 'varchar' ) {
753 $size = $row->size - 4;
761 public function limitResult( $sql, $limit, $offset = false ) {
762 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
765 public function wasDeadlock() {
766 // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
767 return $this->lastErrno() === '40P01';
770 public function wasLockTimeout() {
771 // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
772 return $this->lastErrno() === '55P03';
775 public function wasConnectionError( $errno ) {
776 // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
777 static $codes = [ '08000', '08003', '08006', '08001', '08004', '57P01', '57P03', '53300' ];
779 return in_array( $errno, $codes, true );
782 protected function wasKnownStatementRollbackError() {
783 return false; // transaction has to be rolled-back from error state
786 public function duplicateTableStructure(
787 $oldName, $newName, $temporary = false, $fname = __METHOD__
789 $newNameE = $this->addIdentifierQuotes( $newName );
790 $oldNameE = $this->addIdentifierQuotes( $oldName );
792 $temporary = $temporary ? 'TEMPORARY' : '';
794 $ret = $this->query( "CREATE $temporary TABLE $newNameE " .
795 "(LIKE $oldNameE INCLUDING DEFAULTS INCLUDING INDEXES)", $fname );
800 $res = $this->query( 'SELECT attname FROM pg_class c'
801 . ' JOIN pg_namespace n ON (n.oid = c.relnamespace)'
802 . ' JOIN pg_attribute a ON (a.attrelid = c.oid)'
803 . ' JOIN pg_attrdef d ON (c.oid=d.adrelid and a.attnum=d.adnum)'
804 . ' WHERE relkind = \'r\''
805 . ' AND nspname = ' . $this->addQuotes( $this->getCoreSchema() )
806 . ' AND relname = ' . $this->addQuotes( $oldName )
807 . ' AND adsrc LIKE \'nextval(%\'',
810 $row = $this->fetchObject( $res );
812 $field = $row->attname;
813 $newSeq = "{$newName}_{$field}_seq";
814 $fieldE = $this->addIdentifierQuotes( $field );
815 $newSeqE = $this->addIdentifierQuotes( $newSeq );
816 $newSeqQ = $this->addQuotes( $newSeq );
817 $this->query( "CREATE $temporary SEQUENCE $newSeqE OWNED BY $newNameE.$fieldE", $fname );
819 "ALTER TABLE $newNameE ALTER COLUMN $fieldE SET DEFAULT nextval({$newSeqQ}::regclass)",
827 public function resetSequenceForTable( $table, $fname = __METHOD__ ) {
828 $table = $this->tableName( $table, 'raw' );
829 foreach ( $this->getCoreSchemas() as $schema ) {
831 'SELECT c.oid FROM pg_class c JOIN pg_namespace n ON (n.oid = c.relnamespace)'
832 . ' WHERE relkind = \'r\''
833 . ' AND nspname = ' . $this->addQuotes( $schema )
834 . ' AND relname = ' . $this->addQuotes( $table ),
837 if ( !$res || !$this->numRows( $res ) ) {
841 $oid = $this->fetchObject( $res )->oid;
842 $res = $this->query( 'SELECT adsrc FROM pg_attribute a'
843 . ' JOIN pg_attrdef d ON (a.attrelid=d.adrelid and a.attnum=d.adnum)'
844 . " WHERE a.attrelid = $oid"
845 . ' AND adsrc LIKE \'nextval(%\'',
848 $row = $this->fetchObject( $res );
851 'SELECT ' . preg_replace( '/^nextval\((.+)\)$/', 'setval($1,1,false)', $row->adsrc ),
862 public function listTables( $prefix = null, $fname = __METHOD__ ) {
863 $eschemas = implode( ',', array_map( [ $this, 'addQuotes' ], $this->getCoreSchemas() ) );
864 $result = $this->query(
865 "SELECT DISTINCT tablename FROM pg_tables WHERE schemaname IN ($eschemas)", $fname );
868 foreach ( $result as $table ) {
869 $vars = get_object_vars( $table );
870 $table = array_pop( $vars );
871 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
872 $endArray[] = $table;
879 public function timestamp( $ts = 0 ) {
880 $ct = new ConvertibleTimestamp( $ts );
882 return $ct->getTimestamp( TS_POSTGRES );
886 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
887 * to https://secure.php.net/manual/en/ref.pgsql.php
889 * Parsing a postgres array can be a tricky problem, he's my
890 * take on this, it handles multi-dimensional arrays plus
891 * escaping using a nasty regexp to determine the limits of each
894 * This should really be handled by PHP PostgreSQL module
897 * @param string $text Postgreql array returned in a text form like {a,b}
898 * @param string[] $output
899 * @param int|bool $limit
903 private function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
904 if ( false === $limit ) {
905 $limit = strlen( $text ) - 1;
908 if ( '{}' == $text ) {
912 if ( '{' != $text[$offset] ) {
913 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
914 $text, $match, 0, $offset );
915 $offset += strlen( $match[0] );
916 $output[] = ( '"' != $match[1][0]
918 : stripcslashes( substr( $match[1], 1, -1 ) ) );
919 if ( '},' == $match[3] ) {
923 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
925 } while ( $limit > $offset );
930 public function aggregateValue( $valuedata, $valuename = 'value' ) {
934 public function getSoftwareLink() {
935 return '[{{int:version-db-postgres-url}} PostgreSQL]';
939 * Return current schema (executes SELECT current_schema())
943 * @return string Default schema for the current session
945 public function getCurrentSchema() {
946 $res = $this->query( "SELECT current_schema()", __METHOD__ );
947 $row = $this->fetchRow( $res );
953 * Return list of schemas which are accessible without schema name
954 * This is list does not contain magic keywords like "$user"
957 * @see getSearchPath()
958 * @see setSearchPath()
960 * @return array List of actual schemas for the current sesson
962 public function getSchemas() {
963 $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
964 $row = $this->fetchRow( $res );
967 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
969 return $this->pg_array_parse( $row[0], $schemas );
973 * Return search patch for schemas
974 * This is different from getSchemas() since it contain magic keywords
979 * @return array How to search for table names schemas for the current user
981 public function getSearchPath() {
982 $res = $this->query( "SHOW search_path", __METHOD__ );
983 $row = $this->fetchRow( $res );
985 /* PostgreSQL returns SHOW values as strings */
987 return explode( ",", $row[0] );
991 * Update search_path, values should already be sanitized
992 * Values may contain magic keywords like "$user"
995 * @param array $search_path List of schemas to be searched by default
997 private function setSearchPath( $search_path ) {
998 $this->query( "SET search_path = " . implode( ", ", $search_path ) );
1002 * Determine default schema for the current application
1003 * Adjust this session schema search path if desired schema exists
1004 * and is not alread there.
1006 * We need to have name of the core schema stored to be able
1007 * to query database metadata.
1009 * This will be also called by the installer after the schema is created
1013 * @param string $desiredSchema
1015 public function determineCoreSchema( $desiredSchema ) {
1016 $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
1017 if ( $this->schemaExists( $desiredSchema ) ) {
1018 if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
1019 $this->coreSchema = $desiredSchema;
1020 $this->queryLogger->debug(
1021 "Schema \"" . $desiredSchema . "\" already in the search path\n" );
1024 * Prepend our schema (e.g. 'mediawiki') in front
1025 * of the search path
1028 $search_path = $this->getSearchPath();
1029 array_unshift( $search_path,
1030 $this->addIdentifierQuotes( $desiredSchema ) );
1031 $this->setSearchPath( $search_path );
1032 $this->coreSchema = $desiredSchema;
1033 $this->queryLogger->debug(
1034 "Schema \"" . $desiredSchema . "\" added to the search path\n" );
1037 $this->coreSchema = $this->getCurrentSchema();
1038 $this->queryLogger->debug(
1039 "Schema \"" . $desiredSchema . "\" not found, using current \"" .
1040 $this->coreSchema . "\"\n" );
1042 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1043 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
1047 * Return schema name for core application tables
1050 * @return string Core schema name
1052 public function getCoreSchema() {
1053 return $this->coreSchema;
1057 * Return schema names for temporary tables and core application tables
1060 * @return string[] schema names
1062 public function getCoreSchemas() {
1063 if ( $this->tempSchema ) {
1064 return [ $this->tempSchema, $this->getCoreSchema() ];
1067 $res = $this->query(
1068 "SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = pg_my_temp_schema()", __METHOD__
1070 $row = $this->fetchObject( $res );
1072 $this->tempSchema = $row->nspname;
1073 return [ $this->tempSchema, $this->getCoreSchema() ];
1076 return [ $this->getCoreSchema() ];
1079 public function getServerVersion() {
1080 if ( !isset( $this->numericVersion ) ) {
1081 $conn = $this->getBindingHandle();
1082 $versionInfo = pg_version( $conn );
1083 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1084 // Old client, abort install
1085 $this->numericVersion = '7.3 or earlier';
1086 } elseif ( isset( $versionInfo['server'] ) ) {
1088 $this->numericVersion = $versionInfo['server'];
1090 // T18937: broken pgsql extension from PHP<5.3
1091 $this->numericVersion = pg_parameter_status( $conn, 'server_version' );
1095 return $this->numericVersion;
1099 * Query whether a given relation exists (in the given schema, or the
1100 * default mw one if not given)
1101 * @param string $table
1102 * @param array|string $types
1103 * @param bool|string $schema
1106 private function relationExists( $table, $types, $schema = false ) {
1107 if ( !is_array( $types ) ) {
1108 $types = [ $types ];
1110 if ( $schema === false ) {
1111 $schemas = $this->getCoreSchemas();
1113 $schemas = [ $schema ];
1115 $table = $this->realTableName( $table, 'raw' );
1116 $etable = $this->addQuotes( $table );
1117 foreach ( $schemas as $schema ) {
1118 $eschema = $this->addQuotes( $schema );
1119 $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1120 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1121 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1122 $res = $this->query( $sql );
1123 if ( $res && $res->numRows() ) {
1132 * For backward compatibility, this function checks both tables and views.
1133 * @param string $table
1134 * @param string $fname
1135 * @param bool|string $schema
1138 public function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1139 return $this->relationExists( $table, [ 'r', 'v' ], $schema );
1142 public function sequenceExists( $sequence, $schema = false ) {
1143 return $this->relationExists( $sequence, 'S', $schema );
1146 public function triggerExists( $table, $trigger ) {
1148 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1149 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1150 AND tgrelid=pg_class.oid
1151 AND nspname=%s AND relname=%s AND tgname=%s
1153 foreach ( $this->getCoreSchemas() as $schema ) {
1154 $res = $this->query(
1157 $this->addQuotes( $schema ),
1158 $this->addQuotes( $table ),
1159 $this->addQuotes( $trigger )
1162 if ( $res && $res->numRows() ) {
1170 public function ruleExists( $table, $rule ) {
1171 $exists = $this->selectField( 'pg_rules', 'rulename',
1173 'rulename' => $rule,
1174 'tablename' => $table,
1175 'schemaname' => $this->getCoreSchemas()
1179 return $exists === $rule;
1182 public function constraintExists( $table, $constraint ) {
1183 foreach ( $this->getCoreSchemas() as $schema ) {
1184 $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1185 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1186 $this->addQuotes( $schema ),
1187 $this->addQuotes( $table ),
1188 $this->addQuotes( $constraint )
1190 $res = $this->query( $sql );
1191 if ( $res && $res->numRows() ) {
1199 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1200 * @param string $schema
1203 public function schemaExists( $schema ) {
1204 if ( !strlen( $schema ) ) {
1205 return false; // short-circuit
1208 $exists = $this->selectField(
1209 '"pg_catalog"."pg_namespace"', 1, [ 'nspname' => $schema ], __METHOD__ );
1211 return (bool)$exists;
1215 * Returns true if a given role (i.e. user) exists, false otherwise.
1216 * @param string $roleName
1219 public function roleExists( $roleName ) {
1220 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1221 [ 'rolname' => $roleName ], __METHOD__ );
1223 return (bool)$exists;
1227 * @param string $table
1228 * @param string $field
1229 * @return PostgresField|null
1231 public function fieldInfo( $table, $field ) {
1232 return PostgresField::fromText( $this, $table, $field );
1236 * pg_field_type() wrapper
1237 * @param ResultWrapper|resource $res ResultWrapper or PostgreSQL query result resource
1238 * @param int $index Field number, starting from 0
1241 public function fieldType( $res, $index ) {
1242 if ( $res instanceof ResultWrapper ) {
1243 $res = $res->result;
1246 return pg_field_type( $res, $index );
1249 public function encodeBlob( $b ) {
1250 return new PostgresBlob( pg_escape_bytea( $b ) );
1253 public function decodeBlob( $b ) {
1254 if ( $b instanceof PostgresBlob ) {
1256 } elseif ( $b instanceof Blob ) {
1260 return pg_unescape_bytea( $b );
1263 public function strencode( $s ) {
1264 // Should not be called by us
1265 return pg_escape_string( $this->getBindingHandle(), (string)$s );
1268 public function addQuotes( $s ) {
1269 $conn = $this->getBindingHandle();
1271 if ( is_null( $s ) ) {
1273 } elseif ( is_bool( $s ) ) {
1274 return intval( $s );
1275 } elseif ( $s instanceof Blob ) {
1276 if ( $s instanceof PostgresBlob ) {
1279 $s = pg_escape_bytea( $conn, $s->fetch() );
1282 } elseif ( $s instanceof NextSequenceValue ) {
1286 return "'" . pg_escape_string( $conn, (string)$s ) . "'";
1289 public function makeSelectOptions( $options ) {
1290 $preLimitTail = $postLimitTail = '';
1291 $startOpts = $useIndex = $ignoreIndex = '';
1294 foreach ( $options as $key => $option ) {
1295 if ( is_numeric( $key ) ) {
1296 $noKeyOptions[$option] = true;
1300 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1302 $preLimitTail .= $this->makeOrderBy( $options );
1304 if ( isset( $options['FOR UPDATE'] ) ) {
1305 $postLimitTail .= ' FOR UPDATE OF ' .
1306 implode( ', ', array_map( [ $this, 'tableName' ], $options['FOR UPDATE'] ) );
1307 } elseif ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1308 $postLimitTail .= ' FOR UPDATE';
1311 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1312 $startOpts .= 'DISTINCT';
1315 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1318 public function getDBname() {
1319 return $this->dbName;
1322 public function getServer() {
1323 return $this->server;
1326 public function buildConcat( $stringList ) {
1327 return implode( ' || ', $stringList );
1330 public function buildGroupConcatField(
1331 $delimiter, $table, $field, $conds = '', $options = [], $join_conds = []
1333 $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1335 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1338 public function buildStringCast( $field ) {
1339 return $field . '::text';
1342 public function streamStatementEnd( &$sql, &$newLine ) {
1343 # Allow dollar quoting for function declarations
1344 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1345 if ( $this->delimiter ) {
1346 $this->delimiter = false;
1348 $this->delimiter = ';';
1352 return parent::streamStatementEnd( $sql, $newLine );
1355 public function doLockTables( array $read, array $write, $method ) {
1357 foreach ( $write as $table ) {
1358 $tablesWrite[] = $this->tableName( $table );
1361 foreach ( $read as $table ) {
1362 $tablesRead[] = $this->tableName( $table );
1365 // Acquire locks for the duration of the current transaction...
1366 if ( $tablesWrite ) {
1368 'LOCK TABLE ONLY ' . implode( ',', $tablesWrite ) . ' IN EXCLUSIVE MODE',
1372 if ( $tablesRead ) {
1374 'LOCK TABLE ONLY ' . implode( ',', $tablesRead ) . ' IN SHARE MODE',
1382 public function lockIsFree( $lockName, $method ) {
1383 if ( !parent::lockIsFree( $lockName, $method ) ) {
1384 return false; // already held
1386 // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1387 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1388 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1389 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1390 $row = $this->fetchObject( $result );
1392 return ( $row->lockstatus === 't' );
1395 public function lock( $lockName, $method, $timeout = 5 ) {
1396 // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1397 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1398 $loop = new WaitConditionLoop(
1399 function () use ( $lockName, $key, $timeout, $method ) {
1400 $res = $this->query( "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1401 $row = $this->fetchObject( $res );
1402 if ( $row->lockstatus === 't' ) {
1403 parent::lock( $lockName, $method, $timeout ); // record
1407 return WaitConditionLoop::CONDITION_CONTINUE;
1412 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1415 public function unlock( $lockName, $method ) {
1416 // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1417 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1418 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1419 $row = $this->fetchObject( $result );
1421 if ( $row->lockstatus === 't' ) {
1422 parent::unlock( $lockName, $method ); // record
1426 $this->queryLogger->debug( __METHOD__ . " failed to release lock\n" );
1431 public function serverIsReadOnly() {
1432 $res = $this->query( "SHOW default_transaction_read_only", __METHOD__ );
1433 $row = $this->fetchObject( $res );
1435 return $row ? ( strtolower( $row->default_transaction_read_only ) === 'on' ) : false;
1439 * @param string $lockName
1440 * @return string Integer
1442 private function bigintFromLockName( $lockName ) {
1443 return \Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1447 class_alias( DatabasePostgres::class, 'DatabasePostgres' );