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.154 2002/03/21 23:27:23 tgl 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"
46 #include "utils/lsyscache.h"
49 /* decls for local routines only used within this module */
50 static TupleDesc InitPlan(CmdType operation,
54 static void initResultRelInfo(ResultRelInfo *resultRelInfo,
55 Index resultRelationIndex,
58 static void EndPlan(Plan *plan, EState *estate);
59 static TupleTableSlot *ExecutePlan(EState *estate, Plan *plan,
62 ScanDirection direction,
63 DestReceiver *destfunc);
64 static void ExecRetrieve(TupleTableSlot *slot,
65 DestReceiver *destfunc,
67 static void ExecAppend(TupleTableSlot *slot, ItemPointer tupleid,
69 static void ExecDelete(TupleTableSlot *slot, ItemPointer tupleid,
71 static void ExecReplace(TupleTableSlot *slot, ItemPointer tupleid,
73 static TupleTableSlot *EvalPlanQualNext(EState *estate);
74 static void EndEvalPlanQual(EState *estate);
75 static void ExecCheckQueryPerms(CmdType operation, Query *parseTree,
77 static void ExecCheckPlanPerms(Plan *plan, List *rangeTable,
79 static void ExecCheckRTPerms(List *rangeTable, CmdType operation);
80 static void ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation);
82 /* end of local decls */
85 /* ----------------------------------------------------------------
88 * This routine must be called at the beginning of any execution of any
91 * returns a TupleDesc which describes the attributes of the tuples to
92 * be returned by the query. (Same value is saved in queryDesc)
94 * NB: the CurrentMemoryContext when this is called must be the context
95 * to be used as the per-query context for the query plan. ExecutorRun()
96 * and ExecutorEnd() must be called in this same memory context.
97 * ----------------------------------------------------------------
100 ExecutorStart(QueryDesc *queryDesc, EState *estate)
105 Assert(queryDesc != NULL);
107 if (queryDesc->plantree->nParamExec > 0)
109 estate->es_param_exec_vals = (ParamExecData *)
110 palloc(queryDesc->plantree->nParamExec * sizeof(ParamExecData));
111 MemSet(estate->es_param_exec_vals, 0,
112 queryDesc->plantree->nParamExec * sizeof(ParamExecData));
116 * Make our own private copy of the current queries snapshot data
118 if (QuerySnapshot == NULL)
119 estate->es_snapshot = NULL;
122 estate->es_snapshot = (Snapshot) palloc(sizeof(SnapshotData));
123 memcpy(estate->es_snapshot, QuerySnapshot, sizeof(SnapshotData));
124 if (estate->es_snapshot->xcnt > 0)
126 estate->es_snapshot->xip = (TransactionId *)
127 palloc(estate->es_snapshot->xcnt * sizeof(TransactionId));
128 memcpy(estate->es_snapshot->xip, QuerySnapshot->xip,
129 estate->es_snapshot->xcnt * sizeof(TransactionId));
134 * Initialize the plan
136 result = InitPlan(queryDesc->operation,
137 queryDesc->parsetree,
141 queryDesc->tupDesc = result;
146 /* ----------------------------------------------------------------
149 * This is the main routine of the executor module. It accepts
150 * the query descriptor from the traffic cop and executes the
153 * ExecutorStart must have been called already.
155 * If direction is NoMovementScanDirection then nothing is done
156 * except to start up/shut down the destination. Otherwise,
157 * we retrieve up to 'count' tuples in the specified direction.
159 * Note: count = 0 is interpreted as "no limit".
161 * ----------------------------------------------------------------
164 ExecutorRun(QueryDesc *queryDesc, EState *estate,
165 ScanDirection direction, long count)
170 DestReceiver *destfunc;
171 TupleTableSlot *result;
176 Assert(queryDesc != NULL);
179 * extract information from the query descriptor and the query
182 operation = queryDesc->operation;
183 plan = queryDesc->plantree;
184 dest = queryDesc->dest;
187 * startup tuple receiver
189 estate->es_processed = 0;
190 estate->es_lastoid = InvalidOid;
192 destfunc = DestToFunction(dest);
193 (*destfunc->setup) (destfunc, (int) operation,
194 queryDesc->portalName, queryDesc->tupDesc);
199 if (direction == NoMovementScanDirection)
202 result = ExecutePlan(estate,
212 (*destfunc->cleanup) (destfunc);
217 /* ----------------------------------------------------------------
220 * This routine must be called at the end of execution of any
222 * ----------------------------------------------------------------
225 ExecutorEnd(QueryDesc *queryDesc, EState *estate)
228 Assert(queryDesc != NULL);
230 EndPlan(queryDesc->plantree, estate);
232 if (estate->es_snapshot != NULL)
234 if (estate->es_snapshot->xcnt > 0)
235 pfree(estate->es_snapshot->xip);
236 pfree(estate->es_snapshot);
237 estate->es_snapshot = NULL;
240 if (estate->es_param_exec_vals != NULL)
242 pfree(estate->es_param_exec_vals);
243 estate->es_param_exec_vals = NULL;
249 * ExecCheckQueryPerms
250 * Check access permissions for all relations referenced in a query.
253 ExecCheckQueryPerms(CmdType operation, Query *parseTree, Plan *plan)
256 * Check RTEs in the query's primary rangetable.
258 ExecCheckRTPerms(parseTree->rtable, operation);
261 * Search for subplans and APPEND nodes to check their rangetables.
263 ExecCheckPlanPerms(plan, parseTree->rtable, operation);
268 * Recursively scan the plan tree to check access permissions in
272 ExecCheckPlanPerms(Plan *plan, List *rangeTable, CmdType operation)
279 /* Check subplans, which we assume are plain SELECT queries */
281 foreach(subp, plan->initPlan)
283 SubPlan *subplan = (SubPlan *) lfirst(subp);
285 ExecCheckRTPerms(subplan->rtable, CMD_SELECT);
286 ExecCheckPlanPerms(subplan->plan, subplan->rtable, CMD_SELECT);
288 foreach(subp, plan->subPlan)
290 SubPlan *subplan = (SubPlan *) lfirst(subp);
292 ExecCheckRTPerms(subplan->rtable, CMD_SELECT);
293 ExecCheckPlanPerms(subplan->plan, subplan->rtable, CMD_SELECT);
296 /* Check lower plan nodes */
298 ExecCheckPlanPerms(plan->lefttree, rangeTable, operation);
299 ExecCheckPlanPerms(plan->righttree, rangeTable, operation);
301 /* Do node-type-specific checks */
303 switch (nodeTag(plan))
307 SubqueryScan *scan = (SubqueryScan *) plan;
310 /* Recursively check the subquery */
311 rte = rt_fetch(scan->scan.scanrelid, rangeTable);
312 Assert(rte->subquery != NULL);
313 ExecCheckQueryPerms(operation, rte->subquery, scan->subplan);
318 Append *app = (Append *) plan;
321 foreach(appendplans, app->appendplans)
323 ExecCheckPlanPerms((Plan *) lfirst(appendplans),
337 * Check access permissions for all relations listed in a range table.
340 ExecCheckRTPerms(List *rangeTable, CmdType operation)
344 foreach(lp, rangeTable)
346 RangeTblEntry *rte = lfirst(lp);
348 ExecCheckRTEPerms(rte, operation);
354 * Check access permissions for a single RTE.
357 ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation)
361 int32 aclcheck_result;
364 * If it's a subquery RTE, ignore it --- it will be checked when
365 * ExecCheckPlanPerms finds the SubqueryScan node for it.
367 if (rte->rtekind != RTE_RELATION)
373 * userid to check as: current user unless we have a setuid
376 * Note: GetUserId() is presently fast enough that there's no harm in
377 * calling it separately for each RTE. If that stops being true, we
378 * could call it once in ExecCheckQueryPerms and pass the userid down
379 * from there. But for now, no need for the extra clutter.
381 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
383 #define CHECK(MODE) pg_class_aclcheck(relOid, userid, MODE)
385 if (rte->checkForRead)
387 aclcheck_result = CHECK(ACL_SELECT);
388 if (aclcheck_result != ACLCHECK_OK)
389 elog(ERROR, "%s: %s",
390 get_rel_name(relOid),
391 aclcheck_error_strings[aclcheck_result]);
394 if (rte->checkForWrite)
397 * Note: write access in a SELECT context means SELECT FOR UPDATE.
398 * Right now we don't distinguish that from true update as far as
399 * permissions checks are concerned.
404 aclcheck_result = CHECK(ACL_INSERT);
408 aclcheck_result = CHECK(ACL_UPDATE);
411 aclcheck_result = CHECK(ACL_DELETE);
414 elog(ERROR, "ExecCheckRTEPerms: bogus operation %d",
416 aclcheck_result = ACLCHECK_OK; /* keep compiler quiet */
419 if (aclcheck_result != ACLCHECK_OK)
420 elog(ERROR, "%s: %s",
421 get_rel_name(relOid),
422 aclcheck_error_strings[aclcheck_result]);
427 /* ===============================================================
428 * ===============================================================
429 static routines follow
430 * ===============================================================
431 * ===============================================================
434 typedef struct execRowMark
441 typedef struct evalPlanQual
446 struct evalPlanQual *free;
449 /* ----------------------------------------------------------------
452 * Initializes the query plan: open files, allocate storage
453 * and start up the rule manager
454 * ----------------------------------------------------------------
457 InitPlan(CmdType operation, Query *parseTree, Plan *plan, EState *estate)
460 Relation intoRelationDesc;
464 * Do permissions checks.
466 ExecCheckQueryPerms(operation, parseTree, plan);
469 * get information from query descriptor
471 rangeTable = parseTree->rtable;
474 * initialize the node's execution state
476 estate->es_range_table = rangeTable;
479 * if there is a result relation, initialize result relation stuff
481 if (parseTree->resultRelation != 0 && operation != CMD_SELECT)
483 List *resultRelations = parseTree->resultRelations;
484 int numResultRelations;
485 ResultRelInfo *resultRelInfos;
487 if (resultRelations != NIL)
490 * Multiple result relations (due to inheritance)
491 * parseTree->resultRelations identifies them all
493 ResultRelInfo *resultRelInfo;
495 numResultRelations = length(resultRelations);
496 resultRelInfos = (ResultRelInfo *)
497 palloc(numResultRelations * sizeof(ResultRelInfo));
498 resultRelInfo = resultRelInfos;
499 while (resultRelations != NIL)
501 initResultRelInfo(resultRelInfo,
502 lfirsti(resultRelations),
506 resultRelations = lnext(resultRelations);
512 * Single result relation identified by
513 * parseTree->resultRelation
515 numResultRelations = 1;
516 resultRelInfos = (ResultRelInfo *) palloc(sizeof(ResultRelInfo));
517 initResultRelInfo(resultRelInfos,
518 parseTree->resultRelation,
523 estate->es_result_relations = resultRelInfos;
524 estate->es_num_result_relations = numResultRelations;
525 /* Initialize to first or only result rel */
526 estate->es_result_relation_info = resultRelInfos;
531 * if no result relation, then set state appropriately
533 estate->es_result_relations = NULL;
534 estate->es_num_result_relations = 0;
535 estate->es_result_relation_info = NULL;
539 * Have to lock relations selected for update
541 estate->es_rowMark = NIL;
542 if (parseTree->rowMarks != NIL)
546 foreach(l, parseTree->rowMarks)
548 Index rti = lfirsti(l);
549 Oid relid = getrelid(rti, rangeTable);
553 relation = heap_open(relid, RowShareLock);
554 erm = (execRowMark *) palloc(sizeof(execRowMark));
555 erm->relation = relation;
557 sprintf(erm->resname, "ctid%u", rti);
558 estate->es_rowMark = lappend(estate->es_rowMark, erm);
563 * initialize the executor "tuple" table. We need slots for all the
564 * plan nodes, plus possibly output slots for the junkfilter(s). At
565 * this point we aren't sure if we need junkfilters, so just add slots
566 * for them unconditionally.
569 int nSlots = ExecCountSlotsNode(plan);
571 if (parseTree->resultRelations != NIL)
572 nSlots += length(parseTree->resultRelations);
575 estate->es_tupleTable = ExecCreateTupleTable(nSlots);
578 /* mark EvalPlanQual not active */
579 estate->es_origPlan = plan;
580 estate->es_evalPlanQual = NULL;
581 estate->es_evTuple = NULL;
582 estate->es_evTupleNull = NULL;
583 estate->es_useEvalPlan = false;
586 * initialize the private state information for all the nodes in the
587 * query tree. This opens files, allocates storage and leaves us
588 * ready to start processing tuples.
590 ExecInitNode(plan, estate, NULL);
593 * Get the tuple descriptor describing the type of tuples to return.
594 * (this is especially important if we are creating a relation with
597 tupType = ExecGetTupType(plan); /* tuple descriptor */
600 * Initialize the junk filter if needed. SELECT and INSERT queries
601 * need a filter if there are any junk attrs in the tlist. UPDATE and
602 * DELETE always need one, since there's always a junk 'ctid'
603 * attribute present --- no need to look first.
606 bool junk_filter_needed = false;
613 foreach(tlist, plan->targetlist)
615 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
617 if (tle->resdom->resjunk)
619 junk_filter_needed = true;
626 junk_filter_needed = true;
632 if (junk_filter_needed)
635 * If there are multiple result relations, each one needs its
636 * own junk filter. Note this is only possible for
637 * UPDATE/DELETE, so we can't be fooled by some needing a
638 * filter and some not.
640 if (parseTree->resultRelations != NIL)
643 ResultRelInfo *resultRelInfo;
645 /* Top plan had better be an Append here. */
646 Assert(IsA(plan, Append));
647 Assert(((Append *) plan)->isTarget);
648 subplans = ((Append *) plan)->appendplans;
649 Assert(length(subplans) == estate->es_num_result_relations);
650 resultRelInfo = estate->es_result_relations;
651 while (subplans != NIL)
653 Plan *subplan = (Plan *) lfirst(subplans);
656 j = ExecInitJunkFilter(subplan->targetlist,
657 ExecGetTupType(subplan),
658 ExecAllocTableSlot(estate->es_tupleTable));
659 resultRelInfo->ri_junkFilter = j;
661 subplans = lnext(subplans);
665 * Set active junkfilter too; at this point ExecInitAppend
666 * has already selected an active result relation...
668 estate->es_junkFilter =
669 estate->es_result_relation_info->ri_junkFilter;
673 /* Normal case with just one JunkFilter */
676 j = ExecInitJunkFilter(plan->targetlist,
678 ExecAllocTableSlot(estate->es_tupleTable));
679 estate->es_junkFilter = j;
680 if (estate->es_result_relation_info)
681 estate->es_result_relation_info->ri_junkFilter = j;
683 /* For SELECT, want to return the cleaned tuple type */
684 if (operation == CMD_SELECT)
685 tupType = j->jf_cleanTupType;
689 estate->es_junkFilter = NULL;
693 * initialize the "into" relation
695 intoRelationDesc = (Relation) NULL;
697 if (operation == CMD_SELECT)
703 if (!parseTree->isPortal)
706 * a select into table
708 if (parseTree->into != NULL)
711 * create the "into" relation
713 intoName = parseTree->into->relname;
716 * have to copy tupType to get rid of constraints
718 tupdesc = CreateTupleDescCopy(tupType);
721 heap_create_with_catalog(intoName,
723 RELKIND_RELATION, true,
724 parseTree->into->istemp,
725 allowSystemTableMods);
727 FreeTupleDesc(tupdesc);
730 * Advance command counter so that the newly-created
731 * relation's catalog tuples will be visible to heap_open.
733 CommandCounterIncrement();
736 * If necessary, create a TOAST table for the into
737 * relation. Note that AlterTableCreateToastTable ends
738 * with CommandCounterIncrement(), so that the TOAST table
739 * will be visible for insertion.
741 AlterTableCreateToastTable(intoName, true);
743 intoRelationDesc = heap_open(intoRelationId,
744 AccessExclusiveLock);
749 estate->es_into_relation_descriptor = intoRelationDesc;
755 * Initialize ResultRelInfo data for one result relation
758 initResultRelInfo(ResultRelInfo *resultRelInfo,
759 Index resultRelationIndex,
763 Oid resultRelationOid;
764 Relation resultRelationDesc;
766 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
767 resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
769 switch (resultRelationDesc->rd_rel->relkind)
771 case RELKIND_SEQUENCE:
772 elog(ERROR, "You can't change sequence relation %s",
773 RelationGetRelationName(resultRelationDesc));
775 case RELKIND_TOASTVALUE:
776 elog(ERROR, "You can't change toast relation %s",
777 RelationGetRelationName(resultRelationDesc));
780 elog(ERROR, "You can't change view relation %s",
781 RelationGetRelationName(resultRelationDesc));
785 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
786 resultRelInfo->type = T_ResultRelInfo;
787 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
788 resultRelInfo->ri_RelationDesc = resultRelationDesc;
789 resultRelInfo->ri_NumIndices = 0;
790 resultRelInfo->ri_IndexRelationDescs = NULL;
791 resultRelInfo->ri_IndexRelationInfo = NULL;
792 resultRelInfo->ri_TrigDesc = resultRelationDesc->trigdesc;
793 resultRelInfo->ri_TrigFunctions = NULL;
794 resultRelInfo->ri_ConstraintExprs = NULL;
795 resultRelInfo->ri_junkFilter = NULL;
798 * If there are indices on the result relation, open them and save
799 * descriptors in the result relation info, so that we can add new
800 * index entries for the tuples we add/update. We need not do this
801 * for a DELETE, however, since deletion doesn't affect indexes.
803 if (resultRelationDesc->rd_rel->relhasindex &&
804 operation != CMD_DELETE)
805 ExecOpenIndices(resultRelInfo);
808 /* ----------------------------------------------------------------
811 * Cleans up the query plan -- closes files and free up storages
812 * ----------------------------------------------------------------
815 EndPlan(Plan *plan, EState *estate)
817 ResultRelInfo *resultRelInfo;
822 * shut down any PlanQual processing we were doing
824 if (estate->es_evalPlanQual != NULL)
825 EndEvalPlanQual(estate);
828 * shut down the node-type-specific query processing
830 ExecEndNode(plan, NULL);
833 * destroy the executor "tuple" table.
835 ExecDropTupleTable(estate->es_tupleTable, true);
836 estate->es_tupleTable = NULL;
839 * close the result relation(s) if any, but hold locks until xact
840 * commit. Also clean up junkfilters if present.
842 resultRelInfo = estate->es_result_relations;
843 for (i = estate->es_num_result_relations; i > 0; i--)
845 /* Close indices and then the relation itself */
846 ExecCloseIndices(resultRelInfo);
847 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
848 /* Delete the junkfilter if any */
849 if (resultRelInfo->ri_junkFilter != NULL)
850 ExecFreeJunkFilter(resultRelInfo->ri_junkFilter);
855 * close the "into" relation if necessary, again keeping lock
857 if (estate->es_into_relation_descriptor != NULL)
858 heap_close(estate->es_into_relation_descriptor, NoLock);
861 * There might be a junkfilter without a result relation.
863 if (estate->es_num_result_relations == 0 &&
864 estate->es_junkFilter != NULL)
866 ExecFreeJunkFilter(estate->es_junkFilter);
867 estate->es_junkFilter = NULL;
871 * close any relations selected FOR UPDATE, again keeping locks
873 foreach(l, estate->es_rowMark)
875 execRowMark *erm = lfirst(l);
877 heap_close(erm->relation, NoLock);
881 /* ----------------------------------------------------------------
884 * processes the query plan to retrieve 'numberTuples' tuples in the
885 * direction specified.
886 * Retrieves all tuples if numberTuples is 0
888 * result is either a slot containing the last tuple in the case
889 * of a RETRIEVE or NULL otherwise.
891 * Note: the ctid attribute is a 'junk' attribute that is removed before the
893 * ----------------------------------------------------------------
895 static TupleTableSlot *
896 ExecutePlan(EState *estate,
900 ScanDirection direction,
901 DestReceiver *destfunc)
903 JunkFilter *junkfilter;
904 TupleTableSlot *slot;
905 ItemPointer tupleid = NULL;
906 ItemPointerData tuple_ctid;
907 long current_tuple_count;
908 TupleTableSlot *result;
911 * initialize local variables
914 current_tuple_count = 0;
920 estate->es_direction = direction;
923 * Loop until we've processed the proper number of tuples from the
929 /* Reset the per-output-tuple exprcontext */
930 ResetPerTupleExprContext(estate);
933 * Execute the plan and obtain a tuple
936 if (estate->es_useEvalPlan)
938 slot = EvalPlanQualNext(estate);
940 slot = ExecProcNode(plan, NULL);
943 slot = ExecProcNode(plan, NULL);
946 * if the tuple is null, then we assume there is nothing more to
947 * process so we just return null...
956 * if we have a junk filter, then project a new tuple with the
959 * Store this new "clean" tuple in the junkfilter's resultSlot.
960 * (Formerly, we stored it back over the "dirty" tuple, which is
961 * WRONG because that tuple slot has the wrong descriptor.)
963 * Also, extract all the junk information we need.
965 if ((junkfilter = estate->es_junkFilter) != (JunkFilter *) NULL)
972 * extract the 'ctid' junk attribute.
974 if (operation == CMD_UPDATE || operation == CMD_DELETE)
976 if (!ExecGetJunkAttribute(junkfilter,
981 elog(ERROR, "ExecutePlan: NO (junk) `ctid' was found!");
983 /* shouldn't ever get a null result... */
985 elog(ERROR, "ExecutePlan: (junk) `ctid' is NULL!");
987 tupleid = (ItemPointer) DatumGetPointer(datum);
988 tuple_ctid = *tupleid; /* make sure we don't free the
990 tupleid = &tuple_ctid;
992 else if (estate->es_rowMark != NIL)
997 foreach(l, estate->es_rowMark)
999 execRowMark *erm = lfirst(l);
1001 HeapTupleData tuple;
1002 TupleTableSlot *newSlot;
1005 if (!ExecGetJunkAttribute(junkfilter,
1010 elog(ERROR, "ExecutePlan: NO (junk) `%s' was found!",
1013 /* shouldn't ever get a null result... */
1015 elog(ERROR, "ExecutePlan: (junk) `%s' is NULL!",
1018 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1019 test = heap_mark4update(erm->relation, &tuple, &buffer);
1020 ReleaseBuffer(buffer);
1023 case HeapTupleSelfUpdated:
1024 case HeapTupleMayBeUpdated:
1027 case HeapTupleUpdated:
1028 if (XactIsoLevel == XACT_SERIALIZABLE)
1029 elog(ERROR, "Can't serialize access due to concurrent update");
1030 if (!(ItemPointerEquals(&(tuple.t_self),
1031 (ItemPointer) DatumGetPointer(datum))))
1033 newSlot = EvalPlanQual(estate, erm->rti, &(tuple.t_self));
1034 if (!(TupIsNull(newSlot)))
1037 estate->es_useEvalPlan = true;
1043 * if tuple was deleted or PlanQual failed for
1044 * updated tuple - we must not return this
1050 elog(ERROR, "Unknown status %u from heap_mark4update", test);
1057 * Finally create a new "clean" tuple with all junk attributes
1060 newTuple = ExecRemoveJunk(junkfilter, slot);
1062 slot = ExecStoreTuple(newTuple, /* tuple to store */
1063 junkfilter->jf_resultSlot, /* dest slot */
1064 InvalidBuffer, /* this tuple has no
1066 true); /* tuple should be pfreed */
1067 } /* if (junkfilter... */
1070 * now that we have a tuple, do the appropriate thing with it..
1071 * either return it to the user, add it to a relation someplace,
1072 * delete it from a relation, or modify some of its attributes.
1078 ExecRetrieve(slot, /* slot containing tuple */
1079 destfunc, /* destination's tuple-receiver
1086 ExecAppend(slot, tupleid, estate);
1091 ExecDelete(slot, tupleid, estate);
1096 ExecReplace(slot, tupleid, estate);
1101 elog(LOG, "ExecutePlan: unknown operation in queryDesc");
1107 * check our tuple count.. if we've processed the proper number
1108 * then quit, else loop again and process more tuples..
1110 current_tuple_count++;
1111 if (numberTuples == current_tuple_count)
1116 * here, result is either a slot containing a tuple in the case of a
1117 * RETRIEVE or NULL otherwise.
1122 /* ----------------------------------------------------------------
1125 * RETRIEVEs are easy.. we just pass the tuple to the appropriate
1126 * print function. The only complexity is when we do a
1127 * "retrieve into", in which case we insert the tuple into
1128 * the appropriate relation (note: this is a newly created relation
1129 * so we don't need to worry about indices or locks.)
1130 * ----------------------------------------------------------------
1133 ExecRetrieve(TupleTableSlot *slot,
1134 DestReceiver *destfunc,
1141 * get the heap tuple out of the tuple table slot
1144 attrtype = slot->ttc_tupleDescriptor;
1147 * insert the tuple into the "into relation"
1149 if (estate->es_into_relation_descriptor != NULL)
1151 heap_insert(estate->es_into_relation_descriptor, tuple);
1156 * send the tuple to the front end (or the screen)
1158 (*destfunc->receiveTuple) (tuple, attrtype, destfunc);
1160 (estate->es_processed)++;
1163 /* ----------------------------------------------------------------
1166 * APPENDs are trickier.. we have to insert the tuple into
1167 * the base relation and insert appropriate tuples into the
1169 * ----------------------------------------------------------------
1173 ExecAppend(TupleTableSlot *slot,
1174 ItemPointer tupleid,
1178 ResultRelInfo *resultRelInfo;
1179 Relation resultRelationDesc;
1184 * get the heap tuple out of the tuple table slot
1189 * get information on the (current) result relation
1191 resultRelInfo = estate->es_result_relation_info;
1192 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1194 /* BEFORE ROW INSERT Triggers */
1195 if (resultRelInfo->ri_TrigDesc &&
1196 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1200 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1202 if (newtuple == NULL) /* "do nothing" */
1205 if (newtuple != tuple) /* modified by Trigger(s) */
1208 * Insert modified tuple into tuple table slot, replacing the
1209 * original. We assume that it was allocated in per-tuple
1210 * memory context, and therefore will go away by itself. The
1211 * tuple table slot should not try to clear it.
1213 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1219 * Check the constraints of the tuple
1221 if (resultRelationDesc->rd_att->constr)
1222 ExecConstraints("ExecAppend", resultRelInfo, slot, estate);
1227 newId = heap_insert(resultRelationDesc, tuple);
1230 (estate->es_processed)++;
1231 estate->es_lastoid = newId;
1232 setLastTid(&(tuple->t_self));
1237 * Note: heap_insert adds a new tuple to a relation. As a side effect,
1238 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1241 numIndices = resultRelInfo->ri_NumIndices;
1243 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1245 /* AFTER ROW INSERT Triggers */
1246 if (resultRelInfo->ri_TrigDesc)
1247 ExecARInsertTriggers(estate, resultRelInfo, tuple);
1250 /* ----------------------------------------------------------------
1253 * DELETE is like append, we delete the tuple and its
1255 * ----------------------------------------------------------------
1258 ExecDelete(TupleTableSlot *slot,
1259 ItemPointer tupleid,
1262 ResultRelInfo *resultRelInfo;
1263 Relation resultRelationDesc;
1264 ItemPointerData ctid;
1268 * get information on the (current) result relation
1270 resultRelInfo = estate->es_result_relation_info;
1271 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1273 /* BEFORE ROW DELETE Triggers */
1274 if (resultRelInfo->ri_TrigDesc &&
1275 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1279 dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid);
1281 if (!dodelete) /* "do nothing" */
1289 result = heap_delete(resultRelationDesc, tupleid, &ctid);
1292 case HeapTupleSelfUpdated:
1295 case HeapTupleMayBeUpdated:
1298 case HeapTupleUpdated:
1299 if (XactIsoLevel == XACT_SERIALIZABLE)
1300 elog(ERROR, "Can't serialize access due to concurrent update");
1301 else if (!(ItemPointerEquals(tupleid, &ctid)))
1303 TupleTableSlot *epqslot = EvalPlanQual(estate,
1304 resultRelInfo->ri_RangeTableIndex, &ctid);
1306 if (!TupIsNull(epqslot))
1312 /* tuple already deleted; nothing to do */
1316 elog(ERROR, "Unknown status %u from heap_delete", result);
1321 (estate->es_processed)++;
1324 * Note: Normally one would think that we have to delete index tuples
1325 * associated with the heap tuple now..
1327 * ... but in POSTGRES, we have no need to do this because the vacuum
1328 * daemon automatically opens an index scan and deletes index tuples
1329 * when it finds deleted heap tuples. -cim 9/27/89
1332 /* AFTER ROW DELETE Triggers */
1333 if (resultRelInfo->ri_TrigDesc)
1334 ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1337 /* ----------------------------------------------------------------
1340 * note: we can't run replace queries with transactions
1341 * off because replaces are actually appends and our
1342 * scan will mistakenly loop forever, replacing the tuple
1343 * it just appended.. This should be fixed but until it
1344 * is, we don't want to get stuck in an infinite loop
1345 * which corrupts your database..
1346 * ----------------------------------------------------------------
1349 ExecReplace(TupleTableSlot *slot,
1350 ItemPointer tupleid,
1354 ResultRelInfo *resultRelInfo;
1355 Relation resultRelationDesc;
1356 ItemPointerData ctid;
1361 * abort the operation if not running transactions
1363 if (IsBootstrapProcessingMode())
1365 elog(WARNING, "ExecReplace: replace can't run without transactions");
1370 * get the heap tuple out of the tuple table slot
1375 * get information on the (current) result relation
1377 resultRelInfo = estate->es_result_relation_info;
1378 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1380 /* BEFORE ROW UPDATE Triggers */
1381 if (resultRelInfo->ri_TrigDesc &&
1382 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1386 newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
1389 if (newtuple == NULL) /* "do nothing" */
1392 if (newtuple != tuple) /* modified by Trigger(s) */
1395 * Insert modified tuple into tuple table slot, replacing the
1396 * original. We assume that it was allocated in per-tuple
1397 * memory context, and therefore will go away by itself. The
1398 * tuple table slot should not try to clear it.
1400 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1406 * Check the constraints of the tuple
1408 * If we generate a new candidate tuple after EvalPlanQual testing, we
1409 * must loop back here and recheck constraints. (We don't need to
1410 * redo triggers, however. If there are any BEFORE triggers then
1411 * trigger.c will have done mark4update to lock the correct tuple, so
1412 * there's no need to do them again.)
1415 if (resultRelationDesc->rd_att->constr)
1416 ExecConstraints("ExecReplace", resultRelInfo, slot, estate);
1419 * replace the heap tuple
1421 result = heap_update(resultRelationDesc, tupleid, tuple, &ctid);
1424 case HeapTupleSelfUpdated:
1427 case HeapTupleMayBeUpdated:
1430 case HeapTupleUpdated:
1431 if (XactIsoLevel == XACT_SERIALIZABLE)
1432 elog(ERROR, "Can't serialize access due to concurrent update");
1433 else if (!(ItemPointerEquals(tupleid, &ctid)))
1435 TupleTableSlot *epqslot = EvalPlanQual(estate,
1436 resultRelInfo->ri_RangeTableIndex, &ctid);
1438 if (!TupIsNull(epqslot))
1441 tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot);
1442 slot = ExecStoreTuple(tuple,
1443 estate->es_junkFilter->jf_resultSlot,
1444 InvalidBuffer, true);
1448 /* tuple already deleted; nothing to do */
1452 elog(ERROR, "Unknown status %u from heap_update", result);
1457 (estate->es_processed)++;
1460 * Note: instead of having to update the old index tuples associated
1461 * with the heap tuple, all we do is form and insert new index tuples.
1462 * This is because replaces are actually deletes and inserts and index
1463 * tuple deletion is done automagically by the vacuum daemon. All we
1464 * do is insert new index tuples. -cim 9/27/89
1470 * heap_update updates a tuple in the base relation by invalidating it
1471 * and then appending a new tuple to the relation. As a side effect,
1472 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1473 * field. So we now insert index tuples using the new tupleid stored
1477 numIndices = resultRelInfo->ri_NumIndices;
1479 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, true);
1481 /* AFTER ROW UPDATE Triggers */
1482 if (resultRelInfo->ri_TrigDesc)
1483 ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
1487 ExecRelCheck(ResultRelInfo *resultRelInfo,
1488 TupleTableSlot *slot, EState *estate)
1490 Relation rel = resultRelInfo->ri_RelationDesc;
1491 int ncheck = rel->rd_att->constr->num_check;
1492 ConstrCheck *check = rel->rd_att->constr->check;
1493 ExprContext *econtext;
1494 MemoryContext oldContext;
1499 * If first time through for this result relation, build expression
1500 * nodetrees for rel's constraint expressions. Keep them in the
1501 * per-query memory context so they'll survive throughout the query.
1503 if (resultRelInfo->ri_ConstraintExprs == NULL)
1505 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1506 resultRelInfo->ri_ConstraintExprs =
1507 (List **) palloc(ncheck * sizeof(List *));
1508 for (i = 0; i < ncheck; i++)
1510 qual = (List *) stringToNode(check[i].ccbin);
1511 resultRelInfo->ri_ConstraintExprs[i] = qual;
1513 MemoryContextSwitchTo(oldContext);
1517 * We will use the EState's per-tuple context for evaluating
1518 * constraint expressions (creating it if it's not already there).
1520 econtext = GetPerTupleExprContext(estate);
1522 /* Arrange for econtext's scan tuple to be the tuple under test */
1523 econtext->ecxt_scantuple = slot;
1525 /* And evaluate the constraints */
1526 for (i = 0; i < ncheck; i++)
1528 qual = resultRelInfo->ri_ConstraintExprs[i];
1531 * NOTE: SQL92 specifies that a NULL result from a constraint
1532 * expression is not to be treated as a failure. Therefore, tell
1533 * ExecQual to return TRUE for NULL.
1535 if (!ExecQual(qual, econtext, true))
1536 return check[i].ccname;
1539 /* NULL result means no error */
1540 return (char *) NULL;
1544 ExecConstraints(char *caller, ResultRelInfo *resultRelInfo,
1545 TupleTableSlot *slot, EState *estate)
1547 Relation rel = resultRelInfo->ri_RelationDesc;
1548 HeapTuple tuple = slot->val;
1549 TupleConstr *constr = rel->rd_att->constr;
1553 if (constr->has_not_null)
1555 int natts = rel->rd_att->natts;
1558 for (attrChk = 1; attrChk <= natts; attrChk++)
1560 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1561 heap_attisnull(tuple, attrChk))
1562 elog(ERROR, "%s: Fail to add null value in not null attribute %s",
1563 caller, NameStr(rel->rd_att->attrs[attrChk - 1]->attname));
1567 if (constr->num_check > 0)
1571 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1572 elog(ERROR, "%s: rejected due to CHECK constraint %s",
1578 * Check a modified tuple to see if we want to process its updated version
1579 * under READ COMMITTED rules.
1581 * See backend/executor/README for some info about how this works.
1584 EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
1589 HeapTupleData tuple;
1590 HeapTuple copyTuple = NULL;
1597 * find relation containing target tuple
1599 if (estate->es_result_relation_info != NULL &&
1600 estate->es_result_relation_info->ri_RangeTableIndex == rti)
1601 relation = estate->es_result_relation_info->ri_RelationDesc;
1607 foreach(l, estate->es_rowMark)
1609 if (((execRowMark *) lfirst(l))->rti == rti)
1611 relation = ((execRowMark *) lfirst(l))->relation;
1615 if (relation == NULL)
1616 elog(ERROR, "EvalPlanQual: can't find RTE %d", (int) rti);
1622 * Loop here to deal with updated or busy tuples
1624 tuple.t_self = *tid;
1629 heap_fetch(relation, SnapshotDirty, &tuple, &buffer, NULL);
1630 if (tuple.t_data != NULL)
1632 TransactionId xwait = SnapshotDirty->xmax;
1634 if (TransactionIdIsValid(SnapshotDirty->xmin))
1635 elog(ERROR, "EvalPlanQual: t_xmin is uncommitted ?!");
1638 * If tuple is being updated by other transaction then we have
1639 * to wait for its commit/abort.
1641 if (TransactionIdIsValid(xwait))
1643 ReleaseBuffer(buffer);
1644 XactLockTableWait(xwait);
1649 * We got tuple - now copy it for use by recheck query.
1651 copyTuple = heap_copytuple(&tuple);
1652 ReleaseBuffer(buffer);
1657 * Oops! Invalid tuple. Have to check is it updated or deleted.
1658 * Note that it's possible to get invalid SnapshotDirty->tid if
1659 * tuple updated by this transaction. Have we to check this ?
1661 if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
1662 !(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
1664 /* updated, so look at the updated copy */
1665 tuple.t_self = SnapshotDirty->tid;
1670 * Deleted or updated by this transaction; forget it.
1676 * For UPDATE/DELETE we have to return tid of actual row we're
1679 *tid = tuple.t_self;
1682 * Need to run a recheck subquery. Find or create a PQ stack entry.
1684 epq = (evalPlanQual *) estate->es_evalPlanQual;
1685 rtsize = length(estate->es_range_table);
1688 if (epq != NULL && epq->rti == 0)
1690 /* Top PQ stack entry is idle, so re-use it */
1691 Assert(!(estate->es_useEvalPlan) &&
1692 epq->estate.es_evalPlanQual == NULL);
1698 * If this is request for another RTE - Ra, - then we have to check
1699 * wasn't PlanQual requested for Ra already and if so then Ra' row was
1700 * updated again and we have to re-start old execution for Ra and
1701 * forget all what we done after Ra was suspended. Cool? -:))
1703 if (epq != NULL && epq->rti != rti &&
1704 epq->estate.es_evTuple[rti - 1] != NULL)
1708 evalPlanQual *oldepq;
1710 /* pop previous PlanQual from the stack */
1711 epqstate = &(epq->estate);
1712 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1713 Assert(oldepq->rti != 0);
1714 /* stop execution */
1715 ExecEndNode(epq->plan, NULL);
1716 ExecDropTupleTable(epqstate->es_tupleTable, true);
1717 epqstate->es_tupleTable = NULL;
1718 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1719 epqstate->es_evTuple[epq->rti - 1] = NULL;
1720 /* push current PQ to freePQ stack */
1723 estate->es_evalPlanQual = (Pointer) epq;
1724 } while (epq->rti != rti);
1728 * If we are requested for another RTE then we have to suspend
1729 * execution of current PlanQual and start execution for new one.
1731 if (epq == NULL || epq->rti != rti)
1733 /* try to reuse plan used previously */
1734 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
1736 if (newepq == NULL) /* first call or freePQ stack is empty */
1738 newepq = (evalPlanQual *) palloc(sizeof(evalPlanQual));
1739 newepq->free = NULL;
1742 * Each stack level has its own copy of the plan tree. This
1743 * is wasteful, but necessary as long as plan nodes point to
1744 * exec state nodes rather than vice versa. Note that
1745 * copyfuncs.c doesn't attempt to copy the exec state nodes,
1746 * which is a good thing in this situation.
1748 newepq->plan = copyObject(estate->es_origPlan);
1751 * Init stack level's EState. We share top level's copy of
1752 * es_result_relations array and other non-changing status. We
1753 * need our own tupletable, es_param_exec_vals, and other
1756 epqstate = &(newepq->estate);
1757 memcpy(epqstate, estate, sizeof(EState));
1758 epqstate->es_direction = ForwardScanDirection;
1759 if (estate->es_origPlan->nParamExec > 0)
1760 epqstate->es_param_exec_vals = (ParamExecData *)
1761 palloc(estate->es_origPlan->nParamExec *
1762 sizeof(ParamExecData));
1763 epqstate->es_tupleTable = NULL;
1764 epqstate->es_per_tuple_exprcontext = NULL;
1767 * Each epqstate must have its own es_evTupleNull state, but
1768 * all the stack entries share es_evTuple state. This allows
1769 * sub-rechecks to inherit the value being examined by an
1772 epqstate->es_evTupleNull = (bool *) palloc(rtsize * sizeof(bool));
1775 /* first PQ stack entry */
1776 epqstate->es_evTuple = (HeapTuple *)
1777 palloc(rtsize * sizeof(HeapTuple));
1778 memset(epqstate->es_evTuple, 0, rtsize * sizeof(HeapTuple));
1782 /* later stack entries share the same storage */
1783 epqstate->es_evTuple = epq->estate.es_evTuple;
1788 /* recycle previously used EState */
1789 epqstate = &(newepq->estate);
1791 /* push current PQ to the stack */
1792 epqstate->es_evalPlanQual = (Pointer) epq;
1794 estate->es_evalPlanQual = (Pointer) epq;
1799 Assert(epq->rti == rti);
1800 epqstate = &(epq->estate);
1803 * Ok - we're requested for the same RTE. Unfortunately we still have
1804 * to end and restart execution of the plan, because ExecReScan
1805 * wouldn't ensure that upper plan nodes would reset themselves. We
1806 * could make that work if insertion of the target tuple were
1807 * integrated with the Param mechanism somehow, so that the upper plan
1808 * nodes know that their children's outputs have changed.
1812 /* stop execution */
1813 ExecEndNode(epq->plan, NULL);
1814 ExecDropTupleTable(epqstate->es_tupleTable, true);
1815 epqstate->es_tupleTable = NULL;
1819 * free old RTE' tuple, if any, and store target tuple where
1820 * relation's scan node will see it
1822 if (epqstate->es_evTuple[rti - 1] != NULL)
1823 heap_freetuple(epqstate->es_evTuple[rti - 1]);
1824 epqstate->es_evTuple[rti - 1] = copyTuple;
1827 * Initialize for new recheck query; be careful to copy down state
1828 * that might have changed in top EState.
1830 epqstate->es_result_relation_info = estate->es_result_relation_info;
1831 epqstate->es_junkFilter = estate->es_junkFilter;
1832 if (estate->es_origPlan->nParamExec > 0)
1833 memset(epqstate->es_param_exec_vals, 0,
1834 estate->es_origPlan->nParamExec * sizeof(ParamExecData));
1835 memset(epqstate->es_evTupleNull, false, rtsize * sizeof(bool));
1836 epqstate->es_useEvalPlan = false;
1837 Assert(epqstate->es_tupleTable == NULL);
1838 epqstate->es_tupleTable =
1839 ExecCreateTupleTable(estate->es_tupleTable->size);
1841 ExecInitNode(epq->plan, epqstate, NULL);
1843 return EvalPlanQualNext(estate);
1846 static TupleTableSlot *
1847 EvalPlanQualNext(EState *estate)
1849 evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1850 EState *epqstate = &(epq->estate);
1851 evalPlanQual *oldepq;
1852 TupleTableSlot *slot;
1854 Assert(epq->rti != 0);
1857 slot = ExecProcNode(epq->plan, NULL);
1860 * No more tuples for this PQ. Continue previous one.
1862 if (TupIsNull(slot))
1864 /* stop execution */
1865 ExecEndNode(epq->plan, NULL);
1866 ExecDropTupleTable(epqstate->es_tupleTable, true);
1867 epqstate->es_tupleTable = NULL;
1868 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1869 epqstate->es_evTuple[epq->rti - 1] = NULL;
1870 /* pop old PQ from the stack */
1871 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1872 if (oldepq == (evalPlanQual *) NULL)
1874 epq->rti = 0; /* this is the first (oldest) */
1875 estate->es_useEvalPlan = false; /* PQ - mark as free and */
1876 return (NULL); /* continue Query execution */
1878 Assert(oldepq->rti != 0);
1879 /* push current PQ to freePQ stack */
1882 epqstate = &(epq->estate);
1883 estate->es_evalPlanQual = (Pointer) epq;
1891 EndEvalPlanQual(EState *estate)
1893 evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1894 EState *epqstate = &(epq->estate);
1895 evalPlanQual *oldepq;
1897 if (epq->rti == 0) /* plans already shutdowned */
1899 Assert(epq->estate.es_evalPlanQual == NULL);
1905 /* stop execution */
1906 ExecEndNode(epq->plan, NULL);
1907 ExecDropTupleTable(epqstate->es_tupleTable, true);
1908 epqstate->es_tupleTable = NULL;
1909 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1911 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1912 epqstate->es_evTuple[epq->rti - 1] = NULL;
1914 /* pop old PQ from the stack */
1915 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1916 if (oldepq == (evalPlanQual *) NULL)
1918 epq->rti = 0; /* this is the first (oldest) */
1919 estate->es_useEvalPlan = false; /* PQ - mark as free */
1922 Assert(oldepq->rti != 0);
1923 /* push current PQ to freePQ stack */
1926 epqstate = &(epq->estate);
1927 estate->es_evalPlanQual = (Pointer) epq;