1 /*-------------------------------------------------------------------------
4 * top level executor interface routines
11 * The old ExecutorMain() has been replaced by ExecutorStart(),
12 * ExecutorRun() and ExecutorEnd()
14 * These three procedures are the external interfaces to the executor.
15 * In each case, the query descriptor is required as an argument.
17 * ExecutorStart() must be called at the beginning of execution of any
18 * query plan and ExecutorEnd() should always be called at the end of
19 * execution of a plan.
21 * ExecutorRun accepts direction and count arguments that specify whether
22 * the plan is to be executed forwards, backwards, and for how many tuples.
24 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
25 * Portions Copyright (c) 1994, Regents of the University of California
29 * $Header: /cvsroot/pgsql/src/backend/executor/execMain.c,v 1.221 2003/11/06 22:08:14 petere Exp $
31 *-------------------------------------------------------------------------
35 #include "access/heapam.h"
36 #include "catalog/heap.h"
37 #include "catalog/namespace.h"
38 #include "commands/tablecmds.h"
39 #include "commands/trigger.h"
40 #include "executor/execdebug.h"
41 #include "executor/execdefs.h"
42 #include "miscadmin.h"
43 #include "optimizer/var.h"
44 #include "parser/parsetree.h"
45 #include "utils/acl.h"
46 #include "utils/lsyscache.h"
49 typedef struct execRowMark
56 typedef struct evalPlanQual
61 struct evalPlanQual *next; /* stack of active PlanQual plans */
62 struct evalPlanQual *free; /* list of free PlanQual plans */
65 /* decls for local routines only used within this module */
66 static void InitPlan(QueryDesc *queryDesc, bool explainOnly);
67 static void initResultRelInfo(ResultRelInfo *resultRelInfo,
68 Index resultRelationIndex,
71 static TupleTableSlot *ExecutePlan(EState *estate, PlanState *planstate,
74 ScanDirection direction,
76 static void ExecSelect(TupleTableSlot *slot,
79 static void ExecInsert(TupleTableSlot *slot, ItemPointer tupleid,
81 static void ExecDelete(TupleTableSlot *slot, ItemPointer tupleid,
83 static void ExecUpdate(TupleTableSlot *slot, ItemPointer tupleid,
85 static TupleTableSlot *EvalPlanQualNext(EState *estate);
86 static void EndEvalPlanQual(EState *estate);
87 static void ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation);
88 static void ExecCheckXactReadOnly(Query *parsetree, CmdType operation);
89 static void EvalPlanQualStart(evalPlanQual *epq, EState *estate,
90 evalPlanQual *priorepq);
91 static void EvalPlanQualStop(evalPlanQual *epq);
93 /* end of local decls */
96 /* ----------------------------------------------------------------
99 * This routine must be called at the beginning of any execution of any
102 * Takes a QueryDesc previously created by CreateQueryDesc (it's not real
103 * clear why we bother to separate the two functions, but...). The tupDesc
104 * field of the QueryDesc is filled in to describe the tuples that will be
105 * returned, and the internal fields (estate and planstate) are set up.
107 * If useCurrentSnapshot is true, run the query with the latest available
108 * snapshot, instead of the normal QuerySnapshot. Also, if it's an update
109 * or delete query, check that the rows to be updated or deleted would be
110 * visible to the normal QuerySnapshot. (This is a special-case behavior
111 * needed for referential integrity updates in serializable transactions.
112 * We must check all currently-committed rows, but we want to throw a
113 * can't-serialize error if any rows that would need updates would not be
114 * visible under the normal serializable snapshot.)
116 * If explainOnly is true, we are not actually intending to run the plan,
117 * only to set up for EXPLAIN; so skip unwanted side-effects.
119 * NB: the CurrentMemoryContext when this is called will become the parent
120 * of the per-query context used for this Executor invocation.
121 * ----------------------------------------------------------------
124 ExecutorStart(QueryDesc *queryDesc, bool useCurrentSnapshot, bool explainOnly)
127 MemoryContext oldcontext;
129 /* sanity checks: queryDesc must not be started already */
130 Assert(queryDesc != NULL);
131 Assert(queryDesc->estate == NULL);
134 * If the transaction is read-only, we need to check if any writes are
135 * planned to non-temporary tables.
138 ExecCheckXactReadOnly(queryDesc->parsetree, queryDesc->operation);
141 * Build EState, switch into per-query memory context for startup.
143 estate = CreateExecutorState();
144 queryDesc->estate = estate;
146 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
149 * Fill in parameters, if any, from queryDesc
151 estate->es_param_list_info = queryDesc->params;
153 if (queryDesc->plantree->nParamExec > 0)
154 estate->es_param_exec_vals = (ParamExecData *)
155 palloc0(queryDesc->plantree->nParamExec * sizeof(ParamExecData));
157 estate->es_instrument = queryDesc->doInstrument;
160 * Make our own private copy of the current query snapshot data.
162 * This "freezes" our idea of which tuples are good and which are not for
163 * the life of this query, even if it outlives the current command and
166 if (useCurrentSnapshot)
168 /* RI update/delete query --- must use an up-to-date snapshot */
169 estate->es_snapshot = CopyCurrentSnapshot();
170 /* crosscheck updates/deletes against transaction snapshot */
171 estate->es_crosscheck_snapshot = CopyQuerySnapshot();
175 /* normal query --- use query snapshot, no crosscheck */
176 estate->es_snapshot = CopyQuerySnapshot();
177 estate->es_crosscheck_snapshot = SnapshotAny;
181 * Initialize the plan state tree
183 InitPlan(queryDesc, explainOnly);
185 MemoryContextSwitchTo(oldcontext);
188 /* ----------------------------------------------------------------
191 * This is the main routine of the executor module. It accepts
192 * the query descriptor from the traffic cop and executes the
195 * ExecutorStart must have been called already.
197 * If direction is NoMovementScanDirection then nothing is done
198 * except to start up/shut down the destination. Otherwise,
199 * we retrieve up to 'count' tuples in the specified direction.
201 * Note: count = 0 is interpreted as no portal limit, i.e., run to
204 * ----------------------------------------------------------------
207 ExecutorRun(QueryDesc *queryDesc,
208 ScanDirection direction, long count)
213 TupleTableSlot *result;
214 MemoryContext oldcontext;
217 Assert(queryDesc != NULL);
219 estate = queryDesc->estate;
221 Assert(estate != NULL);
224 * Switch into per-query memory context
226 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
229 * extract information from the query descriptor and the query
232 operation = queryDesc->operation;
233 dest = queryDesc->dest;
236 * startup tuple receiver
238 estate->es_processed = 0;
239 estate->es_lastoid = InvalidOid;
241 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
246 if (direction == NoMovementScanDirection)
249 result = ExecutePlan(estate,
250 queryDesc->planstate,
259 (*dest->rShutdown) (dest);
261 MemoryContextSwitchTo(oldcontext);
266 /* ----------------------------------------------------------------
269 * This routine must be called at the end of execution of any
271 * ----------------------------------------------------------------
274 ExecutorEnd(QueryDesc *queryDesc)
277 MemoryContext oldcontext;
280 Assert(queryDesc != NULL);
282 estate = queryDesc->estate;
284 Assert(estate != NULL);
287 * Switch into per-query memory context to run ExecEndPlan
289 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
291 ExecEndPlan(queryDesc->planstate, estate);
294 * Must switch out of context before destroying it
296 MemoryContextSwitchTo(oldcontext);
299 * Release EState and per-query memory context. This should release
300 * everything the executor has allocated.
302 FreeExecutorState(estate);
304 /* Reset queryDesc fields that no longer point to anything */
305 queryDesc->tupDesc = NULL;
306 queryDesc->estate = NULL;
307 queryDesc->planstate = NULL;
310 /* ----------------------------------------------------------------
313 * This routine may be called on an open queryDesc to rewind it
315 * ----------------------------------------------------------------
318 ExecutorRewind(QueryDesc *queryDesc)
321 MemoryContext oldcontext;
324 Assert(queryDesc != NULL);
326 estate = queryDesc->estate;
328 Assert(estate != NULL);
330 /* It's probably not sensible to rescan updating queries */
331 Assert(queryDesc->operation == CMD_SELECT);
334 * Switch into per-query memory context
336 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
341 ExecReScan(queryDesc->planstate, NULL);
343 MemoryContextSwitchTo(oldcontext);
349 * Check access permissions for all relations listed in a range table.
352 ExecCheckRTPerms(List *rangeTable, CmdType operation)
356 foreach(lp, rangeTable)
358 RangeTblEntry *rte = lfirst(lp);
360 ExecCheckRTEPerms(rte, operation);
366 * Check access permissions for a single RTE.
369 ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation)
373 AclResult aclcheck_result;
376 * If it's a subquery, recursively examine its rangetable.
378 if (rte->rtekind == RTE_SUBQUERY)
380 ExecCheckRTPerms(rte->subquery->rtable, operation);
385 * Otherwise, only plain-relation RTEs need to be checked here.
386 * Function RTEs are checked by init_fcache when the function is
387 * prepared for execution. Join and special RTEs need no checks.
389 if (rte->rtekind != RTE_RELATION)
395 * userid to check as: current user unless we have a setuid
398 * Note: GetUserId() is presently fast enough that there's no harm in
399 * calling it separately for each RTE. If that stops being true, we
400 * could call it once in ExecCheckRTPerms and pass the userid down
401 * from there. But for now, no need for the extra clutter.
403 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
405 #define CHECK(MODE) pg_class_aclcheck(relOid, userid, MODE)
407 if (rte->checkForRead)
409 aclcheck_result = CHECK(ACL_SELECT);
410 if (aclcheck_result != ACLCHECK_OK)
411 aclcheck_error(aclcheck_result, ACL_KIND_CLASS,
412 get_rel_name(relOid));
415 if (rte->checkForWrite)
418 * Note: write access in a SELECT context means SELECT FOR UPDATE.
419 * Right now we don't distinguish that from true update as far as
420 * permissions checks are concerned.
425 aclcheck_result = CHECK(ACL_INSERT);
429 aclcheck_result = CHECK(ACL_UPDATE);
432 aclcheck_result = CHECK(ACL_DELETE);
435 elog(ERROR, "unrecognized operation code: %d",
437 aclcheck_result = ACLCHECK_OK; /* keep compiler quiet */
440 if (aclcheck_result != ACLCHECK_OK)
441 aclcheck_error(aclcheck_result, ACL_KIND_CLASS,
442 get_rel_name(relOid));
447 ExecCheckXactReadOnly(Query *parsetree, CmdType operation)
452 /* CREATE TABLE AS or SELECT INTO */
453 if (operation == CMD_SELECT && parsetree->into != NULL)
456 if (operation == CMD_DELETE || operation == CMD_INSERT
457 || operation == CMD_UPDATE)
461 foreach(lp, parsetree->rtable)
463 RangeTblEntry *rte = lfirst(lp);
465 if (rte->rtekind != RTE_RELATION)
468 if (!rte->checkForWrite)
471 if (isTempNamespace(get_rel_namespace(rte->relid)))
482 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
483 errmsg("transaction is read-only")));
487 /* ----------------------------------------------------------------
490 * Initializes the query plan: open files, allocate storage
491 * and start up the rule manager
492 * ----------------------------------------------------------------
495 InitPlan(QueryDesc *queryDesc, bool explainOnly)
497 CmdType operation = queryDesc->operation;
498 Query *parseTree = queryDesc->parsetree;
499 Plan *plan = queryDesc->plantree;
500 EState *estate = queryDesc->estate;
501 PlanState *planstate;
503 Relation intoRelationDesc;
508 * Do permissions checks. It's sufficient to examine the query's top
509 * rangetable here --- subplan RTEs will be checked during
512 ExecCheckRTPerms(parseTree->rtable, operation);
515 * get information from query descriptor
517 rangeTable = parseTree->rtable;
520 * initialize the node's execution state
522 estate->es_range_table = rangeTable;
525 * if there is a result relation, initialize result relation stuff
527 if (parseTree->resultRelation != 0 && operation != CMD_SELECT)
529 List *resultRelations = parseTree->resultRelations;
530 int numResultRelations;
531 ResultRelInfo *resultRelInfos;
533 if (resultRelations != NIL)
536 * Multiple result relations (due to inheritance)
537 * parseTree->resultRelations identifies them all
539 ResultRelInfo *resultRelInfo;
541 numResultRelations = length(resultRelations);
542 resultRelInfos = (ResultRelInfo *)
543 palloc(numResultRelations * sizeof(ResultRelInfo));
544 resultRelInfo = resultRelInfos;
545 while (resultRelations != NIL)
547 initResultRelInfo(resultRelInfo,
548 lfirsti(resultRelations),
552 resultRelations = lnext(resultRelations);
558 * Single result relation identified by
559 * parseTree->resultRelation
561 numResultRelations = 1;
562 resultRelInfos = (ResultRelInfo *) palloc(sizeof(ResultRelInfo));
563 initResultRelInfo(resultRelInfos,
564 parseTree->resultRelation,
569 estate->es_result_relations = resultRelInfos;
570 estate->es_num_result_relations = numResultRelations;
571 /* Initialize to first or only result rel */
572 estate->es_result_relation_info = resultRelInfos;
577 * if no result relation, then set state appropriately
579 estate->es_result_relations = NULL;
580 estate->es_num_result_relations = 0;
581 estate->es_result_relation_info = NULL;
585 * Detect whether we're doing SELECT INTO. If so, set the force_oids
586 * flag appropriately so that the plan tree will be initialized with
587 * the correct tuple descriptors.
589 do_select_into = false;
591 if (operation == CMD_SELECT && parseTree->into != NULL)
593 do_select_into = true;
596 * For now, always create OIDs in SELECT INTO; this is for
597 * backwards compatibility with pre-7.3 behavior. Eventually we
598 * might want to allow the user to choose.
600 estate->es_force_oids = true;
604 * Have to lock relations selected for update
606 estate->es_rowMark = NIL;
607 if (parseTree->rowMarks != NIL)
611 foreach(l, parseTree->rowMarks)
613 Index rti = lfirsti(l);
614 Oid relid = getrelid(rti, rangeTable);
618 relation = heap_open(relid, RowShareLock);
619 erm = (execRowMark *) palloc(sizeof(execRowMark));
620 erm->relation = relation;
622 snprintf(erm->resname, sizeof(erm->resname), "ctid%u", rti);
623 estate->es_rowMark = lappend(estate->es_rowMark, erm);
628 * initialize the executor "tuple" table. We need slots for all the
629 * plan nodes, plus possibly output slots for the junkfilter(s). At
630 * this point we aren't sure if we need junkfilters, so just add slots
631 * for them unconditionally.
634 int nSlots = ExecCountSlotsNode(plan);
636 if (parseTree->resultRelations != NIL)
637 nSlots += length(parseTree->resultRelations);
640 estate->es_tupleTable = ExecCreateTupleTable(nSlots);
643 /* mark EvalPlanQual not active */
644 estate->es_topPlan = plan;
645 estate->es_evalPlanQual = NULL;
646 estate->es_evTupleNull = NULL;
647 estate->es_evTuple = NULL;
648 estate->es_useEvalPlan = false;
651 * initialize the private state information for all the nodes in the
652 * query tree. This opens files, allocates storage and leaves us
653 * ready to start processing tuples.
655 planstate = ExecInitNode(plan, estate);
658 * Get the tuple descriptor describing the type of tuples to return.
659 * (this is especially important if we are creating a relation with
662 tupType = ExecGetResultType(planstate);
665 * Initialize the junk filter if needed. SELECT and INSERT queries
666 * need a filter if there are any junk attrs in the tlist. INSERT and
667 * SELECT INTO also need a filter if the top plan node is a scan node
668 * that's not doing projection (else we'll be scribbling on the scan
669 * tuple!) UPDATE and DELETE always need a filter, since there's
670 * always a junk 'ctid' attribute present --- no need to look first.
673 bool junk_filter_needed = false;
680 foreach(tlist, plan->targetlist)
682 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
684 if (tle->resdom->resjunk)
686 junk_filter_needed = true;
690 if (!junk_filter_needed &&
691 (operation == CMD_INSERT || do_select_into))
693 if (IsA(planstate, SeqScanState) ||
694 IsA(planstate, IndexScanState) ||
695 IsA(planstate, TidScanState) ||
696 IsA(planstate, SubqueryScanState) ||
697 IsA(planstate, FunctionScanState))
699 if (planstate->ps_ProjInfo == NULL)
700 junk_filter_needed = true;
706 junk_filter_needed = true;
712 if (junk_filter_needed)
715 * If there are multiple result relations, each one needs its
716 * own junk filter. Note this is only possible for
717 * UPDATE/DELETE, so we can't be fooled by some needing a
718 * filter and some not.
720 if (parseTree->resultRelations != NIL)
722 PlanState **appendplans;
724 ResultRelInfo *resultRelInfo;
727 /* Top plan had better be an Append here. */
728 Assert(IsA(plan, Append));
729 Assert(((Append *) plan)->isTarget);
730 Assert(IsA(planstate, AppendState));
731 appendplans = ((AppendState *) planstate)->appendplans;
732 as_nplans = ((AppendState *) planstate)->as_nplans;
733 Assert(as_nplans == estate->es_num_result_relations);
734 resultRelInfo = estate->es_result_relations;
735 for (i = 0; i < as_nplans; i++)
737 PlanState *subplan = appendplans[i];
740 j = ExecInitJunkFilter(subplan->plan->targetlist,
741 ExecGetResultType(subplan),
742 ExecAllocTableSlot(estate->es_tupleTable));
743 resultRelInfo->ri_junkFilter = j;
748 * Set active junkfilter too; at this point ExecInitAppend
749 * has already selected an active result relation...
751 estate->es_junkFilter =
752 estate->es_result_relation_info->ri_junkFilter;
756 /* Normal case with just one JunkFilter */
759 j = ExecInitJunkFilter(planstate->plan->targetlist,
761 ExecAllocTableSlot(estate->es_tupleTable));
762 estate->es_junkFilter = j;
763 if (estate->es_result_relation_info)
764 estate->es_result_relation_info->ri_junkFilter = j;
766 /* For SELECT, want to return the cleaned tuple type */
767 if (operation == CMD_SELECT)
768 tupType = j->jf_cleanTupType;
772 estate->es_junkFilter = NULL;
776 * If doing SELECT INTO, initialize the "into" relation. We must wait
777 * till now so we have the "clean" result tuple type to create the new
780 * If EXPLAIN, skip creating the "into" relation.
782 intoRelationDesc = (Relation) NULL;
784 if (do_select_into && !explainOnly)
793 * find namespace to create in, check permissions
795 intoName = parseTree->into->relname;
796 namespaceId = RangeVarGetCreationNamespace(parseTree->into);
798 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
800 if (aclresult != ACLCHECK_OK)
801 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
802 get_namespace_name(namespaceId));
805 * have to copy tupType to get rid of constraints
807 tupdesc = CreateTupleDescCopy(tupType);
809 intoRelationId = heap_create_with_catalog(intoName,
815 allowSystemTableMods);
817 FreeTupleDesc(tupdesc);
820 * Advance command counter so that the newly-created relation's
821 * catalog tuples will be visible to heap_open.
823 CommandCounterIncrement();
826 * If necessary, create a TOAST table for the into relation. Note
827 * that AlterTableCreateToastTable ends with
828 * CommandCounterIncrement(), so that the TOAST table will be
829 * visible for insertion.
831 AlterTableCreateToastTable(intoRelationId, true);
834 * And open the constructed table for writing.
836 intoRelationDesc = heap_open(intoRelationId, AccessExclusiveLock);
839 estate->es_into_relation_descriptor = intoRelationDesc;
841 queryDesc->tupDesc = tupType;
842 queryDesc->planstate = planstate;
846 * Initialize ResultRelInfo data for one result relation
849 initResultRelInfo(ResultRelInfo *resultRelInfo,
850 Index resultRelationIndex,
854 Oid resultRelationOid;
855 Relation resultRelationDesc;
857 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
858 resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
860 switch (resultRelationDesc->rd_rel->relkind)
862 case RELKIND_SEQUENCE:
864 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
865 errmsg("cannot change sequence \"%s\"",
866 RelationGetRelationName(resultRelationDesc))));
868 case RELKIND_TOASTVALUE:
870 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
871 errmsg("cannot change TOAST relation \"%s\"",
872 RelationGetRelationName(resultRelationDesc))));
876 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
877 errmsg("cannot change view \"%s\"",
878 RelationGetRelationName(resultRelationDesc))));
882 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
883 resultRelInfo->type = T_ResultRelInfo;
884 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
885 resultRelInfo->ri_RelationDesc = resultRelationDesc;
886 resultRelInfo->ri_NumIndices = 0;
887 resultRelInfo->ri_IndexRelationDescs = NULL;
888 resultRelInfo->ri_IndexRelationInfo = NULL;
889 /* make a copy so as not to depend on relcache info not changing... */
890 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
891 resultRelInfo->ri_TrigFunctions = NULL;
892 resultRelInfo->ri_ConstraintExprs = NULL;
893 resultRelInfo->ri_junkFilter = NULL;
896 * If there are indices on the result relation, open them and save
897 * descriptors in the result relation info, so that we can add new
898 * index entries for the tuples we add/update. We need not do this
899 * for a DELETE, however, since deletion doesn't affect indexes.
901 if (resultRelationDesc->rd_rel->relhasindex &&
902 operation != CMD_DELETE)
903 ExecOpenIndices(resultRelInfo);
906 /* ----------------------------------------------------------------
909 * Cleans up the query plan -- closes files and frees up storage
911 * NOTE: we are no longer very worried about freeing storage per se
912 * in this code; FreeExecutorState should be guaranteed to release all
913 * memory that needs to be released. What we are worried about doing
914 * is closing relations and dropping buffer pins. Thus, for example,
915 * tuple tables must be cleared or dropped to ensure pins are released.
916 * ----------------------------------------------------------------
919 ExecEndPlan(PlanState *planstate, EState *estate)
921 ResultRelInfo *resultRelInfo;
926 * shut down any PlanQual processing we were doing
928 if (estate->es_evalPlanQual != NULL)
929 EndEvalPlanQual(estate);
932 * shut down the node-type-specific query processing
934 ExecEndNode(planstate);
937 * destroy the executor "tuple" table.
939 ExecDropTupleTable(estate->es_tupleTable, true);
940 estate->es_tupleTable = NULL;
943 * close the result relation(s) if any, but hold locks until xact
946 resultRelInfo = estate->es_result_relations;
947 for (i = estate->es_num_result_relations; i > 0; i--)
949 /* Close indices and then the relation itself */
950 ExecCloseIndices(resultRelInfo);
951 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
956 * close the "into" relation if necessary, again keeping lock
958 if (estate->es_into_relation_descriptor != NULL)
959 heap_close(estate->es_into_relation_descriptor, NoLock);
962 * close any relations selected FOR UPDATE, again keeping locks
964 foreach(l, estate->es_rowMark)
966 execRowMark *erm = lfirst(l);
968 heap_close(erm->relation, NoLock);
972 /* ----------------------------------------------------------------
975 * processes the query plan to retrieve 'numberTuples' tuples in the
976 * direction specified.
978 * Retrieves all tuples if numberTuples is 0
980 * result is either a slot containing the last tuple in the case
981 * of a SELECT or NULL otherwise.
983 * Note: the ctid attribute is a 'junk' attribute that is removed before the
985 * ----------------------------------------------------------------
987 static TupleTableSlot *
988 ExecutePlan(EState *estate,
989 PlanState *planstate,
992 ScanDirection direction,
995 JunkFilter *junkfilter;
996 TupleTableSlot *slot;
997 ItemPointer tupleid = NULL;
998 ItemPointerData tuple_ctid;
999 long current_tuple_count;
1000 TupleTableSlot *result;
1003 * initialize local variables
1006 current_tuple_count = 0;
1010 * Set the direction.
1012 estate->es_direction = direction;
1015 * Process BEFORE EACH STATEMENT triggers
1020 ExecBSUpdateTriggers(estate, estate->es_result_relation_info);
1023 ExecBSDeleteTriggers(estate, estate->es_result_relation_info);
1026 ExecBSInsertTriggers(estate, estate->es_result_relation_info);
1034 * Loop until we've processed the proper number of tuples from the
1040 /* Reset the per-output-tuple exprcontext */
1041 ResetPerTupleExprContext(estate);
1044 * Execute the plan and obtain a tuple
1047 if (estate->es_useEvalPlan)
1049 slot = EvalPlanQualNext(estate);
1050 if (TupIsNull(slot))
1051 slot = ExecProcNode(planstate);
1054 slot = ExecProcNode(planstate);
1057 * if the tuple is null, then we assume there is nothing more to
1058 * process so we just return null...
1060 if (TupIsNull(slot))
1067 * if we have a junk filter, then project a new tuple with the
1070 * Store this new "clean" tuple in the junkfilter's resultSlot.
1071 * (Formerly, we stored it back over the "dirty" tuple, which is
1072 * WRONG because that tuple slot has the wrong descriptor.)
1074 * Also, extract all the junk information we need.
1076 if ((junkfilter = estate->es_junkFilter) != (JunkFilter *) NULL)
1083 * extract the 'ctid' junk attribute.
1085 if (operation == CMD_UPDATE || operation == CMD_DELETE)
1087 if (!ExecGetJunkAttribute(junkfilter,
1092 elog(ERROR, "could not find junk ctid column");
1094 /* shouldn't ever get a null result... */
1096 elog(ERROR, "ctid is NULL");
1098 tupleid = (ItemPointer) DatumGetPointer(datum);
1099 tuple_ctid = *tupleid; /* make sure we don't free the
1101 tupleid = &tuple_ctid;
1103 else if (estate->es_rowMark != NIL)
1108 foreach(l, estate->es_rowMark)
1110 execRowMark *erm = lfirst(l);
1112 HeapTupleData tuple;
1113 TupleTableSlot *newSlot;
1116 if (!ExecGetJunkAttribute(junkfilter,
1121 elog(ERROR, "could not find junk \"%s\" column",
1124 /* shouldn't ever get a null result... */
1126 elog(ERROR, "\"%s\" is NULL", erm->resname);
1128 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1129 test = heap_mark4update(erm->relation, &tuple, &buffer,
1130 estate->es_snapshot->curcid);
1131 ReleaseBuffer(buffer);
1134 case HeapTupleSelfUpdated:
1135 /* treat it as deleted; do not process */
1138 case HeapTupleMayBeUpdated:
1141 case HeapTupleUpdated:
1142 if (IsXactIsoLevelSerializable)
1144 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1145 errmsg("could not serialize access due to concurrent update")));
1146 if (!(ItemPointerEquals(&(tuple.t_self),
1147 (ItemPointer) DatumGetPointer(datum))))
1149 newSlot = EvalPlanQual(estate, erm->rti, &(tuple.t_self));
1150 if (!(TupIsNull(newSlot)))
1153 estate->es_useEvalPlan = true;
1159 * if tuple was deleted or PlanQual failed for
1160 * updated tuple - we must not return this
1166 elog(ERROR, "unrecognized heap_mark4update status: %u",
1174 * Finally create a new "clean" tuple with all junk attributes
1177 newTuple = ExecRemoveJunk(junkfilter, slot);
1179 slot = ExecStoreTuple(newTuple, /* tuple to store */
1180 junkfilter->jf_resultSlot, /* dest slot */
1181 InvalidBuffer, /* this tuple has no
1183 true); /* tuple should be pfreed */
1187 * now that we have a tuple, do the appropriate thing with it..
1188 * either return it to the user, add it to a relation someplace,
1189 * delete it from a relation, or modify some of its attributes.
1194 ExecSelect(slot, /* slot containing tuple */
1195 dest, /* destination's tuple-receiver obj */
1201 ExecInsert(slot, tupleid, estate);
1206 ExecDelete(slot, tupleid, estate);
1211 ExecUpdate(slot, tupleid, estate);
1216 elog(ERROR, "unrecognized operation code: %d",
1223 * check our tuple count.. if we've processed the proper number
1224 * then quit, else loop again and process more tuples. Zero
1225 * numberTuples means no limit.
1227 current_tuple_count++;
1228 if (numberTuples && numberTuples == current_tuple_count)
1233 * Process AFTER EACH STATEMENT triggers
1238 ExecASUpdateTriggers(estate, estate->es_result_relation_info);
1241 ExecASDeleteTriggers(estate, estate->es_result_relation_info);
1244 ExecASInsertTriggers(estate, estate->es_result_relation_info);
1252 * here, result is either a slot containing a tuple in the case of a
1253 * SELECT or NULL otherwise.
1258 /* ----------------------------------------------------------------
1261 * SELECTs are easy.. we just pass the tuple to the appropriate
1262 * print function. The only complexity is when we do a
1263 * "SELECT INTO", in which case we insert the tuple into
1264 * the appropriate relation (note: this is a newly created relation
1265 * so we don't need to worry about indices or locks.)
1266 * ----------------------------------------------------------------
1269 ExecSelect(TupleTableSlot *slot,
1277 * get the heap tuple out of the tuple table slot
1280 attrtype = slot->ttc_tupleDescriptor;
1283 * insert the tuple into the "into relation"
1285 * XXX this probably ought to be replaced by a separate destination
1287 if (estate->es_into_relation_descriptor != NULL)
1289 heap_insert(estate->es_into_relation_descriptor, tuple,
1290 estate->es_snapshot->curcid);
1295 * send the tuple to the destination
1297 (*dest->receiveTuple) (tuple, attrtype, dest);
1299 (estate->es_processed)++;
1302 /* ----------------------------------------------------------------
1305 * INSERTs are trickier.. we have to insert the tuple into
1306 * the base relation and insert appropriate tuples into the
1308 * ----------------------------------------------------------------
1311 ExecInsert(TupleTableSlot *slot,
1312 ItemPointer tupleid,
1316 ResultRelInfo *resultRelInfo;
1317 Relation resultRelationDesc;
1322 * get the heap tuple out of the tuple table slot
1327 * get information on the (current) result relation
1329 resultRelInfo = estate->es_result_relation_info;
1330 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1332 /* BEFORE ROW INSERT Triggers */
1333 if (resultRelInfo->ri_TrigDesc &&
1334 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1338 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1340 if (newtuple == NULL) /* "do nothing" */
1343 if (newtuple != tuple) /* modified by Trigger(s) */
1346 * Insert modified tuple into tuple table slot, replacing the
1347 * original. We assume that it was allocated in per-tuple
1348 * memory context, and therefore will go away by itself. The
1349 * tuple table slot should not try to clear it.
1351 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1357 * Check the constraints of the tuple
1359 if (resultRelationDesc->rd_att->constr)
1360 ExecConstraints(resultRelInfo, slot, estate);
1365 newId = heap_insert(resultRelationDesc, tuple,
1366 estate->es_snapshot->curcid);
1369 (estate->es_processed)++;
1370 estate->es_lastoid = newId;
1371 setLastTid(&(tuple->t_self));
1376 * Note: heap_insert adds a new tuple to a relation. As a side effect,
1377 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1380 numIndices = resultRelInfo->ri_NumIndices;
1382 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1384 /* AFTER ROW INSERT Triggers */
1385 ExecARInsertTriggers(estate, resultRelInfo, tuple);
1388 /* ----------------------------------------------------------------
1391 * DELETE is like UPDATE, we delete the tuple and its
1393 * ----------------------------------------------------------------
1396 ExecDelete(TupleTableSlot *slot,
1397 ItemPointer tupleid,
1400 ResultRelInfo *resultRelInfo;
1401 Relation resultRelationDesc;
1402 ItemPointerData ctid;
1406 * get information on the (current) result relation
1408 resultRelInfo = estate->es_result_relation_info;
1409 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1411 /* BEFORE ROW DELETE Triggers */
1412 if (resultRelInfo->ri_TrigDesc &&
1413 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1417 dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid,
1418 estate->es_snapshot->curcid);
1420 if (!dodelete) /* "do nothing" */
1428 result = heap_delete(resultRelationDesc, tupleid,
1430 estate->es_snapshot->curcid,
1431 estate->es_crosscheck_snapshot,
1432 true /* wait for commit */);
1435 case HeapTupleSelfUpdated:
1436 /* already deleted by self; nothing to do */
1439 case HeapTupleMayBeUpdated:
1442 case HeapTupleUpdated:
1443 if (IsXactIsoLevelSerializable)
1445 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1446 errmsg("could not serialize access due to concurrent update")));
1447 else if (!(ItemPointerEquals(tupleid, &ctid)))
1449 TupleTableSlot *epqslot = EvalPlanQual(estate,
1450 resultRelInfo->ri_RangeTableIndex, &ctid);
1452 if (!TupIsNull(epqslot))
1458 /* tuple already deleted; nothing to do */
1462 elog(ERROR, "unrecognized heap_delete status: %u", result);
1467 (estate->es_processed)++;
1470 * Note: Normally one would think that we have to delete index tuples
1471 * associated with the heap tuple now..
1473 * ... but in POSTGRES, we have no need to do this because the vacuum
1474 * daemon automatically opens an index scan and deletes index tuples
1475 * when it finds deleted heap tuples. -cim 9/27/89
1478 /* AFTER ROW DELETE Triggers */
1479 ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1482 /* ----------------------------------------------------------------
1485 * note: we can't run UPDATE queries with transactions
1486 * off because UPDATEs are actually INSERTs and our
1487 * scan will mistakenly loop forever, updating the tuple
1488 * it just inserted.. This should be fixed but until it
1489 * is, we don't want to get stuck in an infinite loop
1490 * which corrupts your database..
1491 * ----------------------------------------------------------------
1494 ExecUpdate(TupleTableSlot *slot,
1495 ItemPointer tupleid,
1499 ResultRelInfo *resultRelInfo;
1500 Relation resultRelationDesc;
1501 ItemPointerData ctid;
1506 * abort the operation if not running transactions
1508 if (IsBootstrapProcessingMode())
1509 elog(ERROR, "cannot UPDATE during bootstrap");
1512 * get the heap tuple out of the tuple table slot
1517 * get information on the (current) result relation
1519 resultRelInfo = estate->es_result_relation_info;
1520 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1522 /* BEFORE ROW UPDATE Triggers */
1523 if (resultRelInfo->ri_TrigDesc &&
1524 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1528 newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
1530 estate->es_snapshot->curcid);
1532 if (newtuple == NULL) /* "do nothing" */
1535 if (newtuple != tuple) /* modified by Trigger(s) */
1538 * Insert modified tuple into tuple table slot, replacing the
1539 * original. We assume that it was allocated in per-tuple
1540 * memory context, and therefore will go away by itself. The
1541 * tuple table slot should not try to clear it.
1543 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1549 * Check the constraints of the tuple
1551 * If we generate a new candidate tuple after EvalPlanQual testing, we
1552 * must loop back here and recheck constraints. (We don't need to
1553 * redo triggers, however. If there are any BEFORE triggers then
1554 * trigger.c will have done mark4update to lock the correct tuple, so
1555 * there's no need to do them again.)
1558 if (resultRelationDesc->rd_att->constr)
1559 ExecConstraints(resultRelInfo, slot, estate);
1562 * replace the heap tuple
1564 result = heap_update(resultRelationDesc, tupleid, tuple,
1566 estate->es_snapshot->curcid,
1567 estate->es_crosscheck_snapshot,
1568 true /* wait for commit */);
1571 case HeapTupleSelfUpdated:
1572 /* already deleted by self; nothing to do */
1575 case HeapTupleMayBeUpdated:
1578 case HeapTupleUpdated:
1579 if (IsXactIsoLevelSerializable)
1581 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1582 errmsg("could not serialize access due to concurrent update")));
1583 else if (!(ItemPointerEquals(tupleid, &ctid)))
1585 TupleTableSlot *epqslot = EvalPlanQual(estate,
1586 resultRelInfo->ri_RangeTableIndex, &ctid);
1588 if (!TupIsNull(epqslot))
1591 tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot);
1592 slot = ExecStoreTuple(tuple,
1593 estate->es_junkFilter->jf_resultSlot,
1594 InvalidBuffer, true);
1598 /* tuple already deleted; nothing to do */
1602 elog(ERROR, "unrecognized heap_update status: %u", result);
1607 (estate->es_processed)++;
1610 * Note: instead of having to update the old index tuples associated
1611 * with the heap tuple, all we do is form and insert new index tuples.
1612 * This is because UPDATEs are actually DELETEs and INSERTs and index
1613 * tuple deletion is done automagically by the vacuum daemon. All we
1614 * do is insert new index tuples. -cim 9/27/89
1620 * heap_update updates a tuple in the base relation by invalidating it
1621 * and then inserting a new tuple to the relation. As a side effect,
1622 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1623 * field. So we now insert index tuples using the new tupleid stored
1627 numIndices = resultRelInfo->ri_NumIndices;
1629 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1631 /* AFTER ROW UPDATE Triggers */
1632 ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
1636 ExecRelCheck(ResultRelInfo *resultRelInfo,
1637 TupleTableSlot *slot, EState *estate)
1639 Relation rel = resultRelInfo->ri_RelationDesc;
1640 int ncheck = rel->rd_att->constr->num_check;
1641 ConstrCheck *check = rel->rd_att->constr->check;
1642 ExprContext *econtext;
1643 MemoryContext oldContext;
1648 * If first time through for this result relation, build expression
1649 * nodetrees for rel's constraint expressions. Keep them in the
1650 * per-query memory context so they'll survive throughout the query.
1652 if (resultRelInfo->ri_ConstraintExprs == NULL)
1654 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1655 resultRelInfo->ri_ConstraintExprs =
1656 (List **) palloc(ncheck * sizeof(List *));
1657 for (i = 0; i < ncheck; i++)
1659 qual = (List *) stringToNode(check[i].ccbin);
1660 resultRelInfo->ri_ConstraintExprs[i] = (List *)
1661 ExecPrepareExpr((Expr *) qual, estate);
1663 MemoryContextSwitchTo(oldContext);
1667 * We will use the EState's per-tuple context for evaluating
1668 * constraint expressions (creating it if it's not already there).
1670 econtext = GetPerTupleExprContext(estate);
1672 /* Arrange for econtext's scan tuple to be the tuple under test */
1673 econtext->ecxt_scantuple = slot;
1675 /* And evaluate the constraints */
1676 for (i = 0; i < ncheck; i++)
1678 qual = resultRelInfo->ri_ConstraintExprs[i];
1681 * NOTE: SQL92 specifies that a NULL result from a constraint
1682 * expression is not to be treated as a failure. Therefore, tell
1683 * ExecQual to return TRUE for NULL.
1685 if (!ExecQual(qual, econtext, true))
1686 return check[i].ccname;
1689 /* NULL result means no error */
1694 ExecConstraints(ResultRelInfo *resultRelInfo,
1695 TupleTableSlot *slot, EState *estate)
1697 Relation rel = resultRelInfo->ri_RelationDesc;
1698 HeapTuple tuple = slot->val;
1699 TupleConstr *constr = rel->rd_att->constr;
1703 if (constr->has_not_null)
1705 int natts = rel->rd_att->natts;
1708 for (attrChk = 1; attrChk <= natts; attrChk++)
1710 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1711 heap_attisnull(tuple, attrChk))
1713 (errcode(ERRCODE_NOT_NULL_VIOLATION),
1714 errmsg("null value in column \"%s\" violates not-null constraint",
1715 NameStr(rel->rd_att->attrs[attrChk - 1]->attname))));
1719 if (constr->num_check > 0)
1723 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1725 (errcode(ERRCODE_CHECK_VIOLATION),
1726 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1727 RelationGetRelationName(rel), failed)));
1732 * Check a modified tuple to see if we want to process its updated version
1733 * under READ COMMITTED rules.
1735 * See backend/executor/README for some info about how this works.
1738 EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
1743 HeapTupleData tuple;
1744 HeapTuple copyTuple = NULL;
1750 * find relation containing target tuple
1752 if (estate->es_result_relation_info != NULL &&
1753 estate->es_result_relation_info->ri_RangeTableIndex == rti)
1754 relation = estate->es_result_relation_info->ri_RelationDesc;
1760 foreach(l, estate->es_rowMark)
1762 if (((execRowMark *) lfirst(l))->rti == rti)
1764 relation = ((execRowMark *) lfirst(l))->relation;
1768 if (relation == NULL)
1769 elog(ERROR, "could not find RowMark for RT index %u", rti);
1775 * Loop here to deal with updated or busy tuples
1777 tuple.t_self = *tid;
1782 if (heap_fetch(relation, SnapshotDirty, &tuple, &buffer, false, NULL))
1784 TransactionId xwait = SnapshotDirty->xmax;
1786 /* xmin should not be dirty... */
1787 if (TransactionIdIsValid(SnapshotDirty->xmin))
1788 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
1791 * If tuple is being updated by other transaction then we have
1792 * to wait for its commit/abort.
1794 if (TransactionIdIsValid(xwait))
1796 ReleaseBuffer(buffer);
1797 XactLockTableWait(xwait);
1802 * We got tuple - now copy it for use by recheck query.
1804 copyTuple = heap_copytuple(&tuple);
1805 ReleaseBuffer(buffer);
1810 * Oops! Invalid tuple. Have to check is it updated or deleted.
1811 * Note that it's possible to get invalid SnapshotDirty->tid if
1812 * tuple updated by this transaction. Have we to check this ?
1814 if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
1815 !(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
1817 /* updated, so look at the updated copy */
1818 tuple.t_self = SnapshotDirty->tid;
1823 * Deleted or updated by this transaction; forget it.
1829 * For UPDATE/DELETE we have to return tid of actual row we're
1832 *tid = tuple.t_self;
1835 * Need to run a recheck subquery. Find or create a PQ stack entry.
1837 epq = estate->es_evalPlanQual;
1840 if (epq != NULL && epq->rti == 0)
1842 /* Top PQ stack entry is idle, so re-use it */
1843 Assert(!(estate->es_useEvalPlan) && epq->next == NULL);
1849 * If this is request for another RTE - Ra, - then we have to check
1850 * wasn't PlanQual requested for Ra already and if so then Ra' row was
1851 * updated again and we have to re-start old execution for Ra and
1852 * forget all what we done after Ra was suspended. Cool? -:))
1854 if (epq != NULL && epq->rti != rti &&
1855 epq->estate->es_evTuple[rti - 1] != NULL)
1859 evalPlanQual *oldepq;
1861 /* stop execution */
1862 EvalPlanQualStop(epq);
1863 /* pop previous PlanQual from the stack */
1865 Assert(oldepq && oldepq->rti != 0);
1866 /* push current PQ to freePQ stack */
1869 estate->es_evalPlanQual = epq;
1870 } while (epq->rti != rti);
1874 * If we are requested for another RTE then we have to suspend
1875 * execution of current PlanQual and start execution for new one.
1877 if (epq == NULL || epq->rti != rti)
1879 /* try to reuse plan used previously */
1880 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
1882 if (newepq == NULL) /* first call or freePQ stack is empty */
1884 newepq = (evalPlanQual *) palloc0(sizeof(evalPlanQual));
1885 newepq->free = NULL;
1886 newepq->estate = NULL;
1887 newepq->planstate = NULL;
1891 /* recycle previously used PlanQual */
1892 Assert(newepq->estate == NULL);
1895 /* push current PQ to the stack */
1898 estate->es_evalPlanQual = epq;
1903 Assert(epq->rti == rti);
1906 * Ok - we're requested for the same RTE. Unfortunately we still have
1907 * to end and restart execution of the plan, because ExecReScan
1908 * wouldn't ensure that upper plan nodes would reset themselves. We
1909 * could make that work if insertion of the target tuple were
1910 * integrated with the Param mechanism somehow, so that the upper plan
1911 * nodes know that their children's outputs have changed.
1913 * Note that the stack of free evalPlanQual nodes is quite useless at the
1914 * moment, since it only saves us from pallocing/releasing the
1915 * evalPlanQual nodes themselves. But it will be useful once we
1916 * implement ReScan instead of end/restart for re-using PlanQual
1921 /* stop execution */
1922 EvalPlanQualStop(epq);
1926 * Initialize new recheck query.
1928 * Note: if we were re-using PlanQual plans via ExecReScan, we'd need to
1929 * instead copy down changeable state from the top plan (including
1930 * es_result_relation_info, es_junkFilter) and reset locally
1931 * changeable state in the epq (including es_param_exec_vals,
1934 EvalPlanQualStart(epq, estate, epq->next);
1937 * free old RTE' tuple, if any, and store target tuple where
1938 * relation's scan node will see it
1940 epqstate = epq->estate;
1941 if (epqstate->es_evTuple[rti - 1] != NULL)
1942 heap_freetuple(epqstate->es_evTuple[rti - 1]);
1943 epqstate->es_evTuple[rti - 1] = copyTuple;
1945 return EvalPlanQualNext(estate);
1948 static TupleTableSlot *
1949 EvalPlanQualNext(EState *estate)
1951 evalPlanQual *epq = estate->es_evalPlanQual;
1952 MemoryContext oldcontext;
1953 TupleTableSlot *slot;
1955 Assert(epq->rti != 0);
1958 oldcontext = MemoryContextSwitchTo(epq->estate->es_query_cxt);
1959 slot = ExecProcNode(epq->planstate);
1960 MemoryContextSwitchTo(oldcontext);
1963 * No more tuples for this PQ. Continue previous one.
1965 if (TupIsNull(slot))
1967 evalPlanQual *oldepq;
1969 /* stop execution */
1970 EvalPlanQualStop(epq);
1971 /* pop old PQ from the stack */
1975 /* this is the first (oldest) PQ - mark as free */
1977 estate->es_useEvalPlan = false;
1978 /* and continue Query execution */
1981 Assert(oldepq->rti != 0);
1982 /* push current PQ to freePQ stack */
1985 estate->es_evalPlanQual = epq;
1993 EndEvalPlanQual(EState *estate)
1995 evalPlanQual *epq = estate->es_evalPlanQual;
1997 if (epq->rti == 0) /* plans already shutdowned */
1999 Assert(epq->next == NULL);
2005 evalPlanQual *oldepq;
2007 /* stop execution */
2008 EvalPlanQualStop(epq);
2009 /* pop old PQ from the stack */
2013 /* this is the first (oldest) PQ - mark as free */
2015 estate->es_useEvalPlan = false;
2018 Assert(oldepq->rti != 0);
2019 /* push current PQ to freePQ stack */
2022 estate->es_evalPlanQual = epq;
2027 * Start execution of one level of PlanQual.
2029 * This is a cut-down version of ExecutorStart(): we copy some state from
2030 * the top-level estate rather than initializing it fresh.
2033 EvalPlanQualStart(evalPlanQual *epq, EState *estate, evalPlanQual *priorepq)
2037 MemoryContext oldcontext;
2039 rtsize = length(estate->es_range_table);
2041 epq->estate = epqstate = CreateExecutorState();
2043 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2046 * The epqstates share the top query's copy of unchanging state such
2047 * as the snapshot, rangetable, result-rel info, and external Param
2048 * info. They need their own copies of local state, including a tuple
2049 * table, es_param_exec_vals, etc.
2051 epqstate->es_direction = ForwardScanDirection;
2052 epqstate->es_snapshot = estate->es_snapshot;
2053 epqstate->es_crosscheck_snapshot = estate->es_crosscheck_snapshot;
2054 epqstate->es_range_table = estate->es_range_table;
2055 epqstate->es_result_relations = estate->es_result_relations;
2056 epqstate->es_num_result_relations = estate->es_num_result_relations;
2057 epqstate->es_result_relation_info = estate->es_result_relation_info;
2058 epqstate->es_junkFilter = estate->es_junkFilter;
2059 epqstate->es_into_relation_descriptor = estate->es_into_relation_descriptor;
2060 epqstate->es_param_list_info = estate->es_param_list_info;
2061 if (estate->es_topPlan->nParamExec > 0)
2062 epqstate->es_param_exec_vals = (ParamExecData *)
2063 palloc0(estate->es_topPlan->nParamExec * sizeof(ParamExecData));
2064 epqstate->es_rowMark = estate->es_rowMark;
2065 epqstate->es_instrument = estate->es_instrument;
2066 epqstate->es_force_oids = estate->es_force_oids;
2067 epqstate->es_topPlan = estate->es_topPlan;
2070 * Each epqstate must have its own es_evTupleNull state, but all the
2071 * stack entries share es_evTuple state. This allows sub-rechecks to
2072 * inherit the value being examined by an outer recheck.
2074 epqstate->es_evTupleNull = (bool *) palloc0(rtsize * sizeof(bool));
2075 if (priorepq == NULL)
2076 /* first PQ stack entry */
2077 epqstate->es_evTuple = (HeapTuple *)
2078 palloc0(rtsize * sizeof(HeapTuple));
2080 /* later stack entries share the same storage */
2081 epqstate->es_evTuple = priorepq->estate->es_evTuple;
2083 epqstate->es_tupleTable =
2084 ExecCreateTupleTable(estate->es_tupleTable->size);
2086 epq->planstate = ExecInitNode(estate->es_topPlan, epqstate);
2088 MemoryContextSwitchTo(oldcontext);
2092 * End execution of one level of PlanQual.
2094 * This is a cut-down version of ExecutorEnd(); basically we want to do most
2095 * of the normal cleanup, but *not* close result relations (which we are
2096 * just sharing from the outer query).
2099 EvalPlanQualStop(evalPlanQual *epq)
2101 EState *epqstate = epq->estate;
2102 MemoryContext oldcontext;
2104 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2106 ExecEndNode(epq->planstate);
2108 ExecDropTupleTable(epqstate->es_tupleTable, true);
2109 epqstate->es_tupleTable = NULL;
2111 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
2113 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
2114 epqstate->es_evTuple[epq->rti - 1] = NULL;
2117 MemoryContextSwitchTo(oldcontext);
2119 FreeExecutorState(epqstate);
2122 epq->planstate = NULL;