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 "utils/tuplestore.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 int read_only_level = 0
 
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 106 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 116 of file connection.c.

117 { \
118 if (toplevel) \
119 snprintf((sql), sizeof(sql), \
120 "ABORT TRANSACTION"); \
122 snprintf((sql), sizeof(sql), \
123 "ROLLBACK TO SAVEPOINT s%d; RELEASE SAVEPOINT s%d", \
124 (entry)->xact_depth, (entry)->xact_depth); \
125 } while(0)

◆ POSTGRES_FDW_GET_CONNECTIONS_COLS

#define POSTGRES_FDW_GET_CONNECTIONS_COLS   6 /* maximum of above */

Definition at line 2271 of file connection.c.

◆ POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1

#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1   2

Definition at line 2269 of file connection.c.

◆ POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2

#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2   6

Definition at line 2270 of file connection.c.

◆ RETRY_CANCEL_TIMEOUT

#define RETRY_CANCEL_TIMEOUT   1000

Definition at line 113 of file connection.c.

Typedef Documentation

◆ ConnCacheEntry

◆ ConnCacheKey

Definition at line 54 of file connection.c.

Enumeration Type Documentation

◆ pgfdwVersion

Enumerator
PGFDW_V1_1 
PGFDW_V1_2 

Definition at line 130 of file connection.c.

131{
132 PGFDW_V1_1 = 0,
134};
@ PGFDW_V1_1
Definition connection.c:132
@ PGFDW_V1_2
Definition connection.c:133

Function Documentation

◆ appendEscapedValue()

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

Definition at line 2449 of file connection.c.

2450{
2452 for (int i = 0; val[i] != '\0'; i++)
2453 {
2454 if (val[i] == '\\' || val[i] == '\'')
2457 }
2459}
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 889 of file connection.c.

890{
892
893 /*
894 * If the current local (sub)transaction is read-only, set the topmost
895 * read-only local transaction's nesting level if we haven't yet.
896 *
897 * Note: once it's set, it's retained until the topmost read-only local
898 * transaction is committed/aborted (see pgfdw_xact_callback and
899 * pgfdw_subxact_callback).
900 */
901 if (XactReadOnly)
902 {
903 if (read_only_level == 0)
906 }
907 else
909
910 /*
911 * Start main transaction if we haven't yet; otherwise, change the current
912 * remote (sub)transaction's read/write mode if needed.
913 */
914 if (entry->xact_depth <= 0)
915 {
916 /*
917 * This is the case when we haven't yet started a main transaction.
918 */
919 StringInfoData sql;
920 bool ro = (read_only_level == 1);
921
922 elog(DEBUG3, "starting remote transaction on connection %p",
923 entry->conn);
924
925 initStringInfo(&sql);
926 appendStringInfoString(&sql, "START TRANSACTION ISOLATION LEVEL ");
928 appendStringInfoString(&sql, "SERIALIZABLE");
929 else
930 appendStringInfoString(&sql, "REPEATABLE READ");
931 if (ro)
932 appendStringInfoString(&sql, " READ ONLY");
933 if (XactDeferrable)
934 appendStringInfoString(&sql, " DEFERRABLE");
935 entry->changing_xact_state = true;
936 do_sql_command(entry->conn, sql.data);
937 entry->xact_depth = 1;
938 if (ro)
939 {
940 Assert(!entry->xact_read_only);
941 entry->xact_read_only = true;
942 }
943 entry->changing_xact_state = false;
944 }
945 else if (!entry->xact_read_only)
946 {
947 /*
948 * The remote (sub)transaction has been opened in read-write mode.
949 */
950 Assert(read_only_level == 0 ||
951 entry->xact_depth <= read_only_level);
952
953 /*
954 * If its nesting depth matches read_only_level, it means that the
955 * local read-write (sub)transaction that started it has changed to
956 * read-only after that; in which case change it to read-only as well.
957 * Otherwise, the local (sub)transaction is still read-write, so there
958 * is no need to do anything.
959 */
960 if (entry->xact_depth == read_only_level)
961 {
962 entry->changing_xact_state = true;
963 do_sql_command(entry->conn, "SET transaction_read_only = on");
964 entry->xact_read_only = true;
965 entry->changing_xact_state = false;
966 }
967 }
968 else
969 {
970 /*
971 * The remote (sub)transaction has been opened in read-only mode.
972 */
974 entry->xact_depth >= read_only_level);
975
976 /*
977 * The local read-only (sub)transaction that started it is guaranteed
978 * to be still read-only (see check_transaction_read_only), so there
979 * is no need to do anything.
980 */
981 }
982
983 /*
984 * If we're in a subtransaction, stack up savepoints to match our level.
985 * This ensures we can rollback just the desired effects when a
986 * subtransaction aborts.
987 */
988 while (entry->xact_depth < curlevel)
989 {
990 StringInfoData sql;
991 bool ro = (entry->xact_depth + 1 == read_only_level);
992
993 initStringInfo(&sql);
994 appendStringInfo(&sql, "SAVEPOINT s%d", entry->xact_depth + 1);
995 if (ro)
996 appendStringInfoString(&sql, "; SET transaction_read_only = on");
997 entry->changing_xact_state = true;
998 do_sql_command(entry->conn, sql.data);
999 entry->xact_depth++;
1000 if (ro)
1001 {
1002 Assert(!entry->xact_read_only);
1003 entry->xact_read_only = true;
1004 }
1005 entry->changing_xact_state = false;
1006 }
1007}
#define Assert(condition)
Definition c.h:943
void do_sql_command(PGconn *conn, const char *sql)
Definition connection.c:841
static int read_only_level
Definition connection.c:94
#define DEBUG3
Definition elog.h:29
#define elog(elevel,...)
Definition elog.h:228
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition stringinfo.c:230
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
PGconn * conn
Definition connection.c:59
bool changing_xact_state
Definition connection.c:66
bool xact_read_only
Definition connection.c:63
int GetCurrentTransactionNestLevel(void)
Definition xact.c:931
bool XactDeferrable
Definition xact.c:87
bool XactReadOnly
Definition xact.c:84
int GetTopReadOnlyTransactionNestLevel(void)
Definition xact.c:1062
#define IsolationIsSerializable()
Definition xact.h:53

References appendStringInfo(), appendStringInfoString(), Assert, ConnCacheEntry::changing_xact_state, ConnCacheEntry::conn, StringInfoData::data, DEBUG3, do_sql_command(), elog, fb(), GetCurrentTransactionNestLevel(), GetTopReadOnlyTransactionNestLevel(), initStringInfo(), IsolationIsSerializable, read_only_level, ConnCacheEntry::xact_depth, ConnCacheEntry::xact_read_only, XactDeferrable, and XactReadOnly.

Referenced by GetConnection().

◆ check_conn_params()

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

Definition at line 751 of file connection.c.

752{
753 int i;
754
755 /* no check required if superuser */
756 if (superuser_arg(user->userid))
757 return;
758
759#ifdef ENABLE_GSS
760 /* ok if the user provided their own delegated credentials */
762 return;
763#endif
764
765 /* ok if params contain a non-empty password */
766 for (i = 0; keywords[i] != NULL; i++)
767 {
768 if (strcmp(keywords[i], "password") == 0 && values[i][0] != '\0')
769 return;
770 }
771
772 /* ok if the superuser explicitly said so at user mapping creation time */
774 return;
775
776 /*
777 * Ok if SCRAM pass-through is being used and all required scram options
778 * are set correctly. If pgfdw_has_required_scram_options returns true we
779 * assume that UseScramPassthrough is also true since SCRAM options are
780 * only set when UseScramPassthrough is enabled.
781 */
783 return;
784
787 errmsg("password or GSSAPI delegated credentials required"),
788 errdetail("Non-superusers must delegate GSSAPI credentials, provide a password, or enable SCRAM pass-through in user mapping.")));
789}
bool be_gssapi_get_delegation(Port *port)
static Datum values[MAXATTR]
Definition bootstrap.c:190
static bool UserMappingPasswordRequired(UserMapping *user)
Definition connection.c:703
static bool pgfdw_has_required_scram_options(const char **keywords, const char **values)
int errcode(int sqlerrcode)
Definition elog.c:875
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define ERROR
Definition elog.h:40
#define ereport(elevel,...)
Definition elog.h:152
struct Port * MyProcPort
Definition globals.c:53
static const JsonPathKeyword keywords[]
static char * errmsg
static char * user
Definition pg_regress.c:121
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 803 of file connection.c.

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

630{
631 PGconn *volatile conn = NULL;
632
633 /*
634 * Use PG_TRY block to ensure closing connection on error.
635 */
636 PG_TRY();
637 {
638 const char **keywords;
639 const char **values;
640 char *appname;
641
642 construct_connection_params(server, user, &keywords, &values, &appname);
643
644 /* first time, allocate or get the custom wait event */
645 if (pgfdw_we_connect == 0)
646 pgfdw_we_connect = WaitEventExtensionNew("PostgresFdwConnect");
647
648 /* OK to make connection */
650 false, /* expand_dbname */
652
653 if (!conn || PQstatus(conn) != CONNECTION_OK)
656 errmsg("could not connect to server \"%s\"",
657 server->servername),
659
661 "received message via remote connection");
662
663 /* Perform post-connection security checks. */
665
666 /* Prepare new session for use */
668
669 if (appname != NULL)
670 pfree(appname);
672 pfree(values);
673 }
674 PG_CATCH();
675 {
677 PG_RE_THROW();
678 }
679 PG_END_TRY();
680
681 return conn;
682}
static void construct_connection_params(ForeignServer *server, UserMapping *user, const char ***p_keywords, const char ***p_values, char **p_appname)
Definition connection.c:495
static void configure_remote_session(PGconn *conn)
Definition connection.c:803
static void pgfdw_security_check(const char **keywords, const char **values, UserMapping *user, PGconn *conn)
Definition connection.c:446
static uint32 pgfdw_we_connect
Definition connection.c:98
#define PG_RE_THROW()
Definition elog.h:407
int int errdetail_internal(const char *fmt,...) pg_attribute_printf(1
#define PG_TRY(...)
Definition elog.h:374
#define PG_END_TRY(...)
Definition elog.h:399
#define PG_CATCH(...)
Definition elog.h:384
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:1619
char * pchomp(const char *in)
Definition mcxt.c:1938
char * servername
Definition foreign.h:40
uint32 WaitEventExtensionNew(const char *wait_event_name)
Definition wait_event.c:149

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 495 of file connection.c.

498{
499 const char **keywords;
500 const char **values;
501 char *appname = NULL;
502 int n;
503
504 /*
505 * Add 4 extra slots for application_name, fallback_application_name,
506 * client_encoding, end marker, and 3 extra slots for scram keys and
507 * required scram pass-through options.
508 */
509 n = list_length(server->options) + list_length(user->options) + 4 + 3;
510 keywords = (const char **) palloc(n * sizeof(char *));
511 values = (const char **) palloc(n * sizeof(char *));
512
513 n = 0;
515 keywords + n, values + n);
516 n += ExtractConnectionOptions(user->options,
517 keywords + n, values + n);
518
519 /*
520 * Use pgfdw_application_name as application_name if set.
521 *
522 * PQconnectdbParams() processes the parameter arrays from start to end.
523 * If any key word is repeated, the last value is used. Therefore note
524 * that pgfdw_application_name must be added to the arrays after options
525 * of ForeignServer are, so that it can override application_name set in
526 * ForeignServer.
527 */
529 {
530 keywords[n] = "application_name";
532 n++;
533 }
534
535 /*
536 * Search the parameter arrays to find application_name setting, and
537 * replace escape sequences in it with status information if found. The
538 * arrays are searched backwards because the last value is used if
539 * application_name is repeatedly set.
540 */
541 for (int i = n - 1; i >= 0; i--)
542 {
543 if (strcmp(keywords[i], "application_name") == 0 &&
544 *(values[i]) != '\0')
545 {
546 /*
547 * Use this application_name setting if it's not empty string even
548 * after any escape sequences in it are replaced.
549 */
550 appname = process_pgfdw_appname(values[i]);
551 if (appname[0] != '\0')
552 {
553 values[i] = appname;
554 break;
555 }
556
557 /*
558 * This empty application_name is not used, so we set values[i] to
559 * NULL and keep searching the array to find the next one.
560 */
561 values[i] = NULL;
562 pfree(appname);
563 appname = NULL;
564 }
565 }
566
567 *p_appname = appname;
568
569 /* Use "postgres_fdw" as fallback_application_name */
570 keywords[n] = "fallback_application_name";
571 values[n] = "postgres_fdw";
572 n++;
573
574 /* Set client_encoding so that libpq can convert encoding properly. */
575 keywords[n] = "client_encoding";
577 n++;
578
579 /* Add required SCRAM pass-through connection options if it's enabled. */
581 {
582 int len;
583 int encoded_len;
584
585 keywords[n] = "scram_client_key";
587 /* don't forget the zero-terminator */
588 values[n] = palloc0(len + 1);
591 (char *) values[n], len);
592 if (encoded_len < 0)
593 elog(ERROR, "could not encode SCRAM client key");
594 n++;
595
596 keywords[n] = "scram_server_key";
598 /* don't forget the zero-terminator */
599 values[n] = palloc0(len + 1);
602 (char *) values[n], len);
603 if (encoded_len < 0)
604 elog(ERROR, "could not encode SCRAM server key");
605 n++;
606
607 /*
608 * Require scram-sha-256 to ensure that no other auth method is used
609 * when connecting with foreign server.
610 */
611 keywords[n] = "require_auth";
612 values[n] = "scram-sha-256";
613 n++;
614 }
615
616 keywords[n] = values[n] = NULL;
617
618 /* Verify the set of connection parameters. */
620
622 *p_values = values;
623}
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:719
static void check_conn_params(const char **keywords, const char **values, UserMapping *user)
Definition connection.c:751
int ExtractConnectionOptions(List *defelems, const char **keywords, const char **values)
Definition option.c:418
char * pgfdw_application_name
Definition option.c:46
char * process_pgfdw_appname(const char *appname)
Definition option.c:495
const char * GetDatabaseEncodingName(void)
Definition mbutils.c:1395
void * palloc0(Size size)
Definition mcxt.c:1420
void * palloc(Size size)
Definition mcxt.c:1390
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 2579 of file connection.c.

2580{
2581 HASH_SEQ_STATUS scan;
2582 ConnCacheEntry *entry;
2583 bool all = !OidIsValid(serverid);
2584 bool result = false;
2585
2586 /*
2587 * Connection cache hashtable has not been initialized yet in this
2588 * session, so return false.
2589 */
2590 if (!ConnectionHash)
2591 return false;
2592
2594 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
2595 {
2596 /* Ignore cache entry if no open connection right now. */
2597 if (!entry->conn)
2598 continue;
2599
2600 if (all || entry->serverid == serverid)
2601 {
2602 /*
2603 * Emit a warning because the connection to close is used in the
2604 * current transaction and cannot be disconnected right now.
2605 */
2606 if (entry->xact_depth > 0)
2607 {
2608 ForeignServer *server;
2609
2610 server = GetForeignServerExtended(entry->serverid,
2612
2613 if (!server)
2614 {
2615 /*
2616 * If the foreign server was dropped while its connection
2617 * was used in the current transaction, the connection
2618 * must have been marked as invalid by
2619 * pgfdw_inval_callback at the end of DROP SERVER command.
2620 */
2621 Assert(entry->invalidated);
2622
2624 (errmsg("cannot close dropped server connection because it is still in use")));
2625 }
2626 else
2628 (errmsg("cannot close connection for server \"%s\" because it is still in use",
2629 server->servername)));
2630 }
2631 else
2632 {
2633 elog(DEBUG3, "discarding connection %p", entry->conn);
2634 disconnect_pg_server(entry);
2635 result = true;
2636 }
2637 }
2638 }
2639
2640 return result;
2641}
#define OidIsValid(objectId)
Definition c.h:858
uint32 result
static void disconnect_pg_server(ConnCacheEntry *entry)
Definition connection.c:688
static HTAB * ConnectionHash
Definition connection.c:81
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition dynahash.c:1352
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition dynahash.c:1317
#define WARNING
Definition elog.h:37
ForeignServer * GetForeignServerExtended(Oid serverid, uint16 flags)
Definition foreign.c:126
#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, result, 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

Definition at line 688 of file connection.c.

689{
690 if (entry->conn != NULL)
691 {
693 entry->conn = NULL;
694 }
695}

References ConnCacheEntry::conn, fb(), and libpqsrv_disconnect().

Referenced by disconnect_cached_connections(), GetConnection(), pgfdw_inval_callback(), and pgfdw_reset_xact_state().

◆ do_sql_command()

void do_sql_command ( PGconn conn,
const char sql 
)

Definition at line 841 of file connection.c.

842{
844 do_sql_command_end(conn, sql, false);
845}
static void do_sql_command_end(PGconn *conn, const char *sql, bool consume_input)
Definition connection.c:855
static void do_sql_command_begin(PGconn *conn, const char *sql)
Definition connection.c:848

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 848 of file connection.c.

849{
850 if (!PQsendQuery(conn, sql))
852}
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 855 of file connection.c.

856{
857 PGresult *res;
858
859 /*
860 * If requested, consume whatever data is available from the socket. (Note
861 * that if all data is available, this allows pgfdw_get_result to call
862 * PQgetResult without forcing the overhead of WaitLatchOrSocket, which
863 * would be large compared to the overhead of PQconsumeInput.)
864 */
867 res = pgfdw_get_result(conn);
869 pgfdw_report_error(res, conn, sql);
870 PQclear(res);
871}
PGresult * pgfdw_get_result(PGconn *conn)
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 216 of file connection.c.

217{
218 bool found;
219 bool retry = false;
220 ConnCacheEntry *entry;
223
224 /* First time through, initialize connection cache hashtable */
225 if (ConnectionHash == NULL)
226 {
227 HASHCTL ctl;
228
229 if (pgfdw_we_get_result == 0)
231 WaitEventExtensionNew("PostgresFdwGetResult");
232
233 ctl.keysize = sizeof(ConnCacheKey);
234 ctl.entrysize = sizeof(ConnCacheEntry);
235 ConnectionHash = hash_create("postgres_fdw connections", 8,
236 &ctl,
238
239 /*
240 * Register some callback functions that manage connection cleanup.
241 * This should be done just once in each backend.
242 */
249 }
250
251 /* Set flag that we did GetConnection during the current transaction */
252 xact_got_connection = true;
253
254 /* Create hash key for the entry. Assume no pad bytes in key struct */
255 key = user->umid;
256
257 /*
258 * Find or create cached entry for requested connection.
259 */
260 entry = hash_search(ConnectionHash, &key, HASH_ENTER, &found);
261 if (!found)
262 {
263 /*
264 * We need only clear "conn" here; remaining fields will be filled
265 * later when "conn" is set.
266 */
267 entry->conn = NULL;
268 }
269
270 /* Reject further use of connections which failed abort cleanup. */
272
273 /*
274 * If the connection needs to be remade due to invalidation, disconnect as
275 * soon as we're out of all transactions.
276 */
277 if (entry->conn != NULL && entry->invalidated && entry->xact_depth == 0)
278 {
279 elog(DEBUG3, "closing connection %p for option changes to take effect",
280 entry->conn);
282 }
283
284 /*
285 * If cache entry doesn't have a connection, we have to establish a new
286 * connection. (If connect_pg_server throws an error, the cache entry
287 * will remain in a valid empty state, ie conn == NULL.)
288 */
289 if (entry->conn == NULL)
291
292 /*
293 * We check the health of the cached connection here when using it. In
294 * cases where we're out of all transactions, if a broken connection is
295 * detected, we try to reestablish a new connection later.
296 */
297 PG_TRY();
298 {
299 /* Process a pending asynchronous request if any. */
300 if (entry->state.pendingAreq)
302 /* Start a new transaction or subtransaction if needed. */
303 begin_remote_xact(entry);
304 }
305 PG_CATCH();
306 {
309
310 /*
311 * Determine whether to try to reestablish the connection.
312 *
313 * After a broken connection is detected in libpq, any error other
314 * than connection failure (e.g., out-of-memory) can be thrown
315 * somewhere between return from libpq and the expected ereport() call
316 * in pgfdw_report_error(). In this case, since PQstatus() indicates
317 * CONNECTION_BAD, checking only PQstatus() causes the false detection
318 * of connection failure. To avoid this, we also verify that the
319 * error's sqlstate is ERRCODE_CONNECTION_FAILURE. Note that also
320 * checking only the sqlstate can cause another false detection
321 * because pgfdw_report_error() may report ERRCODE_CONNECTION_FAILURE
322 * for any libpq-originated error condition.
323 */
324 if (errdata->sqlerrcode != ERRCODE_CONNECTION_FAILURE ||
325 PQstatus(entry->conn) != CONNECTION_BAD ||
326 entry->xact_depth > 0)
327 {
329 PG_RE_THROW();
330 }
331
332 /* Clean up the error state */
335 errdata = NULL;
336
337 retry = true;
338 }
339 PG_END_TRY();
340
341 /*
342 * If a broken connection is detected, disconnect it, reestablish a new
343 * connection and retry a new remote transaction. If connection failure is
344 * reported again, we give up getting a connection.
345 */
346 if (retry)
347 {
348 Assert(entry->xact_depth == 0);
349
351 (errmsg_internal("could not start remote transaction on connection %p",
352 entry->conn)),
354
355 elog(DEBUG3, "closing connection %p to reestablish a new one",
356 entry->conn);
358
360
361 begin_remote_xact(entry);
362 }
363
364 /* Remember if caller will prepare statements */
366
367 /* If caller needs access to the per-connection state, return it. */
368 if (state)
369 *state = &entry->state;
370
371 return entry->conn;
372}
Oid ConnCacheKey
Definition connection.c:54
static uint32 pgfdw_we_get_result
Definition connection.c:99
static bool xact_got_connection
Definition connection.c:88
static void make_new_connection(ConnCacheEntry *entry, UserMapping *user)
Definition connection.c:379
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:889
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:889
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:360
void FreeErrorData(ErrorData *edata)
Definition elog.c:2014
ErrorData * CopyErrorData(void)
Definition elog.c:1942
void FlushErrorState(void)
Definition elog.c:2063
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
@ HASH_ENTER
Definition hsearch.h:109
#define HASH_ELEM
Definition hsearch.h:90
#define HASH_BLOBS
Definition hsearch.h:92
void CacheRegisterSyscacheCallback(SysCacheIdentifier cacheid, SyscacheCallbackFunction func, Datum arg)
Definition inval.c:1813
@ CONNECTION_BAD
Definition libpq-fe.h:91
MemoryContext CurrentMemoryContext
Definition mcxt.c:161
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:138
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:64
PgFdwConnState state
Definition connection.c:75
AsyncRequest * pendingAreq
void RegisterXactCallback(XactCallback callback, void *arg)
Definition xact.c:3855
void RegisterSubXactCallback(SubXactCallback callback, void *arg)
Definition xact.c:3915

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 1034 of file connection.c.

1035{
1036 return ++cursor_number;
1037}
static unsigned int cursor_number
Definition connection.c:84

References cursor_number.

Referenced by postgresAcquireSampleRowsFunc(), and postgresBeginForeignScan().

◆ GetPrepStmtNumber()

unsigned int GetPrepStmtNumber ( PGconn conn)

Definition at line 1048 of file connection.c.

1049{
1050 return ++prep_stmt_number;
1051}
static unsigned int prep_stmt_number
Definition connection.c:85

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 379 of file connection.c.

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

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 1866 of file connection.c.

1867{
1868 char sql[100];
1869
1870 /*
1871 * Don't try to clean up the connection if we're already in error
1872 * recursion trouble.
1873 */
1875 entry->changing_xact_state = true;
1876
1877 /*
1878 * If connection is already unsalvageable, don't touch it further.
1879 */
1880 if (entry->changing_xact_state)
1881 return;
1882
1883 /*
1884 * Mark this connection as in the process of changing transaction state.
1885 */
1886 entry->changing_xact_state = true;
1887
1888 /* Assume we might have lost track of prepared statements */
1889 entry->have_error = true;
1890
1891 /*
1892 * If a command has been submitted to the remote server by using an
1893 * asynchronous execution function, the command might not have yet
1894 * completed. Check to see if a command is still being processed by the
1895 * remote server, and if so, request cancellation of the command.
1896 */
1897 if (PQtransactionStatus(entry->conn) == PQTRANS_ACTIVE &&
1898 !pgfdw_cancel_query(entry->conn))
1899 return; /* Unable to cancel running query */
1900
1901 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
1902 if (!pgfdw_exec_cleanup_query(entry->conn, sql, false))
1903 return; /* Unable to abort remote (sub)transaction */
1904
1905 if (toplevel)
1906 {
1907 if (entry->have_prep_stmt && entry->have_error &&
1909 "DEALLOCATE ALL",
1910 true))
1911 return; /* Trouble clearing prepared statements */
1912
1913 entry->have_prep_stmt = false;
1914 entry->have_error = false;
1915 }
1916
1917 /*
1918 * If pendingAreq of the per-connection state is not NULL, it means that
1919 * an asynchronous fetch begun by fetch_more_data_begin() was not done
1920 * successfully and thus the per-connection state was not reset in
1921 * fetch_more_data(); in that case reset the per-connection state here.
1922 */
1923 if (entry->state.pendingAreq)
1924 memset(&entry->state, 0, sizeof(entry->state));
1925
1926 /* Disarm changing_xact_state if it all worked */
1927 entry->changing_xact_state = false;
1928}
#define CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel)
Definition connection.c:116
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:306
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 1940 of file connection.c.

1942{
1943 /*
1944 * Don't try to clean up the connection if we're already in error
1945 * recursion trouble.
1946 */
1948 entry->changing_xact_state = true;
1949
1950 /*
1951 * If connection is already unsalvageable, don't touch it further.
1952 */
1953 if (entry->changing_xact_state)
1954 return false;
1955
1956 /*
1957 * Mark this connection as in the process of changing transaction state.
1958 */
1959 entry->changing_xact_state = true;
1960
1961 /* Assume we might have lost track of prepared statements */
1962 entry->have_error = true;
1963
1964 /*
1965 * If a command has been submitted to the remote server by using an
1966 * asynchronous execution function, the command might not have yet
1967 * completed. Check to see if a command is still being processed by the
1968 * remote server, and if so, request cancellation of the command.
1969 */
1971 {
1973
1977 return false; /* Unable to cancel running query */
1979 }
1980 else
1981 {
1982 char sql[100];
1983
1984 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
1985 if (!pgfdw_exec_cleanup_query_begin(entry->conn, sql))
1986 return false; /* Unable to abort remote transaction */
1988 }
1989
1990 return true;
1991}
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1649
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:106
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 1563 of file connection.c.

1564{
1568
1569 /*
1570 * If it takes too long to cancel the query and discard the result, assume
1571 * the connection is dead.
1572 */
1574
1575 /*
1576 * Also, lose patience and re-issue the cancel request after a little bit.
1577 * (This serves to close some race conditions.)
1578 */
1580
1582 return false;
1584}
Datum now(PG_FUNCTION_ARGS)
Definition timestamp.c:1613
#define RETRY_CANCEL_TIMEOUT
Definition connection.c:113
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 1596 of file connection.c.

1597{
1598 const char *errormsg = libpqsrv_cancel(conn, endtime);
1599
1600 if (errormsg != NULL)
1603 errmsg("could not send cancel request: %s", errormsg));
1604
1605 return errormsg == NULL;
1606}
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 1609 of file connection.c.

1611{
1613 bool timed_out;
1614
1615 /*
1616 * If requested, consume whatever data is available from the socket. (Note
1617 * that if all data is available, this allows pgfdw_get_cleanup_result to
1618 * call PQgetResult without forcing the overhead of WaitLatchOrSocket,
1619 * which would be large compared to the overhead of PQconsumeInput.)
1620 */
1622 {
1625 errmsg("could not get result of cancel request: %s",
1627 return false;
1628 }
1629
1630 /* Get and discard the result of the query. */
1632 &result, &timed_out))
1633 {
1634 if (timed_out)
1636 (errmsg("could not get result of cancel request due to timeout")));
1637 else
1640 errmsg("could not get result of cancel request: %s",
1642
1643 return false;
1644 }
1645 PQclear(result);
1646
1647 return true;
1648}
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(), result, 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 2651 of file connection.c.

2652{
2653 int sock = PQsocket(conn);
2654
2655 if (PQstatus(conn) != CONNECTION_OK || sock == -1)
2656 return -1;
2657
2658#if (defined(HAVE_POLL) && defined(POLLRDHUP))
2659 {
2660 struct pollfd input_fd;
2661 int result;
2662
2663 input_fd.fd = sock;
2664 input_fd.events = POLLRDHUP;
2665 input_fd.revents = 0;
2666
2667 do
2668 result = poll(&input_fd, 1, 0);
2669 while (result < 0 && errno == EINTR);
2670
2671 if (result < 0)
2672 return -1;
2673
2674 return (input_fd.revents &
2675 (POLLRDHUP | POLLHUP | POLLERR | POLLNVAL)) ? 1 : 0;
2676 }
2677#else
2678 return 0;
2679#endif
2680}
int PQsocket(const PGconn *conn)
#define EINTR
Definition win32_port.h:361

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

Referenced by postgres_fdw_get_connections_internal().

◆ pgfdw_conn_checkable()

static bool pgfdw_conn_checkable ( void  )
static

Definition at line 2688 of file connection.c.

2689{
2690#if (defined(HAVE_POLL) && defined(POLLRDHUP))
2691 return true;
2692#else
2693 return false;
2694#endif
2695}

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 1663 of file connection.c.

1664{
1666
1667 /*
1668 * If it takes too long to execute a cleanup query, assume the connection
1669 * is dead. It's fairly likely that this is why we aborted in the first
1670 * place (e.g. statement timeout, user cancel), so the timeout shouldn't
1671 * be too long.
1672 */
1675
1677 return false;
1679 false, ignore_errors);
1680}
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 1683 of file connection.c.

1684{
1685 Assert(query != NULL);
1686
1687 /*
1688 * Submit a query. Since we don't use non-blocking mode, this also can
1689 * block. But its risk is relatively small, so we ignore that for now.
1690 */
1691 if (!PQsendQuery(conn, query))
1692 {
1693 pgfdw_report(WARNING, NULL, conn, query);
1694 return false;
1695 }
1696
1697 return true;
1698}
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 1701 of file connection.c.

1704{
1706 bool timed_out;
1707
1708 Assert(query != NULL);
1709
1710 /*
1711 * If requested, consume whatever data is available from the socket. (Note
1712 * that if all data is available, this allows pgfdw_get_cleanup_result to
1713 * call PQgetResult without forcing the overhead of WaitLatchOrSocket,
1714 * which would be large compared to the overhead of PQconsumeInput.)
1715 */
1717 {
1718 pgfdw_report(WARNING, NULL, conn, query);
1719 return false;
1720 }
1721
1722 /* Get the result of the query. */
1724 {
1725 if (timed_out)
1727 (errmsg("could not get query result due to timeout"),
1728 errcontext("remote SQL command: %s", query)));
1729 else
1730 pgfdw_report(WARNING, NULL, conn, query);
1731
1732 return false;
1733 }
1734
1735 /* Issue a warning if not successful. */
1737 {
1738 pgfdw_report(WARNING, result, conn, query);
1739 return ignore_errors;
1740 }
1741 PQclear(result);
1742
1743 return true;
1744}
#define errcontext
Definition elog.h:200

References Assert, conn, ereport, errcontext, errmsg, fb(), pgfdw_get_cleanup_result(), pgfdw_report(), PGRES_COMMAND_OK, PQclear, PQconsumeInput(), PQresultStatus, result, 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 
)

◆ pgfdw_finish_abort_cleanup()

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

Definition at line 2106 of file connection.c.

2108{
2110 ListCell *lc;
2111
2112 /*
2113 * For each of the pending cancel requests (if any), get and discard the
2114 * result of the query, and submit an abort command to the remote server.
2115 */
2116 if (cancel_requested)
2117 {
2118 foreach(lc, cancel_requested)
2119 {
2120 ConnCacheEntry *entry = (ConnCacheEntry *) lfirst(lc);
2124 char sql[100];
2125
2127
2128 /*
2129 * Set end time. You might think we should do this before issuing
2130 * cancel request like in normal mode, but that is problematic,
2131 * because if, for example, it took longer than 30 seconds to
2132 * process the first few entries in the cancel_requested list, it
2133 * would cause a timeout error when processing each of the
2134 * remaining entries in the list, leading to slamming that entry's
2135 * connection shut.
2136 */
2141
2142 if (!pgfdw_cancel_query_end(entry->conn, endtime,
2143 retrycanceltime, true))
2144 {
2145 /* Unable to cancel running query */
2146 pgfdw_reset_xact_state(entry, toplevel);
2147 continue;
2148 }
2149
2150 /* Send an abort command in parallel if needed */
2151 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
2152 if (!pgfdw_exec_cleanup_query_begin(entry->conn, sql))
2153 {
2154 /* Unable to abort remote (sub)transaction */
2155 pgfdw_reset_xact_state(entry, toplevel);
2156 }
2157 else
2159 }
2160 }
2161
2162 /* No further work if no pending entries */
2163 if (!pending_entries)
2164 return;
2165
2166 /*
2167 * Get the result of the abort command for each of the pending entries
2168 */
2169 foreach(lc, pending_entries)
2170 {
2171 ConnCacheEntry *entry = (ConnCacheEntry *) lfirst(lc);
2173 char sql[100];
2174
2176
2177 /*
2178 * Set end time. We do this now, not before issuing the command like
2179 * in normal mode, for the same reason as for the cancel_requested
2180 * entries.
2181 */
2184
2185 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
2186 if (!pgfdw_exec_cleanup_query_end(entry->conn, sql, endtime,
2187 true, false))
2188 {
2189 /* Unable to abort remote (sub)transaction */
2190 pgfdw_reset_xact_state(entry, toplevel);
2191 continue;
2192 }
2193
2194 if (toplevel)
2195 {
2196 /* Do a DEALLOCATE ALL in parallel if needed */
2197 if (entry->have_prep_stmt && entry->have_error)
2198 {
2200 "DEALLOCATE ALL"))
2201 {
2202 /* Trouble clearing prepared statements */
2203 pgfdw_reset_xact_state(entry, toplevel);
2204 }
2205 else
2207 continue;
2208 }
2209 entry->have_prep_stmt = false;
2210 entry->have_error = false;
2211 }
2212
2213 /* Reset the per-connection state if needed */
2214 if (entry->state.pendingAreq)
2215 memset(&entry->state, 0, sizeof(entry->state));
2216
2217 /* We're done with this entry; unset the changing_xact_state flag */
2218 entry->changing_xact_state = false;
2219 pgfdw_reset_xact_state(entry, toplevel);
2220 }
2221
2222 /* No further work if no pending entries */
2223 if (!pending_deallocs)
2224 return;
2225 Assert(toplevel);
2226
2227 /*
2228 * Get the result of the DEALLOCATE command for each of the pending
2229 * entries
2230 */
2231 foreach(lc, pending_deallocs)
2232 {
2233 ConnCacheEntry *entry = (ConnCacheEntry *) lfirst(lc);
2235
2237 Assert(entry->have_prep_stmt);
2238 Assert(entry->have_error);
2239
2240 /*
2241 * Set end time. We do this now, not before issuing the command like
2242 * in normal mode, for the same reason as for the cancel_requested
2243 * entries.
2244 */
2247
2248 if (!pgfdw_exec_cleanup_query_end(entry->conn, "DEALLOCATE ALL",
2249 endtime, true, true))
2250 {
2251 /* Trouble clearing prepared statements */
2252 pgfdw_reset_xact_state(entry, toplevel);
2253 continue;
2254 }
2255 entry->have_prep_stmt = false;
2256 entry->have_error = false;
2257
2258 /* Reset the per-connection state if needed */
2259 if (entry->state.pendingAreq)
2260 memset(&entry->state, 0, sizeof(entry->state));
2261
2262 /* We're done with this entry; unset the changing_xact_state flag */
2263 entry->changing_xact_state = false;
2264 pgfdw_reset_xact_state(entry, toplevel);
2265 }
2266}
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 1998 of file connection.c.

1999{
2000 ConnCacheEntry *entry;
2002 ListCell *lc;
2003
2005
2006 /*
2007 * Get the result of the COMMIT command for each of the pending entries
2008 */
2009 foreach(lc, pending_entries)
2010 {
2011 entry = (ConnCacheEntry *) lfirst(lc);
2012
2014
2015 /*
2016 * We might already have received the result on the socket, so pass
2017 * consume_input=true to try to consume it first
2018 */
2019 do_sql_command_end(entry->conn, "COMMIT TRANSACTION", true);
2020 entry->changing_xact_state = false;
2021
2022 /* Do a DEALLOCATE ALL in parallel if needed */
2023 if (entry->have_prep_stmt && entry->have_error)
2024 {
2025 /* Ignore errors (see notes in pgfdw_xact_callback) */
2026 if (PQsendQuery(entry->conn, "DEALLOCATE ALL"))
2027 {
2029 continue;
2030 }
2031 }
2032 entry->have_prep_stmt = false;
2033 entry->have_error = false;
2034
2035 pgfdw_reset_xact_state(entry, true);
2036 }
2037
2038 /* No further work if no pending entries */
2039 if (!pending_deallocs)
2040 return;
2041
2042 /*
2043 * Get the result of the DEALLOCATE command for each of the pending
2044 * entries
2045 */
2046 foreach(lc, pending_deallocs)
2047 {
2048 PGresult *res;
2049
2050 entry = (ConnCacheEntry *) lfirst(lc);
2051
2052 /* Ignore errors (see notes in pgfdw_xact_callback) */
2053 while ((res = PQgetResult(entry->conn)) != NULL)
2054 {
2055 PQclear(res);
2056 /* Stop if the connection is lost (else we'll loop infinitely) */
2057 if (PQstatus(entry->conn) == CONNECTION_BAD)
2058 break;
2059 }
2060 entry->have_prep_stmt = false;
2061 entry->have_error = false;
2062
2063 pgfdw_reset_xact_state(entry, true);
2064 }
2065}
#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 2072 of file connection.c.

2073{
2074 ConnCacheEntry *entry;
2075 char sql[100];
2076 ListCell *lc;
2077
2079
2080 /*
2081 * Get the result of the RELEASE command for each of the pending entries
2082 */
2083 snprintf(sql, sizeof(sql), "RELEASE SAVEPOINT s%d", curlevel);
2084 foreach(lc, pending_entries)
2085 {
2086 entry = (ConnCacheEntry *) lfirst(lc);
2087
2089
2090 /*
2091 * We might already have received the result on the socket, so pass
2092 * consume_input=true to try to consume it first
2093 */
2094 do_sql_command_end(entry->conn, sql, true);
2095 entry->changing_xact_state = false;
2096
2097 pgfdw_reset_xact_state(entry, false);
2098 }
2099}
#define snprintf
Definition port.h:261

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 1761 of file connection.c.

1765{
1766 bool failed = false;
1767 PGresult *last_res = NULL;
1769
1770 *result = NULL;
1771 *timed_out = false;
1772 for (;;)
1773 {
1774 PGresult *res;
1775
1776 while (PQisBusy(conn))
1777 {
1778 int wc;
1780 long cur_timeout;
1781
1782 /* If timeout has expired, give up. */
1783 if (now >= endtime)
1784 {
1785 *timed_out = true;
1786 failed = true;
1787 goto exit;
1788 }
1789
1790 /* If we need to re-issue the cancel request, do that. */
1791 if (now >= retrycanceltime)
1792 {
1793 /* We ignore failure to issue the repeated request. */
1795
1796 /* Recompute "now" in case that took measurable time. */
1798
1799 /* Adjust re-cancel timeout in increasing steps. */
1801 canceldelta);
1803 }
1804
1805 /* If timeout has expired, give up, else get sleep time. */
1807 Min(endtime,
1809 if (cur_timeout <= 0)
1810 {
1811 *timed_out = true;
1812 failed = true;
1813 goto exit;
1814 }
1815
1816 /* first time, allocate or get the custom wait event */
1817 if (pgfdw_we_cleanup_result == 0)
1818 pgfdw_we_cleanup_result = WaitEventExtensionNew("PostgresFdwCleanupResult");
1819
1820 /* Sleep until there's something to do */
1824 PQsocket(conn),
1827
1829
1830 /* Data available in socket? */
1831 if (wc & WL_SOCKET_READABLE)
1832 {
1833 if (!PQconsumeInput(conn))
1834 {
1835 /* connection trouble */
1836 failed = true;
1837 goto exit;
1838 }
1839 }
1840 }
1841
1842 res = PQgetResult(conn);
1843 if (res == NULL)
1844 break; /* query is complete */
1845
1846 PQclear(last_res);
1847 last_res = res;
1848 }
1849exit:
1850 if (failed)
1851 PQclear(last_res);
1852 else
1853 *result = last_res;
1854 return failed;
1855}
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition timestamp.c:1765
#define Min(x, y)
Definition c.h:1091
static uint32 pgfdw_we_cleanup_result
Definition connection.c:97
int PQisBusy(PGconn *conn)
Definition fe-exec.c:2048
struct Latch * MyLatch
Definition globals.c:65
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:125
#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(), result, 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 1080 of file connection.c.

1081{
1083}
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 2706 of file connection.c.

2707{
2708 bool has_scram_server_key = false;
2709 bool has_scram_client_key = false;
2710 bool has_require_auth = false;
2711 bool has_scram_keys = false;
2712
2713 /*
2714 * Continue iterating even if we found the keys that we need to validate
2715 * to make sure that there is no other declaration of these keys that can
2716 * overwrite the first.
2717 */
2718 for (int i = 0; keywords[i] != NULL; i++)
2719 {
2720 if (strcmp(keywords[i], "scram_client_key") == 0)
2721 {
2722 if (values[i] != NULL && values[i][0] != '\0')
2723 has_scram_client_key = true;
2724 else
2725 has_scram_client_key = false;
2726 }
2727
2728 if (strcmp(keywords[i], "scram_server_key") == 0)
2729 {
2730 if (values[i] != NULL && values[i][0] != '\0')
2731 has_scram_server_key = true;
2732 else
2733 has_scram_server_key = false;
2734 }
2735
2736 if (strcmp(keywords[i], "require_auth") == 0)
2737 {
2738 if (values[i] != NULL && strcmp(values[i], "scram-sha-256") == 0)
2739 has_require_auth = true;
2740 else
2741 has_require_auth = false;
2742 }
2743 }
2744
2746
2747 return (has_scram_keys && has_require_auth);
2748}

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 1435 of file connection.c.

1436{
1437 HASH_SEQ_STATUS scan;
1438 ConnCacheEntry *entry;
1439
1441
1442 /* ConnectionHash must exist already, if we're registered */
1444 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1445 {
1446 /* Ignore invalid entries */
1447 if (entry->conn == NULL)
1448 continue;
1449
1450 /* hashvalue == 0 means a cache reset, must clear all state */
1451 if (hashvalue == 0 ||
1453 entry->server_hashvalue == hashvalue) ||
1454 (cacheid == USERMAPPINGOID &&
1455 entry->mapping_hashvalue == hashvalue))
1456 {
1457 /*
1458 * Close the connection immediately if it's not used yet in this
1459 * transaction. Otherwise mark it as invalid so that
1460 * pgfdw_xact_callback() can close it at the end of this
1461 * transaction.
1462 */
1463 if (entry->xact_depth == 0)
1464 {
1465 elog(DEBUG3, "discarding connection %p", entry->conn);
1466 disconnect_pg_server(entry);
1467 }
1468 else
1469 entry->invalidated = true;
1470 }
1471 }
1472}

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 1490 of file connection.c.

1491{
1492 ForeignServer *server;
1493
1494 /* nothing to do for inactive entries and entries of sane state */
1495 if (entry->conn == NULL || !entry->changing_xact_state)
1496 return;
1497
1498 /* find server name to be shown in the message below */
1499 server = GetForeignServer(entry->serverid);
1500
1501 ereport(ERROR,
1503 errmsg("connection to server \"%s\" cannot be used due to abort cleanup failure",
1504 server->servername)));
1505}

References ConnCacheEntry::changing_xact_state, ConnCacheEntry::conn, 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 1111 of file connection.c.

1112{
1113 Assert(elevel < ERROR); /* use pgfdw_report_error for that */
1114 pgfdw_report_internal(elevel, res, conn, sql);
1115}
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 1118 of file connection.c.

1120{
1126 int sqlstate;
1127
1128 if (diag_sqlstate)
1129 sqlstate = MAKE_SQLSTATE(diag_sqlstate[0],
1130 diag_sqlstate[1],
1131 diag_sqlstate[2],
1132 diag_sqlstate[3],
1133 diag_sqlstate[4]);
1134 else
1135 sqlstate = ERRCODE_CONNECTION_FAILURE;
1136
1137 /*
1138 * If we don't get a message from the PGresult, try the PGconn. This is
1139 * needed because for connection-level failures, PQgetResult may just
1140 * return NULL, not a PGresult at all.
1141 */
1142 if (message_primary == NULL)
1144
1145 ereport(elevel,
1146 (errcode(sqlstate),
1147 (message_primary != NULL && message_primary[0] != '\0') ?
1149 errmsg("could not obtain message string for remote error"),
1151 message_hint ? errhint("%s", message_hint) : 0,
1153 sql ? errcontext("remote SQL command: %s", sql) : 0));
1154 PQclear(res);
1155}
int errhint(const char *fmt,...) pg_attribute_printf(1
#define MAKE_SQLSTATE(ch1, ch2, ch3, ch4, ch5)
Definition elog.h:58
#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 1511 of file connection.c.

1512{
1513 if (toplevel)
1514 {
1515 /* Reset state to show we're out of a transaction */
1516 entry->xact_depth = 0;
1517
1518 /* Reset xact r/o state */
1519 entry->xact_read_only = false;
1520
1521 /*
1522 * If the connection isn't in a good idle state, it is marked as
1523 * invalid or keep_connections option of its server is disabled, then
1524 * discard it to recover. Next GetConnection will open a new
1525 * connection.
1526 */
1527 if (PQstatus(entry->conn) != CONNECTION_OK ||
1529 entry->changing_xact_state ||
1530 entry->invalidated ||
1531 !entry->keep_connections)
1532 {
1533 elog(DEBUG3, "discarding connection %p", entry->conn);
1534 disconnect_pg_server(entry);
1535 }
1536 }
1537 else
1538 {
1539 /* Reset state to show we're out of a subtransaction */
1540 entry->xact_depth--;
1541
1542 /* If in read_only_level, reset xact r/o state */
1543 if (entry->xact_depth + 1 == read_only_level)
1544 entry->xact_read_only = false;
1545 }
1546}
@ 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(), read_only_level, ConnCacheEntry::xact_depth, and ConnCacheEntry::xact_read_only.

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 446 of file connection.c.

447{
448 /* Superusers bypass the check */
449 if (superuser_arg(user->userid))
450 return;
451
452#ifdef ENABLE_GSS
453 /* Connected via GSSAPI with delegated credentials- all good. */
455 return;
456#endif
457
458 /* Ok if superuser set PW required false. */
460 return;
461
462 /* Connected via PW, with PW required true, and provided non-empty PW. */
464 {
465 /* ok if params contain a non-empty password */
466 for (int i = 0; keywords[i] != NULL; i++)
467 {
468 if (strcmp(keywords[i], "password") == 0 && values[i][0] != '\0')
469 return;
470 }
471 }
472
473 /*
474 * Ok if SCRAM pass-through is being used and all required SCRAM options
475 * are set correctly. If pgfdw_has_required_scram_options returns true we
476 * assume that UseScramPassthrough is also true since SCRAM options are
477 * only set when UseScramPassthrough is enabled.
478 */
480 return;
481
484 errmsg("password or GSSAPI delegated credentials required"),
485 errdetail("Non-superuser cannot connect if the server does not request a password or use GSSAPI with delegated credentials."),
486 errhint("Target server's authentication method must be changed or password_required=false set in the user mapping attributes.")));
487}
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 1318 of file connection.c.

1320{
1321 HASH_SEQ_STATUS scan;
1322 ConnCacheEntry *entry;
1323 int curlevel;
1326
1327 /* Nothing to do at subxact start, nor after commit. */
1328 if (!(event == SUBXACT_EVENT_PRE_COMMIT_SUB ||
1329 event == SUBXACT_EVENT_ABORT_SUB))
1330 return;
1331
1332 /* Quick exit if no connections were touched in this transaction. */
1334 return;
1335
1336 /*
1337 * Scan all connection cache entries to find open remote subtransactions
1338 * of the current level, and close them.
1339 */
1342 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1343 {
1344 char sql[100];
1345
1346 /*
1347 * We only care about connections with open remote subtransactions of
1348 * the current level.
1349 */
1350 if (entry->conn == NULL || entry->xact_depth < curlevel)
1351 continue;
1352
1353 if (entry->xact_depth > curlevel)
1354 elog(ERROR, "missed cleaning up remote subtransaction at level %d",
1355 entry->xact_depth);
1356
1357 if (event == SUBXACT_EVENT_PRE_COMMIT_SUB)
1358 {
1359 /*
1360 * If abort cleanup previously failed for this connection, we
1361 * can't issue any more commands against it.
1362 */
1364
1365 /* Commit all remote subtransactions during pre-commit */
1366 snprintf(sql, sizeof(sql), "RELEASE SAVEPOINT s%d", curlevel);
1367 entry->changing_xact_state = true;
1368 if (entry->parallel_commit)
1369 {
1370 do_sql_command_begin(entry->conn, sql);
1372 continue;
1373 }
1374 do_sql_command(entry->conn, sql);
1375 entry->changing_xact_state = false;
1376 }
1377 else
1378 {
1379 /* Rollback all remote subtransactions during abort */
1380 if (entry->parallel_abort)
1381 {
1382 if (pgfdw_abort_cleanup_begin(entry, false,
1385 continue;
1386 }
1387 else
1388 pgfdw_abort_cleanup(entry, false);
1389 }
1390
1391 /* OK, we're outta that level of subtransaction */
1392 pgfdw_reset_xact_state(entry, false);
1393 }
1394
1395 /* If there are any pending connections, finish cleaning them up */
1397 {
1398 if (event == SUBXACT_EVENT_PRE_COMMIT_SUB)
1399 {
1402 }
1403 else
1404 {
1407 false);
1408 }
1409 }
1410
1411 /* If in read_only_level, reset it */
1413 read_only_level = 0;
1414}
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(), read_only_level, 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 1165 of file connection.c.

1166{
1167 HASH_SEQ_STATUS scan;
1168 ConnCacheEntry *entry;
1171
1172 /* Quick exit if no connections were touched in this transaction. */
1174 return;
1175
1176 /*
1177 * Scan all connection cache entries to find open remote transactions, and
1178 * close them.
1179 */
1181 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1182 {
1183 PGresult *res;
1184
1185 /* Ignore cache entry if no open connection right now */
1186 if (entry->conn == NULL)
1187 continue;
1188
1189 /* If it has an open remote transaction, try to close it */
1190 if (entry->xact_depth > 0)
1191 {
1192 elog(DEBUG3, "closing remote transaction on connection %p",
1193 entry->conn);
1194
1195 switch (event)
1196 {
1199
1200 /*
1201 * If abort cleanup previously failed for this connection,
1202 * we can't issue any more commands against it.
1203 */
1205
1206 /* Commit all remote transactions during pre-commit */
1207 entry->changing_xact_state = true;
1208 if (entry->parallel_commit)
1209 {
1210 do_sql_command_begin(entry->conn, "COMMIT TRANSACTION");
1212 continue;
1213 }
1214 do_sql_command(entry->conn, "COMMIT TRANSACTION");
1215 entry->changing_xact_state = false;
1216
1217 /*
1218 * If there were any errors in subtransactions, and we
1219 * made prepared statements, do a DEALLOCATE ALL to make
1220 * sure we get rid of all prepared statements. This is
1221 * annoying and not terribly bulletproof, but it's
1222 * probably not worth trying harder.
1223 *
1224 * DEALLOCATE ALL only exists in 8.3 and later, so this
1225 * constrains how old a server postgres_fdw can
1226 * communicate with. We intentionally ignore errors in
1227 * the DEALLOCATE, so that we can hobble along to some
1228 * extent with older servers (leaking prepared statements
1229 * as we go; but we don't really support update operations
1230 * pre-8.3 anyway).
1231 */
1232 if (entry->have_prep_stmt && entry->have_error)
1233 {
1234 res = pgfdw_exec_query(entry->conn, "DEALLOCATE ALL",
1235 NULL);
1236 PQclear(res);
1237 }
1238 entry->have_prep_stmt = false;
1239 entry->have_error = false;
1240 break;
1242
1243 /*
1244 * We disallow any remote transactions, since it's not
1245 * very reasonable to hold them open until the prepared
1246 * transaction is committed. For the moment, throw error
1247 * unconditionally; later we might allow read-only cases.
1248 * Note that the error will cause us to come right back
1249 * here with event == XACT_EVENT_ABORT, so we'll clean up
1250 * the connection state at that point.
1251 */
1252 ereport(ERROR,
1254 errmsg("cannot PREPARE a transaction that has operated on postgres_fdw foreign tables")));
1255 break;
1257 case XACT_EVENT_COMMIT:
1258 case XACT_EVENT_PREPARE:
1259 /* Pre-commit should have closed the open transaction */
1260 elog(ERROR, "missed cleaning up connection during pre-commit");
1261 break;
1263 case XACT_EVENT_ABORT:
1264 /* Rollback all remote transactions during abort */
1265 if (entry->parallel_abort)
1266 {
1267 if (pgfdw_abort_cleanup_begin(entry, true,
1270 continue;
1271 }
1272 else
1273 pgfdw_abort_cleanup(entry, true);
1274 break;
1275 }
1276 }
1277
1278 /* Reset state to show we're out of a transaction */
1279 pgfdw_reset_xact_state(entry, true);
1280 }
1281
1282 /* If there are any pending connections, finish cleaning them up */
1284 {
1285 if (event == XACT_EVENT_PARALLEL_PRE_COMMIT ||
1286 event == XACT_EVENT_PRE_COMMIT)
1287 {
1290 }
1291 else
1292 {
1294 event == XACT_EVENT_ABORT);
1296 true);
1297 }
1298 }
1299
1300 /*
1301 * Regardless of the event type, we can now mark ourselves as out of the
1302 * transaction. (Note: if we are here during PRE_COMMIT or PRE_PREPARE,
1303 * this saves a useless scan of the hashtable during COMMIT or PREPARE.)
1304 */
1305 xact_got_connection = false;
1306
1307 /* Also reset cursor numbering for next transaction */
1308 cursor_number = 0;
1309
1310 /* Likewise for read_only_level */
1311 read_only_level = 0;
1312}
PGresult * pgfdw_exec_query(PGconn *conn, const char *query, PgFdwConnState *state)
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, read_only_level, 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 2462 of file connection.c.

2463{
2464 Oid userid = PG_GETARG_OID(0);
2465 Oid serverid = PG_GETARG_OID(1);
2466 ForeignServer *server = GetForeignServer(serverid);
2467 UserMapping *user = GetUserMapping(userid, serverid);
2469 const char **keywords;
2470 const char **values;
2471 char *appname;
2472 char *sep = "";
2473
2474 construct_connection_params(server, user, &keywords, &values, &appname);
2475
2477 for (int i = 0; keywords[i] != NULL; i++)
2478 {
2479 if (values[i] == NULL)
2480 continue;
2481 appendStringInfo(&str, "%s%s = ", sep, keywords[i]);
2483 sep = " ";
2484 }
2485
2486 if (appname != NULL)
2487 pfree(appname);
2488 pfree(keywords);
2489 pfree(values);
2491}
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:232
unsigned int Oid
text * cstring_to_text(const char *s)
Definition varlena.c:184

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 2530 of file connection.c.

2531{
2532 ForeignServer *server;
2533 char *servername;
2534
2535 servername = text_to_cstring(PG_GETARG_TEXT_PP(0));
2536 server = GetForeignServerByName(servername, false);
2537
2539}
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:185
char * text_to_cstring(const text *t)
Definition varlena.c:217

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 2551 of file connection.c.

2552{
2554}
#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 2510 of file connection.c.

2511{
2513
2515}
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 2502 of file connection.c.

2503{
2505
2507}

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 2300 of file connection.c.

2302{
2304 HASH_SEQ_STATUS scan;
2305 ConnCacheEntry *entry;
2306
2307 InitMaterializedSRF(fcinfo, 0);
2308
2309 /* If cache doesn't exist, we return no records */
2310 if (!ConnectionHash)
2311 return;
2312
2313 /* Check we have the expected number of output arguments */
2314 switch (rsinfo->setDesc->natts)
2315 {
2317 if (api_version != PGFDW_V1_1)
2318 elog(ERROR, "incorrect number of output arguments");
2319 break;
2321 if (api_version != PGFDW_V1_2)
2322 elog(ERROR, "incorrect number of output arguments");
2323 break;
2324 default:
2325 elog(ERROR, "incorrect number of output arguments");
2326 }
2327
2329 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
2330 {
2331 ForeignServer *server;
2333 bool nulls[POSTGRES_FDW_GET_CONNECTIONS_COLS] = {0};
2334 int i = 0;
2335
2336 /* We only look for open remote connections */
2337 if (!entry->conn)
2338 continue;
2339
2341
2342 /*
2343 * The foreign server may have been dropped in current explicit
2344 * transaction. It is not possible to drop the server from another
2345 * session when the connection associated with it is in use in the
2346 * current transaction, if tried so, the drop query in another session
2347 * blocks until the current transaction finishes.
2348 *
2349 * Even though the server is dropped in the current transaction, the
2350 * cache can still have associated active connection entry, say we
2351 * call such connections dangling. Since we can not fetch the server
2352 * name from system catalogs for dangling connections, instead we show
2353 * NULL value for server name in output.
2354 *
2355 * We could have done better by storing the server name in the cache
2356 * entry instead of server oid so that it could be used in the output.
2357 * But the server name in each cache entry requires 64 bytes of
2358 * memory, which is huge, when there are many cached connections and
2359 * the use case i.e. dropping the foreign server within the explicit
2360 * current transaction seems rare. So, we chose to show NULL value for
2361 * server name in output.
2362 *
2363 * Such dangling connections get closed either in next use or at the
2364 * end of current explicit transaction in pgfdw_xact_callback.
2365 */
2366 if (!server)
2367 {
2368 /*
2369 * If the server has been dropped in the current explicit
2370 * transaction, then this entry would have been invalidated in
2371 * pgfdw_inval_callback at the end of drop server command. Note
2372 * that this connection would not have been closed in
2373 * pgfdw_inval_callback because it is still being used in the
2374 * current explicit transaction. So, assert that here.
2375 */
2376 Assert(entry->conn && entry->xact_depth > 0 && entry->invalidated);
2377
2378 /* Show null, if no server name was found */
2379 nulls[i++] = true;
2380 }
2381 else
2382 values[i++] = CStringGetTextDatum(server->servername);
2383
2384 if (api_version >= PGFDW_V1_2)
2385 {
2386 HeapTuple tp;
2387
2388 /* Use the system cache to obtain the user mapping */
2390
2391 /*
2392 * Just like in the foreign server case, user mappings can also be
2393 * dropped in the current explicit transaction. Therefore, the
2394 * similar check as in the server case is required.
2395 */
2396 if (!HeapTupleIsValid(tp))
2397 {
2398 /*
2399 * If we reach here, this entry must have been invalidated in
2400 * pgfdw_inval_callback, same as in the server case.
2401 */
2402 Assert(entry->conn && entry->xact_depth > 0 &&
2403 entry->invalidated);
2404
2405 nulls[i++] = true;
2406 }
2407 else
2408 {
2409 Oid userid;
2410
2411 userid = ((Form_pg_user_mapping) GETSTRUCT(tp))->umuser;
2413 ReleaseSysCache(tp);
2414 }
2415 }
2416
2417 values[i++] = BoolGetDatum(!entry->invalidated);
2418
2419 if (api_version >= PGFDW_V1_2)
2420 {
2421 bool check_conn = PG_GETARG_BOOL(0);
2422
2423 /* Is this connection used in the current transaction? */
2424 values[i++] = BoolGetDatum(entry->xact_depth > 0);
2425
2426 /*
2427 * If a connection status check is requested and supported, return
2428 * whether the connection is closed. Otherwise, return NULL.
2429 */
2431 values[i++] = BoolGetDatum(pgfdw_conn_check(entry->conn) != 0);
2432 else
2433 nulls[i++] = true;
2434
2435 /* Return process ID of remote backend */
2436 values[i++] = Int32GetDatum(PQbackendPID(entry->conn));
2437 }
2438
2439 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
2440 }
2441}
#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, uint32 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:212
ConnCacheKey key
Definition connection.c:58
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:221
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition tuplestore.c:785

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 1013 of file connection.c.

1014{
1015 /*
1016 * Currently, we don't actually track connection references because all
1017 * cleanup is managed on a transaction or subtransaction basis instead. So
1018 * there's nothing to do here.
1019 */
1020}

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

◆ UserMappingPasswordRequired()

static bool UserMappingPasswordRequired ( UserMapping user)
static

Definition at line 703 of file connection.c.

704{
705 ListCell *cell;
706
707 foreach(cell, user->options)
708 {
709 DefElem *def = (DefElem *) lfirst(cell);
710
711 if (strcmp(def->defname, "password_required") == 0)
712 return defGetBoolean(def);
713 }
714
715 return true;
716}

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 719 of file connection.c.

720{
721 ListCell *cell;
722
723 foreach(cell, server->options)
724 {
725 DefElem *def = (DefElem *) lfirst(cell);
726
727 if (strcmp(def->defname, "use_scram_passthrough") == 0)
728 return defGetBoolean(def);
729 }
730
731 foreach(cell, user->options)
732 {
733 DefElem *def = (DefElem *) lfirst(cell);
734
735 if (strcmp(def->defname, "use_scram_passthrough") == 0)
736 return defGetBoolean(def);
737 }
738
739 return false;
740}

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 97 of file connection.c.

Referenced by pgfdw_get_cleanup_result().

◆ pgfdw_we_connect

uint32 pgfdw_we_connect = 0
static

Definition at line 98 of file connection.c.

Referenced by connect_pg_server().

◆ pgfdw_we_get_result

uint32 pgfdw_we_get_result = 0
static

Definition at line 99 of file connection.c.

Referenced by GetConnection(), and pgfdw_get_result().

◆ prep_stmt_number

unsigned int prep_stmt_number = 0
static

Definition at line 85 of file connection.c.

Referenced by GetPrepStmtNumber().

◆ read_only_level

int read_only_level = 0
static

◆ xact_got_connection

bool xact_got_connection = false
static

Definition at line 88 of file connection.c.

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