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-2000, PostgreSQL, Inc
26 * Portions Copyright (c) 1994, Regents of the University of California
30 * $Header: /cvsroot/pgsql/src/backend/executor/execMain.c,v 1.134 2001/01/01 21:22:54 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 any execution of any
258 * returns (AttrInfo*) which describes the attributes of the tuples to
259 * be returned by the query.
261 * ----------------------------------------------------------------
264 ExecutorEnd(QueryDesc *queryDesc, EState *estate)
267 Assert(queryDesc != NULL);
269 EndPlan(queryDesc->plantree, estate);
271 /* XXX - clean up some more from ExecutorStart() - er1p */
272 if (NULL == estate->es_snapshot)
274 /* nothing to free */
278 if (estate->es_snapshot->xcnt > 0)
279 pfree(estate->es_snapshot->xip);
280 pfree(estate->es_snapshot);
283 if (NULL == estate->es_param_exec_vals)
285 /* nothing to free */
289 pfree(estate->es_param_exec_vals);
290 estate->es_param_exec_vals = NULL;
296 * ExecCheckQueryPerms
297 * Check access permissions for all relations referenced in a query.
300 ExecCheckQueryPerms(CmdType operation, Query *parseTree, Plan *plan)
303 * Check RTEs in the query's primary rangetable.
305 ExecCheckRTPerms(parseTree->rtable, operation);
308 * Search for subplans and APPEND nodes to check their rangetables.
310 ExecCheckPlanPerms(plan, parseTree->rtable, operation);
315 * Recursively scan the plan tree to check access permissions in
319 ExecCheckPlanPerms(Plan *plan, List *rangeTable, CmdType operation)
326 /* Check subplans, which we assume are plain SELECT queries */
328 foreach(subp, plan->initPlan)
330 SubPlan *subplan = (SubPlan *) lfirst(subp);
332 ExecCheckRTPerms(subplan->rtable, CMD_SELECT);
333 ExecCheckPlanPerms(subplan->plan, subplan->rtable, CMD_SELECT);
335 foreach(subp, plan->subPlan)
337 SubPlan *subplan = (SubPlan *) lfirst(subp);
339 ExecCheckRTPerms(subplan->rtable, CMD_SELECT);
340 ExecCheckPlanPerms(subplan->plan, subplan->rtable, CMD_SELECT);
343 /* Check lower plan nodes */
345 ExecCheckPlanPerms(plan->lefttree, rangeTable, operation);
346 ExecCheckPlanPerms(plan->righttree, rangeTable, operation);
348 /* Do node-type-specific checks */
350 switch (nodeTag(plan))
354 SubqueryScan *scan = (SubqueryScan *) plan;
357 /* Recursively check the subquery */
358 rte = rt_fetch(scan->scan.scanrelid, rangeTable);
359 Assert(rte->subquery != NULL);
360 ExecCheckQueryPerms(operation, rte->subquery, scan->subplan);
365 Append *app = (Append *) plan;
368 foreach(appendplans, app->appendplans)
370 ExecCheckPlanPerms((Plan *) lfirst(appendplans),
384 * Check access permissions for all relations listed in a range table.
387 ExecCheckRTPerms(List *rangeTable, CmdType operation)
391 foreach(lp, rangeTable)
393 RangeTblEntry *rte = lfirst(lp);
395 ExecCheckRTEPerms(rte, operation);
401 * Check access permissions for a single RTE.
404 ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation)
408 int32 aclcheck_result;
411 * If it's a subquery RTE, ignore it --- it will be checked when
412 * ExecCheckPlanPerms finds the SubqueryScan node for it.
417 relName = rte->relname;
420 * userid to check as: current user unless we have a setuid indication.
422 * Note: GetUserId() is presently fast enough that there's no harm
423 * in calling it separately for each RTE. If that stops being true,
424 * we could call it once in ExecCheckQueryPerms and pass the userid
425 * down from there. But for now, no need for the extra clutter.
427 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
429 #define CHECK(MODE) pg_aclcheck(relName, userid, MODE)
431 if (rte->checkForRead)
433 aclcheck_result = CHECK(ACL_RD);
434 if (aclcheck_result != ACLCHECK_OK)
435 elog(ERROR, "%s: %s",
436 relName, aclcheck_error_strings[aclcheck_result]);
439 if (rte->checkForWrite)
442 * Note: write access in a SELECT context means SELECT FOR UPDATE.
443 * Right now we don't distinguish that from true update as far as
444 * permissions checks are concerned.
449 /* Accept either APPEND or WRITE access for this */
450 aclcheck_result = CHECK(ACL_AP);
451 if (aclcheck_result != ACLCHECK_OK)
452 aclcheck_result = CHECK(ACL_WR);
457 aclcheck_result = CHECK(ACL_WR);
460 elog(ERROR, "ExecCheckRTEPerms: bogus operation %d",
462 aclcheck_result = ACLCHECK_OK; /* keep compiler quiet */
465 if (aclcheck_result != ACLCHECK_OK)
466 elog(ERROR, "%s: %s",
467 relName, aclcheck_error_strings[aclcheck_result]);
472 /* ===============================================================
473 * ===============================================================
474 static routines follow
475 * ===============================================================
476 * ===============================================================
479 typedef struct execRowMark
486 typedef struct evalPlanQual
491 struct evalPlanQual *free;
494 /* ----------------------------------------------------------------
497 * Initializes the query plan: open files, allocate storage
498 * and start up the rule manager
499 * ----------------------------------------------------------------
502 InitPlan(CmdType operation, Query *parseTree, Plan *plan, EState *estate)
505 Relation intoRelationDesc;
509 * Do permissions checks.
511 ExecCheckQueryPerms(operation, parseTree, plan);
514 * get information from query descriptor
516 rangeTable = parseTree->rtable;
519 * initialize the node's execution state
521 estate->es_range_table = rangeTable;
524 * if there is a result relation, initialize result relation stuff
526 if (parseTree->resultRelation != 0 && operation != CMD_SELECT)
528 List *resultRelations = parseTree->resultRelations;
529 int numResultRelations;
530 ResultRelInfo *resultRelInfos;
532 if (resultRelations != NIL)
535 * Multiple result relations (due to inheritance)
536 * parseTree->resultRelations identifies them all
538 ResultRelInfo *resultRelInfo;
540 numResultRelations = length(resultRelations);
541 resultRelInfos = (ResultRelInfo *)
542 palloc(numResultRelations * sizeof(ResultRelInfo));
543 resultRelInfo = resultRelInfos;
544 while (resultRelations != NIL)
546 initResultRelInfo(resultRelInfo,
547 lfirsti(resultRelations),
551 resultRelations = lnext(resultRelations);
557 * Single result relation identified by parseTree->resultRelation
559 numResultRelations = 1;
560 resultRelInfos = (ResultRelInfo *) palloc(sizeof(ResultRelInfo));
561 initResultRelInfo(resultRelInfos,
562 parseTree->resultRelation,
567 estate->es_result_relations = resultRelInfos;
568 estate->es_num_result_relations = numResultRelations;
569 /* Initialize to first or only result rel */
570 estate->es_result_relation_info = resultRelInfos;
575 * if no result relation, then set state appropriately
577 estate->es_result_relations = NULL;
578 estate->es_num_result_relations = 0;
579 estate->es_result_relation_info = NULL;
583 * Have to lock relations selected for update
585 estate->es_rowMark = NIL;
586 if (parseTree->rowMarks != NIL)
590 foreach(l, parseTree->rowMarks)
592 Index rti = lfirsti(l);
593 Oid relid = getrelid(rti, rangeTable);
597 relation = heap_open(relid, RowShareLock);
598 erm = (execRowMark *) palloc(sizeof(execRowMark));
599 erm->relation = relation;
601 sprintf(erm->resname, "ctid%u", rti);
602 estate->es_rowMark = lappend(estate->es_rowMark, erm);
607 * initialize the executor "tuple" table.
610 int nSlots = ExecCountSlotsNode(plan);
611 TupleTable tupleTable = ExecCreateTupleTable(nSlots + 10); /* why add ten? - jolly */
613 estate->es_tupleTable = tupleTable;
617 * initialize the private state information for all the nodes in the
618 * query tree. This opens files, allocates storage and leaves us
619 * ready to start processing tuples.
621 ExecInitNode(plan, estate, NULL);
624 * Get the tuple descriptor describing the type of tuples to return.
625 * (this is especially important if we are creating a relation with
628 tupType = ExecGetTupType(plan); /* tuple descriptor */
631 * Initialize the junk filter if needed. SELECT and INSERT queries need
632 * a filter if there are any junk attrs in the tlist. UPDATE and
633 * DELETE always need one, since there's always a junk 'ctid' attribute
634 * present --- no need to look first.
637 bool junk_filter_needed = false;
644 foreach(tlist, plan->targetlist)
646 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
648 if (tle->resdom->resjunk)
650 junk_filter_needed = true;
657 junk_filter_needed = true;
663 if (junk_filter_needed)
666 * If there are multiple result relations, each one needs
667 * its own junk filter. Note this is only possible for
668 * UPDATE/DELETE, so we can't be fooled by some needing
669 * a filter and some not.
671 if (parseTree->resultRelations != NIL)
674 ResultRelInfo *resultRelInfo;
676 /* Top plan had better be an Append here. */
677 Assert(IsA(plan, Append));
678 Assert(((Append *) plan)->isTarget);
679 subplans = ((Append *) plan)->appendplans;
680 Assert(length(subplans) == estate->es_num_result_relations);
681 resultRelInfo = estate->es_result_relations;
682 while (subplans != NIL)
684 Plan *subplan = (Plan *) lfirst(subplans);
687 j = ExecInitJunkFilter(subplan->targetlist,
688 ExecGetTupType(subplan));
689 resultRelInfo->ri_junkFilter = j;
691 subplans = lnext(subplans);
694 * Set active junkfilter too; at this point ExecInitAppend
695 * has already selected an active result relation...
697 estate->es_junkFilter =
698 estate->es_result_relation_info->ri_junkFilter;
702 /* Normal case with just one JunkFilter */
703 JunkFilter *j = ExecInitJunkFilter(plan->targetlist,
706 estate->es_junkFilter = j;
707 if (estate->es_result_relation_info)
708 estate->es_result_relation_info->ri_junkFilter = j;
710 /* For SELECT, want to return the cleaned tuple type */
711 if (operation == CMD_SELECT)
712 tupType = j->jf_cleanTupType;
716 estate->es_junkFilter = NULL;
720 * initialize the "into" relation
722 intoRelationDesc = (Relation) NULL;
724 if (operation == CMD_SELECT)
730 if (!parseTree->isPortal)
734 * a select into table
736 if (parseTree->into != NULL)
740 * create the "into" relation
742 intoName = parseTree->into;
745 * have to copy tupType to get rid of constraints
747 tupdesc = CreateTupleDescCopy(tupType);
750 heap_create_with_catalog(intoName,
754 allowSystemTableMods);
756 FreeTupleDesc(tupdesc);
759 * Advance command counter so that the newly-created
760 * relation's catalog tuples will be visible to heap_open.
762 CommandCounterIncrement();
765 * If necessary, create a TOAST table for the into relation.
766 * Note that AlterTableCreateToastTable ends with
767 * CommandCounterIncrement(), so that the TOAST table will
768 * be visible for insertion.
770 AlterTableCreateToastTable(intoName, true);
772 intoRelationDesc = heap_open(intoRelationId,
773 AccessExclusiveLock);
778 estate->es_into_relation_descriptor = intoRelationDesc;
780 estate->es_origPlan = plan;
781 estate->es_evalPlanQual = NULL;
782 estate->es_evTuple = NULL;
783 estate->es_useEvalPlan = false;
789 * Initialize ResultRelInfo data for one result relation
792 initResultRelInfo(ResultRelInfo *resultRelInfo,
793 Index resultRelationIndex,
797 Oid resultRelationOid;
798 Relation resultRelationDesc;
800 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
801 resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
803 switch (resultRelationDesc->rd_rel->relkind)
805 case RELKIND_SEQUENCE:
806 elog(ERROR, "You can't change sequence relation %s",
807 RelationGetRelationName(resultRelationDesc));
809 case RELKIND_TOASTVALUE:
810 elog(ERROR, "You can't change toast relation %s",
811 RelationGetRelationName(resultRelationDesc));
814 elog(ERROR, "You can't change view relation %s",
815 RelationGetRelationName(resultRelationDesc));
819 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
820 resultRelInfo->type = T_ResultRelInfo;
821 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
822 resultRelInfo->ri_RelationDesc = resultRelationDesc;
823 resultRelInfo->ri_NumIndices = 0;
824 resultRelInfo->ri_IndexRelationDescs = NULL;
825 resultRelInfo->ri_IndexRelationInfo = NULL;
826 resultRelInfo->ri_ConstraintExprs = NULL;
827 resultRelInfo->ri_junkFilter = NULL;
830 * If there are indices on the result relation, open them and save
831 * descriptors in the result relation info, so that we can add new
832 * index entries for the tuples we add/update. We need not do
833 * this for a DELETE, however, since deletion doesn't affect
836 if (resultRelationDesc->rd_rel->relhasindex &&
837 operation != CMD_DELETE)
838 ExecOpenIndices(resultRelInfo);
841 /* ----------------------------------------------------------------
844 * Cleans up the query plan -- closes files and free up storages
845 * ----------------------------------------------------------------
848 EndPlan(Plan *plan, EState *estate)
850 ResultRelInfo *resultRelInfo;
855 * shut down any PlanQual processing we were doing
857 if (estate->es_evalPlanQual != NULL)
858 EndEvalPlanQual(estate);
861 * shut down the node-type-specific query processing
863 ExecEndNode(plan, plan);
866 * destroy the executor "tuple" table.
868 ExecDropTupleTable(estate->es_tupleTable, true);
869 estate->es_tupleTable = NULL;
872 * close the result relation(s) if any, but hold locks
875 resultRelInfo = estate->es_result_relations;
876 for (i = estate->es_num_result_relations; i > 0; i--)
878 /* Close indices and then the relation itself */
879 ExecCloseIndices(resultRelInfo);
880 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
885 * close the "into" relation if necessary, again keeping lock
887 if (estate->es_into_relation_descriptor != NULL)
888 heap_close(estate->es_into_relation_descriptor, NoLock);
891 * close any relations selected FOR UPDATE, again keeping locks
893 foreach(l, estate->es_rowMark)
895 execRowMark *erm = lfirst(l);
897 heap_close(erm->relation, NoLock);
901 /* ----------------------------------------------------------------
904 * processes the query plan to retrieve 'numberTuples' tuples in the
905 * direction specified.
906 * Retrieves all tuples if tupleCount is 0
908 * result is either a slot containing the last tuple in the case
909 * of a RETRIEVE or NULL otherwise.
911 * Note: the ctid attribute is a 'junk' attribute that is removed before the
913 * ----------------------------------------------------------------
915 static TupleTableSlot *
916 ExecutePlan(EState *estate,
920 ScanDirection direction,
921 DestReceiver *destfunc)
923 JunkFilter *junkfilter;
924 TupleTableSlot *slot;
925 ItemPointer tupleid = NULL;
926 ItemPointerData tuple_ctid;
927 long current_tuple_count;
928 TupleTableSlot *result;
931 * initialize local variables
934 current_tuple_count = 0;
940 estate->es_direction = direction;
943 * Loop until we've processed the proper number of tuples from the
951 * Execute the plan and obtain a tuple
953 /* at the top level, the parent of a plan (2nd arg) is itself */
955 if (estate->es_useEvalPlan)
957 slot = EvalPlanQualNext(estate);
959 slot = ExecProcNode(plan, plan);
962 slot = ExecProcNode(plan, plan);
965 * if the tuple is null, then we assume there is nothing more to
966 * process so we just return null...
975 * if we have a junk filter, then project a new tuple with the
978 * Store this new "clean" tuple in the place of the original tuple.
980 * Also, extract all the junk information we need.
982 if ((junkfilter = estate->es_junkFilter) != (JunkFilter *) NULL)
989 * extract the 'ctid' junk attribute.
991 if (operation == CMD_UPDATE || operation == CMD_DELETE)
993 if (!ExecGetJunkAttribute(junkfilter,
998 elog(ERROR, "ExecutePlan: NO (junk) `ctid' was found!");
1000 /* shouldn't ever get a null result... */
1002 elog(ERROR, "ExecutePlan: (junk) `ctid' is NULL!");
1004 tupleid = (ItemPointer) DatumGetPointer(datum);
1005 tuple_ctid = *tupleid; /* make sure we don't free the
1007 tupleid = &tuple_ctid;
1009 else if (estate->es_rowMark != NIL)
1014 foreach(l, estate->es_rowMark)
1016 execRowMark *erm = lfirst(l);
1018 HeapTupleData tuple;
1019 TupleTableSlot *newSlot;
1022 if (!ExecGetJunkAttribute(junkfilter,
1027 elog(ERROR, "ExecutePlan: NO (junk) `%s' was found!",
1031 * Unlike the UPDATE/DELETE case, a null result is
1032 * possible here, when the referenced table is on the
1033 * nullable side of an outer join. Ignore nulls.
1038 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1039 test = heap_mark4update(erm->relation, &tuple, &buffer);
1040 ReleaseBuffer(buffer);
1043 case HeapTupleSelfUpdated:
1044 case HeapTupleMayBeUpdated:
1047 case HeapTupleUpdated:
1048 if (XactIsoLevel == XACT_SERIALIZABLE)
1049 elog(ERROR, "Can't serialize access due to concurrent update");
1050 if (!(ItemPointerEquals(&(tuple.t_self),
1051 (ItemPointer) DatumGetPointer(datum))))
1053 newSlot = EvalPlanQual(estate, erm->rti, &(tuple.t_self));
1054 if (!(TupIsNull(newSlot)))
1057 estate->es_useEvalPlan = true;
1063 * if tuple was deleted or PlanQual failed for
1064 * updated tuple - we have not return this
1070 elog(ERROR, "Unknown status %u from heap_mark4update", test);
1077 * Finally create a new "clean" tuple with all junk attributes
1080 newTuple = ExecRemoveJunk(junkfilter, slot);
1082 slot = ExecStoreTuple(newTuple, /* tuple to store */
1083 slot, /* destination slot */
1084 InvalidBuffer, /* this tuple has no
1086 true); /* tuple should be pfreed */
1087 } /* if (junkfilter... */
1090 * now that we have a tuple, do the appropriate thing with it..
1091 * either return it to the user, add it to a relation someplace,
1092 * delete it from a relation, or modify some of its attributes.
1098 ExecRetrieve(slot, /* slot containing tuple */
1099 destfunc, /* destination's tuple-receiver
1106 ExecAppend(slot, tupleid, estate);
1111 ExecDelete(slot, tupleid, estate);
1116 ExecReplace(slot, tupleid, estate);
1121 elog(DEBUG, "ExecutePlan: unknown operation in queryDesc");
1127 * check our tuple count.. if we've processed the proper number
1128 * then quit, else loop again and process more tuples..
1130 current_tuple_count++;
1131 if (numberTuples == current_tuple_count)
1136 * here, result is either a slot containing a tuple in the case of a
1137 * RETRIEVE or NULL otherwise.
1142 /* ----------------------------------------------------------------
1145 * RETRIEVEs are easy.. we just pass the tuple to the appropriate
1146 * print function. The only complexity is when we do a
1147 * "retrieve into", in which case we insert the tuple into
1148 * the appropriate relation (note: this is a newly created relation
1149 * so we don't need to worry about indices or locks.)
1150 * ----------------------------------------------------------------
1153 ExecRetrieve(TupleTableSlot *slot,
1154 DestReceiver *destfunc,
1161 * get the heap tuple out of the tuple table slot
1164 attrtype = slot->ttc_tupleDescriptor;
1167 * insert the tuple into the "into relation"
1169 if (estate->es_into_relation_descriptor != NULL)
1171 heap_insert(estate->es_into_relation_descriptor, tuple);
1176 * send the tuple to the front end (or the screen)
1178 (*destfunc->receiveTuple) (tuple, attrtype, destfunc);
1180 (estate->es_processed)++;
1183 /* ----------------------------------------------------------------
1186 * APPENDs are trickier.. we have to insert the tuple into
1187 * the base relation and insert appropriate tuples into the
1189 * ----------------------------------------------------------------
1193 ExecAppend(TupleTableSlot *slot,
1194 ItemPointer tupleid,
1198 ResultRelInfo *resultRelInfo;
1199 Relation resultRelationDesc;
1204 * get the heap tuple out of the tuple table slot
1209 * get information on the (current) result relation
1211 resultRelInfo = estate->es_result_relation_info;
1212 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1214 /* BEFORE ROW INSERT Triggers */
1215 if (resultRelationDesc->trigdesc &&
1216 resultRelationDesc->trigdesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1220 newtuple = ExecBRInsertTriggers(resultRelationDesc, tuple);
1222 if (newtuple == NULL) /* "do nothing" */
1225 if (newtuple != tuple) /* modified by Trigger(s) */
1227 Assert(slot->ttc_shouldFree);
1228 heap_freetuple(tuple);
1229 slot->val = tuple = newtuple;
1234 * Check the constraints of the tuple
1236 if (resultRelationDesc->rd_att->constr)
1237 ExecConstraints("ExecAppend", resultRelInfo, slot, estate);
1242 newId = heap_insert(resultRelationDesc, tuple);
1245 (estate->es_processed)++;
1246 estate->es_lastoid = newId;
1251 * Note: heap_insert adds a new tuple to a relation. As a side effect,
1252 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1255 numIndices = resultRelInfo->ri_NumIndices;
1257 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1259 /* AFTER ROW INSERT Triggers */
1260 if (resultRelationDesc->trigdesc)
1261 ExecARInsertTriggers(resultRelationDesc, tuple);
1264 /* ----------------------------------------------------------------
1267 * DELETE is like append, we delete the tuple and its
1269 * ----------------------------------------------------------------
1272 ExecDelete(TupleTableSlot *slot,
1273 ItemPointer tupleid,
1276 ResultRelInfo *resultRelInfo;
1277 Relation resultRelationDesc;
1278 ItemPointerData ctid;
1282 * get information on the (current) result relation
1284 resultRelInfo = estate->es_result_relation_info;
1285 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1287 /* BEFORE ROW DELETE Triggers */
1288 if (resultRelationDesc->trigdesc &&
1289 resultRelationDesc->trigdesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1293 dodelete = ExecBRDeleteTriggers(estate, tupleid);
1295 if (!dodelete) /* "do nothing" */
1303 result = heap_delete(resultRelationDesc, tupleid, &ctid);
1306 case HeapTupleSelfUpdated:
1309 case HeapTupleMayBeUpdated:
1312 case HeapTupleUpdated:
1313 if (XactIsoLevel == XACT_SERIALIZABLE)
1314 elog(ERROR, "Can't serialize access due to concurrent update");
1315 else if (!(ItemPointerEquals(tupleid, &ctid)))
1317 TupleTableSlot *epqslot = EvalPlanQual(estate,
1318 resultRelInfo->ri_RangeTableIndex, &ctid);
1320 if (!TupIsNull(epqslot))
1329 elog(ERROR, "Unknown status %u from heap_delete", result);
1334 (estate->es_processed)++;
1337 * Note: Normally one would think that we have to delete index tuples
1338 * associated with the heap tuple now..
1340 * ... but in POSTGRES, we have no need to do this because the vacuum
1341 * daemon automatically opens an index scan and deletes index tuples
1342 * when it finds deleted heap tuples. -cim 9/27/89
1345 /* AFTER ROW DELETE Triggers */
1346 if (resultRelationDesc->trigdesc)
1347 ExecARDeleteTriggers(estate, tupleid);
1351 /* ----------------------------------------------------------------
1354 * note: we can't run replace queries with transactions
1355 * off because replaces are actually appends and our
1356 * scan will mistakenly loop forever, replacing the tuple
1357 * it just appended.. This should be fixed but until it
1358 * is, we don't want to get stuck in an infinite loop
1359 * which corrupts your database..
1360 * ----------------------------------------------------------------
1363 ExecReplace(TupleTableSlot *slot,
1364 ItemPointer tupleid,
1368 ResultRelInfo *resultRelInfo;
1369 Relation resultRelationDesc;
1370 ItemPointerData ctid;
1375 * abort the operation if not running transactions
1377 if (IsBootstrapProcessingMode())
1379 elog(NOTICE, "ExecReplace: replace can't run without transactions");
1384 * get the heap tuple out of the tuple table slot
1389 * get information on the (current) result relation
1391 resultRelInfo = estate->es_result_relation_info;
1392 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1394 /* BEFORE ROW UPDATE Triggers */
1395 if (resultRelationDesc->trigdesc &&
1396 resultRelationDesc->trigdesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1400 newtuple = ExecBRUpdateTriggers(estate, tupleid, tuple);
1402 if (newtuple == NULL) /* "do nothing" */
1405 if (newtuple != tuple) /* modified by Trigger(s) */
1407 Assert(slot->ttc_shouldFree);
1408 heap_freetuple(tuple);
1409 slot->val = tuple = newtuple;
1414 * Check the constraints of the tuple
1416 if (resultRelationDesc->rd_att->constr)
1417 ExecConstraints("ExecReplace", resultRelInfo, slot, estate);
1420 * replace the heap tuple
1423 result = heap_update(resultRelationDesc, tupleid, tuple, &ctid);
1426 case HeapTupleSelfUpdated:
1429 case HeapTupleMayBeUpdated:
1432 case HeapTupleUpdated:
1433 if (XactIsoLevel == XACT_SERIALIZABLE)
1434 elog(ERROR, "Can't serialize access due to concurrent update");
1435 else if (!(ItemPointerEquals(tupleid, &ctid)))
1437 TupleTableSlot *epqslot = EvalPlanQual(estate,
1438 resultRelInfo->ri_RangeTableIndex, &ctid);
1440 if (!TupIsNull(epqslot))
1443 tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot);
1444 slot = ExecStoreTuple(tuple, slot, InvalidBuffer, true);
1451 elog(ERROR, "Unknown status %u from heap_update", result);
1456 (estate->es_processed)++;
1459 * Note: instead of having to update the old index tuples associated
1460 * with the heap tuple, all we do is form and insert new index
1461 * tuples. This is because replaces are actually deletes and inserts
1462 * and index tuple deletion is done automagically by the vacuum
1463 * daemon. All we do is insert new index tuples. -cim 9/27/89
1469 * heap_update updates a tuple in the base relation by invalidating it
1470 * and then appending a new tuple to the relation. As a side effect,
1471 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1472 * field. So we now insert index tuples using the new tupleid stored
1476 numIndices = resultRelInfo->ri_NumIndices;
1478 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, true);
1480 /* AFTER ROW UPDATE Triggers */
1481 if (resultRelationDesc->trigdesc)
1482 ExecARUpdateTriggers(estate, tupleid, tuple);
1486 ExecRelCheck(ResultRelInfo *resultRelInfo,
1487 TupleTableSlot *slot, EState *estate)
1489 Relation rel = resultRelInfo->ri_RelationDesc;
1490 int ncheck = rel->rd_att->constr->num_check;
1491 ConstrCheck *check = rel->rd_att->constr->check;
1492 ExprContext *econtext;
1493 MemoryContext oldContext;
1498 * If first time through for this result relation, build expression
1499 * nodetrees for rel's constraint expressions. Keep them in the
1500 * per-query memory context so they'll survive throughout the query.
1502 if (resultRelInfo->ri_ConstraintExprs == NULL)
1504 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1505 resultRelInfo->ri_ConstraintExprs =
1506 (List **) palloc(ncheck * sizeof(List *));
1507 for (i = 0; i < ncheck; i++)
1509 qual = (List *) stringToNode(check[i].ccbin);
1510 resultRelInfo->ri_ConstraintExprs[i] = qual;
1512 MemoryContextSwitchTo(oldContext);
1516 * We will use the EState's per-tuple context for evaluating constraint
1517 * expressions. Create it if it's not already there; if it is, reset it
1518 * to free previously-used storage.
1520 econtext = estate->es_per_tuple_exprcontext;
1521 if (econtext == NULL)
1523 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1524 estate->es_per_tuple_exprcontext = econtext =
1525 MakeExprContext(NULL, estate->es_query_cxt);
1526 MemoryContextSwitchTo(oldContext);
1529 ResetExprContext(econtext);
1531 /* Arrange for econtext's scan tuple to be the tuple under test */
1532 econtext->ecxt_scantuple = slot;
1534 /* And evaluate the constraints */
1535 for (i = 0; i < ncheck; i++)
1537 qual = resultRelInfo->ri_ConstraintExprs[i];
1540 * NOTE: SQL92 specifies that a NULL result from a constraint
1541 * expression is not to be treated as a failure. Therefore, tell
1542 * ExecQual to return TRUE for NULL.
1544 if (!ExecQual(qual, econtext, true))
1545 return check[i].ccname;
1548 /* NULL result means no error */
1549 return (char *) NULL;
1553 ExecConstraints(char *caller, ResultRelInfo *resultRelInfo,
1554 TupleTableSlot *slot, EState *estate)
1556 Relation rel = resultRelInfo->ri_RelationDesc;
1557 HeapTuple tuple = slot->val;
1558 TupleConstr *constr = rel->rd_att->constr;
1562 if (constr->has_not_null)
1564 int natts = rel->rd_att->natts;
1567 for (attrChk = 1; attrChk <= natts; attrChk++)
1569 if (rel->rd_att->attrs[attrChk-1]->attnotnull &&
1570 heap_attisnull(tuple, attrChk))
1571 elog(ERROR, "%s: Fail to add null value in not null attribute %s",
1572 caller, NameStr(rel->rd_att->attrs[attrChk-1]->attname));
1576 if (constr->num_check > 0)
1580 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1581 elog(ERROR, "%s: rejected due to CHECK constraint %s",
1587 EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
1589 evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1590 evalPlanQual *oldepq;
1591 EState *epqstate = NULL;
1594 HeapTupleData tuple;
1595 bool endNode = true;
1599 if (epq != NULL && epq->rti == 0)
1601 Assert(!(estate->es_useEvalPlan) &&
1602 epq->estate.es_evalPlanQual == NULL);
1608 * If this is request for another RTE - Ra, - then we have to check
1609 * wasn't PlanQual requested for Ra already and if so then Ra' row was
1610 * updated again and we have to re-start old execution for Ra and
1611 * forget all what we done after Ra was suspended. Cool? -:))
1613 if (epq != NULL && epq->rti != rti &&
1614 epq->estate.es_evTuple[rti - 1] != NULL)
1618 /* pop previous PlanQual from the stack */
1619 epqstate = &(epq->estate);
1620 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1621 Assert(oldepq->rti != 0);
1622 /* stop execution */
1623 ExecEndNode(epq->plan, epq->plan);
1624 epqstate->es_tupleTable->next = 0;
1625 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1626 epqstate->es_evTuple[epq->rti - 1] = NULL;
1627 /* push current PQ to freePQ stack */
1630 } while (epq->rti != rti);
1631 estate->es_evalPlanQual = (Pointer) epq;
1635 * If we are requested for another RTE then we have to suspend
1636 * execution of current PlanQual and start execution for new one.
1638 if (epq == NULL || epq->rti != rti)
1640 /* try to reuse plan used previously */
1641 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
1643 if (newepq == NULL) /* first call or freePQ stack is empty */
1645 newepq = (evalPlanQual *) palloc(sizeof(evalPlanQual));
1647 epqstate = &(newepq->estate);
1648 memset(epqstate, 0, sizeof(EState));
1649 epqstate->type = T_EState;
1650 epqstate->es_direction = ForwardScanDirection;
1651 epqstate->es_snapshot = estate->es_snapshot;
1652 epqstate->es_range_table = estate->es_range_table;
1653 epqstate->es_param_list_info = estate->es_param_list_info;
1654 if (estate->es_origPlan->nParamExec > 0)
1655 epqstate->es_param_exec_vals = (ParamExecData *)
1656 palloc(estate->es_origPlan->nParamExec *
1657 sizeof(ParamExecData));
1658 epqstate->es_tupleTable =
1659 ExecCreateTupleTable(estate->es_tupleTable->size);
1661 newepq->plan = copyObject(estate->es_origPlan);
1662 newepq->free = NULL;
1663 epqstate->es_evTupleNull = (bool *)
1664 palloc(length(estate->es_range_table) * sizeof(bool));
1665 if (epq == NULL) /* first call */
1667 epqstate->es_evTuple = (HeapTuple *)
1668 palloc(length(estate->es_range_table) * sizeof(HeapTuple));
1669 memset(epqstate->es_evTuple, 0,
1670 length(estate->es_range_table) * sizeof(HeapTuple));
1673 epqstate->es_evTuple = epq->estate.es_evTuple;
1676 epqstate = &(newepq->estate);
1677 /* push current PQ to the stack */
1678 epqstate->es_evalPlanQual = (Pointer) epq;
1680 estate->es_evalPlanQual = (Pointer) epq;
1685 epqstate = &(epq->estate);
1688 * Ok - we're requested for the same RTE (-:)). I'm not sure about
1689 * ability to use ExecReScan instead of ExecInitNode, so...
1693 ExecEndNode(epq->plan, epq->plan);
1694 epqstate->es_tupleTable->next = 0;
1697 /* free old RTE' tuple */
1698 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1700 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1701 epqstate->es_evTuple[epq->rti - 1] = NULL;
1704 /* ** fetch tid tuple ** */
1705 if (estate->es_result_relation_info != NULL &&
1706 estate->es_result_relation_info->ri_RangeTableIndex == rti)
1707 relation = estate->es_result_relation_info->ri_RelationDesc;
1712 foreach(l, estate->es_rowMark)
1714 if (((execRowMark *) lfirst(l))->rti == rti)
1717 relation = ((execRowMark *) lfirst(l))->relation;
1719 tuple.t_self = *tid;
1722 heap_fetch(relation, SnapshotDirty, &tuple, &buffer);
1723 if (tuple.t_data != NULL)
1725 TransactionId xwait = SnapshotDirty->xmax;
1727 if (TransactionIdIsValid(SnapshotDirty->xmin))
1729 elog(NOTICE, "EvalPlanQual: t_xmin is uncommitted ?!");
1730 Assert(!TransactionIdIsValid(SnapshotDirty->xmin));
1731 elog(ERROR, "Aborting this transaction");
1735 * If tuple is being updated by other transaction then we have
1736 * to wait for its commit/abort.
1738 if (TransactionIdIsValid(xwait))
1740 ReleaseBuffer(buffer);
1741 XactLockTableWait(xwait);
1746 * Nice! We got tuple - now copy it.
1748 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1749 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1750 epqstate->es_evTuple[epq->rti - 1] = heap_copytuple(&tuple);
1751 ReleaseBuffer(buffer);
1756 * Ops! Invalid tuple. Have to check is it updated or deleted.
1757 * Note that it's possible to get invalid SnapshotDirty->tid if
1758 * tuple updated by this transaction. Have we to check this ?
1760 if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
1761 !(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
1763 tuple.t_self = SnapshotDirty->tid; /* updated ... */
1768 * Deleted or updated by this transaction. Do not (re-)start
1769 * execution of this PQ. Continue previous PQ.
1771 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1774 Assert(oldepq->rti != 0);
1775 /* push current PQ to freePQ stack */
1778 epqstate = &(epq->estate);
1779 estate->es_evalPlanQual = (Pointer) epq;
1783 epq->rti = 0; /* this is the first (oldest) */
1784 estate->es_useEvalPlan = false; /* PQ - mark as free and */
1785 return (NULL); /* continue Query execution */
1789 if (estate->es_origPlan->nParamExec > 0)
1790 memset(epqstate->es_param_exec_vals, 0,
1791 estate->es_origPlan->nParamExec * sizeof(ParamExecData));
1792 memset(epqstate->es_evTupleNull, false,
1793 length(estate->es_range_table) * sizeof(bool));
1794 Assert(epqstate->es_tupleTable->next == 0);
1795 ExecInitNode(epq->plan, epqstate, NULL);
1798 * For UPDATE/DELETE we have to return tid of actual row we're
1801 *tid = tuple.t_self;
1803 return EvalPlanQualNext(estate);
1806 static TupleTableSlot *
1807 EvalPlanQualNext(EState *estate)
1809 evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1810 EState *epqstate = &(epq->estate);
1811 evalPlanQual *oldepq;
1812 TupleTableSlot *slot;
1814 Assert(epq->rti != 0);
1817 slot = ExecProcNode(epq->plan, epq->plan);
1820 * No more tuples for this PQ. Continue previous one.
1822 if (TupIsNull(slot))
1824 ExecEndNode(epq->plan, epq->plan);
1825 epqstate->es_tupleTable->next = 0;
1826 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1827 epqstate->es_evTuple[epq->rti - 1] = NULL;
1828 /* pop old PQ from the stack */
1829 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1830 if (oldepq == (evalPlanQual *) NULL)
1832 epq->rti = 0; /* this is the first (oldest) */
1833 estate->es_useEvalPlan = false; /* PQ - mark as free and */
1834 return (NULL); /* continue Query execution */
1836 Assert(oldepq->rti != 0);
1837 /* push current PQ to freePQ stack */
1840 epqstate = &(epq->estate);
1841 estate->es_evalPlanQual = (Pointer) epq;
1849 EndEvalPlanQual(EState *estate)
1851 evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1852 EState *epqstate = &(epq->estate);
1853 evalPlanQual *oldepq;
1855 if (epq->rti == 0) /* plans already shutdowned */
1857 Assert(epq->estate.es_evalPlanQual == NULL);
1863 ExecEndNode(epq->plan, epq->plan);
1864 epqstate->es_tupleTable->next = 0;
1865 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1867 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1868 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 */
1878 Assert(oldepq->rti != 0);
1879 /* push current PQ to freePQ stack */
1882 epqstate = &(epq->estate);
1883 estate->es_evalPlanQual = (Pointer) epq;