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.155 2002/03/26 19:15:54 tgl Exp $
32 *-------------------------------------------------------------------------
36 #include "access/heapam.h"
37 #include "catalog/heap.h"
38 #include "catalog/namespace.h"
39 #include "commands/command.h"
40 #include "commands/trigger.h"
41 #include "executor/execdebug.h"
42 #include "executor/execdefs.h"
43 #include "miscadmin.h"
44 #include "optimizer/var.h"
45 #include "parser/parsetree.h"
46 #include "utils/acl.h"
47 #include "utils/lsyscache.h"
50 /* decls for local routines only used within this module */
51 static TupleDesc InitPlan(CmdType operation,
55 static void initResultRelInfo(ResultRelInfo *resultRelInfo,
56 Index resultRelationIndex,
59 static void EndPlan(Plan *plan, EState *estate);
60 static TupleTableSlot *ExecutePlan(EState *estate, Plan *plan,
63 ScanDirection direction,
64 DestReceiver *destfunc);
65 static void ExecRetrieve(TupleTableSlot *slot,
66 DestReceiver *destfunc,
68 static void ExecAppend(TupleTableSlot *slot, ItemPointer tupleid,
70 static void ExecDelete(TupleTableSlot *slot, ItemPointer tupleid,
72 static void ExecReplace(TupleTableSlot *slot, ItemPointer tupleid,
74 static TupleTableSlot *EvalPlanQualNext(EState *estate);
75 static void EndEvalPlanQual(EState *estate);
76 static void ExecCheckQueryPerms(CmdType operation, Query *parseTree,
78 static void ExecCheckPlanPerms(Plan *plan, List *rangeTable,
80 static void ExecCheckRTPerms(List *rangeTable, CmdType operation);
81 static void ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation);
83 /* end of local decls */
86 /* ----------------------------------------------------------------
89 * This routine must be called at the beginning of any execution of any
92 * returns a TupleDesc which describes the attributes of the tuples to
93 * be returned by the query. (Same value is saved in queryDesc)
95 * NB: the CurrentMemoryContext when this is called must be the context
96 * to be used as the per-query context for the query plan. ExecutorRun()
97 * and ExecutorEnd() must be called in this same memory context.
98 * ----------------------------------------------------------------
101 ExecutorStart(QueryDesc *queryDesc, EState *estate)
106 Assert(queryDesc != NULL);
108 if (queryDesc->plantree->nParamExec > 0)
110 estate->es_param_exec_vals = (ParamExecData *)
111 palloc(queryDesc->plantree->nParamExec * sizeof(ParamExecData));
112 MemSet(estate->es_param_exec_vals, 0,
113 queryDesc->plantree->nParamExec * sizeof(ParamExecData));
117 * Make our own private copy of the current queries snapshot data
119 if (QuerySnapshot == NULL)
120 estate->es_snapshot = NULL;
123 estate->es_snapshot = (Snapshot) palloc(sizeof(SnapshotData));
124 memcpy(estate->es_snapshot, QuerySnapshot, sizeof(SnapshotData));
125 if (estate->es_snapshot->xcnt > 0)
127 estate->es_snapshot->xip = (TransactionId *)
128 palloc(estate->es_snapshot->xcnt * sizeof(TransactionId));
129 memcpy(estate->es_snapshot->xip, QuerySnapshot->xip,
130 estate->es_snapshot->xcnt * sizeof(TransactionId));
135 * Initialize the plan
137 result = InitPlan(queryDesc->operation,
138 queryDesc->parsetree,
142 queryDesc->tupDesc = result;
147 /* ----------------------------------------------------------------
150 * This is the main routine of the executor module. It accepts
151 * the query descriptor from the traffic cop and executes the
154 * ExecutorStart must have been called already.
156 * If direction is NoMovementScanDirection then nothing is done
157 * except to start up/shut down the destination. Otherwise,
158 * we retrieve up to 'count' tuples in the specified direction.
160 * Note: count = 0 is interpreted as "no limit".
162 * ----------------------------------------------------------------
165 ExecutorRun(QueryDesc *queryDesc, EState *estate,
166 ScanDirection direction, long count)
171 DestReceiver *destfunc;
172 TupleTableSlot *result;
177 Assert(queryDesc != NULL);
180 * extract information from the query descriptor and the query
183 operation = queryDesc->operation;
184 plan = queryDesc->plantree;
185 dest = queryDesc->dest;
188 * startup tuple receiver
190 estate->es_processed = 0;
191 estate->es_lastoid = InvalidOid;
193 destfunc = DestToFunction(dest);
194 (*destfunc->setup) (destfunc, (int) operation,
195 queryDesc->portalName, queryDesc->tupDesc);
200 if (direction == NoMovementScanDirection)
203 result = ExecutePlan(estate,
213 (*destfunc->cleanup) (destfunc);
218 /* ----------------------------------------------------------------
221 * This routine must be called at the end of execution of any
223 * ----------------------------------------------------------------
226 ExecutorEnd(QueryDesc *queryDesc, EState *estate)
229 Assert(queryDesc != NULL);
231 EndPlan(queryDesc->plantree, estate);
233 if (estate->es_snapshot != NULL)
235 if (estate->es_snapshot->xcnt > 0)
236 pfree(estate->es_snapshot->xip);
237 pfree(estate->es_snapshot);
238 estate->es_snapshot = NULL;
241 if (estate->es_param_exec_vals != NULL)
243 pfree(estate->es_param_exec_vals);
244 estate->es_param_exec_vals = NULL;
250 * ExecCheckQueryPerms
251 * Check access permissions for all relations referenced in a query.
254 ExecCheckQueryPerms(CmdType operation, Query *parseTree, Plan *plan)
257 * Check RTEs in the query's primary rangetable.
259 ExecCheckRTPerms(parseTree->rtable, operation);
262 * Search for subplans and APPEND nodes to check their rangetables.
264 ExecCheckPlanPerms(plan, parseTree->rtable, operation);
269 * Recursively scan the plan tree to check access permissions in
273 ExecCheckPlanPerms(Plan *plan, List *rangeTable, CmdType operation)
280 /* Check subplans, which we assume are plain SELECT queries */
282 foreach(subp, plan->initPlan)
284 SubPlan *subplan = (SubPlan *) lfirst(subp);
286 ExecCheckRTPerms(subplan->rtable, CMD_SELECT);
287 ExecCheckPlanPerms(subplan->plan, subplan->rtable, CMD_SELECT);
289 foreach(subp, plan->subPlan)
291 SubPlan *subplan = (SubPlan *) lfirst(subp);
293 ExecCheckRTPerms(subplan->rtable, CMD_SELECT);
294 ExecCheckPlanPerms(subplan->plan, subplan->rtable, CMD_SELECT);
297 /* Check lower plan nodes */
299 ExecCheckPlanPerms(plan->lefttree, rangeTable, operation);
300 ExecCheckPlanPerms(plan->righttree, rangeTable, operation);
302 /* Do node-type-specific checks */
304 switch (nodeTag(plan))
308 SubqueryScan *scan = (SubqueryScan *) plan;
311 /* Recursively check the subquery */
312 rte = rt_fetch(scan->scan.scanrelid, rangeTable);
313 Assert(rte->subquery != NULL);
314 ExecCheckQueryPerms(operation, rte->subquery, scan->subplan);
319 Append *app = (Append *) plan;
322 foreach(appendplans, app->appendplans)
324 ExecCheckPlanPerms((Plan *) lfirst(appendplans),
338 * Check access permissions for all relations listed in a range table.
341 ExecCheckRTPerms(List *rangeTable, CmdType operation)
345 foreach(lp, rangeTable)
347 RangeTblEntry *rte = lfirst(lp);
349 ExecCheckRTEPerms(rte, operation);
355 * Check access permissions for a single RTE.
358 ExecCheckRTEPerms(RangeTblEntry *rte, CmdType operation)
362 int32 aclcheck_result;
365 * If it's a subquery RTE, ignore it --- it will be checked when
366 * ExecCheckPlanPerms finds the SubqueryScan node for it.
368 if (rte->rtekind != RTE_RELATION)
374 * userid to check as: current user unless we have a setuid
377 * Note: GetUserId() is presently fast enough that there's no harm in
378 * calling it separately for each RTE. If that stops being true, we
379 * could call it once in ExecCheckQueryPerms and pass the userid down
380 * from there. But for now, no need for the extra clutter.
382 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
384 #define CHECK(MODE) pg_class_aclcheck(relOid, userid, MODE)
386 if (rte->checkForRead)
388 aclcheck_result = CHECK(ACL_SELECT);
389 if (aclcheck_result != ACLCHECK_OK)
390 elog(ERROR, "%s: %s",
391 get_rel_name(relOid),
392 aclcheck_error_strings[aclcheck_result]);
395 if (rte->checkForWrite)
398 * Note: write access in a SELECT context means SELECT FOR UPDATE.
399 * Right now we don't distinguish that from true update as far as
400 * permissions checks are concerned.
405 aclcheck_result = CHECK(ACL_INSERT);
409 aclcheck_result = CHECK(ACL_UPDATE);
412 aclcheck_result = CHECK(ACL_DELETE);
415 elog(ERROR, "ExecCheckRTEPerms: bogus operation %d",
417 aclcheck_result = ACLCHECK_OK; /* keep compiler quiet */
420 if (aclcheck_result != ACLCHECK_OK)
421 elog(ERROR, "%s: %s",
422 get_rel_name(relOid),
423 aclcheck_error_strings[aclcheck_result]);
428 /* ===============================================================
429 * ===============================================================
430 static routines follow
431 * ===============================================================
432 * ===============================================================
435 typedef struct execRowMark
442 typedef struct evalPlanQual
447 struct evalPlanQual *free;
450 /* ----------------------------------------------------------------
453 * Initializes the query plan: open files, allocate storage
454 * and start up the rule manager
455 * ----------------------------------------------------------------
458 InitPlan(CmdType operation, Query *parseTree, Plan *plan, EState *estate)
461 Relation intoRelationDesc;
465 * Do permissions checks.
467 ExecCheckQueryPerms(operation, parseTree, plan);
470 * get information from query descriptor
472 rangeTable = parseTree->rtable;
475 * initialize the node's execution state
477 estate->es_range_table = rangeTable;
480 * if there is a result relation, initialize result relation stuff
482 if (parseTree->resultRelation != 0 && operation != CMD_SELECT)
484 List *resultRelations = parseTree->resultRelations;
485 int numResultRelations;
486 ResultRelInfo *resultRelInfos;
488 if (resultRelations != NIL)
491 * Multiple result relations (due to inheritance)
492 * parseTree->resultRelations identifies them all
494 ResultRelInfo *resultRelInfo;
496 numResultRelations = length(resultRelations);
497 resultRelInfos = (ResultRelInfo *)
498 palloc(numResultRelations * sizeof(ResultRelInfo));
499 resultRelInfo = resultRelInfos;
500 while (resultRelations != NIL)
502 initResultRelInfo(resultRelInfo,
503 lfirsti(resultRelations),
507 resultRelations = lnext(resultRelations);
513 * Single result relation identified by
514 * parseTree->resultRelation
516 numResultRelations = 1;
517 resultRelInfos = (ResultRelInfo *) palloc(sizeof(ResultRelInfo));
518 initResultRelInfo(resultRelInfos,
519 parseTree->resultRelation,
524 estate->es_result_relations = resultRelInfos;
525 estate->es_num_result_relations = numResultRelations;
526 /* Initialize to first or only result rel */
527 estate->es_result_relation_info = resultRelInfos;
532 * if no result relation, then set state appropriately
534 estate->es_result_relations = NULL;
535 estate->es_num_result_relations = 0;
536 estate->es_result_relation_info = NULL;
540 * Have to lock relations selected for update
542 estate->es_rowMark = NIL;
543 if (parseTree->rowMarks != NIL)
547 foreach(l, parseTree->rowMarks)
549 Index rti = lfirsti(l);
550 Oid relid = getrelid(rti, rangeTable);
554 relation = heap_open(relid, RowShareLock);
555 erm = (execRowMark *) palloc(sizeof(execRowMark));
556 erm->relation = relation;
558 sprintf(erm->resname, "ctid%u", rti);
559 estate->es_rowMark = lappend(estate->es_rowMark, erm);
564 * initialize the executor "tuple" table. We need slots for all the
565 * plan nodes, plus possibly output slots for the junkfilter(s). At
566 * this point we aren't sure if we need junkfilters, so just add slots
567 * for them unconditionally.
570 int nSlots = ExecCountSlotsNode(plan);
572 if (parseTree->resultRelations != NIL)
573 nSlots += length(parseTree->resultRelations);
576 estate->es_tupleTable = ExecCreateTupleTable(nSlots);
579 /* mark EvalPlanQual not active */
580 estate->es_origPlan = plan;
581 estate->es_evalPlanQual = NULL;
582 estate->es_evTuple = NULL;
583 estate->es_evTupleNull = NULL;
584 estate->es_useEvalPlan = false;
587 * initialize the private state information for all the nodes in the
588 * query tree. This opens files, allocates storage and leaves us
589 * ready to start processing tuples.
591 ExecInitNode(plan, estate, NULL);
594 * Get the tuple descriptor describing the type of tuples to return.
595 * (this is especially important if we are creating a relation with
598 tupType = ExecGetTupType(plan); /* tuple descriptor */
601 * Initialize the junk filter if needed. SELECT and INSERT queries
602 * need a filter if there are any junk attrs in the tlist. UPDATE and
603 * DELETE always need one, since there's always a junk 'ctid'
604 * attribute present --- no need to look first.
607 bool junk_filter_needed = false;
614 foreach(tlist, plan->targetlist)
616 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
618 if (tle->resdom->resjunk)
620 junk_filter_needed = true;
627 junk_filter_needed = true;
633 if (junk_filter_needed)
636 * If there are multiple result relations, each one needs its
637 * own junk filter. Note this is only possible for
638 * UPDATE/DELETE, so we can't be fooled by some needing a
639 * filter and some not.
641 if (parseTree->resultRelations != NIL)
644 ResultRelInfo *resultRelInfo;
646 /* Top plan had better be an Append here. */
647 Assert(IsA(plan, Append));
648 Assert(((Append *) plan)->isTarget);
649 subplans = ((Append *) plan)->appendplans;
650 Assert(length(subplans) == estate->es_num_result_relations);
651 resultRelInfo = estate->es_result_relations;
652 while (subplans != NIL)
654 Plan *subplan = (Plan *) lfirst(subplans);
657 j = ExecInitJunkFilter(subplan->targetlist,
658 ExecGetTupType(subplan),
659 ExecAllocTableSlot(estate->es_tupleTable));
660 resultRelInfo->ri_junkFilter = j;
662 subplans = lnext(subplans);
666 * Set active junkfilter too; at this point ExecInitAppend
667 * has already selected an active result relation...
669 estate->es_junkFilter =
670 estate->es_result_relation_info->ri_junkFilter;
674 /* Normal case with just one JunkFilter */
677 j = ExecInitJunkFilter(plan->targetlist,
679 ExecAllocTableSlot(estate->es_tupleTable));
680 estate->es_junkFilter = j;
681 if (estate->es_result_relation_info)
682 estate->es_result_relation_info->ri_junkFilter = j;
684 /* For SELECT, want to return the cleaned tuple type */
685 if (operation == CMD_SELECT)
686 tupType = j->jf_cleanTupType;
690 estate->es_junkFilter = NULL;
694 * initialize the "into" relation
696 intoRelationDesc = (Relation) NULL;
698 if (operation == CMD_SELECT)
700 if (!parseTree->isPortal)
703 * a select into table
705 if (parseTree->into != NULL)
713 * create the "into" relation
715 intoName = parseTree->into->relname;
716 namespaceId = RangeVarGetCreationNamespace(parseTree->into);
719 * have to copy tupType to get rid of constraints
721 tupdesc = CreateTupleDescCopy(tupType);
724 heap_create_with_catalog(intoName,
727 RELKIND_RELATION, true,
728 parseTree->into->istemp,
729 allowSystemTableMods);
731 FreeTupleDesc(tupdesc);
734 * Advance command counter so that the newly-created
735 * relation's catalog tuples will be visible to heap_open.
737 CommandCounterIncrement();
740 * If necessary, create a TOAST table for the into
741 * relation. Note that AlterTableCreateToastTable ends
742 * with CommandCounterIncrement(), so that the TOAST table
743 * will be visible for insertion.
745 AlterTableCreateToastTable(intoRelationId, true);
747 intoRelationDesc = heap_open(intoRelationId,
748 AccessExclusiveLock);
753 estate->es_into_relation_descriptor = intoRelationDesc;
759 * Initialize ResultRelInfo data for one result relation
762 initResultRelInfo(ResultRelInfo *resultRelInfo,
763 Index resultRelationIndex,
767 Oid resultRelationOid;
768 Relation resultRelationDesc;
770 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
771 resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
773 switch (resultRelationDesc->rd_rel->relkind)
775 case RELKIND_SEQUENCE:
776 elog(ERROR, "You can't change sequence relation %s",
777 RelationGetRelationName(resultRelationDesc));
779 case RELKIND_TOASTVALUE:
780 elog(ERROR, "You can't change toast relation %s",
781 RelationGetRelationName(resultRelationDesc));
784 elog(ERROR, "You can't change view relation %s",
785 RelationGetRelationName(resultRelationDesc));
789 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
790 resultRelInfo->type = T_ResultRelInfo;
791 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
792 resultRelInfo->ri_RelationDesc = resultRelationDesc;
793 resultRelInfo->ri_NumIndices = 0;
794 resultRelInfo->ri_IndexRelationDescs = NULL;
795 resultRelInfo->ri_IndexRelationInfo = NULL;
796 resultRelInfo->ri_TrigDesc = resultRelationDesc->trigdesc;
797 resultRelInfo->ri_TrigFunctions = NULL;
798 resultRelInfo->ri_ConstraintExprs = NULL;
799 resultRelInfo->ri_junkFilter = NULL;
802 * If there are indices on the result relation, open them and save
803 * descriptors in the result relation info, so that we can add new
804 * index entries for the tuples we add/update. We need not do this
805 * for a DELETE, however, since deletion doesn't affect indexes.
807 if (resultRelationDesc->rd_rel->relhasindex &&
808 operation != CMD_DELETE)
809 ExecOpenIndices(resultRelInfo);
812 /* ----------------------------------------------------------------
815 * Cleans up the query plan -- closes files and free up storages
816 * ----------------------------------------------------------------
819 EndPlan(Plan *plan, EState *estate)
821 ResultRelInfo *resultRelInfo;
826 * shut down any PlanQual processing we were doing
828 if (estate->es_evalPlanQual != NULL)
829 EndEvalPlanQual(estate);
832 * shut down the node-type-specific query processing
834 ExecEndNode(plan, NULL);
837 * destroy the executor "tuple" table.
839 ExecDropTupleTable(estate->es_tupleTable, true);
840 estate->es_tupleTable = NULL;
843 * close the result relation(s) if any, but hold locks until xact
844 * commit. Also clean up junkfilters if present.
846 resultRelInfo = estate->es_result_relations;
847 for (i = estate->es_num_result_relations; i > 0; i--)
849 /* Close indices and then the relation itself */
850 ExecCloseIndices(resultRelInfo);
851 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
852 /* Delete the junkfilter if any */
853 if (resultRelInfo->ri_junkFilter != NULL)
854 ExecFreeJunkFilter(resultRelInfo->ri_junkFilter);
859 * close the "into" relation if necessary, again keeping lock
861 if (estate->es_into_relation_descriptor != NULL)
862 heap_close(estate->es_into_relation_descriptor, NoLock);
865 * There might be a junkfilter without a result relation.
867 if (estate->es_num_result_relations == 0 &&
868 estate->es_junkFilter != NULL)
870 ExecFreeJunkFilter(estate->es_junkFilter);
871 estate->es_junkFilter = NULL;
875 * close any relations selected FOR UPDATE, again keeping locks
877 foreach(l, estate->es_rowMark)
879 execRowMark *erm = lfirst(l);
881 heap_close(erm->relation, NoLock);
885 /* ----------------------------------------------------------------
888 * processes the query plan to retrieve 'numberTuples' tuples in the
889 * direction specified.
890 * Retrieves all tuples if numberTuples is 0
892 * result is either a slot containing the last tuple in the case
893 * of a RETRIEVE or NULL otherwise.
895 * Note: the ctid attribute is a 'junk' attribute that is removed before the
897 * ----------------------------------------------------------------
899 static TupleTableSlot *
900 ExecutePlan(EState *estate,
904 ScanDirection direction,
905 DestReceiver *destfunc)
907 JunkFilter *junkfilter;
908 TupleTableSlot *slot;
909 ItemPointer tupleid = NULL;
910 ItemPointerData tuple_ctid;
911 long current_tuple_count;
912 TupleTableSlot *result;
915 * initialize local variables
918 current_tuple_count = 0;
924 estate->es_direction = direction;
927 * Loop until we've processed the proper number of tuples from the
933 /* Reset the per-output-tuple exprcontext */
934 ResetPerTupleExprContext(estate);
937 * Execute the plan and obtain a tuple
940 if (estate->es_useEvalPlan)
942 slot = EvalPlanQualNext(estate);
944 slot = ExecProcNode(plan, NULL);
947 slot = ExecProcNode(plan, NULL);
950 * if the tuple is null, then we assume there is nothing more to
951 * process so we just return null...
960 * if we have a junk filter, then project a new tuple with the
963 * Store this new "clean" tuple in the junkfilter's resultSlot.
964 * (Formerly, we stored it back over the "dirty" tuple, which is
965 * WRONG because that tuple slot has the wrong descriptor.)
967 * Also, extract all the junk information we need.
969 if ((junkfilter = estate->es_junkFilter) != (JunkFilter *) NULL)
976 * extract the 'ctid' junk attribute.
978 if (operation == CMD_UPDATE || operation == CMD_DELETE)
980 if (!ExecGetJunkAttribute(junkfilter,
985 elog(ERROR, "ExecutePlan: NO (junk) `ctid' was found!");
987 /* shouldn't ever get a null result... */
989 elog(ERROR, "ExecutePlan: (junk) `ctid' is NULL!");
991 tupleid = (ItemPointer) DatumGetPointer(datum);
992 tuple_ctid = *tupleid; /* make sure we don't free the
994 tupleid = &tuple_ctid;
996 else if (estate->es_rowMark != NIL)
1001 foreach(l, estate->es_rowMark)
1003 execRowMark *erm = lfirst(l);
1005 HeapTupleData tuple;
1006 TupleTableSlot *newSlot;
1009 if (!ExecGetJunkAttribute(junkfilter,
1014 elog(ERROR, "ExecutePlan: NO (junk) `%s' was found!",
1017 /* shouldn't ever get a null result... */
1019 elog(ERROR, "ExecutePlan: (junk) `%s' is NULL!",
1022 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1023 test = heap_mark4update(erm->relation, &tuple, &buffer);
1024 ReleaseBuffer(buffer);
1027 case HeapTupleSelfUpdated:
1028 case HeapTupleMayBeUpdated:
1031 case HeapTupleUpdated:
1032 if (XactIsoLevel == XACT_SERIALIZABLE)
1033 elog(ERROR, "Can't serialize access due to concurrent update");
1034 if (!(ItemPointerEquals(&(tuple.t_self),
1035 (ItemPointer) DatumGetPointer(datum))))
1037 newSlot = EvalPlanQual(estate, erm->rti, &(tuple.t_self));
1038 if (!(TupIsNull(newSlot)))
1041 estate->es_useEvalPlan = true;
1047 * if tuple was deleted or PlanQual failed for
1048 * updated tuple - we must not return this
1054 elog(ERROR, "Unknown status %u from heap_mark4update", test);
1061 * Finally create a new "clean" tuple with all junk attributes
1064 newTuple = ExecRemoveJunk(junkfilter, slot);
1066 slot = ExecStoreTuple(newTuple, /* tuple to store */
1067 junkfilter->jf_resultSlot, /* dest slot */
1068 InvalidBuffer, /* this tuple has no
1070 true); /* tuple should be pfreed */
1071 } /* if (junkfilter... */
1074 * now that we have a tuple, do the appropriate thing with it..
1075 * either return it to the user, add it to a relation someplace,
1076 * delete it from a relation, or modify some of its attributes.
1082 ExecRetrieve(slot, /* slot containing tuple */
1083 destfunc, /* destination's tuple-receiver
1090 ExecAppend(slot, tupleid, estate);
1095 ExecDelete(slot, tupleid, estate);
1100 ExecReplace(slot, tupleid, estate);
1105 elog(LOG, "ExecutePlan: unknown operation in queryDesc");
1111 * check our tuple count.. if we've processed the proper number
1112 * then quit, else loop again and process more tuples..
1114 current_tuple_count++;
1115 if (numberTuples == current_tuple_count)
1120 * here, result is either a slot containing a tuple in the case of a
1121 * RETRIEVE or NULL otherwise.
1126 /* ----------------------------------------------------------------
1129 * RETRIEVEs are easy.. we just pass the tuple to the appropriate
1130 * print function. The only complexity is when we do a
1131 * "retrieve into", in which case we insert the tuple into
1132 * the appropriate relation (note: this is a newly created relation
1133 * so we don't need to worry about indices or locks.)
1134 * ----------------------------------------------------------------
1137 ExecRetrieve(TupleTableSlot *slot,
1138 DestReceiver *destfunc,
1145 * get the heap tuple out of the tuple table slot
1148 attrtype = slot->ttc_tupleDescriptor;
1151 * insert the tuple into the "into relation"
1153 if (estate->es_into_relation_descriptor != NULL)
1155 heap_insert(estate->es_into_relation_descriptor, tuple);
1160 * send the tuple to the front end (or the screen)
1162 (*destfunc->receiveTuple) (tuple, attrtype, destfunc);
1164 (estate->es_processed)++;
1167 /* ----------------------------------------------------------------
1170 * APPENDs are trickier.. we have to insert the tuple into
1171 * the base relation and insert appropriate tuples into the
1173 * ----------------------------------------------------------------
1177 ExecAppend(TupleTableSlot *slot,
1178 ItemPointer tupleid,
1182 ResultRelInfo *resultRelInfo;
1183 Relation resultRelationDesc;
1188 * get the heap tuple out of the tuple table slot
1193 * get information on the (current) result relation
1195 resultRelInfo = estate->es_result_relation_info;
1196 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1198 /* BEFORE ROW INSERT Triggers */
1199 if (resultRelInfo->ri_TrigDesc &&
1200 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1204 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1206 if (newtuple == NULL) /* "do nothing" */
1209 if (newtuple != tuple) /* modified by Trigger(s) */
1212 * Insert modified tuple into tuple table slot, replacing the
1213 * original. We assume that it was allocated in per-tuple
1214 * memory context, and therefore will go away by itself. The
1215 * tuple table slot should not try to clear it.
1217 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1223 * Check the constraints of the tuple
1225 if (resultRelationDesc->rd_att->constr)
1226 ExecConstraints("ExecAppend", resultRelInfo, slot, estate);
1231 newId = heap_insert(resultRelationDesc, tuple);
1234 (estate->es_processed)++;
1235 estate->es_lastoid = newId;
1236 setLastTid(&(tuple->t_self));
1241 * Note: heap_insert adds a new tuple to a relation. As a side effect,
1242 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1245 numIndices = resultRelInfo->ri_NumIndices;
1247 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1249 /* AFTER ROW INSERT Triggers */
1250 if (resultRelInfo->ri_TrigDesc)
1251 ExecARInsertTriggers(estate, resultRelInfo, tuple);
1254 /* ----------------------------------------------------------------
1257 * DELETE is like append, we delete the tuple and its
1259 * ----------------------------------------------------------------
1262 ExecDelete(TupleTableSlot *slot,
1263 ItemPointer tupleid,
1266 ResultRelInfo *resultRelInfo;
1267 Relation resultRelationDesc;
1268 ItemPointerData ctid;
1272 * get information on the (current) result relation
1274 resultRelInfo = estate->es_result_relation_info;
1275 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1277 /* BEFORE ROW DELETE Triggers */
1278 if (resultRelInfo->ri_TrigDesc &&
1279 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1283 dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid);
1285 if (!dodelete) /* "do nothing" */
1293 result = heap_delete(resultRelationDesc, tupleid, &ctid);
1296 case HeapTupleSelfUpdated:
1299 case HeapTupleMayBeUpdated:
1302 case HeapTupleUpdated:
1303 if (XactIsoLevel == XACT_SERIALIZABLE)
1304 elog(ERROR, "Can't serialize access due to concurrent update");
1305 else if (!(ItemPointerEquals(tupleid, &ctid)))
1307 TupleTableSlot *epqslot = EvalPlanQual(estate,
1308 resultRelInfo->ri_RangeTableIndex, &ctid);
1310 if (!TupIsNull(epqslot))
1316 /* tuple already deleted; nothing to do */
1320 elog(ERROR, "Unknown status %u from heap_delete", result);
1325 (estate->es_processed)++;
1328 * Note: Normally one would think that we have to delete index tuples
1329 * associated with the heap tuple now..
1331 * ... but in POSTGRES, we have no need to do this because the vacuum
1332 * daemon automatically opens an index scan and deletes index tuples
1333 * when it finds deleted heap tuples. -cim 9/27/89
1336 /* AFTER ROW DELETE Triggers */
1337 if (resultRelInfo->ri_TrigDesc)
1338 ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1341 /* ----------------------------------------------------------------
1344 * note: we can't run replace queries with transactions
1345 * off because replaces are actually appends and our
1346 * scan will mistakenly loop forever, replacing the tuple
1347 * it just appended.. This should be fixed but until it
1348 * is, we don't want to get stuck in an infinite loop
1349 * which corrupts your database..
1350 * ----------------------------------------------------------------
1353 ExecReplace(TupleTableSlot *slot,
1354 ItemPointer tupleid,
1358 ResultRelInfo *resultRelInfo;
1359 Relation resultRelationDesc;
1360 ItemPointerData ctid;
1365 * abort the operation if not running transactions
1367 if (IsBootstrapProcessingMode())
1369 elog(WARNING, "ExecReplace: replace can't run without transactions");
1374 * get the heap tuple out of the tuple table slot
1379 * get information on the (current) result relation
1381 resultRelInfo = estate->es_result_relation_info;
1382 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1384 /* BEFORE ROW UPDATE Triggers */
1385 if (resultRelInfo->ri_TrigDesc &&
1386 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1390 newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
1393 if (newtuple == NULL) /* "do nothing" */
1396 if (newtuple != tuple) /* modified by Trigger(s) */
1399 * Insert modified tuple into tuple table slot, replacing the
1400 * original. We assume that it was allocated in per-tuple
1401 * memory context, and therefore will go away by itself. The
1402 * tuple table slot should not try to clear it.
1404 ExecStoreTuple(newtuple, slot, InvalidBuffer, false);
1410 * Check the constraints of the tuple
1412 * If we generate a new candidate tuple after EvalPlanQual testing, we
1413 * must loop back here and recheck constraints. (We don't need to
1414 * redo triggers, however. If there are any BEFORE triggers then
1415 * trigger.c will have done mark4update to lock the correct tuple, so
1416 * there's no need to do them again.)
1419 if (resultRelationDesc->rd_att->constr)
1420 ExecConstraints("ExecReplace", resultRelInfo, slot, estate);
1423 * replace the heap tuple
1425 result = heap_update(resultRelationDesc, tupleid, tuple, &ctid);
1428 case HeapTupleSelfUpdated:
1431 case HeapTupleMayBeUpdated:
1434 case HeapTupleUpdated:
1435 if (XactIsoLevel == XACT_SERIALIZABLE)
1436 elog(ERROR, "Can't serialize access due to concurrent update");
1437 else if (!(ItemPointerEquals(tupleid, &ctid)))
1439 TupleTableSlot *epqslot = EvalPlanQual(estate,
1440 resultRelInfo->ri_RangeTableIndex, &ctid);
1442 if (!TupIsNull(epqslot))
1445 tuple = ExecRemoveJunk(estate->es_junkFilter, epqslot);
1446 slot = ExecStoreTuple(tuple,
1447 estate->es_junkFilter->jf_resultSlot,
1448 InvalidBuffer, true);
1452 /* tuple already deleted; nothing to do */
1456 elog(ERROR, "Unknown status %u from heap_update", result);
1461 (estate->es_processed)++;
1464 * Note: instead of having to update the old index tuples associated
1465 * with the heap tuple, all we do is form and insert new index tuples.
1466 * This is because replaces are actually deletes and inserts and index
1467 * tuple deletion is done automagically by the vacuum daemon. All we
1468 * do is insert new index tuples. -cim 9/27/89
1474 * heap_update updates a tuple in the base relation by invalidating it
1475 * and then appending a new tuple to the relation. As a side effect,
1476 * the tupleid of the new tuple is placed in the new tuple's t_ctid
1477 * field. So we now insert index tuples using the new tupleid stored
1481 numIndices = resultRelInfo->ri_NumIndices;
1483 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, true);
1485 /* AFTER ROW UPDATE Triggers */
1486 if (resultRelInfo->ri_TrigDesc)
1487 ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
1491 ExecRelCheck(ResultRelInfo *resultRelInfo,
1492 TupleTableSlot *slot, EState *estate)
1494 Relation rel = resultRelInfo->ri_RelationDesc;
1495 int ncheck = rel->rd_att->constr->num_check;
1496 ConstrCheck *check = rel->rd_att->constr->check;
1497 ExprContext *econtext;
1498 MemoryContext oldContext;
1503 * If first time through for this result relation, build expression
1504 * nodetrees for rel's constraint expressions. Keep them in the
1505 * per-query memory context so they'll survive throughout the query.
1507 if (resultRelInfo->ri_ConstraintExprs == NULL)
1509 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1510 resultRelInfo->ri_ConstraintExprs =
1511 (List **) palloc(ncheck * sizeof(List *));
1512 for (i = 0; i < ncheck; i++)
1514 qual = (List *) stringToNode(check[i].ccbin);
1515 resultRelInfo->ri_ConstraintExprs[i] = qual;
1517 MemoryContextSwitchTo(oldContext);
1521 * We will use the EState's per-tuple context for evaluating
1522 * constraint expressions (creating it if it's not already there).
1524 econtext = GetPerTupleExprContext(estate);
1526 /* Arrange for econtext's scan tuple to be the tuple under test */
1527 econtext->ecxt_scantuple = slot;
1529 /* And evaluate the constraints */
1530 for (i = 0; i < ncheck; i++)
1532 qual = resultRelInfo->ri_ConstraintExprs[i];
1535 * NOTE: SQL92 specifies that a NULL result from a constraint
1536 * expression is not to be treated as a failure. Therefore, tell
1537 * ExecQual to return TRUE for NULL.
1539 if (!ExecQual(qual, econtext, true))
1540 return check[i].ccname;
1543 /* NULL result means no error */
1544 return (char *) NULL;
1548 ExecConstraints(char *caller, ResultRelInfo *resultRelInfo,
1549 TupleTableSlot *slot, EState *estate)
1551 Relation rel = resultRelInfo->ri_RelationDesc;
1552 HeapTuple tuple = slot->val;
1553 TupleConstr *constr = rel->rd_att->constr;
1557 if (constr->has_not_null)
1559 int natts = rel->rd_att->natts;
1562 for (attrChk = 1; attrChk <= natts; attrChk++)
1564 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1565 heap_attisnull(tuple, attrChk))
1566 elog(ERROR, "%s: Fail to add null value in not null attribute %s",
1567 caller, NameStr(rel->rd_att->attrs[attrChk - 1]->attname));
1571 if (constr->num_check > 0)
1575 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1576 elog(ERROR, "%s: rejected due to CHECK constraint %s",
1582 * Check a modified tuple to see if we want to process its updated version
1583 * under READ COMMITTED rules.
1585 * See backend/executor/README for some info about how this works.
1588 EvalPlanQual(EState *estate, Index rti, ItemPointer tid)
1593 HeapTupleData tuple;
1594 HeapTuple copyTuple = NULL;
1601 * find relation containing target tuple
1603 if (estate->es_result_relation_info != NULL &&
1604 estate->es_result_relation_info->ri_RangeTableIndex == rti)
1605 relation = estate->es_result_relation_info->ri_RelationDesc;
1611 foreach(l, estate->es_rowMark)
1613 if (((execRowMark *) lfirst(l))->rti == rti)
1615 relation = ((execRowMark *) lfirst(l))->relation;
1619 if (relation == NULL)
1620 elog(ERROR, "EvalPlanQual: can't find RTE %d", (int) rti);
1626 * Loop here to deal with updated or busy tuples
1628 tuple.t_self = *tid;
1633 heap_fetch(relation, SnapshotDirty, &tuple, &buffer, NULL);
1634 if (tuple.t_data != NULL)
1636 TransactionId xwait = SnapshotDirty->xmax;
1638 if (TransactionIdIsValid(SnapshotDirty->xmin))
1639 elog(ERROR, "EvalPlanQual: t_xmin is uncommitted ?!");
1642 * If tuple is being updated by other transaction then we have
1643 * to wait for its commit/abort.
1645 if (TransactionIdIsValid(xwait))
1647 ReleaseBuffer(buffer);
1648 XactLockTableWait(xwait);
1653 * We got tuple - now copy it for use by recheck query.
1655 copyTuple = heap_copytuple(&tuple);
1656 ReleaseBuffer(buffer);
1661 * Oops! Invalid tuple. Have to check is it updated or deleted.
1662 * Note that it's possible to get invalid SnapshotDirty->tid if
1663 * tuple updated by this transaction. Have we to check this ?
1665 if (ItemPointerIsValid(&(SnapshotDirty->tid)) &&
1666 !(ItemPointerEquals(&(tuple.t_self), &(SnapshotDirty->tid))))
1668 /* updated, so look at the updated copy */
1669 tuple.t_self = SnapshotDirty->tid;
1674 * Deleted or updated by this transaction; forget it.
1680 * For UPDATE/DELETE we have to return tid of actual row we're
1683 *tid = tuple.t_self;
1686 * Need to run a recheck subquery. Find or create a PQ stack entry.
1688 epq = (evalPlanQual *) estate->es_evalPlanQual;
1689 rtsize = length(estate->es_range_table);
1692 if (epq != NULL && epq->rti == 0)
1694 /* Top PQ stack entry is idle, so re-use it */
1695 Assert(!(estate->es_useEvalPlan) &&
1696 epq->estate.es_evalPlanQual == NULL);
1702 * If this is request for another RTE - Ra, - then we have to check
1703 * wasn't PlanQual requested for Ra already and if so then Ra' row was
1704 * updated again and we have to re-start old execution for Ra and
1705 * forget all what we done after Ra was suspended. Cool? -:))
1707 if (epq != NULL && epq->rti != rti &&
1708 epq->estate.es_evTuple[rti - 1] != NULL)
1712 evalPlanQual *oldepq;
1714 /* pop previous PlanQual from the stack */
1715 epqstate = &(epq->estate);
1716 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1717 Assert(oldepq->rti != 0);
1718 /* stop execution */
1719 ExecEndNode(epq->plan, NULL);
1720 ExecDropTupleTable(epqstate->es_tupleTable, true);
1721 epqstate->es_tupleTable = NULL;
1722 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1723 epqstate->es_evTuple[epq->rti - 1] = NULL;
1724 /* push current PQ to freePQ stack */
1727 estate->es_evalPlanQual = (Pointer) epq;
1728 } while (epq->rti != rti);
1732 * If we are requested for another RTE then we have to suspend
1733 * execution of current PlanQual and start execution for new one.
1735 if (epq == NULL || epq->rti != rti)
1737 /* try to reuse plan used previously */
1738 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
1740 if (newepq == NULL) /* first call or freePQ stack is empty */
1742 newepq = (evalPlanQual *) palloc(sizeof(evalPlanQual));
1743 newepq->free = NULL;
1746 * Each stack level has its own copy of the plan tree. This
1747 * is wasteful, but necessary as long as plan nodes point to
1748 * exec state nodes rather than vice versa. Note that
1749 * copyfuncs.c doesn't attempt to copy the exec state nodes,
1750 * which is a good thing in this situation.
1752 newepq->plan = copyObject(estate->es_origPlan);
1755 * Init stack level's EState. We share top level's copy of
1756 * es_result_relations array and other non-changing status. We
1757 * need our own tupletable, es_param_exec_vals, and other
1760 epqstate = &(newepq->estate);
1761 memcpy(epqstate, estate, sizeof(EState));
1762 epqstate->es_direction = ForwardScanDirection;
1763 if (estate->es_origPlan->nParamExec > 0)
1764 epqstate->es_param_exec_vals = (ParamExecData *)
1765 palloc(estate->es_origPlan->nParamExec *
1766 sizeof(ParamExecData));
1767 epqstate->es_tupleTable = NULL;
1768 epqstate->es_per_tuple_exprcontext = NULL;
1771 * Each epqstate must have its own es_evTupleNull state, but
1772 * all the stack entries share es_evTuple state. This allows
1773 * sub-rechecks to inherit the value being examined by an
1776 epqstate->es_evTupleNull = (bool *) palloc(rtsize * sizeof(bool));
1779 /* first PQ stack entry */
1780 epqstate->es_evTuple = (HeapTuple *)
1781 palloc(rtsize * sizeof(HeapTuple));
1782 memset(epqstate->es_evTuple, 0, rtsize * sizeof(HeapTuple));
1786 /* later stack entries share the same storage */
1787 epqstate->es_evTuple = epq->estate.es_evTuple;
1792 /* recycle previously used EState */
1793 epqstate = &(newepq->estate);
1795 /* push current PQ to the stack */
1796 epqstate->es_evalPlanQual = (Pointer) epq;
1798 estate->es_evalPlanQual = (Pointer) epq;
1803 Assert(epq->rti == rti);
1804 epqstate = &(epq->estate);
1807 * Ok - we're requested for the same RTE. Unfortunately we still have
1808 * to end and restart execution of the plan, because ExecReScan
1809 * wouldn't ensure that upper plan nodes would reset themselves. We
1810 * could make that work if insertion of the target tuple were
1811 * integrated with the Param mechanism somehow, so that the upper plan
1812 * nodes know that their children's outputs have changed.
1816 /* stop execution */
1817 ExecEndNode(epq->plan, NULL);
1818 ExecDropTupleTable(epqstate->es_tupleTable, true);
1819 epqstate->es_tupleTable = NULL;
1823 * free old RTE' tuple, if any, and store target tuple where
1824 * relation's scan node will see it
1826 if (epqstate->es_evTuple[rti - 1] != NULL)
1827 heap_freetuple(epqstate->es_evTuple[rti - 1]);
1828 epqstate->es_evTuple[rti - 1] = copyTuple;
1831 * Initialize for new recheck query; be careful to copy down state
1832 * that might have changed in top EState.
1834 epqstate->es_result_relation_info = estate->es_result_relation_info;
1835 epqstate->es_junkFilter = estate->es_junkFilter;
1836 if (estate->es_origPlan->nParamExec > 0)
1837 memset(epqstate->es_param_exec_vals, 0,
1838 estate->es_origPlan->nParamExec * sizeof(ParamExecData));
1839 memset(epqstate->es_evTupleNull, false, rtsize * sizeof(bool));
1840 epqstate->es_useEvalPlan = false;
1841 Assert(epqstate->es_tupleTable == NULL);
1842 epqstate->es_tupleTable =
1843 ExecCreateTupleTable(estate->es_tupleTable->size);
1845 ExecInitNode(epq->plan, epqstate, NULL);
1847 return EvalPlanQualNext(estate);
1850 static TupleTableSlot *
1851 EvalPlanQualNext(EState *estate)
1853 evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1854 EState *epqstate = &(epq->estate);
1855 evalPlanQual *oldepq;
1856 TupleTableSlot *slot;
1858 Assert(epq->rti != 0);
1861 slot = ExecProcNode(epq->plan, NULL);
1864 * No more tuples for this PQ. Continue previous one.
1866 if (TupIsNull(slot))
1868 /* stop execution */
1869 ExecEndNode(epq->plan, NULL);
1870 ExecDropTupleTable(epqstate->es_tupleTable, true);
1871 epqstate->es_tupleTable = NULL;
1872 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1873 epqstate->es_evTuple[epq->rti - 1] = NULL;
1874 /* pop old PQ from the stack */
1875 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1876 if (oldepq == (evalPlanQual *) NULL)
1878 epq->rti = 0; /* this is the first (oldest) */
1879 estate->es_useEvalPlan = false; /* PQ - mark as free and */
1880 return (NULL); /* continue Query execution */
1882 Assert(oldepq->rti != 0);
1883 /* push current PQ to freePQ stack */
1886 epqstate = &(epq->estate);
1887 estate->es_evalPlanQual = (Pointer) epq;
1895 EndEvalPlanQual(EState *estate)
1897 evalPlanQual *epq = (evalPlanQual *) estate->es_evalPlanQual;
1898 EState *epqstate = &(epq->estate);
1899 evalPlanQual *oldepq;
1901 if (epq->rti == 0) /* plans already shutdowned */
1903 Assert(epq->estate.es_evalPlanQual == NULL);
1909 /* stop execution */
1910 ExecEndNode(epq->plan, NULL);
1911 ExecDropTupleTable(epqstate->es_tupleTable, true);
1912 epqstate->es_tupleTable = NULL;
1913 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
1915 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
1916 epqstate->es_evTuple[epq->rti - 1] = NULL;
1918 /* pop old PQ from the stack */
1919 oldepq = (evalPlanQual *) epqstate->es_evalPlanQual;
1920 if (oldepq == (evalPlanQual *) NULL)
1922 epq->rti = 0; /* this is the first (oldest) */
1923 estate->es_useEvalPlan = false; /* PQ - mark as free */
1926 Assert(oldepq->rti != 0);
1927 /* push current PQ to freePQ stack */
1930 epqstate = &(epq->estate);
1931 estate->es_evalPlanQual = (Pointer) epq;