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-2008, 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.319 2008/11/30 20:51:25 tgl Exp $
31 *-------------------------------------------------------------------------
35 #include "access/heapam.h"
36 #include "access/reloptions.h"
37 #include "access/transam.h"
38 #include "access/xact.h"
39 #include "catalog/heap.h"
40 #include "catalog/namespace.h"
41 #include "catalog/toasting.h"
42 #include "commands/tablespace.h"
43 #include "commands/trigger.h"
44 #include "executor/execdebug.h"
45 #include "executor/instrument.h"
46 #include "executor/nodeSubplan.h"
47 #include "miscadmin.h"
48 #include "nodes/nodeFuncs.h"
49 #include "optimizer/clauses.h"
50 #include "parser/parse_clause.h"
51 #include "parser/parsetree.h"
52 #include "storage/bufmgr.h"
53 #include "storage/lmgr.h"
54 #include "storage/smgr.h"
55 #include "utils/acl.h"
56 #include "utils/builtins.h"
57 #include "utils/lsyscache.h"
58 #include "utils/memutils.h"
59 #include "utils/snapmgr.h"
60 #include "utils/tqual.h"
63 /* Hooks for plugins to get control in ExecutorStart/Run/End() */
64 ExecutorStart_hook_type ExecutorStart_hook = NULL;
65 ExecutorRun_hook_type ExecutorRun_hook = NULL;
66 ExecutorEnd_hook_type ExecutorEnd_hook = NULL;
68 typedef struct evalPlanQual
73 struct evalPlanQual *next; /* stack of active PlanQual plans */
74 struct evalPlanQual *free; /* list of free PlanQual plans */
77 /* decls for local routines only used within this module */
78 static void InitPlan(QueryDesc *queryDesc, int eflags);
79 static void ExecCheckPlanOutput(Relation resultRel, List *targetList);
80 static void ExecEndPlan(PlanState *planstate, EState *estate);
81 static void ExecutePlan(EState *estate, PlanState *planstate,
84 ScanDirection direction,
86 static void ExecSelect(TupleTableSlot *slot,
87 DestReceiver *dest, EState *estate);
88 static void ExecInsert(TupleTableSlot *slot, ItemPointer tupleid,
89 TupleTableSlot *planSlot,
90 DestReceiver *dest, EState *estate);
91 static void ExecDelete(ItemPointer tupleid,
92 TupleTableSlot *planSlot,
93 DestReceiver *dest, EState *estate);
94 static void ExecUpdate(TupleTableSlot *slot, ItemPointer tupleid,
95 TupleTableSlot *planSlot,
96 DestReceiver *dest, EState *estate);
97 static void ExecProcessReturning(ProjectionInfo *projectReturning,
98 TupleTableSlot *tupleSlot,
99 TupleTableSlot *planSlot,
101 static TupleTableSlot *EvalPlanQualNext(EState *estate);
102 static void EndEvalPlanQual(EState *estate);
103 static void ExecCheckRTPerms(List *rangeTable);
104 static void ExecCheckRTEPerms(RangeTblEntry *rte);
105 static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
106 static void EvalPlanQualStart(evalPlanQual *epq, EState *estate,
107 evalPlanQual *priorepq);
108 static void EvalPlanQualStop(evalPlanQual *epq);
109 static void OpenIntoRel(QueryDesc *queryDesc);
110 static void CloseIntoRel(QueryDesc *queryDesc);
111 static void intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
112 static void intorel_receive(TupleTableSlot *slot, DestReceiver *self);
113 static void intorel_shutdown(DestReceiver *self);
114 static void intorel_destroy(DestReceiver *self);
116 /* end of local decls */
119 /* ----------------------------------------------------------------
122 * This routine must be called at the beginning of any execution of any
125 * Takes a QueryDesc previously created by CreateQueryDesc (it's not real
126 * clear why we bother to separate the two functions, but...). The tupDesc
127 * field of the QueryDesc is filled in to describe the tuples that will be
128 * returned, and the internal fields (estate and planstate) are set up.
130 * eflags contains flag bits as described in executor.h.
132 * NB: the CurrentMemoryContext when this is called will become the parent
133 * of the per-query context used for this Executor invocation.
135 * We provide a function hook variable that lets loadable plugins
136 * get control when ExecutorStart is called. Such a plugin would
137 * normally call standard_ExecutorStart().
139 * ----------------------------------------------------------------
142 ExecutorStart(QueryDesc *queryDesc, int eflags)
144 if (ExecutorStart_hook)
145 (*ExecutorStart_hook) (queryDesc, eflags);
147 standard_ExecutorStart(queryDesc, eflags);
151 standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
154 MemoryContext oldcontext;
156 /* sanity checks: queryDesc must not be started already */
157 Assert(queryDesc != NULL);
158 Assert(queryDesc->estate == NULL);
161 * If the transaction is read-only, we need to check if any writes are
162 * planned to non-temporary tables. EXPLAIN is considered read-only.
164 if (XactReadOnly && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
165 ExecCheckXactReadOnly(queryDesc->plannedstmt);
168 * Build EState, switch into per-query memory context for startup.
170 estate = CreateExecutorState();
171 queryDesc->estate = estate;
173 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
176 * Fill in parameters, if any, from queryDesc
178 estate->es_param_list_info = queryDesc->params;
180 if (queryDesc->plannedstmt->nParamExec > 0)
181 estate->es_param_exec_vals = (ParamExecData *)
182 palloc0(queryDesc->plannedstmt->nParamExec * sizeof(ParamExecData));
185 * If non-read-only query, set the command ID to mark output tuples with
187 switch (queryDesc->operation)
190 /* SELECT INTO and SELECT FOR UPDATE/SHARE need to mark tuples */
191 if (queryDesc->plannedstmt->intoClause != NULL ||
192 queryDesc->plannedstmt->rowMarks != NIL)
193 estate->es_output_cid = GetCurrentCommandId(true);
199 estate->es_output_cid = GetCurrentCommandId(true);
203 elog(ERROR, "unrecognized operation code: %d",
204 (int) queryDesc->operation);
209 * Copy other important information into the EState
211 estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
212 estate->es_crosscheck_snapshot = RegisterSnapshot(queryDesc->crosscheck_snapshot);
213 estate->es_instrument = queryDesc->doInstrument;
216 * Initialize the plan state tree
218 InitPlan(queryDesc, eflags);
220 MemoryContextSwitchTo(oldcontext);
223 /* ----------------------------------------------------------------
226 * This is the main routine of the executor module. It accepts
227 * the query descriptor from the traffic cop and executes the
230 * ExecutorStart must have been called already.
232 * If direction is NoMovementScanDirection then nothing is done
233 * except to start up/shut down the destination. Otherwise,
234 * we retrieve up to 'count' tuples in the specified direction.
236 * Note: count = 0 is interpreted as no portal limit, i.e., run to
239 * There is no return value, but output tuples (if any) are sent to
240 * the destination receiver specified in the QueryDesc; and the number
241 * of tuples processed at the top level can be found in
242 * estate->es_processed.
244 * We provide a function hook variable that lets loadable plugins
245 * get control when ExecutorRun is called. Such a plugin would
246 * normally call standard_ExecutorRun().
248 * ----------------------------------------------------------------
251 ExecutorRun(QueryDesc *queryDesc,
252 ScanDirection direction, long count)
254 if (ExecutorRun_hook)
255 (*ExecutorRun_hook) (queryDesc, direction, count);
257 standard_ExecutorRun(queryDesc, direction, count);
261 standard_ExecutorRun(QueryDesc *queryDesc,
262 ScanDirection direction, long count)
268 MemoryContext oldcontext;
271 Assert(queryDesc != NULL);
273 estate = queryDesc->estate;
275 Assert(estate != NULL);
278 * Switch into per-query memory context
280 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
282 /* Allow instrumentation of ExecutorRun overall runtime */
283 if (queryDesc->totaltime)
284 InstrStartNode(queryDesc->totaltime);
287 * extract information from the query descriptor and the query feature.
289 operation = queryDesc->operation;
290 dest = queryDesc->dest;
293 * startup tuple receiver, if we will be emitting tuples
295 estate->es_processed = 0;
296 estate->es_lastoid = InvalidOid;
298 sendTuples = (operation == CMD_SELECT ||
299 queryDesc->plannedstmt->returningLists);
302 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
307 if (!ScanDirectionIsNoMovement(direction))
309 queryDesc->planstate,
316 * shutdown tuple receiver, if we started it
319 (*dest->rShutdown) (dest);
321 if (queryDesc->totaltime)
322 InstrStopNode(queryDesc->totaltime, estate->es_processed);
324 MemoryContextSwitchTo(oldcontext);
327 /* ----------------------------------------------------------------
330 * This routine must be called at the end of execution of any
333 * We provide a function hook variable that lets loadable plugins
334 * get control when ExecutorEnd is called. Such a plugin would
335 * normally call standard_ExecutorEnd().
337 * ----------------------------------------------------------------
340 ExecutorEnd(QueryDesc *queryDesc)
342 if (ExecutorEnd_hook)
343 (*ExecutorEnd_hook) (queryDesc);
345 standard_ExecutorEnd(queryDesc);
349 standard_ExecutorEnd(QueryDesc *queryDesc)
352 MemoryContext oldcontext;
355 Assert(queryDesc != NULL);
357 estate = queryDesc->estate;
359 Assert(estate != NULL);
362 * Switch into per-query memory context to run ExecEndPlan
364 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
366 ExecEndPlan(queryDesc->planstate, estate);
369 * Close the SELECT INTO relation if any
371 if (estate->es_select_into)
372 CloseIntoRel(queryDesc);
374 /* do away with our snapshots */
375 UnregisterSnapshot(estate->es_snapshot);
376 UnregisterSnapshot(estate->es_crosscheck_snapshot);
379 * Must switch out of context before destroying it
381 MemoryContextSwitchTo(oldcontext);
384 * Release EState and per-query memory context. This should release
385 * everything the executor has allocated.
387 FreeExecutorState(estate);
389 /* Reset queryDesc fields that no longer point to anything */
390 queryDesc->tupDesc = NULL;
391 queryDesc->estate = NULL;
392 queryDesc->planstate = NULL;
393 queryDesc->totaltime = NULL;
396 /* ----------------------------------------------------------------
399 * This routine may be called on an open queryDesc to rewind it
401 * ----------------------------------------------------------------
404 ExecutorRewind(QueryDesc *queryDesc)
407 MemoryContext oldcontext;
410 Assert(queryDesc != NULL);
412 estate = queryDesc->estate;
414 Assert(estate != NULL);
416 /* It's probably not sensible to rescan updating queries */
417 Assert(queryDesc->operation == CMD_SELECT);
420 * Switch into per-query memory context
422 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
427 ExecReScan(queryDesc->planstate, NULL);
429 MemoryContextSwitchTo(oldcontext);
435 * Check access permissions for all relations listed in a range table.
438 ExecCheckRTPerms(List *rangeTable)
442 foreach(l, rangeTable)
444 ExecCheckRTEPerms((RangeTblEntry *) lfirst(l));
450 * Check access permissions for a single RTE.
453 ExecCheckRTEPerms(RangeTblEntry *rte)
455 AclMode requiredPerms;
460 * Only plain-relation RTEs need to be checked here. Function RTEs are
461 * checked by init_fcache when the function is prepared for execution.
462 * Join, subquery, and special RTEs need no checks.
464 if (rte->rtekind != RTE_RELATION)
468 * No work if requiredPerms is empty.
470 requiredPerms = rte->requiredPerms;
471 if (requiredPerms == 0)
477 * userid to check as: current user unless we have a setuid indication.
479 * Note: GetUserId() is presently fast enough that there's no harm in
480 * calling it separately for each RTE. If that stops being true, we could
481 * call it once in ExecCheckRTPerms and pass the userid down from there.
482 * But for now, no need for the extra clutter.
484 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
487 * We must have *all* the requiredPerms bits, so use aclmask not aclcheck.
489 if (pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL)
491 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
492 get_rel_name(relOid));
496 * Check that the query does not imply any writes to non-temp tables.
499 ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
504 * CREATE TABLE AS or SELECT INTO?
506 * XXX should we allow this if the destination is temp?
508 if (plannedstmt->intoClause != NULL)
511 /* Fail if write permissions are requested on any non-temp table */
512 foreach(l, plannedstmt->rtable)
514 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
516 if (rte->rtekind != RTE_RELATION)
519 if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
522 if (isTempNamespace(get_rel_namespace(rte->relid)))
532 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
533 errmsg("transaction is read-only")));
537 /* ----------------------------------------------------------------
540 * Initializes the query plan: open files, allocate storage
541 * and start up the rule manager
542 * ----------------------------------------------------------------
545 InitPlan(QueryDesc *queryDesc, int eflags)
547 CmdType operation = queryDesc->operation;
548 PlannedStmt *plannedstmt = queryDesc->plannedstmt;
549 Plan *plan = plannedstmt->planTree;
550 List *rangeTable = plannedstmt->rtable;
551 EState *estate = queryDesc->estate;
552 PlanState *planstate;
558 * Do permissions checks
560 ExecCheckRTPerms(rangeTable);
563 * initialize the node's execution state
565 estate->es_range_table = rangeTable;
568 * initialize result relation stuff
570 if (plannedstmt->resultRelations)
572 List *resultRelations = plannedstmt->resultRelations;
573 int numResultRelations = list_length(resultRelations);
574 ResultRelInfo *resultRelInfos;
575 ResultRelInfo *resultRelInfo;
577 resultRelInfos = (ResultRelInfo *)
578 palloc(numResultRelations * sizeof(ResultRelInfo));
579 resultRelInfo = resultRelInfos;
580 foreach(l, resultRelations)
582 Index resultRelationIndex = lfirst_int(l);
583 Oid resultRelationOid;
584 Relation resultRelation;
586 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
587 resultRelation = heap_open(resultRelationOid, RowExclusiveLock);
588 InitResultRelInfo(resultRelInfo,
592 estate->es_instrument);
595 estate->es_result_relations = resultRelInfos;
596 estate->es_num_result_relations = numResultRelations;
597 /* Initialize to first or only result rel */
598 estate->es_result_relation_info = resultRelInfos;
603 * if no result relation, then set state appropriately
605 estate->es_result_relations = NULL;
606 estate->es_num_result_relations = 0;
607 estate->es_result_relation_info = NULL;
611 * Detect whether we're doing SELECT INTO. If so, set the es_into_oids
612 * flag appropriately so that the plan tree will be initialized with the
613 * correct tuple descriptors. (Other SELECT INTO stuff comes later.)
615 estate->es_select_into = false;
616 if (operation == CMD_SELECT && plannedstmt->intoClause != NULL)
618 estate->es_select_into = true;
619 estate->es_into_oids = interpretOidsOption(plannedstmt->intoClause->options);
623 * Have to lock relations selected FOR UPDATE/FOR SHARE before we
624 * initialize the plan tree, else we'd be doing a lock upgrade. While we
625 * are at it, build the ExecRowMark list.
627 estate->es_rowMarks = NIL;
628 foreach(l, plannedstmt->rowMarks)
630 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
635 /* ignore "parent" rowmarks; they are irrelevant at runtime */
639 relid = getrelid(rc->rti, rangeTable);
640 relation = heap_open(relid, RowShareLock);
641 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
642 erm->relation = relation;
644 erm->prti = rc->prti;
645 erm->forUpdate = rc->forUpdate;
646 erm->noWait = rc->noWait;
647 /* We'll locate the junk attrs below */
648 erm->ctidAttNo = InvalidAttrNumber;
649 erm->toidAttNo = InvalidAttrNumber;
650 ItemPointerSetInvalid(&(erm->curCtid));
651 estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
655 * Initialize the executor "tuple" table. We need slots for all the plan
656 * nodes, plus possibly output slots for the junkfilter(s). At this point
657 * we aren't sure if we need junkfilters, so just add slots for them
658 * unconditionally. Also, if it's not a SELECT, set up a slot for use for
659 * trigger output tuples. Also, one for RETURNING-list evaluation.
664 /* Slots for the main plan tree */
665 nSlots = ExecCountSlotsNode(plan);
666 /* Add slots for subplans and initplans */
667 foreach(l, plannedstmt->subplans)
669 Plan *subplan = (Plan *) lfirst(l);
671 nSlots += ExecCountSlotsNode(subplan);
673 /* Add slots for junkfilter(s) */
674 if (plannedstmt->resultRelations != NIL)
675 nSlots += list_length(plannedstmt->resultRelations);
678 if (operation != CMD_SELECT)
679 nSlots++; /* for es_trig_tuple_slot */
680 if (plannedstmt->returningLists)
681 nSlots++; /* for RETURNING projection */
683 estate->es_tupleTable = ExecCreateTupleTable(nSlots);
685 if (operation != CMD_SELECT)
686 estate->es_trig_tuple_slot =
687 ExecAllocTableSlot(estate->es_tupleTable);
690 /* mark EvalPlanQual not active */
691 estate->es_plannedstmt = plannedstmt;
692 estate->es_evalPlanQual = NULL;
693 estate->es_evTupleNull = NULL;
694 estate->es_evTuple = NULL;
695 estate->es_useEvalPlan = false;
698 * Initialize private state information for each SubPlan. We must do this
699 * before running ExecInitNode on the main query tree, since
700 * ExecInitSubPlan expects to be able to find these entries.
702 Assert(estate->es_subplanstates == NIL);
703 i = 1; /* subplan indices count from 1 */
704 foreach(l, plannedstmt->subplans)
706 Plan *subplan = (Plan *) lfirst(l);
707 PlanState *subplanstate;
711 * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
712 * it is a parameterless subplan (not initplan), we suggest that it be
713 * prepared to handle REWIND efficiently; otherwise there is no need.
715 sp_eflags = eflags & EXEC_FLAG_EXPLAIN_ONLY;
716 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
717 sp_eflags |= EXEC_FLAG_REWIND;
719 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
721 estate->es_subplanstates = lappend(estate->es_subplanstates,
728 * Initialize the private state information for all the nodes in the query
729 * tree. This opens files, allocates storage and leaves us ready to start
732 planstate = ExecInitNode(plan, estate, eflags);
735 * Get the tuple descriptor describing the type of tuples to return. (this
736 * is especially important if we are creating a relation with "SELECT
739 tupType = ExecGetResultType(planstate);
742 * Initialize the junk filter if needed. SELECT and INSERT queries need a
743 * filter if there are any junk attrs in the tlist. UPDATE and
744 * DELETE always need a filter, since there's always a junk 'ctid'
745 * attribute present --- no need to look first.
747 * This section of code is also a convenient place to verify that the
748 * output of an INSERT or UPDATE matches the target table(s).
751 bool junk_filter_needed = false;
758 foreach(tlist, plan->targetlist)
760 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
764 junk_filter_needed = true;
771 junk_filter_needed = true;
777 if (junk_filter_needed)
780 * If there are multiple result relations, each one needs its own
781 * junk filter. Note this is only possible for UPDATE/DELETE, so
782 * we can't be fooled by some needing a filter and some not.
784 if (list_length(plannedstmt->resultRelations) > 1)
786 PlanState **appendplans;
788 ResultRelInfo *resultRelInfo;
790 /* Top plan had better be an Append here. */
791 Assert(IsA(plan, Append));
792 Assert(((Append *) plan)->isTarget);
793 Assert(IsA(planstate, AppendState));
794 appendplans = ((AppendState *) planstate)->appendplans;
795 as_nplans = ((AppendState *) planstate)->as_nplans;
796 Assert(as_nplans == estate->es_num_result_relations);
797 resultRelInfo = estate->es_result_relations;
798 for (i = 0; i < as_nplans; i++)
800 PlanState *subplan = appendplans[i];
803 if (operation == CMD_UPDATE)
804 ExecCheckPlanOutput(resultRelInfo->ri_RelationDesc,
805 subplan->plan->targetlist);
807 j = ExecInitJunkFilter(subplan->plan->targetlist,
808 resultRelInfo->ri_RelationDesc->rd_att->tdhasoid,
809 ExecAllocTableSlot(estate->es_tupleTable));
812 * Since it must be UPDATE/DELETE, there had better be a
813 * "ctid" junk attribute in the tlist ... but ctid could
814 * be at a different resno for each result relation. We
815 * look up the ctid resnos now and save them in the
818 j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
819 if (!AttributeNumberIsValid(j->jf_junkAttNo))
820 elog(ERROR, "could not find junk ctid column");
821 resultRelInfo->ri_junkFilter = j;
826 * Set active junkfilter too; at this point ExecInitAppend has
827 * already selected an active result relation...
829 estate->es_junkFilter =
830 estate->es_result_relation_info->ri_junkFilter;
833 * We currently can't support rowmarks in this case, because
834 * the associated junk CTIDs might have different resnos in
835 * different subplans.
837 if (estate->es_rowMarks)
839 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
840 errmsg("SELECT FOR UPDATE/SHARE is not supported within a query with multiple result relations")));
844 /* Normal case with just one JunkFilter */
847 if (operation == CMD_INSERT || operation == CMD_UPDATE)
848 ExecCheckPlanOutput(estate->es_result_relation_info->ri_RelationDesc,
849 planstate->plan->targetlist);
851 j = ExecInitJunkFilter(planstate->plan->targetlist,
853 ExecAllocTableSlot(estate->es_tupleTable));
854 estate->es_junkFilter = j;
855 if (estate->es_result_relation_info)
856 estate->es_result_relation_info->ri_junkFilter = j;
858 if (operation == CMD_SELECT)
860 /* For SELECT, want to return the cleaned tuple type */
861 tupType = j->jf_cleanTupType;
863 else if (operation == CMD_UPDATE || operation == CMD_DELETE)
865 /* For UPDATE/DELETE, find the ctid junk attr now */
866 j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
867 if (!AttributeNumberIsValid(j->jf_junkAttNo))
868 elog(ERROR, "could not find junk ctid column");
871 /* For SELECT FOR UPDATE/SHARE, find the junk attrs now */
872 foreach(l, estate->es_rowMarks)
874 ExecRowMark *erm = (ExecRowMark *) lfirst(l);
877 /* always need the ctid */
878 snprintf(resname, sizeof(resname), "ctid%u",
880 erm->ctidAttNo = ExecFindJunkAttribute(j, resname);
881 if (!AttributeNumberIsValid(erm->ctidAttNo))
882 elog(ERROR, "could not find junk \"%s\" column",
884 /* if child relation, need tableoid too */
885 if (erm->rti != erm->prti)
887 snprintf(resname, sizeof(resname), "tableoid%u",
889 erm->toidAttNo = ExecFindJunkAttribute(j, resname);
890 if (!AttributeNumberIsValid(erm->toidAttNo))
891 elog(ERROR, "could not find junk \"%s\" column",
899 if (operation == CMD_INSERT)
900 ExecCheckPlanOutput(estate->es_result_relation_info->ri_RelationDesc,
901 planstate->plan->targetlist);
903 estate->es_junkFilter = NULL;
904 if (estate->es_rowMarks)
905 elog(ERROR, "SELECT FOR UPDATE/SHARE, but no junk columns");
910 * Initialize RETURNING projections if needed.
912 if (plannedstmt->returningLists)
914 TupleTableSlot *slot;
915 ExprContext *econtext;
916 ResultRelInfo *resultRelInfo;
919 * We set QueryDesc.tupDesc to be the RETURNING rowtype in this case.
920 * We assume all the sublists will generate the same output tupdesc.
922 tupType = ExecTypeFromTL((List *) linitial(plannedstmt->returningLists),
925 /* Set up a slot for the output of the RETURNING projection(s) */
926 slot = ExecAllocTableSlot(estate->es_tupleTable);
927 ExecSetSlotDescriptor(slot, tupType);
928 /* Need an econtext too */
929 econtext = CreateExprContext(estate);
932 * Build a projection for each result rel. Note that any SubPlans in
933 * the RETURNING lists get attached to the topmost plan node.
935 Assert(list_length(plannedstmt->returningLists) == estate->es_num_result_relations);
936 resultRelInfo = estate->es_result_relations;
937 foreach(l, plannedstmt->returningLists)
939 List *rlist = (List *) lfirst(l);
942 rliststate = (List *) ExecInitExpr((Expr *) rlist, planstate);
943 resultRelInfo->ri_projectReturning =
944 ExecBuildProjectionInfo(rliststate, econtext, slot,
945 resultRelInfo->ri_RelationDesc->rd_att);
950 queryDesc->tupDesc = tupType;
951 queryDesc->planstate = planstate;
954 * If doing SELECT INTO, initialize the "into" relation. We must wait
955 * till now so we have the "clean" result tuple type to create the new
958 * If EXPLAIN, skip creating the "into" relation.
960 if (estate->es_select_into && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
961 OpenIntoRel(queryDesc);
965 * Initialize ResultRelInfo data for one result relation
968 InitResultRelInfo(ResultRelInfo *resultRelInfo,
969 Relation resultRelationDesc,
970 Index resultRelationIndex,
975 * Check valid relkind ... parser and/or planner should have noticed this
976 * already, but let's make sure.
978 switch (resultRelationDesc->rd_rel->relkind)
980 case RELKIND_RELATION:
983 case RELKIND_SEQUENCE:
985 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
986 errmsg("cannot change sequence \"%s\"",
987 RelationGetRelationName(resultRelationDesc))));
989 case RELKIND_TOASTVALUE:
991 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
992 errmsg("cannot change TOAST relation \"%s\"",
993 RelationGetRelationName(resultRelationDesc))));
997 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
998 errmsg("cannot change view \"%s\"",
999 RelationGetRelationName(resultRelationDesc))));
1003 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1004 errmsg("cannot change relation \"%s\"",
1005 RelationGetRelationName(resultRelationDesc))));
1009 /* OK, fill in the node */
1010 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1011 resultRelInfo->type = T_ResultRelInfo;
1012 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1013 resultRelInfo->ri_RelationDesc = resultRelationDesc;
1014 resultRelInfo->ri_NumIndices = 0;
1015 resultRelInfo->ri_IndexRelationDescs = NULL;
1016 resultRelInfo->ri_IndexRelationInfo = NULL;
1017 /* make a copy so as not to depend on relcache info not changing... */
1018 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1019 if (resultRelInfo->ri_TrigDesc)
1021 int n = resultRelInfo->ri_TrigDesc->numtriggers;
1023 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1024 palloc0(n * sizeof(FmgrInfo));
1026 resultRelInfo->ri_TrigInstrument = InstrAlloc(n);
1028 resultRelInfo->ri_TrigInstrument = NULL;
1032 resultRelInfo->ri_TrigFunctions = NULL;
1033 resultRelInfo->ri_TrigInstrument = NULL;
1035 resultRelInfo->ri_ConstraintExprs = NULL;
1036 resultRelInfo->ri_junkFilter = NULL;
1037 resultRelInfo->ri_projectReturning = NULL;
1040 * If there are indices on the result relation, open them and save
1041 * descriptors in the result relation info, so that we can add new index
1042 * entries for the tuples we add/update. We need not do this for a
1043 * DELETE, however, since deletion doesn't affect indexes.
1045 if (resultRelationDesc->rd_rel->relhasindex &&
1046 operation != CMD_DELETE)
1047 ExecOpenIndices(resultRelInfo);
1051 * Verify that the tuples to be produced by INSERT or UPDATE match the
1052 * target relation's rowtype
1054 * We do this to guard against stale plans. If plan invalidation is
1055 * functioning properly then we should never get a failure here, but better
1056 * safe than sorry. Note that this is called after we have obtained lock
1057 * on the target rel, so the rowtype can't change underneath us.
1059 * The plan output is represented by its targetlist, because that makes
1060 * handling the dropped-column case easier.
1063 ExecCheckPlanOutput(Relation resultRel, List *targetList)
1065 TupleDesc resultDesc = RelationGetDescr(resultRel);
1069 foreach(lc, targetList)
1071 TargetEntry *tle = (TargetEntry *) lfirst(lc);
1072 Form_pg_attribute attr;
1075 continue; /* ignore junk tlist items */
1077 if (attno >= resultDesc->natts)
1079 (errcode(ERRCODE_DATATYPE_MISMATCH),
1080 errmsg("table row type and query-specified row type do not match"),
1081 errdetail("Query has too many columns.")));
1082 attr = resultDesc->attrs[attno++];
1084 if (!attr->attisdropped)
1086 /* Normal case: demand type match */
1087 if (exprType((Node *) tle->expr) != attr->atttypid)
1089 (errcode(ERRCODE_DATATYPE_MISMATCH),
1090 errmsg("table row type and query-specified row type do not match"),
1091 errdetail("Table has type %s at ordinal position %d, but query expects %s.",
1092 format_type_be(attr->atttypid),
1094 format_type_be(exprType((Node *) tle->expr)))));
1099 * For a dropped column, we can't check atttypid (it's likely 0).
1100 * In any case the planner has most likely inserted an INT4 null.
1101 * What we insist on is just *some* NULL constant.
1103 if (!IsA(tle->expr, Const) ||
1104 !((Const *) tle->expr)->constisnull)
1106 (errcode(ERRCODE_DATATYPE_MISMATCH),
1107 errmsg("table row type and query-specified row type do not match"),
1108 errdetail("Query provides a value for a dropped column at ordinal position %d.",
1112 if (attno != resultDesc->natts)
1114 (errcode(ERRCODE_DATATYPE_MISMATCH),
1115 errmsg("table row type and query-specified row type do not match"),
1116 errdetail("Query has too few columns.")));
1120 * ExecGetTriggerResultRel
1122 * Get a ResultRelInfo for a trigger target relation. Most of the time,
1123 * triggers are fired on one of the result relations of the query, and so
1124 * we can just return a member of the es_result_relations array. (Note: in
1125 * self-join situations there might be multiple members with the same OID;
1126 * if so it doesn't matter which one we pick.) However, it is sometimes
1127 * necessary to fire triggers on other relations; this happens mainly when an
1128 * RI update trigger queues additional triggers on other relations, which will
1129 * be processed in the context of the outer query. For efficiency's sake,
1130 * we want to have a ResultRelInfo for those triggers too; that can avoid
1131 * repeated re-opening of the relation. (It also provides a way for EXPLAIN
1132 * ANALYZE to report the runtimes of such triggers.) So we make additional
1133 * ResultRelInfo's as needed, and save them in es_trig_target_relations.
1136 ExecGetTriggerResultRel(EState *estate, Oid relid)
1138 ResultRelInfo *rInfo;
1142 MemoryContext oldcontext;
1144 /* First, search through the query result relations */
1145 rInfo = estate->es_result_relations;
1146 nr = estate->es_num_result_relations;
1149 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1154 /* Nope, but maybe we already made an extra ResultRelInfo for it */
1155 foreach(l, estate->es_trig_target_relations)
1157 rInfo = (ResultRelInfo *) lfirst(l);
1158 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1161 /* Nope, so we need a new one */
1164 * Open the target relation's relcache entry. We assume that an
1165 * appropriate lock is still held by the backend from whenever the trigger
1166 * event got queued, so we need take no new lock here.
1168 rel = heap_open(relid, NoLock);
1171 * Make the new entry in the right context. Currently, we don't need any
1172 * index information in ResultRelInfos used only for triggers, so tell
1173 * InitResultRelInfo it's a DELETE.
1175 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1176 rInfo = makeNode(ResultRelInfo);
1177 InitResultRelInfo(rInfo,
1179 0, /* dummy rangetable index */
1181 estate->es_instrument);
1182 estate->es_trig_target_relations =
1183 lappend(estate->es_trig_target_relations, rInfo);
1184 MemoryContextSwitchTo(oldcontext);
1190 * ExecContextForcesOids
1192 * This is pretty grotty: when doing INSERT, UPDATE, or SELECT INTO,
1193 * we need to ensure that result tuples have space for an OID iff they are
1194 * going to be stored into a relation that has OIDs. In other contexts
1195 * we are free to choose whether to leave space for OIDs in result tuples
1196 * (we generally don't want to, but we do if a physical-tlist optimization
1197 * is possible). This routine checks the plan context and returns TRUE if the
1198 * choice is forced, FALSE if the choice is not forced. In the TRUE case,
1199 * *hasoids is set to the required value.
1201 * One reason this is ugly is that all plan nodes in the plan tree will emit
1202 * tuples with space for an OID, though we really only need the topmost node
1203 * to do so. However, node types like Sort don't project new tuples but just
1204 * return their inputs, and in those cases the requirement propagates down
1205 * to the input node. Eventually we might make this code smart enough to
1206 * recognize how far down the requirement really goes, but for now we just
1207 * make all plan nodes do the same thing if the top level forces the choice.
1209 * We assume that estate->es_result_relation_info is already set up to
1210 * describe the target relation. Note that in an UPDATE that spans an
1211 * inheritance tree, some of the target relations may have OIDs and some not.
1212 * We have to make the decisions on a per-relation basis as we initialize
1213 * each of the child plans of the topmost Append plan.
1215 * SELECT INTO is even uglier, because we don't have the INTO relation's
1216 * descriptor available when this code runs; we have to look aside at a
1217 * flag set by InitPlan().
1220 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
1222 if (planstate->state->es_select_into)
1224 *hasoids = planstate->state->es_into_oids;
1229 ResultRelInfo *ri = planstate->state->es_result_relation_info;
1233 Relation rel = ri->ri_RelationDesc;
1237 *hasoids = rel->rd_rel->relhasoids;
1246 /* ----------------------------------------------------------------
1249 * Cleans up the query plan -- closes files and frees up storage
1251 * NOTE: we are no longer very worried about freeing storage per se
1252 * in this code; FreeExecutorState should be guaranteed to release all
1253 * memory that needs to be released. What we are worried about doing
1254 * is closing relations and dropping buffer pins. Thus, for example,
1255 * tuple tables must be cleared or dropped to ensure pins are released.
1256 * ----------------------------------------------------------------
1259 ExecEndPlan(PlanState *planstate, EState *estate)
1261 ResultRelInfo *resultRelInfo;
1266 * shut down any PlanQual processing we were doing
1268 if (estate->es_evalPlanQual != NULL)
1269 EndEvalPlanQual(estate);
1272 * shut down the node-type-specific query processing
1274 ExecEndNode(planstate);
1279 foreach(l, estate->es_subplanstates)
1281 PlanState *subplanstate = (PlanState *) lfirst(l);
1283 ExecEndNode(subplanstate);
1287 * destroy the executor "tuple" table.
1289 ExecDropTupleTable(estate->es_tupleTable, true);
1290 estate->es_tupleTable = NULL;
1293 * close the result relation(s) if any, but hold locks until xact commit.
1295 resultRelInfo = estate->es_result_relations;
1296 for (i = estate->es_num_result_relations; i > 0; i--)
1298 /* Close indices and then the relation itself */
1299 ExecCloseIndices(resultRelInfo);
1300 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1305 * likewise close any trigger target relations
1307 foreach(l, estate->es_trig_target_relations)
1309 resultRelInfo = (ResultRelInfo *) lfirst(l);
1310 /* Close indices and then the relation itself */
1311 ExecCloseIndices(resultRelInfo);
1312 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1316 * close any relations selected FOR UPDATE/FOR SHARE, again keeping locks
1318 foreach(l, estate->es_rowMarks)
1320 ExecRowMark *erm = lfirst(l);
1322 heap_close(erm->relation, NoLock);
1326 /* ----------------------------------------------------------------
1329 * Processes the query plan until we have processed 'numberTuples' tuples,
1330 * moving in the specified direction.
1332 * Runs to completion if numberTuples is 0
1334 * Note: the ctid attribute is a 'junk' attribute that is removed before the
1336 * ----------------------------------------------------------------
1339 ExecutePlan(EState *estate,
1340 PlanState *planstate,
1343 ScanDirection direction,
1346 JunkFilter *junkfilter;
1347 TupleTableSlot *planSlot;
1348 TupleTableSlot *slot;
1349 ItemPointer tupleid = NULL;
1350 ItemPointerData tuple_ctid;
1351 long current_tuple_count;
1354 * initialize local variables
1356 current_tuple_count = 0;
1359 * Set the direction.
1361 estate->es_direction = direction;
1364 * Process BEFORE EACH STATEMENT triggers
1369 ExecBSUpdateTriggers(estate, estate->es_result_relation_info);
1372 ExecBSDeleteTriggers(estate, estate->es_result_relation_info);
1375 ExecBSInsertTriggers(estate, estate->es_result_relation_info);
1383 * Loop until we've processed the proper number of tuples from the plan.
1387 /* Reset the per-output-tuple exprcontext */
1388 ResetPerTupleExprContext(estate);
1391 * Execute the plan and obtain a tuple
1394 if (estate->es_useEvalPlan)
1396 planSlot = EvalPlanQualNext(estate);
1397 if (TupIsNull(planSlot))
1398 planSlot = ExecProcNode(planstate);
1401 planSlot = ExecProcNode(planstate);
1404 * if the tuple is null, then we assume there is nothing more to
1405 * process so we just end the loop...
1407 if (TupIsNull(planSlot))
1412 * If we have a junk filter, then project a new tuple with the junk
1415 * Store this new "clean" tuple in the junkfilter's resultSlot.
1416 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1417 * because that tuple slot has the wrong descriptor.)
1419 * But first, extract all the junk information we need.
1421 if ((junkfilter = estate->es_junkFilter) != NULL)
1424 * Process any FOR UPDATE or FOR SHARE locking requested.
1426 if (estate->es_rowMarks != NIL)
1431 foreach(l, estate->es_rowMarks)
1433 ExecRowMark *erm = lfirst(l);
1436 HeapTupleData tuple;
1438 ItemPointerData update_ctid;
1439 TransactionId update_xmax;
1440 TupleTableSlot *newSlot;
1441 LockTupleMode lockmode;
1444 /* if child rel, must check whether it produced this row */
1445 if (erm->rti != erm->prti)
1449 datum = ExecGetJunkAttribute(slot,
1452 /* shouldn't ever get a null result... */
1454 elog(ERROR, "tableoid is NULL");
1455 tableoid = DatumGetObjectId(datum);
1457 if (tableoid != RelationGetRelid(erm->relation))
1459 /* this child is inactive right now */
1460 ItemPointerSetInvalid(&(erm->curCtid));
1465 /* okay, fetch the tuple by ctid */
1466 datum = ExecGetJunkAttribute(slot,
1469 /* shouldn't ever get a null result... */
1471 elog(ERROR, "ctid is NULL");
1472 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1475 lockmode = LockTupleExclusive;
1477 lockmode = LockTupleShared;
1479 test = heap_lock_tuple(erm->relation, &tuple, &buffer,
1480 &update_ctid, &update_xmax,
1481 estate->es_output_cid,
1482 lockmode, erm->noWait);
1483 ReleaseBuffer(buffer);
1486 case HeapTupleSelfUpdated:
1487 /* treat it as deleted; do not process */
1490 case HeapTupleMayBeUpdated:
1493 case HeapTupleUpdated:
1494 if (IsXactIsoLevelSerializable)
1496 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1497 errmsg("could not serialize access due to concurrent update")));
1498 if (!ItemPointerEquals(&update_ctid,
1501 /* updated, so look at updated version */
1502 newSlot = EvalPlanQual(estate,
1506 if (!TupIsNull(newSlot))
1508 slot = planSlot = newSlot;
1509 estate->es_useEvalPlan = true;
1515 * if tuple was deleted or PlanQual failed for
1516 * updated tuple - we must not return this tuple!
1521 elog(ERROR, "unrecognized heap_lock_tuple status: %u",
1525 /* Remember tuple TID for WHERE CURRENT OF */
1526 erm->curCtid = tuple.t_self;
1531 * extract the 'ctid' junk attribute.
1533 if (operation == CMD_UPDATE || operation == CMD_DELETE)
1538 datum = ExecGetJunkAttribute(slot, junkfilter->jf_junkAttNo,
1540 /* shouldn't ever get a null result... */
1542 elog(ERROR, "ctid is NULL");
1544 tupleid = (ItemPointer) DatumGetPointer(datum);
1545 tuple_ctid = *tupleid; /* make sure we don't free the ctid!! */
1546 tupleid = &tuple_ctid;
1550 * Create a new "clean" tuple with all junk attributes removed. We
1551 * don't need to do this for DELETE, however (there will in fact
1552 * be no non-junk attributes in a DELETE!)
1554 if (operation != CMD_DELETE)
1555 slot = ExecFilterJunk(junkfilter, slot);
1559 * now that we have a tuple, do the appropriate thing with it.. either
1560 * send it to the output destination, add it to a relation someplace,
1561 * delete it from a relation, or modify some of its attributes.
1566 ExecSelect(slot, dest, estate);
1570 ExecInsert(slot, tupleid, planSlot, dest, estate);
1574 ExecDelete(tupleid, planSlot, dest, estate);
1578 ExecUpdate(slot, tupleid, planSlot, dest, estate);
1582 elog(ERROR, "unrecognized operation code: %d",
1588 * check our tuple count.. if we've processed the proper number then
1589 * quit, else loop again and process more tuples. Zero numberTuples
1592 current_tuple_count++;
1593 if (numberTuples && numberTuples == current_tuple_count)
1598 * Process AFTER EACH STATEMENT triggers
1603 ExecASUpdateTriggers(estate, estate->es_result_relation_info);
1606 ExecASDeleteTriggers(estate, estate->es_result_relation_info);
1609 ExecASInsertTriggers(estate, estate->es_result_relation_info);
1617 /* ----------------------------------------------------------------
1620 * SELECTs are easy.. we just pass the tuple to the appropriate
1622 * ----------------------------------------------------------------
1625 ExecSelect(TupleTableSlot *slot,
1629 (*dest->receiveSlot) (slot, dest);
1631 (estate->es_processed)++;
1634 /* ----------------------------------------------------------------
1637 * INSERTs are trickier.. we have to insert the tuple into
1638 * the base relation and insert appropriate tuples into the
1640 * ----------------------------------------------------------------
1643 ExecInsert(TupleTableSlot *slot,
1644 ItemPointer tupleid,
1645 TupleTableSlot *planSlot,
1650 ResultRelInfo *resultRelInfo;
1651 Relation resultRelationDesc;
1655 * get the heap tuple out of the tuple table slot, making sure we have a
1658 tuple = ExecMaterializeSlot(slot);
1661 * get information on the (current) result relation
1663 resultRelInfo = estate->es_result_relation_info;
1664 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1666 /* BEFORE ROW INSERT Triggers */
1667 if (resultRelInfo->ri_TrigDesc &&
1668 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1672 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1674 if (newtuple == NULL) /* "do nothing" */
1677 if (newtuple != tuple) /* modified by Trigger(s) */
1680 * Put the modified tuple into a slot for convenience of routines
1681 * below. We assume the tuple was allocated in per-tuple memory
1682 * context, and therefore will go away by itself. The tuple table
1683 * slot should not try to clear it.
1685 TupleTableSlot *newslot = estate->es_trig_tuple_slot;
1687 if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
1688 ExecSetSlotDescriptor(newslot, slot->tts_tupleDescriptor);
1689 ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
1696 * Check the constraints of the tuple
1698 if (resultRelationDesc->rd_att->constr)
1699 ExecConstraints(resultRelInfo, slot, estate);
1704 * Note: heap_insert returns the tid (location) of the new tuple in the
1707 newId = heap_insert(resultRelationDesc, tuple,
1708 estate->es_output_cid, 0, NULL);
1711 (estate->es_processed)++;
1712 estate->es_lastoid = newId;
1713 setLastTid(&(tuple->t_self));
1716 * insert index entries for tuple
1718 if (resultRelInfo->ri_NumIndices > 0)
1719 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1721 /* AFTER ROW INSERT Triggers */
1722 ExecARInsertTriggers(estate, resultRelInfo, tuple);
1724 /* Process RETURNING if present */
1725 if (resultRelInfo->ri_projectReturning)
1726 ExecProcessReturning(resultRelInfo->ri_projectReturning,
1727 slot, planSlot, dest);
1730 /* ----------------------------------------------------------------
1733 * DELETE is like UPDATE, except that we delete the tuple and no
1734 * index modifications are needed
1735 * ----------------------------------------------------------------
1738 ExecDelete(ItemPointer tupleid,
1739 TupleTableSlot *planSlot,
1743 ResultRelInfo *resultRelInfo;
1744 Relation resultRelationDesc;
1746 ItemPointerData update_ctid;
1747 TransactionId update_xmax;
1750 * get information on the (current) result relation
1752 resultRelInfo = estate->es_result_relation_info;
1753 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1755 /* BEFORE ROW DELETE Triggers */
1756 if (resultRelInfo->ri_TrigDesc &&
1757 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1761 dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid);
1763 if (!dodelete) /* "do nothing" */
1770 * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
1771 * the row to be deleted is visible to that snapshot, and throw a can't-
1772 * serialize error if not. This is a special-case behavior needed for
1773 * referential integrity updates in serializable transactions.
1776 result = heap_delete(resultRelationDesc, tupleid,
1777 &update_ctid, &update_xmax,
1778 estate->es_output_cid,
1779 estate->es_crosscheck_snapshot,
1780 true /* wait for commit */ );
1783 case HeapTupleSelfUpdated:
1784 /* already deleted by self; nothing to do */
1787 case HeapTupleMayBeUpdated:
1790 case HeapTupleUpdated:
1791 if (IsXactIsoLevelSerializable)
1793 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1794 errmsg("could not serialize access due to concurrent update")));
1795 else if (!ItemPointerEquals(tupleid, &update_ctid))
1797 TupleTableSlot *epqslot;
1799 epqslot = EvalPlanQual(estate,
1800 resultRelInfo->ri_RangeTableIndex,
1803 if (!TupIsNull(epqslot))
1805 *tupleid = update_ctid;
1809 /* tuple already deleted; nothing to do */
1813 elog(ERROR, "unrecognized heap_delete status: %u", result);
1818 (estate->es_processed)++;
1821 * Note: Normally one would think that we have to delete index tuples
1822 * associated with the heap tuple now...
1824 * ... but in POSTGRES, we have no need to do this because VACUUM will
1825 * take care of it later. We can't delete index tuples immediately
1826 * anyway, since the tuple is still visible to other transactions.
1829 /* AFTER ROW DELETE Triggers */
1830 ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1832 /* Process RETURNING if present */
1833 if (resultRelInfo->ri_projectReturning)
1836 * We have to put the target tuple into a slot, which means first we
1837 * gotta fetch it. We can use the trigger tuple slot.
1839 TupleTableSlot *slot = estate->es_trig_tuple_slot;
1840 HeapTupleData deltuple;
1843 deltuple.t_self = *tupleid;
1844 if (!heap_fetch(resultRelationDesc, SnapshotAny,
1845 &deltuple, &delbuffer, false, NULL))
1846 elog(ERROR, "failed to fetch deleted tuple for DELETE RETURNING");
1848 if (slot->tts_tupleDescriptor != RelationGetDescr(resultRelationDesc))
1849 ExecSetSlotDescriptor(slot, RelationGetDescr(resultRelationDesc));
1850 ExecStoreTuple(&deltuple, slot, InvalidBuffer, false);
1852 ExecProcessReturning(resultRelInfo->ri_projectReturning,
1853 slot, planSlot, dest);
1855 ExecClearTuple(slot);
1856 ReleaseBuffer(delbuffer);
1860 /* ----------------------------------------------------------------
1863 * note: we can't run UPDATE queries with transactions
1864 * off because UPDATEs are actually INSERTs and our
1865 * scan will mistakenly loop forever, updating the tuple
1866 * it just inserted.. This should be fixed but until it
1867 * is, we don't want to get stuck in an infinite loop
1868 * which corrupts your database..
1869 * ----------------------------------------------------------------
1872 ExecUpdate(TupleTableSlot *slot,
1873 ItemPointer tupleid,
1874 TupleTableSlot *planSlot,
1879 ResultRelInfo *resultRelInfo;
1880 Relation resultRelationDesc;
1882 ItemPointerData update_ctid;
1883 TransactionId update_xmax;
1886 * abort the operation if not running transactions
1888 if (IsBootstrapProcessingMode())
1889 elog(ERROR, "cannot UPDATE during bootstrap");
1892 * get the heap tuple out of the tuple table slot, making sure we have a
1895 tuple = ExecMaterializeSlot(slot);
1898 * get information on the (current) result relation
1900 resultRelInfo = estate->es_result_relation_info;
1901 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1903 /* BEFORE ROW UPDATE Triggers */
1904 if (resultRelInfo->ri_TrigDesc &&
1905 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1909 newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
1912 if (newtuple == NULL) /* "do nothing" */
1915 if (newtuple != tuple) /* modified by Trigger(s) */
1918 * Put the modified tuple into a slot for convenience of routines
1919 * below. We assume the tuple was allocated in per-tuple memory
1920 * context, and therefore will go away by itself. The tuple table
1921 * slot should not try to clear it.
1923 TupleTableSlot *newslot = estate->es_trig_tuple_slot;
1925 if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
1926 ExecSetSlotDescriptor(newslot, slot->tts_tupleDescriptor);
1927 ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
1934 * Check the constraints of the tuple
1936 * If we generate a new candidate tuple after EvalPlanQual testing, we
1937 * must loop back here and recheck constraints. (We don't need to redo
1938 * triggers, however. If there are any BEFORE triggers then trigger.c
1939 * will have done heap_lock_tuple to lock the correct tuple, so there's no
1940 * need to do them again.)
1943 if (resultRelationDesc->rd_att->constr)
1944 ExecConstraints(resultRelInfo, slot, estate);
1947 * replace the heap tuple
1949 * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
1950 * the row to be updated is visible to that snapshot, and throw a can't-
1951 * serialize error if not. This is a special-case behavior needed for
1952 * referential integrity updates in serializable transactions.
1954 result = heap_update(resultRelationDesc, tupleid, tuple,
1955 &update_ctid, &update_xmax,
1956 estate->es_output_cid,
1957 estate->es_crosscheck_snapshot,
1958 true /* wait for commit */ );
1961 case HeapTupleSelfUpdated:
1962 /* already deleted by self; nothing to do */
1965 case HeapTupleMayBeUpdated:
1968 case HeapTupleUpdated:
1969 if (IsXactIsoLevelSerializable)
1971 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1972 errmsg("could not serialize access due to concurrent update")));
1973 else if (!ItemPointerEquals(tupleid, &update_ctid))
1975 TupleTableSlot *epqslot;
1977 epqslot = EvalPlanQual(estate,
1978 resultRelInfo->ri_RangeTableIndex,
1981 if (!TupIsNull(epqslot))
1983 *tupleid = update_ctid;
1984 slot = ExecFilterJunk(estate->es_junkFilter, epqslot);
1985 tuple = ExecMaterializeSlot(slot);
1989 /* tuple already deleted; nothing to do */
1993 elog(ERROR, "unrecognized heap_update status: %u", result);
1998 (estate->es_processed)++;
2001 * Note: instead of having to update the old index tuples associated with
2002 * the heap tuple, all we do is form and insert new index tuples. This is
2003 * because UPDATEs are actually DELETEs and INSERTs, and index tuple
2004 * deletion is done later by VACUUM (see notes in ExecDelete). All we do
2005 * here is insert new index tuples. -cim 9/27/89
2009 * insert index entries for tuple
2011 * Note: heap_update returns the tid (location) of the new tuple in the
2014 * If it's a HOT update, we mustn't insert new index entries.
2016 if (resultRelInfo->ri_NumIndices > 0 && !HeapTupleIsHeapOnly(tuple))
2017 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
2019 /* AFTER ROW UPDATE Triggers */
2020 ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
2022 /* Process RETURNING if present */
2023 if (resultRelInfo->ri_projectReturning)
2024 ExecProcessReturning(resultRelInfo->ri_projectReturning,
2025 slot, planSlot, dest);
2029 * ExecRelCheck --- check that tuple meets constraints for result relation
2032 ExecRelCheck(ResultRelInfo *resultRelInfo,
2033 TupleTableSlot *slot, EState *estate)
2035 Relation rel = resultRelInfo->ri_RelationDesc;
2036 int ncheck = rel->rd_att->constr->num_check;
2037 ConstrCheck *check = rel->rd_att->constr->check;
2038 ExprContext *econtext;
2039 MemoryContext oldContext;
2044 * If first time through for this result relation, build expression
2045 * nodetrees for rel's constraint expressions. Keep them in the per-query
2046 * memory context so they'll survive throughout the query.
2048 if (resultRelInfo->ri_ConstraintExprs == NULL)
2050 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
2051 resultRelInfo->ri_ConstraintExprs =
2052 (List **) palloc(ncheck * sizeof(List *));
2053 for (i = 0; i < ncheck; i++)
2055 /* ExecQual wants implicit-AND form */
2056 qual = make_ands_implicit(stringToNode(check[i].ccbin));
2057 resultRelInfo->ri_ConstraintExprs[i] = (List *)
2058 ExecPrepareExpr((Expr *) qual, estate);
2060 MemoryContextSwitchTo(oldContext);
2064 * We will use the EState's per-tuple context for evaluating constraint
2065 * expressions (creating it if it's not already there).
2067 econtext = GetPerTupleExprContext(estate);
2069 /* Arrange for econtext's scan tuple to be the tuple under test */
2070 econtext->ecxt_scantuple = slot;
2072 /* And evaluate the constraints */
2073 for (i = 0; i < ncheck; i++)
2075 qual = resultRelInfo->ri_ConstraintExprs[i];
2078 * NOTE: SQL92 specifies that a NULL result from a constraint
2079 * expression is not to be treated as a failure. Therefore, tell
2080 * ExecQual to return TRUE for NULL.
2082 if (!ExecQual(qual, econtext, true))
2083 return check[i].ccname;
2086 /* NULL result means no error */
2091 ExecConstraints(ResultRelInfo *resultRelInfo,
2092 TupleTableSlot *slot, EState *estate)
2094 Relation rel = resultRelInfo->ri_RelationDesc;
2095 TupleConstr *constr = rel->rd_att->constr;
2099 if (constr->has_not_null)
2101 int natts = rel->rd_att->natts;
2104 for (attrChk = 1; attrChk <= natts; attrChk++)
2106 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
2107 slot_attisnull(slot, attrChk))
2109 (errcode(ERRCODE_NOT_NULL_VIOLATION),
2110 errmsg("null value in column \"%s\" violates not-null constraint",
2111 NameStr(rel->rd_att->attrs[attrChk - 1]->attname))));
2115 if (constr->num_check > 0)
2119 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
2121 (errcode(ERRCODE_CHECK_VIOLATION),
2122 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
2123 RelationGetRelationName(rel), failed)));
2128 * ExecProcessReturning --- evaluate a RETURNING list and send to dest
2130 * projectReturning: RETURNING projection info for current result rel
2131 * tupleSlot: slot holding tuple actually inserted/updated/deleted
2132 * planSlot: slot holding tuple returned by top plan node
2133 * dest: where to send the output
2136 ExecProcessReturning(ProjectionInfo *projectReturning,
2137 TupleTableSlot *tupleSlot,
2138 TupleTableSlot *planSlot,
2141 ExprContext *econtext = projectReturning->pi_exprContext;
2142 TupleTableSlot *retSlot;
2145 * Reset per-tuple memory context to free any expression evaluation
2146 * storage allocated in the previous cycle.
2148 ResetExprContext(econtext);
2150 /* Make tuple and any needed join variables available to ExecProject */
2151 econtext->ecxt_scantuple = tupleSlot;
2152 econtext->ecxt_outertuple = planSlot;
2154 /* Compute the RETURNING expressions */
2155 retSlot = ExecProject(projectReturning, NULL);
2158 (*dest->receiveSlot) (retSlot, dest);
2160 ExecClearTuple(retSlot);
2164 * Check a modified tuple to see if we want to process its updated version
2165 * under READ COMMITTED rules.
2167 * See backend/executor/README for some info about how this works.
2169 * estate - executor state data
2170 * rti - rangetable index of table containing tuple
2171 * *tid - t_ctid from the outdated tuple (ie, next updated version)
2172 * priorXmax - t_xmax from the outdated tuple
2174 * *tid is also an output parameter: it's modified to hold the TID of the
2175 * latest version of the tuple (note this may be changed even on failure)
2177 * Returns a slot containing the new candidate update/delete tuple, or
2178 * NULL if we determine we shouldn't process the row.
2181 EvalPlanQual(EState *estate, Index rti,
2182 ItemPointer tid, TransactionId priorXmax)
2187 HeapTupleData tuple;
2188 HeapTuple copyTuple = NULL;
2189 SnapshotData SnapshotDirty;
2195 * find relation containing target tuple
2197 if (estate->es_result_relation_info != NULL &&
2198 estate->es_result_relation_info->ri_RangeTableIndex == rti)
2199 relation = estate->es_result_relation_info->ri_RelationDesc;
2205 foreach(l, estate->es_rowMarks)
2207 ExecRowMark *erm = lfirst(l);
2209 if (erm->rti == rti)
2211 relation = erm->relation;
2215 if (relation == NULL)
2216 elog(ERROR, "could not find RowMark for RT index %u", rti);
2222 * Loop here to deal with updated or busy tuples
2224 InitDirtySnapshot(SnapshotDirty);
2225 tuple.t_self = *tid;
2230 if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
2233 * If xmin isn't what we're expecting, the slot must have been
2234 * recycled and reused for an unrelated tuple. This implies that
2235 * the latest version of the row was deleted, so we need do
2236 * nothing. (Should be safe to examine xmin without getting
2237 * buffer's content lock, since xmin never changes in an existing
2240 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2243 ReleaseBuffer(buffer);
2247 /* otherwise xmin should not be dirty... */
2248 if (TransactionIdIsValid(SnapshotDirty.xmin))
2249 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
2252 * If tuple is being updated by other transaction then we have to
2253 * wait for its commit/abort.
2255 if (TransactionIdIsValid(SnapshotDirty.xmax))
2257 ReleaseBuffer(buffer);
2258 XactLockTableWait(SnapshotDirty.xmax);
2259 continue; /* loop back to repeat heap_fetch */
2263 * If tuple was inserted by our own transaction, we have to check
2264 * cmin against es_output_cid: cmin >= current CID means our
2265 * command cannot see the tuple, so we should ignore it. Without
2266 * this we are open to the "Halloween problem" of indefinitely
2267 * re-updating the same tuple. (We need not check cmax because
2268 * HeapTupleSatisfiesDirty will consider a tuple deleted by our
2269 * transaction dead, regardless of cmax.) We just checked that
2270 * priorXmax == xmin, so we can test that variable instead of
2271 * doing HeapTupleHeaderGetXmin again.
2273 if (TransactionIdIsCurrentTransactionId(priorXmax) &&
2274 HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
2276 ReleaseBuffer(buffer);
2281 * We got tuple - now copy it for use by recheck query.
2283 copyTuple = heap_copytuple(&tuple);
2284 ReleaseBuffer(buffer);
2289 * If the referenced slot was actually empty, the latest version of
2290 * the row must have been deleted, so we need do nothing.
2292 if (tuple.t_data == NULL)
2294 ReleaseBuffer(buffer);
2299 * As above, if xmin isn't what we're expecting, do nothing.
2301 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2304 ReleaseBuffer(buffer);
2309 * If we get here, the tuple was found but failed SnapshotDirty.
2310 * Assuming the xmin is either a committed xact or our own xact (as it
2311 * certainly should be if we're trying to modify the tuple), this must
2312 * mean that the row was updated or deleted by either a committed xact
2313 * or our own xact. If it was deleted, we can ignore it; if it was
2314 * updated then chain up to the next version and repeat the whole
2317 * As above, it should be safe to examine xmax and t_ctid without the
2318 * buffer content lock, because they can't be changing.
2320 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
2322 /* deleted, so forget about it */
2323 ReleaseBuffer(buffer);
2327 /* updated, so look at the updated row */
2328 tuple.t_self = tuple.t_data->t_ctid;
2329 /* updated row should have xmin matching this xmax */
2330 priorXmax = HeapTupleHeaderGetXmax(tuple.t_data);
2331 ReleaseBuffer(buffer);
2332 /* loop back to fetch next in chain */
2336 * For UPDATE/DELETE we have to return tid of actual row we're executing
2339 *tid = tuple.t_self;
2342 * Need to run a recheck subquery. Find or create a PQ stack entry.
2344 epq = estate->es_evalPlanQual;
2347 if (epq != NULL && epq->rti == 0)
2349 /* Top PQ stack entry is idle, so re-use it */
2350 Assert(!(estate->es_useEvalPlan) && epq->next == NULL);
2356 * If this is request for another RTE - Ra, - then we have to check wasn't
2357 * PlanQual requested for Ra already and if so then Ra' row was updated
2358 * again and we have to re-start old execution for Ra and forget all what
2359 * we done after Ra was suspended. Cool? -:))
2361 if (epq != NULL && epq->rti != rti &&
2362 epq->estate->es_evTuple[rti - 1] != NULL)
2366 evalPlanQual *oldepq;
2368 /* stop execution */
2369 EvalPlanQualStop(epq);
2370 /* pop previous PlanQual from the stack */
2372 Assert(oldepq && oldepq->rti != 0);
2373 /* push current PQ to freePQ stack */
2376 estate->es_evalPlanQual = epq;
2377 } while (epq->rti != rti);
2381 * If we are requested for another RTE then we have to suspend execution
2382 * of current PlanQual and start execution for new one.
2384 if (epq == NULL || epq->rti != rti)
2386 /* try to reuse plan used previously */
2387 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
2389 if (newepq == NULL) /* first call or freePQ stack is empty */
2391 newepq = (evalPlanQual *) palloc0(sizeof(evalPlanQual));
2392 newepq->free = NULL;
2393 newepq->estate = NULL;
2394 newepq->planstate = NULL;
2398 /* recycle previously used PlanQual */
2399 Assert(newepq->estate == NULL);
2402 /* push current PQ to the stack */
2405 estate->es_evalPlanQual = epq;
2410 Assert(epq->rti == rti);
2413 * Ok - we're requested for the same RTE. Unfortunately we still have to
2414 * end and restart execution of the plan, because ExecReScan wouldn't
2415 * ensure that upper plan nodes would reset themselves. We could make
2416 * that work if insertion of the target tuple were integrated with the
2417 * Param mechanism somehow, so that the upper plan nodes know that their
2418 * children's outputs have changed.
2420 * Note that the stack of free evalPlanQual nodes is quite useless at the
2421 * moment, since it only saves us from pallocing/releasing the
2422 * evalPlanQual nodes themselves. But it will be useful once we implement
2423 * ReScan instead of end/restart for re-using PlanQual nodes.
2427 /* stop execution */
2428 EvalPlanQualStop(epq);
2432 * Initialize new recheck query.
2434 * Note: if we were re-using PlanQual plans via ExecReScan, we'd need to
2435 * instead copy down changeable state from the top plan (including
2436 * es_result_relation_info, es_junkFilter) and reset locally changeable
2437 * state in the epq (including es_param_exec_vals, es_evTupleNull).
2439 EvalPlanQualStart(epq, estate, epq->next);
2442 * free old RTE' tuple, if any, and store target tuple where relation's
2443 * scan node will see it
2445 epqstate = epq->estate;
2446 if (epqstate->es_evTuple[rti - 1] != NULL)
2447 heap_freetuple(epqstate->es_evTuple[rti - 1]);
2448 epqstate->es_evTuple[rti - 1] = copyTuple;
2450 return EvalPlanQualNext(estate);
2453 static TupleTableSlot *
2454 EvalPlanQualNext(EState *estate)
2456 evalPlanQual *epq = estate->es_evalPlanQual;
2457 MemoryContext oldcontext;
2458 TupleTableSlot *slot;
2460 Assert(epq->rti != 0);
2463 oldcontext = MemoryContextSwitchTo(epq->estate->es_query_cxt);
2464 slot = ExecProcNode(epq->planstate);
2465 MemoryContextSwitchTo(oldcontext);
2468 * No more tuples for this PQ. Continue previous one.
2470 if (TupIsNull(slot))
2472 evalPlanQual *oldepq;
2474 /* stop execution */
2475 EvalPlanQualStop(epq);
2476 /* pop old PQ from the stack */
2480 /* this is the first (oldest) PQ - mark as free */
2482 estate->es_useEvalPlan = false;
2483 /* and continue Query execution */
2486 Assert(oldepq->rti != 0);
2487 /* push current PQ to freePQ stack */
2490 estate->es_evalPlanQual = epq;
2498 EndEvalPlanQual(EState *estate)
2500 evalPlanQual *epq = estate->es_evalPlanQual;
2502 if (epq->rti == 0) /* plans already shutdowned */
2504 Assert(epq->next == NULL);
2510 evalPlanQual *oldepq;
2512 /* stop execution */
2513 EvalPlanQualStop(epq);
2514 /* pop old PQ from the stack */
2518 /* this is the first (oldest) PQ - mark as free */
2520 estate->es_useEvalPlan = false;
2523 Assert(oldepq->rti != 0);
2524 /* push current PQ to freePQ stack */
2527 estate->es_evalPlanQual = epq;
2532 * Start execution of one level of PlanQual.
2534 * This is a cut-down version of ExecutorStart(): we copy some state from
2535 * the top-level estate rather than initializing it fresh.
2538 EvalPlanQualStart(evalPlanQual *epq, EState *estate, evalPlanQual *priorepq)
2542 MemoryContext oldcontext;
2545 rtsize = list_length(estate->es_range_table);
2547 epq->estate = epqstate = CreateExecutorState();
2549 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2552 * The epqstates share the top query's copy of unchanging state such as
2553 * the snapshot, rangetable, result-rel info, and external Param info.
2554 * They need their own copies of local state, including a tuple table,
2555 * es_param_exec_vals, etc.
2557 epqstate->es_direction = ForwardScanDirection;
2558 epqstate->es_snapshot = estate->es_snapshot;
2559 epqstate->es_crosscheck_snapshot = estate->es_crosscheck_snapshot;
2560 epqstate->es_range_table = estate->es_range_table;
2561 epqstate->es_output_cid = estate->es_output_cid;
2562 epqstate->es_result_relations = estate->es_result_relations;
2563 epqstate->es_num_result_relations = estate->es_num_result_relations;
2564 epqstate->es_result_relation_info = estate->es_result_relation_info;
2565 epqstate->es_junkFilter = estate->es_junkFilter;
2566 /* es_trig_target_relations must NOT be copied */
2567 epqstate->es_param_list_info = estate->es_param_list_info;
2568 if (estate->es_plannedstmt->nParamExec > 0)
2569 epqstate->es_param_exec_vals = (ParamExecData *)
2570 palloc0(estate->es_plannedstmt->nParamExec * sizeof(ParamExecData));
2571 epqstate->es_rowMarks = estate->es_rowMarks;
2572 epqstate->es_instrument = estate->es_instrument;
2573 epqstate->es_select_into = estate->es_select_into;
2574 epqstate->es_into_oids = estate->es_into_oids;
2575 epqstate->es_plannedstmt = estate->es_plannedstmt;
2578 * Each epqstate must have its own es_evTupleNull state, but all the stack
2579 * entries share es_evTuple state. This allows sub-rechecks to inherit
2580 * the value being examined by an outer recheck.
2582 epqstate->es_evTupleNull = (bool *) palloc0(rtsize * sizeof(bool));
2583 if (priorepq == NULL)
2584 /* first PQ stack entry */
2585 epqstate->es_evTuple = (HeapTuple *)
2586 palloc0(rtsize * sizeof(HeapTuple));
2588 /* later stack entries share the same storage */
2589 epqstate->es_evTuple = priorepq->estate->es_evTuple;
2592 * Create sub-tuple-table; we needn't redo the CountSlots work though.
2594 epqstate->es_tupleTable =
2595 ExecCreateTupleTable(estate->es_tupleTable->size);
2598 * Initialize private state information for each SubPlan. We must do this
2599 * before running ExecInitNode on the main query tree, since
2600 * ExecInitSubPlan expects to be able to find these entries.
2602 Assert(epqstate->es_subplanstates == NIL);
2603 foreach(l, estate->es_plannedstmt->subplans)
2605 Plan *subplan = (Plan *) lfirst(l);
2606 PlanState *subplanstate;
2608 subplanstate = ExecInitNode(subplan, epqstate, 0);
2610 epqstate->es_subplanstates = lappend(epqstate->es_subplanstates,
2615 * Initialize the private state information for all the nodes in the query
2616 * tree. This opens files, allocates storage and leaves us ready to start
2617 * processing tuples.
2619 epq->planstate = ExecInitNode(estate->es_plannedstmt->planTree, epqstate, 0);
2621 MemoryContextSwitchTo(oldcontext);
2625 * End execution of one level of PlanQual.
2627 * This is a cut-down version of ExecutorEnd(); basically we want to do most
2628 * of the normal cleanup, but *not* close result relations (which we are
2629 * just sharing from the outer query). We do, however, have to close any
2630 * trigger target relations that got opened, since those are not shared.
2633 EvalPlanQualStop(evalPlanQual *epq)
2635 EState *epqstate = epq->estate;
2636 MemoryContext oldcontext;
2639 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2641 ExecEndNode(epq->planstate);
2643 foreach(l, epqstate->es_subplanstates)
2645 PlanState *subplanstate = (PlanState *) lfirst(l);
2647 ExecEndNode(subplanstate);
2650 ExecDropTupleTable(epqstate->es_tupleTable, true);
2651 epqstate->es_tupleTable = NULL;
2653 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
2655 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
2656 epqstate->es_evTuple[epq->rti - 1] = NULL;
2659 foreach(l, epqstate->es_trig_target_relations)
2661 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
2663 /* Close indices and then the relation itself */
2664 ExecCloseIndices(resultRelInfo);
2665 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
2668 MemoryContextSwitchTo(oldcontext);
2670 FreeExecutorState(epqstate);
2673 epq->planstate = NULL;
2677 * ExecGetActivePlanTree --- get the active PlanState tree from a QueryDesc
2679 * Ordinarily this is just the one mentioned in the QueryDesc, but if we
2680 * are looking at a row returned by the EvalPlanQual machinery, we need
2681 * to look at the subsidiary state instead.
2684 ExecGetActivePlanTree(QueryDesc *queryDesc)
2686 EState *estate = queryDesc->estate;
2688 if (estate && estate->es_useEvalPlan && estate->es_evalPlanQual != NULL)
2689 return estate->es_evalPlanQual->planstate;
2691 return queryDesc->planstate;
2696 * Support for SELECT INTO (a/k/a CREATE TABLE AS)
2698 * We implement SELECT INTO by diverting SELECT's normal output with
2699 * a specialized DestReceiver type.
2704 DestReceiver pub; /* publicly-known function pointers */
2705 EState *estate; /* EState we are working with */
2706 Relation rel; /* Relation to write to */
2707 int hi_options; /* heap_insert performance options */
2708 BulkInsertState bistate; /* bulk insert state */
2712 * OpenIntoRel --- actually create the SELECT INTO target relation
2714 * This also replaces QueryDesc->dest with the special DestReceiver for
2715 * SELECT INTO. We assume that the correct result tuple type has already
2716 * been placed in queryDesc->tupDesc.
2719 OpenIntoRel(QueryDesc *queryDesc)
2721 IntoClause *into = queryDesc->plannedstmt->intoClause;
2722 EState *estate = queryDesc->estate;
2723 Relation intoRelationDesc;
2728 AclResult aclresult;
2731 DR_intorel *myState;
2736 * Check consistency of arguments
2738 if (into->onCommit != ONCOMMIT_NOOP && !into->rel->istemp)
2740 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2741 errmsg("ON COMMIT can only be used on temporary tables")));
2744 * Find namespace to create in, check its permissions
2746 intoName = into->rel->relname;
2747 namespaceId = RangeVarGetCreationNamespace(into->rel);
2749 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
2751 if (aclresult != ACLCHECK_OK)
2752 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2753 get_namespace_name(namespaceId));
2756 * Select tablespace to use. If not specified, use default tablespace
2757 * (which may in turn default to database's default).
2759 if (into->tableSpaceName)
2761 tablespaceId = get_tablespace_oid(into->tableSpaceName);
2762 if (!OidIsValid(tablespaceId))
2764 (errcode(ERRCODE_UNDEFINED_OBJECT),
2765 errmsg("tablespace \"%s\" does not exist",
2766 into->tableSpaceName)));
2770 tablespaceId = GetDefaultTablespace(into->rel->istemp);
2771 /* note InvalidOid is OK in this case */
2774 /* Check permissions except when using the database's default space */
2775 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
2777 AclResult aclresult;
2779 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
2782 if (aclresult != ACLCHECK_OK)
2783 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
2784 get_tablespace_name(tablespaceId));
2787 /* Parse and validate any reloptions */
2788 reloptions = transformRelOptions((Datum) 0,
2792 (void) heap_reloptions(RELKIND_RELATION, reloptions, true);
2794 /* Copy the tupdesc because heap_create_with_catalog modifies it */
2795 tupdesc = CreateTupleDescCopy(queryDesc->tupDesc);
2797 /* Now we can actually create the new relation */
2798 intoRelationId = heap_create_with_catalog(intoName,
2811 allowSystemTableMods);
2813 FreeTupleDesc(tupdesc);
2816 * Advance command counter so that the newly-created relation's catalog
2817 * tuples will be visible to heap_open.
2819 CommandCounterIncrement();
2822 * If necessary, create a TOAST table for the INTO relation. Note that
2823 * AlterTableCreateToastTable ends with CommandCounterIncrement(), so that
2824 * the TOAST table will be visible for insertion.
2826 AlterTableCreateToastTable(intoRelationId);
2829 * And open the constructed table for writing.
2831 intoRelationDesc = heap_open(intoRelationId, AccessExclusiveLock);
2834 * Now replace the query's DestReceiver with one for SELECT INTO
2836 queryDesc->dest = CreateDestReceiver(DestIntoRel);
2837 myState = (DR_intorel *) queryDesc->dest;
2838 Assert(myState->pub.mydest == DestIntoRel);
2839 myState->estate = estate;
2840 myState->rel = intoRelationDesc;
2843 * We can skip WAL-logging the insertions, unless PITR is in use. We
2844 * can skip the FSM in any case.
2846 myState->hi_options = HEAP_INSERT_SKIP_FSM |
2847 (XLogArchivingActive() ? 0 : HEAP_INSERT_SKIP_WAL);
2848 myState->bistate = GetBulkInsertState();
2850 /* Not using WAL requires rd_targblock be initially invalid */
2851 Assert(intoRelationDesc->rd_targblock == InvalidBlockNumber);
2855 * CloseIntoRel --- clean up SELECT INTO at ExecutorEnd time
2858 CloseIntoRel(QueryDesc *queryDesc)
2860 DR_intorel *myState = (DR_intorel *) queryDesc->dest;
2862 /* OpenIntoRel might never have gotten called */
2863 if (myState && myState->pub.mydest == DestIntoRel && myState->rel)
2865 FreeBulkInsertState(myState->bistate);
2867 /* If we skipped using WAL, must heap_sync before commit */
2868 if (myState->hi_options & HEAP_INSERT_SKIP_WAL)
2869 heap_sync(myState->rel);
2871 /* close rel, but keep lock until commit */
2872 heap_close(myState->rel, NoLock);
2874 myState->rel = NULL;
2879 * CreateIntoRelDestReceiver -- create a suitable DestReceiver object
2882 CreateIntoRelDestReceiver(void)
2884 DR_intorel *self = (DR_intorel *) palloc0(sizeof(DR_intorel));
2886 self->pub.receiveSlot = intorel_receive;
2887 self->pub.rStartup = intorel_startup;
2888 self->pub.rShutdown = intorel_shutdown;
2889 self->pub.rDestroy = intorel_destroy;
2890 self->pub.mydest = DestIntoRel;
2892 /* private fields will be set by OpenIntoRel */
2894 return (DestReceiver *) self;
2898 * intorel_startup --- executor startup
2901 intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
2907 * intorel_receive --- receive one tuple
2910 intorel_receive(TupleTableSlot *slot, DestReceiver *self)
2912 DR_intorel *myState = (DR_intorel *) self;
2916 * get the heap tuple out of the tuple table slot, making sure we have a
2919 tuple = ExecMaterializeSlot(slot);
2921 heap_insert(myState->rel,
2923 myState->estate->es_output_cid,
2924 myState->hi_options,
2927 /* We know this is a newly created relation, so there are no indexes */
2933 * intorel_shutdown --- executor end
2936 intorel_shutdown(DestReceiver *self)
2942 * intorel_destroy --- release DestReceiver object
2945 intorel_destroy(DestReceiver *self)