1 /*-------------------------------------------------------------------------
4 * POSTGRES process query command code
6 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/tcop/pquery.c,v 1.107 2006/08/14 22:57:15 tgl Exp $
13 *-------------------------------------------------------------------------
18 #include "access/xact.h"
19 #include "commands/prepare.h"
20 #include "commands/trigger.h"
21 #include "miscadmin.h"
22 #include "tcop/pquery.h"
23 #include "tcop/tcopprot.h"
24 #include "tcop/utility.h"
25 #include "utils/memutils.h"
29 * ActivePortal is the currently executing Portal (the most closely nested,
30 * if there are several).
32 Portal ActivePortal = NULL;
35 static void ProcessQuery(Query *parsetree,
40 static void FillPortalStore(Portal portal);
41 static uint32 RunFromStore(Portal portal, ScanDirection direction, long count,
43 static long PortalRunSelect(Portal portal, bool forward, long count,
45 static void PortalRunUtility(Portal portal, Query *query,
46 DestReceiver *dest, char *completionTag);
47 static void PortalRunMulti(Portal portal,
48 DestReceiver *dest, DestReceiver *altdest,
50 static long DoPortalRunFetch(Portal portal,
51 FetchDirection fdirection,
54 static void DoPortalRewind(Portal portal);
61 CreateQueryDesc(Query *parsetree,
64 Snapshot crosscheck_snapshot,
69 QueryDesc *qd = (QueryDesc *) palloc(sizeof(QueryDesc));
71 qd->operation = parsetree->commandType; /* operation */
72 qd->parsetree = parsetree; /* parse tree */
73 qd->plantree = plantree; /* plan */
74 qd->snapshot = snapshot; /* snapshot */
75 qd->crosscheck_snapshot = crosscheck_snapshot; /* RI check snapshot */
76 qd->dest = dest; /* output dest */
77 qd->params = params; /* parameter values passed into query */
78 qd->doInstrument = doInstrument; /* instrumentation wanted? */
80 /* null these fields until set by ExecutorStart */
92 FreeQueryDesc(QueryDesc *qdesc)
94 /* Can't be a live query */
95 Assert(qdesc->estate == NULL);
96 /* Only the QueryDesc itself need be freed */
103 * Execute a single plannable query within a PORTAL_MULTI_QUERY
104 * or PORTAL_ONE_RETURNING portal
106 * parsetree: the query tree
107 * plan: the plan tree for the query
108 * params: any parameters needed
109 * dest: where to send results
110 * completionTag: points to a buffer of size COMPLETION_TAG_BUFSIZE
111 * in which to store a command completion status string.
113 * completionTag may be NULL if caller doesn't want a status string.
115 * Must be called in a memory context that will be reset or deleted on
116 * error; otherwise the executor's memory usage will be leaked.
119 ProcessQuery(Query *parsetree,
121 ParamListInfo params,
125 int operation = parsetree->commandType;
126 QueryDesc *queryDesc;
129 (errmsg_internal("ProcessQuery")));
132 * Must always set snapshot for plannable queries. Note we assume that
133 * caller will take care of restoring ActiveSnapshot on exit/error.
135 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
138 * Create the QueryDesc object
140 queryDesc = CreateQueryDesc(parsetree, plan,
141 ActiveSnapshot, InvalidSnapshot,
142 dest, params, false);
145 * Set up to collect AFTER triggers
147 AfterTriggerBeginQuery();
150 * Call ExecutorStart to prepare the plan for execution
152 ExecutorStart(queryDesc, 0);
155 * Run the plan to completion.
157 ExecutorRun(queryDesc, ForwardScanDirection, 0L);
160 * Build command completion status string, if caller wants one.
169 strcpy(completionTag, "SELECT");
172 if (queryDesc->estate->es_processed == 1)
173 lastOid = queryDesc->estate->es_lastoid;
175 lastOid = InvalidOid;
176 snprintf(completionTag, COMPLETION_TAG_BUFSIZE,
177 "INSERT %u %u", lastOid, queryDesc->estate->es_processed);
180 snprintf(completionTag, COMPLETION_TAG_BUFSIZE,
181 "UPDATE %u", queryDesc->estate->es_processed);
184 snprintf(completionTag, COMPLETION_TAG_BUFSIZE,
185 "DELETE %u", queryDesc->estate->es_processed);
188 strcpy(completionTag, "???");
193 /* Now take care of any queued AFTER triggers */
194 AfterTriggerEndQuery(queryDesc->estate);
197 * Now, we close down all the scans and free allocated resources.
199 ExecutorEnd(queryDesc);
201 FreeQueryDesc(queryDesc);
203 FreeSnapshot(ActiveSnapshot);
204 ActiveSnapshot = NULL;
208 * ChoosePortalStrategy
209 * Select portal execution strategy given the intended query list.
211 * See the comments in portal.h.
214 ChoosePortalStrategy(List *parseTrees)
220 * PORTAL_ONE_SELECT and PORTAL_UTIL_SELECT need only consider the
221 * single-Query-struct case, since there are no rewrite rules that
222 * can add auxiliary queries to a SELECT or a utility command.
224 if (list_length(parseTrees) == 1)
226 Query *query = (Query *) linitial(parseTrees);
228 Assert(IsA(query, Query));
229 if (query->canSetTag)
231 if (query->commandType == CMD_SELECT &&
233 return PORTAL_ONE_SELECT;
234 if (query->commandType == CMD_UTILITY &&
235 query->utilityStmt != NULL)
237 if (UtilityReturnsTuples(query->utilityStmt))
238 return PORTAL_UTIL_SELECT;
239 /* it can't be ONE_RETURNING, so give up */
240 return PORTAL_MULTI_QUERY;
246 * PORTAL_ONE_RETURNING has to allow auxiliary queries added by rewrite.
247 * Choose PORTAL_ONE_RETURNING if there is exactly one canSetTag query
248 * and it has a RETURNING list.
251 foreach(lc, parseTrees)
253 Query *query = (Query *) lfirst(lc);
255 Assert(IsA(query, Query));
256 if (query->canSetTag)
259 return PORTAL_MULTI_QUERY; /* no need to look further */
260 if (query->returningList == NIL)
261 return PORTAL_MULTI_QUERY; /* no need to look further */
265 return PORTAL_ONE_RETURNING;
267 /* Else, it's the general case... */
268 return PORTAL_MULTI_QUERY;
272 * FetchPortalTargetList
273 * Given a portal that returns tuples, extract the query targetlist.
274 * Returns NIL if the portal doesn't have a determinable targetlist.
276 * Note: do not modify the result.
278 * XXX be careful to keep this in sync with FetchPreparedStatementTargetList,
279 * and with UtilityReturnsTuples.
282 FetchPortalTargetList(Portal portal)
284 if (portal->strategy == PORTAL_ONE_SELECT)
285 return ((Query *) linitial(portal->parseTrees))->targetList;
286 if (portal->strategy == PORTAL_ONE_RETURNING)
287 return (PortalGetPrimaryQuery(portal))->returningList;
288 if (portal->strategy == PORTAL_UTIL_SELECT)
292 utilityStmt = ((Query *) linitial(portal->parseTrees))->utilityStmt;
293 switch (nodeTag(utilityStmt))
297 FetchStmt *substmt = (FetchStmt *) utilityStmt;
300 Assert(!substmt->ismove);
301 subportal = GetPortalByName(substmt->portalname);
302 Assert(PortalIsValid(subportal));
303 return FetchPortalTargetList(subportal);
308 ExecuteStmt *substmt = (ExecuteStmt *) utilityStmt;
309 PreparedStatement *entry;
311 Assert(!substmt->into);
312 entry = FetchPreparedStatement(substmt->name, true);
313 return FetchPreparedStatementTargetList(entry);
325 * Prepare a portal for execution.
327 * Caller must already have created the portal, done PortalDefineQuery(),
328 * and adjusted portal options if needed. If parameters are needed by
329 * the query, they must be passed in here (caller is responsible for
330 * giving them appropriate lifetime).
332 * The caller can optionally pass a snapshot to be used; pass InvalidSnapshot
333 * for the normal behavior of setting a new snapshot. This parameter is
334 * presently ignored for non-PORTAL_ONE_SELECT portals (it's only intended
335 * to be used for cursors).
337 * On return, portal is ready to accept PortalRun() calls, and the result
338 * tupdesc (if any) is known.
341 PortalStart(Portal portal, ParamListInfo params, Snapshot snapshot)
343 Portal saveActivePortal;
344 Snapshot saveActiveSnapshot;
345 ResourceOwner saveResourceOwner;
346 MemoryContext savePortalContext;
347 MemoryContext oldContext;
348 QueryDesc *queryDesc;
351 AssertArg(PortalIsValid(portal));
352 AssertState(portal->queryContext != NULL); /* query defined? */
353 AssertState(portal->status == PORTAL_NEW); /* else extra PortalStart */
356 * Set up global portal context pointers. (Should we set QueryContext?)
358 saveActivePortal = ActivePortal;
359 saveActiveSnapshot = ActiveSnapshot;
360 saveResourceOwner = CurrentResourceOwner;
361 savePortalContext = PortalContext;
364 ActivePortal = portal;
365 ActiveSnapshot = NULL; /* will be set later */
366 CurrentResourceOwner = portal->resowner;
367 PortalContext = PortalGetHeapMemory(portal);
369 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
371 /* Must remember portal param list, if any */
372 portal->portalParams = params;
375 * Determine the portal execution strategy
377 portal->strategy = ChoosePortalStrategy(portal->parseTrees);
380 * Fire her up according to the strategy
382 switch (portal->strategy)
384 case PORTAL_ONE_SELECT:
387 * Must set snapshot before starting executor. Be sure to
388 * copy it into the portal's context.
391 ActiveSnapshot = CopySnapshot(snapshot);
393 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
396 * Create QueryDesc in portal's context; for the moment, set
397 * the destination to DestNone.
399 queryDesc = CreateQueryDesc((Query *) linitial(portal->parseTrees),
400 (Plan *) linitial(portal->planTrees),
408 * We do *not* call AfterTriggerBeginQuery() here. We assume
409 * that a SELECT cannot queue any triggers. It would be messy
410 * to support triggers since the execution of the portal may
411 * be interleaved with other queries.
415 * If it's a scrollable cursor, executor needs to support
416 * REWIND and backwards scan.
418 if (portal->cursorOptions & CURSOR_OPT_SCROLL)
419 eflags = EXEC_FLAG_REWIND | EXEC_FLAG_BACKWARD;
421 eflags = 0; /* default run-to-completion flags */
424 * Call ExecutorStart to prepare the plan for execution
426 ExecutorStart(queryDesc, eflags);
429 * This tells PortalCleanup to shut down the executor
431 portal->queryDesc = queryDesc;
434 * Remember tuple descriptor (computed by ExecutorStart)
436 portal->tupDesc = queryDesc->tupDesc;
439 * Reset cursor position data to "start of query"
441 portal->atStart = true;
442 portal->atEnd = false; /* allow fetches */
443 portal->portalPos = 0;
444 portal->posOverflow = false;
447 case PORTAL_ONE_RETURNING:
450 * We don't start the executor until we are told to run
451 * the portal. We do need to set up the result tupdesc.
454 ExecCleanTypeFromTL((PortalGetPrimaryQuery(portal))->returningList, false);
457 * Reset cursor position data to "start of query"
459 portal->atStart = true;
460 portal->atEnd = false; /* allow fetches */
461 portal->portalPos = 0;
462 portal->posOverflow = false;
465 case PORTAL_UTIL_SELECT:
468 * We don't set snapshot here, because PortalRunUtility will
469 * take care of it if needed.
472 UtilityTupleDescriptor(((Query *) linitial(portal->parseTrees))->utilityStmt);
475 * Reset cursor position data to "start of query"
477 portal->atStart = true;
478 portal->atEnd = false; /* allow fetches */
479 portal->portalPos = 0;
480 portal->posOverflow = false;
483 case PORTAL_MULTI_QUERY:
484 /* Need do nothing now */
485 portal->tupDesc = NULL;
491 /* Uncaught error while executing portal: mark it dead */
492 portal->status = PORTAL_FAILED;
494 /* Restore global vars and propagate error */
495 ActivePortal = saveActivePortal;
496 ActiveSnapshot = saveActiveSnapshot;
497 CurrentResourceOwner = saveResourceOwner;
498 PortalContext = savePortalContext;
504 MemoryContextSwitchTo(oldContext);
506 ActivePortal = saveActivePortal;
507 ActiveSnapshot = saveActiveSnapshot;
508 CurrentResourceOwner = saveResourceOwner;
509 PortalContext = savePortalContext;
511 portal->status = PORTAL_READY;
515 * PortalSetResultFormat
516 * Select the format codes for a portal's output.
518 * This must be run after PortalStart for a portal that will be read by
519 * a DestRemote or DestRemoteExecute destination. It is not presently needed
520 * for other destination types.
522 * formats[] is the client format request, as per Bind message conventions.
525 PortalSetResultFormat(Portal portal, int nFormats, int16 *formats)
530 /* Do nothing if portal won't return tuples */
531 if (portal->tupDesc == NULL)
533 natts = portal->tupDesc->natts;
534 portal->formats = (int16 *)
535 MemoryContextAlloc(PortalGetHeapMemory(portal),
536 natts * sizeof(int16));
539 /* format specified for each column */
540 if (nFormats != natts)
542 (errcode(ERRCODE_PROTOCOL_VIOLATION),
543 errmsg("bind message has %d result formats but query has %d columns",
545 memcpy(portal->formats, formats, natts * sizeof(int16));
547 else if (nFormats > 0)
549 /* single format specified, use for all columns */
550 int16 format1 = formats[0];
552 for (i = 0; i < natts; i++)
553 portal->formats[i] = format1;
557 /* use default format for all columns */
558 for (i = 0; i < natts; i++)
559 portal->formats[i] = 0;
565 * Run a portal's query or queries.
567 * count <= 0 is interpreted as a no-op: the destination gets started up
568 * and shut down, but nothing else happens. Also, count == FETCH_ALL is
569 * interpreted as "all rows". Note that count is ignored in multi-query
570 * situations, where we always run the portal to completion.
572 * dest: where to send output of primary (canSetTag) query
574 * altdest: where to send output of non-primary queries
576 * completionTag: points to a buffer of size COMPLETION_TAG_BUFSIZE
577 * in which to store a command completion status string.
578 * May be NULL if caller doesn't want a status string.
580 * Returns TRUE if the portal's execution is complete, FALSE if it was
581 * suspended due to exhaustion of the count parameter.
584 PortalRun(Portal portal, long count,
585 DestReceiver *dest, DestReceiver *altdest,
589 ResourceOwner saveTopTransactionResourceOwner;
590 MemoryContext saveTopTransactionContext;
591 Portal saveActivePortal;
592 Snapshot saveActiveSnapshot;
593 ResourceOwner saveResourceOwner;
594 MemoryContext savePortalContext;
595 MemoryContext saveQueryContext;
596 MemoryContext saveMemoryContext;
598 AssertArg(PortalIsValid(portal));
600 /* Initialize completion tag to empty string */
602 completionTag[0] = '\0';
604 if (log_executor_stats && portal->strategy != PORTAL_MULTI_QUERY)
607 (errmsg_internal("PortalRun")));
608 /* PORTAL_MULTI_QUERY logs its own stats per query */
613 * Check for improper portal use, and mark portal active.
615 if (portal->status != PORTAL_READY)
617 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
618 errmsg("portal \"%s\" cannot be run", portal->name)));
619 portal->status = PORTAL_ACTIVE;
622 * Set up global portal context pointers.
624 * We have to play a special game here to support utility commands like
625 * VACUUM and CLUSTER, which internally start and commit transactions.
626 * When we are called to execute such a command, CurrentResourceOwner will
627 * be pointing to the TopTransactionResourceOwner --- which will be
628 * destroyed and replaced in the course of the internal commit and
629 * restart. So we need to be prepared to restore it as pointing to the
630 * exit-time TopTransactionResourceOwner. (Ain't that ugly? This idea of
631 * internally starting whole new transactions is not good.)
632 * CurrentMemoryContext has a similar problem, but the other pointers we
633 * save here will be NULL or pointing to longer-lived objects.
635 saveTopTransactionResourceOwner = TopTransactionResourceOwner;
636 saveTopTransactionContext = TopTransactionContext;
637 saveActivePortal = ActivePortal;
638 saveActiveSnapshot = ActiveSnapshot;
639 saveResourceOwner = CurrentResourceOwner;
640 savePortalContext = PortalContext;
641 saveQueryContext = QueryContext;
642 saveMemoryContext = CurrentMemoryContext;
645 ActivePortal = portal;
646 ActiveSnapshot = NULL; /* will be set later */
647 CurrentResourceOwner = portal->resowner;
648 PortalContext = PortalGetHeapMemory(portal);
649 QueryContext = portal->queryContext;
651 MemoryContextSwitchTo(PortalContext);
653 switch (portal->strategy)
655 case PORTAL_ONE_SELECT:
656 (void) PortalRunSelect(portal, true, count, dest);
658 /* we know the query is supposed to set the tag */
659 if (completionTag && portal->commandTag)
660 strcpy(completionTag, portal->commandTag);
662 /* Mark portal not active */
663 portal->status = PORTAL_READY;
666 * Since it's a forward fetch, say DONE iff atEnd is now true.
668 result = portal->atEnd;
671 case PORTAL_ONE_RETURNING:
672 case PORTAL_UTIL_SELECT:
675 * If we have not yet run the command, do so,
676 * storing its results in the portal's tuplestore.
678 if (!portal->holdStore)
679 FillPortalStore(portal);
682 * Now fetch desired portion of results.
684 (void) PortalRunSelect(portal, true, count, dest);
686 /* we know the query is supposed to set the tag */
687 if (completionTag && portal->commandTag)
688 strcpy(completionTag, portal->commandTag);
690 /* Mark portal not active */
691 portal->status = PORTAL_READY;
694 * Since it's a forward fetch, say DONE iff atEnd is now true.
696 result = portal->atEnd;
699 case PORTAL_MULTI_QUERY:
700 PortalRunMulti(portal, dest, altdest, completionTag);
702 /* Prevent portal's commands from being re-executed */
703 portal->status = PORTAL_DONE;
705 /* Always complete at end of RunMulti */
710 elog(ERROR, "unrecognized portal strategy: %d",
711 (int) portal->strategy);
712 result = false; /* keep compiler quiet */
718 /* Uncaught error while executing portal: mark it dead */
719 portal->status = PORTAL_FAILED;
721 /* Restore global vars and propagate error */
722 if (saveMemoryContext == saveTopTransactionContext)
723 MemoryContextSwitchTo(TopTransactionContext);
725 MemoryContextSwitchTo(saveMemoryContext);
726 ActivePortal = saveActivePortal;
727 ActiveSnapshot = saveActiveSnapshot;
728 if (saveResourceOwner == saveTopTransactionResourceOwner)
729 CurrentResourceOwner = TopTransactionResourceOwner;
731 CurrentResourceOwner = saveResourceOwner;
732 PortalContext = savePortalContext;
733 QueryContext = saveQueryContext;
739 if (saveMemoryContext == saveTopTransactionContext)
740 MemoryContextSwitchTo(TopTransactionContext);
742 MemoryContextSwitchTo(saveMemoryContext);
743 ActivePortal = saveActivePortal;
744 ActiveSnapshot = saveActiveSnapshot;
745 if (saveResourceOwner == saveTopTransactionResourceOwner)
746 CurrentResourceOwner = TopTransactionResourceOwner;
748 CurrentResourceOwner = saveResourceOwner;
749 PortalContext = savePortalContext;
750 QueryContext = saveQueryContext;
752 if (log_executor_stats && portal->strategy != PORTAL_MULTI_QUERY)
753 ShowUsage("EXECUTOR STATISTICS");
760 * Execute a portal's query in PORTAL_ONE_SELECT mode, and also
761 * when fetching from a completed holdStore in PORTAL_ONE_RETURNING
762 * and PORTAL_UTIL_SELECT cases.
764 * This handles simple N-rows-forward-or-backward cases. For more complex
765 * nonsequential access to a portal, see PortalRunFetch.
767 * count <= 0 is interpreted as a no-op: the destination gets started up
768 * and shut down, but nothing else happens. Also, count == FETCH_ALL is
769 * interpreted as "all rows".
771 * Caller must already have validated the Portal and done appropriate
772 * setup (cf. PortalRun).
774 * Returns number of rows processed (suitable for use in result tag)
777 PortalRunSelect(Portal portal,
782 QueryDesc *queryDesc;
783 ScanDirection direction;
787 * NB: queryDesc will be NULL if we are fetching from a held cursor or a
788 * completed utility query; can't use it in that path.
790 queryDesc = PortalGetQueryDesc(portal);
792 /* Caller messed up if we have neither a ready query nor held data. */
793 Assert(queryDesc || portal->holdStore);
796 * Force the queryDesc destination to the right thing. This supports
797 * MOVE, for example, which will pass in dest = DestNone. This is okay to
798 * change as long as we do it on every fetch. (The Executor must not
799 * assume that dest never changes.)
802 queryDesc->dest = dest;
805 * Determine which direction to go in, and check to see if we're already
806 * at the end of the available tuples in that direction. If so, set the
807 * direction to NoMovement to avoid trying to fetch any tuples. (This
808 * check exists because not all plan node types are robust about being
809 * called again if they've already returned NULL once.) Then call the
810 * executor (we must not skip this, because the destination needs to see a
811 * setup and shutdown even if no tuples are available). Finally, update
812 * the portal position state depending on the number of tuples that were
817 if (portal->atEnd || count <= 0)
818 direction = NoMovementScanDirection;
820 direction = ForwardScanDirection;
822 /* In the executor, zero count processes all rows */
823 if (count == FETCH_ALL)
826 if (portal->holdStore)
827 nprocessed = RunFromStore(portal, direction, count, dest);
830 ActiveSnapshot = queryDesc->snapshot;
831 ExecutorRun(queryDesc, direction, count);
832 nprocessed = queryDesc->estate->es_processed;
835 if (!ScanDirectionIsNoMovement(direction))
840 portal->atStart = false; /* OK to go backward now */
842 (unsigned long) nprocessed < (unsigned long) count)
843 portal->atEnd = true; /* we retrieved 'em all */
844 oldPos = portal->portalPos;
845 portal->portalPos += nprocessed;
846 /* portalPos doesn't advance when we fall off the end */
847 if (portal->portalPos < oldPos)
848 portal->posOverflow = true;
853 if (portal->cursorOptions & CURSOR_OPT_NO_SCROLL)
855 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
856 errmsg("cursor can only scan forward"),
857 errhint("Declare it with SCROLL option to enable backward scan.")));
859 if (portal->atStart || count <= 0)
860 direction = NoMovementScanDirection;
862 direction = BackwardScanDirection;
864 /* In the executor, zero count processes all rows */
865 if (count == FETCH_ALL)
868 if (portal->holdStore)
869 nprocessed = RunFromStore(portal, direction, count, dest);
872 ActiveSnapshot = queryDesc->snapshot;
873 ExecutorRun(queryDesc, direction, count);
874 nprocessed = queryDesc->estate->es_processed;
877 if (!ScanDirectionIsNoMovement(direction))
879 if (nprocessed > 0 && portal->atEnd)
881 portal->atEnd = false; /* OK to go forward now */
882 portal->portalPos++; /* adjust for endpoint case */
885 (unsigned long) nprocessed < (unsigned long) count)
887 portal->atStart = true; /* we retrieved 'em all */
888 portal->portalPos = 0;
889 portal->posOverflow = false;
895 oldPos = portal->portalPos;
896 portal->portalPos -= nprocessed;
897 if (portal->portalPos > oldPos ||
898 portal->portalPos <= 0)
899 portal->posOverflow = true;
909 * Run the query and load result tuples into the portal's tuple store.
911 * This is used for PORTAL_ONE_RETURNING and PORTAL_UTIL_SELECT cases only.
914 FillPortalStore(Portal portal)
916 DestReceiver *treceiver;
917 char completionTag[COMPLETION_TAG_BUFSIZE];
919 PortalCreateHoldStore(portal);
920 treceiver = CreateDestReceiver(DestTuplestore, portal);
922 switch (portal->strategy)
924 case PORTAL_ONE_RETURNING:
926 * Run the portal to completion just as for the default MULTI_QUERY
927 * case, but send the primary query's output to the tuplestore.
928 * Auxiliary query outputs are discarded.
930 PortalRunMulti(portal, treceiver, None_Receiver, completionTag);
931 /* Override default completion tag with actual command result */
932 portal->commandTag = pstrdup(completionTag);
935 case PORTAL_UTIL_SELECT:
936 PortalRunUtility(portal, linitial(portal->parseTrees),
941 elog(ERROR, "unsupported portal strategy: %d",
942 (int) portal->strategy);
946 (*treceiver->rDestroy) (treceiver);
951 * Fetch tuples from the portal's tuple store.
953 * Calling conventions are similar to ExecutorRun, except that we
954 * do not depend on having a queryDesc or estate. Therefore we return the
955 * number of tuples processed as the result, not in estate->es_processed.
957 * One difference from ExecutorRun is that the destination receiver functions
958 * are run in the caller's memory context (since we have no estate). Watch
959 * out for memory leaks.
962 RunFromStore(Portal portal, ScanDirection direction, long count,
965 long current_tuple_count = 0;
966 TupleTableSlot *slot;
968 slot = MakeSingleTupleTableSlot(portal->tupDesc);
970 (*dest->rStartup) (dest, CMD_SELECT, portal->tupDesc);
972 if (ScanDirectionIsNoMovement(direction))
974 /* do nothing except start/stop the destination */
978 bool forward = ScanDirectionIsForward(direction);
982 MemoryContext oldcontext;
985 oldcontext = MemoryContextSwitchTo(portal->holdContext);
987 ok = tuplestore_gettupleslot(portal->holdStore, forward, slot);
989 MemoryContextSwitchTo(oldcontext);
994 (*dest->receiveSlot) (slot, dest);
996 ExecClearTuple(slot);
999 * check our tuple count.. if we've processed the proper number
1000 * then quit, else loop again and process more tuples. Zero count
1003 current_tuple_count++;
1004 if (count && count == current_tuple_count)
1009 (*dest->rShutdown) (dest);
1011 ExecDropSingleTupleTableSlot(slot);
1013 return (uint32) current_tuple_count;
1018 * Execute a utility statement inside a portal.
1021 PortalRunUtility(Portal portal, Query *query,
1022 DestReceiver *dest, char *completionTag)
1024 Node *utilityStmt = query->utilityStmt;
1027 (errmsg_internal("ProcessUtility")));
1030 * Set snapshot if utility stmt needs one. Most reliable way to do this
1031 * seems to be to enumerate those that do not need one; this is a short
1032 * list. Transaction control, LOCK, and SET must *not* set a snapshot
1033 * since they need to be executable at the start of a serializable
1034 * transaction without freezing a snapshot. By extension we allow SHOW
1035 * not to set a snapshot. The other stmts listed are just efficiency
1036 * hacks. Beware of listing anything that can modify the database --- if,
1037 * say, it has to update an index with expressions that invoke
1038 * user-defined functions, then it had better have a snapshot.
1040 * Note we assume that caller will take care of restoring ActiveSnapshot
1043 if (!(IsA(utilityStmt, TransactionStmt) ||
1044 IsA(utilityStmt, LockStmt) ||
1045 IsA(utilityStmt, VariableSetStmt) ||
1046 IsA(utilityStmt, VariableShowStmt) ||
1047 IsA(utilityStmt, VariableResetStmt) ||
1048 IsA(utilityStmt, ConstraintsSetStmt) ||
1049 /* efficiency hacks from here down */
1050 IsA(utilityStmt, FetchStmt) ||
1051 IsA(utilityStmt, ListenStmt) ||
1052 IsA(utilityStmt, NotifyStmt) ||
1053 IsA(utilityStmt, UnlistenStmt) ||
1054 IsA(utilityStmt, CheckPointStmt)))
1055 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
1057 ActiveSnapshot = NULL;
1059 if (query->canSetTag)
1061 /* utility statement can override default tag string */
1062 ProcessUtility(utilityStmt, portal->portalParams, dest, completionTag);
1063 if (completionTag && completionTag[0] == '\0' && portal->commandTag)
1064 strcpy(completionTag, portal->commandTag); /* use the default */
1068 /* utility added by rewrite cannot set tag */
1069 ProcessUtility(utilityStmt, portal->portalParams, dest, NULL);
1072 /* Some utility statements may change context on us */
1073 MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1076 FreeSnapshot(ActiveSnapshot);
1077 ActiveSnapshot = NULL;
1082 * Execute a portal's queries in the general case (multi queries
1083 * or non-SELECT-like queries)
1086 PortalRunMulti(Portal portal,
1087 DestReceiver *dest, DestReceiver *altdest,
1088 char *completionTag)
1090 ListCell *querylist_item;
1091 ListCell *planlist_item;
1094 * If the destination is DestRemoteExecute, change to DestNone. The
1095 * reason is that the client won't be expecting any tuples, and indeed has
1096 * no way to know what they are, since there is no provision for Describe
1097 * to send a RowDescription message when this portal execution strategy is
1098 * in effect. This presently will only affect SELECT commands added to
1099 * non-SELECT queries by rewrite rules: such commands will be executed,
1100 * but the results will be discarded unless you use "simple Query"
1103 if (dest->mydest == DestRemoteExecute)
1104 dest = None_Receiver;
1105 if (altdest->mydest == DestRemoteExecute)
1106 altdest = None_Receiver;
1109 * Loop to handle the individual queries generated from a single parsetree
1110 * by analysis and rewrite.
1112 forboth(querylist_item, portal->parseTrees,
1113 planlist_item, portal->planTrees)
1115 Query *query = (Query *) lfirst(querylist_item);
1116 Plan *plan = (Plan *) lfirst(planlist_item);
1119 * If we got a cancel signal in prior command, quit
1121 CHECK_FOR_INTERRUPTS();
1123 if (query->commandType == CMD_UTILITY)
1126 * process utility functions (create, destroy, etc..)
1128 Assert(plan == NULL);
1130 PortalRunUtility(portal, query,
1131 query->canSetTag ? dest : altdest,
1137 * process a plannable query.
1139 if (log_executor_stats)
1142 if (query->canSetTag)
1144 /* statement can set tag string */
1145 ProcessQuery(query, plan,
1146 portal->portalParams,
1147 dest, completionTag);
1151 /* stmt added by rewrite cannot set tag */
1152 ProcessQuery(query, plan,
1153 portal->portalParams,
1157 if (log_executor_stats)
1158 ShowUsage("EXECUTOR STATISTICS");
1162 * Increment command counter between queries, but not after the last
1165 if (lnext(planlist_item) != NULL)
1166 CommandCounterIncrement();
1169 * Clear subsidiary contexts to recover temporary memory.
1171 Assert(PortalGetHeapMemory(portal) == CurrentMemoryContext);
1173 MemoryContextDeleteChildren(PortalGetHeapMemory(portal));
1177 * If a command completion tag was supplied, use it. Otherwise use the
1178 * portal's commandTag as the default completion tag.
1180 * Exception: clients will expect INSERT/UPDATE/DELETE tags to have
1181 * counts, so fake something up if necessary. (This could happen if the
1182 * original query was replaced by a DO INSTEAD rule.)
1184 if (completionTag && completionTag[0] == '\0')
1186 if (portal->commandTag)
1187 strcpy(completionTag, portal->commandTag);
1188 if (strcmp(completionTag, "INSERT") == 0)
1189 strcpy(completionTag, "INSERT 0 0");
1190 else if (strcmp(completionTag, "UPDATE") == 0)
1191 strcpy(completionTag, "UPDATE 0");
1192 else if (strcmp(completionTag, "DELETE") == 0)
1193 strcpy(completionTag, "DELETE 0");
1199 * Variant form of PortalRun that supports SQL FETCH directions.
1201 * Returns number of rows processed (suitable for use in result tag)
1204 PortalRunFetch(Portal portal,
1205 FetchDirection fdirection,
1210 Portal saveActivePortal;
1211 Snapshot saveActiveSnapshot;
1212 ResourceOwner saveResourceOwner;
1213 MemoryContext savePortalContext;
1214 MemoryContext saveQueryContext;
1215 MemoryContext oldContext;
1217 AssertArg(PortalIsValid(portal));
1220 * Check for improper portal use, and mark portal active.
1222 if (portal->status != PORTAL_READY)
1224 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1225 errmsg("portal \"%s\" cannot be run", portal->name)));
1226 portal->status = PORTAL_ACTIVE;
1229 * Set up global portal context pointers.
1231 saveActivePortal = ActivePortal;
1232 saveActiveSnapshot = ActiveSnapshot;
1233 saveResourceOwner = CurrentResourceOwner;
1234 savePortalContext = PortalContext;
1235 saveQueryContext = QueryContext;
1238 ActivePortal = portal;
1239 ActiveSnapshot = NULL; /* will be set later */
1240 CurrentResourceOwner = portal->resowner;
1241 PortalContext = PortalGetHeapMemory(portal);
1242 QueryContext = portal->queryContext;
1244 oldContext = MemoryContextSwitchTo(PortalContext);
1246 switch (portal->strategy)
1248 case PORTAL_ONE_SELECT:
1249 result = DoPortalRunFetch(portal, fdirection, count, dest);
1252 case PORTAL_ONE_RETURNING:
1253 case PORTAL_UTIL_SELECT:
1256 * If we have not yet run the command, do so,
1257 * storing its results in the portal's tuplestore.
1259 if (!portal->holdStore)
1260 FillPortalStore(portal);
1263 * Now fetch desired portion of results.
1265 result = DoPortalRunFetch(portal, fdirection, count, dest);
1269 elog(ERROR, "unsupported portal strategy");
1270 result = 0; /* keep compiler quiet */
1276 /* Uncaught error while executing portal: mark it dead */
1277 portal->status = PORTAL_FAILED;
1279 /* Restore global vars and propagate error */
1280 ActivePortal = saveActivePortal;
1281 ActiveSnapshot = saveActiveSnapshot;
1282 CurrentResourceOwner = saveResourceOwner;
1283 PortalContext = savePortalContext;
1284 QueryContext = saveQueryContext;
1290 MemoryContextSwitchTo(oldContext);
1292 /* Mark portal not active */
1293 portal->status = PORTAL_READY;
1295 ActivePortal = saveActivePortal;
1296 ActiveSnapshot = saveActiveSnapshot;
1297 CurrentResourceOwner = saveResourceOwner;
1298 PortalContext = savePortalContext;
1299 QueryContext = saveQueryContext;
1306 * Guts of PortalRunFetch --- the portal context is already set up
1308 * Returns number of rows processed (suitable for use in result tag)
1311 DoPortalRunFetch(Portal portal,
1312 FetchDirection fdirection,
1318 Assert(portal->strategy == PORTAL_ONE_SELECT ||
1319 portal->strategy == PORTAL_ONE_RETURNING ||
1320 portal->strategy == PORTAL_UTIL_SELECT);
1327 fdirection = FETCH_BACKWARD;
1330 /* fall out of switch to share code with FETCH_BACKWARD */
1332 case FETCH_BACKWARD:
1335 fdirection = FETCH_FORWARD;
1338 /* fall out of switch to share code with FETCH_FORWARD */
1340 case FETCH_ABSOLUTE:
1344 * Definition: Rewind to start, advance count-1 rows, return
1345 * next row (if any). In practice, if the goal is less than
1346 * halfway back to the start, it's better to scan from where
1347 * we are. In any case, we arrange to fetch the target row
1350 if (portal->posOverflow || portal->portalPos == LONG_MAX ||
1351 count - 1 <= portal->portalPos / 2)
1353 DoPortalRewind(portal);
1355 PortalRunSelect(portal, true, count - 1,
1360 long pos = portal->portalPos;
1363 pos++; /* need one extra fetch if off end */
1365 PortalRunSelect(portal, false, pos - count + 1,
1367 else if (count > pos + 1)
1368 PortalRunSelect(portal, true, count - pos - 1,
1371 return PortalRunSelect(portal, true, 1L, dest);
1376 * Definition: Advance to end, back up abs(count)-1 rows,
1377 * return prior row (if any). We could optimize this if we
1378 * knew in advance where the end was, but typically we won't.
1379 * (Is it worth considering case where count > half of size of
1380 * query? We could rewind once we know the size ...)
1382 PortalRunSelect(portal, true, FETCH_ALL, None_Receiver);
1384 PortalRunSelect(portal, false, -count - 1, None_Receiver);
1385 return PortalRunSelect(portal, false, 1L, dest);
1390 /* Rewind to start, return zero rows */
1391 DoPortalRewind(portal);
1392 return PortalRunSelect(portal, true, 0L, dest);
1395 case FETCH_RELATIVE:
1399 * Definition: advance count-1 rows, return next row (if any).
1402 PortalRunSelect(portal, true, count - 1, None_Receiver);
1403 return PortalRunSelect(portal, true, 1L, dest);
1408 * Definition: back up abs(count)-1 rows, return prior row (if
1412 PortalRunSelect(portal, false, -count - 1, None_Receiver);
1413 return PortalRunSelect(portal, false, 1L, dest);
1418 /* Same as FETCH FORWARD 0, so fall out of switch */
1419 fdirection = FETCH_FORWARD;
1423 elog(ERROR, "bogus direction");
1428 * Get here with fdirection == FETCH_FORWARD or FETCH_BACKWARD, and count
1431 forward = (fdirection == FETCH_FORWARD);
1434 * Zero count means to re-fetch the current row, if any (per SQL92)
1440 /* Are we sitting on a row? */
1441 on_row = (!portal->atStart && !portal->atEnd);
1443 if (dest->mydest == DestNone)
1445 /* MOVE 0 returns 0/1 based on if FETCH 0 would return a row */
1446 return on_row ? 1L : 0L;
1451 * If we are sitting on a row, back up one so we can re-fetch it.
1452 * If we are not sitting on a row, we still have to start up and
1453 * shut down the executor so that the destination is initialized
1454 * and shut down correctly; so keep going. To PortalRunSelect,
1455 * count == 0 means we will retrieve no row.
1459 PortalRunSelect(portal, false, 1L, None_Receiver);
1460 /* Set up to fetch one row forward */
1468 * Optimize MOVE BACKWARD ALL into a Rewind.
1470 if (!forward && count == FETCH_ALL && dest->mydest == DestNone)
1472 long result = portal->portalPos;
1474 if (result > 0 && !portal->atEnd)
1476 DoPortalRewind(portal);
1477 /* result is bogus if pos had overflowed, but it's best we can do */
1481 return PortalRunSelect(portal, forward, count, dest);
1485 * DoPortalRewind - rewind a Portal to starting point
1488 DoPortalRewind(Portal portal)
1490 if (portal->holdStore)
1492 MemoryContext oldcontext;
1494 oldcontext = MemoryContextSwitchTo(portal->holdContext);
1495 tuplestore_rescan(portal->holdStore);
1496 MemoryContextSwitchTo(oldcontext);
1498 if (PortalGetQueryDesc(portal))
1499 ExecutorRewind(PortalGetQueryDesc(portal));
1501 portal->atStart = true;
1502 portal->atEnd = false;
1503 portal->portalPos = 0;
1504 portal->posOverflow = false;