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-2006, 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.271 2006/06/16 18:42:21 tgl 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, int eflags);
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 * eflags contains flag bits as described in executor.h.
110 * NB: the CurrentMemoryContext when this is called will become the parent
111 * of the per-query context used for this Executor invocation.
112 * ----------------------------------------------------------------
115 ExecutorStart(QueryDesc *queryDesc, int eflags)
118 MemoryContext oldcontext;
120 /* sanity checks: queryDesc must not be started already */
121 Assert(queryDesc != NULL);
122 Assert(queryDesc->estate == NULL);
125 * If the transaction is read-only, we need to check if any writes are
126 * planned to non-temporary tables. EXPLAIN is considered read-only.
128 if (XactReadOnly && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
129 ExecCheckXactReadOnly(queryDesc->parsetree);
132 * Build EState, switch into per-query memory context for startup.
134 estate = CreateExecutorState();
135 queryDesc->estate = estate;
137 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
140 * Fill in parameters, if any, from queryDesc
142 estate->es_param_list_info = queryDesc->params;
144 if (queryDesc->plantree->nParamExec > 0)
145 estate->es_param_exec_vals = (ParamExecData *)
146 palloc0(queryDesc->plantree->nParamExec * sizeof(ParamExecData));
149 * Copy other important information into the EState
151 estate->es_snapshot = queryDesc->snapshot;
152 estate->es_crosscheck_snapshot = queryDesc->crosscheck_snapshot;
153 estate->es_instrument = queryDesc->doInstrument;
156 * Initialize the plan state tree
158 InitPlan(queryDesc, eflags);
160 MemoryContextSwitchTo(oldcontext);
163 /* ----------------------------------------------------------------
166 * This is the main routine of the executor module. It accepts
167 * the query descriptor from the traffic cop and executes the
170 * ExecutorStart must have been called already.
172 * If direction is NoMovementScanDirection then nothing is done
173 * except to start up/shut down the destination. Otherwise,
174 * we retrieve up to 'count' tuples in the specified direction.
176 * Note: count = 0 is interpreted as no portal limit, i.e., run to
179 * ----------------------------------------------------------------
182 ExecutorRun(QueryDesc *queryDesc,
183 ScanDirection direction, long count)
188 TupleTableSlot *result;
189 MemoryContext oldcontext;
192 Assert(queryDesc != NULL);
194 estate = queryDesc->estate;
196 Assert(estate != NULL);
199 * Switch into per-query memory context
201 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
204 * extract information from the query descriptor and the query feature.
206 operation = queryDesc->operation;
207 dest = queryDesc->dest;
210 * startup tuple receiver
212 estate->es_processed = 0;
213 estate->es_lastoid = InvalidOid;
215 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
220 if (ScanDirectionIsNoMovement(direction))
223 result = ExecutePlan(estate,
224 queryDesc->planstate,
233 (*dest->rShutdown) (dest);
235 MemoryContextSwitchTo(oldcontext);
240 /* ----------------------------------------------------------------
243 * This routine must be called at the end of execution of any
245 * ----------------------------------------------------------------
248 ExecutorEnd(QueryDesc *queryDesc)
251 MemoryContext oldcontext;
254 Assert(queryDesc != NULL);
256 estate = queryDesc->estate;
258 Assert(estate != NULL);
261 * Switch into per-query memory context to run ExecEndPlan
263 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
265 ExecEndPlan(queryDesc->planstate, estate);
268 * Must switch out of context before destroying it
270 MemoryContextSwitchTo(oldcontext);
273 * Release EState and per-query memory context. This should release
274 * everything the executor has allocated.
276 FreeExecutorState(estate);
278 /* Reset queryDesc fields that no longer point to anything */
279 queryDesc->tupDesc = NULL;
280 queryDesc->estate = NULL;
281 queryDesc->planstate = NULL;
284 /* ----------------------------------------------------------------
287 * This routine may be called on an open queryDesc to rewind it
289 * ----------------------------------------------------------------
292 ExecutorRewind(QueryDesc *queryDesc)
295 MemoryContext oldcontext;
298 Assert(queryDesc != NULL);
300 estate = queryDesc->estate;
302 Assert(estate != NULL);
304 /* It's probably not sensible to rescan updating queries */
305 Assert(queryDesc->operation == CMD_SELECT);
308 * Switch into per-query memory context
310 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
315 ExecReScan(queryDesc->planstate, NULL);
317 MemoryContextSwitchTo(oldcontext);
323 * Check access permissions for all relations listed in a range table.
326 ExecCheckRTPerms(List *rangeTable)
330 foreach(l, rangeTable)
332 RangeTblEntry *rte = lfirst(l);
334 ExecCheckRTEPerms(rte);
340 * Check access permissions for a single RTE.
343 ExecCheckRTEPerms(RangeTblEntry *rte)
345 AclMode requiredPerms;
350 * Only plain-relation RTEs need to be checked here. Subquery RTEs are
351 * checked by ExecInitSubqueryScan if the subquery is still a separate
352 * subquery --- if it's been pulled up into our query level then the RTEs
353 * are in our rangetable and will be checked here. Function RTEs are
354 * checked by init_fcache when the function is prepared for execution.
355 * Join and special RTEs need no checks.
357 if (rte->rtekind != RTE_RELATION)
361 * No work if requiredPerms is empty.
363 requiredPerms = rte->requiredPerms;
364 if (requiredPerms == 0)
370 * userid to check as: current user unless we have a setuid indication.
372 * Note: GetUserId() is presently fast enough that there's no harm in
373 * calling it separately for each RTE. If that stops being true, we could
374 * call it once in ExecCheckRTPerms and pass the userid down from there.
375 * But for now, no need for the extra clutter.
377 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
380 * We must have *all* the requiredPerms bits, so use aclmask not aclcheck.
382 if (pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL)
384 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
385 get_rel_name(relOid));
389 * Check that the query does not imply any writes to non-temp tables.
392 ExecCheckXactReadOnly(Query *parsetree)
397 * CREATE TABLE AS or SELECT INTO?
399 * XXX should we allow this if the destination is temp?
401 if (parsetree->into != NULL)
404 /* Fail if write permissions are requested on any non-temp table */
405 foreach(l, parsetree->rtable)
407 RangeTblEntry *rte = lfirst(l);
409 if (rte->rtekind == RTE_SUBQUERY)
411 ExecCheckXactReadOnly(rte->subquery);
415 if (rte->rtekind != RTE_RELATION)
418 if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
421 if (isTempNamespace(get_rel_namespace(rte->relid)))
431 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
432 errmsg("transaction is read-only")));
436 /* ----------------------------------------------------------------
439 * Initializes the query plan: open files, allocate storage
440 * and start up the rule manager
441 * ----------------------------------------------------------------
444 InitPlan(QueryDesc *queryDesc, int eflags)
446 CmdType operation = queryDesc->operation;
447 Query *parseTree = queryDesc->parsetree;
448 Plan *plan = queryDesc->plantree;
449 EState *estate = queryDesc->estate;
450 PlanState *planstate;
452 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;
491 numResultRelations = list_length(resultRelations);
492 resultRelInfos = (ResultRelInfo *)
493 palloc(numResultRelations * sizeof(ResultRelInfo));
494 resultRelInfo = resultRelInfos;
495 foreach(l, resultRelations)
497 initResultRelInfo(resultRelInfo,
501 estate->es_instrument);
508 * Single result relation identified by parseTree->resultRelation
510 numResultRelations = 1;
511 resultRelInfos = (ResultRelInfo *) palloc(sizeof(ResultRelInfo));
512 initResultRelInfo(resultRelInfos,
513 parseTree->resultRelation,
516 estate->es_instrument);
519 estate->es_result_relations = resultRelInfos;
520 estate->es_num_result_relations = numResultRelations;
521 /* Initialize to first or only result rel */
522 estate->es_result_relation_info = resultRelInfos;
527 * if no result relation, then set state appropriately
529 estate->es_result_relations = NULL;
530 estate->es_num_result_relations = 0;
531 estate->es_result_relation_info = NULL;
535 * Detect whether we're doing SELECT INTO. If so, set the es_into_oids
536 * flag appropriately so that the plan tree will be initialized with the
537 * correct tuple descriptors.
539 do_select_into = false;
541 if (operation == CMD_SELECT && parseTree->into != NULL)
543 do_select_into = true;
544 estate->es_select_into = true;
545 estate->es_into_oids = parseTree->intoHasOids;
549 * Have to lock relations selected FOR UPDATE/FOR SHARE
551 estate->es_rowMarks = NIL;
552 foreach(l, parseTree->rowMarks)
554 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
555 Oid relid = getrelid(rc->rti, rangeTable);
559 relation = heap_open(relid, RowShareLock);
560 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
561 erm->relation = relation;
563 erm->forUpdate = rc->forUpdate;
564 erm->noWait = rc->noWait;
565 snprintf(erm->resname, sizeof(erm->resname), "ctid%u", rc->rti);
566 estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
570 * initialize the executor "tuple" table. We need slots for all the plan
571 * nodes, plus possibly output slots for the junkfilter(s). At this point
572 * we aren't sure if we need junkfilters, so just add slots for them
573 * unconditionally. Also, if it's not a SELECT, set up a slot for use for
574 * trigger output tuples.
577 int nSlots = ExecCountSlotsNode(plan);
579 if (parseTree->resultRelations != NIL)
580 nSlots += list_length(parseTree->resultRelations);
583 if (operation != CMD_SELECT)
586 estate->es_tupleTable = ExecCreateTupleTable(nSlots);
588 if (operation != CMD_SELECT)
589 estate->es_trig_tuple_slot =
590 ExecAllocTableSlot(estate->es_tupleTable);
593 /* mark EvalPlanQual not active */
594 estate->es_topPlan = plan;
595 estate->es_evalPlanQual = NULL;
596 estate->es_evTupleNull = NULL;
597 estate->es_evTuple = NULL;
598 estate->es_useEvalPlan = false;
601 * initialize the private state information for all the nodes in the query
602 * tree. This opens files, allocates storage and leaves us ready to start
605 planstate = ExecInitNode(plan, estate, eflags);
608 * Get the tuple descriptor describing the type of tuples to return. (this
609 * is especially important if we are creating a relation with "SELECT
612 tupType = ExecGetResultType(planstate);
615 * Initialize the junk filter if needed. SELECT and INSERT queries need a
616 * filter if there are any junk attrs in the tlist. INSERT and SELECT
617 * INTO also need a filter if the plan may return raw disk tuples (else
618 * heap_insert will be scribbling on the source relation!). UPDATE and
619 * DELETE always need a filter, since there's always a junk 'ctid'
620 * attribute present --- no need to look first.
623 bool junk_filter_needed = false;
630 foreach(tlist, plan->targetlist)
632 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
636 junk_filter_needed = true;
640 if (!junk_filter_needed &&
641 (operation == CMD_INSERT || do_select_into) &&
642 ExecMayReturnRawTuples(planstate))
643 junk_filter_needed = true;
647 junk_filter_needed = true;
653 if (junk_filter_needed)
656 * If there are multiple result relations, each one needs its own
657 * junk filter. Note this is only possible for UPDATE/DELETE, so
658 * we can't be fooled by some needing a filter and some not.
660 if (parseTree->resultRelations != NIL)
662 PlanState **appendplans;
664 ResultRelInfo *resultRelInfo;
667 /* Top plan had better be an Append here. */
668 Assert(IsA(plan, Append));
669 Assert(((Append *) plan)->isTarget);
670 Assert(IsA(planstate, AppendState));
671 appendplans = ((AppendState *) planstate)->appendplans;
672 as_nplans = ((AppendState *) planstate)->as_nplans;
673 Assert(as_nplans == estate->es_num_result_relations);
674 resultRelInfo = estate->es_result_relations;
675 for (i = 0; i < as_nplans; i++)
677 PlanState *subplan = appendplans[i];
680 j = ExecInitJunkFilter(subplan->plan->targetlist,
681 resultRelInfo->ri_RelationDesc->rd_att->tdhasoid,
682 ExecAllocTableSlot(estate->es_tupleTable));
683 resultRelInfo->ri_junkFilter = j;
688 * Set active junkfilter too; at this point ExecInitAppend has
689 * already selected an active result relation...
691 estate->es_junkFilter =
692 estate->es_result_relation_info->ri_junkFilter;
696 /* Normal case with just one JunkFilter */
699 j = ExecInitJunkFilter(planstate->plan->targetlist,
701 ExecAllocTableSlot(estate->es_tupleTable));
702 estate->es_junkFilter = j;
703 if (estate->es_result_relation_info)
704 estate->es_result_relation_info->ri_junkFilter = j;
706 /* For SELECT, want to return the cleaned tuple type */
707 if (operation == CMD_SELECT)
708 tupType = j->jf_cleanTupType;
712 estate->es_junkFilter = NULL;
716 * If doing SELECT INTO, initialize the "into" relation. We must wait
717 * till now so we have the "clean" result tuple type to create the new
720 * If EXPLAIN, skip creating the "into" relation.
722 intoRelationDesc = NULL;
724 if (do_select_into && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
734 * Check consistency of arguments
736 if (parseTree->intoOnCommit != ONCOMMIT_NOOP && !parseTree->into->istemp)
738 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
739 errmsg("ON COMMIT can only be used on temporary tables")));
742 * find namespace to create in, check permissions
744 intoName = parseTree->into->relname;
745 namespaceId = RangeVarGetCreationNamespace(parseTree->into);
747 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
749 if (aclresult != ACLCHECK_OK)
750 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
751 get_namespace_name(namespaceId));
754 * Select tablespace to use. If not specified, use default_tablespace
755 * (which may in turn default to database's default).
757 if (parseTree->intoTableSpaceName)
759 tablespaceId = get_tablespace_oid(parseTree->intoTableSpaceName);
760 if (!OidIsValid(tablespaceId))
762 (errcode(ERRCODE_UNDEFINED_OBJECT),
763 errmsg("tablespace \"%s\" does not exist",
764 parseTree->intoTableSpaceName)));
767 tablespaceId = GetDefaultTablespace();
768 /* note InvalidOid is OK in this case */
771 /* Check permissions except when using the database's default */
772 if (OidIsValid(tablespaceId))
776 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
779 if (aclresult != ACLCHECK_OK)
780 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
781 get_tablespace_name(tablespaceId));
785 * have to copy tupType to get rid of constraints
787 tupdesc = CreateTupleDescCopy(tupType);
789 intoRelationId = heap_create_with_catalog(intoName,
799 parseTree->intoOnCommit,
800 allowSystemTableMods);
802 FreeTupleDesc(tupdesc);
805 * Advance command counter so that the newly-created relation's
806 * catalog tuples will be visible to heap_open.
808 CommandCounterIncrement();
811 * If necessary, create a TOAST table for the into relation. Note that
812 * AlterTableCreateToastTable ends with CommandCounterIncrement(), so
813 * that the TOAST table will be visible for insertion.
815 AlterTableCreateToastTable(intoRelationId, true);
818 * And open the constructed table for writing.
820 intoRelationDesc = heap_open(intoRelationId, AccessExclusiveLock);
822 /* use_wal off requires rd_targblock be initially invalid */
823 Assert(intoRelationDesc->rd_targblock == InvalidBlockNumber);
826 * We can skip WAL-logging the insertions, unless PITR is in use.
828 * Note that for a non-temp INTO table, this is safe only because we
829 * know that the catalog changes above will have been WAL-logged, and
830 * so RecordTransactionCommit will think it needs to WAL-log the
831 * eventual transaction commit. Else the commit might be lost, even
832 * though all the data is safely fsync'd ...
834 estate->es_into_relation_use_wal = XLogArchivingActive();
837 estate->es_into_relation_descriptor = intoRelationDesc;
839 queryDesc->tupDesc = tupType;
840 queryDesc->planstate = planstate;
844 * Initialize ResultRelInfo data for one result relation
847 initResultRelInfo(ResultRelInfo *resultRelInfo,
848 Index resultRelationIndex,
853 Oid resultRelationOid;
854 Relation resultRelationDesc;
856 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
857 resultRelationDesc = heap_open(resultRelationOid, RowExclusiveLock);
859 switch (resultRelationDesc->rd_rel->relkind)
861 case RELKIND_SEQUENCE:
863 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
864 errmsg("cannot change sequence \"%s\"",
865 RelationGetRelationName(resultRelationDesc))));
867 case RELKIND_TOASTVALUE:
869 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
870 errmsg("cannot change TOAST relation \"%s\"",
871 RelationGetRelationName(resultRelationDesc))));
875 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
876 errmsg("cannot change view \"%s\"",
877 RelationGetRelationName(resultRelationDesc))));
881 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
882 resultRelInfo->type = T_ResultRelInfo;
883 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
884 resultRelInfo->ri_RelationDesc = resultRelationDesc;
885 resultRelInfo->ri_NumIndices = 0;
886 resultRelInfo->ri_IndexRelationDescs = NULL;
887 resultRelInfo->ri_IndexRelationInfo = NULL;
888 /* make a copy so as not to depend on relcache info not changing... */
889 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
890 if (resultRelInfo->ri_TrigDesc)
892 int n = resultRelInfo->ri_TrigDesc->numtriggers;
894 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
895 palloc0(n * sizeof(FmgrInfo));
897 resultRelInfo->ri_TrigInstrument = InstrAlloc(n);
899 resultRelInfo->ri_TrigInstrument = NULL;
903 resultRelInfo->ri_TrigFunctions = NULL;
904 resultRelInfo->ri_TrigInstrument = NULL;
906 resultRelInfo->ri_ConstraintExprs = NULL;
907 resultRelInfo->ri_junkFilter = NULL;
910 * If there are indices on the result relation, open them and save
911 * descriptors in the result relation info, so that we can add new index
912 * entries for the tuples we add/update. We need not do this for a
913 * DELETE, however, since deletion doesn't affect indexes.
915 if (resultRelationDesc->rd_rel->relhasindex &&
916 operation != CMD_DELETE)
917 ExecOpenIndices(resultRelInfo);
921 * ExecContextForcesOids
923 * This is pretty grotty: when doing INSERT, UPDATE, or SELECT INTO,
924 * we need to ensure that result tuples have space for an OID iff they are
925 * going to be stored into a relation that has OIDs. In other contexts
926 * we are free to choose whether to leave space for OIDs in result tuples
927 * (we generally don't want to, but we do if a physical-tlist optimization
928 * is possible). This routine checks the plan context and returns TRUE if the
929 * choice is forced, FALSE if the choice is not forced. In the TRUE case,
930 * *hasoids is set to the required value.
932 * One reason this is ugly is that all plan nodes in the plan tree will emit
933 * tuples with space for an OID, though we really only need the topmost node
934 * to do so. However, node types like Sort don't project new tuples but just
935 * return their inputs, and in those cases the requirement propagates down
936 * to the input node. Eventually we might make this code smart enough to
937 * recognize how far down the requirement really goes, but for now we just
938 * make all plan nodes do the same thing if the top level forces the choice.
940 * We assume that estate->es_result_relation_info is already set up to
941 * describe the target relation. Note that in an UPDATE that spans an
942 * inheritance tree, some of the target relations may have OIDs and some not.
943 * We have to make the decisions on a per-relation basis as we initialize
944 * each of the child plans of the topmost Append plan.
946 * SELECT INTO is even uglier, because we don't have the INTO relation's
947 * descriptor available when this code runs; we have to look aside at a
948 * flag set by InitPlan().
951 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
953 if (planstate->state->es_select_into)
955 *hasoids = planstate->state->es_into_oids;
960 ResultRelInfo *ri = planstate->state->es_result_relation_info;
964 Relation rel = ri->ri_RelationDesc;
968 *hasoids = rel->rd_rel->relhasoids;
977 /* ----------------------------------------------------------------
980 * Cleans up the query plan -- closes files and frees up storage
982 * NOTE: we are no longer very worried about freeing storage per se
983 * in this code; FreeExecutorState should be guaranteed to release all
984 * memory that needs to be released. What we are worried about doing
985 * is closing relations and dropping buffer pins. Thus, for example,
986 * tuple tables must be cleared or dropped to ensure pins are released.
987 * ----------------------------------------------------------------
990 ExecEndPlan(PlanState *planstate, EState *estate)
992 ResultRelInfo *resultRelInfo;
997 * shut down any PlanQual processing we were doing
999 if (estate->es_evalPlanQual != NULL)
1000 EndEvalPlanQual(estate);
1003 * shut down the node-type-specific query processing
1005 ExecEndNode(planstate);
1008 * destroy the executor "tuple" table.
1010 ExecDropTupleTable(estate->es_tupleTable, true);
1011 estate->es_tupleTable = NULL;
1014 * close the result relation(s) if any, but hold locks until xact commit.
1016 resultRelInfo = estate->es_result_relations;
1017 for (i = estate->es_num_result_relations; i > 0; i--)
1019 /* Close indices and then the relation itself */
1020 ExecCloseIndices(resultRelInfo);
1021 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1026 * close the "into" relation if necessary, again keeping lock
1028 if (estate->es_into_relation_descriptor != NULL)
1031 * If we skipped using WAL, and it's not a temp relation, we must
1032 * force the relation down to disk before it's safe to commit the
1033 * transaction. This requires forcing out any dirty buffers and then
1034 * doing a forced fsync.
1036 if (!estate->es_into_relation_use_wal &&
1037 !estate->es_into_relation_descriptor->rd_istemp)
1039 FlushRelationBuffers(estate->es_into_relation_descriptor);
1040 /* FlushRelationBuffers will have opened rd_smgr */
1041 smgrimmedsync(estate->es_into_relation_descriptor->rd_smgr);
1044 heap_close(estate->es_into_relation_descriptor, NoLock);
1048 * close any relations selected FOR UPDATE/FOR SHARE, again keeping locks
1050 foreach(l, estate->es_rowMarks)
1052 ExecRowMark *erm = lfirst(l);
1054 heap_close(erm->relation, NoLock);
1058 /* ----------------------------------------------------------------
1061 * processes the query plan to retrieve 'numberTuples' tuples in the
1062 * direction specified.
1064 * Retrieves all tuples if numberTuples is 0
1066 * result is either a slot containing the last tuple in the case
1067 * of a SELECT or NULL otherwise.
1069 * Note: the ctid attribute is a 'junk' attribute that is removed before the
1071 * ----------------------------------------------------------------
1073 static TupleTableSlot *
1074 ExecutePlan(EState *estate,
1075 PlanState *planstate,
1078 ScanDirection direction,
1081 JunkFilter *junkfilter;
1082 TupleTableSlot *slot;
1083 ItemPointer tupleid = NULL;
1084 ItemPointerData tuple_ctid;
1085 long current_tuple_count;
1086 TupleTableSlot *result;
1089 * initialize local variables
1092 current_tuple_count = 0;
1096 * Set the direction.
1098 estate->es_direction = direction;
1101 * Process BEFORE EACH STATEMENT triggers
1106 ExecBSUpdateTriggers(estate, estate->es_result_relation_info);
1109 ExecBSDeleteTriggers(estate, estate->es_result_relation_info);
1112 ExecBSInsertTriggers(estate, estate->es_result_relation_info);
1120 * Loop until we've processed the proper number of tuples from the plan.
1125 /* Reset the per-output-tuple exprcontext */
1126 ResetPerTupleExprContext(estate);
1129 * Execute the plan and obtain a tuple
1132 if (estate->es_useEvalPlan)
1134 slot = EvalPlanQualNext(estate);
1135 if (TupIsNull(slot))
1136 slot = ExecProcNode(planstate);
1139 slot = ExecProcNode(planstate);
1142 * if the tuple is null, then we assume there is nothing more to
1143 * process so we just return null...
1145 if (TupIsNull(slot))
1152 * if we have a junk filter, then project a new tuple with the junk
1155 * Store this new "clean" tuple in the junkfilter's resultSlot.
1156 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1157 * because that tuple slot has the wrong descriptor.)
1159 * Also, extract all the junk information we need.
1161 if ((junkfilter = estate->es_junkFilter) != NULL)
1167 * extract the 'ctid' junk attribute.
1169 if (operation == CMD_UPDATE || operation == CMD_DELETE)
1171 if (!ExecGetJunkAttribute(junkfilter,
1176 elog(ERROR, "could not find junk ctid column");
1178 /* shouldn't ever get a null result... */
1180 elog(ERROR, "ctid is NULL");
1182 tupleid = (ItemPointer) DatumGetPointer(datum);
1183 tuple_ctid = *tupleid; /* make sure we don't free the ctid!! */
1184 tupleid = &tuple_ctid;
1188 * Process any FOR UPDATE or FOR SHARE locking requested.
1190 else if (estate->es_rowMarks != NIL)
1195 foreach(l, estate->es_rowMarks)
1197 ExecRowMark *erm = lfirst(l);
1198 HeapTupleData tuple;
1200 ItemPointerData update_ctid;
1201 TransactionId update_xmax;
1202 TupleTableSlot *newSlot;
1203 LockTupleMode lockmode;
1206 if (!ExecGetJunkAttribute(junkfilter,
1211 elog(ERROR, "could not find junk \"%s\" column",
1214 /* shouldn't ever get a null result... */
1216 elog(ERROR, "\"%s\" is NULL", erm->resname);
1218 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1221 lockmode = LockTupleExclusive;
1223 lockmode = LockTupleShared;
1225 test = heap_lock_tuple(erm->relation, &tuple, &buffer,
1226 &update_ctid, &update_xmax,
1227 estate->es_snapshot->curcid,
1228 lockmode, erm->noWait);
1229 ReleaseBuffer(buffer);
1232 case HeapTupleSelfUpdated:
1233 /* treat it as deleted; do not process */
1236 case HeapTupleMayBeUpdated:
1239 case HeapTupleUpdated:
1240 if (IsXactIsoLevelSerializable)
1242 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1243 errmsg("could not serialize access due to concurrent update")));
1244 if (!ItemPointerEquals(&update_ctid,
1247 /* updated, so look at updated version */
1248 newSlot = EvalPlanQual(estate,
1252 estate->es_snapshot->curcid);
1253 if (!TupIsNull(newSlot))
1256 estate->es_useEvalPlan = true;
1262 * if tuple was deleted or PlanQual failed for
1263 * updated tuple - we must not return this tuple!
1268 elog(ERROR, "unrecognized heap_lock_tuple status: %u",
1276 * Finally create a new "clean" tuple with all junk attributes
1279 slot = ExecFilterJunk(junkfilter, slot);
1283 * now that we have a tuple, do the appropriate thing with it.. either
1284 * return it to the user, add it to a relation someplace, delete it
1285 * from a relation, or modify some of its attributes.
1290 ExecSelect(slot, /* slot containing tuple */
1291 dest, /* destination's tuple-receiver obj */
1297 ExecInsert(slot, tupleid, estate);
1302 ExecDelete(slot, tupleid, estate);
1307 ExecUpdate(slot, tupleid, estate);
1312 elog(ERROR, "unrecognized operation code: %d",
1319 * check our tuple count.. if we've processed the proper number then
1320 * quit, else loop again and process more tuples. Zero numberTuples
1323 current_tuple_count++;
1324 if (numberTuples && numberTuples == current_tuple_count)
1329 * Process AFTER EACH STATEMENT triggers
1334 ExecASUpdateTriggers(estate, estate->es_result_relation_info);
1337 ExecASDeleteTriggers(estate, estate->es_result_relation_info);
1340 ExecASInsertTriggers(estate, estate->es_result_relation_info);
1348 * here, result is either a slot containing a tuple in the case of a
1349 * SELECT or NULL otherwise.
1354 /* ----------------------------------------------------------------
1357 * SELECTs are easy.. we just pass the tuple to the appropriate
1358 * print function. The only complexity is when we do a
1359 * "SELECT INTO", in which case we insert the tuple into
1360 * the appropriate relation (note: this is a newly created relation
1361 * so we don't need to worry about indices or locks.)
1362 * ----------------------------------------------------------------
1365 ExecSelect(TupleTableSlot *slot,
1370 * insert the tuple into the "into relation"
1372 * XXX this probably ought to be replaced by a separate destination
1374 if (estate->es_into_relation_descriptor != NULL)
1378 tuple = ExecCopySlotTuple(slot);
1379 heap_insert(estate->es_into_relation_descriptor, tuple,
1380 estate->es_snapshot->curcid,
1381 estate->es_into_relation_use_wal,
1382 false); /* never any point in using FSM */
1383 /* we know there are no indexes to update */
1384 heap_freetuple(tuple);
1389 * send the tuple to the destination
1391 (*dest->receiveSlot) (slot, dest);
1393 (estate->es_processed)++;
1396 /* ----------------------------------------------------------------
1399 * INSERTs are trickier.. we have to insert the tuple into
1400 * the base relation and insert appropriate tuples into the
1402 * ----------------------------------------------------------------
1405 ExecInsert(TupleTableSlot *slot,
1406 ItemPointer tupleid,
1410 ResultRelInfo *resultRelInfo;
1411 Relation resultRelationDesc;
1415 * get the heap tuple out of the tuple table slot, making sure we have a
1418 tuple = ExecMaterializeSlot(slot);
1421 * get information on the (current) result relation
1423 resultRelInfo = estate->es_result_relation_info;
1424 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1426 /* BEFORE ROW INSERT Triggers */
1427 if (resultRelInfo->ri_TrigDesc &&
1428 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1432 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1434 if (newtuple == NULL) /* "do nothing" */
1437 if (newtuple != tuple) /* modified by Trigger(s) */
1440 * Put the modified tuple into a slot for convenience of routines
1441 * below. We assume the tuple was allocated in per-tuple memory
1442 * context, and therefore will go away by itself. The tuple table
1443 * slot should not try to clear it.
1445 TupleTableSlot *newslot = estate->es_trig_tuple_slot;
1447 if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
1448 ExecSetSlotDescriptor(newslot, slot->tts_tupleDescriptor);
1449 ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
1456 * Check the constraints of the tuple
1458 if (resultRelationDesc->rd_att->constr)
1459 ExecConstraints(resultRelInfo, slot, estate);
1464 * Note: heap_insert returns the tid (location) of the new tuple in the
1467 newId = heap_insert(resultRelationDesc, tuple,
1468 estate->es_snapshot->curcid,
1472 (estate->es_processed)++;
1473 estate->es_lastoid = newId;
1474 setLastTid(&(tuple->t_self));
1477 * insert index entries for tuple
1479 if (resultRelInfo->ri_NumIndices > 0)
1480 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1482 /* AFTER ROW INSERT Triggers */
1483 ExecARInsertTriggers(estate, resultRelInfo, tuple);
1486 /* ----------------------------------------------------------------
1489 * DELETE is like UPDATE, except that we delete the tuple and no
1490 * index modifications are needed
1491 * ----------------------------------------------------------------
1494 ExecDelete(TupleTableSlot *slot,
1495 ItemPointer tupleid,
1498 ResultRelInfo *resultRelInfo;
1499 Relation resultRelationDesc;
1501 ItemPointerData update_ctid;
1502 TransactionId update_xmax;
1505 * get information on the (current) result relation
1507 resultRelInfo = estate->es_result_relation_info;
1508 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1510 /* BEFORE ROW DELETE Triggers */
1511 if (resultRelInfo->ri_TrigDesc &&
1512 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1516 dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid,
1517 estate->es_snapshot->curcid);
1519 if (!dodelete) /* "do nothing" */
1526 * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
1527 * the row to be deleted is visible to that snapshot, and throw a can't-
1528 * serialize error if not. This is a special-case behavior needed for
1529 * referential integrity updates in serializable transactions.
1532 result = heap_delete(resultRelationDesc, tupleid,
1533 &update_ctid, &update_xmax,
1534 estate->es_snapshot->curcid,
1535 estate->es_crosscheck_snapshot,
1536 true /* wait for commit */ );
1539 case HeapTupleSelfUpdated:
1540 /* already deleted by self; nothing to do */
1543 case HeapTupleMayBeUpdated:
1546 case HeapTupleUpdated:
1547 if (IsXactIsoLevelSerializable)
1549 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1550 errmsg("could not serialize access due to concurrent update")));
1551 else if (!ItemPointerEquals(tupleid, &update_ctid))
1553 TupleTableSlot *epqslot;
1555 epqslot = EvalPlanQual(estate,
1556 resultRelInfo->ri_RangeTableIndex,
1559 estate->es_snapshot->curcid);
1560 if (!TupIsNull(epqslot))
1562 *tupleid = update_ctid;
1566 /* tuple already deleted; nothing to do */
1570 elog(ERROR, "unrecognized heap_delete status: %u", result);
1575 (estate->es_processed)++;
1578 * Note: Normally one would think that we have to delete index tuples
1579 * associated with the heap tuple now...
1581 * ... but in POSTGRES, we have no need to do this because VACUUM will
1582 * take care of it later. We can't delete index tuples immediately
1583 * anyway, since the tuple is still visible to other transactions.
1586 /* AFTER ROW DELETE Triggers */
1587 ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1590 /* ----------------------------------------------------------------
1593 * note: we can't run UPDATE queries with transactions
1594 * off because UPDATEs are actually INSERTs and our
1595 * scan will mistakenly loop forever, updating the tuple
1596 * it just inserted.. This should be fixed but until it
1597 * is, we don't want to get stuck in an infinite loop
1598 * which corrupts your database..
1599 * ----------------------------------------------------------------
1602 ExecUpdate(TupleTableSlot *slot,
1603 ItemPointer tupleid,
1607 ResultRelInfo *resultRelInfo;
1608 Relation resultRelationDesc;
1610 ItemPointerData update_ctid;
1611 TransactionId update_xmax;
1614 * abort the operation if not running transactions
1616 if (IsBootstrapProcessingMode())
1617 elog(ERROR, "cannot UPDATE during bootstrap");
1620 * get the heap tuple out of the tuple table slot, making sure we have a
1623 tuple = ExecMaterializeSlot(slot);
1626 * get information on the (current) result relation
1628 resultRelInfo = estate->es_result_relation_info;
1629 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1631 /* BEFORE ROW UPDATE Triggers */
1632 if (resultRelInfo->ri_TrigDesc &&
1633 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1637 newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
1639 estate->es_snapshot->curcid);
1641 if (newtuple == NULL) /* "do nothing" */
1644 if (newtuple != tuple) /* modified by Trigger(s) */
1647 * Put the modified tuple into a slot for convenience of routines
1648 * below. We assume the tuple was allocated in per-tuple memory
1649 * context, and therefore will go away by itself. The tuple table
1650 * slot should not try to clear it.
1652 TupleTableSlot *newslot = estate->es_trig_tuple_slot;
1654 if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
1655 ExecSetSlotDescriptor(newslot, slot->tts_tupleDescriptor);
1656 ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
1663 * Check the constraints of the tuple
1665 * If we generate a new candidate tuple after EvalPlanQual testing, we
1666 * must loop back here and recheck constraints. (We don't need to redo
1667 * triggers, however. If there are any BEFORE triggers then trigger.c
1668 * will have done heap_lock_tuple to lock the correct tuple, so there's no
1669 * need to do them again.)
1672 if (resultRelationDesc->rd_att->constr)
1673 ExecConstraints(resultRelInfo, slot, estate);
1676 * replace the heap tuple
1678 * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
1679 * the row to be updated is visible to that snapshot, and throw a can't-
1680 * serialize error if not. This is a special-case behavior needed for
1681 * referential integrity updates in serializable transactions.
1683 result = heap_update(resultRelationDesc, tupleid, tuple,
1684 &update_ctid, &update_xmax,
1685 estate->es_snapshot->curcid,
1686 estate->es_crosscheck_snapshot,
1687 true /* wait for commit */ );
1690 case HeapTupleSelfUpdated:
1691 /* already deleted by self; nothing to do */
1694 case HeapTupleMayBeUpdated:
1697 case HeapTupleUpdated:
1698 if (IsXactIsoLevelSerializable)
1700 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1701 errmsg("could not serialize access due to concurrent update")));
1702 else if (!ItemPointerEquals(tupleid, &update_ctid))
1704 TupleTableSlot *epqslot;
1706 epqslot = EvalPlanQual(estate,
1707 resultRelInfo->ri_RangeTableIndex,
1710 estate->es_snapshot->curcid);
1711 if (!TupIsNull(epqslot))
1713 *tupleid = update_ctid;
1714 slot = ExecFilterJunk(estate->es_junkFilter, epqslot);
1715 tuple = ExecMaterializeSlot(slot);
1719 /* tuple already deleted; nothing to do */
1723 elog(ERROR, "unrecognized heap_update status: %u", result);
1728 (estate->es_processed)++;
1731 * Note: instead of having to update the old index tuples associated with
1732 * the heap tuple, all we do is form and insert new index tuples. This is
1733 * because UPDATEs are actually DELETEs and INSERTs, and index tuple
1734 * deletion is done later by VACUUM (see notes in ExecDelete). All we do
1735 * here is insert new index tuples. -cim 9/27/89
1739 * insert index entries for tuple
1741 * Note: heap_update returns the tid (location) of the new tuple in the
1744 if (resultRelInfo->ri_NumIndices > 0)
1745 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1747 /* AFTER ROW UPDATE Triggers */
1748 ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
1752 ExecRelCheck(ResultRelInfo *resultRelInfo,
1753 TupleTableSlot *slot, EState *estate)
1755 Relation rel = resultRelInfo->ri_RelationDesc;
1756 int ncheck = rel->rd_att->constr->num_check;
1757 ConstrCheck *check = rel->rd_att->constr->check;
1758 ExprContext *econtext;
1759 MemoryContext oldContext;
1764 * If first time through for this result relation, build expression
1765 * nodetrees for rel's constraint expressions. Keep them in the per-query
1766 * memory context so they'll survive throughout the query.
1768 if (resultRelInfo->ri_ConstraintExprs == NULL)
1770 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1771 resultRelInfo->ri_ConstraintExprs =
1772 (List **) palloc(ncheck * sizeof(List *));
1773 for (i = 0; i < ncheck; i++)
1775 /* ExecQual wants implicit-AND form */
1776 qual = make_ands_implicit(stringToNode(check[i].ccbin));
1777 resultRelInfo->ri_ConstraintExprs[i] = (List *)
1778 ExecPrepareExpr((Expr *) qual, estate);
1780 MemoryContextSwitchTo(oldContext);
1784 * We will use the EState's per-tuple context for evaluating constraint
1785 * expressions (creating it if it's not already there).
1787 econtext = GetPerTupleExprContext(estate);
1789 /* Arrange for econtext's scan tuple to be the tuple under test */
1790 econtext->ecxt_scantuple = slot;
1792 /* And evaluate the constraints */
1793 for (i = 0; i < ncheck; i++)
1795 qual = resultRelInfo->ri_ConstraintExprs[i];
1798 * NOTE: SQL92 specifies that a NULL result from a constraint
1799 * expression is not to be treated as a failure. Therefore, tell
1800 * ExecQual to return TRUE for NULL.
1802 if (!ExecQual(qual, econtext, true))
1803 return check[i].ccname;
1806 /* NULL result means no error */
1811 ExecConstraints(ResultRelInfo *resultRelInfo,
1812 TupleTableSlot *slot, EState *estate)
1814 Relation rel = resultRelInfo->ri_RelationDesc;
1815 TupleConstr *constr = rel->rd_att->constr;
1819 if (constr->has_not_null)
1821 int natts = rel->rd_att->natts;
1824 for (attrChk = 1; attrChk <= natts; attrChk++)
1826 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1827 slot_attisnull(slot, attrChk))
1829 (errcode(ERRCODE_NOT_NULL_VIOLATION),
1830 errmsg("null value in column \"%s\" violates not-null constraint",
1831 NameStr(rel->rd_att->attrs[attrChk - 1]->attname))));
1835 if (constr->num_check > 0)
1839 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1841 (errcode(ERRCODE_CHECK_VIOLATION),
1842 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1843 RelationGetRelationName(rel), failed)));
1848 * Check a modified tuple to see if we want to process its updated version
1849 * under READ COMMITTED rules.
1851 * See backend/executor/README for some info about how this works.
1853 * estate - executor state data
1854 * rti - rangetable index of table containing tuple
1855 * *tid - t_ctid from the outdated tuple (ie, next updated version)
1856 * priorXmax - t_xmax from the outdated tuple
1857 * curCid - command ID of current command of my transaction
1859 * *tid is also an output parameter: it's modified to hold the TID of the
1860 * latest version of the tuple (note this may be changed even on failure)
1862 * Returns a slot containing the new candidate update/delete tuple, or
1863 * NULL if we determine we shouldn't process the row.
1866 EvalPlanQual(EState *estate, Index rti,
1867 ItemPointer tid, TransactionId priorXmax, CommandId curCid)
1872 HeapTupleData tuple;
1873 HeapTuple copyTuple = NULL;
1879 * find relation containing target tuple
1881 if (estate->es_result_relation_info != NULL &&
1882 estate->es_result_relation_info->ri_RangeTableIndex == rti)
1883 relation = estate->es_result_relation_info->ri_RelationDesc;
1889 foreach(l, estate->es_rowMarks)
1891 if (((ExecRowMark *) lfirst(l))->rti == rti)
1893 relation = ((ExecRowMark *) lfirst(l))->relation;
1897 if (relation == NULL)
1898 elog(ERROR, "could not find RowMark for RT index %u", rti);
1904 * Loop here to deal with updated or busy tuples
1906 tuple.t_self = *tid;
1911 if (heap_fetch(relation, SnapshotDirty, &tuple, &buffer, true, NULL))
1914 * If xmin isn't what we're expecting, the slot must have been
1915 * recycled and reused for an unrelated tuple. This implies that
1916 * the latest version of the row was deleted, so we need do
1917 * nothing. (Should be safe to examine xmin without getting
1918 * buffer's content lock, since xmin never changes in an existing
1921 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1924 ReleaseBuffer(buffer);
1928 /* otherwise xmin should not be dirty... */
1929 if (TransactionIdIsValid(SnapshotDirty->xmin))
1930 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
1933 * If tuple is being updated by other transaction then we have to
1934 * wait for its commit/abort.
1936 if (TransactionIdIsValid(SnapshotDirty->xmax))
1938 ReleaseBuffer(buffer);
1939 XactLockTableWait(SnapshotDirty->xmax);
1940 continue; /* loop back to repeat heap_fetch */
1944 * If tuple was inserted by our own transaction, we have to check
1945 * cmin against curCid: cmin >= curCid means our command cannot
1946 * see the tuple, so we should ignore it. Without this we are
1947 * open to the "Halloween problem" of indefinitely re-updating
1948 * the same tuple. (We need not check cmax because
1949 * HeapTupleSatisfiesDirty will consider a tuple deleted by
1950 * our transaction dead, regardless of cmax.) We just checked
1951 * that priorXmax == xmin, so we can test that variable instead
1952 * of doing HeapTupleHeaderGetXmin again.
1954 if (TransactionIdIsCurrentTransactionId(priorXmax) &&
1955 HeapTupleHeaderGetCmin(tuple.t_data) >= curCid)
1957 ReleaseBuffer(buffer);
1962 * We got tuple - now copy it for use by recheck query.
1964 copyTuple = heap_copytuple(&tuple);
1965 ReleaseBuffer(buffer);
1970 * If the referenced slot was actually empty, the latest version of
1971 * the row must have been deleted, so we need do nothing.
1973 if (tuple.t_data == NULL)
1975 ReleaseBuffer(buffer);
1980 * As above, if xmin isn't what we're expecting, do nothing.
1982 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1985 ReleaseBuffer(buffer);
1990 * If we get here, the tuple was found but failed SnapshotDirty.
1991 * Assuming the xmin is either a committed xact or our own xact (as it
1992 * certainly should be if we're trying to modify the tuple), this must
1993 * mean that the row was updated or deleted by either a committed xact
1994 * or our own xact. If it was deleted, we can ignore it; if it was
1995 * updated then chain up to the next version and repeat the whole
1998 * As above, it should be safe to examine xmax and t_ctid without the
1999 * buffer content lock, because they can't be changing.
2001 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
2003 /* deleted, so forget about it */
2004 ReleaseBuffer(buffer);
2008 /* updated, so look at the updated row */
2009 tuple.t_self = tuple.t_data->t_ctid;
2010 /* updated row should have xmin matching this xmax */
2011 priorXmax = HeapTupleHeaderGetXmax(tuple.t_data);
2012 ReleaseBuffer(buffer);
2013 /* loop back to fetch next in chain */
2017 * For UPDATE/DELETE we have to return tid of actual row we're executing
2020 *tid = tuple.t_self;
2023 * Need to run a recheck subquery. Find or create a PQ stack entry.
2025 epq = estate->es_evalPlanQual;
2028 if (epq != NULL && epq->rti == 0)
2030 /* Top PQ stack entry is idle, so re-use it */
2031 Assert(!(estate->es_useEvalPlan) && epq->next == NULL);
2037 * If this is request for another RTE - Ra, - then we have to check wasn't
2038 * PlanQual requested for Ra already and if so then Ra' row was updated
2039 * again and we have to re-start old execution for Ra and forget all what
2040 * we done after Ra was suspended. Cool? -:))
2042 if (epq != NULL && epq->rti != rti &&
2043 epq->estate->es_evTuple[rti - 1] != NULL)
2047 evalPlanQual *oldepq;
2049 /* stop execution */
2050 EvalPlanQualStop(epq);
2051 /* pop previous PlanQual from the stack */
2053 Assert(oldepq && oldepq->rti != 0);
2054 /* push current PQ to freePQ stack */
2057 estate->es_evalPlanQual = epq;
2058 } while (epq->rti != rti);
2062 * If we are requested for another RTE then we have to suspend execution
2063 * of current PlanQual and start execution for new one.
2065 if (epq == NULL || epq->rti != rti)
2067 /* try to reuse plan used previously */
2068 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
2070 if (newepq == NULL) /* first call or freePQ stack is empty */
2072 newepq = (evalPlanQual *) palloc0(sizeof(evalPlanQual));
2073 newepq->free = NULL;
2074 newepq->estate = NULL;
2075 newepq->planstate = NULL;
2079 /* recycle previously used PlanQual */
2080 Assert(newepq->estate == NULL);
2083 /* push current PQ to the stack */
2086 estate->es_evalPlanQual = epq;
2091 Assert(epq->rti == rti);
2094 * Ok - we're requested for the same RTE. Unfortunately we still have to
2095 * end and restart execution of the plan, because ExecReScan wouldn't
2096 * ensure that upper plan nodes would reset themselves. We could make
2097 * that work if insertion of the target tuple were integrated with the
2098 * Param mechanism somehow, so that the upper plan nodes know that their
2099 * children's outputs have changed.
2101 * Note that the stack of free evalPlanQual nodes is quite useless at the
2102 * moment, since it only saves us from pallocing/releasing the
2103 * evalPlanQual nodes themselves. But it will be useful once we implement
2104 * ReScan instead of end/restart for re-using PlanQual nodes.
2108 /* stop execution */
2109 EvalPlanQualStop(epq);
2113 * Initialize new recheck query.
2115 * Note: if we were re-using PlanQual plans via ExecReScan, we'd need to
2116 * instead copy down changeable state from the top plan (including
2117 * es_result_relation_info, es_junkFilter) and reset locally changeable
2118 * state in the epq (including es_param_exec_vals, es_evTupleNull).
2120 EvalPlanQualStart(epq, estate, epq->next);
2123 * free old RTE' tuple, if any, and store target tuple where relation's
2124 * scan node will see it
2126 epqstate = epq->estate;
2127 if (epqstate->es_evTuple[rti - 1] != NULL)
2128 heap_freetuple(epqstate->es_evTuple[rti - 1]);
2129 epqstate->es_evTuple[rti - 1] = copyTuple;
2131 return EvalPlanQualNext(estate);
2134 static TupleTableSlot *
2135 EvalPlanQualNext(EState *estate)
2137 evalPlanQual *epq = estate->es_evalPlanQual;
2138 MemoryContext oldcontext;
2139 TupleTableSlot *slot;
2141 Assert(epq->rti != 0);
2144 oldcontext = MemoryContextSwitchTo(epq->estate->es_query_cxt);
2145 slot = ExecProcNode(epq->planstate);
2146 MemoryContextSwitchTo(oldcontext);
2149 * No more tuples for this PQ. Continue previous one.
2151 if (TupIsNull(slot))
2153 evalPlanQual *oldepq;
2155 /* stop execution */
2156 EvalPlanQualStop(epq);
2157 /* pop old PQ from the stack */
2161 /* this is the first (oldest) PQ - mark as free */
2163 estate->es_useEvalPlan = false;
2164 /* and continue Query execution */
2167 Assert(oldepq->rti != 0);
2168 /* push current PQ to freePQ stack */
2171 estate->es_evalPlanQual = epq;
2179 EndEvalPlanQual(EState *estate)
2181 evalPlanQual *epq = estate->es_evalPlanQual;
2183 if (epq->rti == 0) /* plans already shutdowned */
2185 Assert(epq->next == NULL);
2191 evalPlanQual *oldepq;
2193 /* stop execution */
2194 EvalPlanQualStop(epq);
2195 /* pop old PQ from the stack */
2199 /* this is the first (oldest) PQ - mark as free */
2201 estate->es_useEvalPlan = false;
2204 Assert(oldepq->rti != 0);
2205 /* push current PQ to freePQ stack */
2208 estate->es_evalPlanQual = epq;
2213 * Start execution of one level of PlanQual.
2215 * This is a cut-down version of ExecutorStart(): we copy some state from
2216 * the top-level estate rather than initializing it fresh.
2219 EvalPlanQualStart(evalPlanQual *epq, EState *estate, evalPlanQual *priorepq)
2223 MemoryContext oldcontext;
2225 rtsize = list_length(estate->es_range_table);
2227 epq->estate = epqstate = CreateExecutorState();
2229 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2232 * The epqstates share the top query's copy of unchanging state such as
2233 * the snapshot, rangetable, result-rel info, and external Param info.
2234 * They need their own copies of local state, including a tuple table,
2235 * es_param_exec_vals, etc.
2237 epqstate->es_direction = ForwardScanDirection;
2238 epqstate->es_snapshot = estate->es_snapshot;
2239 epqstate->es_crosscheck_snapshot = estate->es_crosscheck_snapshot;
2240 epqstate->es_range_table = estate->es_range_table;
2241 epqstate->es_result_relations = estate->es_result_relations;
2242 epqstate->es_num_result_relations = estate->es_num_result_relations;
2243 epqstate->es_result_relation_info = estate->es_result_relation_info;
2244 epqstate->es_junkFilter = estate->es_junkFilter;
2245 epqstate->es_into_relation_descriptor = estate->es_into_relation_descriptor;
2246 epqstate->es_into_relation_use_wal = estate->es_into_relation_use_wal;
2247 epqstate->es_param_list_info = estate->es_param_list_info;
2248 if (estate->es_topPlan->nParamExec > 0)
2249 epqstate->es_param_exec_vals = (ParamExecData *)
2250 palloc0(estate->es_topPlan->nParamExec * sizeof(ParamExecData));
2251 epqstate->es_rowMarks = estate->es_rowMarks;
2252 epqstate->es_instrument = estate->es_instrument;
2253 epqstate->es_select_into = estate->es_select_into;
2254 epqstate->es_into_oids = estate->es_into_oids;
2255 epqstate->es_topPlan = estate->es_topPlan;
2258 * Each epqstate must have its own es_evTupleNull state, but all the stack
2259 * entries share es_evTuple state. This allows sub-rechecks to inherit
2260 * the value being examined by an outer recheck.
2262 epqstate->es_evTupleNull = (bool *) palloc0(rtsize * sizeof(bool));
2263 if (priorepq == NULL)
2264 /* first PQ stack entry */
2265 epqstate->es_evTuple = (HeapTuple *)
2266 palloc0(rtsize * sizeof(HeapTuple));
2268 /* later stack entries share the same storage */
2269 epqstate->es_evTuple = priorepq->estate->es_evTuple;
2271 epqstate->es_tupleTable =
2272 ExecCreateTupleTable(estate->es_tupleTable->size);
2274 epq->planstate = ExecInitNode(estate->es_topPlan, epqstate, 0);
2276 MemoryContextSwitchTo(oldcontext);
2280 * End execution of one level of PlanQual.
2282 * This is a cut-down version of ExecutorEnd(); basically we want to do most
2283 * of the normal cleanup, but *not* close result relations (which we are
2284 * just sharing from the outer query).
2287 EvalPlanQualStop(evalPlanQual *epq)
2289 EState *epqstate = epq->estate;
2290 MemoryContext oldcontext;
2292 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2294 ExecEndNode(epq->planstate);
2296 ExecDropTupleTable(epqstate->es_tupleTable, true);
2297 epqstate->es_tupleTable = NULL;
2299 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
2301 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
2302 epqstate->es_evTuple[epq->rti - 1] = NULL;
2305 MemoryContextSwitchTo(oldcontext);
2307 FreeExecutorState(epqstate);
2310 epq->planstate = NULL;