1 /*-------------------------------------------------------------------------
4 * Utility commands affecting portals (that is, SQL cursor commands)
6 * Note: see also tcop/pquery.c, which implements portal operations for
7 * the FE/BE protocol. This module uses pquery.c for some operations.
8 * And both modules depend on utils/mmgr/portalmem.c, which controls
9 * storage management for portals (but doesn't run any queries in them).
12 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
13 * Portions Copyright (c) 1994, Regents of the University of California
17 * $Header: /cvsroot/pgsql/src/backend/commands/portalcmds.c,v 1.23 2003/08/08 21:41:32 momjian Exp $
19 *-------------------------------------------------------------------------
26 #include "commands/portalcmds.h"
27 #include "executor/executor.h"
28 #include "optimizer/planner.h"
29 #include "rewrite/rewriteHandler.h"
30 #include "tcop/pquery.h"
31 #include "utils/memutils.h"
36 * Execute SQL DECLARE CURSOR command.
39 PerformCursorOpen(DeclareCursorStmt *stmt)
45 MemoryContext oldContext;
48 * Disallow empty-string cursor name (conflicts with protocol-level
51 if (!stmt->portalname || stmt->portalname[0] == '\0')
53 (errcode(ERRCODE_INVALID_CURSOR_NAME),
54 errmsg("invalid cursor name: must not be empty")));
57 * If this is a non-holdable cursor, we require that this statement
58 * has been executed inside a transaction block (or else, it would
59 * have no user-visible effect).
61 if (!(stmt->options & CURSOR_OPT_HOLD))
62 RequireTransactionChain((void *) stmt, "DECLARE CURSOR");
65 * The query has been through parse analysis, but not rewriting or
66 * planning as yet. Note that the grammar ensured we have a SELECT
67 * query, so we are not expecting rule rewriting to do anything
70 rewritten = QueryRewrite((Query *) stmt->query);
71 if (length(rewritten) != 1 || !IsA(lfirst(rewritten), Query))
72 elog(ERROR, "unexpected rewrite result");
73 query = (Query *) lfirst(rewritten);
74 if (query->commandType != CMD_SELECT)
75 elog(ERROR, "unexpected rewrite result");
79 (errcode(ERRCODE_SYNTAX_ERROR),
80 errmsg("DECLARE CURSOR may not specify INTO")));
81 if (query->rowMarks != NIL)
83 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
84 errmsg("DECLARE CURSOR ... FOR UPDATE is not supported"),
85 errdetail("Cursors must be READ ONLY.")));
87 plan = planner(query, true, stmt->options);
90 * Create a portal and copy the query and plan into its memory
91 * context. (If a duplicate cursor name already exists, warn and drop
94 portal = CreatePortal(stmt->portalname, true, false);
96 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
98 query = copyObject(query);
99 plan = copyObject(plan);
101 PortalDefineQuery(portal,
102 NULL, /* unfortunately don't have sourceText */
103 "SELECT", /* cursor's query is always a SELECT */
106 PortalGetHeapMemory(portal));
108 MemoryContextSwitchTo(oldContext);
111 * Set up options for portal.
113 * If the user didn't specify a SCROLL type, allow or disallow scrolling
114 * based on whether it would require any additional runtime overhead
117 portal->cursorOptions = stmt->options;
118 if (!(portal->cursorOptions & (CURSOR_OPT_SCROLL | CURSOR_OPT_NO_SCROLL)))
120 if (ExecSupportsBackwardScan(plan))
121 portal->cursorOptions |= CURSOR_OPT_SCROLL;
123 portal->cursorOptions |= CURSOR_OPT_NO_SCROLL;
127 * Start execution --- never any params for a cursor.
129 PortalStart(portal, NULL);
131 Assert(portal->strategy == PORTAL_ONE_SELECT);
134 * We're done; the query won't actually be run until
135 * PerformPortalFetch is called.
141 * Execute SQL FETCH or MOVE command.
143 * stmt: parsetree node for command
144 * dest: where to send results
145 * completionTag: points to a buffer of size COMPLETION_TAG_BUFSIZE
146 * in which to store a command completion status string.
148 * completionTag may be NULL if caller doesn't want a status string.
151 PerformPortalFetch(FetchStmt *stmt,
159 * Disallow empty-string cursor name (conflicts with protocol-level
162 if (!stmt->portalname || stmt->portalname[0] == '\0')
164 (errcode(ERRCODE_INVALID_CURSOR_NAME),
165 errmsg("invalid cursor name: must not be empty")));
167 /* get the portal from the portal name */
168 portal = GetPortalByName(stmt->portalname);
169 if (!PortalIsValid(portal))
171 /* FIXME: shouldn't this be an ERROR? */
173 (errcode(ERRCODE_UNDEFINED_CURSOR),
174 errmsg("portal \"%s\" does not exist", stmt->portalname)));
176 strcpy(completionTag, stmt->ismove ? "MOVE 0" : "FETCH 0");
180 /* Adjust dest if needed. MOVE wants destination None */
182 dest = None_Receiver;
185 nprocessed = PortalRunFetch(portal,
190 /* Return command status if wanted */
192 snprintf(completionTag, COMPLETION_TAG_BUFSIZE, "%s %ld",
193 stmt->ismove ? "MOVE" : "FETCH",
202 PerformPortalClose(const char *name)
207 * Disallow empty-string cursor name (conflicts with protocol-level
210 if (!name || name[0] == '\0')
212 (errcode(ERRCODE_INVALID_CURSOR_NAME),
213 errmsg("invalid cursor name: must not be empty")));
216 * get the portal from the portal name
218 portal = GetPortalByName(name);
219 if (!PortalIsValid(portal))
222 (errcode(ERRCODE_UNDEFINED_CURSOR),
223 errmsg("portal \"%s\" does not exist", name),
224 errfunction("PerformPortalClose"))); /* for ecpg */
229 * Note: PortalCleanup is called as a side-effect
231 PortalDrop(portal, false);
237 * Clean up a portal when it's dropped. This is the standard cleanup hook
241 PortalCleanup(Portal portal, bool isError)
243 QueryDesc *queryDesc;
248 AssertArg(PortalIsValid(portal));
249 AssertArg(portal->cleanup == PortalCleanup);
252 * Shut down executor, if still running. We skip this during error
253 * abort, since other mechanisms will take care of releasing executor
254 * resources, and we can't be sure that ExecutorEnd itself wouldn't
257 queryDesc = PortalGetQueryDesc(portal);
260 portal->queryDesc = NULL;
262 ExecutorEnd(queryDesc);
267 * PersistHoldablePortal
269 * Prepare the specified Portal for access outside of the current
270 * transaction. When this function returns, all future accesses to the
271 * portal must be done via the Tuplestore (not by invoking the
275 PersistHoldablePortal(Portal portal)
277 QueryDesc *queryDesc = PortalGetQueryDesc(portal);
278 MemoryContext savePortalContext;
279 MemoryContext saveQueryContext;
280 MemoryContext oldcxt;
283 * If we're preserving a holdable portal, we had better be inside the
284 * transaction that originally created it.
286 Assert(portal->createXact == GetCurrentTransactionId());
287 Assert(queryDesc != NULL);
288 Assert(portal->portalReady);
289 Assert(!portal->portalDone);
292 * Caller must have created the tuplestore already.
294 Assert(portal->holdContext != NULL);
295 Assert(portal->holdStore != NULL);
298 * Before closing down the executor, we must copy the tupdesc into
299 * long-term memory, since it was created in executor memory.
301 oldcxt = MemoryContextSwitchTo(portal->holdContext);
303 portal->tupDesc = CreateTupleDescCopy(portal->tupDesc);
305 MemoryContextSwitchTo(oldcxt);
308 * Check for improper portal use, and mark portal active.
310 if (portal->portalActive)
312 (errcode(ERRCODE_OBJECT_IN_USE),
313 errmsg("portal \"%s\" already active", portal->name)));
314 portal->portalActive = true;
317 * Set global portal context pointers.
319 savePortalContext = PortalContext;
320 PortalContext = PortalGetHeapMemory(portal);
321 saveQueryContext = QueryContext;
322 QueryContext = portal->queryContext;
324 MemoryContextSwitchTo(PortalContext);
327 * Rewind the executor: we need to store the entire result set in the
328 * tuplestore, so that subsequent backward FETCHs can be processed.
330 ExecutorRewind(queryDesc);
332 /* Change the destination to output to the tuplestore */
333 queryDesc->dest = CreateDestReceiver(Tuplestore, portal);
335 /* Fetch the result set into the tuplestore */
336 ExecutorRun(queryDesc, ForwardScanDirection, 0L);
338 (*queryDesc->dest->rDestroy) (queryDesc->dest);
339 queryDesc->dest = NULL;
342 * Now shut down the inner executor.
344 portal->queryDesc = NULL; /* prevent double shutdown */
345 ExecutorEnd(queryDesc);
347 /* Mark portal not active */
348 portal->portalActive = false;
350 PortalContext = savePortalContext;
351 QueryContext = saveQueryContext;
354 * Reset the position in the result set: ideally, this could be
355 * implemented by just skipping straight to the tuple # that we need
356 * to be at, but the tuplestore API doesn't support that. So we start
357 * at the beginning of the tuplestore and iterate through it until we
358 * reach where we need to be. FIXME someday?
360 MemoryContextSwitchTo(portal->holdContext);
366 if (portal->posOverflow) /* oops, cannot trust portalPos */
368 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
369 errmsg("could not reposition held cursor")));
371 tuplestore_rescan(portal->holdStore);
373 for (store_pos = 0; store_pos < portal->portalPos; store_pos++)
378 tup = tuplestore_gettuple(portal->holdStore, true,
382 elog(ERROR, "unexpected end of tuple stream");
389 MemoryContextSwitchTo(oldcxt);
392 * We can now release any subsidiary memory of the portal's heap
393 * context; we'll never use it again. The executor already dropped
394 * its context, but this will clean up anything that glommed onto the
395 * portal's heap via PortalContext.
397 MemoryContextDeleteChildren(PortalGetHeapMemory(portal));