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

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-2025, PostgreSQL Global Development Group
7 *
8 * IDENTIFICATION
9 * contrib/postgres_fdw/connection.c
10 *
11 *-------------------------------------------------------------------------
12 */
13#include "postgres.h"
14
15#if HAVE_POLL_H
16#include <poll.h>
17#endif
18
19#include "access/xact.h"
21#include "commands/defrem.h"
22#include "common/base64.h"
23#include "funcapi.h"
24#include "libpq/libpq-be.h"
26#include "mb/pg_wchar.h"
27#include "miscadmin.h"
28#include "pgstat.h"
29#include "postgres_fdw.h"
30#include "storage/latch.h"
31#include "utils/builtins.h"
32#include "utils/hsearch.h"
33#include "utils/inval.h"
34#include "utils/syscache.h"
35
36/*
37 * Connection cache hash table entry
38 *
39 * The lookup key in this hash table is the user mapping OID. We use just one
40 * connection per user mapping ID, which ensures that all the scans use the
41 * same snapshot during a query. Using the user mapping OID rather than
42 * the foreign server OID + user OID avoids creating multiple connections when
43 * the public user mapping applies to all user OIDs.
44 *
45 * The "conn" pointer can be NULL if we don't currently have a live connection.
46 * When we do have a connection, xact_depth tracks the current depth of
47 * transactions and subtransactions open on the remote side. We need to issue
48 * commands at the same nesting depth on the remote as we're executing at
49 * ourselves, so that rolling back a subtransaction will kill the right
50 * queries and not the wrong ones.
51 */
53
54typedef struct ConnCacheEntry
55{
56 ConnCacheKey key; /* hash key (must be first) */
57 PGconn *conn; /* connection to foreign server, or NULL */
58 /* Remaining fields are invalid when conn is NULL: */
59 int xact_depth; /* 0 = no xact open, 1 = main xact open, 2 =
60 * one level of subxact open, etc */
61 bool have_prep_stmt; /* have we prepared any stmts in this xact? */
62 bool have_error; /* have any subxacts aborted in this xact? */
63 bool changing_xact_state; /* xact state change in process */
64 bool parallel_commit; /* do we commit (sub)xacts in parallel? */
65 bool parallel_abort; /* do we abort (sub)xacts in parallel? */
66 bool invalidated; /* true if reconnect is pending */
67 bool keep_connections; /* setting value of keep_connections
68 * server option */
69 Oid serverid; /* foreign server OID used to get server name */
70 uint32 server_hashvalue; /* hash value of foreign server OID */
71 uint32 mapping_hashvalue; /* hash value of user mapping OID */
72 PgFdwConnState state; /* extra per-connection state */
74
75/*
76 * Connection cache (initialized on first use)
77 */
78static HTAB *ConnectionHash = NULL;
79
80/* for assigning cursor numbers and prepared statement numbers */
81static unsigned int cursor_number = 0;
82static unsigned int prep_stmt_number = 0;
83
84/* tracks whether any work is needed in callback functions */
85static bool xact_got_connection = false;
86
87/* custom wait event values, retrieved from shared memory */
91
92/*
93 * Milliseconds to wait to cancel an in-progress query or execute a cleanup
94 * query; if it takes longer than 30 seconds to do these, we assume the
95 * connection is dead.
96 */
97#define CONNECTION_CLEANUP_TIMEOUT 30000
98
99/*
100 * Milliseconds to wait before issuing another cancel request. This covers
101 * the race condition where the remote session ignored our cancel request
102 * because it arrived while idle.
103 */
104#define RETRY_CANCEL_TIMEOUT 1000
105
106/* Macro for constructing abort command to be sent */
107#define CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel) \
108 do { \
109 if (toplevel) \
110 snprintf((sql), sizeof(sql), \
111 "ABORT TRANSACTION"); \
112 else \
113 snprintf((sql), sizeof(sql), \
114 "ROLLBACK TO SAVEPOINT s%d; RELEASE SAVEPOINT s%d", \
115 (entry)->xact_depth, (entry)->xact_depth); \
116 } while(0)
117
118/*
119 * Extension version number, for supporting older extension versions' objects
120 */
122{
125};
126
127/*
128 * SQL functions
129 */
134
135/* prototypes of private functions */
138static void disconnect_pg_server(ConnCacheEntry *entry);
139static void check_conn_params(const char **keywords, const char **values, UserMapping *user);
141static void do_sql_command_begin(PGconn *conn, const char *sql);
142static void do_sql_command_end(PGconn *conn, const char *sql,
143 bool consume_input);
144static void begin_remote_xact(ConnCacheEntry *entry);
145static void pgfdw_report_internal(int elevel, PGresult *res, PGconn *conn,
146 const char *sql);
147static void pgfdw_xact_callback(XactEvent event, void *arg);
148static void pgfdw_subxact_callback(SubXactEvent event,
149 SubTransactionId mySubid,
150 SubTransactionId parentSubid,
151 void *arg);
152static void pgfdw_inval_callback(Datum arg, int cacheid, uint32 hashvalue);
154static void pgfdw_reset_xact_state(ConnCacheEntry *entry, bool toplevel);
155static bool pgfdw_cancel_query(PGconn *conn);
156static bool pgfdw_cancel_query_begin(PGconn *conn, TimestampTz endtime);
157static bool pgfdw_cancel_query_end(PGconn *conn, TimestampTz endtime,
158 TimestampTz retrycanceltime,
159 bool consume_input);
160static bool pgfdw_exec_cleanup_query(PGconn *conn, const char *query,
161 bool ignore_errors);
162static bool pgfdw_exec_cleanup_query_begin(PGconn *conn, const char *query);
163static bool pgfdw_exec_cleanup_query_end(PGconn *conn, const char *query,
164 TimestampTz endtime,
165 bool consume_input,
166 bool ignore_errors);
167static bool pgfdw_get_cleanup_result(PGconn *conn, TimestampTz endtime,
168 TimestampTz retrycanceltime,
169 PGresult **result, bool *timed_out);
170static void pgfdw_abort_cleanup(ConnCacheEntry *entry, bool toplevel);
171static bool pgfdw_abort_cleanup_begin(ConnCacheEntry *entry, bool toplevel,
172 List **pending_entries,
173 List **cancel_requested);
174static void pgfdw_finish_pre_commit_cleanup(List *pending_entries);
175static void pgfdw_finish_pre_subcommit_cleanup(List *pending_entries,
176 int curlevel);
177static void pgfdw_finish_abort_cleanup(List *pending_entries,
178 List *cancel_requested,
179 bool toplevel);
180static void pgfdw_security_check(const char **keywords, const char **values,
184static bool disconnect_cached_connections(Oid serverid);
186 enum pgfdwVersion api_version);
187static int pgfdw_conn_check(PGconn *conn);
188static bool pgfdw_conn_checkable(void);
189static bool pgfdw_has_required_scram_options(const char **keywords, const char **values);
190
191/*
192 * Get a PGconn which can be used to execute queries on the remote PostgreSQL
193 * server with the user's authorization. A new connection is established
194 * if we don't already have a suitable one, and a transaction is opened at
195 * the right subtransaction nesting depth if we didn't do that already.
196 *
197 * will_prep_stmt must be true if caller intends to create any prepared
198 * statements. Since those don't go away automatically at transaction end
199 * (not even on error), we need this flag to cue manual cleanup.
200 *
201 * If state is not NULL, *state receives the per-connection state associated
202 * with the PGconn.
203 */
204PGconn *
206{
207 bool found;
208 bool retry = false;
209 ConnCacheEntry *entry;
212
213 /* First time through, initialize connection cache hashtable */
214 if (ConnectionHash == NULL)
215 {
216 HASHCTL ctl;
217
218 if (pgfdw_we_get_result == 0)
220 WaitEventExtensionNew("PostgresFdwGetResult");
221
222 ctl.keysize = sizeof(ConnCacheKey);
223 ctl.entrysize = sizeof(ConnCacheEntry);
224 ConnectionHash = hash_create("postgres_fdw connections", 8,
225 &ctl,
227
228 /*
229 * Register some callback functions that manage connection cleanup.
230 * This should be done just once in each backend.
231 */
234 CacheRegisterSyscacheCallback(FOREIGNSERVEROID,
236 CacheRegisterSyscacheCallback(USERMAPPINGOID,
238 }
239
240 /* Set flag that we did GetConnection during the current transaction */
241 xact_got_connection = true;
242
243 /* Create hash key for the entry. Assume no pad bytes in key struct */
244 key = user->umid;
245
246 /*
247 * Find or create cached entry for requested connection.
248 */
249 entry = hash_search(ConnectionHash, &key, HASH_ENTER, &found);
250 if (!found)
251 {
252 /*
253 * We need only clear "conn" here; remaining fields will be filled
254 * later when "conn" is set.
255 */
256 entry->conn = NULL;
257 }
258
259 /* Reject further use of connections which failed abort cleanup. */
261
262 /*
263 * If the connection needs to be remade due to invalidation, disconnect as
264 * soon as we're out of all transactions.
265 */
266 if (entry->conn != NULL && entry->invalidated && entry->xact_depth == 0)
267 {
268 elog(DEBUG3, "closing connection %p for option changes to take effect",
269 entry->conn);
271 }
272
273 /*
274 * If cache entry doesn't have a connection, we have to establish a new
275 * connection. (If connect_pg_server throws an error, the cache entry
276 * will remain in a valid empty state, ie conn == NULL.)
277 */
278 if (entry->conn == NULL)
280
281 /*
282 * We check the health of the cached connection here when using it. In
283 * cases where we're out of all transactions, if a broken connection is
284 * detected, we try to reestablish a new connection later.
285 */
286 PG_TRY();
287 {
288 /* Process a pending asynchronous request if any. */
289 if (entry->state.pendingAreq)
291 /* Start a new transaction or subtransaction if needed. */
292 begin_remote_xact(entry);
293 }
294 PG_CATCH();
295 {
297 ErrorData *errdata = CopyErrorData();
298
299 /*
300 * Determine whether to try to reestablish the connection.
301 *
302 * After a broken connection is detected in libpq, any error other
303 * than connection failure (e.g., out-of-memory) can be thrown
304 * somewhere between return from libpq and the expected ereport() call
305 * in pgfdw_report_error(). In this case, since PQstatus() indicates
306 * CONNECTION_BAD, checking only PQstatus() causes the false detection
307 * of connection failure. To avoid this, we also verify that the
308 * error's sqlstate is ERRCODE_CONNECTION_FAILURE. Note that also
309 * checking only the sqlstate can cause another false detection
310 * because pgfdw_report_error() may report ERRCODE_CONNECTION_FAILURE
311 * for any libpq-originated error condition.
312 */
313 if (errdata->sqlerrcode != ERRCODE_CONNECTION_FAILURE ||
314 PQstatus(entry->conn) != CONNECTION_BAD ||
315 entry->xact_depth > 0)
316 {
318 PG_RE_THROW();
319 }
320
321 /* Clean up the error state */
323 FreeErrorData(errdata);
324 errdata = NULL;
325
326 retry = true;
327 }
328 PG_END_TRY();
329
330 /*
331 * If a broken connection is detected, disconnect it, reestablish a new
332 * connection and retry a new remote transaction. If connection failure is
333 * reported again, we give up getting a connection.
334 */
335 if (retry)
336 {
337 Assert(entry->xact_depth == 0);
338
340 (errmsg_internal("could not start remote transaction on connection %p",
341 entry->conn)),
343
344 elog(DEBUG3, "closing connection %p to reestablish a new one",
345 entry->conn);
347
349
350 begin_remote_xact(entry);
351 }
352
353 /* Remember if caller will prepare statements */
354 entry->have_prep_stmt |= will_prep_stmt;
355
356 /* If caller needs access to the per-connection state, return it. */
357 if (state)
358 *state = &entry->state;
359
360 return entry->conn;
361}
362
363/*
364 * Reset all transient state fields in the cached connection entry and
365 * establish new connection to the remote server.
366 */
367static void
369{
370 ForeignServer *server = GetForeignServer(user->serverid);
371 ListCell *lc;
372
373 Assert(entry->conn == NULL);
374
375 /* Reset all transient state fields, to be sure all are clean */
376 entry->xact_depth = 0;
377 entry->have_prep_stmt = false;
378 entry->have_error = false;
379 entry->changing_xact_state = false;
380 entry->invalidated = false;
381 entry->serverid = server->serverid;
382 entry->server_hashvalue =
383 GetSysCacheHashValue1(FOREIGNSERVEROID,
384 ObjectIdGetDatum(server->serverid));
385 entry->mapping_hashvalue =
386 GetSysCacheHashValue1(USERMAPPINGOID,
387 ObjectIdGetDatum(user->umid));
388 memset(&entry->state, 0, sizeof(entry->state));
389
390 /*
391 * Determine whether to keep the connection that we're about to make here
392 * open even after the transaction using it ends, so that the subsequent
393 * transactions can re-use it.
394 *
395 * By default, all the connections to any foreign servers are kept open.
396 *
397 * Also determine whether to commit/abort (sub)transactions opened on the
398 * remote server in parallel at (sub)transaction end, which is disabled by
399 * default.
400 *
401 * Note: it's enough to determine these only when making a new connection
402 * because if these settings for it are changed, it will be closed and
403 * re-made later.
404 */
405 entry->keep_connections = true;
406 entry->parallel_commit = false;
407 entry->parallel_abort = false;
408 foreach(lc, server->options)
409 {
410 DefElem *def = (DefElem *) lfirst(lc);
411
412 if (strcmp(def->defname, "keep_connections") == 0)
413 entry->keep_connections = defGetBoolean(def);
414 else if (strcmp(def->defname, "parallel_commit") == 0)
415 entry->parallel_commit = defGetBoolean(def);
416 else if (strcmp(def->defname, "parallel_abort") == 0)
417 entry->parallel_abort = defGetBoolean(def);
418 }
419
420 /* Now try to make the connection */
421 entry->conn = connect_pg_server(server, user);
422
423 elog(DEBUG3, "new postgres_fdw connection %p for server \"%s\" (user mapping oid %u, userid %u)",
424 entry->conn, server->servername, user->umid, user->userid);
425}
426
427/*
428 * Check that non-superuser has used password or delegated credentials
429 * to establish connection; otherwise, he's piggybacking on the
430 * postgres server's user identity. See also dblink_security_check()
431 * in contrib/dblink and check_conn_params.
432 */
433static void
435{
436 /* Superusers bypass the check */
437 if (superuser_arg(user->userid))
438 return;
439
440#ifdef ENABLE_GSS
441 /* Connected via GSSAPI with delegated credentials- all good. */
443 return;
444#endif
445
446 /* Ok if superuser set PW required false. */
448 return;
449
450 /* Connected via PW, with PW required true, and provided non-empty PW. */
452 {
453 /* ok if params contain a non-empty password */
454 for (int i = 0; keywords[i] != NULL; i++)
455 {
456 if (strcmp(keywords[i], "password") == 0 && values[i][0] != '\0')
457 return;
458 }
459 }
460
461 /*
462 * Ok if SCRAM pass-through is being used and all required SCRAM options
463 * are set correctly. If pgfdw_has_required_scram_options returns true we
464 * assume that UseScramPassthrough is also true since SCRAM options are
465 * only set when UseScramPassthrough is enabled.
466 */
468 return;
469
471 (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
472 errmsg("password or GSSAPI delegated credentials required"),
473 errdetail("Non-superuser cannot connect if the server does not request a password or use GSSAPI with delegated credentials."),
474 errhint("Target server's authentication method must be changed or password_required=false set in the user mapping attributes.")));
475}
476
477/*
478 * Connect to remote server using specified server and user mapping properties.
479 */
480static PGconn *
482{
483 PGconn *volatile conn = NULL;
484
485 /*
486 * Use PG_TRY block to ensure closing connection on error.
487 */
488 PG_TRY();
489 {
490 const char **keywords;
491 const char **values;
492 char *appname = NULL;
493 int n;
494
495 /*
496 * Construct connection params from generic options of ForeignServer
497 * and UserMapping. (Some of them might not be libpq options, in
498 * which case we'll just waste a few array slots.) Add 4 extra slots
499 * for application_name, fallback_application_name, client_encoding,
500 * end marker, and 3 extra slots for scram keys and required scram
501 * pass-through options.
502 */
503 n = list_length(server->options) + list_length(user->options) + 4 + 3;
504 keywords = (const char **) palloc(n * sizeof(char *));
505 values = (const char **) palloc(n * sizeof(char *));
506
507 n = 0;
509 keywords + n, values + n);
510 n += ExtractConnectionOptions(user->options,
511 keywords + n, values + n);
512
513 /*
514 * Use pgfdw_application_name as application_name if set.
515 *
516 * PQconnectdbParams() processes the parameter arrays from start to
517 * end. If any key word is repeated, the last value is used. Therefore
518 * note that pgfdw_application_name must be added to the arrays after
519 * options of ForeignServer are, so that it can override
520 * application_name set in ForeignServer.
521 */
523 {
524 keywords[n] = "application_name";
526 n++;
527 }
528
529 /*
530 * Search the parameter arrays to find application_name setting, and
531 * replace escape sequences in it with status information if found.
532 * The arrays are searched backwards because the last value is used if
533 * application_name is repeatedly set.
534 */
535 for (int i = n - 1; i >= 0; i--)
536 {
537 if (strcmp(keywords[i], "application_name") == 0 &&
538 *(values[i]) != '\0')
539 {
540 /*
541 * Use this application_name setting if it's not empty string
542 * even after any escape sequences in it are replaced.
543 */
544 appname = process_pgfdw_appname(values[i]);
545 if (appname[0] != '\0')
546 {
547 values[i] = appname;
548 break;
549 }
550
551 /*
552 * This empty application_name is not used, so we set
553 * values[i] to NULL and keep searching the array to find the
554 * next one.
555 */
556 values[i] = NULL;
557 pfree(appname);
558 appname = NULL;
559 }
560 }
561
562 /* Use "postgres_fdw" as fallback_application_name */
563 keywords[n] = "fallback_application_name";
564 values[n] = "postgres_fdw";
565 n++;
566
567 /* Set client_encoding so that libpq can convert encoding properly. */
568 keywords[n] = "client_encoding";
570 n++;
571
572 /* Add required SCRAM pass-through connection options if it's enabled. */
573 if (MyProcPort != NULL && MyProcPort->has_scram_keys && UseScramPassthrough(server, user))
574 {
575 int len;
576 int encoded_len;
577
578 keywords[n] = "scram_client_key";
580 /* don't forget the zero-terminator */
581 values[n] = palloc0(len + 1);
584 (char *) values[n], len);
585 if (encoded_len < 0)
586 elog(ERROR, "could not encode SCRAM client key");
587 n++;
588
589 keywords[n] = "scram_server_key";
591 /* don't forget the zero-terminator */
592 values[n] = palloc0(len + 1);
595 (char *) values[n], len);
596 if (encoded_len < 0)
597 elog(ERROR, "could not encode SCRAM server key");
598 n++;
599
600 /*
601 * Require scram-sha-256 to ensure that no other auth method is
602 * used when connecting with foreign server.
603 */
604 keywords[n] = "require_auth";
605 values[n] = "scram-sha-256";
606 n++;
607 }
608
609 keywords[n] = values[n] = NULL;
610
611 /* Verify the set of connection parameters. */
613
614 /* first time, allocate or get the custom wait event */
615 if (pgfdw_we_connect == 0)
616 pgfdw_we_connect = WaitEventExtensionNew("PostgresFdwConnect");
617
618 /* OK to make connection */
620 false, /* expand_dbname */
622
623 if (!conn || PQstatus(conn) != CONNECTION_OK)
625 (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
626 errmsg("could not connect to server \"%s\"",
627 server->servername),
629
631 "received message via remote connection");
632
633 /* Perform post-connection security checks. */
635
636 /* Prepare new session for use */
638
639 if (appname != NULL)
640 pfree(appname);
642 pfree(values);
643 }
644 PG_CATCH();
645 {
647 PG_RE_THROW();
648 }
649 PG_END_TRY();
650
651 return conn;
652}
653
654/*
655 * Disconnect any open connection for a connection cache entry.
656 */
657static void
659{
660 if (entry->conn != NULL)
661 {
663 entry->conn = NULL;
664 }
665}
666
667/*
668 * Return true if the password_required is defined and false for this user
669 * mapping, otherwise false. The mapping has been pre-validated.
670 */
671static bool
673{
674 ListCell *cell;
675
676 foreach(cell, user->options)
677 {
678 DefElem *def = (DefElem *) lfirst(cell);
679
680 if (strcmp(def->defname, "password_required") == 0)
681 return defGetBoolean(def);
682 }
683
684 return true;
685}
686
687static bool
689{
690 ListCell *cell;
691
692 foreach(cell, server->options)
693 {
694 DefElem *def = (DefElem *) lfirst(cell);
695
696 if (strcmp(def->defname, "use_scram_passthrough") == 0)
697 return defGetBoolean(def);
698 }
699
700 foreach(cell, user->options)
701 {
702 DefElem *def = (DefElem *) lfirst(cell);
703
704 if (strcmp(def->defname, "use_scram_passthrough") == 0)
705 return defGetBoolean(def);
706 }
707
708 return false;
709}
710
711/*
712 * For non-superusers, insist that the connstr specify a password or that the
713 * user provided their own GSSAPI delegated credentials. This
714 * prevents a password from being picked up from .pgpass, a service file, the
715 * environment, etc. We don't want the postgres user's passwords,
716 * certificates, etc to be accessible to non-superusers. (See also
717 * dblink_connstr_check in contrib/dblink.)
718 */
719static void
720check_conn_params(const char **keywords, const char **values, UserMapping *user)
721{
722 int i;
723
724 /* no check required if superuser */
725 if (superuser_arg(user->userid))
726 return;
727
728#ifdef ENABLE_GSS
729 /* ok if the user provided their own delegated credentials */
731 return;
732#endif
733
734 /* ok if params contain a non-empty password */
735 for (i = 0; keywords[i] != NULL; i++)
736 {
737 if (strcmp(keywords[i], "password") == 0 && values[i][0] != '\0')
738 return;
739 }
740
741 /* ok if the superuser explicitly said so at user mapping creation time */
743 return;
744
745 /*
746 * Ok if SCRAM pass-through is being used and all required scram options
747 * are set correctly. If pgfdw_has_required_scram_options returns true we
748 * assume that UseScramPassthrough is also true since SCRAM options are
749 * only set when UseScramPassthrough is enabled.
750 */
752 return;
753
755 (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
756 errmsg("password or GSSAPI delegated credentials required"),
757 errdetail("Non-superusers must delegate GSSAPI credentials, provide a password, or enable SCRAM pass-through in user mapping.")));
758}
759
760/*
761 * Issue SET commands to make sure remote session is configured properly.
762 *
763 * We do this just once at connection, assuming nothing will change the
764 * values later. Since we'll never send volatile function calls to the
765 * remote, there shouldn't be any way to break this assumption from our end.
766 * It's possible to think of ways to break it at the remote end, eg making
767 * a foreign table point to a view that includes a set_config call ---
768 * but once you admit the possibility of a malicious view definition,
769 * there are any number of ways to break things.
770 */
771static void
773{
774 int remoteversion = PQserverVersion(conn);
775
776 /* Force the search path to contain only pg_catalog (see deparse.c) */
777 do_sql_command(conn, "SET search_path = pg_catalog");
778
779 /*
780 * Set remote timezone; this is basically just cosmetic, since all
781 * transmitted and returned timestamptzs should specify a zone explicitly
782 * anyway. However it makes the regression test outputs more predictable.
783 *
784 * We don't risk setting remote zone equal to ours, since the remote
785 * server might use a different timezone database. Instead, use GMT
786 * (quoted, because very old servers are picky about case). That's
787 * guaranteed to work regardless of the remote's timezone database,
788 * because pg_tzset() hard-wires it (at least in PG 9.2 and later).
789 */
790 do_sql_command(conn, "SET timezone = 'GMT'");
791
792 /*
793 * Set values needed to ensure unambiguous data output from remote. (This
794 * logic should match what pg_dump does. See also set_transmission_modes
795 * in postgres_fdw.c.)
796 */
797 do_sql_command(conn, "SET datestyle = ISO");
798 if (remoteversion >= 80400)
799 do_sql_command(conn, "SET intervalstyle = postgres");
800 if (remoteversion >= 90000)
801 do_sql_command(conn, "SET extra_float_digits = 3");
802 else
803 do_sql_command(conn, "SET extra_float_digits = 2");
804}
805
806/*
807 * Convenience subroutine to issue a non-data-returning SQL command to remote
808 */
809void
810do_sql_command(PGconn *conn, const char *sql)
811{
813 do_sql_command_end(conn, sql, false);
814}
815
816static void
818{
819 if (!PQsendQuery(conn, sql))
820 pgfdw_report_error(NULL, conn, sql);
821}
822
823static void
824do_sql_command_end(PGconn *conn, const char *sql, bool consume_input)
825{
826 PGresult *res;
827
828 /*
829 * If requested, consume whatever data is available from the socket. (Note
830 * that if all data is available, this allows pgfdw_get_result to call
831 * PQgetResult without forcing the overhead of WaitLatchOrSocket, which
832 * would be large compared to the overhead of PQconsumeInput.)
833 */
834 if (consume_input && !PQconsumeInput(conn))
835 pgfdw_report_error(NULL, conn, sql);
836 res = pgfdw_get_result(conn);
838 pgfdw_report_error(res, conn, sql);
839 PQclear(res);
840}
841
842/*
843 * Start remote transaction or subtransaction, if needed.
844 *
845 * Note that we always use at least REPEATABLE READ in the remote session.
846 * This is so that, if a query initiates multiple scans of the same or
847 * different foreign tables, we will get snapshot-consistent results from
848 * those scans. A disadvantage is that we can't provide sane emulation of
849 * READ COMMITTED behavior --- it would be nice if we had some other way to
850 * control which remote queries share a snapshot.
851 */
852static void
854{
855 int curlevel = GetCurrentTransactionNestLevel();
856
857 /* Start main transaction if we haven't yet */
858 if (entry->xact_depth <= 0)
859 {
860 const char *sql;
861
862 elog(DEBUG3, "starting remote transaction on connection %p",
863 entry->conn);
864
866 sql = "START TRANSACTION ISOLATION LEVEL SERIALIZABLE";
867 else
868 sql = "START TRANSACTION ISOLATION LEVEL REPEATABLE READ";
869 entry->changing_xact_state = true;
870 do_sql_command(entry->conn, sql);
871 entry->xact_depth = 1;
872 entry->changing_xact_state = false;
873 }
874
875 /*
876 * If we're in a subtransaction, stack up savepoints to match our level.
877 * This ensures we can rollback just the desired effects when a
878 * subtransaction aborts.
879 */
880 while (entry->xact_depth < curlevel)
881 {
882 char sql[64];
883
884 snprintf(sql, sizeof(sql), "SAVEPOINT s%d", entry->xact_depth + 1);
885 entry->changing_xact_state = true;
886 do_sql_command(entry->conn, sql);
887 entry->xact_depth++;
888 entry->changing_xact_state = false;
889 }
890}
891
892/*
893 * Release connection reference count created by calling GetConnection.
894 */
895void
897{
898 /*
899 * Currently, we don't actually track connection references because all
900 * cleanup is managed on a transaction or subtransaction basis instead. So
901 * there's nothing to do here.
902 */
903}
904
905/*
906 * Assign a "unique" number for a cursor.
907 *
908 * These really only need to be unique per connection within a transaction.
909 * For the moment we ignore the per-connection point and assign them across
910 * all connections in the transaction, but we ask for the connection to be
911 * supplied in case we want to refine that.
912 *
913 * Note that even if wraparound happens in a very long transaction, actual
914 * collisions are highly improbable; just be sure to use %u not %d to print.
915 */
916unsigned int
918{
919 return ++cursor_number;
920}
921
922/*
923 * Assign a "unique" number for a prepared statement.
924 *
925 * This works much like GetCursorNumber, except that we never reset the counter
926 * within a session. That's because we can't be 100% sure we've gotten rid
927 * of all prepared statements on all connections, and it's not really worth
928 * increasing the risk of prepared-statement name collisions by resetting.
929 */
930unsigned int
932{
933 return ++prep_stmt_number;
934}
935
936/*
937 * Submit a query and wait for the result.
938 *
939 * Since we don't use non-blocking mode, this can't process interrupts while
940 * pushing the query text to the server. That risk is relatively small, so we
941 * ignore that for now.
942 *
943 * Caller is responsible for the error handling on the result.
944 */
945PGresult *
947{
948 /* First, process a pending asynchronous request, if any. */
949 if (state && state->pendingAreq)
950 process_pending_request(state->pendingAreq);
951
952 if (!PQsendQuery(conn, query))
953 return NULL;
954 return pgfdw_get_result(conn);
955}
956
957/*
958 * Wrap libpqsrv_get_result_last(), adding wait event.
959 *
960 * Caller is responsible for the error handling on the result.
961 */
962PGresult *
964{
966}
967
968/*
969 * Report an error we got from the remote server.
970 *
971 * Callers should use pgfdw_report_error() to throw an error, or use
972 * pgfdw_report() for lesser message levels. (We make this distinction
973 * so that pgfdw_report_error() can be marked noreturn.)
974 *
975 * res: PGresult containing the error (might be NULL)
976 * conn: connection we did the query on
977 * sql: NULL, or text of remote command we tried to execute
978 *
979 * If "res" is not NULL, it'll be PQclear'ed here (unless we throw error,
980 * in which case memory context cleanup will clear it eventually).
981 *
982 * Note: callers that choose not to throw ERROR for a remote error are
983 * responsible for making sure that the associated ConnCacheEntry gets
984 * marked with have_error = true.
985 */
986void
987pgfdw_report_error(PGresult *res, PGconn *conn, const char *sql)
988{
989 pgfdw_report_internal(ERROR, res, conn, sql);
991}
992
993void
994pgfdw_report(int elevel, PGresult *res, PGconn *conn, const char *sql)
995{
996 Assert(elevel < ERROR); /* use pgfdw_report_error for that */
997 pgfdw_report_internal(elevel, res, conn, sql);
998}
999
1000static void
1002 const char *sql)
1003{
1004 char *diag_sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
1005 char *message_primary = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
1006 char *message_detail = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
1007 char *message_hint = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
1008 char *message_context = PQresultErrorField(res, PG_DIAG_CONTEXT);
1009 int sqlstate;
1010
1011 if (diag_sqlstate)
1012 sqlstate = MAKE_SQLSTATE(diag_sqlstate[0],
1013 diag_sqlstate[1],
1014 diag_sqlstate[2],
1015 diag_sqlstate[3],
1016 diag_sqlstate[4]);
1017 else
1018 sqlstate = ERRCODE_CONNECTION_FAILURE;
1019
1020 /*
1021 * If we don't get a message from the PGresult, try the PGconn. This is
1022 * needed because for connection-level failures, PQgetResult may just
1023 * return NULL, not a PGresult at all.
1024 */
1025 if (message_primary == NULL)
1026 message_primary = pchomp(PQerrorMessage(conn));
1027
1028 ereport(elevel,
1029 (errcode(sqlstate),
1030 (message_primary != NULL && message_primary[0] != '\0') ?
1031 errmsg_internal("%s", message_primary) :
1032 errmsg("could not obtain message string for remote error"),
1033 message_detail ? errdetail_internal("%s", message_detail) : 0,
1034 message_hint ? errhint("%s", message_hint) : 0,
1035 message_context ? errcontext("%s", message_context) : 0,
1036 sql ? errcontext("remote SQL command: %s", sql) : 0));
1037 PQclear(res);
1038}
1039
1040/*
1041 * pgfdw_xact_callback --- cleanup at main-transaction end.
1042 *
1043 * This runs just late enough that it must not enter user-defined code
1044 * locally. (Entering such code on the remote side is fine. Its remote
1045 * COMMIT TRANSACTION may run deferred triggers.)
1046 */
1047static void
1049{
1050 HASH_SEQ_STATUS scan;
1051 ConnCacheEntry *entry;
1052 List *pending_entries = NIL;
1053 List *cancel_requested = NIL;
1054
1055 /* Quick exit if no connections were touched in this transaction. */
1057 return;
1058
1059 /*
1060 * Scan all connection cache entries to find open remote transactions, and
1061 * close them.
1062 */
1064 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1065 {
1066 PGresult *res;
1067
1068 /* Ignore cache entry if no open connection right now */
1069 if (entry->conn == NULL)
1070 continue;
1071
1072 /* If it has an open remote transaction, try to close it */
1073 if (entry->xact_depth > 0)
1074 {
1075 elog(DEBUG3, "closing remote transaction on connection %p",
1076 entry->conn);
1077
1078 switch (event)
1079 {
1082
1083 /*
1084 * If abort cleanup previously failed for this connection,
1085 * we can't issue any more commands against it.
1086 */
1088
1089 /* Commit all remote transactions during pre-commit */
1090 entry->changing_xact_state = true;
1091 if (entry->parallel_commit)
1092 {
1093 do_sql_command_begin(entry->conn, "COMMIT TRANSACTION");
1094 pending_entries = lappend(pending_entries, entry);
1095 continue;
1096 }
1097 do_sql_command(entry->conn, "COMMIT TRANSACTION");
1098 entry->changing_xact_state = false;
1099
1100 /*
1101 * If there were any errors in subtransactions, and we
1102 * made prepared statements, do a DEALLOCATE ALL to make
1103 * sure we get rid of all prepared statements. This is
1104 * annoying and not terribly bulletproof, but it's
1105 * probably not worth trying harder.
1106 *
1107 * DEALLOCATE ALL only exists in 8.3 and later, so this
1108 * constrains how old a server postgres_fdw can
1109 * communicate with. We intentionally ignore errors in
1110 * the DEALLOCATE, so that we can hobble along to some
1111 * extent with older servers (leaking prepared statements
1112 * as we go; but we don't really support update operations
1113 * pre-8.3 anyway).
1114 */
1115 if (entry->have_prep_stmt && entry->have_error)
1116 {
1117 res = pgfdw_exec_query(entry->conn, "DEALLOCATE ALL",
1118 NULL);
1119 PQclear(res);
1120 }
1121 entry->have_prep_stmt = false;
1122 entry->have_error = false;
1123 break;
1125
1126 /*
1127 * We disallow any remote transactions, since it's not
1128 * very reasonable to hold them open until the prepared
1129 * transaction is committed. For the moment, throw error
1130 * unconditionally; later we might allow read-only cases.
1131 * Note that the error will cause us to come right back
1132 * here with event == XACT_EVENT_ABORT, so we'll clean up
1133 * the connection state at that point.
1134 */
1135 ereport(ERROR,
1136 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1137 errmsg("cannot PREPARE a transaction that has operated on postgres_fdw foreign tables")));
1138 break;
1140 case XACT_EVENT_COMMIT:
1141 case XACT_EVENT_PREPARE:
1142 /* Pre-commit should have closed the open transaction */
1143 elog(ERROR, "missed cleaning up connection during pre-commit");
1144 break;
1146 case XACT_EVENT_ABORT:
1147 /* Rollback all remote transactions during abort */
1148 if (entry->parallel_abort)
1149 {
1150 if (pgfdw_abort_cleanup_begin(entry, true,
1151 &pending_entries,
1152 &cancel_requested))
1153 continue;
1154 }
1155 else
1156 pgfdw_abort_cleanup(entry, true);
1157 break;
1158 }
1159 }
1160
1161 /* Reset state to show we're out of a transaction */
1162 pgfdw_reset_xact_state(entry, true);
1163 }
1164
1165 /* If there are any pending connections, finish cleaning them up */
1166 if (pending_entries || cancel_requested)
1167 {
1168 if (event == XACT_EVENT_PARALLEL_PRE_COMMIT ||
1169 event == XACT_EVENT_PRE_COMMIT)
1170 {
1171 Assert(cancel_requested == NIL);
1172 pgfdw_finish_pre_commit_cleanup(pending_entries);
1173 }
1174 else
1175 {
1177 event == XACT_EVENT_ABORT);
1178 pgfdw_finish_abort_cleanup(pending_entries, cancel_requested,
1179 true);
1180 }
1181 }
1182
1183 /*
1184 * Regardless of the event type, we can now mark ourselves as out of the
1185 * transaction. (Note: if we are here during PRE_COMMIT or PRE_PREPARE,
1186 * this saves a useless scan of the hashtable during COMMIT or PREPARE.)
1187 */
1188 xact_got_connection = false;
1189
1190 /* Also reset cursor numbering for next transaction */
1191 cursor_number = 0;
1192}
1193
1194/*
1195 * pgfdw_subxact_callback --- cleanup at subtransaction end.
1196 */
1197static void
1199 SubTransactionId parentSubid, void *arg)
1200{
1201 HASH_SEQ_STATUS scan;
1202 ConnCacheEntry *entry;
1203 int curlevel;
1204 List *pending_entries = NIL;
1205 List *cancel_requested = NIL;
1206
1207 /* Nothing to do at subxact start, nor after commit. */
1208 if (!(event == SUBXACT_EVENT_PRE_COMMIT_SUB ||
1209 event == SUBXACT_EVENT_ABORT_SUB))
1210 return;
1211
1212 /* Quick exit if no connections were touched in this transaction. */
1214 return;
1215
1216 /*
1217 * Scan all connection cache entries to find open remote subtransactions
1218 * of the current level, and close them.
1219 */
1220 curlevel = GetCurrentTransactionNestLevel();
1222 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1223 {
1224 char sql[100];
1225
1226 /*
1227 * We only care about connections with open remote subtransactions of
1228 * the current level.
1229 */
1230 if (entry->conn == NULL || entry->xact_depth < curlevel)
1231 continue;
1232
1233 if (entry->xact_depth > curlevel)
1234 elog(ERROR, "missed cleaning up remote subtransaction at level %d",
1235 entry->xact_depth);
1236
1237 if (event == SUBXACT_EVENT_PRE_COMMIT_SUB)
1238 {
1239 /*
1240 * If abort cleanup previously failed for this connection, we
1241 * can't issue any more commands against it.
1242 */
1244
1245 /* Commit all remote subtransactions during pre-commit */
1246 snprintf(sql, sizeof(sql), "RELEASE SAVEPOINT s%d", curlevel);
1247 entry->changing_xact_state = true;
1248 if (entry->parallel_commit)
1249 {
1250 do_sql_command_begin(entry->conn, sql);
1251 pending_entries = lappend(pending_entries, entry);
1252 continue;
1253 }
1254 do_sql_command(entry->conn, sql);
1255 entry->changing_xact_state = false;
1256 }
1257 else
1258 {
1259 /* Rollback all remote subtransactions during abort */
1260 if (entry->parallel_abort)
1261 {
1262 if (pgfdw_abort_cleanup_begin(entry, false,
1263 &pending_entries,
1264 &cancel_requested))
1265 continue;
1266 }
1267 else
1268 pgfdw_abort_cleanup(entry, false);
1269 }
1270
1271 /* OK, we're outta that level of subtransaction */
1272 pgfdw_reset_xact_state(entry, false);
1273 }
1274
1275 /* If there are any pending connections, finish cleaning them up */
1276 if (pending_entries || cancel_requested)
1277 {
1278 if (event == SUBXACT_EVENT_PRE_COMMIT_SUB)
1279 {
1280 Assert(cancel_requested == NIL);
1281 pgfdw_finish_pre_subcommit_cleanup(pending_entries, curlevel);
1282 }
1283 else
1284 {
1286 pgfdw_finish_abort_cleanup(pending_entries, cancel_requested,
1287 false);
1288 }
1289 }
1290}
1291
1292/*
1293 * Connection invalidation callback function
1294 *
1295 * After a change to a pg_foreign_server or pg_user_mapping catalog entry,
1296 * close connections depending on that entry immediately if current transaction
1297 * has not used those connections yet. Otherwise, mark those connections as
1298 * invalid and then make pgfdw_xact_callback() close them at the end of current
1299 * transaction, since they cannot be closed in the midst of the transaction
1300 * using them. Closed connections will be remade at the next opportunity if
1301 * necessary.
1302 *
1303 * Although most cache invalidation callbacks blow away all the related stuff
1304 * regardless of the given hashvalue, connections are expensive enough that
1305 * it's worth trying to avoid that.
1306 *
1307 * NB: We could avoid unnecessary disconnection more strictly by examining
1308 * individual option values, but it seems too much effort for the gain.
1309 */
1310static void
1311pgfdw_inval_callback(Datum arg, int cacheid, uint32 hashvalue)
1312{
1313 HASH_SEQ_STATUS scan;
1314 ConnCacheEntry *entry;
1315
1316 Assert(cacheid == FOREIGNSERVEROID || cacheid == USERMAPPINGOID);
1317
1318 /* ConnectionHash must exist already, if we're registered */
1320 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1321 {
1322 /* Ignore invalid entries */
1323 if (entry->conn == NULL)
1324 continue;
1325
1326 /* hashvalue == 0 means a cache reset, must clear all state */
1327 if (hashvalue == 0 ||
1328 (cacheid == FOREIGNSERVEROID &&
1329 entry->server_hashvalue == hashvalue) ||
1330 (cacheid == USERMAPPINGOID &&
1331 entry->mapping_hashvalue == hashvalue))
1332 {
1333 /*
1334 * Close the connection immediately if it's not used yet in this
1335 * transaction. Otherwise mark it as invalid so that
1336 * pgfdw_xact_callback() can close it at the end of this
1337 * transaction.
1338 */
1339 if (entry->xact_depth == 0)
1340 {
1341 elog(DEBUG3, "discarding connection %p", entry->conn);
1342 disconnect_pg_server(entry);
1343 }
1344 else
1345 entry->invalidated = true;
1346 }
1347 }
1348}
1349
1350/*
1351 * Raise an error if the given connection cache entry is marked as being
1352 * in the middle of an xact state change. This should be called at which no
1353 * such change is expected to be in progress; if one is found to be in
1354 * progress, it means that we aborted in the middle of a previous state change
1355 * and now don't know what the remote transaction state actually is.
1356 * Such connections can't safely be further used. Re-establishing the
1357 * connection would change the snapshot and roll back any writes already
1358 * performed, so that's not an option, either. Thus, we must abort.
1359 */
1360static void
1362{
1363 ForeignServer *server;
1364
1365 /* nothing to do for inactive entries and entries of sane state */
1366 if (entry->conn == NULL || !entry->changing_xact_state)
1367 return;
1368
1369 /* make sure this entry is inactive */
1370 disconnect_pg_server(entry);
1371
1372 /* find server name to be shown in the message below */
1373 server = GetForeignServer(entry->serverid);
1374
1375 ereport(ERROR,
1376 (errcode(ERRCODE_CONNECTION_EXCEPTION),
1377 errmsg("connection to server \"%s\" was lost",
1378 server->servername)));
1379}
1380
1381/*
1382 * Reset state to show we're out of a (sub)transaction.
1383 */
1384static void
1386{
1387 if (toplevel)
1388 {
1389 /* Reset state to show we're out of a transaction */
1390 entry->xact_depth = 0;
1391
1392 /*
1393 * If the connection isn't in a good idle state, it is marked as
1394 * invalid or keep_connections option of its server is disabled, then
1395 * discard it to recover. Next GetConnection will open a new
1396 * connection.
1397 */
1398 if (PQstatus(entry->conn) != CONNECTION_OK ||
1400 entry->changing_xact_state ||
1401 entry->invalidated ||
1402 !entry->keep_connections)
1403 {
1404 elog(DEBUG3, "discarding connection %p", entry->conn);
1405 disconnect_pg_server(entry);
1406 }
1407 }
1408 else
1409 {
1410 /* Reset state to show we're out of a subtransaction */
1411 entry->xact_depth--;
1412 }
1413}
1414
1415/*
1416 * Cancel the currently-in-progress query (whose query text we do not have)
1417 * and ignore the result. Returns true if we successfully cancel the query
1418 * and discard any pending result, and false if not.
1419 *
1420 * It's not a huge problem if we throw an ERROR here, but if we get into error
1421 * recursion trouble, we'll end up slamming the connection shut, which will
1422 * necessitate failing the entire toplevel transaction even if subtransactions
1423 * were used. Try to use WARNING where we can.
1424 *
1425 * XXX: if the query was one sent by fetch_more_data_begin(), we could get the
1426 * query text from the pendingAreq saved in the per-connection state, then
1427 * report the query using it.
1428 */
1429static bool
1431{
1433 TimestampTz endtime;
1434 TimestampTz retrycanceltime;
1435
1436 /*
1437 * If it takes too long to cancel the query and discard the result, assume
1438 * the connection is dead.
1439 */
1441
1442 /*
1443 * Also, lose patience and re-issue the cancel request after a little bit.
1444 * (This serves to close some race conditions.)
1445 */
1447
1448 if (!pgfdw_cancel_query_begin(conn, endtime))
1449 return false;
1450 return pgfdw_cancel_query_end(conn, endtime, retrycanceltime, false);
1451}
1452
1453/*
1454 * Submit a cancel request to the given connection, waiting only until
1455 * the given time.
1456 *
1457 * We sleep interruptibly until we receive confirmation that the cancel
1458 * request has been accepted, and if it is, return true; if the timeout
1459 * lapses without that, or the request fails for whatever reason, return
1460 * false.
1461 */
1462static bool
1464{
1465 const char *errormsg = libpqsrv_cancel(conn, endtime);
1466
1467 if (errormsg != NULL)
1469 errcode(ERRCODE_CONNECTION_FAILURE),
1470 errmsg("could not send cancel request: %s", errormsg));
1471
1472 return errormsg == NULL;
1473}
1474
1475static bool
1477 TimestampTz retrycanceltime, bool consume_input)
1478{
1479 PGresult *result;
1480 bool timed_out;
1481
1482 /*
1483 * If requested, consume whatever data is available from the socket. (Note
1484 * that if all data is available, this allows pgfdw_get_cleanup_result to
1485 * call PQgetResult without forcing the overhead of WaitLatchOrSocket,
1486 * which would be large compared to the overhead of PQconsumeInput.)
1487 */
1488 if (consume_input && !PQconsumeInput(conn))
1489 {
1491 (errcode(ERRCODE_CONNECTION_FAILURE),
1492 errmsg("could not get result of cancel request: %s",
1494 return false;
1495 }
1496
1497 /* Get and discard the result of the query. */
1498 if (pgfdw_get_cleanup_result(conn, endtime, retrycanceltime,
1499 &result, &timed_out))
1500 {
1501 if (timed_out)
1503 (errmsg("could not get result of cancel request due to timeout")));
1504 else
1506 (errcode(ERRCODE_CONNECTION_FAILURE),
1507 errmsg("could not get result of cancel request: %s",
1509
1510 return false;
1511 }
1512 PQclear(result);
1513
1514 return true;
1515}
1516
1517/*
1518 * Submit a query during (sub)abort cleanup and wait up to 30 seconds for the
1519 * result. If the query is executed without error, the return value is true.
1520 * If the query is executed successfully but returns an error, the return
1521 * value is true if and only if ignore_errors is set. If the query can't be
1522 * sent or times out, the return value is false.
1523 *
1524 * It's not a huge problem if we throw an ERROR here, but if we get into error
1525 * recursion trouble, we'll end up slamming the connection shut, which will
1526 * necessitate failing the entire toplevel transaction even if subtransactions
1527 * were used. Try to use WARNING where we can.
1528 */
1529static bool
1530pgfdw_exec_cleanup_query(PGconn *conn, const char *query, bool ignore_errors)
1531{
1532 TimestampTz endtime;
1533
1534 /*
1535 * If it takes too long to execute a cleanup query, assume the connection
1536 * is dead. It's fairly likely that this is why we aborted in the first
1537 * place (e.g. statement timeout, user cancel), so the timeout shouldn't
1538 * be too long.
1539 */
1542
1544 return false;
1545 return pgfdw_exec_cleanup_query_end(conn, query, endtime,
1546 false, ignore_errors);
1547}
1548
1549static bool
1551{
1552 Assert(query != NULL);
1553
1554 /*
1555 * Submit a query. Since we don't use non-blocking mode, this also can
1556 * block. But its risk is relatively small, so we ignore that for now.
1557 */
1558 if (!PQsendQuery(conn, query))
1559 {
1560 pgfdw_report(WARNING, NULL, conn, query);
1561 return false;
1562 }
1563
1564 return true;
1565}
1566
1567static bool
1569 TimestampTz endtime, bool consume_input,
1570 bool ignore_errors)
1571{
1572 PGresult *result;
1573 bool timed_out;
1574
1575 Assert(query != NULL);
1576
1577 /*
1578 * If requested, consume whatever data is available from the socket. (Note
1579 * that if all data is available, this allows pgfdw_get_cleanup_result to
1580 * call PQgetResult without forcing the overhead of WaitLatchOrSocket,
1581 * which would be large compared to the overhead of PQconsumeInput.)
1582 */
1583 if (consume_input && !PQconsumeInput(conn))
1584 {
1585 pgfdw_report(WARNING, NULL, conn, query);
1586 return false;
1587 }
1588
1589 /* Get the result of the query. */
1590 if (pgfdw_get_cleanup_result(conn, endtime, endtime, &result, &timed_out))
1591 {
1592 if (timed_out)
1594 (errmsg("could not get query result due to timeout"),
1595 errcontext("remote SQL command: %s", query)));
1596 else
1597 pgfdw_report(WARNING, NULL, conn, query);
1598
1599 return false;
1600 }
1601
1602 /* Issue a warning if not successful. */
1603 if (PQresultStatus(result) != PGRES_COMMAND_OK)
1604 {
1605 pgfdw_report(WARNING, result, conn, query);
1606 return ignore_errors;
1607 }
1608 PQclear(result);
1609
1610 return true;
1611}
1612
1613/*
1614 * Get, during abort cleanup, the result of a query that is in progress.
1615 * This might be a query that is being interrupted by a cancel request or by
1616 * transaction abort, or it might be a query that was initiated as part of
1617 * transaction abort to get the remote side back to the appropriate state.
1618 *
1619 * endtime is the time at which we should give up and assume the remote side
1620 * is dead. retrycanceltime is the time at which we should issue a fresh
1621 * cancel request (pass the same value as endtime if this is not wanted).
1622 *
1623 * Returns true if the timeout expired or connection trouble occurred,
1624 * false otherwise. Sets *result except in case of a true result.
1625 * Sets *timed_out to true only when the timeout expired.
1626 */
1627static bool
1629 TimestampTz retrycanceltime,
1630 PGresult **result,
1631 bool *timed_out)
1632{
1633 bool failed = false;
1634 PGresult *last_res = NULL;
1635 int canceldelta = RETRY_CANCEL_TIMEOUT * 2;
1636
1637 *result = NULL;
1638 *timed_out = false;
1639 for (;;)
1640 {
1641 PGresult *res;
1642
1643 while (PQisBusy(conn))
1644 {
1645 int wc;
1647 long cur_timeout;
1648
1649 /* If timeout has expired, give up. */
1650 if (now >= endtime)
1651 {
1652 *timed_out = true;
1653 failed = true;
1654 goto exit;
1655 }
1656
1657 /* If we need to re-issue the cancel request, do that. */
1658 if (now >= retrycanceltime)
1659 {
1660 /* We ignore failure to issue the repeated request. */
1661 (void) libpqsrv_cancel(conn, endtime);
1662
1663 /* Recompute "now" in case that took measurable time. */
1665
1666 /* Adjust re-cancel timeout in increasing steps. */
1667 retrycanceltime = TimestampTzPlusMilliseconds(now,
1668 canceldelta);
1669 canceldelta += canceldelta;
1670 }
1671
1672 /* If timeout has expired, give up, else get sleep time. */
1674 Min(endtime,
1675 retrycanceltime));
1676 if (cur_timeout <= 0)
1677 {
1678 *timed_out = true;
1679 failed = true;
1680 goto exit;
1681 }
1682
1683 /* first time, allocate or get the custom wait event */
1684 if (pgfdw_we_cleanup_result == 0)
1685 pgfdw_we_cleanup_result = WaitEventExtensionNew("PostgresFdwCleanupResult");
1686
1687 /* Sleep until there's something to do */
1691 PQsocket(conn),
1692 cur_timeout, pgfdw_we_cleanup_result);
1694
1696
1697 /* Data available in socket? */
1698 if (wc & WL_SOCKET_READABLE)
1699 {
1700 if (!PQconsumeInput(conn))
1701 {
1702 /* connection trouble */
1703 failed = true;
1704 goto exit;
1705 }
1706 }
1707 }
1708
1709 res = PQgetResult(conn);
1710 if (res == NULL)
1711 break; /* query is complete */
1712
1713 PQclear(last_res);
1714 last_res = res;
1715 }
1716exit:
1717 if (failed)
1718 PQclear(last_res);
1719 else
1720 *result = last_res;
1721 return failed;
1722}
1723
1724/*
1725 * Abort remote transaction or subtransaction.
1726 *
1727 * "toplevel" should be set to true if toplevel (main) transaction is
1728 * rollbacked, false otherwise.
1729 *
1730 * Set entry->changing_xact_state to false on success, true on failure.
1731 */
1732static void
1734{
1735 char sql[100];
1736
1737 /*
1738 * Don't try to clean up the connection if we're already in error
1739 * recursion trouble.
1740 */
1742 entry->changing_xact_state = true;
1743
1744 /*
1745 * If connection is already unsalvageable, don't touch it further.
1746 */
1747 if (entry->changing_xact_state)
1748 return;
1749
1750 /*
1751 * Mark this connection as in the process of changing transaction state.
1752 */
1753 entry->changing_xact_state = true;
1754
1755 /* Assume we might have lost track of prepared statements */
1756 entry->have_error = true;
1757
1758 /*
1759 * If a command has been submitted to the remote server by using an
1760 * asynchronous execution function, the command might not have yet
1761 * completed. Check to see if a command is still being processed by the
1762 * remote server, and if so, request cancellation of the command.
1763 */
1764 if (PQtransactionStatus(entry->conn) == PQTRANS_ACTIVE &&
1765 !pgfdw_cancel_query(entry->conn))
1766 return; /* Unable to cancel running query */
1767
1768 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
1769 if (!pgfdw_exec_cleanup_query(entry->conn, sql, false))
1770 return; /* Unable to abort remote (sub)transaction */
1771
1772 if (toplevel)
1773 {
1774 if (entry->have_prep_stmt && entry->have_error &&
1776 "DEALLOCATE ALL",
1777 true))
1778 return; /* Trouble clearing prepared statements */
1779
1780 entry->have_prep_stmt = false;
1781 entry->have_error = false;
1782 }
1783
1784 /*
1785 * If pendingAreq of the per-connection state is not NULL, it means that
1786 * an asynchronous fetch begun by fetch_more_data_begin() was not done
1787 * successfully and thus the per-connection state was not reset in
1788 * fetch_more_data(); in that case reset the per-connection state here.
1789 */
1790 if (entry->state.pendingAreq)
1791 memset(&entry->state, 0, sizeof(entry->state));
1792
1793 /* Disarm changing_xact_state if it all worked */
1794 entry->changing_xact_state = false;
1795}
1796
1797/*
1798 * Like pgfdw_abort_cleanup, submit an abort command or cancel request, but
1799 * don't wait for the result.
1800 *
1801 * Returns true if the abort command or cancel request is successfully issued,
1802 * false otherwise. If the abort command is successfully issued, the given
1803 * connection cache entry is appended to *pending_entries. Otherwise, if the
1804 * cancel request is successfully issued, it is appended to *cancel_requested.
1805 */
1806static bool
1808 List **pending_entries, List **cancel_requested)
1809{
1810 /*
1811 * Don't try to clean up the connection if we're already in error
1812 * recursion trouble.
1813 */
1815 entry->changing_xact_state = true;
1816
1817 /*
1818 * If connection is already unsalvageable, don't touch it further.
1819 */
1820 if (entry->changing_xact_state)
1821 return false;
1822
1823 /*
1824 * Mark this connection as in the process of changing transaction state.
1825 */
1826 entry->changing_xact_state = true;
1827
1828 /* Assume we might have lost track of prepared statements */
1829 entry->have_error = true;
1830
1831 /*
1832 * If a command has been submitted to the remote server by using an
1833 * asynchronous execution function, the command might not have yet
1834 * completed. Check to see if a command is still being processed by the
1835 * remote server, and if so, request cancellation of the command.
1836 */
1838 {
1839 TimestampTz endtime;
1840
1843 if (!pgfdw_cancel_query_begin(entry->conn, endtime))
1844 return false; /* Unable to cancel running query */
1845 *cancel_requested = lappend(*cancel_requested, entry);
1846 }
1847 else
1848 {
1849 char sql[100];
1850
1851 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
1852 if (!pgfdw_exec_cleanup_query_begin(entry->conn, sql))
1853 return false; /* Unable to abort remote transaction */
1854 *pending_entries = lappend(*pending_entries, entry);
1855 }
1856
1857 return true;
1858}
1859
1860/*
1861 * Finish pre-commit cleanup of connections on each of which we've sent a
1862 * COMMIT command to the remote server.
1863 */
1864static void
1866{
1867 ConnCacheEntry *entry;
1868 List *pending_deallocs = NIL;
1869 ListCell *lc;
1870
1871 Assert(pending_entries);
1872
1873 /*
1874 * Get the result of the COMMIT command for each of the pending entries
1875 */
1876 foreach(lc, pending_entries)
1877 {
1878 entry = (ConnCacheEntry *) lfirst(lc);
1879
1881
1882 /*
1883 * We might already have received the result on the socket, so pass
1884 * consume_input=true to try to consume it first
1885 */
1886 do_sql_command_end(entry->conn, "COMMIT TRANSACTION", true);
1887 entry->changing_xact_state = false;
1888
1889 /* Do a DEALLOCATE ALL in parallel if needed */
1890 if (entry->have_prep_stmt && entry->have_error)
1891 {
1892 /* Ignore errors (see notes in pgfdw_xact_callback) */
1893 if (PQsendQuery(entry->conn, "DEALLOCATE ALL"))
1894 {
1895 pending_deallocs = lappend(pending_deallocs, entry);
1896 continue;
1897 }
1898 }
1899 entry->have_prep_stmt = false;
1900 entry->have_error = false;
1901
1902 pgfdw_reset_xact_state(entry, true);
1903 }
1904
1905 /* No further work if no pending entries */
1906 if (!pending_deallocs)
1907 return;
1908
1909 /*
1910 * Get the result of the DEALLOCATE command for each of the pending
1911 * entries
1912 */
1913 foreach(lc, pending_deallocs)
1914 {
1915 PGresult *res;
1916
1917 entry = (ConnCacheEntry *) lfirst(lc);
1918
1919 /* Ignore errors (see notes in pgfdw_xact_callback) */
1920 while ((res = PQgetResult(entry->conn)) != NULL)
1921 {
1922 PQclear(res);
1923 /* Stop if the connection is lost (else we'll loop infinitely) */
1924 if (PQstatus(entry->conn) == CONNECTION_BAD)
1925 break;
1926 }
1927 entry->have_prep_stmt = false;
1928 entry->have_error = false;
1929
1930 pgfdw_reset_xact_state(entry, true);
1931 }
1932}
1933
1934/*
1935 * Finish pre-subcommit cleanup of connections on each of which we've sent a
1936 * RELEASE command to the remote server.
1937 */
1938static void
1939pgfdw_finish_pre_subcommit_cleanup(List *pending_entries, int curlevel)
1940{
1941 ConnCacheEntry *entry;
1942 char sql[100];
1943 ListCell *lc;
1944
1945 Assert(pending_entries);
1946
1947 /*
1948 * Get the result of the RELEASE command for each of the pending entries
1949 */
1950 snprintf(sql, sizeof(sql), "RELEASE SAVEPOINT s%d", curlevel);
1951 foreach(lc, pending_entries)
1952 {
1953 entry = (ConnCacheEntry *) lfirst(lc);
1954
1956
1957 /*
1958 * We might already have received the result on the socket, so pass
1959 * consume_input=true to try to consume it first
1960 */
1961 do_sql_command_end(entry->conn, sql, true);
1962 entry->changing_xact_state = false;
1963
1964 pgfdw_reset_xact_state(entry, false);
1965 }
1966}
1967
1968/*
1969 * Finish abort cleanup of connections on each of which we've sent an abort
1970 * command or cancel request to the remote server.
1971 */
1972static void
1973pgfdw_finish_abort_cleanup(List *pending_entries, List *cancel_requested,
1974 bool toplevel)
1975{
1976 List *pending_deallocs = NIL;
1977 ListCell *lc;
1978
1979 /*
1980 * For each of the pending cancel requests (if any), get and discard the
1981 * result of the query, and submit an abort command to the remote server.
1982 */
1983 if (cancel_requested)
1984 {
1985 foreach(lc, cancel_requested)
1986 {
1987 ConnCacheEntry *entry = (ConnCacheEntry *) lfirst(lc);
1989 TimestampTz endtime;
1990 TimestampTz retrycanceltime;
1991 char sql[100];
1992
1994
1995 /*
1996 * Set end time. You might think we should do this before issuing
1997 * cancel request like in normal mode, but that is problematic,
1998 * because if, for example, it took longer than 30 seconds to
1999 * process the first few entries in the cancel_requested list, it
2000 * would cause a timeout error when processing each of the
2001 * remaining entries in the list, leading to slamming that entry's
2002 * connection shut.
2003 */
2006 retrycanceltime = TimestampTzPlusMilliseconds(now,
2008
2009 if (!pgfdw_cancel_query_end(entry->conn, endtime,
2010 retrycanceltime, true))
2011 {
2012 /* Unable to cancel running query */
2013 pgfdw_reset_xact_state(entry, toplevel);
2014 continue;
2015 }
2016
2017 /* Send an abort command in parallel if needed */
2018 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
2019 if (!pgfdw_exec_cleanup_query_begin(entry->conn, sql))
2020 {
2021 /* Unable to abort remote (sub)transaction */
2022 pgfdw_reset_xact_state(entry, toplevel);
2023 }
2024 else
2025 pending_entries = lappend(pending_entries, entry);
2026 }
2027 }
2028
2029 /* No further work if no pending entries */
2030 if (!pending_entries)
2031 return;
2032
2033 /*
2034 * Get the result of the abort command for each of the pending entries
2035 */
2036 foreach(lc, pending_entries)
2037 {
2038 ConnCacheEntry *entry = (ConnCacheEntry *) lfirst(lc);
2039 TimestampTz endtime;
2040 char sql[100];
2041
2043
2044 /*
2045 * Set end time. We do this now, not before issuing the command like
2046 * in normal mode, for the same reason as for the cancel_requested
2047 * entries.
2048 */
2051
2052 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
2053 if (!pgfdw_exec_cleanup_query_end(entry->conn, sql, endtime,
2054 true, false))
2055 {
2056 /* Unable to abort remote (sub)transaction */
2057 pgfdw_reset_xact_state(entry, toplevel);
2058 continue;
2059 }
2060
2061 if (toplevel)
2062 {
2063 /* Do a DEALLOCATE ALL in parallel if needed */
2064 if (entry->have_prep_stmt && entry->have_error)
2065 {
2067 "DEALLOCATE ALL"))
2068 {
2069 /* Trouble clearing prepared statements */
2070 pgfdw_reset_xact_state(entry, toplevel);
2071 }
2072 else
2073 pending_deallocs = lappend(pending_deallocs, entry);
2074 continue;
2075 }
2076 entry->have_prep_stmt = false;
2077 entry->have_error = false;
2078 }
2079
2080 /* Reset the per-connection state if needed */
2081 if (entry->state.pendingAreq)
2082 memset(&entry->state, 0, sizeof(entry->state));
2083
2084 /* We're done with this entry; unset the changing_xact_state flag */
2085 entry->changing_xact_state = false;
2086 pgfdw_reset_xact_state(entry, toplevel);
2087 }
2088
2089 /* No further work if no pending entries */
2090 if (!pending_deallocs)
2091 return;
2092 Assert(toplevel);
2093
2094 /*
2095 * Get the result of the DEALLOCATE command for each of the pending
2096 * entries
2097 */
2098 foreach(lc, pending_deallocs)
2099 {
2100 ConnCacheEntry *entry = (ConnCacheEntry *) lfirst(lc);
2101 TimestampTz endtime;
2102
2104 Assert(entry->have_prep_stmt);
2105 Assert(entry->have_error);
2106
2107 /*
2108 * Set end time. We do this now, not before issuing the command like
2109 * in normal mode, for the same reason as for the cancel_requested
2110 * entries.
2111 */
2114
2115 if (!pgfdw_exec_cleanup_query_end(entry->conn, "DEALLOCATE ALL",
2116 endtime, true, true))
2117 {
2118 /* Trouble clearing prepared statements */
2119 pgfdw_reset_xact_state(entry, toplevel);
2120 continue;
2121 }
2122 entry->have_prep_stmt = false;
2123 entry->have_error = false;
2124
2125 /* Reset the per-connection state if needed */
2126 if (entry->state.pendingAreq)
2127 memset(&entry->state, 0, sizeof(entry->state));
2128
2129 /* We're done with this entry; unset the changing_xact_state flag */
2130 entry->changing_xact_state = false;
2131 pgfdw_reset_xact_state(entry, toplevel);
2132 }
2133}
2134
2135/* Number of output arguments (columns) for various API versions */
2136#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1 2
2137#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2 6
2138#define POSTGRES_FDW_GET_CONNECTIONS_COLS 6 /* maximum of above */
2139
2140/*
2141 * Internal function used by postgres_fdw_get_connections variants.
2142 *
2143 * For API version 1.1, this function takes no input parameter and
2144 * returns a set of records with the following values:
2145 *
2146 * - server_name - server name of active connection. In case the foreign server
2147 * is dropped but still the connection is active, then the server name will
2148 * be NULL in output.
2149 * - valid - true/false representing whether the connection is valid or not.
2150 * Note that connections can become invalid in pgfdw_inval_callback.
2151 *
2152 * For API version 1.2 and later, this function takes an input parameter
2153 * to check a connection status and returns the following
2154 * additional values along with the four values from version 1.1:
2155 *
2156 * - user_name - the local user name of the active connection. In case the
2157 * user mapping is dropped but the connection is still active, then the
2158 * user name will be NULL in the output.
2159 * - used_in_xact - true if the connection is used in the current transaction.
2160 * - closed - true if the connection is closed.
2161 * - remote_backend_pid - process ID of the remote backend, on the foreign
2162 * server, handling the connection.
2163 *
2164 * No records are returned when there are no cached connections at all.
2165 */
2166static void
2168 enum pgfdwVersion api_version)
2169{
2170 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
2171 HASH_SEQ_STATUS scan;
2172 ConnCacheEntry *entry;
2173
2174 InitMaterializedSRF(fcinfo, 0);
2175
2176 /* If cache doesn't exist, we return no records */
2177 if (!ConnectionHash)
2178 return;
2179
2180 /* Check we have the expected number of output arguments */
2181 switch (rsinfo->setDesc->natts)
2182 {
2184 if (api_version != PGFDW_V1_1)
2185 elog(ERROR, "incorrect number of output arguments");
2186 break;
2188 if (api_version != PGFDW_V1_2)
2189 elog(ERROR, "incorrect number of output arguments");
2190 break;
2191 default:
2192 elog(ERROR, "incorrect number of output arguments");
2193 }
2194
2196 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
2197 {
2198 ForeignServer *server;
2200 bool nulls[POSTGRES_FDW_GET_CONNECTIONS_COLS] = {0};
2201 int i = 0;
2202
2203 /* We only look for open remote connections */
2204 if (!entry->conn)
2205 continue;
2206
2207 server = GetForeignServerExtended(entry->serverid, FSV_MISSING_OK);
2208
2209 /*
2210 * The foreign server may have been dropped in current explicit
2211 * transaction. It is not possible to drop the server from another
2212 * session when the connection associated with it is in use in the
2213 * current transaction, if tried so, the drop query in another session
2214 * blocks until the current transaction finishes.
2215 *
2216 * Even though the server is dropped in the current transaction, the
2217 * cache can still have associated active connection entry, say we
2218 * call such connections dangling. Since we can not fetch the server
2219 * name from system catalogs for dangling connections, instead we show
2220 * NULL value for server name in output.
2221 *
2222 * We could have done better by storing the server name in the cache
2223 * entry instead of server oid so that it could be used in the output.
2224 * But the server name in each cache entry requires 64 bytes of
2225 * memory, which is huge, when there are many cached connections and
2226 * the use case i.e. dropping the foreign server within the explicit
2227 * current transaction seems rare. So, we chose to show NULL value for
2228 * server name in output.
2229 *
2230 * Such dangling connections get closed either in next use or at the
2231 * end of current explicit transaction in pgfdw_xact_callback.
2232 */
2233 if (!server)
2234 {
2235 /*
2236 * If the server has been dropped in the current explicit
2237 * transaction, then this entry would have been invalidated in
2238 * pgfdw_inval_callback at the end of drop server command. Note
2239 * that this connection would not have been closed in
2240 * pgfdw_inval_callback because it is still being used in the
2241 * current explicit transaction. So, assert that here.
2242 */
2243 Assert(entry->conn && entry->xact_depth > 0 && entry->invalidated);
2244
2245 /* Show null, if no server name was found */
2246 nulls[i++] = true;
2247 }
2248 else
2249 values[i++] = CStringGetTextDatum(server->servername);
2250
2251 if (api_version >= PGFDW_V1_2)
2252 {
2253 HeapTuple tp;
2254
2255 /* Use the system cache to obtain the user mapping */
2256 tp = SearchSysCache1(USERMAPPINGOID, ObjectIdGetDatum(entry->key));
2257
2258 /*
2259 * Just like in the foreign server case, user mappings can also be
2260 * dropped in the current explicit transaction. Therefore, the
2261 * similar check as in the server case is required.
2262 */
2263 if (!HeapTupleIsValid(tp))
2264 {
2265 /*
2266 * If we reach here, this entry must have been invalidated in
2267 * pgfdw_inval_callback, same as in the server case.
2268 */
2269 Assert(entry->conn && entry->xact_depth > 0 &&
2270 entry->invalidated);
2271
2272 nulls[i++] = true;
2273 }
2274 else
2275 {
2276 Oid userid;
2277
2278 userid = ((Form_pg_user_mapping) GETSTRUCT(tp))->umuser;
2280 ReleaseSysCache(tp);
2281 }
2282 }
2283
2284 values[i++] = BoolGetDatum(!entry->invalidated);
2285
2286 if (api_version >= PGFDW_V1_2)
2287 {
2288 bool check_conn = PG_GETARG_BOOL(0);
2289
2290 /* Is this connection used in the current transaction? */
2291 values[i++] = BoolGetDatum(entry->xact_depth > 0);
2292
2293 /*
2294 * If a connection status check is requested and supported, return
2295 * whether the connection is closed. Otherwise, return NULL.
2296 */
2297 if (check_conn && pgfdw_conn_checkable())
2298 values[i++] = BoolGetDatum(pgfdw_conn_check(entry->conn) != 0);
2299 else
2300 nulls[i++] = true;
2301
2302 /* Return process ID of remote backend */
2303 values[i++] = Int32GetDatum(PQbackendPID(entry->conn));
2304 }
2305
2306 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
2307 }
2308}
2309
2310/*
2311 * List active foreign server connections.
2312 *
2313 * The SQL API of this function has changed multiple times, and will likely
2314 * do so again in future. To support the case where a newer version of this
2315 * loadable module is being used with an old SQL declaration of the function,
2316 * we continue to support the older API versions.
2317 */
2318Datum
2320{
2322
2324}
2325
2326Datum
2328{
2330
2332}
2333
2334/*
2335 * Disconnect the specified cached connections.
2336 *
2337 * This function discards the open connections that are established by
2338 * postgres_fdw from the local session to the foreign server with
2339 * the given name. Note that there can be multiple connections to
2340 * the given server using different user mappings. If the connections
2341 * are used in the current local transaction, they are not disconnected
2342 * and warning messages are reported. This function returns true
2343 * if it disconnects at least one connection, otherwise false. If no
2344 * foreign server with the given name is found, an error is reported.
2345 */
2346Datum
2348{
2349 ForeignServer *server;
2350 char *servername;
2351
2352 servername = text_to_cstring(PG_GETARG_TEXT_PP(0));
2353 server = GetForeignServerByName(servername, false);
2354
2356}
2357
2358/*
2359 * Disconnect all the cached connections.
2360 *
2361 * This function discards all the open connections that are established by
2362 * postgres_fdw from the local session to the foreign servers.
2363 * If the connections are used in the current local transaction, they are
2364 * not disconnected and warning messages are reported. This function
2365 * returns true if it disconnects at least one connection, otherwise false.
2366 */
2367Datum
2369{
2371}
2372
2373/*
2374 * Workhorse to disconnect cached connections.
2375 *
2376 * This function scans all the connection cache entries and disconnects
2377 * the open connections whose foreign server OID matches with
2378 * the specified one. If InvalidOid is specified, it disconnects all
2379 * the cached connections.
2380 *
2381 * This function emits a warning for each connection that's used in
2382 * the current transaction and doesn't close it. It returns true if
2383 * it disconnects at least one connection, otherwise false.
2384 *
2385 * Note that this function disconnects even the connections that are
2386 * established by other users in the same local session using different
2387 * user mappings. This leads even non-superuser to be able to close
2388 * the connections established by superusers in the same local session.
2389 *
2390 * XXX As of now we don't see any security risk doing this. But we should
2391 * set some restrictions on that, for example, prevent non-superuser
2392 * from closing the connections established by superusers even
2393 * in the same session?
2394 */
2395static bool
2397{
2398 HASH_SEQ_STATUS scan;
2399 ConnCacheEntry *entry;
2400 bool all = !OidIsValid(serverid);
2401 bool result = false;
2402
2403 /*
2404 * Connection cache hashtable has not been initialized yet in this
2405 * session, so return false.
2406 */
2407 if (!ConnectionHash)
2408 return false;
2409
2411 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
2412 {
2413 /* Ignore cache entry if no open connection right now. */
2414 if (!entry->conn)
2415 continue;
2416
2417 if (all || entry->serverid == serverid)
2418 {
2419 /*
2420 * Emit a warning because the connection to close is used in the
2421 * current transaction and cannot be disconnected right now.
2422 */
2423 if (entry->xact_depth > 0)
2424 {
2425 ForeignServer *server;
2426
2427 server = GetForeignServerExtended(entry->serverid,
2429
2430 if (!server)
2431 {
2432 /*
2433 * If the foreign server was dropped while its connection
2434 * was used in the current transaction, the connection
2435 * must have been marked as invalid by
2436 * pgfdw_inval_callback at the end of DROP SERVER command.
2437 */
2438 Assert(entry->invalidated);
2439
2441 (errmsg("cannot close dropped server connection because it is still in use")));
2442 }
2443 else
2445 (errmsg("cannot close connection for server \"%s\" because it is still in use",
2446 server->servername)));
2447 }
2448 else
2449 {
2450 elog(DEBUG3, "discarding connection %p", entry->conn);
2451 disconnect_pg_server(entry);
2452 result = true;
2453 }
2454 }
2455 }
2456
2457 return result;
2458}
2459
2460/*
2461 * Check if the remote server closed the connection.
2462 *
2463 * Returns 1 if the connection is closed, -1 if an error occurred,
2464 * and 0 if it's not closed or if the connection check is unavailable
2465 * on this platform.
2466 */
2467static int
2469{
2470 int sock = PQsocket(conn);
2471
2472 if (PQstatus(conn) != CONNECTION_OK || sock == -1)
2473 return -1;
2474
2475#if (defined(HAVE_POLL) && defined(POLLRDHUP))
2476 {
2477 struct pollfd input_fd;
2478 int result;
2479
2480 input_fd.fd = sock;
2481 input_fd.events = POLLRDHUP;
2482 input_fd.revents = 0;
2483
2484 do
2485 result = poll(&input_fd, 1, 0);
2486 while (result < 0 && errno == EINTR);
2487
2488 if (result < 0)
2489 return -1;
2490
2491 return (input_fd.revents &
2492 (POLLRDHUP | POLLHUP | POLLERR | POLLNVAL)) ? 1 : 0;
2493 }
2494#else
2495 return 0;
2496#endif
2497}
2498
2499/*
2500 * Check if connection status checking is available on this platform.
2501 *
2502 * Returns true if available, false otherwise.
2503 */
2504static bool
2506{
2507#if (defined(HAVE_POLL) && defined(POLLRDHUP))
2508 return true;
2509#else
2510 return false;
2511#endif
2512}
2513
2514/*
2515 * Ensure that require_auth and SCRAM keys are correctly set on values. SCRAM
2516 * keys used to pass-through are coming from the initial connection from the
2517 * client with the server.
2518 *
2519 * All required SCRAM options are set by postgres_fdw, so we just need to
2520 * ensure that these options are not overwritten by the user.
2521 */
2522static bool
2524{
2525 bool has_scram_server_key = false;
2526 bool has_scram_client_key = false;
2527 bool has_require_auth = false;
2528 bool has_scram_keys = false;
2529
2530 /*
2531 * Continue iterating even if we found the keys that we need to validate
2532 * to make sure that there is no other declaration of these keys that can
2533 * overwrite the first.
2534 */
2535 for (int i = 0; keywords[i] != NULL; i++)
2536 {
2537 if (strcmp(keywords[i], "scram_client_key") == 0)
2538 {
2539 if (values[i] != NULL && values[i][0] != '\0')
2540 has_scram_client_key = true;
2541 else
2542 has_scram_client_key = false;
2543 }
2544
2545 if (strcmp(keywords[i], "scram_server_key") == 0)
2546 {
2547 if (values[i] != NULL && values[i][0] != '\0')
2548 has_scram_server_key = true;
2549 else
2550 has_scram_server_key = false;
2551 }
2552
2553 if (strcmp(keywords[i], "require_auth") == 0)
2554 {
2555 if (values[i] != NULL && strcmp(values[i], "scram-sha-256") == 0)
2556 has_require_auth = true;
2557 else
2558 has_require_auth = false;
2559 }
2560 }
2561
2562 has_scram_keys = has_scram_client_key && has_scram_server_key && MyProcPort != NULL && MyProcPort->has_scram_keys;
2563
2564 return (has_scram_keys && has_require_auth);
2565}
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition: timestamp.c:1757
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1645
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1609
int pg_b64_enc_len(int srclen)
Definition: base64.c:224
int pg_b64_encode(const uint8 *src, int len, char *dst, int dstlen)
Definition: base64.c:49
bool be_gssapi_get_delegation(Port *port)
static Datum values[MAXATTR]
Definition: bootstrap.c:153
#define CStringGetTextDatum(s)
Definition: builtins.h:97
#define Min(x, y)
Definition: c.h:1004
uint32 SubTransactionId
Definition: c.h:662
#define pg_unreachable()
Definition: c.h:331
uint32_t uint32
Definition: c.h:539
#define OidIsValid(objectId)
Definition: c.h:775
Oid ConnCacheKey
Definition: connection.c:52
static unsigned int prep_stmt_number
Definition: connection.c:82
unsigned int GetCursorNumber(PGconn *conn)
Definition: connection.c:917
static bool UserMappingPasswordRequired(UserMapping *user)
Definition: connection.c:672
Datum postgres_fdw_get_connections(PG_FUNCTION_ARGS)
Definition: connection.c:2327
void do_sql_command(PGconn *conn, const char *sql)
Definition: connection.c:810
#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2
Definition: connection.c:2137
PGresult * pgfdw_exec_query(PGconn *conn, const char *query, PgFdwConnState *state)
Definition: connection.c:946
static void pgfdw_finish_pre_subcommit_cleanup(List *pending_entries, int curlevel)
Definition: connection.c:1939
static void disconnect_pg_server(ConnCacheEntry *entry)
Definition: connection.c:658
void ReleaseConnection(PGconn *conn)
Definition: connection.c:896
PGconn * GetConnection(UserMapping *user, bool will_prep_stmt, PgFdwConnState **state)
Definition: connection.c:205
static uint32 pgfdw_we_get_result
Definition: connection.c:90
PG_FUNCTION_INFO_V1(postgres_fdw_get_connections)
static bool UseScramPassthrough(ForeignServer *server, UserMapping *user)
Definition: connection.c:688
#define RETRY_CANCEL_TIMEOUT
Definition: connection.c:104
PGresult * pgfdw_get_result(PGconn *conn)
Definition: connection.c:963
void pgfdw_report_error(PGresult *res, PGconn *conn, const char *sql)
Definition: connection.c:987
static bool pgfdw_cancel_query_begin(PGconn *conn, TimestampTz endtime)
Definition: connection.c:1463
static void pgfdw_finish_abort_cleanup(List *pending_entries, List *cancel_requested, bool toplevel)
Definition: connection.c:1973
static void pgfdw_reset_xact_state(ConnCacheEntry *entry, bool toplevel)
Definition: connection.c:1385
static int pgfdw_conn_check(PGconn *conn)
Definition: connection.c:2468
#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1
Definition: connection.c:2136
static void configure_remote_session(PGconn *conn)
Definition: connection.c:772
static bool pgfdw_cancel_query_end(PGconn *conn, TimestampTz endtime, TimestampTz retrycanceltime, bool consume_input)
Definition: connection.c:1476
static bool xact_got_connection
Definition: connection.c:85
#define POSTGRES_FDW_GET_CONNECTIONS_COLS
Definition: connection.c:2138
struct ConnCacheEntry ConnCacheEntry
void pgfdw_report(int elevel, PGresult *res, PGconn *conn, const char *sql)
Definition: connection.c:994
Datum postgres_fdw_disconnect_all(PG_FUNCTION_ARGS)
Definition: connection.c:2368
static void do_sql_command_end(PGconn *conn, const char *sql, bool consume_input)
Definition: connection.c:824
#define CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel)
Definition: connection.c:107
static bool pgfdw_conn_checkable(void)
Definition: connection.c:2505
static uint32 pgfdw_we_cleanup_result
Definition: connection.c:88
static bool pgfdw_abort_cleanup_begin(ConnCacheEntry *entry, bool toplevel, List **pending_entries, List **cancel_requested)
Definition: connection.c:1807
static HTAB * ConnectionHash
Definition: connection.c:78
static bool pgfdw_exec_cleanup_query_end(PGconn *conn, const char *query, TimestampTz endtime, bool consume_input, bool ignore_errors)
Definition: connection.c:1568
static unsigned int cursor_number
Definition: connection.c:81
static bool pgfdw_has_required_scram_options(const char **keywords, const char **values)
Definition: connection.c:2523
static void make_new_connection(ConnCacheEntry *entry, UserMapping *user)
Definition: connection.c:368
static void pgfdw_security_check(const char **keywords, const char **values, UserMapping *user, PGconn *conn)
Definition: connection.c:434
Datum postgres_fdw_disconnect(PG_FUNCTION_ARGS)
Definition: connection.c:2347
static void pgfdw_subxact_callback(SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid, void *arg)
Definition: connection.c:1198
static PGconn * connect_pg_server(ForeignServer *server, UserMapping *user)
Definition: connection.c:481
static bool pgfdw_exec_cleanup_query(PGconn *conn, const char *query, bool ignore_errors)
Definition: connection.c:1530
unsigned int GetPrepStmtNumber(PGconn *conn)
Definition: connection.c:931
Datum postgres_fdw_get_connections_1_2(PG_FUNCTION_ARGS)
Definition: connection.c:2319
static bool pgfdw_exec_cleanup_query_begin(PGconn *conn, const char *query)
Definition: connection.c:1550
static void pgfdw_reject_incomplete_xact_state_change(ConnCacheEntry *entry)
Definition: connection.c:1361
static void check_conn_params(const char **keywords, const char **values, UserMapping *user)
Definition: connection.c:720
static uint32 pgfdw_we_connect
Definition: connection.c:89
static void pgfdw_inval_callback(Datum arg, int cacheid, uint32 hashvalue)
Definition: connection.c:1311
static void pgfdw_xact_callback(XactEvent event, void *arg)
Definition: connection.c:1048
static void postgres_fdw_get_connections_internal(FunctionCallInfo fcinfo, enum pgfdwVersion api_version)
Definition: connection.c:2167
static void pgfdw_report_internal(int elevel, PGresult *res, PGconn *conn, const char *sql)
Definition: connection.c:1001
#define CONNECTION_CLEANUP_TIMEOUT
Definition: connection.c:97
static void do_sql_command_begin(PGconn *conn, const char *sql)
Definition: connection.c:817
static void pgfdw_abort_cleanup(ConnCacheEntry *entry, bool toplevel)
Definition: connection.c:1733
static bool pgfdw_get_cleanup_result(PGconn *conn, TimestampTz endtime, TimestampTz retrycanceltime, PGresult **result, bool *timed_out)
Definition: connection.c:1628
static void begin_remote_xact(ConnCacheEntry *entry)
Definition: connection.c:853
pgfdwVersion
Definition: connection.c:122
@ PGFDW_V1_1
Definition: connection.c:123
@ PGFDW_V1_2
Definition: connection.c:124
static bool pgfdw_cancel_query(PGconn *conn)
Definition: connection.c:1430
static void pgfdw_finish_pre_commit_cleanup(List *pending_entries)
Definition: connection.c:1865
static bool disconnect_cached_connections(Oid serverid)
Definition: connection.c:2396
int ExtractConnectionOptions(List *defelems, const char **keywords, const char **values)
Definition: option.c:414
char * pgfdw_application_name
Definition: option.c:46
char * process_pgfdw_appname(const char *appname)
Definition: option.c:491
int64 TimestampTz
Definition: timestamp.h:39
bool defGetBoolean(DefElem *def)
Definition: define.c:94
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:952
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:358
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1415
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1380
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1161
void FreeErrorData(ErrorData *edata)
Definition: elog.c:1826
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1234
int errdetail(const char *fmt,...)
Definition: elog.c:1207
ErrorData * CopyErrorData(void)
Definition: elog.c:1754
void FlushErrorState(void)
Definition: elog.c:1875
int errhint(const char *fmt,...)
Definition: elog.c:1321
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
bool in_error_recursion_trouble(void)
Definition: elog.c:294
#define PG_RE_THROW()
Definition: elog.h:405
#define errcontext
Definition: elog.h:198
#define DEBUG3
Definition: elog.h:28
#define PG_TRY(...)
Definition: elog.h:372
#define WARNING
Definition: elog.h:36
#define PG_END_TRY(...)
Definition: elog.h:397
#define ERROR
Definition: elog.h:39
#define PG_CATCH(...)
Definition: elog.h:382
#define MAKE_SQLSTATE(ch1, ch2, ch3, ch4, ch5)
Definition: elog.h:56
#define elog(elevel,...)
Definition: elog.h:226
#define ereport(elevel,...)
Definition: elog.h:150
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:7669
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:7624
int PQconnectionUsedPassword(const PGconn *conn)
Definition: fe-connect.c:7747
int PQconnectionUsedGSSAPI(const PGconn *conn)
Definition: fe-connect.c:7758
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:7616
PQnoticeReceiver PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
Definition: fe-connect.c:7843
int PQbackendPID(const PGconn *conn)
Definition: fe-connect.c:7715
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:7679
int PQsocket(const PGconn *conn)
Definition: fe-connect.c:7705
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1995
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1427
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2042
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:359
ForeignServer * GetForeignServerByName(const char *srvname, bool missing_ok)
Definition: foreign.c:183
ForeignServer * GetForeignServer(Oid serverid)
Definition: foreign.c:112
ForeignServer * GetForeignServerExtended(Oid serverid, bits16 flags)
Definition: foreign.c:124
#define MappingUserName(userid)
Definition: foreign.h:20
#define FSV_MISSING_OK
Definition: foreign.h:61
void InitMaterializedSRF(FunctionCallInfo fcinfo, bits32 flags)
Definition: funcapi.c:76
struct Port * MyProcPort
Definition: globals.c:51
struct Latch * MyLatch
Definition: globals.c:63
Assert(PointerIsAligned(start, uint64))
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
Definition: htup_details.h:728
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1812
int i
Definition: isn.c:77
static const JsonPathKeyword keywords[]
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:223
void ResetLatch(Latch *latch)
Definition: latch.c:374
static const char * libpqsrv_cancel(PGconn *conn, TimestampTz endtime)
static PGconn * libpqsrv_connect_params(const char *const *keywords, const char *const *values, int expand_dbname, uint32 wait_event_info)
static void libpqsrv_notice_receiver(void *arg, const PGresult *res)
static void libpqsrv_disconnect(PGconn *conn)
static PGresult * libpqsrv_get_result_last(PGconn *conn, uint32 wait_event_info)
#define PQgetResult
Definition: libpq-be-fe.h:246
#define PQclear
Definition: libpq-be-fe.h:245
#define PQresultErrorField
Definition: libpq-be-fe.h:249
#define PQresultStatus
Definition: libpq-be-fe.h:247
@ CONNECTION_BAD
Definition: libpq-fe.h:85
@ CONNECTION_OK
Definition: libpq-fe.h:84
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:125
@ PQTRANS_IDLE
Definition: libpq-fe.h:147
@ PQTRANS_ACTIVE
Definition: libpq-fe.h:148
List * lappend(List *list, void *datum)
Definition: list.c:339
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1268
void pfree(void *pointer)
Definition: mcxt.c:1594
void * palloc0(Size size)
Definition: mcxt.c:1395
char * pchomp(const char *in)
Definition: mcxt.c:1787
void * palloc(Size size)
Definition: mcxt.c:1365
MemoryContext CurrentMemoryContext
Definition: mcxt.c:160
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
void * arg
const void size_t len
#define lfirst(lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
static char * user
Definition: pg_regress.c:119
FormData_pg_user_mapping * Form_pg_user_mapping
#define snprintf
Definition: port.h:239
static Datum BoolGetDatum(bool X)
Definition: postgres.h:112
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:262
uint64_t Datum
Definition: postgres.h:70
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:222
#define InvalidOid
Definition: postgres_ext.h:37
unsigned int Oid
Definition: postgres_ext.h:32
#define PG_DIAG_MESSAGE_HINT
Definition: postgres_ext.h:60
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:57
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:58
#define PG_DIAG_MESSAGE_DETAIL
Definition: postgres_ext.h:59
#define PG_DIAG_CONTEXT
Definition: postgres_ext.h:64
void process_pending_request(AsyncRequest *areq)
tree ctl
Definition: radixtree.h:1838
PGconn * conn
Definition: streamutil.c:52
PGconn * conn
Definition: connection.c:57
bool have_prep_stmt
Definition: connection.c:61
PgFdwConnState state
Definition: connection.c:72
bool invalidated
Definition: connection.c:66
ConnCacheKey key
Definition: connection.c:56
bool parallel_commit
Definition: connection.c:64
uint32 server_hashvalue
Definition: connection.c:70
uint32 mapping_hashvalue
Definition: connection.c:71
bool keep_connections
Definition: connection.c:67
bool parallel_abort
Definition: connection.c:65
bool changing_xact_state
Definition: connection.c:63
char * defname
Definition: parsenodes.h:841
int sqlerrcode
Definition: elog.h:431
List * options
Definition: foreign.h:42
char * servername
Definition: foreign.h:39
Oid serverid
Definition: foreign.h:36
Definition: dynahash.c:222
Definition: pg_list.h:54
AsyncRequest * pendingAreq
Definition: postgres_fdw.h:139
uint8 scram_ServerKey[SCRAM_MAX_KEY_LEN]
Definition: libpq-be.h:187
bool has_scram_keys
Definition: libpq-be.h:188
uint8 scram_ClientKey[SCRAM_MAX_KEY_LEN]
Definition: libpq-be.h:186
TupleDesc setDesc
Definition: execnodes.h:364
Tuplestorestate * setResult
Definition: execnodes.h:363
Definition: regguts.h:323
bool superuser_arg(Oid roleid)
Definition: superuser.c:56
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:264
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:220
#define GetSysCacheHashValue1(cacheId, key1)
Definition: syscache.h:118
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition: tuplestore.c:784
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:85
char * text_to_cstring(const text *t)
Definition: varlena.c:214
uint32 WaitEventExtensionNew(const char *wait_event_name)
Definition: wait_event.c:163
#define WL_SOCKET_READABLE
Definition: waiteventset.h:35
#define WL_TIMEOUT
Definition: waiteventset.h:37
#define WL_EXIT_ON_PM_DEATH
Definition: waiteventset.h:39
#define WL_LATCH_SET
Definition: waiteventset.h:34
#define EINTR
Definition: win32_port.h:364
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:929
void RegisterXactCallback(XactCallback callback, void *arg)
Definition: xact.c:3816
void RegisterSubXactCallback(SubXactCallback callback, void *arg)
Definition: xact.c:3876
SubXactEvent
Definition: xact.h:142
@ SUBXACT_EVENT_PRE_COMMIT_SUB
Definition: xact.h:146
@ SUBXACT_EVENT_ABORT_SUB
Definition: xact.h:145
XactEvent
Definition: xact.h:128
@ XACT_EVENT_PRE_PREPARE
Definition: xact.h:136
@ XACT_EVENT_COMMIT
Definition: xact.h:129
@ XACT_EVENT_PARALLEL_PRE_COMMIT
Definition: xact.h:135
@ XACT_EVENT_PARALLEL_COMMIT
Definition: xact.h:130
@ XACT_EVENT_ABORT
Definition: xact.h:131
@ XACT_EVENT_PRE_COMMIT
Definition: xact.h:134
@ XACT_EVENT_PARALLEL_ABORT
Definition: xact.h:132
@ XACT_EVENT_PREPARE
Definition: xact.h:133
#define IsolationIsSerializable()
Definition: xact.h:53