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-2005, 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.267 2006/02/21 23:01:54 neilc Exp $
31 *-------------------------------------------------------------------------
35 #include "access/heapam.h"
36 #include "access/xlog.h"
37 #include "catalog/heap.h"
38 #include "catalog/namespace.h"
39 #include "commands/tablecmds.h"
40 #include "commands/tablespace.h"
41 #include "commands/trigger.h"
42 #include "executor/execdebug.h"
43 #include "executor/execdefs.h"
44 #include "executor/instrument.h"
45 #include "miscadmin.h"
46 #include "optimizer/clauses.h"
47 #include "optimizer/var.h"
48 #include "parser/parsetree.h"
49 #include "storage/smgr.h"
50 #include "utils/acl.h"
51 #include "utils/guc.h"
52 #include "utils/lsyscache.h"
53 #include "utils/memutils.h"
56 typedef struct evalPlanQual
61 struct evalPlanQual *next; /* stack of active PlanQual plans */
62 struct evalPlanQual *free; /* list of free PlanQual plans */
65 /* decls for local routines only used within this module */
66 static void InitPlan(QueryDesc *queryDesc, bool explainOnly);
67 static void initResultRelInfo(ResultRelInfo *resultRelInfo,
68 Index resultRelationIndex,
72 static TupleTableSlot *ExecutePlan(EState *estate, PlanState *planstate,
75 ScanDirection direction,
77 static void ExecSelect(TupleTableSlot *slot,
80 static void ExecInsert(TupleTableSlot *slot, ItemPointer tupleid,
82 static void ExecDelete(TupleTableSlot *slot, ItemPointer tupleid,
84 static void ExecUpdate(TupleTableSlot *slot, ItemPointer tupleid,
86 static TupleTableSlot *EvalPlanQualNext(EState *estate);
87 static void EndEvalPlanQual(EState *estate);
88 static void ExecCheckRTEPerms(RangeTblEntry *rte);
89 static void ExecCheckXactReadOnly(Query *parsetree);
90 static void EvalPlanQualStart(evalPlanQual *epq, EState *estate,
91 evalPlanQual *priorepq);
92 static void EvalPlanQualStop(evalPlanQual *epq);
94 /* end of local decls */
97 /* ----------------------------------------------------------------
100 * This routine must be called at the beginning of any execution of any
103 * Takes a QueryDesc previously created by CreateQueryDesc (it's not real
104 * clear why we bother to separate the two functions, but...). The tupDesc
105 * field of the QueryDesc is filled in to describe the tuples that will be
106 * returned, and the internal fields (estate and planstate) are set up.
108 * If explainOnly is true, we are not actually intending to run the plan,
109 * only to set up for EXPLAIN; so skip unwanted side-effects.
111 * NB: the CurrentMemoryContext when this is called will become the parent
112 * of the per-query context used for this Executor invocation.
113 * ----------------------------------------------------------------
116 ExecutorStart(QueryDesc *queryDesc, bool explainOnly)
119 MemoryContext oldcontext;
121 /* sanity checks: queryDesc must not be started already */
122 Assert(queryDesc != NULL);
123 Assert(queryDesc->estate == NULL);
126 * If the transaction is read-only, we need to check if any writes are
127 * planned to non-temporary tables.
129 if (XactReadOnly && !explainOnly)
130 ExecCheckXactReadOnly(queryDesc->parsetree);
133 * Build EState, switch into per-query memory context for startup.
135 estate = CreateExecutorState();
136 queryDesc->estate = estate;
138 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
141 * Fill in parameters, if any, from queryDesc
143 estate->es_param_list_info = queryDesc->params;
145 if (queryDesc->plantree->nParamExec > 0)
146 estate->es_param_exec_vals = (ParamExecData *)
147 palloc0(queryDesc->plantree->nParamExec * sizeof(ParamExecData));
150 * Copy other important information into the EState
152 estate->es_snapshot = queryDesc->snapshot;
153 estate->es_crosscheck_snapshot = queryDesc->crosscheck_snapshot;
154 estate->es_instrument = queryDesc->doInstrument;
157 * Initialize the plan state tree
159 InitPlan(queryDesc, explainOnly);
161 MemoryContextSwitchTo(oldcontext);
164 /* ----------------------------------------------------------------
167 * This is the main routine of the executor module. It accepts
168 * the query descriptor from the traffic cop and executes the
171 * ExecutorStart must have been called already.
173 * If direction is NoMovementScanDirection then nothing is done
174 * except to start up/shut down the destination. Otherwise,
175 * we retrieve up to 'count' tuples in the specified direction.
177 * Note: count = 0 is interpreted as no portal limit, i.e., run to
180 * ----------------------------------------------------------------
183 ExecutorRun(QueryDesc *queryDesc,
184 ScanDirection direction, long count)
189 TupleTableSlot *result;
190 MemoryContext oldcontext;
193 Assert(queryDesc != NULL);
195 estate = queryDesc->estate;
197 Assert(estate != NULL);
200 * Switch into per-query memory context
202 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
205 * extract information from the query descriptor and the query feature.
207 operation = queryDesc->operation;
208 dest = queryDesc->dest;
211 * startup tuple receiver
213 estate->es_processed = 0;
214 estate->es_lastoid = InvalidOid;
216 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
221 if (ScanDirectionIsNoMovement(direction))
224 result = ExecutePlan(estate,
225 queryDesc->planstate,
234 (*dest->rShutdown) (dest);
236 MemoryContextSwitchTo(oldcontext);
241 /* ----------------------------------------------------------------
244 * This routine must be called at the end of execution of any
246 * ----------------------------------------------------------------
249 ExecutorEnd(QueryDesc *queryDesc)
252 MemoryContext oldcontext;
255 Assert(queryDesc != NULL);
257 estate = queryDesc->estate;
259 Assert(estate != NULL);
262 * Switch into per-query memory context to run ExecEndPlan
264 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
266 ExecEndPlan(queryDesc->planstate, estate);
269 * Must switch out of context before destroying it
271 MemoryContextSwitchTo(oldcontext);
274 * Release EState and per-query memory context. This should release
275 * everything the executor has allocated.
277 FreeExecutorState(estate);
279 /* Reset queryDesc fields that no longer point to anything */
280 queryDesc->tupDesc = NULL;
281 queryDesc->estate = NULL;
282 queryDesc->planstate = NULL;
285 /* ----------------------------------------------------------------
288 * This routine may be called on an open queryDesc to rewind it
290 * ----------------------------------------------------------------
293 ExecutorRewind(QueryDesc *queryDesc)
296 MemoryContext oldcontext;
299 Assert(queryDesc != NULL);
301 estate = queryDesc->estate;
303 Assert(estate != NULL);
305 /* It's probably not sensible to rescan updating queries */
306 Assert(queryDesc->operation == CMD_SELECT);
309 * Switch into per-query memory context
311 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
316 ExecReScan(queryDesc->planstate, NULL);
318 MemoryContextSwitchTo(oldcontext);
324 * Check access permissions for all relations listed in a range table.
327 ExecCheckRTPerms(List *rangeTable)
331 foreach(l, rangeTable)
333 RangeTblEntry *rte = lfirst(l);
335 ExecCheckRTEPerms(rte);
341 * Check access permissions for a single RTE.
344 ExecCheckRTEPerms(RangeTblEntry *rte)
346 AclMode requiredPerms;
351 * Only plain-relation RTEs need to be checked here. Subquery RTEs are
352 * checked by ExecInitSubqueryScan if the subquery is still a separate
353 * subquery --- if it's been pulled up into our query level then the RTEs
354 * are in our rangetable and will be checked here. Function RTEs are
355 * checked by init_fcache when the function is prepared for execution.
356 * Join and special RTEs need no checks.
358 if (rte->rtekind != RTE_RELATION)
362 * No work if requiredPerms is empty.
364 requiredPerms = rte->requiredPerms;
365 if (requiredPerms == 0)
371 * userid to check as: current user unless we have a setuid indication.
373 * Note: GetUserId() is presently fast enough that there's no harm in
374 * calling it separately for each RTE. If that stops being true, we could
375 * call it once in ExecCheckRTPerms and pass the userid down from there.
376 * But for now, no need for the extra clutter.
378 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
381 * We must have *all* the requiredPerms bits, so use aclmask not aclcheck.
383 if (pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL)
385 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
386 get_rel_name(relOid));
390 * Check that the query does not imply any writes to non-temp tables.
393 ExecCheckXactReadOnly(Query *parsetree)
398 * CREATE TABLE AS or SELECT INTO?
400 * XXX should we allow this if the destination is temp?
402 if (parsetree->into != NULL)
405 /* Fail if write permissions are requested on any non-temp table */
406 foreach(l, parsetree->rtable)
408 RangeTblEntry *rte = lfirst(l);
410 if (rte->rtekind == RTE_SUBQUERY)
412 ExecCheckXactReadOnly(rte->subquery);
416 if (rte->rtekind != RTE_RELATION)
419 if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
422 if (isTempNamespace(get_rel_namespace(rte->relid)))
432 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
433 errmsg("transaction is read-only")));
437 /* ----------------------------------------------------------------
440 * Initializes the query plan: open files, allocate storage
441 * and start up the rule manager
442 * ----------------------------------------------------------------
445 InitPlan(QueryDesc *queryDesc, bool explainOnly)
447 CmdType operation = queryDesc->operation;
448 Query *parseTree = queryDesc->parsetree;
449 Plan *plan = queryDesc->plantree;
450 EState *estate = queryDesc->estate;
451 PlanState *planstate;
453 Relation intoRelationDesc;
458 * Do permissions checks. It's sufficient to examine the query's top
459 * rangetable here --- subplan RTEs will be checked during
462 ExecCheckRTPerms(parseTree->rtable);
465 * get information from query descriptor
467 rangeTable = parseTree->rtable;
470 * initialize the node's execution state
472 estate->es_range_table = rangeTable;
475 * if there is a result relation, initialize result relation stuff
477 if (parseTree->resultRelation != 0 && operation != CMD_SELECT)
479 List *resultRelations = parseTree->resultRelations;
480 int numResultRelations;
481 ResultRelInfo *resultRelInfos;
483 if (resultRelations != NIL)
486 * Multiple result relations (due to inheritance)
487 * parseTree->resultRelations identifies them all
489 ResultRelInfo *resultRelInfo;
492 numResultRelations = list_length(resultRelations);
493 resultRelInfos = (ResultRelInfo *)
494 palloc(numResultRelations * sizeof(ResultRelInfo));
495 resultRelInfo = resultRelInfos;
496 foreach(l, resultRelations)
498 initResultRelInfo(resultRelInfo,
502 estate->es_instrument);
509 * Single result relation identified by parseTree->resultRelation
511 numResultRelations = 1;
512 resultRelInfos = (ResultRelInfo *) palloc(sizeof(ResultRelInfo));
513 initResultRelInfo(resultRelInfos,
514 parseTree->resultRelation,
517 estate->es_instrument);
520 estate->es_result_relations = resultRelInfos;
521 estate->es_num_result_relations = numResultRelations;
522 /* Initialize to first or only result rel */
523 estate->es_result_relation_info = resultRelInfos;
528 * if no result relation, then set state appropriately
530 estate->es_result_relations = NULL;
531 estate->es_num_result_relations = 0;
532 estate->es_result_relation_info = NULL;
536 * Detect whether we're doing SELECT INTO. If so, set the es_into_oids
537 * flag appropriately so that the plan tree will be initialized with the
538 * correct tuple descriptors.
540 do_select_into = false;
542 if (operation == CMD_SELECT && parseTree->into != NULL)
544 do_select_into = true;
545 estate->es_select_into = true;
546 estate->es_into_oids = parseTree->intoHasOids;
550 * Have to lock relations selected FOR UPDATE/FOR SHARE
552 estate->es_rowMarks = NIL;
553 estate->es_forUpdate = parseTree->forUpdate;
554 estate->es_rowNoWait = parseTree->rowNoWait;
555 if (parseTree->rowMarks != NIL)
559 foreach(l, parseTree->rowMarks)
561 Index rti = lfirst_int(l);
562 Oid relid = getrelid(rti, rangeTable);
566 relation = heap_open(relid, RowShareLock);
567 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
568 erm->relation = relation;
570 snprintf(erm->resname, sizeof(erm->resname), "ctid%u", rti);
571 estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
576 * initialize the executor "tuple" table. We need slots for all the plan
577 * nodes, plus possibly output slots for the junkfilter(s). At this point
578 * we aren't sure if we need junkfilters, so just add slots for them
579 * unconditionally. Also, if it's not a SELECT, set up a slot for use for
580 * trigger output tuples.
583 int nSlots = ExecCountSlotsNode(plan);
585 if (parseTree->resultRelations != NIL)
586 nSlots += list_length(parseTree->resultRelations);
589 if (operation != CMD_SELECT)
592 estate->es_tupleTable = ExecCreateTupleTable(nSlots);
594 if (operation != CMD_SELECT)
595 estate->es_trig_tuple_slot =
596 ExecAllocTableSlot(estate->es_tupleTable);
599 /* mark EvalPlanQual not active */
600 estate->es_topPlan = plan;
601 estate->es_evalPlanQual = NULL;
602 estate->es_evTupleNull = NULL;
603 estate->es_evTuple = NULL;
604 estate->es_useEvalPlan = false;
607 * initialize the private state information for all the nodes in the query
608 * tree. This opens files, allocates storage and leaves us ready to start
611 planstate = ExecInitNode(plan, estate);
614 * Get the tuple descriptor describing the type of tuples to return. (this
615 * is especially important if we are creating a relation with "SELECT
618 tupType = ExecGetResultType(planstate);
621 * Initialize the junk filter if needed. SELECT and INSERT queries need a
622 * filter if there are any junk attrs in the tlist. INSERT and SELECT
623 * INTO also need a filter if the plan may return raw disk tuples (else
624 * heap_insert will be scribbling on the source relation!). UPDATE and
625 * DELETE always need a filter, since there's always a junk 'ctid'
626 * attribute present --- no need to look first.
629 bool junk_filter_needed = false;
636 foreach(tlist, plan->targetlist)
638 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
642 junk_filter_needed = true;
646 if (!junk_filter_needed &&
647 (operation == CMD_INSERT || do_select_into) &&
648 ExecMayReturnRawTuples(planstate))
649 junk_filter_needed = true;
653 junk_filter_needed = true;
659 if (junk_filter_needed)
662 * If there are multiple result relations, each one needs its own
663 * junk filter. Note this is only possible for UPDATE/DELETE, so
664 * we can't be fooled by some needing a filter and some not.
666 if (parseTree->resultRelations != NIL)
668 PlanState **appendplans;
670 ResultRelInfo *resultRelInfo;
673 /* Top plan had better be an Append here. */
674 Assert(IsA(plan, Append));
675 Assert(((Append *) plan)->isTarget);
676 Assert(IsA(planstate, AppendState));
677 appendplans = ((AppendState *) planstate)->appendplans;
678 as_nplans = ((AppendState *) planstate)->as_nplans;
679 Assert(as_nplans == estate->es_num_result_relations);
680 resultRelInfo = estate->es_result_relations;
681 for (i = 0; i < as_nplans; i++)
683 PlanState *subplan = appendplans[i];
686 j = ExecInitJunkFilter(subplan->plan->targetlist,
687 resultRelInfo->ri_RelationDesc->rd_att->tdhasoid,
688 ExecAllocTableSlot(estate->es_tupleTable));
689 resultRelInfo->ri_junkFilter = j;
694 * Set active junkfilter too; at this point ExecInitAppend has
695 * already selected an active result relation...
697 estate->es_junkFilter =
698 estate->es_result_relation_info->ri_junkFilter;
702 /* Normal case with just one JunkFilter */
705 j = ExecInitJunkFilter(planstate->plan->targetlist,
707 ExecAllocTableSlot(estate->es_tupleTable));
708 estate->es_junkFilter = j;
709 if (estate->es_result_relation_info)
710 estate->es_result_relation_info->ri_junkFilter = j;
712 /* For SELECT, want to return the cleaned tuple type */
713 if (operation == CMD_SELECT)
714 tupType = j->jf_cleanTupType;
718 estate->es_junkFilter = NULL;
722 * If doing SELECT INTO, initialize the "into" relation. We must wait
723 * till now so we have the "clean" result tuple type to create the new
726 * If EXPLAIN, skip creating the "into" relation.
728 intoRelationDesc = NULL;
730 if (do_select_into && !explainOnly)
740 * Check consistency of arguments
742 if (parseTree->intoOnCommit != ONCOMMIT_NOOP && !parseTree->into->istemp)
744 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
745 errmsg("ON COMMIT can only be used on temporary tables")));
748 * find namespace to create in, check permissions
750 intoName = parseTree->into->relname;
751 namespaceId = RangeVarGetCreationNamespace(parseTree->into);
753 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
755 if (aclresult != ACLCHECK_OK)
756 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
757 get_namespace_name(namespaceId));
760 * Select tablespace to use. If not specified, use default_tablespace
761 * (which may in turn default to database's default).
763 if (parseTree->intoTableSpaceName)
765 tablespaceId = get_tablespace_oid(parseTree->intoTableSpaceName);
766 if (!OidIsValid(tablespaceId))
768 (errcode(ERRCODE_UNDEFINED_OBJECT),
769 errmsg("tablespace \"%s\" does not exist",
770 parseTree->intoTableSpaceName)));
773 tablespaceId = GetDefaultTablespace();
774 /* note InvalidOid is OK in this case */
777 /* Check permissions except when using the database's default */
778 if (OidIsValid(tablespaceId))
782 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
785 if (aclresult != ACLCHECK_OK)
786 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
787 get_tablespace_name(tablespaceId));
791 * have to copy tupType to get rid of constraints
793 tupdesc = CreateTupleDescCopy(tupType);
795 intoRelationId = heap_create_with_catalog(intoName,
805 parseTree->intoOnCommit,
806 allowSystemTableMods);
808 FreeTupleDesc(tupdesc);
811 * Advance command counter so that the newly-created relation's
812 * catalog tuples will be visible to heap_open.
814 CommandCounterIncrement();
817 * If necessary, create a TOAST table for the into relation. Note that
818 * AlterTableCreateToastTable ends with CommandCounterIncrement(), so
819 * that the TOAST table will be visible for insertion.
821 AlterTableCreateToastTable(intoRelationId, true);
824 * And open the constructed table for writing.
826 intoRelationDesc = heap_open(intoRelationId, AccessExclusiveLock);
828 /* use_wal off requires rd_targblock be initially invalid */
829 Assert(intoRelationDesc->rd_targblock == InvalidBlockNumber);
832 * We can skip WAL-logging the insertions, unless PITR is in use.
834 * Note that for a non-temp INTO table, this is safe only because we
835 * know that the catalog changes above will have been WAL-logged, and
836 * so RecordTransactionCommit will think it needs to WAL-log the
837 * eventual transaction commit. Else the commit might be lost, even
838 * though all the data is safely fsync'd ...
840 estate->es_into_relation_use_wal = XLogArchivingActive();
843 estate->es_into_relation_descriptor = intoRelationDesc;
845 queryDesc->tupDesc = tupType;
846 queryDesc->planstate = planstate;
850 * Initialize ResultRelInfo data for one result relation
853 initResultRelInfo(ResultRelInfo *resultRelInfo,
854 Index resultRelationIndex,
859 Oid resultRelationOid;
860 Relation resultRelationDesc;
862 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
863 resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
865 switch (resultRelationDesc->rd_rel->relkind)
867 case RELKIND_SEQUENCE:
869 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
870 errmsg("cannot change sequence \"%s\"",
871 RelationGetRelationName(resultRelationDesc))));
873 case RELKIND_TOASTVALUE:
875 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
876 errmsg("cannot change TOAST relation \"%s\"",
877 RelationGetRelationName(resultRelationDesc))));
881 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
882 errmsg("cannot change view \"%s\"",
883 RelationGetRelationName(resultRelationDesc))));
887 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
888 resultRelInfo->type = T_ResultRelInfo;
889 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
890 resultRelInfo->ri_RelationDesc = resultRelationDesc;
891 resultRelInfo->ri_NumIndices = 0;
892 resultRelInfo->ri_IndexRelationDescs = NULL;
893 resultRelInfo->ri_IndexRelationInfo = NULL;
894 /* make a copy so as not to depend on relcache info not changing... */
895 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
896 if (resultRelInfo->ri_TrigDesc)
898 int n = resultRelInfo->ri_TrigDesc->numtriggers;
900 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
901 palloc0(n * sizeof(FmgrInfo));
903 resultRelInfo->ri_TrigInstrument = InstrAlloc(n);
905 resultRelInfo->ri_TrigInstrument = NULL;
909 resultRelInfo->ri_TrigFunctions = NULL;
910 resultRelInfo->ri_TrigInstrument = NULL;
912 resultRelInfo->ri_ConstraintExprs = NULL;
913 resultRelInfo->ri_junkFilter = NULL;
916 * If there are indices on the result relation, open them and save
917 * descriptors in the result relation info, so that we can add new index
918 * entries for the tuples we add/update. We need not do this for a
919 * DELETE, however, since deletion doesn't affect indexes.
921 if (resultRelationDesc->rd_rel->relhasindex &&
922 operation != CMD_DELETE)
923 ExecOpenIndices(resultRelInfo);
927 * ExecContextForcesOids
929 * This is pretty grotty: when doing INSERT, UPDATE, or SELECT INTO,
930 * we need to ensure that result tuples have space for an OID iff they are
931 * going to be stored into a relation that has OIDs. In other contexts
932 * we are free to choose whether to leave space for OIDs in result tuples
933 * (we generally don't want to, but we do if a physical-tlist optimization
934 * is possible). This routine checks the plan context and returns TRUE if the
935 * choice is forced, FALSE if the choice is not forced. In the TRUE case,
936 * *hasoids is set to the required value.
938 * One reason this is ugly is that all plan nodes in the plan tree will emit
939 * tuples with space for an OID, though we really only need the topmost node
940 * to do so. However, node types like Sort don't project new tuples but just
941 * return their inputs, and in those cases the requirement propagates down
942 * to the input node. Eventually we might make this code smart enough to
943 * recognize how far down the requirement really goes, but for now we just
944 * make all plan nodes do the same thing if the top level forces the choice.
946 * We assume that estate->es_result_relation_info is already set up to
947 * describe the target relation. Note that in an UPDATE that spans an
948 * inheritance tree, some of the target relations may have OIDs and some not.
949 * We have to make the decisions on a per-relation basis as we initialize
950 * each of the child plans of the topmost Append plan.
952 * SELECT INTO is even uglier, because we don't have the INTO relation's
953 * descriptor available when this code runs; we have to look aside at a
954 * flag set by InitPlan().
957 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
959 if (planstate->state->es_select_into)
961 *hasoids = planstate->state->es_into_oids;
966 ResultRelInfo *ri = planstate->state->es_result_relation_info;
970 Relation rel = ri->ri_RelationDesc;
974 *hasoids = rel->rd_rel->relhasoids;
983 /* ----------------------------------------------------------------
986 * Cleans up the query plan -- closes files and frees up storage
988 * NOTE: we are no longer very worried about freeing storage per se
989 * in this code; FreeExecutorState should be guaranteed to release all
990 * memory that needs to be released. What we are worried about doing
991 * is closing relations and dropping buffer pins. Thus, for example,
992 * tuple tables must be cleared or dropped to ensure pins are released.
993 * ----------------------------------------------------------------
996 ExecEndPlan(PlanState *planstate, EState *estate)
998 ResultRelInfo *resultRelInfo;
1003 * shut down any PlanQual processing we were doing
1005 if (estate->es_evalPlanQual != NULL)
1006 EndEvalPlanQual(estate);
1009 * shut down the node-type-specific query processing
1011 ExecEndNode(planstate);
1014 * destroy the executor "tuple" table.
1016 ExecDropTupleTable(estate->es_tupleTable, true);
1017 estate->es_tupleTable = NULL;
1020 * close the result relation(s) if any, but hold locks until xact commit.
1022 resultRelInfo = estate->es_result_relations;
1023 for (i = estate->es_num_result_relations; i > 0; i--)
1025 /* Close indices and then the relation itself */
1026 ExecCloseIndices(resultRelInfo);
1027 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1032 * close the "into" relation if necessary, again keeping lock
1034 if (estate->es_into_relation_descriptor != NULL)
1037 * If we skipped using WAL, and it's not a temp relation, we must
1038 * force the relation down to disk before it's safe to commit the
1039 * transaction. This requires forcing out any dirty buffers and then
1040 * doing a forced fsync.
1042 if (!estate->es_into_relation_use_wal &&
1043 !estate->es_into_relation_descriptor->rd_istemp)
1045 FlushRelationBuffers(estate->es_into_relation_descriptor);
1046 /* FlushRelationBuffers will have opened rd_smgr */
1047 smgrimmedsync(estate->es_into_relation_descriptor->rd_smgr);
1050 heap_close(estate->es_into_relation_descriptor, NoLock);
1054 * close any relations selected FOR UPDATE/FOR SHARE, again keeping locks
1056 foreach(l, estate->es_rowMarks)
1058 ExecRowMark *erm = lfirst(l);
1060 heap_close(erm->relation, NoLock);
1064 /* ----------------------------------------------------------------
1067 * processes the query plan to retrieve 'numberTuples' tuples in the
1068 * direction specified.
1070 * Retrieves all tuples if numberTuples is 0
1072 * result is either a slot containing the last tuple in the case
1073 * of a SELECT or NULL otherwise.
1075 * Note: the ctid attribute is a 'junk' attribute that is removed before the
1077 * ----------------------------------------------------------------
1079 static TupleTableSlot *
1080 ExecutePlan(EState *estate,
1081 PlanState *planstate,
1084 ScanDirection direction,
1087 JunkFilter *junkfilter;
1088 TupleTableSlot *slot;
1089 ItemPointer tupleid = NULL;
1090 ItemPointerData tuple_ctid;
1091 long current_tuple_count;
1092 TupleTableSlot *result;
1095 * initialize local variables
1098 current_tuple_count = 0;
1102 * Set the direction.
1104 estate->es_direction = direction;
1107 * Process BEFORE EACH STATEMENT triggers
1112 ExecBSUpdateTriggers(estate, estate->es_result_relation_info);
1115 ExecBSDeleteTriggers(estate, estate->es_result_relation_info);
1118 ExecBSInsertTriggers(estate, estate->es_result_relation_info);
1126 * Loop until we've processed the proper number of tuples from the plan.
1131 /* Reset the per-output-tuple exprcontext */
1132 ResetPerTupleExprContext(estate);
1135 * Execute the plan and obtain a tuple
1138 if (estate->es_useEvalPlan)
1140 slot = EvalPlanQualNext(estate);
1141 if (TupIsNull(slot))
1142 slot = ExecProcNode(planstate);
1145 slot = ExecProcNode(planstate);
1148 * if the tuple is null, then we assume there is nothing more to
1149 * process so we just return null...
1151 if (TupIsNull(slot))
1158 * if we have a junk filter, then project a new tuple with the junk
1161 * Store this new "clean" tuple in the junkfilter's resultSlot.
1162 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1163 * because that tuple slot has the wrong descriptor.)
1165 * Also, extract all the junk information we need.
1167 if ((junkfilter = estate->es_junkFilter) != NULL)
1173 * extract the 'ctid' junk attribute.
1175 if (operation == CMD_UPDATE || operation == CMD_DELETE)
1177 if (!ExecGetJunkAttribute(junkfilter,
1182 elog(ERROR, "could not find junk ctid column");
1184 /* shouldn't ever get a null result... */
1186 elog(ERROR, "ctid is NULL");
1188 tupleid = (ItemPointer) DatumGetPointer(datum);
1189 tuple_ctid = *tupleid; /* make sure we don't free the ctid!! */
1190 tupleid = &tuple_ctid;
1194 * Process any FOR UPDATE or FOR SHARE locking requested.
1196 else if (estate->es_rowMarks != NIL)
1201 foreach(l, estate->es_rowMarks)
1203 ExecRowMark *erm = lfirst(l);
1204 HeapTupleData tuple;
1206 ItemPointerData update_ctid;
1207 TransactionId update_xmax;
1208 TupleTableSlot *newSlot;
1209 LockTupleMode lockmode;
1212 if (!ExecGetJunkAttribute(junkfilter,
1217 elog(ERROR, "could not find junk \"%s\" column",
1220 /* shouldn't ever get a null result... */
1222 elog(ERROR, "\"%s\" is NULL", erm->resname);
1224 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1226 if (estate->es_forUpdate)
1227 lockmode = LockTupleExclusive;
1229 lockmode = LockTupleShared;
1231 test = heap_lock_tuple(erm->relation, &tuple, &buffer,
1232 &update_ctid, &update_xmax,
1233 estate->es_snapshot->curcid,
1234 lockmode, estate->es_rowNoWait);
1235 ReleaseBuffer(buffer);
1238 case HeapTupleSelfUpdated:
1239 /* treat it as deleted; do not process */
1242 case HeapTupleMayBeUpdated:
1245 case HeapTupleUpdated:
1246 if (IsXactIsoLevelSerializable)
1248 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1249 errmsg("could not serialize access due to concurrent update")));
1250 if (!ItemPointerEquals(&update_ctid,
1253 /* updated, so look at updated version */
1254 newSlot = EvalPlanQual(estate,
1258 estate->es_snapshot->curcid);
1259 if (!TupIsNull(newSlot))
1262 estate->es_useEvalPlan = true;
1268 * if tuple was deleted or PlanQual failed for
1269 * updated tuple - we must not return this tuple!
1274 elog(ERROR, "unrecognized heap_lock_tuple status: %u",
1282 * Finally create a new "clean" tuple with all junk attributes
1285 slot = ExecFilterJunk(junkfilter, slot);
1289 * now that we have a tuple, do the appropriate thing with it.. either
1290 * return it to the user, add it to a relation someplace, delete it
1291 * from a relation, or modify some of its attributes.
1296 ExecSelect(slot, /* slot containing tuple */
1297 dest, /* destination's tuple-receiver obj */
1303 ExecInsert(slot, tupleid, estate);
1308 ExecDelete(slot, tupleid, estate);
1313 ExecUpdate(slot, tupleid, estate);
1318 elog(ERROR, "unrecognized operation code: %d",
1325 * check our tuple count.. if we've processed the proper number then
1326 * quit, else loop again and process more tuples. Zero numberTuples
1329 current_tuple_count++;
1330 if (numberTuples && numberTuples == current_tuple_count)
1335 * Process AFTER EACH STATEMENT triggers
1340 ExecASUpdateTriggers(estate, estate->es_result_relation_info);
1343 ExecASDeleteTriggers(estate, estate->es_result_relation_info);
1346 ExecASInsertTriggers(estate, estate->es_result_relation_info);
1354 * here, result is either a slot containing a tuple in the case of a
1355 * SELECT or NULL otherwise.
1360 /* ----------------------------------------------------------------
1363 * SELECTs are easy.. we just pass the tuple to the appropriate
1364 * print function. The only complexity is when we do a
1365 * "SELECT INTO", in which case we insert the tuple into
1366 * the appropriate relation (note: this is a newly created relation
1367 * so we don't need to worry about indices or locks.)
1368 * ----------------------------------------------------------------
1371 ExecSelect(TupleTableSlot *slot,
1376 * insert the tuple into the "into relation"
1378 * XXX this probably ought to be replaced by a separate destination
1380 if (estate->es_into_relation_descriptor != NULL)
1384 tuple = ExecCopySlotTuple(slot);
1385 heap_insert(estate->es_into_relation_descriptor, tuple,
1386 estate->es_snapshot->curcid,
1387 estate->es_into_relation_use_wal,
1388 false); /* never any point in using FSM */
1389 /* we know there are no indexes to update */
1390 heap_freetuple(tuple);
1395 * send the tuple to the destination
1397 (*dest->receiveSlot) (slot, dest);
1399 (estate->es_processed)++;
1402 /* ----------------------------------------------------------------
1405 * INSERTs are trickier.. we have to insert the tuple into
1406 * the base relation and insert appropriate tuples into the
1408 * ----------------------------------------------------------------
1411 ExecInsert(TupleTableSlot *slot,
1412 ItemPointer tupleid,
1416 ResultRelInfo *resultRelInfo;
1417 Relation resultRelationDesc;
1421 * get the heap tuple out of the tuple table slot, making sure we have a
1424 tuple = ExecMaterializeSlot(slot);
1427 * get information on the (current) result relation
1429 resultRelInfo = estate->es_result_relation_info;
1430 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1432 /* BEFORE ROW INSERT Triggers */
1433 if (resultRelInfo->ri_TrigDesc &&
1434 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1438 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1440 if (newtuple == NULL) /* "do nothing" */
1443 if (newtuple != tuple) /* modified by Trigger(s) */
1446 * Put the modified tuple into a slot for convenience of routines
1447 * below. We assume the tuple was allocated in per-tuple memory
1448 * context, and therefore will go away by itself. The tuple table
1449 * slot should not try to clear it.
1451 TupleTableSlot *newslot = estate->es_trig_tuple_slot;
1453 if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
1454 ExecSetSlotDescriptor(newslot,
1455 slot->tts_tupleDescriptor,
1457 ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
1464 * Check the constraints of the tuple
1466 if (resultRelationDesc->rd_att->constr)
1467 ExecConstraints(resultRelInfo, slot, estate);
1472 * Note: heap_insert returns the tid (location) of the new tuple in the
1475 newId = heap_insert(resultRelationDesc, tuple,
1476 estate->es_snapshot->curcid,
1480 (estate->es_processed)++;
1481 estate->es_lastoid = newId;
1482 setLastTid(&(tuple->t_self));
1485 * insert index entries for tuple
1487 if (resultRelInfo->ri_NumIndices > 0)
1488 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1490 /* AFTER ROW INSERT Triggers */
1491 ExecARInsertTriggers(estate, resultRelInfo, tuple);
1494 /* ----------------------------------------------------------------
1497 * DELETE is like UPDATE, except that we delete the tuple and no
1498 * index modifications are needed
1499 * ----------------------------------------------------------------
1502 ExecDelete(TupleTableSlot *slot,
1503 ItemPointer tupleid,
1506 ResultRelInfo *resultRelInfo;
1507 Relation resultRelationDesc;
1509 ItemPointerData update_ctid;
1510 TransactionId update_xmax;
1513 * get information on the (current) result relation
1515 resultRelInfo = estate->es_result_relation_info;
1516 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1518 /* BEFORE ROW DELETE Triggers */
1519 if (resultRelInfo->ri_TrigDesc &&
1520 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1524 dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid,
1525 estate->es_snapshot->curcid);
1527 if (!dodelete) /* "do nothing" */
1534 * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
1535 * the row to be deleted is visible to that snapshot, and throw a can't-
1536 * serialize error if not. This is a special-case behavior needed for
1537 * referential integrity updates in serializable transactions.
1540 result = heap_delete(resultRelationDesc, tupleid,
1541 &update_ctid, &update_xmax,
1542 estate->es_snapshot->curcid,
1543 estate->es_crosscheck_snapshot,
1544 true /* wait for commit */ );
1547 case HeapTupleSelfUpdated:
1548 /* already deleted by self; nothing to do */
1551 case HeapTupleMayBeUpdated:
1554 case HeapTupleUpdated:
1555 if (IsXactIsoLevelSerializable)
1557 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1558 errmsg("could not serialize access due to concurrent update")));
1559 else if (!ItemPointerEquals(tupleid, &update_ctid))
1561 TupleTableSlot *epqslot;
1563 epqslot = EvalPlanQual(estate,
1564 resultRelInfo->ri_RangeTableIndex,
1567 estate->es_snapshot->curcid);
1568 if (!TupIsNull(epqslot))
1570 *tupleid = update_ctid;
1574 /* tuple already deleted; nothing to do */
1578 elog(ERROR, "unrecognized heap_delete status: %u", result);
1583 (estate->es_processed)++;
1586 * Note: Normally one would think that we have to delete index tuples
1587 * associated with the heap tuple now...
1589 * ... but in POSTGRES, we have no need to do this because VACUUM will
1590 * take care of it later. We can't delete index tuples immediately
1591 * anyway, since the tuple is still visible to other transactions.
1594 /* AFTER ROW DELETE Triggers */
1595 ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1598 /* ----------------------------------------------------------------
1601 * note: we can't run UPDATE queries with transactions
1602 * off because UPDATEs are actually INSERTs and our
1603 * scan will mistakenly loop forever, updating the tuple
1604 * it just inserted.. This should be fixed but until it
1605 * is, we don't want to get stuck in an infinite loop
1606 * which corrupts your database..
1607 * ----------------------------------------------------------------
1610 ExecUpdate(TupleTableSlot *slot,
1611 ItemPointer tupleid,
1615 ResultRelInfo *resultRelInfo;
1616 Relation resultRelationDesc;
1618 ItemPointerData update_ctid;
1619 TransactionId update_xmax;
1622 * abort the operation if not running transactions
1624 if (IsBootstrapProcessingMode())
1625 elog(ERROR, "cannot UPDATE during bootstrap");
1628 * get the heap tuple out of the tuple table slot, making sure we have a
1631 tuple = ExecMaterializeSlot(slot);
1634 * get information on the (current) result relation
1636 resultRelInfo = estate->es_result_relation_info;
1637 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1639 /* BEFORE ROW UPDATE Triggers */
1640 if (resultRelInfo->ri_TrigDesc &&
1641 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1645 newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
1647 estate->es_snapshot->curcid);
1649 if (newtuple == NULL) /* "do nothing" */
1652 if (newtuple != tuple) /* modified by Trigger(s) */
1655 * Put the modified tuple into a slot for convenience of routines
1656 * below. We assume the tuple was allocated in per-tuple memory
1657 * context, and therefore will go away by itself. The tuple table
1658 * slot should not try to clear it.
1660 TupleTableSlot *newslot = estate->es_trig_tuple_slot;
1662 if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
1663 ExecSetSlotDescriptor(newslot,
1664 slot->tts_tupleDescriptor,
1666 ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
1673 * Check the constraints of the tuple
1675 * If we generate a new candidate tuple after EvalPlanQual testing, we
1676 * must loop back here and recheck constraints. (We don't need to redo
1677 * triggers, however. If there are any BEFORE triggers then trigger.c
1678 * will have done heap_lock_tuple to lock the correct tuple, so there's no
1679 * need to do them again.)
1682 if (resultRelationDesc->rd_att->constr)
1683 ExecConstraints(resultRelInfo, slot, estate);
1686 * replace the heap tuple
1688 * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
1689 * the row to be updated is visible to that snapshot, and throw a can't-
1690 * serialize error if not. This is a special-case behavior needed for
1691 * referential integrity updates in serializable transactions.
1693 result = heap_update(resultRelationDesc, tupleid, tuple,
1694 &update_ctid, &update_xmax,
1695 estate->es_snapshot->curcid,
1696 estate->es_crosscheck_snapshot,
1697 true /* wait for commit */ );
1700 case HeapTupleSelfUpdated:
1701 /* already deleted by self; nothing to do */
1704 case HeapTupleMayBeUpdated:
1707 case HeapTupleUpdated:
1708 if (IsXactIsoLevelSerializable)
1710 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1711 errmsg("could not serialize access due to concurrent update")));
1712 else if (!ItemPointerEquals(tupleid, &update_ctid))
1714 TupleTableSlot *epqslot;
1716 epqslot = EvalPlanQual(estate,
1717 resultRelInfo->ri_RangeTableIndex,
1720 estate->es_snapshot->curcid);
1721 if (!TupIsNull(epqslot))
1723 *tupleid = update_ctid;
1724 slot = ExecFilterJunk(estate->es_junkFilter, epqslot);
1725 tuple = ExecMaterializeSlot(slot);
1729 /* tuple already deleted; nothing to do */
1733 elog(ERROR, "unrecognized heap_update status: %u", result);
1738 (estate->es_processed)++;
1741 * Note: instead of having to update the old index tuples associated with
1742 * the heap tuple, all we do is form and insert new index tuples. This is
1743 * because UPDATEs are actually DELETEs and INSERTs, and index tuple
1744 * deletion is done later by VACUUM (see notes in ExecDelete). All we do
1745 * here is insert new index tuples. -cim 9/27/89
1749 * insert index entries for tuple
1751 * Note: heap_update returns the tid (location) of the new tuple in the
1754 if (resultRelInfo->ri_NumIndices > 0)
1755 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1757 /* AFTER ROW UPDATE Triggers */
1758 ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
1762 ExecRelCheck(ResultRelInfo *resultRelInfo,
1763 TupleTableSlot *slot, EState *estate)
1765 Relation rel = resultRelInfo->ri_RelationDesc;
1766 int ncheck = rel->rd_att->constr->num_check;
1767 ConstrCheck *check = rel->rd_att->constr->check;
1768 ExprContext *econtext;
1769 MemoryContext oldContext;
1774 * If first time through for this result relation, build expression
1775 * nodetrees for rel's constraint expressions. Keep them in the per-query
1776 * memory context so they'll survive throughout the query.
1778 if (resultRelInfo->ri_ConstraintExprs == NULL)
1780 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1781 resultRelInfo->ri_ConstraintExprs =
1782 (List **) palloc(ncheck * sizeof(List *));
1783 for (i = 0; i < ncheck; i++)
1785 /* ExecQual wants implicit-AND form */
1786 qual = make_ands_implicit(stringToNode(check[i].ccbin));
1787 resultRelInfo->ri_ConstraintExprs[i] = (List *)
1788 ExecPrepareExpr((Expr *) qual, estate);
1790 MemoryContextSwitchTo(oldContext);
1794 * We will use the EState's per-tuple context for evaluating constraint
1795 * expressions (creating it if it's not already there).
1797 econtext = GetPerTupleExprContext(estate);
1799 /* Arrange for econtext's scan tuple to be the tuple under test */
1800 econtext->ecxt_scantuple = slot;
1802 /* And evaluate the constraints */
1803 for (i = 0; i < ncheck; i++)
1805 qual = resultRelInfo->ri_ConstraintExprs[i];
1808 * NOTE: SQL92 specifies that a NULL result from a constraint
1809 * expression is not to be treated as a failure. Therefore, tell
1810 * ExecQual to return TRUE for NULL.
1812 if (!ExecQual(qual, econtext, true))
1813 return check[i].ccname;
1816 /* NULL result means no error */
1821 ExecConstraints(ResultRelInfo *resultRelInfo,
1822 TupleTableSlot *slot, EState *estate)
1824 Relation rel = resultRelInfo->ri_RelationDesc;
1825 TupleConstr *constr = rel->rd_att->constr;
1829 if (constr->has_not_null)
1831 int natts = rel->rd_att->natts;
1834 for (attrChk = 1; attrChk <= natts; attrChk++)
1836 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1837 slot_attisnull(slot, attrChk))
1839 (errcode(ERRCODE_NOT_NULL_VIOLATION),
1840 errmsg("null value in column \"%s\" violates not-null constraint",
1841 NameStr(rel->rd_att->attrs[attrChk - 1]->attname))));
1845 if (constr->num_check > 0)
1849 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1851 (errcode(ERRCODE_CHECK_VIOLATION),
1852 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1853 RelationGetRelationName(rel), failed)));
1858 * Check a modified tuple to see if we want to process its updated version
1859 * under READ COMMITTED rules.
1861 * See backend/executor/README for some info about how this works.
1863 * estate - executor state data
1864 * rti - rangetable index of table containing tuple
1865 * *tid - t_ctid from the outdated tuple (ie, next updated version)
1866 * priorXmax - t_xmax from the outdated tuple
1867 * curCid - command ID of current command of my transaction
1869 * *tid is also an output parameter: it's modified to hold the TID of the
1870 * latest version of the tuple (note this may be changed even on failure)
1872 * Returns a slot containing the new candidate update/delete tuple, or
1873 * NULL if we determine we shouldn't process the row.
1876 EvalPlanQual(EState *estate, Index rti,
1877 ItemPointer tid, TransactionId priorXmax, CommandId curCid)
1882 HeapTupleData tuple;
1883 HeapTuple copyTuple = NULL;
1889 * find relation containing target tuple
1891 if (estate->es_result_relation_info != NULL &&
1892 estate->es_result_relation_info->ri_RangeTableIndex == rti)
1893 relation = estate->es_result_relation_info->ri_RelationDesc;
1899 foreach(l, estate->es_rowMarks)
1901 if (((ExecRowMark *) lfirst(l))->rti == rti)
1903 relation = ((ExecRowMark *) lfirst(l))->relation;
1907 if (relation == NULL)
1908 elog(ERROR, "could not find RowMark for RT index %u", rti);
1914 * Loop here to deal with updated or busy tuples
1916 tuple.t_self = *tid;
1921 if (heap_fetch(relation, SnapshotDirty, &tuple, &buffer, true, NULL))
1924 * If xmin isn't what we're expecting, the slot must have been
1925 * recycled and reused for an unrelated tuple. This implies that
1926 * the latest version of the row was deleted, so we need do
1927 * nothing. (Should be safe to examine xmin without getting
1928 * buffer's content lock, since xmin never changes in an existing
1931 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1934 ReleaseBuffer(buffer);
1938 /* otherwise xmin should not be dirty... */
1939 if (TransactionIdIsValid(SnapshotDirty->xmin))
1940 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
1943 * If tuple is being updated by other transaction then we have to
1944 * wait for its commit/abort.
1946 if (TransactionIdIsValid(SnapshotDirty->xmax))
1948 ReleaseBuffer(buffer);
1949 XactLockTableWait(SnapshotDirty->xmax);
1950 continue; /* loop back to repeat heap_fetch */
1954 * If tuple was inserted by our own transaction, we have to check
1955 * cmin against curCid: cmin >= curCid means our command cannot
1956 * see the tuple, so we should ignore it. Without this we are
1957 * open to the "Halloween problem" of indefinitely re-updating
1958 * the same tuple. (We need not check cmax because
1959 * HeapTupleSatisfiesDirty will consider a tuple deleted by
1960 * our transaction dead, regardless of cmax.) We just checked
1961 * that priorXmax == xmin, so we can test that variable instead
1962 * of doing HeapTupleHeaderGetXmin again.
1964 if (TransactionIdIsCurrentTransactionId(priorXmax) &&
1965 HeapTupleHeaderGetCmin(tuple.t_data) >= curCid)
1967 ReleaseBuffer(buffer);
1972 * We got tuple - now copy it for use by recheck query.
1974 copyTuple = heap_copytuple(&tuple);
1975 ReleaseBuffer(buffer);
1980 * If the referenced slot was actually empty, the latest version of
1981 * the row must have been deleted, so we need do nothing.
1983 if (tuple.t_data == NULL)
1985 ReleaseBuffer(buffer);
1990 * As above, if xmin isn't what we're expecting, do nothing.
1992 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1995 ReleaseBuffer(buffer);
2000 * If we get here, the tuple was found but failed SnapshotDirty.
2001 * Assuming the xmin is either a committed xact or our own xact (as it
2002 * certainly should be if we're trying to modify the tuple), this must
2003 * mean that the row was updated or deleted by either a committed xact
2004 * or our own xact. If it was deleted, we can ignore it; if it was
2005 * updated then chain up to the next version and repeat the whole
2008 * As above, it should be safe to examine xmax and t_ctid without the
2009 * buffer content lock, because they can't be changing.
2011 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
2013 /* deleted, so forget about it */
2014 ReleaseBuffer(buffer);
2018 /* updated, so look at the updated row */
2019 tuple.t_self = tuple.t_data->t_ctid;
2020 /* updated row should have xmin matching this xmax */
2021 priorXmax = HeapTupleHeaderGetXmax(tuple.t_data);
2022 ReleaseBuffer(buffer);
2023 /* loop back to fetch next in chain */
2027 * For UPDATE/DELETE we have to return tid of actual row we're executing
2030 *tid = tuple.t_self;
2033 * Need to run a recheck subquery. Find or create a PQ stack entry.
2035 epq = estate->es_evalPlanQual;
2038 if (epq != NULL && epq->rti == 0)
2040 /* Top PQ stack entry is idle, so re-use it */
2041 Assert(!(estate->es_useEvalPlan) && epq->next == NULL);
2047 * If this is request for another RTE - Ra, - then we have to check wasn't
2048 * PlanQual requested for Ra already and if so then Ra' row was updated
2049 * again and we have to re-start old execution for Ra and forget all what
2050 * we done after Ra was suspended. Cool? -:))
2052 if (epq != NULL && epq->rti != rti &&
2053 epq->estate->es_evTuple[rti - 1] != NULL)
2057 evalPlanQual *oldepq;
2059 /* stop execution */
2060 EvalPlanQualStop(epq);
2061 /* pop previous PlanQual from the stack */
2063 Assert(oldepq && oldepq->rti != 0);
2064 /* push current PQ to freePQ stack */
2067 estate->es_evalPlanQual = epq;
2068 } while (epq->rti != rti);
2072 * If we are requested for another RTE then we have to suspend execution
2073 * of current PlanQual and start execution for new one.
2075 if (epq == NULL || epq->rti != rti)
2077 /* try to reuse plan used previously */
2078 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
2080 if (newepq == NULL) /* first call or freePQ stack is empty */
2082 newepq = (evalPlanQual *) palloc0(sizeof(evalPlanQual));
2083 newepq->free = NULL;
2084 newepq->estate = NULL;
2085 newepq->planstate = NULL;
2089 /* recycle previously used PlanQual */
2090 Assert(newepq->estate == NULL);
2093 /* push current PQ to the stack */
2096 estate->es_evalPlanQual = epq;
2101 Assert(epq->rti == rti);
2104 * Ok - we're requested for the same RTE. Unfortunately we still have to
2105 * end and restart execution of the plan, because ExecReScan wouldn't
2106 * ensure that upper plan nodes would reset themselves. We could make
2107 * that work if insertion of the target tuple were integrated with the
2108 * Param mechanism somehow, so that the upper plan nodes know that their
2109 * children's outputs have changed.
2111 * Note that the stack of free evalPlanQual nodes is quite useless at the
2112 * moment, since it only saves us from pallocing/releasing the
2113 * evalPlanQual nodes themselves. But it will be useful once we implement
2114 * ReScan instead of end/restart for re-using PlanQual nodes.
2118 /* stop execution */
2119 EvalPlanQualStop(epq);
2123 * Initialize new recheck query.
2125 * Note: if we were re-using PlanQual plans via ExecReScan, we'd need to
2126 * instead copy down changeable state from the top plan (including
2127 * es_result_relation_info, es_junkFilter) and reset locally changeable
2128 * state in the epq (including es_param_exec_vals, es_evTupleNull).
2130 EvalPlanQualStart(epq, estate, epq->next);
2133 * free old RTE' tuple, if any, and store target tuple where relation's
2134 * scan node will see it
2136 epqstate = epq->estate;
2137 if (epqstate->es_evTuple[rti - 1] != NULL)
2138 heap_freetuple(epqstate->es_evTuple[rti - 1]);
2139 epqstate->es_evTuple[rti - 1] = copyTuple;
2141 return EvalPlanQualNext(estate);
2144 static TupleTableSlot *
2145 EvalPlanQualNext(EState *estate)
2147 evalPlanQual *epq = estate->es_evalPlanQual;
2148 MemoryContext oldcontext;
2149 TupleTableSlot *slot;
2151 Assert(epq->rti != 0);
2154 oldcontext = MemoryContextSwitchTo(epq->estate->es_query_cxt);
2155 slot = ExecProcNode(epq->planstate);
2156 MemoryContextSwitchTo(oldcontext);
2159 * No more tuples for this PQ. Continue previous one.
2161 if (TupIsNull(slot))
2163 evalPlanQual *oldepq;
2165 /* stop execution */
2166 EvalPlanQualStop(epq);
2167 /* pop old PQ from the stack */
2171 /* this is the first (oldest) PQ - mark as free */
2173 estate->es_useEvalPlan = false;
2174 /* and continue Query execution */
2177 Assert(oldepq->rti != 0);
2178 /* push current PQ to freePQ stack */
2181 estate->es_evalPlanQual = epq;
2189 EndEvalPlanQual(EState *estate)
2191 evalPlanQual *epq = estate->es_evalPlanQual;
2193 if (epq->rti == 0) /* plans already shutdowned */
2195 Assert(epq->next == NULL);
2201 evalPlanQual *oldepq;
2203 /* stop execution */
2204 EvalPlanQualStop(epq);
2205 /* pop old PQ from the stack */
2209 /* this is the first (oldest) PQ - mark as free */
2211 estate->es_useEvalPlan = false;
2214 Assert(oldepq->rti != 0);
2215 /* push current PQ to freePQ stack */
2218 estate->es_evalPlanQual = epq;
2223 * Start execution of one level of PlanQual.
2225 * This is a cut-down version of ExecutorStart(): we copy some state from
2226 * the top-level estate rather than initializing it fresh.
2229 EvalPlanQualStart(evalPlanQual *epq, EState *estate, evalPlanQual *priorepq)
2233 MemoryContext oldcontext;
2235 rtsize = list_length(estate->es_range_table);
2237 epq->estate = epqstate = CreateExecutorState();
2239 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2242 * The epqstates share the top query's copy of unchanging state such as
2243 * the snapshot, rangetable, result-rel info, and external Param info.
2244 * They need their own copies of local state, including a tuple table,
2245 * es_param_exec_vals, etc.
2247 epqstate->es_direction = ForwardScanDirection;
2248 epqstate->es_snapshot = estate->es_snapshot;
2249 epqstate->es_crosscheck_snapshot = estate->es_crosscheck_snapshot;
2250 epqstate->es_range_table = estate->es_range_table;
2251 epqstate->es_result_relations = estate->es_result_relations;
2252 epqstate->es_num_result_relations = estate->es_num_result_relations;
2253 epqstate->es_result_relation_info = estate->es_result_relation_info;
2254 epqstate->es_junkFilter = estate->es_junkFilter;
2255 epqstate->es_into_relation_descriptor = estate->es_into_relation_descriptor;
2256 epqstate->es_into_relation_use_wal = estate->es_into_relation_use_wal;
2257 epqstate->es_param_list_info = estate->es_param_list_info;
2258 if (estate->es_topPlan->nParamExec > 0)
2259 epqstate->es_param_exec_vals = (ParamExecData *)
2260 palloc0(estate->es_topPlan->nParamExec * sizeof(ParamExecData));
2261 epqstate->es_rowMarks = estate->es_rowMarks;
2262 epqstate->es_forUpdate = estate->es_forUpdate;
2263 epqstate->es_rowNoWait = estate->es_rowNoWait;
2264 epqstate->es_instrument = estate->es_instrument;
2265 epqstate->es_select_into = estate->es_select_into;
2266 epqstate->es_into_oids = estate->es_into_oids;
2267 epqstate->es_topPlan = estate->es_topPlan;
2270 * Each epqstate must have its own es_evTupleNull state, but all the stack
2271 * entries share es_evTuple state. This allows sub-rechecks to inherit
2272 * the value being examined by an outer recheck.
2274 epqstate->es_evTupleNull = (bool *) palloc0(rtsize * sizeof(bool));
2275 if (priorepq == NULL)
2276 /* first PQ stack entry */
2277 epqstate->es_evTuple = (HeapTuple *)
2278 palloc0(rtsize * sizeof(HeapTuple));
2280 /* later stack entries share the same storage */
2281 epqstate->es_evTuple = priorepq->estate->es_evTuple;
2283 epqstate->es_tupleTable =
2284 ExecCreateTupleTable(estate->es_tupleTable->size);
2286 epq->planstate = ExecInitNode(estate->es_topPlan, epqstate);
2288 MemoryContextSwitchTo(oldcontext);
2292 * End execution of one level of PlanQual.
2294 * This is a cut-down version of ExecutorEnd(); basically we want to do most
2295 * of the normal cleanup, but *not* close result relations (which we are
2296 * just sharing from the outer query).
2299 EvalPlanQualStop(evalPlanQual *epq)
2301 EState *epqstate = epq->estate;
2302 MemoryContext oldcontext;
2304 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2306 ExecEndNode(epq->planstate);
2308 ExecDropTupleTable(epqstate->es_tupleTable, true);
2309 epqstate->es_tupleTable = NULL;
2311 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
2313 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
2314 epqstate->es_evTuple[epq->rti - 1] = NULL;
2317 MemoryContextSwitchTo(oldcontext);
2319 FreeExecutorState(epqstate);
2322 epq->planstate = NULL;