PostgreSQL Source Code git master
Loading...
Searching...
No Matches
connection.c File Reference
#include "postgres.h"
#include <poll.h>
#include "access/htup_details.h"
#include "access/xact.h"
#include "catalog/pg_user_mapping.h"
#include "commands/defrem.h"
#include "common/base64.h"
#include "funcapi.h"
#include "libpq/libpq-be.h"
#include "libpq/libpq-be-fe-helpers.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "postgres_fdw.h"
#include "storage/latch.h"
#include "utils/builtins.h"
#include "utils/hsearch.h"
#include "utils/inval.h"
#include "utils/syscache.h"
Include dependency graph for connection.c:

Go to the source code of this file.

Data Structures

struct  ConnCacheEntry
 

Macros

#define CONNECTION_CLEANUP_TIMEOUT   30000
 
#define RETRY_CANCEL_TIMEOUT   1000
 
#define CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel)
 
#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1   2
 
#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2   6
 
#define POSTGRES_FDW_GET_CONNECTIONS_COLS   6 /* maximum of above */
 

Typedefs

typedef Oid ConnCacheKey
 
typedef struct ConnCacheEntry ConnCacheEntry
 

Enumerations

enum  pgfdwVersion { PGFDW_V1_1 = 0 , PGFDW_V1_2 }
 

Functions

 PG_FUNCTION_INFO_V1 (postgres_fdw_get_connections)
 
 PG_FUNCTION_INFO_V1 (postgres_fdw_get_connections_1_2)
 
 PG_FUNCTION_INFO_V1 (postgres_fdw_disconnect)
 
 PG_FUNCTION_INFO_V1 (postgres_fdw_disconnect_all)
 
 PG_FUNCTION_INFO_V1 (postgres_fdw_connection)
 
static void make_new_connection (ConnCacheEntry *entry, UserMapping *user)
 
static PGconnconnect_pg_server (ForeignServer *server, UserMapping *user)
 
static void disconnect_pg_server (ConnCacheEntry *entry)
 
static void check_conn_params (const char **keywords, const char **values, UserMapping *user)
 
static void configure_remote_session (PGconn *conn)
 
static void do_sql_command_begin (PGconn *conn, const char *sql)
 
static void do_sql_command_end (PGconn *conn, const char *sql, bool consume_input)
 
static void begin_remote_xact (ConnCacheEntry *entry)
 
static void pgfdw_report_internal (int elevel, PGresult *res, PGconn *conn, const char *sql)
 
static void pgfdw_xact_callback (XactEvent event, void *arg)
 
static void pgfdw_subxact_callback (SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid, void *arg)
 
static void pgfdw_inval_callback (Datum arg, SysCacheIdentifier cacheid, uint32 hashvalue)
 
static void pgfdw_reject_incomplete_xact_state_change (ConnCacheEntry *entry)
 
static void pgfdw_reset_xact_state (ConnCacheEntry *entry, bool toplevel)
 
static bool pgfdw_cancel_query (PGconn *conn)
 
static bool pgfdw_cancel_query_begin (PGconn *conn, TimestampTz endtime)
 
static bool pgfdw_cancel_query_end (PGconn *conn, TimestampTz endtime, TimestampTz retrycanceltime, bool consume_input)
 
static bool pgfdw_exec_cleanup_query (PGconn *conn, const char *query, bool ignore_errors)
 
static bool pgfdw_exec_cleanup_query_begin (PGconn *conn, const char *query)
 
static bool pgfdw_exec_cleanup_query_end (PGconn *conn, const char *query, TimestampTz endtime, bool consume_input, bool ignore_errors)
 
static bool pgfdw_get_cleanup_result (PGconn *conn, TimestampTz endtime, TimestampTz retrycanceltime, PGresult **result, bool *timed_out)
 
static void pgfdw_abort_cleanup (ConnCacheEntry *entry, bool toplevel)
 
static bool pgfdw_abort_cleanup_begin (ConnCacheEntry *entry, bool toplevel, List **pending_entries, List **cancel_requested)
 
static void pgfdw_finish_pre_commit_cleanup (List *pending_entries)
 
static void pgfdw_finish_pre_subcommit_cleanup (List *pending_entries, int curlevel)
 
static void pgfdw_finish_abort_cleanup (List *pending_entries, List *cancel_requested, bool toplevel)
 
static void pgfdw_security_check (const char **keywords, const char **values, UserMapping *user, PGconn *conn)
 
static bool UserMappingPasswordRequired (UserMapping *user)
 
static bool UseScramPassthrough (ForeignServer *server, UserMapping *user)
 
static bool disconnect_cached_connections (Oid serverid)
 
static void postgres_fdw_get_connections_internal (FunctionCallInfo fcinfo, enum pgfdwVersion api_version)
 
static int pgfdw_conn_check (PGconn *conn)
 
static bool pgfdw_conn_checkable (void)
 
static bool pgfdw_has_required_scram_options (const char **keywords, const char **values)
 
PGconnGetConnection (UserMapping *user, bool will_prep_stmt, PgFdwConnState **state)
 
static void construct_connection_params (ForeignServer *server, UserMapping *user, const char ***p_keywords, const char ***p_values, char **p_appname)
 
void do_sql_command (PGconn *conn, const char *sql)
 
void ReleaseConnection (PGconn *conn)
 
unsigned int GetCursorNumber (PGconn *conn)
 
unsigned int GetPrepStmtNumber (PGconn *conn)
 
PGresultpgfdw_exec_query (PGconn *conn, const char *query, PgFdwConnState *state)
 
PGresultpgfdw_get_result (PGconn *conn)
 
void pgfdw_report_error (PGresult *res, PGconn *conn, const char *sql)
 
void pgfdw_report (int elevel, PGresult *res, PGconn *conn, const char *sql)
 
static void appendEscapedValue (StringInfo str, const char *val)
 
Datum postgres_fdw_connection (PG_FUNCTION_ARGS)
 
Datum postgres_fdw_get_connections_1_2 (PG_FUNCTION_ARGS)
 
Datum postgres_fdw_get_connections (PG_FUNCTION_ARGS)
 
Datum postgres_fdw_disconnect (PG_FUNCTION_ARGS)
 
Datum postgres_fdw_disconnect_all (PG_FUNCTION_ARGS)
 

Variables

static HTABConnectionHash = NULL
 
static unsigned int cursor_number = 0
 
static unsigned int prep_stmt_number = 0
 
static bool xact_got_connection = false
 
static uint32 pgfdw_we_cleanup_result = 0
 
static uint32 pgfdw_we_connect = 0
 
static uint32 pgfdw_we_get_result = 0
 

Macro Definition Documentation

◆ CONNECTION_CLEANUP_TIMEOUT

#define CONNECTION_CLEANUP_TIMEOUT   30000

Definition at line 98 of file connection.c.

◆ CONSTRUCT_ABORT_COMMAND

#define CONSTRUCT_ABORT_COMMAND (   sql,
  entry,
  toplevel 
)
Value:
do { \
if (toplevel) \
snprintf((sql), sizeof(sql), \
"ABORT TRANSACTION"); \
snprintf((sql), sizeof(sql), \
"ROLLBACK TO SAVEPOINT s%d; RELEASE SAVEPOINT s%d", \
(entry)->xact_depth, (entry)->xact_depth); \
} while(0)
static int fb(int x)

Definition at line 108 of file connection.c.

109 { \
110 if (toplevel) \
111 snprintf((sql), sizeof(sql), \
112 "ABORT TRANSACTION"); \
114 snprintf((sql), sizeof(sql), \
115 "ROLLBACK TO SAVEPOINT s%d; RELEASE SAVEPOINT s%d", \
116 (entry)->xact_depth, (entry)->xact_depth); \
117 } while(0)

◆ POSTGRES_FDW_GET_CONNECTIONS_COLS

#define POSTGRES_FDW_GET_CONNECTIONS_COLS   6 /* maximum of above */

Definition at line 2160 of file connection.c.

◆ POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1

#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1   2

Definition at line 2158 of file connection.c.

◆ POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2

#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2   6

Definition at line 2159 of file connection.c.

◆ RETRY_CANCEL_TIMEOUT

#define RETRY_CANCEL_TIMEOUT   1000

Definition at line 105 of file connection.c.

Typedef Documentation

◆ ConnCacheEntry

◆ ConnCacheKey

Definition at line 53 of file connection.c.

Enumeration Type Documentation

◆ pgfdwVersion

Enumerator
PGFDW_V1_1 
PGFDW_V1_2 

Definition at line 122 of file connection.c.

123{
124 PGFDW_V1_1 = 0,
126};
@ PGFDW_V1_1
Definition connection.c:124
@ PGFDW_V1_2
Definition connection.c:125

Function Documentation

◆ appendEscapedValue()

static void appendEscapedValue ( StringInfo  str,
const char val 
)
static

Definition at line 2338 of file connection.c.

2339{
2341 for (int i = 0; val[i] != '\0'; i++)
2342 {
2343 if (val[i] == '\\' || val[i] == '\'')
2346 }
2348}
const char * str
long val
Definition informix.c:689
int i
Definition isn.c:77
void appendStringInfoChar(StringInfo str, char ch)
Definition stringinfo.c:242

References appendStringInfoChar(), i, str, and val.

Referenced by postgres_fdw_connection().

◆ begin_remote_xact()

static void begin_remote_xact ( ConnCacheEntry entry)
static

Definition at line 875 of file connection.c.

876{
878
879 /* Start main transaction if we haven't yet */
880 if (entry->xact_depth <= 0)
881 {
882 const char *sql;
883
884 elog(DEBUG3, "starting remote transaction on connection %p",
885 entry->conn);
886
888 sql = "START TRANSACTION ISOLATION LEVEL SERIALIZABLE";
889 else
890 sql = "START TRANSACTION ISOLATION LEVEL REPEATABLE READ";
891 entry->changing_xact_state = true;
892 do_sql_command(entry->conn, sql);
893 entry->xact_depth = 1;
894 entry->changing_xact_state = false;
895 }
896
897 /*
898 * If we're in a subtransaction, stack up savepoints to match our level.
899 * This ensures we can rollback just the desired effects when a
900 * subtransaction aborts.
901 */
902 while (entry->xact_depth < curlevel)
903 {
904 char sql[64];
905
906 snprintf(sql, sizeof(sql), "SAVEPOINT s%d", entry->xact_depth + 1);
907 entry->changing_xact_state = true;
908 do_sql_command(entry->conn, sql);
909 entry->xact_depth++;
910 entry->changing_xact_state = false;
911 }
912}
void do_sql_command(PGconn *conn, const char *sql)
Definition connection.c:832
#define DEBUG3
Definition elog.h:28
#define elog(elevel,...)
Definition elog.h:226
#define snprintf
Definition port.h:260
PGconn * conn
Definition connection.c:58
bool changing_xact_state
Definition connection.c:64
int GetCurrentTransactionNestLevel(void)
Definition xact.c:931
#define IsolationIsSerializable()
Definition xact.h:53

References ConnCacheEntry::changing_xact_state, ConnCacheEntry::conn, DEBUG3, do_sql_command(), elog, fb(), GetCurrentTransactionNestLevel(), IsolationIsSerializable, snprintf, and ConnCacheEntry::xact_depth.

Referenced by GetConnection().

◆ check_conn_params()

static void check_conn_params ( const char **  keywords,
const char **  values,
UserMapping user 
)
static

Definition at line 742 of file connection.c.

743{
744 int i;
745
746 /* no check required if superuser */
747 if (superuser_arg(user->userid))
748 return;
749
750#ifdef ENABLE_GSS
751 /* ok if the user provided their own delegated credentials */
753 return;
754#endif
755
756 /* ok if params contain a non-empty password */
757 for (i = 0; keywords[i] != NULL; i++)
758 {
759 if (strcmp(keywords[i], "password") == 0 && values[i][0] != '\0')
760 return;
761 }
762
763 /* ok if the superuser explicitly said so at user mapping creation time */
765 return;
766
767 /*
768 * Ok if SCRAM pass-through is being used and all required scram options
769 * are set correctly. If pgfdw_has_required_scram_options returns true we
770 * assume that UseScramPassthrough is also true since SCRAM options are
771 * only set when UseScramPassthrough is enabled.
772 */
774 return;
775
778 errmsg("password or GSSAPI delegated credentials required"),
779 errdetail("Non-superusers must delegate GSSAPI credentials, provide a password, or enable SCRAM pass-through in user mapping.")));
780}
bool be_gssapi_get_delegation(Port *port)
static Datum values[MAXATTR]
Definition bootstrap.c:187
static bool UserMappingPasswordRequired(UserMapping *user)
Definition connection.c:694
static bool pgfdw_has_required_scram_options(const char **keywords, const char **values)
int errcode(int sqlerrcode)
Definition elog.c:874
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define ERROR
Definition elog.h:39
#define ereport(elevel,...)
Definition elog.h:150
struct Port * MyProcPort
Definition globals.c:51
static const JsonPathKeyword keywords[]
static char * errmsg
static char * user
Definition pg_regress.c:119
bool has_scram_keys
Definition libpq-be.h:188
bool superuser_arg(Oid roleid)
Definition superuser.c:57

References be_gssapi_get_delegation(), ereport, errcode(), errdetail(), errmsg, ERROR, fb(), Port::has_scram_keys, i, keywords, MyProcPort, pgfdw_has_required_scram_options(), superuser_arg(), user, UserMappingPasswordRequired(), and values.

Referenced by construct_connection_params().

◆ configure_remote_session()

static void configure_remote_session ( PGconn conn)
static

Definition at line 794 of file connection.c.

795{
797
798 /* Force the search path to contain only pg_catalog (see deparse.c) */
799 do_sql_command(conn, "SET search_path = pg_catalog");
800
801 /*
802 * Set remote timezone; this is basically just cosmetic, since all
803 * transmitted and returned timestamptzs should specify a zone explicitly
804 * anyway. However it makes the regression test outputs more predictable.
805 *
806 * We don't risk setting remote zone equal to ours, since the remote
807 * server might use a different timezone database. Instead, use GMT
808 * (quoted, because very old servers are picky about case). That's
809 * guaranteed to work regardless of the remote's timezone database,
810 * because pg_tzset() hard-wires it (at least in PG 9.2 and later).
811 */
812 do_sql_command(conn, "SET timezone = 'GMT'");
813
814 /*
815 * Set values needed to ensure unambiguous data output from remote. (This
816 * logic should match what pg_dump does. See also set_transmission_modes
817 * in postgres_fdw.c.)
818 */
819 do_sql_command(conn, "SET datestyle = ISO");
820 if (remoteversion >= 80400)
821 do_sql_command(conn, "SET intervalstyle = postgres");
822 if (remoteversion >= 90000)
823 do_sql_command(conn, "SET extra_float_digits = 3");
824 else
825 do_sql_command(conn, "SET extra_float_digits = 2");
826}
int PQserverVersion(const PGconn *conn)
PGconn * conn
Definition streamutil.c:52

References conn, do_sql_command(), fb(), and PQserverVersion().

Referenced by connect_pg_server().

◆ connect_pg_server()

static PGconn * connect_pg_server ( ForeignServer server,
UserMapping user 
)
static

Definition at line 620 of file connection.c.

621{
622 PGconn *volatile conn = NULL;
623
624 /*
625 * Use PG_TRY block to ensure closing connection on error.
626 */
627 PG_TRY();
628 {
629 const char **keywords;
630 const char **values;
631 char *appname;
632
633 construct_connection_params(server, user, &keywords, &values, &appname);
634
635 /* first time, allocate or get the custom wait event */
636 if (pgfdw_we_connect == 0)
637 pgfdw_we_connect = WaitEventExtensionNew("PostgresFdwConnect");
638
639 /* OK to make connection */
641 false, /* expand_dbname */
643
644 if (!conn || PQstatus(conn) != CONNECTION_OK)
647 errmsg("could not connect to server \"%s\"",
648 server->servername),
650
652 "received message via remote connection");
653
654 /* Perform post-connection security checks. */
656
657 /* Prepare new session for use */
659
660 if (appname != NULL)
661 pfree(appname);
663 pfree(values);
664 }
665 PG_CATCH();
666 {
668 PG_RE_THROW();
669 }
670 PG_END_TRY();
671
672 return conn;
673}
static void construct_connection_params(ForeignServer *server, UserMapping *user, const char ***p_keywords, const char ***p_values, char **p_appname)
Definition connection.c:486
static void configure_remote_session(PGconn *conn)
Definition connection.c:794
static void pgfdw_security_check(const char **keywords, const char **values, UserMapping *user, PGconn *conn)
Definition connection.c:437
static uint32 pgfdw_we_connect
Definition connection.c:90
#define PG_RE_THROW()
Definition elog.h:405
int int errdetail_internal(const char *fmt,...) pg_attribute_printf(1
#define PG_TRY(...)
Definition elog.h:372
#define PG_END_TRY(...)
Definition elog.h:397
#define PG_CATCH(...)
Definition elog.h:382
ConnStatusType PQstatus(const PGconn *conn)
PQnoticeReceiver PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
char * PQerrorMessage(const PGconn *conn)
static PGconn * libpqsrv_connect_params(const char *const *keywords, const char *const *values, int expand_dbname, uint32 wait_event_info)
static void libpqsrv_notice_receiver(void *arg, const PGresult *res)
static void libpqsrv_disconnect(PGconn *conn)
@ CONNECTION_OK
Definition libpq-fe.h:90
void pfree(void *pointer)
Definition mcxt.c:1616
char * pchomp(const char *in)
Definition mcxt.c:1809
char * servername
Definition foreign.h:40
uint32 WaitEventExtensionNew(const char *wait_event_name)
Definition wait_event.c:163

References configure_remote_session(), conn, CONNECTION_OK, construct_connection_params(), ereport, errcode(), errdetail_internal(), errmsg, ERROR, fb(), keywords, libpqsrv_connect_params(), libpqsrv_disconnect(), libpqsrv_notice_receiver(), pchomp(), pfree(), PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, pgfdw_security_check(), pgfdw_we_connect, PQerrorMessage(), PQsetNoticeReceiver(), PQstatus(), ForeignServer::servername, user, values, and WaitEventExtensionNew().

Referenced by make_new_connection().

◆ construct_connection_params()

static void construct_connection_params ( ForeignServer server,
UserMapping user,
const char ***  p_keywords,
const char ***  p_values,
char **  p_appname 
)
static

Definition at line 486 of file connection.c.

489{
490 const char **keywords;
491 const char **values;
492 char *appname = NULL;
493 int n;
494
495 /*
496 * Add 4 extra slots for application_name, fallback_application_name,
497 * client_encoding, end marker, and 3 extra slots for scram keys and
498 * required scram pass-through options.
499 */
500 n = list_length(server->options) + list_length(user->options) + 4 + 3;
501 keywords = (const char **) palloc(n * sizeof(char *));
502 values = (const char **) palloc(n * sizeof(char *));
503
504 n = 0;
506 keywords + n, values + n);
507 n += ExtractConnectionOptions(user->options,
508 keywords + n, values + n);
509
510 /*
511 * Use pgfdw_application_name as application_name if set.
512 *
513 * PQconnectdbParams() processes the parameter arrays from start to end.
514 * If any key word is repeated, the last value is used. Therefore note
515 * that pgfdw_application_name must be added to the arrays after options
516 * of ForeignServer are, so that it can override application_name set in
517 * ForeignServer.
518 */
520 {
521 keywords[n] = "application_name";
523 n++;
524 }
525
526 /*
527 * Search the parameter arrays to find application_name setting, and
528 * replace escape sequences in it with status information if found. The
529 * arrays are searched backwards because the last value is used if
530 * application_name is repeatedly set.
531 */
532 for (int i = n - 1; i >= 0; i--)
533 {
534 if (strcmp(keywords[i], "application_name") == 0 &&
535 *(values[i]) != '\0')
536 {
537 /*
538 * Use this application_name setting if it's not empty string even
539 * after any escape sequences in it are replaced.
540 */
541 appname = process_pgfdw_appname(values[i]);
542 if (appname[0] != '\0')
543 {
544 values[i] = appname;
545 break;
546 }
547
548 /*
549 * This empty application_name is not used, so we set values[i] to
550 * NULL and keep searching the array to find the next one.
551 */
552 values[i] = NULL;
553 pfree(appname);
554 appname = NULL;
555 }
556 }
557
558 *p_appname = appname;
559
560 /* Use "postgres_fdw" as fallback_application_name */
561 keywords[n] = "fallback_application_name";
562 values[n] = "postgres_fdw";
563 n++;
564
565 /* Set client_encoding so that libpq can convert encoding properly. */
566 keywords[n] = "client_encoding";
568 n++;
569
570 /* Add required SCRAM pass-through connection options if it's enabled. */
572 {
573 int len;
574 int encoded_len;
575
576 keywords[n] = "scram_client_key";
578 /* don't forget the zero-terminator */
579 values[n] = palloc0(len + 1);
582 (char *) values[n], len);
583 if (encoded_len < 0)
584 elog(ERROR, "could not encode SCRAM client key");
585 n++;
586
587 keywords[n] = "scram_server_key";
589 /* don't forget the zero-terminator */
590 values[n] = palloc0(len + 1);
593 (char *) values[n], len);
594 if (encoded_len < 0)
595 elog(ERROR, "could not encode SCRAM server key");
596 n++;
597
598 /*
599 * Require scram-sha-256 to ensure that no other auth method is used
600 * when connecting with foreign server.
601 */
602 keywords[n] = "require_auth";
603 values[n] = "scram-sha-256";
604 n++;
605 }
606
607 keywords[n] = values[n] = NULL;
608
609 /* Verify the set of connection parameters. */
611
613 *p_values = values;
614}
int pg_b64_enc_len(int srclen)
Definition base64.c:224
int pg_b64_encode(const uint8 *src, int len, char *dst, int dstlen)
Definition base64.c:49
static bool UseScramPassthrough(ForeignServer *server, UserMapping *user)
Definition connection.c:710
static void check_conn_params(const char **keywords, const char **values, UserMapping *user)
Definition connection.c:742
int ExtractConnectionOptions(List *defelems, const char **keywords, const char **values)
Definition option.c:414
char * pgfdw_application_name
Definition option.c:46
char * process_pgfdw_appname(const char *appname)
Definition option.c:491
const char * GetDatabaseEncodingName(void)
Definition mbutils.c:1395
void * palloc0(Size size)
Definition mcxt.c:1417
void * palloc(Size size)
Definition mcxt.c:1387
const void size_t len
static int list_length(const List *l)
Definition pg_list.h:152
List * options
Definition foreign.h:43
uint8 scram_ServerKey[SCRAM_MAX_KEY_LEN]
Definition libpq-be.h:187
uint8 scram_ClientKey[SCRAM_MAX_KEY_LEN]
Definition libpq-be.h:186

References check_conn_params(), elog, ERROR, ExtractConnectionOptions(), fb(), GetDatabaseEncodingName(), Port::has_scram_keys, i, keywords, len, list_length(), MyProcPort, ForeignServer::options, palloc(), palloc0(), pfree(), pg_b64_enc_len(), pg_b64_encode(), pgfdw_application_name, process_pgfdw_appname(), Port::scram_ClientKey, Port::scram_ServerKey, user, UseScramPassthrough(), and values.

Referenced by connect_pg_server(), and postgres_fdw_connection().

◆ disconnect_cached_connections()

static bool disconnect_cached_connections ( Oid  serverid)
static

Definition at line 2468 of file connection.c.

2469{
2470 HASH_SEQ_STATUS scan;
2471 ConnCacheEntry *entry;
2472 bool all = !OidIsValid(serverid);
2473 bool result = false;
2474
2475 /*
2476 * Connection cache hashtable has not been initialized yet in this
2477 * session, so return false.
2478 */
2479 if (!ConnectionHash)
2480 return false;
2481
2483 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
2484 {
2485 /* Ignore cache entry if no open connection right now. */
2486 if (!entry->conn)
2487 continue;
2488
2489 if (all || entry->serverid == serverid)
2490 {
2491 /*
2492 * Emit a warning because the connection to close is used in the
2493 * current transaction and cannot be disconnected right now.
2494 */
2495 if (entry->xact_depth > 0)
2496 {
2497 ForeignServer *server;
2498
2499 server = GetForeignServerExtended(entry->serverid,
2501
2502 if (!server)
2503 {
2504 /*
2505 * If the foreign server was dropped while its connection
2506 * was used in the current transaction, the connection
2507 * must have been marked as invalid by
2508 * pgfdw_inval_callback at the end of DROP SERVER command.
2509 */
2510 Assert(entry->invalidated);
2511
2513 (errmsg("cannot close dropped server connection because it is still in use")));
2514 }
2515 else
2517 (errmsg("cannot close connection for server \"%s\" because it is still in use",
2518 server->servername)));
2519 }
2520 else
2521 {
2522 elog(DEBUG3, "discarding connection %p", entry->conn);
2523 disconnect_pg_server(entry);
2524 result = true;
2525 }
2526 }
2527 }
2528
2529 return result;
2530}
#define Assert(condition)
Definition c.h:906
#define OidIsValid(objectId)
Definition c.h:821
static void disconnect_pg_server(ConnCacheEntry *entry)
Definition connection.c:679
static HTAB * ConnectionHash
Definition connection.c:79
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition dynahash.c:1415
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition dynahash.c:1380
#define WARNING
Definition elog.h:36
ForeignServer * GetForeignServerExtended(Oid serverid, bits16 flags)
Definition foreign.c:125
#define FSV_MISSING_OK
Definition foreign.h:62

References Assert, ConnCacheEntry::conn, ConnectionHash, DEBUG3, disconnect_pg_server(), elog, ereport, errmsg, FSV_MISSING_OK, GetForeignServerExtended(), hash_seq_init(), hash_seq_search(), ConnCacheEntry::invalidated, OidIsValid, ConnCacheEntry::serverid, ForeignServer::servername, WARNING, and ConnCacheEntry::xact_depth.

Referenced by postgres_fdw_disconnect(), and postgres_fdw_disconnect_all().

◆ disconnect_pg_server()

static void disconnect_pg_server ( ConnCacheEntry entry)
static

◆ do_sql_command()

void do_sql_command ( PGconn conn,
const char sql 
)

Definition at line 832 of file connection.c.

833{
835 do_sql_command_end(conn, sql, false);
836}
static void do_sql_command_end(PGconn *conn, const char *sql, bool consume_input)
Definition connection.c:846
static void do_sql_command_begin(PGconn *conn, const char *sql)
Definition connection.c:839

References conn, do_sql_command_begin(), and do_sql_command_end().

Referenced by begin_remote_xact(), configure_remote_session(), pgfdw_subxact_callback(), pgfdw_xact_callback(), and postgresExecForeignTruncate().

◆ do_sql_command_begin()

static void do_sql_command_begin ( PGconn conn,
const char sql 
)
static

Definition at line 839 of file connection.c.

840{
841 if (!PQsendQuery(conn, sql))
843}
void pgfdw_report_error(PGresult *res, PGconn *conn, const char *sql)
int PQsendQuery(PGconn *conn, const char *query)
Definition fe-exec.c:1433

References conn, fb(), pgfdw_report_error(), and PQsendQuery().

Referenced by do_sql_command(), pgfdw_subxact_callback(), and pgfdw_xact_callback().

◆ do_sql_command_end()

static void do_sql_command_end ( PGconn conn,
const char sql,
bool  consume_input 
)
static

Definition at line 846 of file connection.c.

847{
848 PGresult *res;
849
850 /*
851 * If requested, consume whatever data is available from the socket. (Note
852 * that if all data is available, this allows pgfdw_get_result to call
853 * PQgetResult without forcing the overhead of WaitLatchOrSocket, which
854 * would be large compared to the overhead of PQconsumeInput.)
855 */
858 res = pgfdw_get_result(conn);
860 pgfdw_report_error(res, conn, sql);
861 PQclear(res);
862}
PGresult * pgfdw_get_result(PGconn *conn)
Definition connection.c:985
int PQconsumeInput(PGconn *conn)
Definition fe-exec.c:2001
#define PQclear
#define PQresultStatus
@ PGRES_COMMAND_OK
Definition libpq-fe.h:131

References conn, fb(), pgfdw_get_result(), pgfdw_report_error(), PGRES_COMMAND_OK, PQclear, PQconsumeInput(), and PQresultStatus.

Referenced by do_sql_command(), pgfdw_finish_pre_commit_cleanup(), and pgfdw_finish_pre_subcommit_cleanup().

◆ GetConnection()

PGconn * GetConnection ( UserMapping user,
bool  will_prep_stmt,
PgFdwConnState **  state 
)

Definition at line 208 of file connection.c.

209{
210 bool found;
211 bool retry = false;
212 ConnCacheEntry *entry;
215
216 /* First time through, initialize connection cache hashtable */
217 if (ConnectionHash == NULL)
218 {
219 HASHCTL ctl;
220
221 if (pgfdw_we_get_result == 0)
223 WaitEventExtensionNew("PostgresFdwGetResult");
224
225 ctl.keysize = sizeof(ConnCacheKey);
226 ctl.entrysize = sizeof(ConnCacheEntry);
227 ConnectionHash = hash_create("postgres_fdw connections", 8,
228 &ctl,
230
231 /*
232 * Register some callback functions that manage connection cleanup.
233 * This should be done just once in each backend.
234 */
241 }
242
243 /* Set flag that we did GetConnection during the current transaction */
244 xact_got_connection = true;
245
246 /* Create hash key for the entry. Assume no pad bytes in key struct */
247 key = user->umid;
248
249 /*
250 * Find or create cached entry for requested connection.
251 */
252 entry = hash_search(ConnectionHash, &key, HASH_ENTER, &found);
253 if (!found)
254 {
255 /*
256 * We need only clear "conn" here; remaining fields will be filled
257 * later when "conn" is set.
258 */
259 entry->conn = NULL;
260 }
261
262 /* Reject further use of connections which failed abort cleanup. */
264
265 /*
266 * If the connection needs to be remade due to invalidation, disconnect as
267 * soon as we're out of all transactions.
268 */
269 if (entry->conn != NULL && entry->invalidated && entry->xact_depth == 0)
270 {
271 elog(DEBUG3, "closing connection %p for option changes to take effect",
272 entry->conn);
274 }
275
276 /*
277 * If cache entry doesn't have a connection, we have to establish a new
278 * connection. (If connect_pg_server throws an error, the cache entry
279 * will remain in a valid empty state, ie conn == NULL.)
280 */
281 if (entry->conn == NULL)
283
284 /*
285 * We check the health of the cached connection here when using it. In
286 * cases where we're out of all transactions, if a broken connection is
287 * detected, we try to reestablish a new connection later.
288 */
289 PG_TRY();
290 {
291 /* Process a pending asynchronous request if any. */
292 if (entry->state.pendingAreq)
294 /* Start a new transaction or subtransaction if needed. */
295 begin_remote_xact(entry);
296 }
297 PG_CATCH();
298 {
301
302 /*
303 * Determine whether to try to reestablish the connection.
304 *
305 * After a broken connection is detected in libpq, any error other
306 * than connection failure (e.g., out-of-memory) can be thrown
307 * somewhere between return from libpq and the expected ereport() call
308 * in pgfdw_report_error(). In this case, since PQstatus() indicates
309 * CONNECTION_BAD, checking only PQstatus() causes the false detection
310 * of connection failure. To avoid this, we also verify that the
311 * error's sqlstate is ERRCODE_CONNECTION_FAILURE. Note that also
312 * checking only the sqlstate can cause another false detection
313 * because pgfdw_report_error() may report ERRCODE_CONNECTION_FAILURE
314 * for any libpq-originated error condition.
315 */
316 if (errdata->sqlerrcode != ERRCODE_CONNECTION_FAILURE ||
317 PQstatus(entry->conn) != CONNECTION_BAD ||
318 entry->xact_depth > 0)
319 {
321 PG_RE_THROW();
322 }
323
324 /* Clean up the error state */
327 errdata = NULL;
328
329 retry = true;
330 }
331 PG_END_TRY();
332
333 /*
334 * If a broken connection is detected, disconnect it, reestablish a new
335 * connection and retry a new remote transaction. If connection failure is
336 * reported again, we give up getting a connection.
337 */
338 if (retry)
339 {
340 Assert(entry->xact_depth == 0);
341
343 (errmsg_internal("could not start remote transaction on connection %p",
344 entry->conn)),
346
347 elog(DEBUG3, "closing connection %p to reestablish a new one",
348 entry->conn);
350
352
353 begin_remote_xact(entry);
354 }
355
356 /* Remember if caller will prepare statements */
358
359 /* If caller needs access to the per-connection state, return it. */
360 if (state)
361 *state = &entry->state;
362
363 return entry->conn;
364}
Oid ConnCacheKey
Definition connection.c:53
static uint32 pgfdw_we_get_result
Definition connection.c:91
static bool xact_got_connection
Definition connection.c:86
static void make_new_connection(ConnCacheEntry *entry, UserMapping *user)
Definition connection.c:371
static void pgfdw_subxact_callback(SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid, void *arg)
static void pgfdw_reject_incomplete_xact_state_change(ConnCacheEntry *entry)
static void pgfdw_xact_callback(XactEvent event, void *arg)
static void begin_remote_xact(ConnCacheEntry *entry)
Definition connection.c:875
static void pgfdw_inval_callback(Datum arg, SysCacheIdentifier cacheid, uint32 hashvalue)
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition dynahash.c:952
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:358
void FreeErrorData(ErrorData *edata)
Definition elog.c:2013
ErrorData * CopyErrorData(void)
Definition elog.c:1941
void FlushErrorState(void)
Definition elog.c:2062
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
@ HASH_ENTER
Definition hsearch.h:114
#define HASH_ELEM
Definition hsearch.h:95
#define HASH_BLOBS
Definition hsearch.h:97
void CacheRegisterSyscacheCallback(SysCacheIdentifier cacheid, SyscacheCallbackFunction func, Datum arg)
Definition inval.c:1816
@ CONNECTION_BAD
Definition libpq-fe.h:91
MemoryContext CurrentMemoryContext
Definition mcxt.c:160
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
uint64_t Datum
Definition postgres.h:70
void process_pending_request(AsyncRequest *areq)
tree ctl
Definition radixtree.h:1838
bool have_prep_stmt
Definition connection.c:62
PgFdwConnState state
Definition connection.c:73
AsyncRequest * pendingAreq
void RegisterXactCallback(XactCallback callback, void *arg)
Definition xact.c:3827
void RegisterSubXactCallback(SubXactCallback callback, void *arg)
Definition xact.c:3887

References Assert, begin_remote_xact(), CacheRegisterSyscacheCallback(), ConnCacheEntry::conn, CONNECTION_BAD, ConnectionHash, CopyErrorData(), ctl, CurrentMemoryContext, DEBUG3, disconnect_pg_server(), elog, ereport, errdetail_internal(), errmsg_internal(), fb(), FlushErrorState(), FreeErrorData(), HASH_BLOBS, hash_create(), HASH_ELEM, HASH_ENTER, hash_search(), ConnCacheEntry::have_prep_stmt, ConnCacheEntry::invalidated, make_new_connection(), MemoryContextSwitchTo(), pchomp(), PgFdwConnState::pendingAreq, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, pgfdw_inval_callback(), pgfdw_reject_incomplete_xact_state_change(), pgfdw_subxact_callback(), pgfdw_we_get_result, pgfdw_xact_callback(), PQerrorMessage(), PQstatus(), process_pending_request(), RegisterSubXactCallback(), RegisterXactCallback(), ConnCacheEntry::state, user, WaitEventExtensionNew(), ConnCacheEntry::xact_depth, and xact_got_connection.

◆ GetCursorNumber()

unsigned int GetCursorNumber ( PGconn conn)

Definition at line 939 of file connection.c.

940{
941 return ++cursor_number;
942}
static unsigned int cursor_number
Definition connection.c:82

References cursor_number.

Referenced by postgresAcquireSampleRowsFunc(), and postgresBeginForeignScan().

◆ GetPrepStmtNumber()

unsigned int GetPrepStmtNumber ( PGconn conn)

Definition at line 953 of file connection.c.

954{
955 return ++prep_stmt_number;
956}
static unsigned int prep_stmt_number
Definition connection.c:83

References prep_stmt_number.

Referenced by prepare_foreign_modify().

◆ make_new_connection()

static void make_new_connection ( ConnCacheEntry entry,
UserMapping user 
)
static

Definition at line 371 of file connection.c.

372{
373 ForeignServer *server = GetForeignServer(user->serverid);
374 ListCell *lc;
375
376 Assert(entry->conn == NULL);
377
378 /* Reset all transient state fields, to be sure all are clean */
379 entry->xact_depth = 0;
380 entry->have_prep_stmt = false;
381 entry->have_error = false;
382 entry->changing_xact_state = false;
383 entry->invalidated = false;
384 entry->serverid = server->serverid;
385 entry->server_hashvalue =
387 ObjectIdGetDatum(server->serverid));
388 entry->mapping_hashvalue =
390 ObjectIdGetDatum(user->umid));
391 memset(&entry->state, 0, sizeof(entry->state));
392
393 /*
394 * Determine whether to keep the connection that we're about to make here
395 * open even after the transaction using it ends, so that the subsequent
396 * transactions can re-use it.
397 *
398 * By default, all the connections to any foreign servers are kept open.
399 *
400 * Also determine whether to commit/abort (sub)transactions opened on the
401 * remote server in parallel at (sub)transaction end, which is disabled by
402 * default.
403 *
404 * Note: it's enough to determine these only when making a new connection
405 * because if these settings for it are changed, it will be closed and
406 * re-made later.
407 */
408 entry->keep_connections = true;
409 entry->parallel_commit = false;
410 entry->parallel_abort = false;
411 foreach(lc, server->options)
412 {
413 DefElem *def = (DefElem *) lfirst(lc);
414
415 if (strcmp(def->defname, "keep_connections") == 0)
416 entry->keep_connections = defGetBoolean(def);
417 else if (strcmp(def->defname, "parallel_commit") == 0)
418 entry->parallel_commit = defGetBoolean(def);
419 else if (strcmp(def->defname, "parallel_abort") == 0)
420 entry->parallel_abort = defGetBoolean(def);
421 }
422
423 /* Now try to make the connection */
424 entry->conn = connect_pg_server(server, user);
425
426 elog(DEBUG3, "new postgres_fdw connection %p for server \"%s\" (user mapping oid %u, userid %u)",
427 entry->conn, server->servername, user->umid, user->userid);
428}
static PGconn * connect_pg_server(ForeignServer *server, UserMapping *user)
Definition connection.c:620
bool defGetBoolean(DefElem *def)
Definition define.c:93
ForeignServer * GetForeignServer(Oid serverid)
Definition foreign.c:113
#define lfirst(lc)
Definition pg_list.h:172
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:262
bool parallel_commit
Definition connection.c:65
uint32 server_hashvalue
Definition connection.c:71
uint32 mapping_hashvalue
Definition connection.c:72
bool keep_connections
Definition connection.c:68
bool parallel_abort
Definition connection.c:66
char * defname
Definition parsenodes.h:844
#define GetSysCacheHashValue1(cacheId, key1)
Definition syscache.h:118

References Assert, ConnCacheEntry::changing_xact_state, ConnCacheEntry::conn, connect_pg_server(), DEBUG3, defGetBoolean(), DefElem::defname, elog, fb(), GetForeignServer(), GetSysCacheHashValue1, ConnCacheEntry::have_error, ConnCacheEntry::have_prep_stmt, ConnCacheEntry::invalidated, ConnCacheEntry::keep_connections, lfirst, ConnCacheEntry::mapping_hashvalue, ObjectIdGetDatum(), ForeignServer::options, ConnCacheEntry::parallel_abort, ConnCacheEntry::parallel_commit, ConnCacheEntry::server_hashvalue, ConnCacheEntry::serverid, ForeignServer::serverid, ForeignServer::servername, ConnCacheEntry::state, user, and ConnCacheEntry::xact_depth.

Referenced by GetConnection().

◆ PG_FUNCTION_INFO_V1() [1/5]

PG_FUNCTION_INFO_V1 ( postgres_fdw_connection  )

◆ PG_FUNCTION_INFO_V1() [2/5]

PG_FUNCTION_INFO_V1 ( postgres_fdw_disconnect  )

◆ PG_FUNCTION_INFO_V1() [3/5]

PG_FUNCTION_INFO_V1 ( postgres_fdw_disconnect_all  )

◆ PG_FUNCTION_INFO_V1() [4/5]

PG_FUNCTION_INFO_V1 ( postgres_fdw_get_connections  )

◆ PG_FUNCTION_INFO_V1() [5/5]

PG_FUNCTION_INFO_V1 ( postgres_fdw_get_connections_1_2  )

◆ pgfdw_abort_cleanup()

static void pgfdw_abort_cleanup ( ConnCacheEntry entry,
bool  toplevel 
)
static

Definition at line 1755 of file connection.c.

1756{
1757 char sql[100];
1758
1759 /*
1760 * Don't try to clean up the connection if we're already in error
1761 * recursion trouble.
1762 */
1764 entry->changing_xact_state = true;
1765
1766 /*
1767 * If connection is already unsalvageable, don't touch it further.
1768 */
1769 if (entry->changing_xact_state)
1770 return;
1771
1772 /*
1773 * Mark this connection as in the process of changing transaction state.
1774 */
1775 entry->changing_xact_state = true;
1776
1777 /* Assume we might have lost track of prepared statements */
1778 entry->have_error = true;
1779
1780 /*
1781 * If a command has been submitted to the remote server by using an
1782 * asynchronous execution function, the command might not have yet
1783 * completed. Check to see if a command is still being processed by the
1784 * remote server, and if so, request cancellation of the command.
1785 */
1786 if (PQtransactionStatus(entry->conn) == PQTRANS_ACTIVE &&
1787 !pgfdw_cancel_query(entry->conn))
1788 return; /* Unable to cancel running query */
1789
1790 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
1791 if (!pgfdw_exec_cleanup_query(entry->conn, sql, false))
1792 return; /* Unable to abort remote (sub)transaction */
1793
1794 if (toplevel)
1795 {
1796 if (entry->have_prep_stmt && entry->have_error &&
1798 "DEALLOCATE ALL",
1799 true))
1800 return; /* Trouble clearing prepared statements */
1801
1802 entry->have_prep_stmt = false;
1803 entry->have_error = false;
1804 }
1805
1806 /*
1807 * If pendingAreq of the per-connection state is not NULL, it means that
1808 * an asynchronous fetch begun by fetch_more_data_begin() was not done
1809 * successfully and thus the per-connection state was not reset in
1810 * fetch_more_data(); in that case reset the per-connection state here.
1811 */
1812 if (entry->state.pendingAreq)
1813 memset(&entry->state, 0, sizeof(entry->state));
1814
1815 /* Disarm changing_xact_state if it all worked */
1816 entry->changing_xact_state = false;
1817}
#define CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel)
Definition connection.c:108
static bool pgfdw_exec_cleanup_query(PGconn *conn, const char *query, bool ignore_errors)
static bool pgfdw_cancel_query(PGconn *conn)
bool in_error_recursion_trouble(void)
Definition elog.c:305
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
@ PQTRANS_ACTIVE
Definition libpq-fe.h:154

References ConnCacheEntry::changing_xact_state, ConnCacheEntry::conn, CONSTRUCT_ABORT_COMMAND, fb(), ConnCacheEntry::have_error, ConnCacheEntry::have_prep_stmt, in_error_recursion_trouble(), PgFdwConnState::pendingAreq, pgfdw_cancel_query(), pgfdw_exec_cleanup_query(), PQTRANS_ACTIVE, PQtransactionStatus(), and ConnCacheEntry::state.

Referenced by pgfdw_subxact_callback(), and pgfdw_xact_callback().

◆ pgfdw_abort_cleanup_begin()

static bool pgfdw_abort_cleanup_begin ( ConnCacheEntry entry,
bool  toplevel,
List **  pending_entries,
List **  cancel_requested 
)
static

Definition at line 1829 of file connection.c.

1831{
1832 /*
1833 * Don't try to clean up the connection if we're already in error
1834 * recursion trouble.
1835 */
1837 entry->changing_xact_state = true;
1838
1839 /*
1840 * If connection is already unsalvageable, don't touch it further.
1841 */
1842 if (entry->changing_xact_state)
1843 return false;
1844
1845 /*
1846 * Mark this connection as in the process of changing transaction state.
1847 */
1848 entry->changing_xact_state = true;
1849
1850 /* Assume we might have lost track of prepared statements */
1851 entry->have_error = true;
1852
1853 /*
1854 * If a command has been submitted to the remote server by using an
1855 * asynchronous execution function, the command might not have yet
1856 * completed. Check to see if a command is still being processed by the
1857 * remote server, and if so, request cancellation of the command.
1858 */
1860 {
1862
1866 return false; /* Unable to cancel running query */
1868 }
1869 else
1870 {
1871 char sql[100];
1872
1873 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
1874 if (!pgfdw_exec_cleanup_query_begin(entry->conn, sql))
1875 return false; /* Unable to abort remote transaction */
1877 }
1878
1879 return true;
1880}
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1643
static bool pgfdw_cancel_query_begin(PGconn *conn, TimestampTz endtime)
static bool pgfdw_exec_cleanup_query_begin(PGconn *conn, const char *query)
#define CONNECTION_CLEANUP_TIMEOUT
Definition connection.c:98
int64 TimestampTz
Definition timestamp.h:39
List * lappend(List *list, void *datum)
Definition list.c:339
#define TimestampTzPlusMilliseconds(tz, ms)
Definition timestamp.h:85

References ConnCacheEntry::changing_xact_state, ConnCacheEntry::conn, CONNECTION_CLEANUP_TIMEOUT, CONSTRUCT_ABORT_COMMAND, fb(), GetCurrentTimestamp(), ConnCacheEntry::have_error, in_error_recursion_trouble(), lappend(), pgfdw_cancel_query_begin(), pgfdw_exec_cleanup_query_begin(), PQTRANS_ACTIVE, PQtransactionStatus(), and TimestampTzPlusMilliseconds.

Referenced by pgfdw_subxact_callback(), and pgfdw_xact_callback().

◆ pgfdw_cancel_query()

static bool pgfdw_cancel_query ( PGconn conn)
static

Definition at line 1452 of file connection.c.

1453{
1457
1458 /*
1459 * If it takes too long to cancel the query and discard the result, assume
1460 * the connection is dead.
1461 */
1463
1464 /*
1465 * Also, lose patience and re-issue the cancel request after a little bit.
1466 * (This serves to close some race conditions.)
1467 */
1469
1471 return false;
1473}
Datum now(PG_FUNCTION_ARGS)
Definition timestamp.c:1607
#define RETRY_CANCEL_TIMEOUT
Definition connection.c:105
static bool pgfdw_cancel_query_end(PGconn *conn, TimestampTz endtime, TimestampTz retrycanceltime, bool consume_input)

References conn, CONNECTION_CLEANUP_TIMEOUT, fb(), GetCurrentTimestamp(), now(), pgfdw_cancel_query_begin(), pgfdw_cancel_query_end(), RETRY_CANCEL_TIMEOUT, and TimestampTzPlusMilliseconds.

Referenced by pgfdw_abort_cleanup().

◆ pgfdw_cancel_query_begin()

static bool pgfdw_cancel_query_begin ( PGconn conn,
TimestampTz  endtime 
)
static

Definition at line 1485 of file connection.c.

1486{
1487 const char *errormsg = libpqsrv_cancel(conn, endtime);
1488
1489 if (errormsg != NULL)
1492 errmsg("could not send cancel request: %s", errormsg));
1493
1494 return errormsg == NULL;
1495}
static const char * libpqsrv_cancel(PGconn *conn, TimestampTz endtime)

References conn, ereport, errcode(), errmsg, fb(), libpqsrv_cancel(), and WARNING.

Referenced by pgfdw_abort_cleanup_begin(), and pgfdw_cancel_query().

◆ pgfdw_cancel_query_end()

static bool pgfdw_cancel_query_end ( PGconn conn,
TimestampTz  endtime,
TimestampTz  retrycanceltime,
bool  consume_input 
)
static

Definition at line 1498 of file connection.c.

1500{
1501 PGresult *result;
1502 bool timed_out;
1503
1504 /*
1505 * If requested, consume whatever data is available from the socket. (Note
1506 * that if all data is available, this allows pgfdw_get_cleanup_result to
1507 * call PQgetResult without forcing the overhead of WaitLatchOrSocket,
1508 * which would be large compared to the overhead of PQconsumeInput.)
1509 */
1511 {
1514 errmsg("could not get result of cancel request: %s",
1516 return false;
1517 }
1518
1519 /* Get and discard the result of the query. */
1521 &result, &timed_out))
1522 {
1523 if (timed_out)
1525 (errmsg("could not get result of cancel request due to timeout")));
1526 else
1529 errmsg("could not get result of cancel request: %s",
1531
1532 return false;
1533 }
1534 PQclear(result);
1535
1536 return true;
1537}
static bool pgfdw_get_cleanup_result(PGconn *conn, TimestampTz endtime, TimestampTz retrycanceltime, PGresult **result, bool *timed_out)

References conn, ereport, errcode(), errmsg, fb(), pchomp(), pgfdw_get_cleanup_result(), PQclear, PQconsumeInput(), PQerrorMessage(), and WARNING.

Referenced by pgfdw_cancel_query(), and pgfdw_finish_abort_cleanup().

◆ pgfdw_conn_check()

static int pgfdw_conn_check ( PGconn conn)
static

Definition at line 2540 of file connection.c.

2541{
2542 int sock = PQsocket(conn);
2543
2544 if (PQstatus(conn) != CONNECTION_OK || sock == -1)
2545 return -1;
2546
2547#if (defined(HAVE_POLL) && defined(POLLRDHUP))
2548 {
2549 struct pollfd input_fd;
2550 int result;
2551
2552 input_fd.fd = sock;
2553 input_fd.events = POLLRDHUP;
2554 input_fd.revents = 0;
2555
2556 do
2557 result = poll(&input_fd, 1, 0);
2558 while (result < 0 && errno == EINTR);
2559
2560 if (result < 0)
2561 return -1;
2562
2563 return (input_fd.revents &
2564 (POLLRDHUP | POLLHUP | POLLERR | POLLNVAL)) ? 1 : 0;
2565 }
2566#else
2567 return 0;
2568#endif
2569}
int PQsocket(const PGconn *conn)
#define EINTR
Definition win32_port.h:361

References conn, CONNECTION_OK, EINTR, fb(), PQsocket(), and PQstatus().

Referenced by postgres_fdw_get_connections_internal().

◆ pgfdw_conn_checkable()

static bool pgfdw_conn_checkable ( void  )
static

Definition at line 2577 of file connection.c.

2578{
2579#if (defined(HAVE_POLL) && defined(POLLRDHUP))
2580 return true;
2581#else
2582 return false;
2583#endif
2584}

Referenced by postgres_fdw_get_connections_internal().

◆ pgfdw_exec_cleanup_query()

static bool pgfdw_exec_cleanup_query ( PGconn conn,
const char query,
bool  ignore_errors 
)
static

Definition at line 1552 of file connection.c.

1553{
1555
1556 /*
1557 * If it takes too long to execute a cleanup query, assume the connection
1558 * is dead. It's fairly likely that this is why we aborted in the first
1559 * place (e.g. statement timeout, user cancel), so the timeout shouldn't
1560 * be too long.
1561 */
1564
1566 return false;
1568 false, ignore_errors);
1569}
static bool pgfdw_exec_cleanup_query_end(PGconn *conn, const char *query, TimestampTz endtime, bool consume_input, bool ignore_errors)

References conn, CONNECTION_CLEANUP_TIMEOUT, fb(), GetCurrentTimestamp(), pgfdw_exec_cleanup_query_begin(), pgfdw_exec_cleanup_query_end(), and TimestampTzPlusMilliseconds.

Referenced by pgfdw_abort_cleanup().

◆ pgfdw_exec_cleanup_query_begin()

static bool pgfdw_exec_cleanup_query_begin ( PGconn conn,
const char query 
)
static

Definition at line 1572 of file connection.c.

1573{
1574 Assert(query != NULL);
1575
1576 /*
1577 * Submit a query. Since we don't use non-blocking mode, this also can
1578 * block. But its risk is relatively small, so we ignore that for now.
1579 */
1580 if (!PQsendQuery(conn, query))
1581 {
1582 pgfdw_report(WARNING, NULL, conn, query);
1583 return false;
1584 }
1585
1586 return true;
1587}
void pgfdw_report(int elevel, PGresult *res, PGconn *conn, const char *sql)

References Assert, conn, fb(), pgfdw_report(), PQsendQuery(), and WARNING.

Referenced by pgfdw_abort_cleanup_begin(), pgfdw_exec_cleanup_query(), and pgfdw_finish_abort_cleanup().

◆ pgfdw_exec_cleanup_query_end()

static bool pgfdw_exec_cleanup_query_end ( PGconn conn,
const char query,
TimestampTz  endtime,
bool  consume_input,
bool  ignore_errors 
)
static

Definition at line 1590 of file connection.c.

1593{
1594 PGresult *result;
1595 bool timed_out;
1596
1597 Assert(query != NULL);
1598
1599 /*
1600 * If requested, consume whatever data is available from the socket. (Note
1601 * that if all data is available, this allows pgfdw_get_cleanup_result to
1602 * call PQgetResult without forcing the overhead of WaitLatchOrSocket,
1603 * which would be large compared to the overhead of PQconsumeInput.)
1604 */
1606 {
1607 pgfdw_report(WARNING, NULL, conn, query);
1608 return false;
1609 }
1610
1611 /* Get the result of the query. */
1613 {
1614 if (timed_out)
1616 (errmsg("could not get query result due to timeout"),
1617 errcontext("remote SQL command: %s", query)));
1618 else
1619 pgfdw_report(WARNING, NULL, conn, query);
1620
1621 return false;
1622 }
1623
1624 /* Issue a warning if not successful. */
1625 if (PQresultStatus(result) != PGRES_COMMAND_OK)
1626 {
1627 pgfdw_report(WARNING, result, conn, query);
1628 return ignore_errors;
1629 }
1630 PQclear(result);
1631
1632 return true;
1633}
#define errcontext
Definition elog.h:198

References Assert, conn, ereport, errcontext, errmsg, fb(), pgfdw_get_cleanup_result(), pgfdw_report(), PGRES_COMMAND_OK, PQclear, PQconsumeInput(), PQresultStatus, and WARNING.

Referenced by pgfdw_exec_cleanup_query(), and pgfdw_finish_abort_cleanup().

◆ pgfdw_exec_query()

PGresult * pgfdw_exec_query ( PGconn conn,
const char query,
PgFdwConnState state 
)

Definition at line 968 of file connection.c.

969{
970 /* First, process a pending asynchronous request, if any. */
971 if (state && state->pendingAreq)
972 process_pending_request(state->pendingAreq);
973
974 if (!PQsendQuery(conn, query))
975 return NULL;
976 return pgfdw_get_result(conn);
977}

References conn, fb(), pgfdw_get_result(), PQsendQuery(), and process_pending_request().

Referenced by close_cursor(), deallocate_query(), fetch_more_data(), get_remote_estimate(), pgfdw_xact_callback(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresGetAnalyzeInfoForForeignTable(), postgresImportForeignSchema(), and postgresReScanForeignScan().

◆ pgfdw_finish_abort_cleanup()

static void pgfdw_finish_abort_cleanup ( List pending_entries,
List cancel_requested,
bool  toplevel 
)
static

Definition at line 1995 of file connection.c.

1997{
1999 ListCell *lc;
2000
2001 /*
2002 * For each of the pending cancel requests (if any), get and discard the
2003 * result of the query, and submit an abort command to the remote server.
2004 */
2005 if (cancel_requested)
2006 {
2007 foreach(lc, cancel_requested)
2008 {
2009 ConnCacheEntry *entry = (ConnCacheEntry *) lfirst(lc);
2013 char sql[100];
2014
2016
2017 /*
2018 * Set end time. You might think we should do this before issuing
2019 * cancel request like in normal mode, but that is problematic,
2020 * because if, for example, it took longer than 30 seconds to
2021 * process the first few entries in the cancel_requested list, it
2022 * would cause a timeout error when processing each of the
2023 * remaining entries in the list, leading to slamming that entry's
2024 * connection shut.
2025 */
2030
2031 if (!pgfdw_cancel_query_end(entry->conn, endtime,
2032 retrycanceltime, true))
2033 {
2034 /* Unable to cancel running query */
2035 pgfdw_reset_xact_state(entry, toplevel);
2036 continue;
2037 }
2038
2039 /* Send an abort command in parallel if needed */
2040 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
2041 if (!pgfdw_exec_cleanup_query_begin(entry->conn, sql))
2042 {
2043 /* Unable to abort remote (sub)transaction */
2044 pgfdw_reset_xact_state(entry, toplevel);
2045 }
2046 else
2048 }
2049 }
2050
2051 /* No further work if no pending entries */
2052 if (!pending_entries)
2053 return;
2054
2055 /*
2056 * Get the result of the abort command for each of the pending entries
2057 */
2058 foreach(lc, pending_entries)
2059 {
2060 ConnCacheEntry *entry = (ConnCacheEntry *) lfirst(lc);
2062 char sql[100];
2063
2065
2066 /*
2067 * Set end time. We do this now, not before issuing the command like
2068 * in normal mode, for the same reason as for the cancel_requested
2069 * entries.
2070 */
2073
2074 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
2075 if (!pgfdw_exec_cleanup_query_end(entry->conn, sql, endtime,
2076 true, false))
2077 {
2078 /* Unable to abort remote (sub)transaction */
2079 pgfdw_reset_xact_state(entry, toplevel);
2080 continue;
2081 }
2082
2083 if (toplevel)
2084 {
2085 /* Do a DEALLOCATE ALL in parallel if needed */
2086 if (entry->have_prep_stmt && entry->have_error)
2087 {
2089 "DEALLOCATE ALL"))
2090 {
2091 /* Trouble clearing prepared statements */
2092 pgfdw_reset_xact_state(entry, toplevel);
2093 }
2094 else
2096 continue;
2097 }
2098 entry->have_prep_stmt = false;
2099 entry->have_error = false;
2100 }
2101
2102 /* Reset the per-connection state if needed */
2103 if (entry->state.pendingAreq)
2104 memset(&entry->state, 0, sizeof(entry->state));
2105
2106 /* We're done with this entry; unset the changing_xact_state flag */
2107 entry->changing_xact_state = false;
2108 pgfdw_reset_xact_state(entry, toplevel);
2109 }
2110
2111 /* No further work if no pending entries */
2112 if (!pending_deallocs)
2113 return;
2114 Assert(toplevel);
2115
2116 /*
2117 * Get the result of the DEALLOCATE command for each of the pending
2118 * entries
2119 */
2120 foreach(lc, pending_deallocs)
2121 {
2122 ConnCacheEntry *entry = (ConnCacheEntry *) lfirst(lc);
2124
2126 Assert(entry->have_prep_stmt);
2127 Assert(entry->have_error);
2128
2129 /*
2130 * Set end time. We do this now, not before issuing the command like
2131 * in normal mode, for the same reason as for the cancel_requested
2132 * entries.
2133 */
2136
2137 if (!pgfdw_exec_cleanup_query_end(entry->conn, "DEALLOCATE ALL",
2138 endtime, true, true))
2139 {
2140 /* Trouble clearing prepared statements */
2141 pgfdw_reset_xact_state(entry, toplevel);
2142 continue;
2143 }
2144 entry->have_prep_stmt = false;
2145 entry->have_error = false;
2146
2147 /* Reset the per-connection state if needed */
2148 if (entry->state.pendingAreq)
2149 memset(&entry->state, 0, sizeof(entry->state));
2150
2151 /* We're done with this entry; unset the changing_xact_state flag */
2152 entry->changing_xact_state = false;
2153 pgfdw_reset_xact_state(entry, toplevel);
2154 }
2155}
static void pgfdw_reset_xact_state(ConnCacheEntry *entry, bool toplevel)
#define NIL
Definition pg_list.h:68
Definition pg_list.h:54

References Assert, ConnCacheEntry::changing_xact_state, ConnCacheEntry::conn, CONNECTION_CLEANUP_TIMEOUT, CONSTRUCT_ABORT_COMMAND, fb(), GetCurrentTimestamp(), ConnCacheEntry::have_error, ConnCacheEntry::have_prep_stmt, lappend(), lfirst, NIL, now(), PgFdwConnState::pendingAreq, pgfdw_cancel_query_end(), pgfdw_exec_cleanup_query_begin(), pgfdw_exec_cleanup_query_end(), pgfdw_reset_xact_state(), RETRY_CANCEL_TIMEOUT, ConnCacheEntry::state, and TimestampTzPlusMilliseconds.

Referenced by pgfdw_subxact_callback(), and pgfdw_xact_callback().

◆ pgfdw_finish_pre_commit_cleanup()

static void pgfdw_finish_pre_commit_cleanup ( List pending_entries)
static

Definition at line 1887 of file connection.c.

1888{
1889 ConnCacheEntry *entry;
1891 ListCell *lc;
1892
1894
1895 /*
1896 * Get the result of the COMMIT command for each of the pending entries
1897 */
1898 foreach(lc, pending_entries)
1899 {
1900 entry = (ConnCacheEntry *) lfirst(lc);
1901
1903
1904 /*
1905 * We might already have received the result on the socket, so pass
1906 * consume_input=true to try to consume it first
1907 */
1908 do_sql_command_end(entry->conn, "COMMIT TRANSACTION", true);
1909 entry->changing_xact_state = false;
1910
1911 /* Do a DEALLOCATE ALL in parallel if needed */
1912 if (entry->have_prep_stmt && entry->have_error)
1913 {
1914 /* Ignore errors (see notes in pgfdw_xact_callback) */
1915 if (PQsendQuery(entry->conn, "DEALLOCATE ALL"))
1916 {
1918 continue;
1919 }
1920 }
1921 entry->have_prep_stmt = false;
1922 entry->have_error = false;
1923
1924 pgfdw_reset_xact_state(entry, true);
1925 }
1926
1927 /* No further work if no pending entries */
1928 if (!pending_deallocs)
1929 return;
1930
1931 /*
1932 * Get the result of the DEALLOCATE command for each of the pending
1933 * entries
1934 */
1935 foreach(lc, pending_deallocs)
1936 {
1937 PGresult *res;
1938
1939 entry = (ConnCacheEntry *) lfirst(lc);
1940
1941 /* Ignore errors (see notes in pgfdw_xact_callback) */
1942 while ((res = PQgetResult(entry->conn)) != NULL)
1943 {
1944 PQclear(res);
1945 /* Stop if the connection is lost (else we'll loop infinitely) */
1946 if (PQstatus(entry->conn) == CONNECTION_BAD)
1947 break;
1948 }
1949 entry->have_prep_stmt = false;
1950 entry->have_error = false;
1951
1952 pgfdw_reset_xact_state(entry, true);
1953 }
1954}
#define PQgetResult

References Assert, ConnCacheEntry::changing_xact_state, ConnCacheEntry::conn, CONNECTION_BAD, do_sql_command_end(), fb(), ConnCacheEntry::have_error, ConnCacheEntry::have_prep_stmt, lappend(), lfirst, NIL, pgfdw_reset_xact_state(), PQclear, PQgetResult, PQsendQuery(), and PQstatus().

Referenced by pgfdw_xact_callback().

◆ pgfdw_finish_pre_subcommit_cleanup()

static void pgfdw_finish_pre_subcommit_cleanup ( List pending_entries,
int  curlevel 
)
static

Definition at line 1961 of file connection.c.

1962{
1963 ConnCacheEntry *entry;
1964 char sql[100];
1965 ListCell *lc;
1966
1968
1969 /*
1970 * Get the result of the RELEASE command for each of the pending entries
1971 */
1972 snprintf(sql, sizeof(sql), "RELEASE SAVEPOINT s%d", curlevel);
1973 foreach(lc, pending_entries)
1974 {
1975 entry = (ConnCacheEntry *) lfirst(lc);
1976
1978
1979 /*
1980 * We might already have received the result on the socket, so pass
1981 * consume_input=true to try to consume it first
1982 */
1983 do_sql_command_end(entry->conn, sql, true);
1984 entry->changing_xact_state = false;
1985
1986 pgfdw_reset_xact_state(entry, false);
1987 }
1988}

References Assert, ConnCacheEntry::changing_xact_state, ConnCacheEntry::conn, do_sql_command_end(), fb(), lfirst, pgfdw_reset_xact_state(), and snprintf.

Referenced by pgfdw_subxact_callback().

◆ pgfdw_get_cleanup_result()

static bool pgfdw_get_cleanup_result ( PGconn conn,
TimestampTz  endtime,
TimestampTz  retrycanceltime,
PGresult **  result,
bool timed_out 
)
static

Definition at line 1650 of file connection.c.

1654{
1655 bool failed = false;
1656 PGresult *last_res = NULL;
1658
1659 *result = NULL;
1660 *timed_out = false;
1661 for (;;)
1662 {
1663 PGresult *res;
1664
1665 while (PQisBusy(conn))
1666 {
1667 int wc;
1669 long cur_timeout;
1670
1671 /* If timeout has expired, give up. */
1672 if (now >= endtime)
1673 {
1674 *timed_out = true;
1675 failed = true;
1676 goto exit;
1677 }
1678
1679 /* If we need to re-issue the cancel request, do that. */
1680 if (now >= retrycanceltime)
1681 {
1682 /* We ignore failure to issue the repeated request. */
1684
1685 /* Recompute "now" in case that took measurable time. */
1687
1688 /* Adjust re-cancel timeout in increasing steps. */
1690 canceldelta);
1692 }
1693
1694 /* If timeout has expired, give up, else get sleep time. */
1696 Min(endtime,
1698 if (cur_timeout <= 0)
1699 {
1700 *timed_out = true;
1701 failed = true;
1702 goto exit;
1703 }
1704
1705 /* first time, allocate or get the custom wait event */
1706 if (pgfdw_we_cleanup_result == 0)
1707 pgfdw_we_cleanup_result = WaitEventExtensionNew("PostgresFdwCleanupResult");
1708
1709 /* Sleep until there's something to do */
1713 PQsocket(conn),
1716
1718
1719 /* Data available in socket? */
1720 if (wc & WL_SOCKET_READABLE)
1721 {
1722 if (!PQconsumeInput(conn))
1723 {
1724 /* connection trouble */
1725 failed = true;
1726 goto exit;
1727 }
1728 }
1729 }
1730
1731 res = PQgetResult(conn);
1732 if (res == NULL)
1733 break; /* query is complete */
1734
1735 PQclear(last_res);
1736 last_res = res;
1737 }
1738exit:
1739 if (failed)
1740 PQclear(last_res);
1741 else
1742 *result = last_res;
1743 return failed;
1744}
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition timestamp.c:1755
#define Min(x, y)
Definition c.h:1054
static uint32 pgfdw_we_cleanup_result
Definition connection.c:89
int PQisBusy(PGconn *conn)
Definition fe-exec.c:2048
struct Latch * MyLatch
Definition globals.c:63
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition latch.c:223
void ResetLatch(Latch *latch)
Definition latch.c:374
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:123
#define WL_SOCKET_READABLE
#define WL_TIMEOUT
#define WL_EXIT_ON_PM_DEATH
#define WL_LATCH_SET

References CHECK_FOR_INTERRUPTS, conn, fb(), GetCurrentTimestamp(), libpqsrv_cancel(), Min, MyLatch, now(), pgfdw_we_cleanup_result, PQclear, PQconsumeInput(), PQgetResult, PQisBusy(), PQsocket(), ResetLatch(), RETRY_CANCEL_TIMEOUT, TimestampDifferenceMilliseconds(), TimestampTzPlusMilliseconds, WaitEventExtensionNew(), WaitLatchOrSocket(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_SOCKET_READABLE, and WL_TIMEOUT.

Referenced by pgfdw_cancel_query_end(), and pgfdw_exec_cleanup_query_end().

◆ pgfdw_get_result()

PGresult * pgfdw_get_result ( PGconn conn)

Definition at line 985 of file connection.c.

986{
988}
static PGresult * libpqsrv_get_result_last(PGconn *conn, uint32 wait_event_info)

References conn, libpqsrv_get_result_last(), and pgfdw_we_get_result.

Referenced by create_cursor(), do_sql_command_end(), execute_dml_stmt(), execute_foreign_modify(), fetch_more_data(), pgfdw_exec_query(), and prepare_foreign_modify().

◆ pgfdw_has_required_scram_options()

static bool pgfdw_has_required_scram_options ( const char **  keywords,
const char **  values 
)
static

Definition at line 2595 of file connection.c.

2596{
2597 bool has_scram_server_key = false;
2598 bool has_scram_client_key = false;
2599 bool has_require_auth = false;
2600 bool has_scram_keys = false;
2601
2602 /*
2603 * Continue iterating even if we found the keys that we need to validate
2604 * to make sure that there is no other declaration of these keys that can
2605 * overwrite the first.
2606 */
2607 for (int i = 0; keywords[i] != NULL; i++)
2608 {
2609 if (strcmp(keywords[i], "scram_client_key") == 0)
2610 {
2611 if (values[i] != NULL && values[i][0] != '\0')
2612 has_scram_client_key = true;
2613 else
2614 has_scram_client_key = false;
2615 }
2616
2617 if (strcmp(keywords[i], "scram_server_key") == 0)
2618 {
2619 if (values[i] != NULL && values[i][0] != '\0')
2620 has_scram_server_key = true;
2621 else
2622 has_scram_server_key = false;
2623 }
2624
2625 if (strcmp(keywords[i], "require_auth") == 0)
2626 {
2627 if (values[i] != NULL && strcmp(values[i], "scram-sha-256") == 0)
2628 has_require_auth = true;
2629 else
2630 has_require_auth = false;
2631 }
2632 }
2633
2635
2636 return (has_scram_keys && has_require_auth);
2637}

References fb(), Port::has_scram_keys, i, keywords, MyProcPort, and values.

Referenced by check_conn_params(), and pgfdw_security_check().

◆ pgfdw_inval_callback()

static void pgfdw_inval_callback ( Datum  arg,
SysCacheIdentifier  cacheid,
uint32  hashvalue 
)
static

Definition at line 1333 of file connection.c.

1334{
1335 HASH_SEQ_STATUS scan;
1336 ConnCacheEntry *entry;
1337
1339
1340 /* ConnectionHash must exist already, if we're registered */
1342 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1343 {
1344 /* Ignore invalid entries */
1345 if (entry->conn == NULL)
1346 continue;
1347
1348 /* hashvalue == 0 means a cache reset, must clear all state */
1349 if (hashvalue == 0 ||
1351 entry->server_hashvalue == hashvalue) ||
1352 (cacheid == USERMAPPINGOID &&
1353 entry->mapping_hashvalue == hashvalue))
1354 {
1355 /*
1356 * Close the connection immediately if it's not used yet in this
1357 * transaction. Otherwise mark it as invalid so that
1358 * pgfdw_xact_callback() can close it at the end of this
1359 * transaction.
1360 */
1361 if (entry->xact_depth == 0)
1362 {
1363 elog(DEBUG3, "discarding connection %p", entry->conn);
1364 disconnect_pg_server(entry);
1365 }
1366 else
1367 entry->invalidated = true;
1368 }
1369 }
1370}

References Assert, ConnCacheEntry::conn, ConnectionHash, DEBUG3, disconnect_pg_server(), elog, fb(), hash_seq_init(), hash_seq_search(), ConnCacheEntry::invalidated, ConnCacheEntry::mapping_hashvalue, ConnCacheEntry::server_hashvalue, and ConnCacheEntry::xact_depth.

Referenced by GetConnection().

◆ pgfdw_reject_incomplete_xact_state_change()

static void pgfdw_reject_incomplete_xact_state_change ( ConnCacheEntry entry)
static

Definition at line 1383 of file connection.c.

1384{
1385 ForeignServer *server;
1386
1387 /* nothing to do for inactive entries and entries of sane state */
1388 if (entry->conn == NULL || !entry->changing_xact_state)
1389 return;
1390
1391 /* make sure this entry is inactive */
1392 disconnect_pg_server(entry);
1393
1394 /* find server name to be shown in the message below */
1395 server = GetForeignServer(entry->serverid);
1396
1397 ereport(ERROR,
1399 errmsg("connection to server \"%s\" was lost",
1400 server->servername)));
1401}

References ConnCacheEntry::changing_xact_state, ConnCacheEntry::conn, disconnect_pg_server(), ereport, errcode(), errmsg, ERROR, fb(), GetForeignServer(), ConnCacheEntry::serverid, and ForeignServer::servername.

Referenced by GetConnection(), pgfdw_subxact_callback(), and pgfdw_xact_callback().

◆ pgfdw_report()

void pgfdw_report ( int  elevel,
PGresult res,
PGconn conn,
const char sql 
)

Definition at line 1016 of file connection.c.

1017{
1018 Assert(elevel < ERROR); /* use pgfdw_report_error for that */
1019 pgfdw_report_internal(elevel, res, conn, sql);
1020}
static void pgfdw_report_internal(int elevel, PGresult *res, PGconn *conn, const char *sql)

References Assert, conn, ERROR, and pgfdw_report_internal().

Referenced by pgfdw_exec_cleanup_query_begin(), and pgfdw_exec_cleanup_query_end().

◆ pgfdw_report_error()

◆ pgfdw_report_internal()

static void pgfdw_report_internal ( int  elevel,
PGresult res,
PGconn conn,
const char sql 
)
static

Definition at line 1023 of file connection.c.

1025{
1031 int sqlstate;
1032
1033 if (diag_sqlstate)
1034 sqlstate = MAKE_SQLSTATE(diag_sqlstate[0],
1035 diag_sqlstate[1],
1036 diag_sqlstate[2],
1037 diag_sqlstate[3],
1038 diag_sqlstate[4]);
1039 else
1040 sqlstate = ERRCODE_CONNECTION_FAILURE;
1041
1042 /*
1043 * If we don't get a message from the PGresult, try the PGconn. This is
1044 * needed because for connection-level failures, PQgetResult may just
1045 * return NULL, not a PGresult at all.
1046 */
1047 if (message_primary == NULL)
1049
1050 ereport(elevel,
1051 (errcode(sqlstate),
1052 (message_primary != NULL && message_primary[0] != '\0') ?
1054 errmsg("could not obtain message string for remote error"),
1056 message_hint ? errhint("%s", message_hint) : 0,
1058 sql ? errcontext("remote SQL command: %s", sql) : 0));
1059 PQclear(res);
1060}
int errhint(const char *fmt,...) pg_attribute_printf(1
#define MAKE_SQLSTATE(ch1, ch2, ch3, ch4, ch5)
Definition elog.h:56
#define PQresultErrorField
#define PG_DIAG_MESSAGE_HINT
#define PG_DIAG_SQLSTATE
#define PG_DIAG_MESSAGE_PRIMARY
#define PG_DIAG_MESSAGE_DETAIL
#define PG_DIAG_CONTEXT

References conn, ereport, errcode(), errcontext, errdetail_internal(), errhint(), errmsg, errmsg_internal(), fb(), MAKE_SQLSTATE, pchomp(), PG_DIAG_CONTEXT, PG_DIAG_MESSAGE_DETAIL, PG_DIAG_MESSAGE_HINT, PG_DIAG_MESSAGE_PRIMARY, PG_DIAG_SQLSTATE, PQclear, PQerrorMessage(), and PQresultErrorField.

Referenced by pgfdw_report(), and pgfdw_report_error().

◆ pgfdw_reset_xact_state()

static void pgfdw_reset_xact_state ( ConnCacheEntry entry,
bool  toplevel 
)
static

Definition at line 1407 of file connection.c.

1408{
1409 if (toplevel)
1410 {
1411 /* Reset state to show we're out of a transaction */
1412 entry->xact_depth = 0;
1413
1414 /*
1415 * If the connection isn't in a good idle state, it is marked as
1416 * invalid or keep_connections option of its server is disabled, then
1417 * discard it to recover. Next GetConnection will open a new
1418 * connection.
1419 */
1420 if (PQstatus(entry->conn) != CONNECTION_OK ||
1422 entry->changing_xact_state ||
1423 entry->invalidated ||
1424 !entry->keep_connections)
1425 {
1426 elog(DEBUG3, "discarding connection %p", entry->conn);
1427 disconnect_pg_server(entry);
1428 }
1429 }
1430 else
1431 {
1432 /* Reset state to show we're out of a subtransaction */
1433 entry->xact_depth--;
1434 }
1435}
@ PQTRANS_IDLE
Definition libpq-fe.h:153

References ConnCacheEntry::changing_xact_state, ConnCacheEntry::conn, CONNECTION_OK, DEBUG3, disconnect_pg_server(), elog, ConnCacheEntry::invalidated, ConnCacheEntry::keep_connections, PQstatus(), PQTRANS_IDLE, PQtransactionStatus(), and ConnCacheEntry::xact_depth.

Referenced by pgfdw_finish_abort_cleanup(), pgfdw_finish_pre_commit_cleanup(), pgfdw_finish_pre_subcommit_cleanup(), pgfdw_subxact_callback(), and pgfdw_xact_callback().

◆ pgfdw_security_check()

static void pgfdw_security_check ( const char **  keywords,
const char **  values,
UserMapping user,
PGconn conn 
)
static

Definition at line 437 of file connection.c.

438{
439 /* Superusers bypass the check */
440 if (superuser_arg(user->userid))
441 return;
442
443#ifdef ENABLE_GSS
444 /* Connected via GSSAPI with delegated credentials- all good. */
446 return;
447#endif
448
449 /* Ok if superuser set PW required false. */
451 return;
452
453 /* Connected via PW, with PW required true, and provided non-empty PW. */
455 {
456 /* ok if params contain a non-empty password */
457 for (int i = 0; keywords[i] != NULL; i++)
458 {
459 if (strcmp(keywords[i], "password") == 0 && values[i][0] != '\0')
460 return;
461 }
462 }
463
464 /*
465 * Ok if SCRAM pass-through is being used and all required SCRAM options
466 * are set correctly. If pgfdw_has_required_scram_options returns true we
467 * assume that UseScramPassthrough is also true since SCRAM options are
468 * only set when UseScramPassthrough is enabled.
469 */
471 return;
472
475 errmsg("password or GSSAPI delegated credentials required"),
476 errdetail("Non-superuser cannot connect if the server does not request a password or use GSSAPI with delegated credentials."),
477 errhint("Target server's authentication method must be changed or password_required=false set in the user mapping attributes.")));
478}
int PQconnectionUsedPassword(const PGconn *conn)
int PQconnectionUsedGSSAPI(const PGconn *conn)

References be_gssapi_get_delegation(), conn, ereport, errcode(), errdetail(), errhint(), errmsg, ERROR, fb(), Port::has_scram_keys, i, keywords, MyProcPort, pgfdw_has_required_scram_options(), PQconnectionUsedGSSAPI(), PQconnectionUsedPassword(), superuser_arg(), user, UserMappingPasswordRequired(), and values.

Referenced by connect_pg_server().

◆ pgfdw_subxact_callback()

static void pgfdw_subxact_callback ( SubXactEvent  event,
SubTransactionId  mySubid,
SubTransactionId  parentSubid,
void arg 
)
static

Definition at line 1220 of file connection.c.

1222{
1223 HASH_SEQ_STATUS scan;
1224 ConnCacheEntry *entry;
1225 int curlevel;
1228
1229 /* Nothing to do at subxact start, nor after commit. */
1230 if (!(event == SUBXACT_EVENT_PRE_COMMIT_SUB ||
1231 event == SUBXACT_EVENT_ABORT_SUB))
1232 return;
1233
1234 /* Quick exit if no connections were touched in this transaction. */
1236 return;
1237
1238 /*
1239 * Scan all connection cache entries to find open remote subtransactions
1240 * of the current level, and close them.
1241 */
1244 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1245 {
1246 char sql[100];
1247
1248 /*
1249 * We only care about connections with open remote subtransactions of
1250 * the current level.
1251 */
1252 if (entry->conn == NULL || entry->xact_depth < curlevel)
1253 continue;
1254
1255 if (entry->xact_depth > curlevel)
1256 elog(ERROR, "missed cleaning up remote subtransaction at level %d",
1257 entry->xact_depth);
1258
1259 if (event == SUBXACT_EVENT_PRE_COMMIT_SUB)
1260 {
1261 /*
1262 * If abort cleanup previously failed for this connection, we
1263 * can't issue any more commands against it.
1264 */
1266
1267 /* Commit all remote subtransactions during pre-commit */
1268 snprintf(sql, sizeof(sql), "RELEASE SAVEPOINT s%d", curlevel);
1269 entry->changing_xact_state = true;
1270 if (entry->parallel_commit)
1271 {
1272 do_sql_command_begin(entry->conn, sql);
1274 continue;
1275 }
1276 do_sql_command(entry->conn, sql);
1277 entry->changing_xact_state = false;
1278 }
1279 else
1280 {
1281 /* Rollback all remote subtransactions during abort */
1282 if (entry->parallel_abort)
1283 {
1284 if (pgfdw_abort_cleanup_begin(entry, false,
1287 continue;
1288 }
1289 else
1290 pgfdw_abort_cleanup(entry, false);
1291 }
1292
1293 /* OK, we're outta that level of subtransaction */
1294 pgfdw_reset_xact_state(entry, false);
1295 }
1296
1297 /* If there are any pending connections, finish cleaning them up */
1299 {
1300 if (event == SUBXACT_EVENT_PRE_COMMIT_SUB)
1301 {
1304 }
1305 else
1306 {
1309 false);
1310 }
1311 }
1312}
static void pgfdw_finish_pre_subcommit_cleanup(List *pending_entries, int curlevel)
static void pgfdw_finish_abort_cleanup(List *pending_entries, List *cancel_requested, bool toplevel)
static bool pgfdw_abort_cleanup_begin(ConnCacheEntry *entry, bool toplevel, List **pending_entries, List **cancel_requested)
static void pgfdw_abort_cleanup(ConnCacheEntry *entry, bool toplevel)
@ SUBXACT_EVENT_PRE_COMMIT_SUB
Definition xact.h:146
@ SUBXACT_EVENT_ABORT_SUB
Definition xact.h:145

References Assert, ConnCacheEntry::changing_xact_state, ConnCacheEntry::conn, ConnectionHash, do_sql_command(), do_sql_command_begin(), elog, ERROR, fb(), GetCurrentTransactionNestLevel(), hash_seq_init(), hash_seq_search(), lappend(), NIL, ConnCacheEntry::parallel_abort, ConnCacheEntry::parallel_commit, pgfdw_abort_cleanup(), pgfdw_abort_cleanup_begin(), pgfdw_finish_abort_cleanup(), pgfdw_finish_pre_subcommit_cleanup(), pgfdw_reject_incomplete_xact_state_change(), pgfdw_reset_xact_state(), snprintf, SUBXACT_EVENT_ABORT_SUB, SUBXACT_EVENT_PRE_COMMIT_SUB, ConnCacheEntry::xact_depth, and xact_got_connection.

Referenced by GetConnection().

◆ pgfdw_xact_callback()

static void pgfdw_xact_callback ( XactEvent  event,
void arg 
)
static

Definition at line 1070 of file connection.c.

1071{
1072 HASH_SEQ_STATUS scan;
1073 ConnCacheEntry *entry;
1076
1077 /* Quick exit if no connections were touched in this transaction. */
1079 return;
1080
1081 /*
1082 * Scan all connection cache entries to find open remote transactions, and
1083 * close them.
1084 */
1086 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1087 {
1088 PGresult *res;
1089
1090 /* Ignore cache entry if no open connection right now */
1091 if (entry->conn == NULL)
1092 continue;
1093
1094 /* If it has an open remote transaction, try to close it */
1095 if (entry->xact_depth > 0)
1096 {
1097 elog(DEBUG3, "closing remote transaction on connection %p",
1098 entry->conn);
1099
1100 switch (event)
1101 {
1104
1105 /*
1106 * If abort cleanup previously failed for this connection,
1107 * we can't issue any more commands against it.
1108 */
1110
1111 /* Commit all remote transactions during pre-commit */
1112 entry->changing_xact_state = true;
1113 if (entry->parallel_commit)
1114 {
1115 do_sql_command_begin(entry->conn, "COMMIT TRANSACTION");
1117 continue;
1118 }
1119 do_sql_command(entry->conn, "COMMIT TRANSACTION");
1120 entry->changing_xact_state = false;
1121
1122 /*
1123 * If there were any errors in subtransactions, and we
1124 * made prepared statements, do a DEALLOCATE ALL to make
1125 * sure we get rid of all prepared statements. This is
1126 * annoying and not terribly bulletproof, but it's
1127 * probably not worth trying harder.
1128 *
1129 * DEALLOCATE ALL only exists in 8.3 and later, so this
1130 * constrains how old a server postgres_fdw can
1131 * communicate with. We intentionally ignore errors in
1132 * the DEALLOCATE, so that we can hobble along to some
1133 * extent with older servers (leaking prepared statements
1134 * as we go; but we don't really support update operations
1135 * pre-8.3 anyway).
1136 */
1137 if (entry->have_prep_stmt && entry->have_error)
1138 {
1139 res = pgfdw_exec_query(entry->conn, "DEALLOCATE ALL",
1140 NULL);
1141 PQclear(res);
1142 }
1143 entry->have_prep_stmt = false;
1144 entry->have_error = false;
1145 break;
1147
1148 /*
1149 * We disallow any remote transactions, since it's not
1150 * very reasonable to hold them open until the prepared
1151 * transaction is committed. For the moment, throw error
1152 * unconditionally; later we might allow read-only cases.
1153 * Note that the error will cause us to come right back
1154 * here with event == XACT_EVENT_ABORT, so we'll clean up
1155 * the connection state at that point.
1156 */
1157 ereport(ERROR,
1159 errmsg("cannot PREPARE a transaction that has operated on postgres_fdw foreign tables")));
1160 break;
1162 case XACT_EVENT_COMMIT:
1163 case XACT_EVENT_PREPARE:
1164 /* Pre-commit should have closed the open transaction */
1165 elog(ERROR, "missed cleaning up connection during pre-commit");
1166 break;
1168 case XACT_EVENT_ABORT:
1169 /* Rollback all remote transactions during abort */
1170 if (entry->parallel_abort)
1171 {
1172 if (pgfdw_abort_cleanup_begin(entry, true,
1175 continue;
1176 }
1177 else
1178 pgfdw_abort_cleanup(entry, true);
1179 break;
1180 }
1181 }
1182
1183 /* Reset state to show we're out of a transaction */
1184 pgfdw_reset_xact_state(entry, true);
1185 }
1186
1187 /* If there are any pending connections, finish cleaning them up */
1189 {
1190 if (event == XACT_EVENT_PARALLEL_PRE_COMMIT ||
1191 event == XACT_EVENT_PRE_COMMIT)
1192 {
1195 }
1196 else
1197 {
1199 event == XACT_EVENT_ABORT);
1201 true);
1202 }
1203 }
1204
1205 /*
1206 * Regardless of the event type, we can now mark ourselves as out of the
1207 * transaction. (Note: if we are here during PRE_COMMIT or PRE_PREPARE,
1208 * this saves a useless scan of the hashtable during COMMIT or PREPARE.)
1209 */
1210 xact_got_connection = false;
1211
1212 /* Also reset cursor numbering for next transaction */
1213 cursor_number = 0;
1214}
PGresult * pgfdw_exec_query(PGconn *conn, const char *query, PgFdwConnState *state)
Definition connection.c:968
static void pgfdw_finish_pre_commit_cleanup(List *pending_entries)
@ XACT_EVENT_PRE_PREPARE
Definition xact.h:136
@ XACT_EVENT_COMMIT
Definition xact.h:129
@ XACT_EVENT_PARALLEL_PRE_COMMIT
Definition xact.h:135
@ XACT_EVENT_PARALLEL_COMMIT
Definition xact.h:130
@ XACT_EVENT_ABORT
Definition xact.h:131
@ XACT_EVENT_PRE_COMMIT
Definition xact.h:134
@ XACT_EVENT_PARALLEL_ABORT
Definition xact.h:132
@ XACT_EVENT_PREPARE
Definition xact.h:133

References Assert, ConnCacheEntry::changing_xact_state, ConnCacheEntry::conn, ConnectionHash, cursor_number, DEBUG3, do_sql_command(), do_sql_command_begin(), elog, ereport, errcode(), errmsg, ERROR, fb(), hash_seq_init(), hash_seq_search(), ConnCacheEntry::have_error, ConnCacheEntry::have_prep_stmt, lappend(), NIL, ConnCacheEntry::parallel_abort, ConnCacheEntry::parallel_commit, pgfdw_abort_cleanup(), pgfdw_abort_cleanup_begin(), pgfdw_exec_query(), pgfdw_finish_abort_cleanup(), pgfdw_finish_pre_commit_cleanup(), pgfdw_reject_incomplete_xact_state_change(), pgfdw_reset_xact_state(), PQclear, ConnCacheEntry::xact_depth, XACT_EVENT_ABORT, XACT_EVENT_COMMIT, XACT_EVENT_PARALLEL_ABORT, XACT_EVENT_PARALLEL_COMMIT, XACT_EVENT_PARALLEL_PRE_COMMIT, XACT_EVENT_PRE_COMMIT, XACT_EVENT_PRE_PREPARE, XACT_EVENT_PREPARE, and xact_got_connection.

Referenced by GetConnection().

◆ postgres_fdw_connection()

Datum postgres_fdw_connection ( PG_FUNCTION_ARGS  )

Definition at line 2351 of file connection.c.

2352{
2353 Oid userid = PG_GETARG_OID(0);
2354 Oid serverid = PG_GETARG_OID(1);
2355 ForeignServer *server = GetForeignServer(serverid);
2356 UserMapping *user = GetUserMapping(userid, serverid);
2358 const char **keywords;
2359 const char **values;
2360 char *appname;
2361 char *sep = "";
2362
2363 construct_connection_params(server, user, &keywords, &values, &appname);
2364
2366 for (int i = 0; keywords[i] != NULL; i++)
2367 {
2368 if (values[i] == NULL)
2369 continue;
2370 appendStringInfo(&str, "%s%s = ", sep, keywords[i]);
2372 sep = " ";
2373 }
2374
2375 if (appname != NULL)
2376 pfree(appname);
2377 pfree(keywords);
2378 pfree(values);
2380}
static void appendEscapedValue(StringInfo str, const char *val)
#define PG_GETARG_OID(n)
Definition fmgr.h:275
#define PG_RETURN_TEXT_P(x)
Definition fmgr.h:374
UserMapping * GetUserMapping(Oid userid, Oid serverid)
Definition foreign.c:287
unsigned int Oid
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition stringinfo.c:145
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
text * cstring_to_text(const char *s)
Definition varlena.c:182

References appendEscapedValue(), appendStringInfo(), construct_connection_params(), cstring_to_text(), fb(), GetForeignServer(), GetUserMapping(), i, initStringInfo(), keywords, pfree(), PG_GETARG_OID, PG_RETURN_TEXT_P, str, user, and values.

◆ postgres_fdw_disconnect()

Datum postgres_fdw_disconnect ( PG_FUNCTION_ARGS  )

Definition at line 2419 of file connection.c.

2420{
2421 ForeignServer *server;
2422 char *servername;
2423
2424 servername = text_to_cstring(PG_GETARG_TEXT_PP(0));
2425 server = GetForeignServerByName(servername, false);
2426
2428}
static bool disconnect_cached_connections(Oid serverid)
#define PG_GETARG_TEXT_PP(n)
Definition fmgr.h:310
#define PG_RETURN_BOOL(x)
Definition fmgr.h:360
ForeignServer * GetForeignServerByName(const char *srvname, bool missing_ok)
Definition foreign.c:209
char * text_to_cstring(const text *t)
Definition varlena.c:215

References disconnect_cached_connections(), GetForeignServerByName(), PG_GETARG_TEXT_PP, PG_RETURN_BOOL, ForeignServer::serverid, and text_to_cstring().

◆ postgres_fdw_disconnect_all()

Datum postgres_fdw_disconnect_all ( PG_FUNCTION_ARGS  )

Definition at line 2440 of file connection.c.

2441{
2443}
#define InvalidOid

References disconnect_cached_connections(), InvalidOid, and PG_RETURN_BOOL.

◆ postgres_fdw_get_connections()

Datum postgres_fdw_get_connections ( PG_FUNCTION_ARGS  )

Definition at line 2399 of file connection.c.

2400{
2402
2404}
static void postgres_fdw_get_connections_internal(FunctionCallInfo fcinfo, enum pgfdwVersion api_version)
#define PG_RETURN_VOID()
Definition fmgr.h:350

References PG_RETURN_VOID, PGFDW_V1_1, and postgres_fdw_get_connections_internal().

◆ postgres_fdw_get_connections_1_2()

Datum postgres_fdw_get_connections_1_2 ( PG_FUNCTION_ARGS  )

Definition at line 2391 of file connection.c.

2392{
2394
2396}

References PG_RETURN_VOID, PGFDW_V1_2, and postgres_fdw_get_connections_internal().

◆ postgres_fdw_get_connections_internal()

static void postgres_fdw_get_connections_internal ( FunctionCallInfo  fcinfo,
enum pgfdwVersion  api_version 
)
static

Definition at line 2189 of file connection.c.

2191{
2193 HASH_SEQ_STATUS scan;
2194 ConnCacheEntry *entry;
2195
2196 InitMaterializedSRF(fcinfo, 0);
2197
2198 /* If cache doesn't exist, we return no records */
2199 if (!ConnectionHash)
2200 return;
2201
2202 /* Check we have the expected number of output arguments */
2203 switch (rsinfo->setDesc->natts)
2204 {
2206 if (api_version != PGFDW_V1_1)
2207 elog(ERROR, "incorrect number of output arguments");
2208 break;
2210 if (api_version != PGFDW_V1_2)
2211 elog(ERROR, "incorrect number of output arguments");
2212 break;
2213 default:
2214 elog(ERROR, "incorrect number of output arguments");
2215 }
2216
2218 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
2219 {
2220 ForeignServer *server;
2222 bool nulls[POSTGRES_FDW_GET_CONNECTIONS_COLS] = {0};
2223 int i = 0;
2224
2225 /* We only look for open remote connections */
2226 if (!entry->conn)
2227 continue;
2228
2230
2231 /*
2232 * The foreign server may have been dropped in current explicit
2233 * transaction. It is not possible to drop the server from another
2234 * session when the connection associated with it is in use in the
2235 * current transaction, if tried so, the drop query in another session
2236 * blocks until the current transaction finishes.
2237 *
2238 * Even though the server is dropped in the current transaction, the
2239 * cache can still have associated active connection entry, say we
2240 * call such connections dangling. Since we can not fetch the server
2241 * name from system catalogs for dangling connections, instead we show
2242 * NULL value for server name in output.
2243 *
2244 * We could have done better by storing the server name in the cache
2245 * entry instead of server oid so that it could be used in the output.
2246 * But the server name in each cache entry requires 64 bytes of
2247 * memory, which is huge, when there are many cached connections and
2248 * the use case i.e. dropping the foreign server within the explicit
2249 * current transaction seems rare. So, we chose to show NULL value for
2250 * server name in output.
2251 *
2252 * Such dangling connections get closed either in next use or at the
2253 * end of current explicit transaction in pgfdw_xact_callback.
2254 */
2255 if (!server)
2256 {
2257 /*
2258 * If the server has been dropped in the current explicit
2259 * transaction, then this entry would have been invalidated in
2260 * pgfdw_inval_callback at the end of drop server command. Note
2261 * that this connection would not have been closed in
2262 * pgfdw_inval_callback because it is still being used in the
2263 * current explicit transaction. So, assert that here.
2264 */
2265 Assert(entry->conn && entry->xact_depth > 0 && entry->invalidated);
2266
2267 /* Show null, if no server name was found */
2268 nulls[i++] = true;
2269 }
2270 else
2271 values[i++] = CStringGetTextDatum(server->servername);
2272
2273 if (api_version >= PGFDW_V1_2)
2274 {
2275 HeapTuple tp;
2276
2277 /* Use the system cache to obtain the user mapping */
2279
2280 /*
2281 * Just like in the foreign server case, user mappings can also be
2282 * dropped in the current explicit transaction. Therefore, the
2283 * similar check as in the server case is required.
2284 */
2285 if (!HeapTupleIsValid(tp))
2286 {
2287 /*
2288 * If we reach here, this entry must have been invalidated in
2289 * pgfdw_inval_callback, same as in the server case.
2290 */
2291 Assert(entry->conn && entry->xact_depth > 0 &&
2292 entry->invalidated);
2293
2294 nulls[i++] = true;
2295 }
2296 else
2297 {
2298 Oid userid;
2299
2300 userid = ((Form_pg_user_mapping) GETSTRUCT(tp))->umuser;
2302 ReleaseSysCache(tp);
2303 }
2304 }
2305
2306 values[i++] = BoolGetDatum(!entry->invalidated);
2307
2308 if (api_version >= PGFDW_V1_2)
2309 {
2310 bool check_conn = PG_GETARG_BOOL(0);
2311
2312 /* Is this connection used in the current transaction? */
2313 values[i++] = BoolGetDatum(entry->xact_depth > 0);
2314
2315 /*
2316 * If a connection status check is requested and supported, return
2317 * whether the connection is closed. Otherwise, return NULL.
2318 */
2320 values[i++] = BoolGetDatum(pgfdw_conn_check(entry->conn) != 0);
2321 else
2322 nulls[i++] = true;
2323
2324 /* Return process ID of remote backend */
2325 values[i++] = Int32GetDatum(PQbackendPID(entry->conn));
2326 }
2327
2328 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
2329 }
2330}
#define CStringGetTextDatum(s)
Definition builtins.h:98
#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2
static int pgfdw_conn_check(PGconn *conn)
#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1
#define POSTGRES_FDW_GET_CONNECTIONS_COLS
static bool pgfdw_conn_checkable(void)
int PQbackendPID(const PGconn *conn)
#define PG_GETARG_BOOL(n)
Definition fmgr.h:274
#define MappingUserName(userid)
Definition foreign.h:20
void InitMaterializedSRF(FunctionCallInfo fcinfo, bits32 flags)
Definition funcapi.c:76
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
END_CATALOG_STRUCT typedef FormData_pg_user_mapping * Form_pg_user_mapping
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
static Datum Int32GetDatum(int32 X)
Definition postgres.h:222
ConnCacheKey key
Definition connection.c:57
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:264
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:220
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition tuplestore.c:784

References Assert, BoolGetDatum(), ConnCacheEntry::conn, ConnectionHash, CStringGetTextDatum, elog, ERROR, fb(), Form_pg_user_mapping, FSV_MISSING_OK, GetForeignServerExtended(), GETSTRUCT(), hash_seq_init(), hash_seq_search(), HeapTupleIsValid, i, InitMaterializedSRF(), Int32GetDatum(), ConnCacheEntry::invalidated, ConnCacheEntry::key, MappingUserName, ObjectIdGetDatum(), PG_GETARG_BOOL, pgfdw_conn_check(), pgfdw_conn_checkable(), PGFDW_V1_1, PGFDW_V1_2, POSTGRES_FDW_GET_CONNECTIONS_COLS, POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1, POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2, PQbackendPID(), ReleaseSysCache(), FunctionCallInfoBaseData::resultinfo, SearchSysCache1(), ConnCacheEntry::serverid, ForeignServer::servername, tuplestore_putvalues(), values, and ConnCacheEntry::xact_depth.

Referenced by postgres_fdw_get_connections(), and postgres_fdw_get_connections_1_2().

◆ ReleaseConnection()

void ReleaseConnection ( PGconn conn)

Definition at line 918 of file connection.c.

919{
920 /*
921 * Currently, we don't actually track connection references because all
922 * cleanup is managed on a transaction or subtransaction basis instead. So
923 * there's nothing to do here.
924 */
925}

Referenced by estimate_path_cost_size(), finish_foreign_modify(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresEndDirectModify(), postgresEndForeignScan(), postgresGetAnalyzeInfoForForeignTable(), and postgresImportForeignSchema().

◆ UserMappingPasswordRequired()

static bool UserMappingPasswordRequired ( UserMapping user)
static

Definition at line 694 of file connection.c.

695{
696 ListCell *cell;
697
698 foreach(cell, user->options)
699 {
700 DefElem *def = (DefElem *) lfirst(cell);
701
702 if (strcmp(def->defname, "password_required") == 0)
703 return defGetBoolean(def);
704 }
705
706 return true;
707}

References defGetBoolean(), DefElem::defname, fb(), lfirst, and user.

Referenced by check_conn_params(), and pgfdw_security_check().

◆ UseScramPassthrough()

static bool UseScramPassthrough ( ForeignServer server,
UserMapping user 
)
static

Definition at line 710 of file connection.c.

711{
712 ListCell *cell;
713
714 foreach(cell, server->options)
715 {
716 DefElem *def = (DefElem *) lfirst(cell);
717
718 if (strcmp(def->defname, "use_scram_passthrough") == 0)
719 return defGetBoolean(def);
720 }
721
722 foreach(cell, user->options)
723 {
724 DefElem *def = (DefElem *) lfirst(cell);
725
726 if (strcmp(def->defname, "use_scram_passthrough") == 0)
727 return defGetBoolean(def);
728 }
729
730 return false;
731}

References defGetBoolean(), DefElem::defname, fb(), lfirst, ForeignServer::options, and user.

Referenced by construct_connection_params().

Variable Documentation

◆ ConnectionHash

◆ cursor_number

unsigned int cursor_number = 0
static

◆ pgfdw_we_cleanup_result

uint32 pgfdw_we_cleanup_result = 0
static

Definition at line 89 of file connection.c.

Referenced by pgfdw_get_cleanup_result().

◆ pgfdw_we_connect

uint32 pgfdw_we_connect = 0
static

Definition at line 90 of file connection.c.

Referenced by connect_pg_server().

◆ pgfdw_we_get_result

uint32 pgfdw_we_get_result = 0
static

Definition at line 91 of file connection.c.

Referenced by GetConnection(), and pgfdw_get_result().

◆ prep_stmt_number

unsigned int prep_stmt_number = 0
static

Definition at line 83 of file connection.c.

Referenced by GetPrepStmtNumber().

◆ xact_got_connection

bool xact_got_connection = false
static

Definition at line 86 of file connection.c.

Referenced by GetConnection(), pgfdw_subxact_callback(), and pgfdw_xact_callback().