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.114 2007/02/20 17:32:16 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(PlannedStmt *plan,
39 static void FillPortalStore(Portal portal);
40 static uint32 RunFromStore(Portal portal, ScanDirection direction, long count,
42 static long PortalRunSelect(Portal portal, bool forward, long count,
44 static void PortalRunUtility(Portal portal, Node *utilityStmt,
45 DestReceiver *dest, char *completionTag);
46 static void PortalRunMulti(Portal portal,
47 DestReceiver *dest, DestReceiver *altdest,
49 static long DoPortalRunFetch(Portal portal,
50 FetchDirection fdirection,
53 static void DoPortalRewind(Portal portal);
60 CreateQueryDesc(PlannedStmt *plannedstmt,
62 Snapshot crosscheck_snapshot,
67 QueryDesc *qd = (QueryDesc *) palloc(sizeof(QueryDesc));
69 qd->operation = plannedstmt->commandType; /* operation */
70 qd->plannedstmt = plannedstmt; /* plan */
71 qd->utilitystmt = NULL;
72 qd->snapshot = snapshot; /* snapshot */
73 qd->crosscheck_snapshot = crosscheck_snapshot; /* RI check snapshot */
74 qd->dest = dest; /* output dest */
75 qd->params = params; /* parameter values passed into query */
76 qd->doInstrument = doInstrument; /* instrumentation wanted? */
78 /* null these fields until set by ExecutorStart */
87 * CreateUtilityQueryDesc
90 CreateUtilityQueryDesc(Node *utilitystmt,
95 QueryDesc *qd = (QueryDesc *) palloc(sizeof(QueryDesc));
97 qd->operation = CMD_UTILITY; /* operation */
98 qd->plannedstmt = NULL;
99 qd->utilitystmt = utilitystmt; /* utility command */
100 qd->snapshot = snapshot; /* snapshot */
101 qd->crosscheck_snapshot = InvalidSnapshot; /* RI check snapshot */
102 qd->dest = dest; /* output dest */
103 qd->params = params; /* parameter values passed into query */
104 qd->doInstrument = false; /* uninteresting for utilities */
106 /* null these fields until set by ExecutorStart */
109 qd->planstate = NULL;
118 FreeQueryDesc(QueryDesc *qdesc)
120 /* Can't be a live query */
121 Assert(qdesc->estate == NULL);
122 /* Only the QueryDesc itself need be freed */
129 * Execute a single plannable query within a PORTAL_MULTI_QUERY
130 * or PORTAL_ONE_RETURNING portal
132 * plan: the plan tree for the query
133 * params: any parameters needed
134 * dest: where to send results
135 * completionTag: points to a buffer of size COMPLETION_TAG_BUFSIZE
136 * in which to store a command completion status string.
138 * completionTag may be NULL if caller doesn't want a status string.
140 * Must be called in a memory context that will be reset or deleted on
141 * error; otherwise the executor's memory usage will be leaked.
144 ProcessQuery(PlannedStmt *plan,
145 ParamListInfo params,
149 QueryDesc *queryDesc;
152 (errmsg_internal("ProcessQuery")));
155 * Must always set snapshot for plannable queries. Note we assume that
156 * caller will take care of restoring ActiveSnapshot on exit/error.
158 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
161 * Create the QueryDesc object
163 queryDesc = CreateQueryDesc(plan,
164 ActiveSnapshot, InvalidSnapshot,
165 dest, params, false);
168 * Set up to collect AFTER triggers
170 AfterTriggerBeginQuery();
173 * Call ExecutorStart to prepare the plan for execution
175 ExecutorStart(queryDesc, 0);
178 * Run the plan to completion.
180 ExecutorRun(queryDesc, ForwardScanDirection, 0L);
183 * Build command completion status string, if caller wants one.
189 switch (queryDesc->operation)
192 strcpy(completionTag, "SELECT");
195 if (queryDesc->estate->es_processed == 1)
196 lastOid = queryDesc->estate->es_lastoid;
198 lastOid = InvalidOid;
199 snprintf(completionTag, COMPLETION_TAG_BUFSIZE,
200 "INSERT %u %u", lastOid, queryDesc->estate->es_processed);
203 snprintf(completionTag, COMPLETION_TAG_BUFSIZE,
204 "UPDATE %u", queryDesc->estate->es_processed);
207 snprintf(completionTag, COMPLETION_TAG_BUFSIZE,
208 "DELETE %u", queryDesc->estate->es_processed);
211 strcpy(completionTag, "???");
216 /* Now take care of any queued AFTER triggers */
217 AfterTriggerEndQuery(queryDesc->estate);
220 * Now, we close down all the scans and free allocated resources.
222 ExecutorEnd(queryDesc);
224 FreeQueryDesc(queryDesc);
226 FreeSnapshot(ActiveSnapshot);
227 ActiveSnapshot = NULL;
231 * ChoosePortalStrategy
232 * Select portal execution strategy given the intended statement list.
234 * The list elements can be Querys, PlannedStmts, or utility statements.
235 * That's more general than portals need, but we use this for prepared
236 * statements as well.
238 * See the comments in portal.h.
241 ChoosePortalStrategy(List *stmts)
247 * PORTAL_ONE_SELECT and PORTAL_UTIL_SELECT need only consider the
248 * single-statement case, since there are no rewrite rules that can add
249 * auxiliary queries to a SELECT or a utility command.
251 if (list_length(stmts) == 1)
253 Node *stmt = (Node *) linitial(stmts);
255 if (IsA(stmt, Query))
257 Query *query = (Query *) stmt;
259 if (query->canSetTag)
261 if (query->commandType == CMD_SELECT &&
263 return PORTAL_ONE_SELECT;
264 if (query->commandType == CMD_UTILITY &&
265 query->utilityStmt != NULL)
267 if (UtilityReturnsTuples(query->utilityStmt))
268 return PORTAL_UTIL_SELECT;
269 /* it can't be ONE_RETURNING, so give up */
270 return PORTAL_MULTI_QUERY;
274 else if (IsA(stmt, PlannedStmt))
276 PlannedStmt *pstmt = (PlannedStmt *) stmt;
278 if (pstmt->canSetTag)
280 if (pstmt->commandType == CMD_SELECT &&
282 return PORTAL_ONE_SELECT;
287 /* must be a utility command; assume it's canSetTag */
288 if (UtilityReturnsTuples(stmt))
289 return PORTAL_UTIL_SELECT;
290 /* it can't be ONE_RETURNING, so give up */
291 return PORTAL_MULTI_QUERY;
296 * PORTAL_ONE_RETURNING has to allow auxiliary queries added by rewrite.
297 * Choose PORTAL_ONE_RETURNING if there is exactly one canSetTag query and
298 * it has a RETURNING list.
303 Node *stmt = (Node *) lfirst(lc);
305 if (IsA(stmt, Query))
307 Query *query = (Query *) stmt;
309 if (query->canSetTag)
312 return PORTAL_MULTI_QUERY; /* no need to look further */
313 if (query->returningList == NIL)
314 return PORTAL_MULTI_QUERY; /* no need to look further */
317 else if (IsA(stmt, PlannedStmt))
319 PlannedStmt *pstmt = (PlannedStmt *) stmt;
321 if (pstmt->canSetTag)
324 return PORTAL_MULTI_QUERY; /* no need to look further */
325 if (pstmt->returningLists == NIL)
326 return PORTAL_MULTI_QUERY; /* no need to look further */
329 /* otherwise, utility command, assumed not canSetTag */
332 return PORTAL_ONE_RETURNING;
334 /* Else, it's the general case... */
335 return PORTAL_MULTI_QUERY;
339 * FetchPortalTargetList
340 * Given a portal that returns tuples, extract the query targetlist.
341 * Returns NIL if the portal doesn't have a determinable targetlist.
343 * Note: do not modify the result.
346 FetchPortalTargetList(Portal portal)
348 /* no point in looking if we determined it doesn't return tuples */
349 if (portal->strategy == PORTAL_MULTI_QUERY)
351 /* get the primary statement and find out what it returns */
352 return FetchStatementTargetList(PortalGetPrimaryStmt(portal));
356 * FetchStatementTargetList
357 * Given a statement that returns tuples, extract the query targetlist.
358 * Returns NIL if the statement doesn't have a determinable targetlist.
360 * This can be applied to a Query, a PlannedStmt, or a utility statement.
361 * That's more general than portals need, but we use this for prepared
362 * statements as well.
364 * Note: do not modify the result.
366 * XXX be careful to keep this in sync with UtilityReturnsTuples.
369 FetchStatementTargetList(Node *stmt)
373 if (IsA(stmt, Query))
375 Query *query = (Query *) stmt;
377 if (query->commandType == CMD_UTILITY &&
378 query->utilityStmt != NULL)
380 /* transfer attention to utility statement */
381 stmt = query->utilityStmt;
385 if (query->commandType == CMD_SELECT &&
387 return query->targetList;
388 if (query->returningList)
389 return query->returningList;
393 if (IsA(stmt, PlannedStmt))
395 PlannedStmt *pstmt = (PlannedStmt *) stmt;
397 if (pstmt->commandType == CMD_SELECT &&
399 return pstmt->planTree->targetlist;
400 if (pstmt->returningLists)
401 return (List *) linitial(pstmt->returningLists);
404 if (IsA(stmt, FetchStmt))
406 FetchStmt *fstmt = (FetchStmt *) stmt;
409 Assert(!fstmt->ismove);
410 subportal = GetPortalByName(fstmt->portalname);
411 Assert(PortalIsValid(subportal));
412 return FetchPortalTargetList(subportal);
414 if (IsA(stmt, ExecuteStmt))
416 ExecuteStmt *estmt = (ExecuteStmt *) stmt;
417 PreparedStatement *entry;
419 Assert(!estmt->into);
420 entry = FetchPreparedStatement(estmt->name, true);
421 return FetchPreparedStatementTargetList(entry);
428 * Prepare a portal for execution.
430 * Caller must already have created the portal, done PortalDefineQuery(),
431 * and adjusted portal options if needed. If parameters are needed by
432 * the query, they must be passed in here (caller is responsible for
433 * giving them appropriate lifetime).
435 * The caller can optionally pass a snapshot to be used; pass InvalidSnapshot
436 * for the normal behavior of setting a new snapshot. This parameter is
437 * presently ignored for non-PORTAL_ONE_SELECT portals (it's only intended
438 * to be used for cursors).
440 * On return, portal is ready to accept PortalRun() calls, and the result
441 * tupdesc (if any) is known.
444 PortalStart(Portal portal, ParamListInfo params, Snapshot snapshot)
446 Portal saveActivePortal;
447 Snapshot saveActiveSnapshot;
448 ResourceOwner saveResourceOwner;
449 MemoryContext savePortalContext;
450 MemoryContext oldContext;
451 QueryDesc *queryDesc;
454 AssertArg(PortalIsValid(portal));
455 AssertState(portal->queryContext != NULL); /* query defined? */
456 AssertState(portal->status == PORTAL_NEW); /* else extra PortalStart */
459 * Set up global portal context pointers. (Should we set QueryContext?)
461 saveActivePortal = ActivePortal;
462 saveActiveSnapshot = ActiveSnapshot;
463 saveResourceOwner = CurrentResourceOwner;
464 savePortalContext = PortalContext;
467 ActivePortal = portal;
468 ActiveSnapshot = NULL; /* will be set later */
469 CurrentResourceOwner = portal->resowner;
470 PortalContext = PortalGetHeapMemory(portal);
472 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
474 /* Must remember portal param list, if any */
475 portal->portalParams = params;
478 * Determine the portal execution strategy
480 portal->strategy = ChoosePortalStrategy(portal->stmts);
483 * Fire her up according to the strategy
485 switch (portal->strategy)
487 case PORTAL_ONE_SELECT:
490 * Must set snapshot before starting executor. Be sure to
491 * copy it into the portal's context.
494 ActiveSnapshot = CopySnapshot(snapshot);
496 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
499 * Create QueryDesc in portal's context; for the moment, set
500 * the destination to DestNone.
502 queryDesc = CreateQueryDesc((PlannedStmt *) linitial(portal->stmts),
510 * We do *not* call AfterTriggerBeginQuery() here. We assume
511 * that a SELECT cannot queue any triggers. It would be messy
512 * to support triggers since the execution of the portal may
513 * be interleaved with other queries.
517 * If it's a scrollable cursor, executor needs to support
518 * REWIND and backwards scan.
520 if (portal->cursorOptions & CURSOR_OPT_SCROLL)
521 eflags = EXEC_FLAG_REWIND | EXEC_FLAG_BACKWARD;
523 eflags = 0; /* default run-to-completion flags */
526 * Call ExecutorStart to prepare the plan for execution
528 ExecutorStart(queryDesc, eflags);
531 * This tells PortalCleanup to shut down the executor
533 portal->queryDesc = queryDesc;
536 * Remember tuple descriptor (computed by ExecutorStart)
538 portal->tupDesc = queryDesc->tupDesc;
541 * Reset cursor position data to "start of query"
543 portal->atStart = true;
544 portal->atEnd = false; /* allow fetches */
545 portal->portalPos = 0;
546 portal->posOverflow = false;
549 case PORTAL_ONE_RETURNING:
552 * We don't start the executor until we are told to run the
553 * portal. We do need to set up the result tupdesc.
558 pstmt = (PlannedStmt *) PortalGetPrimaryStmt(portal);
559 Assert(IsA(pstmt, PlannedStmt));
560 Assert(pstmt->returningLists);
562 ExecCleanTypeFromTL((List *) linitial(pstmt->returningLists),
567 * Reset cursor position data to "start of query"
569 portal->atStart = true;
570 portal->atEnd = false; /* allow fetches */
571 portal->portalPos = 0;
572 portal->posOverflow = false;
575 case PORTAL_UTIL_SELECT:
578 * We don't set snapshot here, because PortalRunUtility will
579 * take care of it if needed.
582 Node *ustmt = PortalGetPrimaryStmt(portal);
584 Assert(!IsA(ustmt, PlannedStmt));
585 portal->tupDesc = UtilityTupleDescriptor(ustmt);
589 * Reset cursor position data to "start of query"
591 portal->atStart = true;
592 portal->atEnd = false; /* allow fetches */
593 portal->portalPos = 0;
594 portal->posOverflow = false;
597 case PORTAL_MULTI_QUERY:
598 /* Need do nothing now */
599 portal->tupDesc = NULL;
605 /* Uncaught error while executing portal: mark it dead */
606 portal->status = PORTAL_FAILED;
608 /* Restore global vars and propagate error */
609 ActivePortal = saveActivePortal;
610 ActiveSnapshot = saveActiveSnapshot;
611 CurrentResourceOwner = saveResourceOwner;
612 PortalContext = savePortalContext;
618 MemoryContextSwitchTo(oldContext);
620 ActivePortal = saveActivePortal;
621 ActiveSnapshot = saveActiveSnapshot;
622 CurrentResourceOwner = saveResourceOwner;
623 PortalContext = savePortalContext;
625 portal->status = PORTAL_READY;
629 * PortalSetResultFormat
630 * Select the format codes for a portal's output.
632 * This must be run after PortalStart for a portal that will be read by
633 * a DestRemote or DestRemoteExecute destination. It is not presently needed
634 * for other destination types.
636 * formats[] is the client format request, as per Bind message conventions.
639 PortalSetResultFormat(Portal portal, int nFormats, int16 *formats)
644 /* Do nothing if portal won't return tuples */
645 if (portal->tupDesc == NULL)
647 natts = portal->tupDesc->natts;
648 portal->formats = (int16 *)
649 MemoryContextAlloc(PortalGetHeapMemory(portal),
650 natts * sizeof(int16));
653 /* format specified for each column */
654 if (nFormats != natts)
656 (errcode(ERRCODE_PROTOCOL_VIOLATION),
657 errmsg("bind message has %d result formats but query has %d columns",
659 memcpy(portal->formats, formats, natts * sizeof(int16));
661 else if (nFormats > 0)
663 /* single format specified, use for all columns */
664 int16 format1 = formats[0];
666 for (i = 0; i < natts; i++)
667 portal->formats[i] = format1;
671 /* use default format for all columns */
672 for (i = 0; i < natts; i++)
673 portal->formats[i] = 0;
679 * Run a portal's query or queries.
681 * count <= 0 is interpreted as a no-op: the destination gets started up
682 * and shut down, but nothing else happens. Also, count == FETCH_ALL is
683 * interpreted as "all rows". Note that count is ignored in multi-query
684 * situations, where we always run the portal to completion.
686 * dest: where to send output of primary (canSetTag) query
688 * altdest: where to send output of non-primary queries
690 * completionTag: points to a buffer of size COMPLETION_TAG_BUFSIZE
691 * in which to store a command completion status string.
692 * May be NULL if caller doesn't want a status string.
694 * Returns TRUE if the portal's execution is complete, FALSE if it was
695 * suspended due to exhaustion of the count parameter.
698 PortalRun(Portal portal, long count,
699 DestReceiver *dest, DestReceiver *altdest,
703 ResourceOwner saveTopTransactionResourceOwner;
704 MemoryContext saveTopTransactionContext;
705 Portal saveActivePortal;
706 Snapshot saveActiveSnapshot;
707 ResourceOwner saveResourceOwner;
708 MemoryContext savePortalContext;
709 MemoryContext saveQueryContext;
710 MemoryContext saveMemoryContext;
712 AssertArg(PortalIsValid(portal));
714 /* Initialize completion tag to empty string */
716 completionTag[0] = '\0';
718 if (log_executor_stats && portal->strategy != PORTAL_MULTI_QUERY)
721 (errmsg_internal("PortalRun")));
722 /* PORTAL_MULTI_QUERY logs its own stats per query */
727 * Check for improper portal use, and mark portal active.
729 if (portal->status != PORTAL_READY)
731 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
732 errmsg("portal \"%s\" cannot be run", portal->name)));
733 portal->status = PORTAL_ACTIVE;
736 * Set up global portal context pointers.
738 * We have to play a special game here to support utility commands like
739 * VACUUM and CLUSTER, which internally start and commit transactions.
740 * When we are called to execute such a command, CurrentResourceOwner will
741 * be pointing to the TopTransactionResourceOwner --- which will be
742 * destroyed and replaced in the course of the internal commit and
743 * restart. So we need to be prepared to restore it as pointing to the
744 * exit-time TopTransactionResourceOwner. (Ain't that ugly? This idea of
745 * internally starting whole new transactions is not good.)
746 * CurrentMemoryContext has a similar problem, but the other pointers we
747 * save here will be NULL or pointing to longer-lived objects.
749 saveTopTransactionResourceOwner = TopTransactionResourceOwner;
750 saveTopTransactionContext = TopTransactionContext;
751 saveActivePortal = ActivePortal;
752 saveActiveSnapshot = ActiveSnapshot;
753 saveResourceOwner = CurrentResourceOwner;
754 savePortalContext = PortalContext;
755 saveQueryContext = QueryContext;
756 saveMemoryContext = CurrentMemoryContext;
759 ActivePortal = portal;
760 ActiveSnapshot = NULL; /* will be set later */
761 CurrentResourceOwner = portal->resowner;
762 PortalContext = PortalGetHeapMemory(portal);
763 QueryContext = portal->queryContext;
765 MemoryContextSwitchTo(PortalContext);
767 switch (portal->strategy)
769 case PORTAL_ONE_SELECT:
770 (void) PortalRunSelect(portal, true, count, dest);
772 /* we know the query is supposed to set the tag */
773 if (completionTag && portal->commandTag)
774 strcpy(completionTag, portal->commandTag);
776 /* Mark portal not active */
777 portal->status = PORTAL_READY;
780 * Since it's a forward fetch, say DONE iff atEnd is now true.
782 result = portal->atEnd;
785 case PORTAL_ONE_RETURNING:
786 case PORTAL_UTIL_SELECT:
789 * If we have not yet run the command, do so, storing its
790 * results in the portal's tuplestore.
792 if (!portal->holdStore)
793 FillPortalStore(portal);
796 * Now fetch desired portion of results.
798 (void) PortalRunSelect(portal, true, count, dest);
800 /* we know the query is supposed to set the tag */
801 if (completionTag && portal->commandTag)
802 strcpy(completionTag, portal->commandTag);
804 /* Mark portal not active */
805 portal->status = PORTAL_READY;
808 * Since it's a forward fetch, say DONE iff atEnd is now true.
810 result = portal->atEnd;
813 case PORTAL_MULTI_QUERY:
814 PortalRunMulti(portal, dest, altdest, completionTag);
816 /* Prevent portal's commands from being re-executed */
817 portal->status = PORTAL_DONE;
819 /* Always complete at end of RunMulti */
824 elog(ERROR, "unrecognized portal strategy: %d",
825 (int) portal->strategy);
826 result = false; /* keep compiler quiet */
832 /* Uncaught error while executing portal: mark it dead */
833 portal->status = PORTAL_FAILED;
835 /* Restore global vars and propagate error */
836 if (saveMemoryContext == saveTopTransactionContext)
837 MemoryContextSwitchTo(TopTransactionContext);
839 MemoryContextSwitchTo(saveMemoryContext);
840 ActivePortal = saveActivePortal;
841 ActiveSnapshot = saveActiveSnapshot;
842 if (saveResourceOwner == saveTopTransactionResourceOwner)
843 CurrentResourceOwner = TopTransactionResourceOwner;
845 CurrentResourceOwner = saveResourceOwner;
846 PortalContext = savePortalContext;
847 QueryContext = saveQueryContext;
853 if (saveMemoryContext == saveTopTransactionContext)
854 MemoryContextSwitchTo(TopTransactionContext);
856 MemoryContextSwitchTo(saveMemoryContext);
857 ActivePortal = saveActivePortal;
858 ActiveSnapshot = saveActiveSnapshot;
859 if (saveResourceOwner == saveTopTransactionResourceOwner)
860 CurrentResourceOwner = TopTransactionResourceOwner;
862 CurrentResourceOwner = saveResourceOwner;
863 PortalContext = savePortalContext;
864 QueryContext = saveQueryContext;
866 if (log_executor_stats && portal->strategy != PORTAL_MULTI_QUERY)
867 ShowUsage("EXECUTOR STATISTICS");
874 * Execute a portal's query in PORTAL_ONE_SELECT mode, and also
875 * when fetching from a completed holdStore in PORTAL_ONE_RETURNING
876 * and PORTAL_UTIL_SELECT cases.
878 * This handles simple N-rows-forward-or-backward cases. For more complex
879 * nonsequential access to a portal, see PortalRunFetch.
881 * count <= 0 is interpreted as a no-op: the destination gets started up
882 * and shut down, but nothing else happens. Also, count == FETCH_ALL is
883 * interpreted as "all rows".
885 * Caller must already have validated the Portal and done appropriate
886 * setup (cf. PortalRun).
888 * Returns number of rows processed (suitable for use in result tag)
891 PortalRunSelect(Portal portal,
896 QueryDesc *queryDesc;
897 ScanDirection direction;
901 * NB: queryDesc will be NULL if we are fetching from a held cursor or a
902 * completed utility query; can't use it in that path.
904 queryDesc = PortalGetQueryDesc(portal);
906 /* Caller messed up if we have neither a ready query nor held data. */
907 Assert(queryDesc || portal->holdStore);
910 * Force the queryDesc destination to the right thing. This supports
911 * MOVE, for example, which will pass in dest = DestNone. This is okay to
912 * change as long as we do it on every fetch. (The Executor must not
913 * assume that dest never changes.)
916 queryDesc->dest = dest;
919 * Determine which direction to go in, and check to see if we're already
920 * at the end of the available tuples in that direction. If so, set the
921 * direction to NoMovement to avoid trying to fetch any tuples. (This
922 * check exists because not all plan node types are robust about being
923 * called again if they've already returned NULL once.) Then call the
924 * executor (we must not skip this, because the destination needs to see a
925 * setup and shutdown even if no tuples are available). Finally, update
926 * the portal position state depending on the number of tuples that were
931 if (portal->atEnd || count <= 0)
932 direction = NoMovementScanDirection;
934 direction = ForwardScanDirection;
936 /* In the executor, zero count processes all rows */
937 if (count == FETCH_ALL)
940 if (portal->holdStore)
941 nprocessed = RunFromStore(portal, direction, count, dest);
944 ActiveSnapshot = queryDesc->snapshot;
945 ExecutorRun(queryDesc, direction, count);
946 nprocessed = queryDesc->estate->es_processed;
949 if (!ScanDirectionIsNoMovement(direction))
954 portal->atStart = false; /* OK to go backward now */
956 (unsigned long) nprocessed < (unsigned long) count)
957 portal->atEnd = true; /* we retrieved 'em all */
958 oldPos = portal->portalPos;
959 portal->portalPos += nprocessed;
960 /* portalPos doesn't advance when we fall off the end */
961 if (portal->portalPos < oldPos)
962 portal->posOverflow = true;
967 if (portal->cursorOptions & CURSOR_OPT_NO_SCROLL)
969 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
970 errmsg("cursor can only scan forward"),
971 errhint("Declare it with SCROLL option to enable backward scan.")));
973 if (portal->atStart || count <= 0)
974 direction = NoMovementScanDirection;
976 direction = BackwardScanDirection;
978 /* In the executor, zero count processes all rows */
979 if (count == FETCH_ALL)
982 if (portal->holdStore)
983 nprocessed = RunFromStore(portal, direction, count, dest);
986 ActiveSnapshot = queryDesc->snapshot;
987 ExecutorRun(queryDesc, direction, count);
988 nprocessed = queryDesc->estate->es_processed;
991 if (!ScanDirectionIsNoMovement(direction))
993 if (nprocessed > 0 && portal->atEnd)
995 portal->atEnd = false; /* OK to go forward now */
996 portal->portalPos++; /* adjust for endpoint case */
999 (unsigned long) nprocessed < (unsigned long) count)
1001 portal->atStart = true; /* we retrieved 'em all */
1002 portal->portalPos = 0;
1003 portal->posOverflow = false;
1009 oldPos = portal->portalPos;
1010 portal->portalPos -= nprocessed;
1011 if (portal->portalPos > oldPos ||
1012 portal->portalPos <= 0)
1013 portal->posOverflow = true;
1023 * Run the query and load result tuples into the portal's tuple store.
1025 * This is used for PORTAL_ONE_RETURNING and PORTAL_UTIL_SELECT cases only.
1028 FillPortalStore(Portal portal)
1030 DestReceiver *treceiver;
1031 char completionTag[COMPLETION_TAG_BUFSIZE];
1033 PortalCreateHoldStore(portal);
1034 treceiver = CreateDestReceiver(DestTuplestore, portal);
1036 completionTag[0] = '\0';
1038 switch (portal->strategy)
1040 case PORTAL_ONE_RETURNING:
1043 * Run the portal to completion just as for the default
1044 * MULTI_QUERY case, but send the primary query's output to the
1045 * tuplestore. Auxiliary query outputs are discarded.
1047 PortalRunMulti(portal, treceiver, None_Receiver, completionTag);
1050 case PORTAL_UTIL_SELECT:
1051 PortalRunUtility(portal, (Node *) linitial(portal->stmts),
1052 treceiver, completionTag);
1056 elog(ERROR, "unsupported portal strategy: %d",
1057 (int) portal->strategy);
1061 /* Override default completion tag with actual command result */
1062 if (completionTag[0] != '\0')
1063 portal->commandTag = pstrdup(completionTag);
1065 (*treceiver->rDestroy) (treceiver);
1070 * Fetch tuples from the portal's tuple store.
1072 * Calling conventions are similar to ExecutorRun, except that we
1073 * do not depend on having a queryDesc or estate. Therefore we return the
1074 * number of tuples processed as the result, not in estate->es_processed.
1076 * One difference from ExecutorRun is that the destination receiver functions
1077 * are run in the caller's memory context (since we have no estate). Watch
1078 * out for memory leaks.
1081 RunFromStore(Portal portal, ScanDirection direction, long count,
1084 long current_tuple_count = 0;
1085 TupleTableSlot *slot;
1087 slot = MakeSingleTupleTableSlot(portal->tupDesc);
1089 (*dest->rStartup) (dest, CMD_SELECT, portal->tupDesc);
1091 if (ScanDirectionIsNoMovement(direction))
1093 /* do nothing except start/stop the destination */
1097 bool forward = ScanDirectionIsForward(direction);
1101 MemoryContext oldcontext;
1104 oldcontext = MemoryContextSwitchTo(portal->holdContext);
1106 ok = tuplestore_gettupleslot(portal->holdStore, forward, slot);
1108 MemoryContextSwitchTo(oldcontext);
1113 (*dest->receiveSlot) (slot, dest);
1115 ExecClearTuple(slot);
1118 * check our tuple count.. if we've processed the proper number
1119 * then quit, else loop again and process more tuples. Zero count
1122 current_tuple_count++;
1123 if (count && count == current_tuple_count)
1128 (*dest->rShutdown) (dest);
1130 ExecDropSingleTupleTableSlot(slot);
1132 return (uint32) current_tuple_count;
1137 * Execute a utility statement inside a portal.
1140 PortalRunUtility(Portal portal, Node *utilityStmt,
1141 DestReceiver *dest, char *completionTag)
1144 (errmsg_internal("ProcessUtility")));
1147 * Set snapshot if utility stmt needs one. Most reliable way to do this
1148 * seems to be to enumerate those that do not need one; this is a short
1149 * list. Transaction control, LOCK, and SET must *not* set a snapshot
1150 * since they need to be executable at the start of a serializable
1151 * transaction without freezing a snapshot. By extension we allow SHOW
1152 * not to set a snapshot. The other stmts listed are just efficiency
1153 * hacks. Beware of listing anything that can modify the database --- if,
1154 * say, it has to update an index with expressions that invoke
1155 * user-defined functions, then it had better have a snapshot.
1157 * Note we assume that caller will take care of restoring ActiveSnapshot
1160 if (!(IsA(utilityStmt, TransactionStmt) ||
1161 IsA(utilityStmt, LockStmt) ||
1162 IsA(utilityStmt, VariableSetStmt) ||
1163 IsA(utilityStmt, VariableShowStmt) ||
1164 IsA(utilityStmt, VariableResetStmt) ||
1165 IsA(utilityStmt, ConstraintsSetStmt) ||
1166 /* efficiency hacks from here down */
1167 IsA(utilityStmt, FetchStmt) ||
1168 IsA(utilityStmt, ListenStmt) ||
1169 IsA(utilityStmt, NotifyStmt) ||
1170 IsA(utilityStmt, UnlistenStmt) ||
1171 IsA(utilityStmt, CheckPointStmt)))
1172 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
1174 ActiveSnapshot = NULL;
1176 ProcessUtility(utilityStmt, portal->portalParams, dest, completionTag);
1178 /* Some utility statements may change context on us */
1179 MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1182 FreeSnapshot(ActiveSnapshot);
1183 ActiveSnapshot = NULL;
1188 * Execute a portal's queries in the general case (multi queries
1189 * or non-SELECT-like queries)
1192 PortalRunMulti(Portal portal,
1193 DestReceiver *dest, DestReceiver *altdest,
1194 char *completionTag)
1196 ListCell *stmtlist_item;
1199 * If the destination is DestRemoteExecute, change to DestNone. The
1200 * reason is that the client won't be expecting any tuples, and indeed has
1201 * no way to know what they are, since there is no provision for Describe
1202 * to send a RowDescription message when this portal execution strategy is
1203 * in effect. This presently will only affect SELECT commands added to
1204 * non-SELECT queries by rewrite rules: such commands will be executed,
1205 * but the results will be discarded unless you use "simple Query"
1208 if (dest->mydest == DestRemoteExecute)
1209 dest = None_Receiver;
1210 if (altdest->mydest == DestRemoteExecute)
1211 altdest = None_Receiver;
1214 * Loop to handle the individual queries generated from a single parsetree
1215 * by analysis and rewrite.
1217 foreach(stmtlist_item, portal->stmts)
1219 Node *stmt = (Node *) lfirst(stmtlist_item);
1222 * If we got a cancel signal in prior command, quit
1224 CHECK_FOR_INTERRUPTS();
1226 if (IsA(stmt, PlannedStmt))
1229 * process a plannable query.
1231 PlannedStmt *pstmt = (PlannedStmt *) stmt;
1233 if (log_executor_stats)
1236 if (pstmt->canSetTag)
1238 /* statement can set tag string */
1240 portal->portalParams,
1241 dest, completionTag);
1245 /* stmt added by rewrite cannot set tag */
1247 portal->portalParams,
1251 if (log_executor_stats)
1252 ShowUsage("EXECUTOR STATISTICS");
1257 * process utility functions (create, destroy, etc..)
1259 * These are assumed canSetTag if they're the only stmt in the
1262 if (list_length(portal->stmts) == 1)
1263 PortalRunUtility(portal, stmt, dest, completionTag);
1265 PortalRunUtility(portal, stmt, altdest, NULL);
1269 * Increment command counter between queries, but not after the last
1272 if (lnext(stmtlist_item) != NULL)
1273 CommandCounterIncrement();
1276 * Clear subsidiary contexts to recover temporary memory.
1278 Assert(PortalGetHeapMemory(portal) == CurrentMemoryContext);
1280 MemoryContextDeleteChildren(PortalGetHeapMemory(portal));
1284 * If a command completion tag was supplied, use it. Otherwise use the
1285 * portal's commandTag as the default completion tag.
1287 * Exception: clients will expect INSERT/UPDATE/DELETE tags to have
1288 * counts, so fake something up if necessary. (This could happen if the
1289 * original query was replaced by a DO INSTEAD rule.)
1291 if (completionTag && completionTag[0] == '\0')
1293 if (portal->commandTag)
1294 strcpy(completionTag, portal->commandTag);
1295 if (strcmp(completionTag, "INSERT") == 0)
1296 strcpy(completionTag, "INSERT 0 0");
1297 else if (strcmp(completionTag, "UPDATE") == 0)
1298 strcpy(completionTag, "UPDATE 0");
1299 else if (strcmp(completionTag, "DELETE") == 0)
1300 strcpy(completionTag, "DELETE 0");
1306 * Variant form of PortalRun that supports SQL FETCH directions.
1308 * Returns number of rows processed (suitable for use in result tag)
1311 PortalRunFetch(Portal portal,
1312 FetchDirection fdirection,
1317 Portal saveActivePortal;
1318 Snapshot saveActiveSnapshot;
1319 ResourceOwner saveResourceOwner;
1320 MemoryContext savePortalContext;
1321 MemoryContext saveQueryContext;
1322 MemoryContext oldContext;
1324 AssertArg(PortalIsValid(portal));
1327 * Check for improper portal use, and mark portal active.
1329 if (portal->status != PORTAL_READY)
1331 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1332 errmsg("portal \"%s\" cannot be run", portal->name)));
1333 portal->status = PORTAL_ACTIVE;
1336 * Set up global portal context pointers.
1338 saveActivePortal = ActivePortal;
1339 saveActiveSnapshot = ActiveSnapshot;
1340 saveResourceOwner = CurrentResourceOwner;
1341 savePortalContext = PortalContext;
1342 saveQueryContext = QueryContext;
1345 ActivePortal = portal;
1346 ActiveSnapshot = NULL; /* will be set later */
1347 CurrentResourceOwner = portal->resowner;
1348 PortalContext = PortalGetHeapMemory(portal);
1349 QueryContext = portal->queryContext;
1351 oldContext = MemoryContextSwitchTo(PortalContext);
1353 switch (portal->strategy)
1355 case PORTAL_ONE_SELECT:
1356 result = DoPortalRunFetch(portal, fdirection, count, dest);
1359 case PORTAL_ONE_RETURNING:
1360 case PORTAL_UTIL_SELECT:
1363 * If we have not yet run the command, do so, storing its
1364 * results in the portal's tuplestore.
1366 if (!portal->holdStore)
1367 FillPortalStore(portal);
1370 * Now fetch desired portion of results.
1372 result = DoPortalRunFetch(portal, fdirection, count, dest);
1376 elog(ERROR, "unsupported portal strategy");
1377 result = 0; /* keep compiler quiet */
1383 /* Uncaught error while executing portal: mark it dead */
1384 portal->status = PORTAL_FAILED;
1386 /* Restore global vars and propagate error */
1387 ActivePortal = saveActivePortal;
1388 ActiveSnapshot = saveActiveSnapshot;
1389 CurrentResourceOwner = saveResourceOwner;
1390 PortalContext = savePortalContext;
1391 QueryContext = saveQueryContext;
1397 MemoryContextSwitchTo(oldContext);
1399 /* Mark portal not active */
1400 portal->status = PORTAL_READY;
1402 ActivePortal = saveActivePortal;
1403 ActiveSnapshot = saveActiveSnapshot;
1404 CurrentResourceOwner = saveResourceOwner;
1405 PortalContext = savePortalContext;
1406 QueryContext = saveQueryContext;
1413 * Guts of PortalRunFetch --- the portal context is already set up
1415 * Returns number of rows processed (suitable for use in result tag)
1418 DoPortalRunFetch(Portal portal,
1419 FetchDirection fdirection,
1425 Assert(portal->strategy == PORTAL_ONE_SELECT ||
1426 portal->strategy == PORTAL_ONE_RETURNING ||
1427 portal->strategy == PORTAL_UTIL_SELECT);
1434 fdirection = FETCH_BACKWARD;
1437 /* fall out of switch to share code with FETCH_BACKWARD */
1439 case FETCH_BACKWARD:
1442 fdirection = FETCH_FORWARD;
1445 /* fall out of switch to share code with FETCH_FORWARD */
1447 case FETCH_ABSOLUTE:
1451 * Definition: Rewind to start, advance count-1 rows, return
1452 * next row (if any). In practice, if the goal is less than
1453 * halfway back to the start, it's better to scan from where
1454 * we are. In any case, we arrange to fetch the target row
1457 if (portal->posOverflow || portal->portalPos == LONG_MAX ||
1458 count - 1 <= portal->portalPos / 2)
1460 DoPortalRewind(portal);
1462 PortalRunSelect(portal, true, count - 1,
1467 long pos = portal->portalPos;
1470 pos++; /* need one extra fetch if off end */
1472 PortalRunSelect(portal, false, pos - count + 1,
1474 else if (count > pos + 1)
1475 PortalRunSelect(portal, true, count - pos - 1,
1478 return PortalRunSelect(portal, true, 1L, dest);
1483 * Definition: Advance to end, back up abs(count)-1 rows,
1484 * return prior row (if any). We could optimize this if we
1485 * knew in advance where the end was, but typically we won't.
1486 * (Is it worth considering case where count > half of size of
1487 * query? We could rewind once we know the size ...)
1489 PortalRunSelect(portal, true, FETCH_ALL, None_Receiver);
1491 PortalRunSelect(portal, false, -count - 1, None_Receiver);
1492 return PortalRunSelect(portal, false, 1L, dest);
1497 /* Rewind to start, return zero rows */
1498 DoPortalRewind(portal);
1499 return PortalRunSelect(portal, true, 0L, dest);
1502 case FETCH_RELATIVE:
1506 * Definition: advance count-1 rows, return next row (if any).
1509 PortalRunSelect(portal, true, count - 1, None_Receiver);
1510 return PortalRunSelect(portal, true, 1L, dest);
1515 * Definition: back up abs(count)-1 rows, return prior row (if
1519 PortalRunSelect(portal, false, -count - 1, None_Receiver);
1520 return PortalRunSelect(portal, false, 1L, dest);
1525 /* Same as FETCH FORWARD 0, so fall out of switch */
1526 fdirection = FETCH_FORWARD;
1530 elog(ERROR, "bogus direction");
1535 * Get here with fdirection == FETCH_FORWARD or FETCH_BACKWARD, and count
1538 forward = (fdirection == FETCH_FORWARD);
1541 * Zero count means to re-fetch the current row, if any (per SQL92)
1547 /* Are we sitting on a row? */
1548 on_row = (!portal->atStart && !portal->atEnd);
1550 if (dest->mydest == DestNone)
1552 /* MOVE 0 returns 0/1 based on if FETCH 0 would return a row */
1553 return on_row ? 1L : 0L;
1558 * If we are sitting on a row, back up one so we can re-fetch it.
1559 * If we are not sitting on a row, we still have to start up and
1560 * shut down the executor so that the destination is initialized
1561 * and shut down correctly; so keep going. To PortalRunSelect,
1562 * count == 0 means we will retrieve no row.
1566 PortalRunSelect(portal, false, 1L, None_Receiver);
1567 /* Set up to fetch one row forward */
1575 * Optimize MOVE BACKWARD ALL into a Rewind.
1577 if (!forward && count == FETCH_ALL && dest->mydest == DestNone)
1579 long result = portal->portalPos;
1581 if (result > 0 && !portal->atEnd)
1583 DoPortalRewind(portal);
1584 /* result is bogus if pos had overflowed, but it's best we can do */
1588 return PortalRunSelect(portal, forward, count, dest);
1592 * DoPortalRewind - rewind a Portal to starting point
1595 DoPortalRewind(Portal portal)
1597 if (portal->holdStore)
1599 MemoryContext oldcontext;
1601 oldcontext = MemoryContextSwitchTo(portal->holdContext);
1602 tuplestore_rescan(portal->holdStore);
1603 MemoryContextSwitchTo(oldcontext);
1605 if (PortalGetQueryDesc(portal))
1606 ExecutorRewind(PortalGetQueryDesc(portal));
1608 portal->atStart = true;
1609 portal->atEnd = false;
1610 portal->portalPos = 0;
1611 portal->posOverflow = false;