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-2009, 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.331 2009/10/08 22:34:57 tgl Exp $
31 *-------------------------------------------------------------------------
35 #include "access/heapam.h"
36 #include "access/reloptions.h"
37 #include "access/sysattr.h"
38 #include "access/transam.h"
39 #include "access/xact.h"
40 #include "catalog/heap.h"
41 #include "catalog/namespace.h"
42 #include "catalog/toasting.h"
43 #include "commands/tablespace.h"
44 #include "commands/trigger.h"
45 #include "executor/execdebug.h"
46 #include "executor/instrument.h"
47 #include "executor/nodeSubplan.h"
48 #include "miscadmin.h"
49 #include "nodes/nodeFuncs.h"
50 #include "optimizer/clauses.h"
51 #include "parser/parse_clause.h"
52 #include "parser/parsetree.h"
53 #include "storage/bufmgr.h"
54 #include "storage/lmgr.h"
55 #include "storage/smgr.h"
56 #include "utils/acl.h"
57 #include "utils/builtins.h"
58 #include "utils/lsyscache.h"
59 #include "utils/memutils.h"
60 #include "utils/snapmgr.h"
61 #include "utils/tqual.h"
64 /* Hooks for plugins to get control in ExecutorStart/Run/End() */
65 ExecutorStart_hook_type ExecutorStart_hook = NULL;
66 ExecutorRun_hook_type ExecutorRun_hook = NULL;
67 ExecutorEnd_hook_type ExecutorEnd_hook = NULL;
69 typedef struct evalPlanQual
74 struct evalPlanQual *next; /* stack of active PlanQual plans */
75 struct evalPlanQual *free; /* list of free PlanQual plans */
78 /* decls for local routines only used within this module */
79 static void InitPlan(QueryDesc *queryDesc, int eflags);
80 static void ExecCheckPlanOutput(Relation resultRel, List *targetList);
81 static void ExecEndPlan(PlanState *planstate, EState *estate);
82 static void ExecutePlan(EState *estate, PlanState *planstate,
85 ScanDirection direction,
87 static void ExecSelect(TupleTableSlot *slot,
88 DestReceiver *dest, EState *estate);
89 static void ExecInsert(TupleTableSlot *slot, ItemPointer tupleid,
90 TupleTableSlot *planSlot,
91 DestReceiver *dest, EState *estate);
92 static void ExecDelete(ItemPointer tupleid,
93 TupleTableSlot *planSlot,
94 DestReceiver *dest, EState *estate);
95 static void ExecUpdate(TupleTableSlot *slot, ItemPointer tupleid,
96 TupleTableSlot *planSlot,
97 DestReceiver *dest, EState *estate);
98 static void ExecProcessReturning(ProjectionInfo *projectReturning,
99 TupleTableSlot *tupleSlot,
100 TupleTableSlot *planSlot,
102 static TupleTableSlot *EvalPlanQualNext(EState *estate);
103 static void EndEvalPlanQual(EState *estate);
104 static void ExecCheckRTPerms(List *rangeTable);
105 static void ExecCheckRTEPerms(RangeTblEntry *rte);
106 static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
107 static void EvalPlanQualStart(evalPlanQual *epq, EState *estate,
108 evalPlanQual *priorepq);
109 static void EvalPlanQualStop(evalPlanQual *epq);
110 static void OpenIntoRel(QueryDesc *queryDesc);
111 static void CloseIntoRel(QueryDesc *queryDesc);
112 static void intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
113 static void intorel_receive(TupleTableSlot *slot, DestReceiver *self);
114 static void intorel_shutdown(DestReceiver *self);
115 static void intorel_destroy(DestReceiver *self);
117 /* end of local decls */
120 /* ----------------------------------------------------------------
123 * This routine must be called at the beginning of any execution of any
126 * Takes a QueryDesc previously created by CreateQueryDesc (it's not real
127 * clear why we bother to separate the two functions, but...). The tupDesc
128 * field of the QueryDesc is filled in to describe the tuples that will be
129 * returned, and the internal fields (estate and planstate) are set up.
131 * eflags contains flag bits as described in executor.h.
133 * NB: the CurrentMemoryContext when this is called will become the parent
134 * of the per-query context used for this Executor invocation.
136 * We provide a function hook variable that lets loadable plugins
137 * get control when ExecutorStart is called. Such a plugin would
138 * normally call standard_ExecutorStart().
140 * ----------------------------------------------------------------
143 ExecutorStart(QueryDesc *queryDesc, int eflags)
145 if (ExecutorStart_hook)
146 (*ExecutorStart_hook) (queryDesc, eflags);
148 standard_ExecutorStart(queryDesc, eflags);
152 standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
155 MemoryContext oldcontext;
157 /* sanity checks: queryDesc must not be started already */
158 Assert(queryDesc != NULL);
159 Assert(queryDesc->estate == NULL);
162 * If the transaction is read-only, we need to check if any writes are
163 * planned to non-temporary tables. EXPLAIN is considered read-only.
165 if (XactReadOnly && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
166 ExecCheckXactReadOnly(queryDesc->plannedstmt);
169 * Build EState, switch into per-query memory context for startup.
171 estate = CreateExecutorState();
172 queryDesc->estate = estate;
174 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
177 * Fill in parameters, if any, from queryDesc
179 estate->es_param_list_info = queryDesc->params;
181 if (queryDesc->plannedstmt->nParamExec > 0)
182 estate->es_param_exec_vals = (ParamExecData *)
183 palloc0(queryDesc->plannedstmt->nParamExec * sizeof(ParamExecData));
186 * If non-read-only query, set the command ID to mark output tuples with
188 switch (queryDesc->operation)
191 /* SELECT INTO and SELECT FOR UPDATE/SHARE need to mark tuples */
192 if (queryDesc->plannedstmt->intoClause != NULL ||
193 queryDesc->plannedstmt->rowMarks != NIL)
194 estate->es_output_cid = GetCurrentCommandId(true);
200 estate->es_output_cid = GetCurrentCommandId(true);
204 elog(ERROR, "unrecognized operation code: %d",
205 (int) queryDesc->operation);
210 * Copy other important information into the EState
212 estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
213 estate->es_crosscheck_snapshot = RegisterSnapshot(queryDesc->crosscheck_snapshot);
214 estate->es_instrument = queryDesc->doInstrument;
217 * Initialize the plan state tree
219 InitPlan(queryDesc, eflags);
221 MemoryContextSwitchTo(oldcontext);
224 /* ----------------------------------------------------------------
227 * This is the main routine of the executor module. It accepts
228 * the query descriptor from the traffic cop and executes the
231 * ExecutorStart must have been called already.
233 * If direction is NoMovementScanDirection then nothing is done
234 * except to start up/shut down the destination. Otherwise,
235 * we retrieve up to 'count' tuples in the specified direction.
237 * Note: count = 0 is interpreted as no portal limit, i.e., run to
240 * There is no return value, but output tuples (if any) are sent to
241 * the destination receiver specified in the QueryDesc; and the number
242 * of tuples processed at the top level can be found in
243 * estate->es_processed.
245 * We provide a function hook variable that lets loadable plugins
246 * get control when ExecutorRun is called. Such a plugin would
247 * normally call standard_ExecutorRun().
249 * ----------------------------------------------------------------
252 ExecutorRun(QueryDesc *queryDesc,
253 ScanDirection direction, long count)
255 if (ExecutorRun_hook)
256 (*ExecutorRun_hook) (queryDesc, direction, count);
258 standard_ExecutorRun(queryDesc, direction, count);
262 standard_ExecutorRun(QueryDesc *queryDesc,
263 ScanDirection direction, long count)
269 MemoryContext oldcontext;
272 Assert(queryDesc != NULL);
274 estate = queryDesc->estate;
276 Assert(estate != NULL);
279 * Switch into per-query memory context
281 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
283 /* Allow instrumentation of ExecutorRun overall runtime */
284 if (queryDesc->totaltime)
285 InstrStartNode(queryDesc->totaltime);
288 * extract information from the query descriptor and the query feature.
290 operation = queryDesc->operation;
291 dest = queryDesc->dest;
294 * startup tuple receiver, if we will be emitting tuples
296 estate->es_processed = 0;
297 estate->es_lastoid = InvalidOid;
299 sendTuples = (operation == CMD_SELECT ||
300 queryDesc->plannedstmt->returningLists);
303 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
308 if (!ScanDirectionIsNoMovement(direction))
310 queryDesc->planstate,
317 * shutdown tuple receiver, if we started it
320 (*dest->rShutdown) (dest);
322 if (queryDesc->totaltime)
323 InstrStopNode(queryDesc->totaltime, estate->es_processed);
325 MemoryContextSwitchTo(oldcontext);
328 /* ----------------------------------------------------------------
331 * This routine must be called at the end of execution of any
334 * We provide a function hook variable that lets loadable plugins
335 * get control when ExecutorEnd is called. Such a plugin would
336 * normally call standard_ExecutorEnd().
338 * ----------------------------------------------------------------
341 ExecutorEnd(QueryDesc *queryDesc)
343 if (ExecutorEnd_hook)
344 (*ExecutorEnd_hook) (queryDesc);
346 standard_ExecutorEnd(queryDesc);
350 standard_ExecutorEnd(QueryDesc *queryDesc)
353 MemoryContext oldcontext;
356 Assert(queryDesc != NULL);
358 estate = queryDesc->estate;
360 Assert(estate != NULL);
363 * Switch into per-query memory context to run ExecEndPlan
365 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
367 ExecEndPlan(queryDesc->planstate, estate);
370 * Close the SELECT INTO relation if any
372 if (estate->es_select_into)
373 CloseIntoRel(queryDesc);
375 /* do away with our snapshots */
376 UnregisterSnapshot(estate->es_snapshot);
377 UnregisterSnapshot(estate->es_crosscheck_snapshot);
380 * Must switch out of context before destroying it
382 MemoryContextSwitchTo(oldcontext);
385 * Release EState and per-query memory context. This should release
386 * everything the executor has allocated.
388 FreeExecutorState(estate);
390 /* Reset queryDesc fields that no longer point to anything */
391 queryDesc->tupDesc = NULL;
392 queryDesc->estate = NULL;
393 queryDesc->planstate = NULL;
394 queryDesc->totaltime = NULL;
397 /* ----------------------------------------------------------------
400 * This routine may be called on an open queryDesc to rewind it
402 * ----------------------------------------------------------------
405 ExecutorRewind(QueryDesc *queryDesc)
408 MemoryContext oldcontext;
411 Assert(queryDesc != NULL);
413 estate = queryDesc->estate;
415 Assert(estate != NULL);
417 /* It's probably not sensible to rescan updating queries */
418 Assert(queryDesc->operation == CMD_SELECT);
421 * Switch into per-query memory context
423 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
428 ExecReScan(queryDesc->planstate, NULL);
430 MemoryContextSwitchTo(oldcontext);
436 * Check access permissions for all relations listed in a range table.
439 ExecCheckRTPerms(List *rangeTable)
443 foreach(l, rangeTable)
445 ExecCheckRTEPerms((RangeTblEntry *) lfirst(l));
451 * Check access permissions for a single RTE.
454 ExecCheckRTEPerms(RangeTblEntry *rte)
456 AclMode requiredPerms;
458 AclMode remainingPerms;
465 * Only plain-relation RTEs need to be checked here. Function RTEs are
466 * checked by init_fcache when the function is prepared for execution.
467 * Join, subquery, and special RTEs need no checks.
469 if (rte->rtekind != RTE_RELATION)
473 * No work if requiredPerms is empty.
475 requiredPerms = rte->requiredPerms;
476 if (requiredPerms == 0)
482 * userid to check as: current user unless we have a setuid indication.
484 * Note: GetUserId() is presently fast enough that there's no harm in
485 * calling it separately for each RTE. If that stops being true, we could
486 * call it once in ExecCheckRTPerms and pass the userid down from there.
487 * But for now, no need for the extra clutter.
489 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
492 * We must have *all* the requiredPerms bits, but some of the bits can be
493 * satisfied from column-level rather than relation-level permissions.
494 * First, remove any bits that are satisfied by relation permissions.
496 relPerms = pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL);
497 remainingPerms = requiredPerms & ~relPerms;
498 if (remainingPerms != 0)
501 * If we lack any permissions that exist only as relation permissions,
502 * we can fail straight away.
504 if (remainingPerms & ~(ACL_SELECT | ACL_INSERT | ACL_UPDATE))
505 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
506 get_rel_name(relOid));
509 * Check to see if we have the needed privileges at column level.
511 * Note: failures just report a table-level error; it would be nicer
512 * to report a column-level error if we have some but not all of the
515 if (remainingPerms & ACL_SELECT)
518 * When the query doesn't explicitly reference any columns (for
519 * example, SELECT COUNT(*) FROM table), allow the query if we
520 * have SELECT on any column of the rel, as per SQL spec.
522 if (bms_is_empty(rte->selectedCols))
524 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
525 ACLMASK_ANY) != ACLCHECK_OK)
526 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
527 get_rel_name(relOid));
530 tmpset = bms_copy(rte->selectedCols);
531 while ((col = bms_first_member(tmpset)) >= 0)
533 /* remove the column number offset */
534 col += FirstLowInvalidHeapAttributeNumber;
535 if (col == InvalidAttrNumber)
537 /* Whole-row reference, must have priv on all cols */
538 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
539 ACLMASK_ALL) != ACLCHECK_OK)
540 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
541 get_rel_name(relOid));
545 if (pg_attribute_aclcheck(relOid, col, userid, ACL_SELECT)
547 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
548 get_rel_name(relOid));
555 * Basically the same for the mod columns, with either INSERT or
556 * UPDATE privilege as specified by remainingPerms.
558 remainingPerms &= ~ACL_SELECT;
559 if (remainingPerms != 0)
562 * When the query doesn't explicitly change any columns, allow the
563 * query if we have permission on any column of the rel. This is
564 * to handle SELECT FOR UPDATE as well as possible corner cases in
567 if (bms_is_empty(rte->modifiedCols))
569 if (pg_attribute_aclcheck_all(relOid, userid, remainingPerms,
570 ACLMASK_ANY) != ACLCHECK_OK)
571 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
572 get_rel_name(relOid));
575 tmpset = bms_copy(rte->modifiedCols);
576 while ((col = bms_first_member(tmpset)) >= 0)
578 /* remove the column number offset */
579 col += FirstLowInvalidHeapAttributeNumber;
580 if (col == InvalidAttrNumber)
582 /* whole-row reference can't happen here */
583 elog(ERROR, "whole-row update is not implemented");
587 if (pg_attribute_aclcheck(relOid, col, userid, remainingPerms)
589 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
590 get_rel_name(relOid));
599 * Check that the query does not imply any writes to non-temp tables.
602 ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
607 * CREATE TABLE AS or SELECT INTO?
609 * XXX should we allow this if the destination is temp?
611 if (plannedstmt->intoClause != NULL)
614 /* Fail if write permissions are requested on any non-temp table */
615 foreach(l, plannedstmt->rtable)
617 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
619 if (rte->rtekind != RTE_RELATION)
622 if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
625 if (isTempNamespace(get_rel_namespace(rte->relid)))
635 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
636 errmsg("transaction is read-only")));
640 /* ----------------------------------------------------------------
643 * Initializes the query plan: open files, allocate storage
644 * and start up the rule manager
645 * ----------------------------------------------------------------
648 InitPlan(QueryDesc *queryDesc, int eflags)
650 CmdType operation = queryDesc->operation;
651 PlannedStmt *plannedstmt = queryDesc->plannedstmt;
652 Plan *plan = plannedstmt->planTree;
653 List *rangeTable = plannedstmt->rtable;
654 EState *estate = queryDesc->estate;
655 PlanState *planstate;
661 * Do permissions checks
663 ExecCheckRTPerms(rangeTable);
666 * initialize the node's execution state
668 estate->es_range_table = rangeTable;
671 * initialize result relation stuff
673 if (plannedstmt->resultRelations)
675 List *resultRelations = plannedstmt->resultRelations;
676 int numResultRelations = list_length(resultRelations);
677 ResultRelInfo *resultRelInfos;
678 ResultRelInfo *resultRelInfo;
680 resultRelInfos = (ResultRelInfo *)
681 palloc(numResultRelations * sizeof(ResultRelInfo));
682 resultRelInfo = resultRelInfos;
683 foreach(l, resultRelations)
685 Index resultRelationIndex = lfirst_int(l);
686 Oid resultRelationOid;
687 Relation resultRelation;
689 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
690 resultRelation = heap_open(resultRelationOid, RowExclusiveLock);
691 InitResultRelInfo(resultRelInfo,
695 estate->es_instrument);
698 estate->es_result_relations = resultRelInfos;
699 estate->es_num_result_relations = numResultRelations;
700 /* Initialize to first or only result rel */
701 estate->es_result_relation_info = resultRelInfos;
706 * if no result relation, then set state appropriately
708 estate->es_result_relations = NULL;
709 estate->es_num_result_relations = 0;
710 estate->es_result_relation_info = NULL;
714 * Detect whether we're doing SELECT INTO. If so, set the es_into_oids
715 * flag appropriately so that the plan tree will be initialized with the
716 * correct tuple descriptors. (Other SELECT INTO stuff comes later.)
718 estate->es_select_into = false;
719 if (operation == CMD_SELECT && plannedstmt->intoClause != NULL)
721 estate->es_select_into = true;
722 estate->es_into_oids = interpretOidsOption(plannedstmt->intoClause->options);
726 * Have to lock relations selected FOR UPDATE/FOR SHARE before we
727 * initialize the plan tree, else we'd be doing a lock upgrade. While we
728 * are at it, build the ExecRowMark list.
730 estate->es_rowMarks = NIL;
731 foreach(l, plannedstmt->rowMarks)
733 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
738 /* ignore "parent" rowmarks; they are irrelevant at runtime */
742 relid = getrelid(rc->rti, rangeTable);
743 relation = heap_open(relid, RowShareLock);
744 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
745 erm->relation = relation;
747 erm->prti = rc->prti;
748 erm->forUpdate = rc->forUpdate;
749 erm->noWait = rc->noWait;
750 /* We'll locate the junk attrs below */
751 erm->ctidAttNo = InvalidAttrNumber;
752 erm->toidAttNo = InvalidAttrNumber;
753 ItemPointerSetInvalid(&(erm->curCtid));
754 estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
758 * Initialize the executor's tuple table. Also, if it's not a SELECT,
759 * set up a tuple table slot for use for trigger output tuples.
761 estate->es_tupleTable = NIL;
762 if (operation != CMD_SELECT)
763 estate->es_trig_tuple_slot = ExecInitExtraTupleSlot(estate);
765 /* mark EvalPlanQual not active */
766 estate->es_plannedstmt = plannedstmt;
767 estate->es_evalPlanQual = NULL;
768 estate->es_evTupleNull = NULL;
769 estate->es_evTuple = NULL;
770 estate->es_useEvalPlan = false;
773 * Initialize private state information for each SubPlan. We must do this
774 * before running ExecInitNode on the main query tree, since
775 * ExecInitSubPlan expects to be able to find these entries.
777 Assert(estate->es_subplanstates == NIL);
778 i = 1; /* subplan indices count from 1 */
779 foreach(l, plannedstmt->subplans)
781 Plan *subplan = (Plan *) lfirst(l);
782 PlanState *subplanstate;
786 * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
787 * it is a parameterless subplan (not initplan), we suggest that it be
788 * prepared to handle REWIND efficiently; otherwise there is no need.
790 sp_eflags = eflags & EXEC_FLAG_EXPLAIN_ONLY;
791 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
792 sp_eflags |= EXEC_FLAG_REWIND;
794 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
796 estate->es_subplanstates = lappend(estate->es_subplanstates,
803 * Initialize the private state information for all the nodes in the query
804 * tree. This opens files, allocates storage and leaves us ready to start
807 planstate = ExecInitNode(plan, estate, eflags);
810 * Get the tuple descriptor describing the type of tuples to return. (this
811 * is especially important if we are creating a relation with "SELECT
814 tupType = ExecGetResultType(planstate);
817 * Initialize the junk filter if needed. SELECT and INSERT queries need a
818 * filter if there are any junk attrs in the tlist. UPDATE and DELETE
819 * always need a filter, since there's always a junk 'ctid' attribute
820 * present --- no need to look first.
822 * This section of code is also a convenient place to verify that the
823 * output of an INSERT or UPDATE matches the target table(s).
826 bool junk_filter_needed = false;
833 foreach(tlist, plan->targetlist)
835 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
839 junk_filter_needed = true;
846 junk_filter_needed = true;
852 if (junk_filter_needed)
855 * If there are multiple result relations, each one needs its own
856 * junk filter. Note this is only possible for UPDATE/DELETE, so
857 * we can't be fooled by some needing a filter and some not.
859 if (list_length(plannedstmt->resultRelations) > 1)
861 PlanState **appendplans;
863 ResultRelInfo *resultRelInfo;
865 /* Top plan had better be an Append here. */
866 Assert(IsA(plan, Append));
867 Assert(((Append *) plan)->isTarget);
868 Assert(IsA(planstate, AppendState));
869 appendplans = ((AppendState *) planstate)->appendplans;
870 as_nplans = ((AppendState *) planstate)->as_nplans;
871 Assert(as_nplans == estate->es_num_result_relations);
872 resultRelInfo = estate->es_result_relations;
873 for (i = 0; i < as_nplans; i++)
875 PlanState *subplan = appendplans[i];
878 if (operation == CMD_UPDATE)
879 ExecCheckPlanOutput(resultRelInfo->ri_RelationDesc,
880 subplan->plan->targetlist);
882 j = ExecInitJunkFilter(subplan->plan->targetlist,
883 resultRelInfo->ri_RelationDesc->rd_att->tdhasoid,
884 ExecInitExtraTupleSlot(estate));
887 * Since it must be UPDATE/DELETE, there had better be a
888 * "ctid" junk attribute in the tlist ... but ctid could
889 * be at a different resno for each result relation. We
890 * look up the ctid resnos now and save them in the
893 j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
894 if (!AttributeNumberIsValid(j->jf_junkAttNo))
895 elog(ERROR, "could not find junk ctid column");
896 resultRelInfo->ri_junkFilter = j;
901 * Set active junkfilter too; at this point ExecInitAppend has
902 * already selected an active result relation...
904 estate->es_junkFilter =
905 estate->es_result_relation_info->ri_junkFilter;
908 * We currently can't support rowmarks in this case, because
909 * the associated junk CTIDs might have different resnos in
910 * different subplans.
912 if (estate->es_rowMarks)
914 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
915 errmsg("SELECT FOR UPDATE/SHARE is not supported within a query with multiple result relations")));
919 /* Normal case with just one JunkFilter */
922 if (operation == CMD_INSERT || operation == CMD_UPDATE)
923 ExecCheckPlanOutput(estate->es_result_relation_info->ri_RelationDesc,
924 planstate->plan->targetlist);
926 j = ExecInitJunkFilter(planstate->plan->targetlist,
928 ExecInitExtraTupleSlot(estate));
929 estate->es_junkFilter = j;
930 if (estate->es_result_relation_info)
931 estate->es_result_relation_info->ri_junkFilter = j;
933 if (operation == CMD_SELECT)
935 /* For SELECT, want to return the cleaned tuple type */
936 tupType = j->jf_cleanTupType;
938 else if (operation == CMD_UPDATE || operation == CMD_DELETE)
940 /* For UPDATE/DELETE, find the ctid junk attr now */
941 j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
942 if (!AttributeNumberIsValid(j->jf_junkAttNo))
943 elog(ERROR, "could not find junk ctid column");
946 /* For SELECT FOR UPDATE/SHARE, find the junk attrs now */
947 foreach(l, estate->es_rowMarks)
949 ExecRowMark *erm = (ExecRowMark *) lfirst(l);
952 /* always need the ctid */
953 snprintf(resname, sizeof(resname), "ctid%u",
955 erm->ctidAttNo = ExecFindJunkAttribute(j, resname);
956 if (!AttributeNumberIsValid(erm->ctidAttNo))
957 elog(ERROR, "could not find junk \"%s\" column",
959 /* if child relation, need tableoid too */
960 if (erm->rti != erm->prti)
962 snprintf(resname, sizeof(resname), "tableoid%u",
964 erm->toidAttNo = ExecFindJunkAttribute(j, resname);
965 if (!AttributeNumberIsValid(erm->toidAttNo))
966 elog(ERROR, "could not find junk \"%s\" column",
974 if (operation == CMD_INSERT)
975 ExecCheckPlanOutput(estate->es_result_relation_info->ri_RelationDesc,
976 planstate->plan->targetlist);
978 estate->es_junkFilter = NULL;
979 if (estate->es_rowMarks)
980 elog(ERROR, "SELECT FOR UPDATE/SHARE, but no junk columns");
985 * Initialize RETURNING projections if needed.
987 if (plannedstmt->returningLists)
989 TupleTableSlot *slot;
990 ExprContext *econtext;
991 ResultRelInfo *resultRelInfo;
994 * We set QueryDesc.tupDesc to be the RETURNING rowtype in this case.
995 * We assume all the sublists will generate the same output tupdesc.
997 tupType = ExecTypeFromTL((List *) linitial(plannedstmt->returningLists),
1000 /* Set up a slot for the output of the RETURNING projection(s) */
1001 slot = ExecInitExtraTupleSlot(estate);
1002 ExecSetSlotDescriptor(slot, tupType);
1003 /* Need an econtext too */
1004 econtext = CreateExprContext(estate);
1007 * Build a projection for each result rel. Note that any SubPlans in
1008 * the RETURNING lists get attached to the topmost plan node.
1010 Assert(list_length(plannedstmt->returningLists) == estate->es_num_result_relations);
1011 resultRelInfo = estate->es_result_relations;
1012 foreach(l, plannedstmt->returningLists)
1014 List *rlist = (List *) lfirst(l);
1017 rliststate = (List *) ExecInitExpr((Expr *) rlist, planstate);
1018 resultRelInfo->ri_projectReturning =
1019 ExecBuildProjectionInfo(rliststate, econtext, slot,
1020 resultRelInfo->ri_RelationDesc->rd_att);
1025 queryDesc->tupDesc = tupType;
1026 queryDesc->planstate = planstate;
1029 * If doing SELECT INTO, initialize the "into" relation. We must wait
1030 * till now so we have the "clean" result tuple type to create the new
1033 * If EXPLAIN, skip creating the "into" relation.
1035 if (estate->es_select_into && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
1036 OpenIntoRel(queryDesc);
1040 * Initialize ResultRelInfo data for one result relation
1043 InitResultRelInfo(ResultRelInfo *resultRelInfo,
1044 Relation resultRelationDesc,
1045 Index resultRelationIndex,
1050 * Check valid relkind ... parser and/or planner should have noticed this
1051 * already, but let's make sure.
1053 switch (resultRelationDesc->rd_rel->relkind)
1055 case RELKIND_RELATION:
1058 case RELKIND_SEQUENCE:
1060 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1061 errmsg("cannot change sequence \"%s\"",
1062 RelationGetRelationName(resultRelationDesc))));
1064 case RELKIND_TOASTVALUE:
1066 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1067 errmsg("cannot change TOAST relation \"%s\"",
1068 RelationGetRelationName(resultRelationDesc))));
1072 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1073 errmsg("cannot change view \"%s\"",
1074 RelationGetRelationName(resultRelationDesc))));
1078 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1079 errmsg("cannot change relation \"%s\"",
1080 RelationGetRelationName(resultRelationDesc))));
1084 /* OK, fill in the node */
1085 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1086 resultRelInfo->type = T_ResultRelInfo;
1087 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1088 resultRelInfo->ri_RelationDesc = resultRelationDesc;
1089 resultRelInfo->ri_NumIndices = 0;
1090 resultRelInfo->ri_IndexRelationDescs = NULL;
1091 resultRelInfo->ri_IndexRelationInfo = NULL;
1092 /* make a copy so as not to depend on relcache info not changing... */
1093 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1094 if (resultRelInfo->ri_TrigDesc)
1096 int n = resultRelInfo->ri_TrigDesc->numtriggers;
1098 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1099 palloc0(n * sizeof(FmgrInfo));
1101 resultRelInfo->ri_TrigInstrument = InstrAlloc(n);
1103 resultRelInfo->ri_TrigInstrument = NULL;
1107 resultRelInfo->ri_TrigFunctions = NULL;
1108 resultRelInfo->ri_TrigInstrument = NULL;
1110 resultRelInfo->ri_ConstraintExprs = NULL;
1111 resultRelInfo->ri_junkFilter = NULL;
1112 resultRelInfo->ri_projectReturning = NULL;
1115 * If there are indices on the result relation, open them and save
1116 * descriptors in the result relation info, so that we can add new index
1117 * entries for the tuples we add/update. We need not do this for a
1118 * DELETE, however, since deletion doesn't affect indexes.
1120 if (resultRelationDesc->rd_rel->relhasindex &&
1121 operation != CMD_DELETE)
1122 ExecOpenIndices(resultRelInfo);
1126 * Verify that the tuples to be produced by INSERT or UPDATE match the
1127 * target relation's rowtype
1129 * We do this to guard against stale plans. If plan invalidation is
1130 * functioning properly then we should never get a failure here, but better
1131 * safe than sorry. Note that this is called after we have obtained lock
1132 * on the target rel, so the rowtype can't change underneath us.
1134 * The plan output is represented by its targetlist, because that makes
1135 * handling the dropped-column case easier.
1138 ExecCheckPlanOutput(Relation resultRel, List *targetList)
1140 TupleDesc resultDesc = RelationGetDescr(resultRel);
1144 foreach(lc, targetList)
1146 TargetEntry *tle = (TargetEntry *) lfirst(lc);
1147 Form_pg_attribute attr;
1150 continue; /* ignore junk tlist items */
1152 if (attno >= resultDesc->natts)
1154 (errcode(ERRCODE_DATATYPE_MISMATCH),
1155 errmsg("table row type and query-specified row type do not match"),
1156 errdetail("Query has too many columns.")));
1157 attr = resultDesc->attrs[attno++];
1159 if (!attr->attisdropped)
1161 /* Normal case: demand type match */
1162 if (exprType((Node *) tle->expr) != attr->atttypid)
1164 (errcode(ERRCODE_DATATYPE_MISMATCH),
1165 errmsg("table row type and query-specified row type do not match"),
1166 errdetail("Table has type %s at ordinal position %d, but query expects %s.",
1167 format_type_be(attr->atttypid),
1169 format_type_be(exprType((Node *) tle->expr)))));
1174 * For a dropped column, we can't check atttypid (it's likely 0).
1175 * In any case the planner has most likely inserted an INT4 null.
1176 * What we insist on is just *some* NULL constant.
1178 if (!IsA(tle->expr, Const) ||
1179 !((Const *) tle->expr)->constisnull)
1181 (errcode(ERRCODE_DATATYPE_MISMATCH),
1182 errmsg("table row type and query-specified row type do not match"),
1183 errdetail("Query provides a value for a dropped column at ordinal position %d.",
1187 if (attno != resultDesc->natts)
1189 (errcode(ERRCODE_DATATYPE_MISMATCH),
1190 errmsg("table row type and query-specified row type do not match"),
1191 errdetail("Query has too few columns.")));
1195 * ExecGetTriggerResultRel
1197 * Get a ResultRelInfo for a trigger target relation. Most of the time,
1198 * triggers are fired on one of the result relations of the query, and so
1199 * we can just return a member of the es_result_relations array. (Note: in
1200 * self-join situations there might be multiple members with the same OID;
1201 * if so it doesn't matter which one we pick.) However, it is sometimes
1202 * necessary to fire triggers on other relations; this happens mainly when an
1203 * RI update trigger queues additional triggers on other relations, which will
1204 * be processed in the context of the outer query. For efficiency's sake,
1205 * we want to have a ResultRelInfo for those triggers too; that can avoid
1206 * repeated re-opening of the relation. (It also provides a way for EXPLAIN
1207 * ANALYZE to report the runtimes of such triggers.) So we make additional
1208 * ResultRelInfo's as needed, and save them in es_trig_target_relations.
1211 ExecGetTriggerResultRel(EState *estate, Oid relid)
1213 ResultRelInfo *rInfo;
1217 MemoryContext oldcontext;
1219 /* First, search through the query result relations */
1220 rInfo = estate->es_result_relations;
1221 nr = estate->es_num_result_relations;
1224 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1229 /* Nope, but maybe we already made an extra ResultRelInfo for it */
1230 foreach(l, estate->es_trig_target_relations)
1232 rInfo = (ResultRelInfo *) lfirst(l);
1233 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1236 /* Nope, so we need a new one */
1239 * Open the target relation's relcache entry. We assume that an
1240 * appropriate lock is still held by the backend from whenever the trigger
1241 * event got queued, so we need take no new lock here.
1243 rel = heap_open(relid, NoLock);
1246 * Make the new entry in the right context. Currently, we don't need any
1247 * index information in ResultRelInfos used only for triggers, so tell
1248 * InitResultRelInfo it's a DELETE.
1250 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1251 rInfo = makeNode(ResultRelInfo);
1252 InitResultRelInfo(rInfo,
1254 0, /* dummy rangetable index */
1256 estate->es_instrument);
1257 estate->es_trig_target_relations =
1258 lappend(estate->es_trig_target_relations, rInfo);
1259 MemoryContextSwitchTo(oldcontext);
1265 * ExecContextForcesOids
1267 * This is pretty grotty: when doing INSERT, UPDATE, or SELECT INTO,
1268 * we need to ensure that result tuples have space for an OID iff they are
1269 * going to be stored into a relation that has OIDs. In other contexts
1270 * we are free to choose whether to leave space for OIDs in result tuples
1271 * (we generally don't want to, but we do if a physical-tlist optimization
1272 * is possible). This routine checks the plan context and returns TRUE if the
1273 * choice is forced, FALSE if the choice is not forced. In the TRUE case,
1274 * *hasoids is set to the required value.
1276 * One reason this is ugly is that all plan nodes in the plan tree will emit
1277 * tuples with space for an OID, though we really only need the topmost node
1278 * to do so. However, node types like Sort don't project new tuples but just
1279 * return their inputs, and in those cases the requirement propagates down
1280 * to the input node. Eventually we might make this code smart enough to
1281 * recognize how far down the requirement really goes, but for now we just
1282 * make all plan nodes do the same thing if the top level forces the choice.
1284 * We assume that estate->es_result_relation_info is already set up to
1285 * describe the target relation. Note that in an UPDATE that spans an
1286 * inheritance tree, some of the target relations may have OIDs and some not.
1287 * We have to make the decisions on a per-relation basis as we initialize
1288 * each of the child plans of the topmost Append plan.
1290 * SELECT INTO is even uglier, because we don't have the INTO relation's
1291 * descriptor available when this code runs; we have to look aside at a
1292 * flag set by InitPlan().
1295 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
1297 if (planstate->state->es_select_into)
1299 *hasoids = planstate->state->es_into_oids;
1304 ResultRelInfo *ri = planstate->state->es_result_relation_info;
1308 Relation rel = ri->ri_RelationDesc;
1312 *hasoids = rel->rd_rel->relhasoids;
1321 /* ----------------------------------------------------------------
1324 * Cleans up the query plan -- closes files and frees up storage
1326 * NOTE: we are no longer very worried about freeing storage per se
1327 * in this code; FreeExecutorState should be guaranteed to release all
1328 * memory that needs to be released. What we are worried about doing
1329 * is closing relations and dropping buffer pins. Thus, for example,
1330 * tuple tables must be cleared or dropped to ensure pins are released.
1331 * ----------------------------------------------------------------
1334 ExecEndPlan(PlanState *planstate, EState *estate)
1336 ResultRelInfo *resultRelInfo;
1341 * shut down any PlanQual processing we were doing
1343 if (estate->es_evalPlanQual != NULL)
1344 EndEvalPlanQual(estate);
1347 * shut down the node-type-specific query processing
1349 ExecEndNode(planstate);
1354 foreach(l, estate->es_subplanstates)
1356 PlanState *subplanstate = (PlanState *) lfirst(l);
1358 ExecEndNode(subplanstate);
1362 * destroy the executor's tuple table. Actually we only care about
1363 * releasing buffer pins and tupdesc refcounts; there's no need to
1364 * pfree the TupleTableSlots, since the containing memory context
1365 * is about to go away anyway.
1367 ExecResetTupleTable(estate->es_tupleTable, false);
1370 * close the result relation(s) if any, but hold locks until xact commit.
1372 resultRelInfo = estate->es_result_relations;
1373 for (i = estate->es_num_result_relations; i > 0; i--)
1375 /* Close indices and then the relation itself */
1376 ExecCloseIndices(resultRelInfo);
1377 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1382 * likewise close any trigger target relations
1384 foreach(l, estate->es_trig_target_relations)
1386 resultRelInfo = (ResultRelInfo *) lfirst(l);
1387 /* Close indices and then the relation itself */
1388 ExecCloseIndices(resultRelInfo);
1389 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1393 * close any relations selected FOR UPDATE/FOR SHARE, again keeping locks
1395 foreach(l, estate->es_rowMarks)
1397 ExecRowMark *erm = lfirst(l);
1399 heap_close(erm->relation, NoLock);
1403 /* ----------------------------------------------------------------
1406 * Processes the query plan until we have processed 'numberTuples' tuples,
1407 * moving in the specified direction.
1409 * Runs to completion if numberTuples is 0
1411 * Note: the ctid attribute is a 'junk' attribute that is removed before the
1413 * ----------------------------------------------------------------
1416 ExecutePlan(EState *estate,
1417 PlanState *planstate,
1420 ScanDirection direction,
1423 JunkFilter *junkfilter;
1424 TupleTableSlot *planSlot;
1425 TupleTableSlot *slot;
1426 ItemPointer tupleid = NULL;
1427 ItemPointerData tuple_ctid;
1428 long current_tuple_count;
1431 * initialize local variables
1433 current_tuple_count = 0;
1436 * Set the direction.
1438 estate->es_direction = direction;
1441 * Process BEFORE EACH STATEMENT triggers
1446 ExecBSUpdateTriggers(estate, estate->es_result_relation_info);
1449 ExecBSDeleteTriggers(estate, estate->es_result_relation_info);
1452 ExecBSInsertTriggers(estate, estate->es_result_relation_info);
1460 * Loop until we've processed the proper number of tuples from the plan.
1464 /* Reset the per-output-tuple exprcontext */
1465 ResetPerTupleExprContext(estate);
1468 * Execute the plan and obtain a tuple
1471 if (estate->es_useEvalPlan)
1473 planSlot = EvalPlanQualNext(estate);
1474 if (TupIsNull(planSlot))
1475 planSlot = ExecProcNode(planstate);
1478 planSlot = ExecProcNode(planstate);
1481 * if the tuple is null, then we assume there is nothing more to
1482 * process so we just end the loop...
1484 if (TupIsNull(planSlot))
1489 * If we have a junk filter, then project a new tuple with the junk
1492 * Store this new "clean" tuple in the junkfilter's resultSlot.
1493 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1494 * because that tuple slot has the wrong descriptor.)
1496 * But first, extract all the junk information we need.
1498 if ((junkfilter = estate->es_junkFilter) != NULL)
1501 * Process any FOR UPDATE or FOR SHARE locking requested.
1503 if (estate->es_rowMarks != NIL)
1508 foreach(l, estate->es_rowMarks)
1510 ExecRowMark *erm = lfirst(l);
1513 HeapTupleData tuple;
1515 ItemPointerData update_ctid;
1516 TransactionId update_xmax;
1517 TupleTableSlot *newSlot;
1518 LockTupleMode lockmode;
1521 /* if child rel, must check whether it produced this row */
1522 if (erm->rti != erm->prti)
1526 datum = ExecGetJunkAttribute(slot,
1529 /* shouldn't ever get a null result... */
1531 elog(ERROR, "tableoid is NULL");
1532 tableoid = DatumGetObjectId(datum);
1534 if (tableoid != RelationGetRelid(erm->relation))
1536 /* this child is inactive right now */
1537 ItemPointerSetInvalid(&(erm->curCtid));
1542 /* okay, fetch the tuple by ctid */
1543 datum = ExecGetJunkAttribute(slot,
1546 /* shouldn't ever get a null result... */
1548 elog(ERROR, "ctid is NULL");
1549 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1552 lockmode = LockTupleExclusive;
1554 lockmode = LockTupleShared;
1556 test = heap_lock_tuple(erm->relation, &tuple, &buffer,
1557 &update_ctid, &update_xmax,
1558 estate->es_output_cid,
1559 lockmode, erm->noWait);
1560 ReleaseBuffer(buffer);
1563 case HeapTupleSelfUpdated:
1564 /* treat it as deleted; do not process */
1567 case HeapTupleMayBeUpdated:
1570 case HeapTupleUpdated:
1571 if (IsXactIsoLevelSerializable)
1573 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1574 errmsg("could not serialize access due to concurrent update")));
1575 if (!ItemPointerEquals(&update_ctid,
1578 /* updated, so look at updated version */
1579 newSlot = EvalPlanQual(estate,
1583 if (!TupIsNull(newSlot))
1585 slot = planSlot = newSlot;
1586 estate->es_useEvalPlan = true;
1592 * if tuple was deleted or PlanQual failed for
1593 * updated tuple - we must not return this tuple!
1598 elog(ERROR, "unrecognized heap_lock_tuple status: %u",
1602 /* Remember tuple TID for WHERE CURRENT OF */
1603 erm->curCtid = tuple.t_self;
1608 * extract the 'ctid' junk attribute.
1610 if (operation == CMD_UPDATE || operation == CMD_DELETE)
1615 datum = ExecGetJunkAttribute(slot, junkfilter->jf_junkAttNo,
1617 /* shouldn't ever get a null result... */
1619 elog(ERROR, "ctid is NULL");
1621 tupleid = (ItemPointer) DatumGetPointer(datum);
1622 tuple_ctid = *tupleid; /* make sure we don't free the ctid!! */
1623 tupleid = &tuple_ctid;
1627 * Create a new "clean" tuple with all junk attributes removed. We
1628 * don't need to do this for DELETE, however (there will in fact
1629 * be no non-junk attributes in a DELETE!)
1631 if (operation != CMD_DELETE)
1632 slot = ExecFilterJunk(junkfilter, slot);
1636 * now that we have a tuple, do the appropriate thing with it.. either
1637 * send it to the output destination, add it to a relation someplace,
1638 * delete it from a relation, or modify some of its attributes.
1643 ExecSelect(slot, dest, estate);
1647 ExecInsert(slot, tupleid, planSlot, dest, estate);
1651 ExecDelete(tupleid, planSlot, dest, estate);
1655 ExecUpdate(slot, tupleid, planSlot, dest, estate);
1659 elog(ERROR, "unrecognized operation code: %d",
1665 * check our tuple count.. if we've processed the proper number then
1666 * quit, else loop again and process more tuples. Zero numberTuples
1669 current_tuple_count++;
1670 if (numberTuples && numberTuples == current_tuple_count)
1675 * Process AFTER EACH STATEMENT triggers
1680 ExecASUpdateTriggers(estate, estate->es_result_relation_info);
1683 ExecASDeleteTriggers(estate, estate->es_result_relation_info);
1686 ExecASInsertTriggers(estate, estate->es_result_relation_info);
1694 /* ----------------------------------------------------------------
1697 * SELECTs are easy.. we just pass the tuple to the appropriate
1699 * ----------------------------------------------------------------
1702 ExecSelect(TupleTableSlot *slot,
1706 (*dest->receiveSlot) (slot, dest);
1707 (estate->es_processed)++;
1710 /* ----------------------------------------------------------------
1713 * INSERTs are trickier.. we have to insert the tuple into
1714 * the base relation and insert appropriate tuples into the
1716 * ----------------------------------------------------------------
1719 ExecInsert(TupleTableSlot *slot,
1720 ItemPointer tupleid,
1721 TupleTableSlot *planSlot,
1726 ResultRelInfo *resultRelInfo;
1727 Relation resultRelationDesc;
1729 List *recheckIndexes = NIL;
1732 * get the heap tuple out of the tuple table slot, making sure we have a
1735 tuple = ExecMaterializeSlot(slot);
1738 * get information on the (current) result relation
1740 resultRelInfo = estate->es_result_relation_info;
1741 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1744 * If the result relation has OIDs, force the tuple's OID to zero so that
1745 * heap_insert will assign a fresh OID. Usually the OID already will be
1746 * zero at this point, but there are corner cases where the plan tree can
1747 * return a tuple extracted literally from some table with the same
1750 * XXX if we ever wanted to allow users to assign their own OIDs to new
1751 * rows, this'd be the place to do it. For the moment, we make a point of
1752 * doing this before calling triggers, so that a user-supplied trigger
1753 * could hack the OID if desired.
1755 if (resultRelationDesc->rd_rel->relhasoids)
1756 HeapTupleSetOid(tuple, InvalidOid);
1758 /* BEFORE ROW INSERT Triggers */
1759 if (resultRelInfo->ri_TrigDesc &&
1760 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1764 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1766 if (newtuple == NULL) /* "do nothing" */
1769 if (newtuple != tuple) /* modified by Trigger(s) */
1772 * Put the modified tuple into a slot for convenience of routines
1773 * below. We assume the tuple was allocated in per-tuple memory
1774 * context, and therefore will go away by itself. The tuple table
1775 * slot should not try to clear it.
1777 TupleTableSlot *newslot = estate->es_trig_tuple_slot;
1779 if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
1780 ExecSetSlotDescriptor(newslot, slot->tts_tupleDescriptor);
1781 ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
1788 * Check the constraints of the tuple
1790 if (resultRelationDesc->rd_att->constr)
1791 ExecConstraints(resultRelInfo, slot, estate);
1796 * Note: heap_insert returns the tid (location) of the new tuple in the
1799 newId = heap_insert(resultRelationDesc, tuple,
1800 estate->es_output_cid, 0, NULL);
1802 (estate->es_processed)++;
1803 estate->es_lastoid = newId;
1804 setLastTid(&(tuple->t_self));
1807 * insert index entries for tuple
1809 if (resultRelInfo->ri_NumIndices > 0)
1810 recheckIndexes = ExecInsertIndexTuples(slot, &(tuple->t_self),
1813 /* AFTER ROW INSERT Triggers */
1814 ExecARInsertTriggers(estate, resultRelInfo, tuple, recheckIndexes);
1816 /* Process RETURNING if present */
1817 if (resultRelInfo->ri_projectReturning)
1818 ExecProcessReturning(resultRelInfo->ri_projectReturning,
1819 slot, planSlot, dest);
1822 /* ----------------------------------------------------------------
1825 * DELETE is like UPDATE, except that we delete the tuple and no
1826 * index modifications are needed
1827 * ----------------------------------------------------------------
1830 ExecDelete(ItemPointer tupleid,
1831 TupleTableSlot *planSlot,
1835 ResultRelInfo *resultRelInfo;
1836 Relation resultRelationDesc;
1838 ItemPointerData update_ctid;
1839 TransactionId update_xmax;
1842 * get information on the (current) result relation
1844 resultRelInfo = estate->es_result_relation_info;
1845 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1847 /* BEFORE ROW DELETE Triggers */
1848 if (resultRelInfo->ri_TrigDesc &&
1849 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1853 dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid);
1855 if (!dodelete) /* "do nothing" */
1862 * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
1863 * the row to be deleted is visible to that snapshot, and throw a can't-
1864 * serialize error if not. This is a special-case behavior needed for
1865 * referential integrity updates in serializable transactions.
1868 result = heap_delete(resultRelationDesc, tupleid,
1869 &update_ctid, &update_xmax,
1870 estate->es_output_cid,
1871 estate->es_crosscheck_snapshot,
1872 true /* wait for commit */ );
1875 case HeapTupleSelfUpdated:
1876 /* already deleted by self; nothing to do */
1879 case HeapTupleMayBeUpdated:
1882 case HeapTupleUpdated:
1883 if (IsXactIsoLevelSerializable)
1885 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1886 errmsg("could not serialize access due to concurrent update")));
1887 else if (!ItemPointerEquals(tupleid, &update_ctid))
1889 TupleTableSlot *epqslot;
1891 epqslot = EvalPlanQual(estate,
1892 resultRelInfo->ri_RangeTableIndex,
1895 if (!TupIsNull(epqslot))
1897 *tupleid = update_ctid;
1901 /* tuple already deleted; nothing to do */
1905 elog(ERROR, "unrecognized heap_delete status: %u", result);
1909 (estate->es_processed)++;
1912 * Note: Normally one would think that we have to delete index tuples
1913 * associated with the heap tuple now...
1915 * ... but in POSTGRES, we have no need to do this because VACUUM will
1916 * take care of it later. We can't delete index tuples immediately
1917 * anyway, since the tuple is still visible to other transactions.
1920 /* AFTER ROW DELETE Triggers */
1921 ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1923 /* Process RETURNING if present */
1924 if (resultRelInfo->ri_projectReturning)
1927 * We have to put the target tuple into a slot, which means first we
1928 * gotta fetch it. We can use the trigger tuple slot.
1930 TupleTableSlot *slot = estate->es_trig_tuple_slot;
1931 HeapTupleData deltuple;
1934 deltuple.t_self = *tupleid;
1935 if (!heap_fetch(resultRelationDesc, SnapshotAny,
1936 &deltuple, &delbuffer, false, NULL))
1937 elog(ERROR, "failed to fetch deleted tuple for DELETE RETURNING");
1939 if (slot->tts_tupleDescriptor != RelationGetDescr(resultRelationDesc))
1940 ExecSetSlotDescriptor(slot, RelationGetDescr(resultRelationDesc));
1941 ExecStoreTuple(&deltuple, slot, InvalidBuffer, false);
1943 ExecProcessReturning(resultRelInfo->ri_projectReturning,
1944 slot, planSlot, dest);
1946 ExecClearTuple(slot);
1947 ReleaseBuffer(delbuffer);
1951 /* ----------------------------------------------------------------
1954 * note: we can't run UPDATE queries with transactions
1955 * off because UPDATEs are actually INSERTs and our
1956 * scan will mistakenly loop forever, updating the tuple
1957 * it just inserted.. This should be fixed but until it
1958 * is, we don't want to get stuck in an infinite loop
1959 * which corrupts your database..
1960 * ----------------------------------------------------------------
1963 ExecUpdate(TupleTableSlot *slot,
1964 ItemPointer tupleid,
1965 TupleTableSlot *planSlot,
1970 ResultRelInfo *resultRelInfo;
1971 Relation resultRelationDesc;
1973 ItemPointerData update_ctid;
1974 TransactionId update_xmax;
1975 List *recheckIndexes = NIL;
1978 * abort the operation if not running transactions
1980 if (IsBootstrapProcessingMode())
1981 elog(ERROR, "cannot UPDATE during bootstrap");
1984 * get the heap tuple out of the tuple table slot, making sure we have a
1987 tuple = ExecMaterializeSlot(slot);
1990 * get information on the (current) result relation
1992 resultRelInfo = estate->es_result_relation_info;
1993 resultRelationDesc = resultRelInfo->ri_RelationDesc;
1995 /* BEFORE ROW UPDATE Triggers */
1996 if (resultRelInfo->ri_TrigDesc &&
1997 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
2001 newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
2004 if (newtuple == NULL) /* "do nothing" */
2007 if (newtuple != tuple) /* modified by Trigger(s) */
2010 * Put the modified tuple into a slot for convenience of routines
2011 * below. We assume the tuple was allocated in per-tuple memory
2012 * context, and therefore will go away by itself. The tuple table
2013 * slot should not try to clear it.
2015 TupleTableSlot *newslot = estate->es_trig_tuple_slot;
2017 if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
2018 ExecSetSlotDescriptor(newslot, slot->tts_tupleDescriptor);
2019 ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
2026 * Check the constraints of the tuple
2028 * If we generate a new candidate tuple after EvalPlanQual testing, we
2029 * must loop back here and recheck constraints. (We don't need to redo
2030 * triggers, however. If there are any BEFORE triggers then trigger.c
2031 * will have done heap_lock_tuple to lock the correct tuple, so there's no
2032 * need to do them again.)
2035 if (resultRelationDesc->rd_att->constr)
2036 ExecConstraints(resultRelInfo, slot, estate);
2039 * replace the heap tuple
2041 * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
2042 * the row to be updated is visible to that snapshot, and throw a can't-
2043 * serialize error if not. This is a special-case behavior needed for
2044 * referential integrity updates in serializable transactions.
2046 result = heap_update(resultRelationDesc, tupleid, tuple,
2047 &update_ctid, &update_xmax,
2048 estate->es_output_cid,
2049 estate->es_crosscheck_snapshot,
2050 true /* wait for commit */ );
2053 case HeapTupleSelfUpdated:
2054 /* already deleted by self; nothing to do */
2057 case HeapTupleMayBeUpdated:
2060 case HeapTupleUpdated:
2061 if (IsXactIsoLevelSerializable)
2063 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2064 errmsg("could not serialize access due to concurrent update")));
2065 else if (!ItemPointerEquals(tupleid, &update_ctid))
2067 TupleTableSlot *epqslot;
2069 epqslot = EvalPlanQual(estate,
2070 resultRelInfo->ri_RangeTableIndex,
2073 if (!TupIsNull(epqslot))
2075 *tupleid = update_ctid;
2076 slot = ExecFilterJunk(estate->es_junkFilter, epqslot);
2077 tuple = ExecMaterializeSlot(slot);
2081 /* tuple already deleted; nothing to do */
2085 elog(ERROR, "unrecognized heap_update status: %u", result);
2089 (estate->es_processed)++;
2092 * Note: instead of having to update the old index tuples associated with
2093 * the heap tuple, all we do is form and insert new index tuples. This is
2094 * because UPDATEs are actually DELETEs and INSERTs, and index tuple
2095 * deletion is done later by VACUUM (see notes in ExecDelete). All we do
2096 * here is insert new index tuples. -cim 9/27/89
2100 * insert index entries for tuple
2102 * Note: heap_update returns the tid (location) of the new tuple in the
2105 * If it's a HOT update, we mustn't insert new index entries.
2107 if (resultRelInfo->ri_NumIndices > 0 && !HeapTupleIsHeapOnly(tuple))
2108 recheckIndexes = ExecInsertIndexTuples(slot, &(tuple->t_self),
2111 /* AFTER ROW UPDATE Triggers */
2112 ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple,
2115 /* Process RETURNING if present */
2116 if (resultRelInfo->ri_projectReturning)
2117 ExecProcessReturning(resultRelInfo->ri_projectReturning,
2118 slot, planSlot, dest);
2122 * ExecRelCheck --- check that tuple meets constraints for result relation
2125 ExecRelCheck(ResultRelInfo *resultRelInfo,
2126 TupleTableSlot *slot, EState *estate)
2128 Relation rel = resultRelInfo->ri_RelationDesc;
2129 int ncheck = rel->rd_att->constr->num_check;
2130 ConstrCheck *check = rel->rd_att->constr->check;
2131 ExprContext *econtext;
2132 MemoryContext oldContext;
2137 * If first time through for this result relation, build expression
2138 * nodetrees for rel's constraint expressions. Keep them in the per-query
2139 * memory context so they'll survive throughout the query.
2141 if (resultRelInfo->ri_ConstraintExprs == NULL)
2143 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
2144 resultRelInfo->ri_ConstraintExprs =
2145 (List **) palloc(ncheck * sizeof(List *));
2146 for (i = 0; i < ncheck; i++)
2148 /* ExecQual wants implicit-AND form */
2149 qual = make_ands_implicit(stringToNode(check[i].ccbin));
2150 resultRelInfo->ri_ConstraintExprs[i] = (List *)
2151 ExecPrepareExpr((Expr *) qual, estate);
2153 MemoryContextSwitchTo(oldContext);
2157 * We will use the EState's per-tuple context for evaluating constraint
2158 * expressions (creating it if it's not already there).
2160 econtext = GetPerTupleExprContext(estate);
2162 /* Arrange for econtext's scan tuple to be the tuple under test */
2163 econtext->ecxt_scantuple = slot;
2165 /* And evaluate the constraints */
2166 for (i = 0; i < ncheck; i++)
2168 qual = resultRelInfo->ri_ConstraintExprs[i];
2171 * NOTE: SQL92 specifies that a NULL result from a constraint
2172 * expression is not to be treated as a failure. Therefore, tell
2173 * ExecQual to return TRUE for NULL.
2175 if (!ExecQual(qual, econtext, true))
2176 return check[i].ccname;
2179 /* NULL result means no error */
2184 ExecConstraints(ResultRelInfo *resultRelInfo,
2185 TupleTableSlot *slot, EState *estate)
2187 Relation rel = resultRelInfo->ri_RelationDesc;
2188 TupleConstr *constr = rel->rd_att->constr;
2192 if (constr->has_not_null)
2194 int natts = rel->rd_att->natts;
2197 for (attrChk = 1; attrChk <= natts; attrChk++)
2199 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
2200 slot_attisnull(slot, attrChk))
2202 (errcode(ERRCODE_NOT_NULL_VIOLATION),
2203 errmsg("null value in column \"%s\" violates not-null constraint",
2204 NameStr(rel->rd_att->attrs[attrChk - 1]->attname))));
2208 if (constr->num_check > 0)
2212 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
2214 (errcode(ERRCODE_CHECK_VIOLATION),
2215 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
2216 RelationGetRelationName(rel), failed)));
2221 * ExecProcessReturning --- evaluate a RETURNING list and send to dest
2223 * projectReturning: RETURNING projection info for current result rel
2224 * tupleSlot: slot holding tuple actually inserted/updated/deleted
2225 * planSlot: slot holding tuple returned by top plan node
2226 * dest: where to send the output
2229 ExecProcessReturning(ProjectionInfo *projectReturning,
2230 TupleTableSlot *tupleSlot,
2231 TupleTableSlot *planSlot,
2234 ExprContext *econtext = projectReturning->pi_exprContext;
2235 TupleTableSlot *retSlot;
2238 * Reset per-tuple memory context to free any expression evaluation
2239 * storage allocated in the previous cycle.
2241 ResetExprContext(econtext);
2243 /* Make tuple and any needed join variables available to ExecProject */
2244 econtext->ecxt_scantuple = tupleSlot;
2245 econtext->ecxt_outertuple = planSlot;
2247 /* Compute the RETURNING expressions */
2248 retSlot = ExecProject(projectReturning, NULL);
2251 (*dest->receiveSlot) (retSlot, dest);
2253 ExecClearTuple(retSlot);
2257 * Check a modified tuple to see if we want to process its updated version
2258 * under READ COMMITTED rules.
2260 * See backend/executor/README for some info about how this works.
2262 * estate - executor state data
2263 * rti - rangetable index of table containing tuple
2264 * *tid - t_ctid from the outdated tuple (ie, next updated version)
2265 * priorXmax - t_xmax from the outdated tuple
2267 * *tid is also an output parameter: it's modified to hold the TID of the
2268 * latest version of the tuple (note this may be changed even on failure)
2270 * Returns a slot containing the new candidate update/delete tuple, or
2271 * NULL if we determine we shouldn't process the row.
2274 EvalPlanQual(EState *estate, Index rti,
2275 ItemPointer tid, TransactionId priorXmax)
2280 HeapTupleData tuple;
2281 HeapTuple copyTuple = NULL;
2282 SnapshotData SnapshotDirty;
2288 * find relation containing target tuple
2290 if (estate->es_result_relation_info != NULL &&
2291 estate->es_result_relation_info->ri_RangeTableIndex == rti)
2292 relation = estate->es_result_relation_info->ri_RelationDesc;
2298 foreach(l, estate->es_rowMarks)
2300 ExecRowMark *erm = lfirst(l);
2302 if (erm->rti == rti)
2304 relation = erm->relation;
2308 if (relation == NULL)
2309 elog(ERROR, "could not find RowMark for RT index %u", rti);
2315 * Loop here to deal with updated or busy tuples
2317 InitDirtySnapshot(SnapshotDirty);
2318 tuple.t_self = *tid;
2323 if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
2326 * If xmin isn't what we're expecting, the slot must have been
2327 * recycled and reused for an unrelated tuple. This implies that
2328 * the latest version of the row was deleted, so we need do
2329 * nothing. (Should be safe to examine xmin without getting
2330 * buffer's content lock, since xmin never changes in an existing
2333 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2336 ReleaseBuffer(buffer);
2340 /* otherwise xmin should not be dirty... */
2341 if (TransactionIdIsValid(SnapshotDirty.xmin))
2342 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
2345 * If tuple is being updated by other transaction then we have to
2346 * wait for its commit/abort.
2348 if (TransactionIdIsValid(SnapshotDirty.xmax))
2350 ReleaseBuffer(buffer);
2351 XactLockTableWait(SnapshotDirty.xmax);
2352 continue; /* loop back to repeat heap_fetch */
2356 * If tuple was inserted by our own transaction, we have to check
2357 * cmin against es_output_cid: cmin >= current CID means our
2358 * command cannot see the tuple, so we should ignore it. Without
2359 * this we are open to the "Halloween problem" of indefinitely
2360 * re-updating the same tuple. (We need not check cmax because
2361 * HeapTupleSatisfiesDirty will consider a tuple deleted by our
2362 * transaction dead, regardless of cmax.) We just checked that
2363 * priorXmax == xmin, so we can test that variable instead of
2364 * doing HeapTupleHeaderGetXmin again.
2366 if (TransactionIdIsCurrentTransactionId(priorXmax) &&
2367 HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
2369 ReleaseBuffer(buffer);
2374 * We got tuple - now copy it for use by recheck query.
2376 copyTuple = heap_copytuple(&tuple);
2377 ReleaseBuffer(buffer);
2382 * If the referenced slot was actually empty, the latest version of
2383 * the row must have been deleted, so we need do nothing.
2385 if (tuple.t_data == NULL)
2387 ReleaseBuffer(buffer);
2392 * As above, if xmin isn't what we're expecting, do nothing.
2394 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2397 ReleaseBuffer(buffer);
2402 * If we get here, the tuple was found but failed SnapshotDirty.
2403 * Assuming the xmin is either a committed xact or our own xact (as it
2404 * certainly should be if we're trying to modify the tuple), this must
2405 * mean that the row was updated or deleted by either a committed xact
2406 * or our own xact. If it was deleted, we can ignore it; if it was
2407 * updated then chain up to the next version and repeat the whole
2410 * As above, it should be safe to examine xmax and t_ctid without the
2411 * buffer content lock, because they can't be changing.
2413 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
2415 /* deleted, so forget about it */
2416 ReleaseBuffer(buffer);
2420 /* updated, so look at the updated row */
2421 tuple.t_self = tuple.t_data->t_ctid;
2422 /* updated row should have xmin matching this xmax */
2423 priorXmax = HeapTupleHeaderGetXmax(tuple.t_data);
2424 ReleaseBuffer(buffer);
2425 /* loop back to fetch next in chain */
2429 * For UPDATE/DELETE we have to return tid of actual row we're executing
2432 *tid = tuple.t_self;
2435 * Need to run a recheck subquery. Find or create a PQ stack entry.
2437 epq = estate->es_evalPlanQual;
2440 if (epq != NULL && epq->rti == 0)
2442 /* Top PQ stack entry is idle, so re-use it */
2443 Assert(!(estate->es_useEvalPlan) && epq->next == NULL);
2449 * If this is request for another RTE - Ra, - then we have to check wasn't
2450 * PlanQual requested for Ra already and if so then Ra' row was updated
2451 * again and we have to re-start old execution for Ra and forget all what
2452 * we done after Ra was suspended. Cool? -:))
2454 if (epq != NULL && epq->rti != rti &&
2455 epq->estate->es_evTuple[rti - 1] != NULL)
2459 evalPlanQual *oldepq;
2461 /* stop execution */
2462 EvalPlanQualStop(epq);
2463 /* pop previous PlanQual from the stack */
2465 Assert(oldepq && oldepq->rti != 0);
2466 /* push current PQ to freePQ stack */
2469 estate->es_evalPlanQual = epq;
2470 } while (epq->rti != rti);
2474 * If we are requested for another RTE then we have to suspend execution
2475 * of current PlanQual and start execution for new one.
2477 if (epq == NULL || epq->rti != rti)
2479 /* try to reuse plan used previously */
2480 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
2482 if (newepq == NULL) /* first call or freePQ stack is empty */
2484 newepq = (evalPlanQual *) palloc0(sizeof(evalPlanQual));
2485 newepq->free = NULL;
2486 newepq->estate = NULL;
2487 newepq->planstate = NULL;
2491 /* recycle previously used PlanQual */
2492 Assert(newepq->estate == NULL);
2495 /* push current PQ to the stack */
2498 estate->es_evalPlanQual = epq;
2503 Assert(epq->rti == rti);
2506 * Ok - we're requested for the same RTE. Unfortunately we still have to
2507 * end and restart execution of the plan, because ExecReScan wouldn't
2508 * ensure that upper plan nodes would reset themselves. We could make
2509 * that work if insertion of the target tuple were integrated with the
2510 * Param mechanism somehow, so that the upper plan nodes know that their
2511 * children's outputs have changed.
2513 * Note that the stack of free evalPlanQual nodes is quite useless at the
2514 * moment, since it only saves us from pallocing/releasing the
2515 * evalPlanQual nodes themselves. But it will be useful once we implement
2516 * ReScan instead of end/restart for re-using PlanQual nodes.
2520 /* stop execution */
2521 EvalPlanQualStop(epq);
2525 * Initialize new recheck query.
2527 * Note: if we were re-using PlanQual plans via ExecReScan, we'd need to
2528 * instead copy down changeable state from the top plan (including
2529 * es_result_relation_info, es_junkFilter) and reset locally changeable
2530 * state in the epq (including es_param_exec_vals, es_evTupleNull).
2532 EvalPlanQualStart(epq, estate, epq->next);
2535 * free old RTE' tuple, if any, and store target tuple where relation's
2536 * scan node will see it
2538 epqstate = epq->estate;
2539 if (epqstate->es_evTuple[rti - 1] != NULL)
2540 heap_freetuple(epqstate->es_evTuple[rti - 1]);
2541 epqstate->es_evTuple[rti - 1] = copyTuple;
2543 return EvalPlanQualNext(estate);
2546 static TupleTableSlot *
2547 EvalPlanQualNext(EState *estate)
2549 evalPlanQual *epq = estate->es_evalPlanQual;
2550 MemoryContext oldcontext;
2551 TupleTableSlot *slot;
2553 Assert(epq->rti != 0);
2556 oldcontext = MemoryContextSwitchTo(epq->estate->es_query_cxt);
2557 slot = ExecProcNode(epq->planstate);
2558 MemoryContextSwitchTo(oldcontext);
2561 * No more tuples for this PQ. Continue previous one.
2563 if (TupIsNull(slot))
2565 evalPlanQual *oldepq;
2567 /* stop execution */
2568 EvalPlanQualStop(epq);
2569 /* pop old PQ from the stack */
2573 /* this is the first (oldest) PQ - mark as free */
2575 estate->es_useEvalPlan = false;
2576 /* and continue Query execution */
2579 Assert(oldepq->rti != 0);
2580 /* push current PQ to freePQ stack */
2583 estate->es_evalPlanQual = epq;
2591 EndEvalPlanQual(EState *estate)
2593 evalPlanQual *epq = estate->es_evalPlanQual;
2595 if (epq->rti == 0) /* plans already shutdowned */
2597 Assert(epq->next == NULL);
2603 evalPlanQual *oldepq;
2605 /* stop execution */
2606 EvalPlanQualStop(epq);
2607 /* pop old PQ from the stack */
2611 /* this is the first (oldest) PQ - mark as free */
2613 estate->es_useEvalPlan = false;
2616 Assert(oldepq->rti != 0);
2617 /* push current PQ to freePQ stack */
2620 estate->es_evalPlanQual = epq;
2625 * Start execution of one level of PlanQual.
2627 * This is a cut-down version of ExecutorStart(): we copy some state from
2628 * the top-level estate rather than initializing it fresh.
2631 EvalPlanQualStart(evalPlanQual *epq, EState *estate, evalPlanQual *priorepq)
2635 MemoryContext oldcontext;
2638 rtsize = list_length(estate->es_range_table);
2640 epq->estate = epqstate = CreateExecutorState();
2642 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2645 * The epqstates share the top query's copy of unchanging state such as
2646 * the snapshot, rangetable, result-rel info, and external Param info.
2647 * They need their own copies of local state, including a tuple table,
2648 * es_param_exec_vals, etc.
2650 epqstate->es_direction = ForwardScanDirection;
2651 epqstate->es_snapshot = estate->es_snapshot;
2652 epqstate->es_crosscheck_snapshot = estate->es_crosscheck_snapshot;
2653 epqstate->es_range_table = estate->es_range_table;
2654 epqstate->es_output_cid = estate->es_output_cid;
2655 epqstate->es_result_relations = estate->es_result_relations;
2656 epqstate->es_num_result_relations = estate->es_num_result_relations;
2657 epqstate->es_result_relation_info = estate->es_result_relation_info;
2658 epqstate->es_junkFilter = estate->es_junkFilter;
2659 /* es_trig_target_relations must NOT be copied */
2660 epqstate->es_param_list_info = estate->es_param_list_info;
2661 if (estate->es_plannedstmt->nParamExec > 0)
2662 epqstate->es_param_exec_vals = (ParamExecData *)
2663 palloc0(estate->es_plannedstmt->nParamExec * sizeof(ParamExecData));
2664 epqstate->es_rowMarks = estate->es_rowMarks;
2665 epqstate->es_instrument = estate->es_instrument;
2666 epqstate->es_select_into = estate->es_select_into;
2667 epqstate->es_into_oids = estate->es_into_oids;
2668 epqstate->es_plannedstmt = estate->es_plannedstmt;
2671 * Each epqstate must have its own es_evTupleNull state, but all the stack
2672 * entries share es_evTuple state. This allows sub-rechecks to inherit
2673 * the value being examined by an outer recheck.
2675 epqstate->es_evTupleNull = (bool *) palloc0(rtsize * sizeof(bool));
2676 if (priorepq == NULL)
2677 /* first PQ stack entry */
2678 epqstate->es_evTuple = (HeapTuple *)
2679 palloc0(rtsize * sizeof(HeapTuple));
2681 /* later stack entries share the same storage */
2682 epqstate->es_evTuple = priorepq->estate->es_evTuple;
2685 * Each epqstate also has its own tuple table.
2687 epqstate->es_tupleTable = NIL;
2690 * Initialize private state information for each SubPlan. We must do this
2691 * before running ExecInitNode on the main query tree, since
2692 * ExecInitSubPlan expects to be able to find these entries.
2694 Assert(epqstate->es_subplanstates == NIL);
2695 foreach(l, estate->es_plannedstmt->subplans)
2697 Plan *subplan = (Plan *) lfirst(l);
2698 PlanState *subplanstate;
2700 subplanstate = ExecInitNode(subplan, epqstate, 0);
2702 epqstate->es_subplanstates = lappend(epqstate->es_subplanstates,
2707 * Initialize the private state information for all the nodes in the query
2708 * tree. This opens files, allocates storage and leaves us ready to start
2709 * processing tuples.
2711 epq->planstate = ExecInitNode(estate->es_plannedstmt->planTree, epqstate, 0);
2713 MemoryContextSwitchTo(oldcontext);
2717 * End execution of one level of PlanQual.
2719 * This is a cut-down version of ExecutorEnd(); basically we want to do most
2720 * of the normal cleanup, but *not* close result relations (which we are
2721 * just sharing from the outer query). We do, however, have to close any
2722 * trigger target relations that got opened, since those are not shared.
2725 EvalPlanQualStop(evalPlanQual *epq)
2727 EState *epqstate = epq->estate;
2728 MemoryContext oldcontext;
2731 oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2733 ExecEndNode(epq->planstate);
2735 foreach(l, epqstate->es_subplanstates)
2737 PlanState *subplanstate = (PlanState *) lfirst(l);
2739 ExecEndNode(subplanstate);
2742 /* throw away the per-epqstate tuple table completely */
2743 ExecResetTupleTable(epqstate->es_tupleTable, true);
2744 epqstate->es_tupleTable = NIL;
2746 if (epqstate->es_evTuple[epq->rti - 1] != NULL)
2748 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
2749 epqstate->es_evTuple[epq->rti - 1] = NULL;
2752 foreach(l, epqstate->es_trig_target_relations)
2754 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
2756 /* Close indices and then the relation itself */
2757 ExecCloseIndices(resultRelInfo);
2758 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
2761 MemoryContextSwitchTo(oldcontext);
2763 FreeExecutorState(epqstate);
2766 epq->planstate = NULL;
2770 * ExecGetActivePlanTree --- get the active PlanState tree from a QueryDesc
2772 * Ordinarily this is just the one mentioned in the QueryDesc, but if we
2773 * are looking at a row returned by the EvalPlanQual machinery, we need
2774 * to look at the subsidiary state instead.
2777 ExecGetActivePlanTree(QueryDesc *queryDesc)
2779 EState *estate = queryDesc->estate;
2781 if (estate && estate->es_useEvalPlan && estate->es_evalPlanQual != NULL)
2782 return estate->es_evalPlanQual->planstate;
2784 return queryDesc->planstate;
2789 * Support for SELECT INTO (a/k/a CREATE TABLE AS)
2791 * We implement SELECT INTO by diverting SELECT's normal output with
2792 * a specialized DestReceiver type.
2797 DestReceiver pub; /* publicly-known function pointers */
2798 EState *estate; /* EState we are working with */
2799 Relation rel; /* Relation to write to */
2800 int hi_options; /* heap_insert performance options */
2801 BulkInsertState bistate; /* bulk insert state */
2805 * OpenIntoRel --- actually create the SELECT INTO target relation
2807 * This also replaces QueryDesc->dest with the special DestReceiver for
2808 * SELECT INTO. We assume that the correct result tuple type has already
2809 * been placed in queryDesc->tupDesc.
2812 OpenIntoRel(QueryDesc *queryDesc)
2814 IntoClause *into = queryDesc->plannedstmt->intoClause;
2815 EState *estate = queryDesc->estate;
2816 Relation intoRelationDesc;
2821 AclResult aclresult;
2824 DR_intorel *myState;
2825 static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
2830 * Check consistency of arguments
2832 if (into->onCommit != ONCOMMIT_NOOP && !into->rel->istemp)
2834 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2835 errmsg("ON COMMIT can only be used on temporary tables")));
2838 * Find namespace to create in, check its permissions
2840 intoName = into->rel->relname;
2841 namespaceId = RangeVarGetCreationNamespace(into->rel);
2843 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
2845 if (aclresult != ACLCHECK_OK)
2846 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2847 get_namespace_name(namespaceId));
2850 * Select tablespace to use. If not specified, use default tablespace
2851 * (which may in turn default to database's default).
2853 if (into->tableSpaceName)
2855 tablespaceId = get_tablespace_oid(into->tableSpaceName);
2856 if (!OidIsValid(tablespaceId))
2858 (errcode(ERRCODE_UNDEFINED_OBJECT),
2859 errmsg("tablespace \"%s\" does not exist",
2860 into->tableSpaceName)));
2864 tablespaceId = GetDefaultTablespace(into->rel->istemp);
2865 /* note InvalidOid is OK in this case */
2868 /* Check permissions except when using the database's default space */
2869 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
2871 AclResult aclresult;
2873 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
2876 if (aclresult != ACLCHECK_OK)
2877 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
2878 get_tablespace_name(tablespaceId));
2881 /* Parse and validate any reloptions */
2882 reloptions = transformRelOptions((Datum) 0,
2888 (void) heap_reloptions(RELKIND_RELATION, reloptions, true);
2890 /* Copy the tupdesc because heap_create_with_catalog modifies it */
2891 tupdesc = CreateTupleDescCopy(queryDesc->tupDesc);
2893 /* Now we can actually create the new relation */
2894 intoRelationId = heap_create_with_catalog(intoName,
2909 allowSystemTableMods);
2911 FreeTupleDesc(tupdesc);
2914 * Advance command counter so that the newly-created relation's catalog
2915 * tuples will be visible to heap_open.
2917 CommandCounterIncrement();
2920 * If necessary, create a TOAST table for the INTO relation. Note that
2921 * AlterTableCreateToastTable ends with CommandCounterIncrement(), so that
2922 * the TOAST table will be visible for insertion.
2924 reloptions = transformRelOptions((Datum) 0,
2931 (void) heap_reloptions(RELKIND_TOASTVALUE, reloptions, true);
2933 AlterTableCreateToastTable(intoRelationId, InvalidOid, reloptions, false);
2936 * And open the constructed table for writing.
2938 intoRelationDesc = heap_open(intoRelationId, AccessExclusiveLock);
2941 * Now replace the query's DestReceiver with one for SELECT INTO
2943 queryDesc->dest = CreateDestReceiver(DestIntoRel);
2944 myState = (DR_intorel *) queryDesc->dest;
2945 Assert(myState->pub.mydest == DestIntoRel);
2946 myState->estate = estate;
2947 myState->rel = intoRelationDesc;
2950 * We can skip WAL-logging the insertions, unless PITR is in use. We can
2951 * skip the FSM in any case.
2953 myState->hi_options = HEAP_INSERT_SKIP_FSM |
2954 (XLogArchivingActive() ? 0 : HEAP_INSERT_SKIP_WAL);
2955 myState->bistate = GetBulkInsertState();
2957 /* Not using WAL requires rd_targblock be initially invalid */
2958 Assert(intoRelationDesc->rd_targblock == InvalidBlockNumber);
2962 * CloseIntoRel --- clean up SELECT INTO at ExecutorEnd time
2965 CloseIntoRel(QueryDesc *queryDesc)
2967 DR_intorel *myState = (DR_intorel *) queryDesc->dest;
2969 /* OpenIntoRel might never have gotten called */
2970 if (myState && myState->pub.mydest == DestIntoRel && myState->rel)
2972 FreeBulkInsertState(myState->bistate);
2974 /* If we skipped using WAL, must heap_sync before commit */
2975 if (myState->hi_options & HEAP_INSERT_SKIP_WAL)
2976 heap_sync(myState->rel);
2978 /* close rel, but keep lock until commit */
2979 heap_close(myState->rel, NoLock);
2981 myState->rel = NULL;
2986 * CreateIntoRelDestReceiver -- create a suitable DestReceiver object
2989 CreateIntoRelDestReceiver(void)
2991 DR_intorel *self = (DR_intorel *) palloc0(sizeof(DR_intorel));
2993 self->pub.receiveSlot = intorel_receive;
2994 self->pub.rStartup = intorel_startup;
2995 self->pub.rShutdown = intorel_shutdown;
2996 self->pub.rDestroy = intorel_destroy;
2997 self->pub.mydest = DestIntoRel;
2999 /* private fields will be set by OpenIntoRel */
3001 return (DestReceiver *) self;
3005 * intorel_startup --- executor startup
3008 intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
3014 * intorel_receive --- receive one tuple
3017 intorel_receive(TupleTableSlot *slot, DestReceiver *self)
3019 DR_intorel *myState = (DR_intorel *) self;
3023 * get the heap tuple out of the tuple table slot, making sure we have a
3026 tuple = ExecMaterializeSlot(slot);
3029 * force assignment of new OID (see comments in ExecInsert)
3031 if (myState->rel->rd_rel->relhasoids)
3032 HeapTupleSetOid(tuple, InvalidOid);
3034 heap_insert(myState->rel,
3036 myState->estate->es_output_cid,
3037 myState->hi_options,
3040 /* We know this is a newly created relation, so there are no indexes */
3044 * intorel_shutdown --- executor end
3047 intorel_shutdown(DestReceiver *self)
3053 * intorel_destroy --- release DestReceiver object
3056 intorel_destroy(DestReceiver *self)