1 /*-------------------------------------------------------------------------
4 * top level executor interface routines
12 * These four procedures are the external interface to the executor.
13 * In each case, the query descriptor is required as an argument.
15 * ExecutorStart must be called at the beginning of execution of any
16 * query plan and ExecutorEnd must always be called at the end of
17 * execution of a plan (unless it is aborted due to error).
19 * ExecutorRun accepts direction and count arguments that specify whether
20 * the plan is to be executed forwards, backwards, and for how many tuples.
21 * In some cases ExecutorRun may be called multiple times to process all
22 * the tuples for a plan. It is also acceptable to stop short of executing
23 * the whole plan (but only if it is a SELECT).
25 * ExecutorFinish must be called after the final ExecutorRun call and
26 * before ExecutorEnd. This can be omitted only in case of EXPLAIN,
27 * which should also omit ExecutorRun.
29 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
30 * Portions Copyright (c) 1994, Regents of the University of California
34 * src/backend/executor/execMain.c
36 *-------------------------------------------------------------------------
40 #include "access/reloptions.h"
41 #include "access/sysattr.h"
42 #include "access/transam.h"
43 #include "access/xact.h"
44 #include "catalog/heap.h"
45 #include "catalog/namespace.h"
46 #include "catalog/toasting.h"
47 #include "commands/tablespace.h"
48 #include "commands/trigger.h"
49 #include "executor/execdebug.h"
50 #include "executor/instrument.h"
51 #include "miscadmin.h"
52 #include "optimizer/clauses.h"
53 #include "parser/parse_clause.h"
54 #include "parser/parsetree.h"
55 #include "storage/bufmgr.h"
56 #include "storage/lmgr.h"
57 #include "storage/smgr.h"
58 #include "tcop/utility.h"
59 #include "utils/acl.h"
60 #include "utils/lsyscache.h"
61 #include "utils/memutils.h"
62 #include "utils/snapmgr.h"
63 #include "utils/tqual.h"
66 /* Hooks for plugins to get control in ExecutorStart/Run/Finish/End */
67 ExecutorStart_hook_type ExecutorStart_hook = NULL;
68 ExecutorRun_hook_type ExecutorRun_hook = NULL;
69 ExecutorFinish_hook_type ExecutorFinish_hook = NULL;
70 ExecutorEnd_hook_type ExecutorEnd_hook = NULL;
72 /* Hook for plugin to get control in ExecCheckRTPerms() */
73 ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL;
75 /* decls for local routines only used within this module */
76 static void InitPlan(QueryDesc *queryDesc, int eflags);
77 static void ExecPostprocessPlan(EState *estate);
78 static void ExecEndPlan(PlanState *planstate, EState *estate);
79 static void ExecutePlan(EState *estate, PlanState *planstate,
83 ScanDirection direction,
85 static bool ExecCheckRTEPerms(RangeTblEntry *rte);
86 static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
87 static void EvalPlanQualStart(EPQState *epqstate, EState *parentestate,
89 static void OpenIntoRel(QueryDesc *queryDesc);
90 static void CloseIntoRel(QueryDesc *queryDesc);
91 static void intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
92 static void intorel_receive(TupleTableSlot *slot, DestReceiver *self);
93 static void intorel_shutdown(DestReceiver *self);
94 static void intorel_destroy(DestReceiver *self);
96 /* end of local decls */
99 /* ----------------------------------------------------------------
102 * This routine must be called at the beginning of any execution of any
105 * Takes a QueryDesc previously created by CreateQueryDesc (which is separate
106 * only because some places use QueryDescs for utility commands). The tupDesc
107 * field of the QueryDesc is filled in to describe the tuples that will be
108 * returned, and the internal fields (estate and planstate) are set up.
110 * eflags contains flag bits as described in executor.h.
112 * NB: the CurrentMemoryContext when this is called will become the parent
113 * of the per-query context used for this Executor invocation.
115 * We provide a function hook variable that lets loadable plugins
116 * get control when ExecutorStart is called. Such a plugin would
117 * normally call standard_ExecutorStart().
119 * ----------------------------------------------------------------
122 ExecutorStart(QueryDesc *queryDesc, int eflags)
124 if (ExecutorStart_hook)
125 (*ExecutorStart_hook) (queryDesc, eflags);
127 standard_ExecutorStart(queryDesc, eflags);
131 standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
134 MemoryContext oldcontext;
136 /* sanity checks: queryDesc must not be started already */
137 Assert(queryDesc != NULL);
138 Assert(queryDesc->estate == NULL);
141 * If the transaction is read-only, we need to check if any writes are
142 * planned to non-temporary tables. EXPLAIN is considered read-only.
144 if (XactReadOnly && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
145 ExecCheckXactReadOnly(queryDesc->plannedstmt);
148 * Build EState, switch into per-query memory context for startup.
150 estate = CreateExecutorState();
151 queryDesc->estate = estate;
153 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
156 * Fill in external parameters, if any, from queryDesc; and allocate
157 * workspace for internal parameters
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)
173 * SELECT INTO, SELECT FOR UPDATE/SHARE and modifying CTEs need to
176 if (queryDesc->plannedstmt->intoClause != NULL ||
177 queryDesc->plannedstmt->rowMarks != NIL ||
178 queryDesc->plannedstmt->hasModifyingCTE)
179 estate->es_output_cid = GetCurrentCommandId(true);
182 * A SELECT without modifying CTEs can't possibly queue triggers,
183 * so force skip-triggers mode. This is just a marginal efficiency
184 * hack, since AfterTriggerBeginQuery/AfterTriggerEndQuery aren't
185 * all that expensive, but we might as well do it.
187 if (!queryDesc->plannedstmt->hasModifyingCTE)
188 eflags |= EXEC_FLAG_SKIP_TRIGGERS;
194 estate->es_output_cid = GetCurrentCommandId(true);
198 elog(ERROR, "unrecognized operation code: %d",
199 (int) queryDesc->operation);
204 * Copy other important information into the EState
206 estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
207 estate->es_crosscheck_snapshot = RegisterSnapshot(queryDesc->crosscheck_snapshot);
208 estate->es_top_eflags = eflags;
209 estate->es_instrument = queryDesc->instrument_options;
212 * Initialize the plan state tree
214 InitPlan(queryDesc, eflags);
217 * Set up an AFTER-trigger statement context, unless told not to, or
218 * unless it's EXPLAIN-only mode (when ExecutorFinish won't be called).
220 if (!(eflags & (EXEC_FLAG_SKIP_TRIGGERS | EXEC_FLAG_EXPLAIN_ONLY)))
221 AfterTriggerBeginQuery();
223 MemoryContextSwitchTo(oldcontext);
226 /* ----------------------------------------------------------------
229 * This is the main routine of the executor module. It accepts
230 * the query descriptor from the traffic cop and executes the
233 * ExecutorStart must have been called already.
235 * If direction is NoMovementScanDirection then nothing is done
236 * except to start up/shut down the destination. Otherwise,
237 * we retrieve up to 'count' tuples in the specified direction.
239 * Note: count = 0 is interpreted as no portal limit, i.e., run to
242 * There is no return value, but output tuples (if any) are sent to
243 * the destination receiver specified in the QueryDesc; and the number
244 * of tuples processed at the top level can be found in
245 * estate->es_processed.
247 * We provide a function hook variable that lets loadable plugins
248 * get control when ExecutorRun is called. Such a plugin would
249 * normally call standard_ExecutorRun().
251 * ----------------------------------------------------------------
254 ExecutorRun(QueryDesc *queryDesc,
255 ScanDirection direction, long count)
257 if (ExecutorRun_hook)
258 (*ExecutorRun_hook) (queryDesc, direction, count);
260 standard_ExecutorRun(queryDesc, direction, count);
264 standard_ExecutorRun(QueryDesc *queryDesc,
265 ScanDirection direction, long count)
271 MemoryContext oldcontext;
274 Assert(queryDesc != NULL);
276 estate = queryDesc->estate;
278 Assert(estate != NULL);
279 Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
282 * Switch into per-query memory context
284 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
286 /* Allow instrumentation of Executor overall runtime */
287 if (queryDesc->totaltime)
288 InstrStartNode(queryDesc->totaltime);
291 * extract information from the query descriptor and the query feature.
293 operation = queryDesc->operation;
294 dest = queryDesc->dest;
297 * startup tuple receiver, if we will be emitting tuples
299 estate->es_processed = 0;
300 estate->es_lastoid = InvalidOid;
302 sendTuples = (operation == CMD_SELECT ||
303 queryDesc->plannedstmt->hasReturning);
306 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
311 if (!ScanDirectionIsNoMovement(direction))
313 queryDesc->planstate,
321 * shutdown tuple receiver, if we started it
324 (*dest->rShutdown) (dest);
326 if (queryDesc->totaltime)
327 InstrStopNode(queryDesc->totaltime, estate->es_processed);
329 MemoryContextSwitchTo(oldcontext);
332 /* ----------------------------------------------------------------
335 * This routine must be called after the last ExecutorRun call.
336 * It performs cleanup such as firing AFTER triggers. It is
337 * separate from ExecutorEnd because EXPLAIN ANALYZE needs to
338 * include these actions in the total runtime.
340 * We provide a function hook variable that lets loadable plugins
341 * get control when ExecutorFinish is called. Such a plugin would
342 * normally call standard_ExecutorFinish().
344 * ----------------------------------------------------------------
347 ExecutorFinish(QueryDesc *queryDesc)
349 if (ExecutorFinish_hook)
350 (*ExecutorFinish_hook) (queryDesc);
352 standard_ExecutorFinish(queryDesc);
356 standard_ExecutorFinish(QueryDesc *queryDesc)
359 MemoryContext oldcontext;
362 Assert(queryDesc != NULL);
364 estate = queryDesc->estate;
366 Assert(estate != NULL);
367 Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
369 /* This should be run once and only once per Executor instance */
370 Assert(!estate->es_finished);
372 /* Switch into per-query memory context */
373 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
375 /* Allow instrumentation of Executor overall runtime */
376 if (queryDesc->totaltime)
377 InstrStartNode(queryDesc->totaltime);
379 /* Run ModifyTable nodes to completion */
380 ExecPostprocessPlan(estate);
382 /* Execute queued AFTER triggers, unless told not to */
383 if (!(estate->es_top_eflags & EXEC_FLAG_SKIP_TRIGGERS))
384 AfterTriggerEndQuery(estate);
386 if (queryDesc->totaltime)
387 InstrStopNode(queryDesc->totaltime, 0);
389 MemoryContextSwitchTo(oldcontext);
391 estate->es_finished = true;
394 /* ----------------------------------------------------------------
397 * This routine must be called at the end of execution of any
400 * We provide a function hook variable that lets loadable plugins
401 * get control when ExecutorEnd is called. Such a plugin would
402 * normally call standard_ExecutorEnd().
404 * ----------------------------------------------------------------
407 ExecutorEnd(QueryDesc *queryDesc)
409 if (ExecutorEnd_hook)
410 (*ExecutorEnd_hook) (queryDesc);
412 standard_ExecutorEnd(queryDesc);
416 standard_ExecutorEnd(QueryDesc *queryDesc)
419 MemoryContext oldcontext;
422 Assert(queryDesc != NULL);
424 estate = queryDesc->estate;
426 Assert(estate != NULL);
429 * Check that ExecutorFinish was called, unless in EXPLAIN-only mode. This
430 * Assert is needed because ExecutorFinish is new as of 9.1, and callers
431 * might forget to call it.
433 Assert(estate->es_finished ||
434 (estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
437 * Switch into per-query memory context to run ExecEndPlan
439 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
441 ExecEndPlan(queryDesc->planstate, estate);
444 * Close the SELECT INTO relation if any
446 if (estate->es_select_into)
447 CloseIntoRel(queryDesc);
449 /* do away with our snapshots */
450 UnregisterSnapshot(estate->es_snapshot);
451 UnregisterSnapshot(estate->es_crosscheck_snapshot);
454 * Must switch out of context before destroying it
456 MemoryContextSwitchTo(oldcontext);
459 * Release EState and per-query memory context. This should release
460 * everything the executor has allocated.
462 FreeExecutorState(estate);
464 /* Reset queryDesc fields that no longer point to anything */
465 queryDesc->tupDesc = NULL;
466 queryDesc->estate = NULL;
467 queryDesc->planstate = NULL;
468 queryDesc->totaltime = NULL;
471 /* ----------------------------------------------------------------
474 * This routine may be called on an open queryDesc to rewind it
476 * ----------------------------------------------------------------
479 ExecutorRewind(QueryDesc *queryDesc)
482 MemoryContext oldcontext;
485 Assert(queryDesc != NULL);
487 estate = queryDesc->estate;
489 Assert(estate != NULL);
491 /* It's probably not sensible to rescan updating queries */
492 Assert(queryDesc->operation == CMD_SELECT);
495 * Switch into per-query memory context
497 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
502 ExecReScan(queryDesc->planstate);
504 MemoryContextSwitchTo(oldcontext);
510 * Check access permissions for all relations listed in a range table.
512 * Returns true if permissions are adequate. Otherwise, throws an appropriate
513 * error if ereport_on_violation is true, or simply returns false otherwise.
516 ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
521 foreach(l, rangeTable)
523 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
525 result = ExecCheckRTEPerms(rte);
528 Assert(rte->rtekind == RTE_RELATION);
529 if (ereport_on_violation)
530 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
531 get_rel_name(rte->relid));
536 if (ExecutorCheckPerms_hook)
537 result = (*ExecutorCheckPerms_hook) (rangeTable,
538 ereport_on_violation);
544 * Check access permissions for a single RTE.
547 ExecCheckRTEPerms(RangeTblEntry *rte)
549 AclMode requiredPerms;
551 AclMode remainingPerms;
558 * Only plain-relation RTEs need to be checked here. Function RTEs are
559 * checked by init_fcache when the function is prepared for execution.
560 * Join, subquery, and special RTEs need no checks.
562 if (rte->rtekind != RTE_RELATION)
566 * No work if requiredPerms is empty.
568 requiredPerms = rte->requiredPerms;
569 if (requiredPerms == 0)
575 * userid to check as: current user unless we have a setuid indication.
577 * Note: GetUserId() is presently fast enough that there's no harm in
578 * calling it separately for each RTE. If that stops being true, we could
579 * call it once in ExecCheckRTPerms and pass the userid down from there.
580 * But for now, no need for the extra clutter.
582 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
585 * We must have *all* the requiredPerms bits, but some of the bits can be
586 * satisfied from column-level rather than relation-level permissions.
587 * First, remove any bits that are satisfied by relation permissions.
589 relPerms = pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL);
590 remainingPerms = requiredPerms & ~relPerms;
591 if (remainingPerms != 0)
594 * If we lack any permissions that exist only as relation permissions,
595 * we can fail straight away.
597 if (remainingPerms & ~(ACL_SELECT | ACL_INSERT | ACL_UPDATE))
601 * Check to see if we have the needed privileges at column level.
603 * Note: failures just report a table-level error; it would be nicer
604 * to report a column-level error if we have some but not all of the
607 if (remainingPerms & ACL_SELECT)
610 * When the query doesn't explicitly reference any columns (for
611 * example, SELECT COUNT(*) FROM table), allow the query if we
612 * have SELECT on any column of the rel, as per SQL spec.
614 if (bms_is_empty(rte->selectedCols))
616 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
617 ACLMASK_ANY) != ACLCHECK_OK)
621 tmpset = bms_copy(rte->selectedCols);
622 while ((col = bms_first_member(tmpset)) >= 0)
624 /* remove the column number offset */
625 col += FirstLowInvalidHeapAttributeNumber;
626 if (col == InvalidAttrNumber)
628 /* Whole-row reference, must have priv on all cols */
629 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
630 ACLMASK_ALL) != ACLCHECK_OK)
635 if (pg_attribute_aclcheck(relOid, col, userid,
636 ACL_SELECT) != ACLCHECK_OK)
644 * Basically the same for the mod columns, with either INSERT or
645 * UPDATE privilege as specified by remainingPerms.
647 remainingPerms &= ~ACL_SELECT;
648 if (remainingPerms != 0)
651 * When the query doesn't explicitly change any columns, allow the
652 * query if we have permission on any column of the rel. This is
653 * to handle SELECT FOR UPDATE as well as possible corner cases in
656 if (bms_is_empty(rte->modifiedCols))
658 if (pg_attribute_aclcheck_all(relOid, userid, remainingPerms,
659 ACLMASK_ANY) != ACLCHECK_OK)
663 tmpset = bms_copy(rte->modifiedCols);
664 while ((col = bms_first_member(tmpset)) >= 0)
666 /* remove the column number offset */
667 col += FirstLowInvalidHeapAttributeNumber;
668 if (col == InvalidAttrNumber)
670 /* whole-row reference can't happen here */
671 elog(ERROR, "whole-row update is not implemented");
675 if (pg_attribute_aclcheck(relOid, col, userid,
676 remainingPerms) != ACLCHECK_OK)
687 * Check that the query does not imply any writes to non-temp tables.
689 * Note: in a Hot Standby slave this would need to reject writes to temp
690 * tables as well; but an HS slave can't have created any temp tables
691 * in the first place, so no need to check that.
694 ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
699 * CREATE TABLE AS or SELECT INTO?
701 * XXX should we allow this if the destination is temp? Considering that
702 * it would still require catalog changes, probably not.
704 if (plannedstmt->intoClause != NULL)
705 PreventCommandIfReadOnly(CreateCommandTag((Node *) plannedstmt));
707 /* Fail if write permissions are requested on any non-temp table */
708 foreach(l, plannedstmt->rtable)
710 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
712 if (rte->rtekind != RTE_RELATION)
715 if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
718 if (isTempNamespace(get_rel_namespace(rte->relid)))
721 PreventCommandIfReadOnly(CreateCommandTag((Node *) plannedstmt));
726 /* ----------------------------------------------------------------
729 * Initializes the query plan: open files, allocate storage
730 * and start up the rule manager
731 * ----------------------------------------------------------------
734 InitPlan(QueryDesc *queryDesc, int eflags)
736 CmdType operation = queryDesc->operation;
737 PlannedStmt *plannedstmt = queryDesc->plannedstmt;
738 Plan *plan = plannedstmt->planTree;
739 List *rangeTable = plannedstmt->rtable;
740 EState *estate = queryDesc->estate;
741 PlanState *planstate;
747 * Do permissions checks
749 ExecCheckRTPerms(rangeTable, true);
752 * initialize the node's execution state
754 estate->es_range_table = rangeTable;
755 estate->es_plannedstmt = plannedstmt;
758 * initialize result relation stuff, and open/lock the result rels.
760 * We must do this before initializing the plan tree, else we might try to
761 * do a lock upgrade if a result rel is also a source rel.
763 if (plannedstmt->resultRelations)
765 List *resultRelations = plannedstmt->resultRelations;
766 int numResultRelations = list_length(resultRelations);
767 ResultRelInfo *resultRelInfos;
768 ResultRelInfo *resultRelInfo;
770 resultRelInfos = (ResultRelInfo *)
771 palloc(numResultRelations * sizeof(ResultRelInfo));
772 resultRelInfo = resultRelInfos;
773 foreach(l, resultRelations)
775 Index resultRelationIndex = lfirst_int(l);
776 Oid resultRelationOid;
777 Relation resultRelation;
779 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
780 resultRelation = heap_open(resultRelationOid, RowExclusiveLock);
781 InitResultRelInfo(resultRelInfo,
784 estate->es_instrument);
787 estate->es_result_relations = resultRelInfos;
788 estate->es_num_result_relations = numResultRelations;
789 /* es_result_relation_info is NULL except when within ModifyTable */
790 estate->es_result_relation_info = NULL;
795 * if no result relation, then set state appropriately
797 estate->es_result_relations = NULL;
798 estate->es_num_result_relations = 0;
799 estate->es_result_relation_info = NULL;
803 * Similarly, we have to lock relations selected FOR UPDATE/FOR SHARE
804 * before we initialize the plan tree, else we'd be risking lock upgrades.
805 * While we are at it, build the ExecRowMark list.
807 estate->es_rowMarks = NIL;
808 foreach(l, plannedstmt->rowMarks)
810 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
815 /* ignore "parent" rowmarks; they are irrelevant at runtime */
819 switch (rc->markType)
821 case ROW_MARK_EXCLUSIVE:
823 relid = getrelid(rc->rti, rangeTable);
824 relation = heap_open(relid, RowShareLock);
826 case ROW_MARK_REFERENCE:
827 relid = getrelid(rc->rti, rangeTable);
828 relation = heap_open(relid, AccessShareLock);
831 /* there's no real table here ... */
835 elog(ERROR, "unrecognized markType: %d", rc->markType);
836 relation = NULL; /* keep compiler quiet */
840 /* if foreign table, tuples can't be locked */
841 if (relation && relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
843 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
844 errmsg("SELECT FOR UPDATE/SHARE cannot be used with foreign table \"%s\"",
845 RelationGetRelationName(relation))));
847 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
848 erm->relation = relation;
850 erm->prti = rc->prti;
851 erm->rowmarkId = rc->rowmarkId;
852 erm->markType = rc->markType;
853 erm->noWait = rc->noWait;
854 ItemPointerSetInvalid(&(erm->curCtid));
855 estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
859 * Detect whether we're doing SELECT INTO. If so, set the es_into_oids
860 * flag appropriately so that the plan tree will be initialized with the
861 * correct tuple descriptors. (Other SELECT INTO stuff comes later.)
863 estate->es_select_into = false;
864 if (operation == CMD_SELECT && plannedstmt->intoClause != NULL)
866 estate->es_select_into = true;
867 estate->es_into_oids = interpretOidsOption(plannedstmt->intoClause->options);
871 * Initialize the executor's tuple table to empty.
873 estate->es_tupleTable = NIL;
874 estate->es_trig_tuple_slot = NULL;
875 estate->es_trig_oldtup_slot = NULL;
877 /* mark EvalPlanQual not active */
878 estate->es_epqTuple = NULL;
879 estate->es_epqTupleSet = NULL;
880 estate->es_epqScanDone = NULL;
883 * Initialize private state information for each SubPlan. We must do this
884 * before running ExecInitNode on the main query tree, since
885 * ExecInitSubPlan expects to be able to find these entries.
887 Assert(estate->es_subplanstates == NIL);
888 i = 1; /* subplan indices count from 1 */
889 foreach(l, plannedstmt->subplans)
891 Plan *subplan = (Plan *) lfirst(l);
892 PlanState *subplanstate;
896 * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
897 * it is a parameterless subplan (not initplan), we suggest that it be
898 * prepared to handle REWIND efficiently; otherwise there is no need.
900 sp_eflags = eflags & EXEC_FLAG_EXPLAIN_ONLY;
901 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
902 sp_eflags |= EXEC_FLAG_REWIND;
904 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
906 estate->es_subplanstates = lappend(estate->es_subplanstates,
913 * Initialize the private state information for all the nodes in the query
914 * tree. This opens files, allocates storage and leaves us ready to start
917 planstate = ExecInitNode(plan, estate, eflags);
920 * Get the tuple descriptor describing the type of tuples to return. (this
921 * is especially important if we are creating a relation with "SELECT
924 tupType = ExecGetResultType(planstate);
927 * Initialize the junk filter if needed. SELECT queries need a filter if
928 * there are any junk attrs in the top-level tlist.
930 if (operation == CMD_SELECT)
932 bool junk_filter_needed = false;
935 foreach(tlist, plan->targetlist)
937 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
941 junk_filter_needed = true;
946 if (junk_filter_needed)
950 j = ExecInitJunkFilter(planstate->plan->targetlist,
952 ExecInitExtraTupleSlot(estate));
953 estate->es_junkFilter = j;
955 /* Want to return the cleaned tuple type */
956 tupType = j->jf_cleanTupType;
960 queryDesc->tupDesc = tupType;
961 queryDesc->planstate = planstate;
964 * If doing SELECT INTO, initialize the "into" relation. We must wait
965 * till now so we have the "clean" result tuple type to create the new
968 * If EXPLAIN, skip creating the "into" relation.
970 if (estate->es_select_into && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
971 OpenIntoRel(queryDesc);
975 * Check that a proposed result relation is a legal target for the operation
977 * In most cases parser and/or planner should have noticed this already, but
978 * let's make sure. In the view case we do need a test here, because if the
979 * view wasn't rewritten by a rule, it had better have an INSTEAD trigger.
982 CheckValidResultRel(Relation resultRel, CmdType operation)
984 TriggerDesc *trigDesc = resultRel->trigdesc;
986 switch (resultRel->rd_rel->relkind)
988 case RELKIND_RELATION:
991 case RELKIND_SEQUENCE:
993 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
994 errmsg("cannot change sequence \"%s\"",
995 RelationGetRelationName(resultRel))));
997 case RELKIND_TOASTVALUE:
999 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1000 errmsg("cannot change TOAST relation \"%s\"",
1001 RelationGetRelationName(resultRel))));
1007 if (!trigDesc || !trigDesc->trig_insert_instead_row)
1009 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1010 errmsg("cannot insert into view \"%s\"",
1011 RelationGetRelationName(resultRel)),
1012 errhint("You need an unconditional ON INSERT DO INSTEAD rule or an INSTEAD OF INSERT trigger.")));
1015 if (!trigDesc || !trigDesc->trig_update_instead_row)
1017 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1018 errmsg("cannot update view \"%s\"",
1019 RelationGetRelationName(resultRel)),
1020 errhint("You need an unconditional ON UPDATE DO INSTEAD rule or an INSTEAD OF UPDATE trigger.")));
1023 if (!trigDesc || !trigDesc->trig_delete_instead_row)
1025 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1026 errmsg("cannot delete from view \"%s\"",
1027 RelationGetRelationName(resultRel)),
1028 errhint("You need an unconditional ON DELETE DO INSTEAD rule or an INSTEAD OF DELETE trigger.")));
1031 elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1035 case RELKIND_FOREIGN_TABLE:
1037 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1038 errmsg("cannot change foreign table \"%s\"",
1039 RelationGetRelationName(resultRel))));
1043 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1044 errmsg("cannot change relation \"%s\"",
1045 RelationGetRelationName(resultRel))));
1051 * Initialize ResultRelInfo data for one result relation
1053 * Caution: before Postgres 9.1, this function included the relkind checking
1054 * that's now in CheckValidResultRel, and it also did ExecOpenIndices if
1055 * appropriate. Be sure callers cover those needs.
1058 InitResultRelInfo(ResultRelInfo *resultRelInfo,
1059 Relation resultRelationDesc,
1060 Index resultRelationIndex,
1061 int instrument_options)
1063 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1064 resultRelInfo->type = T_ResultRelInfo;
1065 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1066 resultRelInfo->ri_RelationDesc = resultRelationDesc;
1067 resultRelInfo->ri_NumIndices = 0;
1068 resultRelInfo->ri_IndexRelationDescs = NULL;
1069 resultRelInfo->ri_IndexRelationInfo = NULL;
1070 /* make a copy so as not to depend on relcache info not changing... */
1071 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1072 if (resultRelInfo->ri_TrigDesc)
1074 int n = resultRelInfo->ri_TrigDesc->numtriggers;
1076 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1077 palloc0(n * sizeof(FmgrInfo));
1078 resultRelInfo->ri_TrigWhenExprs = (List **)
1079 palloc0(n * sizeof(List *));
1080 if (instrument_options)
1081 resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options);
1085 resultRelInfo->ri_TrigFunctions = NULL;
1086 resultRelInfo->ri_TrigWhenExprs = NULL;
1087 resultRelInfo->ri_TrigInstrument = NULL;
1089 resultRelInfo->ri_ConstraintExprs = NULL;
1090 resultRelInfo->ri_junkFilter = NULL;
1091 resultRelInfo->ri_projectReturning = NULL;
1095 * ExecGetTriggerResultRel
1097 * Get a ResultRelInfo for a trigger target relation. Most of the time,
1098 * triggers are fired on one of the result relations of the query, and so
1099 * we can just return a member of the es_result_relations array. (Note: in
1100 * self-join situations there might be multiple members with the same OID;
1101 * if so it doesn't matter which one we pick.) However, it is sometimes
1102 * necessary to fire triggers on other relations; this happens mainly when an
1103 * RI update trigger queues additional triggers on other relations, which will
1104 * be processed in the context of the outer query. For efficiency's sake,
1105 * we want to have a ResultRelInfo for those triggers too; that can avoid
1106 * repeated re-opening of the relation. (It also provides a way for EXPLAIN
1107 * ANALYZE to report the runtimes of such triggers.) So we make additional
1108 * ResultRelInfo's as needed, and save them in es_trig_target_relations.
1111 ExecGetTriggerResultRel(EState *estate, Oid relid)
1113 ResultRelInfo *rInfo;
1117 MemoryContext oldcontext;
1119 /* First, search through the query result relations */
1120 rInfo = estate->es_result_relations;
1121 nr = estate->es_num_result_relations;
1124 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1129 /* Nope, but maybe we already made an extra ResultRelInfo for it */
1130 foreach(l, estate->es_trig_target_relations)
1132 rInfo = (ResultRelInfo *) lfirst(l);
1133 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1136 /* Nope, so we need a new one */
1139 * Open the target relation's relcache entry. We assume that an
1140 * appropriate lock is still held by the backend from whenever the trigger
1141 * event got queued, so we need take no new lock here. Also, we need not
1142 * recheck the relkind, so no need for CheckValidResultRel.
1144 rel = heap_open(relid, NoLock);
1147 * Make the new entry in the right context.
1149 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1150 rInfo = makeNode(ResultRelInfo);
1151 InitResultRelInfo(rInfo,
1153 0, /* dummy rangetable index */
1154 estate->es_instrument);
1155 estate->es_trig_target_relations =
1156 lappend(estate->es_trig_target_relations, rInfo);
1157 MemoryContextSwitchTo(oldcontext);
1160 * Currently, we don't need any index information in ResultRelInfos used
1161 * only for triggers, so no need to call ExecOpenIndices.
1168 * ExecContextForcesOids
1170 * This is pretty grotty: when doing INSERT, UPDATE, or SELECT INTO,
1171 * we need to ensure that result tuples have space for an OID iff they are
1172 * going to be stored into a relation that has OIDs. In other contexts
1173 * we are free to choose whether to leave space for OIDs in result tuples
1174 * (we generally don't want to, but we do if a physical-tlist optimization
1175 * is possible). This routine checks the plan context and returns TRUE if the
1176 * choice is forced, FALSE if the choice is not forced. In the TRUE case,
1177 * *hasoids is set to the required value.
1179 * One reason this is ugly is that all plan nodes in the plan tree will emit
1180 * tuples with space for an OID, though we really only need the topmost node
1181 * to do so. However, node types like Sort don't project new tuples but just
1182 * return their inputs, and in those cases the requirement propagates down
1183 * to the input node. Eventually we might make this code smart enough to
1184 * recognize how far down the requirement really goes, but for now we just
1185 * make all plan nodes do the same thing if the top level forces the choice.
1187 * We assume that if we are generating tuples for INSERT or UPDATE,
1188 * estate->es_result_relation_info is already set up to describe the target
1189 * relation. Note that in an UPDATE that spans an inheritance tree, some of
1190 * the target relations may have OIDs and some not. We have to make the
1191 * decisions on a per-relation basis as we initialize each of the subplans of
1192 * the ModifyTable node, so ModifyTable has to set es_result_relation_info
1193 * while initializing each subplan.
1195 * SELECT INTO is even uglier, because we don't have the INTO relation's
1196 * descriptor available when this code runs; we have to look aside at a
1197 * flag set by InitPlan().
1200 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
1202 ResultRelInfo *ri = planstate->state->es_result_relation_info;
1206 Relation rel = ri->ri_RelationDesc;
1210 *hasoids = rel->rd_rel->relhasoids;
1215 if (planstate->state->es_select_into)
1217 *hasoids = planstate->state->es_into_oids;
1224 /* ----------------------------------------------------------------
1225 * ExecPostprocessPlan
1227 * Give plan nodes a final chance to execute before shutdown
1228 * ----------------------------------------------------------------
1231 ExecPostprocessPlan(EState *estate)
1236 * Make sure nodes run forward.
1238 estate->es_direction = ForwardScanDirection;
1241 * Run any secondary ModifyTable nodes to completion, in case the main
1242 * query did not fetch all rows from them. (We do this to ensure that
1243 * such nodes have predictable results.)
1245 foreach(lc, estate->es_auxmodifytables)
1247 PlanState *ps = (PlanState *) lfirst(lc);
1251 TupleTableSlot *slot;
1253 /* Reset the per-output-tuple exprcontext each time */
1254 ResetPerTupleExprContext(estate);
1256 slot = ExecProcNode(ps);
1258 if (TupIsNull(slot))
1264 /* ----------------------------------------------------------------
1267 * Cleans up the query plan -- closes files and frees up storage
1269 * NOTE: we are no longer very worried about freeing storage per se
1270 * in this code; FreeExecutorState should be guaranteed to release all
1271 * memory that needs to be released. What we are worried about doing
1272 * is closing relations and dropping buffer pins. Thus, for example,
1273 * tuple tables must be cleared or dropped to ensure pins are released.
1274 * ----------------------------------------------------------------
1277 ExecEndPlan(PlanState *planstate, EState *estate)
1279 ResultRelInfo *resultRelInfo;
1284 * shut down the node-type-specific query processing
1286 ExecEndNode(planstate);
1291 foreach(l, estate->es_subplanstates)
1293 PlanState *subplanstate = (PlanState *) lfirst(l);
1295 ExecEndNode(subplanstate);
1299 * destroy the executor's tuple table. Actually we only care about
1300 * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1301 * the TupleTableSlots, since the containing memory context is about to go
1304 ExecResetTupleTable(estate->es_tupleTable, false);
1307 * close the result relation(s) if any, but hold locks until xact commit.
1309 resultRelInfo = estate->es_result_relations;
1310 for (i = estate->es_num_result_relations; i > 0; i--)
1312 /* Close indices and then the relation itself */
1313 ExecCloseIndices(resultRelInfo);
1314 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1319 * likewise close any trigger target relations
1321 foreach(l, estate->es_trig_target_relations)
1323 resultRelInfo = (ResultRelInfo *) lfirst(l);
1324 /* Close indices and then the relation itself */
1325 ExecCloseIndices(resultRelInfo);
1326 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1330 * close any relations selected FOR UPDATE/FOR SHARE, again keeping locks
1332 foreach(l, estate->es_rowMarks)
1334 ExecRowMark *erm = (ExecRowMark *) lfirst(l);
1337 heap_close(erm->relation, NoLock);
1341 /* ----------------------------------------------------------------
1344 * Processes the query plan until we have processed 'numberTuples' tuples,
1345 * moving in the specified direction.
1347 * Runs to completion if numberTuples is 0
1349 * Note: the ctid attribute is a 'junk' attribute that is removed before the
1351 * ----------------------------------------------------------------
1354 ExecutePlan(EState *estate,
1355 PlanState *planstate,
1359 ScanDirection direction,
1362 TupleTableSlot *slot;
1363 long current_tuple_count;
1366 * initialize local variables
1368 current_tuple_count = 0;
1371 * Set the direction.
1373 estate->es_direction = direction;
1376 * Loop until we've processed the proper number of tuples from the plan.
1380 /* Reset the per-output-tuple exprcontext */
1381 ResetPerTupleExprContext(estate);
1384 * Execute the plan and obtain a tuple
1386 slot = ExecProcNode(planstate);
1389 * if the tuple is null, then we assume there is nothing more to
1390 * process so we just end the loop...
1392 if (TupIsNull(slot))
1396 * If we have a junk filter, then project a new tuple with the junk
1399 * Store this new "clean" tuple in the junkfilter's resultSlot.
1400 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1401 * because that tuple slot has the wrong descriptor.)
1403 if (estate->es_junkFilter != NULL)
1404 slot = ExecFilterJunk(estate->es_junkFilter, slot);
1407 * If we are supposed to send the tuple somewhere, do so. (In
1408 * practice, this is probably always the case at this point.)
1411 (*dest->receiveSlot) (slot, dest);
1414 * Count tuples processed, if this is a SELECT. (For other operation
1415 * types, the ModifyTable plan node must count the appropriate
1418 if (operation == CMD_SELECT)
1419 (estate->es_processed)++;
1422 * check our tuple count.. if we've processed the proper number then
1423 * quit, else loop again and process more tuples. Zero numberTuples
1426 current_tuple_count++;
1427 if (numberTuples && numberTuples == current_tuple_count)
1434 * ExecRelCheck --- check that tuple meets constraints for result relation
1437 ExecRelCheck(ResultRelInfo *resultRelInfo,
1438 TupleTableSlot *slot, EState *estate)
1440 Relation rel = resultRelInfo->ri_RelationDesc;
1441 int ncheck = rel->rd_att->constr->num_check;
1442 ConstrCheck *check = rel->rd_att->constr->check;
1443 ExprContext *econtext;
1444 MemoryContext oldContext;
1449 * If first time through for this result relation, build expression
1450 * nodetrees for rel's constraint expressions. Keep them in the per-query
1451 * memory context so they'll survive throughout the query.
1453 if (resultRelInfo->ri_ConstraintExprs == NULL)
1455 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1456 resultRelInfo->ri_ConstraintExprs =
1457 (List **) palloc(ncheck * sizeof(List *));
1458 for (i = 0; i < ncheck; i++)
1460 /* ExecQual wants implicit-AND form */
1461 qual = make_ands_implicit(stringToNode(check[i].ccbin));
1462 resultRelInfo->ri_ConstraintExprs[i] = (List *)
1463 ExecPrepareExpr((Expr *) qual, estate);
1465 MemoryContextSwitchTo(oldContext);
1469 * We will use the EState's per-tuple context for evaluating constraint
1470 * expressions (creating it if it's not already there).
1472 econtext = GetPerTupleExprContext(estate);
1474 /* Arrange for econtext's scan tuple to be the tuple under test */
1475 econtext->ecxt_scantuple = slot;
1477 /* And evaluate the constraints */
1478 for (i = 0; i < ncheck; i++)
1480 qual = resultRelInfo->ri_ConstraintExprs[i];
1483 * NOTE: SQL92 specifies that a NULL result from a constraint
1484 * expression is not to be treated as a failure. Therefore, tell
1485 * ExecQual to return TRUE for NULL.
1487 if (!ExecQual(qual, econtext, true))
1488 return check[i].ccname;
1491 /* NULL result means no error */
1496 ExecConstraints(ResultRelInfo *resultRelInfo,
1497 TupleTableSlot *slot, EState *estate)
1499 Relation rel = resultRelInfo->ri_RelationDesc;
1500 TupleConstr *constr = rel->rd_att->constr;
1504 if (constr->has_not_null)
1506 int natts = rel->rd_att->natts;
1509 for (attrChk = 1; attrChk <= natts; attrChk++)
1511 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1512 slot_attisnull(slot, attrChk))
1514 (errcode(ERRCODE_NOT_NULL_VIOLATION),
1515 errmsg("null value in column \"%s\" violates not-null constraint",
1516 NameStr(rel->rd_att->attrs[attrChk - 1]->attname))));
1520 if (constr->num_check > 0)
1524 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1526 (errcode(ERRCODE_CHECK_VIOLATION),
1527 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1528 RelationGetRelationName(rel), failed)));
1534 * ExecFindRowMark -- find the ExecRowMark struct for given rangetable index
1537 ExecFindRowMark(EState *estate, Index rti)
1541 foreach(lc, estate->es_rowMarks)
1543 ExecRowMark *erm = (ExecRowMark *) lfirst(lc);
1545 if (erm->rti == rti)
1548 elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
1549 return NULL; /* keep compiler quiet */
1553 * ExecBuildAuxRowMark -- create an ExecAuxRowMark struct
1555 * Inputs are the underlying ExecRowMark struct and the targetlist of the
1556 * input plan node (not planstate node!). We need the latter to find out
1557 * the column numbers of the resjunk columns.
1560 ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
1562 ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
1565 aerm->rowmark = erm;
1567 /* Look up the resjunk columns associated with this rowmark */
1570 Assert(erm->markType != ROW_MARK_COPY);
1572 /* if child rel, need tableoid */
1573 if (erm->rti != erm->prti)
1575 snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
1576 aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
1578 if (!AttributeNumberIsValid(aerm->toidAttNo))
1579 elog(ERROR, "could not find junk %s column", resname);
1582 /* always need ctid for real relations */
1583 snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
1584 aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
1586 if (!AttributeNumberIsValid(aerm->ctidAttNo))
1587 elog(ERROR, "could not find junk %s column", resname);
1591 Assert(erm->markType == ROW_MARK_COPY);
1593 snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
1594 aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
1596 if (!AttributeNumberIsValid(aerm->wholeAttNo))
1597 elog(ERROR, "could not find junk %s column", resname);
1605 * EvalPlanQual logic --- recheck modified tuple(s) to see if we want to
1606 * process the updated version under READ COMMITTED rules.
1608 * See backend/executor/README for some info about how this works.
1613 * Check a modified tuple to see if we want to process its updated version
1614 * under READ COMMITTED rules.
1616 * estate - outer executor state data
1617 * epqstate - state for EvalPlanQual rechecking
1618 * relation - table containing tuple
1619 * rti - rangetable index of table containing tuple
1620 * *tid - t_ctid from the outdated tuple (ie, next updated version)
1621 * priorXmax - t_xmax from the outdated tuple
1623 * *tid is also an output parameter: it's modified to hold the TID of the
1624 * latest version of the tuple (note this may be changed even on failure)
1626 * Returns a slot containing the new candidate update/delete tuple, or
1627 * NULL if we determine we shouldn't process the row.
1630 EvalPlanQual(EState *estate, EPQState *epqstate,
1631 Relation relation, Index rti,
1632 ItemPointer tid, TransactionId priorXmax)
1634 TupleTableSlot *slot;
1635 HeapTuple copyTuple;
1640 * Get and lock the updated version of the row; if fail, return NULL.
1642 copyTuple = EvalPlanQualFetch(estate, relation, LockTupleExclusive,
1645 if (copyTuple == NULL)
1649 * For UPDATE/DELETE we have to return tid of actual row we're executing
1652 *tid = copyTuple->t_self;
1655 * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
1657 EvalPlanQualBegin(epqstate, estate);
1660 * Free old test tuple, if any, and store new tuple where relation's scan
1663 EvalPlanQualSetTuple(epqstate, rti, copyTuple);
1666 * Fetch any non-locked source rows
1668 EvalPlanQualFetchRowMarks(epqstate);
1671 * Run the EPQ query. We assume it will return at most one tuple.
1673 slot = EvalPlanQualNext(epqstate);
1676 * If we got a tuple, force the slot to materialize the tuple so that it
1677 * is not dependent on any local state in the EPQ query (in particular,
1678 * it's highly likely that the slot contains references to any pass-by-ref
1679 * datums that may be present in copyTuple). As with the next step, this
1680 * is to guard against early re-use of the EPQ query.
1682 if (!TupIsNull(slot))
1683 (void) ExecMaterializeSlot(slot);
1686 * Clear out the test tuple. This is needed in case the EPQ query is
1687 * re-used to test a tuple for a different relation. (Not clear that can
1688 * really happen, but let's be safe.)
1690 EvalPlanQualSetTuple(epqstate, rti, NULL);
1696 * Fetch a copy of the newest version of an outdated tuple
1698 * estate - executor state data
1699 * relation - table containing tuple
1700 * lockmode - requested tuple lock mode
1701 * *tid - t_ctid from the outdated tuple (ie, next updated version)
1702 * priorXmax - t_xmax from the outdated tuple
1704 * Returns a palloc'd copy of the newest tuple version, or NULL if we find
1705 * that there is no newest version (ie, the row was deleted not updated).
1706 * If successful, we have locked the newest tuple version, so caller does not
1707 * need to worry about it changing anymore.
1709 * Note: properly, lockmode should be declared as enum LockTupleMode,
1710 * but we use "int" to avoid having to include heapam.h in executor.h.
1713 EvalPlanQualFetch(EState *estate, Relation relation, int lockmode,
1714 ItemPointer tid, TransactionId priorXmax)
1716 HeapTuple copyTuple = NULL;
1717 HeapTupleData tuple;
1718 SnapshotData SnapshotDirty;
1721 * fetch target tuple
1723 * Loop here to deal with updated or busy tuples
1725 InitDirtySnapshot(SnapshotDirty);
1726 tuple.t_self = *tid;
1731 if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
1734 ItemPointerData update_ctid;
1735 TransactionId update_xmax;
1738 * If xmin isn't what we're expecting, the slot must have been
1739 * recycled and reused for an unrelated tuple. This implies that
1740 * the latest version of the row was deleted, so we need do
1741 * nothing. (Should be safe to examine xmin without getting
1742 * buffer's content lock, since xmin never changes in an existing
1745 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1748 ReleaseBuffer(buffer);
1752 /* otherwise xmin should not be dirty... */
1753 if (TransactionIdIsValid(SnapshotDirty.xmin))
1754 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
1757 * If tuple is being updated by other transaction then we have to
1758 * wait for its commit/abort.
1760 if (TransactionIdIsValid(SnapshotDirty.xmax))
1762 ReleaseBuffer(buffer);
1763 XactLockTableWait(SnapshotDirty.xmax);
1764 continue; /* loop back to repeat heap_fetch */
1768 * If tuple was inserted by our own transaction, we have to check
1769 * cmin against es_output_cid: cmin >= current CID means our
1770 * command cannot see the tuple, so we should ignore it. Without
1771 * this we are open to the "Halloween problem" of indefinitely
1772 * re-updating the same tuple. (We need not check cmax because
1773 * HeapTupleSatisfiesDirty will consider a tuple deleted by our
1774 * transaction dead, regardless of cmax.) We just checked that
1775 * priorXmax == xmin, so we can test that variable instead of
1776 * doing HeapTupleHeaderGetXmin again.
1778 if (TransactionIdIsCurrentTransactionId(priorXmax) &&
1779 HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
1781 ReleaseBuffer(buffer);
1786 * This is a live tuple, so now try to lock it.
1788 test = heap_lock_tuple(relation, &tuple, &buffer,
1789 &update_ctid, &update_xmax,
1790 estate->es_output_cid,
1792 /* We now have two pins on the buffer, get rid of one */
1793 ReleaseBuffer(buffer);
1797 case HeapTupleSelfUpdated:
1798 /* treat it as deleted; do not process */
1799 ReleaseBuffer(buffer);
1802 case HeapTupleMayBeUpdated:
1803 /* successfully locked */
1806 case HeapTupleUpdated:
1807 ReleaseBuffer(buffer);
1808 if (IsolationUsesXactSnapshot())
1810 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1811 errmsg("could not serialize access due to concurrent update")));
1812 if (!ItemPointerEquals(&update_ctid, &tuple.t_self))
1814 /* it was updated, so look at the updated version */
1815 tuple.t_self = update_ctid;
1816 /* updated row should have xmin matching this xmax */
1817 priorXmax = update_xmax;
1820 /* tuple was deleted, so give up */
1824 ReleaseBuffer(buffer);
1825 elog(ERROR, "unrecognized heap_lock_tuple status: %u",
1827 return NULL; /* keep compiler quiet */
1831 * We got tuple - now copy it for use by recheck query.
1833 copyTuple = heap_copytuple(&tuple);
1834 ReleaseBuffer(buffer);
1839 * If the referenced slot was actually empty, the latest version of
1840 * the row must have been deleted, so we need do nothing.
1842 if (tuple.t_data == NULL)
1844 ReleaseBuffer(buffer);
1849 * As above, if xmin isn't what we're expecting, do nothing.
1851 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1854 ReleaseBuffer(buffer);
1859 * If we get here, the tuple was found but failed SnapshotDirty.
1860 * Assuming the xmin is either a committed xact or our own xact (as it
1861 * certainly should be if we're trying to modify the tuple), this must
1862 * mean that the row was updated or deleted by either a committed xact
1863 * or our own xact. If it was deleted, we can ignore it; if it was
1864 * updated then chain up to the next version and repeat the whole
1867 * As above, it should be safe to examine xmax and t_ctid without the
1868 * buffer content lock, because they can't be changing.
1870 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
1872 /* deleted, so forget about it */
1873 ReleaseBuffer(buffer);
1877 /* updated, so look at the updated row */
1878 tuple.t_self = tuple.t_data->t_ctid;
1879 /* updated row should have xmin matching this xmax */
1880 priorXmax = HeapTupleHeaderGetXmax(tuple.t_data);
1881 ReleaseBuffer(buffer);
1882 /* loop back to fetch next in chain */
1886 * Return the copied tuple
1892 * EvalPlanQualInit -- initialize during creation of a plan state node
1893 * that might need to invoke EPQ processing.
1895 * Note: subplan/auxrowmarks can be NULL/NIL if they will be set later
1896 * with EvalPlanQualSetPlan.
1899 EvalPlanQualInit(EPQState *epqstate, EState *estate,
1900 Plan *subplan, List *auxrowmarks, int epqParam)
1902 /* Mark the EPQ state inactive */
1903 epqstate->estate = NULL;
1904 epqstate->planstate = NULL;
1905 epqstate->origslot = NULL;
1906 /* ... and remember data that EvalPlanQualBegin will need */
1907 epqstate->plan = subplan;
1908 epqstate->arowMarks = auxrowmarks;
1909 epqstate->epqParam = epqParam;
1913 * EvalPlanQualSetPlan -- set or change subplan of an EPQState.
1915 * We need this so that ModifyTuple can deal with multiple subplans.
1918 EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan, List *auxrowmarks)
1920 /* If we have a live EPQ query, shut it down */
1921 EvalPlanQualEnd(epqstate);
1922 /* And set/change the plan pointer */
1923 epqstate->plan = subplan;
1924 /* The rowmarks depend on the plan, too */
1925 epqstate->arowMarks = auxrowmarks;
1929 * Install one test tuple into EPQ state, or clear test tuple if tuple == NULL
1931 * NB: passed tuple must be palloc'd; it may get freed later
1934 EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
1936 EState *estate = epqstate->estate;
1941 * free old test tuple, if any, and store new tuple where relation's scan
1944 if (estate->es_epqTuple[rti - 1] != NULL)
1945 heap_freetuple(estate->es_epqTuple[rti - 1]);
1946 estate->es_epqTuple[rti - 1] = tuple;
1947 estate->es_epqTupleSet[rti - 1] = true;
1951 * Fetch back the current test tuple (if any) for the specified RTI
1954 EvalPlanQualGetTuple(EPQState *epqstate, Index rti)
1956 EState *estate = epqstate->estate;
1960 return estate->es_epqTuple[rti - 1];
1964 * Fetch the current row values for any non-locked relations that need
1965 * to be scanned by an EvalPlanQual operation. origslot must have been set
1966 * to contain the current result row (top-level row) that we need to recheck.
1969 EvalPlanQualFetchRowMarks(EPQState *epqstate)
1973 Assert(epqstate->origslot != NULL);
1975 foreach(l, epqstate->arowMarks)
1977 ExecAuxRowMark *aerm = (ExecAuxRowMark *) lfirst(l);
1978 ExecRowMark *erm = aerm->rowmark;
1981 HeapTupleData tuple;
1983 if (RowMarkRequiresRowShareLock(erm->markType))
1984 elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
1986 /* clear any leftover test tuple for this rel */
1987 EvalPlanQualSetTuple(epqstate, erm->rti, NULL);
1993 Assert(erm->markType == ROW_MARK_REFERENCE);
1995 /* if child rel, must check whether it produced this row */
1996 if (erm->rti != erm->prti)
2000 datum = ExecGetJunkAttribute(epqstate->origslot,
2003 /* non-locked rels could be on the inside of outer joins */
2006 tableoid = DatumGetObjectId(datum);
2008 if (tableoid != RelationGetRelid(erm->relation))
2010 /* this child is inactive right now */
2015 /* fetch the tuple's ctid */
2016 datum = ExecGetJunkAttribute(epqstate->origslot,
2019 /* non-locked rels could be on the inside of outer joins */
2022 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
2024 /* okay, fetch the tuple */
2025 if (!heap_fetch(erm->relation, SnapshotAny, &tuple, &buffer,
2027 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2029 /* successful, copy and store tuple */
2030 EvalPlanQualSetTuple(epqstate, erm->rti,
2031 heap_copytuple(&tuple));
2032 ReleaseBuffer(buffer);
2038 Assert(erm->markType == ROW_MARK_COPY);
2040 /* fetch the whole-row Var for the relation */
2041 datum = ExecGetJunkAttribute(epqstate->origslot,
2044 /* non-locked rels could be on the inside of outer joins */
2047 td = DatumGetHeapTupleHeader(datum);
2049 /* build a temporary HeapTuple control structure */
2050 tuple.t_len = HeapTupleHeaderGetDatumLength(td);
2051 ItemPointerSetInvalid(&(tuple.t_self));
2052 tuple.t_tableOid = InvalidOid;
2055 /* copy and store tuple */
2056 EvalPlanQualSetTuple(epqstate, erm->rti,
2057 heap_copytuple(&tuple));
2063 * Fetch the next row (if any) from EvalPlanQual testing
2065 * (In practice, there should never be more than one row...)
2068 EvalPlanQualNext(EPQState *epqstate)
2070 MemoryContext oldcontext;
2071 TupleTableSlot *slot;
2073 oldcontext = MemoryContextSwitchTo(epqstate->estate->es_query_cxt);
2074 slot = ExecProcNode(epqstate->planstate);
2075 MemoryContextSwitchTo(oldcontext);
2081 * Initialize or reset an EvalPlanQual state tree
2084 EvalPlanQualBegin(EPQState *epqstate, EState *parentestate)
2086 EState *estate = epqstate->estate;
2090 /* First time through, so create a child EState */
2091 EvalPlanQualStart(epqstate, parentestate, epqstate->plan);
2096 * We already have a suitable child EPQ tree, so just reset it.
2098 int rtsize = list_length(parentestate->es_range_table);
2099 PlanState *planstate = epqstate->planstate;
2101 MemSet(estate->es_epqScanDone, 0, rtsize * sizeof(bool));
2103 /* Recopy current values of parent parameters */
2104 if (parentestate->es_plannedstmt->nParamExec > 0)
2106 int i = parentestate->es_plannedstmt->nParamExec;
2110 /* copy value if any, but not execPlan link */
2111 estate->es_param_exec_vals[i].value =
2112 parentestate->es_param_exec_vals[i].value;
2113 estate->es_param_exec_vals[i].isnull =
2114 parentestate->es_param_exec_vals[i].isnull;
2119 * Mark child plan tree as needing rescan at all scan nodes. The
2120 * first ExecProcNode will take care of actually doing the rescan.
2122 planstate->chgParam = bms_add_member(planstate->chgParam,
2123 epqstate->epqParam);
2128 * Start execution of an EvalPlanQual plan tree.
2130 * This is a cut-down version of ExecutorStart(): we copy some state from
2131 * the top-level estate rather than initializing it fresh.
2134 EvalPlanQualStart(EPQState *epqstate, EState *parentestate, Plan *planTree)
2138 MemoryContext oldcontext;
2141 rtsize = list_length(parentestate->es_range_table);
2143 epqstate->estate = estate = CreateExecutorState();
2145 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2148 * Child EPQ EStates share the parent's copy of unchanging state such as
2149 * the snapshot, rangetable, result-rel info, and external Param info.
2150 * They need their own copies of local state, including a tuple table,
2151 * es_param_exec_vals, etc.
2153 estate->es_direction = ForwardScanDirection;
2154 estate->es_snapshot = parentestate->es_snapshot;
2155 estate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
2156 estate->es_range_table = parentestate->es_range_table;
2157 estate->es_plannedstmt = parentestate->es_plannedstmt;
2158 estate->es_junkFilter = parentestate->es_junkFilter;
2159 estate->es_output_cid = parentestate->es_output_cid;
2160 estate->es_result_relations = parentestate->es_result_relations;
2161 estate->es_num_result_relations = parentestate->es_num_result_relations;
2162 estate->es_result_relation_info = parentestate->es_result_relation_info;
2163 /* es_trig_target_relations must NOT be copied */
2164 estate->es_rowMarks = parentestate->es_rowMarks;
2165 estate->es_top_eflags = parentestate->es_top_eflags;
2166 estate->es_instrument = parentestate->es_instrument;
2167 estate->es_select_into = parentestate->es_select_into;
2168 estate->es_into_oids = parentestate->es_into_oids;
2169 /* es_auxmodifytables must NOT be copied */
2172 * The external param list is simply shared from parent. The internal
2173 * param workspace has to be local state, but we copy the initial values
2174 * from the parent, so as to have access to any param values that were
2175 * already set from other parts of the parent's plan tree.
2177 estate->es_param_list_info = parentestate->es_param_list_info;
2178 if (parentestate->es_plannedstmt->nParamExec > 0)
2180 int i = parentestate->es_plannedstmt->nParamExec;
2182 estate->es_param_exec_vals = (ParamExecData *)
2183 palloc0(i * sizeof(ParamExecData));
2186 /* copy value if any, but not execPlan link */
2187 estate->es_param_exec_vals[i].value =
2188 parentestate->es_param_exec_vals[i].value;
2189 estate->es_param_exec_vals[i].isnull =
2190 parentestate->es_param_exec_vals[i].isnull;
2195 * Each EState must have its own es_epqScanDone state, but if we have
2196 * nested EPQ checks they should share es_epqTuple arrays. This allows
2197 * sub-rechecks to inherit the values being examined by an outer recheck.
2199 estate->es_epqScanDone = (bool *) palloc0(rtsize * sizeof(bool));
2200 if (parentestate->es_epqTuple != NULL)
2202 estate->es_epqTuple = parentestate->es_epqTuple;
2203 estate->es_epqTupleSet = parentestate->es_epqTupleSet;
2207 estate->es_epqTuple = (HeapTuple *)
2208 palloc0(rtsize * sizeof(HeapTuple));
2209 estate->es_epqTupleSet = (bool *)
2210 palloc0(rtsize * sizeof(bool));
2214 * Each estate also has its own tuple table.
2216 estate->es_tupleTable = NIL;
2219 * Initialize private state information for each SubPlan. We must do this
2220 * before running ExecInitNode on the main query tree, since
2221 * ExecInitSubPlan expects to be able to find these entries. Some of the
2222 * SubPlans might not be used in the part of the plan tree we intend to
2223 * run, but since it's not easy to tell which, we just initialize them
2224 * all. (However, if the subplan is headed by a ModifyTable node, then it
2225 * must be a data-modifying CTE, which we will certainly not need to
2226 * re-run, so we can skip initializing it. This is just an efficiency
2227 * hack; it won't skip data-modifying CTEs for which the ModifyTable node
2228 * is not at the top.)
2230 Assert(estate->es_subplanstates == NIL);
2231 foreach(l, parentestate->es_plannedstmt->subplans)
2233 Plan *subplan = (Plan *) lfirst(l);
2234 PlanState *subplanstate;
2236 /* Don't initialize ModifyTable subplans, per comment above */
2237 if (IsA(subplan, ModifyTable))
2238 subplanstate = NULL;
2240 subplanstate = ExecInitNode(subplan, estate, 0);
2242 estate->es_subplanstates = lappend(estate->es_subplanstates,
2247 * Initialize the private state information for all the nodes in the part
2248 * of the plan tree we need to run. This opens files, allocates storage
2249 * and leaves us ready to start processing tuples.
2251 epqstate->planstate = ExecInitNode(planTree, estate, 0);
2253 MemoryContextSwitchTo(oldcontext);
2257 * EvalPlanQualEnd -- shut down at termination of parent plan state node,
2258 * or if we are done with the current EPQ child.
2260 * This is a cut-down version of ExecutorEnd(); basically we want to do most
2261 * of the normal cleanup, but *not* close result relations (which we are
2262 * just sharing from the outer query). We do, however, have to close any
2263 * trigger target relations that got opened, since those are not shared.
2264 * (There probably shouldn't be any of the latter, but just in case...)
2267 EvalPlanQualEnd(EPQState *epqstate)
2269 EState *estate = epqstate->estate;
2270 MemoryContext oldcontext;
2274 return; /* idle, so nothing to do */
2276 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2278 ExecEndNode(epqstate->planstate);
2280 foreach(l, estate->es_subplanstates)
2282 PlanState *subplanstate = (PlanState *) lfirst(l);
2284 ExecEndNode(subplanstate);
2287 /* throw away the per-estate tuple table */
2288 ExecResetTupleTable(estate->es_tupleTable, false);
2290 /* close any trigger target relations attached to this EState */
2291 foreach(l, estate->es_trig_target_relations)
2293 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
2295 /* Close indices and then the relation itself */
2296 ExecCloseIndices(resultRelInfo);
2297 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
2300 MemoryContextSwitchTo(oldcontext);
2302 FreeExecutorState(estate);
2304 /* Mark EPQState idle */
2305 epqstate->estate = NULL;
2306 epqstate->planstate = NULL;
2307 epqstate->origslot = NULL;
2312 * Support for SELECT INTO (a/k/a CREATE TABLE AS)
2314 * We implement SELECT INTO by diverting SELECT's normal output with
2315 * a specialized DestReceiver type.
2320 DestReceiver pub; /* publicly-known function pointers */
2321 EState *estate; /* EState we are working with */
2322 Relation rel; /* Relation to write to */
2323 int hi_options; /* heap_insert performance options */
2324 BulkInsertState bistate; /* bulk insert state */
2328 * OpenIntoRel --- actually create the SELECT INTO target relation
2330 * This also replaces QueryDesc->dest with the special DestReceiver for
2331 * SELECT INTO. We assume that the correct result tuple type has already
2332 * been placed in queryDesc->tupDesc.
2335 OpenIntoRel(QueryDesc *queryDesc)
2337 IntoClause *into = queryDesc->plannedstmt->intoClause;
2338 EState *estate = queryDesc->estate;
2339 Relation intoRelationDesc;
2346 DR_intorel *myState;
2347 static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
2352 * XXX This code needs to be kept in sync with DefineRelation(). Maybe we
2353 * should try to use that function instead.
2357 * Check consistency of arguments
2359 if (into->onCommit != ONCOMMIT_NOOP
2360 && into->rel->relpersistence != RELPERSISTENCE_TEMP)
2362 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2363 errmsg("ON COMMIT can only be used on temporary tables")));
2366 * Security check: disallow creating temp tables from security-restricted
2367 * code. This is needed because calling code might not expect untrusted
2368 * tables to appear in pg_temp at the front of its search path.
2370 if (into->rel->relpersistence == RELPERSISTENCE_TEMP
2371 && InSecurityRestrictedOperation())
2373 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2374 errmsg("cannot create temporary table within security-restricted operation")));
2377 * Find namespace to create in, check its permissions
2379 intoName = into->rel->relname;
2380 namespaceId = RangeVarGetAndCheckCreationNamespace(into->rel);
2383 * Select tablespace to use. If not specified, use default tablespace
2384 * (which may in turn default to database's default).
2386 if (into->tableSpaceName)
2388 tablespaceId = get_tablespace_oid(into->tableSpaceName, false);
2392 tablespaceId = GetDefaultTablespace(into->rel->relpersistence);
2393 /* note InvalidOid is OK in this case */
2396 /* Check permissions except when using the database's default space */
2397 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
2399 AclResult aclresult;
2401 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
2404 if (aclresult != ACLCHECK_OK)
2405 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
2406 get_tablespace_name(tablespaceId));
2409 /* Parse and validate any reloptions */
2410 reloptions = transformRelOptions((Datum) 0,
2416 (void) heap_reloptions(RELKIND_RELATION, reloptions, true);
2418 /* Copy the tupdesc because heap_create_with_catalog modifies it */
2419 tupdesc = CreateTupleDescCopy(queryDesc->tupDesc);
2421 /* Now we can actually create the new relation */
2422 intoRelationId = heap_create_with_catalog(intoName,
2432 into->rel->relpersistence,
2440 allowSystemTableMods);
2441 Assert(intoRelationId != InvalidOid);
2443 FreeTupleDesc(tupdesc);
2446 * Advance command counter so that the newly-created relation's catalog
2447 * tuples will be visible to heap_open.
2449 CommandCounterIncrement();
2452 * If necessary, create a TOAST table for the INTO relation. Note that
2453 * AlterTableCreateToastTable ends with CommandCounterIncrement(), so that
2454 * the TOAST table will be visible for insertion.
2456 reloptions = transformRelOptions((Datum) 0,
2463 (void) heap_reloptions(RELKIND_TOASTVALUE, reloptions, true);
2465 AlterTableCreateToastTable(intoRelationId, reloptions);
2468 * And open the constructed table for writing.
2470 intoRelationDesc = heap_open(intoRelationId, AccessExclusiveLock);
2473 * Now replace the query's DestReceiver with one for SELECT INTO
2475 queryDesc->dest = CreateDestReceiver(DestIntoRel);
2476 myState = (DR_intorel *) queryDesc->dest;
2477 Assert(myState->pub.mydest == DestIntoRel);
2478 myState->estate = estate;
2479 myState->rel = intoRelationDesc;
2482 * We can skip WAL-logging the insertions, unless PITR or streaming
2483 * replication is in use. We can skip the FSM in any case.
2485 myState->hi_options = HEAP_INSERT_SKIP_FSM |
2486 (XLogIsNeeded() ? 0 : HEAP_INSERT_SKIP_WAL);
2487 myState->bistate = GetBulkInsertState();
2489 /* Not using WAL requires smgr_targblock be initially invalid */
2490 Assert(RelationGetTargetBlock(intoRelationDesc) == InvalidBlockNumber);
2494 * CloseIntoRel --- clean up SELECT INTO at ExecutorEnd time
2497 CloseIntoRel(QueryDesc *queryDesc)
2499 DR_intorel *myState = (DR_intorel *) queryDesc->dest;
2501 /* OpenIntoRel might never have gotten called */
2502 if (myState && myState->pub.mydest == DestIntoRel && myState->rel)
2504 FreeBulkInsertState(myState->bistate);
2506 /* If we skipped using WAL, must heap_sync before commit */
2507 if (myState->hi_options & HEAP_INSERT_SKIP_WAL)
2508 heap_sync(myState->rel);
2510 /* close rel, but keep lock until commit */
2511 heap_close(myState->rel, NoLock);
2513 myState->rel = NULL;
2518 * CreateIntoRelDestReceiver -- create a suitable DestReceiver object
2521 CreateIntoRelDestReceiver(void)
2523 DR_intorel *self = (DR_intorel *) palloc0(sizeof(DR_intorel));
2525 self->pub.receiveSlot = intorel_receive;
2526 self->pub.rStartup = intorel_startup;
2527 self->pub.rShutdown = intorel_shutdown;
2528 self->pub.rDestroy = intorel_destroy;
2529 self->pub.mydest = DestIntoRel;
2531 /* private fields will be set by OpenIntoRel */
2533 return (DestReceiver *) self;
2537 * intorel_startup --- executor startup
2540 intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
2546 * intorel_receive --- receive one tuple
2549 intorel_receive(TupleTableSlot *slot, DestReceiver *self)
2551 DR_intorel *myState = (DR_intorel *) self;
2555 * get the heap tuple out of the tuple table slot, making sure we have a
2558 tuple = ExecMaterializeSlot(slot);
2561 * force assignment of new OID (see comments in ExecInsert)
2563 if (myState->rel->rd_rel->relhasoids)
2564 HeapTupleSetOid(tuple, InvalidOid);
2566 heap_insert(myState->rel,
2568 myState->estate->es_output_cid,
2569 myState->hi_options,
2572 /* We know this is a newly created relation, so there are no indexes */
2576 * intorel_shutdown --- executor end
2579 intorel_shutdown(DestReceiver *self)
2585 * intorel_destroy --- release DestReceiver object
2588 intorel_destroy(DestReceiver *self)