PostgreSQL Source Code  git master
connection.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/xact.h"
#include "catalog/pg_user_mapping.h"
#include "commands/defrem.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "postgres_fdw.h"
#include "storage/fd.h"
#include "storage/latch.h"
#include "utils/hsearch.h"
#include "utils/inval.h"
#include "utils/memutils.h"
#include "utils/syscache.h"
Include dependency graph for connection.c:

Go to the source code of this file.

Data Structures

struct  ConnCacheEntry
 

Typedefs

typedef Oid ConnCacheKey
 
typedef struct ConnCacheEntry ConnCacheEntry
 

Functions

static PGconnconnect_pg_server (ForeignServer *server, UserMapping *user)
 
static void disconnect_pg_server (ConnCacheEntry *entry)
 
static void check_conn_params (const char **keywords, const char **values, UserMapping *user)
 
static void configure_remote_session (PGconn *conn)
 
static void do_sql_command (PGconn *conn, const char *sql)
 
static void begin_remote_xact (ConnCacheEntry *entry)
 
static void pgfdw_xact_callback (XactEvent event, void *arg)
 
static void pgfdw_subxact_callback (SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid, void *arg)
 
static void pgfdw_inval_callback (Datum arg, int cacheid, uint32 hashvalue)
 
static void pgfdw_reject_incomplete_xact_state_change (ConnCacheEntry *entry)
 
static bool pgfdw_cancel_query (PGconn *conn)
 
static bool pgfdw_exec_cleanup_query (PGconn *conn, const char *query, bool ignore_errors)
 
static bool pgfdw_get_cleanup_result (PGconn *conn, TimestampTz endtime, PGresult **result)
 
static bool UserMappingPasswordRequired (UserMapping *user)
 
PGconnGetConnection (UserMapping *user, bool will_prep_stmt)
 
void ReleaseConnection (PGconn *conn)
 
unsigned int GetCursorNumber (PGconn *conn)
 
unsigned int GetPrepStmtNumber (PGconn *conn)
 
PGresultpgfdw_exec_query (PGconn *conn, const char *query)
 
PGresultpgfdw_get_result (PGconn *conn, const char *query)
 
void pgfdw_report_error (int elevel, PGresult *res, PGconn *conn, bool clear, 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
 

Typedef Documentation

◆ ConnCacheEntry

◆ ConnCacheKey

typedef Oid ConnCacheKey

Definition at line 46 of file connection.c.

Function Documentation

◆ begin_remote_xact()

static void begin_remote_xact ( ConnCacheEntry entry)
static

Definition at line 476 of file connection.c.

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

Referenced by GetConnection().

477 {
478  int curlevel = GetCurrentTransactionNestLevel();
479 
480  /* Start main transaction if we haven't yet */
481  if (entry->xact_depth <= 0)
482  {
483  const char *sql;
484 
485  elog(DEBUG3, "starting remote transaction on connection %p",
486  entry->conn);
487 
489  sql = "START TRANSACTION ISOLATION LEVEL SERIALIZABLE";
490  else
491  sql = "START TRANSACTION ISOLATION LEVEL REPEATABLE READ";
492  entry->changing_xact_state = true;
493  do_sql_command(entry->conn, sql);
494  entry->xact_depth = 1;
495  entry->changing_xact_state = false;
496  }
497 
498  /*
499  * If we're in a subtransaction, stack up savepoints to match our level.
500  * This ensures we can rollback just the desired effects when a
501  * subtransaction aborts.
502  */
503  while (entry->xact_depth < curlevel)
504  {
505  char sql[64];
506 
507  snprintf(sql, sizeof(sql), "SAVEPOINT s%d", entry->xact_depth + 1);
508  entry->changing_xact_state = true;
509  do_sql_command(entry->conn, sql);
510  entry->xact_depth++;
511  entry->changing_xact_state = false;
512  }
513 }
#define DEBUG3
Definition: elog.h:23
bool changing_xact_state
Definition: connection.c:57
static void do_sql_command(PGconn *conn, const char *sql)
Definition: connection.c:453
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:842
PGconn * conn
Definition: connection.c:51
#define IsolationIsSerializable()
Definition: xact.h:52
#define elog(elevel,...)
Definition: elog.h:214
#define snprintf
Definition: port.h:193

◆ check_conn_params()

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

Definition at line 380 of file connection.c.

References ereport, errcode(), errdetail(), errmsg(), ERROR, i, superuser_arg(), UserMapping::userid, and UserMappingPasswordRequired().

Referenced by connect_pg_server().

381 {
382  int i;
383 
384  /* no check required if superuser */
385  if (superuser_arg(user->userid))
386  return;
387 
388  /* ok if params contain a non-empty password */
389  for (i = 0; keywords[i] != NULL; i++)
390  {
391  if (strcmp(keywords[i], "password") == 0 && values[i][0] != '\0')
392  return;
393  }
394 
395  /* ok if the superuser explicitly said so at user mapping creation time */
396  if (!UserMappingPasswordRequired(user))
397  return;
398 
399  ereport(ERROR,
400  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
401  errmsg("password is required"),
402  errdetail("Non-superusers must provide a password in the user mapping.")));
403 }
int errcode(int sqlerrcode)
Definition: elog.c:610
Oid userid
Definition: foreign.h:48
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:957
bool superuser_arg(Oid roleid)
Definition: superuser.c:56
static bool UserMappingPasswordRequired(UserMapping *user)
Definition: connection.c:357
#define ereport(elevel,...)
Definition: elog.h:144
static Datum values[MAXATTR]
Definition: bootstrap.c:167
int errmsg(const char *fmt,...)
Definition: elog.c:824
int i

◆ configure_remote_session()

static void configure_remote_session ( PGconn conn)
static

Definition at line 417 of file connection.c.

References do_sql_command(), and PQserverVersion().

Referenced by connect_pg_server().

418 {
419  int remoteversion = PQserverVersion(conn);
420 
421  /* Force the search path to contain only pg_catalog (see deparse.c) */
422  do_sql_command(conn, "SET search_path = pg_catalog");
423 
424  /*
425  * Set remote timezone; this is basically just cosmetic, since all
426  * transmitted and returned timestamptzs should specify a zone explicitly
427  * anyway. However it makes the regression test outputs more predictable.
428  *
429  * We don't risk setting remote zone equal to ours, since the remote
430  * server might use a different timezone database. Instead, use UTC
431  * (quoted, because very old servers are picky about case).
432  */
433  do_sql_command(conn, "SET timezone = 'UTC'");
434 
435  /*
436  * Set values needed to ensure unambiguous data output from remote. (This
437  * logic should match what pg_dump does. See also set_transmission_modes
438  * in postgres_fdw.c.)
439  */
440  do_sql_command(conn, "SET datestyle = ISO");
441  if (remoteversion >= 80400)
442  do_sql_command(conn, "SET intervalstyle = postgres");
443  if (remoteversion >= 90000)
444  do_sql_command(conn, "SET extra_float_digits = 3");
445  else
446  do_sql_command(conn, "SET extra_float_digits = 2");
447 }
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:6677
static void do_sql_command(PGconn *conn, const char *sql)
Definition: connection.c:453

◆ connect_pg_server()

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

Definition at line 222 of file connection.c.

References AcquireExternalFD(), check_conn_params(), configure_remote_session(), ConnCacheEntry::conn, CONNECTION_OK, ereport, errcode(), errdetail(), errdetail_internal(), errhint(), errmsg(), ERROR, ExtractConnectionOptions(), GetDatabaseEncodingName(), list_length(), ForeignServer::options, UserMapping::options, palloc(), pchomp(), pfree(), PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, PQconnectdbParams(), PQconnectionUsedPassword(), PQerrorMessage(), PQfinish(), PQstatus(), ReleaseExternalFD(), ForeignServer::servername, superuser_arg(), UserMapping::userid, UserMappingPasswordRequired(), and values.

Referenced by GetConnection().

223 {
224  PGconn *volatile conn = NULL;
225 
226  /*
227  * Use PG_TRY block to ensure closing connection on error.
228  */
229  PG_TRY();
230  {
231  const char **keywords;
232  const char **values;
233  int n;
234 
235  /*
236  * Construct connection params from generic options of ForeignServer
237  * and UserMapping. (Some of them might not be libpq options, in
238  * which case we'll just waste a few array slots.) Add 3 extra slots
239  * for fallback_application_name, client_encoding, end marker.
240  */
241  n = list_length(server->options) + list_length(user->options) + 3;
242  keywords = (const char **) palloc(n * sizeof(char *));
243  values = (const char **) palloc(n * sizeof(char *));
244 
245  n = 0;
246  n += ExtractConnectionOptions(server->options,
247  keywords + n, values + n);
249  keywords + n, values + n);
250 
251  /* Use "postgres_fdw" as fallback_application_name. */
252  keywords[n] = "fallback_application_name";
253  values[n] = "postgres_fdw";
254  n++;
255 
256  /* Set client_encoding so that libpq can convert encoding properly. */
257  keywords[n] = "client_encoding";
258  values[n] = GetDatabaseEncodingName();
259  n++;
260 
261  keywords[n] = values[n] = NULL;
262 
263  /* verify the set of connection parameters */
264  check_conn_params(keywords, values, user);
265 
266  /*
267  * We must obey fd.c's limit on non-virtual file descriptors. Assume
268  * that a PGconn represents one long-lived FD. (Doing this here also
269  * ensures that VFDs are closed if needed to make room.)
270  */
271  if (!AcquireExternalFD())
272  {
273 #ifndef WIN32 /* can't write #if within ereport() macro */
274  ereport(ERROR,
275  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
276  errmsg("could not connect to server \"%s\"",
277  server->servername),
278  errdetail("There are too many open files on the local server."),
279  errhint("Raise the server's max_files_per_process and/or \"ulimit -n\" limits.")));
280 #else
281  ereport(ERROR,
282  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
283  errmsg("could not connect to server \"%s\"",
284  server->servername),
285  errdetail("There are too many open files on the local server."),
286  errhint("Raise the server's max_files_per_process setting.")));
287 #endif
288  }
289 
290  /* OK to make connection */
291  conn = PQconnectdbParams(keywords, values, false);
292 
293  if (!conn)
294  ReleaseExternalFD(); /* because the PG_CATCH block won't */
295 
296  if (!conn || PQstatus(conn) != CONNECTION_OK)
297  ereport(ERROR,
298  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
299  errmsg("could not connect to server \"%s\"",
300  server->servername),
301  errdetail_internal("%s", pchomp(PQerrorMessage(conn)))));
302 
303  /*
304  * Check that non-superuser has used password to establish connection;
305  * otherwise, he's piggybacking on the postgres server's user
306  * identity. See also dblink_security_check() in contrib/dblink and
307  * check_conn_params.
308  */
309  if (!superuser_arg(user->userid) && UserMappingPasswordRequired(user) &&
311  ereport(ERROR,
312  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
313  errmsg("password is required"),
314  errdetail("Non-superuser cannot connect if the server does not request a password."),
315  errhint("Target server's authentication method must be changed or password_required=false set in the user mapping attributes.")));
316 
317  /* Prepare new session for use */
319 
320  pfree(keywords);
321  pfree(values);
322  }
323  PG_CATCH();
324  {
325  /* Release PGconn data structure if we managed to create one */
326  if (conn)
327  {
328  PQfinish(conn);
330  }
331  PG_RE_THROW();
332  }
333  PG_END_TRY();
334 
335  return conn;
336 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6687
static void configure_remote_session(PGconn *conn)
Definition: connection.c:417
int errhint(const char *fmt,...)
Definition: elog.c:1071
static void check_conn_params(const char **keywords, const char **values, UserMapping *user)
Definition: connection.c:380
int errcode(int sqlerrcode)
Definition: elog.c:610
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4185
Oid userid
Definition: foreign.h:48
PGconn * PQconnectdbParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:640
int errdetail_internal(const char *fmt,...)
Definition: elog.c:984
char * pchomp(const char *in)
Definition: mcxt.c:1214
void pfree(void *pointer)
Definition: mcxt.c:1056
int ExtractConnectionOptions(List *defelems, const char **keywords, const char **values)
Definition: option.c:333
#define ERROR
Definition: elog.h:43
PGconn * conn
Definition: streamutil.c:54
int errdetail(const char *fmt,...)
Definition: elog.c:957
List * options
Definition: foreign.h:50
bool superuser_arg(Oid roleid)
Definition: superuser.c:56
static bool UserMappingPasswordRequired(UserMapping *user)
Definition: connection.c:357
bool AcquireExternalFD(void)
Definition: fd.c:1045
#define ereport(elevel,...)
Definition: elog.h:144
#define PG_CATCH()
Definition: elog.h:305
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1157
static int list_length(const List *l)
Definition: pg_list.h:169
#define PG_RE_THROW()
Definition: elog.h:336
static Datum values[MAXATTR]
Definition: bootstrap.c:167
int PQconnectionUsedPassword(const PGconn *conn)
Definition: fe-connect.c:6736
void ReleaseExternalFD(void)
Definition: fd.c:1098
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:824
char * servername
Definition: foreign.h:39
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6634
#define PG_TRY()
Definition: elog.h:295
List * options
Definition: foreign.h:42
#define PG_END_TRY()
Definition: elog.h:320

◆ disconnect_pg_server()

static void disconnect_pg_server ( ConnCacheEntry entry)
static

Definition at line 342 of file connection.c.

References ConnCacheEntry::conn, PQfinish(), and ReleaseExternalFD().

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

343 {
344  if (entry->conn != NULL)
345  {
346  PQfinish(entry->conn);
347  entry->conn = NULL;
349  }
350 }
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4185
PGconn * conn
Definition: connection.c:51
void ReleaseExternalFD(void)
Definition: fd.c:1098

◆ do_sql_command()

static void do_sql_command ( PGconn conn,
const char *  sql 
)
static

Definition at line 453 of file connection.c.

References ERROR, pgfdw_get_result(), pgfdw_report_error(), PGRES_COMMAND_OK, PQclear(), PQresultStatus(), and PQsendQuery().

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

454 {
455  PGresult *res;
456 
457  if (!PQsendQuery(conn, sql))
458  pgfdw_report_error(ERROR, NULL, conn, false, sql);
459  res = pgfdw_get_result(conn, sql);
460  if (PQresultStatus(res) != PGRES_COMMAND_OK)
461  pgfdw_report_error(ERROR, res, conn, true, sql);
462  PQclear(res);
463 }
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1234
#define ERROR
Definition: elog.h:43
void pgfdw_report_error(int elevel, PGresult *res, PGconn *conn, bool clear, const char *sql)
Definition: connection.c:656
void PQclear(PGresult *res)
Definition: fe-exec.c:694
PGresult * pgfdw_get_result(PGconn *conn, const char *query)
Definition: connection.c:591

◆ GetConnection()

PGconn* GetConnection ( UserMapping user,
bool  will_prep_stmt 
)

Definition at line 107 of file connection.c.

References begin_remote_xact(), CacheMemoryContext, CacheRegisterSyscacheCallback(), ConnCacheEntry::changing_xact_state, ConnCacheEntry::conn, connect_pg_server(), DEBUG3, disconnect_pg_server(), elog, HASHCTL::entrysize, FOREIGNSERVEROID, GetForeignServer(), GetSysCacheHashValue1, HASH_BLOBS, HASH_CONTEXT, hash_create(), HASH_ELEM, HASH_ENTER, hash_search(), ConnCacheEntry::have_error, ConnCacheEntry::have_prep_stmt, HASHCTL::hcxt, ConnCacheEntry::invalidated, ConnCacheEntry::key, HASHCTL::keysize, ConnCacheEntry::mapping_hashvalue, MemSet, ObjectIdGetDatum, pgfdw_inval_callback(), pgfdw_reject_incomplete_xact_state_change(), pgfdw_subxact_callback(), pgfdw_xact_callback(), RegisterSubXactCallback(), RegisterXactCallback(), ConnCacheEntry::server_hashvalue, ForeignServer::serverid, UserMapping::serverid, ForeignServer::servername, UserMapping::umid, UserMapping::userid, USERMAPPINGOID, ConnCacheEntry::xact_depth, and xact_got_connection.

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

108 {
109  bool found;
110  ConnCacheEntry *entry;
112 
113  /* First time through, initialize connection cache hashtable */
114  if (ConnectionHash == NULL)
115  {
116  HASHCTL ctl;
117 
118  MemSet(&ctl, 0, sizeof(ctl));
119  ctl.keysize = sizeof(ConnCacheKey);
120  ctl.entrysize = sizeof(ConnCacheEntry);
121  /* allocate ConnectionHash in the cache context */
122  ctl.hcxt = CacheMemoryContext;
123  ConnectionHash = hash_create("postgres_fdw connections", 8,
124  &ctl,
126 
127  /*
128  * Register some callback functions that manage connection cleanup.
129  * This should be done just once in each backend.
130  */
137  }
138 
139  /* Set flag that we did GetConnection during the current transaction */
140  xact_got_connection = true;
141 
142  /* Create hash key for the entry. Assume no pad bytes in key struct */
143  key = user->umid;
144 
145  /*
146  * Find or create cached entry for requested connection.
147  */
148  entry = hash_search(ConnectionHash, &key, HASH_ENTER, &found);
149  if (!found)
150  {
151  /*
152  * We need only clear "conn" here; remaining fields will be filled
153  * later when "conn" is set.
154  */
155  entry->conn = NULL;
156  }
157 
158  /* Reject further use of connections which failed abort cleanup. */
160 
161  /*
162  * If the connection needs to be remade due to invalidation, disconnect as
163  * soon as we're out of all transactions.
164  */
165  if (entry->conn != NULL && entry->invalidated && entry->xact_depth == 0)
166  {
167  elog(DEBUG3, "closing connection %p for option changes to take effect",
168  entry->conn);
169  disconnect_pg_server(entry);
170  }
171 
172  /*
173  * We don't check the health of cached connection here, because it would
174  * require some overhead. Broken connection will be detected when the
175  * connection is actually used.
176  */
177 
178  /*
179  * If cache entry doesn't have a connection, we have to establish a new
180  * connection. (If connect_pg_server throws an error, the cache entry
181  * will remain in a valid empty state, ie conn == NULL.)
182  */
183  if (entry->conn == NULL)
184  {
185  ForeignServer *server = GetForeignServer(user->serverid);
186 
187  /* Reset all transient state fields, to be sure all are clean */
188  entry->xact_depth = 0;
189  entry->have_prep_stmt = false;
190  entry->have_error = false;
191  entry->changing_xact_state = false;
192  entry->invalidated = false;
193  entry->server_hashvalue =
195  ObjectIdGetDatum(server->serverid));
196  entry->mapping_hashvalue =
198  ObjectIdGetDatum(user->umid));
199 
200  /* Now try to make the connection */
201  entry->conn = connect_pg_server(server, user);
202 
203  elog(DEBUG3, "new postgres_fdw connection %p for server \"%s\" (user mapping oid %u, userid %u)",
204  entry->conn, server->servername, user->umid, user->userid);
205  }
206 
207  /*
208  * Start a new transaction or subtransaction if needed.
209  */
210  begin_remote_xact(entry);
211 
212  /* Remember if caller will prepare statements */
213  entry->have_prep_stmt |= will_prep_stmt;
214 
215  return entry->conn;
216 }
Oid umid
Definition: foreign.h:47
#define HASH_CONTEXT
Definition: hsearch.h:93
#define HASH_ELEM
Definition: hsearch.h:87
MemoryContext hcxt
Definition: hsearch.h:78
#define DEBUG3
Definition: elog.h:23
struct ConnCacheEntry ConnCacheEntry
Size entrysize
Definition: hsearch.h:73
#define MemSet(start, val, len)
Definition: c.h:971
bool have_prep_stmt
Definition: connection.c:55
#define GetSysCacheHashValue1(cacheId, key1)
Definition: syscache.h:201
uint32 server_hashvalue
Definition: connection.c:59
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:908
Oid userid
Definition: foreign.h:48
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
bool changing_xact_state
Definition: connection.c:57
bool invalidated
Definition: connection.c:58
static void pgfdw_inval_callback(Datum arg, int cacheid, uint32 hashvalue)
Definition: connection.c:1008
#define HASH_BLOBS
Definition: hsearch.h:88
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1426
static void pgfdw_xact_callback(XactEvent event, void *arg)
Definition: connection.c:707
static HTAB * ConnectionHash
Definition: connection.c:66
ForeignServer * GetForeignServer(Oid serverid)
Definition: foreign.c:109
uintptr_t Datum
Definition: postgres.h:367
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:318
void RegisterSubXactCallback(SubXactCallback callback, void *arg)
Definition: xact.c:3553
Size keysize
Definition: hsearch.h:72
uint32 mapping_hashvalue
Definition: connection.c:60
PGconn * conn
Definition: connection.c:51
static void disconnect_pg_server(ConnCacheEntry *entry)
Definition: connection.c:342
void RegisterXactCallback(XactCallback callback, void *arg)
Definition: xact.c:3498
static void pgfdw_reject_incomplete_xact_state_change(ConnCacheEntry *entry)
Definition: connection.c:1044
static bool xact_got_connection
Definition: connection.c:73
Oid serverid
Definition: foreign.h:49
char * servername
Definition: foreign.h:39
#define elog(elevel,...)
Definition: elog.h:214
static void pgfdw_subxact_callback(SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid, void *arg)
Definition: connection.c:894
static void begin_remote_xact(ConnCacheEntry *entry)
Definition: connection.c:476
Oid ConnCacheKey
Definition: connection.c:46
Oid serverid
Definition: foreign.h:36
MemoryContext CacheMemoryContext
Definition: mcxt.c:47
static PGconn * connect_pg_server(ForeignServer *server, UserMapping *user)
Definition: connection.c:222

◆ GetCursorNumber()

unsigned int GetCursorNumber ( PGconn conn)

Definition at line 540 of file connection.c.

References cursor_number.

Referenced by postgresAcquireSampleRowsFunc(), and postgresBeginForeignScan().

541 {
542  return ++cursor_number;
543 }
static unsigned int cursor_number
Definition: connection.c:69

◆ GetPrepStmtNumber()

unsigned int GetPrepStmtNumber ( PGconn conn)

Definition at line 554 of file connection.c.

References prep_stmt_number.

Referenced by prepare_foreign_modify().

555 {
556  return ++prep_stmt_number;
557 }
static unsigned int prep_stmt_number
Definition: connection.c:70

◆ pgfdw_cancel_query()

static bool pgfdw_cancel_query ( PGconn conn)
static

Definition at line 1078 of file connection.c.

References ereport, errcode(), errmsg(), GetCurrentTimestamp(), pgfdw_get_cleanup_result(), PQcancel(), PQclear(), PQfreeCancel(), PQgetCancel(), TimestampTzPlusMilliseconds, and WARNING.

Referenced by pgfdw_subxact_callback(), and pgfdw_xact_callback().

1079 {
1080  PGcancel *cancel;
1081  char errbuf[256];
1082  PGresult *result = NULL;
1083  TimestampTz endtime;
1084 
1085  /*
1086  * If it takes too long to cancel the query and discard the result, assume
1087  * the connection is dead.
1088  */
1090 
1091  /*
1092  * Issue cancel request. Unfortunately, there's no good way to limit the
1093  * amount of time that we might block inside PQgetCancel().
1094  */
1095  if ((cancel = PQgetCancel(conn)))
1096  {
1097  if (!PQcancel(cancel, errbuf, sizeof(errbuf)))
1098  {
1099  ereport(WARNING,
1100  (errcode(ERRCODE_CONNECTION_FAILURE),
1101  errmsg("could not send cancel request: %s",
1102  errbuf)));
1103  PQfreeCancel(cancel);
1104  return false;
1105  }
1106  PQfreeCancel(cancel);
1107  }
1108 
1109  /* Get and discard the result of the query. */
1110  if (pgfdw_get_cleanup_result(conn, endtime, &result))
1111  return false;
1112  PQclear(result);
1113 
1114  return true;
1115 }
static bool pgfdw_get_cleanup_result(PGconn *conn, TimestampTz endtime, PGresult **result)
Definition: connection.c:1179
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
int64 TimestampTz
Definition: timestamp.h:39
void PQfreeCancel(PGcancel *cancel)
Definition: fe-connect.c:4329
int errcode(int sqlerrcode)
Definition: elog.c:610
PGcancel * PQgetCancel(PGconn *conn)
Definition: fe-connect.c:4306
#define WARNING
Definition: elog.h:40
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
#define ereport(elevel,...)
Definition: elog.h:144
void PQclear(PGresult *res)
Definition: fe-exec.c:694
int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
Definition: fe-connect.c:4461
int errmsg(const char *fmt,...)
Definition: elog.c:824

◆ pgfdw_exec_cleanup_query()

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

Definition at line 1125 of file connection.c.

References GetCurrentTimestamp(), pgfdw_get_cleanup_result(), pgfdw_report_error(), PGRES_COMMAND_OK, PQclear(), PQresultStatus(), PQsendQuery(), TimestampTzPlusMilliseconds, and WARNING.

Referenced by pgfdw_subxact_callback(), and pgfdw_xact_callback().

1126 {
1127  PGresult *result = NULL;
1128  TimestampTz endtime;
1129 
1130  /*
1131  * If it takes too long to execute a cleanup query, assume the connection
1132  * is dead. It's fairly likely that this is why we aborted in the first
1133  * place (e.g. statement timeout, user cancel), so the timeout shouldn't
1134  * be too long.
1135  */
1137 
1138  /*
1139  * Submit a query. Since we don't use non-blocking mode, this also can
1140  * block. But its risk is relatively small, so we ignore that for now.
1141  */
1142  if (!PQsendQuery(conn, query))
1143  {
1144  pgfdw_report_error(WARNING, NULL, conn, false, query);
1145  return false;
1146  }
1147 
1148  /* Get the result of the query. */
1149  if (pgfdw_get_cleanup_result(conn, endtime, &result))
1150  return false;
1151 
1152  /* Issue a warning if not successful. */
1153  if (PQresultStatus(result) != PGRES_COMMAND_OK)
1154  {
1155  pgfdw_report_error(WARNING, result, conn, true, query);
1156  return ignore_errors;
1157  }
1158  PQclear(result);
1159 
1160  return true;
1161 }
static bool pgfdw_get_cleanup_result(PGconn *conn, TimestampTz endtime, PGresult **result)
Definition: connection.c:1179
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
int64 TimestampTz
Definition: timestamp.h:39
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1234
void pgfdw_report_error(int elevel, PGresult *res, PGconn *conn, bool clear, const char *sql)
Definition: connection.c:656
#define WARNING
Definition: elog.h:40
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
void PQclear(PGresult *res)
Definition: fe-exec.c:694

◆ pgfdw_exec_query()

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

Definition at line 567 of file connection.c.

References ERROR, pgfdw_get_result(), pgfdw_report_error(), and PQsendQuery().

Referenced by close_cursor(), fetch_more_data(), finish_foreign_modify(), get_remote_estimate(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresImportForeignSchema(), and postgresReScanForeignScan().

568 {
569  /*
570  * Submit a query. Since we don't use non-blocking mode, this also can
571  * block. But its risk is relatively small, so we ignore that for now.
572  */
573  if (!PQsendQuery(conn, query))
574  pgfdw_report_error(ERROR, NULL, conn, false, query);
575 
576  /* Wait for the result. */
577  return pgfdw_get_result(conn, query);
578 }
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1234
#define ERROR
Definition: elog.h:43
void pgfdw_report_error(int elevel, PGresult *res, PGconn *conn, bool clear, const char *sql)
Definition: connection.c:656
PGresult * pgfdw_get_result(PGconn *conn, const char *query)
Definition: connection.c:591

◆ pgfdw_get_cleanup_result()

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

Definition at line 1179 of file connection.c.

References CHECK_FOR_INTERRUPTS, GetCurrentTimestamp(), Min, MyLatch, now(), PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, PG_WAIT_EXTENSION, PQclear(), PQconsumeInput(), PQgetResult(), PQisBusy(), PQsocket(), ResetLatch(), TimestampDifference(), USECS_PER_SEC, WaitLatchOrSocket(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_SOCKET_READABLE, and WL_TIMEOUT.

Referenced by pgfdw_cancel_query(), and pgfdw_exec_cleanup_query().

1180 {
1181  volatile bool timed_out = false;
1182  PGresult *volatile last_res = NULL;
1183 
1184  /* In what follows, do not leak any PGresults on an error. */
1185  PG_TRY();
1186  {
1187  for (;;)
1188  {
1189  PGresult *res;
1190 
1191  while (PQisBusy(conn))
1192  {
1193  int wc;
1195  long secs;
1196  int microsecs;
1197  long cur_timeout;
1198 
1199  /* If timeout has expired, give up, else get sleep time. */
1200  if (now >= endtime)
1201  {
1202  timed_out = true;
1203  goto exit;
1204  }
1205  TimestampDifference(now, endtime, &secs, &microsecs);
1206 
1207  /* To protect against clock skew, limit sleep to one minute. */
1208  cur_timeout = Min(60000, secs * USECS_PER_SEC + microsecs);
1209 
1210  /* Sleep until there's something to do */
1214  PQsocket(conn),
1215  cur_timeout, PG_WAIT_EXTENSION);
1217 
1219 
1220  /* Data available in socket? */
1221  if (wc & WL_SOCKET_READABLE)
1222  {
1223  if (!PQconsumeInput(conn))
1224  {
1225  /* connection trouble; treat the same as a timeout */
1226  timed_out = true;
1227  goto exit;
1228  }
1229  }
1230  }
1231 
1232  res = PQgetResult(conn);
1233  if (res == NULL)
1234  break; /* query is complete */
1235 
1236  PQclear(last_res);
1237  last_res = res;
1238  }
1239 exit: ;
1240  }
1241  PG_CATCH();
1242  {
1243  PQclear(last_res);
1244  PG_RE_THROW();
1245  }
1246  PG_END_TRY();
1247 
1248  if (timed_out)
1249  PQclear(last_res);
1250  else
1251  *result = last_res;
1252  return timed_out;
1253 }
#define WL_TIMEOUT
Definition: latch.h:127
#define USECS_PER_SEC
Definition: timestamp.h:94
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
int64 TimestampTz
Definition: timestamp.h:39
#define Min(x, y)
Definition: c.h:920
#define WL_SOCKET_READABLE
Definition: latch.h:125
void ResetLatch(Latch *latch)
Definition: latch.c:540
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:390
#define PG_WAIT_EXTENSION
Definition: pgstat.h:789
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1704
void PQclear(PGresult *res)
Definition: fe-exec.c:694
#define PG_CATCH()
Definition: elog.h:305
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:1754
#define PG_RE_THROW()
Definition: elog.h:336
struct Latch * MyLatch
Definition: globals.c:54
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1657
#define PG_TRY()
Definition: elog.h:295
#define WL_LATCH_SET
Definition: latch.h:124
int PQsocket(const PGconn *conn)
Definition: fe-connect.c:6705
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1547
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1778
#define PG_END_TRY()
Definition: elog.h:320
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129

◆ pgfdw_get_result()

PGresult* pgfdw_get_result ( PGconn conn,
const char *  query 
)

Definition at line 591 of file connection.c.

References CHECK_FOR_INTERRUPTS, ERROR, MyLatch, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, PG_WAIT_EXTENSION, pgfdw_report_error(), PQclear(), PQconsumeInput(), PQgetResult(), PQisBusy(), PQsocket(), ResetLatch(), WaitLatchOrSocket(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, and WL_SOCKET_READABLE.

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

592 {
593  PGresult *volatile last_res = NULL;
594 
595  /* In what follows, do not leak any PGresults on an error. */
596  PG_TRY();
597  {
598  for (;;)
599  {
600  PGresult *res;
601 
602  while (PQisBusy(conn))
603  {
604  int wc;
605 
606  /* Sleep until there's something to do */
610  PQsocket(conn),
611  -1L, PG_WAIT_EXTENSION);
613 
615 
616  /* Data available in socket? */
617  if (wc & WL_SOCKET_READABLE)
618  {
619  if (!PQconsumeInput(conn))
620  pgfdw_report_error(ERROR, NULL, conn, false, query);
621  }
622  }
623 
624  res = PQgetResult(conn);
625  if (res == NULL)
626  break; /* query is complete */
627 
628  PQclear(last_res);
629  last_res = res;
630  }
631  }
632  PG_CATCH();
633  {
634  PQclear(last_res);
635  PG_RE_THROW();
636  }
637  PG_END_TRY();
638 
639  return last_res;
640 }
#define WL_SOCKET_READABLE
Definition: latch.h:125
void ResetLatch(Latch *latch)
Definition: latch.c:540
#define ERROR
Definition: elog.h:43
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:390
void pgfdw_report_error(int elevel, PGresult *res, PGconn *conn, bool clear, const char *sql)
Definition: connection.c:656
#define PG_WAIT_EXTENSION
Definition: pgstat.h:789
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1704
void PQclear(PGresult *res)
Definition: fe-exec.c:694
#define PG_CATCH()
Definition: elog.h:305
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:1754
#define PG_RE_THROW()
Definition: elog.h:336
struct Latch * MyLatch
Definition: globals.c:54
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
#define PG_TRY()
Definition: elog.h:295
#define WL_LATCH_SET
Definition: latch.h:124
int PQsocket(const PGconn *conn)
Definition: fe-connect.c:6705
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1778
#define PG_END_TRY()
Definition: elog.h:320
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129

◆ pgfdw_inval_callback()

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

Definition at line 1008 of file connection.c.

References Assert, ConnCacheEntry::conn, FOREIGNSERVEROID, hash_seq_init(), hash_seq_search(), ConnCacheEntry::invalidated, ConnCacheEntry::mapping_hashvalue, ConnCacheEntry::server_hashvalue, and USERMAPPINGOID.

Referenced by GetConnection().

1009 {
1010  HASH_SEQ_STATUS scan;
1011  ConnCacheEntry *entry;
1012 
1013  Assert(cacheid == FOREIGNSERVEROID || cacheid == USERMAPPINGOID);
1014 
1015  /* ConnectionHash must exist already, if we're registered */
1016  hash_seq_init(&scan, ConnectionHash);
1017  while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1018  {
1019  /* Ignore invalid entries */
1020  if (entry->conn == NULL)
1021  continue;
1022 
1023  /* hashvalue == 0 means a cache reset, must clear all state */
1024  if (hashvalue == 0 ||
1025  (cacheid == FOREIGNSERVEROID &&
1026  entry->server_hashvalue == hashvalue) ||
1027  (cacheid == USERMAPPINGOID &&
1028  entry->mapping_hashvalue == hashvalue))
1029  entry->invalidated = true;
1030  }
1031 }
uint32 server_hashvalue
Definition: connection.c:59
bool invalidated
Definition: connection.c:58
static HTAB * ConnectionHash
Definition: connection.c:66
uint32 mapping_hashvalue
Definition: connection.c:60
PGconn * conn
Definition: connection.c:51
#define Assert(condition)
Definition: c.h:738
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1391
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1381

◆ pgfdw_reject_incomplete_xact_state_change()

static void pgfdw_reject_incomplete_xact_state_change ( ConnCacheEntry entry)
static

Definition at line 1044 of file connection.c.

References ConnCacheEntry::changing_xact_state, ConnCacheEntry::conn, disconnect_pg_server(), elog, ereport, errcode(), errmsg(), ERROR, GetForeignServer(), GETSTRUCT, HeapTupleIsValid, ConnCacheEntry::key, ObjectIdGetDatum, ReleaseSysCache(), SearchSysCache1(), ForeignServer::servername, and USERMAPPINGOID.

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

1045 {
1046  HeapTuple tup;
1047  Form_pg_user_mapping umform;
1048  ForeignServer *server;
1049 
1050  /* nothing to do for inactive entries and entries of sane state */
1051  if (entry->conn == NULL || !entry->changing_xact_state)
1052  return;
1053 
1054  /* make sure this entry is inactive */
1055  disconnect_pg_server(entry);
1056 
1057  /* find server name to be shown in the message below */
1059  ObjectIdGetDatum(entry->key));
1060  if (!HeapTupleIsValid(tup))
1061  elog(ERROR, "cache lookup failed for user mapping %u", entry->key);
1062  umform = (Form_pg_user_mapping) GETSTRUCT(tup);
1063  server = GetForeignServer(umform->umserver);
1064  ReleaseSysCache(tup);
1065 
1066  ereport(ERROR,
1067  (errcode(ERRCODE_CONNECTION_EXCEPTION),
1068  errmsg("connection to server \"%s\" was lost",
1069  server->servername)));
1070 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
ConnCacheKey key
Definition: connection.c:50
int errcode(int sqlerrcode)
Definition: elog.c:610
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
bool changing_xact_state
Definition: connection.c:57
FormData_pg_user_mapping * Form_pg_user_mapping
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
ForeignServer * GetForeignServer(Oid serverid)
Definition: foreign.c:109
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define ereport(elevel,...)
Definition: elog.h:144
PGconn * conn
Definition: connection.c:51
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void disconnect_pg_server(ConnCacheEntry *entry)
Definition: connection.c:342
int errmsg(const char *fmt,...)
Definition: elog.c:824
char * servername
Definition: foreign.h:39
#define elog(elevel,...)
Definition: elog.h:214

◆ pgfdw_report_error()

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

Definition at line 656 of file connection.c.

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

Referenced by close_cursor(), create_cursor(), do_sql_command(), execute_dml_stmt(), execute_foreign_modify(), fetch_more_data(), finish_foreign_modify(), get_remote_estimate(), pgfdw_exec_cleanup_query(), pgfdw_exec_query(), pgfdw_get_result(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresImportForeignSchema(), postgresReScanForeignScan(), and prepare_foreign_modify().

658 {
659  /* If requested, PGresult must be released before leaving this function. */
660  PG_TRY();
661  {
662  char *diag_sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
663  char *message_primary = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
664  char *message_detail = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
665  char *message_hint = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
666  char *message_context = PQresultErrorField(res, PG_DIAG_CONTEXT);
667  int sqlstate;
668 
669  if (diag_sqlstate)
670  sqlstate = MAKE_SQLSTATE(diag_sqlstate[0],
671  diag_sqlstate[1],
672  diag_sqlstate[2],
673  diag_sqlstate[3],
674  diag_sqlstate[4]);
675  else
676  sqlstate = ERRCODE_CONNECTION_FAILURE;
677 
678  /*
679  * If we don't get a message from the PGresult, try the PGconn. This
680  * is needed because for connection-level failures, PQexec may just
681  * return NULL, not a PGresult at all.
682  */
683  if (message_primary == NULL)
684  message_primary = pchomp(PQerrorMessage(conn));
685 
686  ereport(elevel,
687  (errcode(sqlstate),
688  message_primary ? errmsg_internal("%s", message_primary) :
689  errmsg("could not obtain message string for remote error"),
690  message_detail ? errdetail_internal("%s", message_detail) : 0,
691  message_hint ? errhint("%s", message_hint) : 0,
692  message_context ? errcontext("%s", message_context) : 0,
693  sql ? errcontext("remote SQL command: %s", sql) : 0));
694  }
695  PG_FINALLY();
696  {
697  if (clear)
698  PQclear(res);
699  }
700  PG_END_TRY();
701 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6687
int errhint(const char *fmt,...)
Definition: elog.c:1071
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:58
#define PG_DIAG_MESSAGE_DETAIL
Definition: postgres_ext.h:59
#define MAKE_SQLSTATE(ch1, ch2, ch3, ch4, ch5)
Definition: elog.h:62
int errcode(int sqlerrcode)
Definition: elog.c:610
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:57
int errdetail_internal(const char *fmt,...)
Definition: elog.c:984
char * pchomp(const char *in)
Definition: mcxt.c:1214
static int elevel
Definition: vacuumlazy.c:323
#define PG_FINALLY()
Definition: elog.h:312
#define PG_DIAG_MESSAGE_HINT
Definition: postgres_ext.h:60
#define ereport(elevel,...)
Definition: elog.h:144
void PQclear(PGresult *res)
Definition: fe-exec.c:694
int errmsg_internal(const char *fmt,...)
Definition: elog.c:911
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:2754
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define errcontext
Definition: elog.h:185
#define PG_TRY()
Definition: elog.h:295
#define PG_END_TRY()
Definition: elog.h:320
#define PG_DIAG_CONTEXT
Definition: postgres_ext.h:64

◆ pgfdw_subxact_callback()

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

Definition at line 894 of file connection.c.

References ConnCacheEntry::changing_xact_state, ConnCacheEntry::conn, do_sql_command(), elog, ERROR, GetCurrentTransactionNestLevel(), hash_seq_init(), hash_seq_search(), ConnCacheEntry::have_error, in_error_recursion_trouble(), pgfdw_cancel_query(), pgfdw_exec_cleanup_query(), pgfdw_reject_incomplete_xact_state_change(), PQTRANS_ACTIVE, PQtransactionStatus(), snprintf, SUBXACT_EVENT_ABORT_SUB, SUBXACT_EVENT_PRE_COMMIT_SUB, ConnCacheEntry::xact_depth, and xact_got_connection.

Referenced by GetConnection().

896 {
897  HASH_SEQ_STATUS scan;
898  ConnCacheEntry *entry;
899  int curlevel;
900 
901  /* Nothing to do at subxact start, nor after commit. */
902  if (!(event == SUBXACT_EVENT_PRE_COMMIT_SUB ||
903  event == SUBXACT_EVENT_ABORT_SUB))
904  return;
905 
906  /* Quick exit if no connections were touched in this transaction. */
907  if (!xact_got_connection)
908  return;
909 
910  /*
911  * Scan all connection cache entries to find open remote subtransactions
912  * of the current level, and close them.
913  */
914  curlevel = GetCurrentTransactionNestLevel();
916  while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
917  {
918  char sql[100];
919 
920  /*
921  * We only care about connections with open remote subtransactions of
922  * the current level.
923  */
924  if (entry->conn == NULL || entry->xact_depth < curlevel)
925  continue;
926 
927  if (entry->xact_depth > curlevel)
928  elog(ERROR, "missed cleaning up remote subtransaction at level %d",
929  entry->xact_depth);
930 
931  if (event == SUBXACT_EVENT_PRE_COMMIT_SUB)
932  {
933  /*
934  * If abort cleanup previously failed for this connection, we
935  * can't issue any more commands against it.
936  */
938 
939  /* Commit all remote subtransactions during pre-commit */
940  snprintf(sql, sizeof(sql), "RELEASE SAVEPOINT s%d", curlevel);
941  entry->changing_xact_state = true;
942  do_sql_command(entry->conn, sql);
943  entry->changing_xact_state = false;
944  }
945  else if (in_error_recursion_trouble())
946  {
947  /*
948  * Don't try to clean up the connection if we're already in error
949  * recursion trouble.
950  */
951  entry->changing_xact_state = true;
952  }
953  else if (!entry->changing_xact_state)
954  {
955  bool abort_cleanup_failure = false;
956 
957  /* Remember that abort cleanup is in progress. */
958  entry->changing_xact_state = true;
959 
960  /* Assume we might have lost track of prepared statements */
961  entry->have_error = true;
962 
963  /*
964  * If a command has been submitted to the remote server by using
965  * an asynchronous execution function, the command might not have
966  * yet completed. Check to see if a command is still being
967  * processed by the remote server, and if so, request cancellation
968  * of the command.
969  */
970  if (PQtransactionStatus(entry->conn) == PQTRANS_ACTIVE &&
971  !pgfdw_cancel_query(entry->conn))
972  abort_cleanup_failure = true;
973  else
974  {
975  /* Rollback all remote subtransactions during abort */
976  snprintf(sql, sizeof(sql),
977  "ROLLBACK TO SAVEPOINT s%d; RELEASE SAVEPOINT s%d",
978  curlevel, curlevel);
979  if (!pgfdw_exec_cleanup_query(entry->conn, sql, false))
980  abort_cleanup_failure = true;
981  }
982 
983  /* Disarm changing_xact_state if it all worked. */
984  entry->changing_xact_state = abort_cleanup_failure;
985  }
986 
987  /* OK, we're outta that level of subtransaction */
988  entry->xact_depth--;
989  }
990 }
#define ERROR
Definition: elog.h:43
bool changing_xact_state
Definition: connection.c:57
static void do_sql_command(PGconn *conn, const char *sql)
Definition: connection.c:453
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:6642
static bool pgfdw_exec_cleanup_query(PGconn *conn, const char *query, bool ignore_errors)
Definition: connection.c:1125
static HTAB * ConnectionHash
Definition: connection.c:66
static bool pgfdw_cancel_query(PGconn *conn)
Definition: connection.c:1078
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:842
bool in_error_recursion_trouble(void)
Definition: elog.c:198
PGconn * conn
Definition: connection.c:51
static void pgfdw_reject_incomplete_xact_state_change(ConnCacheEntry *entry)
Definition: connection.c:1044
static bool xact_got_connection
Definition: connection.c:73
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1391
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1381
#define elog(elevel,...)
Definition: elog.h:214
#define snprintf
Definition: port.h:193

◆ pgfdw_xact_callback()

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

Definition at line 707 of file connection.c.

References ConnCacheEntry::changing_xact_state, ConnCacheEntry::conn, CONNECTION_OK, cursor_number, DEBUG3, disconnect_pg_server(), do_sql_command(), elog, ereport, errcode(), errmsg(), ERROR, hash_seq_init(), hash_seq_search(), ConnCacheEntry::have_error, ConnCacheEntry::have_prep_stmt, in_error_recursion_trouble(), pgfdw_cancel_query(), pgfdw_exec_cleanup_query(), pgfdw_reject_incomplete_xact_state_change(), PQclear(), PQexec(), PQstatus(), PQTRANS_ACTIVE, PQTRANS_IDLE, PQtransactionStatus(), 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().

708 {
709  HASH_SEQ_STATUS scan;
710  ConnCacheEntry *entry;
711 
712  /* Quick exit if no connections were touched in this transaction. */
713  if (!xact_got_connection)
714  return;
715 
716  /*
717  * Scan all connection cache entries to find open remote transactions, and
718  * close them.
719  */
721  while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
722  {
723  PGresult *res;
724 
725  /* Ignore cache entry if no open connection right now */
726  if (entry->conn == NULL)
727  continue;
728 
729  /* If it has an open remote transaction, try to close it */
730  if (entry->xact_depth > 0)
731  {
732  bool abort_cleanup_failure = false;
733 
734  elog(DEBUG3, "closing remote transaction on connection %p",
735  entry->conn);
736 
737  switch (event)
738  {
741 
742  /*
743  * If abort cleanup previously failed for this connection,
744  * we can't issue any more commands against it.
745  */
747 
748  /* Commit all remote transactions during pre-commit */
749  entry->changing_xact_state = true;
750  do_sql_command(entry->conn, "COMMIT TRANSACTION");
751  entry->changing_xact_state = false;
752 
753  /*
754  * If there were any errors in subtransactions, and we
755  * made prepared statements, do a DEALLOCATE ALL to make
756  * sure we get rid of all prepared statements. This is
757  * annoying and not terribly bulletproof, but it's
758  * probably not worth trying harder.
759  *
760  * DEALLOCATE ALL only exists in 8.3 and later, so this
761  * constrains how old a server postgres_fdw can
762  * communicate with. We intentionally ignore errors in
763  * the DEALLOCATE, so that we can hobble along to some
764  * extent with older servers (leaking prepared statements
765  * as we go; but we don't really support update operations
766  * pre-8.3 anyway).
767  */
768  if (entry->have_prep_stmt && entry->have_error)
769  {
770  res = PQexec(entry->conn, "DEALLOCATE ALL");
771  PQclear(res);
772  }
773  entry->have_prep_stmt = false;
774  entry->have_error = false;
775  break;
777 
778  /*
779  * We disallow any remote transactions, since it's not
780  * very reasonable to hold them open until the prepared
781  * transaction is committed. For the moment, throw error
782  * unconditionally; later we might allow read-only cases.
783  * Note that the error will cause us to come right back
784  * here with event == XACT_EVENT_ABORT, so we'll clean up
785  * the connection state at that point.
786  */
787  ereport(ERROR,
788  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
789  errmsg("cannot PREPARE a transaction that has operated on postgres_fdw foreign tables")));
790  break;
792  case XACT_EVENT_COMMIT:
793  case XACT_EVENT_PREPARE:
794  /* Pre-commit should have closed the open transaction */
795  elog(ERROR, "missed cleaning up connection during pre-commit");
796  break;
798  case XACT_EVENT_ABORT:
799 
800  /*
801  * Don't try to clean up the connection if we're already
802  * in error recursion trouble.
803  */
805  entry->changing_xact_state = true;
806 
807  /*
808  * If connection is already unsalvageable, don't touch it
809  * further.
810  */
811  if (entry->changing_xact_state)
812  break;
813 
814  /*
815  * Mark this connection as in the process of changing
816  * transaction state.
817  */
818  entry->changing_xact_state = true;
819 
820  /* Assume we might have lost track of prepared statements */
821  entry->have_error = true;
822 
823  /*
824  * If a command has been submitted to the remote server by
825  * using an asynchronous execution function, the command
826  * might not have yet completed. Check to see if a
827  * command is still being processed by the remote server,
828  * and if so, request cancellation of the command.
829  */
830  if (PQtransactionStatus(entry->conn) == PQTRANS_ACTIVE &&
831  !pgfdw_cancel_query(entry->conn))
832  {
833  /* Unable to cancel running query. */
834  abort_cleanup_failure = true;
835  }
836  else if (!pgfdw_exec_cleanup_query(entry->conn,
837  "ABORT TRANSACTION",
838  false))
839  {
840  /* Unable to abort remote transaction. */
841  abort_cleanup_failure = true;
842  }
843  else if (entry->have_prep_stmt && entry->have_error &&
845  "DEALLOCATE ALL",
846  true))
847  {
848  /* Trouble clearing prepared statements. */
849  abort_cleanup_failure = true;
850  }
851  else
852  {
853  entry->have_prep_stmt = false;
854  entry->have_error = false;
855  }
856 
857  /* Disarm changing_xact_state if it all worked. */
858  entry->changing_xact_state = abort_cleanup_failure;
859  break;
860  }
861  }
862 
863  /* Reset state to show we're out of a transaction */
864  entry->xact_depth = 0;
865 
866  /*
867  * If the connection isn't in a good idle state, discard it to
868  * recover. Next GetConnection will open a new connection.
869  */
870  if (PQstatus(entry->conn) != CONNECTION_OK ||
872  entry->changing_xact_state)
873  {
874  elog(DEBUG3, "discarding connection %p", entry->conn);
875  disconnect_pg_server(entry);
876  }
877  }
878 
879  /*
880  * Regardless of the event type, we can now mark ourselves as out of the
881  * transaction. (Note: if we are here during PRE_COMMIT or PRE_PREPARE,
882  * this saves a useless scan of the hashtable during COMMIT or PREPARE.)
883  */
884  xact_got_connection = false;
885 
886  /* Also reset cursor numbering for next transaction */
887  cursor_number = 0;
888 }
#define DEBUG3
Definition: elog.h:23
int errcode(int sqlerrcode)
Definition: elog.c:610
bool have_prep_stmt
Definition: connection.c:55
#define ERROR
Definition: elog.h:43
bool changing_xact_state
Definition: connection.c:57
static void do_sql_command(PGconn *conn, const char *sql)
Definition: connection.c:453
static unsigned int cursor_number
Definition: connection.c:69
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:6642
static bool pgfdw_exec_cleanup_query(PGconn *conn, const char *query, bool ignore_errors)
Definition: connection.c:1125
static HTAB * ConnectionHash
Definition: connection.c:66
static bool pgfdw_cancel_query(PGconn *conn)
Definition: connection.c:1078
#define ereport(elevel,...)
Definition: elog.h:144
void PQclear(PGresult *res)
Definition: fe-exec.c:694
bool in_error_recursion_trouble(void)
Definition: elog.c:198
PGconn * conn
Definition: connection.c:51
static void disconnect_pg_server(ConnCacheEntry *entry)
Definition: connection.c:342
static void pgfdw_reject_incomplete_xact_state_change(ConnCacheEntry *entry)
Definition: connection.c:1044
static bool xact_got_connection
Definition: connection.c:73
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1391
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1381
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1939
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6634

◆ ReleaseConnection()

void ReleaseConnection ( PGconn conn)

Definition at line 519 of file connection.c.

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

520 {
521  /*
522  * Currently, we don't actually track connection references because all
523  * cleanup is managed on a transaction or subtransaction basis instead. So
524  * there's nothing to do here.
525  */
526 }

◆ UserMappingPasswordRequired()

static bool UserMappingPasswordRequired ( UserMapping user)
static

Definition at line 357 of file connection.c.

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

Referenced by check_conn_params(), and connect_pg_server().

358 {
359  ListCell *cell;
360 
361  foreach(cell, user->options)
362  {
363  DefElem *def = (DefElem *) lfirst(cell);
364 
365  if (strcmp(def->defname, "password_required") == 0)
366  return defGetBoolean(def);
367  }
368 
369  return true;
370 }
bool defGetBoolean(DefElem *def)
Definition: define.c:111
List * options
Definition: foreign.h:50
#define lfirst(lc)
Definition: pg_list.h:190
char * defname
Definition: parsenodes.h:732

Variable Documentation

◆ ConnectionHash

HTAB* ConnectionHash = NULL
static

Definition at line 66 of file connection.c.

◆ cursor_number

unsigned int cursor_number = 0
static

Definition at line 69 of file connection.c.

Referenced by GetCursorNumber(), and pgfdw_xact_callback().

◆ prep_stmt_number

unsigned int prep_stmt_number = 0
static

Definition at line 70 of file connection.c.

Referenced by GetPrepStmtNumber().

◆ xact_got_connection

bool xact_got_connection = false
static

Definition at line 73 of file connection.c.

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