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 'feature' 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.138 2001/01/29 00:39:18 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"
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.
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,
143 /* ----------------------------------------------------------------
146 * This is the main routine of the executor module. It accepts
147 * the query descriptor from the traffic cop and executes the
150 * ExecutorStart must have been called already.
152 * the different features supported are:
153 * EXEC_RUN: retrieve all tuples in the forward direction
154 * EXEC_FOR: retrieve 'count' number of tuples in the forward dir
155 * EXEC_BACK: retrieve 'count' number of tuples in the backward dir
156 * EXEC_RETONE: return one tuple but don't 'retrieve' it
157 * used in postquel function processing
159 * Note: count = 0 is interpreted as "no limit".
161 * ----------------------------------------------------------------
164 ExecutorRun(QueryDesc *queryDesc, EState *estate, int feature, long count)
168 TupleTableSlot *result;
170 DestReceiver *destfunc;
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;
184 destfunc = DestToFunction(dest);
185 estate->es_processed = 0;
186 estate->es_lastoid = InvalidOid;
189 * FIXME: the dest setup function ought to be handed the tuple desc
190 * for the tuples to be output, but I'm not quite sure how to get that
191 * info at this point. For now, passing NULL is OK because no
192 * existing dest setup function actually uses the pointer.
194 (*destfunc->setup) (destfunc, (TupleDesc) NULL);
199 result = ExecutePlan(estate,
203 ForwardScanDirection,
208 result = ExecutePlan(estate,
212 ForwardScanDirection,
217 * retrieve next n "backward" tuples
220 result = ExecutePlan(estate,
224 BackwardScanDirection,
229 * return one tuple but don't "retrieve" it. (this is used by
230 * the rule manager..) -cim 9/14/89
233 result = ExecutePlan(estate,
237 ForwardScanDirection,
242 elog(DEBUG, "ExecutorRun: Unknown feature %d", feature);
247 (*destfunc->cleanup) (destfunc);
252 /* ----------------------------------------------------------------
255 * This routine must be called at the end of execution of any
257 * ----------------------------------------------------------------
260 ExecutorEnd(QueryDesc *queryDesc, EState *estate)
263 Assert(queryDesc != NULL);
265 EndPlan(queryDesc->plantree, estate);
267 if (estate->es_snapshot != NULL)
269 if (estate->es_snapshot->xcnt > 0)
270 pfree(estate->es_snapshot->xip);
271 pfree(estate->es_snapshot);
272 estate->es_snapshot = NULL;
275 if (estate->es_param_exec_vals != NULL)
277 pfree(estate->es_param_exec_vals);
278 estate->es_param_exec_vals = NULL;
284 * ExecCheckQueryPerms
285 * Check access permissions for all relations referenced in a query.
288 ExecCheckQueryPerms(CmdType operation, Query *parseTree, Plan *plan)
291 * Check RTEs in the query's primary rangetable.
293 ExecCheckRTPerms(parseTree->rtable, operation);
296 * Search for subplans and APPEND nodes to check their rangetables.
298 ExecCheckPlanPerms(plan, parseTree->rtable, operation);
303 * Recursively scan the plan tree to check access permissions in
307 ExecCheckPlanPerms(Plan *plan, List *rangeTable, CmdType operation)
314 /* Check subplans, which we assume are plain SELECT queries */
316 foreach(subp, plan->initPlan)
318 SubPlan *subplan = (SubPlan *) lfirst(subp);
320 ExecCheckRTPerms(subplan->rtable, CMD_SELECT);
321 ExecCheckPlanPerms(subplan->plan, subplan->rtable, CMD_SELECT);
323 foreach(subp, plan->subPlan)
325 SubPlan *subplan = (SubPlan *) lfirst(subp);
327 ExecCheckRTPerms(subplan->rtable, CMD_SELECT);
328 ExecCheckPlanPerms(subplan->plan, subplan->rtable, CMD_SELECT);
331 /* Check lower plan nodes */
333 ExecCheckPlanPerms(plan->lefttree, rangeTable, operation);
334 ExecCheckPlanPerms(plan->righttree, rangeTable, operation);
336 /* Do node-type-specific checks */
338 switch (nodeTag(plan))
342 SubqueryScan *scan = (SubqueryScan *) plan;
345 /* Recursively check the subquery */
346 rte = rt_fetch(scan->scan.scanrelid, rangeTable);
347 Assert(rte->subquery != NULL);
348 ExecCheckQueryPerms(operation, rte->subquery, scan->subplan);
353 Append *app = (Append *) plan;
356 foreach(appendplans, app->appendplans)
358 ExecCheckPlanPerms((Plan *) lfirst(appendplans),
372 * Check access permissions for all relations listed in a range table.
375 ExecCheckRTPerms(List *rangeTable, CmdType operation)
379 foreach(lp, rangeTable)
381 RangeTblEntry *rte = lfirst(lp);
383 ExecCheckRTEPerms(rte, operation);
389 * Check access permissions for a single RTE.
392 ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation)
396 int32 aclcheck_result;
399 * If it's a subquery RTE, ignore it --- it will be checked when
400 * ExecCheckPlanPerms finds the SubqueryScan node for it.
405 relName = rte->relname;
408 * userid to check as: current user unless we have a setuid indication.
410 * Note: GetUserId() is presently fast enough that there's no harm
411 * in calling it separately for each RTE. If that stops being true,
412 * we could call it once in ExecCheckQueryPerms and pass the userid
413 * down from there. But for now, no need for the extra clutter.
415 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
417 #define CHECK(MODE) pg_aclcheck(relName, userid, MODE)
419 if (rte->checkForRead)
421 aclcheck_result = CHECK(ACL_RD);
422 if (aclcheck_result != ACLCHECK_OK)
423 elog(ERROR, "%s: %s",
424 relName, aclcheck_error_strings[aclcheck_result]);
427 if (rte->checkForWrite)
430 * Note: write access in a SELECT context means SELECT FOR UPDATE.
431 * Right now we don't distinguish that from true update as far as
432 * permissions checks are concerned.
437 /* Accept either APPEND or WRITE access for this */
438 aclcheck_result = CHECK(ACL_AP);
439 if (aclcheck_result != ACLCHECK_OK)
440 aclcheck_result = CHECK(ACL_WR);
445 aclcheck_result = CHECK(ACL_WR);
448 elog(ERROR, "ExecCheckRTEPerms: bogus operation %d",
450 aclcheck_result = ACLCHECK_OK; /* keep compiler quiet */
453 if (aclcheck_result != ACLCHECK_OK)
454 elog(ERROR, "%s: %s",
455 relName, aclcheck_error_strings[aclcheck_result]);
460 /* ===============================================================
461 * ===============================================================
462 static routines follow
463 * ===============================================================
464 * ===============================================================
467 typedef struct execRowMark
474 typedef struct evalPlanQual
479 struct evalPlanQual *free;
482 /* ----------------------------------------------------------------
485 * Initializes the query plan: open files, allocate storage
486 * and start up the rule manager
487 * ----------------------------------------------------------------
490 InitPlan(CmdType operation, Query *parseTree, Plan *plan, EState *estate)
493 Relation intoRelationDesc;
497 * Do permissions checks.
499 ExecCheckQueryPerms(operation, parseTree, plan);
502 * get information from query descriptor
504 rangeTable = parseTree->rtable;
507 * initialize the node's execution state
509 estate->es_range_table = rangeTable;
512 * if there is a result relation, initialize result relation stuff
514 if (parseTree->resultRelation != 0 && operation != CMD_SELECT)
516 List *resultRelations = parseTree->resultRelations;
517 int numResultRelations;
518 ResultRelInfo *resultRelInfos;
520 if (resultRelations != NIL)
523 * Multiple result relations (due to inheritance)
524 * parseTree->resultRelations identifies them all
526 ResultRelInfo *resultRelInfo;
528 numResultRelations = length(resultRelations);
529 resultRelInfos = (ResultRelInfo *)
530 palloc(numResultRelations * sizeof(ResultRelInfo));
531 resultRelInfo = resultRelInfos;
532 while (resultRelations != NIL)
534 initResultRelInfo(resultRelInfo,
535 lfirsti(resultRelations),
539 resultRelations = lnext(resultRelations);
545 * Single result relation identified by parseTree->resultRelation
547 numResultRelations = 1;
548 resultRelInfos = (ResultRelInfo *) palloc(sizeof(ResultRelInfo));
549 initResultRelInfo(resultRelInfos,
550 parseTree->resultRelation,
555 estate->es_result_relations = resultRelInfos;
556 estate->es_num_result_relations = numResultRelations;
557 /* Initialize to first or only result rel */
558 estate->es_result_relation_info = resultRelInfos;
563 * if no result relation, then set state appropriately
565 estate->es_result_relations = NULL;
566 estate->es_num_result_relations = 0;
567 estate->es_result_relation_info = NULL;
571 * Have to lock relations selected for update
573 estate->es_rowMark = NIL;
574 if (parseTree->rowMarks != NIL)
578 foreach(l, parseTree->rowMarks)
580 Index rti = lfirsti(l);
581 Oid relid = getrelid(rti, rangeTable);
585 relation = heap_open(relid, RowShareLock);
586 erm = (execRowMark *) palloc(sizeof(execRowMark));
587 erm->relation = relation;
589 sprintf(erm->resname, "ctid%u", rti);
590 estate->es_rowMark = lappend(estate->es_rowMark, erm);
595 * initialize the executor "tuple" table.
598 int nSlots = ExecCountSlotsNode(plan);
599 TupleTable tupleTable = ExecCreateTupleTable(nSlots + 10); /* why add ten? - jolly */
601 estate->es_tupleTable = tupleTable;
605 * initialize the private state information for all the nodes in the
606 * query tree. This opens files, allocates storage and leaves us
607 * ready to start processing tuples.
609 ExecInitNode(plan, estate, NULL);
612 * Get the tuple descriptor describing the type of tuples to return.
613 * (this is especially important if we are creating a relation with
616 tupType = ExecGetTupType(plan); /* tuple descriptor */
619 * Initialize the junk filter if needed. SELECT and INSERT queries need
620 * a filter if there are any junk attrs in the tlist. UPDATE and
621 * DELETE always need one, since there's always a junk 'ctid' attribute
622 * present --- no need to look first.
625 bool junk_filter_needed = false;
632 foreach(tlist, plan->targetlist)
634 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
636 if (tle->resdom->resjunk)
638 junk_filter_needed = true;
645 junk_filter_needed = true;
651 if (junk_filter_needed)
654 * If there are multiple result relations, each one needs
655 * its own junk filter. Note this is only possible for
656 * UPDATE/DELETE, so we can't be fooled by some needing
657 * a filter and some not.
659 if (parseTree->resultRelations != NIL)
662 ResultRelInfo *resultRelInfo;
664 /* Top plan had better be an Append here. */
665 Assert(IsA(plan, Append));
666 Assert(((Append *) plan)->isTarget);
667 subplans = ((Append *) plan)->appendplans;
668 Assert(length(subplans) == estate->es_num_result_relations);
669 resultRelInfo = estate->es_result_relations;
670 while (subplans != NIL)
672 Plan *subplan = (Plan *) lfirst(subplans);
675 j = ExecInitJunkFilter(subplan->targetlist,
676 ExecGetTupType(subplan));
677 resultRelInfo->ri_junkFilter = j;
679 subplans = lnext(subplans);
682 * Set active junkfilter too; at this point ExecInitAppend
683 * has already selected an active result relation...
685 estate->es_junkFilter =
686 estate->es_result_relation_info->ri_junkFilter;
690 /* Normal case with just one JunkFilter */
691 JunkFilter *j = ExecInitJunkFilter(plan->targetlist,
694 estate->es_junkFilter = j;
695 if (estate->es_result_relation_info)
696 estate->es_result_relation_info->ri_junkFilter = j;
698 /* For SELECT, want to return the cleaned tuple type */
699 if (operation == CMD_SELECT)
700 tupType = j->jf_cleanTupType;
704 estate->es_junkFilter = NULL;
708 * initialize the "into" relation
710 intoRelationDesc = (Relation) NULL;
712 if (operation == CMD_SELECT)
718 if (!parseTree->isPortal)
722 * a select into table
724 if (parseTree->into != NULL)
728 * create the "into" relation
730 intoName = parseTree->into;
733 * have to copy tupType to get rid of constraints
735 tupdesc = CreateTupleDescCopy(tupType);
738 heap_create_with_catalog(intoName,
742 allowSystemTableMods);
744 FreeTupleDesc(tupdesc);
747 * Advance command counter so that the newly-created
748 * relation's catalog tuples will be visible to heap_open.
750 CommandCounterIncrement();
753 * If necessary, create a TOAST table for the into relation.
754 * Note that AlterTableCreateToastTable ends with
755 * CommandCounterIncrement(), so that the TOAST table will
756 * be visible for insertion.
758 AlterTableCreateToastTable(intoName, true);
760 intoRelationDesc = heap_open(intoRelationId,
761 AccessExclusiveLock);
766 estate->es_into_relation_descriptor = intoRelationDesc;
768 estate->es_origPlan = plan;
769 estate->es_evalPlanQual = NULL;
770 estate->es_evTuple = NULL;
771 estate->es_useEvalPlan = false;
777 * Initialize ResultRelInfo data for one result relation
780 initResultRelInfo(ResultRelInfo *resultRelInfo,
781 Index resultRelationIndex,
785 Oid resultRelationOid;
786 Relation resultRelationDesc;
788 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
789 resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
791 switch (resultRelationDesc->rd_rel->relkind)
793 case RELKIND_SEQUENCE:
794 elog(ERROR, "You can't change sequence relation %s",
795 RelationGetRelationName(resultRelationDesc));
797 case RELKIND_TOASTVALUE:
798 elog(ERROR, "You can't change toast relation %s",
799 RelationGetRelationName(resultRelationDesc));
802 elog(ERROR, "You can't change view relation %s",
803 RelationGetRelationName(resultRelationDesc));
807 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
808 resultRelInfo->type = T_ResultRelInfo;
809 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
810 resultRelInfo->ri_RelationDesc = resultRelationDesc;
811 resultRelInfo->ri_NumIndices = 0;
812 resultRelInfo->ri_IndexRelationDescs = NULL;
813 resultRelInfo->ri_IndexRelationInfo = NULL;
814 resultRelInfo->ri_ConstraintExprs = NULL;
815 resultRelInfo->ri_junkFilter = NULL;
818 * If there are indices on the result relation, open them and save
819 * descriptors in the result relation info, so that we can add new
820 * index entries for the tuples we add/update. We need not do
821 * this for a DELETE, however, since deletion doesn't affect
824 if (resultRelationDesc->rd_rel->relhasindex &&
825 operation != CMD_DELETE)
826 ExecOpenIndices(resultRelInfo);
829 /* ----------------------------------------------------------------
832 * Cleans up the query plan -- closes files and free up storages
833 * ----------------------------------------------------------------
836 EndPlan(Plan *plan, EState *estate)
838 ResultRelInfo *resultRelInfo;
843 * shut down any PlanQual processing we were doing
845 if (estate->es_evalPlanQual != NULL)
846 EndEvalPlanQual(estate);
849 * shut down the node-type-specific query processing
851 ExecEndNode(plan, plan);
854 * destroy the executor "tuple" table.
856 ExecDropTupleTable(estate->es_tupleTable, true);
857 estate->es_tupleTable = NULL;
860 * close the result relation(s) if any, but hold locks
861 * until xact commit. Also clean up junkfilters if present.
863 resultRelInfo = estate->es_result_relations;
864 for (i = estate->es_num_result_relations; i > 0; i--)
866 /* Close indices and then the relation itself */
867 ExecCloseIndices(resultRelInfo);
868 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
869 /* Delete the junkfilter if any */
870 if (resultRelInfo->ri_junkFilter != NULL)
871 ExecFreeJunkFilter(resultRelInfo->ri_junkFilter);
876 * close the "into" relation if necessary, again keeping lock
878 if (estate->es_into_relation_descriptor != NULL)
879 heap_close(estate->es_into_relation_descriptor, NoLock);
882 * There might be a junkfilter without a result relation.
884 if (estate->es_num_result_relations == 0 &&
885 estate->es_junkFilter != NULL)
887 ExecFreeJunkFilter(estate->es_junkFilter);
888 estate->es_junkFilter = NULL;
892 * close any relations selected FOR UPDATE, again keeping locks
894 foreach(l, estate->es_rowMark)
896 execRowMark *erm = lfirst(l);
898 heap_close(erm->relation, NoLock);
902 /* ----------------------------------------------------------------
905 * processes the query plan to retrieve 'numberTuples' tuples in the
906 * direction specified.
907 * Retrieves all tuples if tupleCount is 0
909 * result is either a slot containing the last tuple in the case
910 * of a RETRIEVE or NULL otherwise.
912 * Note: the ctid attribute is a 'junk' attribute that is removed before the
914 * ----------------------------------------------------------------
916 static TupleTableSlot *
917 ExecutePlan(EState *estate,
921 ScanDirection direction,
922 DestReceiver *destfunc)
924 JunkFilter *junkfilter;
925 TupleTableSlot *slot;
926 ItemPointer tupleid = NULL;
927 ItemPointerData tuple_ctid;
928 long current_tuple_count;
929 TupleTableSlot *result;
932 * initialize local variables
935 current_tuple_count = 0;
941 estate->es_direction = direction;
944 * Loop until we've processed the proper number of tuples from the
950 /* Reset the per-output-tuple exprcontext */
951 ResetPerTupleExprContext(estate);
954 * Execute the plan and obtain a tuple
956 /* at the top level, the parent of a plan (2nd arg) is itself */
958 if (estate->es_useEvalPlan)
960 slot = EvalPlanQualNext(estate);
962 slot = ExecProcNode(plan, plan);
965 slot = ExecProcNode(plan, plan);
968 * if the tuple is null, then we assume there is nothing more to
969 * process so we just return null...
978 * if we have a junk filter, then project a new tuple with the
981 * Store this new "clean" tuple in the place of the original tuple.
983 * Also, extract all the junk information we need.
985 if ((junkfilter = estate->es_junkFilter) != (JunkFilter *) NULL)
992 * extract the 'ctid' junk attribute.
994 if (operation == CMD_UPDATE || operation == CMD_DELETE)
996 if (!ExecGetJunkAttribute(junkfilter,
1001 elog(ERROR, "ExecutePlan: NO (junk) `ctid' was found!");
1003 /* shouldn't ever get a null result... */
1005 elog(ERROR, "ExecutePlan: (junk) `ctid' is NULL!");
1007 tupleid = (ItemPointer) DatumGetPointer(datum);
1008 tuple_ctid = *tupleid; /* make sure we don't free the
1010 tupleid = &tuple_ctid;
1012 else if (estate->es_rowMark != NIL)
1017 foreach(l, estate->es_rowMark)
1019 execRowMark *erm = lfirst(l);
1021 HeapTupleData tuple;
1022 TupleTableSlot *newSlot;
1025 if (!ExecGetJunkAttribute(junkfilter,
1030 elog(ERROR, "ExecutePlan: NO (junk) `%s' was found!",
1034 * Unlike the UPDATE/DELETE case, a null result is
1035 * possible here, when the referenced table is on the
1036 * nullable side of an outer join. Ignore nulls.
1041 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1042 test = heap_mark4update(erm->relation, &tuple, &buffer);
1043 ReleaseBuffer(buffer);
1046 case HeapTupleSelfUpdated:
1047 case HeapTupleMayBeUpdated:
1050 case HeapTupleUpdated:
1051 if (XactIsoLevel == XACT_SERIALIZABLE)
1052 elog(ERROR, "Can't serialize access due to concurrent update");
1053 if (!(ItemPointerEquals(&(tuple.t_self),
1054 (ItemPointer) DatumGetPointer(datum))))
1056 newSlot = EvalPlanQual(estate, erm->rti, &(tuple.t_self));
1057 if (!(TupIsNull(newSlot)))
1060 estate->es_useEvalPlan = true;
1066 * if tuple was deleted or PlanQual failed for
1067 * updated tuple - we have not return this
1073 elog(ERROR, "Unknown status %u from heap_mark4update", test);
1080 * Finally create a new "clean" tuple with all junk attributes
1083 newTuple = ExecRemoveJunk(junkfilter, slot);
1085 slot = ExecStoreTuple(newTuple, /* tuple to store */
1086 slot, /* destination slot */
1087 InvalidBuffer, /* this tuple has no
1089 true); /* tuple should be pfreed */
1090 } /* if (junkfilter... */
1093 * now that we have a tuple, do the appropriate thing with it..
1094 * either return it to the user, add it to a relation someplace,
1095 * delete it from a relation, or modify some of its attributes.
1101 ExecRetrieve(slot, /* slot containing tuple */
1102 destfunc, /* destination's tuple-receiver
1109 ExecAppend(slot, tupleid, estate);
1114 ExecDelete(slot, tupleid, estate);
1119 ExecReplace(slot, tupleid, estate);
1124 elog(DEBUG, "ExecutePlan: unknown operation in queryDesc");
1130 * check our tuple count.. if we've processed the proper number
1131 * then quit, else loop again and process more tuples..
1133 current_tuple_count++;
1134 if (numberTuples == current_tuple_count)
1139 * here, result is either a slot containing a tuple in the case of a
1140 * RETRIEVE or NULL otherwise.
1145 /* ----------------------------------------------------------------
1148 * RETRIEVEs are easy.. we just pass the tuple to the appropriate
1149 * print function. The only complexity is when we do a
1150 * "retrieve into", in which case we insert the tuple into
1151 * the appropriate relation (note: this is a newly created relation
1152 * so we don't need to worry about indices or locks.)
1153 * ----------------------------------------------------------------
1156 ExecRetrieve(TupleTableSlot *slot,
1157 DestReceiver *destfunc,
1164 * get the heap tuple out of the tuple table slot
1167 attrtype = slot->ttc_tupleDescriptor;
1170 * insert the tuple into the "into relation"
1172 if (estate->es_into_relation_descriptor != NULL)
1174 heap_insert(estate->es_into_relation_descriptor, tuple);
1179 * send the tuple to the front end (or the screen)
1181 (*destfunc->receiveTuple) (tuple, attrtype, destfunc);
1183 (estate->es_processed)++;
1186 /* ----------------------------------------------------------------
1189 * APPENDs are trickier.. we have to insert the tuple into
1190 * the base relation and insert appropriate tuples into the
1192 * ----------------------------------------------------------------
1196 ExecAppend(TupleTableSlot *slot,
1197 ItemPointer tupleid,
1201 ResultRelInfo *resultRelInfo;
1202 Relation resultRelationDesc;
1207 * get the heap tuple out of the tuple table slot
1212 * get information on the (current) result relation
1214 resultRelInfo = estate->es_result_relation_info;
1215 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1217 /* BEFORE ROW INSERT Triggers */
1218 if (resultRelationDesc->trigdesc &&
1219 resultRelationDesc->trigdesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1223 newtuple = ExecBRInsertTriggers(estate, resultRelationDesc, tuple);
1225 if (newtuple == NULL) /* "do nothing" */
1228 if (newtuple != tuple) /* modified by Trigger(s) */
1231 * Insert modified tuple into tuple table slot, replacing the
1232 * original. We assume that it was allocated in per-tuple
1233 * memory context, and therefore will go away by itself.
1234 * The tuple table slot should not try to clear it.
1236 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1242 * Check the constraints of the tuple
1244 if (resultRelationDesc->rd_att->constr)
1245 ExecConstraints("ExecAppend", resultRelInfo, slot, estate);
1250 newId = heap_insert(resultRelationDesc, tuple);
1253 (estate->es_processed)++;
1254 estate->es_lastoid = newId;
1259 * Note: heap_insert adds a new tuple to a relation. As a side effect,
1260 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1263 numIndices = resultRelInfo->ri_NumIndices;
1265 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1267 /* AFTER ROW INSERT Triggers */
1268 if (resultRelationDesc->trigdesc)
1269 ExecARInsertTriggers(estate, resultRelationDesc, tuple);
1272 /* ----------------------------------------------------------------
1275 * DELETE is like append, we delete the tuple and its
1277 * ----------------------------------------------------------------
1280 ExecDelete(TupleTableSlot *slot,
1281 ItemPointer tupleid,
1284 ResultRelInfo *resultRelInfo;
1285 Relation resultRelationDesc;
1286 ItemPointerData ctid;
1290 * get information on the (current) result relation
1292 resultRelInfo = estate->es_result_relation_info;
1293 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1295 /* BEFORE ROW DELETE Triggers */
1296 if (resultRelationDesc->trigdesc &&
1297 resultRelationDesc->trigdesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1301 dodelete = ExecBRDeleteTriggers(estate, tupleid);
1303 if (!dodelete) /* "do nothing" */
1311 result = heap_delete(resultRelationDesc, tupleid, &ctid);
1314 case HeapTupleSelfUpdated:
1317 case HeapTupleMayBeUpdated:
1320 case HeapTupleUpdated:
1321 if (XactIsoLevel == XACT_SERIALIZABLE)
1322 elog(ERROR, "Can't serialize access due to concurrent update");
1323 else if (!(ItemPointerEquals(tupleid, &ctid)))
1325 TupleTableSlot *epqslot = EvalPlanQual(estate,
1326 resultRelInfo->ri_RangeTableIndex, &ctid);
1328 if (!TupIsNull(epqslot))
1337 elog(ERROR, "Unknown status %u from heap_delete", result);
1342 (estate->es_processed)++;
1345 * Note: Normally one would think that we have to delete index tuples
1346 * associated with the heap tuple now..
1348 * ... but in POSTGRES, we have no need to do this because the vacuum
1349 * daemon automatically opens an index scan and deletes index tuples
1350 * when it finds deleted heap tuples. -cim 9/27/89
1353 /* AFTER ROW DELETE Triggers */
1354 if (resultRelationDesc->trigdesc)
1355 ExecARDeleteTriggers(estate, tupleid);
1358 /* ----------------------------------------------------------------
1361 * note: we can't run replace queries with transactions
1362 * off because replaces are actually appends and our
1363 * scan will mistakenly loop forever, replacing the tuple
1364 * it just appended.. This should be fixed but until it
1365 * is, we don't want to get stuck in an infinite loop
1366 * which corrupts your database..
1367 * ----------------------------------------------------------------
1370 ExecReplace(TupleTableSlot *slot,
1371 ItemPointer tupleid,
1375 ResultRelInfo *resultRelInfo;
1376 Relation resultRelationDesc;
1377 ItemPointerData ctid;
1382 * abort the operation if not running transactions
1384 if (IsBootstrapProcessingMode())
1386 elog(NOTICE, "ExecReplace: replace can't run without transactions");
1391 * get the heap tuple out of the tuple table slot
1396 * get information on the (current) result relation
1398 resultRelInfo = estate->es_result_relation_info;
1399 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1401 /* BEFORE ROW UPDATE Triggers */
1402 if (resultRelationDesc->trigdesc &&
1403 resultRelationDesc->trigdesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1407 newtuple = ExecBRUpdateTriggers(estate, tupleid, tuple);
1409 if (newtuple == NULL) /* "do nothing" */
1412 if (newtuple != tuple) /* modified by Trigger(s) */
1415 * Insert modified tuple into tuple table slot, replacing the
1416 * original. We assume that it was allocated in per-tuple
1417 * memory context, and therefore will go away by itself.
1418 * The tuple table slot should not try to clear it.
1420 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1426 * Check the constraints of the tuple
1428 if (resultRelationDesc->rd_att->constr)
1429 ExecConstraints("ExecReplace", resultRelInfo, slot, estate);
1432 * replace the heap tuple
1435 result = heap_update(resultRelationDesc, tupleid, tuple, &ctid);
1438 case HeapTupleSelfUpdated:
1441 case HeapTupleMayBeUpdated:
1444 case HeapTupleUpdated:
1445 if (XactIsoLevel == XACT_SERIALIZABLE)
1446 elog(ERROR, "Can't serialize access due to concurrent update");
1447 else if (!(ItemPointerEquals(tupleid, &ctid)))
1449 TupleTableSlot *epqslot = EvalPlanQual(estate,
1450 resultRelInfo->ri_RangeTableIndex, &ctid);
1452 if (!TupIsNull(epqslot))
1455 tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot);
1456 slot = ExecStoreTuple(tuple, slot, InvalidBuffer, true);
1463 elog(ERROR, "Unknown status %u from heap_update", result);
1468 (estate->es_processed)++;
1471 * Note: instead of having to update the old index tuples associated
1472 * with the heap tuple, all we do is form and insert new index
1473 * tuples. This is because replaces are actually deletes and inserts
1474 * and index tuple deletion is done automagically by the vacuum
1475 * daemon. All we do is insert new index tuples. -cim 9/27/89
1481 * heap_update updates a tuple in the base relation by invalidating it
1482 * and then appending a new tuple to the relation. As a side effect,
1483 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1484 * field. So we now insert index tuples using the new tupleid stored
1488 numIndices = resultRelInfo->ri_NumIndices;
1490 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, true);
1492 /* AFTER ROW UPDATE Triggers */
1493 if (resultRelationDesc->trigdesc)
1494 ExecARUpdateTriggers(estate, tupleid, tuple);
1498 ExecRelCheck(ResultRelInfo *resultRelInfo,
1499 TupleTableSlot *slot, EState *estate)
1501 Relation rel = resultRelInfo->ri_RelationDesc;
1502 int ncheck = rel->rd_att->constr->num_check;
1503 ConstrCheck *check = rel->rd_att->constr->check;
1504 ExprContext *econtext;
1505 MemoryContext oldContext;
1510 * If first time through for this result relation, build expression
1511 * nodetrees for rel's constraint expressions. Keep them in the
1512 * per-query memory context so they'll survive throughout the query.
1514 if (resultRelInfo->ri_ConstraintExprs == NULL)
1516 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1517 resultRelInfo->ri_ConstraintExprs =
1518 (List **) palloc(ncheck * sizeof(List *));
1519 for (i = 0; i < ncheck; i++)
1521 qual = (List *) stringToNode(check[i].ccbin);
1522 resultRelInfo->ri_ConstraintExprs[i] = qual;
1524 MemoryContextSwitchTo(oldContext);
1528 * We will use the EState's per-tuple context for evaluating constraint
1529 * expressions (creating it if it's not already there).
1531 econtext = GetPerTupleExprContext(estate);
1533 /* Arrange for econtext's scan tuple to be the tuple under test */
1534 econtext->ecxt_scantuple = slot;
1536 /* And evaluate the constraints */
1537 for (i = 0; i < ncheck; i++)
1539 qual = resultRelInfo->ri_ConstraintExprs[i];
1542 * NOTE: SQL92 specifies that a NULL result from a constraint
1543 * expression is not to be treated as a failure. Therefore, tell
1544 * ExecQual to return TRUE for NULL.
1546 if (!ExecQual(qual, econtext, true))
1547 return check[i].ccname;
1550 /* NULL result means no error */
1551 return (char *) NULL;
1555 ExecConstraints(char *caller, ResultRelInfo *resultRelInfo,
1556 TupleTableSlot *slot, EState *estate)
1558 Relation rel = resultRelInfo->ri_RelationDesc;
1559 HeapTuple tuple = slot->val;
1560 TupleConstr *constr = rel->rd_att->constr;
1564 if (constr->has_not_null)
1566 int natts = rel->rd_att->natts;
1569 for (attrChk = 1; attrChk <= natts; attrChk++)
1571 if (rel->rd_att->attrs[attrChk-1]->attnotnull &&
1572 heap_attisnull(tuple, attrChk))
1573 elog(ERROR, "%s: Fail to add null value in not null attribute %s",
1574 caller, NameStr(rel->rd_att->attrs[attrChk-1]->attname));
1578 if (constr->num_check > 0)
1582 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1583 elog(ERROR, "%s: rejected due to CHECK constraint %s",
1589 EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
1591 evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1592 evalPlanQual *oldepq;
1593 EState *epqstate = NULL;
1596 HeapTupleData tuple;
1597 bool endNode = true;
1601 if (epq != NULL && epq->rti == 0)
1603 Assert(!(estate->es_useEvalPlan) &&
1604 epq->estate.es_evalPlanQual == NULL);
1610 * If this is request for another RTE - Ra, - then we have to check
1611 * wasn't PlanQual requested for Ra already and if so then Ra' row was
1612 * updated again and we have to re-start old execution for Ra and
1613 * forget all what we done after Ra was suspended. Cool? -:))
1615 if (epq != NULL && epq->rti != rti &&
1616 epq->estate.es_evTuple[rti - 1] != NULL)
1620 /* pop previous PlanQual from the stack */
1621 epqstate = &(epq->estate);
1622 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1623 Assert(oldepq->rti != 0);
1624 /* stop execution */
1625 ExecEndNode(epq->plan, epq->plan);
1626 epqstate->es_tupleTable->next = 0;
1627 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1628 epqstate->es_evTuple[epq->rti - 1] = NULL;
1629 /* push current PQ to freePQ stack */
1632 } while (epq->rti != rti);
1633 estate->es_evalPlanQual = (Pointer) epq;
1637 * If we are requested for another RTE then we have to suspend
1638 * execution of current PlanQual and start execution for new one.
1640 if (epq == NULL || epq->rti != rti)
1642 /* try to reuse plan used previously */
1643 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
1645 if (newepq == NULL) /* first call or freePQ stack is empty */
1647 newepq = (evalPlanQual *) palloc(sizeof(evalPlanQual));
1649 epqstate = &(newepq->estate);
1650 memset(epqstate, 0, sizeof(EState));
1651 epqstate->type = T_EState;
1652 epqstate->es_direction = ForwardScanDirection;
1653 epqstate->es_snapshot = estate->es_snapshot;
1654 epqstate->es_range_table = estate->es_range_table;
1655 epqstate->es_param_list_info = estate->es_param_list_info;
1656 if (estate->es_origPlan->nParamExec > 0)
1657 epqstate->es_param_exec_vals = (ParamExecData *)
1658 palloc(estate->es_origPlan->nParamExec *
1659 sizeof(ParamExecData));
1660 epqstate->es_tupleTable =
1661 ExecCreateTupleTable(estate->es_tupleTable->size);
1663 newepq->plan = copyObject(estate->es_origPlan);
1664 newepq->free = NULL;
1665 epqstate->es_evTupleNull = (bool *)
1666 palloc(length(estate->es_range_table) * sizeof(bool));
1667 if (epq == NULL) /* first call */
1669 epqstate->es_evTuple = (HeapTuple *)
1670 palloc(length(estate->es_range_table) * sizeof(HeapTuple));
1671 memset(epqstate->es_evTuple, 0,
1672 length(estate->es_range_table) * sizeof(HeapTuple));
1675 epqstate->es_evTuple = epq->estate.es_evTuple;
1678 epqstate = &(newepq->estate);
1679 /* push current PQ to the stack */
1680 epqstate->es_evalPlanQual = (Pointer) epq;
1682 estate->es_evalPlanQual = (Pointer) epq;
1687 epqstate = &(epq->estate);
1690 * Ok - we're requested for the same RTE (-:)). I'm not sure about
1691 * ability to use ExecReScan instead of ExecInitNode, so...
1695 ExecEndNode(epq->plan, epq->plan);
1696 epqstate->es_tupleTable->next = 0;
1699 /* free old RTE' tuple */
1700 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1702 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1703 epqstate->es_evTuple[epq->rti - 1] = NULL;
1706 /* ** fetch tid tuple ** */
1707 if (estate->es_result_relation_info != NULL &&
1708 estate->es_result_relation_info->ri_RangeTableIndex == rti)
1709 relation = estate->es_result_relation_info->ri_RelationDesc;
1714 foreach(l, estate->es_rowMark)
1716 if (((execRowMark *) lfirst(l))->rti == rti)
1719 relation = ((execRowMark *) lfirst(l))->relation;
1721 tuple.t_self = *tid;
1724 heap_fetch(relation, SnapshotDirty, &tuple, &buffer);
1725 if (tuple.t_data != NULL)
1727 TransactionId xwait = SnapshotDirty->xmax;
1729 if (TransactionIdIsValid(SnapshotDirty->xmin))
1731 elog(NOTICE, "EvalPlanQual: t_xmin is uncommitted ?!");
1732 Assert(!TransactionIdIsValid(SnapshotDirty->xmin));
1733 elog(ERROR, "Aborting this transaction");
1737 * If tuple is being updated by other transaction then we have
1738 * to wait for its commit/abort.
1740 if (TransactionIdIsValid(xwait))
1742 ReleaseBuffer(buffer);
1743 XactLockTableWait(xwait);
1748 * Nice! We got tuple - now copy it.
1750 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1751 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1752 epqstate->es_evTuple[epq->rti - 1] = heap_copytuple(&tuple);
1753 ReleaseBuffer(buffer);
1758 * Ops! Invalid tuple. Have to check is it updated or deleted.
1759 * Note that it's possible to get invalid SnapshotDirty->tid if
1760 * tuple updated by this transaction. Have we to check this ?
1762 if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
1763 !(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
1765 tuple.t_self = SnapshotDirty->tid; /* updated ... */
1770 * Deleted or updated by this transaction. Do not (re-)start
1771 * execution of this PQ. Continue previous PQ.
1773 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1776 Assert(oldepq->rti != 0);
1777 /* push current PQ to freePQ stack */
1780 epqstate = &(epq->estate);
1781 estate->es_evalPlanQual = (Pointer) epq;
1785 epq->rti = 0; /* this is the first (oldest) */
1786 estate->es_useEvalPlan = false; /* PQ - mark as free and */
1787 return (NULL); /* continue Query execution */
1791 if (estate->es_origPlan->nParamExec > 0)
1792 memset(epqstate->es_param_exec_vals, 0,
1793 estate->es_origPlan->nParamExec * sizeof(ParamExecData));
1794 memset(epqstate->es_evTupleNull, false,
1795 length(estate->es_range_table) * sizeof(bool));
1796 Assert(epqstate->es_tupleTable->next == 0);
1797 ExecInitNode(epq->plan, epqstate, NULL);
1800 * For UPDATE/DELETE we have to return tid of actual row we're
1803 *tid = tuple.t_self;
1805 return EvalPlanQualNext(estate);
1808 static TupleTableSlot *
1809 EvalPlanQualNext(EState *estate)
1811 evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1812 EState *epqstate = &(epq->estate);
1813 evalPlanQual *oldepq;
1814 TupleTableSlot *slot;
1816 Assert(epq->rti != 0);
1819 slot = ExecProcNode(epq->plan, epq->plan);
1822 * No more tuples for this PQ. Continue previous one.
1824 if (TupIsNull(slot))
1826 ExecEndNode(epq->plan, epq->plan);
1827 epqstate->es_tupleTable->next = 0;
1828 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1829 epqstate->es_evTuple[epq->rti - 1] = NULL;
1830 /* pop old PQ from the stack */
1831 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1832 if (oldepq == (evalPlanQual *) NULL)
1834 epq->rti = 0; /* this is the first (oldest) */
1835 estate->es_useEvalPlan = false; /* PQ - mark as free and */
1836 return (NULL); /* continue Query execution */
1838 Assert(oldepq->rti != 0);
1839 /* push current PQ to freePQ stack */
1842 epqstate = &(epq->estate);
1843 estate->es_evalPlanQual = (Pointer) epq;
1851 EndEvalPlanQual(EState *estate)
1853 evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1854 EState *epqstate = &(epq->estate);
1855 evalPlanQual *oldepq;
1857 if (epq->rti == 0) /* plans already shutdowned */
1859 Assert(epq->estate.es_evalPlanQual == NULL);
1865 ExecEndNode(epq->plan, epq->plan);
1866 epqstate->es_tupleTable->next = 0;
1867 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1869 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1870 epqstate->es_evTuple[epq->rti - 1] = NULL;
1872 /* pop old PQ from the stack */
1873 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1874 if (oldepq == (evalPlanQual *) NULL)
1876 epq->rti = 0; /* this is the first (oldest) */
1877 estate->es_useEvalPlan = false; /* PQ - mark as free */
1880 Assert(oldepq->rti != 0);
1881 /* push current PQ to freePQ stack */
1884 epqstate = &(epq->estate);
1885 estate->es_evalPlanQual = (Pointer) epq;