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 is required as an argument.
17 * ExecutorStart() must be called at the beginning of execution of any
18 * query plan and ExecutorEnd() should always be called at the end of
19 * execution of a plan.
21 * ExecutorRun accepts direction and count arguments that specify whether
22 * the plan is to be executed forwards, backwards, and for how many tuples.
24 * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
25 * Portions Copyright (c) 1994, Regents of the University of California
29 * $PostgreSQL: pgsql/src/backend/executor/execMain.c,v 1.286 2007/02/02 00:07:02 tgl Exp $
31 *-------------------------------------------------------------------------
35 #include "access/heapam.h"
36 #include "access/reloptions.h"
37 #include "access/transam.h"
38 #include "access/xact.h"
39 #include "catalog/heap.h"
40 #include "catalog/namespace.h"
41 #include "catalog/toasting.h"
42 #include "commands/tablespace.h"
43 #include "commands/trigger.h"
44 #include "executor/execdebug.h"
45 #include "executor/instrument.h"
46 #include "executor/nodeSubplan.h"
47 #include "miscadmin.h"
48 #include "optimizer/clauses.h"
49 #include "parser/parse_clause.h"
50 #include "parser/parsetree.h"
51 #include "storage/smgr.h"
52 #include "utils/acl.h"
53 #include "utils/lsyscache.h"
54 #include "utils/memutils.h"
57 typedef struct evalPlanQual
62 struct evalPlanQual *next; /* stack of active PlanQual plans */
63 struct evalPlanQual *free; /* list of free PlanQual plans */
66 /* decls for local routines only used within this module */
67 static void InitPlan(QueryDesc *queryDesc, int eflags);
68 static void initResultRelInfo(ResultRelInfo *resultRelInfo,
69 Index resultRelationIndex,
73 static TupleTableSlot *ExecutePlan(EState *estate, PlanState *planstate,
76 ScanDirection direction,
78 static void ExecSelect(TupleTableSlot *slot,
79 DestReceiver *dest, EState *estate);
80 static void ExecInsert(TupleTableSlot *slot, ItemPointer tupleid,
81 TupleTableSlot *planSlot,
82 DestReceiver *dest, EState *estate);
83 static void ExecDelete(ItemPointer tupleid,
84 TupleTableSlot *planSlot,
85 DestReceiver *dest, EState *estate);
86 static void ExecUpdate(TupleTableSlot *slot, ItemPointer tupleid,
87 TupleTableSlot *planSlot,
88 DestReceiver *dest, EState *estate);
89 static void ExecProcessReturning(ProjectionInfo *projectReturning,
90 TupleTableSlot *tupleSlot,
91 TupleTableSlot *planSlot,
93 static TupleTableSlot *EvalPlanQualNext(EState *estate);
94 static void EndEvalPlanQual(EState *estate);
95 static void ExecCheckRTEPerms(RangeTblEntry *rte);
96 static void ExecCheckXactReadOnly(Query *parsetree);
97 static void EvalPlanQualStart(evalPlanQual *epq, EState *estate,
98 evalPlanQual *priorepq);
99 static void EvalPlanQualStop(evalPlanQual *epq);
100 static void OpenIntoRel(QueryDesc *queryDesc);
101 static void CloseIntoRel(QueryDesc *queryDesc);
102 static void intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
103 static void intorel_receive(TupleTableSlot *slot, DestReceiver *self);
104 static void intorel_shutdown(DestReceiver *self);
105 static void intorel_destroy(DestReceiver *self);
107 /* end of local decls */
110 /* ----------------------------------------------------------------
113 * This routine must be called at the beginning of any execution of any
116 * Takes a QueryDesc previously created by CreateQueryDesc (it's not real
117 * clear why we bother to separate the two functions, but...). The tupDesc
118 * field of the QueryDesc is filled in to describe the tuples that will be
119 * returned, and the internal fields (estate and planstate) are set up.
121 * eflags contains flag bits as described in executor.h.
123 * NB: the CurrentMemoryContext when this is called will become the parent
124 * of the per-query context used for this Executor invocation.
125 * ----------------------------------------------------------------
128 ExecutorStart(QueryDesc *queryDesc, int eflags)
131 MemoryContext oldcontext;
133 /* sanity checks: queryDesc must not be started already */
134 Assert(queryDesc != NULL);
135 Assert(queryDesc->estate == NULL);
138 * If the transaction is read-only, we need to check if any writes are
139 * planned to non-temporary tables. EXPLAIN is considered read-only.
141 if (XactReadOnly && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
142 ExecCheckXactReadOnly(queryDesc->parsetree);
145 * Build EState, switch into per-query memory context for startup.
147 estate = CreateExecutorState();
148 queryDesc->estate = estate;
150 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
153 * Fill in parameters, if any, from queryDesc
155 estate->es_param_list_info = queryDesc->params;
157 if (queryDesc->plantree->nParamExec > 0)
158 estate->es_param_exec_vals = (ParamExecData *)
159 palloc0(queryDesc->plantree->nParamExec * sizeof(ParamExecData));
162 * Copy other important information into the EState
164 estate->es_snapshot = queryDesc->snapshot;
165 estate->es_crosscheck_snapshot = queryDesc->crosscheck_snapshot;
166 estate->es_instrument = queryDesc->doInstrument;
169 * Initialize the plan state tree
171 InitPlan(queryDesc, eflags);
173 MemoryContextSwitchTo(oldcontext);
176 /* ----------------------------------------------------------------
179 * This is the main routine of the executor module. It accepts
180 * the query descriptor from the traffic cop and executes the
183 * ExecutorStart must have been called already.
185 * If direction is NoMovementScanDirection then nothing is done
186 * except to start up/shut down the destination. Otherwise,
187 * we retrieve up to 'count' tuples in the specified direction.
189 * Note: count = 0 is interpreted as no portal limit, i.e., run to
192 * ----------------------------------------------------------------
195 ExecutorRun(QueryDesc *queryDesc,
196 ScanDirection direction, long count)
202 TupleTableSlot *result;
203 MemoryContext oldcontext;
206 Assert(queryDesc != NULL);
208 estate = queryDesc->estate;
210 Assert(estate != NULL);
213 * Switch into per-query memory context
215 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
218 * extract information from the query descriptor and the query feature.
220 operation = queryDesc->operation;
221 dest = queryDesc->dest;
224 * startup tuple receiver, if we will be emitting tuples
226 estate->es_processed = 0;
227 estate->es_lastoid = InvalidOid;
229 sendTuples = (operation == CMD_SELECT ||
230 queryDesc->parsetree->returningList);
233 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
238 if (ScanDirectionIsNoMovement(direction))
241 result = ExecutePlan(estate,
242 queryDesc->planstate,
249 * shutdown tuple receiver, if we started it
252 (*dest->rShutdown) (dest);
254 MemoryContextSwitchTo(oldcontext);
259 /* ----------------------------------------------------------------
262 * This routine must be called at the end of execution of any
264 * ----------------------------------------------------------------
267 ExecutorEnd(QueryDesc *queryDesc)
270 MemoryContext oldcontext;
273 Assert(queryDesc != NULL);
275 estate = queryDesc->estate;
277 Assert(estate != NULL);
280 * Switch into per-query memory context to run ExecEndPlan
282 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
284 ExecEndPlan(queryDesc->planstate, estate);
287 * Close the SELECT INTO relation if any
289 if (estate->es_select_into)
290 CloseIntoRel(queryDesc);
293 * Must switch out of context before destroying it
295 MemoryContextSwitchTo(oldcontext);
298 * Release EState and per-query memory context. This should release
299 * everything the executor has allocated.
301 FreeExecutorState(estate);
303 /* Reset queryDesc fields that no longer point to anything */
304 queryDesc->tupDesc = NULL;
305 queryDesc->estate = NULL;
306 queryDesc->planstate = NULL;
309 /* ----------------------------------------------------------------
312 * This routine may be called on an open queryDesc to rewind it
314 * ----------------------------------------------------------------
317 ExecutorRewind(QueryDesc *queryDesc)
320 MemoryContext oldcontext;
323 Assert(queryDesc != NULL);
325 estate = queryDesc->estate;
327 Assert(estate != NULL);
329 /* It's probably not sensible to rescan updating queries */
330 Assert(queryDesc->operation == CMD_SELECT);
333 * Switch into per-query memory context
335 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
340 ExecReScan(queryDesc->planstate, NULL);
342 MemoryContextSwitchTo(oldcontext);
348 * Check access permissions for all relations listed in a range table.
351 ExecCheckRTPerms(List *rangeTable)
355 foreach(l, rangeTable)
357 RangeTblEntry *rte = lfirst(l);
359 ExecCheckRTEPerms(rte);
365 * Check access permissions for a single RTE.
368 ExecCheckRTEPerms(RangeTblEntry *rte)
370 AclMode requiredPerms;
375 * Only plain-relation RTEs need to be checked here. Subquery RTEs are
376 * checked by ExecInitSubqueryScan if the subquery is still a separate
377 * subquery --- if it's been pulled up into our query level then the RTEs
378 * are in our rangetable and will be checked here. Function RTEs are
379 * checked by init_fcache when the function is prepared for execution.
380 * Join and special RTEs need no checks.
382 if (rte->rtekind != RTE_RELATION)
386 * No work if requiredPerms is empty.
388 requiredPerms = rte->requiredPerms;
389 if (requiredPerms == 0)
395 * userid to check as: current user unless we have a setuid indication.
397 * Note: GetUserId() is presently fast enough that there's no harm in
398 * calling it separately for each RTE. If that stops being true, we could
399 * call it once in ExecCheckRTPerms and pass the userid down from there.
400 * But for now, no need for the extra clutter.
402 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
405 * We must have *all* the requiredPerms bits, so use aclmask not aclcheck.
407 if (pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL)
409 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
410 get_rel_name(relOid));
414 * Check that the query does not imply any writes to non-temp tables.
417 ExecCheckXactReadOnly(Query *parsetree)
422 * CREATE TABLE AS or SELECT INTO?
424 * XXX should we allow this if the destination is temp?
426 if (parsetree->into != NULL)
429 /* Fail if write permissions are requested on any non-temp table */
430 foreach(l, parsetree->rtable)
432 RangeTblEntry *rte = lfirst(l);
434 if (rte->rtekind == RTE_SUBQUERY)
436 ExecCheckXactReadOnly(rte->subquery);
440 if (rte->rtekind != RTE_RELATION)
443 if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
446 if (isTempNamespace(get_rel_namespace(rte->relid)))
456 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
457 errmsg("transaction is read-only")));
461 /* ----------------------------------------------------------------
464 * Initializes the query plan: open files, allocate storage
465 * and start up the rule manager
466 * ----------------------------------------------------------------
469 InitPlan(QueryDesc *queryDesc, int eflags)
471 CmdType operation = queryDesc->operation;
472 Query *parseTree = queryDesc->parsetree;
473 Plan *plan = queryDesc->plantree;
474 EState *estate = queryDesc->estate;
475 PlanState *planstate;
481 * Do permissions checks. It's sufficient to examine the query's top
482 * rangetable here --- subplan RTEs will be checked during
485 ExecCheckRTPerms(parseTree->rtable);
488 * get information from query descriptor
490 rangeTable = parseTree->rtable;
493 * initialize the node's execution state
495 estate->es_range_table = rangeTable;
498 * if there is a result relation, initialize result relation stuff
500 if (parseTree->resultRelation)
502 List *resultRelations = parseTree->resultRelations;
503 int numResultRelations;
504 ResultRelInfo *resultRelInfos;
506 if (resultRelations != NIL)
509 * Multiple result relations (due to inheritance)
510 * parseTree->resultRelations identifies them all
512 ResultRelInfo *resultRelInfo;
514 numResultRelations = list_length(resultRelations);
515 resultRelInfos = (ResultRelInfo *)
516 palloc(numResultRelations * sizeof(ResultRelInfo));
517 resultRelInfo = resultRelInfos;
518 foreach(l, resultRelations)
520 initResultRelInfo(resultRelInfo,
524 estate->es_instrument);
531 * Single result relation identified by parseTree->resultRelation
533 numResultRelations = 1;
534 resultRelInfos = (ResultRelInfo *) palloc(sizeof(ResultRelInfo));
535 initResultRelInfo(resultRelInfos,
536 parseTree->resultRelation,
539 estate->es_instrument);
542 estate->es_result_relations = resultRelInfos;
543 estate->es_num_result_relations = numResultRelations;
544 /* Initialize to first or only result rel */
545 estate->es_result_relation_info = resultRelInfos;
550 * if no result relation, then set state appropriately
552 estate->es_result_relations = NULL;
553 estate->es_num_result_relations = 0;
554 estate->es_result_relation_info = NULL;
558 * Detect whether we're doing SELECT INTO. If so, set the es_into_oids
559 * flag appropriately so that the plan tree will be initialized with the
560 * correct tuple descriptors. (Other SELECT INTO stuff comes later.)
562 estate->es_select_into = false;
563 if (operation == CMD_SELECT && parseTree->into != NULL)
565 estate->es_select_into = true;
566 estate->es_into_oids = interpretOidsOption(parseTree->intoOptions);
570 * Have to lock relations selected FOR UPDATE/FOR SHARE before we
571 * initialize the plan tree, else we'd be doing a lock upgrade.
572 * While we are at it, build the ExecRowMark list.
574 estate->es_rowMarks = NIL;
575 foreach(l, parseTree->rowMarks)
577 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
578 Oid relid = getrelid(rc->rti, rangeTable);
582 relation = heap_open(relid, RowShareLock);
583 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
584 erm->relation = relation;
586 erm->forUpdate = rc->forUpdate;
587 erm->noWait = rc->noWait;
588 /* We'll set up ctidAttno below */
589 erm->ctidAttNo = InvalidAttrNumber;
590 estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
594 * initialize the executor "tuple" table. We need slots for all the plan
595 * nodes, plus possibly output slots for the junkfilter(s). At this point
596 * we aren't sure if we need junkfilters, so just add slots for them
597 * unconditionally. Also, if it's not a SELECT, set up a slot for use for
598 * trigger output tuples.
601 int nSlots = ExecCountSlotsNode(plan);
603 if (parseTree->resultRelations != NIL)
604 nSlots += list_length(parseTree->resultRelations);
607 if (operation != CMD_SELECT)
608 nSlots++; /* for es_trig_tuple_slot */
609 if (parseTree->returningLists)
610 nSlots++; /* for RETURNING projection */
612 estate->es_tupleTable = ExecCreateTupleTable(nSlots);
614 if (operation != CMD_SELECT)
615 estate->es_trig_tuple_slot =
616 ExecAllocTableSlot(estate->es_tupleTable);
619 /* mark EvalPlanQual not active */
620 estate->es_topPlan = plan;
621 estate->es_evalPlanQual = NULL;
622 estate->es_evTupleNull = NULL;
623 estate->es_evTuple = NULL;
624 estate->es_useEvalPlan = false;
627 * initialize the private state information for all the nodes in the query
628 * tree. This opens files, allocates storage and leaves us ready to start
631 planstate = ExecInitNode(plan, estate, eflags);
634 * Get the tuple descriptor describing the type of tuples to return. (this
635 * is especially important if we are creating a relation with "SELECT
638 tupType = ExecGetResultType(planstate);
641 * Initialize the junk filter if needed. SELECT and INSERT queries need a
642 * filter if there are any junk attrs in the tlist. INSERT and SELECT
643 * INTO also need a filter if the plan may return raw disk tuples (else
644 * heap_insert will be scribbling on the source relation!). UPDATE and
645 * DELETE always need a filter, since there's always a junk 'ctid'
646 * attribute present --- no need to look first.
649 bool junk_filter_needed = false;
656 foreach(tlist, plan->targetlist)
658 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
662 junk_filter_needed = true;
666 if (!junk_filter_needed &&
667 (operation == CMD_INSERT || estate->es_select_into) &&
668 ExecMayReturnRawTuples(planstate))
669 junk_filter_needed = true;
673 junk_filter_needed = true;
679 if (junk_filter_needed)
682 * If there are multiple result relations, each one needs its own
683 * junk filter. Note this is only possible for UPDATE/DELETE, so
684 * we can't be fooled by some needing a filter and some not.
686 if (parseTree->resultRelations != NIL)
688 PlanState **appendplans;
690 ResultRelInfo *resultRelInfo;
693 /* Top plan had better be an Append here. */
694 Assert(IsA(plan, Append));
695 Assert(((Append *) plan)->isTarget);
696 Assert(IsA(planstate, AppendState));
697 appendplans = ((AppendState *) planstate)->appendplans;
698 as_nplans = ((AppendState *) planstate)->as_nplans;
699 Assert(as_nplans == estate->es_num_result_relations);
700 resultRelInfo = estate->es_result_relations;
701 for (i = 0; i < as_nplans; i++)
703 PlanState *subplan = appendplans[i];
706 j = ExecInitJunkFilter(subplan->plan->targetlist,
707 resultRelInfo->ri_RelationDesc->rd_att->tdhasoid,
708 ExecAllocTableSlot(estate->es_tupleTable));
710 * Since it must be UPDATE/DELETE, there had better be
711 * a "ctid" junk attribute in the tlist ... but ctid could
712 * be at a different resno for each result relation.
713 * We look up the ctid resnos now and save them in the
716 j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
717 if (!AttributeNumberIsValid(j->jf_junkAttNo))
718 elog(ERROR, "could not find junk ctid column");
719 resultRelInfo->ri_junkFilter = j;
724 * Set active junkfilter too; at this point ExecInitAppend has
725 * already selected an active result relation...
727 estate->es_junkFilter =
728 estate->es_result_relation_info->ri_junkFilter;
732 /* Normal case with just one JunkFilter */
735 j = ExecInitJunkFilter(planstate->plan->targetlist,
737 ExecAllocTableSlot(estate->es_tupleTable));
738 estate->es_junkFilter = j;
739 if (estate->es_result_relation_info)
740 estate->es_result_relation_info->ri_junkFilter = j;
742 if (operation == CMD_SELECT)
744 /* For SELECT, want to return the cleaned tuple type */
745 tupType = j->jf_cleanTupType;
746 /* For SELECT FOR UPDATE/SHARE, find the ctid attrs now */
747 foreach(l, estate->es_rowMarks)
749 ExecRowMark *erm = (ExecRowMark *) lfirst(l);
752 snprintf(resname, sizeof(resname), "ctid%u", erm->rti);
753 erm->ctidAttNo = ExecFindJunkAttribute(j, resname);
754 if (!AttributeNumberIsValid(erm->ctidAttNo))
755 elog(ERROR, "could not find junk \"%s\" column",
759 else if (operation == CMD_UPDATE || operation == CMD_DELETE)
761 /* For UPDATE/DELETE, find the ctid junk attr now */
762 j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
763 if (!AttributeNumberIsValid(j->jf_junkAttNo))
764 elog(ERROR, "could not find junk ctid column");
769 estate->es_junkFilter = NULL;
773 * Initialize RETURNING projections if needed.
775 if (parseTree->returningLists)
777 TupleTableSlot *slot;
778 ExprContext *econtext;
779 ResultRelInfo *resultRelInfo;
782 * We set QueryDesc.tupDesc to be the RETURNING rowtype in this case.
783 * We assume all the sublists will generate the same output tupdesc.
785 tupType = ExecTypeFromTL((List *) linitial(parseTree->returningLists),
788 /* Set up a slot for the output of the RETURNING projection(s) */
789 slot = ExecAllocTableSlot(estate->es_tupleTable);
790 ExecSetSlotDescriptor(slot, tupType);
791 /* Need an econtext too */
792 econtext = CreateExprContext(estate);
795 * Build a projection for each result rel. Note that any SubPlans in
796 * the RETURNING lists get attached to the topmost plan node.
798 Assert(list_length(parseTree->returningLists) == estate->es_num_result_relations);
799 resultRelInfo = estate->es_result_relations;
800 foreach(l, parseTree->returningLists)
802 List *rlist = (List *) lfirst(l);
805 rliststate = (List *) ExecInitExpr((Expr *) rlist, planstate);
806 resultRelInfo->ri_projectReturning =
807 ExecBuildProjectionInfo(rliststate, econtext, slot,
808 resultRelInfo->ri_RelationDesc->rd_att);
813 * Because we already ran ExecInitNode() for the top plan node, any
814 * subplans we just attached to it won't have been initialized; so we
815 * have to do it here. (Ugly, but the alternatives seem worse.)
817 foreach(l, planstate->subPlan)
819 SubPlanState *sstate = (SubPlanState *) lfirst(l);
821 Assert(IsA(sstate, SubPlanState));
822 if (sstate->planstate == NULL) /* already inited? */
823 ExecInitSubPlan(sstate, estate, eflags);
827 queryDesc->tupDesc = tupType;
828 queryDesc->planstate = planstate;
831 * If doing SELECT INTO, initialize the "into" relation. We must wait
832 * till now so we have the "clean" result tuple type to create the new
835 * If EXPLAIN, skip creating the "into" relation.
837 if (estate->es_select_into && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
838 OpenIntoRel(queryDesc);
842 * Initialize ResultRelInfo data for one result relation
845 initResultRelInfo(ResultRelInfo *resultRelInfo,
846 Index resultRelationIndex,
851 Oid resultRelationOid;
852 Relation resultRelationDesc;
854 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
855 resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
857 switch (resultRelationDesc->rd_rel->relkind)
859 case RELKIND_SEQUENCE:
861 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
862 errmsg("cannot change sequence \"%s\"",
863 RelationGetRelationName(resultRelationDesc))));
865 case RELKIND_TOASTVALUE:
867 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
868 errmsg("cannot change TOAST relation \"%s\"",
869 RelationGetRelationName(resultRelationDesc))));
873 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
874 errmsg("cannot change view \"%s\"",
875 RelationGetRelationName(resultRelationDesc))));
879 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
880 resultRelInfo->type = T_ResultRelInfo;
881 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
882 resultRelInfo->ri_RelationDesc = resultRelationDesc;
883 resultRelInfo->ri_NumIndices = 0;
884 resultRelInfo->ri_IndexRelationDescs = NULL;
885 resultRelInfo->ri_IndexRelationInfo = NULL;
886 /* make a copy so as not to depend on relcache info not changing... */
887 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
888 if (resultRelInfo->ri_TrigDesc)
890 int n = resultRelInfo->ri_TrigDesc->numtriggers;
892 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
893 palloc0(n * sizeof(FmgrInfo));
895 resultRelInfo->ri_TrigInstrument = InstrAlloc(n);
897 resultRelInfo->ri_TrigInstrument = NULL;
901 resultRelInfo->ri_TrigFunctions = NULL;
902 resultRelInfo->ri_TrigInstrument = NULL;
904 resultRelInfo->ri_ConstraintExprs = NULL;
905 resultRelInfo->ri_junkFilter = NULL;
906 resultRelInfo->ri_projectReturning = NULL;
909 * If there are indices on the result relation, open them and save
910 * descriptors in the result relation info, so that we can add new index
911 * entries for the tuples we add/update. We need not do this for a
912 * DELETE, however, since deletion doesn't affect indexes.
914 if (resultRelationDesc->rd_rel->relhasindex &&
915 operation != CMD_DELETE)
916 ExecOpenIndices(resultRelInfo);
920 * ExecContextForcesOids
922 * This is pretty grotty: when doing INSERT, UPDATE, or SELECT INTO,
923 * we need to ensure that result tuples have space for an OID iff they are
924 * going to be stored into a relation that has OIDs. In other contexts
925 * we are free to choose whether to leave space for OIDs in result tuples
926 * (we generally don't want to, but we do if a physical-tlist optimization
927 * is possible). This routine checks the plan context and returns TRUE if the
928 * choice is forced, FALSE if the choice is not forced. In the TRUE case,
929 * *hasoids is set to the required value.
931 * One reason this is ugly is that all plan nodes in the plan tree will emit
932 * tuples with space for an OID, though we really only need the topmost node
933 * to do so. However, node types like Sort don't project new tuples but just
934 * return their inputs, and in those cases the requirement propagates down
935 * to the input node. Eventually we might make this code smart enough to
936 * recognize how far down the requirement really goes, but for now we just
937 * make all plan nodes do the same thing if the top level forces the choice.
939 * We assume that estate->es_result_relation_info is already set up to
940 * describe the target relation. Note that in an UPDATE that spans an
941 * inheritance tree, some of the target relations may have OIDs and some not.
942 * We have to make the decisions on a per-relation basis as we initialize
943 * each of the child plans of the topmost Append plan.
945 * SELECT INTO is even uglier, because we don't have the INTO relation's
946 * descriptor available when this code runs; we have to look aside at a
947 * flag set by InitPlan().
950 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
952 if (planstate->state->es_select_into)
954 *hasoids = planstate->state->es_into_oids;
959 ResultRelInfo *ri = planstate->state->es_result_relation_info;
963 Relation rel = ri->ri_RelationDesc;
967 *hasoids = rel->rd_rel->relhasoids;
976 /* ----------------------------------------------------------------
979 * Cleans up the query plan -- closes files and frees up storage
981 * NOTE: we are no longer very worried about freeing storage per se
982 * in this code; FreeExecutorState should be guaranteed to release all
983 * memory that needs to be released. What we are worried about doing
984 * is closing relations and dropping buffer pins. Thus, for example,
985 * tuple tables must be cleared or dropped to ensure pins are released.
986 * ----------------------------------------------------------------
989 ExecEndPlan(PlanState *planstate, EState *estate)
991 ResultRelInfo *resultRelInfo;
996 * shut down any PlanQual processing we were doing
998 if (estate->es_evalPlanQual != NULL)
999 EndEvalPlanQual(estate);
1002 * shut down the node-type-specific query processing
1004 ExecEndNode(planstate);
1007 * destroy the executor "tuple" table.
1009 ExecDropTupleTable(estate->es_tupleTable, true);
1010 estate->es_tupleTable = NULL;
1013 * close the result relation(s) if any, but hold locks until xact commit.
1015 resultRelInfo = estate->es_result_relations;
1016 for (i = estate->es_num_result_relations; i > 0; i--)
1018 /* Close indices and then the relation itself */
1019 ExecCloseIndices(resultRelInfo);
1020 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1025 * close any relations selected FOR UPDATE/FOR SHARE, again keeping locks
1027 foreach(l, estate->es_rowMarks)
1029 ExecRowMark *erm = lfirst(l);
1031 heap_close(erm->relation, NoLock);
1035 /* ----------------------------------------------------------------
1038 * processes the query plan to retrieve 'numberTuples' tuples in the
1039 * direction specified.
1041 * Retrieves all tuples if numberTuples is 0
1043 * result is either a slot containing the last tuple in the case
1044 * of a SELECT or NULL otherwise.
1046 * Note: the ctid attribute is a 'junk' attribute that is removed before the
1048 * ----------------------------------------------------------------
1050 static TupleTableSlot *
1051 ExecutePlan(EState *estate,
1052 PlanState *planstate,
1055 ScanDirection direction,
1058 JunkFilter *junkfilter;
1059 TupleTableSlot *planSlot;
1060 TupleTableSlot *slot;
1061 ItemPointer tupleid = NULL;
1062 ItemPointerData tuple_ctid;
1063 long current_tuple_count;
1064 TupleTableSlot *result;
1067 * initialize local variables
1069 current_tuple_count = 0;
1073 * Set the direction.
1075 estate->es_direction = direction;
1078 * Process BEFORE EACH STATEMENT triggers
1083 ExecBSUpdateTriggers(estate, estate->es_result_relation_info);
1086 ExecBSDeleteTriggers(estate, estate->es_result_relation_info);
1089 ExecBSInsertTriggers(estate, estate->es_result_relation_info);
1097 * Loop until we've processed the proper number of tuples from the plan.
1102 /* Reset the per-output-tuple exprcontext */
1103 ResetPerTupleExprContext(estate);
1106 * Execute the plan and obtain a tuple
1109 if (estate->es_useEvalPlan)
1111 planSlot = EvalPlanQualNext(estate);
1112 if (TupIsNull(planSlot))
1113 planSlot = ExecProcNode(planstate);
1116 planSlot = ExecProcNode(planstate);
1119 * if the tuple is null, then we assume there is nothing more to
1120 * process so we just return null...
1122 if (TupIsNull(planSlot))
1130 * if we have a junk filter, then project a new tuple with the junk
1133 * Store this new "clean" tuple in the junkfilter's resultSlot.
1134 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1135 * because that tuple slot has the wrong descriptor.)
1137 * Also, extract all the junk information we need.
1139 if ((junkfilter = estate->es_junkFilter) != NULL)
1145 * extract the 'ctid' junk attribute.
1147 if (operation == CMD_UPDATE || operation == CMD_DELETE)
1149 datum = ExecGetJunkAttribute(slot, junkfilter->jf_junkAttNo,
1151 /* shouldn't ever get a null result... */
1153 elog(ERROR, "ctid is NULL");
1155 tupleid = (ItemPointer) DatumGetPointer(datum);
1156 tuple_ctid = *tupleid; /* make sure we don't free the ctid!! */
1157 tupleid = &tuple_ctid;
1161 * Process any FOR UPDATE or FOR SHARE locking requested.
1163 else if (estate->es_rowMarks != NIL)
1168 foreach(l, estate->es_rowMarks)
1170 ExecRowMark *erm = lfirst(l);
1171 HeapTupleData tuple;
1173 ItemPointerData update_ctid;
1174 TransactionId update_xmax;
1175 TupleTableSlot *newSlot;
1176 LockTupleMode lockmode;
1179 datum = ExecGetJunkAttribute(slot,
1182 /* shouldn't ever get a null result... */
1184 elog(ERROR, "ctid is NULL");
1186 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1189 lockmode = LockTupleExclusive;
1191 lockmode = LockTupleShared;
1193 test = heap_lock_tuple(erm->relation, &tuple, &buffer,
1194 &update_ctid, &update_xmax,
1195 estate->es_snapshot->curcid,
1196 lockmode, erm->noWait);
1197 ReleaseBuffer(buffer);
1200 case HeapTupleSelfUpdated:
1201 /* treat it as deleted; do not process */
1204 case HeapTupleMayBeUpdated:
1207 case HeapTupleUpdated:
1208 if (IsXactIsoLevelSerializable)
1210 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1211 errmsg("could not serialize access due to concurrent update")));
1212 if (!ItemPointerEquals(&update_ctid,
1215 /* updated, so look at updated version */
1216 newSlot = EvalPlanQual(estate,
1220 estate->es_snapshot->curcid);
1221 if (!TupIsNull(newSlot))
1223 slot = planSlot = newSlot;
1224 estate->es_useEvalPlan = true;
1230 * if tuple was deleted or PlanQual failed for
1231 * updated tuple - we must not return this tuple!
1236 elog(ERROR, "unrecognized heap_lock_tuple status: %u",
1244 * Create a new "clean" tuple with all junk attributes removed. We
1245 * don't need to do this for DELETE, however (there will in fact
1246 * be no non-junk attributes in a DELETE!)
1248 if (operation != CMD_DELETE)
1249 slot = ExecFilterJunk(junkfilter, slot);
1253 * now that we have a tuple, do the appropriate thing with it.. either
1254 * return it to the user, add it to a relation someplace, delete it
1255 * from a relation, or modify some of its attributes.
1260 ExecSelect(slot, dest, estate);
1265 ExecInsert(slot, tupleid, planSlot, dest, estate);
1270 ExecDelete(tupleid, planSlot, dest, estate);
1275 ExecUpdate(slot, tupleid, planSlot, dest, estate);
1280 elog(ERROR, "unrecognized operation code: %d",
1287 * check our tuple count.. if we've processed the proper number then
1288 * quit, else loop again and process more tuples. Zero numberTuples
1291 current_tuple_count++;
1292 if (numberTuples && numberTuples == current_tuple_count)
1297 * Process AFTER EACH STATEMENT triggers
1302 ExecASUpdateTriggers(estate, estate->es_result_relation_info);
1305 ExecASDeleteTriggers(estate, estate->es_result_relation_info);
1308 ExecASInsertTriggers(estate, estate->es_result_relation_info);
1316 * here, result is either a slot containing a tuple in the case of a
1317 * SELECT or NULL otherwise.
1322 /* ----------------------------------------------------------------
1325 * SELECTs are easy.. we just pass the tuple to the appropriate
1327 * ----------------------------------------------------------------
1330 ExecSelect(TupleTableSlot *slot,
1334 (*dest->receiveSlot) (slot, dest);
1336 (estate->es_processed)++;
1339 /* ----------------------------------------------------------------
1342 * INSERTs are trickier.. we have to insert the tuple into
1343 * the base relation and insert appropriate tuples into the
1345 * ----------------------------------------------------------------
1348 ExecInsert(TupleTableSlot *slot,
1349 ItemPointer tupleid,
1350 TupleTableSlot *planSlot,
1355 ResultRelInfo *resultRelInfo;
1356 Relation resultRelationDesc;
1360 * get the heap tuple out of the tuple table slot, making sure we have a
1363 tuple = ExecMaterializeSlot(slot);
1366 * get information on the (current) result relation
1368 resultRelInfo = estate->es_result_relation_info;
1369 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1371 /* BEFORE ROW INSERT Triggers */
1372 if (resultRelInfo->ri_TrigDesc &&
1373 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1377 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1379 if (newtuple == NULL) /* "do nothing" */
1382 if (newtuple != tuple) /* modified by Trigger(s) */
1385 * Put the modified tuple into a slot for convenience of routines
1386 * below. We assume the tuple was allocated in per-tuple memory
1387 * context, and therefore will go away by itself. The tuple table
1388 * slot should not try to clear it.
1390 TupleTableSlot *newslot = estate->es_trig_tuple_slot;
1392 if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
1393 ExecSetSlotDescriptor(newslot, slot->tts_tupleDescriptor);
1394 ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
1401 * Check the constraints of the tuple
1403 if (resultRelationDesc->rd_att->constr)
1404 ExecConstraints(resultRelInfo, slot, estate);
1409 * Note: heap_insert returns the tid (location) of the new tuple in the
1412 newId = heap_insert(resultRelationDesc, tuple,
1413 estate->es_snapshot->curcid,
1417 (estate->es_processed)++;
1418 estate->es_lastoid = newId;
1419 setLastTid(&(tuple->t_self));
1422 * insert index entries for tuple
1424 if (resultRelInfo->ri_NumIndices > 0)
1425 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1427 /* AFTER ROW INSERT Triggers */
1428 ExecARInsertTriggers(estate, resultRelInfo, tuple);
1430 /* Process RETURNING if present */
1431 if (resultRelInfo->ri_projectReturning)
1432 ExecProcessReturning(resultRelInfo->ri_projectReturning,
1433 slot, planSlot, dest);
1436 /* ----------------------------------------------------------------
1439 * DELETE is like UPDATE, except that we delete the tuple and no
1440 * index modifications are needed
1441 * ----------------------------------------------------------------
1444 ExecDelete(ItemPointer tupleid,
1445 TupleTableSlot *planSlot,
1449 ResultRelInfo *resultRelInfo;
1450 Relation resultRelationDesc;
1452 ItemPointerData update_ctid;
1453 TransactionId update_xmax;
1456 * get information on the (current) result relation
1458 resultRelInfo = estate->es_result_relation_info;
1459 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1461 /* BEFORE ROW DELETE Triggers */
1462 if (resultRelInfo->ri_TrigDesc &&
1463 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1467 dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid,
1468 estate->es_snapshot->curcid);
1470 if (!dodelete) /* "do nothing" */
1477 * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
1478 * the row to be deleted is visible to that snapshot, and throw a can't-
1479 * serialize error if not. This is a special-case behavior needed for
1480 * referential integrity updates in serializable transactions.
1483 result = heap_delete(resultRelationDesc, tupleid,
1484 &update_ctid, &update_xmax,
1485 estate->es_snapshot->curcid,
1486 estate->es_crosscheck_snapshot,
1487 true /* wait for commit */ );
1490 case HeapTupleSelfUpdated:
1491 /* already deleted by self; nothing to do */
1494 case HeapTupleMayBeUpdated:
1497 case HeapTupleUpdated:
1498 if (IsXactIsoLevelSerializable)
1500 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1501 errmsg("could not serialize access due to concurrent update")));
1502 else if (!ItemPointerEquals(tupleid, &update_ctid))
1504 TupleTableSlot *epqslot;
1506 epqslot = EvalPlanQual(estate,
1507 resultRelInfo->ri_RangeTableIndex,
1510 estate->es_snapshot->curcid);
1511 if (!TupIsNull(epqslot))
1513 *tupleid = update_ctid;
1517 /* tuple already deleted; nothing to do */
1521 elog(ERROR, "unrecognized heap_delete status: %u", result);
1526 (estate->es_processed)++;
1529 * Note: Normally one would think that we have to delete index tuples
1530 * associated with the heap tuple now...
1532 * ... but in POSTGRES, we have no need to do this because VACUUM will
1533 * take care of it later. We can't delete index tuples immediately
1534 * anyway, since the tuple is still visible to other transactions.
1537 /* AFTER ROW DELETE Triggers */
1538 ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1540 /* Process RETURNING if present */
1541 if (resultRelInfo->ri_projectReturning)
1544 * We have to put the target tuple into a slot, which means first we
1545 * gotta fetch it. We can use the trigger tuple slot.
1547 TupleTableSlot *slot = estate->es_trig_tuple_slot;
1548 HeapTupleData deltuple;
1551 deltuple.t_self = *tupleid;
1552 if (!heap_fetch(resultRelationDesc, SnapshotAny,
1553 &deltuple, &delbuffer, false, NULL))
1554 elog(ERROR, "failed to fetch deleted tuple for DELETE RETURNING");
1556 if (slot->tts_tupleDescriptor != RelationGetDescr(resultRelationDesc))
1557 ExecSetSlotDescriptor(slot, RelationGetDescr(resultRelationDesc));
1558 ExecStoreTuple(&deltuple, slot, InvalidBuffer, false);
1560 ExecProcessReturning(resultRelInfo->ri_projectReturning,
1561 slot, planSlot, dest);
1563 ExecClearTuple(slot);
1564 ReleaseBuffer(delbuffer);
1568 /* ----------------------------------------------------------------
1571 * note: we can't run UPDATE queries with transactions
1572 * off because UPDATEs are actually INSERTs and our
1573 * scan will mistakenly loop forever, updating the tuple
1574 * it just inserted.. This should be fixed but until it
1575 * is, we don't want to get stuck in an infinite loop
1576 * which corrupts your database..
1577 * ----------------------------------------------------------------
1580 ExecUpdate(TupleTableSlot *slot,
1581 ItemPointer tupleid,
1582 TupleTableSlot *planSlot,
1587 ResultRelInfo *resultRelInfo;
1588 Relation resultRelationDesc;
1590 ItemPointerData update_ctid;
1591 TransactionId update_xmax;
1594 * abort the operation if not running transactions
1596 if (IsBootstrapProcessingMode())
1597 elog(ERROR, "cannot UPDATE during bootstrap");
1600 * get the heap tuple out of the tuple table slot, making sure we have a
1603 tuple = ExecMaterializeSlot(slot);
1606 * get information on the (current) result relation
1608 resultRelInfo = estate->es_result_relation_info;
1609 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1611 /* BEFORE ROW UPDATE Triggers */
1612 if (resultRelInfo->ri_TrigDesc &&
1613 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1617 newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
1619 estate->es_snapshot->curcid);
1621 if (newtuple == NULL) /* "do nothing" */
1624 if (newtuple != tuple) /* modified by Trigger(s) */
1627 * Put the modified tuple into a slot for convenience of routines
1628 * below. We assume the tuple was allocated in per-tuple memory
1629 * context, and therefore will go away by itself. The tuple table
1630 * slot should not try to clear it.
1632 TupleTableSlot *newslot = estate->es_trig_tuple_slot;
1634 if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
1635 ExecSetSlotDescriptor(newslot, slot->tts_tupleDescriptor);
1636 ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
1643 * Check the constraints of the tuple
1645 * If we generate a new candidate tuple after EvalPlanQual testing, we
1646 * must loop back here and recheck constraints. (We don't need to redo
1647 * triggers, however. If there are any BEFORE triggers then trigger.c
1648 * will have done heap_lock_tuple to lock the correct tuple, so there's no
1649 * need to do them again.)
1652 if (resultRelationDesc->rd_att->constr)
1653 ExecConstraints(resultRelInfo, slot, estate);
1656 * replace the heap tuple
1658 * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
1659 * the row to be updated is visible to that snapshot, and throw a can't-
1660 * serialize error if not. This is a special-case behavior needed for
1661 * referential integrity updates in serializable transactions.
1663 result = heap_update(resultRelationDesc, tupleid, tuple,
1664 &update_ctid, &update_xmax,
1665 estate->es_snapshot->curcid,
1666 estate->es_crosscheck_snapshot,
1667 true /* wait for commit */ );
1670 case HeapTupleSelfUpdated:
1671 /* already deleted by self; nothing to do */
1674 case HeapTupleMayBeUpdated:
1677 case HeapTupleUpdated:
1678 if (IsXactIsoLevelSerializable)
1680 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1681 errmsg("could not serialize access due to concurrent update")));
1682 else if (!ItemPointerEquals(tupleid, &update_ctid))
1684 TupleTableSlot *epqslot;
1686 epqslot = EvalPlanQual(estate,
1687 resultRelInfo->ri_RangeTableIndex,
1690 estate->es_snapshot->curcid);
1691 if (!TupIsNull(epqslot))
1693 *tupleid = update_ctid;
1694 slot = ExecFilterJunk(estate->es_junkFilter, epqslot);
1695 tuple = ExecMaterializeSlot(slot);
1699 /* tuple already deleted; nothing to do */
1703 elog(ERROR, "unrecognized heap_update status: %u", result);
1708 (estate->es_processed)++;
1711 * Note: instead of having to update the old index tuples associated with
1712 * the heap tuple, all we do is form and insert new index tuples. This is
1713 * because UPDATEs are actually DELETEs and INSERTs, and index tuple
1714 * deletion is done later by VACUUM (see notes in ExecDelete). All we do
1715 * here is insert new index tuples. -cim 9/27/89
1719 * insert index entries for tuple
1721 * Note: heap_update returns the tid (location) of the new tuple in the
1724 if (resultRelInfo->ri_NumIndices > 0)
1725 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1727 /* AFTER ROW UPDATE Triggers */
1728 ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
1730 /* Process RETURNING if present */
1731 if (resultRelInfo->ri_projectReturning)
1732 ExecProcessReturning(resultRelInfo->ri_projectReturning,
1733 slot, planSlot, dest);
1737 * ExecRelCheck --- check that tuple meets constraints for result relation
1740 ExecRelCheck(ResultRelInfo *resultRelInfo,
1741 TupleTableSlot *slot, EState *estate)
1743 Relation rel = resultRelInfo->ri_RelationDesc;
1744 int ncheck = rel->rd_att->constr->num_check;
1745 ConstrCheck *check = rel->rd_att->constr->check;
1746 ExprContext *econtext;
1747 MemoryContext oldContext;
1752 * If first time through for this result relation, build expression
1753 * nodetrees for rel's constraint expressions. Keep them in the per-query
1754 * memory context so they'll survive throughout the query.
1756 if (resultRelInfo->ri_ConstraintExprs == NULL)
1758 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1759 resultRelInfo->ri_ConstraintExprs =
1760 (List **) palloc(ncheck * sizeof(List *));
1761 for (i = 0; i < ncheck; i++)
1763 /* ExecQual wants implicit-AND form */
1764 qual = make_ands_implicit(stringToNode(check[i].ccbin));
1765 resultRelInfo->ri_ConstraintExprs[i] = (List *)
1766 ExecPrepareExpr((Expr *) qual, estate);
1768 MemoryContextSwitchTo(oldContext);
1772 * We will use the EState's per-tuple context for evaluating constraint
1773 * expressions (creating it if it's not already there).
1775 econtext = GetPerTupleExprContext(estate);
1777 /* Arrange for econtext's scan tuple to be the tuple under test */
1778 econtext->ecxt_scantuple = slot;
1780 /* And evaluate the constraints */
1781 for (i = 0; i < ncheck; i++)
1783 qual = resultRelInfo->ri_ConstraintExprs[i];
1786 * NOTE: SQL92 specifies that a NULL result from a constraint
1787 * expression is not to be treated as a failure. Therefore, tell
1788 * ExecQual to return TRUE for NULL.
1790 if (!ExecQual(qual, econtext, true))
1791 return check[i].ccname;
1794 /* NULL result means no error */
1799 ExecConstraints(ResultRelInfo *resultRelInfo,
1800 TupleTableSlot *slot, EState *estate)
1802 Relation rel = resultRelInfo->ri_RelationDesc;
1803 TupleConstr *constr = rel->rd_att->constr;
1807 if (constr->has_not_null)
1809 int natts = rel->rd_att->natts;
1812 for (attrChk = 1; attrChk <= natts; attrChk++)
1814 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1815 slot_attisnull(slot, attrChk))
1817 (errcode(ERRCODE_NOT_NULL_VIOLATION),
1818 errmsg("null value in column \"%s\" violates not-null constraint",
1819 NameStr(rel->rd_att->attrs[attrChk - 1]->attname))));
1823 if (constr->num_check > 0)
1827 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1829 (errcode(ERRCODE_CHECK_VIOLATION),
1830 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1831 RelationGetRelationName(rel), failed)));
1836 * ExecProcessReturning --- evaluate a RETURNING list and send to dest
1838 * projectReturning: RETURNING projection info for current result rel
1839 * tupleSlot: slot holding tuple actually inserted/updated/deleted
1840 * planSlot: slot holding tuple returned by top plan node
1841 * dest: where to send the output
1844 ExecProcessReturning(ProjectionInfo *projectReturning,
1845 TupleTableSlot *tupleSlot,
1846 TupleTableSlot *planSlot,
1849 ExprContext *econtext = projectReturning->pi_exprContext;
1850 TupleTableSlot *retSlot;
1853 * Reset per-tuple memory context to free any expression evaluation
1854 * storage allocated in the previous cycle.
1856 ResetExprContext(econtext);
1858 /* Make tuple and any needed join variables available to ExecProject */
1859 econtext->ecxt_scantuple = tupleSlot;
1860 econtext->ecxt_outertuple = planSlot;
1862 /* Compute the RETURNING expressions */
1863 retSlot = ExecProject(projectReturning, NULL);
1866 (*dest->receiveSlot) (retSlot, dest);
1868 ExecClearTuple(retSlot);
1872 * Check a modified tuple to see if we want to process its updated version
1873 * under READ COMMITTED rules.
1875 * See backend/executor/README for some info about how this works.
1877 * estate - executor state data
1878 * rti - rangetable index of table containing tuple
1879 * *tid - t_ctid from the outdated tuple (ie, next updated version)
1880 * priorXmax - t_xmax from the outdated tuple
1881 * curCid - command ID of current command of my transaction
1883 * *tid is also an output parameter: it's modified to hold the TID of the
1884 * latest version of the tuple (note this may be changed even on failure)
1886 * Returns a slot containing the new candidate update/delete tuple, or
1887 * NULL if we determine we shouldn't process the row.
1890 EvalPlanQual(EState *estate, Index rti,
1891 ItemPointer tid, TransactionId priorXmax, CommandId curCid)
1896 HeapTupleData tuple;
1897 HeapTuple copyTuple = NULL;
1903 * find relation containing target tuple
1905 if (estate->es_result_relation_info != NULL &&
1906 estate->es_result_relation_info->ri_RangeTableIndex == rti)
1907 relation = estate->es_result_relation_info->ri_RelationDesc;
1913 foreach(l, estate->es_rowMarks)
1915 if (((ExecRowMark *) lfirst(l))->rti == rti)
1917 relation = ((ExecRowMark *) lfirst(l))->relation;
1921 if (relation == NULL)
1922 elog(ERROR, "could not find RowMark for RT index %u", rti);
1928 * Loop here to deal with updated or busy tuples
1930 tuple.t_self = *tid;
1935 if (heap_fetch(relation, SnapshotDirty, &tuple, &buffer, true, NULL))
1938 * If xmin isn't what we're expecting, the slot must have been
1939 * recycled and reused for an unrelated tuple. This implies that
1940 * the latest version of the row was deleted, so we need do
1941 * nothing. (Should be safe to examine xmin without getting
1942 * buffer's content lock, since xmin never changes in an existing
1945 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1948 ReleaseBuffer(buffer);
1952 /* otherwise xmin should not be dirty... */
1953 if (TransactionIdIsValid(SnapshotDirty->xmin))
1954 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
1957 * If tuple is being updated by other transaction then we have to
1958 * wait for its commit/abort.
1960 if (TransactionIdIsValid(SnapshotDirty->xmax))
1962 ReleaseBuffer(buffer);
1963 XactLockTableWait(SnapshotDirty->xmax);
1964 continue; /* loop back to repeat heap_fetch */
1968 * If tuple was inserted by our own transaction, we have to check
1969 * cmin against curCid: cmin >= curCid means our command cannot
1970 * see the tuple, so we should ignore it. Without this we are
1971 * open to the "Halloween problem" of indefinitely re-updating the
1972 * same tuple. (We need not check cmax because
1973 * HeapTupleSatisfiesDirty will consider a tuple deleted by our
1974 * transaction dead, regardless of cmax.) We just checked that
1975 * priorXmax == xmin, so we can test that variable instead of
1976 * doing HeapTupleHeaderGetXmin again.
1978 if (TransactionIdIsCurrentTransactionId(priorXmax) &&
1979 HeapTupleHeaderGetCmin(tuple.t_data) >= curCid)
1981 ReleaseBuffer(buffer);
1986 * We got tuple - now copy it for use by recheck query.
1988 copyTuple = heap_copytuple(&tuple);
1989 ReleaseBuffer(buffer);
1994 * If the referenced slot was actually empty, the latest version of
1995 * the row must have been deleted, so we need do nothing.
1997 if (tuple.t_data == NULL)
1999 ReleaseBuffer(buffer);
2004 * As above, if xmin isn't what we're expecting, do nothing.
2006 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2009 ReleaseBuffer(buffer);
2014 * If we get here, the tuple was found but failed SnapshotDirty.
2015 * Assuming the xmin is either a committed xact or our own xact (as it
2016 * certainly should be if we're trying to modify the tuple), this must
2017 * mean that the row was updated or deleted by either a committed xact
2018 * or our own xact. If it was deleted, we can ignore it; if it was
2019 * updated then chain up to the next version and repeat the whole
2022 * As above, it should be safe to examine xmax and t_ctid without the
2023 * buffer content lock, because they can't be changing.
2025 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
2027 /* deleted, so forget about it */
2028 ReleaseBuffer(buffer);
2032 /* updated, so look at the updated row */
2033 tuple.t_self = tuple.t_data->t_ctid;
2034 /* updated row should have xmin matching this xmax */
2035 priorXmax = HeapTupleHeaderGetXmax(tuple.t_data);
2036 ReleaseBuffer(buffer);
2037 /* loop back to fetch next in chain */
2041 * For UPDATE/DELETE we have to return tid of actual row we're executing
2044 *tid = tuple.t_self;
2047 * Need to run a recheck subquery. Find or create a PQ stack entry.
2049 epq = estate->es_evalPlanQual;
2052 if (epq != NULL && epq->rti == 0)
2054 /* Top PQ stack entry is idle, so re-use it */
2055 Assert(!(estate->es_useEvalPlan) && epq->next == NULL);
2061 * If this is request for another RTE - Ra, - then we have to check wasn't
2062 * PlanQual requested for Ra already and if so then Ra' row was updated
2063 * again and we have to re-start old execution for Ra and forget all what
2064 * we done after Ra was suspended. Cool? -:))
2066 if (epq != NULL && epq->rti != rti &&
2067 epq->estate->es_evTuple[rti - 1] != NULL)
2071 evalPlanQual *oldepq;
2073 /* stop execution */
2074 EvalPlanQualStop(epq);
2075 /* pop previous PlanQual from the stack */
2077 Assert(oldepq && oldepq->rti != 0);
2078 /* push current PQ to freePQ stack */
2081 estate->es_evalPlanQual = epq;
2082 } while (epq->rti != rti);
2086 * If we are requested for another RTE then we have to suspend execution
2087 * of current PlanQual and start execution for new one.
2089 if (epq == NULL || epq->rti != rti)
2091 /* try to reuse plan used previously */
2092 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
2094 if (newepq == NULL) /* first call or freePQ stack is empty */
2096 newepq = (evalPlanQual *) palloc0(sizeof(evalPlanQual));
2097 newepq->free = NULL;
2098 newepq->estate = NULL;
2099 newepq->planstate = NULL;
2103 /* recycle previously used PlanQual */
2104 Assert(newepq->estate == NULL);
2107 /* push current PQ to the stack */
2110 estate->es_evalPlanQual = epq;
2115 Assert(epq->rti == rti);
2118 * Ok - we're requested for the same RTE. Unfortunately we still have to
2119 * end and restart execution of the plan, because ExecReScan wouldn't
2120 * ensure that upper plan nodes would reset themselves. We could make
2121 * that work if insertion of the target tuple were integrated with the
2122 * Param mechanism somehow, so that the upper plan nodes know that their
2123 * children's outputs have changed.
2125 * Note that the stack of free evalPlanQual nodes is quite useless at the
2126 * moment, since it only saves us from pallocing/releasing the
2127 * evalPlanQual nodes themselves. But it will be useful once we implement
2128 * ReScan instead of end/restart for re-using PlanQual nodes.
2132 /* stop execution */
2133 EvalPlanQualStop(epq);
2137 * Initialize new recheck query.
2139 * Note: if we were re-using PlanQual plans via ExecReScan, we'd need to
2140 * instead copy down changeable state from the top plan (including
2141 * es_result_relation_info, es_junkFilter) and reset locally changeable
2142 * state in the epq (including es_param_exec_vals, es_evTupleNull).
2144 EvalPlanQualStart(epq, estate, epq->next);
2147 * free old RTE' tuple, if any, and store target tuple where relation's
2148 * scan node will see it
2150 epqstate = epq->estate;
2151 if (epqstate->es_evTuple[rti - 1] != NULL)
2152 heap_freetuple(epqstate->es_evTuple[rti - 1]);
2153 epqstate->es_evTuple[rti - 1] = copyTuple;
2155 return EvalPlanQualNext(estate);
2158 static TupleTableSlot *
2159 EvalPlanQualNext(EState *estate)
2161 evalPlanQual *epq = estate->es_evalPlanQual;
2162 MemoryContext oldcontext;
2163 TupleTableSlot *slot;
2165 Assert(epq->rti != 0);
2168 oldcontext = MemoryContextSwitchTo(epq->estate->es_query_cxt);
2169 slot = ExecProcNode(epq->planstate);
2170 MemoryContextSwitchTo(oldcontext);
2173 * No more tuples for this PQ. Continue previous one.
2175 if (TupIsNull(slot))
2177 evalPlanQual *oldepq;
2179 /* stop execution */
2180 EvalPlanQualStop(epq);
2181 /* pop old PQ from the stack */
2185 /* this is the first (oldest) PQ - mark as free */
2187 estate->es_useEvalPlan = false;
2188 /* and continue Query execution */
2191 Assert(oldepq->rti != 0);
2192 /* push current PQ to freePQ stack */
2195 estate->es_evalPlanQual = epq;
2203 EndEvalPlanQual(EState *estate)
2205 evalPlanQual *epq = estate->es_evalPlanQual;
2207 if (epq->rti == 0) /* plans already shutdowned */
2209 Assert(epq->next == NULL);
2215 evalPlanQual *oldepq;
2217 /* stop execution */
2218 EvalPlanQualStop(epq);
2219 /* pop old PQ from the stack */
2223 /* this is the first (oldest) PQ - mark as free */
2225 estate->es_useEvalPlan = false;
2228 Assert(oldepq->rti != 0);
2229 /* push current PQ to freePQ stack */
2232 estate->es_evalPlanQual = epq;
2237 * Start execution of one level of PlanQual.
2239 * This is a cut-down version of ExecutorStart(): we copy some state from
2240 * the top-level estate rather than initializing it fresh.
2243 EvalPlanQualStart(evalPlanQual *epq, EState *estate, evalPlanQual *priorepq)
2247 MemoryContext oldcontext;
2249 rtsize = list_length(estate->es_range_table);
2252 * It's tempting to think about using CreateSubExecutorState here, but
2253 * at present we can't because of memory leakage concerns ...
2255 epq->estate = epqstate = CreateExecutorState();
2257 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2260 * The epqstates share the top query's copy of unchanging state such as
2261 * the snapshot, rangetable, result-rel info, and external Param info.
2262 * They need their own copies of local state, including a tuple table,
2263 * es_param_exec_vals, etc.
2265 epqstate->es_direction = ForwardScanDirection;
2266 epqstate->es_snapshot = estate->es_snapshot;
2267 epqstate->es_crosscheck_snapshot = estate->es_crosscheck_snapshot;
2268 epqstate->es_range_table = estate->es_range_table;
2269 epqstate->es_result_relations = estate->es_result_relations;
2270 epqstate->es_num_result_relations = estate->es_num_result_relations;
2271 epqstate->es_result_relation_info = estate->es_result_relation_info;
2272 epqstate->es_junkFilter = estate->es_junkFilter;
2273 epqstate->es_into_relation_descriptor = estate->es_into_relation_descriptor;
2274 epqstate->es_into_relation_use_wal = estate->es_into_relation_use_wal;
2275 epqstate->es_param_list_info = estate->es_param_list_info;
2276 if (estate->es_topPlan->nParamExec > 0)
2277 epqstate->es_param_exec_vals = (ParamExecData *)
2278 palloc0(estate->es_topPlan->nParamExec * sizeof(ParamExecData));
2279 epqstate->es_rowMarks = estate->es_rowMarks;
2280 epqstate->es_instrument = estate->es_instrument;
2281 epqstate->es_select_into = estate->es_select_into;
2282 epqstate->es_into_oids = estate->es_into_oids;
2283 epqstate->es_topPlan = estate->es_topPlan;
2286 * Each epqstate must have its own es_evTupleNull state, but all the stack
2287 * entries share es_evTuple state. This allows sub-rechecks to inherit
2288 * the value being examined by an outer recheck.
2290 epqstate->es_evTupleNull = (bool *) palloc0(rtsize * sizeof(bool));
2291 if (priorepq == NULL)
2292 /* first PQ stack entry */
2293 epqstate->es_evTuple = (HeapTuple *)
2294 palloc0(rtsize * sizeof(HeapTuple));
2296 /* later stack entries share the same storage */
2297 epqstate->es_evTuple = priorepq->estate->es_evTuple;
2299 epqstate->es_tupleTable =
2300 ExecCreateTupleTable(estate->es_tupleTable->size);
2302 epq->planstate = ExecInitNode(estate->es_topPlan, epqstate, 0);
2304 MemoryContextSwitchTo(oldcontext);
2308 * End execution of one level of PlanQual.
2310 * This is a cut-down version of ExecutorEnd(); basically we want to do most
2311 * of the normal cleanup, but *not* close result relations (which we are
2312 * just sharing from the outer query).
2315 EvalPlanQualStop(evalPlanQual *epq)
2317 EState *epqstate = epq->estate;
2318 MemoryContext oldcontext;
2320 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2322 ExecEndNode(epq->planstate);
2324 ExecDropTupleTable(epqstate->es_tupleTable, true);
2325 epqstate->es_tupleTable = NULL;
2327 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
2329 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
2330 epqstate->es_evTuple[epq->rti - 1] = NULL;
2333 MemoryContextSwitchTo(oldcontext);
2335 FreeExecutorState(epqstate);
2338 epq->planstate = NULL;
2343 * Support for SELECT INTO (a/k/a CREATE TABLE AS)
2345 * We implement SELECT INTO by diverting SELECT's normal output with
2346 * a specialized DestReceiver type.
2348 * TODO: remove some of the INTO-specific cruft from EState, and keep
2349 * it in the DestReceiver instead.
2354 DestReceiver pub; /* publicly-known function pointers */
2355 EState *estate; /* EState we are working with */
2359 * OpenIntoRel --- actually create the SELECT INTO target relation
2361 * This also replaces QueryDesc->dest with the special DestReceiver for
2362 * SELECT INTO. We assume that the correct result tuple type has already
2363 * been placed in queryDesc->tupDesc.
2366 OpenIntoRel(QueryDesc *queryDesc)
2368 Query *parseTree = queryDesc->parsetree;
2369 EState *estate = queryDesc->estate;
2370 Relation intoRelationDesc;
2375 AclResult aclresult;
2378 DR_intorel *myState;
2381 * Check consistency of arguments
2383 if (parseTree->intoOnCommit != ONCOMMIT_NOOP && !parseTree->into->istemp)
2385 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2386 errmsg("ON COMMIT can only be used on temporary tables")));
2389 * Find namespace to create in, check its permissions
2391 intoName = parseTree->into->relname;
2392 namespaceId = RangeVarGetCreationNamespace(parseTree->into);
2394 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
2396 if (aclresult != ACLCHECK_OK)
2397 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2398 get_namespace_name(namespaceId));
2401 * Select tablespace to use. If not specified, use default_tablespace
2402 * (which may in turn default to database's default).
2404 if (parseTree->intoTableSpaceName)
2406 tablespaceId = get_tablespace_oid(parseTree->intoTableSpaceName);
2407 if (!OidIsValid(tablespaceId))
2409 (errcode(ERRCODE_UNDEFINED_OBJECT),
2410 errmsg("tablespace \"%s\" does not exist",
2411 parseTree->intoTableSpaceName)));
2413 else if (parseTree->into->istemp)
2415 tablespaceId = GetTempTablespace();
2419 tablespaceId = GetDefaultTablespace();
2420 /* note InvalidOid is OK in this case */
2423 /* Check permissions except when using the database's default space */
2424 if (OidIsValid(tablespaceId))
2426 AclResult aclresult;
2428 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
2431 if (aclresult != ACLCHECK_OK)
2432 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
2433 get_tablespace_name(tablespaceId));
2436 /* Parse and validate any reloptions */
2437 reloptions = transformRelOptions((Datum) 0,
2438 parseTree->intoOptions,
2441 (void) heap_reloptions(RELKIND_RELATION, reloptions, true);
2443 /* have to copy the actual tupdesc to get rid of any constraints */
2444 tupdesc = CreateTupleDescCopy(queryDesc->tupDesc);
2446 /* Now we can actually create the new relation */
2447 intoRelationId = heap_create_with_catalog(intoName,
2457 parseTree->intoOnCommit,
2459 allowSystemTableMods);
2461 FreeTupleDesc(tupdesc);
2464 * Advance command counter so that the newly-created relation's catalog
2465 * tuples will be visible to heap_open.
2467 CommandCounterIncrement();
2470 * If necessary, create a TOAST table for the INTO relation. Note that
2471 * AlterTableCreateToastTable ends with CommandCounterIncrement(), so that
2472 * the TOAST table will be visible for insertion.
2474 AlterTableCreateToastTable(intoRelationId);
2477 * And open the constructed table for writing.
2479 intoRelationDesc = heap_open(intoRelationId, AccessExclusiveLock);
2481 /* use_wal off requires rd_targblock be initially invalid */
2482 Assert(intoRelationDesc->rd_targblock == InvalidBlockNumber);
2485 * We can skip WAL-logging the insertions, unless PITR is in use.
2487 * Note that for a non-temp INTO table, this is safe only because we know
2488 * that the catalog changes above will have been WAL-logged, and so
2489 * RecordTransactionCommit will think it needs to WAL-log the eventual
2490 * transaction commit. Else the commit might be lost, even though all the
2491 * data is safely fsync'd ...
2493 estate->es_into_relation_use_wal = XLogArchivingActive();
2494 estate->es_into_relation_descriptor = intoRelationDesc;
2497 * Now replace the query's DestReceiver with one for SELECT INTO
2499 queryDesc->dest = CreateDestReceiver(DestIntoRel, NULL);
2500 myState = (DR_intorel *) queryDesc->dest;
2501 Assert(myState->pub.mydest == DestIntoRel);
2502 myState->estate = estate;
2506 * CloseIntoRel --- clean up SELECT INTO at ExecutorEnd time
2509 CloseIntoRel(QueryDesc *queryDesc)
2511 EState *estate = queryDesc->estate;
2513 /* OpenIntoRel might never have gotten called */
2514 if (estate->es_into_relation_descriptor)
2517 * If we skipped using WAL, and it's not a temp relation, we must
2518 * force the relation down to disk before it's safe to commit the
2519 * transaction. This requires forcing out any dirty buffers and then
2520 * doing a forced fsync.
2522 if (!estate->es_into_relation_use_wal &&
2523 !estate->es_into_relation_descriptor->rd_istemp)
2524 heap_sync(estate->es_into_relation_descriptor);
2526 /* close rel, but keep lock until commit */
2527 heap_close(estate->es_into_relation_descriptor, NoLock);
2529 estate->es_into_relation_descriptor = NULL;
2534 * CreateIntoRelDestReceiver -- create a suitable DestReceiver object
2536 * Since CreateDestReceiver doesn't accept the parameters we'd need,
2537 * we just leave the private fields empty here. OpenIntoRel will
2541 CreateIntoRelDestReceiver(void)
2543 DR_intorel *self = (DR_intorel *) palloc(sizeof(DR_intorel));
2545 self->pub.receiveSlot = intorel_receive;
2546 self->pub.rStartup = intorel_startup;
2547 self->pub.rShutdown = intorel_shutdown;
2548 self->pub.rDestroy = intorel_destroy;
2549 self->pub.mydest = DestIntoRel;
2551 self->estate = NULL;
2553 return (DestReceiver *) self;
2557 * intorel_startup --- executor startup
2560 intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
2566 * intorel_receive --- receive one tuple
2569 intorel_receive(TupleTableSlot *slot, DestReceiver *self)
2571 DR_intorel *myState = (DR_intorel *) self;
2572 EState *estate = myState->estate;
2575 tuple = ExecCopySlotTuple(slot);
2577 heap_insert(estate->es_into_relation_descriptor,
2579 estate->es_snapshot->curcid,
2580 estate->es_into_relation_use_wal,
2581 false); /* never any point in using FSM */
2583 /* We know this is a newly created relation, so there are no indexes */
2585 heap_freetuple(tuple);
2591 * intorel_shutdown --- executor end
2594 intorel_shutdown(DestReceiver *self)
2600 * intorel_destroy --- release DestReceiver object
2603 intorel_destroy(DestReceiver *self)