3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 // Suppress UnusedPluginSuppression because Phan on PHP 7.4 and PHP 8.1 need different suppressions
22 // @phan-file-suppress UnusedPluginSuppression,UnusedPluginFileSuppression
24 namespace Wikimedia\Rdbms
;
27 use Wikimedia\Rdbms\Platform\PostgresPlatform
;
28 use Wikimedia\Rdbms\Replication\ReplicationReporter
;
29 use Wikimedia\WaitConditionLoop
;
32 * Postgres database abstraction layer.
36 class DatabasePostgres
extends Database
{
41 /** @var float|string|null */
42 private $numericVersion;
44 /** @var resource|null */
45 private $lastResultHandle;
47 /** @var PostgresPlatform */
51 * @see Database::__construct()
52 * @param array $params Additional parameters include:
53 * - port: A port to append to the hostname
55 public function __construct( array $params ) {
56 $this->port
= intval( $params['port'] ??
null );
57 parent
::__construct( $params );
59 $this->platform
= new PostgresPlatform(
65 $this->replicationReporter
= new ReplicationReporter(
66 $params['topologyRole'],
72 public function getType() {
76 protected function open( $server, $user, $password, $db, $schema, $tablePrefix ) {
77 if ( !function_exists( 'pg_connect' ) ) {
78 throw $this->newExceptionAfterConnectError(
79 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
80 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
81 "webserver and database)"
85 $this->close( __METHOD__
);
88 // A database must be specified in order to connect to Postgres. If $dbName is not
89 // specified, then use the standard "postgres" database that should exist by default.
90 'dbname' => ( $db !== null && $db !== '' ) ?
$db : 'postgres',
92 'password' => $password
94 if ( $server !== null && $server !== '' ) {
95 $connectVars['host'] = $server;
97 if ( $this->port
> 0 ) {
98 $connectVars['port'] = $this->port
;
101 $connectVars['sslmode'] = 'require';
103 $connectString = $this->makeConnectionString( $connectVars );
105 $this->installErrorHandler();
107 $this->conn
= pg_connect( $connectString, PGSQL_CONNECT_FORCE_NEW
) ?
: null;
108 } catch ( RuntimeException
$e ) {
109 $this->restoreErrorHandler();
110 throw $this->newExceptionAfterConnectError( $e->getMessage() );
112 $error = $this->restoreErrorHandler();
114 if ( !$this->conn
) {
115 throw $this->newExceptionAfterConnectError( $error ?
: $this->lastError() );
119 // Since no transaction is active at this point, any SET commands should apply
120 // for the entire session (e.g. will not be reverted on transaction rollback).
121 // See https://www.postgresql.org/docs/8.3/sql-set.html
123 'client_encoding' => 'UTF8',
124 'datestyle' => 'ISO, YMD',
126 'standard_conforming_strings' => 'on',
127 'bytea_output' => 'escape',
128 'client_min_messages' => 'ERROR'
130 foreach ( $variables as $var => $val ) {
131 $sql = 'SET ' . $this->platform
->addIdentifierQuotes( $var ) . ' = ' . $this->addQuotes( $val );
132 $query = new Query( $sql, self
::QUERY_NO_RETRY | self
::QUERY_CHANGE_TRX
, 'SET' );
133 $this->query( $query, __METHOD__
);
135 $this->determineCoreSchema( $schema );
136 $this->currentDomain
= new DatabaseDomain( $db, $schema, $tablePrefix );
137 $this->platform
->setCurrentDomain( $this->currentDomain
);
138 } catch ( RuntimeException
$e ) {
139 throw $this->newExceptionAfterConnectError( $e->getMessage() );
143 public function databasesAreIndependent() {
147 public function doSelectDomain( DatabaseDomain
$domain ) {
148 $database = $domain->getDatabase();
149 if ( $database === null ) {
150 // A null database means "don't care" so leave it as is and update the table prefix
151 $this->currentDomain
= new DatabaseDomain(
152 $this->currentDomain
->getDatabase(),
153 $domain->getSchema() ??
$this->currentDomain
->getSchema(),
154 $domain->getTablePrefix()
156 $this->platform
->setCurrentDomain( $this->currentDomain
);
157 } elseif ( $this->getDBname() !== $database ) {
158 // Postgres doesn't support selectDB in the same way MySQL does.
159 // So if the DB name doesn't match the open connection, open a new one
161 $this->connectionParams
[self
::CONN_HOST
],
162 $this->connectionParams
[self
::CONN_USER
],
163 $this->connectionParams
[self
::CONN_PASSWORD
],
165 $domain->getSchema(),
166 $domain->getTablePrefix()
169 $this->currentDomain
= $domain;
170 $this->platform
->setCurrentDomain( $domain );
177 * @param string[] $vars
180 private function makeConnectionString( $vars ) {
182 foreach ( $vars as $name => $value ) {
183 $s .= "$name='" . str_replace( [ "\\", "'" ], [ "\\\\", "\\'" ], $value ) . "' ";
189 protected function closeConnection() {
190 return $this->conn ?
pg_close( $this->conn
) : true;
193 public function doSingleStatementQuery( string $sql ): QueryStatus
{
194 $conn = $this->getBindingHandle();
196 $sql = mb_convert_encoding( $sql, 'UTF-8' );
197 // Clear any previously left over result
198 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
199 while ( $priorRes = pg_get_result( $conn ) ) {
200 pg_free_result( $priorRes );
203 if ( pg_send_query( $conn, $sql ) === false ) {
204 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
207 // Newer PHP versions use PgSql\Result instead of resource variables
208 // https://www.php.net/manual/en/function.pg-get-result.php
209 $pgRes = pg_get_result( $conn );
210 // Phan on PHP 7.4 and PHP 8.1 need different suppressions
211 // @phan-suppress-next-line PhanTypeMismatchProperty,PhanTypeMismatchPropertyProbablyReal
212 $this->lastResultHandle
= $pgRes;
213 $res = pg_result_error( $pgRes ) ?
false : $pgRes;
215 return new QueryStatus(
216 // @phan-suppress-next-line PhanTypeMismatchArgument
217 is_bool( $res ) ?
$res : new PostgresResultWrapper( $this, $conn, $res ),
218 $pgRes ?
pg_affected_rows( $pgRes ) : 0,
224 protected function dumpError() {
228 PGSQL_DIAG_MESSAGE_PRIMARY
,
229 PGSQL_DIAG_MESSAGE_DETAIL
,
230 PGSQL_DIAG_MESSAGE_HINT
,
231 PGSQL_DIAG_STATEMENT_POSITION
,
232 PGSQL_DIAG_INTERNAL_POSITION
,
233 PGSQL_DIAG_INTERNAL_QUERY
,
235 PGSQL_DIAG_SOURCE_FILE
,
236 PGSQL_DIAG_SOURCE_LINE
,
237 PGSQL_DIAG_SOURCE_FUNCTION
239 foreach ( $diags as $d ) {
240 $this->logger
->debug( sprintf( "PgSQL ERROR(%d): %s",
241 // @phan-suppress-next-line PhanTypeMismatchArgumentInternal
242 $d, pg_result_error_field( $this->lastResultHandle
, $d ) ) );
246 protected function lastInsertId() {
247 // Avoid using query() to prevent unwanted side-effects like changing affected
248 // row counts or connection retries. Note that lastval() is connection-specific.
249 // Note that this causes "lastval is not yet defined in this session" errors if
250 // nextval() was never directly or implicitly triggered (error out any transaction).
251 $qs = $this->doSingleStatementQuery( "SELECT lastval() AS id" );
253 return $qs->res ?
(int)$qs->res
->fetchRow()['id'] : 0;
256 public function lastError() {
258 if ( $this->lastResultHandle
) {
259 // @phan-suppress-next-line PhanTypeMismatchArgumentInternal
260 return pg_result_error( $this->lastResultHandle
);
262 return pg_last_error() ?
: $this->lastConnectError
;
266 return $this->getLastPHPError() ?
: 'No database connection';
269 public function lastErrno() {
270 if ( $this->lastResultHandle
) {
271 // @phan-suppress-next-line PhanTypeMismatchArgumentInternal
272 $lastErrno = pg_result_error_field( $this->lastResultHandle
, PGSQL_DIAG_SQLSTATE
);
273 if ( $lastErrno !== false ) {
281 public function estimateRowCount( $table, $var = '*', $conds = '',
282 $fname = __METHOD__
, $options = [], $join_conds = []
284 $conds = $this->platform
->normalizeConditions( $conds, $fname );
285 $column = $this->platform
->extractSingleFieldFromList( $var );
286 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
287 $conds[] = "$column IS NOT NULL";
290 $options['EXPLAIN'] = true;
291 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
294 $row = $res->fetchRow();
296 if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
297 $rows = (int)$count[1];
304 public function indexInfo( $table, $index, $fname = __METHOD__
) {
305 $components = $this->platform
->qualifiedTableComponents( $table );
306 if ( count( $components ) === 1 ) {
307 $schema = $this->getCoreSchema();
308 $tableComponent = $components[0];
309 } elseif ( count( $components ) === 2 ) {
310 [ $schema, $tableComponent ] = $components;
312 [ , $schema, $tableComponent ] = $components;
314 $encSchema = $this->addQuotes( $schema );
315 $encTable = $this->addQuotes( $tableComponent );
316 $encIndex = $this->addQuotes( $this->platform
->indexName( $index ) );
318 "SELECT indexname,indexdef FROM pg_indexes " .
319 "WHERE schemaname=$encSchema AND tablename=$encTable AND indexname=$encIndex",
320 self
::QUERY_IGNORE_DBO_TRX | self
::QUERY_CHANGE_NONE
,
323 $res = $this->query( $query );
324 $row = $res->fetchObject();
327 return [ 'unique' => ( strpos( $row->indexdef
, 'CREATE UNIQUE ' ) === 0 ) ];
333 public function indexAttributes( $index, $schema = false ) {
334 if ( $schema === false ) {
335 $schemas = $this->getCoreSchemas();
337 $schemas = [ $schema ];
340 $eindex = $this->addQuotes( $index );
342 $flags = self
::QUERY_IGNORE_DBO_TRX | self
::QUERY_CHANGE_NONE
;
343 foreach ( $schemas as $schema ) {
344 $eschema = $this->addQuotes( $schema );
346 * A subquery would be not needed if we didn't care about the order
347 * of attributes, but we do
349 $sql = <<<__INDEXATTR__
353 i.indoption[s.g] as option,
356 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
360 ON cis.oid=isub.indexrelid
362 ON cis.relnamespace = ns.oid
363 WHERE cis.relname=$eindex AND ns.nspname=$eschema) AS s,
369 ON ci.oid=i.indexrelid
371 ON ct.oid = i.indrelid
373 ON ci.relnamespace = n.oid
375 ci.relname=$eindex AND n.nspname=$eschema
376 AND attrelid = ct.oid
377 AND i.indkey[s.g] = attnum
378 AND i.indclass[s.g] = opcls.oid
379 AND pg_am.oid = opcls.opcmethod
381 $query = new Query( $sql, $flags, 'SELECT' );
382 $res = $this->query( $query, __METHOD__ );
385 foreach ( $res as $row ) {
398 protected function doInsertSelectNative(
404 array $insertOptions,
405 array $selectOptions,
408 if ( in_array( 'IGNORE', $insertOptions ) ) {
409 // Use "ON CONFLICT DO" if we have it for IGNORE
410 $destTableEnc = $this->tableName( $destTable );
412 $selectSql = $this->selectSQLText(
414 array_values( $varMap ),
421 $sql = "INSERT INTO $destTableEnc (" . implode( ',', array_keys( $varMap ) ) . ') ' .
422 $selectSql . ' ON CONFLICT DO NOTHING';
423 $query = new Query( $sql, self::QUERY_CHANGE_ROWS, 'INSERT', $destTable );
424 $this->query( $query, $fname );
426 parent::doInsertSelectNative( $destTable, $srcTable, $varMap, $conds, $fname,
427 $insertOptions, $selectOptions, $selectJoinConds );
431 public function getValueTypesForWithClause( $table ) {
434 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
435 $encTable = $this->addQuotes( $table );
436 foreach ( $this->getCoreSchemas() as $schema ) {
437 $encSchema = $this->addQuotes( $schema );
438 $sql = "SELECT column_name,udt_name " .
439 "FROM information_schema.columns " .
440 "WHERE table_name = $encTable AND table_schema = $encSchema";
441 $query = new Query( $sql, $flags, 'SELECT' );
442 $res = $this->query( $query, __METHOD__ );
443 if ( $res->numRows() ) {
444 foreach ( $res as $row ) {
445 $typesByColumn[$row->column_name] = $row->udt_name;
451 return $typesByColumn;
454 protected function isConnectionError( $errno ) {
455 // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
456 static $codes = [ '08000', '08003', '08006', '08001', '08004', '57P01', '57P03', '53300' ];
458 return in_array( $errno, $codes, true );
461 protected function isQueryTimeoutError( $errno ) {
462 // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
463 return ( $errno === '57014' );
466 protected function isKnownStatementRollbackError( $errno ) {
467 return false; // transaction has to be rolled-back from error state
470 public function duplicateTableStructure(
471 $oldName, $newName, $temporary = false, $fname = __METHOD__
473 $newNameE = $this->platform->addIdentifierQuotes( $newName );
474 $oldNameE = $this->platform->addIdentifierQuotes( $oldName );
476 $temporary = $temporary ? 'TEMPORARY' : '';
478 "CREATE $temporary TABLE $newNameE " .
479 "(LIKE $oldNameE INCLUDING DEFAULTS INCLUDING INDEXES)",
480 self::QUERY_PSEUDO_PERMANENT | self::QUERY_CHANGE_SCHEMA,
481 $temporary ? 'CREATE TEMPORARY' : 'CREATE',
482 // Use a dot to avoid double-prefixing in Database::getTempTableWrites()
485 $ret = $this->query( $query, $fname );
490 $sql = 'SELECT attname FROM pg_class c'
491 . ' JOIN pg_namespace n ON (n.oid = c.relnamespace)'
492 . ' JOIN pg_attribute a ON (a.attrelid = c.oid)'
493 . ' JOIN pg_attrdef d ON (c.oid=d.adrelid and a.attnum=d.adnum)'
494 . ' WHERE relkind = \'r\''
495 . ' AND nspname = ' . $this->addQuotes( $this->getCoreSchema() )
496 . ' AND relname = ' . $this->addQuotes( $oldName )
497 . ' AND pg_get_expr(adbin, adrelid) LIKE \'nextval(%\'';
500 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
504 $res = $this->query( $query, $fname );
505 $row = $res->fetchObject();
507 $field = $row->attname;
508 $newSeq = "{$newName}_{$field}_seq";
509 $fieldE = $this->platform->addIdentifierQuotes( $field );
510 $newSeqE = $this->platform->addIdentifierQuotes( $newSeq );
511 $newSeqQ = $this->addQuotes( $newSeq );
513 "CREATE $temporary SEQUENCE $newSeqE OWNED BY $newNameE.$fieldE",
514 self::QUERY_CHANGE_SCHEMA,
516 // Do not treat this is as a table modification on top of the CREATE above.
519 $this->query( $query, $fname );
521 "ALTER TABLE $newNameE ALTER COLUMN $fieldE SET DEFAULT nextval({$newSeqQ}::regclass)",
522 self::QUERY_CHANGE_SCHEMA,
524 // Do not treat this is as a table modification on top of the CREATE above.
527 $this->query( $query, $fname );
533 public function truncateTable( $table, $fname = __METHOD__ ) {
534 $sql = "TRUNCATE TABLE " . $this->tableName( $table ) . " RESTART IDENTITY";
535 $query = new Query( $sql, self::QUERY_CHANGE_SCHEMA, 'TRUNCATE', $table );
536 $this->query( $query, $fname );
540 * @param string $prefix Only show tables with this prefix, e.g. mw_
541 * @param string $fname Calling function name
543 * @suppress SecurityCheck-SQLInjection array_map not recognized T204911
545 public function listTables( $prefix = '', $fname = __METHOD__ ) {
546 $eschemas = implode( ',', array_map( [ $this, 'addQuotes' ], $this->getCoreSchemas() ) );
548 "SELECT DISTINCT tablename FROM pg_tables WHERE schemaname IN ($eschemas)",
549 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
552 $result = $this->query( $query, $fname );
555 foreach ( $result as $table ) {
556 $vars = get_object_vars( $table );
557 $table = array_pop( $vars );
558 if ( $prefix == '' || strpos( $table, $prefix ) === 0 ) {
559 $endArray[] = $table;
567 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
568 * to https://www.php.net/manual/en/ref.pgsql.php
570 * Parsing a postgres array can be a tricky problem, he's my
571 * take on this, it handles multi-dimensional arrays plus
572 * escaping using a nasty regexp to determine the limits of each
575 * This should really be handled by PHP PostgreSQL module
578 * @param string $text Postgreql array returned in a text form like {a,b}
579 * @param string[] &$output
580 * @param int|false $limit
584 private function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
585 if ( $limit === false ) {
586 $limit = strlen( $text ) - 1;
589 if ( $text == '{}' ) {
593 if ( $text[$offset] != '{' ) {
594 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
595 $text, $match, 0, $offset );
596 $offset += strlen( $match[0] );
597 $output[] = ( $match[1][0] != '"'
599 : stripcslashes( substr( $match[1], 1, -1 ) ) );
600 if ( $match[3] == '},' ) {
604 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
606 } while ( $limit > $offset );
611 public function getSoftwareLink() {
612 return '[{{int:version-db-postgres-url}} PostgreSQL]';
616 * Return current schema (executes SELECT current_schema())
620 * @return string Default schema for the current session
622 public function getCurrentSchema() {
624 "SELECT current_schema()",
625 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
628 $res = $this->query( $query, __METHOD__ );
629 $row = $res->fetchRow();
635 * Return list of schemas which are accessible without schema name
636 * This is list does not contain magic keywords like "$user"
639 * @see getSearchPath()
640 * @see setSearchPath()
642 * @return array List of actual schemas for the current session
644 public function getSchemas() {
646 "SELECT current_schemas(false)",
647 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
650 $res = $this->query( $query, __METHOD__ );
651 $row = $res->fetchRow();
654 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
656 return $this->pg_array_parse( $row[0], $schemas );
660 * Return search patch for schemas
661 * This is different from getSchemas() since it contain magic keywords
666 * @return array How to search for table names schemas for the current user
668 public function getSearchPath() {
671 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
674 $res = $this->query( $query, __METHOD__ );
675 $row = $res->fetchRow();
677 /* PostgreSQL returns SHOW values as strings */
679 return explode( ",", $row[0] );
683 * Update search_path, values should already be sanitized
684 * Values may contain magic keywords like "$user"
687 * @param string[] $search_path List of schemas to be searched by default
689 private function setSearchPath( $search_path ) {
691 "SET search_path = " . implode( ", ", $search_path ),
692 self::QUERY_CHANGE_TRX,
695 $this->query( $query, __METHOD__ );
699 * Determine default schema for the current application
700 * Adjust this session schema search path if desired schema exists
701 * and is not already there.
703 * We need to have name of the core schema stored to be able
704 * to query database metadata.
706 * This will be also called by the installer after the schema is created
710 * @param string|null $desiredSchema
712 public function determineCoreSchema( $desiredSchema ) {
713 if ( $this->trxLevel() ) {
714 // We do not want the schema selection to change on ROLLBACK or INSERT SELECT.
715 // See https://www.postgresql.org/docs/8.3/sql-set.html
716 throw new DBUnexpectedError(
718 __METHOD__ . ": a transaction is currently active"
722 if ( $this->schemaExists( $desiredSchema ) ) {
723 if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
724 $this->platform->setCoreSchema( $desiredSchema );
725 $this->logger->debug(
726 "Schema \"" . $desiredSchema . "\" already in the search path\n" );
728 // Prepend the desired schema to the search path (T17816)
729 $search_path = $this->getSearchPath();
730 array_unshift( $search_path, $this->platform->addIdentifierQuotes( $desiredSchema ) );
731 $this->setSearchPath( $search_path );
732 $this->platform->setCoreSchema( $desiredSchema );
733 $this->logger->debug(
734 "Schema \"" . $desiredSchema . "\" added to the search path\n" );
737 $this->platform->setCoreSchema( $this->getCurrentSchema() );
738 $this->logger->debug(
739 "Schema \"" . $desiredSchema . "\" not found, using current \"" .
740 $this->getCoreSchema() . "\"\n" );
745 * Return schema name for core application tables
748 * @return string Core schema name
750 public function getCoreSchema() {
751 return $this->platform->getCoreSchema();
755 * Return schema names for temporary tables and core application tables
758 * @return string[] schema names
760 public function getCoreSchemas() {
761 if ( $this->tempSchema ) {
762 return [ $this->tempSchema, $this->getCoreSchema() ];
765 "SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = pg_my_temp_schema()",
766 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
769 $res = $this->query( $query, __METHOD__ );
770 $row = $res->fetchObject();
772 $this->tempSchema = $row->nspname;
773 return [ $this->tempSchema, $this->getCoreSchema() ];
776 return [ $this->getCoreSchema() ];
779 public function getServerVersion() {
780 if ( $this->numericVersion === null ) {
782 $this->numericVersion = pg_version( $this->getBindingHandle() )['server'];
785 return $this->numericVersion;
789 * Query whether a given relation exists (in the given schema, or the
790 * default mw one if not given)
791 * @param string $table
792 * @param array|string $types
795 private function relationExists( $table, $types ) {
796 if ( !is_array( $types ) ) {
799 $schemas = $this->getCoreSchemas();
800 $components = $this->platform->qualifiedTableComponents( $table );
801 $etable = $this->addQuotes( end( $components ) );
802 foreach ( $schemas as $schema ) {
803 $eschema = $this->addQuotes( $schema );
804 $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
805 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
806 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
809 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
812 $res = $this->query( $query, __METHOD__ );
813 if ( $res && $res->numRows() ) {
821 public function tableExists( $table, $fname = __METHOD__ ) {
822 return $this->relationExists( $table, [ 'r', 'v' ] );
825 public function sequenceExists( $sequence ) {
826 return $this->relationExists( $sequence, 'S' );
829 public function constraintExists( $table, $constraint ) {
830 foreach ( $this->getCoreSchemas() as $schema ) {
831 $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
832 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
833 $this->addQuotes( $schema ),
834 $this->addQuotes( $table ),
835 $this->addQuotes( $constraint )
839 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
842 $res = $this->query( $query, __METHOD__ );
843 if ( $res && $res->numRows() ) {
851 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
852 * @param string|null $schema
855 public function schemaExists( $schema ) {
856 if ( !strlen( $schema ?? '' ) ) {
857 return false; // short-circuit
860 "SELECT 1 FROM pg_catalog.pg_namespace " .
861 "WHERE nspname = " . $this->addQuotes( $schema ) . " LIMIT 1",
862 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
865 $res = $this->query( $query, __METHOD__ );
867 return ( $res->numRows() > 0 );
871 * Returns true if a given role (i.e. user) exists, false otherwise.
872 * @param string $roleName
875 public function roleExists( $roleName ) {
877 "SELECT 1 FROM pg_catalog.pg_roles " .
878 "WHERE rolname = " . $this->addQuotes( $roleName ) . " LIMIT 1",
879 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
882 $res = $this->query( $query, __METHOD__ );
884 return ( $res->numRows() > 0 );
888 * @param string $table
889 * @param string $field
890 * @return PostgresField|null
892 public function fieldInfo( $table, $field ) {
893 return PostgresField::fromText( $this, $table, $field );
896 public function encodeBlob( $b ) {
897 $conn = $this->getBindingHandle();
899 return new PostgresBlob( pg_escape_bytea( $conn, $b ) );
902 public function decodeBlob( $b ) {
903 if ( $b instanceof PostgresBlob ) {
905 } elseif ( $b instanceof Blob ) {
909 return pg_unescape_bytea( $b );
912 public function strencode( $s ) {
913 // Should not be called by us
914 return pg_escape_string( $this->getBindingHandle(), (string)$s );
917 public function addQuotes( $s ) {
918 if ( $s instanceof RawSQLValue ) {
921 $conn = $this->getBindingHandle();
925 } elseif ( is_bool( $s ) ) {
926 return (string)intval( $s );
927 } elseif ( is_int( $s ) ) {
929 } elseif ( $s instanceof Blob ) {
930 if ( $s instanceof PostgresBlob ) {
933 $s = pg_escape_bytea( $conn, $s->fetch() );
938 return "'" . pg_escape_string( $conn, (string)$s ) . "'";
941 public function streamStatementEnd( &$sql, &$newLine ) {
942 # Allow dollar quoting for function declarations
943 if ( str_starts_with( $newLine, '$mw$' ) ) {
944 if ( $this->delimiter ) {
945 $this->delimiter = false;
947 $this->delimiter = ';';
951 return parent::streamStatementEnd( $sql, $newLine );
954 public function doLockIsFree( string $lockName, string $method ) {
956 $this->platform->lockIsFreeSQLText( $lockName ),
957 self::QUERY_CHANGE_LOCKS,
960 $res = $this->query( $query, $method );
961 $row = $res->fetchObject();
963 return (bool)$row->unlocked;
966 public function doLock( string $lockName, string $method, int $timeout ) {
968 $this->platform->lockSQLText( $lockName, $timeout ),
969 self::QUERY_CHANGE_LOCKS,
974 $loop = new WaitConditionLoop(
975 function () use ( $query, $method, &$acquired ) {
976 $res = $this->query( $query, $method );
977 $row = $res->fetchObject();
979 if ( $row->acquired !== null ) {
980 $acquired = (float)$row->acquired;
982 return WaitConditionLoop::CONDITION_REACHED;
985 return WaitConditionLoop::CONDITION_CONTINUE;
994 public function doUnlock( string $lockName, string $method ) {
996 $this->platform->unlockSQLText( $lockName ),
997 self::QUERY_CHANGE_LOCKS,
1000 $result = $this->query( $query, $method );
1001 $row = $result->fetchObject();
1003 return (bool)$row->released;
1006 protected function doFlushSession( $fname ) {
1007 $flags = self::QUERY_CHANGE_LOCKS | self::QUERY_NO_RETRY;
1009 // https://www.postgresql.org/docs/9.1/functions-admin.html
1010 $sql = "SELECT pg_advisory_unlock_all()";
1011 $query = new Query( $sql, $flags, 'UNLOCK' );
1012 $qs = $this->executeQuery( $query, __METHOD__, $flags );
1013 if ( $qs->res === false ) {
1014 $this->reportQueryError( $qs->message, $qs->code, $sql, $fname, true );
1018 public function serverIsReadOnly() {
1020 "SHOW default_transaction_read_only",
1021 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
1024 $res = $this->query( $query, __METHOD__ );
1025 $row = $res->fetchObject();
1027 return $row && strtolower( $row->default_transaction_read_only ) === 'on';
1030 protected function getInsertIdColumnForUpsert( $table ) {
1033 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
1034 $components = $this->platform->qualifiedTableComponents( $table );
1035 $encTable = $this->addQuotes( end( $components ) );
1036 foreach ( $this->getCoreSchemas() as $schema ) {
1037 $encSchema = $this->addQuotes( $schema );
1039 "SELECT column_name,data_type,column_default " .
1040 "FROM information_schema.columns " .
1041 "WHERE table_name = $encTable AND table_schema = $encSchema",
1042 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
1045 $res = $this->query( $query, __METHOD__ );
1046 if ( $res->numRows() ) {
1047 foreach ( $res as $row ) {
1049 $row->column_default !== null &&
1050 str_starts_with( $row->column_default, "nextval(" ) &&
1051 in_array( $row->data_type, [ 'integer', 'bigint' ], true )
1053 $column = $row->column_name;
1063 public static function getAttributes() {
1064 return [ self::ATTR_SCHEMAS_AS_TABLE_GROUPS => true ];