Header And Logo

PostgreSQL
| The world's most advanced open source database.

connection.c

Go to the documentation of this file.
00001 /*-------------------------------------------------------------------------
00002  *
00003  * connection.c
00004  *        Connection management functions for postgres_fdw
00005  *
00006  * Portions Copyright (c) 2012-2013, PostgreSQL Global Development Group
00007  *
00008  * IDENTIFICATION
00009  *        contrib/postgres_fdw/connection.c
00010  *
00011  *-------------------------------------------------------------------------
00012  */
00013 #include "postgres.h"
00014 
00015 #include "postgres_fdw.h"
00016 
00017 #include "access/xact.h"
00018 #include "mb/pg_wchar.h"
00019 #include "miscadmin.h"
00020 #include "utils/hsearch.h"
00021 #include "utils/memutils.h"
00022 
00023 
00024 /*
00025  * Connection cache hash table entry
00026  *
00027  * The lookup key in this hash table is the foreign server OID plus the user
00028  * mapping OID.  (We use just one connection per user per foreign server,
00029  * so that we can ensure all scans use the same snapshot during a query.)
00030  *
00031  * The "conn" pointer can be NULL if we don't currently have a live connection.
00032  * When we do have a connection, xact_depth tracks the current depth of
00033  * transactions and subtransactions open on the remote side.  We need to issue
00034  * commands at the same nesting depth on the remote as we're executing at
00035  * ourselves, so that rolling back a subtransaction will kill the right
00036  * queries and not the wrong ones.
00037  */
00038 typedef struct ConnCacheKey
00039 {
00040     Oid         serverid;       /* OID of foreign server */
00041     Oid         userid;         /* OID of local user whose mapping we use */
00042 } ConnCacheKey;
00043 
00044 typedef struct ConnCacheEntry
00045 {
00046     ConnCacheKey key;           /* hash key (must be first) */
00047     PGconn     *conn;           /* connection to foreign server, or NULL */
00048     int         xact_depth;     /* 0 = no xact open, 1 = main xact open, 2 =
00049                                  * one level of subxact open, etc */
00050     bool        have_prep_stmt; /* have we prepared any stmts in this xact? */
00051     bool        have_error;     /* have any subxacts aborted in this xact? */
00052 } ConnCacheEntry;
00053 
00054 /*
00055  * Connection cache (initialized on first use)
00056  */
00057 static HTAB *ConnectionHash = NULL;
00058 
00059 /* for assigning cursor numbers and prepared statement numbers */
00060 static unsigned int cursor_number = 0;
00061 static unsigned int prep_stmt_number = 0;
00062 
00063 /* tracks whether any work is needed in callback functions */
00064 static bool xact_got_connection = false;
00065 
00066 /* prototypes of private functions */
00067 static PGconn *connect_pg_server(ForeignServer *server, UserMapping *user);
00068 static void check_conn_params(const char **keywords, const char **values);
00069 static void configure_remote_session(PGconn *conn);
00070 static void do_sql_command(PGconn *conn, const char *sql);
00071 static void begin_remote_xact(ConnCacheEntry *entry);
00072 static void pgfdw_xact_callback(XactEvent event, void *arg);
00073 static void pgfdw_subxact_callback(SubXactEvent event,
00074                        SubTransactionId mySubid,
00075                        SubTransactionId parentSubid,
00076                        void *arg);
00077 
00078 
00079 /*
00080  * Get a PGconn which can be used to execute queries on the remote PostgreSQL
00081  * server with the user's authorization.  A new connection is established
00082  * if we don't already have a suitable one, and a transaction is opened at
00083  * the right subtransaction nesting depth if we didn't do that already.
00084  *
00085  * will_prep_stmt must be true if caller intends to create any prepared
00086  * statements.  Since those don't go away automatically at transaction end
00087  * (not even on error), we need this flag to cue manual cleanup.
00088  *
00089  * XXX Note that caching connections theoretically requires a mechanism to
00090  * detect change of FDW objects to invalidate already established connections.
00091  * We could manage that by watching for invalidation events on the relevant
00092  * syscaches.  For the moment, though, it's not clear that this would really
00093  * be useful and not mere pedantry.  We could not flush any active connections
00094  * mid-transaction anyway.
00095  */
00096 PGconn *
00097 GetConnection(ForeignServer *server, UserMapping *user,
00098               bool will_prep_stmt)
00099 {
00100     bool        found;
00101     ConnCacheEntry *entry;
00102     ConnCacheKey key;
00103 
00104     /* First time through, initialize connection cache hashtable */
00105     if (ConnectionHash == NULL)
00106     {
00107         HASHCTL     ctl;
00108 
00109         MemSet(&ctl, 0, sizeof(ctl));
00110         ctl.keysize = sizeof(ConnCacheKey);
00111         ctl.entrysize = sizeof(ConnCacheEntry);
00112         ctl.hash = tag_hash;
00113         /* allocate ConnectionHash in the cache context */
00114         ctl.hcxt = CacheMemoryContext;
00115         ConnectionHash = hash_create("postgres_fdw connections", 8,
00116                                      &ctl,
00117                                    HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
00118 
00119         /*
00120          * Register some callback functions that manage connection cleanup.
00121          * This should be done just once in each backend.
00122          */
00123         RegisterXactCallback(pgfdw_xact_callback, NULL);
00124         RegisterSubXactCallback(pgfdw_subxact_callback, NULL);
00125     }
00126 
00127     /* Set flag that we did GetConnection during the current transaction */
00128     xact_got_connection = true;
00129 
00130     /* Create hash key for the entry.  Assume no pad bytes in key struct */
00131     key.serverid = server->serverid;
00132     key.userid = user->userid;
00133 
00134     /*
00135      * Find or create cached entry for requested connection.
00136      */
00137     entry = hash_search(ConnectionHash, &key, HASH_ENTER, &found);
00138     if (!found)
00139     {
00140         /* initialize new hashtable entry (key is already filled in) */
00141         entry->conn = NULL;
00142         entry->xact_depth = 0;
00143         entry->have_prep_stmt = false;
00144         entry->have_error = false;
00145     }
00146 
00147     /*
00148      * We don't check the health of cached connection here, because it would
00149      * require some overhead.  Broken connection will be detected when the
00150      * connection is actually used.
00151      */
00152 
00153     /*
00154      * If cache entry doesn't have a connection, we have to establish a new
00155      * connection.  (If connect_pg_server throws an error, the cache entry
00156      * will be left in a valid empty state.)
00157      */
00158     if (entry->conn == NULL)
00159     {
00160         entry->xact_depth = 0;  /* just to be sure */
00161         entry->have_prep_stmt = false;
00162         entry->have_error = false;
00163         entry->conn = connect_pg_server(server, user);
00164         elog(DEBUG3, "new postgres_fdw connection %p for server \"%s\"",
00165              entry->conn, server->servername);
00166     }
00167 
00168     /*
00169      * Start a new transaction or subtransaction if needed.
00170      */
00171     begin_remote_xact(entry);
00172 
00173     /* Remember if caller will prepare statements */
00174     entry->have_prep_stmt |= will_prep_stmt;
00175 
00176     return entry->conn;
00177 }
00178 
00179 /*
00180  * Connect to remote server using specified server and user mapping properties.
00181  */
00182 static PGconn *
00183 connect_pg_server(ForeignServer *server, UserMapping *user)
00184 {
00185     PGconn     *volatile conn = NULL;
00186 
00187     /*
00188      * Use PG_TRY block to ensure closing connection on error.
00189      */
00190     PG_TRY();
00191     {
00192         const char **keywords;
00193         const char **values;
00194         int         n;
00195 
00196         /*
00197          * Construct connection params from generic options of ForeignServer
00198          * and UserMapping.  (Some of them might not be libpq options, in
00199          * which case we'll just waste a few array slots.)  Add 3 extra slots
00200          * for fallback_application_name, client_encoding, end marker.
00201          */
00202         n = list_length(server->options) + list_length(user->options) + 3;
00203         keywords = (const char **) palloc(n * sizeof(char *));
00204         values = (const char **) palloc(n * sizeof(char *));
00205 
00206         n = 0;
00207         n += ExtractConnectionOptions(server->options,
00208                                       keywords + n, values + n);
00209         n += ExtractConnectionOptions(user->options,
00210                                       keywords + n, values + n);
00211 
00212         /* Use "postgres_fdw" as fallback_application_name. */
00213         keywords[n] = "fallback_application_name";
00214         values[n] = "postgres_fdw";
00215         n++;
00216 
00217         /* Set client_encoding so that libpq can convert encoding properly. */
00218         keywords[n] = "client_encoding";
00219         values[n] = GetDatabaseEncodingName();
00220         n++;
00221 
00222         keywords[n] = values[n] = NULL;
00223 
00224         /* verify connection parameters and make connection */
00225         check_conn_params(keywords, values);
00226 
00227         conn = PQconnectdbParams(keywords, values, false);
00228         if (!conn || PQstatus(conn) != CONNECTION_OK)
00229         {
00230             char       *connmessage;
00231             int         msglen;
00232 
00233             /* libpq typically appends a newline, strip that */
00234             connmessage = pstrdup(PQerrorMessage(conn));
00235             msglen = strlen(connmessage);
00236             if (msglen > 0 && connmessage[msglen - 1] == '\n')
00237                 connmessage[msglen - 1] = '\0';
00238             ereport(ERROR,
00239                (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
00240                 errmsg("could not connect to server \"%s\"",
00241                        server->servername),
00242                 errdetail_internal("%s", connmessage)));
00243         }
00244 
00245         /*
00246          * Check that non-superuser has used password to establish connection;
00247          * otherwise, he's piggybacking on the postgres server's user
00248          * identity. See also dblink_security_check() in contrib/dblink.
00249          */
00250         if (!superuser() && !PQconnectionUsedPassword(conn))
00251             ereport(ERROR,
00252                   (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
00253                    errmsg("password is required"),
00254                    errdetail("Non-superuser cannot connect if the server does not request a password."),
00255                    errhint("Target server's authentication method must be changed.")));
00256 
00257         /* Prepare new session for use */
00258         configure_remote_session(conn);
00259 
00260         pfree(keywords);
00261         pfree(values);
00262     }
00263     PG_CATCH();
00264     {
00265         /* Release PGconn data structure if we managed to create one */
00266         if (conn)
00267             PQfinish(conn);
00268         PG_RE_THROW();
00269     }
00270     PG_END_TRY();
00271 
00272     return conn;
00273 }
00274 
00275 /*
00276  * For non-superusers, insist that the connstr specify a password.  This
00277  * prevents a password from being picked up from .pgpass, a service file,
00278  * the environment, etc.  We don't want the postgres user's passwords
00279  * to be accessible to non-superusers.  (See also dblink_connstr_check in
00280  * contrib/dblink.)
00281  */
00282 static void
00283 check_conn_params(const char **keywords, const char **values)
00284 {
00285     int         i;
00286 
00287     /* no check required if superuser */
00288     if (superuser())
00289         return;
00290 
00291     /* ok if params contain a non-empty password */
00292     for (i = 0; keywords[i] != NULL; i++)
00293     {
00294         if (strcmp(keywords[i], "password") == 0 && values[i][0] != '\0')
00295             return;
00296     }
00297 
00298     ereport(ERROR,
00299             (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
00300              errmsg("password is required"),
00301              errdetail("Non-superusers must provide a password in the user mapping.")));
00302 }
00303 
00304 /*
00305  * Issue SET commands to make sure remote session is configured properly.
00306  *
00307  * We do this just once at connection, assuming nothing will change the
00308  * values later.  Since we'll never send volatile function calls to the
00309  * remote, there shouldn't be any way to break this assumption from our end.
00310  * It's possible to think of ways to break it at the remote end, eg making
00311  * a foreign table point to a view that includes a set_config call ---
00312  * but once you admit the possibility of a malicious view definition,
00313  * there are any number of ways to break things.
00314  */
00315 static void
00316 configure_remote_session(PGconn *conn)
00317 {
00318     int         remoteversion = PQserverVersion(conn);
00319 
00320     /* Force the search path to contain only pg_catalog (see deparse.c) */
00321     do_sql_command(conn, "SET search_path = pg_catalog");
00322 
00323     /*
00324      * Set remote timezone; this is basically just cosmetic, since all
00325      * transmitted and returned timestamptzs should specify a zone explicitly
00326      * anyway.  However it makes the regression test outputs more predictable.
00327      *
00328      * We don't risk setting remote zone equal to ours, since the remote
00329      * server might use a different timezone database.  Instead, use UTC
00330      * (quoted, because very old servers are picky about case).
00331      */
00332     do_sql_command(conn, "SET timezone = 'UTC'");
00333 
00334     /*
00335      * Set values needed to ensure unambiguous data output from remote.  (This
00336      * logic should match what pg_dump does.  See also set_transmission_modes
00337      * in postgres_fdw.c.)
00338      */
00339     do_sql_command(conn, "SET datestyle = ISO");
00340     if (remoteversion >= 80400)
00341         do_sql_command(conn, "SET intervalstyle = postgres");
00342     if (remoteversion >= 90000)
00343         do_sql_command(conn, "SET extra_float_digits = 3");
00344     else
00345         do_sql_command(conn, "SET extra_float_digits = 2");
00346 }
00347 
00348 /*
00349  * Convenience subroutine to issue a non-data-returning SQL command to remote
00350  */
00351 static void
00352 do_sql_command(PGconn *conn, const char *sql)
00353 {
00354     PGresult   *res;
00355 
00356     res = PQexec(conn, sql);
00357     if (PQresultStatus(res) != PGRES_COMMAND_OK)
00358         pgfdw_report_error(ERROR, res, true, sql);
00359     PQclear(res);
00360 }
00361 
00362 /*
00363  * Start remote transaction or subtransaction, if needed.
00364  *
00365  * Note that we always use at least REPEATABLE READ in the remote session.
00366  * This is so that, if a query initiates multiple scans of the same or
00367  * different foreign tables, we will get snapshot-consistent results from
00368  * those scans.  A disadvantage is that we can't provide sane emulation of
00369  * READ COMMITTED behavior --- it would be nice if we had some other way to
00370  * control which remote queries share a snapshot.
00371  */
00372 static void
00373 begin_remote_xact(ConnCacheEntry *entry)
00374 {
00375     int         curlevel = GetCurrentTransactionNestLevel();
00376 
00377     /* Start main transaction if we haven't yet */
00378     if (entry->xact_depth <= 0)
00379     {
00380         const char *sql;
00381 
00382         elog(DEBUG3, "starting remote transaction on connection %p",
00383              entry->conn);
00384 
00385         if (IsolationIsSerializable())
00386             sql = "START TRANSACTION ISOLATION LEVEL SERIALIZABLE";
00387         else
00388             sql = "START TRANSACTION ISOLATION LEVEL REPEATABLE READ";
00389         do_sql_command(entry->conn, sql);
00390         entry->xact_depth = 1;
00391     }
00392 
00393     /*
00394      * If we're in a subtransaction, stack up savepoints to match our level.
00395      * This ensures we can rollback just the desired effects when a
00396      * subtransaction aborts.
00397      */
00398     while (entry->xact_depth < curlevel)
00399     {
00400         char        sql[64];
00401 
00402         snprintf(sql, sizeof(sql), "SAVEPOINT s%d", entry->xact_depth + 1);
00403         do_sql_command(entry->conn, sql);
00404         entry->xact_depth++;
00405     }
00406 }
00407 
00408 /*
00409  * Release connection reference count created by calling GetConnection.
00410  */
00411 void
00412 ReleaseConnection(PGconn *conn)
00413 {
00414     /*
00415      * Currently, we don't actually track connection references because all
00416      * cleanup is managed on a transaction or subtransaction basis instead. So
00417      * there's nothing to do here.
00418      */
00419 }
00420 
00421 /*
00422  * Assign a "unique" number for a cursor.
00423  *
00424  * These really only need to be unique per connection within a transaction.
00425  * For the moment we ignore the per-connection point and assign them across
00426  * all connections in the transaction, but we ask for the connection to be
00427  * supplied in case we want to refine that.
00428  *
00429  * Note that even if wraparound happens in a very long transaction, actual
00430  * collisions are highly improbable; just be sure to use %u not %d to print.
00431  */
00432 unsigned int
00433 GetCursorNumber(PGconn *conn)
00434 {
00435     return ++cursor_number;
00436 }
00437 
00438 /*
00439  * Assign a "unique" number for a prepared statement.
00440  *
00441  * This works much like GetCursorNumber, except that we never reset the counter
00442  * within a session.  That's because we can't be 100% sure we've gotten rid
00443  * of all prepared statements on all connections, and it's not really worth
00444  * increasing the risk of prepared-statement name collisions by resetting.
00445  */
00446 unsigned int
00447 GetPrepStmtNumber(PGconn *conn)
00448 {
00449     return ++prep_stmt_number;
00450 }
00451 
00452 /*
00453  * Report an error we got from the remote server.
00454  *
00455  * elevel: error level to use (typically ERROR, but might be less)
00456  * res: PGresult containing the error
00457  * clear: if true, PQclear the result (otherwise caller will handle it)
00458  * sql: NULL, or text of remote command we tried to execute
00459  *
00460  * Note: callers that choose not to throw ERROR for a remote error are
00461  * responsible for making sure that the associated ConnCacheEntry gets
00462  * marked with have_error = true.
00463  */
00464 void
00465 pgfdw_report_error(int elevel, PGresult *res, bool clear, const char *sql)
00466 {
00467     /* If requested, PGresult must be released before leaving this function. */
00468     PG_TRY();
00469     {
00470         char       *diag_sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
00471         char       *message_primary = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
00472         char       *message_detail = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
00473         char       *message_hint = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
00474         char       *message_context = PQresultErrorField(res, PG_DIAG_CONTEXT);
00475         int         sqlstate;
00476 
00477         if (diag_sqlstate)
00478             sqlstate = MAKE_SQLSTATE(diag_sqlstate[0],
00479                                      diag_sqlstate[1],
00480                                      diag_sqlstate[2],
00481                                      diag_sqlstate[3],
00482                                      diag_sqlstate[4]);
00483         else
00484             sqlstate = ERRCODE_CONNECTION_FAILURE;
00485 
00486         ereport(elevel,
00487                 (errcode(sqlstate),
00488                  message_primary ? errmsg_internal("%s", message_primary) :
00489                  errmsg("unknown error"),
00490                message_detail ? errdetail_internal("%s", message_detail) : 0,
00491                  message_hint ? errhint("%s", message_hint) : 0,
00492                  message_context ? errcontext("%s", message_context) : 0,
00493                  sql ? errcontext("Remote SQL command: %s", sql) : 0));
00494     }
00495     PG_CATCH();
00496     {
00497         if (clear)
00498             PQclear(res);
00499         PG_RE_THROW();
00500     }
00501     PG_END_TRY();
00502     if (clear)
00503         PQclear(res);
00504 }
00505 
00506 /*
00507  * pgfdw_xact_callback --- cleanup at main-transaction end.
00508  */
00509 static void
00510 pgfdw_xact_callback(XactEvent event, void *arg)
00511 {
00512     HASH_SEQ_STATUS scan;
00513     ConnCacheEntry *entry;
00514 
00515     /* Quick exit if no connections were touched in this transaction. */
00516     if (!xact_got_connection)
00517         return;
00518 
00519     /*
00520      * Scan all connection cache entries to find open remote transactions, and
00521      * close them.
00522      */
00523     hash_seq_init(&scan, ConnectionHash);
00524     while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
00525     {
00526         PGresult   *res;
00527 
00528         /* We only care about connections with open remote transactions */
00529         if (entry->conn == NULL || entry->xact_depth == 0)
00530             continue;
00531 
00532         elog(DEBUG3, "closing remote transaction on connection %p",
00533              entry->conn);
00534 
00535         switch (event)
00536         {
00537             case XACT_EVENT_PRE_COMMIT:
00538                 /* Commit all remote transactions during pre-commit */
00539                 do_sql_command(entry->conn, "COMMIT TRANSACTION");
00540 
00541                 /*
00542                  * If there were any errors in subtransactions, and we made
00543                  * prepared statements, do a DEALLOCATE ALL to make sure we
00544                  * get rid of all prepared statements.  This is annoying and
00545                  * not terribly bulletproof, but it's probably not worth
00546                  * trying harder.
00547                  *
00548                  * DEALLOCATE ALL only exists in 8.3 and later, so this
00549                  * constrains how old a server postgres_fdw can communicate
00550                  * with.  We intentionally ignore errors in the DEALLOCATE, so
00551                  * that we can hobble along to some extent with older servers
00552                  * (leaking prepared statements as we go; but we don't really
00553                  * support update operations pre-8.3 anyway).
00554                  */
00555                 if (entry->have_prep_stmt && entry->have_error)
00556                 {
00557                     res = PQexec(entry->conn, "DEALLOCATE ALL");
00558                     PQclear(res);
00559                 }
00560                 entry->have_prep_stmt = false;
00561                 entry->have_error = false;
00562                 break;
00563             case XACT_EVENT_PRE_PREPARE:
00564 
00565                 /*
00566                  * We disallow remote transactions that modified anything,
00567                  * since it's not really reasonable to hold them open until
00568                  * the prepared transaction is committed.  For the moment,
00569                  * throw error unconditionally; later we might allow read-only
00570                  * cases.  Note that the error will cause us to come right
00571                  * back here with event == XACT_EVENT_ABORT, so we'll clean up
00572                  * the connection state at that point.
00573                  */
00574                 ereport(ERROR,
00575                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
00576                          errmsg("cannot prepare a transaction that modified remote tables")));
00577                 break;
00578             case XACT_EVENT_COMMIT:
00579             case XACT_EVENT_PREPARE:
00580                 /* Should not get here -- pre-commit should have handled it */
00581                 elog(ERROR, "missed cleaning up connection during pre-commit");
00582                 break;
00583             case XACT_EVENT_ABORT:
00584                 /* Assume we might have lost track of prepared statements */
00585                 entry->have_error = true;
00586                 /* If we're aborting, abort all remote transactions too */
00587                 res = PQexec(entry->conn, "ABORT TRANSACTION");
00588                 /* Note: can't throw ERROR, it would be infinite loop */
00589                 if (PQresultStatus(res) != PGRES_COMMAND_OK)
00590                     pgfdw_report_error(WARNING, res, true,
00591                                        "ABORT TRANSACTION");
00592                 else
00593                 {
00594                     PQclear(res);
00595                     /* As above, make sure we've cleared any prepared stmts */
00596                     if (entry->have_prep_stmt && entry->have_error)
00597                     {
00598                         res = PQexec(entry->conn, "DEALLOCATE ALL");
00599                         PQclear(res);
00600                     }
00601                     entry->have_prep_stmt = false;
00602                     entry->have_error = false;
00603                 }
00604                 break;
00605         }
00606 
00607         /* Reset state to show we're out of a transaction */
00608         entry->xact_depth = 0;
00609 
00610         /*
00611          * If the connection isn't in a good idle state, discard it to
00612          * recover. Next GetConnection will open a new connection.
00613          */
00614         if (PQstatus(entry->conn) != CONNECTION_OK ||
00615             PQtransactionStatus(entry->conn) != PQTRANS_IDLE)
00616         {
00617             elog(DEBUG3, "discarding connection %p", entry->conn);
00618             PQfinish(entry->conn);
00619             entry->conn = NULL;
00620         }
00621     }
00622 
00623     /*
00624      * Regardless of the event type, we can now mark ourselves as out of the
00625      * transaction.  (Note: if we are here during PRE_COMMIT or PRE_PREPARE,
00626      * this saves a useless scan of the hashtable during COMMIT or PREPARE.)
00627      */
00628     xact_got_connection = false;
00629 
00630     /* Also reset cursor numbering for next transaction */
00631     cursor_number = 0;
00632 }
00633 
00634 /*
00635  * pgfdw_subxact_callback --- cleanup at subtransaction end.
00636  */
00637 static void
00638 pgfdw_subxact_callback(SubXactEvent event, SubTransactionId mySubid,
00639                        SubTransactionId parentSubid, void *arg)
00640 {
00641     HASH_SEQ_STATUS scan;
00642     ConnCacheEntry *entry;
00643     int         curlevel;
00644 
00645     /* Nothing to do at subxact start, nor after commit. */
00646     if (!(event == SUBXACT_EVENT_PRE_COMMIT_SUB ||
00647           event == SUBXACT_EVENT_ABORT_SUB))
00648         return;
00649 
00650     /* Quick exit if no connections were touched in this transaction. */
00651     if (!xact_got_connection)
00652         return;
00653 
00654     /*
00655      * Scan all connection cache entries to find open remote subtransactions
00656      * of the current level, and close them.
00657      */
00658     curlevel = GetCurrentTransactionNestLevel();
00659     hash_seq_init(&scan, ConnectionHash);
00660     while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
00661     {
00662         PGresult   *res;
00663         char        sql[100];
00664 
00665         /*
00666          * We only care about connections with open remote subtransactions of
00667          * the current level.
00668          */
00669         if (entry->conn == NULL || entry->xact_depth < curlevel)
00670             continue;
00671 
00672         if (entry->xact_depth > curlevel)
00673             elog(ERROR, "missed cleaning up remote subtransaction at level %d",
00674                  entry->xact_depth);
00675 
00676         if (event == SUBXACT_EVENT_PRE_COMMIT_SUB)
00677         {
00678             /* Commit all remote subtransactions during pre-commit */
00679             snprintf(sql, sizeof(sql), "RELEASE SAVEPOINT s%d", curlevel);
00680             do_sql_command(entry->conn, sql);
00681         }
00682         else
00683         {
00684             /* Assume we might have lost track of prepared statements */
00685             entry->have_error = true;
00686             /* Rollback all remote subtransactions during abort */
00687             snprintf(sql, sizeof(sql),
00688                      "ROLLBACK TO SAVEPOINT s%d; RELEASE SAVEPOINT s%d",
00689                      curlevel, curlevel);
00690             res = PQexec(entry->conn, sql);
00691             if (PQresultStatus(res) != PGRES_COMMAND_OK)
00692                 pgfdw_report_error(WARNING, res, true, sql);
00693             else
00694                 PQclear(res);
00695         }
00696 
00697         /* OK, we're outta that level of subtransaction */
00698         entry->xact_depth--;
00699     }
00700 }