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

Go to the source code of this file.

Data Structures

struct   ConnCacheEntry
 

Macros

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

Typedefs

typedef Oid  ConnCacheKey
 
typedef struct ConnCacheEntry  ConnCacheEntry
 

Enumerations

 

Functions

 
 
 
 
 
 
static void  disconnect_pg_server (ConnCacheEntry *entry)
 
static void  check_conn_params (const char **keywords, const char **values, UserMapping *user)
 
 
static void  do_sql_command_begin (PGconn *conn, const char *sql)
 
static void  do_sql_command_end (PGconn *conn, const char *sql, bool consume_input)
 
static void  begin_remote_xact (ConnCacheEntry *entry)
 
static void  pgfdw_report_internal (int elevel, PGresult *res, PGconn *conn, const char *sql)
 
static void  pgfdw_xact_callback (XactEvent event, void *arg)
 
static void  pgfdw_subxact_callback (SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid, void *arg)
 
static void  pgfdw_inval_callback (Datum arg, int cacheid, uint32 hashvalue)
 
 
static void  pgfdw_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  disconnect_cached_connections (Oid serverid)
 
static void  postgres_fdw_get_connections_internal (FunctionCallInfo fcinfo, enum pgfdwVersion api_version)
 
static int  pgfdw_conn_check (PGconn *conn)
 
static bool  pgfdw_conn_checkable (void)
 
static bool  pgfdw_has_required_scram_options (const char **keywords, const char **values)
 
PGconnGetConnection (UserMapping *user, bool will_prep_stmt, PgFdwConnState **state)
 
void  do_sql_command (PGconn *conn, const char *sql)
 
 
unsigned int  GetCursorNumber (PGconn *conn)
 
unsigned int  GetPrepStmtNumber (PGconn *conn)
 
 
 
void  pgfdw_report_error (PGresult *res, PGconn *conn, const char *sql)
 
void  pgfdw_report (int elevel, PGresult *res, PGconn *conn, const char *sql)
 
 
 
 
 

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_connect = 0
 
 

Macro Definition Documentation

CONNECTION_CLEANUP_TIMEOUT

#define CONNECTION_CLEANUP_TIMEOUT   30000

Definition at line 98 of file connection.c.

CONSTRUCT_ABORT_COMMAND

#define CONSTRUCT_ABORT_COMMAND (   sql,
  entry,
  toplevel 
)
Value:
do { \
if (toplevel) \
snprintf((sql), sizeof(sql), \
"ABORT TRANSACTION"); \
snprintf((sql), sizeof(sql), \
"ROLLBACK TO SAVEPOINT s%d; RELEASE SAVEPOINT s%d", \
(entry)->xact_depth, (entry)->xact_depth); \
} while(0)
#define snprintf
Definition: port.h:239

Definition at line 108 of file connection.c.

POSTGRES_FDW_GET_CONNECTIONS_COLS

#define POSTGRES_FDW_GET_CONNECTIONS_COLS   6 /* maximum of above */

Definition at line 2139 of file connection.c.

POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1

#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1   2

Definition at line 2137 of file connection.c.

POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2

#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2   6

Definition at line 2138 of file connection.c.

RETRY_CANCEL_TIMEOUT

#define RETRY_CANCEL_TIMEOUT   1000

Definition at line 105 of file connection.c.

Typedef Documentation

ConnCacheEntry

ConnCacheKey

typedef Oid ConnCacheKey

Definition at line 53 of file connection.c.

Enumeration Type Documentation

pgfdwVersion

Enumerator
PGFDW_V1_1 
PGFDW_V1_2 

Definition at line 122 of file connection.c.

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

Function Documentation

begin_remote_xact()

static void begin_remote_xact ( ConnCacheEntryentry )
static

Definition at line 854 of file connection.c.

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

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

Referenced by GetConnection().

check_conn_params()

static void check_conn_params ( const char **  keywords,
const char **  values,
UserMappinguser 
)
static

Definition at line 721 of file connection.c.

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

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

Referenced by connect_pg_server().

configure_remote_session()

static void configure_remote_session ( PGconnconn )
static

Definition at line 773 of file connection.c.

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

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

Referenced by connect_pg_server().

connect_pg_server()

static PGconn * connect_pg_server ( ForeignServerserver,
UserMappinguser 
)
static

Definition at line 482 of file connection.c.

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

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

Referenced by make_new_connection().

disconnect_cached_connections()

static bool disconnect_cached_connections ( Oid  serverid )
static

Definition at line 2397 of file connection.c.

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

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 ( ConnCacheEntryentry )
static

Definition at line 659 of file connection.c.

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

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 ( PGconnconn,
const char *  sql 
)

Definition at line 811 of file connection.c.

812{
814 do_sql_command_end(conn, sql, false);
815}
static void do_sql_command_end(PGconn *conn, const char *sql, bool consume_input)
Definition: connection.c:825
static void do_sql_command_begin(PGconn *conn, const char *sql)
Definition: connection.c:818

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 ( PGconnconn,
const char *  sql 
)
static

Definition at line 818 of file connection.c.

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

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

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

do_sql_command_end()

static void do_sql_command_end ( PGconnconn,
const char *  sql,
bool  consume_input 
)
static

Definition at line 825 of file connection.c.

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

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

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

GetConnection()

PGconn * GetConnection ( UserMappinguser,
bool  will_prep_stmt,
PgFdwConnState **  state 
)

Definition at line 206 of file connection.c.

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

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

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

GetCursorNumber()

unsigned int GetCursorNumber ( PGconnconn )

Definition at line 918 of file connection.c.

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

References cursor_number.

Referenced by postgresAcquireSampleRowsFunc(), and postgresBeginForeignScan().

GetPrepStmtNumber()

unsigned int GetPrepStmtNumber ( PGconnconn )

Definition at line 932 of file connection.c.

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

References prep_stmt_number.

Referenced by prepare_foreign_modify().

make_new_connection()

static void make_new_connection ( ConnCacheEntryentry,
UserMappinguser 
)
static

Definition at line 369 of file connection.c.

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

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 ( ConnCacheEntryentry,
bool  toplevel 
)
static

Definition at line 1734 of file connection.c.

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

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

Referenced by pgfdw_subxact_callback(), and pgfdw_xact_callback().

pgfdw_abort_cleanup_begin()

static bool pgfdw_abort_cleanup_begin ( ConnCacheEntryentry,
bool  toplevel,
List **  pending_entries,
List **  cancel_requested 
)
static

Definition at line 1808 of file connection.c.

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

References ConnCacheEntry::changing_xact_state, ConnCacheEntry::conn, CONNECTION_CLEANUP_TIMEOUT, CONSTRUCT_ABORT_COMMAND, 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 ( PGconnconn )
static

Definition at line 1431 of file connection.c.

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

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 ( PGconnconn,
TimestampTz  endtime 
)
static

Definition at line 1464 of file connection.c.

1465{
1466 const char *errormsg = libpqsrv_cancel(conn, endtime);
1467
1468 if (errormsg != NULL)
1470 errcode(ERRCODE_CONNECTION_FAILURE),
1471 errmsg("could not send cancel request: %s", errormsg));
1472
1473 return errormsg == NULL;
1474}
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 ( PGconnconn,
TimestampTz  endtime,
TimestampTz  retrycanceltime,
bool  consume_input 
)
static

Definition at line 1477 of file connection.c.

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

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 ( PGconnconn )
static

Definition at line 2469 of file connection.c.

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

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

Referenced by postgres_fdw_get_connections_internal().

pgfdw_conn_checkable()

static bool pgfdw_conn_checkable ( void  )
static

Definition at line 2506 of file connection.c.

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

Referenced by postgres_fdw_get_connections_internal().

pgfdw_exec_cleanup_query()

static bool pgfdw_exec_cleanup_query ( PGconnconn,
const char *  query,
bool  ignore_errors 
)
static

Definition at line 1531 of file connection.c.

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

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 ( PGconnconn,
const char *  query 
)
static

Definition at line 1551 of file connection.c.

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

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

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

pgfdw_exec_cleanup_query_end()

static bool pgfdw_exec_cleanup_query_end ( PGconnconn,
const char *  query,
TimestampTz  endtime,
bool  consume_input,
bool  ignore_errors 
)
static

Definition at line 1569 of file connection.c.

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

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

Referenced by pgfdw_exec_cleanup_query(), and pgfdw_finish_abort_cleanup().

pgfdw_exec_query()

PGresult * pgfdw_exec_query ( PGconnconn,
const char *  query,
PgFdwConnStatestate 
)

Definition at line 947 of file connection.c.

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

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 ( Listpending_entries,
Listcancel_requested,
bool  toplevel 
)
static

Definition at line 1974 of file connection.c.

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

Definition at line 1866 of file connection.c.

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

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

Referenced by pgfdw_xact_callback().

pgfdw_finish_pre_subcommit_cleanup()

static void pgfdw_finish_pre_subcommit_cleanup ( Listpending_entries,
int  curlevel 
)
static

Definition at line 1940 of file connection.c.

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

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 ( PGconnconn,
TimestampTz  endtime,
TimestampTz  retrycanceltime,
PGresult **  result,
bool *  timed_out 
)
static

Definition at line 1629 of file connection.c.

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

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

Referenced by pgfdw_cancel_query_end(), and pgfdw_exec_cleanup_query_end().

pgfdw_get_result()

PGresult * pgfdw_get_result ( PGconnconn )

Definition at line 964 of file connection.c.

965{
967}
static PGresult * libpqsrv_get_result_last(PGconn *conn, uint32 wait_event_info)

References conn, libpqsrv_get_result_last(), and pgfdw_we_get_result.

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

pgfdw_has_required_scram_options()

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

Definition at line 2524 of file connection.c.

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

References Port::has_scram_keys, i, keywords, MyProcPort, and values.

Referenced by check_conn_params(), and pgfdw_security_check().

pgfdw_inval_callback()

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

Definition at line 1312 of file connection.c.

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

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 ( ConnCacheEntryentry )
static

Definition at line 1362 of file connection.c.

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

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

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

pgfdw_report()

void pgfdw_report ( int  elevel,
PGresultres,
PGconnconn,
const char *  sql 
)

Definition at line 995 of file connection.c.

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

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

Referenced by pgfdw_exec_cleanup_query_begin(), and pgfdw_exec_cleanup_query_end().

pgfdw_report_error()

pgfdw_report_internal()

static void pgfdw_report_internal ( int  elevel,
PGresultres,
PGconnconn,
const char *  sql 
)
static

Definition at line 1002 of file connection.c.

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

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

Referenced by pgfdw_report(), and pgfdw_report_error().

pgfdw_reset_xact_state()

static void pgfdw_reset_xact_state ( ConnCacheEntryentry,
bool  toplevel 
)
static

Definition at line 1386 of file connection.c.

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

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

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

pgfdw_security_check()

static void pgfdw_security_check ( const char **  keywords,
const char **  values,
UserMappinguser,
PGconnconn 
)
static

Definition at line 435 of file connection.c.

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

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

Referenced by connect_pg_server().

pgfdw_subxact_callback()

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

Definition at line 1199 of file connection.c.

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

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

Referenced by GetConnection().

pgfdw_xact_callback()

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

Definition at line 1049 of file connection.c.

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

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

Referenced by GetConnection().

postgres_fdw_disconnect()

Datum postgres_fdw_disconnect ( PG_FUNCTION_ARGS  )

Definition at line 2348 of file connection.c.

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

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

postgres_fdw_disconnect_all()

Datum postgres_fdw_disconnect_all ( PG_FUNCTION_ARGS  )

Definition at line 2369 of file connection.c.

2370{
2372}
#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 2328 of file connection.c.

2329{
2331
2333}
static void postgres_fdw_get_connections_internal(FunctionCallInfo fcinfo, enum pgfdwVersion api_version)
Definition: connection.c:2168
#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 2320 of file connection.c.

2321{
2323
2325}

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

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

References Assert(), BoolGetDatum(), ConnectionHash, CStringGetTextDatum, elog, ERROR, FSV_MISSING_OK, GetForeignServerExtended(), GETSTRUCT(), hash_seq_init(), hash_seq_search(), HeapTupleIsValid, i, InitMaterializedSRF(), Int32GetDatum(), MappingUserName, TupleDescData::natts, ObjectIdGetDatum(), PG_GETARG_BOOL, pgfdw_conn_check(), pgfdw_conn_checkable(), PGFDW_V1_1, PGFDW_V1_2, POSTGRES_FDW_GET_CONNECTIONS_COLS, POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1, POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2, PQbackendPID(), ReleaseSysCache(), FunctionCallInfoBaseData::resultinfo, SearchSysCache1(), ForeignServer::servername, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, tuplestore_putvalues(), and values.

Referenced by postgres_fdw_get_connections(), and postgres_fdw_get_connections_1_2().

ReleaseConnection()

void ReleaseConnection ( PGconnconn )

Definition at line 897 of file connection.c.

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

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

UserMappingPasswordRequired()

static bool UserMappingPasswordRequired ( UserMappinguser )
static

Definition at line 673 of file connection.c.

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

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

Referenced by check_conn_params(), and pgfdw_security_check().

UseScramPassthrough()

static bool UseScramPassthrough ( ForeignServerserver,
UserMappinguser 
)
static

Definition at line 689 of file connection.c.

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

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

Referenced by pgfdw_get_cleanup_result().

pgfdw_we_connect

uint32 pgfdw_we_connect = 0
static

Definition at line 90 of file connection.c.

Referenced by connect_pg_server().

pgfdw_we_get_result

uint32 pgfdw_we_get_result = 0
static

Definition at line 91 of file connection.c.

Referenced by GetConnection(), and pgfdw_get_result().

prep_stmt_number

unsigned int prep_stmt_number = 0
static

Definition at line 83 of file connection.c.

Referenced by GetPrepStmtNumber().

xact_got_connection

bool xact_got_connection = false
static

Definition at line 86 of file connection.c.

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

AltStyle によって変換されたページ (->オリジナル) /