PostgreSQL Source Code  git master
connection.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * connection.c
4  * Connection management functions for postgres_fdw
5  *
6  * Portions Copyright (c) 2012-2020, PostgreSQL Global Development Group
7  *
8  * IDENTIFICATION
9  * contrib/postgres_fdw/connection.c
10  *
11  *-------------------------------------------------------------------------
12  */
13 #include "postgres.h"
14 
15 #include "access/htup_details.h"
16 #include "access/xact.h"
18 #include "commands/defrem.h"
19 #include "mb/pg_wchar.h"
20 #include "miscadmin.h"
21 #include "pgstat.h"
22 #include "postgres_fdw.h"
23 #include "storage/fd.h"
24 #include "storage/latch.h"
25 #include "utils/datetime.h"
26 #include "utils/hsearch.h"
27 #include "utils/inval.h"
28 #include "utils/memutils.h"
29 #include "utils/syscache.h"
30 
31 /*
32  * Connection cache hash table entry
33  *
34  * The lookup key in this hash table is the user mapping OID. We use just one
35  * connection per user mapping ID, which ensures that all the scans use the
36  * same snapshot during a query. Using the user mapping OID rather than
37  * the foreign server OID + user OID avoids creating multiple connections when
38  * the public user mapping applies to all user OIDs.
39  *
40  * The "conn" pointer can be NULL if we don't currently have a live connection.
41  * When we do have a connection, xact_depth tracks the current depth of
42  * transactions and subtransactions open on the remote side. We need to issue
43  * commands at the same nesting depth on the remote as we're executing at
44  * ourselves, so that rolling back a subtransaction will kill the right
45  * queries and not the wrong ones.
46  */
47 typedef Oid ConnCacheKey;
48 
49 typedef struct ConnCacheEntry
50 {
51  ConnCacheKey key; /* hash key (must be first) */
52  PGconn *conn; /* connection to foreign server, or NULL */
53  /* Remaining fields are invalid when conn is NULL: */
54  int xact_depth; /* 0 = no xact open, 1 = main xact open, 2 =
55  * one level of subxact open, etc */
56  bool have_prep_stmt; /* have we prepared any stmts in this xact? */
57  bool have_error; /* have any subxacts aborted in this xact? */
58  bool changing_xact_state; /* xact state change in process */
59  bool invalidated; /* true if reconnect is pending */
60  uint32 server_hashvalue; /* hash value of foreign server OID */
61  uint32 mapping_hashvalue; /* hash value of user mapping OID */
63 
64 /*
65  * Connection cache (initialized on first use)
66  */
67 static HTAB *ConnectionHash = NULL;
68 
69 /* for assigning cursor numbers and prepared statement numbers */
70 static unsigned int cursor_number = 0;
71 static unsigned int prep_stmt_number = 0;
72 
73 /* tracks whether any work is needed in callback functions */
74 static bool xact_got_connection = false;
75 
76 /* prototypes of private functions */
79 static void disconnect_pg_server(ConnCacheEntry *entry);
80 static void check_conn_params(const char **keywords, const char **values, UserMapping *user);
82 static void do_sql_command(PGconn *conn, const char *sql);
83 static void begin_remote_xact(ConnCacheEntry *entry);
84 static void pgfdw_xact_callback(XactEvent event, void *arg);
85 static void pgfdw_subxact_callback(SubXactEvent event,
86  SubTransactionId mySubid,
87  SubTransactionId parentSubid,
88  void *arg);
89 static void pgfdw_inval_callback(Datum arg, int cacheid, uint32 hashvalue);
91 static bool pgfdw_cancel_query(PGconn *conn);
92 static bool pgfdw_exec_cleanup_query(PGconn *conn, const char *query,
93  bool ignore_errors);
94 static bool pgfdw_get_cleanup_result(PGconn *conn, TimestampTz endtime,
95  PGresult **result);
97 
98 /*
99  * Get a PGconn which can be used to execute queries on the remote PostgreSQL
100  * server with the user's authorization. A new connection is established
101  * if we don't already have a suitable one, and a transaction is opened at
102  * the right subtransaction nesting depth if we didn't do that already.
103  *
104  * will_prep_stmt must be true if caller intends to create any prepared
105  * statements. Since those don't go away automatically at transaction end
106  * (not even on error), we need this flag to cue manual cleanup.
107  */
108 PGconn *
109 GetConnection(UserMapping *user, bool will_prep_stmt)
110 {
111  bool found;
112  bool retry = false;
113  ConnCacheEntry *entry;
116 
117  /* First time through, initialize connection cache hashtable */
118  if (ConnectionHash == NULL)
119  {
120  HASHCTL ctl;
121 
122  MemSet(&ctl, 0, sizeof(ctl));
123  ctl.keysize = sizeof(ConnCacheKey);
124  ctl.entrysize = sizeof(ConnCacheEntry);
125  /* allocate ConnectionHash in the cache context */
126  ctl.hcxt = CacheMemoryContext;
127  ConnectionHash = hash_create("postgres_fdw connections", 8,
128  &ctl,
130 
131  /*
132  * Register some callback functions that manage connection cleanup.
133  * This should be done just once in each backend.
134  */
141  }
142 
143  /* Set flag that we did GetConnection during the current transaction */
144  xact_got_connection = true;
145 
146  /* Create hash key for the entry. Assume no pad bytes in key struct */
147  key = user->umid;
148 
149  /*
150  * Find or create cached entry for requested connection.
151  */
152  entry = hash_search(ConnectionHash, &key, HASH_ENTER, &found);
153  if (!found)
154  {
155  /*
156  * We need only clear "conn" here; remaining fields will be filled
157  * later when "conn" is set.
158  */
159  entry->conn = NULL;
160  }
161 
162  /* Reject further use of connections which failed abort cleanup. */
164 
165  /*
166  * If the connection needs to be remade due to invalidation, disconnect as
167  * soon as we're out of all transactions.
168  */
169  if (entry->conn != NULL && entry->invalidated && entry->xact_depth == 0)
170  {
171  elog(DEBUG3, "closing connection %p for option changes to take effect",
172  entry->conn);
173  disconnect_pg_server(entry);
174  }
175 
176  /*
177  * If cache entry doesn't have a connection, we have to establish a new
178  * connection. (If connect_pg_server throws an error, the cache entry
179  * will remain in a valid empty state, ie conn == NULL.)
180  */
181  if (entry->conn == NULL)
182  make_new_connection(entry, user);
183 
184  /*
185  * We check the health of the cached connection here when starting a new
186  * remote transaction. If a broken connection is detected, we try to
187  * reestablish a new connection later.
188  */
189  PG_TRY();
190  {
191  /* Start a new transaction or subtransaction if needed. */
192  begin_remote_xact(entry);
193  }
194  PG_CATCH();
195  {
197  ErrorData *errdata = CopyErrorData();
198 
199  /*
200  * If connection failure is reported when starting a new remote
201  * transaction (not subtransaction), new connection will be
202  * reestablished later.
203  *
204  * After a broken connection is detected in libpq, any error other
205  * than connection failure (e.g., out-of-memory) can be thrown
206  * somewhere between return from libpq and the expected ereport() call
207  * in pgfdw_report_error(). In this case, since PQstatus() indicates
208  * CONNECTION_BAD, checking only PQstatus() causes the false detection
209  * of connection failure. To avoid this, we also verify that the
210  * error's sqlstate is ERRCODE_CONNECTION_FAILURE. Note that also
211  * checking only the sqlstate can cause another false detection
212  * because pgfdw_report_error() may report ERRCODE_CONNECTION_FAILURE
213  * for any libpq-originated error condition.
214  */
215  if (errdata->sqlerrcode != ERRCODE_CONNECTION_FAILURE ||
216  PQstatus(entry->conn) != CONNECTION_BAD ||
217  entry->xact_depth > 0)
218  {
219  MemoryContextSwitchTo(ecxt);
220  PG_RE_THROW();
221  }
222 
223  /* Clean up the error state */
224  FlushErrorState();
225  FreeErrorData(errdata);
226  errdata = NULL;
227 
228  retry = true;
229  }
230  PG_END_TRY();
231 
232  /*
233  * If a broken connection is detected, disconnect it, reestablish a new
234  * connection and retry a new remote transaction. If connection failure is
235  * reported again, we give up getting a connection.
236  */
237  if (retry)
238  {
239  Assert(entry->xact_depth == 0);
240 
241  ereport(DEBUG3,
242  (errmsg_internal("could not start remote transaction on connection %p",
243  entry->conn)),
244  errdetail_internal("%s", pchomp(PQerrorMessage(entry->conn))));
245 
246  elog(DEBUG3, "closing connection %p to reestablish a new one",
247  entry->conn);
248  disconnect_pg_server(entry);
249 
250  if (entry->conn == NULL)
251  make_new_connection(entry, user);
252 
253  begin_remote_xact(entry);
254  }
255 
256  /* Remember if caller will prepare statements */
257  entry->have_prep_stmt |= will_prep_stmt;
258 
259  return entry->conn;
260 }
261 
262 /*
263  * Reset all transient state fields in the cached connection entry and
264  * establish new connection to the remote server.
265  */
266 static void
268 {
269  ForeignServer *server = GetForeignServer(user->serverid);
270 
271  Assert(entry->conn == NULL);
272 
273  /* Reset all transient state fields, to be sure all are clean */
274  entry->xact_depth = 0;
275  entry->have_prep_stmt = false;
276  entry->have_error = false;
277  entry->changing_xact_state = false;
278  entry->invalidated = false;
279  entry->server_hashvalue =
281  ObjectIdGetDatum(server->serverid));
282  entry->mapping_hashvalue =
284  ObjectIdGetDatum(user->umid));
285 
286  /* Now try to make the connection */
287  entry->conn = connect_pg_server(server, user);
288 
289  elog(DEBUG3, "new postgres_fdw connection %p for server \"%s\" (user mapping oid %u, userid %u)",
290  entry->conn, server->servername, user->umid, user->userid);
291 }
292 
293 /*
294  * Connect to remote server using specified server and user mapping properties.
295  */
296 static PGconn *
298 {
299  PGconn *volatile conn = NULL;
300 
301  /*
302  * Use PG_TRY block to ensure closing connection on error.
303  */
304  PG_TRY();
305  {
306  const char **keywords;
307  const char **values;
308  int n;
309 
310  /*
311  * Construct connection params from generic options of ForeignServer
312  * and UserMapping. (Some of them might not be libpq options, in
313  * which case we'll just waste a few array slots.) Add 3 extra slots
314  * for fallback_application_name, client_encoding, end marker.
315  */
316  n = list_length(server->options) + list_length(user->options) + 3;
317  keywords = (const char **) palloc(n * sizeof(char *));
318  values = (const char **) palloc(n * sizeof(char *));
319 
320  n = 0;
321  n += ExtractConnectionOptions(server->options,
322  keywords + n, values + n);
324  keywords + n, values + n);
325 
326  /* Use "postgres_fdw" as fallback_application_name. */
327  keywords[n] = "fallback_application_name";
328  values[n] = "postgres_fdw";
329  n++;
330 
331  /* Set client_encoding so that libpq can convert encoding properly. */
332  keywords[n] = "client_encoding";
333  values[n] = GetDatabaseEncodingName();
334  n++;
335 
336  keywords[n] = values[n] = NULL;
337 
338  /* verify the set of connection parameters */
339  check_conn_params(keywords, values, user);
340 
341  /*
342  * We must obey fd.c's limit on non-virtual file descriptors. Assume
343  * that a PGconn represents one long-lived FD. (Doing this here also
344  * ensures that VFDs are closed if needed to make room.)
345  */
346  if (!AcquireExternalFD())
347  {
348 #ifndef WIN32 /* can't write #if within ereport() macro */
349  ereport(ERROR,
350  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
351  errmsg("could not connect to server \"%s\"",
352  server->servername),
353  errdetail("There are too many open files on the local server."),
354  errhint("Raise the server's max_files_per_process and/or \"ulimit -n\" limits.")));
355 #else
356  ereport(ERROR,
357  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
358  errmsg("could not connect to server \"%s\"",
359  server->servername),
360  errdetail("There are too many open files on the local server."),
361  errhint("Raise the server's max_files_per_process setting.")));
362 #endif
363  }
364 
365  /* OK to make connection */
366  conn = PQconnectdbParams(keywords, values, false);
367 
368  if (!conn)
369  ReleaseExternalFD(); /* because the PG_CATCH block won't */
370 
371  if (!conn || PQstatus(conn) != CONNECTION_OK)
372  ereport(ERROR,
373  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
374  errmsg("could not connect to server \"%s\"",
375  server->servername),
376  errdetail_internal("%s", pchomp(PQerrorMessage(conn)))));
377 
378  /*
379  * Check that non-superuser has used password to establish connection;
380  * otherwise, he's piggybacking on the postgres server's user
381  * identity. See also dblink_security_check() in contrib/dblink and
382  * check_conn_params.
383  */
384  if (!superuser_arg(user->userid) && UserMappingPasswordRequired(user) &&
386  ereport(ERROR,
387  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
388  errmsg("password is required"),
389  errdetail("Non-superuser cannot connect if the server does not request a password."),
390  errhint("Target server's authentication method must be changed or password_required=false set in the user mapping attributes.")));
391 
392  /* Prepare new session for use */
394 
395  pfree(keywords);
396  pfree(values);
397  }
398  PG_CATCH();
399  {
400  /* Release PGconn data structure if we managed to create one */
401  if (conn)
402  {
403  PQfinish(conn);
405  }
406  PG_RE_THROW();
407  }
408  PG_END_TRY();
409 
410  return conn;
411 }
412 
413 /*
414  * Disconnect any open connection for a connection cache entry.
415  */
416 static void
418 {
419  if (entry->conn != NULL)
420  {
421  PQfinish(entry->conn);
422  entry->conn = NULL;
424  }
425 }
426 
427 /*
428  * Return true if the password_required is defined and false for this user
429  * mapping, otherwise false. The mapping has been pre-validated.
430  */
431 static bool
433 {
434  ListCell *cell;
435 
436  foreach(cell, user->options)
437  {
438  DefElem *def = (DefElem *) lfirst(cell);
439 
440  if (strcmp(def->defname, "password_required") == 0)
441  return defGetBoolean(def);
442  }
443 
444  return true;
445 }
446 
447 /*
448  * For non-superusers, insist that the connstr specify a password. This
449  * prevents a password from being picked up from .pgpass, a service file, the
450  * environment, etc. We don't want the postgres user's passwords,
451  * certificates, etc to be accessible to non-superusers. (See also
452  * dblink_connstr_check in contrib/dblink.)
453  */
454 static void
455 check_conn_params(const char **keywords, const char **values, UserMapping *user)
456 {
457  int i;
458 
459  /* no check required if superuser */
460  if (superuser_arg(user->userid))
461  return;
462 
463  /* ok if params contain a non-empty password */
464  for (i = 0; keywords[i] != NULL; i++)
465  {
466  if (strcmp(keywords[i], "password") == 0 && values[i][0] != '\0')
467  return;
468  }
469 
470  /* ok if the superuser explicitly said so at user mapping creation time */
471  if (!UserMappingPasswordRequired(user))
472  return;
473 
474  ereport(ERROR,
475  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
476  errmsg("password is required"),
477  errdetail("Non-superusers must provide a password in the user mapping.")));
478 }
479 
480 /*
481  * Issue SET commands to make sure remote session is configured properly.
482  *
483  * We do this just once at connection, assuming nothing will change the
484  * values later. Since we'll never send volatile function calls to the
485  * remote, there shouldn't be any way to break this assumption from our end.
486  * It's possible to think of ways to break it at the remote end, eg making
487  * a foreign table point to a view that includes a set_config call ---
488  * but once you admit the possibility of a malicious view definition,
489  * there are any number of ways to break things.
490  */
491 static void
493 {
494  int remoteversion = PQserverVersion(conn);
495 
496  /* Force the search path to contain only pg_catalog (see deparse.c) */
497  do_sql_command(conn, "SET search_path = pg_catalog");
498 
499  /*
500  * Set remote timezone; this is basically just cosmetic, since all
501  * transmitted and returned timestamptzs should specify a zone explicitly
502  * anyway. However it makes the regression test outputs more predictable.
503  *
504  * We don't risk setting remote zone equal to ours, since the remote
505  * server might use a different timezone database. Instead, use UTC
506  * (quoted, because very old servers are picky about case).
507  */
508  do_sql_command(conn, "SET timezone = 'UTC'");
509 
510  /*
511  * Set values needed to ensure unambiguous data output from remote. (This
512  * logic should match what pg_dump does. See also set_transmission_modes
513  * in postgres_fdw.c.)
514  */
515  do_sql_command(conn, "SET datestyle = ISO");
516  if (remoteversion >= 80400)
517  do_sql_command(conn, "SET intervalstyle = postgres");
518  if (remoteversion >= 90000)
519  do_sql_command(conn, "SET extra_float_digits = 3");
520  else
521  do_sql_command(conn, "SET extra_float_digits = 2");
522 }
523 
524 /*
525  * Convenience subroutine to issue a non-data-returning SQL command to remote
526  */
527 static void
528 do_sql_command(PGconn *conn, const char *sql)
529 {
530  PGresult *res;
531 
532  if (!PQsendQuery(conn, sql))
533  pgfdw_report_error(ERROR, NULL, conn, false, sql);
534  res = pgfdw_get_result(conn, sql);
535  if (PQresultStatus(res) != PGRES_COMMAND_OK)
536  pgfdw_report_error(ERROR, res, conn, true, sql);
537  PQclear(res);
538 }
539 
540 /*
541  * Start remote transaction or subtransaction, if needed.
542  *
543  * Note that we always use at least REPEATABLE READ in the remote session.
544  * This is so that, if a query initiates multiple scans of the same or
545  * different foreign tables, we will get snapshot-consistent results from
546  * those scans. A disadvantage is that we can't provide sane emulation of
547  * READ COMMITTED behavior --- it would be nice if we had some other way to
548  * control which remote queries share a snapshot.
549  */
550 static void
552 {
553  int curlevel = GetCurrentTransactionNestLevel();
554 
555  /* Start main transaction if we haven't yet */
556  if (entry->xact_depth <= 0)
557  {
558  const char *sql;
559 
560  elog(DEBUG3, "starting remote transaction on connection %p",
561  entry->conn);
562 
564  sql = "START TRANSACTION ISOLATION LEVEL SERIALIZABLE";
565  else
566  sql = "START TRANSACTION ISOLATION LEVEL REPEATABLE READ";
567  entry->changing_xact_state = true;
568  do_sql_command(entry->conn, sql);
569  entry->xact_depth = 1;
570  entry->changing_xact_state = false;
571  }
572 
573  /*
574  * If we're in a subtransaction, stack up savepoints to match our level.
575  * This ensures we can rollback just the desired effects when a
576  * subtransaction aborts.
577  */
578  while (entry->xact_depth < curlevel)
579  {
580  char sql[64];
581 
582  snprintf(sql, sizeof(sql), "SAVEPOINT s%d", entry->xact_depth + 1);
583  entry->changing_xact_state = true;
584  do_sql_command(entry->conn, sql);
585  entry->xact_depth++;
586  entry->changing_xact_state = false;
587  }
588 }
589 
590 /*
591  * Release connection reference count created by calling GetConnection.
592  */
593 void
595 {
596  /*
597  * Currently, we don't actually track connection references because all
598  * cleanup is managed on a transaction or subtransaction basis instead. So
599  * there's nothing to do here.
600  */
601 }
602 
603 /*
604  * Assign a "unique" number for a cursor.
605  *
606  * These really only need to be unique per connection within a transaction.
607  * For the moment we ignore the per-connection point and assign them across
608  * all connections in the transaction, but we ask for the connection to be
609  * supplied in case we want to refine that.
610  *
611  * Note that even if wraparound happens in a very long transaction, actual
612  * collisions are highly improbable; just be sure to use %u not %d to print.
613  */
614 unsigned int
616 {
617  return ++cursor_number;
618 }
619 
620 /*
621  * Assign a "unique" number for a prepared statement.
622  *
623  * This works much like GetCursorNumber, except that we never reset the counter
624  * within a session. That's because we can't be 100% sure we've gotten rid
625  * of all prepared statements on all connections, and it's not really worth
626  * increasing the risk of prepared-statement name collisions by resetting.
627  */
628 unsigned int
630 {
631  return ++prep_stmt_number;
632 }
633 
634 /*
635  * Submit a query and wait for the result.
636  *
637  * This function is interruptible by signals.
638  *
639  * Caller is responsible for the error handling on the result.
640  */
641 PGresult *
642 pgfdw_exec_query(PGconn *conn, const char *query)
643 {
644  /*
645  * Submit a query. Since we don't use non-blocking mode, this also can
646  * block. But its risk is relatively small, so we ignore that for now.
647  */
648  if (!PQsendQuery(conn, query))
649  pgfdw_report_error(ERROR, NULL, conn, false, query);
650 
651  /* Wait for the result. */
652  return pgfdw_get_result(conn, query);
653 }
654 
655 /*
656  * Wait for the result from a prior asynchronous execution function call.
657  *
658  * This function offers quick responsiveness by checking for any interruptions.
659  *
660  * This function emulates PQexec()'s behavior of returning the last result
661  * when there are many.
662  *
663  * Caller is responsible for the error handling on the result.
664  */
665 PGresult *
666 pgfdw_get_result(PGconn *conn, const char *query)
667 {
668  PGresult *volatile last_res = NULL;
669 
670  /* In what follows, do not leak any PGresults on an error. */
671  PG_TRY();
672  {
673  for (;;)
674  {
675  PGresult *res;
676 
677  while (PQisBusy(conn))
678  {
679  int wc;
680 
681  /* Sleep until there's something to do */
685  PQsocket(conn),
686  -1L, PG_WAIT_EXTENSION);
688 
690 
691  /* Data available in socket? */
692  if (wc & WL_SOCKET_READABLE)
693  {
694  if (!PQconsumeInput(conn))
695  pgfdw_report_error(ERROR, NULL, conn, false, query);
696  }
697  }
698 
699  res = PQgetResult(conn);
700  if (res == NULL)
701  break; /* query is complete */
702 
703  PQclear(last_res);
704  last_res = res;
705  }
706  }
707  PG_CATCH();
708  {
709  PQclear(last_res);
710  PG_RE_THROW();
711  }
712  PG_END_TRY();
713 
714  return last_res;
715 }
716 
717 /*
718  * Report an error we got from the remote server.
719  *
720  * elevel: error level to use (typically ERROR, but might be less)
721  * res: PGresult containing the error
722  * conn: connection we did the query on
723  * clear: if true, PQclear the result (otherwise caller will handle it)
724  * sql: NULL, or text of remote command we tried to execute
725  *
726  * Note: callers that choose not to throw ERROR for a remote error are
727  * responsible for making sure that the associated ConnCacheEntry gets
728  * marked with have_error = true.
729  */
730 void
732  bool clear, const char *sql)
733 {
734  /* If requested, PGresult must be released before leaving this function. */
735  PG_TRY();
736  {
737  char *diag_sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
738  char *message_primary = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
739  char *message_detail = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
740  char *message_hint = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
741  char *message_context = PQresultErrorField(res, PG_DIAG_CONTEXT);
742  int sqlstate;
743 
744  if (diag_sqlstate)
745  sqlstate = MAKE_SQLSTATE(diag_sqlstate[0],
746  diag_sqlstate[1],
747  diag_sqlstate[2],
748  diag_sqlstate[3],
749  diag_sqlstate[4]);
750  else
751  sqlstate = ERRCODE_CONNECTION_FAILURE;
752 
753  /*
754  * If we don't get a message from the PGresult, try the PGconn. This
755  * is needed because for connection-level failures, PQexec may just
756  * return NULL, not a PGresult at all.
757  */
758  if (message_primary == NULL)
759  message_primary = pchomp(PQerrorMessage(conn));
760 
761  ereport(elevel,
762  (errcode(sqlstate),
763  message_primary ? errmsg_internal("%s", message_primary) :
764  errmsg("could not obtain message string for remote error"),
765  message_detail ? errdetail_internal("%s", message_detail) : 0,
766  message_hint ? errhint("%s", message_hint) : 0,
767  message_context ? errcontext("%s", message_context) : 0,
768  sql ? errcontext("remote SQL command: %s", sql) : 0));
769  }
770  PG_FINALLY();
771  {
772  if (clear)
773  PQclear(res);
774  }
775  PG_END_TRY();
776 }
777 
778 /*
779  * pgfdw_xact_callback --- cleanup at main-transaction end.
780  *
781  * This runs just late enough that it must not enter user-defined code
782  * locally. (Entering such code on the remote side is fine. Its remote
783  * COMMIT TRANSACTION may run deferred triggers.)
784  */
785 static void
787 {
788  HASH_SEQ_STATUS scan;
789  ConnCacheEntry *entry;
790 
791  /* Quick exit if no connections were touched in this transaction. */
792  if (!xact_got_connection)
793  return;
794 
795  /*
796  * Scan all connection cache entries to find open remote transactions, and
797  * close them.
798  */
799  hash_seq_init(&scan, ConnectionHash);
800  while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
801  {
802  PGresult *res;
803 
804  /* Ignore cache entry if no open connection right now */
805  if (entry->conn == NULL)
806  continue;
807 
808  /* If it has an open remote transaction, try to close it */
809  if (entry->xact_depth > 0)
810  {
811  bool abort_cleanup_failure = false;
812 
813  elog(DEBUG3, "closing remote transaction on connection %p",
814  entry->conn);
815 
816  switch (event)
817  {
820 
821  /*
822  * If abort cleanup previously failed for this connection,
823  * we can't issue any more commands against it.
824  */
826 
827  /* Commit all remote transactions during pre-commit */
828  entry->changing_xact_state = true;
829  do_sql_command(entry->conn, "COMMIT TRANSACTION");
830  entry->changing_xact_state = false;
831 
832  /*
833  * If there were any errors in subtransactions, and we
834  * made prepared statements, do a DEALLOCATE ALL to make
835  * sure we get rid of all prepared statements. This is
836  * annoying and not terribly bulletproof, but it's
837  * probably not worth trying harder.
838  *
839  * DEALLOCATE ALL only exists in 8.3 and later, so this
840  * constrains how old a server postgres_fdw can
841  * communicate with. We intentionally ignore errors in
842  * the DEALLOCATE, so that we can hobble along to some
843  * extent with older servers (leaking prepared statements
844  * as we go; but we don't really support update operations
845  * pre-8.3 anyway).
846  */
847  if (entry->have_prep_stmt && entry->have_error)
848  {
849  res = PQexec(entry->conn, "DEALLOCATE ALL");
850  PQclear(res);
851  }
852  entry->have_prep_stmt = false;
853  entry->have_error = false;
854  break;
856 
857  /*
858  * We disallow any remote transactions, since it's not
859  * very reasonable to hold them open until the prepared
860  * transaction is committed. For the moment, throw error
861  * unconditionally; later we might allow read-only cases.
862  * Note that the error will cause us to come right back
863  * here with event == XACT_EVENT_ABORT, so we'll clean up
864  * the connection state at that point.
865  */
866  ereport(ERROR,
867  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
868  errmsg("cannot PREPARE a transaction that has operated on postgres_fdw foreign tables")));
869  break;
871  case XACT_EVENT_COMMIT:
872  case XACT_EVENT_PREPARE:
873  /* Pre-commit should have closed the open transaction */
874  elog(ERROR, "missed cleaning up connection during pre-commit");
875  break;
877  case XACT_EVENT_ABORT:
878 
879  /*
880  * Don't try to clean up the connection if we're already
881  * in error recursion trouble.
882  */
884  entry->changing_xact_state = true;
885 
886  /*
887  * If connection is already unsalvageable, don't touch it
888  * further.
889  */
890  if (entry->changing_xact_state)
891  break;
892 
893  /*
894  * Mark this connection as in the process of changing
895  * transaction state.
896  */
897  entry->changing_xact_state = true;
898 
899  /* Assume we might have lost track of prepared statements */
900  entry->have_error = true;
901 
902  /*
903  * If a command has been submitted to the remote server by
904  * using an asynchronous execution function, the command
905  * might not have yet completed. Check to see if a
906  * command is still being processed by the remote server,
907  * and if so, request cancellation of the command.
908  */
909  if (PQtransactionStatus(entry->conn) == PQTRANS_ACTIVE &&
910  !pgfdw_cancel_query(entry->conn))
911  {
912  /* Unable to cancel running query. */
913  abort_cleanup_failure = true;
914  }
915  else if (!pgfdw_exec_cleanup_query(entry->conn,
916  "ABORT TRANSACTION",
917  false))
918  {
919  /* Unable to abort remote transaction. */
920  abort_cleanup_failure = true;
921  }
922  else if (entry->have_prep_stmt && entry->have_error &&
924  "DEALLOCATE ALL",
925  true))
926  {
927  /* Trouble clearing prepared statements. */
928  abort_cleanup_failure = true;
929  }
930  else
931  {
932  entry->have_prep_stmt = false;
933  entry->have_error = false;
934  }
935 
936  /* Disarm changing_xact_state if it all worked. */
937  entry->changing_xact_state = abort_cleanup_failure;
938  break;
939  }
940  }
941 
942  /* Reset state to show we're out of a transaction */
943  entry->xact_depth = 0;
944 
945  /*
946  * If the connection isn't in a good idle state, discard it to
947  * recover. Next GetConnection will open a new connection.
948  */
949  if (PQstatus(entry->conn) != CONNECTION_OK ||
951  entry->changing_xact_state)
952  {
953  elog(DEBUG3, "discarding connection %p", entry->conn);
954  disconnect_pg_server(entry);
955  }
956  }
957 
958  /*
959  * Regardless of the event type, we can now mark ourselves as out of the
960  * transaction. (Note: if we are here during PRE_COMMIT or PRE_PREPARE,
961  * this saves a useless scan of the hashtable during COMMIT or PREPARE.)
962  */
963  xact_got_connection = false;
964 
965  /* Also reset cursor numbering for next transaction */
966  cursor_number = 0;
967 }
968 
969 /*
970  * pgfdw_subxact_callback --- cleanup at subtransaction end.
971  */
972 static void
974  SubTransactionId parentSubid, void *arg)
975 {
976  HASH_SEQ_STATUS scan;
977  ConnCacheEntry *entry;
978  int curlevel;
979 
980  /* Nothing to do at subxact start, nor after commit. */
981  if (!(event == SUBXACT_EVENT_PRE_COMMIT_SUB ||
982  event == SUBXACT_EVENT_ABORT_SUB))
983  return;
984 
985  /* Quick exit if no connections were touched in this transaction. */
986  if (!xact_got_connection)
987  return;
988 
989  /*
990  * Scan all connection cache entries to find open remote subtransactions
991  * of the current level, and close them.
992  */
993  curlevel = GetCurrentTransactionNestLevel();
994  hash_seq_init(&scan, ConnectionHash);
995  while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
996  {
997  char sql[100];
998 
999  /*
1000  * We only care about connections with open remote subtransactions of
1001  * the current level.
1002  */
1003  if (entry->conn == NULL || entry->xact_depth < curlevel)
1004  continue;
1005 
1006  if (entry->xact_depth > curlevel)
1007  elog(ERROR, "missed cleaning up remote subtransaction at level %d",
1008  entry->xact_depth);
1009 
1010  if (event == SUBXACT_EVENT_PRE_COMMIT_SUB)
1011  {
1012  /*
1013  * If abort cleanup previously failed for this connection, we
1014  * can't issue any more commands against it.
1015  */
1017 
1018  /* Commit all remote subtransactions during pre-commit */
1019  snprintf(sql, sizeof(sql), "RELEASE SAVEPOINT s%d", curlevel);
1020  entry->changing_xact_state = true;
1021  do_sql_command(entry->conn, sql);
1022  entry->changing_xact_state = false;
1023  }
1024  else if (in_error_recursion_trouble())
1025  {
1026  /*
1027  * Don't try to clean up the connection if we're already in error
1028  * recursion trouble.
1029  */
1030  entry->changing_xact_state = true;
1031  }
1032  else if (!entry->changing_xact_state)
1033  {
1034  bool abort_cleanup_failure = false;
1035 
1036  /* Remember that abort cleanup is in progress. */
1037  entry->changing_xact_state = true;
1038 
1039  /* Assume we might have lost track of prepared statements */
1040  entry->have_error = true;
1041 
1042  /*
1043  * If a command has been submitted to the remote server by using
1044  * an asynchronous execution function, the command might not have
1045  * yet completed. Check to see if a command is still being
1046  * processed by the remote server, and if so, request cancellation
1047  * of the command.
1048  */
1049  if (PQtransactionStatus(entry->conn) == PQTRANS_ACTIVE &&
1050  !pgfdw_cancel_query(entry->conn))
1051  abort_cleanup_failure = true;
1052  else
1053  {
1054  /* Rollback all remote subtransactions during abort */
1055  snprintf(sql, sizeof(sql),
1056  "ROLLBACK TO SAVEPOINT s%d; RELEASE SAVEPOINT s%d",
1057  curlevel, curlevel);
1058  if (!pgfdw_exec_cleanup_query(entry->conn, sql, false))
1059  abort_cleanup_failure = true;
1060  }
1061 
1062  /* Disarm changing_xact_state if it all worked. */
1063  entry->changing_xact_state = abort_cleanup_failure;
1064  }
1065 
1066  /* OK, we're outta that level of subtransaction */
1067  entry->xact_depth--;
1068  }
1069 }
1070 
1071 /*
1072  * Connection invalidation callback function
1073  *
1074  * After a change to a pg_foreign_server or pg_user_mapping catalog entry,
1075  * mark connections depending on that entry as needing to be remade.
1076  * We can't immediately destroy them, since they might be in the midst of
1077  * a transaction, but we'll remake them at the next opportunity.
1078  *
1079  * Although most cache invalidation callbacks blow away all the related stuff
1080  * regardless of the given hashvalue, connections are expensive enough that
1081  * it's worth trying to avoid that.
1082  *
1083  * NB: We could avoid unnecessary disconnection more strictly by examining
1084  * individual option values, but it seems too much effort for the gain.
1085  */
1086 static void
1087 pgfdw_inval_callback(Datum arg, int cacheid, uint32 hashvalue)
1088 {
1089  HASH_SEQ_STATUS scan;
1090  ConnCacheEntry *entry;
1091 
1092  Assert(cacheid == FOREIGNSERVEROID || cacheid == USERMAPPINGOID);
1093 
1094  /* ConnectionHash must exist already, if we're registered */
1095  hash_seq_init(&scan, ConnectionHash);
1096  while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1097  {
1098  /* Ignore invalid entries */
1099  if (entry->conn == NULL)
1100  continue;
1101 
1102  /* hashvalue == 0 means a cache reset, must clear all state */
1103  if (hashvalue == 0 ||
1104  (cacheid == FOREIGNSERVEROID &&
1105  entry->server_hashvalue == hashvalue) ||
1106  (cacheid == USERMAPPINGOID &&
1107  entry->mapping_hashvalue == hashvalue))
1108  entry->invalidated = true;
1109  }
1110 }
1111 
1112 /*
1113  * Raise an error if the given connection cache entry is marked as being
1114  * in the middle of an xact state change. This should be called at which no
1115  * such change is expected to be in progress; if one is found to be in
1116  * progress, it means that we aborted in the middle of a previous state change
1117  * and now don't know what the remote transaction state actually is.
1118  * Such connections can't safely be further used. Re-establishing the
1119  * connection would change the snapshot and roll back any writes already
1120  * performed, so that's not an option, either. Thus, we must abort.
1121  */
1122 static void
1124 {
1125  HeapTuple tup;
1126  Form_pg_user_mapping umform;
1127  ForeignServer *server;
1128 
1129  /* nothing to do for inactive entries and entries of sane state */
1130  if (entry->conn == NULL || !entry->changing_xact_state)
1131  return;
1132 
1133  /* make sure this entry is inactive */
1134  disconnect_pg_server(entry);
1135 
1136  /* find server name to be shown in the message below */
1138  ObjectIdGetDatum(entry->key));
1139  if (!HeapTupleIsValid(tup))
1140  elog(ERROR, "cache lookup failed for user mapping %u", entry->key);
1141  umform = (Form_pg_user_mapping) GETSTRUCT(tup);
1142  server = GetForeignServer(umform->umserver);
1143  ReleaseSysCache(tup);
1144 
1145  ereport(ERROR,
1146  (errcode(ERRCODE_CONNECTION_EXCEPTION),
1147  errmsg("connection to server \"%s\" was lost",
1148  server->servername)));
1149 }
1150 
1151 /*
1152  * Cancel the currently-in-progress query (whose query text we do not have)
1153  * and ignore the result. Returns true if we successfully cancel the query
1154  * and discard any pending result, and false if not.
1155  */
1156 static bool
1158 {
1159  PGcancel *cancel;
1160  char errbuf[256];
1161  PGresult *result = NULL;
1162  TimestampTz endtime;
1163 
1164  /*
1165  * If it takes too long to cancel the query and discard the result, assume
1166  * the connection is dead.
1167  */
1169 
1170  /*
1171  * Issue cancel request. Unfortunately, there's no good way to limit the
1172  * amount of time that we might block inside PQgetCancel().
1173  */
1174  if ((cancel = PQgetCancel(conn)))
1175  {
1176  if (!PQcancel(cancel, errbuf, sizeof(errbuf)))
1177  {
1178  ereport(WARNING,
1179  (errcode(ERRCODE_CONNECTION_FAILURE),
1180  errmsg("could not send cancel request: %s",
1181  errbuf)));
1182  PQfreeCancel(cancel);
1183  return false;
1184  }
1185  PQfreeCancel(cancel);
1186  }
1187 
1188  /* Get and discard the result of the query. */
1189  if (pgfdw_get_cleanup_result(conn, endtime, &result))
1190  return false;
1191  PQclear(result);
1192 
1193  return true;
1194 }
1195 
1196 /*
1197  * Submit a query during (sub)abort cleanup and wait up to 30 seconds for the
1198  * result. If the query is executed without error, the return value is true.
1199  * If the query is executed successfully but returns an error, the return
1200  * value is true if and only if ignore_errors is set. If the query can't be
1201  * sent or times out, the return value is false.
1202  */
1203 static bool
1204 pgfdw_exec_cleanup_query(PGconn *conn, const char *query, bool ignore_errors)
1205 {
1206  PGresult *result = NULL;
1207  TimestampTz endtime;
1208 
1209  /*
1210  * If it takes too long to execute a cleanup query, assume the connection
1211  * is dead. It's fairly likely that this is why we aborted in the first
1212  * place (e.g. statement timeout, user cancel), so the timeout shouldn't
1213  * be too long.
1214  */
1216 
1217  /*
1218  * Submit a query. Since we don't use non-blocking mode, this also can
1219  * block. But its risk is relatively small, so we ignore that for now.
1220  */
1221  if (!PQsendQuery(conn, query))
1222  {
1223  pgfdw_report_error(WARNING, NULL, conn, false, query);
1224  return false;
1225  }
1226 
1227  /* Get the result of the query. */
1228  if (pgfdw_get_cleanup_result(conn, endtime, &result))
1229  return false;
1230 
1231  /* Issue a warning if not successful. */
1232  if (PQresultStatus(result) != PGRES_COMMAND_OK)
1233  {
1234  pgfdw_report_error(WARNING, result, conn, true, query);
1235  return ignore_errors;
1236  }
1237  PQclear(result);
1238 
1239  return true;
1240 }
1241 
1242 /*
1243  * Get, during abort cleanup, the result of a query that is in progress. This
1244  * might be a query that is being interrupted by transaction abort, or it might
1245  * be a query that was initiated as part of transaction abort to get the remote
1246  * side back to the appropriate state.
1247  *
1248  * It's not a huge problem if we throw an ERROR here, but if we get into error
1249  * recursion trouble, we'll end up slamming the connection shut, which will
1250  * necessitate failing the entire toplevel transaction even if subtransactions
1251  * were used. Try to use WARNING where we can.
1252  *
1253  * endtime is the time at which we should give up and assume the remote
1254  * side is dead. Returns true if the timeout expired, otherwise false.
1255  * Sets *result except in case of a timeout.
1256  */
1257 static bool
1259 {
1260  volatile bool timed_out = false;
1261  PGresult *volatile last_res = NULL;
1262 
1263  /* In what follows, do not leak any PGresults on an error. */
1264  PG_TRY();
1265  {
1266  for (;;)
1267  {
1268  PGresult *res;
1269 
1270  while (PQisBusy(conn))
1271  {
1272  int wc;
1274  long cur_timeout;
1275 
1276  /* If timeout has expired, give up, else get sleep time. */
1277  cur_timeout = TimestampDifferenceMilliseconds(now, endtime);
1278  if (cur_timeout <= 0)
1279  {
1280  timed_out = true;
1281  goto exit;
1282  }
1283 
1284  /* Sleep until there's something to do */
1288  PQsocket(conn),
1289  cur_timeout, PG_WAIT_EXTENSION);
1291 
1293 
1294  /* Data available in socket? */
1295  if (wc & WL_SOCKET_READABLE)
1296  {
1297  if (!PQconsumeInput(conn))
1298  {
1299  /* connection trouble; treat the same as a timeout */
1300  timed_out = true;
1301  goto exit;
1302  }
1303  }
1304  }
1305 
1306  res = PQgetResult(conn);
1307  if (res == NULL)
1308  break; /* query is complete */
1309 
1310  PQclear(last_res);
1311  last_res = res;
1312  }
1313 exit: ;
1314  }
1315  PG_CATCH();
1316  {
1317  PQclear(last_res);
1318  PG_RE_THROW();
1319  }
1320  PG_END_TRY();
1321 
1322  if (timed_out)
1323  PQclear(last_res);
1324  else
1325  *result = last_res;
1326  return timed_out;
1327 }
Oid umid
Definition: foreign.h:47
XactEvent
Definition: xact.h:113
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6669
static void configure_remote_session(PGconn *conn)
Definition: connection.c:492
int errhint(const char *fmt,...)
Definition: elog.c:1149
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:58
#define HASH_CONTEXT
Definition: hsearch.h:91
#define HASH_ELEM
Definition: hsearch.h:85
#define WL_TIMEOUT
Definition: latch.h:127
MemoryContext hcxt
Definition: hsearch.h:77
static bool pgfdw_get_cleanup_result(PGconn *conn, TimestampTz endtime, PGresult **result)
Definition: connection.c:1258
int sqlerrcode
Definition: elog.h:378
#define DEBUG3
Definition: elog.h:23
#define PG_DIAG_MESSAGE_DETAIL
Definition: postgres_ext.h:59
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1578
struct ConnCacheEntry ConnCacheEntry
ErrorData * CopyErrorData(void)
Definition: elog.c:1552
int64 TimestampTz
Definition: timestamp.h:39
#define MAKE_SQLSTATE(ch1, ch2, ch3, ch4, ch5)
Definition: elog.h:62
void PQfreeCancel(PGcancel *cancel)
Definition: fe-connect.c:4318
ConnCacheKey key
Definition: connection.c:51
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Size entrysize
Definition: hsearch.h:72
static void check_conn_params(const char **keywords, const char **values, UserMapping *user)
Definition: connection.c:455
int errcode(int sqlerrcode)
Definition: elog.c:691
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4174
#define MemSet(start, val, len)
Definition: c.h:1004
#define WL_SOCKET_READABLE
Definition: latch.h:125
bool have_prep_stmt
Definition: connection.c:56
#define GetSysCacheHashValue1(cacheId, key1)
Definition: syscache.h:201
uint32 server_hashvalue
Definition: connection.c:60
uint32 SubTransactionId
Definition: c.h:579
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:919
unsigned int Oid
Definition: postgres_ext.h:31
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:6659
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:57
Oid userid
Definition: foreign.h:48
void FlushErrorState(void)
Definition: elog.c:1646
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
void ResetLatch(Latch *latch)
Definition: latch.c:588
PGconn * PQconnectdbParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:647
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1062
void ReleaseConnection(PGconn *conn)
Definition: connection.c:594
char * pchomp(const char *in)
Definition: mcxt.c:1215
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1234
Definition: dynahash.c:218
bool defGetBoolean(DefElem *def)
Definition: define.c:111
void pfree(void *pointer)
Definition: mcxt.c:1057
static unsigned int prep_stmt_number
Definition: connection.c:71
int ExtractConnectionOptions(List *defelems, const char **keywords, const char **values)
Definition: option.c:333
void FreeErrorData(ErrorData *edata)
Definition: elog.c:1608
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
bool changing_xact_state
Definition: connection.c:58
static void do_sql_command(PGconn *conn, const char *sql)
Definition: connection.c:528
FormData_pg_user_mapping * Form_pg_user_mapping
PGcancel * PQgetCancel(PGconn *conn)
Definition: fe-connect.c:4295
int errdetail(const char *fmt,...)
Definition: elog.c:1035
List * options
Definition: foreign.h:50
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:438
unsigned int uint32
Definition: c.h:429
void pgfdw_report_error(int elevel, PGresult *res, PGconn *conn, bool clear, const char *sql)
Definition: connection.c:731
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
static unsigned int cursor_number
Definition: connection.c:70
bool invalidated
Definition: connection.c:59
bool superuser_arg(Oid roleid)
Definition: superuser.c:56
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:6624
#define WARNING
Definition: elog.h:40
static bool pgfdw_exec_cleanup_query(PGconn *conn, const char *query, bool ignore_errors)
Definition: connection.c:1204
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1115
static void pgfdw_inval_callback(Datum arg, int cacheid, uint32 hashvalue)
Definition: connection.c:1087
static int elevel
Definition: vacuumlazy.c:333
#define HASH_BLOBS
Definition: hsearch.h:86
SubXactEvent
Definition: xact.h:127
#define PG_FINALLY()
Definition: elog.h:326
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1434
static void pgfdw_xact_callback(XactEvent event, void *arg)
Definition: connection.c:786
static HTAB * ConnectionHash
Definition: connection.c:67
ForeignServer * GetForeignServer(Oid serverid)
Definition: foreign.c:109
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:326
uintptr_t Datum
Definition: postgres.h:367
void RegisterSubXactCallback(SubXactCallback callback, void *arg)
Definition: xact.c:3584
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1163
static bool pgfdw_cancel_query(PGconn *conn)
Definition: connection.c:1157
#define PG_WAIT_EXTENSION
Definition: pgstat.h:860
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1704
Size keysize
Definition: hsearch.h:71
static bool UserMappingPasswordRequired(UserMapping *user)
Definition: connection.c:432
bool AcquireExternalFD(void)
Definition: fd.c:1048
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
#define PG_DIAG_MESSAGE_HINT
Definition: postgres_ext.h:60
#define ereport(elevel,...)
Definition: elog.h:155
void PQclear(PGresult *res)
Definition: fe-exec.c:694
uint32 mapping_hashvalue
Definition: connection.c:61
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
bool in_error_recursion_trouble(void)
Definition: elog.c:285
PGconn * GetConnection(UserMapping *user, bool will_prep_stmt)
Definition: connection.c:109
int errmsg_internal(const char *fmt,...)
Definition: elog.c:989
#define PG_CATCH()
Definition: elog.h:319
PGconn * conn
Definition: connection.c:52
PGresult * pgfdw_get_result(PGconn *conn, const char *query)
Definition: connection.c:666
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:2754
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void disconnect_pg_server(ConnCacheEntry *entry)
Definition: connection.c:417
#define Assert(condition)
Definition: c.h:800
#define lfirst(lc)
Definition: pg_list.h:169
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1157
void RegisterXactCallback(XactCallback callback, void *arg)
Definition: xact.c:3529
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:1754
static void pgfdw_reject_incomplete_xact_state_change(ConnCacheEntry *entry)
Definition: connection.c:1123
static bool xact_got_connection
Definition: connection.c:74
unsigned int GetCursorNumber(PGconn *conn)
Definition: connection.c:615
static int list_length(const List *l)
Definition: pg_list.h:149
Oid serverid
Definition: foreign.h:49
#define PG_RE_THROW()
Definition: elog.h:350
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1401
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1391
static Datum values[MAXATTR]
Definition: bootstrap.c:165
int PQconnectionUsedPassword(const PGconn *conn)
Definition: fe-connect.c:6718
int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
Definition: fe-connect.c:4450
void ReleaseExternalFD(void)
Definition: fd.c:1101
static char * user
Definition: pg_regress.c:95
static void make_new_connection(ConnCacheEntry *entry, UserMapping *user)
Definition: connection.c:267
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define IsolationIsSerializable()
Definition: xact.h:52
char * servername
Definition: foreign.h:39
#define elog(elevel,...)
Definition: elog.h:228
int i
#define errcontext
Definition: elog.h:199
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1939
void * arg
struct Latch * MyLatch
Definition: globals.c:54
char * defname
Definition: parsenodes.h:733
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
unsigned int GetPrepStmtNumber(PGconn *conn)
Definition: connection.c:629
static void pgfdw_subxact_callback(SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid, void *arg)
Definition: connection.c:973
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6616
#define PG_TRY()
Definition: elog.h:309
static void begin_remote_xact(ConnCacheEntry *entry)
Definition: connection.c:551
Oid ConnCacheKey
Definition: connection.c:47
PGresult * pgfdw_exec_query(PGconn *conn, const char *query)
Definition: connection.c:642
#define snprintf
Definition: port.h:215
List * options
Definition: foreign.h:42
#define WL_LATCH_SET
Definition: latch.h:124
int PQsocket(const PGconn *conn)
Definition: fe-connect.c:6687
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1542
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1778
Oid serverid
Definition: foreign.h:36
#define PG_END_TRY()
Definition: elog.h:334
#define PG_DIAG_CONTEXT
Definition: postgres_ext.h:64
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition: timestamp.c:1691
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129
MemoryContext CacheMemoryContext
Definition: mcxt.c:47
static PGconn * connect_pg_server(ForeignServer *server, UserMapping *user)
Definition: connection.c:297