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   5
 
#define POSTGRES_FDW_GET_CONNECTIONS_COLS   5 /* 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_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)
 
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 (int elevel, PGresult *res, PGconn *conn, bool clear, 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:238

Definition at line 107 of file connection.c.

◆ POSTGRES_FDW_GET_CONNECTIONS_COLS

#define POSTGRES_FDW_GET_CONNECTIONS_COLS   5 /* maximum of above */

Definition at line 2115 of file connection.c.

◆ POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1

#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1   2

Definition at line 2113 of file connection.c.

◆ POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2

#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2   5

Definition at line 2114 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 827 of file connection.c.

828{
829 int curlevel = GetCurrentTransactionNestLevel();
830
831 /* Start main transaction if we haven't yet */
832 if (entry->xact_depth <= 0)
833 {
834 const char *sql;
835
836 elog(DEBUG3, "starting remote transaction on connection %p",
837 entry->conn);
838
840 sql = "START TRANSACTION ISOLATION LEVEL SERIALIZABLE";
841 else
842 sql = "START TRANSACTION ISOLATION LEVEL REPEATABLE READ";
843 entry->changing_xact_state = true;
844 do_sql_command(entry->conn, sql);
845 entry->xact_depth = 1;
846 entry->changing_xact_state = false;
847 }
848
849 /*
850 * If we're in a subtransaction, stack up savepoints to match our level.
851 * This ensures we can rollback just the desired effects when a
852 * subtransaction aborts.
853 */
854 while (entry->xact_depth < curlevel)
855 {
856 char sql[64];
857
858 snprintf(sql, sizeof(sql), "SAVEPOINT s%d", entry->xact_depth + 1);
859 entry->changing_xact_state = true;
860 do_sql_command(entry->conn, sql);
861 entry->xact_depth++;
862 entry->changing_xact_state = false;
863 }
864}
void do_sql_command(PGconn *conn, const char *sql)
Definition: connection.c:784
#define DEBUG3
Definition: elog.h:28
#define elog(elevel,...)
Definition: elog.h:225
PGconn * conn
Definition: connection.c:57
bool changing_xact_state
Definition: connection.c:63
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:928
#define IsolationIsSerializable()
Definition: xact.h:52

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

704{
705 int i;
706
707 /* no check required if superuser */
708 if (superuser_arg(user->userid))
709 return;
710
711#ifdef ENABLE_GSS
712 /* ok if the user provided their own delegated credentials */
714 return;
715#endif
716
717 /* ok if params contain a non-empty password */
718 for (i = 0; keywords[i] != NULL; i++)
719 {
720 if (strcmp(keywords[i], "password") == 0 && values[i][0] != '\0')
721 return;
722 }
723
724 /* ok if the superuser explicitly said so at user mapping creation time */
726 return;
727
729 (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
730 errmsg("password or GSSAPI delegated credentials required"),
731 errdetail("Non-superusers must delegate GSSAPI credentials, provide a password, or enable SCRAM pass-through in user mapping.")));
732}
bool be_gssapi_get_delegation(Port *port)
static Datum values[MAXATTR]
Definition: bootstrap.c:151
static bool UserMappingPasswordRequired(UserMapping *user)
Definition: connection.c:655
int errdetail(const char *fmt,...)
Definition: elog.c:1203
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
struct Port * MyProcPort
Definition: globals.c:50
int i
Definition: isn.c:72
static const JsonPathKeyword keywords[]
static char * user
Definition: pg_regress.c:119
bool superuser_arg(Oid roleid)
Definition: superuser.c:56

References be_gssapi_get_delegation(), ereport, errcode(), errdetail(), errmsg(), ERROR, i, keywords, MyProcPort, 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 746 of file connection.c.

747{
748 int remoteversion = PQserverVersion(conn);
749
750 /* Force the search path to contain only pg_catalog (see deparse.c) */
751 do_sql_command(conn, "SET search_path = pg_catalog");
752
753 /*
754 * Set remote timezone; this is basically just cosmetic, since all
755 * transmitted and returned timestamptzs should specify a zone explicitly
756 * anyway. However it makes the regression test outputs more predictable.
757 *
758 * We don't risk setting remote zone equal to ours, since the remote
759 * server might use a different timezone database. Instead, use GMT
760 * (quoted, because very old servers are picky about case). That's
761 * guaranteed to work regardless of the remote's timezone database,
762 * because pg_tzset() hard-wires it (at least in PG 9.2 and later).
763 */
764 do_sql_command(conn, "SET timezone = 'GMT'");
765
766 /*
767 * Set values needed to ensure unambiguous data output from remote. (This
768 * logic should match what pg_dump does. See also set_transmission_modes
769 * in postgres_fdw.c.)
770 */
771 do_sql_command(conn, "SET datestyle = ISO");
772 if (remoteversion >= 80400)
773 do_sql_command(conn, "SET intervalstyle = postgres");
774 if (remoteversion >= 90000)
775 do_sql_command(conn, "SET extra_float_digits = 3");
776 else
777 do_sql_command(conn, "SET extra_float_digits = 2");
778}
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:7258
PGconn * conn
Definition: streamutil.c:53

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

470{
471 PGconn *volatile conn = NULL;
472
473 /*
474 * Use PG_TRY block to ensure closing connection on error.
475 */
476 PG_TRY();
477 {
478 const char **keywords;
479 const char **values;
480 char *appname = NULL;
481 int n;
482
483 /*
484 * Construct connection params from generic options of ForeignServer
485 * and UserMapping. (Some of them might not be libpq options, in
486 * which case we'll just waste a few array slots.) Add 4 extra slots
487 * for application_name, fallback_application_name, client_encoding,
488 * end marker.
489 */
490 n = list_length(server->options) + list_length(user->options) + 4 + 2;
491 keywords = (const char **) palloc(n * sizeof(char *));
492 values = (const char **) palloc(n * sizeof(char *));
493
494 n = 0;
496 keywords + n, values + n);
497 n += ExtractConnectionOptions(user->options,
498 keywords + n, values + n);
499
500 /*
501 * Use pgfdw_application_name as application_name if set.
502 *
503 * PQconnectdbParams() processes the parameter arrays from start to
504 * end. If any key word is repeated, the last value is used. Therefore
505 * note that pgfdw_application_name must be added to the arrays after
506 * options of ForeignServer are, so that it can override
507 * application_name set in ForeignServer.
508 */
510 {
511 keywords[n] = "application_name";
513 n++;
514 }
515
516 /*
517 * Search the parameter arrays to find application_name setting, and
518 * replace escape sequences in it with status information if found.
519 * The arrays are searched backwards because the last value is used if
520 * application_name is repeatedly set.
521 */
522 for (int i = n - 1; i >= 0; i--)
523 {
524 if (strcmp(keywords[i], "application_name") == 0 &&
525 *(values[i]) != '\0')
526 {
527 /*
528 * Use this application_name setting if it's not empty string
529 * even after any escape sequences in it are replaced.
530 */
531 appname = process_pgfdw_appname(values[i]);
532 if (appname[0] != '\0')
533 {
534 values[i] = appname;
535 break;
536 }
537
538 /*
539 * This empty application_name is not used, so we set
540 * values[i] to NULL and keep searching the array to find the
541 * next one.
542 */
543 values[i] = NULL;
544 pfree(appname);
545 appname = NULL;
546 }
547 }
548
549 /* Use "postgres_fdw" as fallback_application_name */
550 keywords[n] = "fallback_application_name";
551 values[n] = "postgres_fdw";
552 n++;
553
554 /* Set client_encoding so that libpq can convert encoding properly. */
555 keywords[n] = "client_encoding";
557 n++;
558
560 {
561 int len;
562 int encoded_len;
563
564 keywords[n] = "scram_client_key";
566 /* don't forget the zero-terminator */
567 values[n] = palloc0(len + 1);
568 encoded_len = pg_b64_encode((const char *) MyProcPort->scram_ClientKey,
570 (char *) values[n], len);
571 if (encoded_len < 0)
572 elog(ERROR, "could not encode SCRAM client key");
573 n++;
574
575 keywords[n] = "scram_server_key";
577 /* don't forget the zero-terminator */
578 values[n] = palloc0(len + 1);
579 encoded_len = pg_b64_encode((const char *) MyProcPort->scram_ServerKey,
581 (char *) values[n], len);
582 if (encoded_len < 0)
583 elog(ERROR, "could not encode SCRAM server key");
584 n++;
585 }
586
587 keywords[n] = values[n] = NULL;
588
589 /*
590 * Verify the set of connection parameters only if scram pass-through
591 * is not being used because the password is not necessary.
592 */
595
596 /* first time, allocate or get the custom wait event */
597 if (pgfdw_we_connect == 0)
598 pgfdw_we_connect = WaitEventExtensionNew("PostgresFdwConnect");
599
600 /* OK to make connection */
602 false, /* expand_dbname */
604
605 if (!conn || PQstatus(conn) != CONNECTION_OK)
607 (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
608 errmsg("could not connect to server \"%s\"",
609 server->servername),
611
612 /*
613 * Perform post-connection security checks only if scram pass-through
614 * is not being used because the password is not necessary.
615 */
618
619 /* Prepare new session for use */
621
622 if (appname != NULL)
623 pfree(appname);
625 pfree(values);
626 }
627 PG_CATCH();
628 {
630 PG_RE_THROW();
631 }
632 PG_END_TRY();
633
634 return conn;
635}
int pg_b64_enc_len(int srclen)
Definition: base64.c:224
int pg_b64_encode(const char *src, int len, char *dst, int dstlen)
Definition: base64.c:49
static bool UseScramPassthrough(ForeignServer *server, UserMapping *user)
Definition: connection.c:671
static void configure_remote_session(PGconn *conn)
Definition: connection.c:746
static void pgfdw_security_check(const char **keywords, const char **values, UserMapping *user, PGconn *conn)
Definition: connection.c:431
static void check_conn_params(const char **keywords, const char **values, UserMapping *user)
Definition: connection.c:703
static uint32 pgfdw_we_connect
Definition: connection.c:89
int ExtractConnectionOptions(List *defelems, const char **keywords, const char **values)
Definition: option.c:416
char * pgfdw_application_name
Definition: option.c:51
char * process_pgfdw_appname(const char *appname)
Definition: option.c:493
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1230
#define PG_RE_THROW()
Definition: elog.h:412
#define PG_TRY(...)
Definition: elog.h:371
#define PG_END_TRY(...)
Definition: elog.h:396
#define PG_CATCH(...)
Definition: elog.h:381
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:7205
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:7268
static PGconn * libpqsrv_connect_params(const char *const *keywords, const char *const *values, int expand_dbname, uint32 wait_event_info)
static void libpqsrv_disconnect(PGconn *conn)
@ CONNECTION_OK
Definition: libpq-fe.h:81
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1267
void pfree(void *pointer)
Definition: mcxt.c:1521
void * palloc0(Size size)
Definition: mcxt.c:1347
char * pchomp(const char *in)
Definition: mcxt.c:1724
void * palloc(Size size)
Definition: mcxt.c:1317
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:190
bool has_scram_keys
Definition: libpq-be.h:191
uint8 scram_ClientKey[SCRAM_MAX_KEY_LEN]
Definition: libpq-be.h:189
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(), 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(), 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 2368 of file connection.c.

2369{
2370 HASH_SEQ_STATUS scan;
2371 ConnCacheEntry *entry;
2372 bool all = !OidIsValid(serverid);
2373 bool result = false;
2374
2375 /*
2376 * Connection cache hashtable has not been initialized yet in this
2377 * session, so return false.
2378 */
2379 if (!ConnectionHash)
2380 return false;
2381
2383 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
2384 {
2385 /* Ignore cache entry if no open connection right now. */
2386 if (!entry->conn)
2387 continue;
2388
2389 if (all || entry->serverid == serverid)
2390 {
2391 /*
2392 * Emit a warning because the connection to close is used in the
2393 * current transaction and cannot be disconnected right now.
2394 */
2395 if (entry->xact_depth > 0)
2396 {
2397 ForeignServer *server;
2398
2399 server = GetForeignServerExtended(entry->serverid,
2401
2402 if (!server)
2403 {
2404 /*
2405 * If the foreign server was dropped while its connection
2406 * was used in the current transaction, the connection
2407 * must have been marked as invalid by
2408 * pgfdw_inval_callback at the end of DROP SERVER command.
2409 */
2410 Assert(entry->invalidated);
2411
2413 (errmsg("cannot close dropped server connection because it is still in use")));
2414 }
2415 else
2417 (errmsg("cannot close connection for server \"%s\" because it is still in use",
2418 server->servername)));
2419 }
2420 else
2421 {
2422 elog(DEBUG3, "discarding connection %p", entry->conn);
2423 disconnect_pg_server(entry);
2424 result = true;
2425 }
2426 }
2427 }
2428
2429 return result;
2430}
#define Assert(condition)
Definition: c.h:815
#define OidIsValid(objectId)
Definition: c.h:732
static void disconnect_pg_server(ConnCacheEntry *entry)
Definition: connection.c:641
static HTAB * ConnectionHash
Definition: connection.c:78
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1420
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1385
#define WARNING
Definition: elog.h:36
ForeignServer * GetForeignServerExtended(Oid serverid, bits16 flags)
Definition: foreign.c:123
#define FSV_MISSING_OK
Definition: foreign.h:61
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 641 of file connection.c.

642{
643 if (entry->conn != NULL)
644 {
646 entry->conn = NULL;
647 }
648}

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

785{
787 do_sql_command_end(conn, sql, false);
788}
static void do_sql_command_end(PGconn *conn, const char *sql, bool consume_input)
Definition: connection.c:798
static void do_sql_command_begin(PGconn *conn, const char *sql)
Definition: connection.c:791

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

792{
793 if (!PQsendQuery(conn, sql))
794 pgfdw_report_error(ERROR, NULL, conn, false, sql);
795}
void pgfdw_report_error(int elevel, PGresult *res, PGconn *conn, bool clear, const char *sql)
Definition: connection.c:956
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1416

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

799{
800 PGresult *res;
801
802 /*
803 * If requested, consume whatever data is available from the socket. (Note
804 * that if all data is available, this allows pgfdw_get_result to call
805 * PQgetResult without forcing the overhead of WaitLatchOrSocket, which
806 * would be large compared to the overhead of PQconsumeInput.)
807 */
808 if (consume_input && !PQconsumeInput(conn))
809 pgfdw_report_error(ERROR, NULL, conn, false, sql);
812 pgfdw_report_error(ERROR, res, conn, true, sql);
813 PQclear(res);
814}
PGresult * pgfdw_get_result(PGconn *conn)
Definition: connection.c:937
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3411
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1984
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:120

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

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

203{
204 bool found;
205 bool retry = false;
206 ConnCacheEntry *entry;
209
210 /* First time through, initialize connection cache hashtable */
211 if (ConnectionHash == NULL)
212 {
213 HASHCTL ctl;
214
215 if (pgfdw_we_get_result == 0)
217 WaitEventExtensionNew("PostgresFdwGetResult");
218
219 ctl.keysize = sizeof(ConnCacheKey);
220 ctl.entrysize = sizeof(ConnCacheEntry);
221 ConnectionHash = hash_create("postgres_fdw connections", 8,
222 &ctl,
224
225 /*
226 * Register some callback functions that manage connection cleanup.
227 * This should be done just once in each backend.
228 */
231 CacheRegisterSyscacheCallback(FOREIGNSERVEROID,
233 CacheRegisterSyscacheCallback(USERMAPPINGOID,
235 }
236
237 /* Set flag that we did GetConnection during the current transaction */
238 xact_got_connection = true;
239
240 /* Create hash key for the entry. Assume no pad bytes in key struct */
241 key = user->umid;
242
243 /*
244 * Find or create cached entry for requested connection.
245 */
246 entry = hash_search(ConnectionHash, &key, HASH_ENTER, &found);
247 if (!found)
248 {
249 /*
250 * We need only clear "conn" here; remaining fields will be filled
251 * later when "conn" is set.
252 */
253 entry->conn = NULL;
254 }
255
256 /* Reject further use of connections which failed abort cleanup. */
258
259 /*
260 * If the connection needs to be remade due to invalidation, disconnect as
261 * soon as we're out of all transactions.
262 */
263 if (entry->conn != NULL && entry->invalidated && entry->xact_depth == 0)
264 {
265 elog(DEBUG3, "closing connection %p for option changes to take effect",
266 entry->conn);
268 }
269
270 /*
271 * If cache entry doesn't have a connection, we have to establish a new
272 * connection. (If connect_pg_server throws an error, the cache entry
273 * will remain in a valid empty state, ie conn == NULL.)
274 */
275 if (entry->conn == NULL)
277
278 /*
279 * We check the health of the cached connection here when using it. In
280 * cases where we're out of all transactions, if a broken connection is
281 * detected, we try to reestablish a new connection later.
282 */
283 PG_TRY();
284 {
285 /* Process a pending asynchronous request if any. */
286 if (entry->state.pendingAreq)
288 /* Start a new transaction or subtransaction if needed. */
289 begin_remote_xact(entry);
290 }
291 PG_CATCH();
292 {
294 ErrorData *errdata = CopyErrorData();
295
296 /*
297 * Determine whether to try to reestablish the connection.
298 *
299 * After a broken connection is detected in libpq, any error other
300 * than connection failure (e.g., out-of-memory) can be thrown
301 * somewhere between return from libpq and the expected ereport() call
302 * in pgfdw_report_error(). In this case, since PQstatus() indicates
303 * CONNECTION_BAD, checking only PQstatus() causes the false detection
304 * of connection failure. To avoid this, we also verify that the
305 * error's sqlstate is ERRCODE_CONNECTION_FAILURE. Note that also
306 * checking only the sqlstate can cause another false detection
307 * because pgfdw_report_error() may report ERRCODE_CONNECTION_FAILURE
308 * for any libpq-originated error condition.
309 */
310 if (errdata->sqlerrcode != ERRCODE_CONNECTION_FAILURE ||
311 PQstatus(entry->conn) != CONNECTION_BAD ||
312 entry->xact_depth > 0)
313 {
315 PG_RE_THROW();
316 }
317
318 /* Clean up the error state */
320 FreeErrorData(errdata);
321 errdata = NULL;
322
323 retry = true;
324 }
325 PG_END_TRY();
326
327 /*
328 * If a broken connection is detected, disconnect it, reestablish a new
329 * connection and retry a new remote transaction. If connection failure is
330 * reported again, we give up getting a connection.
331 */
332 if (retry)
333 {
334 Assert(entry->xact_depth == 0);
335
337 (errmsg_internal("could not start remote transaction on connection %p",
338 entry->conn)),
340
341 elog(DEBUG3, "closing connection %p to reestablish a new one",
342 entry->conn);
344
346
347 begin_remote_xact(entry);
348 }
349
350 /* Remember if caller will prepare statements */
351 entry->have_prep_stmt |= will_prep_stmt;
352
353 /* If caller needs access to the per-connection state, return it. */
354 if (state)
355 *state = &entry->state;
356
357 return entry->conn;
358}
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:365
static void pgfdw_subxact_callback(SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid, void *arg)
Definition: connection.c:1162
static void pgfdw_reject_incomplete_xact_state_change(ConnCacheEntry *entry)
Definition: connection.c:1325
static void pgfdw_inval_callback(Datum arg, int cacheid, uint32 hashvalue)
Definition: connection.c:1275
static void pgfdw_xact_callback(XactEvent event, void *arg)
Definition: connection.c:1012
static void begin_remote_xact(ConnCacheEntry *entry)
Definition: connection.c:827
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:955
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:352
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
void FreeErrorData(ErrorData *edata)
Definition: elog.c:1818
ErrorData * CopyErrorData(void)
Definition: elog.c:1746
void FlushErrorState(void)
Definition: elog.c:1867
@ 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:1704
@ CONNECTION_BAD
Definition: libpq-fe.h:82
MemoryContext CurrentMemoryContext
Definition: mcxt.c:143
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
uintptr_t Datum
Definition: postgres.h:69
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:439
AsyncRequest * pendingAreq
Definition: postgres_fdw.h:139
Definition: regguts.h:323
void RegisterXactCallback(XactCallback callback, void *arg)
Definition: xact.c:3796
void RegisterSubXactCallback(SubXactCallback callback, void *arg)
Definition: xact.c:3856

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

892{
893 return ++cursor_number;
894}
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 905 of file connection.c.

906{
907 return ++prep_stmt_number;
908}
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 365 of file connection.c.

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

1711{
1712 char sql[100];
1713
1714 /*
1715 * Don't try to clean up the connection if we're already in error
1716 * recursion trouble.
1717 */
1719 entry->changing_xact_state = true;
1720
1721 /*
1722 * If connection is already unsalvageable, don't touch it further.
1723 */
1724 if (entry->changing_xact_state)
1725 return;
1726
1727 /*
1728 * Mark this connection as in the process of changing transaction state.
1729 */
1730 entry->changing_xact_state = true;
1731
1732 /* Assume we might have lost track of prepared statements */
1733 entry->have_error = true;
1734
1735 /*
1736 * If a command has been submitted to the remote server by using an
1737 * asynchronous execution function, the command might not have yet
1738 * completed. Check to see if a command is still being processed by the
1739 * remote server, and if so, request cancellation of the command.
1740 */
1741 if (PQtransactionStatus(entry->conn) == PQTRANS_ACTIVE &&
1742 !pgfdw_cancel_query(entry->conn))
1743 return; /* Unable to cancel running query */
1744
1745 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
1746 if (!pgfdw_exec_cleanup_query(entry->conn, sql, false))
1747 return; /* Unable to abort remote (sub)transaction */
1748
1749 if (toplevel)
1750 {
1751 if (entry->have_prep_stmt && entry->have_error &&
1753 "DEALLOCATE ALL",
1754 true))
1755 return; /* Trouble clearing prepared statements */
1756
1757 entry->have_prep_stmt = false;
1758 entry->have_error = false;
1759 }
1760
1761 /*
1762 * If pendingAreq of the per-connection state is not NULL, it means that
1763 * an asynchronous fetch begun by fetch_more_data_begin() was not done
1764 * successfully and thus the per-connection state was not reset in
1765 * fetch_more_data(); in that case reset the per-connection state here.
1766 */
1767 if (entry->state.pendingAreq)
1768 memset(&entry->state, 0, sizeof(entry->state));
1769
1770 /* Disarm changing_xact_state if it all worked */
1771 entry->changing_xact_state = false;
1772}
#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:1494
static bool pgfdw_cancel_query(PGconn *conn)
Definition: connection.c:1394
bool in_error_recursion_trouble(void)
Definition: elog.c:293
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:7213
@ PQTRANS_ACTIVE
Definition: libpq-fe.h:143

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

1786{
1787 /*
1788 * Don't try to clean up the connection if we're already in error
1789 * recursion trouble.
1790 */
1792 entry->changing_xact_state = true;
1793
1794 /*
1795 * If connection is already unsalvageable, don't touch it further.
1796 */
1797 if (entry->changing_xact_state)
1798 return false;
1799
1800 /*
1801 * Mark this connection as in the process of changing transaction state.
1802 */
1803 entry->changing_xact_state = true;
1804
1805 /* Assume we might have lost track of prepared statements */
1806 entry->have_error = true;
1807
1808 /*
1809 * If a command has been submitted to the remote server by using an
1810 * asynchronous execution function, the command might not have yet
1811 * completed. Check to see if a command is still being processed by the
1812 * remote server, and if so, request cancellation of the command.
1813 */
1815 {
1816 TimestampTz endtime;
1817
1820 if (!pgfdw_cancel_query_begin(entry->conn, endtime))
1821 return false; /* Unable to cancel running query */
1822 *cancel_requested = lappend(*cancel_requested, entry);
1823 }
1824 else
1825 {
1826 char sql[100];
1827
1828 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
1829 if (!pgfdw_exec_cleanup_query_begin(entry->conn, sql))
1830 return false; /* Unable to abort remote transaction */
1831 *pending_entries = lappend(*pending_entries, entry);
1832 }
1833
1834 return true;
1835}
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1644
static bool pgfdw_cancel_query_begin(PGconn *conn, TimestampTz endtime)
Definition: connection.c:1427
static bool pgfdw_exec_cleanup_query_begin(PGconn *conn, const char *query)
Definition: connection.c:1514
#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 1394 of file connection.c.

1395{
1397 TimestampTz endtime;
1398 TimestampTz retrycanceltime;
1399
1400 /*
1401 * If it takes too long to cancel the query and discard the result, assume
1402 * the connection is dead.
1403 */
1405
1406 /*
1407 * Also, lose patience and re-issue the cancel request after a little bit.
1408 * (This serves to close some race conditions.)
1409 */
1411
1412 if (!pgfdw_cancel_query_begin(conn, endtime))
1413 return false;
1414 return pgfdw_cancel_query_end(conn, endtime, retrycanceltime, false);
1415}
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1608
#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:1440

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

1428{
1429 const char *errormsg = libpqsrv_cancel(conn, endtime);
1430
1431 if (errormsg != NULL)
1433 errcode(ERRCODE_CONNECTION_FAILURE),
1434 errmsg("could not send cancel request: %s", errormsg));
1435
1436 return errormsg == NULL;
1437}
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 1440 of file connection.c.

1442{
1443 PGresult *result;
1444 bool timed_out;
1445
1446 /*
1447 * If requested, consume whatever data is available from the socket. (Note
1448 * that if all data is available, this allows pgfdw_get_cleanup_result to
1449 * call PQgetResult without forcing the overhead of WaitLatchOrSocket,
1450 * which would be large compared to the overhead of PQconsumeInput.)
1451 */
1452 if (consume_input && !PQconsumeInput(conn))
1453 {
1455 (errcode(ERRCODE_CONNECTION_FAILURE),
1456 errmsg("could not get result of cancel request: %s",
1458 return false;
1459 }
1460
1461 /* Get and discard the result of the query. */
1462 if (pgfdw_get_cleanup_result(conn, endtime, retrycanceltime,
1463 &result, &timed_out))
1464 {
1465 if (timed_out)
1467 (errmsg("could not get result of cancel request due to timeout")));
1468 else
1470 (errcode(ERRCODE_CONNECTION_FAILURE),
1471 errmsg("could not get result of cancel request: %s",
1473
1474 return false;
1475 }
1476 PQclear(result);
1477
1478 return true;
1479}
static bool pgfdw_get_cleanup_result(PGconn *conn, TimestampTz endtime, TimestampTz retrycanceltime, PGresult **result, bool *timed_out)
Definition: connection.c:1592

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

2441{
2442 int sock = PQsocket(conn);
2443
2444 if (PQstatus(conn) != CONNECTION_OK || sock == -1)
2445 return -1;
2446
2447#if (defined(HAVE_POLL) && defined(POLLRDHUP))
2448 {
2449 struct pollfd input_fd;
2450 int result;
2451
2452 input_fd.fd = sock;
2453 input_fd.events = POLLRDHUP;
2454 input_fd.revents = 0;
2455
2456 do
2457 result = poll(&input_fd, 1, 0);
2458 while (result < 0 && errno == EINTR);
2459
2460 if (result < 0)
2461 return -1;
2462
2463 return (input_fd.revents &
2464 (POLLRDHUP | POLLHUP | POLLERR | POLLNVAL)) ? 1 : 0;
2465 }
2466#else
2467 return 0;
2468#endif
2469}
int PQsocket(const PGconn *conn)
Definition: fe-connect.c:7294
#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 2477 of file connection.c.

2478{
2479#if (defined(HAVE_POLL) && defined(POLLRDHUP))
2480 return true;
2481#else
2482 return false;
2483#endif
2484}

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

1495{
1496 TimestampTz endtime;
1497
1498 /*
1499 * If it takes too long to execute a cleanup query, assume the connection
1500 * is dead. It's fairly likely that this is why we aborted in the first
1501 * place (e.g. statement timeout, user cancel), so the timeout shouldn't
1502 * be too long.
1503 */
1506
1508 return false;
1509 return pgfdw_exec_cleanup_query_end(conn, query, endtime,
1510 false, ignore_errors);
1511}
static bool pgfdw_exec_cleanup_query_end(PGconn *conn, const char *query, TimestampTz endtime, bool consume_input, bool ignore_errors)
Definition: connection.c:1532

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

1515{
1516 Assert(query != NULL);
1517
1518 /*
1519 * Submit a query. Since we don't use non-blocking mode, this also can
1520 * block. But its risk is relatively small, so we ignore that for now.
1521 */
1522 if (!PQsendQuery(conn, query))
1523 {
1524 pgfdw_report_error(WARNING, NULL, conn, false, query);
1525 return false;
1526 }
1527
1528 return true;
1529}

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

1535{
1536 PGresult *result;
1537 bool timed_out;
1538
1539 Assert(query != NULL);
1540
1541 /*
1542 * If requested, consume whatever data is available from the socket. (Note
1543 * that if all data is available, this allows pgfdw_get_cleanup_result to
1544 * call PQgetResult without forcing the overhead of WaitLatchOrSocket,
1545 * which would be large compared to the overhead of PQconsumeInput.)
1546 */
1547 if (consume_input && !PQconsumeInput(conn))
1548 {
1549 pgfdw_report_error(WARNING, NULL, conn, false, query);
1550 return false;
1551 }
1552
1553 /* Get the result of the query. */
1554 if (pgfdw_get_cleanup_result(conn, endtime, endtime, &result, &timed_out))
1555 {
1556 if (timed_out)
1558 (errmsg("could not get query result due to timeout"),
1559 errcontext("remote SQL command: %s", query)));
1560 else
1561 pgfdw_report_error(WARNING, NULL, conn, false, query);
1562
1563 return false;
1564 }
1565
1566 /* Issue a warning if not successful. */
1567 if (PQresultStatus(result) != PGRES_COMMAND_OK)
1568 {
1569 pgfdw_report_error(WARNING, result, conn, true, query);
1570 return ignore_errors;
1571 }
1572 PQclear(result);
1573
1574 return true;
1575}
#define errcontext
Definition: elog.h:196

References Assert, conn, ereport, errcontext, errmsg(), pgfdw_get_cleanup_result(), pgfdw_report_error(), 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 920 of file connection.c.

921{
922 /* First, process a pending asynchronous request, if any. */
923 if (state && state->pendingAreq)
924 process_pending_request(state->pendingAreq);
925
926 if (!PQsendQuery(conn, query))
927 return NULL;
928 return pgfdw_get_result(conn);
929}

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

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

1843{
1844 ConnCacheEntry *entry;
1845 List *pending_deallocs = NIL;
1846 ListCell *lc;
1847
1848 Assert(pending_entries);
1849
1850 /*
1851 * Get the result of the COMMIT command for each of the pending entries
1852 */
1853 foreach(lc, pending_entries)
1854 {
1855 entry = (ConnCacheEntry *) lfirst(lc);
1856
1858
1859 /*
1860 * We might already have received the result on the socket, so pass
1861 * consume_input=true to try to consume it first
1862 */
1863 do_sql_command_end(entry->conn, "COMMIT TRANSACTION", true);
1864 entry->changing_xact_state = false;
1865
1866 /* Do a DEALLOCATE ALL in parallel if needed */
1867 if (entry->have_prep_stmt && entry->have_error)
1868 {
1869 /* Ignore errors (see notes in pgfdw_xact_callback) */
1870 if (PQsendQuery(entry->conn, "DEALLOCATE ALL"))
1871 {
1872 pending_deallocs = lappend(pending_deallocs, entry);
1873 continue;
1874 }
1875 }
1876 entry->have_prep_stmt = false;
1877 entry->have_error = false;
1878
1879 pgfdw_reset_xact_state(entry, true);
1880 }
1881
1882 /* No further work if no pending entries */
1883 if (!pending_deallocs)
1884 return;
1885
1886 /*
1887 * Get the result of the DEALLOCATE command for each of the pending
1888 * entries
1889 */
1890 foreach(lc, pending_deallocs)
1891 {
1892 PGresult *res;
1893
1894 entry = (ConnCacheEntry *) lfirst(lc);
1895
1896 /* Ignore errors (see notes in pgfdw_xact_callback) */
1897 while ((res = PQgetResult(entry->conn)) != NULL)
1898 {
1899 PQclear(res);
1900 /* Stop if the connection is lost (else we'll loop infinitely) */
1901 if (PQstatus(entry->conn) == CONNECTION_BAD)
1902 break;
1903 }
1904 entry->have_prep_stmt = false;
1905 entry->have_error = false;
1906
1907 pgfdw_reset_xact_state(entry, true);
1908 }
1909}
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2062

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(), PQstatus(), and res.

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

1917{
1918 ConnCacheEntry *entry;
1919 char sql[100];
1920 ListCell *lc;
1921
1922 Assert(pending_entries);
1923
1924 /*
1925 * Get the result of the RELEASE command for each of the pending entries
1926 */
1927 snprintf(sql, sizeof(sql), "RELEASE SAVEPOINT s%d", curlevel);
1928 foreach(lc, pending_entries)
1929 {
1930 entry = (ConnCacheEntry *) lfirst(lc);
1931
1933
1934 /*
1935 * We might already have received the result on the socket, so pass
1936 * consume_input=true to try to consume it first
1937 */
1938 do_sql_command_end(entry->conn, sql, true);
1939 entry->changing_xact_state = false;
1940
1941 pgfdw_reset_xact_state(entry, false);
1942 }
1943}

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

1596{
1597 volatile bool failed = false;
1598 PGresult *volatile last_res = NULL;
1599
1600 *result = NULL;
1601 *timed_out = false;
1602
1603 /* In what follows, do not leak any PGresults on an error. */
1604 PG_TRY();
1605 {
1606 int canceldelta = RETRY_CANCEL_TIMEOUT * 2;
1607
1608 for (;;)
1609 {
1610 PGresult *res;
1611
1612 while (PQisBusy(conn))
1613 {
1614 int wc;
1616 long cur_timeout;
1617
1618 /* If timeout has expired, give up. */
1619 if (now >= endtime)
1620 {
1621 *timed_out = true;
1622 failed = true;
1623 goto exit;
1624 }
1625
1626 /* If we need to re-issue the cancel request, do that. */
1627 if (now >= retrycanceltime)
1628 {
1629 /* We ignore failure to issue the repeated request. */
1630 (void) libpqsrv_cancel(conn, endtime);
1631
1632 /* Recompute "now" in case that took measurable time. */
1634
1635 /* Adjust re-cancel timeout in increasing steps. */
1636 retrycanceltime = TimestampTzPlusMilliseconds(now,
1637 canceldelta);
1638 canceldelta += canceldelta;
1639 }
1640
1641 /* If timeout has expired, give up, else get sleep time. */
1643 Min(endtime,
1644 retrycanceltime));
1645 if (cur_timeout <= 0)
1646 {
1647 *timed_out = true;
1648 failed = true;
1649 goto exit;
1650 }
1651
1652 /* first time, allocate or get the custom wait event */
1653 if (pgfdw_we_cleanup_result == 0)
1654 pgfdw_we_cleanup_result = WaitEventExtensionNew("PostgresFdwCleanupResult");
1655
1656 /* Sleep until there's something to do */
1660 PQsocket(conn),
1661 cur_timeout, pgfdw_we_cleanup_result);
1663
1665
1666 /* Data available in socket? */
1667 if (wc & WL_SOCKET_READABLE)
1668 {
1669 if (!PQconsumeInput(conn))
1670 {
1671 /* connection trouble */
1672 failed = true;
1673 goto exit;
1674 }
1675 }
1676 }
1677
1678 res = PQgetResult(conn);
1679 if (res == NULL)
1680 break; /* query is complete */
1681
1682 PQclear(last_res);
1683 last_res = res;
1684 }
1685exit: ;
1686 }
1687 PG_CATCH();
1688 {
1689 PQclear(last_res);
1690 PG_RE_THROW();
1691 }
1692 PG_END_TRY();
1693
1694 if (failed)
1695 PQclear(last_res);
1696 else
1697 *result = last_res;
1698 return failed;
1699}
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition: timestamp.c:1756
#define Min(x, y)
Definition: c.h:961
static uint32 pgfdw_we_cleanup_result
Definition: connection.c:88
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2031
struct Latch * MyLatch
Definition: globals.c:62
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:565
void ResetLatch(Latch *latch)
Definition: latch.c:724
#define WL_SOCKET_READABLE
Definition: latch.h:128
#define WL_TIMEOUT
Definition: latch.h:130
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:132
#define WL_LATCH_SET
Definition: latch.h:127
exit(1)
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122

References CHECK_FOR_INTERRUPTS, conn, exit(), GetCurrentTimestamp(), libpqsrv_cancel(), Min, MyLatch, now(), PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, pgfdw_we_cleanup_result, PQclear(), PQconsumeInput(), PQgetResult(), PQisBusy(), PQsocket(), res, 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 937 of file connection.c.

938{
940}
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_inval_callback()

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

Definition at line 1275 of file connection.c.

1276{
1277 HASH_SEQ_STATUS scan;
1278 ConnCacheEntry *entry;
1279
1280 Assert(cacheid == FOREIGNSERVEROID || cacheid == USERMAPPINGOID);
1281
1282 /* ConnectionHash must exist already, if we're registered */
1284 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1285 {
1286 /* Ignore invalid entries */
1287 if (entry->conn == NULL)
1288 continue;
1289
1290 /* hashvalue == 0 means a cache reset, must clear all state */
1291 if (hashvalue == 0 ||
1292 (cacheid == FOREIGNSERVEROID &&
1293 entry->server_hashvalue == hashvalue) ||
1294 (cacheid == USERMAPPINGOID &&
1295 entry->mapping_hashvalue == hashvalue))
1296 {
1297 /*
1298 * Close the connection immediately if it's not used yet in this
1299 * transaction. Otherwise mark it as invalid so that
1300 * pgfdw_xact_callback() can close it at the end of this
1301 * transaction.
1302 */
1303 if (entry->xact_depth == 0)
1304 {
1305 elog(DEBUG3, "discarding connection %p", entry->conn);
1306 disconnect_pg_server(entry);
1307 }
1308 else
1309 entry->invalidated = true;
1310 }
1311 }
1312}

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

1326{
1327 ForeignServer *server;
1328
1329 /* nothing to do for inactive entries and entries of sane state */
1330 if (entry->conn == NULL || !entry->changing_xact_state)
1331 return;
1332
1333 /* make sure this entry is inactive */
1334 disconnect_pg_server(entry);
1335
1336 /* find server name to be shown in the message below */
1337 server = GetForeignServer(entry->serverid);
1338
1339 ereport(ERROR,
1340 (errcode(ERRCODE_CONNECTION_EXCEPTION),
1341 errmsg("connection to server \"%s\" was lost",
1342 server->servername)));
1343}

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_error()

void pgfdw_report_error ( int  elevel,
PGresult res,
PGconn conn,
bool  clear,
const char *  sql 
)

Definition at line 956 of file connection.c.

958{
959 /* If requested, PGresult must be released before leaving this function. */
960 PG_TRY();
961 {
962 char *diag_sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
963 char *message_primary = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
964 char *message_detail = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
965 char *message_hint = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
966 char *message_context = PQresultErrorField(res, PG_DIAG_CONTEXT);
967 int sqlstate;
968
969 if (diag_sqlstate)
970 sqlstate = MAKE_SQLSTATE(diag_sqlstate[0],
971 diag_sqlstate[1],
972 diag_sqlstate[2],
973 diag_sqlstate[3],
974 diag_sqlstate[4]);
975 else
976 sqlstate = ERRCODE_CONNECTION_FAILURE;
977
978 /*
979 * If we don't get a message from the PGresult, try the PGconn. This
980 * is needed because for connection-level failures, PQgetResult may
981 * just return NULL, not a PGresult at all.
982 */
983 if (message_primary == NULL)
984 message_primary = pchomp(PQerrorMessage(conn));
985
986 ereport(elevel,
987 (errcode(sqlstate),
988 (message_primary != NULL && message_primary[0] != '\0') ?
989 errmsg_internal("%s", message_primary) :
990 errmsg("could not obtain message string for remote error"),
991 message_detail ? errdetail_internal("%s", message_detail) : 0,
992 message_hint ? errhint("%s", message_hint) : 0,
993 message_context ? errcontext("%s", message_context) : 0,
994 sql ? errcontext("remote SQL command: %s", sql) : 0));
995 }
996 PG_FINALLY();
997 {
998 if (clear)
999 PQclear(res);
1000 }
1001 PG_END_TRY();
1002}
int errhint(const char *fmt,...)
Definition: elog.c:1317
#define MAKE_SQLSTATE(ch1, ch2, ch3, ch4, ch5)
Definition: elog.h:56
#define PG_FINALLY(...)
Definition: elog.h:388
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3466
#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, PG_END_TRY, PG_FINALLY, PG_TRY, PQclear(), PQerrorMessage(), PQresultErrorField(), and res.

Referenced by close_cursor(), create_cursor(), deallocate_query(), do_sql_command_begin(), do_sql_command_end(), execute_dml_stmt(), execute_foreign_modify(), fetch_more_data(), fetch_more_data_begin(), get_remote_estimate(), pgfdw_exec_cleanup_query_begin(), pgfdw_exec_cleanup_query_end(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresForeignAsyncNotify(), postgresGetAnalyzeInfoForForeignTable(), postgresImportForeignSchema(), postgresReScanForeignScan(), and prepare_foreign_modify().

◆ pgfdw_reset_xact_state()

static void pgfdw_reset_xact_state ( ConnCacheEntry entry,
bool  toplevel 
)
static

Definition at line 1349 of file connection.c.

1350{
1351 if (toplevel)
1352 {
1353 /* Reset state to show we're out of a transaction */
1354 entry->xact_depth = 0;
1355
1356 /*
1357 * If the connection isn't in a good idle state, it is marked as
1358 * invalid or keep_connections option of its server is disabled, then
1359 * discard it to recover. Next GetConnection will open a new
1360 * connection.
1361 */
1362 if (PQstatus(entry->conn) != CONNECTION_OK ||
1364 entry->changing_xact_state ||
1365 entry->invalidated ||
1366 !entry->keep_connections)
1367 {
1368 elog(DEBUG3, "discarding connection %p", entry->conn);
1369 disconnect_pg_server(entry);
1370 }
1371 }
1372 else
1373 {
1374 /* Reset state to show we're out of a subtransaction */
1375 entry->xact_depth--;
1376 }
1377}
@ PQTRANS_IDLE
Definition: libpq-fe.h:142

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

432{
433 /* Superusers bypass the check */
434 if (superuser_arg(user->userid))
435 return;
436
437#ifdef ENABLE_GSS
438 /* Connected via GSSAPI with delegated credentials- all good. */
440 return;
441#endif
442
443 /* Ok if superuser set PW required false. */
445 return;
446
447 /* Connected via PW, with PW required true, and provided non-empty PW. */
449 {
450 /* ok if params contain a non-empty password */
451 for (int i = 0; keywords[i] != NULL; i++)
452 {
453 if (strcmp(keywords[i], "password") == 0 && values[i][0] != '\0')
454 return;
455 }
456 }
457
459 (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
460 errmsg("password or GSSAPI delegated credentials required"),
461 errdetail("Non-superuser cannot connect if the server does not request a password or use GSSAPI with delegated credentials."),
462 errhint("Target server's authentication method must be changed or password_required=false set in the user mapping attributes.")));
463}
int PQconnectionUsedPassword(const PGconn *conn)
Definition: fe-connect.c:7334
int PQconnectionUsedGSSAPI(const PGconn *conn)
Definition: fe-connect.c:7345

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

1164{
1165 HASH_SEQ_STATUS scan;
1166 ConnCacheEntry *entry;
1167 int curlevel;
1168 List *pending_entries = NIL;
1169 List *cancel_requested = NIL;
1170
1171 /* Nothing to do at subxact start, nor after commit. */
1172 if (!(event == SUBXACT_EVENT_PRE_COMMIT_SUB ||
1173 event == SUBXACT_EVENT_ABORT_SUB))
1174 return;
1175
1176 /* Quick exit if no connections were touched in this transaction. */
1178 return;
1179
1180 /*
1181 * Scan all connection cache entries to find open remote subtransactions
1182 * of the current level, and close them.
1183 */
1184 curlevel = GetCurrentTransactionNestLevel();
1186 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1187 {
1188 char sql[100];
1189
1190 /*
1191 * We only care about connections with open remote subtransactions of
1192 * the current level.
1193 */
1194 if (entry->conn == NULL || entry->xact_depth < curlevel)
1195 continue;
1196
1197 if (entry->xact_depth > curlevel)
1198 elog(ERROR, "missed cleaning up remote subtransaction at level %d",
1199 entry->xact_depth);
1200
1201 if (event == SUBXACT_EVENT_PRE_COMMIT_SUB)
1202 {
1203 /*
1204 * If abort cleanup previously failed for this connection, we
1205 * can't issue any more commands against it.
1206 */
1208
1209 /* Commit all remote subtransactions during pre-commit */
1210 snprintf(sql, sizeof(sql), "RELEASE SAVEPOINT s%d", curlevel);
1211 entry->changing_xact_state = true;
1212 if (entry->parallel_commit)
1213 {
1214 do_sql_command_begin(entry->conn, sql);
1215 pending_entries = lappend(pending_entries, entry);
1216 continue;
1217 }
1218 do_sql_command(entry->conn, sql);
1219 entry->changing_xact_state = false;
1220 }
1221 else
1222 {
1223 /* Rollback all remote subtransactions during abort */
1224 if (entry->parallel_abort)
1225 {
1226 if (pgfdw_abort_cleanup_begin(entry, false,
1227 &pending_entries,
1228 &cancel_requested))
1229 continue;
1230 }
1231 else
1232 pgfdw_abort_cleanup(entry, false);
1233 }
1234
1235 /* OK, we're outta that level of subtransaction */
1236 pgfdw_reset_xact_state(entry, false);
1237 }
1238
1239 /* If there are any pending connections, finish cleaning them up */
1240 if (pending_entries || cancel_requested)
1241 {
1242 if (event == SUBXACT_EVENT_PRE_COMMIT_SUB)
1243 {
1244 Assert(cancel_requested == NIL);
1245 pgfdw_finish_pre_subcommit_cleanup(pending_entries, curlevel);
1246 }
1247 else
1248 {
1250 pgfdw_finish_abort_cleanup(pending_entries, cancel_requested,
1251 false);
1252 }
1253 }
1254}
static void pgfdw_finish_pre_subcommit_cleanup(List *pending_entries, int curlevel)
Definition: connection.c:1916
static void pgfdw_finish_abort_cleanup(List *pending_entries, List *cancel_requested, bool toplevel)
Definition: connection.c:1950
static bool pgfdw_abort_cleanup_begin(ConnCacheEntry *entry, bool toplevel, List **pending_entries, List **cancel_requested)
Definition: connection.c:1784
static void pgfdw_abort_cleanup(ConnCacheEntry *entry, bool toplevel)
Definition: connection.c:1710
@ SUBXACT_EVENT_PRE_COMMIT_SUB
Definition: xact.h:145
@ SUBXACT_EVENT_ABORT_SUB
Definition: xact.h:144

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

1013{
1014 HASH_SEQ_STATUS scan;
1015 ConnCacheEntry *entry;
1016 List *pending_entries = NIL;
1017 List *cancel_requested = NIL;
1018
1019 /* Quick exit if no connections were touched in this transaction. */
1021 return;
1022
1023 /*
1024 * Scan all connection cache entries to find open remote transactions, and
1025 * close them.
1026 */
1028 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1029 {
1030 PGresult *res;
1031
1032 /* Ignore cache entry if no open connection right now */
1033 if (entry->conn == NULL)
1034 continue;
1035
1036 /* If it has an open remote transaction, try to close it */
1037 if (entry->xact_depth > 0)
1038 {
1039 elog(DEBUG3, "closing remote transaction on connection %p",
1040 entry->conn);
1041
1042 switch (event)
1043 {
1046
1047 /*
1048 * If abort cleanup previously failed for this connection,
1049 * we can't issue any more commands against it.
1050 */
1052
1053 /* Commit all remote transactions during pre-commit */
1054 entry->changing_xact_state = true;
1055 if (entry->parallel_commit)
1056 {
1057 do_sql_command_begin(entry->conn, "COMMIT TRANSACTION");
1058 pending_entries = lappend(pending_entries, entry);
1059 continue;
1060 }
1061 do_sql_command(entry->conn, "COMMIT TRANSACTION");
1062 entry->changing_xact_state = false;
1063
1064 /*
1065 * If there were any errors in subtransactions, and we
1066 * made prepared statements, do a DEALLOCATE ALL to make
1067 * sure we get rid of all prepared statements. This is
1068 * annoying and not terribly bulletproof, but it's
1069 * probably not worth trying harder.
1070 *
1071 * DEALLOCATE ALL only exists in 8.3 and later, so this
1072 * constrains how old a server postgres_fdw can
1073 * communicate with. We intentionally ignore errors in
1074 * the DEALLOCATE, so that we can hobble along to some
1075 * extent with older servers (leaking prepared statements
1076 * as we go; but we don't really support update operations
1077 * pre-8.3 anyway).
1078 */
1079 if (entry->have_prep_stmt && entry->have_error)
1080 {
1081 res = pgfdw_exec_query(entry->conn, "DEALLOCATE ALL",
1082 NULL);
1083 PQclear(res);
1084 }
1085 entry->have_prep_stmt = false;
1086 entry->have_error = false;
1087 break;
1089
1090 /*
1091 * We disallow any remote transactions, since it's not
1092 * very reasonable to hold them open until the prepared
1093 * transaction is committed. For the moment, throw error
1094 * unconditionally; later we might allow read-only cases.
1095 * Note that the error will cause us to come right back
1096 * here with event == XACT_EVENT_ABORT, so we'll clean up
1097 * the connection state at that point.
1098 */
1099 ereport(ERROR,
1100 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1101 errmsg("cannot PREPARE a transaction that has operated on postgres_fdw foreign tables")));
1102 break;
1104 case XACT_EVENT_COMMIT:
1105 case XACT_EVENT_PREPARE:
1106 /* Pre-commit should have closed the open transaction */
1107 elog(ERROR, "missed cleaning up connection during pre-commit");
1108 break;
1110 case XACT_EVENT_ABORT:
1111 /* Rollback all remote transactions during abort */
1112 if (entry->parallel_abort)
1113 {
1114 if (pgfdw_abort_cleanup_begin(entry, true,
1115 &pending_entries,
1116 &cancel_requested))
1117 continue;
1118 }
1119 else
1120 pgfdw_abort_cleanup(entry, true);
1121 break;
1122 }
1123 }
1124
1125 /* Reset state to show we're out of a transaction */
1126 pgfdw_reset_xact_state(entry, true);
1127 }
1128
1129 /* If there are any pending connections, finish cleaning them up */
1130 if (pending_entries || cancel_requested)
1131 {
1132 if (event == XACT_EVENT_PARALLEL_PRE_COMMIT ||
1133 event == XACT_EVENT_PRE_COMMIT)
1134 {
1135 Assert(cancel_requested == NIL);
1136 pgfdw_finish_pre_commit_cleanup(pending_entries);
1137 }
1138 else
1139 {
1141 event == XACT_EVENT_ABORT);
1142 pgfdw_finish_abort_cleanup(pending_entries, cancel_requested,
1143 true);
1144 }
1145 }
1146
1147 /*
1148 * Regardless of the event type, we can now mark ourselves as out of the
1149 * transaction. (Note: if we are here during PRE_COMMIT or PRE_PREPARE,
1150 * this saves a useless scan of the hashtable during COMMIT or PREPARE.)
1151 */
1152 xact_got_connection = false;
1153
1154 /* Also reset cursor numbering for next transaction */
1155 cursor_number = 0;
1156}
PGresult * pgfdw_exec_query(PGconn *conn, const char *query, PgFdwConnState *state)
Definition: connection.c:920
static void pgfdw_finish_pre_commit_cleanup(List *pending_entries)
Definition: connection.c:1842
@ XACT_EVENT_PRE_PREPARE
Definition: xact.h:135
@ XACT_EVENT_COMMIT
Definition: xact.h:128
@ XACT_EVENT_PARALLEL_PRE_COMMIT
Definition: xact.h:134
@ XACT_EVENT_PARALLEL_COMMIT
Definition: xact.h:129
@ XACT_EVENT_ABORT
Definition: xact.h:130
@ XACT_EVENT_PRE_COMMIT
Definition: xact.h:133
@ XACT_EVENT_PARALLEL_ABORT
Definition: xact.h:131
@ XACT_EVENT_PREPARE
Definition: xact.h:132

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(), res, 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 2319 of file connection.c.

2320{
2321 ForeignServer *server;
2322 char *servername;
2323
2324 servername = text_to_cstring(PG_GETARG_TEXT_PP(0));
2325 server = GetForeignServerByName(servername, false);
2326
2328}
static bool disconnect_cached_connections(Oid serverid)
Definition: connection.c:2368
#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:182
char * text_to_cstring(const text *t)
Definition: varlena.c:217

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

◆ postgres_fdw_disconnect_all()

Datum postgres_fdw_disconnect_all ( PG_FUNCTION_ARGS  )

Definition at line 2340 of file connection.c.

2341{
2343}
#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 2299 of file connection.c.

2300{
2302
2304}
static void postgres_fdw_get_connections_internal(FunctionCallInfo fcinfo, enum pgfdwVersion api_version)
Definition: connection.c:2142
#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 2291 of file connection.c.

2292{
2294
2296}

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

2144{
2145 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
2146 HASH_SEQ_STATUS scan;
2147 ConnCacheEntry *entry;
2148
2149 InitMaterializedSRF(fcinfo, 0);
2150
2151 /* If cache doesn't exist, we return no records */
2152 if (!ConnectionHash)
2153 return;
2154
2155 /* Check we have the expected number of output arguments */
2156 switch (rsinfo->setDesc->natts)
2157 {
2159 if (api_version != PGFDW_V1_1)
2160 elog(ERROR, "incorrect number of output arguments");
2161 break;
2163 if (api_version != PGFDW_V1_2)
2164 elog(ERROR, "incorrect number of output arguments");
2165 break;
2166 default:
2167 elog(ERROR, "incorrect number of output arguments");
2168 }
2169
2171 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
2172 {
2173 ForeignServer *server;
2175 bool nulls[POSTGRES_FDW_GET_CONNECTIONS_COLS] = {0};
2176 int i = 0;
2177
2178 /* We only look for open remote connections */
2179 if (!entry->conn)
2180 continue;
2181
2182 server = GetForeignServerExtended(entry->serverid, FSV_MISSING_OK);
2183
2184 /*
2185 * The foreign server may have been dropped in current explicit
2186 * transaction. It is not possible to drop the server from another
2187 * session when the connection associated with it is in use in the
2188 * current transaction, if tried so, the drop query in another session
2189 * blocks until the current transaction finishes.
2190 *
2191 * Even though the server is dropped in the current transaction, the
2192 * cache can still have associated active connection entry, say we
2193 * call such connections dangling. Since we can not fetch the server
2194 * name from system catalogs for dangling connections, instead we show
2195 * NULL value for server name in output.
2196 *
2197 * We could have done better by storing the server name in the cache
2198 * entry instead of server oid so that it could be used in the output.
2199 * But the server name in each cache entry requires 64 bytes of
2200 * memory, which is huge, when there are many cached connections and
2201 * the use case i.e. dropping the foreign server within the explicit
2202 * current transaction seems rare. So, we chose to show NULL value for
2203 * server name in output.
2204 *
2205 * Such dangling connections get closed either in next use or at the
2206 * end of current explicit transaction in pgfdw_xact_callback.
2207 */
2208 if (!server)
2209 {
2210 /*
2211 * If the server has been dropped in the current explicit
2212 * transaction, then this entry would have been invalidated in
2213 * pgfdw_inval_callback at the end of drop server command. Note
2214 * that this connection would not have been closed in
2215 * pgfdw_inval_callback because it is still being used in the
2216 * current explicit transaction. So, assert that here.
2217 */
2218 Assert(entry->conn && entry->xact_depth > 0 && entry->invalidated);
2219
2220 /* Show null, if no server name was found */
2221 nulls[i++] = true;
2222 }
2223 else
2224 values[i++] = CStringGetTextDatum(server->servername);
2225
2226 if (api_version >= PGFDW_V1_2)
2227 {
2228 HeapTuple tp;
2229
2230 /* Use the system cache to obtain the user mapping */
2231 tp = SearchSysCache1(USERMAPPINGOID, ObjectIdGetDatum(entry->key));
2232
2233 /*
2234 * Just like in the foreign server case, user mappings can also be
2235 * dropped in the current explicit transaction. Therefore, the
2236 * similar check as in the server case is required.
2237 */
2238 if (!HeapTupleIsValid(tp))
2239 {
2240 /*
2241 * If we reach here, this entry must have been invalidated in
2242 * pgfdw_inval_callback, same as in the server case.
2243 */
2244 Assert(entry->conn && entry->xact_depth > 0 &&
2245 entry->invalidated);
2246
2247 nulls[i++] = true;
2248 }
2249 else
2250 {
2251 Oid userid;
2252
2253 userid = ((Form_pg_user_mapping) GETSTRUCT(tp))->umuser;
2255 ReleaseSysCache(tp);
2256 }
2257 }
2258
2259 values[i++] = BoolGetDatum(!entry->invalidated);
2260
2261 if (api_version >= PGFDW_V1_2)
2262 {
2263 bool check_conn = PG_GETARG_BOOL(0);
2264
2265 /* Is this connection used in the current transaction? */
2266 values[i++] = BoolGetDatum(entry->xact_depth > 0);
2267
2268 /*
2269 * If a connection status check is requested and supported, return
2270 * whether the connection is closed. Otherwise, return NULL.
2271 */
2272 if (check_conn && pgfdw_conn_checkable())
2273 values[i++] = BoolGetDatum(pgfdw_conn_check(entry->conn) != 0);
2274 else
2275 nulls[i++] = true;
2276 }
2277
2278 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
2279 }
2280}
#define CStringGetTextDatum(s)
Definition: builtins.h:97
#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2
Definition: connection.c:2114
static int pgfdw_conn_check(PGconn *conn)
Definition: connection.c:2440
#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1
Definition: connection.c:2113
#define POSTGRES_FDW_GET_CONNECTIONS_COLS
Definition: connection.c:2115
static bool pgfdw_conn_checkable(void)
Definition: connection.c:2477
#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
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
FormData_pg_user_mapping * Form_pg_user_mapping
static Datum BoolGetDatum(bool X)
Definition: postgres.h:107
unsigned int Oid
Definition: postgres_ext.h:32
fmNodePtr resultinfo
Definition: fmgr.h:89
TupleDesc setDesc
Definition: execnodes.h:358
Tuplestorestate * setResult
Definition: execnodes.h:357
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:269
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:221
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(), 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, 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 870 of file connection.c.

871{
872 /*
873 * Currently, we don't actually track connection references because all
874 * cleanup is managed on a transaction or subtransaction basis instead. So
875 * there's nothing to do here.
876 */
877}

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

656{
657 ListCell *cell;
658
659 foreach(cell, user->options)
660 {
661 DefElem *def = (DefElem *) lfirst(cell);
662
663 if (strcmp(def->defname, "password_required") == 0)
664 return defGetBoolean(def);
665 }
666
667 return true;
668}

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

672{
673 ListCell *cell;
674
675 foreach(cell, server->options)
676 {
677 DefElem *def = (DefElem *) lfirst(cell);
678
679 if (strcmp(def->defname, "use_scram_passthrough") == 0)
680 return defGetBoolean(def);
681 }
682
683 foreach(cell, user->options)
684 {
685 DefElem *def = (DefElem *) lfirst(cell);
686
687 if (strcmp(def->defname, "use_scram_passthrough") == 0)
688 return defGetBoolean(def);
689 }
690
691 return false;
692}

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().