1 /*-------------------------------------------------------------------------
4 * POSTGRES process query command code
6 * Portions Copyright (c) 1996-2007, 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.112 2007/01/05 22:19:39 momjian 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 can add
222 * 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 and
248 * 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 the
451 * 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, storing its
676 * 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:
927 * Run the portal to completion just as for the default
928 * MULTI_QUERY case, but send the primary query's output to the
929 * tuplestore. Auxiliary query outputs are discarded.
931 PortalRunMulti(portal, treceiver, None_Receiver, completionTag);
932 /* Override default completion tag with actual command result */
933 portal->commandTag = pstrdup(completionTag);
936 case PORTAL_UTIL_SELECT:
937 PortalRunUtility(portal, linitial(portal->parseTrees),
942 elog(ERROR, "unsupported portal strategy: %d",
943 (int) portal->strategy);
947 (*treceiver->rDestroy) (treceiver);
952 * Fetch tuples from the portal's tuple store.
954 * Calling conventions are similar to ExecutorRun, except that we
955 * do not depend on having a queryDesc or estate. Therefore we return the
956 * number of tuples processed as the result, not in estate->es_processed.
958 * One difference from ExecutorRun is that the destination receiver functions
959 * are run in the caller's memory context (since we have no estate). Watch
960 * out for memory leaks.
963 RunFromStore(Portal portal, ScanDirection direction, long count,
966 long current_tuple_count = 0;
967 TupleTableSlot *slot;
969 slot = MakeSingleTupleTableSlot(portal->tupDesc);
971 (*dest->rStartup) (dest, CMD_SELECT, portal->tupDesc);
973 if (ScanDirectionIsNoMovement(direction))
975 /* do nothing except start/stop the destination */
979 bool forward = ScanDirectionIsForward(direction);
983 MemoryContext oldcontext;
986 oldcontext = MemoryContextSwitchTo(portal->holdContext);
988 ok = tuplestore_gettupleslot(portal->holdStore, forward, slot);
990 MemoryContextSwitchTo(oldcontext);
995 (*dest->receiveSlot) (slot, dest);
997 ExecClearTuple(slot);
1000 * check our tuple count.. if we've processed the proper number
1001 * then quit, else loop again and process more tuples. Zero count
1004 current_tuple_count++;
1005 if (count && count == current_tuple_count)
1010 (*dest->rShutdown) (dest);
1012 ExecDropSingleTupleTableSlot(slot);
1014 return (uint32) current_tuple_count;
1019 * Execute a utility statement inside a portal.
1022 PortalRunUtility(Portal portal, Query *query,
1023 DestReceiver *dest, char *completionTag)
1025 Node *utilityStmt = query->utilityStmt;
1028 (errmsg_internal("ProcessUtility")));
1031 * Set snapshot if utility stmt needs one. Most reliable way to do this
1032 * seems to be to enumerate those that do not need one; this is a short
1033 * list. Transaction control, LOCK, and SET must *not* set a snapshot
1034 * since they need to be executable at the start of a serializable
1035 * transaction without freezing a snapshot. By extension we allow SHOW
1036 * not to set a snapshot. The other stmts listed are just efficiency
1037 * hacks. Beware of listing anything that can modify the database --- if,
1038 * say, it has to update an index with expressions that invoke
1039 * user-defined functions, then it had better have a snapshot.
1041 * Note we assume that caller will take care of restoring ActiveSnapshot
1044 if (!(IsA(utilityStmt, TransactionStmt) ||
1045 IsA(utilityStmt, LockStmt) ||
1046 IsA(utilityStmt, VariableSetStmt) ||
1047 IsA(utilityStmt, VariableShowStmt) ||
1048 IsA(utilityStmt, VariableResetStmt) ||
1049 IsA(utilityStmt, ConstraintsSetStmt) ||
1050 /* efficiency hacks from here down */
1051 IsA(utilityStmt, FetchStmt) ||
1052 IsA(utilityStmt, ListenStmt) ||
1053 IsA(utilityStmt, NotifyStmt) ||
1054 IsA(utilityStmt, UnlistenStmt) ||
1055 IsA(utilityStmt, CheckPointStmt)))
1056 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
1058 ActiveSnapshot = NULL;
1060 if (query->canSetTag)
1062 /* utility statement can override default tag string */
1063 ProcessUtility(utilityStmt, portal->portalParams, dest, completionTag);
1064 if (completionTag && completionTag[0] == '\0' && portal->commandTag)
1065 strcpy(completionTag, portal->commandTag); /* use the default */
1069 /* utility added by rewrite cannot set tag */
1070 ProcessUtility(utilityStmt, portal->portalParams, dest, NULL);
1073 /* Some utility statements may change context on us */
1074 MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1077 FreeSnapshot(ActiveSnapshot);
1078 ActiveSnapshot = NULL;
1083 * Execute a portal's queries in the general case (multi queries
1084 * or non-SELECT-like queries)
1087 PortalRunMulti(Portal portal,
1088 DestReceiver *dest, DestReceiver *altdest,
1089 char *completionTag)
1091 ListCell *querylist_item;
1092 ListCell *planlist_item;
1095 * If the destination is DestRemoteExecute, change to DestNone. The
1096 * reason is that the client won't be expecting any tuples, and indeed has
1097 * no way to know what they are, since there is no provision for Describe
1098 * to send a RowDescription message when this portal execution strategy is
1099 * in effect. This presently will only affect SELECT commands added to
1100 * non-SELECT queries by rewrite rules: such commands will be executed,
1101 * but the results will be discarded unless you use "simple Query"
1104 if (dest->mydest == DestRemoteExecute)
1105 dest = None_Receiver;
1106 if (altdest->mydest == DestRemoteExecute)
1107 altdest = None_Receiver;
1110 * Loop to handle the individual queries generated from a single parsetree
1111 * by analysis and rewrite.
1113 forboth(querylist_item, portal->parseTrees,
1114 planlist_item, portal->planTrees)
1116 Query *query = (Query *) lfirst(querylist_item);
1117 Plan *plan = (Plan *) lfirst(planlist_item);
1120 * If we got a cancel signal in prior command, quit
1122 CHECK_FOR_INTERRUPTS();
1124 if (query->commandType == CMD_UTILITY)
1127 * process utility functions (create, destroy, etc..)
1129 Assert(plan == NULL);
1131 PortalRunUtility(portal, query,
1132 query->canSetTag ? dest : altdest,
1138 * process a plannable query.
1140 if (log_executor_stats)
1143 if (query->canSetTag)
1145 /* statement can set tag string */
1146 ProcessQuery(query, plan,
1147 portal->portalParams,
1148 dest, completionTag);
1152 /* stmt added by rewrite cannot set tag */
1153 ProcessQuery(query, plan,
1154 portal->portalParams,
1158 if (log_executor_stats)
1159 ShowUsage("EXECUTOR STATISTICS");
1163 * Increment command counter between queries, but not after the last
1166 if (lnext(planlist_item) != NULL)
1167 CommandCounterIncrement();
1170 * Clear subsidiary contexts to recover temporary memory.
1172 Assert(PortalGetHeapMemory(portal) == CurrentMemoryContext);
1174 MemoryContextDeleteChildren(PortalGetHeapMemory(portal));
1178 * If a command completion tag was supplied, use it. Otherwise use the
1179 * portal's commandTag as the default completion tag.
1181 * Exception: clients will expect INSERT/UPDATE/DELETE tags to have
1182 * counts, so fake something up if necessary. (This could happen if the
1183 * original query was replaced by a DO INSTEAD rule.)
1185 if (completionTag && completionTag[0] == '\0')
1187 if (portal->commandTag)
1188 strcpy(completionTag, portal->commandTag);
1189 if (strcmp(completionTag, "INSERT") == 0)
1190 strcpy(completionTag, "INSERT 0 0");
1191 else if (strcmp(completionTag, "UPDATE") == 0)
1192 strcpy(completionTag, "UPDATE 0");
1193 else if (strcmp(completionTag, "DELETE") == 0)
1194 strcpy(completionTag, "DELETE 0");
1200 * Variant form of PortalRun that supports SQL FETCH directions.
1202 * Returns number of rows processed (suitable for use in result tag)
1205 PortalRunFetch(Portal portal,
1206 FetchDirection fdirection,
1211 Portal saveActivePortal;
1212 Snapshot saveActiveSnapshot;
1213 ResourceOwner saveResourceOwner;
1214 MemoryContext savePortalContext;
1215 MemoryContext saveQueryContext;
1216 MemoryContext oldContext;
1218 AssertArg(PortalIsValid(portal));
1221 * Check for improper portal use, and mark portal active.
1223 if (portal->status != PORTAL_READY)
1225 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1226 errmsg("portal \"%s\" cannot be run", portal->name)));
1227 portal->status = PORTAL_ACTIVE;
1230 * Set up global portal context pointers.
1232 saveActivePortal = ActivePortal;
1233 saveActiveSnapshot = ActiveSnapshot;
1234 saveResourceOwner = CurrentResourceOwner;
1235 savePortalContext = PortalContext;
1236 saveQueryContext = QueryContext;
1239 ActivePortal = portal;
1240 ActiveSnapshot = NULL; /* will be set later */
1241 CurrentResourceOwner = portal->resowner;
1242 PortalContext = PortalGetHeapMemory(portal);
1243 QueryContext = portal->queryContext;
1245 oldContext = MemoryContextSwitchTo(PortalContext);
1247 switch (portal->strategy)
1249 case PORTAL_ONE_SELECT:
1250 result = DoPortalRunFetch(portal, fdirection, count, dest);
1253 case PORTAL_ONE_RETURNING:
1254 case PORTAL_UTIL_SELECT:
1257 * If we have not yet run the command, do so, storing its
1258 * results in the portal's tuplestore.
1260 if (!portal->holdStore)
1261 FillPortalStore(portal);
1264 * Now fetch desired portion of results.
1266 result = DoPortalRunFetch(portal, fdirection, count, dest);
1270 elog(ERROR, "unsupported portal strategy");
1271 result = 0; /* keep compiler quiet */
1277 /* Uncaught error while executing portal: mark it dead */
1278 portal->status = PORTAL_FAILED;
1280 /* Restore global vars and propagate error */
1281 ActivePortal = saveActivePortal;
1282 ActiveSnapshot = saveActiveSnapshot;
1283 CurrentResourceOwner = saveResourceOwner;
1284 PortalContext = savePortalContext;
1285 QueryContext = saveQueryContext;
1291 MemoryContextSwitchTo(oldContext);
1293 /* Mark portal not active */
1294 portal->status = PORTAL_READY;
1296 ActivePortal = saveActivePortal;
1297 ActiveSnapshot = saveActiveSnapshot;
1298 CurrentResourceOwner = saveResourceOwner;
1299 PortalContext = savePortalContext;
1300 QueryContext = saveQueryContext;
1307 * Guts of PortalRunFetch --- the portal context is already set up
1309 * Returns number of rows processed (suitable for use in result tag)
1312 DoPortalRunFetch(Portal portal,
1313 FetchDirection fdirection,
1319 Assert(portal->strategy == PORTAL_ONE_SELECT ||
1320 portal->strategy == PORTAL_ONE_RETURNING ||
1321 portal->strategy == PORTAL_UTIL_SELECT);
1328 fdirection = FETCH_BACKWARD;
1331 /* fall out of switch to share code with FETCH_BACKWARD */
1333 case FETCH_BACKWARD:
1336 fdirection = FETCH_FORWARD;
1339 /* fall out of switch to share code with FETCH_FORWARD */
1341 case FETCH_ABSOLUTE:
1345 * Definition: Rewind to start, advance count-1 rows, return
1346 * next row (if any). In practice, if the goal is less than
1347 * halfway back to the start, it's better to scan from where
1348 * we are. In any case, we arrange to fetch the target row
1351 if (portal->posOverflow || portal->portalPos == LONG_MAX ||
1352 count - 1 <= portal->portalPos / 2)
1354 DoPortalRewind(portal);
1356 PortalRunSelect(portal, true, count - 1,
1361 long pos = portal->portalPos;
1364 pos++; /* need one extra fetch if off end */
1366 PortalRunSelect(portal, false, pos - count + 1,
1368 else if (count > pos + 1)
1369 PortalRunSelect(portal, true, count - pos - 1,
1372 return PortalRunSelect(portal, true, 1L, dest);
1377 * Definition: Advance to end, back up abs(count)-1 rows,
1378 * return prior row (if any). We could optimize this if we
1379 * knew in advance where the end was, but typically we won't.
1380 * (Is it worth considering case where count > half of size of
1381 * query? We could rewind once we know the size ...)
1383 PortalRunSelect(portal, true, FETCH_ALL, None_Receiver);
1385 PortalRunSelect(portal, false, -count - 1, None_Receiver);
1386 return PortalRunSelect(portal, false, 1L, dest);
1391 /* Rewind to start, return zero rows */
1392 DoPortalRewind(portal);
1393 return PortalRunSelect(portal, true, 0L, dest);
1396 case FETCH_RELATIVE:
1400 * Definition: advance count-1 rows, return next row (if any).
1403 PortalRunSelect(portal, true, count - 1, None_Receiver);
1404 return PortalRunSelect(portal, true, 1L, dest);
1409 * Definition: back up abs(count)-1 rows, return prior row (if
1413 PortalRunSelect(portal, false, -count - 1, None_Receiver);
1414 return PortalRunSelect(portal, false, 1L, dest);
1419 /* Same as FETCH FORWARD 0, so fall out of switch */
1420 fdirection = FETCH_FORWARD;
1424 elog(ERROR, "bogus direction");
1429 * Get here with fdirection == FETCH_FORWARD or FETCH_BACKWARD, and count
1432 forward = (fdirection == FETCH_FORWARD);
1435 * Zero count means to re-fetch the current row, if any (per SQL92)
1441 /* Are we sitting on a row? */
1442 on_row = (!portal->atStart && !portal->atEnd);
1444 if (dest->mydest == DestNone)
1446 /* MOVE 0 returns 0/1 based on if FETCH 0 would return a row */
1447 return on_row ? 1L : 0L;
1452 * If we are sitting on a row, back up one so we can re-fetch it.
1453 * If we are not sitting on a row, we still have to start up and
1454 * shut down the executor so that the destination is initialized
1455 * and shut down correctly; so keep going. To PortalRunSelect,
1456 * count == 0 means we will retrieve no row.
1460 PortalRunSelect(portal, false, 1L, None_Receiver);
1461 /* Set up to fetch one row forward */
1469 * Optimize MOVE BACKWARD ALL into a Rewind.
1471 if (!forward && count == FETCH_ALL && dest->mydest == DestNone)
1473 long result = portal->portalPos;
1475 if (result > 0 && !portal->atEnd)
1477 DoPortalRewind(portal);
1478 /* result is bogus if pos had overflowed, but it's best we can do */
1482 return PortalRunSelect(portal, forward, count, dest);
1486 * DoPortalRewind - rewind a Portal to starting point
1489 DoPortalRewind(Portal portal)
1491 if (portal->holdStore)
1493 MemoryContext oldcontext;
1495 oldcontext = MemoryContextSwitchTo(portal->holdContext);
1496 tuplestore_rescan(portal->holdStore);
1497 MemoryContextSwitchTo(oldcontext);
1499 if (PortalGetQueryDesc(portal))
1500 ExecutorRewind(PortalGetQueryDesc(portal));
1502 portal->atStart = true;
1503 portal->atEnd = false;
1504 portal->portalPos = 0;
1505 portal->posOverflow = false;