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
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 "optimizer/clauses.h"
49 #include "parser/parse_clause.h"
50 #include "parser/parsetree.h"
51 #include "storage/bufmgr.h"
52 #include "storage/lmgr.h"
53 #include "storage/smgr.h"
54 #include "utils/acl.h"
55 #include "utils/lsyscache.h"
56 #include "utils/memutils.h"
57 #include "utils/snapmgr.h"
58 #include "utils/tqual.h"
61 /* Hook for plugins to get control in ExecutorRun() */
62 ExecutorRun_hook_type ExecutorRun_hook
= NULL
;
64 typedef struct evalPlanQual
69 struct evalPlanQual
*next
; /* stack of active PlanQual plans */
70 struct evalPlanQual
*free
; /* list of free PlanQual plans */
73 /* decls for local routines only used within this module */
74 static void InitPlan(QueryDesc
*queryDesc
, int eflags
);
75 static void ExecEndPlan(PlanState
*planstate
, EState
*estate
);
76 static TupleTableSlot
*ExecutePlan(EState
*estate
, PlanState
*planstate
,
79 ScanDirection direction
,
81 static void ExecSelect(TupleTableSlot
*slot
,
82 DestReceiver
*dest
, EState
*estate
);
83 static void ExecInsert(TupleTableSlot
*slot
, ItemPointer tupleid
,
84 TupleTableSlot
*planSlot
,
85 DestReceiver
*dest
, EState
*estate
);
86 static void ExecDelete(ItemPointer tupleid
,
87 TupleTableSlot
*planSlot
,
88 DestReceiver
*dest
, EState
*estate
);
89 static void ExecUpdate(TupleTableSlot
*slot
, ItemPointer tupleid
,
90 TupleTableSlot
*planSlot
,
91 DestReceiver
*dest
, EState
*estate
);
92 static void ExecProcessReturning(ProjectionInfo
*projectReturning
,
93 TupleTableSlot
*tupleSlot
,
94 TupleTableSlot
*planSlot
,
96 static TupleTableSlot
*EvalPlanQualNext(EState
*estate
);
97 static void EndEvalPlanQual(EState
*estate
);
98 static void ExecCheckRTPerms(List
*rangeTable
);
99 static void ExecCheckRTEPerms(RangeTblEntry
*rte
);
100 static void ExecCheckXactReadOnly(PlannedStmt
*plannedstmt
);
101 static void EvalPlanQualStart(evalPlanQual
*epq
, EState
*estate
,
102 evalPlanQual
*priorepq
);
103 static void EvalPlanQualStop(evalPlanQual
*epq
);
104 static void OpenIntoRel(QueryDesc
*queryDesc
);
105 static void CloseIntoRel(QueryDesc
*queryDesc
);
106 static void intorel_startup(DestReceiver
*self
, int operation
, TupleDesc typeinfo
);
107 static void intorel_receive(TupleTableSlot
*slot
, DestReceiver
*self
);
108 static void intorel_shutdown(DestReceiver
*self
);
109 static void intorel_destroy(DestReceiver
*self
);
111 /* end of local decls */
114 /* ----------------------------------------------------------------
117 * This routine must be called at the beginning of any execution of any
120 * Takes a QueryDesc previously created by CreateQueryDesc (it's not real
121 * clear why we bother to separate the two functions, but...). The tupDesc
122 * field of the QueryDesc is filled in to describe the tuples that will be
123 * returned, and the internal fields (estate and planstate) are set up.
125 * eflags contains flag bits as described in executor.h.
127 * NB: the CurrentMemoryContext when this is called will become the parent
128 * of the per-query context used for this Executor invocation.
129 * ----------------------------------------------------------------
132 ExecutorStart(QueryDesc
*queryDesc
, int eflags
)
135 MemoryContext oldcontext
;
137 /* sanity checks: queryDesc must not be started already */
138 Assert(queryDesc
!= NULL
);
139 Assert(queryDesc
->estate
== NULL
);
142 * If the transaction is read-only, we need to check if any writes are
143 * planned to non-temporary tables. EXPLAIN is considered read-only.
145 if (XactReadOnly
&& !(eflags
& EXEC_FLAG_EXPLAIN_ONLY
))
146 ExecCheckXactReadOnly(queryDesc
->plannedstmt
);
149 * Build EState, switch into per-query memory context for startup.
151 estate
= CreateExecutorState();
152 queryDesc
->estate
= estate
;
154 oldcontext
= MemoryContextSwitchTo(estate
->es_query_cxt
);
157 * Fill in parameters, if any, from queryDesc
159 estate
->es_param_list_info
= queryDesc
->params
;
161 if (queryDesc
->plannedstmt
->nParamExec
> 0)
162 estate
->es_param_exec_vals
= (ParamExecData
*)
163 palloc0(queryDesc
->plannedstmt
->nParamExec
* sizeof(ParamExecData
));
166 * If non-read-only query, set the command ID to mark output tuples with
168 switch (queryDesc
->operation
)
171 /* SELECT INTO and SELECT FOR UPDATE/SHARE need to mark tuples */
172 if (queryDesc
->plannedstmt
->intoClause
!= NULL
||
173 queryDesc
->plannedstmt
->rowMarks
!= NIL
)
174 estate
->es_output_cid
= GetCurrentCommandId(true);
180 estate
->es_output_cid
= GetCurrentCommandId(true);
184 elog(ERROR
, "unrecognized operation code: %d",
185 (int) queryDesc
->operation
);
190 * Copy other important information into the EState
192 estate
->es_snapshot
= RegisterSnapshot(queryDesc
->snapshot
);
193 estate
->es_crosscheck_snapshot
= RegisterSnapshot(queryDesc
->crosscheck_snapshot
);
194 estate
->es_instrument
= queryDesc
->doInstrument
;
197 * Initialize the plan state tree
199 InitPlan(queryDesc
, eflags
);
201 MemoryContextSwitchTo(oldcontext
);
204 /* ----------------------------------------------------------------
207 * This is the main routine of the executor module. It accepts
208 * the query descriptor from the traffic cop and executes the
211 * ExecutorStart must have been called already.
213 * If direction is NoMovementScanDirection then nothing is done
214 * except to start up/shut down the destination. Otherwise,
215 * we retrieve up to 'count' tuples in the specified direction.
217 * Note: count = 0 is interpreted as no portal limit, i.e., run to
220 * We provide a function hook variable that lets loadable plugins
221 * get control when ExecutorRun is called. Such a plugin would
222 * normally call standard_ExecutorRun().
224 * ----------------------------------------------------------------
227 ExecutorRun(QueryDesc
*queryDesc
,
228 ScanDirection direction
, long count
)
230 TupleTableSlot
*result
;
232 if (ExecutorRun_hook
)
233 result
= (*ExecutorRun_hook
) (queryDesc
, direction
, count
);
235 result
= standard_ExecutorRun(queryDesc
, direction
, count
);
240 standard_ExecutorRun(QueryDesc
*queryDesc
,
241 ScanDirection direction
, long count
)
247 TupleTableSlot
*result
;
248 MemoryContext oldcontext
;
251 Assert(queryDesc
!= NULL
);
253 estate
= queryDesc
->estate
;
255 Assert(estate
!= NULL
);
258 * Switch into per-query memory context
260 oldcontext
= MemoryContextSwitchTo(estate
->es_query_cxt
);
263 * extract information from the query descriptor and the query feature.
265 operation
= queryDesc
->operation
;
266 dest
= queryDesc
->dest
;
269 * startup tuple receiver, if we will be emitting tuples
271 estate
->es_processed
= 0;
272 estate
->es_lastoid
= InvalidOid
;
274 sendTuples
= (operation
== CMD_SELECT
||
275 queryDesc
->plannedstmt
->returningLists
);
278 (*dest
->rStartup
) (dest
, operation
, queryDesc
->tupDesc
);
283 if (ScanDirectionIsNoMovement(direction
))
286 result
= ExecutePlan(estate
,
287 queryDesc
->planstate
,
294 * shutdown tuple receiver, if we started it
297 (*dest
->rShutdown
) (dest
);
299 MemoryContextSwitchTo(oldcontext
);
304 /* ----------------------------------------------------------------
307 * This routine must be called at the end of execution of any
309 * ----------------------------------------------------------------
312 ExecutorEnd(QueryDesc
*queryDesc
)
315 MemoryContext oldcontext
;
318 Assert(queryDesc
!= NULL
);
320 estate
= queryDesc
->estate
;
322 Assert(estate
!= NULL
);
325 * Switch into per-query memory context to run ExecEndPlan
327 oldcontext
= MemoryContextSwitchTo(estate
->es_query_cxt
);
329 ExecEndPlan(queryDesc
->planstate
, estate
);
332 * Close the SELECT INTO relation if any
334 if (estate
->es_select_into
)
335 CloseIntoRel(queryDesc
);
337 /* do away with our snapshots */
338 UnregisterSnapshot(estate
->es_snapshot
);
339 UnregisterSnapshot(estate
->es_crosscheck_snapshot
);
342 * Must switch out of context before destroying it
344 MemoryContextSwitchTo(oldcontext
);
347 * Release EState and per-query memory context. This should release
348 * everything the executor has allocated.
350 FreeExecutorState(estate
);
352 /* Reset queryDesc fields that no longer point to anything */
353 queryDesc
->tupDesc
= NULL
;
354 queryDesc
->estate
= NULL
;
355 queryDesc
->planstate
= NULL
;
358 /* ----------------------------------------------------------------
361 * This routine may be called on an open queryDesc to rewind it
363 * ----------------------------------------------------------------
366 ExecutorRewind(QueryDesc
*queryDesc
)
369 MemoryContext oldcontext
;
372 Assert(queryDesc
!= NULL
);
374 estate
= queryDesc
->estate
;
376 Assert(estate
!= NULL
);
378 /* It's probably not sensible to rescan updating queries */
379 Assert(queryDesc
->operation
== CMD_SELECT
);
382 * Switch into per-query memory context
384 oldcontext
= MemoryContextSwitchTo(estate
->es_query_cxt
);
389 ExecReScan(queryDesc
->planstate
, NULL
);
391 MemoryContextSwitchTo(oldcontext
);
397 * Check access permissions for all relations listed in a range table.
400 ExecCheckRTPerms(List
*rangeTable
)
404 foreach(l
, rangeTable
)
406 ExecCheckRTEPerms((RangeTblEntry
*) lfirst(l
));
412 * Check access permissions for a single RTE.
415 ExecCheckRTEPerms(RangeTblEntry
*rte
)
417 AclMode requiredPerms
;
422 * Only plain-relation RTEs need to be checked here. Function RTEs are
423 * checked by init_fcache when the function is prepared for execution.
424 * Join, subquery, and special RTEs need no checks.
426 if (rte
->rtekind
!= RTE_RELATION
)
430 * No work if requiredPerms is empty.
432 requiredPerms
= rte
->requiredPerms
;
433 if (requiredPerms
== 0)
439 * userid to check as: current user unless we have a setuid indication.
441 * Note: GetUserId() is presently fast enough that there's no harm in
442 * calling it separately for each RTE. If that stops being true, we could
443 * call it once in ExecCheckRTPerms and pass the userid down from there.
444 * But for now, no need for the extra clutter.
446 userid
= rte
->checkAsUser
? rte
->checkAsUser
: GetUserId();
449 * We must have *all* the requiredPerms bits, so use aclmask not aclcheck.
451 if (pg_class_aclmask(relOid
, userid
, requiredPerms
, ACLMASK_ALL
)
453 aclcheck_error(ACLCHECK_NO_PRIV
, ACL_KIND_CLASS
,
454 get_rel_name(relOid
));
458 * Check that the query does not imply any writes to non-temp tables.
461 ExecCheckXactReadOnly(PlannedStmt
*plannedstmt
)
466 * CREATE TABLE AS or SELECT INTO?
468 * XXX should we allow this if the destination is temp?
470 if (plannedstmt
->intoClause
!= NULL
)
473 /* Fail if write permissions are requested on any non-temp table */
474 foreach(l
, plannedstmt
->rtable
)
476 RangeTblEntry
*rte
= (RangeTblEntry
*) lfirst(l
);
478 if (rte
->rtekind
!= RTE_RELATION
)
481 if ((rte
->requiredPerms
& (~ACL_SELECT
)) == 0)
484 if (isTempNamespace(get_rel_namespace(rte
->relid
)))
494 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION
),
495 errmsg("transaction is read-only")));
499 /* ----------------------------------------------------------------
502 * Initializes the query plan: open files, allocate storage
503 * and start up the rule manager
504 * ----------------------------------------------------------------
507 InitPlan(QueryDesc
*queryDesc
, int eflags
)
509 CmdType operation
= queryDesc
->operation
;
510 PlannedStmt
*plannedstmt
= queryDesc
->plannedstmt
;
511 Plan
*plan
= plannedstmt
->planTree
;
512 List
*rangeTable
= plannedstmt
->rtable
;
513 EState
*estate
= queryDesc
->estate
;
514 PlanState
*planstate
;
520 * Do permissions checks
522 ExecCheckRTPerms(rangeTable
);
525 * initialize the node's execution state
527 estate
->es_range_table
= rangeTable
;
530 * initialize result relation stuff
532 if (plannedstmt
->resultRelations
)
534 List
*resultRelations
= plannedstmt
->resultRelations
;
535 int numResultRelations
= list_length(resultRelations
);
536 ResultRelInfo
*resultRelInfos
;
537 ResultRelInfo
*resultRelInfo
;
539 resultRelInfos
= (ResultRelInfo
*)
540 palloc(numResultRelations
* sizeof(ResultRelInfo
));
541 resultRelInfo
= resultRelInfos
;
542 foreach(l
, resultRelations
)
544 Index resultRelationIndex
= lfirst_int(l
);
545 Oid resultRelationOid
;
546 Relation resultRelation
;
548 resultRelationOid
= getrelid(resultRelationIndex
, rangeTable
);
549 resultRelation
= heap_open(resultRelationOid
, RowExclusiveLock
);
550 InitResultRelInfo(resultRelInfo
,
554 estate
->es_instrument
);
557 estate
->es_result_relations
= resultRelInfos
;
558 estate
->es_num_result_relations
= numResultRelations
;
559 /* Initialize to first or only result rel */
560 estate
->es_result_relation_info
= resultRelInfos
;
565 * if no result relation, then set state appropriately
567 estate
->es_result_relations
= NULL
;
568 estate
->es_num_result_relations
= 0;
569 estate
->es_result_relation_info
= NULL
;
573 * Detect whether we're doing SELECT INTO. If so, set the es_into_oids
574 * flag appropriately so that the plan tree will be initialized with the
575 * correct tuple descriptors. (Other SELECT INTO stuff comes later.)
577 estate
->es_select_into
= false;
578 if (operation
== CMD_SELECT
&& plannedstmt
->intoClause
!= NULL
)
580 estate
->es_select_into
= true;
581 estate
->es_into_oids
= interpretOidsOption(plannedstmt
->intoClause
->options
);
585 * Have to lock relations selected FOR UPDATE/FOR SHARE before we
586 * initialize the plan tree, else we'd be doing a lock upgrade. While we
587 * are at it, build the ExecRowMark list.
589 estate
->es_rowMarks
= NIL
;
590 foreach(l
, plannedstmt
->rowMarks
)
592 RowMarkClause
*rc
= (RowMarkClause
*) lfirst(l
);
593 Oid relid
= getrelid(rc
->rti
, rangeTable
);
597 relation
= heap_open(relid
, RowShareLock
);
598 erm
= (ExecRowMark
*) palloc(sizeof(ExecRowMark
));
599 erm
->relation
= relation
;
601 erm
->forUpdate
= rc
->forUpdate
;
602 erm
->noWait
= rc
->noWait
;
603 /* We'll set up ctidAttno below */
604 erm
->ctidAttNo
= InvalidAttrNumber
;
605 estate
->es_rowMarks
= lappend(estate
->es_rowMarks
, erm
);
609 * Initialize the executor "tuple" table. We need slots for all the plan
610 * nodes, plus possibly output slots for the junkfilter(s). At this point
611 * we aren't sure if we need junkfilters, so just add slots for them
612 * unconditionally. Also, if it's not a SELECT, set up a slot for use for
613 * trigger output tuples. Also, one for RETURNING-list evaluation.
618 /* Slots for the main plan tree */
619 nSlots
= ExecCountSlotsNode(plan
);
620 /* Add slots for subplans and initplans */
621 foreach(l
, plannedstmt
->subplans
)
623 Plan
*subplan
= (Plan
*) lfirst(l
);
625 nSlots
+= ExecCountSlotsNode(subplan
);
627 /* Add slots for junkfilter(s) */
628 if (plannedstmt
->resultRelations
!= NIL
)
629 nSlots
+= list_length(plannedstmt
->resultRelations
);
632 if (operation
!= CMD_SELECT
)
633 nSlots
++; /* for es_trig_tuple_slot */
634 if (plannedstmt
->returningLists
)
635 nSlots
++; /* for RETURNING projection */
637 estate
->es_tupleTable
= ExecCreateTupleTable(nSlots
);
639 if (operation
!= CMD_SELECT
)
640 estate
->es_trig_tuple_slot
=
641 ExecAllocTableSlot(estate
->es_tupleTable
);
644 /* mark EvalPlanQual not active */
645 estate
->es_plannedstmt
= plannedstmt
;
646 estate
->es_evalPlanQual
= NULL
;
647 estate
->es_evTupleNull
= NULL
;
648 estate
->es_evTuple
= NULL
;
649 estate
->es_useEvalPlan
= false;
652 * Initialize private state information for each SubPlan. We must do this
653 * before running ExecInitNode on the main query tree, since
654 * ExecInitSubPlan expects to be able to find these entries.
656 Assert(estate
->es_subplanstates
== NIL
);
657 i
= 1; /* subplan indices count from 1 */
658 foreach(l
, plannedstmt
->subplans
)
660 Plan
*subplan
= (Plan
*) lfirst(l
);
661 PlanState
*subplanstate
;
665 * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
666 * it is a parameterless subplan (not initplan), we suggest that it be
667 * prepared to handle REWIND efficiently; otherwise there is no need.
669 sp_eflags
= eflags
& EXEC_FLAG_EXPLAIN_ONLY
;
670 if (bms_is_member(i
, plannedstmt
->rewindPlanIDs
))
671 sp_eflags
|= EXEC_FLAG_REWIND
;
673 subplanstate
= ExecInitNode(subplan
, estate
, sp_eflags
);
675 estate
->es_subplanstates
= lappend(estate
->es_subplanstates
,
682 * Initialize the private state information for all the nodes in the query
683 * tree. This opens files, allocates storage and leaves us ready to start
686 planstate
= ExecInitNode(plan
, estate
, eflags
);
689 * Get the tuple descriptor describing the type of tuples to return. (this
690 * is especially important if we are creating a relation with "SELECT
693 tupType
= ExecGetResultType(planstate
);
696 * Initialize the junk filter if needed. SELECT and INSERT queries need a
697 * filter if there are any junk attrs in the tlist. INSERT and SELECT
698 * INTO also need a filter if the plan may return raw disk tuples (else
699 * heap_insert will be scribbling on the source relation!). UPDATE and
700 * DELETE always need a filter, since there's always a junk 'ctid'
701 * attribute present --- no need to look first.
704 bool junk_filter_needed
= false;
711 foreach(tlist
, plan
->targetlist
)
713 TargetEntry
*tle
= (TargetEntry
*) lfirst(tlist
);
717 junk_filter_needed
= true;
721 if (!junk_filter_needed
&&
722 (operation
== CMD_INSERT
|| estate
->es_select_into
) &&
723 ExecMayReturnRawTuples(planstate
))
724 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 j
= ExecInitJunkFilter(subplan
->plan
->targetlist
,
761 resultRelInfo
->ri_RelationDesc
->rd_att
->tdhasoid
,
762 ExecAllocTableSlot(estate
->es_tupleTable
));
765 * Since it must be UPDATE/DELETE, there had better be a
766 * "ctid" junk attribute in the tlist ... but ctid could
767 * be at a different resno for each result relation. We
768 * look up the ctid resnos now and save them in the
771 j
->jf_junkAttNo
= ExecFindJunkAttribute(j
, "ctid");
772 if (!AttributeNumberIsValid(j
->jf_junkAttNo
))
773 elog(ERROR
, "could not find junk ctid column");
774 resultRelInfo
->ri_junkFilter
= j
;
779 * Set active junkfilter too; at this point ExecInitAppend has
780 * already selected an active result relation...
782 estate
->es_junkFilter
=
783 estate
->es_result_relation_info
->ri_junkFilter
;
786 * We currently can't support rowmarks in this case, because
787 * the associated junk CTIDs might have different resnos in
788 * different subplans.
790 if (estate
->es_rowMarks
)
792 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
793 errmsg("SELECT FOR UPDATE/SHARE is not supported within a query with multiple result relations")));
797 /* Normal case with just one JunkFilter */
800 j
= ExecInitJunkFilter(planstate
->plan
->targetlist
,
802 ExecAllocTableSlot(estate
->es_tupleTable
));
803 estate
->es_junkFilter
= j
;
804 if (estate
->es_result_relation_info
)
805 estate
->es_result_relation_info
->ri_junkFilter
= j
;
807 if (operation
== CMD_SELECT
)
809 /* For SELECT, want to return the cleaned tuple type */
810 tupType
= j
->jf_cleanTupType
;
812 else if (operation
== CMD_UPDATE
|| operation
== CMD_DELETE
)
814 /* For UPDATE/DELETE, find the ctid junk attr now */
815 j
->jf_junkAttNo
= ExecFindJunkAttribute(j
, "ctid");
816 if (!AttributeNumberIsValid(j
->jf_junkAttNo
))
817 elog(ERROR
, "could not find junk ctid column");
820 /* For SELECT FOR UPDATE/SHARE, find the ctid attrs now */
821 foreach(l
, estate
->es_rowMarks
)
823 ExecRowMark
*erm
= (ExecRowMark
*) lfirst(l
);
826 snprintf(resname
, sizeof(resname
), "ctid%u", erm
->rti
);
827 erm
->ctidAttNo
= ExecFindJunkAttribute(j
, resname
);
828 if (!AttributeNumberIsValid(erm
->ctidAttNo
))
829 elog(ERROR
, "could not find junk \"%s\" column",
836 estate
->es_junkFilter
= NULL
;
837 if (estate
->es_rowMarks
)
838 elog(ERROR
, "SELECT FOR UPDATE/SHARE, but no junk columns");
843 * Initialize RETURNING projections if needed.
845 if (plannedstmt
->returningLists
)
847 TupleTableSlot
*slot
;
848 ExprContext
*econtext
;
849 ResultRelInfo
*resultRelInfo
;
852 * We set QueryDesc.tupDesc to be the RETURNING rowtype in this case.
853 * We assume all the sublists will generate the same output tupdesc.
855 tupType
= ExecTypeFromTL((List
*) linitial(plannedstmt
->returningLists
),
858 /* Set up a slot for the output of the RETURNING projection(s) */
859 slot
= ExecAllocTableSlot(estate
->es_tupleTable
);
860 ExecSetSlotDescriptor(slot
, tupType
);
861 /* Need an econtext too */
862 econtext
= CreateExprContext(estate
);
865 * Build a projection for each result rel. Note that any SubPlans in
866 * the RETURNING lists get attached to the topmost plan node.
868 Assert(list_length(plannedstmt
->returningLists
) == estate
->es_num_result_relations
);
869 resultRelInfo
= estate
->es_result_relations
;
870 foreach(l
, plannedstmt
->returningLists
)
872 List
*rlist
= (List
*) lfirst(l
);
875 rliststate
= (List
*) ExecInitExpr((Expr
*) rlist
, planstate
);
876 resultRelInfo
->ri_projectReturning
=
877 ExecBuildProjectionInfo(rliststate
, econtext
, slot
,
878 resultRelInfo
->ri_RelationDesc
->rd_att
);
883 queryDesc
->tupDesc
= tupType
;
884 queryDesc
->planstate
= planstate
;
887 * If doing SELECT INTO, initialize the "into" relation. We must wait
888 * till now so we have the "clean" result tuple type to create the new
891 * If EXPLAIN, skip creating the "into" relation.
893 if (estate
->es_select_into
&& !(eflags
& EXEC_FLAG_EXPLAIN_ONLY
))
894 OpenIntoRel(queryDesc
);
898 * Initialize ResultRelInfo data for one result relation
901 InitResultRelInfo(ResultRelInfo
*resultRelInfo
,
902 Relation resultRelationDesc
,
903 Index resultRelationIndex
,
908 * Check valid relkind ... parser and/or planner should have noticed this
909 * already, but let's make sure.
911 switch (resultRelationDesc
->rd_rel
->relkind
)
913 case RELKIND_RELATION
:
916 case RELKIND_SEQUENCE
:
918 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
919 errmsg("cannot change sequence \"%s\"",
920 RelationGetRelationName(resultRelationDesc
))));
922 case RELKIND_TOASTVALUE
:
924 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
925 errmsg("cannot change TOAST relation \"%s\"",
926 RelationGetRelationName(resultRelationDesc
))));
930 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
931 errmsg("cannot change view \"%s\"",
932 RelationGetRelationName(resultRelationDesc
))));
936 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
937 errmsg("cannot change relation \"%s\"",
938 RelationGetRelationName(resultRelationDesc
))));
942 /* OK, fill in the node */
943 MemSet(resultRelInfo
, 0, sizeof(ResultRelInfo
));
944 resultRelInfo
->type
= T_ResultRelInfo
;
945 resultRelInfo
->ri_RangeTableIndex
= resultRelationIndex
;
946 resultRelInfo
->ri_RelationDesc
= resultRelationDesc
;
947 resultRelInfo
->ri_NumIndices
= 0;
948 resultRelInfo
->ri_IndexRelationDescs
= NULL
;
949 resultRelInfo
->ri_IndexRelationInfo
= NULL
;
950 /* make a copy so as not to depend on relcache info not changing... */
951 resultRelInfo
->ri_TrigDesc
= CopyTriggerDesc(resultRelationDesc
->trigdesc
);
952 if (resultRelInfo
->ri_TrigDesc
)
954 int n
= resultRelInfo
->ri_TrigDesc
->numtriggers
;
956 resultRelInfo
->ri_TrigFunctions
= (FmgrInfo
*)
957 palloc0(n
* sizeof(FmgrInfo
));
959 resultRelInfo
->ri_TrigInstrument
= InstrAlloc(n
);
961 resultRelInfo
->ri_TrigInstrument
= NULL
;
965 resultRelInfo
->ri_TrigFunctions
= NULL
;
966 resultRelInfo
->ri_TrigInstrument
= NULL
;
968 resultRelInfo
->ri_ConstraintExprs
= NULL
;
969 resultRelInfo
->ri_junkFilter
= NULL
;
970 resultRelInfo
->ri_projectReturning
= NULL
;
973 * If there are indices on the result relation, open them and save
974 * descriptors in the result relation info, so that we can add new index
975 * entries for the tuples we add/update. We need not do this for a
976 * DELETE, however, since deletion doesn't affect indexes.
978 if (resultRelationDesc
->rd_rel
->relhasindex
&&
979 operation
!= CMD_DELETE
)
980 ExecOpenIndices(resultRelInfo
);
984 * ExecGetTriggerResultRel
986 * Get a ResultRelInfo for a trigger target relation. Most of the time,
987 * triggers are fired on one of the result relations of the query, and so
988 * we can just return a member of the es_result_relations array. (Note: in
989 * self-join situations there might be multiple members with the same OID;
990 * if so it doesn't matter which one we pick.) However, it is sometimes
991 * necessary to fire triggers on other relations; this happens mainly when an
992 * RI update trigger queues additional triggers on other relations, which will
993 * be processed in the context of the outer query. For efficiency's sake,
994 * we want to have a ResultRelInfo for those triggers too; that can avoid
995 * repeated re-opening of the relation. (It also provides a way for EXPLAIN
996 * ANALYZE to report the runtimes of such triggers.) So we make additional
997 * ResultRelInfo's as needed, and save them in es_trig_target_relations.
1000 ExecGetTriggerResultRel(EState
*estate
, Oid relid
)
1002 ResultRelInfo
*rInfo
;
1006 MemoryContext oldcontext
;
1008 /* First, search through the query result relations */
1009 rInfo
= estate
->es_result_relations
;
1010 nr
= estate
->es_num_result_relations
;
1013 if (RelationGetRelid(rInfo
->ri_RelationDesc
) == relid
)
1018 /* Nope, but maybe we already made an extra ResultRelInfo for it */
1019 foreach(l
, estate
->es_trig_target_relations
)
1021 rInfo
= (ResultRelInfo
*) lfirst(l
);
1022 if (RelationGetRelid(rInfo
->ri_RelationDesc
) == relid
)
1025 /* Nope, so we need a new one */
1028 * Open the target relation's relcache entry. We assume that an
1029 * appropriate lock is still held by the backend from whenever the trigger
1030 * event got queued, so we need take no new lock here.
1032 rel
= heap_open(relid
, NoLock
);
1035 * Make the new entry in the right context. Currently, we don't need any
1036 * index information in ResultRelInfos used only for triggers, so tell
1037 * InitResultRelInfo it's a DELETE.
1039 oldcontext
= MemoryContextSwitchTo(estate
->es_query_cxt
);
1040 rInfo
= makeNode(ResultRelInfo
);
1041 InitResultRelInfo(rInfo
,
1043 0, /* dummy rangetable index */
1045 estate
->es_instrument
);
1046 estate
->es_trig_target_relations
=
1047 lappend(estate
->es_trig_target_relations
, rInfo
);
1048 MemoryContextSwitchTo(oldcontext
);
1054 * ExecContextForcesOids
1056 * This is pretty grotty: when doing INSERT, UPDATE, or SELECT INTO,
1057 * we need to ensure that result tuples have space for an OID iff they are
1058 * going to be stored into a relation that has OIDs. In other contexts
1059 * we are free to choose whether to leave space for OIDs in result tuples
1060 * (we generally don't want to, but we do if a physical-tlist optimization
1061 * is possible). This routine checks the plan context and returns TRUE if the
1062 * choice is forced, FALSE if the choice is not forced. In the TRUE case,
1063 * *hasoids is set to the required value.
1065 * One reason this is ugly is that all plan nodes in the plan tree will emit
1066 * tuples with space for an OID, though we really only need the topmost node
1067 * to do so. However, node types like Sort don't project new tuples but just
1068 * return their inputs, and in those cases the requirement propagates down
1069 * to the input node. Eventually we might make this code smart enough to
1070 * recognize how far down the requirement really goes, but for now we just
1071 * make all plan nodes do the same thing if the top level forces the choice.
1073 * We assume that estate->es_result_relation_info is already set up to
1074 * describe the target relation. Note that in an UPDATE that spans an
1075 * inheritance tree, some of the target relations may have OIDs and some not.
1076 * We have to make the decisions on a per-relation basis as we initialize
1077 * each of the child plans of the topmost Append plan.
1079 * SELECT INTO is even uglier, because we don't have the INTO relation's
1080 * descriptor available when this code runs; we have to look aside at a
1081 * flag set by InitPlan().
1084 ExecContextForcesOids(PlanState
*planstate
, bool *hasoids
)
1086 if (planstate
->state
->es_select_into
)
1088 *hasoids
= planstate
->state
->es_into_oids
;
1093 ResultRelInfo
*ri
= planstate
->state
->es_result_relation_info
;
1097 Relation rel
= ri
->ri_RelationDesc
;
1101 *hasoids
= rel
->rd_rel
->relhasoids
;
1110 /* ----------------------------------------------------------------
1113 * Cleans up the query plan -- closes files and frees up storage
1115 * NOTE: we are no longer very worried about freeing storage per se
1116 * in this code; FreeExecutorState should be guaranteed to release all
1117 * memory that needs to be released. What we are worried about doing
1118 * is closing relations and dropping buffer pins. Thus, for example,
1119 * tuple tables must be cleared or dropped to ensure pins are released.
1120 * ----------------------------------------------------------------
1123 ExecEndPlan(PlanState
*planstate
, EState
*estate
)
1125 ResultRelInfo
*resultRelInfo
;
1130 * shut down any PlanQual processing we were doing
1132 if (estate
->es_evalPlanQual
!= NULL
)
1133 EndEvalPlanQual(estate
);
1136 * shut down the node-type-specific query processing
1138 ExecEndNode(planstate
);
1143 foreach(l
, estate
->es_subplanstates
)
1145 PlanState
*subplanstate
= (PlanState
*) lfirst(l
);
1147 ExecEndNode(subplanstate
);
1151 * destroy the executor "tuple" table.
1153 ExecDropTupleTable(estate
->es_tupleTable
, true);
1154 estate
->es_tupleTable
= NULL
;
1157 * close the result relation(s) if any, but hold locks until xact commit.
1159 resultRelInfo
= estate
->es_result_relations
;
1160 for (i
= estate
->es_num_result_relations
; i
> 0; i
--)
1162 /* Close indices and then the relation itself */
1163 ExecCloseIndices(resultRelInfo
);
1164 heap_close(resultRelInfo
->ri_RelationDesc
, NoLock
);
1169 * likewise close any trigger target relations
1171 foreach(l
, estate
->es_trig_target_relations
)
1173 resultRelInfo
= (ResultRelInfo
*) lfirst(l
);
1174 /* Close indices and then the relation itself */
1175 ExecCloseIndices(resultRelInfo
);
1176 heap_close(resultRelInfo
->ri_RelationDesc
, NoLock
);
1180 * close any relations selected FOR UPDATE/FOR SHARE, again keeping locks
1182 foreach(l
, estate
->es_rowMarks
)
1184 ExecRowMark
*erm
= lfirst(l
);
1186 heap_close(erm
->relation
, NoLock
);
1190 /* ----------------------------------------------------------------
1193 * processes the query plan to retrieve 'numberTuples' tuples in the
1194 * direction specified.
1196 * Retrieves all tuples if numberTuples is 0
1198 * result is either a slot containing the last tuple in the case
1199 * of a SELECT or NULL otherwise.
1201 * Note: the ctid attribute is a 'junk' attribute that is removed before the
1203 * ----------------------------------------------------------------
1205 static TupleTableSlot
*
1206 ExecutePlan(EState
*estate
,
1207 PlanState
*planstate
,
1210 ScanDirection direction
,
1213 JunkFilter
*junkfilter
;
1214 TupleTableSlot
*planSlot
;
1215 TupleTableSlot
*slot
;
1216 ItemPointer tupleid
= NULL
;
1217 ItemPointerData tuple_ctid
;
1218 long current_tuple_count
;
1219 TupleTableSlot
*result
;
1222 * initialize local variables
1224 current_tuple_count
= 0;
1228 * Set the direction.
1230 estate
->es_direction
= direction
;
1233 * Process BEFORE EACH STATEMENT triggers
1238 ExecBSUpdateTriggers(estate
, estate
->es_result_relation_info
);
1241 ExecBSDeleteTriggers(estate
, estate
->es_result_relation_info
);
1244 ExecBSInsertTriggers(estate
, estate
->es_result_relation_info
);
1252 * Loop until we've processed the proper number of tuples from the plan.
1257 /* Reset the per-output-tuple exprcontext */
1258 ResetPerTupleExprContext(estate
);
1261 * Execute the plan and obtain a tuple
1264 if (estate
->es_useEvalPlan
)
1266 planSlot
= EvalPlanQualNext(estate
);
1267 if (TupIsNull(planSlot
))
1268 planSlot
= ExecProcNode(planstate
);
1271 planSlot
= ExecProcNode(planstate
);
1274 * if the tuple is null, then we assume there is nothing more to
1275 * process so we just return null...
1277 if (TupIsNull(planSlot
))
1285 * If we have a junk filter, then project a new tuple with the junk
1288 * Store this new "clean" tuple in the junkfilter's resultSlot.
1289 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1290 * because that tuple slot has the wrong descriptor.)
1292 * But first, extract all the junk information we need.
1294 if ((junkfilter
= estate
->es_junkFilter
) != NULL
)
1297 * Process any FOR UPDATE or FOR SHARE locking requested.
1299 if (estate
->es_rowMarks
!= NIL
)
1304 foreach(l
, estate
->es_rowMarks
)
1306 ExecRowMark
*erm
= lfirst(l
);
1309 HeapTupleData tuple
;
1311 ItemPointerData update_ctid
;
1312 TransactionId update_xmax
;
1313 TupleTableSlot
*newSlot
;
1314 LockTupleMode lockmode
;
1317 datum
= ExecGetJunkAttribute(slot
,
1320 /* shouldn't ever get a null result... */
1322 elog(ERROR
, "ctid is NULL");
1324 tuple
.t_self
= *((ItemPointer
) DatumGetPointer(datum
));
1327 lockmode
= LockTupleExclusive
;
1329 lockmode
= LockTupleShared
;
1331 test
= heap_lock_tuple(erm
->relation
, &tuple
, &buffer
,
1332 &update_ctid
, &update_xmax
,
1333 estate
->es_output_cid
,
1334 lockmode
, erm
->noWait
);
1335 ReleaseBuffer(buffer
);
1338 case HeapTupleSelfUpdated
:
1339 /* treat it as deleted; do not process */
1342 case HeapTupleMayBeUpdated
:
1345 case HeapTupleUpdated
:
1346 if (IsXactIsoLevelSerializable
)
1348 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE
),
1349 errmsg("could not serialize access due to concurrent update")));
1350 if (!ItemPointerEquals(&update_ctid
,
1353 /* updated, so look at updated version */
1354 newSlot
= EvalPlanQual(estate
,
1358 if (!TupIsNull(newSlot
))
1360 slot
= planSlot
= newSlot
;
1361 estate
->es_useEvalPlan
= true;
1367 * if tuple was deleted or PlanQual failed for
1368 * updated tuple - we must not return this tuple!
1373 elog(ERROR
, "unrecognized heap_lock_tuple status: %u",
1381 * extract the 'ctid' junk attribute.
1383 if (operation
== CMD_UPDATE
|| operation
== CMD_DELETE
)
1388 datum
= ExecGetJunkAttribute(slot
, junkfilter
->jf_junkAttNo
,
1390 /* shouldn't ever get a null result... */
1392 elog(ERROR
, "ctid is NULL");
1394 tupleid
= (ItemPointer
) DatumGetPointer(datum
);
1395 tuple_ctid
= *tupleid
; /* make sure we don't free the ctid!! */
1396 tupleid
= &tuple_ctid
;
1400 * Create a new "clean" tuple with all junk attributes removed. We
1401 * don't need to do this for DELETE, however (there will in fact
1402 * be no non-junk attributes in a DELETE!)
1404 if (operation
!= CMD_DELETE
)
1405 slot
= ExecFilterJunk(junkfilter
, slot
);
1409 * now that we have a tuple, do the appropriate thing with it.. either
1410 * return it to the user, add it to a relation someplace, delete it
1411 * from a relation, or modify some of its attributes.
1416 ExecSelect(slot
, dest
, estate
);
1421 ExecInsert(slot
, tupleid
, planSlot
, dest
, estate
);
1426 ExecDelete(tupleid
, planSlot
, dest
, estate
);
1431 ExecUpdate(slot
, tupleid
, planSlot
, dest
, estate
);
1436 elog(ERROR
, "unrecognized operation code: %d",
1443 * check our tuple count.. if we've processed the proper number then
1444 * quit, else loop again and process more tuples. Zero numberTuples
1447 current_tuple_count
++;
1448 if (numberTuples
&& numberTuples
== current_tuple_count
)
1453 * Process AFTER EACH STATEMENT triggers
1458 ExecASUpdateTriggers(estate
, estate
->es_result_relation_info
);
1461 ExecASDeleteTriggers(estate
, estate
->es_result_relation_info
);
1464 ExecASInsertTriggers(estate
, estate
->es_result_relation_info
);
1472 * here, result is either a slot containing a tuple in the case of a
1473 * SELECT or NULL otherwise.
1478 /* ----------------------------------------------------------------
1481 * SELECTs are easy.. we just pass the tuple to the appropriate
1483 * ----------------------------------------------------------------
1486 ExecSelect(TupleTableSlot
*slot
,
1490 (*dest
->receiveSlot
) (slot
, dest
);
1492 (estate
->es_processed
)++;
1495 /* ----------------------------------------------------------------
1498 * INSERTs are trickier.. we have to insert the tuple into
1499 * the base relation and insert appropriate tuples into the
1501 * ----------------------------------------------------------------
1504 ExecInsert(TupleTableSlot
*slot
,
1505 ItemPointer tupleid
,
1506 TupleTableSlot
*planSlot
,
1511 ResultRelInfo
*resultRelInfo
;
1512 Relation resultRelationDesc
;
1516 * get the heap tuple out of the tuple table slot, making sure we have a
1519 tuple
= ExecMaterializeSlot(slot
);
1522 * get information on the (current) result relation
1524 resultRelInfo
= estate
->es_result_relation_info
;
1525 resultRelationDesc
= resultRelInfo
->ri_RelationDesc
;
1527 /* BEFORE ROW INSERT Triggers */
1528 if (resultRelInfo
->ri_TrigDesc
&&
1529 resultRelInfo
->ri_TrigDesc
->n_before_row
[TRIGGER_EVENT_INSERT
] > 0)
1533 newtuple
= ExecBRInsertTriggers(estate
, resultRelInfo
, tuple
);
1535 if (newtuple
== NULL
) /* "do nothing" */
1538 if (newtuple
!= tuple
) /* modified by Trigger(s) */
1541 * Put the modified tuple into a slot for convenience of routines
1542 * below. We assume the tuple was allocated in per-tuple memory
1543 * context, and therefore will go away by itself. The tuple table
1544 * slot should not try to clear it.
1546 TupleTableSlot
*newslot
= estate
->es_trig_tuple_slot
;
1548 if (newslot
->tts_tupleDescriptor
!= slot
->tts_tupleDescriptor
)
1549 ExecSetSlotDescriptor(newslot
, slot
->tts_tupleDescriptor
);
1550 ExecStoreTuple(newtuple
, newslot
, InvalidBuffer
, false);
1557 * Check the constraints of the tuple
1559 if (resultRelationDesc
->rd_att
->constr
)
1560 ExecConstraints(resultRelInfo
, slot
, estate
);
1565 * Note: heap_insert returns the tid (location) of the new tuple in the
1568 newId
= heap_insert(resultRelationDesc
, tuple
,
1569 estate
->es_output_cid
,
1573 (estate
->es_processed
)++;
1574 estate
->es_lastoid
= newId
;
1575 setLastTid(&(tuple
->t_self
));
1578 * insert index entries for tuple
1580 if (resultRelInfo
->ri_NumIndices
> 0)
1581 ExecInsertIndexTuples(slot
, &(tuple
->t_self
), estate
, false);
1583 /* AFTER ROW INSERT Triggers */
1584 ExecARInsertTriggers(estate
, resultRelInfo
, tuple
);
1586 /* Process RETURNING if present */
1587 if (resultRelInfo
->ri_projectReturning
)
1588 ExecProcessReturning(resultRelInfo
->ri_projectReturning
,
1589 slot
, planSlot
, dest
);
1592 /* ----------------------------------------------------------------
1595 * DELETE is like UPDATE, except that we delete the tuple and no
1596 * index modifications are needed
1597 * ----------------------------------------------------------------
1600 ExecDelete(ItemPointer tupleid
,
1601 TupleTableSlot
*planSlot
,
1605 ResultRelInfo
*resultRelInfo
;
1606 Relation resultRelationDesc
;
1608 ItemPointerData update_ctid
;
1609 TransactionId update_xmax
;
1612 * get information on the (current) result relation
1614 resultRelInfo
= estate
->es_result_relation_info
;
1615 resultRelationDesc
= resultRelInfo
->ri_RelationDesc
;
1617 /* BEFORE ROW DELETE Triggers */
1618 if (resultRelInfo
->ri_TrigDesc
&&
1619 resultRelInfo
->ri_TrigDesc
->n_before_row
[TRIGGER_EVENT_DELETE
] > 0)
1623 dodelete
= ExecBRDeleteTriggers(estate
, resultRelInfo
, tupleid
);
1625 if (!dodelete
) /* "do nothing" */
1632 * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
1633 * the row to be deleted is visible to that snapshot, and throw a can't-
1634 * serialize error if not. This is a special-case behavior needed for
1635 * referential integrity updates in serializable transactions.
1638 result
= heap_delete(resultRelationDesc
, tupleid
,
1639 &update_ctid
, &update_xmax
,
1640 estate
->es_output_cid
,
1641 estate
->es_crosscheck_snapshot
,
1642 true /* wait for commit */ );
1645 case HeapTupleSelfUpdated
:
1646 /* already deleted by self; nothing to do */
1649 case HeapTupleMayBeUpdated
:
1652 case HeapTupleUpdated
:
1653 if (IsXactIsoLevelSerializable
)
1655 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE
),
1656 errmsg("could not serialize access due to concurrent update")));
1657 else if (!ItemPointerEquals(tupleid
, &update_ctid
))
1659 TupleTableSlot
*epqslot
;
1661 epqslot
= EvalPlanQual(estate
,
1662 resultRelInfo
->ri_RangeTableIndex
,
1665 if (!TupIsNull(epqslot
))
1667 *tupleid
= update_ctid
;
1671 /* tuple already deleted; nothing to do */
1675 elog(ERROR
, "unrecognized heap_delete status: %u", result
);
1680 (estate
->es_processed
)++;
1683 * Note: Normally one would think that we have to delete index tuples
1684 * associated with the heap tuple now...
1686 * ... but in POSTGRES, we have no need to do this because VACUUM will
1687 * take care of it later. We can't delete index tuples immediately
1688 * anyway, since the tuple is still visible to other transactions.
1691 /* AFTER ROW DELETE Triggers */
1692 ExecARDeleteTriggers(estate
, resultRelInfo
, tupleid
);
1694 /* Process RETURNING if present */
1695 if (resultRelInfo
->ri_projectReturning
)
1698 * We have to put the target tuple into a slot, which means first we
1699 * gotta fetch it. We can use the trigger tuple slot.
1701 TupleTableSlot
*slot
= estate
->es_trig_tuple_slot
;
1702 HeapTupleData deltuple
;
1705 deltuple
.t_self
= *tupleid
;
1706 if (!heap_fetch(resultRelationDesc
, SnapshotAny
,
1707 &deltuple
, &delbuffer
, false, NULL
))
1708 elog(ERROR
, "failed to fetch deleted tuple for DELETE RETURNING");
1710 if (slot
->tts_tupleDescriptor
!= RelationGetDescr(resultRelationDesc
))
1711 ExecSetSlotDescriptor(slot
, RelationGetDescr(resultRelationDesc
));
1712 ExecStoreTuple(&deltuple
, slot
, InvalidBuffer
, false);
1714 ExecProcessReturning(resultRelInfo
->ri_projectReturning
,
1715 slot
, planSlot
, dest
);
1717 ExecClearTuple(slot
);
1718 ReleaseBuffer(delbuffer
);
1722 /* ----------------------------------------------------------------
1725 * note: we can't run UPDATE queries with transactions
1726 * off because UPDATEs are actually INSERTs and our
1727 * scan will mistakenly loop forever, updating the tuple
1728 * it just inserted.. This should be fixed but until it
1729 * is, we don't want to get stuck in an infinite loop
1730 * which corrupts your database..
1731 * ----------------------------------------------------------------
1734 ExecUpdate(TupleTableSlot
*slot
,
1735 ItemPointer tupleid
,
1736 TupleTableSlot
*planSlot
,
1741 ResultRelInfo
*resultRelInfo
;
1742 Relation resultRelationDesc
;
1744 ItemPointerData update_ctid
;
1745 TransactionId update_xmax
;
1748 * abort the operation if not running transactions
1750 if (IsBootstrapProcessingMode())
1751 elog(ERROR
, "cannot UPDATE during bootstrap");
1754 * get the heap tuple out of the tuple table slot, making sure we have a
1757 tuple
= ExecMaterializeSlot(slot
);
1760 * get information on the (current) result relation
1762 resultRelInfo
= estate
->es_result_relation_info
;
1763 resultRelationDesc
= resultRelInfo
->ri_RelationDesc
;
1765 /* BEFORE ROW UPDATE Triggers */
1766 if (resultRelInfo
->ri_TrigDesc
&&
1767 resultRelInfo
->ri_TrigDesc
->n_before_row
[TRIGGER_EVENT_UPDATE
] > 0)
1771 newtuple
= ExecBRUpdateTriggers(estate
, resultRelInfo
,
1774 if (newtuple
== NULL
) /* "do nothing" */
1777 if (newtuple
!= tuple
) /* modified by Trigger(s) */
1780 * Put the modified tuple into a slot for convenience of routines
1781 * below. We assume the tuple was allocated in per-tuple memory
1782 * context, and therefore will go away by itself. The tuple table
1783 * slot should not try to clear it.
1785 TupleTableSlot
*newslot
= estate
->es_trig_tuple_slot
;
1787 if (newslot
->tts_tupleDescriptor
!= slot
->tts_tupleDescriptor
)
1788 ExecSetSlotDescriptor(newslot
, slot
->tts_tupleDescriptor
);
1789 ExecStoreTuple(newtuple
, newslot
, InvalidBuffer
, false);
1796 * Check the constraints of the tuple
1798 * If we generate a new candidate tuple after EvalPlanQual testing, we
1799 * must loop back here and recheck constraints. (We don't need to redo
1800 * triggers, however. If there are any BEFORE triggers then trigger.c
1801 * will have done heap_lock_tuple to lock the correct tuple, so there's no
1802 * need to do them again.)
1805 if (resultRelationDesc
->rd_att
->constr
)
1806 ExecConstraints(resultRelInfo
, slot
, estate
);
1809 * replace the heap tuple
1811 * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
1812 * the row to be updated is visible to that snapshot, and throw a can't-
1813 * serialize error if not. This is a special-case behavior needed for
1814 * referential integrity updates in serializable transactions.
1816 result
= heap_update(resultRelationDesc
, tupleid
, tuple
,
1817 &update_ctid
, &update_xmax
,
1818 estate
->es_output_cid
,
1819 estate
->es_crosscheck_snapshot
,
1820 true /* wait for commit */ );
1823 case HeapTupleSelfUpdated
:
1824 /* already deleted by self; nothing to do */
1827 case HeapTupleMayBeUpdated
:
1830 case HeapTupleUpdated
:
1831 if (IsXactIsoLevelSerializable
)
1833 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE
),
1834 errmsg("could not serialize access due to concurrent update")));
1835 else if (!ItemPointerEquals(tupleid
, &update_ctid
))
1837 TupleTableSlot
*epqslot
;
1839 epqslot
= EvalPlanQual(estate
,
1840 resultRelInfo
->ri_RangeTableIndex
,
1843 if (!TupIsNull(epqslot
))
1845 *tupleid
= update_ctid
;
1846 slot
= ExecFilterJunk(estate
->es_junkFilter
, epqslot
);
1847 tuple
= ExecMaterializeSlot(slot
);
1851 /* tuple already deleted; nothing to do */
1855 elog(ERROR
, "unrecognized heap_update status: %u", result
);
1860 (estate
->es_processed
)++;
1863 * Note: instead of having to update the old index tuples associated with
1864 * the heap tuple, all we do is form and insert new index tuples. This is
1865 * because UPDATEs are actually DELETEs and INSERTs, and index tuple
1866 * deletion is done later by VACUUM (see notes in ExecDelete). All we do
1867 * here is insert new index tuples. -cim 9/27/89
1871 * insert index entries for tuple
1873 * Note: heap_update returns the tid (location) of the new tuple in the
1876 * If it's a HOT update, we mustn't insert new index entries.
1878 if (resultRelInfo
->ri_NumIndices
> 0 && !HeapTupleIsHeapOnly(tuple
))
1879 ExecInsertIndexTuples(slot
, &(tuple
->t_self
), estate
, false);
1881 /* AFTER ROW UPDATE Triggers */
1882 ExecARUpdateTriggers(estate
, resultRelInfo
, tupleid
, tuple
);
1884 /* Process RETURNING if present */
1885 if (resultRelInfo
->ri_projectReturning
)
1886 ExecProcessReturning(resultRelInfo
->ri_projectReturning
,
1887 slot
, planSlot
, dest
);
1891 * ExecRelCheck --- check that tuple meets constraints for result relation
1894 ExecRelCheck(ResultRelInfo
*resultRelInfo
,
1895 TupleTableSlot
*slot
, EState
*estate
)
1897 Relation rel
= resultRelInfo
->ri_RelationDesc
;
1898 int ncheck
= rel
->rd_att
->constr
->num_check
;
1899 ConstrCheck
*check
= rel
->rd_att
->constr
->check
;
1900 ExprContext
*econtext
;
1901 MemoryContext oldContext
;
1906 * If first time through for this result relation, build expression
1907 * nodetrees for rel's constraint expressions. Keep them in the per-query
1908 * memory context so they'll survive throughout the query.
1910 if (resultRelInfo
->ri_ConstraintExprs
== NULL
)
1912 oldContext
= MemoryContextSwitchTo(estate
->es_query_cxt
);
1913 resultRelInfo
->ri_ConstraintExprs
=
1914 (List
**) palloc(ncheck
* sizeof(List
*));
1915 for (i
= 0; i
< ncheck
; i
++)
1917 /* ExecQual wants implicit-AND form */
1918 qual
= make_ands_implicit(stringToNode(check
[i
].ccbin
));
1919 resultRelInfo
->ri_ConstraintExprs
[i
] = (List
*)
1920 ExecPrepareExpr((Expr
*) qual
, estate
);
1922 MemoryContextSwitchTo(oldContext
);
1926 * We will use the EState's per-tuple context for evaluating constraint
1927 * expressions (creating it if it's not already there).
1929 econtext
= GetPerTupleExprContext(estate
);
1931 /* Arrange for econtext's scan tuple to be the tuple under test */
1932 econtext
->ecxt_scantuple
= slot
;
1934 /* And evaluate the constraints */
1935 for (i
= 0; i
< ncheck
; i
++)
1937 qual
= resultRelInfo
->ri_ConstraintExprs
[i
];
1940 * NOTE: SQL92 specifies that a NULL result from a constraint
1941 * expression is not to be treated as a failure. Therefore, tell
1942 * ExecQual to return TRUE for NULL.
1944 if (!ExecQual(qual
, econtext
, true))
1945 return check
[i
].ccname
;
1948 /* NULL result means no error */
1953 ExecConstraints(ResultRelInfo
*resultRelInfo
,
1954 TupleTableSlot
*slot
, EState
*estate
)
1956 Relation rel
= resultRelInfo
->ri_RelationDesc
;
1957 TupleConstr
*constr
= rel
->rd_att
->constr
;
1961 if (constr
->has_not_null
)
1963 int natts
= rel
->rd_att
->natts
;
1966 for (attrChk
= 1; attrChk
<= natts
; attrChk
++)
1968 if (rel
->rd_att
->attrs
[attrChk
- 1]->attnotnull
&&
1969 slot_attisnull(slot
, attrChk
))
1971 (errcode(ERRCODE_NOT_NULL_VIOLATION
),
1972 errmsg("null value in column \"%s\" violates not-null constraint",
1973 NameStr(rel
->rd_att
->attrs
[attrChk
- 1]->attname
))));
1977 if (constr
->num_check
> 0)
1981 if ((failed
= ExecRelCheck(resultRelInfo
, slot
, estate
)) != NULL
)
1983 (errcode(ERRCODE_CHECK_VIOLATION
),
1984 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1985 RelationGetRelationName(rel
), failed
)));
1990 * ExecProcessReturning --- evaluate a RETURNING list and send to dest
1992 * projectReturning: RETURNING projection info for current result rel
1993 * tupleSlot: slot holding tuple actually inserted/updated/deleted
1994 * planSlot: slot holding tuple returned by top plan node
1995 * dest: where to send the output
1998 ExecProcessReturning(ProjectionInfo
*projectReturning
,
1999 TupleTableSlot
*tupleSlot
,
2000 TupleTableSlot
*planSlot
,
2003 ExprContext
*econtext
= projectReturning
->pi_exprContext
;
2004 TupleTableSlot
*retSlot
;
2007 * Reset per-tuple memory context to free any expression evaluation
2008 * storage allocated in the previous cycle.
2010 ResetExprContext(econtext
);
2012 /* Make tuple and any needed join variables available to ExecProject */
2013 econtext
->ecxt_scantuple
= tupleSlot
;
2014 econtext
->ecxt_outertuple
= planSlot
;
2016 /* Compute the RETURNING expressions */
2017 retSlot
= ExecProject(projectReturning
, NULL
);
2020 (*dest
->receiveSlot
) (retSlot
, dest
);
2022 ExecClearTuple(retSlot
);
2026 * Check a modified tuple to see if we want to process its updated version
2027 * under READ COMMITTED rules.
2029 * See backend/executor/README for some info about how this works.
2031 * estate - executor state data
2032 * rti - rangetable index of table containing tuple
2033 * *tid - t_ctid from the outdated tuple (ie, next updated version)
2034 * priorXmax - t_xmax from the outdated tuple
2036 * *tid is also an output parameter: it's modified to hold the TID of the
2037 * latest version of the tuple (note this may be changed even on failure)
2039 * Returns a slot containing the new candidate update/delete tuple, or
2040 * NULL if we determine we shouldn't process the row.
2043 EvalPlanQual(EState
*estate
, Index rti
,
2044 ItemPointer tid
, TransactionId priorXmax
)
2049 HeapTupleData tuple
;
2050 HeapTuple copyTuple
= NULL
;
2051 SnapshotData SnapshotDirty
;
2057 * find relation containing target tuple
2059 if (estate
->es_result_relation_info
!= NULL
&&
2060 estate
->es_result_relation_info
->ri_RangeTableIndex
== rti
)
2061 relation
= estate
->es_result_relation_info
->ri_RelationDesc
;
2067 foreach(l
, estate
->es_rowMarks
)
2069 if (((ExecRowMark
*) lfirst(l
))->rti
== rti
)
2071 relation
= ((ExecRowMark
*) lfirst(l
))->relation
;
2075 if (relation
== NULL
)
2076 elog(ERROR
, "could not find RowMark for RT index %u", rti
);
2082 * Loop here to deal with updated or busy tuples
2084 InitDirtySnapshot(SnapshotDirty
);
2085 tuple
.t_self
= *tid
;
2090 if (heap_fetch(relation
, &SnapshotDirty
, &tuple
, &buffer
, true, NULL
))
2093 * If xmin isn't what we're expecting, the slot must have been
2094 * recycled and reused for an unrelated tuple. This implies that
2095 * the latest version of the row was deleted, so we need do
2096 * nothing. (Should be safe to examine xmin without getting
2097 * buffer's content lock, since xmin never changes in an existing
2100 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple
.t_data
),
2103 ReleaseBuffer(buffer
);
2107 /* otherwise xmin should not be dirty... */
2108 if (TransactionIdIsValid(SnapshotDirty
.xmin
))
2109 elog(ERROR
, "t_xmin is uncommitted in tuple to be updated");
2112 * If tuple is being updated by other transaction then we have to
2113 * wait for its commit/abort.
2115 if (TransactionIdIsValid(SnapshotDirty
.xmax
))
2117 ReleaseBuffer(buffer
);
2118 XactLockTableWait(SnapshotDirty
.xmax
);
2119 continue; /* loop back to repeat heap_fetch */
2123 * If tuple was inserted by our own transaction, we have to check
2124 * cmin against es_output_cid: cmin >= current CID means our
2125 * command cannot see the tuple, so we should ignore it. Without
2126 * this we are open to the "Halloween problem" of indefinitely
2127 * re-updating the same tuple. (We need not check cmax because
2128 * HeapTupleSatisfiesDirty will consider a tuple deleted by our
2129 * transaction dead, regardless of cmax.) We just checked that
2130 * priorXmax == xmin, so we can test that variable instead of
2131 * doing HeapTupleHeaderGetXmin again.
2133 if (TransactionIdIsCurrentTransactionId(priorXmax
) &&
2134 HeapTupleHeaderGetCmin(tuple
.t_data
) >= estate
->es_output_cid
)
2136 ReleaseBuffer(buffer
);
2141 * We got tuple - now copy it for use by recheck query.
2143 copyTuple
= heap_copytuple(&tuple
);
2144 ReleaseBuffer(buffer
);
2149 * If the referenced slot was actually empty, the latest version of
2150 * the row must have been deleted, so we need do nothing.
2152 if (tuple
.t_data
== NULL
)
2154 ReleaseBuffer(buffer
);
2159 * As above, if xmin isn't what we're expecting, do nothing.
2161 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple
.t_data
),
2164 ReleaseBuffer(buffer
);
2169 * If we get here, the tuple was found but failed SnapshotDirty.
2170 * Assuming the xmin is either a committed xact or our own xact (as it
2171 * certainly should be if we're trying to modify the tuple), this must
2172 * mean that the row was updated or deleted by either a committed xact
2173 * or our own xact. If it was deleted, we can ignore it; if it was
2174 * updated then chain up to the next version and repeat the whole
2177 * As above, it should be safe to examine xmax and t_ctid without the
2178 * buffer content lock, because they can't be changing.
2180 if (ItemPointerEquals(&tuple
.t_self
, &tuple
.t_data
->t_ctid
))
2182 /* deleted, so forget about it */
2183 ReleaseBuffer(buffer
);
2187 /* updated, so look at the updated row */
2188 tuple
.t_self
= tuple
.t_data
->t_ctid
;
2189 /* updated row should have xmin matching this xmax */
2190 priorXmax
= HeapTupleHeaderGetXmax(tuple
.t_data
);
2191 ReleaseBuffer(buffer
);
2192 /* loop back to fetch next in chain */
2196 * For UPDATE/DELETE we have to return tid of actual row we're executing
2199 *tid
= tuple
.t_self
;
2202 * Need to run a recheck subquery. Find or create a PQ stack entry.
2204 epq
= estate
->es_evalPlanQual
;
2207 if (epq
!= NULL
&& epq
->rti
== 0)
2209 /* Top PQ stack entry is idle, so re-use it */
2210 Assert(!(estate
->es_useEvalPlan
) && epq
->next
== NULL
);
2216 * If this is request for another RTE - Ra, - then we have to check wasn't
2217 * PlanQual requested for Ra already and if so then Ra' row was updated
2218 * again and we have to re-start old execution for Ra and forget all what
2219 * we done after Ra was suspended. Cool? -:))
2221 if (epq
!= NULL
&& epq
->rti
!= rti
&&
2222 epq
->estate
->es_evTuple
[rti
- 1] != NULL
)
2226 evalPlanQual
*oldepq
;
2228 /* stop execution */
2229 EvalPlanQualStop(epq
);
2230 /* pop previous PlanQual from the stack */
2232 Assert(oldepq
&& oldepq
->rti
!= 0);
2233 /* push current PQ to freePQ stack */
2236 estate
->es_evalPlanQual
= epq
;
2237 } while (epq
->rti
!= rti
);
2241 * If we are requested for another RTE then we have to suspend execution
2242 * of current PlanQual and start execution for new one.
2244 if (epq
== NULL
|| epq
->rti
!= rti
)
2246 /* try to reuse plan used previously */
2247 evalPlanQual
*newepq
= (epq
!= NULL
) ? epq
->free
: NULL
;
2249 if (newepq
== NULL
) /* first call or freePQ stack is empty */
2251 newepq
= (evalPlanQual
*) palloc0(sizeof(evalPlanQual
));
2252 newepq
->free
= NULL
;
2253 newepq
->estate
= NULL
;
2254 newepq
->planstate
= NULL
;
2258 /* recycle previously used PlanQual */
2259 Assert(newepq
->estate
== NULL
);
2262 /* push current PQ to the stack */
2265 estate
->es_evalPlanQual
= epq
;
2270 Assert(epq
->rti
== rti
);
2273 * Ok - we're requested for the same RTE. Unfortunately we still have to
2274 * end and restart execution of the plan, because ExecReScan wouldn't
2275 * ensure that upper plan nodes would reset themselves. We could make
2276 * that work if insertion of the target tuple were integrated with the
2277 * Param mechanism somehow, so that the upper plan nodes know that their
2278 * children's outputs have changed.
2280 * Note that the stack of free evalPlanQual nodes is quite useless at the
2281 * moment, since it only saves us from pallocing/releasing the
2282 * evalPlanQual nodes themselves. But it will be useful once we implement
2283 * ReScan instead of end/restart for re-using PlanQual nodes.
2287 /* stop execution */
2288 EvalPlanQualStop(epq
);
2292 * Initialize new recheck query.
2294 * Note: if we were re-using PlanQual plans via ExecReScan, we'd need to
2295 * instead copy down changeable state from the top plan (including
2296 * es_result_relation_info, es_junkFilter) and reset locally changeable
2297 * state in the epq (including es_param_exec_vals, es_evTupleNull).
2299 EvalPlanQualStart(epq
, estate
, epq
->next
);
2302 * free old RTE' tuple, if any, and store target tuple where relation's
2303 * scan node will see it
2305 epqstate
= epq
->estate
;
2306 if (epqstate
->es_evTuple
[rti
- 1] != NULL
)
2307 heap_freetuple(epqstate
->es_evTuple
[rti
- 1]);
2308 epqstate
->es_evTuple
[rti
- 1] = copyTuple
;
2310 return EvalPlanQualNext(estate
);
2313 static TupleTableSlot
*
2314 EvalPlanQualNext(EState
*estate
)
2316 evalPlanQual
*epq
= estate
->es_evalPlanQual
;
2317 MemoryContext oldcontext
;
2318 TupleTableSlot
*slot
;
2320 Assert(epq
->rti
!= 0);
2323 oldcontext
= MemoryContextSwitchTo(epq
->estate
->es_query_cxt
);
2324 slot
= ExecProcNode(epq
->planstate
);
2325 MemoryContextSwitchTo(oldcontext
);
2328 * No more tuples for this PQ. Continue previous one.
2330 if (TupIsNull(slot
))
2332 evalPlanQual
*oldepq
;
2334 /* stop execution */
2335 EvalPlanQualStop(epq
);
2336 /* pop old PQ from the stack */
2340 /* this is the first (oldest) PQ - mark as free */
2342 estate
->es_useEvalPlan
= false;
2343 /* and continue Query execution */
2346 Assert(oldepq
->rti
!= 0);
2347 /* push current PQ to freePQ stack */
2350 estate
->es_evalPlanQual
= epq
;
2358 EndEvalPlanQual(EState
*estate
)
2360 evalPlanQual
*epq
= estate
->es_evalPlanQual
;
2362 if (epq
->rti
== 0) /* plans already shutdowned */
2364 Assert(epq
->next
== NULL
);
2370 evalPlanQual
*oldepq
;
2372 /* stop execution */
2373 EvalPlanQualStop(epq
);
2374 /* pop old PQ from the stack */
2378 /* this is the first (oldest) PQ - mark as free */
2380 estate
->es_useEvalPlan
= false;
2383 Assert(oldepq
->rti
!= 0);
2384 /* push current PQ to freePQ stack */
2387 estate
->es_evalPlanQual
= epq
;
2392 * Start execution of one level of PlanQual.
2394 * This is a cut-down version of ExecutorStart(): we copy some state from
2395 * the top-level estate rather than initializing it fresh.
2398 EvalPlanQualStart(evalPlanQual
*epq
, EState
*estate
, evalPlanQual
*priorepq
)
2402 MemoryContext oldcontext
;
2405 rtsize
= list_length(estate
->es_range_table
);
2407 epq
->estate
= epqstate
= CreateExecutorState();
2409 oldcontext
= MemoryContextSwitchTo(epqstate
->es_query_cxt
);
2412 * The epqstates share the top query's copy of unchanging state such as
2413 * the snapshot, rangetable, result-rel info, and external Param info.
2414 * They need their own copies of local state, including a tuple table,
2415 * es_param_exec_vals, etc.
2417 epqstate
->es_direction
= ForwardScanDirection
;
2418 epqstate
->es_snapshot
= estate
->es_snapshot
;
2419 epqstate
->es_crosscheck_snapshot
= estate
->es_crosscheck_snapshot
;
2420 epqstate
->es_range_table
= estate
->es_range_table
;
2421 epqstate
->es_output_cid
= estate
->es_output_cid
;
2422 epqstate
->es_result_relations
= estate
->es_result_relations
;
2423 epqstate
->es_num_result_relations
= estate
->es_num_result_relations
;
2424 epqstate
->es_result_relation_info
= estate
->es_result_relation_info
;
2425 epqstate
->es_junkFilter
= estate
->es_junkFilter
;
2426 /* es_trig_target_relations must NOT be copied */
2427 epqstate
->es_into_relation_descriptor
= estate
->es_into_relation_descriptor
;
2428 epqstate
->es_into_relation_use_wal
= estate
->es_into_relation_use_wal
;
2429 epqstate
->es_param_list_info
= estate
->es_param_list_info
;
2430 if (estate
->es_plannedstmt
->nParamExec
> 0)
2431 epqstate
->es_param_exec_vals
= (ParamExecData
*)
2432 palloc0(estate
->es_plannedstmt
->nParamExec
* sizeof(ParamExecData
));
2433 epqstate
->es_rowMarks
= estate
->es_rowMarks
;
2434 epqstate
->es_instrument
= estate
->es_instrument
;
2435 epqstate
->es_select_into
= estate
->es_select_into
;
2436 epqstate
->es_into_oids
= estate
->es_into_oids
;
2437 epqstate
->es_plannedstmt
= estate
->es_plannedstmt
;
2440 * Each epqstate must have its own es_evTupleNull state, but all the stack
2441 * entries share es_evTuple state. This allows sub-rechecks to inherit
2442 * the value being examined by an outer recheck.
2444 epqstate
->es_evTupleNull
= (bool *) palloc0(rtsize
* sizeof(bool));
2445 if (priorepq
== NULL
)
2446 /* first PQ stack entry */
2447 epqstate
->es_evTuple
= (HeapTuple
*)
2448 palloc0(rtsize
* sizeof(HeapTuple
));
2450 /* later stack entries share the same storage */
2451 epqstate
->es_evTuple
= priorepq
->estate
->es_evTuple
;
2454 * Create sub-tuple-table; we needn't redo the CountSlots work though.
2456 epqstate
->es_tupleTable
=
2457 ExecCreateTupleTable(estate
->es_tupleTable
->size
);
2460 * Initialize private state information for each SubPlan. We must do this
2461 * before running ExecInitNode on the main query tree, since
2462 * ExecInitSubPlan expects to be able to find these entries.
2464 Assert(epqstate
->es_subplanstates
== NIL
);
2465 foreach(l
, estate
->es_plannedstmt
->subplans
)
2467 Plan
*subplan
= (Plan
*) lfirst(l
);
2468 PlanState
*subplanstate
;
2470 subplanstate
= ExecInitNode(subplan
, epqstate
, 0);
2472 epqstate
->es_subplanstates
= lappend(epqstate
->es_subplanstates
,
2477 * Initialize the private state information for all the nodes in the query
2478 * tree. This opens files, allocates storage and leaves us ready to start
2479 * processing tuples.
2481 epq
->planstate
= ExecInitNode(estate
->es_plannedstmt
->planTree
, epqstate
, 0);
2483 MemoryContextSwitchTo(oldcontext
);
2487 * End execution of one level of PlanQual.
2489 * This is a cut-down version of ExecutorEnd(); basically we want to do most
2490 * of the normal cleanup, but *not* close result relations (which we are
2491 * just sharing from the outer query). We do, however, have to close any
2492 * trigger target relations that got opened, since those are not shared.
2495 EvalPlanQualStop(evalPlanQual
*epq
)
2497 EState
*epqstate
= epq
->estate
;
2498 MemoryContext oldcontext
;
2501 oldcontext
= MemoryContextSwitchTo(epqstate
->es_query_cxt
);
2503 ExecEndNode(epq
->planstate
);
2505 foreach(l
, epqstate
->es_subplanstates
)
2507 PlanState
*subplanstate
= (PlanState
*) lfirst(l
);
2509 ExecEndNode(subplanstate
);
2512 ExecDropTupleTable(epqstate
->es_tupleTable
, true);
2513 epqstate
->es_tupleTable
= NULL
;
2515 if (epqstate
->es_evTuple
[epq
->rti
- 1] != NULL
)
2517 heap_freetuple(epqstate
->es_evTuple
[epq
->rti
- 1]);
2518 epqstate
->es_evTuple
[epq
->rti
- 1] = NULL
;
2521 foreach(l
, epqstate
->es_trig_target_relations
)
2523 ResultRelInfo
*resultRelInfo
= (ResultRelInfo
*) lfirst(l
);
2525 /* Close indices and then the relation itself */
2526 ExecCloseIndices(resultRelInfo
);
2527 heap_close(resultRelInfo
->ri_RelationDesc
, NoLock
);
2530 MemoryContextSwitchTo(oldcontext
);
2532 FreeExecutorState(epqstate
);
2535 epq
->planstate
= NULL
;
2539 * ExecGetActivePlanTree --- get the active PlanState tree from a QueryDesc
2541 * Ordinarily this is just the one mentioned in the QueryDesc, but if we
2542 * are looking at a row returned by the EvalPlanQual machinery, we need
2543 * to look at the subsidiary state instead.
2546 ExecGetActivePlanTree(QueryDesc
*queryDesc
)
2548 EState
*estate
= queryDesc
->estate
;
2550 if (estate
&& estate
->es_useEvalPlan
&& estate
->es_evalPlanQual
!= NULL
)
2551 return estate
->es_evalPlanQual
->planstate
;
2553 return queryDesc
->planstate
;
2558 * Support for SELECT INTO (a/k/a CREATE TABLE AS)
2560 * We implement SELECT INTO by diverting SELECT's normal output with
2561 * a specialized DestReceiver type.
2563 * TODO: remove some of the INTO-specific cruft from EState, and keep
2564 * it in the DestReceiver instead.
2569 DestReceiver pub
; /* publicly-known function pointers */
2570 EState
*estate
; /* EState we are working with */
2574 * OpenIntoRel --- actually create the SELECT INTO target relation
2576 * This also replaces QueryDesc->dest with the special DestReceiver for
2577 * SELECT INTO. We assume that the correct result tuple type has already
2578 * been placed in queryDesc->tupDesc.
2581 OpenIntoRel(QueryDesc
*queryDesc
)
2583 IntoClause
*into
= queryDesc
->plannedstmt
->intoClause
;
2584 EState
*estate
= queryDesc
->estate
;
2585 Relation intoRelationDesc
;
2590 AclResult aclresult
;
2593 DR_intorel
*myState
;
2598 * Check consistency of arguments
2600 if (into
->onCommit
!= ONCOMMIT_NOOP
&& !into
->rel
->istemp
)
2602 (errcode(ERRCODE_INVALID_TABLE_DEFINITION
),
2603 errmsg("ON COMMIT can only be used on temporary tables")));
2606 * Find namespace to create in, check its permissions
2608 intoName
= into
->rel
->relname
;
2609 namespaceId
= RangeVarGetCreationNamespace(into
->rel
);
2611 aclresult
= pg_namespace_aclcheck(namespaceId
, GetUserId(),
2613 if (aclresult
!= ACLCHECK_OK
)
2614 aclcheck_error(aclresult
, ACL_KIND_NAMESPACE
,
2615 get_namespace_name(namespaceId
));
2618 * Select tablespace to use. If not specified, use default tablespace
2619 * (which may in turn default to database's default).
2621 if (into
->tableSpaceName
)
2623 tablespaceId
= get_tablespace_oid(into
->tableSpaceName
);
2624 if (!OidIsValid(tablespaceId
))
2626 (errcode(ERRCODE_UNDEFINED_OBJECT
),
2627 errmsg("tablespace \"%s\" does not exist",
2628 into
->tableSpaceName
)));
2632 tablespaceId
= GetDefaultTablespace(into
->rel
->istemp
);
2633 /* note InvalidOid is OK in this case */
2636 /* Check permissions except when using the database's default space */
2637 if (OidIsValid(tablespaceId
) && tablespaceId
!= MyDatabaseTableSpace
)
2639 AclResult aclresult
;
2641 aclresult
= pg_tablespace_aclcheck(tablespaceId
, GetUserId(),
2644 if (aclresult
!= ACLCHECK_OK
)
2645 aclcheck_error(aclresult
, ACL_KIND_TABLESPACE
,
2646 get_tablespace_name(tablespaceId
));
2649 /* Parse and validate any reloptions */
2650 reloptions
= transformRelOptions((Datum
) 0,
2654 (void) heap_reloptions(RELKIND_RELATION
, reloptions
, true);
2656 /* Copy the tupdesc because heap_create_with_catalog modifies it */
2657 tupdesc
= CreateTupleDescCopy(queryDesc
->tupDesc
);
2659 /* Now we can actually create the new relation */
2660 intoRelationId
= heap_create_with_catalog(intoName
,
2673 allowSystemTableMods
);
2675 FreeTupleDesc(tupdesc
);
2678 * Advance command counter so that the newly-created relation's catalog
2679 * tuples will be visible to heap_open.
2681 CommandCounterIncrement();
2684 * If necessary, create a TOAST table for the INTO relation. Note that
2685 * AlterTableCreateToastTable ends with CommandCounterIncrement(), so that
2686 * the TOAST table will be visible for insertion.
2688 AlterTableCreateToastTable(intoRelationId
);
2691 * And open the constructed table for writing.
2693 intoRelationDesc
= heap_open(intoRelationId
, AccessExclusiveLock
);
2695 /* use_wal off requires rd_targblock be initially invalid */
2696 Assert(intoRelationDesc
->rd_targblock
== InvalidBlockNumber
);
2699 * We can skip WAL-logging the insertions, unless PITR is in use.
2701 estate
->es_into_relation_use_wal
= XLogArchivingActive();
2702 estate
->es_into_relation_descriptor
= intoRelationDesc
;
2705 * Now replace the query's DestReceiver with one for SELECT INTO
2707 queryDesc
->dest
= CreateDestReceiver(DestIntoRel
, NULL
);
2708 myState
= (DR_intorel
*) queryDesc
->dest
;
2709 Assert(myState
->pub
.mydest
== DestIntoRel
);
2710 myState
->estate
= estate
;
2714 * CloseIntoRel --- clean up SELECT INTO at ExecutorEnd time
2717 CloseIntoRel(QueryDesc
*queryDesc
)
2719 EState
*estate
= queryDesc
->estate
;
2721 /* OpenIntoRel might never have gotten called */
2722 if (estate
->es_into_relation_descriptor
)
2724 /* If we skipped using WAL, must heap_sync before commit */
2725 if (!estate
->es_into_relation_use_wal
)
2726 heap_sync(estate
->es_into_relation_descriptor
);
2728 /* close rel, but keep lock until commit */
2729 heap_close(estate
->es_into_relation_descriptor
, NoLock
);
2731 estate
->es_into_relation_descriptor
= NULL
;
2736 * CreateIntoRelDestReceiver -- create a suitable DestReceiver object
2738 * Since CreateDestReceiver doesn't accept the parameters we'd need,
2739 * we just leave the private fields empty here. OpenIntoRel will
2743 CreateIntoRelDestReceiver(void)
2745 DR_intorel
*self
= (DR_intorel
*) palloc(sizeof(DR_intorel
));
2747 self
->pub
.receiveSlot
= intorel_receive
;
2748 self
->pub
.rStartup
= intorel_startup
;
2749 self
->pub
.rShutdown
= intorel_shutdown
;
2750 self
->pub
.rDestroy
= intorel_destroy
;
2751 self
->pub
.mydest
= DestIntoRel
;
2753 self
->estate
= NULL
;
2755 return (DestReceiver
*) self
;
2759 * intorel_startup --- executor startup
2762 intorel_startup(DestReceiver
*self
, int operation
, TupleDesc typeinfo
)
2768 * intorel_receive --- receive one tuple
2771 intorel_receive(TupleTableSlot
*slot
, DestReceiver
*self
)
2773 DR_intorel
*myState
= (DR_intorel
*) self
;
2774 EState
*estate
= myState
->estate
;
2777 tuple
= ExecCopySlotTuple(slot
);
2779 heap_insert(estate
->es_into_relation_descriptor
,
2781 estate
->es_output_cid
,
2782 estate
->es_into_relation_use_wal
,
2783 false); /* never any point in using FSM */
2785 /* We know this is a newly created relation, so there are no indexes */
2787 heap_freetuple(tuple
);
2793 * intorel_shutdown --- executor end
2796 intorel_shutdown(DestReceiver
*self
)
2802 * intorel_destroy --- release DestReceiver object
2805 intorel_destroy(DestReceiver
*self
)