1/*-------------------------------------------------------------------------
4 * Connection management functions for postgres_fdw
6 * Portions Copyright (c) 2012-2025, PostgreSQL Global Development Group
9 * contrib/postgres_fdw/connection.c
11 *-------------------------------------------------------------------------
38 * Connection cache hash table entry
40 * The lookup key in this hash table is the user mapping OID. We use just one
41 * connection per user mapping ID, which ensures that all the scans use the
42 * same snapshot during a query. Using the user mapping OID rather than
43 * the foreign server OID + user OID avoids creating multiple connections when
44 * the public user mapping applies to all user OIDs.
46 * The "conn" pointer can be NULL if we don't currently have a live connection.
47 * When we do have a connection, xact_depth tracks the current depth of
48 * transactions and subtransactions open on the remote side. We need to issue
49 * commands at the same nesting depth on the remote as we're executing at
50 * ourselves, so that rolling back a subtransaction will kill the right
51 * queries and not the wrong ones.
58 PGconn *
conn;
/* connection to foreign server, or NULL */
59 /* Remaining fields are invalid when conn is NULL: */
60 int xact_depth;
/* 0 = no xact open, 1 = main xact open, 2 =
61 * one level of subxact open, etc */
63 bool have_error;
/* have any subxacts aborted in this xact? */
70 Oid serverid;
/* foreign server OID used to get server name */
77 * Connection cache (initialized on first use)
81/* for assigning cursor numbers and prepared statement numbers */
85/* tracks whether any work is needed in callback functions */
88/* custom wait event values, retrieved from shared memory */
94 * Milliseconds to wait to cancel an in-progress query or execute a cleanup
95 * query; if it takes longer than 30 seconds to do these, we assume the
98 #define CONNECTION_CLEANUP_TIMEOUT 30000
101 * Milliseconds to wait before issuing another cancel request. This covers
102 * the race condition where the remote session ignored our cancel request
103 * because it arrived while idle.
105 #define RETRY_CANCEL_TIMEOUT 1000
107/* Macro for constructing abort command to be sent */
108 #define CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel) \
111 snprintf((sql), sizeof(sql), \
112 "ABORT TRANSACTION"); \
114 snprintf((sql), sizeof(sql), \
115 "ROLLBACK TO SAVEPOINT s%d; RELEASE SAVEPOINT s%d", \
116 (entry)->xact_depth, (entry)->xact_depth); \
120 * Extension version number, for supporting older extension versions' objects
136/* prototypes of private functions */
170 PGresult **result,
bool *timed_out);
173 List **pending_entries,
174 List **cancel_requested);
179 List *cancel_requested,
193 * Get a PGconn which can be used to execute queries on the remote PostgreSQL
194 * server with the user's authorization. A new connection is established
195 * if we don't already have a suitable one, and a transaction is opened at
196 * the right subtransaction nesting depth if we didn't do that already.
198 * will_prep_stmt must be true if caller intends to create any prepared
199 * statements. Since those don't go away automatically at transaction end
200 * (not even on error), we need this flag to cue manual cleanup.
202 * If state is not NULL, *state receives the per-connection state associated
214 /* First time through, initialize connection cache hashtable */
230 * Register some callback functions that manage connection cleanup.
231 * This should be done just once in each backend.
241 /* Set flag that we did GetConnection during the current transaction */
244 /* Create hash key for the entry. Assume no pad bytes in key struct */
248 * Find or create cached entry for requested connection.
254 * We need only clear "conn" here; remaining fields will be filled
255 * later when "conn" is set.
260 /* Reject further use of connections which failed abort cleanup. */
264 * If the connection needs to be remade due to invalidation, disconnect as
265 * soon as we're out of all transactions.
269 elog(
DEBUG3,
"closing connection %p for option changes to take effect",
275 * If cache entry doesn't have a connection, we have to establish a new
276 * connection. (If connect_pg_server throws an error, the cache entry
277 * will remain in a valid empty state, ie conn == NULL.)
279 if (entry->
conn == NULL)
283 * We check the health of the cached connection here when using it. In
284 * cases where we're out of all transactions, if a broken connection is
285 * detected, we try to reestablish a new connection later.
289 /* Process a pending asynchronous request if any. */
292 /* Start a new transaction or subtransaction if needed. */
301 * Determine whether to try to reestablish the connection.
303 * After a broken connection is detected in libpq, any error other
304 * than connection failure (e.g., out-of-memory) can be thrown
305 * somewhere between return from libpq and the expected ereport() call
306 * in pgfdw_report_error(). In this case, since PQstatus() indicates
307 * CONNECTION_BAD, checking only PQstatus() causes the false detection
308 * of connection failure. To avoid this, we also verify that the
309 * error's sqlstate is ERRCODE_CONNECTION_FAILURE. Note that also
310 * checking only the sqlstate can cause another false detection
311 * because pgfdw_report_error() may report ERRCODE_CONNECTION_FAILURE
312 * for any libpq-originated error condition.
314 if (errdata->
sqlerrcode != ERRCODE_CONNECTION_FAILURE ||
322 /* Clean up the error state */
332 * If a broken connection is detected, disconnect it, reestablish a new
333 * connection and retry a new remote transaction. If connection failure is
334 * reported again, we give up getting a connection.
341 (
errmsg_internal(
"could not start remote transaction on connection %p",
345 elog(
DEBUG3,
"closing connection %p to reestablish a new one",
354 /* Remember if caller will prepare statements */
357 /* If caller needs access to the per-connection state, return it. */
365 * Reset all transient state fields in the cached connection entry and
366 * establish new connection to the remote server.
376 /* Reset all transient state fields, to be sure all are clean */
389 memset(&entry->
state, 0,
sizeof(entry->
state));
392 * Determine whether to keep the connection that we're about to make here
393 * open even after the transaction using it ends, so that the subsequent
394 * transactions can re-use it.
396 * By default, all the connections to any foreign servers are kept open.
398 * Also determine whether to commit/abort (sub)transactions opened on the
399 * remote server in parallel at (sub)transaction end, which is disabled by
402 * Note: it's enough to determine these only when making a new connection
403 * because if these settings for it are changed, it will be closed and
413 if (strcmp(def->
defname,
"keep_connections") == 0)
415 else if (strcmp(def->
defname,
"parallel_commit") == 0)
417 else if (strcmp(def->
defname,
"parallel_abort") == 0)
421 /* Now try to make the connection */
424 elog(
DEBUG3,
"new postgres_fdw connection %p for server \"%s\" (user mapping oid %u, userid %u)",
429 * Check that non-superuser has used password or delegated credentials
430 * to establish connection; otherwise, he's piggybacking on the
431 * postgres server's user identity. See also dblink_security_check()
432 * in contrib/dblink and check_conn_params.
437 /* Superusers bypass the check */
442 /* Connected via GSSAPI with delegated credentials- all good. */
447 /* Ok if superuser set PW required false. */
451 /* Connected via PW, with PW required true, and provided non-empty PW. */
454 /* ok if params contain a non-empty password */
463 * Ok if SCRAM pass-through is being used and all required SCRAM options
464 * are set correctly. If pgfdw_has_required_scram_options returns true we
465 * assume that UseScramPassthrough is also true since SCRAM options are
466 * only set when UseScramPassthrough is enabled.
472 (
errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
473 errmsg(
"password or GSSAPI delegated credentials required"),
474 errdetail(
"Non-superuser cannot connect if the server does not request a password or use GSSAPI with delegated credentials."),
475 errhint(
"Target server's authentication method must be changed or password_required=false set in the user mapping attributes.")));
479 * Connect to remote server using specified server and user mapping properties.
487 * Use PG_TRY block to ensure closing connection on error.
493 char *appname = NULL;
497 * Construct connection params from generic options of ForeignServer
498 * and UserMapping. (Some of them might not be libpq options, in
499 * which case we'll just waste a few array slots.) Add 4 extra slots
500 * for application_name, fallback_application_name, client_encoding,
501 * end marker, and 3 extra slots for scram keys and required scram
502 * pass-through options.
515 * Use pgfdw_application_name as application_name if set.
517 * PQconnectdbParams() processes the parameter arrays from start to
518 * end. If any key word is repeated, the last value is used. Therefore
519 * note that pgfdw_application_name must be added to the arrays after
520 * options of ForeignServer are, so that it can override
521 * application_name set in ForeignServer.
531 * Search the parameter arrays to find application_name setting, and
532 * replace escape sequences in it with status information if found.
533 * The arrays are searched backwards because the last value is used if
534 * application_name is repeatedly set.
536 for (
int i = n - 1;
i >= 0;
i--)
538 if (strcmp(
keywords[
i],
"application_name") == 0 &&
542 * Use this application_name setting if it's not empty string
543 * even after any escape sequences in it are replaced.
546 if (appname[0] !=
'0円')
553 * This empty application_name is not used, so we set
554 * values[i] to NULL and keep searching the array to find the
563 /* Use "postgres_fdw" as fallback_application_name */
564 keywords[n] =
"fallback_application_name";
565 values[n] =
"postgres_fdw";
568 /* Set client_encoding so that libpq can convert encoding properly. */
573 /* Add required SCRAM pass-through connection options if it's enabled. */
581 /* don't forget the zero-terminator */
587 elog(
ERROR,
"could not encode SCRAM client key");
592 /* don't forget the zero-terminator */
598 elog(
ERROR,
"could not encode SCRAM server key");
602 * Require scram-sha-256 to ensure that no other auth method is
603 * used when connecting with foreign server.
606 values[n] =
"scram-sha-256";
612 /* Verify the set of connection parameters. */
615 /* first time, allocate or get the custom wait event */
619 /* OK to make connection */
621 false,
/* expand_dbname */
626 (
errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
627 errmsg(
"could not connect to server \"%s\"",
632 "received message via remote connection");
634 /* Perform post-connection security checks. */
637 /* Prepare new session for use */
656 * Disconnect any open connection for a connection cache entry.
661 if (entry->
conn != NULL)
669 * Return true if the password_required is defined and false for this user
670 * mapping, otherwise false. The mapping has been pre-validated.
677 foreach(cell,
user->options)
681 if (strcmp(def->
defname,
"password_required") == 0)
697 if (strcmp(def->
defname,
"use_scram_passthrough") == 0)
701 foreach(cell,
user->options)
705 if (strcmp(def->
defname,
"use_scram_passthrough") == 0)
713 * For non-superusers, insist that the connstr specify a password or that the
714 * user provided their own GSSAPI delegated credentials. This
715 * prevents a password from being picked up from .pgpass, a service file, the
716 * environment, etc. We don't want the postgres user's passwords,
717 * certificates, etc to be accessible to non-superusers. (See also
718 * dblink_connstr_check in contrib/dblink.)
725 /* no check required if superuser */
730 /* ok if the user provided their own delegated credentials */
735 /* ok if params contain a non-empty password */
742 /* ok if the superuser explicitly said so at user mapping creation time */
747 * Ok if SCRAM pass-through is being used and all required scram options
748 * are set correctly. If pgfdw_has_required_scram_options returns true we
749 * assume that UseScramPassthrough is also true since SCRAM options are
750 * only set when UseScramPassthrough is enabled.
756 (
errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
757 errmsg(
"password or GSSAPI delegated credentials required"),
758 errdetail(
"Non-superusers must delegate GSSAPI credentials, provide a password, or enable SCRAM pass-through in user mapping.")));
762 * Issue SET commands to make sure remote session is configured properly.
764 * We do this just once at connection, assuming nothing will change the
765 * values later. Since we'll never send volatile function calls to the
766 * remote, there shouldn't be any way to break this assumption from our end.
767 * It's possible to think of ways to break it at the remote end, eg making
768 * a foreign table point to a view that includes a set_config call ---
769 * but once you admit the possibility of a malicious view definition,
770 * there are any number of ways to break things.
777 /* Force the search path to contain only pg_catalog (see deparse.c) */
781 * Set remote timezone; this is basically just cosmetic, since all
782 * transmitted and returned timestamptzs should specify a zone explicitly
783 * anyway. However it makes the regression test outputs more predictable.
785 * We don't risk setting remote zone equal to ours, since the remote
786 * server might use a different timezone database. Instead, use GMT
787 * (quoted, because very old servers are picky about case). That's
788 * guaranteed to work regardless of the remote's timezone database,
789 * because pg_tzset() hard-wires it (at least in PG 9.2 and later).
794 * Set values needed to ensure unambiguous data output from remote. (This
795 * logic should match what pg_dump does. See also set_transmission_modes
796 * in postgres_fdw.c.)
799 if (remoteversion >= 80400)
801 if (remoteversion >= 90000)
808 * Convenience subroutine to issue a non-data-returning SQL command to remote
830 * If requested, consume whatever data is available from the socket. (Note
831 * that if all data is available, this allows pgfdw_get_result to call
832 * PQgetResult without forcing the overhead of WaitLatchOrSocket, which
833 * would be large compared to the overhead of PQconsumeInput.)
844 * Start remote transaction or subtransaction, if needed.
846 * Note that we always use at least REPEATABLE READ in the remote session.
847 * This is so that, if a query initiates multiple scans of the same or
848 * different foreign tables, we will get snapshot-consistent results from
849 * those scans. A disadvantage is that we can't provide sane emulation of
850 * READ COMMITTED behavior --- it would be nice if we had some other way to
851 * control which remote queries share a snapshot.
858 /* Start main transaction if we haven't yet */
863 elog(
DEBUG3,
"starting remote transaction on connection %p",
867 sql =
"START TRANSACTION ISOLATION LEVEL SERIALIZABLE";
869 sql =
"START TRANSACTION ISOLATION LEVEL REPEATABLE READ";
877 * If we're in a subtransaction, stack up savepoints to match our level.
878 * This ensures we can rollback just the desired effects when a
879 * subtransaction aborts.
894 * Release connection reference count created by calling GetConnection.
900 * Currently, we don't actually track connection references because all
901 * cleanup is managed on a transaction or subtransaction basis instead. So
902 * there's nothing to do here.
907 * Assign a "unique" number for a cursor.
909 * These really only need to be unique per connection within a transaction.
910 * For the moment we ignore the per-connection point and assign them across
911 * all connections in the transaction, but we ask for the connection to be
912 * supplied in case we want to refine that.
914 * Note that even if wraparound happens in a very long transaction, actual
915 * collisions are highly improbable; just be sure to use %u not %d to print.
924 * Assign a "unique" number for a prepared statement.
926 * This works much like GetCursorNumber, except that we never reset the counter
927 * within a session. That's because we can't be 100% sure we've gotten rid
928 * of all prepared statements on all connections, and it's not really worth
929 * increasing the risk of prepared-statement name collisions by resetting.
938 * Submit a query and wait for the result.
940 * Since we don't use non-blocking mode, this can't process interrupts while
941 * pushing the query text to the server. That risk is relatively small, so we
942 * ignore that for now.
944 * Caller is responsible for the error handling on the result.
949 /* First, process a pending asynchronous request, if any. */
959 * Wrap libpqsrv_get_result_last(), adding wait event.
961 * Caller is responsible for the error handling on the result.
970 * Report an error we got from the remote server.
972 * Callers should use pgfdw_report_error() to throw an error, or use
973 * pgfdw_report() for lesser message levels. (We make this distinction
974 * so that pgfdw_report_error() can be marked noreturn.)
976 * res: PGresult containing the error (might be NULL)
977 * conn: connection we did the query on
978 * sql: NULL, or text of remote command we tried to execute
980 * If "res" is not NULL, it'll be PQclear'ed here (unless we throw error,
981 * in which case memory context cleanup will clear it eventually).
983 * Note: callers that choose not to throw ERROR for a remote error are
984 * responsible for making sure that the associated ConnCacheEntry gets
985 * marked with have_error = true.
997 Assert(elevel <
ERROR);
/* use pgfdw_report_error for that */
1019 sqlstate = ERRCODE_CONNECTION_FAILURE;
1022 * If we don't get a message from the PGresult, try the PGconn. This is
1023 * needed because for connection-level failures, PQgetResult may just
1024 * return NULL, not a PGresult at all.
1026 if (message_primary == NULL)
1031 (message_primary != NULL && message_primary[0] !=
'0円') ?
1033 errmsg(
"could not obtain message string for remote error"),
1035 message_hint ?
errhint(
"%s", message_hint) : 0,
1036 message_context ?
errcontext(
"%s", message_context) : 0,
1037 sql ?
errcontext(
"remote SQL command: %s", sql) : 0));
1042 * pgfdw_xact_callback --- cleanup at main-transaction end.
1044 * This runs just late enough that it must not enter user-defined code
1045 * locally. (Entering such code on the remote side is fine. Its remote
1046 * COMMIT TRANSACTION may run deferred triggers.)
1056 /* Quick exit if no connections were touched in this transaction. */
1061 * Scan all connection cache entries to find open remote transactions, and
1069 /* Ignore cache entry if no open connection right now */
1070 if (entry->
conn == NULL)
1073 /* If it has an open remote transaction, try to close it */
1076 elog(
DEBUG3,
"closing remote transaction on connection %p",
1085 * If abort cleanup previously failed for this connection,
1086 * we can't issue any more commands against it.
1090 /* Commit all remote transactions during pre-commit */
1095 pending_entries =
lappend(pending_entries, entry);
1102 * If there were any errors in subtransactions, and we
1103 * made prepared statements, do a DEALLOCATE ALL to make
1104 * sure we get rid of all prepared statements. This is
1105 * annoying and not terribly bulletproof, but it's
1106 * probably not worth trying harder.
1108 * DEALLOCATE ALL only exists in 8.3 and later, so this
1109 * constrains how old a server postgres_fdw can
1110 * communicate with. We intentionally ignore errors in
1111 * the DEALLOCATE, so that we can hobble along to some
1112 * extent with older servers (leaking prepared statements
1113 * as we go; but we don't really support update operations
1128 * We disallow any remote transactions, since it's not
1129 * very reasonable to hold them open until the prepared
1130 * transaction is committed. For the moment, throw error
1131 * unconditionally; later we might allow read-only cases.
1132 * Note that the error will cause us to come right back
1133 * here with event == XACT_EVENT_ABORT, so we'll clean up
1134 * the connection state at that point.
1137 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1138 errmsg(
"cannot PREPARE a transaction that has operated on postgres_fdw foreign tables")));
1143 /* Pre-commit should have closed the open transaction */
1144 elog(
ERROR,
"missed cleaning up connection during pre-commit");
1148 /* Rollback all remote transactions during abort */
1162 /* Reset state to show we're out of a transaction */
1166 /* If there are any pending connections, finish cleaning them up */
1167 if (pending_entries || cancel_requested)
1185 * Regardless of the event type, we can now mark ourselves as out of the
1186 * transaction. (Note: if we are here during PRE_COMMIT or PRE_PREPARE,
1187 * this saves a useless scan of the hashtable during COMMIT or PREPARE.)
1191 /* Also reset cursor numbering for next transaction */
1196 * pgfdw_subxact_callback --- cleanup at subtransaction end.
1208 /* Nothing to do at subxact start, nor after commit. */
1213 /* Quick exit if no connections were touched in this transaction. */
1218 * Scan all connection cache entries to find open remote subtransactions
1219 * of the current level, and close them.
1228 * We only care about connections with open remote subtransactions of
1229 * the current level.
1235 elog(
ERROR,
"missed cleaning up remote subtransaction at level %d",
1241 * If abort cleanup previously failed for this connection, we
1242 * can't issue any more commands against it.
1246 /* Commit all remote subtransactions during pre-commit */
1247 snprintf(sql,
sizeof(sql),
"RELEASE SAVEPOINT s%d", curlevel);
1252 pending_entries =
lappend(pending_entries, entry);
1260 /* Rollback all remote subtransactions during abort */
1272 /* OK, we're outta that level of subtransaction */
1276 /* If there are any pending connections, finish cleaning them up */
1277 if (pending_entries || cancel_requested)
1294 * Connection invalidation callback function
1296 * After a change to a pg_foreign_server or pg_user_mapping catalog entry,
1297 * close connections depending on that entry immediately if current transaction
1298 * has not used those connections yet. Otherwise, mark those connections as
1299 * invalid and then make pgfdw_xact_callback() close them at the end of current
1300 * transaction, since they cannot be closed in the midst of the transaction
1301 * using them. Closed connections will be remade at the next opportunity if
1304 * Although most cache invalidation callbacks blow away all the related stuff
1305 * regardless of the given hashvalue, connections are expensive enough that
1306 * it's worth trying to avoid that.
1308 * NB: We could avoid unnecessary disconnection more strictly by examining
1309 * individual option values, but it seems too much effort for the gain.
1317 Assert(cacheid == FOREIGNSERVEROID || cacheid == USERMAPPINGOID);
1319 /* ConnectionHash must exist already, if we're registered */
1323 /* Ignore invalid entries */
1324 if (entry->
conn == NULL)
1327 /* hashvalue == 0 means a cache reset, must clear all state */
1328 if (hashvalue == 0 ||
1329 (cacheid == FOREIGNSERVEROID &&
1331 (cacheid == USERMAPPINGOID &&
1335 * Close the connection immediately if it's not used yet in this
1336 * transaction. Otherwise mark it as invalid so that
1337 * pgfdw_xact_callback() can close it at the end of this
1352 * Raise an error if the given connection cache entry is marked as being
1353 * in the middle of an xact state change. This should be called at which no
1354 * such change is expected to be in progress; if one is found to be in
1355 * progress, it means that we aborted in the middle of a previous state change
1356 * and now don't know what the remote transaction state actually is.
1357 * Such connections can't safely be further used. Re-establishing the
1358 * connection would change the snapshot and roll back any writes already
1359 * performed, so that's not an option, either. Thus, we must abort.
1366 /* nothing to do for inactive entries and entries of sane state */
1370 /* make sure this entry is inactive */
1373 /* find server name to be shown in the message below */
1377 (
errcode(ERRCODE_CONNECTION_EXCEPTION),
1378 errmsg(
"connection to server \"%s\" was lost",
1383 * Reset state to show we're out of a (sub)transaction.
1390 /* Reset state to show we're out of a transaction */
1394 * If the connection isn't in a good idle state, it is marked as
1395 * invalid or keep_connections option of its server is disabled, then
1396 * discard it to recover. Next GetConnection will open a new
1411 /* Reset state to show we're out of a subtransaction */
1417 * Cancel the currently-in-progress query (whose query text we do not have)
1418 * and ignore the result. Returns true if we successfully cancel the query
1419 * and discard any pending result, and false if not.
1421 * It's not a huge problem if we throw an ERROR here, but if we get into error
1422 * recursion trouble, we'll end up slamming the connection shut, which will
1423 * necessitate failing the entire toplevel transaction even if subtransactions
1424 * were used. Try to use WARNING where we can.
1426 * XXX: if the query was one sent by fetch_more_data_begin(), we could get the
1427 * query text from the pendingAreq saved in the per-connection state, then
1428 * report the query using it.
1438 * If it takes too long to cancel the query and discard the result, assume
1439 * the connection is dead.
1444 * Also, lose patience and re-issue the cancel request after a little bit.
1445 * (This serves to close some race conditions.)
1455 * Submit a cancel request to the given connection, waiting only until
1458 * We sleep interruptibly until we receive confirmation that the cancel
1459 * request has been accepted, and if it is, return true; if the timeout
1460 * lapses without that, or the request fails for whatever reason, return
1468 if (errormsg != NULL)
1470 errcode(ERRCODE_CONNECTION_FAILURE),
1471 errmsg(
"could not send cancel request: %s", errormsg));
1473 return errormsg == NULL;
1484 * If requested, consume whatever data is available from the socket. (Note
1485 * that if all data is available, this allows pgfdw_get_cleanup_result to
1486 * call PQgetResult without forcing the overhead of WaitLatchOrSocket,
1487 * which would be large compared to the overhead of PQconsumeInput.)
1492 (
errcode(ERRCODE_CONNECTION_FAILURE),
1493 errmsg(
"could not get result of cancel request: %s",
1498 /* Get and discard the result of the query. */
1500 &result, &timed_out))
1504 (
errmsg(
"could not get result of cancel request due to timeout")));
1507 (
errcode(ERRCODE_CONNECTION_FAILURE),
1508 errmsg(
"could not get result of cancel request: %s",
1519 * Submit a query during (sub)abort cleanup and wait up to 30 seconds for the
1520 * result. If the query is executed without error, the return value is true.
1521 * If the query is executed successfully but returns an error, the return
1522 * value is true if and only if ignore_errors is set. If the query can't be
1523 * sent or times out, the return value is false.
1525 * It's not a huge problem if we throw an ERROR here, but if we get into error
1526 * recursion trouble, we'll end up slamming the connection shut, which will
1527 * necessitate failing the entire toplevel transaction even if subtransactions
1528 * were used. Try to use WARNING where we can.
1536 * If it takes too long to execute a cleanup query, assume the connection
1537 * is dead. It's fairly likely that this is why we aborted in the first
1538 * place (e.g. statement timeout, user cancel), so the timeout shouldn't
1547 false, ignore_errors);
1556 * Submit a query. Since we don't use non-blocking mode, this also can
1557 * block. But its risk is relatively small, so we ignore that for now.
1579 * If requested, consume whatever data is available from the socket. (Note
1580 * that if all data is available, this allows pgfdw_get_cleanup_result to
1581 * call PQgetResult without forcing the overhead of WaitLatchOrSocket,
1582 * which would be large compared to the overhead of PQconsumeInput.)
1590 /* Get the result of the query. */
1595 (
errmsg(
"could not get query result due to timeout"),
1596 errcontext(
"remote SQL command: %s", query)));
1603 /* Issue a warning if not successful. */
1607 return ignore_errors;
1615 * Get, during abort cleanup, the result of a query that is in progress.
1616 * This might be a query that is being interrupted by a cancel request or by
1617 * transaction abort, or it might be a query that was initiated as part of
1618 * transaction abort to get the remote side back to the appropriate state.
1620 * endtime is the time at which we should give up and assume the remote side
1621 * is dead. retrycanceltime is the time at which we should issue a fresh
1622 * cancel request (pass the same value as endtime if this is not wanted).
1624 * Returns true if the timeout expired or connection trouble occurred,
1625 * false otherwise. Sets *result except in case of a true result.
1626 * Sets *timed_out to true only when the timeout expired.
1634 bool failed =
false;
1650 /* If timeout has expired, give up. */
1658 /* If we need to re-issue the cancel request, do that. */
1659 if (
now >= retrycanceltime)
1661 /* We ignore failure to issue the repeated request. */
1664 /* Recompute "now" in case that took measurable time. */
1667 /* Adjust re-cancel timeout in increasing steps. */
1670 canceldelta += canceldelta;
1673 /* If timeout has expired, give up, else get sleep time. */
1677 if (cur_timeout <= 0)
1684 /* first time, allocate or get the custom wait event */
1688 /* Sleep until there's something to do */
1698 /* Data available in socket? */
1703 /* connection trouble */
1712 break;
/* query is complete */
1726 * Abort remote transaction or subtransaction.
1728 * "toplevel" should be set to true if toplevel (main) transaction is
1729 * rollbacked, false otherwise.
1731 * Set entry->changing_xact_state to false on success, true on failure.
1739 * Don't try to clean up the connection if we're already in error
1740 * recursion trouble.
1746 * If connection is already unsalvageable, don't touch it further.
1752 * Mark this connection as in the process of changing transaction state.
1756 /* Assume we might have lost track of prepared statements */
1760 * If a command has been submitted to the remote server by using an
1761 * asynchronous execution function, the command might not have yet
1762 * completed. Check to see if a command is still being processed by the
1763 * remote server, and if so, request cancellation of the command.
1767 return;
/* Unable to cancel running query */
1771 return;
/* Unable to abort remote (sub)transaction */
1779 return;
/* Trouble clearing prepared statements */
1786 * If pendingAreq of the per-connection state is not NULL, it means that
1787 * an asynchronous fetch begun by fetch_more_data_begin() was not done
1788 * successfully and thus the per-connection state was not reset in
1789 * fetch_more_data(); in that case reset the per-connection state here.
1792 memset(&entry->
state, 0,
sizeof(entry->
state));
1794 /* Disarm changing_xact_state if it all worked */
1799 * Like pgfdw_abort_cleanup, submit an abort command or cancel request, but
1800 * don't wait for the result.
1802 * Returns true if the abort command or cancel request is successfully issued,
1803 * false otherwise. If the abort command is successfully issued, the given
1804 * connection cache entry is appended to *pending_entries. Otherwise, if the
1805 * cancel request is successfully issued, it is appended to *cancel_requested.
1809 List **pending_entries,
List **cancel_requested)
1812 * Don't try to clean up the connection if we're already in error
1813 * recursion trouble.
1819 * If connection is already unsalvageable, don't touch it further.
1825 * Mark this connection as in the process of changing transaction state.
1829 /* Assume we might have lost track of prepared statements */
1833 * If a command has been submitted to the remote server by using an
1834 * asynchronous execution function, the command might not have yet
1835 * completed. Check to see if a command is still being processed by the
1836 * remote server, and if so, request cancellation of the command.
1845 return false;
/* Unable to cancel running query */
1846 *cancel_requested =
lappend(*cancel_requested, entry);
1854 return false;
/* Unable to abort remote transaction */
1855 *pending_entries =
lappend(*pending_entries, entry);
1862 * Finish pre-commit cleanup of connections on each of which we've sent a
1863 * COMMIT command to the remote server.
1875 * Get the result of the COMMIT command for each of the pending entries
1877 foreach(lc, pending_entries)
1884 * We might already have received the result on the socket, so pass
1885 * consume_input=true to try to consume it first
1890 /* Do a DEALLOCATE ALL in parallel if needed */
1893 /* Ignore errors (see notes in pgfdw_xact_callback) */
1896 pending_deallocs =
lappend(pending_deallocs, entry);
1906 /* No further work if no pending entries */
1907 if (!pending_deallocs)
1911 * Get the result of the DEALLOCATE command for each of the pending
1914 foreach(lc, pending_deallocs)
1920 /* Ignore errors (see notes in pgfdw_xact_callback) */
1924 /* Stop if the connection is lost (else we'll loop infinitely) */
1936 * Finish pre-subcommit cleanup of connections on each of which we've sent a
1937 * RELEASE command to the remote server.
1949 * Get the result of the RELEASE command for each of the pending entries
1951 snprintf(sql,
sizeof(sql),
"RELEASE SAVEPOINT s%d", curlevel);
1952 foreach(lc, pending_entries)
1959 * We might already have received the result on the socket, so pass
1960 * consume_input=true to try to consume it first
1970 * Finish abort cleanup of connections on each of which we've sent an abort
1971 * command or cancel request to the remote server.
1981 * For each of the pending cancel requests (if any), get and discard the
1982 * result of the query, and submit an abort command to the remote server.
1984 if (cancel_requested)
1986 foreach(lc, cancel_requested)
1997 * Set end time. You might think we should do this before issuing
1998 * cancel request like in normal mode, but that is problematic,
1999 * because if, for example, it took longer than 30 seconds to
2000 * process the first few entries in the cancel_requested list, it
2001 * would cause a timeout error when processing each of the
2002 * remaining entries in the list, leading to slamming that entry's
2011 retrycanceltime,
true))
2013 /* Unable to cancel running query */
2018 /* Send an abort command in parallel if needed */
2022 /* Unable to abort remote (sub)transaction */
2026 pending_entries =
lappend(pending_entries, entry);
2030 /* No further work if no pending entries */
2031 if (!pending_entries)
2035 * Get the result of the abort command for each of the pending entries
2037 foreach(lc, pending_entries)
2046 * Set end time. We do this now, not before issuing the command like
2047 * in normal mode, for the same reason as for the cancel_requested
2057 /* Unable to abort remote (sub)transaction */
2064 /* Do a DEALLOCATE ALL in parallel if needed */
2070 /* Trouble clearing prepared statements */
2074 pending_deallocs =
lappend(pending_deallocs, entry);
2081 /* Reset the per-connection state if needed */
2083 memset(&entry->
state, 0,
sizeof(entry->
state));
2085 /* We're done with this entry; unset the changing_xact_state flag */
2090 /* No further work if no pending entries */
2091 if (!pending_deallocs)
2096 * Get the result of the DEALLOCATE command for each of the pending
2099 foreach(lc, pending_deallocs)
2109 * Set end time. We do this now, not before issuing the command like
2110 * in normal mode, for the same reason as for the cancel_requested
2117 endtime,
true,
true))
2119 /* Trouble clearing prepared statements */
2126 /* Reset the per-connection state if needed */
2128 memset(&entry->
state, 0,
sizeof(entry->
state));
2130 /* We're done with this entry; unset the changing_xact_state flag */
2136/* Number of output arguments (columns) for various API versions */
2137 #define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1 2
2138 #define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2 6
2139 #define POSTGRES_FDW_GET_CONNECTIONS_COLS 6 /* maximum of above */
2142 * Internal function used by postgres_fdw_get_connections variants.
2144 * For API version 1.1, this function takes no input parameter and
2145 * returns a set of records with the following values:
2147 * - server_name - server name of active connection. In case the foreign server
2148 * is dropped but still the connection is active, then the server name will
2149 * be NULL in output.
2150 * - valid - true/false representing whether the connection is valid or not.
2151 * Note that connections can become invalid in pgfdw_inval_callback.
2153 * For API version 1.2 and later, this function takes an input parameter
2154 * to check a connection status and returns the following
2155 * additional values along with the four values from version 1.1:
2157 * - user_name - the local user name of the active connection. In case the
2158 * user mapping is dropped but the connection is still active, then the
2159 * user name will be NULL in the output.
2160 * - used_in_xact - true if the connection is used in the current transaction.
2161 * - closed - true if the connection is closed.
2162 * - remote_backend_pid - process ID of the remote backend, on the foreign
2163 * server, handling the connection.
2165 * No records are returned when there are no cached connections at all.
2177 /* If cache doesn't exist, we return no records */
2181 /* Check we have the expected number of output arguments */
2186 elog(
ERROR,
"incorrect number of output arguments");
2190 elog(
ERROR,
"incorrect number of output arguments");
2193 elog(
ERROR,
"incorrect number of output arguments");
2204 /* We only look for open remote connections */
2211 * The foreign server may have been dropped in current explicit
2212 * transaction. It is not possible to drop the server from another
2213 * session when the connection associated with it is in use in the
2214 * current transaction, if tried so, the drop query in another session
2215 * blocks until the current transaction finishes.
2217 * Even though the server is dropped in the current transaction, the
2218 * cache can still have associated active connection entry, say we
2219 * call such connections dangling. Since we can not fetch the server
2220 * name from system catalogs for dangling connections, instead we show
2221 * NULL value for server name in output.
2223 * We could have done better by storing the server name in the cache
2224 * entry instead of server oid so that it could be used in the output.
2225 * But the server name in each cache entry requires 64 bytes of
2226 * memory, which is huge, when there are many cached connections and
2227 * the use case i.e. dropping the foreign server within the explicit
2228 * current transaction seems rare. So, we chose to show NULL value for
2229 * server name in output.
2231 * Such dangling connections get closed either in next use or at the
2232 * end of current explicit transaction in pgfdw_xact_callback.
2237 * If the server has been dropped in the current explicit
2238 * transaction, then this entry would have been invalidated in
2239 * pgfdw_inval_callback at the end of drop server command. Note
2240 * that this connection would not have been closed in
2241 * pgfdw_inval_callback because it is still being used in the
2242 * current explicit transaction. So, assert that here.
2244 Assert(entry->conn && entry->xact_depth > 0 && entry->invalidated);
2246 /* Show null, if no server name was found */
2256 /* Use the system cache to obtain the user mapping */
2260 * Just like in the foreign server case, user mappings can also be
2261 * dropped in the current explicit transaction. Therefore, the
2262 * similar check as in the server case is required.
2267 * If we reach here, this entry must have been invalidated in
2268 * pgfdw_inval_callback, same as in the server case.
2270 Assert(entry->conn && entry->xact_depth > 0 &&
2271 entry->invalidated);
2291 /* Is this connection used in the current transaction? */
2295 * If a connection status check is requested and supported, return
2296 * whether the connection is closed. Otherwise, return NULL.
2303 /* Return process ID of remote backend */
2312 * List active foreign server connections.
2314 * The SQL API of this function has changed multiple times, and will likely
2315 * do so again in future. To support the case where a newer version of this
2316 * loadable module is being used with an old SQL declaration of the function,
2317 * we continue to support the older API versions.
2336 * Disconnect the specified cached connections.
2338 * This function discards the open connections that are established by
2339 * postgres_fdw from the local session to the foreign server with
2340 * the given name. Note that there can be multiple connections to
2341 * the given server using different user mappings. If the connections
2342 * are used in the current local transaction, they are not disconnected
2343 * and warning messages are reported. This function returns true
2344 * if it disconnects at least one connection, otherwise false. If no
2345 * foreign server with the given name is found, an error is reported.
2360 * Disconnect all the cached connections.
2362 * This function discards all the open connections that are established by
2363 * postgres_fdw from the local session to the foreign servers.
2364 * If the connections are used in the current local transaction, they are
2365 * not disconnected and warning messages are reported. This function
2366 * returns true if it disconnects at least one connection, otherwise false.
2375 * Workhorse to disconnect cached connections.
2377 * This function scans all the connection cache entries and disconnects
2378 * the open connections whose foreign server OID matches with
2379 * the specified one. If InvalidOid is specified, it disconnects all
2380 * the cached connections.
2382 * This function emits a warning for each connection that's used in
2383 * the current transaction and doesn't close it. It returns true if
2384 * it disconnects at least one connection, otherwise false.
2386 * Note that this function disconnects even the connections that are
2387 * established by other users in the same local session using different
2388 * user mappings. This leads even non-superuser to be able to close
2389 * the connections established by superusers in the same local session.
2391 * XXX As of now we don't see any security risk doing this. But we should
2392 * set some restrictions on that, for example, prevent non-superuser
2393 * from closing the connections established by superusers even
2394 * in the same session?
2402 bool result =
false;
2405 * Connection cache hashtable has not been initialized yet in this
2406 * session, so return false.
2414 /* Ignore cache entry if no open connection right now. */
2418 if (all || entry->
serverid == serverid)
2421 * Emit a warning because the connection to close is used in the
2422 * current transaction and cannot be disconnected right now.
2434 * If the foreign server was dropped while its connection
2435 * was used in the current transaction, the connection
2436 * must have been marked as invalid by
2437 * pgfdw_inval_callback at the end of DROP SERVER command.
2442 (
errmsg(
"cannot close dropped server connection because it is still in use")));
2446 (
errmsg(
"cannot close connection for server \"%s\" because it is still in use",
2462 * Check if the remote server closed the connection.
2464 * Returns 1 if the connection is closed, -1 if an error occurred,
2465 * and 0 if it's not closed or if the connection check is unavailable
2476#if (defined(HAVE_POLL) && defined(POLLRDHUP))
2478 struct pollfd input_fd;
2482 input_fd.events = POLLRDHUP;
2483 input_fd.revents = 0;
2486 result = poll(&input_fd, 1, 0);
2487 while (result < 0 && errno ==
EINTR);
2492 return (input_fd.revents &
2493 (POLLRDHUP | POLLHUP | POLLERR | POLLNVAL)) ? 1 : 0;
2501 * Check if connection status checking is available on this platform.
2503 * Returns true if available, false otherwise.
2508#if (defined(HAVE_POLL) && defined(POLLRDHUP))
2516 * Ensure that require_auth and SCRAM keys are correctly set on values. SCRAM
2517 * keys used to pass-through are coming from the initial connection from the
2518 * client with the server.
2520 * All required SCRAM options are set by postgres_fdw, so we just need to
2521 * ensure that these options are not overwritten by the user.
2526 bool has_scram_server_key =
false;
2527 bool has_scram_client_key =
false;
2528 bool has_require_auth =
false;
2529 bool has_scram_keys =
false;
2532 * Continue iterating even if we found the keys that we need to validate
2533 * to make sure that there is no other declaration of these keys that can
2534 * overwrite the first.
2538 if (strcmp(
keywords[
i],
"scram_client_key") == 0)
2541 has_scram_client_key =
true;
2543 has_scram_client_key =
false;
2546 if (strcmp(
keywords[
i],
"scram_server_key") == 0)
2549 has_scram_server_key =
true;
2551 has_scram_server_key =
false;
2554 if (strcmp(
keywords[
i],
"require_auth") == 0)
2556 if (
values[
i] != NULL && strcmp(
values[
i],
"scram-sha-256") == 0)
2557 has_require_auth =
true;
2559 has_require_auth =
false;
2565 return (has_scram_keys && has_require_auth);
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
TimestampTz GetCurrentTimestamp(void)
Datum now(PG_FUNCTION_ARGS)
int pg_b64_enc_len(int srclen)
int pg_b64_encode(const uint8 *src, int len, char *dst, int dstlen)
bool be_gssapi_get_delegation(Port *port)
static Datum values[MAXATTR]
#define CStringGetTextDatum(s)
#define OidIsValid(objectId)
static unsigned int prep_stmt_number
unsigned int GetCursorNumber(PGconn *conn)
static bool UserMappingPasswordRequired(UserMapping *user)
Datum postgres_fdw_get_connections(PG_FUNCTION_ARGS)
void do_sql_command(PGconn *conn, const char *sql)
#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2
PGresult * pgfdw_exec_query(PGconn *conn, const char *query, PgFdwConnState *state)
static void pgfdw_finish_pre_subcommit_cleanup(List *pending_entries, int curlevel)
static void disconnect_pg_server(ConnCacheEntry *entry)
void ReleaseConnection(PGconn *conn)
PGconn * GetConnection(UserMapping *user, bool will_prep_stmt, PgFdwConnState **state)
static uint32 pgfdw_we_get_result
PG_FUNCTION_INFO_V1(postgres_fdw_get_connections)
static bool UseScramPassthrough(ForeignServer *server, UserMapping *user)
#define RETRY_CANCEL_TIMEOUT
PGresult * pgfdw_get_result(PGconn *conn)
void pgfdw_report_error(PGresult *res, PGconn *conn, const char *sql)
static bool pgfdw_cancel_query_begin(PGconn *conn, TimestampTz endtime)
static void pgfdw_finish_abort_cleanup(List *pending_entries, List *cancel_requested, bool toplevel)
static void pgfdw_reset_xact_state(ConnCacheEntry *entry, bool toplevel)
static int pgfdw_conn_check(PGconn *conn)
#define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1
static void configure_remote_session(PGconn *conn)
static bool pgfdw_cancel_query_end(PGconn *conn, TimestampTz endtime, TimestampTz retrycanceltime, bool consume_input)
static bool xact_got_connection
#define POSTGRES_FDW_GET_CONNECTIONS_COLS
struct ConnCacheEntry ConnCacheEntry
void pgfdw_report(int elevel, PGresult *res, PGconn *conn, const char *sql)
Datum postgres_fdw_disconnect_all(PG_FUNCTION_ARGS)
static void do_sql_command_end(PGconn *conn, const char *sql, bool consume_input)
#define CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel)
static bool pgfdw_conn_checkable(void)
static uint32 pgfdw_we_cleanup_result
static bool pgfdw_abort_cleanup_begin(ConnCacheEntry *entry, bool toplevel, List **pending_entries, List **cancel_requested)
static HTAB * ConnectionHash
static bool pgfdw_exec_cleanup_query_end(PGconn *conn, const char *query, TimestampTz endtime, bool consume_input, bool ignore_errors)
static unsigned int cursor_number
static bool pgfdw_has_required_scram_options(const char **keywords, const char **values)
static void make_new_connection(ConnCacheEntry *entry, UserMapping *user)
static void pgfdw_security_check(const char **keywords, const char **values, UserMapping *user, PGconn *conn)
Datum postgres_fdw_disconnect(PG_FUNCTION_ARGS)
static void pgfdw_subxact_callback(SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid, void *arg)
static PGconn * connect_pg_server(ForeignServer *server, UserMapping *user)
static bool pgfdw_exec_cleanup_query(PGconn *conn, const char *query, bool ignore_errors)
unsigned int GetPrepStmtNumber(PGconn *conn)
Datum postgres_fdw_get_connections_1_2(PG_FUNCTION_ARGS)
static bool pgfdw_exec_cleanup_query_begin(PGconn *conn, const char *query)
static void pgfdw_reject_incomplete_xact_state_change(ConnCacheEntry *entry)
static void check_conn_params(const char **keywords, const char **values, UserMapping *user)
static uint32 pgfdw_we_connect
static void pgfdw_inval_callback(Datum arg, int cacheid, uint32 hashvalue)
static void pgfdw_xact_callback(XactEvent event, void *arg)
static void postgres_fdw_get_connections_internal(FunctionCallInfo fcinfo, enum pgfdwVersion api_version)
static void pgfdw_report_internal(int elevel, PGresult *res, PGconn *conn, const char *sql)
#define CONNECTION_CLEANUP_TIMEOUT
static void do_sql_command_begin(PGconn *conn, const char *sql)
static void pgfdw_abort_cleanup(ConnCacheEntry *entry, bool toplevel)
static bool pgfdw_get_cleanup_result(PGconn *conn, TimestampTz endtime, TimestampTz retrycanceltime, PGresult **result, bool *timed_out)
static void begin_remote_xact(ConnCacheEntry *entry)
static bool pgfdw_cancel_query(PGconn *conn)
static void pgfdw_finish_pre_commit_cleanup(List *pending_entries)
static bool disconnect_cached_connections(Oid serverid)
int ExtractConnectionOptions(List *defelems, const char **keywords, const char **values)
char * pgfdw_application_name
char * process_pgfdw_appname(const char *appname)
bool defGetBoolean(DefElem *def)
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
void * hash_seq_search(HASH_SEQ_STATUS *status)
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
int errmsg_internal(const char *fmt,...)
void FreeErrorData(ErrorData *edata)
int errdetail_internal(const char *fmt,...)
int errdetail(const char *fmt,...)
ErrorData * CopyErrorData(void)
void FlushErrorState(void)
int errhint(const char *fmt,...)
int errcode(int sqlerrcode)
int errmsg(const char *fmt,...)
bool in_error_recursion_trouble(void)
#define MAKE_SQLSTATE(ch1, ch2, ch3, ch4, ch5)
#define ereport(elevel,...)
int PQserverVersion(const PGconn *conn)
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
int PQconnectionUsedPassword(const PGconn *conn)
int PQconnectionUsedGSSAPI(const PGconn *conn)
ConnStatusType PQstatus(const PGconn *conn)
PQnoticeReceiver PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
int PQbackendPID(const PGconn *conn)
char * PQerrorMessage(const PGconn *conn)
int PQsocket(const PGconn *conn)
int PQconsumeInput(PGconn *conn)
int PQsendQuery(PGconn *conn, const char *query)
int PQisBusy(PGconn *conn)
#define PG_GETARG_TEXT_PP(n)
#define PG_GETARG_BOOL(n)
#define PG_RETURN_BOOL(x)
ForeignServer * GetForeignServerByName(const char *srvname, bool missing_ok)
ForeignServer * GetForeignServer(Oid serverid)
ForeignServer * GetForeignServerExtended(Oid serverid, bits16 flags)
#define MappingUserName(userid)
void InitMaterializedSRF(FunctionCallInfo fcinfo, bits32 flags)
Assert(PointerIsAligned(start, uint64))
#define HeapTupleIsValid(tuple)
static void * GETSTRUCT(const HeapTupleData *tuple)
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
static const JsonPathKeyword keywords[]
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
void ResetLatch(Latch *latch)
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 PQresultErrorField
List * lappend(List *list, void *datum)
const char * GetDatabaseEncodingName(void)
void pfree(void *pointer)
void * palloc0(Size size)
char * pchomp(const char *in)
MemoryContext CurrentMemoryContext
#define CHECK_FOR_INTERRUPTS()
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
static int list_length(const List *l)
FormData_pg_user_mapping * Form_pg_user_mapping
static Datum BoolGetDatum(bool X)
static Datum ObjectIdGetDatum(Oid X)
static Datum Int32GetDatum(int32 X)
#define PG_DIAG_MESSAGE_HINT
#define PG_DIAG_MESSAGE_PRIMARY
#define PG_DIAG_MESSAGE_DETAIL
void process_pending_request(AsyncRequest *areq)
AsyncRequest * pendingAreq
uint8 scram_ServerKey[SCRAM_MAX_KEY_LEN]
uint8 scram_ClientKey[SCRAM_MAX_KEY_LEN]
Tuplestorestate * setResult
bool superuser_arg(Oid roleid)
void ReleaseSysCache(HeapTuple tuple)
HeapTuple SearchSysCache1(int cacheId, Datum key1)
#define GetSysCacheHashValue1(cacheId, key1)
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
#define TimestampTzPlusMilliseconds(tz, ms)
char * text_to_cstring(const text *t)
uint32 WaitEventExtensionNew(const char *wait_event_name)
#define WL_SOCKET_READABLE
#define WL_EXIT_ON_PM_DEATH
int GetCurrentTransactionNestLevel(void)
void RegisterXactCallback(XactCallback callback, void *arg)
void RegisterSubXactCallback(SubXactCallback callback, void *arg)
@ SUBXACT_EVENT_PRE_COMMIT_SUB
@ SUBXACT_EVENT_ABORT_SUB
@ XACT_EVENT_PARALLEL_PRE_COMMIT
@ XACT_EVENT_PARALLEL_COMMIT
@ XACT_EVENT_PARALLEL_ABORT
#define IsolationIsSerializable()