]> granicus.if.org Git - postgresql/blobdiff - src/backend/utils/mmgr/portalmem.c
RESET SESSION, plus related new DDL commands. Patch from Marko Kreen,
[postgresql] / src / backend / utils / mmgr / portalmem.c
index 4068b13467aab09fade239a6dd455d9c41435c71..eeba207dc94fdf5ea8b845672dcdd86d6d4c3351 100644 (file)
 /*-------------------------------------------------------------------------
  *
  * portalmem.c
- *       backend portal memory context management stuff
+ *       backend portal memory management
  *
- * Copyright (c) 1994, Regents of the University of California
+ * Portals are objects representing the execution state of a query.
+ * This module provides memory management services for portals, but it
+ * doesn't actually run the executor for them.
  *
  *
+ * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
  * IDENTIFICATION
- *       $Header: /cvsroot/pgsql/src/backend/utils/mmgr/portalmem.c,v 1.18 1999/02/13 23:20:12 momjian Exp $
+ *       $PostgreSQL: pgsql/src/backend/utils/mmgr/portalmem.c,v 1.101 2007/04/12 06:53:48 neilc Exp $
  *
  *-------------------------------------------------------------------------
  */
-/*
- * NOTES
- *             Do not confuse "Portal" with "PortalEntry" (or "PortalBuffer").
- *             When a PQexec() routine is run, the resulting tuples
- *             find their way into a "PortalEntry".  The contents of the resulting
- *             "PortalEntry" can then be inspected by other PQxxx functions.
- *
- *             A "Portal" is a structure used to keep track of queries of the
- *             form:
- *                             retrieve portal FOO ( blah... ) where blah...
- *
- *             When the backend sees a "retrieve portal" query, it allocates
- *             a "PortalD" structure, plans the query and then stores the query
- *             in the portal without executing it.  Later, when the backend
- *             sees a
- *                             fetch 1 into FOO
- *
- *             the system looks up the portal named "FOO" in the portal table,
- *             gets the planned query and then calls the executor with a feature of
- *             '(EXEC_FOR 1).  The executor then runs the query and returns a single
- *             tuple.  The problem is that we have to hold onto the state of the
- *             portal query until we see a "close p".  This means we have to be
- *             careful about memory management.
- *
- *             Having said all that, here is what a PortalD currently looks like:
- *
- * struct PortalD {
- *             char*                                                   name;
- *             classObj(PortalVariableMemory)  variable;
- *             classObj(PortalHeapMemory)              heap;
- *             List                                                    queryDesc;
- *             EState                                                  state;
- *             void                                                    (*cleanup) ARGS((Portal portal));
- * };
- *
- *             I hope this makes things clearer to whoever reads this -cim 2/22/91
- *
- *             Here is an old comment taken from nodes/memnodes.h
- *
- * MemoryContext 
- *             A logical context in which memory allocations occur.
- *
- * The types of memory contexts can be thought of as members of the
- * following inheritance hierarchy with properties summarized below.
- *
- *                                             Node
- *                                             |
- *                             MemoryContext___
- *                             /                               \
- *             GlobalMemory    PortalMemoryContext
- *                                             /                               \
- *             PortalVariableMemory    PortalHeapMemory
- *
- *                                             Flushed at              Flushed at              Checkpoints
- *                                             Transaction             Portal
- *                                             Commit                  Close
- *
- * GlobalMemory                                        n                               n                               n
- * PortalVariableMemory                        n                               y                               n
- * PortalHeapMemory                            y                               y                               y *
- *
- */
-#include <stdio.h>                             /* for sprintf() */
-#include <string.h>                            /* for strlen, strncpy */
-
 #include "postgres.h"
 
-#include "lib/hasht.h"
-#include "utils/module.h"
-#include "utils/excid.h"               /* for Unimplemented */
-#include "utils/mcxt.h"
-#include "utils/hsearch.h"
-
-#include "nodes/memnodes.h"
-#include "nodes/nodes.h"
-#include "nodes/pg_list.h"
-#include "nodes/execnodes.h"   /* for EState */
-
-#include "utils/portal.h"
+#include "access/heapam.h"
+#include "access/xact.h"
+#include "catalog/pg_type.h"
+#include "commands/portalcmds.h"
+#include "funcapi.h"
+#include "miscadmin.h"
+#include "utils/builtins.h"
+#include "utils/memutils.h"
 
-static void CollectNamedPortals(Portal *portalP, int destroy);
-static Portal PortalHeapMemoryGetPortal(PortalHeapMemory context);
-static PortalVariableMemory PortalHeapMemoryGetVariableMemory(PortalHeapMemory context);
-static void PortalResetHeapMemory(Portal portal);
-static Portal PortalVariableMemoryGetPortal(PortalVariableMemory context);
-
-/* ----------------
- *             ALLOCFREE_ERROR_ABORT
- *             define this if you want a core dump when you try to
- *             free memory already freed -cim 2/9/91
- * ----------------
+/*
+ * Estimate of the maximum number of open portals a user would have,
+ * used in initially sizing the PortalHashTable in EnablePortalManager().
+ * Since the hash table can expand, there's no need to make this overly
+ * generous, and keeping it small avoids unnecessary overhead in the
+ * hash_seq_search() calls executed during transaction end.
  */
-#undef ALLOCFREE_ERROR_ABORT
+#define PORTALS_PER_USER          16
+
 
 /* ----------------
  *             Global state
  * ----------------
  */
 
-static int     PortalManagerEnableCount = 0;
-
-#define MAX_PORTALNAME_LEN             64              /* XXX LONGALIGNable value */
+#define MAX_PORTALNAME_LEN             NAMEDATALEN
 
 typedef struct portalhashent
 {
@@ -120,916 +50,904 @@ typedef struct portalhashent
        Portal          portal;
 } PortalHashEnt;
 
-#define PortalManagerEnabled   (PortalManagerEnableCount >= 1)
-
 static HTAB *PortalHashTable = NULL;
 
 #define PortalHashTableLookup(NAME, PORTAL) \
 do { \
-       PortalHashEnt *hentry; bool found; char key[MAX_PORTALNAME_LEN]; \
+       PortalHashEnt *hentry; \
        \
-       MemSet(key, 0, MAX_PORTALNAME_LEN); \
-       snprintf(key, MAX_PORTALNAME_LEN - 1, "%s", NAME); \
-       hentry = (PortalHashEnt*)hash_search(PortalHashTable, \
-                                                                                key, HASH_FIND, &found); \
-       if (hentry == NULL) \
-               elog(FATAL, "error in PortalHashTable"); \
-       if (found) \
+       hentry = (PortalHashEnt *) hash_search(PortalHashTable, \
+                                                                                  (NAME), HASH_FIND, NULL); \
+       if (hentry) \
                PORTAL = hentry->portal; \
        else \
                PORTAL = NULL; \
 } while(0)
 
-#define PortalHashTableInsert(PORTAL) \
+#define PortalHashTableInsert(PORTAL, NAME) \
 do { \
-       PortalHashEnt *hentry; bool found; char key[MAX_PORTALNAME_LEN]; \
+       PortalHashEnt *hentry; bool found; \
        \
-       MemSet(key, 0, MAX_PORTALNAME_LEN); \
-       snprintf(key, MAX_PORTALNAME_LEN - 1, "%s", PORTAL->name); \
-       hentry = (PortalHashEnt*)hash_search(PortalHashTable, \
-                                                                                key, HASH_ENTER, &found); \
-       if (hentry == NULL) \
-               elog(FATAL, "error in PortalHashTable"); \
+       hentry = (PortalHashEnt *) hash_search(PortalHashTable, \
+                                                                                  (NAME), HASH_ENTER, &found); \
        if (found) \
-               elog(NOTICE, "trying to insert a portal name that exists."); \
+               elog(ERROR, "duplicate portal name"); \
        hentry->portal = PORTAL; \
+       /* To avoid duplicate storage, make PORTAL->name point to htab entry */ \
+       PORTAL->name = hentry->portalname; \
 } while(0)
 
 #define PortalHashTableDelete(PORTAL) \
-{ \
-       PortalHashEnt *hentry; bool found; char key[MAX_PORTALNAME_LEN]; \
+do { \
+       PortalHashEnt *hentry; \
        \
-       MemSet(key, 0, MAX_PORTALNAME_LEN); \
-       snprintf(key, MAX_PORTALNAME_LEN - 1, "%s", PORTAL->name); \
-       hentry = (PortalHashEnt*)hash_search(PortalHashTable, \
-                                                                                key, HASH_REMOVE, &found); \
+       hentry = (PortalHashEnt *) hash_search(PortalHashTable, \
+                                                                                  PORTAL->name, HASH_REMOVE, NULL); \
        if (hentry == NULL) \
-               elog(FATAL, "error in PortalHashTable"); \
-       if (!found) \
-               elog(NOTICE, "trying to delete portal name that does not exist."); \
+               elog(WARNING, "trying to delete portal name that does not exist"); \
 } while(0)
 
-static GlobalMemory PortalMemory = NULL;
-static char PortalMemoryName[] = "Portal";
-
-static Portal BlankPortal = NULL;
-
-/* ----------------
- *             Internal class definitions
- * ----------------
- */
-typedef struct HeapMemoryBlockData
-{
-       AllocSetData setData;
-       FixedItemData itemData;
-} HeapMemoryBlockData;
-
-typedef HeapMemoryBlockData *HeapMemoryBlock;
+static MemoryContext PortalMemory = NULL;
 
-#define HEAPMEMBLOCK(context) \
-       ((HeapMemoryBlock)(context)->block)
 
 /* ----------------------------------------------------------------
- *                               Variable and heap memory methods
+ *                                public portal interface functions
  * ----------------------------------------------------------------
  */
-/* ----------------
- *             PortalVariableMemoryAlloc
- * ----------------
- */
-static Pointer
-PortalVariableMemoryAlloc(PortalVariableMemory this,
-                                                 Size size)
-{
-       return AllocSetAlloc(&this->setData, size);
-}
 
-/* ----------------
- *             PortalVariableMemoryFree
- * ----------------
+/*
+ * EnablePortalManager
+ *             Enables the portal management module at backend startup.
  */
-static void
-PortalVariableMemoryFree(PortalVariableMemory this,
-                                                Pointer pointer)
+void
+EnablePortalManager(void)
 {
-       AllocSetFree(&this->setData, pointer);
-}
+       HASHCTL         ctl;
 
-/* ----------------
- *             PortalVariableMemoryRealloc
- * ----------------
- */
-static Pointer
-PortalVariableMemoryRealloc(PortalVariableMemory this,
-                                                       Pointer pointer,
-                                                       Size size)
-{
-       return AllocSetRealloc(&this->setData, pointer, size);
-}
+       Assert(PortalMemory == NULL);
 
-/* ----------------
- *             PortalVariableMemoryGetName
- * ----------------
- */
-static char *
-PortalVariableMemoryGetName(PortalVariableMemory this)
-{
-       return form("%s-var", PortalVariableMemoryGetPortal(this)->name);
+       PortalMemory = AllocSetContextCreate(TopMemoryContext,
+                                                                                "PortalMemory",
+                                                                                ALLOCSET_DEFAULT_MINSIZE,
+                                                                                ALLOCSET_DEFAULT_INITSIZE,
+                                                                                ALLOCSET_DEFAULT_MAXSIZE);
+
+       ctl.keysize = MAX_PORTALNAME_LEN;
+       ctl.entrysize = sizeof(PortalHashEnt);
+
+       /*
+        * use PORTALS_PER_USER as a guess of how many hash table entries to
+        * create, initially
+        */
+       PortalHashTable = hash_create("Portal hash", PORTALS_PER_USER,
+                                                                 &ctl, HASH_ELEM);
 }
 
-/* ----------------
- *             PortalVariableMemoryDump
- * ----------------
+/*
+ * GetPortalByName
+ *             Returns a portal given a portal name, or NULL if name not found.
  */
-static void
-PortalVariableMemoryDump(PortalVariableMemory this)
+Portal
+GetPortalByName(const char *name)
 {
-       printf("--\n%s:\n", PortalVariableMemoryGetName(this));
+       Portal          portal;
+
+       if (PointerIsValid(name))
+               PortalHashTableLookup(name, portal);
+       else
+               portal = NULL;
 
-       AllocSetDump(&this->setData);           /* XXX is this the right interface */
+       return portal;
 }
 
-/* ----------------
- *             PortalHeapMemoryAlloc
- * ----------------
+/*
+ * PortalListGetPrimaryStmt
+ *             Get the "primary" stmt within a portal, ie, the one marked canSetTag.
+ *
+ * Returns NULL if no such stmt.  If multiple PlannedStmt structs within the
+ * portal are marked canSetTag, returns the first one. Neither of these
+ * cases should occur in present usages of this function.
+ *
+ * Copes if given a list of Querys --- can't happen in a portal, but this
+ * code also supports plancache.c, which needs both cases.
+ *
+ * Note: the reason this is just handed a List is so that plancache.c
+ * can share the code. For use with a portal, use PortalGetPrimaryStmt
+ * rather than calling this directly.
  */
-static Pointer
-PortalHeapMemoryAlloc(PortalHeapMemory this,
-                                         Size size)
+Node *
+PortalListGetPrimaryStmt(List *stmts)
 {
-       HeapMemoryBlock block = HEAPMEMBLOCK(this);
+       ListCell   *lc;
 
-       AssertState(PointerIsValid(block));
+       foreach(lc, stmts)
+       {
+               Node   *stmt = (Node *) lfirst(lc);
 
-       return AllocSetAlloc(&block->setData, size);
+               if (IsA(stmt, PlannedStmt))
+               {
+                       if (((PlannedStmt *) stmt)->canSetTag)
+                               return stmt;
+               }
+               else if (IsA(stmt, Query))
+               {
+                       if (((Query *) stmt)->canSetTag)
+                               return stmt;
+               }
+               else
+               {
+                       /* Utility stmts are assumed canSetTag if they're the only stmt */
+                       if (list_length(stmts) == 1)
+                               return stmt;
+               }
+       }
+       return NULL;
 }
 
-/* ----------------
- *             PortalHeapMemoryFree
- * ----------------
+/*
+ * CreatePortal
+ *             Returns a new portal given a name.
+ *
+ * allowDup: if true, automatically drop any pre-existing portal of the
+ * same name (if false, an error is raised).
+ *
+ * dupSilent: if true, don't even emit a WARNING.
  */
-static void
-PortalHeapMemoryFree(PortalHeapMemory this,
-                                        Pointer pointer)
+Portal
+CreatePortal(const char *name, bool allowDup, bool dupSilent)
 {
-       HeapMemoryBlock block = HEAPMEMBLOCK(this);
+       Portal          portal;
 
-       AssertState(PointerIsValid(block));
+       AssertArg(PointerIsValid(name));
 
-       if (AllocSetContains(&block->setData, pointer))
-               AllocSetFree(&block->setData, pointer);
-       else
+       portal = GetPortalByName(name);
+       if (PortalIsValid(portal))
        {
-               elog(NOTICE,
-                        "PortalHeapMemoryFree: 0x%x not in alloc set!",
-                        pointer);
-#ifdef ALLOCFREE_ERROR_ABORT
-               Assert(AllocSetContains(&block->setData, pointer));
-#endif  /* ALLOCFREE_ERROR_ABORT */
+               if (!allowDup)
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_DUPLICATE_CURSOR),
+                                        errmsg("cursor \"%s\" already exists", name)));
+               if (!dupSilent)
+                       ereport(WARNING,
+                                       (errcode(ERRCODE_DUPLICATE_CURSOR),
+                                        errmsg("closing existing cursor \"%s\"",
+                                                       name)));
+               PortalDrop(portal, false);
        }
+
+       /* make new portal structure */
+       portal = (Portal) MemoryContextAllocZero(PortalMemory, sizeof *portal);
+
+       /* initialize portal heap context; typically it won't store much */
+       portal->heap = AllocSetContextCreate(PortalMemory,
+                                                                                "PortalHeapMemory",
+                                                                                ALLOCSET_SMALL_MINSIZE,
+                                                                                ALLOCSET_SMALL_INITSIZE,
+                                                                                ALLOCSET_SMALL_MAXSIZE);
+
+       /* create a resource owner for the portal */
+       portal->resowner = ResourceOwnerCreate(CurTransactionResourceOwner,
+                                                                                  "Portal");
+
+       /* initialize portal fields that don't start off zero */
+       portal->status = PORTAL_NEW;
+       portal->cleanup = PortalCleanup;
+       portal->createSubid = GetCurrentSubTransactionId();
+       portal->strategy = PORTAL_MULTI_QUERY;
+       portal->cursorOptions = CURSOR_OPT_NO_SCROLL;
+       portal->atStart = true;
+       portal->atEnd = true;           /* disallow fetches until query is set */
+       portal->visible = true;
+       portal->creation_time = GetCurrentStatementStartTimestamp();
+
+       /* put portal in table (sets portal->name) */
+       PortalHashTableInsert(portal, name);
+
+       return portal;
 }
 
-/* ----------------
- *             PortalHeapMemoryRealloc
- * ----------------
+/*
+ * CreateNewPortal
+ *             Create a new portal, assigning it a random nonconflicting name.
  */
-static Pointer
-PortalHeapMemoryRealloc(PortalHeapMemory this,
-                                               Pointer pointer,
-                                               Size size)
+Portal
+CreateNewPortal(void)
 {
-       HeapMemoryBlock block = HEAPMEMBLOCK(this);
+       static unsigned int unnamed_portal_count = 0;
 
-       AssertState(PointerIsValid(block));
+       char            portalname[MAX_PORTALNAME_LEN];
 
-       return AllocSetRealloc(&block->setData, pointer, size);
+       /* Select a nonconflicting name */
+       for (;;)
+       {
+               unnamed_portal_count++;
+               sprintf(portalname, "<unnamed portal %u>", unnamed_portal_count);
+               if (GetPortalByName(portalname) == NULL)
+                       break;
+       }
+
+       return CreatePortal(portalname, false, false);
 }
 
-/* ----------------
- *             PortalHeapMemoryGetName
- * ----------------
+/*
+ * PortalDefineQuery
+ *             A simple subroutine to establish a portal's query.
+ *
+ * Notes: commandTag shall be NULL if and only if the original query string
+ * (before rewriting) was an empty string.     Also, the passed commandTag must
+ * be a pointer to a constant string, since it is not copied.  However,
+ * prepStmtName and sourceText, if provided, are copied into the portal's
+ * heap context for safekeeping.
+ *
+ * If cplan is provided, then it is a cached plan containing the stmts,
+ * and the caller must have done RevalidateCachedPlan(), causing a refcount
+ * increment.  The refcount will be released when the portal is destroyed.
+ *
+ * If cplan is NULL, then it is the caller's responsibility to ensure that
+ * the passed plan trees have adequate lifetime.  Typically this is done by
+ * copying them into the portal's heap context.
  */
-static char *
-PortalHeapMemoryGetName(PortalHeapMemory this)
+void
+PortalDefineQuery(Portal portal,
+                                 const char *prepStmtName,
+                                 const char *sourceText,
+                                 const char *commandTag,
+                                 List *stmts,
+                                 CachedPlan *cplan)
 {
-       return form("%s-heap", PortalHeapMemoryGetPortal(this)->name);
+       AssertArg(PortalIsValid(portal));
+       AssertState(portal->status == PORTAL_NEW);
+
+       Assert(commandTag != NULL || stmts == NIL);
+
+       portal->prepStmtName = prepStmtName ? 
+               MemoryContextStrdup(PortalGetHeapMemory(portal), prepStmtName) : NULL;
+       portal->sourceText = sourceText ? 
+               MemoryContextStrdup(PortalGetHeapMemory(portal), sourceText) : NULL;
+       portal->commandTag = commandTag;
+       portal->stmts = stmts;
+       portal->cplan = cplan;
+       portal->status = PORTAL_DEFINED;
 }
 
-/* ----------------
- *             PortalHeapMemoryDump
- * ----------------
+/*
+ * PortalReleaseCachedPlan
+ *             Release a portal's reference to its cached plan, if any.
  */
 static void
-PortalHeapMemoryDump(PortalHeapMemory this)
+PortalReleaseCachedPlan(Portal portal)
 {
-       HeapMemoryBlock block;
-
-       printf("--\n%s:\n", PortalHeapMemoryGetName(this));
-
-       /* XXX is this the right interface */
-       if (PointerIsValid(this->block))
-               AllocSetDump(&HEAPMEMBLOCK(this)->setData);
-
-       /* dump the stack too */
-       for (block = (HeapMemoryBlock) FixedStackGetTop(&this->stackData);
-                PointerIsValid(block);
-                block = (HeapMemoryBlock)
-                FixedStackGetNext(&this->stackData, (Pointer) block))
+       if (portal->cplan)
        {
-
-               printf("--\n");
-               AllocSetDump(&block->setData);
+               ReleaseCachedPlan(portal->cplan, false);
+               portal->cplan = NULL;
        }
 }
 
-/* ----------------------------------------------------------------
- *                             variable / heap context method tables
- * ----------------------------------------------------------------
- */
-static struct MemoryContextMethodsData PortalVariableContextMethodsData = {
-       PortalVariableMemoryAlloc,      /* Pointer (*)(this, uint32)    palloc */
-       PortalVariableMemoryFree,       /* void (*)(this, Pointer)              pfree */
-       PortalVariableMemoryRealloc,/* Pointer (*)(this, Pointer)       repalloc */
-       PortalVariableMemoryGetName,/* char* (*)(this)                          getName */
-       PortalVariableMemoryDump        /* void (*)(this)                               dump */
-};
-
-static struct MemoryContextMethodsData PortalHeapContextMethodsData = {
-       PortalHeapMemoryAlloc,          /* Pointer (*)(this, uint32)    palloc */
-       PortalHeapMemoryFree,           /* void (*)(this, Pointer)              pfree */
-       PortalHeapMemoryRealloc,        /* Pointer (*)(this, Pointer)   repalloc */
-       PortalHeapMemoryGetName,        /* char* (*)(this)                              getName */
-       PortalHeapMemoryDump            /* void (*)(this)                               dump */
-};
-
-
-/* ----------------------------------------------------------------
- *                               private internal support routines
- * ----------------------------------------------------------------
- */
-/* ----------------
- *             CreateNewBlankPortal
- * ----------------
+/*
+ * PortalCreateHoldStore
+ *             Create the tuplestore for a portal.
  */
-static void
-CreateNewBlankPortal()
+void
+PortalCreateHoldStore(Portal portal)
 {
-       Portal          portal;
+       MemoryContext oldcxt;
 
-       AssertState(!PortalIsValid(BlankPortal));
+       Assert(portal->holdContext == NULL);
+       Assert(portal->holdStore == NULL);
 
        /*
-        * make new portal structure
+        * Create the memory context that is used for storage of the tuple set.
+        * Note this is NOT a child of the portal's heap memory.
         */
-       portal = (Portal)
-               MemoryContextAlloc((MemoryContext) PortalMemory, sizeof *portal);
+       portal->holdContext =
+               AllocSetContextCreate(PortalMemory,
+                                                         "PortalHoldContext",
+                                                         ALLOCSET_DEFAULT_MINSIZE,
+                                                         ALLOCSET_DEFAULT_INITSIZE,
+                                                         ALLOCSET_DEFAULT_MAXSIZE);
 
-       /*
-        * initialize portal variable context
-        */
-       NodeSetTag((Node *) &portal->variable, T_PortalVariableMemory);
-       AllocSetInit(&portal->variable.setData, DynamicAllocMode, (Size) 0);
-       portal->variable.method = &PortalVariableContextMethodsData;
+       /* Create the tuple store, selecting cross-transaction temp files. */
+       oldcxt = MemoryContextSwitchTo(portal->holdContext);
 
-       /*
-        * initialize portal heap context
-        */
-       NodeSetTag((Node *) &portal->heap, T_PortalHeapMemory);
-       portal->heap.block = NULL;
-       FixedStackInit(&portal->heap.stackData,
-                                  offsetof(HeapMemoryBlockData, itemData));
-       portal->heap.method = &PortalHeapContextMethodsData;
-
-       /*
-        * set bogus portal name
-        */
-       portal->name = "** Blank Portal **";
-
-       /* initialize portal query */
-       portal->queryDesc = NULL;
-       portal->attinfo = NULL;
-       portal->state = NULL;
-       portal->cleanup = NULL;
-
-       /*
-        * install blank portal
-        */
-       BlankPortal = portal;
-}
+       /* XXX: Should maintenance_work_mem be used for the portal size? */
+       portal->holdStore = tuplestore_begin_heap(true, true, work_mem);
 
-bool
-PortalNameIsSpecial(char *pname)
-{
-       if (strcmp(pname, VACPNAME) == 0)
-               return true;
-       return false;
+       MemoryContextSwitchTo(oldcxt);
 }
 
 /*
- * This routine is used to collect all portals created in this xaction
- * and then destroy them.  There is a little trickiness required as a
- * result of the dynamic hashing interface to getting every hash entry
- * sequentially.  Its use of static variables requires that we get every
- * entry *before* we destroy anything (destroying updates the hashtable
- * and screws up the sequential walk of the table). -mer 17 Aug 1992
+ * PortalDrop
+ *             Destroy the portal.
  */
-static void
-CollectNamedPortals(Portal *portalP, int destroy)
+void
+PortalDrop(Portal portal, bool isTopCommit)
 {
-       static Portal *portalList = (Portal *) NULL;
-       static int      listIndex = 0;
-       static int      maxIndex = 9;
+       AssertArg(PortalIsValid(portal));
 
-       if (portalList == (Portal *) NULL)
-               portalList = (Portal *) malloc(10 * sizeof(Portal));
+       /* Not sure if this case can validly happen or not... */
+       if (portal->status == PORTAL_ACTIVE)
+               elog(ERROR, "cannot drop active portal");
 
-       if (destroy != 0)
-       {
-               int                     i;
+       /*
+        * Remove portal from hash table.  Because we do this first, we will not
+        * come back to try to remove the portal again if there's any error in the
+        * subsequent steps.  Better to leak a little memory than to get into an
+        * infinite error-recovery loop.
+        */
+       PortalHashTableDelete(portal);
 
-               for (i = 0; i < listIndex; i++)
-                       PortalDestroy(&portalList[i]);
-               listIndex = 0;
-       }
-       else
-       {
-               Assert(portalP);
-               Assert(*portalP);
+       /* let portalcmds.c clean up the state it knows about */
+       if (PointerIsValid(portal->cleanup))
+               (*portal->cleanup) (portal);
 
-               /*
-                * Don't delete special portals, up to portal creator to do this
-                */
-               if (PortalNameIsSpecial((*portalP)->name))
-                       return;
+       /* drop cached plan reference, if any */
+       if (portal->cplan)
+               PortalReleaseCachedPlan(portal);
 
-               portalList[listIndex] = *portalP;
-               listIndex++;
-               if (listIndex == maxIndex)
-               {
-                       portalList = (Portal *)
-                               realloc(portalList, (maxIndex + 11) * sizeof(Portal));
-                       maxIndex += 10;
-               }
+       /*
+        * Release any resources still attached to the portal.  There are several
+        * cases being covered here:
+        *
+        * Top transaction commit (indicated by isTopCommit): normally we should
+        * do nothing here and let the regular end-of-transaction resource
+        * releasing mechanism handle these resources too.      However, if we have a
+        * FAILED portal (eg, a cursor that got an error), we'd better clean up
+        * its resources to avoid resource-leakage warning messages.
+        *
+        * Sub transaction commit: never comes here at all, since we don't kill
+        * any portals in AtSubCommit_Portals().
+        *
+        * Main or sub transaction abort: we will do nothing here because
+        * portal->resowner was already set NULL; the resources were already
+        * cleaned up in transaction abort.
+        *
+        * Ordinary portal drop: must release resources.  However, if the portal
+        * is not FAILED then we do not release its locks.      The locks become the
+        * responsibility of the transaction's ResourceOwner (since it is the
+        * parent of the portal's owner) and will be released when the transaction
+        * eventually ends.
+        */
+       if (portal->resowner &&
+               (!isTopCommit || portal->status == PORTAL_FAILED))
+       {
+               bool            isCommit = (portal->status != PORTAL_FAILED);
+
+               ResourceOwnerRelease(portal->resowner,
+                                                        RESOURCE_RELEASE_BEFORE_LOCKS,
+                                                        isCommit, false);
+               ResourceOwnerRelease(portal->resowner,
+                                                        RESOURCE_RELEASE_LOCKS,
+                                                        isCommit, false);
+               ResourceOwnerRelease(portal->resowner,
+                                                        RESOURCE_RELEASE_AFTER_LOCKS,
+                                                        isCommit, false);
+               ResourceOwnerDelete(portal->resowner);
        }
-       return;
-}
-
-void
-AtEOXact_portals()
-{
-       HashTableWalk(PortalHashTable, CollectNamedPortals, 0);
-       CollectNamedPortals(NULL, 1);
-}
+       portal->resowner = NULL;
 
-/* ----------------
- *             PortalDump
- * ----------------
- */
-#ifdef NOT_USED
-static void
-PortalDump(Portal *thisP)
-{
-       /* XXX state/argument checking here */
+       /*
+        * Delete tuplestore if present.  We should do this even under error
+        * conditions; since the tuplestore would have been using cross-
+        * transaction storage, its temp files need to be explicitly deleted.
+        */
+       if (portal->holdStore)
+       {
+               MemoryContext oldcontext;
 
-       PortalVariableMemoryDump(PortalGetVariableMemory(*thisP));
-       PortalHeapMemoryDump(PortalGetHeapMemory(*thisP));
-}
+               oldcontext = MemoryContextSwitchTo(portal->holdContext);
+               tuplestore_end(portal->holdStore);
+               MemoryContextSwitchTo(oldcontext);
+               portal->holdStore = NULL;
+       }
 
-#endif
+       /* delete tuplestore storage, if any */
+       if (portal->holdContext)
+               MemoryContextDelete(portal->holdContext);
 
-/* ----------------
- *             DumpPortals
- * ----------------
- */
-#ifdef NOT_USED
-static void
-DumpPortals()
-{
-       /* XXX state checking here */
+       /* release subsidiary storage */
+       MemoryContextDelete(PortalGetHeapMemory(portal));
 
-       HashTableWalk(PortalHashTable, PortalDump, 0);
+       /* release portal struct (it's in PortalMemory) */
+       pfree(portal);
 }
 
-#endif
-
-/* ----------------------------------------------------------------
- *                                public portal interface functions
- * ----------------------------------------------------------------
- */
 /*
- * EnablePortalManager 
- *             Enables/disables the portal management module.
+ * Delete all declared cursors.
+ *
+ * Used by commands: CLOSE ALL, RESET SESSION
  */
 void
-EnablePortalManager(bool on)
+PortalHashTableDeleteAll(void)
 {
-       static bool processing = false;
-       HASHCTL         ctl;
+       HASH_SEQ_STATUS status;
+       PortalHashEnt *hentry;
 
-       AssertState(!processing);
-       AssertArg(BoolIsValid(on));
-
-       if (BypassEnable(&PortalManagerEnableCount, on))
+       if (PortalHashTable == NULL)
                return;
 
-       processing = true;
-
-       if (on)
-       {                                                       /* initialize */
-               EnableMemoryContext(true);
+       hash_seq_init(&status, PortalHashTable);
+       while ((hentry = hash_seq_search(&status)) != NULL)
+       {
+               Portal portal = hentry->portal;
+               if (portal->status != PORTAL_ACTIVE)
+                       PortalDrop(portal, false);
+       }
+}
 
-               PortalMemory = CreateGlobalMemory(PortalMemoryName);
 
-               ctl.keysize = MAX_PORTALNAME_LEN;
-               ctl.datasize = sizeof(Portal);
+/*
+ * Pre-commit processing for portals.
+ *
+ * Any holdable cursors created in this transaction need to be converted to
+ * materialized form, since we are going to close down the executor and
+ * release locks.  Other portals are not touched yet.
+ *
+ * Returns TRUE if any holdable cursors were processed, FALSE if not.
+ */
+bool
+CommitHoldablePortals(void)
+{
+       bool            result = false;
+       HASH_SEQ_STATUS status;
+       PortalHashEnt *hentry;
 
-               /*
-                * use PORTALS_PER_USER, defined in utils/portal.h as a guess of
-                * how many hash table entries to create, initially
-                */
-               PortalHashTable = hash_create(PORTALS_PER_USER * 3, &ctl, HASH_ELEM);
+       hash_seq_init(&status, PortalHashTable);
 
-               CreateNewBlankPortal();
+       while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
+       {
+               Portal          portal = hentry->portal;
 
-       }
-       else
-       {                                                       /* cleanup */
-               if (PortalIsValid(BlankPortal))
+               /* Is it a holdable portal created in the current xact? */
+               if ((portal->cursorOptions & CURSOR_OPT_HOLD) &&
+                       portal->createSubid != InvalidSubTransactionId &&
+                       portal->status == PORTAL_READY)
                {
-                       PortalDestroy(&BlankPortal);
-                       MemoryContextFree((MemoryContext) PortalMemory,
-                                                         (Pointer) BlankPortal);
-                       BlankPortal = NULL;
+                       /*
+                        * We are exiting the transaction that created a holdable cursor.
+                        * Instead of dropping the portal, prepare it for access by later
+                        * transactions.
+                        *
+                        * Note that PersistHoldablePortal() must release all resources
+                        * used by the portal that are local to the creating transaction.
+                        */
+                       PortalCreateHoldStore(portal);
+                       PersistHoldablePortal(portal);
+
+                       /* drop cached plan reference, if any */
+                       if (portal->cplan)
+                               PortalReleaseCachedPlan(portal);
+
+                       /*
+                        * Any resources belonging to the portal will be released in the
+                        * upcoming transaction-wide cleanup; the portal will no longer
+                        * have its own resources.
+                        */
+                       portal->resowner = NULL;
+
+                       /*
+                        * Having successfully exported the holdable cursor, mark it as
+                        * not belonging to this transaction.
+                        */
+                       portal->createSubid = InvalidSubTransactionId;
+
+                       result = true;
                }
-
-               /*
-                * Each portal must free its non-memory resources specially.
-                */
-               HashTableWalk(PortalHashTable, PortalDestroy, 0);
-               hash_destroy(PortalHashTable);
-               PortalHashTable = NULL;
-
-               GlobalMemoryDestroy(PortalMemory);
-               PortalMemory = NULL;
-
-               EnableMemoryContext(true);
        }
 
-       processing = false;
+       return result;
 }
 
 /*
- * GetPortalByName 
- *             Returns a portal given a portal name; returns blank portal given
- * NULL; returns invalid portal if portal not found.
+ * Pre-prepare processing for portals.
  *
- * Exceptions:
- *             BadState if called when disabled.
+ * Currently we refuse PREPARE if the transaction created any holdable
+ * cursors, since it's quite unclear what to do with one.  However, this
+ * has the same API as CommitHoldablePortals and is invoked in the same
+ * way by xact.c, so that we can easily do something reasonable if anyone
+ * comes up with something reasonable to do.
+ *
+ * Returns TRUE if any holdable cursors were processed, FALSE if not.
  */
-Portal
-GetPortalByName(char *name)
+bool
+PrepareHoldablePortals(void)
 {
-       Portal          portal;
+       bool            result = false;
+       HASH_SEQ_STATUS status;
+       PortalHashEnt *hentry;
 
-       AssertState(PortalManagerEnabled);
+       hash_seq_init(&status, PortalHashTable);
 
-       if (PointerIsValid(name))
-               PortalHashTableLookup(name, portal);
-       else
+       while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
        {
-               if (!PortalIsValid(BlankPortal))
-                       CreateNewBlankPortal();
-               portal = BlankPortal;
+               Portal          portal = hentry->portal;
+
+               /* Is it a holdable portal created in the current xact? */
+               if ((portal->cursorOptions & CURSOR_OPT_HOLD) &&
+                       portal->createSubid != InvalidSubTransactionId &&
+                       portal->status == PORTAL_READY)
+               {
+                       /*
+                        * We are exiting the transaction that created a holdable cursor.
+                        * Can't do PREPARE.
+                        */
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+                                        errmsg("cannot PREPARE a transaction that has created a cursor WITH HOLD")));
+               }
        }
 
-       return portal;
+       return result;
 }
 
 /*
- * BlankPortalAssignName 
- *             Returns former blank portal as portal with given name.
- *
- * Side effect:
- *             All references to the former blank portal become incorrect.
+ * Pre-commit processing for portals.
  *
- * Exceptions:
- *             BadState if called when disabled.
- *             BadState if called without an intervening call to GetPortalByName(NULL).
- *             BadArg if portal name is invalid.
- *             "WARN" if portal name is in use.
+ * Remove all non-holdable portals created in this transaction.
+ * Portals remaining from prior transactions should be left untouched.
  */
-Portal
-BlankPortalAssignName(char *name)              /* XXX PortalName */
+void
+AtCommit_Portals(void)
 {
-       Portal          portal;
-       uint16          length;
+       HASH_SEQ_STATUS status;
+       PortalHashEnt *hentry;
 
-       AssertState(PortalManagerEnabled);
-       AssertState(PortalIsValid(BlankPortal));
-       AssertArg(PointerIsValid(name));        /* XXX PortalName */
+       hash_seq_init(&status, PortalHashTable);
 
-       portal = GetPortalByName(name);
-       if (PortalIsValid(portal))
+       while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
        {
-               elog(NOTICE, "BlankPortalAssignName: portal %s already exists", name);
-               return portal;
-       }
+               Portal          portal = hentry->portal;
 
-       /*
-        * remove blank portal
-        */
-       portal = BlankPortal;
-       BlankPortal = NULL;
-
-       /*
-        * initialize portal name
-        */
-       length = 1 + strlen(name);
-       portal->name = (char *)
-               MemoryContextAlloc((MemoryContext) &portal->variable, length);
+               /*
+                * Do not touch active portals --- this can only happen in the case of
+                * a multi-transaction utility command, such as VACUUM.
+                *
+                * Note however that any resource owner attached to such a portal is
+                * still going to go away, so don't leave a dangling pointer.
+                */
+               if (portal->status == PORTAL_ACTIVE)
+               {
+                       portal->resowner = NULL;
+                       continue;
+               }
 
-       strncpy(portal->name, name, length);
+               /*
+                * Do nothing to cursors held over from a previous transaction
+                * (including holdable ones just frozen by CommitHoldablePortals).
+                */
+               if (portal->createSubid == InvalidSubTransactionId)
+                       continue;
 
-       /*
-        * put portal in table
-        */
-       PortalHashTableInsert(portal);
+               /* Zap all non-holdable portals */
+               PortalDrop(portal, true);
 
-       return portal;
+               /* Restart the iteration */
+               hash_seq_init(&status, PortalHashTable);
+       }
 }
 
 /*
- * PortalSetQuery 
- *             Attaches a "query" to portal.
+ * Abort processing for portals.
  *
- * Exceptions:
- *             BadState if called when disabled.
- *             BadArg if portal is invalid.
- *             BadArg if queryDesc is "invalid."
- *             BadArg if state is "invalid."
+ * At this point we reset "active" status and run the cleanup hook if
+ * present, but we can't release the portal's memory until the cleanup call.
+ *
+ * The reason we need to reset active is so that we can replace the unnamed
+ * portal, else we'll fail to execute ROLLBACK when it arrives.
  */
 void
-PortalSetQuery(Portal portal,
-                          QueryDesc *queryDesc,
-                          TupleDesc attinfo,
-                          EState *state,
-                          void (*cleanup) (Portal portal))
+AtAbort_Portals(void)
 {
-       AssertState(PortalManagerEnabled);
-       AssertArg(PortalIsValid(portal));
-       AssertArg(IsA((Node *) state, EState));
+       HASH_SEQ_STATUS status;
+       PortalHashEnt *hentry;
 
-       portal->queryDesc = queryDesc;
-       portal->state = state;
-       portal->attinfo = attinfo;
-       portal->cleanup = cleanup;
-}
+       hash_seq_init(&status, PortalHashTable);
 
-/*
- * PortalGetQueryDesc 
- *             Returns query attached to portal.
- *
- * Exceptions:
- *             BadState if called when disabled.
- *             BadArg if portal is invalid.
- */
-QueryDesc  *
-PortalGetQueryDesc(Portal portal)
-{
-       AssertState(PortalManagerEnabled);
-       AssertArg(PortalIsValid(portal));
+       while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
+       {
+               Portal          portal = hentry->portal;
 
-       return portal->queryDesc;
-}
+               if (portal->status == PORTAL_ACTIVE)
+                       portal->status = PORTAL_FAILED;
 
-/*
- * PortalGetState 
- *             Returns state attached to portal.
- *
- * Exceptions:
- *             BadState if called when disabled.
- *             BadArg if portal is invalid.
- */
-EState *
-PortalGetState(Portal portal)
-{
-       AssertState(PortalManagerEnabled);
-       AssertArg(PortalIsValid(portal));
+               /*
+                * Do nothing else to cursors held over from a previous transaction.
+                */
+               if (portal->createSubid == InvalidSubTransactionId)
+                       continue;
 
-       return portal->state;
-}
+               /* let portalcmds.c clean up the state it knows about */
+               if (PointerIsValid(portal->cleanup))
+               {
+                       (*portal->cleanup) (portal);
+                       portal->cleanup = NULL;
+               }
 
-/*
- * CreatePortal 
- *             Returns a new portal given a name.
- *
- * Note:
- *             This is expected to be of very limited usability.  See instead,
- * BlankPortalAssignName.
- *
- * Exceptions:
- *             BadState if called when disabled.
- *             BadArg if portal name is invalid.
- *             "WARN" if portal name is in use.
- */
-Portal
-CreatePortal(char *name)               /* XXX PortalName */
-{
-       Portal          portal;
-       uint16          length;
+               /* drop cached plan reference, if any */
+               if (portal->cplan)
+                       PortalReleaseCachedPlan(portal);
 
-       AssertState(PortalManagerEnabled);
-       AssertArg(PointerIsValid(name));        /* XXX PortalName */
+               /*
+                * Any resources belonging to the portal will be released in the
+                * upcoming transaction-wide cleanup; they will be gone before we run
+                * PortalDrop.
+                */
+               portal->resowner = NULL;
 
-       portal = GetPortalByName(name);
-       if (PortalIsValid(portal))
-       {
-               elog(NOTICE, "CreatePortal: portal %s already exists", name);
-               return portal;
+               /*
+                * Although we can't delete the portal data structure proper, we can
+                * release any memory in subsidiary contexts, such as executor state.
+                * The cleanup hook was the last thing that might have needed data
+                * there.
+                */
+               MemoryContextDeleteChildren(PortalGetHeapMemory(portal));
        }
-
-       /* make new portal structure */
-       portal = (Portal)
-               MemoryContextAlloc((MemoryContext) PortalMemory, sizeof *portal);
-
-       /* initialize portal variable context */
-       NodeSetTag((Node *) &portal->variable, T_PortalVariableMemory);
-       AllocSetInit(&portal->variable.setData, DynamicAllocMode, (Size) 0);
-       portal->variable.method = &PortalVariableContextMethodsData;
-
-       /* initialize portal heap context */
-       NodeSetTag((Node *) &portal->heap, T_PortalHeapMemory);
-       portal->heap.block = NULL;
-       FixedStackInit(&portal->heap.stackData,
-                                  offsetof(HeapMemoryBlockData, itemData));
-       portal->heap.method = &PortalHeapContextMethodsData;
-
-       /* initialize portal name */
-       length = 1 + strlen(name);
-       portal->name = (char *)
-               MemoryContextAlloc((MemoryContext) &portal->variable, length);
-       strncpy(portal->name, name, length);
-
-       /* initialize portal query */
-       portal->queryDesc = NULL;
-       portal->attinfo = NULL;
-       portal->state = NULL;
-       portal->cleanup = NULL;
-
-       /* put portal in table */
-       PortalHashTableInsert(portal);
-
-       /* Trap(PointerIsValid(name), Unimplemented); */
-       return portal;
 }
 
 /*
- * PortalDestroy 
- *             Destroys portal.
+ * Post-abort cleanup for portals.
  *
- * Exceptions:
- *             BadState if called when disabled.
- *             BadArg if portal is invalid.
- */
+ * Delete all portals not held over from prior transactions.  */
 void
-PortalDestroy(Portal *portalP)
+AtCleanup_Portals(void)
 {
-       Portal          portal = *portalP;
+       HASH_SEQ_STATUS status;
+       PortalHashEnt *hentry;
 
-       AssertState(PortalManagerEnabled);
-       AssertArg(PortalIsValid(portal));
+       hash_seq_init(&status, PortalHashTable);
 
-       /* remove portal from table if not blank portal */
-       if (portal != BlankPortal)
-               PortalHashTableDelete(portal);
-
-       /* reset portal */
-       if (PointerIsValid(portal->cleanup))
-               (*portal->cleanup) (portal);
-
-       PortalResetHeapMemory(portal);
-       MemoryContextFree((MemoryContext) &portal->variable,
-                                         (Pointer) portal->name);
-       AllocSetReset(&portal->variable.setData);       /* XXX log */
+       while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
+       {
+               Portal          portal = hentry->portal;
 
-       /*
-        * In the case of a transaction abort it is possible that
-        * we get called while one of the memory contexts of the portal
-        * we're destroying is the current memory context.
-        * 
-        * Don't know how to handle that cleanly because it is required
-        * to be in that context right now. This portal struct remains
-        * allocated in the PortalMemory context until backend dies.
-        *
-        * Not happy with that, but it's better to loose some bytes of
-        * memory than to have the backend dump core.
-        *
-        * --- Feb. 04, 1999 Jan Wieck
-        */
-       if (CurrentMemoryContext == (MemoryContext)PortalGetHeapMemory(portal))
-               return;
-       if (CurrentMemoryContext == (MemoryContext)PortalGetVariableMemory(portal))
-               return;
+               /* Do nothing to cursors held over from a previous transaction */
+               if (portal->createSubid == InvalidSubTransactionId)
+               {
+                       Assert(portal->status != PORTAL_ACTIVE);
+                       Assert(portal->resowner == NULL);
+                       continue;
+               }
 
-       if (portal != BlankPortal)
-               MemoryContextFree((MemoryContext) PortalMemory, (Pointer) portal);
+               /* Else zap it. */
+               PortalDrop(portal, false);
+       }
 }
 
-/* ----------------
- *             PortalResetHeapMemory 
- *                             Resets portal's heap memory context.
- *
- * Someday, Reset, Start, and End can be optimized by keeping a global
- * portal module stack of free HeapMemoryBlock's.  This will make Start
- * and End be fast.
+/*
+ * Pre-subcommit processing for portals.
  *
- * Exceptions:
- *             BadState if called when disabled.
- *             BadState if called when not in PortalHeapMemory context.
- *             BadArg if mode is invalid.
- * ----------------
+ * Reassign the portals created in the current subtransaction to the parent
+ * subtransaction.
  */
-static void
-PortalResetHeapMemory(Portal portal)
+void
+AtSubCommit_Portals(SubTransactionId mySubid,
+                                       SubTransactionId parentSubid,
+                                       ResourceOwner parentXactOwner)
 {
-       PortalHeapMemory context;
-       MemoryContext currentContext;
+       HASH_SEQ_STATUS status;
+       PortalHashEnt *hentry;
 
-       context = PortalGetHeapMemory(portal);
+       hash_seq_init(&status, PortalHashTable);
 
-       if (PointerIsValid(context->block))
+       while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
        {
-               /* save present context */
-               currentContext = MemoryContextSwitchTo((MemoryContext) context);
+               Portal          portal = hentry->portal;
 
-               do
+               if (portal->createSubid == mySubid)
                {
-                       EndPortalAllocMode();
-               } while (PointerIsValid(context->block));
-
-               /* restore context */
-               MemoryContextSwitchTo(currentContext);
+                       portal->createSubid = parentSubid;
+                       if (portal->resowner)
+                               ResourceOwnerNewParent(portal->resowner, parentXactOwner);
+               }
        }
 }
 
 /*
- * StartPortalAllocMode 
- *             Starts a new block of portal heap allocation using mode and limit;
- *             the current block is disabled until EndPortalAllocMode is called.
+ * Subtransaction abort handling for portals.
  *
- * Note:
- *             Note blocks may be stacked and restored arbitarily.
- *             The semantics of mode and limit are described in aset.h.
+ * Deactivate portals created during the failed subtransaction.
+ * Note that per AtSubCommit_Portals, this will catch portals created
+ * in descendants of the subtransaction too.
  *
- * Exceptions:
- *             BadState if called when disabled.
- *             BadState if called when not in PortalHeapMemory context.
- *             BadArg if mode is invalid.
+ * We don't destroy any portals here; that's done in AtSubCleanup_Portals.
  */
 void
-StartPortalAllocMode(AllocMode mode, Size limit)
+AtSubAbort_Portals(SubTransactionId mySubid,
+                                  SubTransactionId parentSubid,
+                                  ResourceOwner parentXactOwner)
 {
-       PortalHeapMemory context;
-
-       AssertState(PortalManagerEnabled);
-       AssertState(IsA(CurrentMemoryContext, PortalHeapMemory));
-       /* AssertArg(AllocModeIsValid); */
+       HASH_SEQ_STATUS status;
+       PortalHashEnt *hentry;
 
-       context = (PortalHeapMemory) CurrentMemoryContext;
+       hash_seq_init(&status, PortalHashTable);
 
-       /* stack current mode */
-       if (PointerIsValid(context->block))
-               FixedStackPush(&context->stackData, context->block);
+       while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
+       {
+               Portal          portal = hentry->portal;
 
-       /* allocate and initialize new block */
-       context->block = MemoryContextAlloc(
-                         (MemoryContext) PortalHeapMemoryGetVariableMemory(context),
-                                                  sizeof(HeapMemoryBlockData));
+               if (portal->createSubid != mySubid)
+                       continue;
 
-       /* XXX careful, context->block has never been stacked => bad state */
+               /*
+                * Force any active portals of my own transaction into FAILED state.
+                * This is mostly to ensure that a portal running a FETCH will go
+                * FAILED if the underlying cursor fails.  (Note we do NOT want to do
+                * this to upper-level portals, since they may be able to continue.)
+                *
+                * This is only needed to dodge the sanity check in PortalDrop.
+                */
+               if (portal->status == PORTAL_ACTIVE)
+                       portal->status = PORTAL_FAILED;
 
-       AllocSetInit(&HEAPMEMBLOCK(context)->setData, mode, limit);
+               /*
+                * If the portal is READY then allow it to survive into the parent
+                * transaction; otherwise shut it down.
+                *
+                * Currently, we can't actually support that because the portal's
+                * query might refer to objects created or changed in the failed
+                * subtransaction, leading to crashes if execution is resumed. So,
+                * even READY portals are deleted.      It would be nice to detect whether
+                * the query actually depends on any such object, instead.
+                */
+#ifdef NOT_USED
+               if (portal->status == PORTAL_READY)
+               {
+                       portal->createSubid = parentSubid;
+                       if (portal->resowner)
+                               ResourceOwnerNewParent(portal->resowner, parentXactOwner);
+               }
+               else
+#endif
+               {
+                       /* let portalcmds.c clean up the state it knows about */
+                       if (PointerIsValid(portal->cleanup))
+                       {
+                               (*portal->cleanup) (portal);
+                               portal->cleanup = NULL;
+                       }
+
+                       /* drop cached plan reference, if any */
+                       if (portal->cplan)
+                               PortalReleaseCachedPlan(portal);
+
+                       /*
+                        * Any resources belonging to the portal will be released in the
+                        * upcoming transaction-wide cleanup; they will be gone before we
+                        * run PortalDrop.
+                        */
+                       portal->resowner = NULL;
+
+                       /*
+                        * Although we can't delete the portal data structure proper, we
+                        * can release any memory in subsidiary contexts, such as executor
+                        * state.  The cleanup hook was the last thing that might have
+                        * needed data there.
+                        */
+                       MemoryContextDeleteChildren(PortalGetHeapMemory(portal));
+               }
+       }
 }
 
 /*
- * EndPortalAllocMode 
- *             Ends current block of portal heap allocation; previous block is
- *             reenabled.
- *
- * Note:
- *             Note blocks may be stacked and restored arbitarily.
+ * Post-subabort cleanup for portals.
  *
- * Exceptions:
- *             BadState if called when disabled.
- *             BadState if called when not in PortalHeapMemory context.
+ * Drop all portals created in the failed subtransaction (but note that
+ * we will not drop any that were reassigned to the parent above).
  */
 void
-EndPortalAllocMode()
+AtSubCleanup_Portals(SubTransactionId mySubid)
 {
-       PortalHeapMemory context;
+       HASH_SEQ_STATUS status;
+       PortalHashEnt *hentry;
 
-       AssertState(PortalManagerEnabled);
-       AssertState(IsA(CurrentMemoryContext, PortalHeapMemory));
+       hash_seq_init(&status, PortalHashTable);
 
-       context = (PortalHeapMemory) CurrentMemoryContext;
-       AssertState(PointerIsValid(context->block));            /* XXX Trap(...) */
+       while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
+       {
+               Portal          portal = hentry->portal;
 
-       /* free current mode */
-       AllocSetReset(&HEAPMEMBLOCK(context)->setData);
-       MemoryContextFree((MemoryContext) PortalHeapMemoryGetVariableMemory(context),
-                                         context->block);
+               if (portal->createSubid != mySubid)
+                       continue;
 
-       /* restore previous mode */
-       context->block = FixedStackPop(&context->stackData);
+               /* Zap it. */
+               PortalDrop(portal, false);
+       }
 }
 
-/*
- * PortalGetVariableMemory 
- *             Returns variable memory context for a given portal.
- *
- * Exceptions:
- *             BadState if called when disabled.
- *             BadArg if portal is invalid.
- */
-PortalVariableMemory
-PortalGetVariableMemory(Portal portal)
+/* Find all available cursors */
+Datum
+pg_cursor(PG_FUNCTION_ARGS)
 {
-       return &portal->variable;
-}
+       FuncCallContext *funcctx;
+       HASH_SEQ_STATUS *hash_seq;
+       PortalHashEnt *hentry;
 
-/*
- * PortalGetHeapMemory 
- *             Returns heap memory context for a given portal.
- *
- * Exceptions:
- *             BadState if called when disabled.
- *             BadArg if portal is invalid.
- */
-PortalHeapMemory
-PortalGetHeapMemory(Portal portal)
-{
-       return &portal->heap;
-}
+       /* stuff done only on the first call of the function */
+       if (SRF_IS_FIRSTCALL())
+       {
+               MemoryContext oldcontext;
+               TupleDesc       tupdesc;
 
-/*
- * PortalVariableMemoryGetPortal 
- *             Returns portal containing given variable memory context.
- *
- * Exceptions:
- *             BadState if called when disabled.
- *             BadArg if context is invalid.
- */
-static Portal
-PortalVariableMemoryGetPortal(PortalVariableMemory context)
-{
-       return (Portal) ((char *) context - offsetof(PortalD, variable));
-}
+               /* create a function context for cross-call persistence */
+               funcctx = SRF_FIRSTCALL_INIT();
 
-/*
- * PortalHeapMemoryGetPortal 
- *             Returns portal containing given heap memory context.
- *
- * Exceptions:
- *             BadState if called when disabled.
- *             BadArg if context is invalid.
- */
-static Portal
-PortalHeapMemoryGetPortal(PortalHeapMemory context)
-{
-       return (Portal) ((char *) context - offsetof(PortalD, heap));
-}
+               /*
+                * switch to memory context appropriate for multiple function calls
+                */
+               oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
 
-/*
- * PortalVariableMemoryGetHeapMemory 
- *             Returns heap memory context associated with given variable memory.
- *
- * Exceptions:
- *             BadState if called when disabled.
- *             BadArg if context is invalid.
- */
-#ifdef NOT_USED
-PortalHeapMemory
-PortalVariableMemoryGetHeapMemory(PortalVariableMemory context)
-{
-       return ((PortalHeapMemory) ((char *) context
-                                                               - offsetof(PortalD, variable)
-                                                               +offsetof(PortalD, heap)));
-}
+               if (PortalHashTable)
+               {
+                       hash_seq = (HASH_SEQ_STATUS *) palloc(sizeof(HASH_SEQ_STATUS));
+                       hash_seq_init(hash_seq, PortalHashTable);
+                       funcctx->user_fctx = (void *) hash_seq;
+               }
+               else
+                       funcctx->user_fctx = NULL;
 
-#endif
+               /*
+                * build tupdesc for result tuples. This must match the definition of
+                * the pg_cursors view in system_views.sql
+                */
+               tupdesc = CreateTemplateTupleDesc(6, false);
+               TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
+                                                  TEXTOID, -1, 0);
+               TupleDescInitEntry(tupdesc, (AttrNumber) 2, "statement",
+                                                  TEXTOID, -1, 0);
+               TupleDescInitEntry(tupdesc, (AttrNumber) 3, "is_holdable",
+                                                  BOOLOID, -1, 0);
+               TupleDescInitEntry(tupdesc, (AttrNumber) 4, "is_binary",
+                                                  BOOLOID, -1, 0);
+               TupleDescInitEntry(tupdesc, (AttrNumber) 5, "is_scrollable",
+                                                  BOOLOID, -1, 0);
+               TupleDescInitEntry(tupdesc, (AttrNumber) 6, "creation_time",
+                                                  TIMESTAMPTZOID, -1, 0);
+
+               funcctx->tuple_desc = BlessTupleDesc(tupdesc);
+               MemoryContextSwitchTo(oldcontext);
+       }
 
-/*
- * PortalHeapMemoryGetVariableMemory 
- *             Returns variable memory context associated with given heap memory.
- *
- * Exceptions:
- *             BadState if called when disabled.
- *             BadArg if context is invalid.
- */
-static PortalVariableMemory
-PortalHeapMemoryGetVariableMemory(PortalHeapMemory context)
-{
-       return ((PortalVariableMemory) ((char *) context
-                                                                       - offsetof(PortalD, heap)
-                                                                       +offsetof(PortalD, variable)));
+       /* stuff done on every call of the function */
+       funcctx = SRF_PERCALL_SETUP();
+       hash_seq = (HASH_SEQ_STATUS *) funcctx->user_fctx;
+
+       /* if the hash table is uninitialized, we're done */
+       if (hash_seq == NULL)
+               SRF_RETURN_DONE(funcctx);
+
+       /* loop until we find a visible portal or hit the end of the list */
+       while ((hentry = hash_seq_search(hash_seq)) != NULL)
+       {
+               if (hentry->portal->visible)
+                       break;
+       }
+
+       if (hentry)
+       {
+               Portal          portal;
+               Datum           result;
+               HeapTuple       tuple;
+               Datum           values[6];
+               bool            nulls[6];
+
+               portal = hentry->portal;
+               MemSet(nulls, 0, sizeof(nulls));
+
+               values[0] = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
+               if (!portal->sourceText)
+                       nulls[1] = true;
+               else
+                       values[1] = DirectFunctionCall1(textin,
+                                                                               CStringGetDatum(portal->sourceText));
+               values[2] = BoolGetDatum(portal->cursorOptions & CURSOR_OPT_HOLD);
+               values[3] = BoolGetDatum(portal->cursorOptions & CURSOR_OPT_BINARY);
+               values[4] = BoolGetDatum(portal->cursorOptions & CURSOR_OPT_SCROLL);
+               values[5] = TimestampTzGetDatum(portal->creation_time);
+
+               tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
+               result = HeapTupleGetDatum(tuple);
+               SRF_RETURN_NEXT(funcctx, result);
+       }
+
+       SRF_RETURN_DONE(funcctx);
 }