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.313 2008/08/25 22:42:32 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 /* Hook for plugins to get control in ExecutorRun() */
64 ExecutorRun_hook_type ExecutorRun_hook = NULL;
66 typedef struct evalPlanQual
71 struct evalPlanQual *next; /* stack of active PlanQual plans */
72 struct evalPlanQual *free; /* list of free PlanQual plans */
75 /* decls for local routines only used within this module */
76 static void InitPlan(QueryDesc *queryDesc, int eflags);
77 static void ExecCheckPlanOutput(Relation resultRel, List *targetList);
78 static void ExecEndPlan(PlanState *planstate, EState *estate);
79 static TupleTableSlot *ExecutePlan(EState *estate, PlanState *planstate,
82 ScanDirection direction,
84 static void ExecSelect(TupleTableSlot *slot,
85 DestReceiver *dest, EState *estate);
86 static void ExecInsert(TupleTableSlot *slot, ItemPointer tupleid,
87 TupleTableSlot *planSlot,
88 DestReceiver *dest, EState *estate);
89 static void ExecDelete(ItemPointer tupleid,
90 TupleTableSlot *planSlot,
91 DestReceiver *dest, EState *estate);
92 static void ExecUpdate(TupleTableSlot *slot, ItemPointer tupleid,
93 TupleTableSlot *planSlot,
94 DestReceiver *dest, EState *estate);
95 static void ExecProcessReturning(ProjectionInfo *projectReturning,
96 TupleTableSlot *tupleSlot,
97 TupleTableSlot *planSlot,
99 static TupleTableSlot *EvalPlanQualNext(EState *estate);
100 static void EndEvalPlanQual(EState *estate);
101 static void ExecCheckRTPerms(List *rangeTable);
102 static void ExecCheckRTEPerms(RangeTblEntry *rte);
103 static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
104 static void EvalPlanQualStart(evalPlanQual *epq, EState *estate,
105 evalPlanQual *priorepq);
106 static void EvalPlanQualStop(evalPlanQual *epq);
107 static void OpenIntoRel(QueryDesc *queryDesc);
108 static void CloseIntoRel(QueryDesc *queryDesc);
109 static void intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
110 static void intorel_receive(TupleTableSlot *slot, DestReceiver *self);
111 static void intorel_shutdown(DestReceiver *self);
112 static void intorel_destroy(DestReceiver *self);
114 /* end of local decls */
117 /* ----------------------------------------------------------------
120 * This routine must be called at the beginning of any execution of any
123 * Takes a QueryDesc previously created by CreateQueryDesc (it's not real
124 * clear why we bother to separate the two functions, but...). The tupDesc
125 * field of the QueryDesc is filled in to describe the tuples that will be
126 * returned, and the internal fields (estate and planstate) are set up.
128 * eflags contains flag bits as described in executor.h.
130 * NB: the CurrentMemoryContext when this is called will become the parent
131 * of the per-query context used for this Executor invocation.
132 * ----------------------------------------------------------------
135 ExecutorStart(QueryDesc *queryDesc, int eflags)
138 MemoryContext oldcontext;
140 /* sanity checks: queryDesc must not be started already */
141 Assert(queryDesc != NULL);
142 Assert(queryDesc->estate == NULL);
145 * If the transaction is read-only, we need to check if any writes are
146 * planned to non-temporary tables. EXPLAIN is considered read-only.
148 if (XactReadOnly && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
149 ExecCheckXactReadOnly(queryDesc->plannedstmt);
152 * Build EState, switch into per-query memory context for startup.
154 estate = CreateExecutorState();
155 queryDesc->estate = estate;
157 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
160 * Fill in parameters, if any, from queryDesc
162 estate->es_param_list_info = queryDesc->params;
164 if (queryDesc->plannedstmt->nParamExec > 0)
165 estate->es_param_exec_vals = (ParamExecData *)
166 palloc0(queryDesc->plannedstmt->nParamExec * sizeof(ParamExecData));
169 * If non-read-only query, set the command ID to mark output tuples with
171 switch (queryDesc->operation)
174 /* SELECT INTO and SELECT FOR UPDATE/SHARE need to mark tuples */
175 if (queryDesc->plannedstmt->intoClause != NULL ||
176 queryDesc->plannedstmt->rowMarks != NIL)
177 estate->es_output_cid = GetCurrentCommandId(true);
183 estate->es_output_cid = GetCurrentCommandId(true);
187 elog(ERROR, "unrecognized operation code: %d",
188 (int) queryDesc->operation);
193 * Copy other important information into the EState
195 estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
196 estate->es_crosscheck_snapshot = RegisterSnapshot(queryDesc->crosscheck_snapshot);
197 estate->es_instrument = queryDesc->doInstrument;
200 * Initialize the plan state tree
202 InitPlan(queryDesc, eflags);
204 MemoryContextSwitchTo(oldcontext);
207 /* ----------------------------------------------------------------
210 * This is the main routine of the executor module. It accepts
211 * the query descriptor from the traffic cop and executes the
214 * ExecutorStart must have been called already.
216 * If direction is NoMovementScanDirection then nothing is done
217 * except to start up/shut down the destination. Otherwise,
218 * we retrieve up to 'count' tuples in the specified direction.
220 * Note: count = 0 is interpreted as no portal limit, i.e., run to
223 * We provide a function hook variable that lets loadable plugins
224 * get control when ExecutorRun is called. Such a plugin would
225 * normally call standard_ExecutorRun().
227 * ----------------------------------------------------------------
230 ExecutorRun(QueryDesc *queryDesc,
231 ScanDirection direction, long count)
233 TupleTableSlot *result;
235 if (ExecutorRun_hook)
236 result = (*ExecutorRun_hook) (queryDesc, direction, count);
238 result = standard_ExecutorRun(queryDesc, direction, count);
243 standard_ExecutorRun(QueryDesc *queryDesc,
244 ScanDirection direction, long count)
250 TupleTableSlot *result;
251 MemoryContext oldcontext;
254 Assert(queryDesc != NULL);
256 estate = queryDesc->estate;
258 Assert(estate != NULL);
261 * Switch into per-query memory context
263 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
266 * extract information from the query descriptor and the query feature.
268 operation = queryDesc->operation;
269 dest = queryDesc->dest;
272 * startup tuple receiver, if we will be emitting tuples
274 estate->es_processed = 0;
275 estate->es_lastoid = InvalidOid;
277 sendTuples = (operation == CMD_SELECT ||
278 queryDesc->plannedstmt->returningLists);
281 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
286 if (ScanDirectionIsNoMovement(direction))
289 result = ExecutePlan(estate,
290 queryDesc->planstate,
297 * shutdown tuple receiver, if we started it
300 (*dest->rShutdown) (dest);
302 MemoryContextSwitchTo(oldcontext);
307 /* ----------------------------------------------------------------
310 * This routine must be called at the end of execution of any
312 * ----------------------------------------------------------------
315 ExecutorEnd(QueryDesc *queryDesc)
318 MemoryContext oldcontext;
321 Assert(queryDesc != NULL);
323 estate = queryDesc->estate;
325 Assert(estate != NULL);
328 * Switch into per-query memory context to run ExecEndPlan
330 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
332 ExecEndPlan(queryDesc->planstate, estate);
335 * Close the SELECT INTO relation if any
337 if (estate->es_select_into)
338 CloseIntoRel(queryDesc);
340 /* do away with our snapshots */
341 UnregisterSnapshot(estate->es_snapshot);
342 UnregisterSnapshot(estate->es_crosscheck_snapshot);
345 * Must switch out of context before destroying it
347 MemoryContextSwitchTo(oldcontext);
350 * Release EState and per-query memory context. This should release
351 * everything the executor has allocated.
353 FreeExecutorState(estate);
355 /* Reset queryDesc fields that no longer point to anything */
356 queryDesc->tupDesc = NULL;
357 queryDesc->estate = NULL;
358 queryDesc->planstate = NULL;
361 /* ----------------------------------------------------------------
364 * This routine may be called on an open queryDesc to rewind it
366 * ----------------------------------------------------------------
369 ExecutorRewind(QueryDesc *queryDesc)
372 MemoryContext oldcontext;
375 Assert(queryDesc != NULL);
377 estate = queryDesc->estate;
379 Assert(estate != NULL);
381 /* It's probably not sensible to rescan updating queries */
382 Assert(queryDesc->operation == CMD_SELECT);
385 * Switch into per-query memory context
387 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
392 ExecReScan(queryDesc->planstate, NULL);
394 MemoryContextSwitchTo(oldcontext);
400 * Check access permissions for all relations listed in a range table.
403 ExecCheckRTPerms(List *rangeTable)
407 foreach(l, rangeTable)
409 ExecCheckRTEPerms((RangeTblEntry *) lfirst(l));
415 * Check access permissions for a single RTE.
418 ExecCheckRTEPerms(RangeTblEntry *rte)
420 AclMode requiredPerms;
425 * Only plain-relation RTEs need to be checked here. Function RTEs are
426 * checked by init_fcache when the function is prepared for execution.
427 * Join, subquery, and special RTEs need no checks.
429 if (rte->rtekind != RTE_RELATION)
433 * No work if requiredPerms is empty.
435 requiredPerms = rte->requiredPerms;
436 if (requiredPerms == 0)
442 * userid to check as: current user unless we have a setuid indication.
444 * Note: GetUserId() is presently fast enough that there's no harm in
445 * calling it separately for each RTE. If that stops being true, we could
446 * call it once in ExecCheckRTPerms and pass the userid down from there.
447 * But for now, no need for the extra clutter.
449 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
452 * We must have *all* the requiredPerms bits, so use aclmask not aclcheck.
454 if (pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL)
456 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
457 get_rel_name(relOid));
461 * Check that the query does not imply any writes to non-temp tables.
464 ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
469 * CREATE TABLE AS or SELECT INTO?
471 * XXX should we allow this if the destination is temp?
473 if (plannedstmt->intoClause != NULL)
476 /* Fail if write permissions are requested on any non-temp table */
477 foreach(l, plannedstmt->rtable)
479 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
481 if (rte->rtekind != RTE_RELATION)
484 if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
487 if (isTempNamespace(get_rel_namespace(rte->relid)))
497 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
498 errmsg("transaction is read-only")));
502 /* ----------------------------------------------------------------
505 * Initializes the query plan: open files, allocate storage
506 * and start up the rule manager
507 * ----------------------------------------------------------------
510 InitPlan(QueryDesc *queryDesc, int eflags)
512 CmdType operation = queryDesc->operation;
513 PlannedStmt *plannedstmt = queryDesc->plannedstmt;
514 Plan *plan = plannedstmt->planTree;
515 List *rangeTable = plannedstmt->rtable;
516 EState *estate = queryDesc->estate;
517 PlanState *planstate;
523 * Do permissions checks
525 ExecCheckRTPerms(rangeTable);
528 * initialize the node's execution state
530 estate->es_range_table = rangeTable;
533 * initialize result relation stuff
535 if (plannedstmt->resultRelations)
537 List *resultRelations = plannedstmt->resultRelations;
538 int numResultRelations = list_length(resultRelations);
539 ResultRelInfo *resultRelInfos;
540 ResultRelInfo *resultRelInfo;
542 resultRelInfos = (ResultRelInfo *)
543 palloc(numResultRelations * sizeof(ResultRelInfo));
544 resultRelInfo = resultRelInfos;
545 foreach(l, resultRelations)
547 Index resultRelationIndex = lfirst_int(l);
548 Oid resultRelationOid;
549 Relation resultRelation;
551 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
552 resultRelation = heap_open(resultRelationOid, RowExclusiveLock);
553 InitResultRelInfo(resultRelInfo,
557 estate->es_instrument);
560 estate->es_result_relations = resultRelInfos;
561 estate->es_num_result_relations = numResultRelations;
562 /* Initialize to first or only result rel */
563 estate->es_result_relation_info = resultRelInfos;
568 * if no result relation, then set state appropriately
570 estate->es_result_relations = NULL;
571 estate->es_num_result_relations = 0;
572 estate->es_result_relation_info = NULL;
576 * Detect whether we're doing SELECT INTO. If so, set the es_into_oids
577 * flag appropriately so that the plan tree will be initialized with the
578 * correct tuple descriptors. (Other SELECT INTO stuff comes later.)
580 estate->es_select_into = false;
581 if (operation == CMD_SELECT && plannedstmt->intoClause != NULL)
583 estate->es_select_into = true;
584 estate->es_into_oids = interpretOidsOption(plannedstmt->intoClause->options);
588 * Have to lock relations selected FOR UPDATE/FOR SHARE before we
589 * initialize the plan tree, else we'd be doing a lock upgrade. While we
590 * are at it, build the ExecRowMark list.
592 estate->es_rowMarks = NIL;
593 foreach(l, plannedstmt->rowMarks)
595 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
596 Oid relid = getrelid(rc->rti, rangeTable);
600 relation = heap_open(relid, RowShareLock);
601 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
602 erm->relation = relation;
604 erm->forUpdate = rc->forUpdate;
605 erm->noWait = rc->noWait;
606 /* We'll set up ctidAttno below */
607 erm->ctidAttNo = InvalidAttrNumber;
608 estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
612 * Initialize the executor "tuple" table. We need slots for all the plan
613 * nodes, plus possibly output slots for the junkfilter(s). At this point
614 * we aren't sure if we need junkfilters, so just add slots for them
615 * unconditionally. Also, if it's not a SELECT, set up a slot for use for
616 * trigger output tuples. Also, one for RETURNING-list evaluation.
621 /* Slots for the main plan tree */
622 nSlots = ExecCountSlotsNode(plan);
623 /* Add slots for subplans and initplans */
624 foreach(l, plannedstmt->subplans)
626 Plan *subplan = (Plan *) lfirst(l);
628 nSlots += ExecCountSlotsNode(subplan);
630 /* Add slots for junkfilter(s) */
631 if (plannedstmt->resultRelations != NIL)
632 nSlots += list_length(plannedstmt->resultRelations);
635 if (operation != CMD_SELECT)
636 nSlots++; /* for es_trig_tuple_slot */
637 if (plannedstmt->returningLists)
638 nSlots++; /* for RETURNING projection */
640 estate->es_tupleTable = ExecCreateTupleTable(nSlots);
642 if (operation != CMD_SELECT)
643 estate->es_trig_tuple_slot =
644 ExecAllocTableSlot(estate->es_tupleTable);
647 /* mark EvalPlanQual not active */
648 estate->es_plannedstmt = plannedstmt;
649 estate->es_evalPlanQual = NULL;
650 estate->es_evTupleNull = NULL;
651 estate->es_evTuple = NULL;
652 estate->es_useEvalPlan = false;
655 * Initialize private state information for each SubPlan. We must do this
656 * before running ExecInitNode on the main query tree, since
657 * ExecInitSubPlan expects to be able to find these entries.
659 Assert(estate->es_subplanstates == NIL);
660 i = 1; /* subplan indices count from 1 */
661 foreach(l, plannedstmt->subplans)
663 Plan *subplan = (Plan *) lfirst(l);
664 PlanState *subplanstate;
668 * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
669 * it is a parameterless subplan (not initplan), we suggest that it be
670 * prepared to handle REWIND efficiently; otherwise there is no need.
672 sp_eflags = eflags & EXEC_FLAG_EXPLAIN_ONLY;
673 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
674 sp_eflags |= EXEC_FLAG_REWIND;
676 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
678 estate->es_subplanstates = lappend(estate->es_subplanstates,
685 * Initialize the private state information for all the nodes in the query
686 * tree. This opens files, allocates storage and leaves us ready to start
689 planstate = ExecInitNode(plan, estate, eflags);
692 * Get the tuple descriptor describing the type of tuples to return. (this
693 * is especially important if we are creating a relation with "SELECT
696 tupType = ExecGetResultType(planstate);
699 * Initialize the junk filter if needed. SELECT and INSERT queries need a
700 * filter if there are any junk attrs in the tlist. UPDATE and
701 * DELETE always need a filter, since there's always a junk 'ctid'
702 * attribute present --- no need to look first.
704 * This section of code is also a convenient place to verify that the
705 * output of an INSERT or UPDATE matches the target table(s).
708 bool junk_filter_needed = false;
715 foreach(tlist, plan->targetlist)
717 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
721 junk_filter_needed = true;
728 junk_filter_needed = true;
734 if (junk_filter_needed)
737 * If there are multiple result relations, each one needs its own
738 * junk filter. Note this is only possible for UPDATE/DELETE, so
739 * we can't be fooled by some needing a filter and some not.
741 if (list_length(plannedstmt->resultRelations) > 1)
743 PlanState **appendplans;
745 ResultRelInfo *resultRelInfo;
747 /* Top plan had better be an Append here. */
748 Assert(IsA(plan, Append));
749 Assert(((Append *) plan)->isTarget);
750 Assert(IsA(planstate, AppendState));
751 appendplans = ((AppendState *) planstate)->appendplans;
752 as_nplans = ((AppendState *) planstate)->as_nplans;
753 Assert(as_nplans == estate->es_num_result_relations);
754 resultRelInfo = estate->es_result_relations;
755 for (i = 0; i < as_nplans; i++)
757 PlanState *subplan = appendplans[i];
760 if (operation == CMD_UPDATE)
761 ExecCheckPlanOutput(resultRelInfo->ri_RelationDesc,
762 subplan->plan->targetlist);
764 j = ExecInitJunkFilter(subplan->plan->targetlist,
765 resultRelInfo->ri_RelationDesc->rd_att->tdhasoid,
766 ExecAllocTableSlot(estate->es_tupleTable));
769 * Since it must be UPDATE/DELETE, there had better be a
770 * "ctid" junk attribute in the tlist ... but ctid could
771 * be at a different resno for each result relation. We
772 * look up the ctid resnos now and save them in the
775 j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
776 if (!AttributeNumberIsValid(j->jf_junkAttNo))
777 elog(ERROR, "could not find junk ctid column");
778 resultRelInfo->ri_junkFilter = j;
783 * Set active junkfilter too; at this point ExecInitAppend has
784 * already selected an active result relation...
786 estate->es_junkFilter =
787 estate->es_result_relation_info->ri_junkFilter;
790 * We currently can't support rowmarks in this case, because
791 * the associated junk CTIDs might have different resnos in
792 * different subplans.
794 if (estate->es_rowMarks)
796 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
797 errmsg("SELECT FOR UPDATE/SHARE is not supported within a query with multiple result relations")));
801 /* Normal case with just one JunkFilter */
804 if (operation == CMD_INSERT || operation == CMD_UPDATE)
805 ExecCheckPlanOutput(estate->es_result_relation_info->ri_RelationDesc,
806 planstate->plan->targetlist);
808 j = ExecInitJunkFilter(planstate->plan->targetlist,
810 ExecAllocTableSlot(estate->es_tupleTable));
811 estate->es_junkFilter = j;
812 if (estate->es_result_relation_info)
813 estate->es_result_relation_info->ri_junkFilter = j;
815 if (operation == CMD_SELECT)
817 /* For SELECT, want to return the cleaned tuple type */
818 tupType = j->jf_cleanTupType;
820 else if (operation == CMD_UPDATE || operation == CMD_DELETE)
822 /* For UPDATE/DELETE, find the ctid junk attr now */
823 j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
824 if (!AttributeNumberIsValid(j->jf_junkAttNo))
825 elog(ERROR, "could not find junk ctid column");
828 /* For SELECT FOR UPDATE/SHARE, find the ctid attrs now */
829 foreach(l, estate->es_rowMarks)
831 ExecRowMark *erm = (ExecRowMark *) lfirst(l);
834 snprintf(resname, sizeof(resname), "ctid%u", erm->rti);
835 erm->ctidAttNo = ExecFindJunkAttribute(j, resname);
836 if (!AttributeNumberIsValid(erm->ctidAttNo))
837 elog(ERROR, "could not find junk \"%s\" column",
844 if (operation == CMD_INSERT)
845 ExecCheckPlanOutput(estate->es_result_relation_info->ri_RelationDesc,
846 planstate->plan->targetlist);
848 estate->es_junkFilter = NULL;
849 if (estate->es_rowMarks)
850 elog(ERROR, "SELECT FOR UPDATE/SHARE, but no junk columns");
855 * Initialize RETURNING projections if needed.
857 if (plannedstmt->returningLists)
859 TupleTableSlot *slot;
860 ExprContext *econtext;
861 ResultRelInfo *resultRelInfo;
864 * We set QueryDesc.tupDesc to be the RETURNING rowtype in this case.
865 * We assume all the sublists will generate the same output tupdesc.
867 tupType = ExecTypeFromTL((List *) linitial(plannedstmt->returningLists),
870 /* Set up a slot for the output of the RETURNING projection(s) */
871 slot = ExecAllocTableSlot(estate->es_tupleTable);
872 ExecSetSlotDescriptor(slot, tupType);
873 /* Need an econtext too */
874 econtext = CreateExprContext(estate);
877 * Build a projection for each result rel. Note that any SubPlans in
878 * the RETURNING lists get attached to the topmost plan node.
880 Assert(list_length(plannedstmt->returningLists) == estate->es_num_result_relations);
881 resultRelInfo = estate->es_result_relations;
882 foreach(l, plannedstmt->returningLists)
884 List *rlist = (List *) lfirst(l);
887 rliststate = (List *) ExecInitExpr((Expr *) rlist, planstate);
888 resultRelInfo->ri_projectReturning =
889 ExecBuildProjectionInfo(rliststate, econtext, slot,
890 resultRelInfo->ri_RelationDesc->rd_att);
895 queryDesc->tupDesc = tupType;
896 queryDesc->planstate = planstate;
899 * If doing SELECT INTO, initialize the "into" relation. We must wait
900 * till now so we have the "clean" result tuple type to create the new
903 * If EXPLAIN, skip creating the "into" relation.
905 if (estate->es_select_into && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
906 OpenIntoRel(queryDesc);
910 * Initialize ResultRelInfo data for one result relation
913 InitResultRelInfo(ResultRelInfo *resultRelInfo,
914 Relation resultRelationDesc,
915 Index resultRelationIndex,
920 * Check valid relkind ... parser and/or planner should have noticed this
921 * already, but let's make sure.
923 switch (resultRelationDesc->rd_rel->relkind)
925 case RELKIND_RELATION:
928 case RELKIND_SEQUENCE:
930 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
931 errmsg("cannot change sequence \"%s\"",
932 RelationGetRelationName(resultRelationDesc))));
934 case RELKIND_TOASTVALUE:
936 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
937 errmsg("cannot change TOAST relation \"%s\"",
938 RelationGetRelationName(resultRelationDesc))));
942 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
943 errmsg("cannot change view \"%s\"",
944 RelationGetRelationName(resultRelationDesc))));
948 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
949 errmsg("cannot change relation \"%s\"",
950 RelationGetRelationName(resultRelationDesc))));
954 /* OK, fill in the node */
955 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
956 resultRelInfo->type = T_ResultRelInfo;
957 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
958 resultRelInfo->ri_RelationDesc = resultRelationDesc;
959 resultRelInfo->ri_NumIndices = 0;
960 resultRelInfo->ri_IndexRelationDescs = NULL;
961 resultRelInfo->ri_IndexRelationInfo = NULL;
962 /* make a copy so as not to depend on relcache info not changing... */
963 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
964 if (resultRelInfo->ri_TrigDesc)
966 int n = resultRelInfo->ri_TrigDesc->numtriggers;
968 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
969 palloc0(n * sizeof(FmgrInfo));
971 resultRelInfo->ri_TrigInstrument = InstrAlloc(n);
973 resultRelInfo->ri_TrigInstrument = NULL;
977 resultRelInfo->ri_TrigFunctions = NULL;
978 resultRelInfo->ri_TrigInstrument = NULL;
980 resultRelInfo->ri_ConstraintExprs = NULL;
981 resultRelInfo->ri_junkFilter = NULL;
982 resultRelInfo->ri_projectReturning = NULL;
985 * If there are indices on the result relation, open them and save
986 * descriptors in the result relation info, so that we can add new index
987 * entries for the tuples we add/update. We need not do this for a
988 * DELETE, however, since deletion doesn't affect indexes.
990 if (resultRelationDesc->rd_rel->relhasindex &&
991 operation != CMD_DELETE)
992 ExecOpenIndices(resultRelInfo);
996 * Verify that the tuples to be produced by INSERT or UPDATE match the
997 * target relation's rowtype
999 * We do this to guard against stale plans. If plan invalidation is
1000 * functioning properly then we should never get a failure here, but better
1001 * safe than sorry. Note that this is called after we have obtained lock
1002 * on the target rel, so the rowtype can't change underneath us.
1004 * The plan output is represented by its targetlist, because that makes
1005 * handling the dropped-column case easier.
1008 ExecCheckPlanOutput(Relation resultRel, List *targetList)
1010 TupleDesc resultDesc = RelationGetDescr(resultRel);
1014 foreach(lc, targetList)
1016 TargetEntry *tle = (TargetEntry *) lfirst(lc);
1017 Form_pg_attribute attr;
1020 continue; /* ignore junk tlist items */
1022 if (attno >= resultDesc->natts)
1024 (errcode(ERRCODE_DATATYPE_MISMATCH),
1025 errmsg("table row type and query-specified row type do not match"),
1026 errdetail("Query has too many columns.")));
1027 attr = resultDesc->attrs[attno++];
1029 if (!attr->attisdropped)
1031 /* Normal case: demand type match */
1032 if (exprType((Node *) tle->expr) != attr->atttypid)
1034 (errcode(ERRCODE_DATATYPE_MISMATCH),
1035 errmsg("table row type and query-specified row type do not match"),
1036 errdetail("Table has type %s at ordinal position %d, but query expects %s.",
1037 format_type_be(attr->atttypid),
1039 format_type_be(exprType((Node *) tle->expr)))));
1044 * For a dropped column, we can't check atttypid (it's likely 0).
1045 * In any case the planner has most likely inserted an INT4 null.
1046 * What we insist on is just *some* NULL constant.
1048 if (!IsA(tle->expr, Const) ||
1049 !((Const *) tle->expr)->constisnull)
1051 (errcode(ERRCODE_DATATYPE_MISMATCH),
1052 errmsg("table row type and query-specified row type do not match"),
1053 errdetail("Query provides a value for a dropped column at ordinal position %d.",
1057 if (attno != resultDesc->natts)
1059 (errcode(ERRCODE_DATATYPE_MISMATCH),
1060 errmsg("table row type and query-specified row type do not match"),
1061 errdetail("Query has too few columns.")));
1065 * ExecGetTriggerResultRel
1067 * Get a ResultRelInfo for a trigger target relation. Most of the time,
1068 * triggers are fired on one of the result relations of the query, and so
1069 * we can just return a member of the es_result_relations array. (Note: in
1070 * self-join situations there might be multiple members with the same OID;
1071 * if so it doesn't matter which one we pick.) However, it is sometimes
1072 * necessary to fire triggers on other relations; this happens mainly when an
1073 * RI update trigger queues additional triggers on other relations, which will
1074 * be processed in the context of the outer query. For efficiency's sake,
1075 * we want to have a ResultRelInfo for those triggers too; that can avoid
1076 * repeated re-opening of the relation. (It also provides a way for EXPLAIN
1077 * ANALYZE to report the runtimes of such triggers.) So we make additional
1078 * ResultRelInfo's as needed, and save them in es_trig_target_relations.
1081 ExecGetTriggerResultRel(EState *estate, Oid relid)
1083 ResultRelInfo *rInfo;
1087 MemoryContext oldcontext;
1089 /* First, search through the query result relations */
1090 rInfo = estate->es_result_relations;
1091 nr = estate->es_num_result_relations;
1094 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1099 /* Nope, but maybe we already made an extra ResultRelInfo for it */
1100 foreach(l, estate->es_trig_target_relations)
1102 rInfo = (ResultRelInfo *) lfirst(l);
1103 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1106 /* Nope, so we need a new one */
1109 * Open the target relation's relcache entry. We assume that an
1110 * appropriate lock is still held by the backend from whenever the trigger
1111 * event got queued, so we need take no new lock here.
1113 rel = heap_open(relid, NoLock);
1116 * Make the new entry in the right context. Currently, we don't need any
1117 * index information in ResultRelInfos used only for triggers, so tell
1118 * InitResultRelInfo it's a DELETE.
1120 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1121 rInfo = makeNode(ResultRelInfo);
1122 InitResultRelInfo(rInfo,
1124 0, /* dummy rangetable index */
1126 estate->es_instrument);
1127 estate->es_trig_target_relations =
1128 lappend(estate->es_trig_target_relations, rInfo);
1129 MemoryContextSwitchTo(oldcontext);
1135 * ExecContextForcesOids
1137 * This is pretty grotty: when doing INSERT, UPDATE, or SELECT INTO,
1138 * we need to ensure that result tuples have space for an OID iff they are
1139 * going to be stored into a relation that has OIDs. In other contexts
1140 * we are free to choose whether to leave space for OIDs in result tuples
1141 * (we generally don't want to, but we do if a physical-tlist optimization
1142 * is possible). This routine checks the plan context and returns TRUE if the
1143 * choice is forced, FALSE if the choice is not forced. In the TRUE case,
1144 * *hasoids is set to the required value.
1146 * One reason this is ugly is that all plan nodes in the plan tree will emit
1147 * tuples with space for an OID, though we really only need the topmost node
1148 * to do so. However, node types like Sort don't project new tuples but just
1149 * return their inputs, and in those cases the requirement propagates down
1150 * to the input node. Eventually we might make this code smart enough to
1151 * recognize how far down the requirement really goes, but for now we just
1152 * make all plan nodes do the same thing if the top level forces the choice.
1154 * We assume that estate->es_result_relation_info is already set up to
1155 * describe the target relation. Note that in an UPDATE that spans an
1156 * inheritance tree, some of the target relations may have OIDs and some not.
1157 * We have to make the decisions on a per-relation basis as we initialize
1158 * each of the child plans of the topmost Append plan.
1160 * SELECT INTO is even uglier, because we don't have the INTO relation's
1161 * descriptor available when this code runs; we have to look aside at a
1162 * flag set by InitPlan().
1165 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
1167 if (planstate->state->es_select_into)
1169 *hasoids = planstate->state->es_into_oids;
1174 ResultRelInfo *ri = planstate->state->es_result_relation_info;
1178 Relation rel = ri->ri_RelationDesc;
1182 *hasoids = rel->rd_rel->relhasoids;
1191 /* ----------------------------------------------------------------
1194 * Cleans up the query plan -- closes files and frees up storage
1196 * NOTE: we are no longer very worried about freeing storage per se
1197 * in this code; FreeExecutorState should be guaranteed to release all
1198 * memory that needs to be released. What we are worried about doing
1199 * is closing relations and dropping buffer pins. Thus, for example,
1200 * tuple tables must be cleared or dropped to ensure pins are released.
1201 * ----------------------------------------------------------------
1204 ExecEndPlan(PlanState *planstate, EState *estate)
1206 ResultRelInfo *resultRelInfo;
1211 * shut down any PlanQual processing we were doing
1213 if (estate->es_evalPlanQual != NULL)
1214 EndEvalPlanQual(estate);
1217 * shut down the node-type-specific query processing
1219 ExecEndNode(planstate);
1224 foreach(l, estate->es_subplanstates)
1226 PlanState *subplanstate = (PlanState *) lfirst(l);
1228 ExecEndNode(subplanstate);
1232 * destroy the executor "tuple" table.
1234 ExecDropTupleTable(estate->es_tupleTable, true);
1235 estate->es_tupleTable = NULL;
1238 * close the result relation(s) if any, but hold locks until xact commit.
1240 resultRelInfo = estate->es_result_relations;
1241 for (i = estate->es_num_result_relations; i > 0; i--)
1243 /* Close indices and then the relation itself */
1244 ExecCloseIndices(resultRelInfo);
1245 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1250 * likewise close any trigger target relations
1252 foreach(l, estate->es_trig_target_relations)
1254 resultRelInfo = (ResultRelInfo *) lfirst(l);
1255 /* Close indices and then the relation itself */
1256 ExecCloseIndices(resultRelInfo);
1257 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1261 * close any relations selected FOR UPDATE/FOR SHARE, again keeping locks
1263 foreach(l, estate->es_rowMarks)
1265 ExecRowMark *erm = lfirst(l);
1267 heap_close(erm->relation, NoLock);
1271 /* ----------------------------------------------------------------
1274 * processes the query plan to retrieve 'numberTuples' tuples in the
1275 * direction specified.
1277 * Retrieves all tuples if numberTuples is 0
1279 * result is either a slot containing the last tuple in the case
1280 * of a SELECT or NULL otherwise.
1282 * Note: the ctid attribute is a 'junk' attribute that is removed before the
1284 * ----------------------------------------------------------------
1286 static TupleTableSlot *
1287 ExecutePlan(EState *estate,
1288 PlanState *planstate,
1291 ScanDirection direction,
1294 JunkFilter *junkfilter;
1295 TupleTableSlot *planSlot;
1296 TupleTableSlot *slot;
1297 ItemPointer tupleid = NULL;
1298 ItemPointerData tuple_ctid;
1299 long current_tuple_count;
1300 TupleTableSlot *result;
1303 * initialize local variables
1305 current_tuple_count = 0;
1309 * Set the direction.
1311 estate->es_direction = direction;
1314 * Process BEFORE EACH STATEMENT triggers
1319 ExecBSUpdateTriggers(estate, estate->es_result_relation_info);
1322 ExecBSDeleteTriggers(estate, estate->es_result_relation_info);
1325 ExecBSInsertTriggers(estate, estate->es_result_relation_info);
1333 * Loop until we've processed the proper number of tuples from the plan.
1338 /* Reset the per-output-tuple exprcontext */
1339 ResetPerTupleExprContext(estate);
1342 * Execute the plan and obtain a tuple
1345 if (estate->es_useEvalPlan)
1347 planSlot = EvalPlanQualNext(estate);
1348 if (TupIsNull(planSlot))
1349 planSlot = ExecProcNode(planstate);
1352 planSlot = ExecProcNode(planstate);
1355 * if the tuple is null, then we assume there is nothing more to
1356 * process so we just return null...
1358 if (TupIsNull(planSlot))
1366 * If we have a junk filter, then project a new tuple with the junk
1369 * Store this new "clean" tuple in the junkfilter's resultSlot.
1370 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1371 * because that tuple slot has the wrong descriptor.)
1373 * But first, extract all the junk information we need.
1375 if ((junkfilter = estate->es_junkFilter) != NULL)
1378 * Process any FOR UPDATE or FOR SHARE locking requested.
1380 if (estate->es_rowMarks != NIL)
1385 foreach(l, estate->es_rowMarks)
1387 ExecRowMark *erm = lfirst(l);
1390 HeapTupleData tuple;
1392 ItemPointerData update_ctid;
1393 TransactionId update_xmax;
1394 TupleTableSlot *newSlot;
1395 LockTupleMode lockmode;
1398 datum = ExecGetJunkAttribute(slot,
1401 /* shouldn't ever get a null result... */
1403 elog(ERROR, "ctid is NULL");
1405 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1408 lockmode = LockTupleExclusive;
1410 lockmode = LockTupleShared;
1412 test = heap_lock_tuple(erm->relation, &tuple, &buffer,
1413 &update_ctid, &update_xmax,
1414 estate->es_output_cid,
1415 lockmode, erm->noWait);
1416 ReleaseBuffer(buffer);
1419 case HeapTupleSelfUpdated:
1420 /* treat it as deleted; do not process */
1423 case HeapTupleMayBeUpdated:
1426 case HeapTupleUpdated:
1427 if (IsXactIsoLevelSerializable)
1429 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1430 errmsg("could not serialize access due to concurrent update")));
1431 if (!ItemPointerEquals(&update_ctid,
1434 /* updated, so look at updated version */
1435 newSlot = EvalPlanQual(estate,
1439 if (!TupIsNull(newSlot))
1441 slot = planSlot = newSlot;
1442 estate->es_useEvalPlan = true;
1448 * if tuple was deleted or PlanQual failed for
1449 * updated tuple - we must not return this tuple!
1454 elog(ERROR, "unrecognized heap_lock_tuple status: %u",
1462 * extract the 'ctid' junk attribute.
1464 if (operation == CMD_UPDATE || operation == CMD_DELETE)
1469 datum = ExecGetJunkAttribute(slot, junkfilter->jf_junkAttNo,
1471 /* shouldn't ever get a null result... */
1473 elog(ERROR, "ctid is NULL");
1475 tupleid = (ItemPointer) DatumGetPointer(datum);
1476 tuple_ctid = *tupleid; /* make sure we don't free the ctid!! */
1477 tupleid = &tuple_ctid;
1481 * Create a new "clean" tuple with all junk attributes removed. We
1482 * don't need to do this for DELETE, however (there will in fact
1483 * be no non-junk attributes in a DELETE!)
1485 if (operation != CMD_DELETE)
1486 slot = ExecFilterJunk(junkfilter, slot);
1490 * now that we have a tuple, do the appropriate thing with it.. either
1491 * return it to the user, add it to a relation someplace, delete it
1492 * from a relation, or modify some of its attributes.
1497 ExecSelect(slot, dest, estate);
1502 ExecInsert(slot, tupleid, planSlot, dest, estate);
1507 ExecDelete(tupleid, planSlot, dest, estate);
1512 ExecUpdate(slot, tupleid, planSlot, dest, estate);
1517 elog(ERROR, "unrecognized operation code: %d",
1524 * check our tuple count.. if we've processed the proper number then
1525 * quit, else loop again and process more tuples. Zero numberTuples
1528 current_tuple_count++;
1529 if (numberTuples && numberTuples == current_tuple_count)
1534 * Process AFTER EACH STATEMENT triggers
1539 ExecASUpdateTriggers(estate, estate->es_result_relation_info);
1542 ExecASDeleteTriggers(estate, estate->es_result_relation_info);
1545 ExecASInsertTriggers(estate, estate->es_result_relation_info);
1553 * here, result is either a slot containing a tuple in the case of a
1554 * SELECT or NULL otherwise.
1559 /* ----------------------------------------------------------------
1562 * SELECTs are easy.. we just pass the tuple to the appropriate
1564 * ----------------------------------------------------------------
1567 ExecSelect(TupleTableSlot *slot,
1571 (*dest->receiveSlot) (slot, dest);
1573 (estate->es_processed)++;
1576 /* ----------------------------------------------------------------
1579 * INSERTs are trickier.. we have to insert the tuple into
1580 * the base relation and insert appropriate tuples into the
1582 * ----------------------------------------------------------------
1585 ExecInsert(TupleTableSlot *slot,
1586 ItemPointer tupleid,
1587 TupleTableSlot *planSlot,
1592 ResultRelInfo *resultRelInfo;
1593 Relation resultRelationDesc;
1597 * get the heap tuple out of the tuple table slot, making sure we have a
1600 tuple = ExecMaterializeSlot(slot);
1603 * get information on the (current) result relation
1605 resultRelInfo = estate->es_result_relation_info;
1606 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1608 /* BEFORE ROW INSERT Triggers */
1609 if (resultRelInfo->ri_TrigDesc &&
1610 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1614 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1616 if (newtuple == NULL) /* "do nothing" */
1619 if (newtuple != tuple) /* modified by Trigger(s) */
1622 * Put the modified tuple into a slot for convenience of routines
1623 * below. We assume the tuple was allocated in per-tuple memory
1624 * context, and therefore will go away by itself. The tuple table
1625 * slot should not try to clear it.
1627 TupleTableSlot *newslot = estate->es_trig_tuple_slot;
1629 if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
1630 ExecSetSlotDescriptor(newslot, slot->tts_tupleDescriptor);
1631 ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
1638 * Check the constraints of the tuple
1640 if (resultRelationDesc->rd_att->constr)
1641 ExecConstraints(resultRelInfo, slot, estate);
1646 * Note: heap_insert returns the tid (location) of the new tuple in the
1649 newId = heap_insert(resultRelationDesc, tuple,
1650 estate->es_output_cid,
1654 (estate->es_processed)++;
1655 estate->es_lastoid = newId;
1656 setLastTid(&(tuple->t_self));
1659 * insert index entries for tuple
1661 if (resultRelInfo->ri_NumIndices > 0)
1662 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1664 /* AFTER ROW INSERT Triggers */
1665 ExecARInsertTriggers(estate, resultRelInfo, tuple);
1667 /* Process RETURNING if present */
1668 if (resultRelInfo->ri_projectReturning)
1669 ExecProcessReturning(resultRelInfo->ri_projectReturning,
1670 slot, planSlot, dest);
1673 /* ----------------------------------------------------------------
1676 * DELETE is like UPDATE, except that we delete the tuple and no
1677 * index modifications are needed
1678 * ----------------------------------------------------------------
1681 ExecDelete(ItemPointer tupleid,
1682 TupleTableSlot *planSlot,
1686 ResultRelInfo *resultRelInfo;
1687 Relation resultRelationDesc;
1689 ItemPointerData update_ctid;
1690 TransactionId update_xmax;
1693 * get information on the (current) result relation
1695 resultRelInfo = estate->es_result_relation_info;
1696 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1698 /* BEFORE ROW DELETE Triggers */
1699 if (resultRelInfo->ri_TrigDesc &&
1700 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1704 dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid);
1706 if (!dodelete) /* "do nothing" */
1713 * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
1714 * the row to be deleted is visible to that snapshot, and throw a can't-
1715 * serialize error if not. This is a special-case behavior needed for
1716 * referential integrity updates in serializable transactions.
1719 result = heap_delete(resultRelationDesc, tupleid,
1720 &update_ctid, &update_xmax,
1721 estate->es_output_cid,
1722 estate->es_crosscheck_snapshot,
1723 true /* wait for commit */ );
1726 case HeapTupleSelfUpdated:
1727 /* already deleted by self; nothing to do */
1730 case HeapTupleMayBeUpdated:
1733 case HeapTupleUpdated:
1734 if (IsXactIsoLevelSerializable)
1736 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1737 errmsg("could not serialize access due to concurrent update")));
1738 else if (!ItemPointerEquals(tupleid, &update_ctid))
1740 TupleTableSlot *epqslot;
1742 epqslot = EvalPlanQual(estate,
1743 resultRelInfo->ri_RangeTableIndex,
1746 if (!TupIsNull(epqslot))
1748 *tupleid = update_ctid;
1752 /* tuple already deleted; nothing to do */
1756 elog(ERROR, "unrecognized heap_delete status: %u", result);
1761 (estate->es_processed)++;
1764 * Note: Normally one would think that we have to delete index tuples
1765 * associated with the heap tuple now...
1767 * ... but in POSTGRES, we have no need to do this because VACUUM will
1768 * take care of it later. We can't delete index tuples immediately
1769 * anyway, since the tuple is still visible to other transactions.
1772 /* AFTER ROW DELETE Triggers */
1773 ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1775 /* Process RETURNING if present */
1776 if (resultRelInfo->ri_projectReturning)
1779 * We have to put the target tuple into a slot, which means first we
1780 * gotta fetch it. We can use the trigger tuple slot.
1782 TupleTableSlot *slot = estate->es_trig_tuple_slot;
1783 HeapTupleData deltuple;
1786 deltuple.t_self = *tupleid;
1787 if (!heap_fetch(resultRelationDesc, SnapshotAny,
1788 &deltuple, &delbuffer, false, NULL))
1789 elog(ERROR, "failed to fetch deleted tuple for DELETE RETURNING");
1791 if (slot->tts_tupleDescriptor != RelationGetDescr(resultRelationDesc))
1792 ExecSetSlotDescriptor(slot, RelationGetDescr(resultRelationDesc));
1793 ExecStoreTuple(&deltuple, slot, InvalidBuffer, false);
1795 ExecProcessReturning(resultRelInfo->ri_projectReturning,
1796 slot, planSlot, dest);
1798 ExecClearTuple(slot);
1799 ReleaseBuffer(delbuffer);
1803 /* ----------------------------------------------------------------
1806 * note: we can't run UPDATE queries with transactions
1807 * off because UPDATEs are actually INSERTs and our
1808 * scan will mistakenly loop forever, updating the tuple
1809 * it just inserted.. This should be fixed but until it
1810 * is, we don't want to get stuck in an infinite loop
1811 * which corrupts your database..
1812 * ----------------------------------------------------------------
1815 ExecUpdate(TupleTableSlot *slot,
1816 ItemPointer tupleid,
1817 TupleTableSlot *planSlot,
1822 ResultRelInfo *resultRelInfo;
1823 Relation resultRelationDesc;
1825 ItemPointerData update_ctid;
1826 TransactionId update_xmax;
1829 * abort the operation if not running transactions
1831 if (IsBootstrapProcessingMode())
1832 elog(ERROR, "cannot UPDATE during bootstrap");
1835 * get the heap tuple out of the tuple table slot, making sure we have a
1838 tuple = ExecMaterializeSlot(slot);
1841 * get information on the (current) result relation
1843 resultRelInfo = estate->es_result_relation_info;
1844 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1846 /* BEFORE ROW UPDATE Triggers */
1847 if (resultRelInfo->ri_TrigDesc &&
1848 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
1852 newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
1855 if (newtuple == NULL) /* "do nothing" */
1858 if (newtuple != tuple) /* modified by Trigger(s) */
1861 * Put the modified tuple into a slot for convenience of routines
1862 * below. We assume the tuple was allocated in per-tuple memory
1863 * context, and therefore will go away by itself. The tuple table
1864 * slot should not try to clear it.
1866 TupleTableSlot *newslot = estate->es_trig_tuple_slot;
1868 if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
1869 ExecSetSlotDescriptor(newslot, slot->tts_tupleDescriptor);
1870 ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
1877 * Check the constraints of the tuple
1879 * If we generate a new candidate tuple after EvalPlanQual testing, we
1880 * must loop back here and recheck constraints. (We don't need to redo
1881 * triggers, however. If there are any BEFORE triggers then trigger.c
1882 * will have done heap_lock_tuple to lock the correct tuple, so there's no
1883 * need to do them again.)
1886 if (resultRelationDesc->rd_att->constr)
1887 ExecConstraints(resultRelInfo, slot, estate);
1890 * replace the heap tuple
1892 * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
1893 * the row to be updated is visible to that snapshot, and throw a can't-
1894 * serialize error if not. This is a special-case behavior needed for
1895 * referential integrity updates in serializable transactions.
1897 result = heap_update(resultRelationDesc, tupleid, tuple,
1898 &update_ctid, &update_xmax,
1899 estate->es_output_cid,
1900 estate->es_crosscheck_snapshot,
1901 true /* wait for commit */ );
1904 case HeapTupleSelfUpdated:
1905 /* already deleted by self; nothing to do */
1908 case HeapTupleMayBeUpdated:
1911 case HeapTupleUpdated:
1912 if (IsXactIsoLevelSerializable)
1914 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1915 errmsg("could not serialize access due to concurrent update")));
1916 else if (!ItemPointerEquals(tupleid, &update_ctid))
1918 TupleTableSlot *epqslot;
1920 epqslot = EvalPlanQual(estate,
1921 resultRelInfo->ri_RangeTableIndex,
1924 if (!TupIsNull(epqslot))
1926 *tupleid = update_ctid;
1927 slot = ExecFilterJunk(estate->es_junkFilter, epqslot);
1928 tuple = ExecMaterializeSlot(slot);
1932 /* tuple already deleted; nothing to do */
1936 elog(ERROR, "unrecognized heap_update status: %u", result);
1941 (estate->es_processed)++;
1944 * Note: instead of having to update the old index tuples associated with
1945 * the heap tuple, all we do is form and insert new index tuples. This is
1946 * because UPDATEs are actually DELETEs and INSERTs, and index tuple
1947 * deletion is done later by VACUUM (see notes in ExecDelete). All we do
1948 * here is insert new index tuples. -cim 9/27/89
1952 * insert index entries for tuple
1954 * Note: heap_update returns the tid (location) of the new tuple in the
1957 * If it's a HOT update, we mustn't insert new index entries.
1959 if (resultRelInfo->ri_NumIndices > 0 && !HeapTupleIsHeapOnly(tuple))
1960 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1962 /* AFTER ROW UPDATE Triggers */
1963 ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
1965 /* Process RETURNING if present */
1966 if (resultRelInfo->ri_projectReturning)
1967 ExecProcessReturning(resultRelInfo->ri_projectReturning,
1968 slot, planSlot, dest);
1972 * ExecRelCheck --- check that tuple meets constraints for result relation
1975 ExecRelCheck(ResultRelInfo *resultRelInfo,
1976 TupleTableSlot *slot, EState *estate)
1978 Relation rel = resultRelInfo->ri_RelationDesc;
1979 int ncheck = rel->rd_att->constr->num_check;
1980 ConstrCheck *check = rel->rd_att->constr->check;
1981 ExprContext *econtext;
1982 MemoryContext oldContext;
1987 * If first time through for this result relation, build expression
1988 * nodetrees for rel's constraint expressions. Keep them in the per-query
1989 * memory context so they'll survive throughout the query.
1991 if (resultRelInfo->ri_ConstraintExprs == NULL)
1993 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1994 resultRelInfo->ri_ConstraintExprs =
1995 (List **) palloc(ncheck * sizeof(List *));
1996 for (i = 0; i < ncheck; i++)
1998 /* ExecQual wants implicit-AND form */
1999 qual = make_ands_implicit(stringToNode(check[i].ccbin));
2000 resultRelInfo->ri_ConstraintExprs[i] = (List *)
2001 ExecPrepareExpr((Expr *) qual, estate);
2003 MemoryContextSwitchTo(oldContext);
2007 * We will use the EState's per-tuple context for evaluating constraint
2008 * expressions (creating it if it's not already there).
2010 econtext = GetPerTupleExprContext(estate);
2012 /* Arrange for econtext's scan tuple to be the tuple under test */
2013 econtext->ecxt_scantuple = slot;
2015 /* And evaluate the constraints */
2016 for (i = 0; i < ncheck; i++)
2018 qual = resultRelInfo->ri_ConstraintExprs[i];
2021 * NOTE: SQL92 specifies that a NULL result from a constraint
2022 * expression is not to be treated as a failure. Therefore, tell
2023 * ExecQual to return TRUE for NULL.
2025 if (!ExecQual(qual, econtext, true))
2026 return check[i].ccname;
2029 /* NULL result means no error */
2034 ExecConstraints(ResultRelInfo *resultRelInfo,
2035 TupleTableSlot *slot, EState *estate)
2037 Relation rel = resultRelInfo->ri_RelationDesc;
2038 TupleConstr *constr = rel->rd_att->constr;
2042 if (constr->has_not_null)
2044 int natts = rel->rd_att->natts;
2047 for (attrChk = 1; attrChk <= natts; attrChk++)
2049 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
2050 slot_attisnull(slot, attrChk))
2052 (errcode(ERRCODE_NOT_NULL_VIOLATION),
2053 errmsg("null value in column \"%s\" violates not-null constraint",
2054 NameStr(rel->rd_att->attrs[attrChk - 1]->attname))));
2058 if (constr->num_check > 0)
2062 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
2064 (errcode(ERRCODE_CHECK_VIOLATION),
2065 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
2066 RelationGetRelationName(rel), failed)));
2071 * ExecProcessReturning --- evaluate a RETURNING list and send to dest
2073 * projectReturning: RETURNING projection info for current result rel
2074 * tupleSlot: slot holding tuple actually inserted/updated/deleted
2075 * planSlot: slot holding tuple returned by top plan node
2076 * dest: where to send the output
2079 ExecProcessReturning(ProjectionInfo *projectReturning,
2080 TupleTableSlot *tupleSlot,
2081 TupleTableSlot *planSlot,
2084 ExprContext *econtext = projectReturning->pi_exprContext;
2085 TupleTableSlot *retSlot;
2088 * Reset per-tuple memory context to free any expression evaluation
2089 * storage allocated in the previous cycle.
2091 ResetExprContext(econtext);
2093 /* Make tuple and any needed join variables available to ExecProject */
2094 econtext->ecxt_scantuple = tupleSlot;
2095 econtext->ecxt_outertuple = planSlot;
2097 /* Compute the RETURNING expressions */
2098 retSlot = ExecProject(projectReturning, NULL);
2101 (*dest->receiveSlot) (retSlot, dest);
2103 ExecClearTuple(retSlot);
2107 * Check a modified tuple to see if we want to process its updated version
2108 * under READ COMMITTED rules.
2110 * See backend/executor/README for some info about how this works.
2112 * estate - executor state data
2113 * rti - rangetable index of table containing tuple
2114 * *tid - t_ctid from the outdated tuple (ie, next updated version)
2115 * priorXmax - t_xmax from the outdated tuple
2117 * *tid is also an output parameter: it's modified to hold the TID of the
2118 * latest version of the tuple (note this may be changed even on failure)
2120 * Returns a slot containing the new candidate update/delete tuple, or
2121 * NULL if we determine we shouldn't process the row.
2124 EvalPlanQual(EState *estate, Index rti,
2125 ItemPointer tid, TransactionId priorXmax)
2130 HeapTupleData tuple;
2131 HeapTuple copyTuple = NULL;
2132 SnapshotData SnapshotDirty;
2138 * find relation containing target tuple
2140 if (estate->es_result_relation_info != NULL &&
2141 estate->es_result_relation_info->ri_RangeTableIndex == rti)
2142 relation = estate->es_result_relation_info->ri_RelationDesc;
2148 foreach(l, estate->es_rowMarks)
2150 if (((ExecRowMark *) lfirst(l))->rti == rti)
2152 relation = ((ExecRowMark *) lfirst(l))->relation;
2156 if (relation == NULL)
2157 elog(ERROR, "could not find RowMark for RT index %u", rti);
2163 * Loop here to deal with updated or busy tuples
2165 InitDirtySnapshot(SnapshotDirty);
2166 tuple.t_self = *tid;
2171 if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
2174 * If xmin isn't what we're expecting, the slot must have been
2175 * recycled and reused for an unrelated tuple. This implies that
2176 * the latest version of the row was deleted, so we need do
2177 * nothing. (Should be safe to examine xmin without getting
2178 * buffer's content lock, since xmin never changes in an existing
2181 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2184 ReleaseBuffer(buffer);
2188 /* otherwise xmin should not be dirty... */
2189 if (TransactionIdIsValid(SnapshotDirty.xmin))
2190 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
2193 * If tuple is being updated by other transaction then we have to
2194 * wait for its commit/abort.
2196 if (TransactionIdIsValid(SnapshotDirty.xmax))
2198 ReleaseBuffer(buffer);
2199 XactLockTableWait(SnapshotDirty.xmax);
2200 continue; /* loop back to repeat heap_fetch */
2204 * If tuple was inserted by our own transaction, we have to check
2205 * cmin against es_output_cid: cmin >= current CID means our
2206 * command cannot see the tuple, so we should ignore it. Without
2207 * this we are open to the "Halloween problem" of indefinitely
2208 * re-updating the same tuple. (We need not check cmax because
2209 * HeapTupleSatisfiesDirty will consider a tuple deleted by our
2210 * transaction dead, regardless of cmax.) We just checked that
2211 * priorXmax == xmin, so we can test that variable instead of
2212 * doing HeapTupleHeaderGetXmin again.
2214 if (TransactionIdIsCurrentTransactionId(priorXmax) &&
2215 HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
2217 ReleaseBuffer(buffer);
2222 * We got tuple - now copy it for use by recheck query.
2224 copyTuple = heap_copytuple(&tuple);
2225 ReleaseBuffer(buffer);
2230 * If the referenced slot was actually empty, the latest version of
2231 * the row must have been deleted, so we need do nothing.
2233 if (tuple.t_data == NULL)
2235 ReleaseBuffer(buffer);
2240 * As above, if xmin isn't what we're expecting, do nothing.
2242 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2245 ReleaseBuffer(buffer);
2250 * If we get here, the tuple was found but failed SnapshotDirty.
2251 * Assuming the xmin is either a committed xact or our own xact (as it
2252 * certainly should be if we're trying to modify the tuple), this must
2253 * mean that the row was updated or deleted by either a committed xact
2254 * or our own xact. If it was deleted, we can ignore it; if it was
2255 * updated then chain up to the next version and repeat the whole
2258 * As above, it should be safe to examine xmax and t_ctid without the
2259 * buffer content lock, because they can't be changing.
2261 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
2263 /* deleted, so forget about it */
2264 ReleaseBuffer(buffer);
2268 /* updated, so look at the updated row */
2269 tuple.t_self = tuple.t_data->t_ctid;
2270 /* updated row should have xmin matching this xmax */
2271 priorXmax = HeapTupleHeaderGetXmax(tuple.t_data);
2272 ReleaseBuffer(buffer);
2273 /* loop back to fetch next in chain */
2277 * For UPDATE/DELETE we have to return tid of actual row we're executing
2280 *tid = tuple.t_self;
2283 * Need to run a recheck subquery. Find or create a PQ stack entry.
2285 epq = estate->es_evalPlanQual;
2288 if (epq != NULL && epq->rti == 0)
2290 /* Top PQ stack entry is idle, so re-use it */
2291 Assert(!(estate->es_useEvalPlan) && epq->next == NULL);
2297 * If this is request for another RTE - Ra, - then we have to check wasn't
2298 * PlanQual requested for Ra already and if so then Ra' row was updated
2299 * again and we have to re-start old execution for Ra and forget all what
2300 * we done after Ra was suspended. Cool? -:))
2302 if (epq != NULL && epq->rti != rti &&
2303 epq->estate->es_evTuple[rti - 1] != NULL)
2307 evalPlanQual *oldepq;
2309 /* stop execution */
2310 EvalPlanQualStop(epq);
2311 /* pop previous PlanQual from the stack */
2313 Assert(oldepq && oldepq->rti != 0);
2314 /* push current PQ to freePQ stack */
2317 estate->es_evalPlanQual = epq;
2318 } while (epq->rti != rti);
2322 * If we are requested for another RTE then we have to suspend execution
2323 * of current PlanQual and start execution for new one.
2325 if (epq == NULL || epq->rti != rti)
2327 /* try to reuse plan used previously */
2328 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
2330 if (newepq == NULL) /* first call or freePQ stack is empty */
2332 newepq = (evalPlanQual *) palloc0(sizeof(evalPlanQual));
2333 newepq->free = NULL;
2334 newepq->estate = NULL;
2335 newepq->planstate = NULL;
2339 /* recycle previously used PlanQual */
2340 Assert(newepq->estate == NULL);
2343 /* push current PQ to the stack */
2346 estate->es_evalPlanQual = epq;
2351 Assert(epq->rti == rti);
2354 * Ok - we're requested for the same RTE. Unfortunately we still have to
2355 * end and restart execution of the plan, because ExecReScan wouldn't
2356 * ensure that upper plan nodes would reset themselves. We could make
2357 * that work if insertion of the target tuple were integrated with the
2358 * Param mechanism somehow, so that the upper plan nodes know that their
2359 * children's outputs have changed.
2361 * Note that the stack of free evalPlanQual nodes is quite useless at the
2362 * moment, since it only saves us from pallocing/releasing the
2363 * evalPlanQual nodes themselves. But it will be useful once we implement
2364 * ReScan instead of end/restart for re-using PlanQual nodes.
2368 /* stop execution */
2369 EvalPlanQualStop(epq);
2373 * Initialize new recheck query.
2375 * Note: if we were re-using PlanQual plans via ExecReScan, we'd need to
2376 * instead copy down changeable state from the top plan (including
2377 * es_result_relation_info, es_junkFilter) and reset locally changeable
2378 * state in the epq (including es_param_exec_vals, es_evTupleNull).
2380 EvalPlanQualStart(epq, estate, epq->next);
2383 * free old RTE' tuple, if any, and store target tuple where relation's
2384 * scan node will see it
2386 epqstate = epq->estate;
2387 if (epqstate->es_evTuple[rti - 1] != NULL)
2388 heap_freetuple(epqstate->es_evTuple[rti - 1]);
2389 epqstate->es_evTuple[rti - 1] = copyTuple;
2391 return EvalPlanQualNext(estate);
2394 static TupleTableSlot *
2395 EvalPlanQualNext(EState *estate)
2397 evalPlanQual *epq = estate->es_evalPlanQual;
2398 MemoryContext oldcontext;
2399 TupleTableSlot *slot;
2401 Assert(epq->rti != 0);
2404 oldcontext = MemoryContextSwitchTo(epq->estate->es_query_cxt);
2405 slot = ExecProcNode(epq->planstate);
2406 MemoryContextSwitchTo(oldcontext);
2409 * No more tuples for this PQ. Continue previous one.
2411 if (TupIsNull(slot))
2413 evalPlanQual *oldepq;
2415 /* stop execution */
2416 EvalPlanQualStop(epq);
2417 /* pop old PQ from the stack */
2421 /* this is the first (oldest) PQ - mark as free */
2423 estate->es_useEvalPlan = false;
2424 /* and continue Query execution */
2427 Assert(oldepq->rti != 0);
2428 /* push current PQ to freePQ stack */
2431 estate->es_evalPlanQual = epq;
2439 EndEvalPlanQual(EState *estate)
2441 evalPlanQual *epq = estate->es_evalPlanQual;
2443 if (epq->rti == 0) /* plans already shutdowned */
2445 Assert(epq->next == NULL);
2451 evalPlanQual *oldepq;
2453 /* stop execution */
2454 EvalPlanQualStop(epq);
2455 /* pop old PQ from the stack */
2459 /* this is the first (oldest) PQ - mark as free */
2461 estate->es_useEvalPlan = false;
2464 Assert(oldepq->rti != 0);
2465 /* push current PQ to freePQ stack */
2468 estate->es_evalPlanQual = epq;
2473 * Start execution of one level of PlanQual.
2475 * This is a cut-down version of ExecutorStart(): we copy some state from
2476 * the top-level estate rather than initializing it fresh.
2479 EvalPlanQualStart(evalPlanQual *epq, EState *estate, evalPlanQual *priorepq)
2483 MemoryContext oldcontext;
2486 rtsize = list_length(estate->es_range_table);
2488 epq->estate = epqstate = CreateExecutorState();
2490 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2493 * The epqstates share the top query's copy of unchanging state such as
2494 * the snapshot, rangetable, result-rel info, and external Param info.
2495 * They need their own copies of local state, including a tuple table,
2496 * es_param_exec_vals, etc.
2498 epqstate->es_direction = ForwardScanDirection;
2499 epqstate->es_snapshot = estate->es_snapshot;
2500 epqstate->es_crosscheck_snapshot = estate->es_crosscheck_snapshot;
2501 epqstate->es_range_table = estate->es_range_table;
2502 epqstate->es_output_cid = estate->es_output_cid;
2503 epqstate->es_result_relations = estate->es_result_relations;
2504 epqstate->es_num_result_relations = estate->es_num_result_relations;
2505 epqstate->es_result_relation_info = estate->es_result_relation_info;
2506 epqstate->es_junkFilter = estate->es_junkFilter;
2507 /* es_trig_target_relations must NOT be copied */
2508 epqstate->es_param_list_info = estate->es_param_list_info;
2509 if (estate->es_plannedstmt->nParamExec > 0)
2510 epqstate->es_param_exec_vals = (ParamExecData *)
2511 palloc0(estate->es_plannedstmt->nParamExec * sizeof(ParamExecData));
2512 epqstate->es_rowMarks = estate->es_rowMarks;
2513 epqstate->es_instrument = estate->es_instrument;
2514 epqstate->es_select_into = estate->es_select_into;
2515 epqstate->es_into_oids = estate->es_into_oids;
2516 epqstate->es_plannedstmt = estate->es_plannedstmt;
2519 * Each epqstate must have its own es_evTupleNull state, but all the stack
2520 * entries share es_evTuple state. This allows sub-rechecks to inherit
2521 * the value being examined by an outer recheck.
2523 epqstate->es_evTupleNull = (bool *) palloc0(rtsize * sizeof(bool));
2524 if (priorepq == NULL)
2525 /* first PQ stack entry */
2526 epqstate->es_evTuple = (HeapTuple *)
2527 palloc0(rtsize * sizeof(HeapTuple));
2529 /* later stack entries share the same storage */
2530 epqstate->es_evTuple = priorepq->estate->es_evTuple;
2533 * Create sub-tuple-table; we needn't redo the CountSlots work though.
2535 epqstate->es_tupleTable =
2536 ExecCreateTupleTable(estate->es_tupleTable->size);
2539 * Initialize private state information for each SubPlan. We must do this
2540 * before running ExecInitNode on the main query tree, since
2541 * ExecInitSubPlan expects to be able to find these entries.
2543 Assert(epqstate->es_subplanstates == NIL);
2544 foreach(l, estate->es_plannedstmt->subplans)
2546 Plan *subplan = (Plan *) lfirst(l);
2547 PlanState *subplanstate;
2549 subplanstate = ExecInitNode(subplan, epqstate, 0);
2551 epqstate->es_subplanstates = lappend(epqstate->es_subplanstates,
2556 * Initialize the private state information for all the nodes in the query
2557 * tree. This opens files, allocates storage and leaves us ready to start
2558 * processing tuples.
2560 epq->planstate = ExecInitNode(estate->es_plannedstmt->planTree, epqstate, 0);
2562 MemoryContextSwitchTo(oldcontext);
2566 * End execution of one level of PlanQual.
2568 * This is a cut-down version of ExecutorEnd(); basically we want to do most
2569 * of the normal cleanup, but *not* close result relations (which we are
2570 * just sharing from the outer query). We do, however, have to close any
2571 * trigger target relations that got opened, since those are not shared.
2574 EvalPlanQualStop(evalPlanQual *epq)
2576 EState *epqstate = epq->estate;
2577 MemoryContext oldcontext;
2580 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2582 ExecEndNode(epq->planstate);
2584 foreach(l, epqstate->es_subplanstates)
2586 PlanState *subplanstate = (PlanState *) lfirst(l);
2588 ExecEndNode(subplanstate);
2591 ExecDropTupleTable(epqstate->es_tupleTable, true);
2592 epqstate->es_tupleTable = NULL;
2594 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
2596 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
2597 epqstate->es_evTuple[epq->rti - 1] = NULL;
2600 foreach(l, epqstate->es_trig_target_relations)
2602 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
2604 /* Close indices and then the relation itself */
2605 ExecCloseIndices(resultRelInfo);
2606 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
2609 MemoryContextSwitchTo(oldcontext);
2611 FreeExecutorState(epqstate);
2614 epq->planstate = NULL;
2618 * ExecGetActivePlanTree --- get the active PlanState tree from a QueryDesc
2620 * Ordinarily this is just the one mentioned in the QueryDesc, but if we
2621 * are looking at a row returned by the EvalPlanQual machinery, we need
2622 * to look at the subsidiary state instead.
2625 ExecGetActivePlanTree(QueryDesc *queryDesc)
2627 EState *estate = queryDesc->estate;
2629 if (estate && estate->es_useEvalPlan && estate->es_evalPlanQual != NULL)
2630 return estate->es_evalPlanQual->planstate;
2632 return queryDesc->planstate;
2637 * Support for SELECT INTO (a/k/a CREATE TABLE AS)
2639 * We implement SELECT INTO by diverting SELECT's normal output with
2640 * a specialized DestReceiver type.
2645 DestReceiver pub; /* publicly-known function pointers */
2646 EState *estate; /* EState we are working with */
2647 Relation rel; /* Relation to write to */
2648 bool use_wal; /* do we need to WAL-log our writes? */
2652 * OpenIntoRel --- actually create the SELECT INTO target relation
2654 * This also replaces QueryDesc->dest with the special DestReceiver for
2655 * SELECT INTO. We assume that the correct result tuple type has already
2656 * been placed in queryDesc->tupDesc.
2659 OpenIntoRel(QueryDesc *queryDesc)
2661 IntoClause *into = queryDesc->plannedstmt->intoClause;
2662 EState *estate = queryDesc->estate;
2663 Relation intoRelationDesc;
2668 AclResult aclresult;
2671 DR_intorel *myState;
2676 * Check consistency of arguments
2678 if (into->onCommit != ONCOMMIT_NOOP && !into->rel->istemp)
2680 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2681 errmsg("ON COMMIT can only be used on temporary tables")));
2684 * Find namespace to create in, check its permissions
2686 intoName = into->rel->relname;
2687 namespaceId = RangeVarGetCreationNamespace(into->rel);
2689 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
2691 if (aclresult != ACLCHECK_OK)
2692 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2693 get_namespace_name(namespaceId));
2696 * Select tablespace to use. If not specified, use default tablespace
2697 * (which may in turn default to database's default).
2699 if (into->tableSpaceName)
2701 tablespaceId = get_tablespace_oid(into->tableSpaceName);
2702 if (!OidIsValid(tablespaceId))
2704 (errcode(ERRCODE_UNDEFINED_OBJECT),
2705 errmsg("tablespace \"%s\" does not exist",
2706 into->tableSpaceName)));
2710 tablespaceId = GetDefaultTablespace(into->rel->istemp);
2711 /* note InvalidOid is OK in this case */
2714 /* Check permissions except when using the database's default space */
2715 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
2717 AclResult aclresult;
2719 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
2722 if (aclresult != ACLCHECK_OK)
2723 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
2724 get_tablespace_name(tablespaceId));
2727 /* Parse and validate any reloptions */
2728 reloptions = transformRelOptions((Datum) 0,
2732 (void) heap_reloptions(RELKIND_RELATION, reloptions, true);
2734 /* Copy the tupdesc because heap_create_with_catalog modifies it */
2735 tupdesc = CreateTupleDescCopy(queryDesc->tupDesc);
2737 /* Now we can actually create the new relation */
2738 intoRelationId = heap_create_with_catalog(intoName,
2751 allowSystemTableMods);
2753 FreeTupleDesc(tupdesc);
2756 * Advance command counter so that the newly-created relation's catalog
2757 * tuples will be visible to heap_open.
2759 CommandCounterIncrement();
2762 * If necessary, create a TOAST table for the INTO relation. Note that
2763 * AlterTableCreateToastTable ends with CommandCounterIncrement(), so that
2764 * the TOAST table will be visible for insertion.
2766 AlterTableCreateToastTable(intoRelationId);
2769 * And open the constructed table for writing.
2771 intoRelationDesc = heap_open(intoRelationId, AccessExclusiveLock);
2774 * Now replace the query's DestReceiver with one for SELECT INTO
2776 queryDesc->dest = CreateDestReceiver(DestIntoRel, NULL);
2777 myState = (DR_intorel *) queryDesc->dest;
2778 Assert(myState->pub.mydest == DestIntoRel);
2779 myState->estate = estate;
2782 * We can skip WAL-logging the insertions, unless PITR is in use.
2784 myState->use_wal = XLogArchivingActive();
2785 myState->rel = intoRelationDesc;
2787 /* use_wal off requires rd_targblock be initially invalid */
2788 Assert(intoRelationDesc->rd_targblock == InvalidBlockNumber);
2792 * CloseIntoRel --- clean up SELECT INTO at ExecutorEnd time
2795 CloseIntoRel(QueryDesc *queryDesc)
2797 DR_intorel *myState = (DR_intorel *) queryDesc->dest;
2799 /* OpenIntoRel might never have gotten called */
2800 if (myState && myState->pub.mydest == DestIntoRel && myState->rel)
2802 /* If we skipped using WAL, must heap_sync before commit */
2803 if (!myState->use_wal)
2804 heap_sync(myState->rel);
2806 /* close rel, but keep lock until commit */
2807 heap_close(myState->rel, NoLock);
2809 myState->rel = NULL;
2814 * CreateIntoRelDestReceiver -- create a suitable DestReceiver object
2816 * Since CreateDestReceiver doesn't accept the parameters we'd need,
2817 * we just leave the private fields zeroed here. OpenIntoRel will
2821 CreateIntoRelDestReceiver(void)
2823 DR_intorel *self = (DR_intorel *) palloc0(sizeof(DR_intorel));
2825 self->pub.receiveSlot = intorel_receive;
2826 self->pub.rStartup = intorel_startup;
2827 self->pub.rShutdown = intorel_shutdown;
2828 self->pub.rDestroy = intorel_destroy;
2829 self->pub.mydest = DestIntoRel;
2831 return (DestReceiver *) self;
2835 * intorel_startup --- executor startup
2838 intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
2844 * intorel_receive --- receive one tuple
2847 intorel_receive(TupleTableSlot *slot, DestReceiver *self)
2849 DR_intorel *myState = (DR_intorel *) self;
2853 * get the heap tuple out of the tuple table slot, making sure we have a
2856 tuple = ExecMaterializeSlot(slot);
2858 heap_insert(myState->rel,
2860 myState->estate->es_output_cid,
2862 false); /* never any point in using FSM */
2864 /* We know this is a newly created relation, so there are no indexes */
2870 * intorel_shutdown --- executor end
2873 intorel_shutdown(DestReceiver *self)
2879 * intorel_destroy --- release DestReceiver object
2882 intorel_destroy(DestReceiver *self)