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 and the execution state is required
18 * ExecutorStart() must be called at the beginning of any execution of any
19 * query plan and ExecutorEnd() should always be called at the end of
20 * execution of a plan.
22 * ExecutorRun accepts direction and count arguments that specify whether
23 * the plan is to be executed forwards, backwards, and for how many tuples.
25 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
26 * Portions Copyright (c) 1994, Regents of the University of California
30 * $Header: /cvsroot/pgsql/src/backend/executor/execMain.c,v 1.151 2002/03/02 21:39:25 momjian Exp $
32 *-------------------------------------------------------------------------
36 #include "access/heapam.h"
37 #include "catalog/heap.h"
38 #include "commands/command.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"
48 /* decls for local routines only used within this module */
49 static TupleDesc InitPlan(CmdType operation,
53 static void initResultRelInfo(ResultRelInfo *resultRelInfo,
54 Index resultRelationIndex,
57 static void EndPlan(Plan *plan, EState *estate);
58 static TupleTableSlot *ExecutePlan(EState *estate, Plan *plan,
61 ScanDirection direction,
62 DestReceiver *destfunc);
63 static void ExecRetrieve(TupleTableSlot *slot,
64 DestReceiver *destfunc,
66 static void ExecAppend(TupleTableSlot *slot, ItemPointer tupleid,
68 static void ExecDelete(TupleTableSlot *slot, ItemPointer tupleid,
70 static void ExecReplace(TupleTableSlot *slot, ItemPointer tupleid,
72 static TupleTableSlot *EvalPlanQualNext(EState *estate);
73 static void EndEvalPlanQual(EState *estate);
74 static void ExecCheckQueryPerms(CmdType operation, Query *parseTree,
76 static void ExecCheckPlanPerms(Plan *plan, List *rangeTable,
78 static void ExecCheckRTPerms(List *rangeTable, CmdType operation);
79 static void ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation);
81 /* end of local decls */
84 /* ----------------------------------------------------------------
87 * This routine must be called at the beginning of any execution of any
90 * returns a TupleDesc which describes the attributes of the tuples to
91 * be returned by the query. (Same value is saved in queryDesc)
93 * NB: the CurrentMemoryContext when this is called must be the context
94 * to be used as the per-query context for the query plan. ExecutorRun()
95 * and ExecutorEnd() must be called in this same memory context.
96 * ----------------------------------------------------------------
99 ExecutorStart(QueryDesc *queryDesc, EState *estate)
104 Assert(queryDesc != NULL);
106 if (queryDesc->plantree->nParamExec > 0)
108 estate->es_param_exec_vals = (ParamExecData *)
109 palloc(queryDesc->plantree->nParamExec * sizeof(ParamExecData));
110 MemSet(estate->es_param_exec_vals, 0,
111 queryDesc->plantree->nParamExec * sizeof(ParamExecData));
115 * Make our own private copy of the current queries snapshot data
117 if (QuerySnapshot == NULL)
118 estate->es_snapshot = NULL;
121 estate->es_snapshot = (Snapshot) palloc(sizeof(SnapshotData));
122 memcpy(estate->es_snapshot, QuerySnapshot, sizeof(SnapshotData));
123 if (estate->es_snapshot->xcnt > 0)
125 estate->es_snapshot->xip = (TransactionId *)
126 palloc(estate->es_snapshot->xcnt * sizeof(TransactionId));
127 memcpy(estate->es_snapshot->xip, QuerySnapshot->xip,
128 estate->es_snapshot->xcnt * sizeof(TransactionId));
133 * Initialize the plan
135 result = InitPlan(queryDesc->operation,
136 queryDesc->parsetree,
140 queryDesc->tupDesc = result;
145 /* ----------------------------------------------------------------
148 * This is the main routine of the executor module. It accepts
149 * the query descriptor from the traffic cop and executes the
152 * ExecutorStart must have been called already.
154 * If direction is NoMovementScanDirection then nothing is done
155 * except to start up/shut down the destination. Otherwise,
156 * we retrieve up to 'count' tuples in the specified direction.
158 * Note: count = 0 is interpreted as "no limit".
160 * ----------------------------------------------------------------
163 ExecutorRun(QueryDesc *queryDesc, EState *estate,
164 ScanDirection direction, long count)
169 DestReceiver *destfunc;
170 TupleTableSlot *result;
175 Assert(queryDesc != NULL);
178 * extract information from the query descriptor and the query
181 operation = queryDesc->operation;
182 plan = queryDesc->plantree;
183 dest = queryDesc->dest;
186 * startup tuple receiver
188 estate->es_processed = 0;
189 estate->es_lastoid = InvalidOid;
191 destfunc = DestToFunction(dest);
192 (*destfunc->setup) (destfunc, (int) operation,
193 queryDesc->portalName, queryDesc->tupDesc);
198 if (direction == NoMovementScanDirection)
201 result = ExecutePlan(estate,
211 (*destfunc->cleanup) (destfunc);
216 /* ----------------------------------------------------------------
219 * This routine must be called at the end of execution of any
221 * ----------------------------------------------------------------
224 ExecutorEnd(QueryDesc *queryDesc, EState *estate)
227 Assert(queryDesc != NULL);
229 EndPlan(queryDesc->plantree, estate);
231 if (estate->es_snapshot != NULL)
233 if (estate->es_snapshot->xcnt > 0)
234 pfree(estate->es_snapshot->xip);
235 pfree(estate->es_snapshot);
236 estate->es_snapshot = NULL;
239 if (estate->es_param_exec_vals != NULL)
241 pfree(estate->es_param_exec_vals);
242 estate->es_param_exec_vals = NULL;
248 * ExecCheckQueryPerms
249 * Check access permissions for all relations referenced in a query.
252 ExecCheckQueryPerms(CmdType operation, Query *parseTree, Plan *plan)
255 * Check RTEs in the query's primary rangetable.
257 ExecCheckRTPerms(parseTree->rtable, operation);
260 * Search for subplans and APPEND nodes to check their rangetables.
262 ExecCheckPlanPerms(plan, parseTree->rtable, operation);
267 * Recursively scan the plan tree to check access permissions in
271 ExecCheckPlanPerms(Plan *plan, List *rangeTable, CmdType operation)
278 /* Check subplans, which we assume are plain SELECT queries */
280 foreach(subp, plan->initPlan)
282 SubPlan *subplan = (SubPlan *) lfirst(subp);
284 ExecCheckRTPerms(subplan->rtable, CMD_SELECT);
285 ExecCheckPlanPerms(subplan->plan, subplan->rtable, CMD_SELECT);
287 foreach(subp, plan->subPlan)
289 SubPlan *subplan = (SubPlan *) lfirst(subp);
291 ExecCheckRTPerms(subplan->rtable, CMD_SELECT);
292 ExecCheckPlanPerms(subplan->plan, subplan->rtable, CMD_SELECT);
295 /* Check lower plan nodes */
297 ExecCheckPlanPerms(plan->lefttree, rangeTable, operation);
298 ExecCheckPlanPerms(plan->righttree, rangeTable, operation);
300 /* Do node-type-specific checks */
302 switch (nodeTag(plan))
306 SubqueryScan *scan = (SubqueryScan *) plan;
309 /* Recursively check the subquery */
310 rte = rt_fetch(scan->scan.scanrelid, rangeTable);
311 Assert(rte->subquery != NULL);
312 ExecCheckQueryPerms(operation, rte->subquery, scan->subplan);
317 Append *app = (Append *) plan;
320 foreach(appendplans, app->appendplans)
322 ExecCheckPlanPerms((Plan *) lfirst(appendplans),
336 * Check access permissions for all relations listed in a range table.
339 ExecCheckRTPerms(List *rangeTable, CmdType operation)
343 foreach(lp, rangeTable)
345 RangeTblEntry *rte = lfirst(lp);
347 ExecCheckRTEPerms(rte, operation);
353 * Check access permissions for a single RTE.
356 ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation)
360 int32 aclcheck_result;
363 * If it's a subquery RTE, ignore it --- it will be checked when
364 * ExecCheckPlanPerms finds the SubqueryScan node for it.
369 relName = rte->relname;
372 * userid to check as: current user unless we have a setuid
375 * Note: GetUserId() is presently fast enough that there's no harm in
376 * calling it separately for each RTE. If that stops being true, we
377 * could call it once in ExecCheckQueryPerms and pass the userid down
378 * from there. But for now, no need for the extra clutter.
380 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
382 #define CHECK(MODE) pg_aclcheck(relName, userid, MODE)
384 if (rte->checkForRead)
386 aclcheck_result = CHECK(ACL_SELECT);
387 if (aclcheck_result != ACLCHECK_OK)
388 elog(ERROR, "%s: %s",
389 relName, aclcheck_error_strings[aclcheck_result]);
392 if (rte->checkForWrite)
395 * Note: write access in a SELECT context means SELECT FOR UPDATE.
396 * Right now we don't distinguish that from true update as far as
397 * permissions checks are concerned.
402 aclcheck_result = CHECK(ACL_INSERT);
406 aclcheck_result = CHECK(ACL_UPDATE);
409 aclcheck_result = CHECK(ACL_DELETE);
412 elog(ERROR, "ExecCheckRTEPerms: bogus operation %d",
414 aclcheck_result = ACLCHECK_OK; /* keep compiler quiet */
417 if (aclcheck_result != ACLCHECK_OK)
418 elog(ERROR, "%s: %s",
419 relName, aclcheck_error_strings[aclcheck_result]);
424 /* ===============================================================
425 * ===============================================================
426 static routines follow
427 * ===============================================================
428 * ===============================================================
431 typedef struct execRowMark
438 typedef struct evalPlanQual
443 struct evalPlanQual *free;
446 /* ----------------------------------------------------------------
449 * Initializes the query plan: open files, allocate storage
450 * and start up the rule manager
451 * ----------------------------------------------------------------
454 InitPlan(CmdType operation, Query *parseTree, Plan *plan, EState *estate)
457 Relation intoRelationDesc;
461 * Do permissions checks.
463 ExecCheckQueryPerms(operation, parseTree, plan);
466 * get information from query descriptor
468 rangeTable = parseTree->rtable;
471 * initialize the node's execution state
473 estate->es_range_table = rangeTable;
476 * if there is a result relation, initialize result relation stuff
478 if (parseTree->resultRelation != 0 && operation != CMD_SELECT)
480 List *resultRelations = parseTree->resultRelations;
481 int numResultRelations;
482 ResultRelInfo *resultRelInfos;
484 if (resultRelations != NIL)
487 * Multiple result relations (due to inheritance)
488 * parseTree->resultRelations identifies them all
490 ResultRelInfo *resultRelInfo;
492 numResultRelations = length(resultRelations);
493 resultRelInfos = (ResultRelInfo *)
494 palloc(numResultRelations * sizeof(ResultRelInfo));
495 resultRelInfo = resultRelInfos;
496 while (resultRelations != NIL)
498 initResultRelInfo(resultRelInfo,
499 lfirsti(resultRelations),
503 resultRelations = lnext(resultRelations);
509 * Single result relation identified by
510 * parseTree->resultRelation
512 numResultRelations = 1;
513 resultRelInfos = (ResultRelInfo *) palloc(sizeof(ResultRelInfo));
514 initResultRelInfo(resultRelInfos,
515 parseTree->resultRelation,
520 estate->es_result_relations = resultRelInfos;
521 estate->es_num_result_relations = numResultRelations;
522 /* Initialize to first or only result rel */
523 estate->es_result_relation_info = resultRelInfos;
528 * if no result relation, then set state appropriately
530 estate->es_result_relations = NULL;
531 estate->es_num_result_relations = 0;
532 estate->es_result_relation_info = NULL;
536 * Have to lock relations selected for update
538 estate->es_rowMark = NIL;
539 if (parseTree->rowMarks != NIL)
543 foreach(l, parseTree->rowMarks)
545 Index rti = lfirsti(l);
546 Oid relid = getrelid(rti, rangeTable);
550 relation = heap_open(relid, RowShareLock);
551 erm = (execRowMark *) palloc(sizeof(execRowMark));
552 erm->relation = relation;
554 sprintf(erm->resname, "ctid%u", rti);
555 estate->es_rowMark = lappend(estate->es_rowMark, erm);
560 * initialize the executor "tuple" table. We need slots for all the
561 * plan nodes, plus possibly output slots for the junkfilter(s). At
562 * this point we aren't sure if we need junkfilters, so just add slots
563 * for them unconditionally.
566 int nSlots = ExecCountSlotsNode(plan);
568 if (parseTree->resultRelations != NIL)
569 nSlots += length(parseTree->resultRelations);
572 estate->es_tupleTable = ExecCreateTupleTable(nSlots);
575 /* mark EvalPlanQual not active */
576 estate->es_origPlan = plan;
577 estate->es_evalPlanQual = NULL;
578 estate->es_evTuple = NULL;
579 estate->es_evTupleNull = NULL;
580 estate->es_useEvalPlan = false;
583 * initialize the private state information for all the nodes in the
584 * query tree. This opens files, allocates storage and leaves us
585 * ready to start processing tuples.
587 ExecInitNode(plan, estate, NULL);
590 * Get the tuple descriptor describing the type of tuples to return.
591 * (this is especially important if we are creating a relation with
594 tupType = ExecGetTupType(plan); /* tuple descriptor */
597 * Initialize the junk filter if needed. SELECT and INSERT queries
598 * need a filter if there are any junk attrs in the tlist. UPDATE and
599 * DELETE always need one, since there's always a junk 'ctid'
600 * attribute present --- no need to look first.
603 bool junk_filter_needed = false;
610 foreach(tlist, plan->targetlist)
612 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
614 if (tle->resdom->resjunk)
616 junk_filter_needed = true;
623 junk_filter_needed = true;
629 if (junk_filter_needed)
632 * If there are multiple result relations, each one needs its
633 * own junk filter. Note this is only possible for
634 * UPDATE/DELETE, so we can't be fooled by some needing a
635 * filter and some not.
637 if (parseTree->resultRelations != NIL)
640 ResultRelInfo *resultRelInfo;
642 /* Top plan had better be an Append here. */
643 Assert(IsA(plan, Append));
644 Assert(((Append *) plan)->isTarget);
645 subplans = ((Append *) plan)->appendplans;
646 Assert(length(subplans) == estate->es_num_result_relations);
647 resultRelInfo = estate->es_result_relations;
648 while (subplans != NIL)
650 Plan *subplan = (Plan *) lfirst(subplans);
653 j = ExecInitJunkFilter(subplan->targetlist,
654 ExecGetTupType(subplan),
655 ExecAllocTableSlot(estate->es_tupleTable));
656 resultRelInfo->ri_junkFilter = j;
658 subplans = lnext(subplans);
662 * Set active junkfilter too; at this point ExecInitAppend
663 * has already selected an active result relation...
665 estate->es_junkFilter =
666 estate->es_result_relation_info->ri_junkFilter;
670 /* Normal case with just one JunkFilter */
673 j = ExecInitJunkFilter(plan->targetlist,
675 ExecAllocTableSlot(estate->es_tupleTable));
676 estate->es_junkFilter = j;
677 if (estate->es_result_relation_info)
678 estate->es_result_relation_info->ri_junkFilter = j;
680 /* For SELECT, want to return the cleaned tuple type */
681 if (operation == CMD_SELECT)
682 tupType = j->jf_cleanTupType;
686 estate->es_junkFilter = NULL;
690 * initialize the "into" relation
692 intoRelationDesc = (Relation) NULL;
694 if (operation == CMD_SELECT)
700 if (!parseTree->isPortal)
703 * a select into table
705 if (parseTree->into != NULL)
708 * create the "into" relation
710 intoName = parseTree->into;
713 * have to copy tupType to get rid of constraints
715 tupdesc = CreateTupleDescCopy(tupType);
718 heap_create_with_catalog(intoName,
720 RELKIND_RELATION, true,
722 allowSystemTableMods);
724 FreeTupleDesc(tupdesc);
727 * Advance command counter so that the newly-created
728 * relation's catalog tuples will be visible to heap_open.
730 CommandCounterIncrement();
733 * If necessary, create a TOAST table for the into
734 * relation. Note that AlterTableCreateToastTable ends
735 * with CommandCounterIncrement(), so that the TOAST table
736 * will be visible for insertion.
738 AlterTableCreateToastTable(intoName, true);
740 intoRelationDesc = heap_open(intoRelationId,
741 AccessExclusiveLock);
746 estate->es_into_relation_descriptor = intoRelationDesc;
752 * Initialize ResultRelInfo data for one result relation
755 initResultRelInfo(ResultRelInfo *resultRelInfo,
756 Index resultRelationIndex,
760 Oid resultRelationOid;
761 Relation resultRelationDesc;
763 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
764 resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
766 switch (resultRelationDesc->rd_rel->relkind)
768 case RELKIND_SEQUENCE:
769 elog(ERROR, "You can't change sequence relation %s",
770 RelationGetRelationName(resultRelationDesc));
772 case RELKIND_TOASTVALUE:
773 elog(ERROR, "You can't change toast relation %s",
774 RelationGetRelationName(resultRelationDesc));
777 elog(ERROR, "You can't change view relation %s",
778 RelationGetRelationName(resultRelationDesc));
782 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
783 resultRelInfo->type = T_ResultRelInfo;
784 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
785 resultRelInfo->ri_RelationDesc = resultRelationDesc;
786 resultRelInfo->ri_NumIndices = 0;
787 resultRelInfo->ri_IndexRelationDescs = NULL;
788 resultRelInfo->ri_IndexRelationInfo = NULL;
789 resultRelInfo->ri_TrigDesc = resultRelationDesc->trigdesc;
790 resultRelInfo->ri_TrigFunctions = NULL;
791 resultRelInfo->ri_ConstraintExprs = NULL;
792 resultRelInfo->ri_junkFilter = NULL;
795 * If there are indices on the result relation, open them and save
796 * descriptors in the result relation info, so that we can add new
797 * index entries for the tuples we add/update. We need not do this
798 * for a DELETE, however, since deletion doesn't affect indexes.
800 if (resultRelationDesc->rd_rel->relhasindex &&
801 operation != CMD_DELETE)
802 ExecOpenIndices(resultRelInfo);
805 /* ----------------------------------------------------------------
808 * Cleans up the query plan -- closes files and free up storages
809 * ----------------------------------------------------------------
812 EndPlan(Plan *plan, EState *estate)
814 ResultRelInfo *resultRelInfo;
819 * shut down any PlanQual processing we were doing
821 if (estate->es_evalPlanQual != NULL)
822 EndEvalPlanQual(estate);
825 * shut down the node-type-specific query processing
827 ExecEndNode(plan, NULL);
830 * destroy the executor "tuple" table.
832 ExecDropTupleTable(estate->es_tupleTable, true);
833 estate->es_tupleTable = NULL;
836 * close the result relation(s) if any, but hold locks until xact
837 * commit. Also clean up junkfilters if present.
839 resultRelInfo = estate->es_result_relations;
840 for (i = estate->es_num_result_relations; i > 0; i--)
842 /* Close indices and then the relation itself */
843 ExecCloseIndices(resultRelInfo);
844 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
845 /* Delete the junkfilter if any */
846 if (resultRelInfo->ri_junkFilter != NULL)
847 ExecFreeJunkFilter(resultRelInfo->ri_junkFilter);
852 * close the "into" relation if necessary, again keeping lock
854 if (estate->es_into_relation_descriptor != NULL)
855 heap_close(estate->es_into_relation_descriptor, NoLock);
858 * There might be a junkfilter without a result relation.
860 if (estate->es_num_result_relations == 0 &&
861 estate->es_junkFilter != NULL)
863 ExecFreeJunkFilter(estate->es_junkFilter);
864 estate->es_junkFilter = NULL;
868 * close any relations selected FOR UPDATE, again keeping locks
870 foreach(l, estate->es_rowMark)
872 execRowMark *erm = lfirst(l);
874 heap_close(erm->relation, NoLock);
878 /* ----------------------------------------------------------------
881 * processes the query plan to retrieve 'numberTuples' tuples in the
882 * direction specified.
883 * Retrieves all tuples if numberTuples is 0
885 * result is either a slot containing the last tuple in the case
886 * of a RETRIEVE or NULL otherwise.
888 * Note: the ctid attribute is a 'junk' attribute that is removed before the
890 * ----------------------------------------------------------------
892 static TupleTableSlot *
893 ExecutePlan(EState *estate,
897 ScanDirection direction,
898 DestReceiver *destfunc)
900 JunkFilter *junkfilter;
901 TupleTableSlot *slot;
902 ItemPointer tupleid = NULL;
903 ItemPointerData tuple_ctid;
904 long current_tuple_count;
905 TupleTableSlot *result;
908 * initialize local variables
911 current_tuple_count = 0;
917 estate->es_direction = direction;
920 * Loop until we've processed the proper number of tuples from the
926 /* Reset the per-output-tuple exprcontext */
927 ResetPerTupleExprContext(estate);
930 * Execute the plan and obtain a tuple
933 if (estate->es_useEvalPlan)
935 slot = EvalPlanQualNext(estate);
937 slot = ExecProcNode(plan, NULL);
940 slot = ExecProcNode(plan, NULL);
943 * if the tuple is null, then we assume there is nothing more to
944 * process so we just return null...
953 * if we have a junk filter, then project a new tuple with the
956 * Store this new "clean" tuple in the junkfilter's resultSlot.
957 * (Formerly, we stored it back over the "dirty" tuple, which is
958 * WRONG because that tuple slot has the wrong descriptor.)
960 * Also, extract all the junk information we need.
962 if ((junkfilter = estate->es_junkFilter) != (JunkFilter *) NULL)
969 * extract the 'ctid' junk attribute.
971 if (operation == CMD_UPDATE || operation == CMD_DELETE)
973 if (!ExecGetJunkAttribute(junkfilter,
978 elog(ERROR, "ExecutePlan: NO (junk) `ctid' was found!");
980 /* shouldn't ever get a null result... */
982 elog(ERROR, "ExecutePlan: (junk) `ctid' is NULL!");
984 tupleid = (ItemPointer) DatumGetPointer(datum);
985 tuple_ctid = *tupleid; /* make sure we don't free the
987 tupleid = &tuple_ctid;
989 else if (estate->es_rowMark != NIL)
994 foreach(l, estate->es_rowMark)
996 execRowMark *erm = lfirst(l);
999 TupleTableSlot *newSlot;
1002 if (!ExecGetJunkAttribute(junkfilter,
1007 elog(ERROR, "ExecutePlan: NO (junk) `%s' was found!",
1010 /* shouldn't ever get a null result... */
1012 elog(ERROR, "ExecutePlan: (junk) `%s' is NULL!",
1015 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1016 test = heap_mark4update(erm->relation, &tuple, &buffer);
1017 ReleaseBuffer(buffer);
1020 case HeapTupleSelfUpdated:
1021 case HeapTupleMayBeUpdated:
1024 case HeapTupleUpdated:
1025 if (XactIsoLevel == XACT_SERIALIZABLE)
1026 elog(ERROR, "Can't serialize access due to concurrent update");
1027 if (!(ItemPointerEquals(&(tuple.t_self),
1028 (ItemPointer) DatumGetPointer(datum))))
1030 newSlot = EvalPlanQual(estate, erm->rti, &(tuple.t_self));
1031 if (!(TupIsNull(newSlot)))
1034 estate->es_useEvalPlan = true;
1040 * if tuple was deleted or PlanQual failed for
1041 * updated tuple - we must not return this
1047 elog(ERROR, "Unknown status %u from heap_mark4update", test);
1054 * Finally create a new "clean" tuple with all junk attributes
1057 newTuple = ExecRemoveJunk(junkfilter, slot);
1059 slot = ExecStoreTuple(newTuple, /* tuple to store */
1060 junkfilter->jf_resultSlot, /* dest slot */
1061 InvalidBuffer, /* this tuple has no
1063 true); /* tuple should be pfreed */
1064 } /* if (junkfilter... */
1067 * now that we have a tuple, do the appropriate thing with it..
1068 * either return it to the user, add it to a relation someplace,
1069 * delete it from a relation, or modify some of its attributes.
1075 ExecRetrieve(slot, /* slot containing tuple */
1076 destfunc, /* destination's tuple-receiver
1083 ExecAppend(slot, tupleid, estate);
1088 ExecDelete(slot, tupleid, estate);
1093 ExecReplace(slot, tupleid, estate);
1098 elog(LOG, "ExecutePlan: unknown operation in queryDesc");
1104 * check our tuple count.. if we've processed the proper number
1105 * then quit, else loop again and process more tuples..
1107 current_tuple_count++;
1108 if (numberTuples == current_tuple_count)
1113 * here, result is either a slot containing a tuple in the case of a
1114 * RETRIEVE or NULL otherwise.
1119 /* ----------------------------------------------------------------
1122 * RETRIEVEs are easy.. we just pass the tuple to the appropriate
1123 * print function. The only complexity is when we do a
1124 * "retrieve into", in which case we insert the tuple into
1125 * the appropriate relation (note: this is a newly created relation
1126 * so we don't need to worry about indices or locks.)
1127 * ----------------------------------------------------------------
1130 ExecRetrieve(TupleTableSlot *slot,
1131 DestReceiver *destfunc,
1138 * get the heap tuple out of the tuple table slot
1141 attrtype = slot->ttc_tupleDescriptor;
1144 * insert the tuple into the "into relation"
1146 if (estate->es_into_relation_descriptor != NULL)
1148 heap_insert(estate->es_into_relation_descriptor, tuple);
1153 * send the tuple to the front end (or the screen)
1155 (*destfunc->receiveTuple) (tuple, attrtype, destfunc);
1157 (estate->es_processed)++;
1160 /* ----------------------------------------------------------------
1163 * APPENDs are trickier.. we have to insert the tuple into
1164 * the base relation and insert appropriate tuples into the
1166 * ----------------------------------------------------------------
1170 ExecAppend(TupleTableSlot *slot,
1171 ItemPointer tupleid,
1175 ResultRelInfo *resultRelInfo;
1176 Relation resultRelationDesc;
1181 * get the heap tuple out of the tuple table slot
1186 * get information on the (current) result relation
1188 resultRelInfo = estate->es_result_relation_info;
1189 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1191 /* BEFORE ROW INSERT Triggers */
1192 if (resultRelInfo->ri_TrigDesc &&
1193 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1197 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1199 if (newtuple == NULL) /* "do nothing" */
1202 if (newtuple != tuple) /* modified by Trigger(s) */
1205 * Insert modified tuple into tuple table slot, replacing the
1206 * original. We assume that it was allocated in per-tuple
1207 * memory context, and therefore will go away by itself. The
1208 * tuple table slot should not try to clear it.
1210 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1216 * Check the constraints of the tuple
1218 if (resultRelationDesc->rd_att->constr)
1219 ExecConstraints("ExecAppend", resultRelInfo, slot, estate);
1224 newId = heap_insert(resultRelationDesc, tuple);
1227 (estate->es_processed)++;
1228 estate->es_lastoid = newId;
1229 setLastTid(&(tuple->t_self));
1234 * Note: heap_insert adds a new tuple to a relation. As a side effect,
1235 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1238 numIndices = resultRelInfo->ri_NumIndices;
1240 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1242 /* AFTER ROW INSERT Triggers */
1243 if (resultRelInfo->ri_TrigDesc)
1244 ExecARInsertTriggers(estate, resultRelInfo, tuple);
1247 /* ----------------------------------------------------------------
1250 * DELETE is like append, we delete the tuple and its
1252 * ----------------------------------------------------------------
1255 ExecDelete(TupleTableSlot *slot,
1256 ItemPointer tupleid,
1259 ResultRelInfo *resultRelInfo;
1260 Relation resultRelationDesc;
1261 ItemPointerData ctid;
1265 * get information on the (current) result relation
1267 resultRelInfo = estate->es_result_relation_info;
1268 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1270 /* BEFORE ROW DELETE Triggers */
1271 if (resultRelInfo->ri_TrigDesc &&
1272 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1276 dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid);
1278 if (!dodelete) /* "do nothing" */
1286 result = heap_delete(resultRelationDesc, tupleid, &ctid);
1289 case HeapTupleSelfUpdated:
1292 case HeapTupleMayBeUpdated:
1295 case HeapTupleUpdated:
1296 if (XactIsoLevel == XACT_SERIALIZABLE)
1297 elog(ERROR, "Can't serialize access due to concurrent update");
1298 else if (!(ItemPointerEquals(tupleid, &ctid)))
1300 TupleTableSlot *epqslot = EvalPlanQual(estate,
1301 resultRelInfo->ri_RangeTableIndex, &ctid);
1303 if (!TupIsNull(epqslot))
1309 /* tuple already deleted; nothing to do */
1313 elog(ERROR, "Unknown status %u from heap_delete", result);
1318 (estate->es_processed)++;
1321 * Note: Normally one would think that we have to delete index tuples
1322 * associated with the heap tuple now..
1324 * ... but in POSTGRES, we have no need to do this because the vacuum
1325 * daemon automatically opens an index scan and deletes index tuples
1326 * when it finds deleted heap tuples. -cim 9/27/89
1329 /* AFTER ROW DELETE Triggers */
1330 if (resultRelInfo->ri_TrigDesc)
1331 ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1334 /* ----------------------------------------------------------------
1337 * note: we can't run replace queries with transactions
1338 * off because replaces are actually appends and our
1339 * scan will mistakenly loop forever, replacing the tuple
1340 * it just appended.. This should be fixed but until it
1341 * is, we don't want to get stuck in an infinite loop
1342 * which corrupts your database..
1343 * ----------------------------------------------------------------
1346 ExecReplace(TupleTableSlot *slot,
1347 ItemPointer tupleid,
1351 ResultRelInfo *resultRelInfo;
1352 Relation resultRelationDesc;
1353 ItemPointerData ctid;
1358 * abort the operation if not running transactions
1360 if (IsBootstrapProcessingMode())
1362 elog(NOTICE, "ExecReplace: replace can't run without transactions");
1367 * get the heap tuple out of the tuple table slot
1372 * get information on the (current) result relation
1374 resultRelInfo = estate->es_result_relation_info;
1375 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1377 /* BEFORE ROW UPDATE Triggers */
1378 if (resultRelInfo->ri_TrigDesc &&
1379 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1383 newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
1386 if (newtuple == NULL) /* "do nothing" */
1389 if (newtuple != tuple) /* modified by Trigger(s) */
1392 * Insert modified tuple into tuple table slot, replacing the
1393 * original. We assume that it was allocated in per-tuple
1394 * memory context, and therefore will go away by itself. The
1395 * tuple table slot should not try to clear it.
1397 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1403 * Check the constraints of the tuple
1405 * If we generate a new candidate tuple after EvalPlanQual testing, we
1406 * must loop back here and recheck constraints. (We don't need to
1407 * redo triggers, however. If there are any BEFORE triggers then
1408 * trigger.c will have done mark4update to lock the correct tuple, so
1409 * there's no need to do them again.)
1412 if (resultRelationDesc->rd_att->constr)
1413 ExecConstraints("ExecReplace", resultRelInfo, slot, estate);
1416 * replace the heap tuple
1418 result = heap_update(resultRelationDesc, tupleid, tuple, &ctid);
1421 case HeapTupleSelfUpdated:
1424 case HeapTupleMayBeUpdated:
1427 case HeapTupleUpdated:
1428 if (XactIsoLevel == XACT_SERIALIZABLE)
1429 elog(ERROR, "Can't serialize access due to concurrent update");
1430 else if (!(ItemPointerEquals(tupleid, &ctid)))
1432 TupleTableSlot *epqslot = EvalPlanQual(estate,
1433 resultRelInfo->ri_RangeTableIndex, &ctid);
1435 if (!TupIsNull(epqslot))
1438 tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot);
1439 slot = ExecStoreTuple(tuple,
1440 estate->es_junkFilter->jf_resultSlot,
1441 InvalidBuffer, true);
1445 /* tuple already deleted; nothing to do */
1449 elog(ERROR, "Unknown status %u from heap_update", result);
1454 (estate->es_processed)++;
1457 * Note: instead of having to update the old index tuples associated
1458 * with the heap tuple, all we do is form and insert new index tuples.
1459 * This is because replaces are actually deletes and inserts and index
1460 * tuple deletion is done automagically by the vacuum daemon. All we
1461 * do is insert new index tuples. -cim 9/27/89
1467 * heap_update updates a tuple in the base relation by invalidating it
1468 * and then appending a new tuple to the relation. As a side effect,
1469 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1470 * field. So we now insert index tuples using the new tupleid stored
1474 numIndices = resultRelInfo->ri_NumIndices;
1476 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, true);
1478 /* AFTER ROW UPDATE Triggers */
1479 if (resultRelInfo->ri_TrigDesc)
1480 ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
1484 ExecRelCheck(ResultRelInfo *resultRelInfo,
1485 TupleTableSlot *slot, EState *estate)
1487 Relation rel = resultRelInfo->ri_RelationDesc;
1488 int ncheck = rel->rd_att->constr->num_check;
1489 ConstrCheck *check = rel->rd_att->constr->check;
1490 ExprContext *econtext;
1491 MemoryContext oldContext;
1496 * If first time through for this result relation, build expression
1497 * nodetrees for rel's constraint expressions. Keep them in the
1498 * per-query memory context so they'll survive throughout the query.
1500 if (resultRelInfo->ri_ConstraintExprs == NULL)
1502 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1503 resultRelInfo->ri_ConstraintExprs =
1504 (List **) palloc(ncheck * sizeof(List *));
1505 for (i = 0; i < ncheck; i++)
1507 qual = (List *) stringToNode(check[i].ccbin);
1508 resultRelInfo->ri_ConstraintExprs[i] = qual;
1510 MemoryContextSwitchTo(oldContext);
1514 * We will use the EState's per-tuple context for evaluating
1515 * constraint expressions (creating it if it's not already there).
1517 econtext = GetPerTupleExprContext(estate);
1519 /* Arrange for econtext's scan tuple to be the tuple under test */
1520 econtext->ecxt_scantuple = slot;
1522 /* And evaluate the constraints */
1523 for (i = 0; i < ncheck; i++)
1525 qual = resultRelInfo->ri_ConstraintExprs[i];
1528 * NOTE: SQL92 specifies that a NULL result from a constraint
1529 * expression is not to be treated as a failure. Therefore, tell
1530 * ExecQual to return TRUE for NULL.
1532 if (!ExecQual(qual, econtext, true))
1533 return check[i].ccname;
1536 /* NULL result means no error */
1537 return (char *) NULL;
1541 ExecConstraints(char *caller, ResultRelInfo *resultRelInfo,
1542 TupleTableSlot *slot, EState *estate)
1544 Relation rel = resultRelInfo->ri_RelationDesc;
1545 HeapTuple tuple = slot->val;
1546 TupleConstr *constr = rel->rd_att->constr;
1550 if (constr->has_not_null)
1552 int natts = rel->rd_att->natts;
1555 for (attrChk = 1; attrChk <= natts; attrChk++)
1557 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1558 heap_attisnull(tuple, attrChk))
1559 elog(ERROR, "%s: Fail to add null value in not null attribute %s",
1560 caller, NameStr(rel->rd_att->attrs[attrChk - 1]->attname));
1564 if (constr->num_check > 0)
1568 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1569 elog(ERROR, "%s: rejected due to CHECK constraint %s",
1575 * Check a modified tuple to see if we want to process its updated version
1576 * under READ COMMITTED rules.
1578 * See backend/executor/README for some info about how this works.
1581 EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
1586 HeapTupleData tuple;
1587 HeapTuple copyTuple = NULL;
1594 * find relation containing target tuple
1596 if (estate->es_result_relation_info != NULL &&
1597 estate->es_result_relation_info->ri_RangeTableIndex == rti)
1598 relation = estate->es_result_relation_info->ri_RelationDesc;
1604 foreach(l, estate->es_rowMark)
1606 if (((execRowMark *) lfirst(l))->rti == rti)
1608 relation = ((execRowMark *) lfirst(l))->relation;
1612 if (relation == NULL)
1613 elog(ERROR, "EvalPlanQual: can't find RTE %d", (int) rti);
1619 * Loop here to deal with updated or busy tuples
1621 tuple.t_self = *tid;
1626 heap_fetch(relation, SnapshotDirty, &tuple, &buffer, NULL);
1627 if (tuple.t_data != NULL)
1629 TransactionId xwait = SnapshotDirty->xmax;
1631 if (TransactionIdIsValid(SnapshotDirty->xmin))
1632 elog(ERROR, "EvalPlanQual: t_xmin is uncommitted ?!");
1635 * If tuple is being updated by other transaction then we have
1636 * to wait for its commit/abort.
1638 if (TransactionIdIsValid(xwait))
1640 ReleaseBuffer(buffer);
1641 XactLockTableWait(xwait);
1646 * We got tuple - now copy it for use by recheck query.
1648 copyTuple = heap_copytuple(&tuple);
1649 ReleaseBuffer(buffer);
1654 * Oops! Invalid tuple. Have to check is it updated or deleted.
1655 * Note that it's possible to get invalid SnapshotDirty->tid if
1656 * tuple updated by this transaction. Have we to check this ?
1658 if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
1659 !(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
1661 /* updated, so look at the updated copy */
1662 tuple.t_self = SnapshotDirty->tid;
1667 * Deleted or updated by this transaction; forget it.
1673 * For UPDATE/DELETE we have to return tid of actual row we're
1676 *tid = tuple.t_self;
1679 * Need to run a recheck subquery. Find or create a PQ stack entry.
1681 epq = (evalPlanQual *) estate->es_evalPlanQual;
1682 rtsize = length(estate->es_range_table);
1685 if (epq != NULL && epq->rti == 0)
1687 /* Top PQ stack entry is idle, so re-use it */
1688 Assert(!(estate->es_useEvalPlan) &&
1689 epq->estate.es_evalPlanQual == NULL);
1695 * If this is request for another RTE - Ra, - then we have to check
1696 * wasn't PlanQual requested for Ra already and if so then Ra' row was
1697 * updated again and we have to re-start old execution for Ra and
1698 * forget all what we done after Ra was suspended. Cool? -:))
1700 if (epq != NULL && epq->rti != rti &&
1701 epq->estate.es_evTuple[rti - 1] != NULL)
1705 evalPlanQual *oldepq;
1707 /* pop previous PlanQual from the stack */
1708 epqstate = &(epq->estate);
1709 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1710 Assert(oldepq->rti != 0);
1711 /* stop execution */
1712 ExecEndNode(epq->plan, NULL);
1713 ExecDropTupleTable(epqstate->es_tupleTable, true);
1714 epqstate->es_tupleTable = NULL;
1715 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1716 epqstate->es_evTuple[epq->rti - 1] = NULL;
1717 /* push current PQ to freePQ stack */
1720 estate->es_evalPlanQual = (Pointer) epq;
1721 } while (epq->rti != rti);
1725 * If we are requested for another RTE then we have to suspend
1726 * execution of current PlanQual and start execution for new one.
1728 if (epq == NULL || epq->rti != rti)
1730 /* try to reuse plan used previously */
1731 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
1733 if (newepq == NULL) /* first call or freePQ stack is empty */
1735 newepq = (evalPlanQual *) palloc(sizeof(evalPlanQual));
1736 newepq->free = NULL;
1739 * Each stack level has its own copy of the plan tree. This
1740 * is wasteful, but necessary as long as plan nodes point to
1741 * exec state nodes rather than vice versa. Note that
1742 * copyfuncs.c doesn't attempt to copy the exec state nodes,
1743 * which is a good thing in this situation.
1745 newepq->plan = copyObject(estate->es_origPlan);
1748 * Init stack level's EState. We share top level's copy of
1749 * es_result_relations array and other non-changing status. We
1750 * need our own tupletable, es_param_exec_vals, and other
1753 epqstate = &(newepq->estate);
1754 memcpy(epqstate, estate, sizeof(EState));
1755 epqstate->es_direction = ForwardScanDirection;
1756 if (estate->es_origPlan->nParamExec > 0)
1757 epqstate->es_param_exec_vals = (ParamExecData *)
1758 palloc(estate->es_origPlan->nParamExec *
1759 sizeof(ParamExecData));
1760 epqstate->es_tupleTable = NULL;
1761 epqstate->es_per_tuple_exprcontext = NULL;
1764 * Each epqstate must have its own es_evTupleNull state, but
1765 * all the stack entries share es_evTuple state. This allows
1766 * sub-rechecks to inherit the value being examined by an
1769 epqstate->es_evTupleNull = (bool *) palloc(rtsize * sizeof(bool));
1772 /* first PQ stack entry */
1773 epqstate->es_evTuple = (HeapTuple *)
1774 palloc(rtsize * sizeof(HeapTuple));
1775 memset(epqstate->es_evTuple, 0, rtsize * sizeof(HeapTuple));
1779 /* later stack entries share the same storage */
1780 epqstate->es_evTuple = epq->estate.es_evTuple;
1785 /* recycle previously used EState */
1786 epqstate = &(newepq->estate);
1788 /* push current PQ to the stack */
1789 epqstate->es_evalPlanQual = (Pointer) epq;
1791 estate->es_evalPlanQual = (Pointer) epq;
1796 Assert(epq->rti == rti);
1797 epqstate = &(epq->estate);
1800 * Ok - we're requested for the same RTE. Unfortunately we still have
1801 * to end and restart execution of the plan, because ExecReScan
1802 * wouldn't ensure that upper plan nodes would reset themselves. We
1803 * could make that work if insertion of the target tuple were
1804 * integrated with the Param mechanism somehow, so that the upper plan
1805 * nodes know that their children's outputs have changed.
1809 /* stop execution */
1810 ExecEndNode(epq->plan, NULL);
1811 ExecDropTupleTable(epqstate->es_tupleTable, true);
1812 epqstate->es_tupleTable = NULL;
1816 * free old RTE' tuple, if any, and store target tuple where
1817 * relation's scan node will see it
1819 if (epqstate->es_evTuple[rti - 1] != NULL)
1820 heap_freetuple(epqstate->es_evTuple[rti - 1]);
1821 epqstate->es_evTuple[rti - 1] = copyTuple;
1824 * Initialize for new recheck query; be careful to copy down state
1825 * that might have changed in top EState.
1827 epqstate->es_result_relation_info = estate->es_result_relation_info;
1828 epqstate->es_junkFilter = estate->es_junkFilter;
1829 if (estate->es_origPlan->nParamExec > 0)
1830 memset(epqstate->es_param_exec_vals, 0,
1831 estate->es_origPlan->nParamExec * sizeof(ParamExecData));
1832 memset(epqstate->es_evTupleNull, false, rtsize * sizeof(bool));
1833 epqstate->es_useEvalPlan = false;
1834 Assert(epqstate->es_tupleTable == NULL);
1835 epqstate->es_tupleTable =
1836 ExecCreateTupleTable(estate->es_tupleTable->size);
1838 ExecInitNode(epq->plan, epqstate, NULL);
1840 return EvalPlanQualNext(estate);
1843 static TupleTableSlot *
1844 EvalPlanQualNext(EState *estate)
1846 evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1847 EState *epqstate = &(epq->estate);
1848 evalPlanQual *oldepq;
1849 TupleTableSlot *slot;
1851 Assert(epq->rti != 0);
1854 slot = ExecProcNode(epq->plan, NULL);
1857 * No more tuples for this PQ. Continue previous one.
1859 if (TupIsNull(slot))
1861 /* stop execution */
1862 ExecEndNode(epq->plan, NULL);
1863 ExecDropTupleTable(epqstate->es_tupleTable, true);
1864 epqstate->es_tupleTable = NULL;
1865 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1866 epqstate->es_evTuple[epq->rti - 1] = NULL;
1867 /* pop old PQ from the stack */
1868 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1869 if (oldepq == (evalPlanQual *) NULL)
1871 epq->rti = 0; /* this is the first (oldest) */
1872 estate->es_useEvalPlan = false; /* PQ - mark as free and */
1873 return (NULL); /* continue Query execution */
1875 Assert(oldepq->rti != 0);
1876 /* push current PQ to freePQ stack */
1879 epqstate = &(epq->estate);
1880 estate->es_evalPlanQual = (Pointer) epq;
1888 EndEvalPlanQual(EState *estate)
1890 evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1891 EState *epqstate = &(epq->estate);
1892 evalPlanQual *oldepq;
1894 if (epq->rti == 0) /* plans already shutdowned */
1896 Assert(epq->estate.es_evalPlanQual == NULL);
1902 /* stop execution */
1903 ExecEndNode(epq->plan, NULL);
1904 ExecDropTupleTable(epqstate->es_tupleTable, true);
1905 epqstate->es_tupleTable = NULL;
1906 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1908 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1909 epqstate->es_evTuple[epq->rti - 1] = NULL;
1911 /* pop old PQ from the stack */
1912 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1913 if (oldepq == (evalPlanQual *) NULL)
1915 epq->rti = 0; /* this is the first (oldest) */
1916 estate->es_useEvalPlan = false; /* PQ - mark as free */
1919 Assert(oldepq->rti != 0);
1920 /* push current PQ to freePQ stack */
1923 epqstate = &(epq->estate);
1924 estate->es_evalPlanQual = (Pointer) epq;