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.219 2003/09/25 18:58:35 tgl 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 useSnapshotNow is true, run the query with SnapshotNow time qual rules
108 * instead of the normal use of QuerySnapshot.
110 * If explainOnly is true, we are not actually intending to run the plan,
111 * only to set up for EXPLAIN; so skip unwanted side-effects.
113 * NB: the CurrentMemoryContext when this is called will become the parent
114 * of the per-query context used for this Executor invocation.
115 * ----------------------------------------------------------------
118 ExecutorStart(QueryDesc *queryDesc, bool useSnapshotNow, bool explainOnly)
121 MemoryContext oldcontext;
123 /* sanity checks: queryDesc must not be started already */
124 Assert(queryDesc != NULL);
125 Assert(queryDesc->estate == NULL);
128 * If the transaction is read-only, we need to check if any writes are
129 * planned to non-temporary tables.
132 ExecCheckXactReadOnly(queryDesc->parsetree, queryDesc->operation);
135 * Build EState, switch into per-query memory context for startup.
137 estate = CreateExecutorState();
138 queryDesc->estate = estate;
140 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
143 * Fill in parameters, if any, from queryDesc
145 estate->es_param_list_info = queryDesc->params;
147 if (queryDesc->plantree->nParamExec > 0)
148 estate->es_param_exec_vals = (ParamExecData *)
149 palloc0(queryDesc->plantree->nParamExec * sizeof(ParamExecData));
151 estate->es_instrument = queryDesc->doInstrument;
154 * Make our own private copy of the current query snapshot data.
156 * This "freezes" our idea of which tuples are good and which are not for
157 * the life of this query, even if it outlives the current command and
162 estate->es_snapshot = SnapshotNow;
163 estate->es_snapshot_cid = GetCurrentCommandId();
167 estate->es_snapshot = CopyQuerySnapshot();
168 estate->es_snapshot_cid = estate->es_snapshot->curcid;
172 * Initialize the plan state tree
174 InitPlan(queryDesc, explainOnly);
176 MemoryContextSwitchTo(oldcontext);
179 /* ----------------------------------------------------------------
182 * This is the main routine of the executor module. It accepts
183 * the query descriptor from the traffic cop and executes the
186 * ExecutorStart must have been called already.
188 * If direction is NoMovementScanDirection then nothing is done
189 * except to start up/shut down the destination. Otherwise,
190 * we retrieve up to 'count' tuples in the specified direction.
192 * Note: count = 0 is interpreted as no portal limit, i.e., run to
195 * ----------------------------------------------------------------
198 ExecutorRun(QueryDesc *queryDesc,
199 ScanDirection direction, long count)
204 TupleTableSlot *result;
205 MemoryContext oldcontext;
208 Assert(queryDesc != NULL);
210 estate = queryDesc->estate;
212 Assert(estate != NULL);
215 * Switch into per-query memory context
217 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
220 * extract information from the query descriptor and the query
223 operation = queryDesc->operation;
224 dest = queryDesc->dest;
227 * startup tuple receiver
229 estate->es_processed = 0;
230 estate->es_lastoid = InvalidOid;
232 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
237 if (direction == NoMovementScanDirection)
240 result = ExecutePlan(estate,
241 queryDesc->planstate,
250 (*dest->rShutdown) (dest);
252 MemoryContextSwitchTo(oldcontext);
257 /* ----------------------------------------------------------------
260 * This routine must be called at the end of execution of any
262 * ----------------------------------------------------------------
265 ExecutorEnd(QueryDesc *queryDesc)
268 MemoryContext oldcontext;
271 Assert(queryDesc != NULL);
273 estate = queryDesc->estate;
275 Assert(estate != NULL);
278 * Switch into per-query memory context to run ExecEndPlan
280 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
282 ExecEndPlan(queryDesc->planstate, estate);
285 * Must switch out of context before destroying it
287 MemoryContextSwitchTo(oldcontext);
290 * Release EState and per-query memory context. This should release
291 * everything the executor has allocated.
293 FreeExecutorState(estate);
295 /* Reset queryDesc fields that no longer point to anything */
296 queryDesc->tupDesc = NULL;
297 queryDesc->estate = NULL;
298 queryDesc->planstate = NULL;
301 /* ----------------------------------------------------------------
304 * This routine may be called on an open queryDesc to rewind it
306 * ----------------------------------------------------------------
309 ExecutorRewind(QueryDesc *queryDesc)
312 MemoryContext oldcontext;
315 Assert(queryDesc != NULL);
317 estate = queryDesc->estate;
319 Assert(estate != NULL);
321 /* It's probably not sensible to rescan updating queries */
322 Assert(queryDesc->operation == CMD_SELECT);
325 * Switch into per-query memory context
327 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
332 ExecReScan(queryDesc->planstate, NULL);
334 MemoryContextSwitchTo(oldcontext);
340 * Check access permissions for all relations listed in a range table.
343 ExecCheckRTPerms(List *rangeTable, CmdType operation)
347 foreach(lp, rangeTable)
349 RangeTblEntry *rte = lfirst(lp);
351 ExecCheckRTEPerms(rte, operation);
357 * Check access permissions for a single RTE.
360 ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation)
364 AclResult aclcheck_result;
367 * If it's a subquery, recursively examine its rangetable.
369 if (rte->rtekind == RTE_SUBQUERY)
371 ExecCheckRTPerms(rte->subquery->rtable, operation);
376 * Otherwise, only plain-relation RTEs need to be checked here.
377 * Function RTEs are checked by init_fcache when the function is
378 * prepared for execution. Join and special RTEs need no checks.
380 if (rte->rtekind != RTE_RELATION)
386 * userid to check as: current user unless we have a setuid
389 * Note: GetUserId() is presently fast enough that there's no harm in
390 * calling it separately for each RTE. If that stops being true, we
391 * could call it once in ExecCheckRTPerms and pass the userid down
392 * from there. But for now, no need for the extra clutter.
394 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
396 #define CHECK(MODE) pg_class_aclcheck(relOid, userid, MODE)
398 if (rte->checkForRead)
400 aclcheck_result = CHECK(ACL_SELECT);
401 if (aclcheck_result != ACLCHECK_OK)
402 aclcheck_error(aclcheck_result, ACL_KIND_CLASS,
403 get_rel_name(relOid));
406 if (rte->checkForWrite)
409 * Note: write access in a SELECT context means SELECT FOR UPDATE.
410 * Right now we don't distinguish that from true update as far as
411 * permissions checks are concerned.
416 aclcheck_result = CHECK(ACL_INSERT);
420 aclcheck_result = CHECK(ACL_UPDATE);
423 aclcheck_result = CHECK(ACL_DELETE);
426 elog(ERROR, "unrecognized operation code: %d",
428 aclcheck_result = ACLCHECK_OK; /* keep compiler quiet */
431 if (aclcheck_result != ACLCHECK_OK)
432 aclcheck_error(aclcheck_result, ACL_KIND_CLASS,
433 get_rel_name(relOid));
438 ExecCheckXactReadOnly(Query *parsetree, CmdType operation)
443 /* CREATE TABLE AS or SELECT INTO */
444 if (operation == CMD_SELECT && parsetree->into != NULL)
447 if (operation == CMD_DELETE || operation == CMD_INSERT
448 || operation == CMD_UPDATE)
452 foreach(lp, parsetree->rtable)
454 RangeTblEntry *rte = lfirst(lp);
456 if (rte->rtekind != RTE_RELATION)
459 if (!rte->checkForWrite)
462 if (isTempNamespace(get_rel_namespace(rte->relid)))
473 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
474 errmsg("transaction is read-only")));
478 /* ----------------------------------------------------------------
481 * Initializes the query plan: open files, allocate storage
482 * and start up the rule manager
483 * ----------------------------------------------------------------
486 InitPlan(QueryDesc *queryDesc, bool explainOnly)
488 CmdType operation = queryDesc->operation;
489 Query *parseTree = queryDesc->parsetree;
490 Plan *plan = queryDesc->plantree;
491 EState *estate = queryDesc->estate;
492 PlanState *planstate;
494 Relation intoRelationDesc;
499 * Do permissions checks. It's sufficient to examine the query's top
500 * rangetable here --- subplan RTEs will be checked during
503 ExecCheckRTPerms(parseTree->rtable, operation);
506 * get information from query descriptor
508 rangeTable = parseTree->rtable;
511 * initialize the node's execution state
513 estate->es_range_table = rangeTable;
516 * if there is a result relation, initialize result relation stuff
518 if (parseTree->resultRelation != 0 && operation != CMD_SELECT)
520 List *resultRelations = parseTree->resultRelations;
521 int numResultRelations;
522 ResultRelInfo *resultRelInfos;
524 if (resultRelations != NIL)
527 * Multiple result relations (due to inheritance)
528 * parseTree->resultRelations identifies them all
530 ResultRelInfo *resultRelInfo;
532 numResultRelations = length(resultRelations);
533 resultRelInfos = (ResultRelInfo *)
534 palloc(numResultRelations * sizeof(ResultRelInfo));
535 resultRelInfo = resultRelInfos;
536 while (resultRelations != NIL)
538 initResultRelInfo(resultRelInfo,
539 lfirsti(resultRelations),
543 resultRelations = lnext(resultRelations);
549 * Single result relation identified by
550 * parseTree->resultRelation
552 numResultRelations = 1;
553 resultRelInfos = (ResultRelInfo *) palloc(sizeof(ResultRelInfo));
554 initResultRelInfo(resultRelInfos,
555 parseTree->resultRelation,
560 estate->es_result_relations = resultRelInfos;
561 estate->es_num_result_relations = numResultRelations;
562 /* Initialize to first or only result rel */
563 estate->es_result_relation_info = resultRelInfos;
568 * if no result relation, then set state appropriately
570 estate->es_result_relations = NULL;
571 estate->es_num_result_relations = 0;
572 estate->es_result_relation_info = NULL;
576 * Detect whether we're doing SELECT INTO. If so, set the force_oids
577 * flag appropriately so that the plan tree will be initialized with
578 * the correct tuple descriptors.
580 do_select_into = false;
582 if (operation == CMD_SELECT && parseTree->into != NULL)
584 do_select_into = true;
587 * For now, always create OIDs in SELECT INTO; this is for
588 * backwards compatibility with pre-7.3 behavior. Eventually we
589 * might want to allow the user to choose.
591 estate->es_force_oids = true;
595 * Have to lock relations selected for update
597 estate->es_rowMark = NIL;
598 if (parseTree->rowMarks != NIL)
602 foreach(l, parseTree->rowMarks)
604 Index rti = lfirsti(l);
605 Oid relid = getrelid(rti, rangeTable);
609 relation = heap_open(relid, RowShareLock);
610 erm = (execRowMark *) palloc(sizeof(execRowMark));
611 erm->relation = relation;
613 snprintf(erm->resname, sizeof(erm->resname), "ctid%u", rti);
614 estate->es_rowMark = lappend(estate->es_rowMark, erm);
619 * initialize the executor "tuple" table. We need slots for all the
620 * plan nodes, plus possibly output slots for the junkfilter(s). At
621 * this point we aren't sure if we need junkfilters, so just add slots
622 * for them unconditionally.
625 int nSlots = ExecCountSlotsNode(plan);
627 if (parseTree->resultRelations != NIL)
628 nSlots += length(parseTree->resultRelations);
631 estate->es_tupleTable = ExecCreateTupleTable(nSlots);
634 /* mark EvalPlanQual not active */
635 estate->es_topPlan = plan;
636 estate->es_evalPlanQual = NULL;
637 estate->es_evTupleNull = NULL;
638 estate->es_evTuple = NULL;
639 estate->es_useEvalPlan = false;
642 * initialize the private state information for all the nodes in the
643 * query tree. This opens files, allocates storage and leaves us
644 * ready to start processing tuples.
646 planstate = ExecInitNode(plan, estate);
649 * Get the tuple descriptor describing the type of tuples to return.
650 * (this is especially important if we are creating a relation with
653 tupType = ExecGetResultType(planstate);
656 * Initialize the junk filter if needed. SELECT and INSERT queries
657 * need a filter if there are any junk attrs in the tlist. INSERT and
658 * SELECT INTO also need a filter if the top plan node is a scan node
659 * that's not doing projection (else we'll be scribbling on the scan
660 * tuple!) UPDATE and DELETE always need a filter, since there's
661 * always a junk 'ctid' attribute present --- no need to look first.
664 bool junk_filter_needed = false;
671 foreach(tlist, plan->targetlist)
673 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
675 if (tle->resdom->resjunk)
677 junk_filter_needed = true;
681 if (!junk_filter_needed &&
682 (operation == CMD_INSERT || do_select_into))
684 if (IsA(planstate, SeqScanState) ||
685 IsA(planstate, IndexScanState) ||
686 IsA(planstate, TidScanState) ||
687 IsA(planstate, SubqueryScanState) ||
688 IsA(planstate, FunctionScanState))
690 if (planstate->ps_ProjInfo == NULL)
691 junk_filter_needed = true;
697 junk_filter_needed = true;
703 if (junk_filter_needed)
706 * If there are multiple result relations, each one needs its
707 * own junk filter. Note this is only possible for
708 * UPDATE/DELETE, so we can't be fooled by some needing a
709 * filter and some not.
711 if (parseTree->resultRelations != NIL)
713 PlanState **appendplans;
715 ResultRelInfo *resultRelInfo;
718 /* Top plan had better be an Append here. */
719 Assert(IsA(plan, Append));
720 Assert(((Append *) plan)->isTarget);
721 Assert(IsA(planstate, AppendState));
722 appendplans = ((AppendState *) planstate)->appendplans;
723 as_nplans = ((AppendState *) planstate)->as_nplans;
724 Assert(as_nplans == estate->es_num_result_relations);
725 resultRelInfo = estate->es_result_relations;
726 for (i = 0; i < as_nplans; i++)
728 PlanState *subplan = appendplans[i];
731 j = ExecInitJunkFilter(subplan->plan->targetlist,
732 ExecGetResultType(subplan),
733 ExecAllocTableSlot(estate->es_tupleTable));
734 resultRelInfo->ri_junkFilter = j;
739 * Set active junkfilter too; at this point ExecInitAppend
740 * has already selected an active result relation...
742 estate->es_junkFilter =
743 estate->es_result_relation_info->ri_junkFilter;
747 /* Normal case with just one JunkFilter */
750 j = ExecInitJunkFilter(planstate->plan->targetlist,
752 ExecAllocTableSlot(estate->es_tupleTable));
753 estate->es_junkFilter = j;
754 if (estate->es_result_relation_info)
755 estate->es_result_relation_info->ri_junkFilter = j;
757 /* For SELECT, want to return the cleaned tuple type */
758 if (operation == CMD_SELECT)
759 tupType = j->jf_cleanTupType;
763 estate->es_junkFilter = NULL;
767 * If doing SELECT INTO, initialize the "into" relation. We must wait
768 * till now so we have the "clean" result tuple type to create the new
771 * If EXPLAIN, skip creating the "into" relation.
773 intoRelationDesc = (Relation) NULL;
775 if (do_select_into && !explainOnly)
784 * find namespace to create in, check permissions
786 intoName = parseTree->into->relname;
787 namespaceId = RangeVarGetCreationNamespace(parseTree->into);
789 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
791 if (aclresult != ACLCHECK_OK)
792 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
793 get_namespace_name(namespaceId));
796 * have to copy tupType to get rid of constraints
798 tupdesc = CreateTupleDescCopy(tupType);
800 intoRelationId = heap_create_with_catalog(intoName,
806 allowSystemTableMods);
808 FreeTupleDesc(tupdesc);
811 * Advance command counter so that the newly-created relation's
812 * catalog tuples will be visible to heap_open.
814 CommandCounterIncrement();
817 * If necessary, create a TOAST table for the into relation. Note
818 * that AlterTableCreateToastTable ends with
819 * CommandCounterIncrement(), so that the TOAST table will be
820 * visible for insertion.
822 AlterTableCreateToastTable(intoRelationId, true);
825 * And open the constructed table for writing.
827 intoRelationDesc = heap_open(intoRelationId, AccessExclusiveLock);
830 estate->es_into_relation_descriptor = intoRelationDesc;
832 queryDesc->tupDesc = tupType;
833 queryDesc->planstate = planstate;
837 * Initialize ResultRelInfo data for one result relation
840 initResultRelInfo(ResultRelInfo *resultRelInfo,
841 Index resultRelationIndex,
845 Oid resultRelationOid;
846 Relation resultRelationDesc;
848 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
849 resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
851 switch (resultRelationDesc->rd_rel->relkind)
853 case RELKIND_SEQUENCE:
855 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
856 errmsg("cannot change sequence \"%s\"",
857 RelationGetRelationName(resultRelationDesc))));
859 case RELKIND_TOASTVALUE:
861 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
862 errmsg("cannot change TOAST relation \"%s\"",
863 RelationGetRelationName(resultRelationDesc))));
867 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
868 errmsg("cannot change view \"%s\"",
869 RelationGetRelationName(resultRelationDesc))));
873 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
874 resultRelInfo->type = T_ResultRelInfo;
875 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
876 resultRelInfo->ri_RelationDesc = resultRelationDesc;
877 resultRelInfo->ri_NumIndices = 0;
878 resultRelInfo->ri_IndexRelationDescs = NULL;
879 resultRelInfo->ri_IndexRelationInfo = NULL;
880 /* make a copy so as not to depend on relcache info not changing... */
881 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
882 resultRelInfo->ri_TrigFunctions = NULL;
883 resultRelInfo->ri_ConstraintExprs = NULL;
884 resultRelInfo->ri_junkFilter = NULL;
887 * If there are indices on the result relation, open them and save
888 * descriptors in the result relation info, so that we can add new
889 * index entries for the tuples we add/update. We need not do this
890 * for a DELETE, however, since deletion doesn't affect indexes.
892 if (resultRelationDesc->rd_rel->relhasindex &&
893 operation != CMD_DELETE)
894 ExecOpenIndices(resultRelInfo);
897 /* ----------------------------------------------------------------
900 * Cleans up the query plan -- closes files and frees up storage
902 * NOTE: we are no longer very worried about freeing storage per se
903 * in this code; FreeExecutorState should be guaranteed to release all
904 * memory that needs to be released. What we are worried about doing
905 * is closing relations and dropping buffer pins. Thus, for example,
906 * tuple tables must be cleared or dropped to ensure pins are released.
907 * ----------------------------------------------------------------
910 ExecEndPlan(PlanState *planstate, EState *estate)
912 ResultRelInfo *resultRelInfo;
917 * shut down any PlanQual processing we were doing
919 if (estate->es_evalPlanQual != NULL)
920 EndEvalPlanQual(estate);
923 * shut down the node-type-specific query processing
925 ExecEndNode(planstate);
928 * destroy the executor "tuple" table.
930 ExecDropTupleTable(estate->es_tupleTable, true);
931 estate->es_tupleTable = NULL;
934 * close the result relation(s) if any, but hold locks until xact
937 resultRelInfo = estate->es_result_relations;
938 for (i = estate->es_num_result_relations; i > 0; i--)
940 /* Close indices and then the relation itself */
941 ExecCloseIndices(resultRelInfo);
942 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
947 * close the "into" relation if necessary, again keeping lock
949 if (estate->es_into_relation_descriptor != NULL)
950 heap_close(estate->es_into_relation_descriptor, NoLock);
953 * close any relations selected FOR UPDATE, again keeping locks
955 foreach(l, estate->es_rowMark)
957 execRowMark *erm = lfirst(l);
959 heap_close(erm->relation, NoLock);
963 /* ----------------------------------------------------------------
966 * processes the query plan to retrieve 'numberTuples' tuples in the
967 * direction specified.
969 * Retrieves all tuples if numberTuples is 0
971 * result is either a slot containing the last tuple in the case
972 * of a SELECT or NULL otherwise.
974 * Note: the ctid attribute is a 'junk' attribute that is removed before the
976 * ----------------------------------------------------------------
978 static TupleTableSlot *
979 ExecutePlan(EState *estate,
980 PlanState *planstate,
983 ScanDirection direction,
986 JunkFilter *junkfilter;
987 TupleTableSlot *slot;
988 ItemPointer tupleid = NULL;
989 ItemPointerData tuple_ctid;
990 long current_tuple_count;
991 TupleTableSlot *result;
994 * initialize local variables
997 current_tuple_count = 0;
1001 * Set the direction.
1003 estate->es_direction = direction;
1006 * Process BEFORE EACH STATEMENT triggers
1011 ExecBSUpdateTriggers(estate, estate->es_result_relation_info);
1014 ExecBSDeleteTriggers(estate, estate->es_result_relation_info);
1017 ExecBSInsertTriggers(estate, estate->es_result_relation_info);
1025 * Loop until we've processed the proper number of tuples from the
1031 /* Reset the per-output-tuple exprcontext */
1032 ResetPerTupleExprContext(estate);
1035 * Execute the plan and obtain a tuple
1038 if (estate->es_useEvalPlan)
1040 slot = EvalPlanQualNext(estate);
1041 if (TupIsNull(slot))
1042 slot = ExecProcNode(planstate);
1045 slot = ExecProcNode(planstate);
1048 * if the tuple is null, then we assume there is nothing more to
1049 * process so we just return null...
1051 if (TupIsNull(slot))
1058 * if we have a junk filter, then project a new tuple with the
1061 * Store this new "clean" tuple in the junkfilter's resultSlot.
1062 * (Formerly, we stored it back over the "dirty" tuple, which is
1063 * WRONG because that tuple slot has the wrong descriptor.)
1065 * Also, extract all the junk information we need.
1067 if ((junkfilter = estate->es_junkFilter) != (JunkFilter *) NULL)
1074 * extract the 'ctid' junk attribute.
1076 if (operation == CMD_UPDATE || operation == CMD_DELETE)
1078 if (!ExecGetJunkAttribute(junkfilter,
1083 elog(ERROR, "could not find junk ctid column");
1085 /* shouldn't ever get a null result... */
1087 elog(ERROR, "ctid is NULL");
1089 tupleid = (ItemPointer) DatumGetPointer(datum);
1090 tuple_ctid = *tupleid; /* make sure we don't free the
1092 tupleid = &tuple_ctid;
1094 else if (estate->es_rowMark != NIL)
1099 foreach(l, estate->es_rowMark)
1101 execRowMark *erm = lfirst(l);
1103 HeapTupleData tuple;
1104 TupleTableSlot *newSlot;
1107 if (!ExecGetJunkAttribute(junkfilter,
1112 elog(ERROR, "could not find junk \"%s\" column",
1115 /* shouldn't ever get a null result... */
1117 elog(ERROR, "\"%s\" is NULL", erm->resname);
1119 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1120 test = heap_mark4update(erm->relation, &tuple, &buffer,
1121 estate->es_snapshot_cid);
1122 ReleaseBuffer(buffer);
1125 case HeapTupleSelfUpdated:
1126 /* treat it as deleted; do not process */
1129 case HeapTupleMayBeUpdated:
1132 case HeapTupleUpdated:
1133 if (XactIsoLevel == XACT_SERIALIZABLE)
1135 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1136 errmsg("could not serialize access due to concurrent update")));
1137 if (!(ItemPointerEquals(&(tuple.t_self),
1138 (ItemPointer) DatumGetPointer(datum))))
1140 newSlot = EvalPlanQual(estate, erm->rti, &(tuple.t_self));
1141 if (!(TupIsNull(newSlot)))
1144 estate->es_useEvalPlan = true;
1150 * if tuple was deleted or PlanQual failed for
1151 * updated tuple - we must not return this
1157 elog(ERROR, "unrecognized heap_mark4update status: %u",
1165 * Finally create a new "clean" tuple with all junk attributes
1168 newTuple = ExecRemoveJunk(junkfilter, slot);
1170 slot = ExecStoreTuple(newTuple, /* tuple to store */
1171 junkfilter->jf_resultSlot, /* dest slot */
1172 InvalidBuffer, /* this tuple has no
1174 true); /* tuple should be pfreed */
1178 * now that we have a tuple, do the appropriate thing with it..
1179 * either return it to the user, add it to a relation someplace,
1180 * delete it from a relation, or modify some of its attributes.
1185 ExecSelect(slot, /* slot containing tuple */
1186 dest, /* destination's tuple-receiver obj */
1192 ExecInsert(slot, tupleid, estate);
1197 ExecDelete(slot, tupleid, estate);
1202 ExecUpdate(slot, tupleid, estate);
1207 elog(ERROR, "unrecognized operation code: %d",
1214 * check our tuple count.. if we've processed the proper number
1215 * then quit, else loop again and process more tuples. Zero
1216 * numberTuples means no limit.
1218 current_tuple_count++;
1219 if (numberTuples && numberTuples == current_tuple_count)
1224 * Process AFTER EACH STATEMENT triggers
1229 ExecASUpdateTriggers(estate, estate->es_result_relation_info);
1232 ExecASDeleteTriggers(estate, estate->es_result_relation_info);
1235 ExecASInsertTriggers(estate, estate->es_result_relation_info);
1243 * here, result is either a slot containing a tuple in the case of a
1244 * SELECT or NULL otherwise.
1249 /* ----------------------------------------------------------------
1252 * SELECTs are easy.. we just pass the tuple to the appropriate
1253 * print function. The only complexity is when we do a
1254 * "SELECT INTO", in which case we insert the tuple into
1255 * the appropriate relation (note: this is a newly created relation
1256 * so we don't need to worry about indices or locks.)
1257 * ----------------------------------------------------------------
1260 ExecSelect(TupleTableSlot *slot,
1268 * get the heap tuple out of the tuple table slot
1271 attrtype = slot->ttc_tupleDescriptor;
1274 * insert the tuple into the "into relation"
1276 * XXX this probably ought to be replaced by a separate destination
1278 if (estate->es_into_relation_descriptor != NULL)
1280 heap_insert(estate->es_into_relation_descriptor, tuple,
1281 estate->es_snapshot_cid);
1286 * send the tuple to the destination
1288 (*dest->receiveTuple) (tuple, attrtype, dest);
1290 (estate->es_processed)++;
1293 /* ----------------------------------------------------------------
1296 * INSERTs are trickier.. we have to insert the tuple into
1297 * the base relation and insert appropriate tuples into the
1299 * ----------------------------------------------------------------
1302 ExecInsert(TupleTableSlot *slot,
1303 ItemPointer tupleid,
1307 ResultRelInfo *resultRelInfo;
1308 Relation resultRelationDesc;
1313 * get the heap tuple out of the tuple table slot
1318 * get information on the (current) result relation
1320 resultRelInfo = estate->es_result_relation_info;
1321 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1323 /* BEFORE ROW INSERT Triggers */
1324 if (resultRelInfo->ri_TrigDesc &&
1325 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1329 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1331 if (newtuple == NULL) /* "do nothing" */
1334 if (newtuple != tuple) /* modified by Trigger(s) */
1337 * Insert modified tuple into tuple table slot, replacing the
1338 * original. We assume that it was allocated in per-tuple
1339 * memory context, and therefore will go away by itself. The
1340 * tuple table slot should not try to clear it.
1342 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1348 * Check the constraints of the tuple
1350 if (resultRelationDesc->rd_att->constr)
1351 ExecConstraints(resultRelInfo, slot, estate);
1356 newId = heap_insert(resultRelationDesc, tuple,
1357 estate->es_snapshot_cid);
1360 (estate->es_processed)++;
1361 estate->es_lastoid = newId;
1362 setLastTid(&(tuple->t_self));
1367 * Note: heap_insert adds a new tuple to a relation. As a side effect,
1368 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1371 numIndices = resultRelInfo->ri_NumIndices;
1373 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1375 /* AFTER ROW INSERT Triggers */
1376 ExecARInsertTriggers(estate, resultRelInfo, tuple);
1379 /* ----------------------------------------------------------------
1382 * DELETE is like UPDATE, we delete the tuple and its
1384 * ----------------------------------------------------------------
1387 ExecDelete(TupleTableSlot *slot,
1388 ItemPointer tupleid,
1391 ResultRelInfo *resultRelInfo;
1392 Relation resultRelationDesc;
1393 ItemPointerData ctid;
1397 * get information on the (current) result relation
1399 resultRelInfo = estate->es_result_relation_info;
1400 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1402 /* BEFORE ROW DELETE Triggers */
1403 if (resultRelInfo->ri_TrigDesc &&
1404 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1408 dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid,
1409 estate->es_snapshot_cid);
1411 if (!dodelete) /* "do nothing" */
1419 result = heap_delete(resultRelationDesc, tupleid,
1421 estate->es_snapshot_cid,
1422 true /* wait for commit */);
1425 case HeapTupleSelfUpdated:
1426 /* already deleted by self; nothing to do */
1429 case HeapTupleMayBeUpdated:
1432 case HeapTupleUpdated:
1433 if (XactIsoLevel == XACT_SERIALIZABLE)
1435 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1436 errmsg("could not serialize access due to concurrent update")));
1437 else if (!(ItemPointerEquals(tupleid, &ctid)))
1439 TupleTableSlot *epqslot = EvalPlanQual(estate,
1440 resultRelInfo->ri_RangeTableIndex, &ctid);
1442 if (!TupIsNull(epqslot))
1448 /* tuple already deleted; nothing to do */
1452 elog(ERROR, "unrecognized heap_delete status: %u", result);
1457 (estate->es_processed)++;
1460 * Note: Normally one would think that we have to delete index tuples
1461 * associated with the heap tuple now..
1463 * ... but in POSTGRES, we have no need to do this because the vacuum
1464 * daemon automatically opens an index scan and deletes index tuples
1465 * when it finds deleted heap tuples. -cim 9/27/89
1468 /* AFTER ROW DELETE Triggers */
1469 ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1472 /* ----------------------------------------------------------------
1475 * note: we can't run UPDATE queries with transactions
1476 * off because UPDATEs are actually INSERTs and our
1477 * scan will mistakenly loop forever, updating the tuple
1478 * it just inserted.. This should be fixed but until it
1479 * is, we don't want to get stuck in an infinite loop
1480 * which corrupts your database..
1481 * ----------------------------------------------------------------
1484 ExecUpdate(TupleTableSlot *slot,
1485 ItemPointer tupleid,
1489 ResultRelInfo *resultRelInfo;
1490 Relation resultRelationDesc;
1491 ItemPointerData ctid;
1496 * abort the operation if not running transactions
1498 if (IsBootstrapProcessingMode())
1499 elog(ERROR, "cannot UPDATE during bootstrap");
1502 * get the heap tuple out of the tuple table slot
1507 * get information on the (current) result relation
1509 resultRelInfo = estate->es_result_relation_info;
1510 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1512 /* BEFORE ROW UPDATE Triggers */
1513 if (resultRelInfo->ri_TrigDesc &&
1514 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1518 newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
1520 estate->es_snapshot_cid);
1522 if (newtuple == NULL) /* "do nothing" */
1525 if (newtuple != tuple) /* modified by Trigger(s) */
1528 * Insert modified tuple into tuple table slot, replacing the
1529 * original. We assume that it was allocated in per-tuple
1530 * memory context, and therefore will go away by itself. The
1531 * tuple table slot should not try to clear it.
1533 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1539 * Check the constraints of the tuple
1541 * If we generate a new candidate tuple after EvalPlanQual testing, we
1542 * must loop back here and recheck constraints. (We don't need to
1543 * redo triggers, however. If there are any BEFORE triggers then
1544 * trigger.c will have done mark4update to lock the correct tuple, so
1545 * there's no need to do them again.)
1548 if (resultRelationDesc->rd_att->constr)
1549 ExecConstraints(resultRelInfo, slot, estate);
1552 * replace the heap tuple
1554 result = heap_update(resultRelationDesc, tupleid, tuple,
1556 estate->es_snapshot_cid,
1557 true /* wait for commit */);
1560 case HeapTupleSelfUpdated:
1561 /* already deleted by self; nothing to do */
1564 case HeapTupleMayBeUpdated:
1567 case HeapTupleUpdated:
1568 if (XactIsoLevel == XACT_SERIALIZABLE)
1570 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1571 errmsg("could not serialize access due to concurrent update")));
1572 else if (!(ItemPointerEquals(tupleid, &ctid)))
1574 TupleTableSlot *epqslot = EvalPlanQual(estate,
1575 resultRelInfo->ri_RangeTableIndex, &ctid);
1577 if (!TupIsNull(epqslot))
1580 tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot);
1581 slot = ExecStoreTuple(tuple,
1582 estate->es_junkFilter->jf_resultSlot,
1583 InvalidBuffer, true);
1587 /* tuple already deleted; nothing to do */
1591 elog(ERROR, "unrecognized heap_update status: %u", result);
1596 (estate->es_processed)++;
1599 * Note: instead of having to update the old index tuples associated
1600 * with the heap tuple, all we do is form and insert new index tuples.
1601 * This is because UPDATEs are actually DELETEs and INSERTs and index
1602 * tuple deletion is done automagically by the vacuum daemon. All we
1603 * do is insert new index tuples. -cim 9/27/89
1609 * heap_update updates a tuple in the base relation by invalidating it
1610 * and then inserting a new tuple to the relation. As a side effect,
1611 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1612 * field. So we now insert index tuples using the new tupleid stored
1616 numIndices = resultRelInfo->ri_NumIndices;
1618 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1620 /* AFTER ROW UPDATE Triggers */
1621 ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
1625 ExecRelCheck(ResultRelInfo *resultRelInfo,
1626 TupleTableSlot *slot, EState *estate)
1628 Relation rel = resultRelInfo->ri_RelationDesc;
1629 int ncheck = rel->rd_att->constr->num_check;
1630 ConstrCheck *check = rel->rd_att->constr->check;
1631 ExprContext *econtext;
1632 MemoryContext oldContext;
1637 * If first time through for this result relation, build expression
1638 * nodetrees for rel's constraint expressions. Keep them in the
1639 * per-query memory context so they'll survive throughout the query.
1641 if (resultRelInfo->ri_ConstraintExprs == NULL)
1643 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1644 resultRelInfo->ri_ConstraintExprs =
1645 (List **) palloc(ncheck * sizeof(List *));
1646 for (i = 0; i < ncheck; i++)
1648 qual = (List *) stringToNode(check[i].ccbin);
1649 resultRelInfo->ri_ConstraintExprs[i] = (List *)
1650 ExecPrepareExpr((Expr *) qual, estate);
1652 MemoryContextSwitchTo(oldContext);
1656 * We will use the EState's per-tuple context for evaluating
1657 * constraint expressions (creating it if it's not already there).
1659 econtext = GetPerTupleExprContext(estate);
1661 /* Arrange for econtext's scan tuple to be the tuple under test */
1662 econtext->ecxt_scantuple = slot;
1664 /* And evaluate the constraints */
1665 for (i = 0; i < ncheck; i++)
1667 qual = resultRelInfo->ri_ConstraintExprs[i];
1670 * NOTE: SQL92 specifies that a NULL result from a constraint
1671 * expression is not to be treated as a failure. Therefore, tell
1672 * ExecQual to return TRUE for NULL.
1674 if (!ExecQual(qual, econtext, true))
1675 return check[i].ccname;
1678 /* NULL result means no error */
1683 ExecConstraints(ResultRelInfo *resultRelInfo,
1684 TupleTableSlot *slot, EState *estate)
1686 Relation rel = resultRelInfo->ri_RelationDesc;
1687 HeapTuple tuple = slot->val;
1688 TupleConstr *constr = rel->rd_att->constr;
1692 if (constr->has_not_null)
1694 int natts = rel->rd_att->natts;
1697 for (attrChk = 1; attrChk <= natts; attrChk++)
1699 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1700 heap_attisnull(tuple, attrChk))
1702 (errcode(ERRCODE_NOT_NULL_VIOLATION),
1703 errmsg("null value in column \"%s\" violates not-null constraint",
1704 NameStr(rel->rd_att->attrs[attrChk - 1]->attname))));
1708 if (constr->num_check > 0)
1712 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1714 (errcode(ERRCODE_CHECK_VIOLATION),
1715 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1716 RelationGetRelationName(rel), failed)));
1721 * Check a modified tuple to see if we want to process its updated version
1722 * under READ COMMITTED rules.
1724 * See backend/executor/README for some info about how this works.
1727 EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
1732 HeapTupleData tuple;
1733 HeapTuple copyTuple = NULL;
1739 * find relation containing target tuple
1741 if (estate->es_result_relation_info != NULL &&
1742 estate->es_result_relation_info->ri_RangeTableIndex == rti)
1743 relation = estate->es_result_relation_info->ri_RelationDesc;
1749 foreach(l, estate->es_rowMark)
1751 if (((execRowMark *) lfirst(l))->rti == rti)
1753 relation = ((execRowMark *) lfirst(l))->relation;
1757 if (relation == NULL)
1758 elog(ERROR, "could not find RowMark for RT index %u", rti);
1764 * Loop here to deal with updated or busy tuples
1766 tuple.t_self = *tid;
1771 if (heap_fetch(relation, SnapshotDirty, &tuple, &buffer, false, NULL))
1773 TransactionId xwait = SnapshotDirty->xmax;
1775 /* xmin should not be dirty... */
1776 if (TransactionIdIsValid(SnapshotDirty->xmin))
1777 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
1780 * If tuple is being updated by other transaction then we have
1781 * to wait for its commit/abort.
1783 if (TransactionIdIsValid(xwait))
1785 ReleaseBuffer(buffer);
1786 XactLockTableWait(xwait);
1791 * We got tuple - now copy it for use by recheck query.
1793 copyTuple = heap_copytuple(&tuple);
1794 ReleaseBuffer(buffer);
1799 * Oops! Invalid tuple. Have to check is it updated or deleted.
1800 * Note that it's possible to get invalid SnapshotDirty->tid if
1801 * tuple updated by this transaction. Have we to check this ?
1803 if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
1804 !(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
1806 /* updated, so look at the updated copy */
1807 tuple.t_self = SnapshotDirty->tid;
1812 * Deleted or updated by this transaction; forget it.
1818 * For UPDATE/DELETE we have to return tid of actual row we're
1821 *tid = tuple.t_self;
1824 * Need to run a recheck subquery. Find or create a PQ stack entry.
1826 epq = estate->es_evalPlanQual;
1829 if (epq != NULL && epq->rti == 0)
1831 /* Top PQ stack entry is idle, so re-use it */
1832 Assert(!(estate->es_useEvalPlan) && epq->next == NULL);
1838 * If this is request for another RTE - Ra, - then we have to check
1839 * wasn't PlanQual requested for Ra already and if so then Ra' row was
1840 * updated again and we have to re-start old execution for Ra and
1841 * forget all what we done after Ra was suspended. Cool? -:))
1843 if (epq != NULL && epq->rti != rti &&
1844 epq->estate->es_evTuple[rti - 1] != NULL)
1848 evalPlanQual *oldepq;
1850 /* stop execution */
1851 EvalPlanQualStop(epq);
1852 /* pop previous PlanQual from the stack */
1854 Assert(oldepq && oldepq->rti != 0);
1855 /* push current PQ to freePQ stack */
1858 estate->es_evalPlanQual = epq;
1859 } while (epq->rti != rti);
1863 * If we are requested for another RTE then we have to suspend
1864 * execution of current PlanQual and start execution for new one.
1866 if (epq == NULL || epq->rti != rti)
1868 /* try to reuse plan used previously */
1869 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
1871 if (newepq == NULL) /* first call or freePQ stack is empty */
1873 newepq = (evalPlanQual *) palloc0(sizeof(evalPlanQual));
1874 newepq->free = NULL;
1875 newepq->estate = NULL;
1876 newepq->planstate = NULL;
1880 /* recycle previously used PlanQual */
1881 Assert(newepq->estate == NULL);
1884 /* push current PQ to the stack */
1887 estate->es_evalPlanQual = epq;
1892 Assert(epq->rti == rti);
1895 * Ok - we're requested for the same RTE. Unfortunately we still have
1896 * to end and restart execution of the plan, because ExecReScan
1897 * wouldn't ensure that upper plan nodes would reset themselves. We
1898 * could make that work if insertion of the target tuple were
1899 * integrated with the Param mechanism somehow, so that the upper plan
1900 * nodes know that their children's outputs have changed.
1902 * Note that the stack of free evalPlanQual nodes is quite useless at the
1903 * moment, since it only saves us from pallocing/releasing the
1904 * evalPlanQual nodes themselves. But it will be useful once we
1905 * implement ReScan instead of end/restart for re-using PlanQual
1910 /* stop execution */
1911 EvalPlanQualStop(epq);
1915 * Initialize new recheck query.
1917 * Note: if we were re-using PlanQual plans via ExecReScan, we'd need to
1918 * instead copy down changeable state from the top plan (including
1919 * es_result_relation_info, es_junkFilter) and reset locally
1920 * changeable state in the epq (including es_param_exec_vals,
1923 EvalPlanQualStart(epq, estate, epq->next);
1926 * free old RTE' tuple, if any, and store target tuple where
1927 * relation's scan node will see it
1929 epqstate = epq->estate;
1930 if (epqstate->es_evTuple[rti - 1] != NULL)
1931 heap_freetuple(epqstate->es_evTuple[rti - 1]);
1932 epqstate->es_evTuple[rti - 1] = copyTuple;
1934 return EvalPlanQualNext(estate);
1937 static TupleTableSlot *
1938 EvalPlanQualNext(EState *estate)
1940 evalPlanQual *epq = estate->es_evalPlanQual;
1941 MemoryContext oldcontext;
1942 TupleTableSlot *slot;
1944 Assert(epq->rti != 0);
1947 oldcontext = MemoryContextSwitchTo(epq->estate->es_query_cxt);
1948 slot = ExecProcNode(epq->planstate);
1949 MemoryContextSwitchTo(oldcontext);
1952 * No more tuples for this PQ. Continue previous one.
1954 if (TupIsNull(slot))
1956 evalPlanQual *oldepq;
1958 /* stop execution */
1959 EvalPlanQualStop(epq);
1960 /* pop old PQ from the stack */
1964 /* this is the first (oldest) PQ - mark as free */
1966 estate->es_useEvalPlan = false;
1967 /* and continue Query execution */
1970 Assert(oldepq->rti != 0);
1971 /* push current PQ to freePQ stack */
1974 estate->es_evalPlanQual = epq;
1982 EndEvalPlanQual(EState *estate)
1984 evalPlanQual *epq = estate->es_evalPlanQual;
1986 if (epq->rti == 0) /* plans already shutdowned */
1988 Assert(epq->next == NULL);
1994 evalPlanQual *oldepq;
1996 /* stop execution */
1997 EvalPlanQualStop(epq);
1998 /* pop old PQ from the stack */
2002 /* this is the first (oldest) PQ - mark as free */
2004 estate->es_useEvalPlan = false;
2007 Assert(oldepq->rti != 0);
2008 /* push current PQ to freePQ stack */
2011 estate->es_evalPlanQual = epq;
2016 * Start execution of one level of PlanQual.
2018 * This is a cut-down version of ExecutorStart(): we copy some state from
2019 * the top-level estate rather than initializing it fresh.
2022 EvalPlanQualStart(evalPlanQual *epq, EState *estate, evalPlanQual *priorepq)
2026 MemoryContext oldcontext;
2028 rtsize = length(estate->es_range_table);
2030 epq->estate = epqstate = CreateExecutorState();
2032 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2035 * The epqstates share the top query's copy of unchanging state such
2036 * as the snapshot, rangetable, result-rel info, and external Param
2037 * info. They need their own copies of local state, including a tuple
2038 * table, es_param_exec_vals, etc.
2040 epqstate->es_direction = ForwardScanDirection;
2041 epqstate->es_snapshot = estate->es_snapshot;
2042 epqstate->es_snapshot_cid = estate->es_snapshot_cid;
2043 epqstate->es_range_table = estate->es_range_table;
2044 epqstate->es_result_relations = estate->es_result_relations;
2045 epqstate->es_num_result_relations = estate->es_num_result_relations;
2046 epqstate->es_result_relation_info = estate->es_result_relation_info;
2047 epqstate->es_junkFilter = estate->es_junkFilter;
2048 epqstate->es_into_relation_descriptor = estate->es_into_relation_descriptor;
2049 epqstate->es_param_list_info = estate->es_param_list_info;
2050 if (estate->es_topPlan->nParamExec > 0)
2051 epqstate->es_param_exec_vals = (ParamExecData *)
2052 palloc0(estate->es_topPlan->nParamExec * sizeof(ParamExecData));
2053 epqstate->es_rowMark = estate->es_rowMark;
2054 epqstate->es_instrument = estate->es_instrument;
2055 epqstate->es_force_oids = estate->es_force_oids;
2056 epqstate->es_topPlan = estate->es_topPlan;
2059 * Each epqstate must have its own es_evTupleNull state, but all the
2060 * stack entries share es_evTuple state. This allows sub-rechecks to
2061 * inherit the value being examined by an outer recheck.
2063 epqstate->es_evTupleNull = (bool *) palloc0(rtsize * sizeof(bool));
2064 if (priorepq == NULL)
2065 /* first PQ stack entry */
2066 epqstate->es_evTuple = (HeapTuple *)
2067 palloc0(rtsize * sizeof(HeapTuple));
2069 /* later stack entries share the same storage */
2070 epqstate->es_evTuple = priorepq->estate->es_evTuple;
2072 epqstate->es_tupleTable =
2073 ExecCreateTupleTable(estate->es_tupleTable->size);
2075 epq->planstate = ExecInitNode(estate->es_topPlan, epqstate);
2077 MemoryContextSwitchTo(oldcontext);
2081 * End execution of one level of PlanQual.
2083 * This is a cut-down version of ExecutorEnd(); basically we want to do most
2084 * of the normal cleanup, but *not* close result relations (which we are
2085 * just sharing from the outer query).
2088 EvalPlanQualStop(evalPlanQual *epq)
2090 EState *epqstate = epq->estate;
2091 MemoryContext oldcontext;
2093 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2095 ExecEndNode(epq->planstate);
2097 ExecDropTupleTable(epqstate->es_tupleTable, true);
2098 epqstate->es_tupleTable = NULL;
2100 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
2102 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
2103 epqstate->es_evTuple[epq->rti - 1] = NULL;
2106 MemoryContextSwitchTo(oldcontext);
2108 FreeExecutorState(epqstate);
2111 epq->planstate = NULL;