Thanks to visit codestin.com
Credit goes to doxygen.postgresql.org

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

Go to the source code of this file.

Data Structures

struct  ConnCacheEntry
 

Macros

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

Typedefs

typedef Oid ConnCacheKey
 
typedef struct ConnCacheEntry ConnCacheEntry
 

Enumerations

enum  pgfdwVersion { PGFDW_V1_1 = 0 , PGFDW_V1_2 }
 

Functions

 PG_FUNCTION_INFO_V1 (postgres_fdw_get_connections)
 
 PG_FUNCTION_INFO_V1 (postgres_fdw_get_connections_1_2)
 
 PG_FUNCTION_INFO_V1 (postgres_fdw_disconnect)
 
 PG_FUNCTION_INFO_V1 (postgres_fdw_disconnect_all)
 
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, int 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)
 
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)
 
Datum postgres_fdw_get_connections_1_2 (PG_FUNCTION_ARGS)
 
Datum postgres_fdw_get_connections (PG_FUNCTION_ARGS)
 
Datum postgres_fdw_disconnect (PG_FUNCTION_ARGS)
 
Datum postgres_fdw_disconnect_all (PG_FUNCTION_ARGS)
 

Variables

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

Macro Definition Documentation

◆ CONNECTION_CLEANUP_TIMEOUT

#define CONNECTION_CLEANUP_TIMEOUT   30000

Definition at line 97 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)
#define snprintf
Definition: port.h:239

Definition at line 107 of file connection.c.

◆ POSTGRES_FDW_GET_CONNECTIONS_COLS

#define POSTGRES_FDW_GET_CONNECTIONS_COLS   6 /* maximum of above */

Definition at line 2138 of file connection.c.

◆ POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1

#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1   2

Definition at line 2136 of file connection.c.

◆ POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2

#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2   6

Definition at line 2137 of file connection.c.

◆ RETRY_CANCEL_TIMEOUT

#define RETRY_CANCEL_TIMEOUT   1000

Definition at line 104 of file connection.c.

Typedef Documentation

◆ ConnCacheEntry

◆ ConnCacheKey

typedef Oid ConnCacheKey

Definition at line 52 of file connection.c.

Enumeration Type Documentation

◆ pgfdwVersion

Enumerator
PGFDW_V1_1 
PGFDW_V1_2 

Definition at line 121 of file connection.c.

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

Function Documentation

◆ begin_remote_xact()

static void begin_remote_xact ( ConnCacheEntry entry)
static

Definition at line 853 of file connection.c.

854{
855 int curlevel = GetCurrentTransactionNestLevel();
856
857 /* Start main transaction if we haven't yet */
858 if (entry->xact_depth <= 0)
859 {
860 const char *sql;
861
862 elog(DEBUG3, "starting remote transaction on connection %p",
863 entry->conn);
864
866 sql = "START TRANSACTION ISOLATION LEVEL SERIALIZABLE";
867 else
868 sql = "START TRANSACTION ISOLATION LEVEL REPEATABLE READ";
869 entry->changing_xact_state = true;
870 do_sql_command(entry->conn, sql);
871 entry->xact_depth = 1;
872 entry->changing_xact_state = false;
873 }
874
875 /*
876 * If we're in a subtransaction, stack up savepoints to match our level.
877 * This ensures we can rollback just the desired effects when a
878 * subtransaction aborts.
879 */
880 while (entry->xact_depth < curlevel)
881 {
882 char sql[64];
883
884 snprintf(sql, sizeof(sql), "SAVEPOINT s%d", entry->xact_depth + 1);
885 entry->changing_xact_state = true;
886 do_sql_command(entry->conn, sql);
887 entry->xact_depth++;
888 entry->changing_xact_state = false;
889 }
890}
void do_sql_command(PGconn *conn, const char *sql)
Definition: connection.c:810
#define DEBUG3
Definition: elog.h:28
#define elog(elevel,...)
Definition: elog.h:226
PGconn * conn
Definition: connection.c:57
bool changing_xact_state
Definition: connection.c:63
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:929
#define IsolationIsSerializable()
Definition: xact.h:53

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

Referenced by GetConnection().

◆ check_conn_params()

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

Definition at line 720 of file connection.c.

721{
722 int i;
723
724 /* no check required if superuser */
725 if (superuser_arg(user->userid))
726 return;
727
728#ifdef ENABLE_GSS
729 /* ok if the user provided their own delegated credentials */
731 return;
732#endif
733
734 /* ok if params contain a non-empty password */
735 for (i = 0; keywords[i] != NULL; i++)
736 {
737 if (strcmp(keywords[i], "password") == 0 && values[i][0] != '\0')
738 return;
739 }
740
741 /* ok if the superuser explicitly said so at user mapping creation time */
743 return;
744
745 /*
746 * Ok if SCRAM pass-through is being used and all required scram options
747 * are set correctly. If pgfdw_has_required_scram_options returns true we
748 * assume that UseScramPassthrough is also true since SCRAM options are
749 * only set when UseScramPassthrough is enabled.
750 */
752 return;
753
755 (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
756 errmsg("password or GSSAPI delegated credentials required"),
757 errdetail("Non-superusers must delegate GSSAPI credentials, provide a password, or enable SCRAM pass-through in user mapping.")));
758}
bool be_gssapi_get_delegation(Port *port)
static Datum values[MAXATTR]
Definition: bootstrap.c:153
static bool UserMappingPasswordRequired(UserMapping *user)
Definition: connection.c:672
static bool pgfdw_has_required_scram_options(const char **keywords, const char **values)
Definition: connection.c:2523
int errdetail(const char *fmt,...)
Definition: elog.c:1207
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:150
struct Port * MyProcPort
Definition: globals.c:51
int i
Definition: isn.c:77
static const JsonPathKeyword keywords[]
static char * user
Definition: pg_regress.c:119
bool has_scram_keys
Definition: libpq-be.h:188
bool superuser_arg(Oid roleid)
Definition: superuser.c:56

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

Referenced by connect_pg_server().

◆ configure_remote_session()

static void configure_remote_session ( PGconn conn)
static

Definition at line 772 of file connection.c.

773{
774 int remoteversion = PQserverVersion(conn);
775
776 /* Force the search path to contain only pg_catalog (see deparse.c) */
777 do_sql_command(conn, "SET search_path = pg_catalog");
778
779 /*
780 * Set remote timezone; this is basically just cosmetic, since all
781 * transmitted and returned timestamptzs should specify a zone explicitly
782 * anyway. However it makes the regression test outputs more predictable.
783 *
784 * We don't risk setting remote zone equal to ours, since the remote
785 * server might use a different timezone database. Instead, use GMT
786 * (quoted, because very old servers are picky about case). That's
787 * guaranteed to work regardless of the remote's timezone database,
788 * because pg_tzset() hard-wires it (at least in PG 9.2 and later).
789 */
790 do_sql_command(conn, "SET timezone = 'GMT'");
791
792 /*
793 * Set values needed to ensure unambiguous data output from remote. (This
794 * logic should match what pg_dump does. See also set_transmission_modes
795 * in postgres_fdw.c.)
796 */
797 do_sql_command(conn, "SET datestyle = ISO");
798 if (remoteversion >= 80400)
799 do_sql_command(conn, "SET intervalstyle = postgres");
800 if (remoteversion >= 90000)
801 do_sql_command(conn, "SET extra_float_digits = 3");
802 else
803 do_sql_command(conn, "SET extra_float_digits = 2");
804}
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:7669
PGconn * conn
Definition: streamutil.c:52

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

Referenced by connect_pg_server().

◆ connect_pg_server()

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

Definition at line 481 of file connection.c.

482{
483 PGconn *volatile conn = NULL;
484
485 /*
486 * Use PG_TRY block to ensure closing connection on error.
487 */
488 PG_TRY();
489 {
490 const char **keywords;
491 const char **values;
492 char *appname = NULL;
493 int n;
494
495 /*
496 * Construct connection params from generic options of ForeignServer
497 * and UserMapping. (Some of them might not be libpq options, in
498 * which case we'll just waste a few array slots.) Add 4 extra slots
499 * for application_name, fallback_application_name, client_encoding,
500 * end marker, and 3 extra slots for scram keys and required scram
501 * pass-through options.
502 */
503 n = list_length(server->options) + list_length(user->options) + 4 + 3;
504 keywords = (const char **) palloc(n * sizeof(char *));
505 values = (const char **) palloc(n * sizeof(char *));
506
507 n = 0;
509 keywords + n, values + n);
510 n += ExtractConnectionOptions(user->options,
511 keywords + n, values + n);
512
513 /*
514 * Use pgfdw_application_name as application_name if set.
515 *
516 * PQconnectdbParams() processes the parameter arrays from start to
517 * end. If any key word is repeated, the last value is used. Therefore
518 * note that pgfdw_application_name must be added to the arrays after
519 * options of ForeignServer are, so that it can override
520 * application_name set in ForeignServer.
521 */
523 {
524 keywords[n] = "application_name";
526 n++;
527 }
528
529 /*
530 * Search the parameter arrays to find application_name setting, and
531 * replace escape sequences in it with status information if found.
532 * The arrays are searched backwards because the last value is used if
533 * application_name is repeatedly set.
534 */
535 for (int i = n - 1; i >= 0; i--)
536 {
537 if (strcmp(keywords[i], "application_name") == 0 &&
538 *(values[i]) != '\0')
539 {
540 /*
541 * Use this application_name setting if it's not empty string
542 * even after any escape sequences in it are replaced.
543 */
544 appname = process_pgfdw_appname(values[i]);
545 if (appname[0] != '\0')
546 {
547 values[i] = appname;
548 break;
549 }
550
551 /*
552 * This empty application_name is not used, so we set
553 * values[i] to NULL and keep searching the array to find the
554 * next one.
555 */
556 values[i] = NULL;
557 pfree(appname);
558 appname = NULL;
559 }
560 }
561
562 /* Use "postgres_fdw" as fallback_application_name */
563 keywords[n] = "fallback_application_name";
564 values[n] = "postgres_fdw";
565 n++;
566
567 /* Set client_encoding so that libpq can convert encoding properly. */
568 keywords[n] = "client_encoding";
570 n++;
571
572 /* Add required SCRAM pass-through connection options if it's enabled. */
573 if (MyProcPort != NULL && MyProcPort->has_scram_keys && UseScramPassthrough(server, user))
574 {
575 int len;
576 int encoded_len;
577
578 keywords[n] = "scram_client_key";
580 /* don't forget the zero-terminator */
581 values[n] = palloc0(len + 1);
584 (char *) values[n], len);
585 if (encoded_len < 0)
586 elog(ERROR, "could not encode SCRAM client key");
587 n++;
588
589 keywords[n] = "scram_server_key";
591 /* don't forget the zero-terminator */
592 values[n] = palloc0(len + 1);
595 (char *) values[n], len);
596 if (encoded_len < 0)
597 elog(ERROR, "could not encode SCRAM server key");
598 n++;
599
600 /*
601 * Require scram-sha-256 to ensure that no other auth method is
602 * used when connecting with foreign server.
603 */
604 keywords[n] = "require_auth";
605 values[n] = "scram-sha-256";
606 n++;
607 }
608
609 keywords[n] = values[n] = NULL;
610
611 /* Verify the set of connection parameters. */
613
614 /* first time, allocate or get the custom wait event */
615 if (pgfdw_we_connect == 0)
616 pgfdw_we_connect = WaitEventExtensionNew("PostgresFdwConnect");
617
618 /* OK to make connection */
620 false, /* expand_dbname */
622
623 if (!conn || PQstatus(conn) != CONNECTION_OK)
625 (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
626 errmsg("could not connect to server \"%s\"",
627 server->servername),
629
631 "received message via remote connection");
632
633 /* Perform post-connection security checks. */
635
636 /* Prepare new session for use */
638
639 if (appname != NULL)
640 pfree(appname);
642 pfree(values);
643 }
644 PG_CATCH();
645 {
647 PG_RE_THROW();
648 }
649 PG_END_TRY();
650
651 return conn;
652}
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:688
static void configure_remote_session(PGconn *conn)
Definition: connection.c:772
static void pgfdw_security_check(const char **keywords, const char **values, UserMapping *user, PGconn *conn)
Definition: connection.c:434
static void check_conn_params(const char **keywords, const char **values, UserMapping *user)
Definition: connection.c:720
static uint32 pgfdw_we_connect
Definition: connection.c:89
int ExtractConnectionOptions(List *defelems, const char **keywords, const char **values)
Definition: option.c:414
char * pgfdw_application_name
Definition: option.c:46
char * process_pgfdw_appname(const char *appname)
Definition: option.c:491
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1234
#define PG_RE_THROW()
Definition: elog.h:405
#define PG_TRY(...)
Definition: elog.h:372
#define PG_END_TRY(...)
Definition: elog.h:397
#define PG_CATCH(...)
Definition: elog.h:382
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:7616
PQnoticeReceiver PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
Definition: fe-connect.c:7843
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:7679
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:84
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1268
void pfree(void *pointer)
Definition: mcxt.c:1594
void * palloc0(Size size)
Definition: mcxt.c:1395
char * pchomp(const char *in)
Definition: mcxt.c:1787
void * palloc(Size size)
Definition: mcxt.c:1365
const void size_t len
static int list_length(const List *l)
Definition: pg_list.h:152
List * options
Definition: foreign.h:42
char * servername
Definition: foreign.h:39
uint8 scram_ServerKey[SCRAM_MAX_KEY_LEN]
Definition: libpq-be.h:187
uint8 scram_ClientKey[SCRAM_MAX_KEY_LEN]
Definition: libpq-be.h:186
uint32 WaitEventExtensionNew(const char *wait_event_name)
Definition: wait_event.c:163

References check_conn_params(), configure_remote_session(), conn, CONNECTION_OK, elog, ereport, errcode(), errdetail_internal(), errmsg(), ERROR, ExtractConnectionOptions(), GetDatabaseEncodingName(), Port::has_scram_keys, i, keywords, len, libpqsrv_connect_params(), libpqsrv_disconnect(), libpqsrv_notice_receiver(), list_length(), MyProcPort, ForeignServer::options, palloc(), palloc0(), pchomp(), pfree(), pg_b64_enc_len(), pg_b64_encode(), PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, pgfdw_application_name, pgfdw_security_check(), pgfdw_we_connect, PQerrorMessage(), PQsetNoticeReceiver(), PQstatus(), process_pgfdw_appname(), Port::scram_ClientKey, Port::scram_ServerKey, ForeignServer::servername, user, UseScramPassthrough(), values, and WaitEventExtensionNew().

Referenced by make_new_connection().

◆ disconnect_cached_connections()

static bool disconnect_cached_connections ( Oid  serverid)
static

Definition at line 2396 of file connection.c.

2397{
2398 HASH_SEQ_STATUS scan;
2399 ConnCacheEntry *entry;
2400 bool all = !OidIsValid(serverid);
2401 bool result = false;
2402
2403 /*
2404 * Connection cache hashtable has not been initialized yet in this
2405 * session, so return false.
2406 */
2407 if (!ConnectionHash)
2408 return false;
2409
2411 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
2412 {
2413 /* Ignore cache entry if no open connection right now. */
2414 if (!entry->conn)
2415 continue;
2416
2417 if (all || entry->serverid == serverid)
2418 {
2419 /*
2420 * Emit a warning because the connection to close is used in the
2421 * current transaction and cannot be disconnected right now.
2422 */
2423 if (entry->xact_depth > 0)
2424 {
2425 ForeignServer *server;
2426
2427 server = GetForeignServerExtended(entry->serverid,
2429
2430 if (!server)
2431 {
2432 /*
2433 * If the foreign server was dropped while its connection
2434 * was used in the current transaction, the connection
2435 * must have been marked as invalid by
2436 * pgfdw_inval_callback at the end of DROP SERVER command.
2437 */
2438 Assert(entry->invalidated);
2439
2441 (errmsg("cannot close dropped server connection because it is still in use")));
2442 }
2443 else
2445 (errmsg("cannot close connection for server \"%s\" because it is still in use",
2446 server->servername)));
2447 }
2448 else
2449 {
2450 elog(DEBUG3, "discarding connection %p", entry->conn);
2451 disconnect_pg_server(entry);
2452 result = true;
2453 }
2454 }
2455 }
2456
2457 return result;
2458}
#define OidIsValid(objectId)
Definition: c.h:775
static void disconnect_pg_server(ConnCacheEntry *entry)
Definition: connection.c:658
static HTAB * ConnectionHash
Definition: connection.c:78
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1415
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1380
#define WARNING
Definition: elog.h:36
ForeignServer * GetForeignServerExtended(Oid serverid, bits16 flags)
Definition: foreign.c:124
#define FSV_MISSING_OK
Definition: foreign.h:61
Assert(PointerIsAligned(start, uint64))
bool invalidated
Definition: connection.c:66

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

Referenced by postgres_fdw_disconnect(), and postgres_fdw_disconnect_all().

◆ disconnect_pg_server()

static void disconnect_pg_server ( ConnCacheEntry entry)
static

Definition at line 658 of file connection.c.

659{
660 if (entry->conn != NULL)
661 {
663 entry->conn = NULL;
664 }
665}

References ConnCacheEntry::conn, and libpqsrv_disconnect().

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

◆ do_sql_command()

void do_sql_command ( PGconn conn,
const char *  sql 
)

Definition at line 810 of file connection.c.

811{
813 do_sql_command_end(conn, sql, false);
814}
static void do_sql_command_end(PGconn *conn, const char *sql, bool consume_input)
Definition: connection.c:824
static void do_sql_command_begin(PGconn *conn, const char *sql)
Definition: connection.c:817

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

818{
819 if (!PQsendQuery(conn, sql))
820 pgfdw_report_error(NULL, conn, sql);
821}
void pgfdw_report_error(PGresult *res, PGconn *conn, const char *sql)
Definition: connection.c:987
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1427

References conn, 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 824 of file connection.c.

825{
826 PGresult *res;
827
828 /*
829 * If requested, consume whatever data is available from the socket. (Note
830 * that if all data is available, this allows pgfdw_get_result to call
831 * PQgetResult without forcing the overhead of WaitLatchOrSocket, which
832 * would be large compared to the overhead of PQconsumeInput.)
833 */
834 if (consume_input && !PQconsumeInput(conn))
835 pgfdw_report_error(NULL, conn, sql);
836 res = pgfdw_get_result(conn);
838 pgfdw_report_error(res, conn, sql);
839 PQclear(res);
840}
PGresult * pgfdw_get_result(PGconn *conn)
Definition: connection.c:963
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1995
#define PQclear
Definition: libpq-be-fe.h:245
#define PQresultStatus
Definition: libpq-be-fe.h:247
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:125

References conn, 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 205 of file connection.c.

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

References Assert(), begin_remote_xact(), CacheRegisterSyscacheCallback(), ConnCacheEntry::conn, CONNECTION_BAD, ConnectionHash, CopyErrorData(), ctl, CurrentMemoryContext, DEBUG3, disconnect_pg_server(), elog, ereport, errdetail_internal(), errmsg_internal(), FlushErrorState(), FreeErrorData(), HASH_BLOBS, hash_create(), HASH_ELEM, HASH_ENTER, hash_search(), ConnCacheEntry::have_prep_stmt, ConnCacheEntry::invalidated, sort-test::key, 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(), ErrorData::sqlerrcode, ConnCacheEntry::state, user, WaitEventExtensionNew(), ConnCacheEntry::xact_depth, and xact_got_connection.

Referenced by create_foreign_modify(), dumpDatabase(), dumpDatabaseConfig(), dumpLOs(), dumpTableData_copy(), estimate_path_cost_size(), expand_extension_name_patterns(), expand_foreign_server_name_patterns(), expand_schema_name_patterns(), expand_table_name_patterns(), getTables(), main(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresBeginDirectModify(), postgresBeginForeignScan(), postgresExecForeignTruncate(), postgresGetAnalyzeInfoForForeignTable(), postgresImportForeignSchema(), setup_connection(), StartLogStreamer(), StreamLog(), and StreamLogicalLog().

◆ GetCursorNumber()

unsigned int GetCursorNumber ( PGconn conn)

Definition at line 917 of file connection.c.

918{
919 return ++cursor_number;
920}
static unsigned int cursor_number
Definition: connection.c:81

References cursor_number.

Referenced by postgresAcquireSampleRowsFunc(), and postgresBeginForeignScan().

◆ GetPrepStmtNumber()

unsigned int GetPrepStmtNumber ( PGconn conn)

Definition at line 931 of file connection.c.

932{
933 return ++prep_stmt_number;
934}
static unsigned int prep_stmt_number
Definition: connection.c:82

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

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

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

Referenced by GetConnection().

◆ PG_FUNCTION_INFO_V1() [1/4]

PG_FUNCTION_INFO_V1 ( postgres_fdw_disconnect  )

◆ PG_FUNCTION_INFO_V1() [2/4]

PG_FUNCTION_INFO_V1 ( postgres_fdw_disconnect_all  )

◆ PG_FUNCTION_INFO_V1() [3/4]

PG_FUNCTION_INFO_V1 ( postgres_fdw_get_connections  )

◆ PG_FUNCTION_INFO_V1() [4/4]

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

1734{
1735 char sql[100];
1736
1737 /*
1738 * Don't try to clean up the connection if we're already in error
1739 * recursion trouble.
1740 */
1742 entry->changing_xact_state = true;
1743
1744 /*
1745 * If connection is already unsalvageable, don't touch it further.
1746 */
1747 if (entry->changing_xact_state)
1748 return;
1749
1750 /*
1751 * Mark this connection as in the process of changing transaction state.
1752 */
1753 entry->changing_xact_state = true;
1754
1755 /* Assume we might have lost track of prepared statements */
1756 entry->have_error = true;
1757
1758 /*
1759 * If a command has been submitted to the remote server by using an
1760 * asynchronous execution function, the command might not have yet
1761 * completed. Check to see if a command is still being processed by the
1762 * remote server, and if so, request cancellation of the command.
1763 */
1764 if (PQtransactionStatus(entry->conn) == PQTRANS_ACTIVE &&
1765 !pgfdw_cancel_query(entry->conn))
1766 return; /* Unable to cancel running query */
1767
1768 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
1769 if (!pgfdw_exec_cleanup_query(entry->conn, sql, false))
1770 return; /* Unable to abort remote (sub)transaction */
1771
1772 if (toplevel)
1773 {
1774 if (entry->have_prep_stmt && entry->have_error &&
1776 "DEALLOCATE ALL",
1777 true))
1778 return; /* Trouble clearing prepared statements */
1779
1780 entry->have_prep_stmt = false;
1781 entry->have_error = false;
1782 }
1783
1784 /*
1785 * If pendingAreq of the per-connection state is not NULL, it means that
1786 * an asynchronous fetch begun by fetch_more_data_begin() was not done
1787 * successfully and thus the per-connection state was not reset in
1788 * fetch_more_data(); in that case reset the per-connection state here.
1789 */
1790 if (entry->state.pendingAreq)
1791 memset(&entry->state, 0, sizeof(entry->state));
1792
1793 /* Disarm changing_xact_state if it all worked */
1794 entry->changing_xact_state = false;
1795}
#define CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel)
Definition: connection.c:107
static bool pgfdw_exec_cleanup_query(PGconn *conn, const char *query, bool ignore_errors)
Definition: connection.c:1530
static bool pgfdw_cancel_query(PGconn *conn)
Definition: connection.c:1430
bool in_error_recursion_trouble(void)
Definition: elog.c:294
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:7624
@ PQTRANS_ACTIVE
Definition: libpq-fe.h:148

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

1809{
1810 /*
1811 * Don't try to clean up the connection if we're already in error
1812 * recursion trouble.
1813 */
1815 entry->changing_xact_state = true;
1816
1817 /*
1818 * If connection is already unsalvageable, don't touch it further.
1819 */
1820 if (entry->changing_xact_state)
1821 return false;
1822
1823 /*
1824 * Mark this connection as in the process of changing transaction state.
1825 */
1826 entry->changing_xact_state = true;
1827
1828 /* Assume we might have lost track of prepared statements */
1829 entry->have_error = true;
1830
1831 /*
1832 * If a command has been submitted to the remote server by using an
1833 * asynchronous execution function, the command might not have yet
1834 * completed. Check to see if a command is still being processed by the
1835 * remote server, and if so, request cancellation of the command.
1836 */
1838 {
1839 TimestampTz endtime;
1840
1843 if (!pgfdw_cancel_query_begin(entry->conn, endtime))
1844 return false; /* Unable to cancel running query */
1845 *cancel_requested = lappend(*cancel_requested, entry);
1846 }
1847 else
1848 {
1849 char sql[100];
1850
1851 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
1852 if (!pgfdw_exec_cleanup_query_begin(entry->conn, sql))
1853 return false; /* Unable to abort remote transaction */
1854 *pending_entries = lappend(*pending_entries, entry);
1855 }
1856
1857 return true;
1858}
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1645
static bool pgfdw_cancel_query_begin(PGconn *conn, TimestampTz endtime)
Definition: connection.c:1463
static bool pgfdw_exec_cleanup_query_begin(PGconn *conn, const char *query)
Definition: connection.c:1550
#define CONNECTION_CLEANUP_TIMEOUT
Definition: connection.c:97
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, 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 1430 of file connection.c.

1431{
1433 TimestampTz endtime;
1434 TimestampTz retrycanceltime;
1435
1436 /*
1437 * If it takes too long to cancel the query and discard the result, assume
1438 * the connection is dead.
1439 */
1441
1442 /*
1443 * Also, lose patience and re-issue the cancel request after a little bit.
1444 * (This serves to close some race conditions.)
1445 */
1447
1448 if (!pgfdw_cancel_query_begin(conn, endtime))
1449 return false;
1450 return pgfdw_cancel_query_end(conn, endtime, retrycanceltime, false);
1451}
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1609
#define RETRY_CANCEL_TIMEOUT
Definition: connection.c:104
static bool pgfdw_cancel_query_end(PGconn *conn, TimestampTz endtime, TimestampTz retrycanceltime, bool consume_input)
Definition: connection.c:1476

References conn, CONNECTION_CLEANUP_TIMEOUT, 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 1463 of file connection.c.

1464{
1465 const char *errormsg = libpqsrv_cancel(conn, endtime);
1466
1467 if (errormsg != NULL)
1469 errcode(ERRCODE_CONNECTION_FAILURE),
1470 errmsg("could not send cancel request: %s", errormsg));
1471
1472 return errormsg == NULL;
1473}
static const char * libpqsrv_cancel(PGconn *conn, TimestampTz endtime)

References conn, ereport, errcode(), errmsg(), 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 1476 of file connection.c.

1478{
1479 PGresult *result;
1480 bool timed_out;
1481
1482 /*
1483 * If requested, consume whatever data is available from the socket. (Note
1484 * that if all data is available, this allows pgfdw_get_cleanup_result to
1485 * call PQgetResult without forcing the overhead of WaitLatchOrSocket,
1486 * which would be large compared to the overhead of PQconsumeInput.)
1487 */
1488 if (consume_input && !PQconsumeInput(conn))
1489 {
1491 (errcode(ERRCODE_CONNECTION_FAILURE),
1492 errmsg("could not get result of cancel request: %s",
1494 return false;
1495 }
1496
1497 /* Get and discard the result of the query. */
1498 if (pgfdw_get_cleanup_result(conn, endtime, retrycanceltime,
1499 &result, &timed_out))
1500 {
1501 if (timed_out)
1503 (errmsg("could not get result of cancel request due to timeout")));
1504 else
1506 (errcode(ERRCODE_CONNECTION_FAILURE),
1507 errmsg("could not get result of cancel request: %s",
1509
1510 return false;
1511 }
1512 PQclear(result);
1513
1514 return true;
1515}
static bool pgfdw_get_cleanup_result(PGconn *conn, TimestampTz endtime, TimestampTz retrycanceltime, PGresult **result, bool *timed_out)
Definition: connection.c:1628

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

Referenced by pgfdw_cancel_query(), and pgfdw_finish_abort_cleanup().

◆ pgfdw_conn_check()

static int pgfdw_conn_check ( PGconn conn)
static

Definition at line 2468 of file connection.c.

2469{
2470 int sock = PQsocket(conn);
2471
2472 if (PQstatus(conn) != CONNECTION_OK || sock == -1)
2473 return -1;
2474
2475#if (defined(HAVE_POLL) && defined(POLLRDHUP))
2476 {
2477 struct pollfd input_fd;
2478 int result;
2479
2480 input_fd.fd = sock;
2481 input_fd.events = POLLRDHUP;
2482 input_fd.revents = 0;
2483
2484 do
2485 result = poll(&input_fd, 1, 0);
2486 while (result < 0 && errno == EINTR);
2487
2488 if (result < 0)
2489 return -1;
2490
2491 return (input_fd.revents &
2492 (POLLRDHUP | POLLHUP | POLLERR | POLLNVAL)) ? 1 : 0;
2493 }
2494#else
2495 return 0;
2496#endif
2497}
int PQsocket(const PGconn *conn)
Definition: fe-connect.c:7705
#define EINTR
Definition: win32_port.h:364

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

Referenced by postgres_fdw_get_connections_internal().

◆ pgfdw_conn_checkable()

static bool pgfdw_conn_checkable ( void  )
static

Definition at line 2505 of file connection.c.

2506{
2507#if (defined(HAVE_POLL) && defined(POLLRDHUP))
2508 return true;
2509#else
2510 return false;
2511#endif
2512}

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

1531{
1532 TimestampTz endtime;
1533
1534 /*
1535 * If it takes too long to execute a cleanup query, assume the connection
1536 * is dead. It's fairly likely that this is why we aborted in the first
1537 * place (e.g. statement timeout, user cancel), so the timeout shouldn't
1538 * be too long.
1539 */
1542
1544 return false;
1545 return pgfdw_exec_cleanup_query_end(conn, query, endtime,
1546 false, ignore_errors);
1547}
static bool pgfdw_exec_cleanup_query_end(PGconn *conn, const char *query, TimestampTz endtime, bool consume_input, bool ignore_errors)
Definition: connection.c:1568

References conn, CONNECTION_CLEANUP_TIMEOUT, 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 1550 of file connection.c.

1551{
1552 Assert(query != NULL);
1553
1554 /*
1555 * Submit a query. Since we don't use non-blocking mode, this also can
1556 * block. But its risk is relatively small, so we ignore that for now.
1557 */
1558 if (!PQsendQuery(conn, query))
1559 {
1560 pgfdw_report(WARNING, NULL, conn, query);
1561 return false;
1562 }
1563
1564 return true;
1565}
void pgfdw_report(int elevel, PGresult *res, PGconn *conn, const char *sql)
Definition: connection.c:994

References Assert(), conn, 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 1568 of file connection.c.

1571{
1572 PGresult *result;
1573 bool timed_out;
1574
1575 Assert(query != NULL);
1576
1577 /*
1578 * If requested, consume whatever data is available from the socket. (Note
1579 * that if all data is available, this allows pgfdw_get_cleanup_result to
1580 * call PQgetResult without forcing the overhead of WaitLatchOrSocket,
1581 * which would be large compared to the overhead of PQconsumeInput.)
1582 */
1583 if (consume_input && !PQconsumeInput(conn))
1584 {
1585 pgfdw_report(WARNING, NULL, conn, query);
1586 return false;
1587 }
1588
1589 /* Get the result of the query. */
1590 if (pgfdw_get_cleanup_result(conn, endtime, endtime, &result, &timed_out))
1591 {
1592 if (timed_out)
1594 (errmsg("could not get query result due to timeout"),
1595 errcontext("remote SQL command: %s", query)));
1596 else
1597 pgfdw_report(WARNING, NULL, conn, query);
1598
1599 return false;
1600 }
1601
1602 /* Issue a warning if not successful. */
1603 if (PQresultStatus(result) != PGRES_COMMAND_OK)
1604 {
1605 pgfdw_report(WARNING, result, conn, query);
1606 return ignore_errors;
1607 }
1608 PQclear(result);
1609
1610 return true;
1611}
#define errcontext
Definition: elog.h:198

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

Referenced by pgfdw_exec_cleanup_query(), and pgfdw_finish_abort_cleanup().

◆ pgfdw_exec_query()

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

Definition at line 946 of file connection.c.

947{
948 /* First, process a pending asynchronous request, if any. */
949 if (state && state->pendingAreq)
950 process_pending_request(state->pendingAreq);
951
952 if (!PQsendQuery(conn, query))
953 return NULL;
954 return pgfdw_get_result(conn);
955}

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

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

◆ pgfdw_finish_abort_cleanup()

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

Definition at line 1973 of file connection.c.

1975{
1976 List *pending_deallocs = NIL;
1977 ListCell *lc;
1978
1979 /*
1980 * For each of the pending cancel requests (if any), get and discard the
1981 * result of the query, and submit an abort command to the remote server.
1982 */
1983 if (cancel_requested)
1984 {
1985 foreach(lc, cancel_requested)
1986 {
1987 ConnCacheEntry *entry = (ConnCacheEntry *) lfirst(lc);
1989 TimestampTz endtime;
1990 TimestampTz retrycanceltime;
1991 char sql[100];
1992
1994
1995 /*
1996 * Set end time. You might think we should do this before issuing
1997 * cancel request like in normal mode, but that is problematic,
1998 * because if, for example, it took longer than 30 seconds to
1999 * process the first few entries in the cancel_requested list, it
2000 * would cause a timeout error when processing each of the
2001 * remaining entries in the list, leading to slamming that entry's
2002 * connection shut.
2003 */
2006 retrycanceltime = TimestampTzPlusMilliseconds(now,
2008
2009 if (!pgfdw_cancel_query_end(entry->conn, endtime,
2010 retrycanceltime, true))
2011 {
2012 /* Unable to cancel running query */
2013 pgfdw_reset_xact_state(entry, toplevel);
2014 continue;
2015 }
2016
2017 /* Send an abort command in parallel if needed */
2018 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
2019 if (!pgfdw_exec_cleanup_query_begin(entry->conn, sql))
2020 {
2021 /* Unable to abort remote (sub)transaction */
2022 pgfdw_reset_xact_state(entry, toplevel);
2023 }
2024 else
2025 pending_entries = lappend(pending_entries, entry);
2026 }
2027 }
2028
2029 /* No further work if no pending entries */
2030 if (!pending_entries)
2031 return;
2032
2033 /*
2034 * Get the result of the abort command for each of the pending entries
2035 */
2036 foreach(lc, pending_entries)
2037 {
2038 ConnCacheEntry *entry = (ConnCacheEntry *) lfirst(lc);
2039 TimestampTz endtime;
2040 char sql[100];
2041
2043
2044 /*
2045 * Set end time. We do this now, not before issuing the command like
2046 * in normal mode, for the same reason as for the cancel_requested
2047 * entries.
2048 */
2051
2052 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
2053 if (!pgfdw_exec_cleanup_query_end(entry->conn, sql, endtime,
2054 true, false))
2055 {
2056 /* Unable to abort remote (sub)transaction */
2057 pgfdw_reset_xact_state(entry, toplevel);
2058 continue;
2059 }
2060
2061 if (toplevel)
2062 {
2063 /* Do a DEALLOCATE ALL in parallel if needed */
2064 if (entry->have_prep_stmt && entry->have_error)
2065 {
2067 "DEALLOCATE ALL"))
2068 {
2069 /* Trouble clearing prepared statements */
2070 pgfdw_reset_xact_state(entry, toplevel);
2071 }
2072 else
2073 pending_deallocs = lappend(pending_deallocs, entry);
2074 continue;
2075 }
2076 entry->have_prep_stmt = false;
2077 entry->have_error = false;
2078 }
2079
2080 /* Reset the per-connection state if needed */
2081 if (entry->state.pendingAreq)
2082 memset(&entry->state, 0, sizeof(entry->state));
2083
2084 /* We're done with this entry; unset the changing_xact_state flag */
2085 entry->changing_xact_state = false;
2086 pgfdw_reset_xact_state(entry, toplevel);
2087 }
2088
2089 /* No further work if no pending entries */
2090 if (!pending_deallocs)
2091 return;
2092 Assert(toplevel);
2093
2094 /*
2095 * Get the result of the DEALLOCATE command for each of the pending
2096 * entries
2097 */
2098 foreach(lc, pending_deallocs)
2099 {
2100 ConnCacheEntry *entry = (ConnCacheEntry *) lfirst(lc);
2101 TimestampTz endtime;
2102
2104 Assert(entry->have_prep_stmt);
2105 Assert(entry->have_error);
2106
2107 /*
2108 * Set end time. We do this now, not before issuing the command like
2109 * in normal mode, for the same reason as for the cancel_requested
2110 * entries.
2111 */
2114
2115 if (!pgfdw_exec_cleanup_query_end(entry->conn, "DEALLOCATE ALL",
2116 endtime, true, true))
2117 {
2118 /* Trouble clearing prepared statements */
2119 pgfdw_reset_xact_state(entry, toplevel);
2120 continue;
2121 }
2122 entry->have_prep_stmt = false;
2123 entry->have_error = false;
2124
2125 /* Reset the per-connection state if needed */
2126 if (entry->state.pendingAreq)
2127 memset(&entry->state, 0, sizeof(entry->state));
2128
2129 /* We're done with this entry; unset the changing_xact_state flag */
2130 entry->changing_xact_state = false;
2131 pgfdw_reset_xact_state(entry, toplevel);
2132 }
2133}
static void pgfdw_reset_xact_state(ConnCacheEntry *entry, bool toplevel)
Definition: connection.c:1385
#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, 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 1865 of file connection.c.

1866{
1867 ConnCacheEntry *entry;
1868 List *pending_deallocs = NIL;
1869 ListCell *lc;
1870
1871 Assert(pending_entries);
1872
1873 /*
1874 * Get the result of the COMMIT command for each of the pending entries
1875 */
1876 foreach(lc, pending_entries)
1877 {
1878 entry = (ConnCacheEntry *) lfirst(lc);
1879
1881
1882 /*
1883 * We might already have received the result on the socket, so pass
1884 * consume_input=true to try to consume it first
1885 */
1886 do_sql_command_end(entry->conn, "COMMIT TRANSACTION", true);
1887 entry->changing_xact_state = false;
1888
1889 /* Do a DEALLOCATE ALL in parallel if needed */
1890 if (entry->have_prep_stmt && entry->have_error)
1891 {
1892 /* Ignore errors (see notes in pgfdw_xact_callback) */
1893 if (PQsendQuery(entry->conn, "DEALLOCATE ALL"))
1894 {
1895 pending_deallocs = lappend(pending_deallocs, entry);
1896 continue;
1897 }
1898 }
1899 entry->have_prep_stmt = false;
1900 entry->have_error = false;
1901
1902 pgfdw_reset_xact_state(entry, true);
1903 }
1904
1905 /* No further work if no pending entries */
1906 if (!pending_deallocs)
1907 return;
1908
1909 /*
1910 * Get the result of the DEALLOCATE command for each of the pending
1911 * entries
1912 */
1913 foreach(lc, pending_deallocs)
1914 {
1915 PGresult *res;
1916
1917 entry = (ConnCacheEntry *) lfirst(lc);
1918
1919 /* Ignore errors (see notes in pgfdw_xact_callback) */
1920 while ((res = PQgetResult(entry->conn)) != NULL)
1921 {
1922 PQclear(res);
1923 /* Stop if the connection is lost (else we'll loop infinitely) */
1924 if (PQstatus(entry->conn) == CONNECTION_BAD)
1925 break;
1926 }
1927 entry->have_prep_stmt = false;
1928 entry->have_error = false;
1929
1930 pgfdw_reset_xact_state(entry, true);
1931 }
1932}
#define PQgetResult
Definition: libpq-be-fe.h:246

References Assert(), ConnCacheEntry::changing_xact_state, ConnCacheEntry::conn, CONNECTION_BAD, do_sql_command_end(), 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 1939 of file connection.c.

1940{
1941 ConnCacheEntry *entry;
1942 char sql[100];
1943 ListCell *lc;
1944
1945 Assert(pending_entries);
1946
1947 /*
1948 * Get the result of the RELEASE command for each of the pending entries
1949 */
1950 snprintf(sql, sizeof(sql), "RELEASE SAVEPOINT s%d", curlevel);
1951 foreach(lc, pending_entries)
1952 {
1953 entry = (ConnCacheEntry *) lfirst(lc);
1954
1956
1957 /*
1958 * We might already have received the result on the socket, so pass
1959 * consume_input=true to try to consume it first
1960 */
1961 do_sql_command_end(entry->conn, sql, true);
1962 entry->changing_xact_state = false;
1963
1964 pgfdw_reset_xact_state(entry, false);
1965 }
1966}

References Assert(), ConnCacheEntry::changing_xact_state, ConnCacheEntry::conn, do_sql_command_end(), 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 1628 of file connection.c.

1632{
1633 bool failed = false;
1634 PGresult *last_res = NULL;
1635 int canceldelta = RETRY_CANCEL_TIMEOUT * 2;
1636
1637 *result = NULL;
1638 *timed_out = false;
1639 for (;;)
1640 {
1641 PGresult *res;
1642
1643 while (PQisBusy(conn))
1644 {
1645 int wc;
1647 long cur_timeout;
1648
1649 /* If timeout has expired, give up. */
1650 if (now >= endtime)
1651 {
1652 *timed_out = true;
1653 failed = true;
1654 goto exit;
1655 }
1656
1657 /* If we need to re-issue the cancel request, do that. */
1658 if (now >= retrycanceltime)
1659 {
1660 /* We ignore failure to issue the repeated request. */
1661 (void) libpqsrv_cancel(conn, endtime);
1662
1663 /* Recompute "now" in case that took measurable time. */
1665
1666 /* Adjust re-cancel timeout in increasing steps. */
1667 retrycanceltime = TimestampTzPlusMilliseconds(now,
1668 canceldelta);
1669 canceldelta += canceldelta;
1670 }
1671
1672 /* If timeout has expired, give up, else get sleep time. */
1674 Min(endtime,
1675 retrycanceltime));
1676 if (cur_timeout <= 0)
1677 {
1678 *timed_out = true;
1679 failed = true;
1680 goto exit;
1681 }
1682
1683 /* first time, allocate or get the custom wait event */
1684 if (pgfdw_we_cleanup_result == 0)
1685 pgfdw_we_cleanup_result = WaitEventExtensionNew("PostgresFdwCleanupResult");
1686
1687 /* Sleep until there's something to do */
1691 PQsocket(conn),
1692 cur_timeout, pgfdw_we_cleanup_result);
1694
1696
1697 /* Data available in socket? */
1698 if (wc & WL_SOCKET_READABLE)
1699 {
1700 if (!PQconsumeInput(conn))
1701 {
1702 /* connection trouble */
1703 failed = true;
1704 goto exit;
1705 }
1706 }
1707 }
1708
1709 res = PQgetResult(conn);
1710 if (res == NULL)
1711 break; /* query is complete */
1712
1713 PQclear(last_res);
1714 last_res = res;
1715 }
1716exit:
1717 if (failed)
1718 PQclear(last_res);
1719 else
1720 *result = last_res;
1721 return failed;
1722}
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition: timestamp.c:1757
#define Min(x, y)
Definition: c.h:1004
static uint32 pgfdw_we_cleanup_result
Definition: connection.c:88
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2042
struct Latch * MyLatch
Definition: globals.c:63
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:223
void ResetLatch(Latch *latch)
Definition: latch.c:374
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
#define WL_SOCKET_READABLE
Definition: waiteventset.h:35
#define WL_TIMEOUT
Definition: waiteventset.h:37
#define WL_EXIT_ON_PM_DEATH
Definition: waiteventset.h:39
#define WL_LATCH_SET
Definition: waiteventset.h:34

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

Referenced by pgfdw_cancel_query_end(), and pgfdw_exec_cleanup_query_end().

◆ pgfdw_get_result()

PGresult * pgfdw_get_result ( PGconn conn)

Definition at line 963 of file connection.c.

964{
966}
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 2523 of file connection.c.

2524{
2525 bool has_scram_server_key = false;
2526 bool has_scram_client_key = false;
2527 bool has_require_auth = false;
2528 bool has_scram_keys = false;
2529
2530 /*
2531 * Continue iterating even if we found the keys that we need to validate
2532 * to make sure that there is no other declaration of these keys that can
2533 * overwrite the first.
2534 */
2535 for (int i = 0; keywords[i] != NULL; i++)
2536 {
2537 if (strcmp(keywords[i], "scram_client_key") == 0)
2538 {
2539 if (values[i] != NULL && values[i][0] != '\0')
2540 has_scram_client_key = true;
2541 else
2542 has_scram_client_key = false;
2543 }
2544
2545 if (strcmp(keywords[i], "scram_server_key") == 0)
2546 {
2547 if (values[i] != NULL && values[i][0] != '\0')
2548 has_scram_server_key = true;
2549 else
2550 has_scram_server_key = false;
2551 }
2552
2553 if (strcmp(keywords[i], "require_auth") == 0)
2554 {
2555 if (values[i] != NULL && strcmp(values[i], "scram-sha-256") == 0)
2556 has_require_auth = true;
2557 else
2558 has_require_auth = false;
2559 }
2560 }
2561
2562 has_scram_keys = has_scram_client_key && has_scram_server_key && MyProcPort != NULL && MyProcPort->has_scram_keys;
2563
2564 return (has_scram_keys && has_require_auth);
2565}

References 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,
int  cacheid,
uint32  hashvalue 
)
static

Definition at line 1311 of file connection.c.

1312{
1313 HASH_SEQ_STATUS scan;
1314 ConnCacheEntry *entry;
1315
1316 Assert(cacheid == FOREIGNSERVEROID || cacheid == USERMAPPINGOID);
1317
1318 /* ConnectionHash must exist already, if we're registered */
1320 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1321 {
1322 /* Ignore invalid entries */
1323 if (entry->conn == NULL)
1324 continue;
1325
1326 /* hashvalue == 0 means a cache reset, must clear all state */
1327 if (hashvalue == 0 ||
1328 (cacheid == FOREIGNSERVEROID &&
1329 entry->server_hashvalue == hashvalue) ||
1330 (cacheid == USERMAPPINGOID &&
1331 entry->mapping_hashvalue == hashvalue))
1332 {
1333 /*
1334 * Close the connection immediately if it's not used yet in this
1335 * transaction. Otherwise mark it as invalid so that
1336 * pgfdw_xact_callback() can close it at the end of this
1337 * transaction.
1338 */
1339 if (entry->xact_depth == 0)
1340 {
1341 elog(DEBUG3, "discarding connection %p", entry->conn);
1342 disconnect_pg_server(entry);
1343 }
1344 else
1345 entry->invalidated = true;
1346 }
1347 }
1348}

References Assert(), ConnCacheEntry::conn, ConnectionHash, DEBUG3, disconnect_pg_server(), elog, 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 1361 of file connection.c.

1362{
1363 ForeignServer *server;
1364
1365 /* nothing to do for inactive entries and entries of sane state */
1366 if (entry->conn == NULL || !entry->changing_xact_state)
1367 return;
1368
1369 /* make sure this entry is inactive */
1370 disconnect_pg_server(entry);
1371
1372 /* find server name to be shown in the message below */
1373 server = GetForeignServer(entry->serverid);
1374
1375 ereport(ERROR,
1376 (errcode(ERRCODE_CONNECTION_EXCEPTION),
1377 errmsg("connection to server \"%s\" was lost",
1378 server->servername)));
1379}

References ConnCacheEntry::changing_xact_state, ConnCacheEntry::conn, disconnect_pg_server(), ereport, errcode(), errmsg(), ERROR, 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 994 of file connection.c.

995{
996 Assert(elevel < ERROR); /* use pgfdw_report_error for that */
997 pgfdw_report_internal(elevel, res, conn, sql);
998}
static void pgfdw_report_internal(int elevel, PGresult *res, PGconn *conn, const char *sql)
Definition: connection.c:1001

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

1003{
1004 char *diag_sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
1005 char *message_primary = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
1006 char *message_detail = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
1007 char *message_hint = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
1008 char *message_context = PQresultErrorField(res, PG_DIAG_CONTEXT);
1009 int sqlstate;
1010
1011 if (diag_sqlstate)
1012 sqlstate = MAKE_SQLSTATE(diag_sqlstate[0],
1013 diag_sqlstate[1],
1014 diag_sqlstate[2],
1015 diag_sqlstate[3],
1016 diag_sqlstate[4]);
1017 else
1018 sqlstate = ERRCODE_CONNECTION_FAILURE;
1019
1020 /*
1021 * If we don't get a message from the PGresult, try the PGconn. This is
1022 * needed because for connection-level failures, PQgetResult may just
1023 * return NULL, not a PGresult at all.
1024 */
1025 if (message_primary == NULL)
1026 message_primary = pchomp(PQerrorMessage(conn));
1027
1028 ereport(elevel,
1029 (errcode(sqlstate),
1030 (message_primary != NULL && message_primary[0] != '\0') ?
1031 errmsg_internal("%s", message_primary) :
1032 errmsg("could not obtain message string for remote error"),
1033 message_detail ? errdetail_internal("%s", message_detail) : 0,
1034 message_hint ? errhint("%s", message_hint) : 0,
1035 message_context ? errcontext("%s", message_context) : 0,
1036 sql ? errcontext("remote SQL command: %s", sql) : 0));
1037 PQclear(res);
1038}
int errhint(const char *fmt,...)
Definition: elog.c:1321
#define MAKE_SQLSTATE(ch1, ch2, ch3, ch4, ch5)
Definition: elog.h:56
#define PQresultErrorField
Definition: libpq-be-fe.h:249
#define PG_DIAG_MESSAGE_HINT
Definition: postgres_ext.h:60
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:57
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:58
#define PG_DIAG_MESSAGE_DETAIL
Definition: postgres_ext.h:59
#define PG_DIAG_CONTEXT
Definition: postgres_ext.h:64

References conn, ereport, errcode(), errcontext, errdetail_internal(), errhint(), errmsg(), errmsg_internal(), 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 1385 of file connection.c.

1386{
1387 if (toplevel)
1388 {
1389 /* Reset state to show we're out of a transaction */
1390 entry->xact_depth = 0;
1391
1392 /*
1393 * If the connection isn't in a good idle state, it is marked as
1394 * invalid or keep_connections option of its server is disabled, then
1395 * discard it to recover. Next GetConnection will open a new
1396 * connection.
1397 */
1398 if (PQstatus(entry->conn) != CONNECTION_OK ||
1400 entry->changing_xact_state ||
1401 entry->invalidated ||
1402 !entry->keep_connections)
1403 {
1404 elog(DEBUG3, "discarding connection %p", entry->conn);
1405 disconnect_pg_server(entry);
1406 }
1407 }
1408 else
1409 {
1410 /* Reset state to show we're out of a subtransaction */
1411 entry->xact_depth--;
1412 }
1413}
@ PQTRANS_IDLE
Definition: libpq-fe.h:147

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

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

◆ pgfdw_security_check()

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

Definition at line 434 of file connection.c.

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

References be_gssapi_get_delegation(), conn, ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, 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 1198 of file connection.c.

1200{
1201 HASH_SEQ_STATUS scan;
1202 ConnCacheEntry *entry;
1203 int curlevel;
1204 List *pending_entries = NIL;
1205 List *cancel_requested = NIL;
1206
1207 /* Nothing to do at subxact start, nor after commit. */
1208 if (!(event == SUBXACT_EVENT_PRE_COMMIT_SUB ||
1209 event == SUBXACT_EVENT_ABORT_SUB))
1210 return;
1211
1212 /* Quick exit if no connections were touched in this transaction. */
1214 return;
1215
1216 /*
1217 * Scan all connection cache entries to find open remote subtransactions
1218 * of the current level, and close them.
1219 */
1220 curlevel = GetCurrentTransactionNestLevel();
1222 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1223 {
1224 char sql[100];
1225
1226 /*
1227 * We only care about connections with open remote subtransactions of
1228 * the current level.
1229 */
1230 if (entry->conn == NULL || entry->xact_depth < curlevel)
1231 continue;
1232
1233 if (entry->xact_depth > curlevel)
1234 elog(ERROR, "missed cleaning up remote subtransaction at level %d",
1235 entry->xact_depth);
1236
1237 if (event == SUBXACT_EVENT_PRE_COMMIT_SUB)
1238 {
1239 /*
1240 * If abort cleanup previously failed for this connection, we
1241 * can't issue any more commands against it.
1242 */
1244
1245 /* Commit all remote subtransactions during pre-commit */
1246 snprintf(sql, sizeof(sql), "RELEASE SAVEPOINT s%d", curlevel);
1247 entry->changing_xact_state = true;
1248 if (entry->parallel_commit)
1249 {
1250 do_sql_command_begin(entry->conn, sql);
1251 pending_entries = lappend(pending_entries, entry);
1252 continue;
1253 }
1254 do_sql_command(entry->conn, sql);
1255 entry->changing_xact_state = false;
1256 }
1257 else
1258 {
1259 /* Rollback all remote subtransactions during abort */
1260 if (entry->parallel_abort)
1261 {
1262 if (pgfdw_abort_cleanup_begin(entry, false,
1263 &pending_entries,
1264 &cancel_requested))
1265 continue;
1266 }
1267 else
1268 pgfdw_abort_cleanup(entry, false);
1269 }
1270
1271 /* OK, we're outta that level of subtransaction */
1272 pgfdw_reset_xact_state(entry, false);
1273 }
1274
1275 /* If there are any pending connections, finish cleaning them up */
1276 if (pending_entries || cancel_requested)
1277 {
1278 if (event == SUBXACT_EVENT_PRE_COMMIT_SUB)
1279 {
1280 Assert(cancel_requested == NIL);
1281 pgfdw_finish_pre_subcommit_cleanup(pending_entries, curlevel);
1282 }
1283 else
1284 {
1286 pgfdw_finish_abort_cleanup(pending_entries, cancel_requested,
1287 false);
1288 }
1289 }
1290}
static void pgfdw_finish_pre_subcommit_cleanup(List *pending_entries, int curlevel)
Definition: connection.c:1939
static void pgfdw_finish_abort_cleanup(List *pending_entries, List *cancel_requested, bool toplevel)
Definition: connection.c:1973
static bool pgfdw_abort_cleanup_begin(ConnCacheEntry *entry, bool toplevel, List **pending_entries, List **cancel_requested)
Definition: connection.c:1807
static void pgfdw_abort_cleanup(ConnCacheEntry *entry, bool toplevel)
Definition: connection.c:1733
@ 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, GetCurrentTransactionNestLevel(), hash_seq_init(), hash_seq_search(), lappend(), NIL, ConnCacheEntry::parallel_abort, ConnCacheEntry::parallel_commit, pgfdw_abort_cleanup(), pgfdw_abort_cleanup_begin(), pgfdw_finish_abort_cleanup(), pgfdw_finish_pre_subcommit_cleanup(), pgfdw_reject_incomplete_xact_state_change(), pgfdw_reset_xact_state(), snprintf, SUBXACT_EVENT_ABORT_SUB, SUBXACT_EVENT_PRE_COMMIT_SUB, ConnCacheEntry::xact_depth, and xact_got_connection.

Referenced by GetConnection().

◆ pgfdw_xact_callback()

static void pgfdw_xact_callback ( XactEvent  event,
void *  arg 
)
static

Definition at line 1048 of file connection.c.

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

Referenced by GetConnection().

◆ postgres_fdw_disconnect()

Datum postgres_fdw_disconnect ( PG_FUNCTION_ARGS  )

Definition at line 2347 of file connection.c.

2348{
2349 ForeignServer *server;
2350 char *servername;
2351
2352 servername = text_to_cstring(PG_GETARG_TEXT_PP(0));
2353 server = GetForeignServerByName(servername, false);
2354
2356}
static bool disconnect_cached_connections(Oid serverid)
Definition: connection.c:2396
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:359
ForeignServer * GetForeignServerByName(const char *srvname, bool missing_ok)
Definition: foreign.c:183
char * text_to_cstring(const text *t)
Definition: varlena.c:214

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

2369{
2371}
#define InvalidOid
Definition: postgres_ext.h:37

References disconnect_cached_connections(), InvalidOid, and PG_RETURN_BOOL.

◆ postgres_fdw_get_connections()

Datum postgres_fdw_get_connections ( PG_FUNCTION_ARGS  )

Definition at line 2327 of file connection.c.

2328{
2330
2332}
static void postgres_fdw_get_connections_internal(FunctionCallInfo fcinfo, enum pgfdwVersion api_version)
Definition: connection.c:2167
#define PG_RETURN_VOID()
Definition: fmgr.h:349

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

2320{
2322
2324}

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

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

References Assert(), BoolGetDatum(), ConnectionHash, CStringGetTextDatum, elog, ERROR, FSV_MISSING_OK, GetForeignServerExtended(), GETSTRUCT(), hash_seq_init(), hash_seq_search(), HeapTupleIsValid, i, InitMaterializedSRF(), Int32GetDatum(), MappingUserName, TupleDescData::natts, 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(), ForeignServer::servername, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, tuplestore_putvalues(), and values.

Referenced by postgres_fdw_get_connections(), and postgres_fdw_get_connections_1_2().

◆ ReleaseConnection()

void ReleaseConnection ( PGconn conn)

Definition at line 896 of file connection.c.

897{
898 /*
899 * Currently, we don't actually track connection references because all
900 * cleanup is managed on a transaction or subtransaction basis instead. So
901 * there's nothing to do here.
902 */
903}

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

◆ UserMappingPasswordRequired()

static bool UserMappingPasswordRequired ( UserMapping user)
static

Definition at line 672 of file connection.c.

673{
674 ListCell *cell;
675
676 foreach(cell, user->options)
677 {
678 DefElem *def = (DefElem *) lfirst(cell);
679
680 if (strcmp(def->defname, "password_required") == 0)
681 return defGetBoolean(def);
682 }
683
684 return true;
685}

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

Referenced by check_conn_params(), and pgfdw_security_check().

◆ UseScramPassthrough()

static bool UseScramPassthrough ( ForeignServer server,
UserMapping user 
)
static

Definition at line 688 of file connection.c.

689{
690 ListCell *cell;
691
692 foreach(cell, server->options)
693 {
694 DefElem *def = (DefElem *) lfirst(cell);
695
696 if (strcmp(def->defname, "use_scram_passthrough") == 0)
697 return defGetBoolean(def);
698 }
699
700 foreach(cell, user->options)
701 {
702 DefElem *def = (DefElem *) lfirst(cell);
703
704 if (strcmp(def->defname, "use_scram_passthrough") == 0)
705 return defGetBoolean(def);
706 }
707
708 return false;
709}

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

Referenced by connect_pg_server().

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

Referenced by pgfdw_get_cleanup_result().

◆ pgfdw_we_connect

uint32 pgfdw_we_connect = 0
static

Definition at line 89 of file connection.c.

Referenced by connect_pg_server().

◆ pgfdw_we_get_result

uint32 pgfdw_we_get_result = 0
static

Definition at line 90 of file connection.c.

Referenced by GetConnection(), and pgfdw_get_result().

◆ prep_stmt_number

unsigned int prep_stmt_number = 0
static

Definition at line 82 of file connection.c.

Referenced by GetPrepStmtNumber().

◆ xact_got_connection

bool xact_got_connection = false
static

Definition at line 85 of file connection.c.

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