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 CheckValidRowMarkRel(Relation rel, RowMarkType markType);
78 static void ExecPostprocessPlan(EState *estate);
79 static void ExecEndPlan(PlanState *planstate, EState *estate);
80 static void ExecutePlan(EState *estate, PlanState *planstate,
84 ScanDirection direction,
86 static bool ExecCheckRTEPerms(RangeTblEntry *rte);
87 static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
88 static void EvalPlanQualStart(EPQState *epqstate, EState *parentestate,
90 static void OpenIntoRel(QueryDesc *queryDesc);
91 static void CloseIntoRel(QueryDesc *queryDesc);
92 static void intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
93 static void intorel_receive(TupleTableSlot *slot, DestReceiver *self);
94 static void intorel_shutdown(DestReceiver *self);
95 static void intorel_destroy(DestReceiver *self);
97 /* end of local decls */
100 /* ----------------------------------------------------------------
103 * This routine must be called at the beginning of any execution of any
106 * Takes a QueryDesc previously created by CreateQueryDesc (which is separate
107 * only because some places use QueryDescs for utility commands). The tupDesc
108 * field of the QueryDesc is filled in to describe the tuples that will be
109 * returned, and the internal fields (estate and planstate) are set up.
111 * eflags contains flag bits as described in executor.h.
113 * NB: the CurrentMemoryContext when this is called will become the parent
114 * of the per-query context used for this Executor invocation.
116 * We provide a function hook variable that lets loadable plugins
117 * get control when ExecutorStart is called. Such a plugin would
118 * normally call standard_ExecutorStart().
120 * ----------------------------------------------------------------
123 ExecutorStart(QueryDesc *queryDesc, int eflags)
125 if (ExecutorStart_hook)
126 (*ExecutorStart_hook) (queryDesc, eflags);
128 standard_ExecutorStart(queryDesc, eflags);
132 standard_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 external parameters, if any, from queryDesc; and allocate
158 * workspace for internal parameters
160 estate->es_param_list_info = queryDesc->params;
162 if (queryDesc->plannedstmt->nParamExec > 0)
163 estate->es_param_exec_vals = (ParamExecData *)
164 palloc0(queryDesc->plannedstmt->nParamExec * sizeof(ParamExecData));
167 * If non-read-only query, set the command ID to mark output tuples with
169 switch (queryDesc->operation)
174 * SELECT INTO, SELECT FOR UPDATE/SHARE and modifying CTEs need to
177 if (queryDesc->plannedstmt->intoClause != NULL ||
178 queryDesc->plannedstmt->rowMarks != NIL ||
179 queryDesc->plannedstmt->hasModifyingCTE)
180 estate->es_output_cid = GetCurrentCommandId(true);
183 * A SELECT without modifying CTEs can't possibly queue triggers,
184 * so force skip-triggers mode. This is just a marginal efficiency
185 * hack, since AfterTriggerBeginQuery/AfterTriggerEndQuery aren't
186 * all that expensive, but we might as well do it.
188 if (!queryDesc->plannedstmt->hasModifyingCTE)
189 eflags |= EXEC_FLAG_SKIP_TRIGGERS;
195 estate->es_output_cid = GetCurrentCommandId(true);
199 elog(ERROR, "unrecognized operation code: %d",
200 (int) queryDesc->operation);
205 * Copy other important information into the EState
207 estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
208 estate->es_crosscheck_snapshot = RegisterSnapshot(queryDesc->crosscheck_snapshot);
209 estate->es_top_eflags = eflags;
210 estate->es_instrument = queryDesc->instrument_options;
213 * Initialize the plan state tree
215 InitPlan(queryDesc, eflags);
218 * Set up an AFTER-trigger statement context, unless told not to, or
219 * unless it's EXPLAIN-only mode (when ExecutorFinish won't be called).
221 if (!(eflags & (EXEC_FLAG_SKIP_TRIGGERS | EXEC_FLAG_EXPLAIN_ONLY)))
222 AfterTriggerBeginQuery();
224 MemoryContextSwitchTo(oldcontext);
227 /* ----------------------------------------------------------------
230 * This is the main routine of the executor module. It accepts
231 * the query descriptor from the traffic cop and executes the
234 * ExecutorStart must have been called already.
236 * If direction is NoMovementScanDirection then nothing is done
237 * except to start up/shut down the destination. Otherwise,
238 * we retrieve up to 'count' tuples in the specified direction.
240 * Note: count = 0 is interpreted as no portal limit, i.e., run to
243 * There is no return value, but output tuples (if any) are sent to
244 * the destination receiver specified in the QueryDesc; and the number
245 * of tuples processed at the top level can be found in
246 * estate->es_processed.
248 * We provide a function hook variable that lets loadable plugins
249 * get control when ExecutorRun is called. Such a plugin would
250 * normally call standard_ExecutorRun().
252 * ----------------------------------------------------------------
255 ExecutorRun(QueryDesc *queryDesc,
256 ScanDirection direction, long count)
258 if (ExecutorRun_hook)
259 (*ExecutorRun_hook) (queryDesc, direction, count);
261 standard_ExecutorRun(queryDesc, direction, count);
265 standard_ExecutorRun(QueryDesc *queryDesc,
266 ScanDirection direction, long count)
272 MemoryContext oldcontext;
275 Assert(queryDesc != NULL);
277 estate = queryDesc->estate;
279 Assert(estate != NULL);
280 Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
283 * Switch into per-query memory context
285 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
287 /* Allow instrumentation of Executor overall runtime */
288 if (queryDesc->totaltime)
289 InstrStartNode(queryDesc->totaltime);
292 * extract information from the query descriptor and the query feature.
294 operation = queryDesc->operation;
295 dest = queryDesc->dest;
298 * startup tuple receiver, if we will be emitting tuples
300 estate->es_processed = 0;
301 estate->es_lastoid = InvalidOid;
303 sendTuples = (operation == CMD_SELECT ||
304 queryDesc->plannedstmt->hasReturning);
307 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
312 if (!ScanDirectionIsNoMovement(direction))
314 queryDesc->planstate,
322 * shutdown tuple receiver, if we started it
325 (*dest->rShutdown) (dest);
327 if (queryDesc->totaltime)
328 InstrStopNode(queryDesc->totaltime, estate->es_processed);
330 MemoryContextSwitchTo(oldcontext);
333 /* ----------------------------------------------------------------
336 * This routine must be called after the last ExecutorRun call.
337 * It performs cleanup such as firing AFTER triggers. It is
338 * separate from ExecutorEnd because EXPLAIN ANALYZE needs to
339 * include these actions in the total runtime.
341 * We provide a function hook variable that lets loadable plugins
342 * get control when ExecutorFinish is called. Such a plugin would
343 * normally call standard_ExecutorFinish().
345 * ----------------------------------------------------------------
348 ExecutorFinish(QueryDesc *queryDesc)
350 if (ExecutorFinish_hook)
351 (*ExecutorFinish_hook) (queryDesc);
353 standard_ExecutorFinish(queryDesc);
357 standard_ExecutorFinish(QueryDesc *queryDesc)
360 MemoryContext oldcontext;
363 Assert(queryDesc != NULL);
365 estate = queryDesc->estate;
367 Assert(estate != NULL);
368 Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
370 /* This should be run once and only once per Executor instance */
371 Assert(!estate->es_finished);
373 /* Switch into per-query memory context */
374 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
376 /* Allow instrumentation of Executor overall runtime */
377 if (queryDesc->totaltime)
378 InstrStartNode(queryDesc->totaltime);
380 /* Run ModifyTable nodes to completion */
381 ExecPostprocessPlan(estate);
383 /* Execute queued AFTER triggers, unless told not to */
384 if (!(estate->es_top_eflags & EXEC_FLAG_SKIP_TRIGGERS))
385 AfterTriggerEndQuery(estate);
387 if (queryDesc->totaltime)
388 InstrStopNode(queryDesc->totaltime, 0);
390 MemoryContextSwitchTo(oldcontext);
392 estate->es_finished = true;
395 /* ----------------------------------------------------------------
398 * This routine must be called at the end of execution of any
401 * We provide a function hook variable that lets loadable plugins
402 * get control when ExecutorEnd is called. Such a plugin would
403 * normally call standard_ExecutorEnd().
405 * ----------------------------------------------------------------
408 ExecutorEnd(QueryDesc *queryDesc)
410 if (ExecutorEnd_hook)
411 (*ExecutorEnd_hook) (queryDesc);
413 standard_ExecutorEnd(queryDesc);
417 standard_ExecutorEnd(QueryDesc *queryDesc)
420 MemoryContext oldcontext;
423 Assert(queryDesc != NULL);
425 estate = queryDesc->estate;
427 Assert(estate != NULL);
430 * Check that ExecutorFinish was called, unless in EXPLAIN-only mode. This
431 * Assert is needed because ExecutorFinish is new as of 9.1, and callers
432 * might forget to call it.
434 Assert(estate->es_finished ||
435 (estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
438 * Switch into per-query memory context to run ExecEndPlan
440 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
442 ExecEndPlan(queryDesc->planstate, estate);
445 * Close the SELECT INTO relation if any
447 if (estate->es_select_into)
448 CloseIntoRel(queryDesc);
450 /* do away with our snapshots */
451 UnregisterSnapshot(estate->es_snapshot);
452 UnregisterSnapshot(estate->es_crosscheck_snapshot);
455 * Must switch out of context before destroying it
457 MemoryContextSwitchTo(oldcontext);
460 * Release EState and per-query memory context. This should release
461 * everything the executor has allocated.
463 FreeExecutorState(estate);
465 /* Reset queryDesc fields that no longer point to anything */
466 queryDesc->tupDesc = NULL;
467 queryDesc->estate = NULL;
468 queryDesc->planstate = NULL;
469 queryDesc->totaltime = NULL;
472 /* ----------------------------------------------------------------
475 * This routine may be called on an open queryDesc to rewind it
477 * ----------------------------------------------------------------
480 ExecutorRewind(QueryDesc *queryDesc)
483 MemoryContext oldcontext;
486 Assert(queryDesc != NULL);
488 estate = queryDesc->estate;
490 Assert(estate != NULL);
492 /* It's probably not sensible to rescan updating queries */
493 Assert(queryDesc->operation == CMD_SELECT);
496 * Switch into per-query memory context
498 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
503 ExecReScan(queryDesc->planstate);
505 MemoryContextSwitchTo(oldcontext);
511 * Check access permissions for all relations listed in a range table.
513 * Returns true if permissions are adequate. Otherwise, throws an appropriate
514 * error if ereport_on_violation is true, or simply returns false otherwise.
517 ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
522 foreach(l, rangeTable)
524 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
526 result = ExecCheckRTEPerms(rte);
529 Assert(rte->rtekind == RTE_RELATION);
530 if (ereport_on_violation)
531 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
532 get_rel_name(rte->relid));
537 if (ExecutorCheckPerms_hook)
538 result = (*ExecutorCheckPerms_hook) (rangeTable,
539 ereport_on_violation);
545 * Check access permissions for a single RTE.
548 ExecCheckRTEPerms(RangeTblEntry *rte)
550 AclMode requiredPerms;
552 AclMode remainingPerms;
559 * Only plain-relation RTEs need to be checked here. Function RTEs are
560 * checked by init_fcache when the function is prepared for execution.
561 * Join, subquery, and special RTEs need no checks.
563 if (rte->rtekind != RTE_RELATION)
567 * No work if requiredPerms is empty.
569 requiredPerms = rte->requiredPerms;
570 if (requiredPerms == 0)
576 * userid to check as: current user unless we have a setuid indication.
578 * Note: GetUserId() is presently fast enough that there's no harm in
579 * calling it separately for each RTE. If that stops being true, we could
580 * call it once in ExecCheckRTPerms and pass the userid down from there.
581 * But for now, no need for the extra clutter.
583 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
586 * We must have *all* the requiredPerms bits, but some of the bits can be
587 * satisfied from column-level rather than relation-level permissions.
588 * First, remove any bits that are satisfied by relation permissions.
590 relPerms = pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL);
591 remainingPerms = requiredPerms & ~relPerms;
592 if (remainingPerms != 0)
595 * If we lack any permissions that exist only as relation permissions,
596 * we can fail straight away.
598 if (remainingPerms & ~(ACL_SELECT | ACL_INSERT | ACL_UPDATE))
602 * Check to see if we have the needed privileges at column level.
604 * Note: failures just report a table-level error; it would be nicer
605 * to report a column-level error if we have some but not all of the
608 if (remainingPerms & ACL_SELECT)
611 * When the query doesn't explicitly reference any columns (for
612 * example, SELECT COUNT(*) FROM table), allow the query if we
613 * have SELECT on any column of the rel, as per SQL spec.
615 if (bms_is_empty(rte->selectedCols))
617 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
618 ACLMASK_ANY) != ACLCHECK_OK)
622 tmpset = bms_copy(rte->selectedCols);
623 while ((col = bms_first_member(tmpset)) >= 0)
625 /* remove the column number offset */
626 col += FirstLowInvalidHeapAttributeNumber;
627 if (col == InvalidAttrNumber)
629 /* Whole-row reference, must have priv on all cols */
630 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
631 ACLMASK_ALL) != ACLCHECK_OK)
636 if (pg_attribute_aclcheck(relOid, col, userid,
637 ACL_SELECT) != ACLCHECK_OK)
645 * Basically the same for the mod columns, with either INSERT or
646 * UPDATE privilege as specified by remainingPerms.
648 remainingPerms &= ~ACL_SELECT;
649 if (remainingPerms != 0)
652 * When the query doesn't explicitly change any columns, allow the
653 * query if we have permission on any column of the rel. This is
654 * to handle SELECT FOR UPDATE as well as possible corner cases in
657 if (bms_is_empty(rte->modifiedCols))
659 if (pg_attribute_aclcheck_all(relOid, userid, remainingPerms,
660 ACLMASK_ANY) != ACLCHECK_OK)
664 tmpset = bms_copy(rte->modifiedCols);
665 while ((col = bms_first_member(tmpset)) >= 0)
667 /* remove the column number offset */
668 col += FirstLowInvalidHeapAttributeNumber;
669 if (col == InvalidAttrNumber)
671 /* whole-row reference can't happen here */
672 elog(ERROR, "whole-row update is not implemented");
676 if (pg_attribute_aclcheck(relOid, col, userid,
677 remainingPerms) != ACLCHECK_OK)
688 * Check that the query does not imply any writes to non-temp tables.
690 * Note: in a Hot Standby slave this would need to reject writes to temp
691 * tables as well; but an HS slave can't have created any temp tables
692 * in the first place, so no need to check that.
695 ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
700 * CREATE TABLE AS or SELECT INTO?
702 * XXX should we allow this if the destination is temp? Considering that
703 * it would still require catalog changes, probably not.
705 if (plannedstmt->intoClause != NULL)
706 PreventCommandIfReadOnly(CreateCommandTag((Node *) plannedstmt));
708 /* Fail if write permissions are requested on any non-temp table */
709 foreach(l, plannedstmt->rtable)
711 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
713 if (rte->rtekind != RTE_RELATION)
716 if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
719 if (isTempNamespace(get_rel_namespace(rte->relid)))
722 PreventCommandIfReadOnly(CreateCommandTag((Node *) plannedstmt));
727 /* ----------------------------------------------------------------
730 * Initializes the query plan: open files, allocate storage
731 * and start up the rule manager
732 * ----------------------------------------------------------------
735 InitPlan(QueryDesc *queryDesc, int eflags)
737 CmdType operation = queryDesc->operation;
738 PlannedStmt *plannedstmt = queryDesc->plannedstmt;
739 Plan *plan = plannedstmt->planTree;
740 List *rangeTable = plannedstmt->rtable;
741 EState *estate = queryDesc->estate;
742 PlanState *planstate;
748 * Do permissions checks
750 ExecCheckRTPerms(rangeTable, true);
753 * initialize the node's execution state
755 estate->es_range_table = rangeTable;
756 estate->es_plannedstmt = plannedstmt;
759 * initialize result relation stuff, and open/lock the result rels.
761 * We must do this before initializing the plan tree, else we might try to
762 * do a lock upgrade if a result rel is also a source rel.
764 if (plannedstmt->resultRelations)
766 List *resultRelations = plannedstmt->resultRelations;
767 int numResultRelations = list_length(resultRelations);
768 ResultRelInfo *resultRelInfos;
769 ResultRelInfo *resultRelInfo;
771 resultRelInfos = (ResultRelInfo *)
772 palloc(numResultRelations * sizeof(ResultRelInfo));
773 resultRelInfo = resultRelInfos;
774 foreach(l, resultRelations)
776 Index resultRelationIndex = lfirst_int(l);
777 Oid resultRelationOid;
778 Relation resultRelation;
780 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
781 resultRelation = heap_open(resultRelationOid, RowExclusiveLock);
782 InitResultRelInfo(resultRelInfo,
785 estate->es_instrument);
788 estate->es_result_relations = resultRelInfos;
789 estate->es_num_result_relations = numResultRelations;
790 /* es_result_relation_info is NULL except when within ModifyTable */
791 estate->es_result_relation_info = NULL;
796 * if no result relation, then set state appropriately
798 estate->es_result_relations = NULL;
799 estate->es_num_result_relations = 0;
800 estate->es_result_relation_info = NULL;
804 * Similarly, we have to lock relations selected FOR UPDATE/FOR SHARE
805 * before we initialize the plan tree, else we'd be risking lock upgrades.
806 * While we are at it, build the ExecRowMark list.
808 estate->es_rowMarks = NIL;
809 foreach(l, plannedstmt->rowMarks)
811 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
816 /* ignore "parent" rowmarks; they are irrelevant at runtime */
820 switch (rc->markType)
822 case ROW_MARK_EXCLUSIVE:
824 relid = getrelid(rc->rti, rangeTable);
825 relation = heap_open(relid, RowShareLock);
827 case ROW_MARK_REFERENCE:
828 relid = getrelid(rc->rti, rangeTable);
829 relation = heap_open(relid, AccessShareLock);
832 /* there's no real table here ... */
836 elog(ERROR, "unrecognized markType: %d", rc->markType);
837 relation = NULL; /* keep compiler quiet */
841 /* Check that relation is a legal target for marking */
843 CheckValidRowMarkRel(relation, rc->markType);
845 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
846 erm->relation = relation;
848 erm->prti = rc->prti;
849 erm->rowmarkId = rc->rowmarkId;
850 erm->markType = rc->markType;
851 erm->noWait = rc->noWait;
852 ItemPointerSetInvalid(&(erm->curCtid));
853 estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
857 * Detect whether we're doing SELECT INTO. If so, set the es_into_oids
858 * flag appropriately so that the plan tree will be initialized with the
859 * correct tuple descriptors. (Other SELECT INTO stuff comes later.)
861 estate->es_select_into = false;
862 if (operation == CMD_SELECT && plannedstmt->intoClause != NULL)
864 estate->es_select_into = true;
865 estate->es_into_oids = interpretOidsOption(plannedstmt->intoClause->options);
869 * Initialize the executor's tuple table to empty.
871 estate->es_tupleTable = NIL;
872 estate->es_trig_tuple_slot = NULL;
873 estate->es_trig_oldtup_slot = NULL;
875 /* mark EvalPlanQual not active */
876 estate->es_epqTuple = NULL;
877 estate->es_epqTupleSet = NULL;
878 estate->es_epqScanDone = NULL;
881 * Initialize private state information for each SubPlan. We must do this
882 * before running ExecInitNode on the main query tree, since
883 * ExecInitSubPlan expects to be able to find these entries.
885 Assert(estate->es_subplanstates == NIL);
886 i = 1; /* subplan indices count from 1 */
887 foreach(l, plannedstmt->subplans)
889 Plan *subplan = (Plan *) lfirst(l);
890 PlanState *subplanstate;
894 * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
895 * it is a parameterless subplan (not initplan), we suggest that it be
896 * prepared to handle REWIND efficiently; otherwise there is no need.
898 sp_eflags = eflags & EXEC_FLAG_EXPLAIN_ONLY;
899 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
900 sp_eflags |= EXEC_FLAG_REWIND;
902 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
904 estate->es_subplanstates = lappend(estate->es_subplanstates,
911 * Initialize the private state information for all the nodes in the query
912 * tree. This opens files, allocates storage and leaves us ready to start
915 planstate = ExecInitNode(plan, estate, eflags);
918 * Get the tuple descriptor describing the type of tuples to return. (this
919 * is especially important if we are creating a relation with "SELECT
922 tupType = ExecGetResultType(planstate);
925 * Initialize the junk filter if needed. SELECT queries need a filter if
926 * there are any junk attrs in the top-level tlist.
928 if (operation == CMD_SELECT)
930 bool junk_filter_needed = false;
933 foreach(tlist, plan->targetlist)
935 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
939 junk_filter_needed = true;
944 if (junk_filter_needed)
948 j = ExecInitJunkFilter(planstate->plan->targetlist,
950 ExecInitExtraTupleSlot(estate));
951 estate->es_junkFilter = j;
953 /* Want to return the cleaned tuple type */
954 tupType = j->jf_cleanTupType;
958 queryDesc->tupDesc = tupType;
959 queryDesc->planstate = planstate;
962 * If doing SELECT INTO, initialize the "into" relation. We must wait
963 * till now so we have the "clean" result tuple type to create the new
966 * If EXPLAIN, skip creating the "into" relation.
968 if (estate->es_select_into && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
969 OpenIntoRel(queryDesc);
973 * Check that a proposed result relation is a legal target for the operation
975 * In most cases parser and/or planner should have noticed this already, but
976 * let's make sure. In the view case we do need a test here, because if the
977 * view wasn't rewritten by a rule, it had better have an INSTEAD trigger.
979 * Note: when changing this function, you probably also need to look at
980 * CheckValidRowMarkRel.
983 CheckValidResultRel(Relation resultRel, CmdType operation)
985 TriggerDesc *trigDesc = resultRel->trigdesc;
987 switch (resultRel->rd_rel->relkind)
989 case RELKIND_RELATION:
992 case RELKIND_SEQUENCE:
994 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
995 errmsg("cannot change sequence \"%s\"",
996 RelationGetRelationName(resultRel))));
998 case RELKIND_TOASTVALUE:
1000 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1001 errmsg("cannot change TOAST relation \"%s\"",
1002 RelationGetRelationName(resultRel))));
1008 if (!trigDesc || !trigDesc->trig_insert_instead_row)
1010 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1011 errmsg("cannot insert into view \"%s\"",
1012 RelationGetRelationName(resultRel)),
1013 errhint("You need an unconditional ON INSERT DO INSTEAD rule or an INSTEAD OF INSERT trigger.")));
1016 if (!trigDesc || !trigDesc->trig_update_instead_row)
1018 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1019 errmsg("cannot update view \"%s\"",
1020 RelationGetRelationName(resultRel)),
1021 errhint("You need an unconditional ON UPDATE DO INSTEAD rule or an INSTEAD OF UPDATE trigger.")));
1024 if (!trigDesc || !trigDesc->trig_delete_instead_row)
1026 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1027 errmsg("cannot delete from view \"%s\"",
1028 RelationGetRelationName(resultRel)),
1029 errhint("You need an unconditional ON DELETE DO INSTEAD rule or an INSTEAD OF DELETE trigger.")));
1032 elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1036 case RELKIND_FOREIGN_TABLE:
1038 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1039 errmsg("cannot change foreign table \"%s\"",
1040 RelationGetRelationName(resultRel))));
1044 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1045 errmsg("cannot change relation \"%s\"",
1046 RelationGetRelationName(resultRel))));
1052 * Check that a proposed rowmark target relation is a legal target
1054 * In most cases parser and/or planner should have noticed this already, but
1055 * they don't cover all cases.
1058 CheckValidRowMarkRel(Relation rel, RowMarkType markType)
1060 switch (rel->rd_rel->relkind)
1062 case RELKIND_RELATION:
1065 case RELKIND_SEQUENCE:
1066 /* Must disallow this because we don't vacuum sequences */
1068 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1069 errmsg("cannot lock rows in sequence \"%s\"",
1070 RelationGetRelationName(rel))));
1072 case RELKIND_TOASTVALUE:
1073 /* We could allow this, but there seems no good reason to */
1075 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1076 errmsg("cannot lock rows in TOAST relation \"%s\"",
1077 RelationGetRelationName(rel))));
1080 /* Should not get here */
1082 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1083 errmsg("cannot lock rows in view \"%s\"",
1084 RelationGetRelationName(rel))));
1086 case RELKIND_FOREIGN_TABLE:
1087 /* Perhaps we can support this someday, but not today */
1089 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1090 errmsg("cannot lock rows in foreign table \"%s\"",
1091 RelationGetRelationName(rel))));
1095 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1096 errmsg("cannot lock rows in relation \"%s\"",
1097 RelationGetRelationName(rel))));
1103 * Initialize ResultRelInfo data for one result relation
1105 * Caution: before Postgres 9.1, this function included the relkind checking
1106 * that's now in CheckValidResultRel, and it also did ExecOpenIndices if
1107 * appropriate. Be sure callers cover those needs.
1110 InitResultRelInfo(ResultRelInfo *resultRelInfo,
1111 Relation resultRelationDesc,
1112 Index resultRelationIndex,
1113 int instrument_options)
1115 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1116 resultRelInfo->type = T_ResultRelInfo;
1117 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1118 resultRelInfo->ri_RelationDesc = resultRelationDesc;
1119 resultRelInfo->ri_NumIndices = 0;
1120 resultRelInfo->ri_IndexRelationDescs = NULL;
1121 resultRelInfo->ri_IndexRelationInfo = NULL;
1122 /* make a copy so as not to depend on relcache info not changing... */
1123 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1124 if (resultRelInfo->ri_TrigDesc)
1126 int n = resultRelInfo->ri_TrigDesc->numtriggers;
1128 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1129 palloc0(n * sizeof(FmgrInfo));
1130 resultRelInfo->ri_TrigWhenExprs = (List **)
1131 palloc0(n * sizeof(List *));
1132 if (instrument_options)
1133 resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options);
1137 resultRelInfo->ri_TrigFunctions = NULL;
1138 resultRelInfo->ri_TrigWhenExprs = NULL;
1139 resultRelInfo->ri_TrigInstrument = NULL;
1141 resultRelInfo->ri_ConstraintExprs = NULL;
1142 resultRelInfo->ri_junkFilter = NULL;
1143 resultRelInfo->ri_projectReturning = NULL;
1147 * ExecGetTriggerResultRel
1149 * Get a ResultRelInfo for a trigger target relation. Most of the time,
1150 * triggers are fired on one of the result relations of the query, and so
1151 * we can just return a member of the es_result_relations array. (Note: in
1152 * self-join situations there might be multiple members with the same OID;
1153 * if so it doesn't matter which one we pick.) However, it is sometimes
1154 * necessary to fire triggers on other relations; this happens mainly when an
1155 * RI update trigger queues additional triggers on other relations, which will
1156 * be processed in the context of the outer query. For efficiency's sake,
1157 * we want to have a ResultRelInfo for those triggers too; that can avoid
1158 * repeated re-opening of the relation. (It also provides a way for EXPLAIN
1159 * ANALYZE to report the runtimes of such triggers.) So we make additional
1160 * ResultRelInfo's as needed, and save them in es_trig_target_relations.
1163 ExecGetTriggerResultRel(EState *estate, Oid relid)
1165 ResultRelInfo *rInfo;
1169 MemoryContext oldcontext;
1171 /* First, search through the query result relations */
1172 rInfo = estate->es_result_relations;
1173 nr = estate->es_num_result_relations;
1176 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1181 /* Nope, but maybe we already made an extra ResultRelInfo for it */
1182 foreach(l, estate->es_trig_target_relations)
1184 rInfo = (ResultRelInfo *) lfirst(l);
1185 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1188 /* Nope, so we need a new one */
1191 * Open the target relation's relcache entry. We assume that an
1192 * appropriate lock is still held by the backend from whenever the trigger
1193 * event got queued, so we need take no new lock here. Also, we need not
1194 * recheck the relkind, so no need for CheckValidResultRel.
1196 rel = heap_open(relid, NoLock);
1199 * Make the new entry in the right context.
1201 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1202 rInfo = makeNode(ResultRelInfo);
1203 InitResultRelInfo(rInfo,
1205 0, /* dummy rangetable index */
1206 estate->es_instrument);
1207 estate->es_trig_target_relations =
1208 lappend(estate->es_trig_target_relations, rInfo);
1209 MemoryContextSwitchTo(oldcontext);
1212 * Currently, we don't need any index information in ResultRelInfos used
1213 * only for triggers, so no need to call ExecOpenIndices.
1220 * ExecContextForcesOids
1222 * This is pretty grotty: when doing INSERT, UPDATE, or SELECT INTO,
1223 * we need to ensure that result tuples have space for an OID iff they are
1224 * going to be stored into a relation that has OIDs. In other contexts
1225 * we are free to choose whether to leave space for OIDs in result tuples
1226 * (we generally don't want to, but we do if a physical-tlist optimization
1227 * is possible). This routine checks the plan context and returns TRUE if the
1228 * choice is forced, FALSE if the choice is not forced. In the TRUE case,
1229 * *hasoids is set to the required value.
1231 * One reason this is ugly is that all plan nodes in the plan tree will emit
1232 * tuples with space for an OID, though we really only need the topmost node
1233 * to do so. However, node types like Sort don't project new tuples but just
1234 * return their inputs, and in those cases the requirement propagates down
1235 * to the input node. Eventually we might make this code smart enough to
1236 * recognize how far down the requirement really goes, but for now we just
1237 * make all plan nodes do the same thing if the top level forces the choice.
1239 * We assume that if we are generating tuples for INSERT or UPDATE,
1240 * estate->es_result_relation_info is already set up to describe the target
1241 * relation. Note that in an UPDATE that spans an inheritance tree, some of
1242 * the target relations may have OIDs and some not. We have to make the
1243 * decisions on a per-relation basis as we initialize each of the subplans of
1244 * the ModifyTable node, so ModifyTable has to set es_result_relation_info
1245 * while initializing each subplan.
1247 * SELECT INTO is even uglier, because we don't have the INTO relation's
1248 * descriptor available when this code runs; we have to look aside at a
1249 * flag set by InitPlan().
1252 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
1254 ResultRelInfo *ri = planstate->state->es_result_relation_info;
1258 Relation rel = ri->ri_RelationDesc;
1262 *hasoids = rel->rd_rel->relhasoids;
1267 if (planstate->state->es_select_into)
1269 *hasoids = planstate->state->es_into_oids;
1276 /* ----------------------------------------------------------------
1277 * ExecPostprocessPlan
1279 * Give plan nodes a final chance to execute before shutdown
1280 * ----------------------------------------------------------------
1283 ExecPostprocessPlan(EState *estate)
1288 * Make sure nodes run forward.
1290 estate->es_direction = ForwardScanDirection;
1293 * Run any secondary ModifyTable nodes to completion, in case the main
1294 * query did not fetch all rows from them. (We do this to ensure that
1295 * such nodes have predictable results.)
1297 foreach(lc, estate->es_auxmodifytables)
1299 PlanState *ps = (PlanState *) lfirst(lc);
1303 TupleTableSlot *slot;
1305 /* Reset the per-output-tuple exprcontext each time */
1306 ResetPerTupleExprContext(estate);
1308 slot = ExecProcNode(ps);
1310 if (TupIsNull(slot))
1316 /* ----------------------------------------------------------------
1319 * Cleans up the query plan -- closes files and frees up storage
1321 * NOTE: we are no longer very worried about freeing storage per se
1322 * in this code; FreeExecutorState should be guaranteed to release all
1323 * memory that needs to be released. What we are worried about doing
1324 * is closing relations and dropping buffer pins. Thus, for example,
1325 * tuple tables must be cleared or dropped to ensure pins are released.
1326 * ----------------------------------------------------------------
1329 ExecEndPlan(PlanState *planstate, EState *estate)
1331 ResultRelInfo *resultRelInfo;
1336 * shut down the node-type-specific query processing
1338 ExecEndNode(planstate);
1343 foreach(l, estate->es_subplanstates)
1345 PlanState *subplanstate = (PlanState *) lfirst(l);
1347 ExecEndNode(subplanstate);
1351 * destroy the executor's tuple table. Actually we only care about
1352 * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1353 * the TupleTableSlots, since the containing memory context is about to go
1356 ExecResetTupleTable(estate->es_tupleTable, false);
1359 * close the result relation(s) if any, but hold locks until xact commit.
1361 resultRelInfo = estate->es_result_relations;
1362 for (i = estate->es_num_result_relations; i > 0; i--)
1364 /* Close indices and then the relation itself */
1365 ExecCloseIndices(resultRelInfo);
1366 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1371 * likewise close any trigger target relations
1373 foreach(l, estate->es_trig_target_relations)
1375 resultRelInfo = (ResultRelInfo *) lfirst(l);
1376 /* Close indices and then the relation itself */
1377 ExecCloseIndices(resultRelInfo);
1378 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1382 * close any relations selected FOR UPDATE/FOR SHARE, again keeping locks
1384 foreach(l, estate->es_rowMarks)
1386 ExecRowMark *erm = (ExecRowMark *) lfirst(l);
1389 heap_close(erm->relation, NoLock);
1393 /* ----------------------------------------------------------------
1396 * Processes the query plan until we have processed 'numberTuples' tuples,
1397 * moving in the specified direction.
1399 * Runs to completion if numberTuples is 0
1401 * Note: the ctid attribute is a 'junk' attribute that is removed before the
1403 * ----------------------------------------------------------------
1406 ExecutePlan(EState *estate,
1407 PlanState *planstate,
1411 ScanDirection direction,
1414 TupleTableSlot *slot;
1415 long current_tuple_count;
1418 * initialize local variables
1420 current_tuple_count = 0;
1423 * Set the direction.
1425 estate->es_direction = direction;
1428 * Loop until we've processed the proper number of tuples from the plan.
1432 /* Reset the per-output-tuple exprcontext */
1433 ResetPerTupleExprContext(estate);
1436 * Execute the plan and obtain a tuple
1438 slot = ExecProcNode(planstate);
1441 * if the tuple is null, then we assume there is nothing more to
1442 * process so we just end the loop...
1444 if (TupIsNull(slot))
1448 * If we have a junk filter, then project a new tuple with the junk
1451 * Store this new "clean" tuple in the junkfilter's resultSlot.
1452 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1453 * because that tuple slot has the wrong descriptor.)
1455 if (estate->es_junkFilter != NULL)
1456 slot = ExecFilterJunk(estate->es_junkFilter, slot);
1459 * If we are supposed to send the tuple somewhere, do so. (In
1460 * practice, this is probably always the case at this point.)
1463 (*dest->receiveSlot) (slot, dest);
1466 * Count tuples processed, if this is a SELECT. (For other operation
1467 * types, the ModifyTable plan node must count the appropriate
1470 if (operation == CMD_SELECT)
1471 (estate->es_processed)++;
1474 * check our tuple count.. if we've processed the proper number then
1475 * quit, else loop again and process more tuples. Zero numberTuples
1478 current_tuple_count++;
1479 if (numberTuples && numberTuples == current_tuple_count)
1486 * ExecRelCheck --- check that tuple meets constraints for result relation
1489 ExecRelCheck(ResultRelInfo *resultRelInfo,
1490 TupleTableSlot *slot, EState *estate)
1492 Relation rel = resultRelInfo->ri_RelationDesc;
1493 int ncheck = rel->rd_att->constr->num_check;
1494 ConstrCheck *check = rel->rd_att->constr->check;
1495 ExprContext *econtext;
1496 MemoryContext oldContext;
1501 * If first time through for this result relation, build expression
1502 * nodetrees for rel's constraint expressions. Keep them in the per-query
1503 * memory context so they'll survive throughout the query.
1505 if (resultRelInfo->ri_ConstraintExprs == NULL)
1507 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1508 resultRelInfo->ri_ConstraintExprs =
1509 (List **) palloc(ncheck * sizeof(List *));
1510 for (i = 0; i < ncheck; i++)
1512 /* ExecQual wants implicit-AND form */
1513 qual = make_ands_implicit(stringToNode(check[i].ccbin));
1514 resultRelInfo->ri_ConstraintExprs[i] = (List *)
1515 ExecPrepareExpr((Expr *) qual, estate);
1517 MemoryContextSwitchTo(oldContext);
1521 * We will use the EState's per-tuple context for evaluating constraint
1522 * expressions (creating it if it's not already there).
1524 econtext = GetPerTupleExprContext(estate);
1526 /* Arrange for econtext's scan tuple to be the tuple under test */
1527 econtext->ecxt_scantuple = slot;
1529 /* And evaluate the constraints */
1530 for (i = 0; i < ncheck; i++)
1532 qual = resultRelInfo->ri_ConstraintExprs[i];
1535 * NOTE: SQL92 specifies that a NULL result from a constraint
1536 * expression is not to be treated as a failure. Therefore, tell
1537 * ExecQual to return TRUE for NULL.
1539 if (!ExecQual(qual, econtext, true))
1540 return check[i].ccname;
1543 /* NULL result means no error */
1548 ExecConstraints(ResultRelInfo *resultRelInfo,
1549 TupleTableSlot *slot, EState *estate)
1551 Relation rel = resultRelInfo->ri_RelationDesc;
1552 TupleConstr *constr = rel->rd_att->constr;
1556 if (constr->has_not_null)
1558 int natts = rel->rd_att->natts;
1561 for (attrChk = 1; attrChk <= natts; attrChk++)
1563 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1564 slot_attisnull(slot, attrChk))
1566 (errcode(ERRCODE_NOT_NULL_VIOLATION),
1567 errmsg("null value in column \"%s\" violates not-null constraint",
1568 NameStr(rel->rd_att->attrs[attrChk - 1]->attname))));
1572 if (constr->num_check > 0)
1576 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1578 (errcode(ERRCODE_CHECK_VIOLATION),
1579 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1580 RelationGetRelationName(rel), failed)));
1586 * ExecFindRowMark -- find the ExecRowMark struct for given rangetable index
1589 ExecFindRowMark(EState *estate, Index rti)
1593 foreach(lc, estate->es_rowMarks)
1595 ExecRowMark *erm = (ExecRowMark *) lfirst(lc);
1597 if (erm->rti == rti)
1600 elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
1601 return NULL; /* keep compiler quiet */
1605 * ExecBuildAuxRowMark -- create an ExecAuxRowMark struct
1607 * Inputs are the underlying ExecRowMark struct and the targetlist of the
1608 * input plan node (not planstate node!). We need the latter to find out
1609 * the column numbers of the resjunk columns.
1612 ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
1614 ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
1617 aerm->rowmark = erm;
1619 /* Look up the resjunk columns associated with this rowmark */
1622 Assert(erm->markType != ROW_MARK_COPY);
1624 /* if child rel, need tableoid */
1625 if (erm->rti != erm->prti)
1627 snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
1628 aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
1630 if (!AttributeNumberIsValid(aerm->toidAttNo))
1631 elog(ERROR, "could not find junk %s column", resname);
1634 /* always need ctid for real relations */
1635 snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
1636 aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
1638 if (!AttributeNumberIsValid(aerm->ctidAttNo))
1639 elog(ERROR, "could not find junk %s column", resname);
1643 Assert(erm->markType == ROW_MARK_COPY);
1645 snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
1646 aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
1648 if (!AttributeNumberIsValid(aerm->wholeAttNo))
1649 elog(ERROR, "could not find junk %s column", resname);
1657 * EvalPlanQual logic --- recheck modified tuple(s) to see if we want to
1658 * process the updated version under READ COMMITTED rules.
1660 * See backend/executor/README for some info about how this works.
1665 * Check a modified tuple to see if we want to process its updated version
1666 * under READ COMMITTED rules.
1668 * estate - outer executor state data
1669 * epqstate - state for EvalPlanQual rechecking
1670 * relation - table containing tuple
1671 * rti - rangetable index of table containing tuple
1672 * *tid - t_ctid from the outdated tuple (ie, next updated version)
1673 * priorXmax - t_xmax from the outdated tuple
1675 * *tid is also an output parameter: it's modified to hold the TID of the
1676 * latest version of the tuple (note this may be changed even on failure)
1678 * Returns a slot containing the new candidate update/delete tuple, or
1679 * NULL if we determine we shouldn't process the row.
1682 EvalPlanQual(EState *estate, EPQState *epqstate,
1683 Relation relation, Index rti,
1684 ItemPointer tid, TransactionId priorXmax)
1686 TupleTableSlot *slot;
1687 HeapTuple copyTuple;
1692 * Get and lock the updated version of the row; if fail, return NULL.
1694 copyTuple = EvalPlanQualFetch(estate, relation, LockTupleExclusive,
1697 if (copyTuple == NULL)
1701 * For UPDATE/DELETE we have to return tid of actual row we're executing
1704 *tid = copyTuple->t_self;
1707 * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
1709 EvalPlanQualBegin(epqstate, estate);
1712 * Free old test tuple, if any, and store new tuple where relation's scan
1715 EvalPlanQualSetTuple(epqstate, rti, copyTuple);
1718 * Fetch any non-locked source rows
1720 EvalPlanQualFetchRowMarks(epqstate);
1723 * Run the EPQ query. We assume it will return at most one tuple.
1725 slot = EvalPlanQualNext(epqstate);
1728 * If we got a tuple, force the slot to materialize the tuple so that it
1729 * is not dependent on any local state in the EPQ query (in particular,
1730 * it's highly likely that the slot contains references to any pass-by-ref
1731 * datums that may be present in copyTuple). As with the next step, this
1732 * is to guard against early re-use of the EPQ query.
1734 if (!TupIsNull(slot))
1735 (void) ExecMaterializeSlot(slot);
1738 * Clear out the test tuple. This is needed in case the EPQ query is
1739 * re-used to test a tuple for a different relation. (Not clear that can
1740 * really happen, but let's be safe.)
1742 EvalPlanQualSetTuple(epqstate, rti, NULL);
1748 * Fetch a copy of the newest version of an outdated tuple
1750 * estate - executor state data
1751 * relation - table containing tuple
1752 * lockmode - requested tuple lock mode
1753 * *tid - t_ctid from the outdated tuple (ie, next updated version)
1754 * priorXmax - t_xmax from the outdated tuple
1756 * Returns a palloc'd copy of the newest tuple version, or NULL if we find
1757 * that there is no newest version (ie, the row was deleted not updated).
1758 * If successful, we have locked the newest tuple version, so caller does not
1759 * need to worry about it changing anymore.
1761 * Note: properly, lockmode should be declared as enum LockTupleMode,
1762 * but we use "int" to avoid having to include heapam.h in executor.h.
1765 EvalPlanQualFetch(EState *estate, Relation relation, int lockmode,
1766 ItemPointer tid, TransactionId priorXmax)
1768 HeapTuple copyTuple = NULL;
1769 HeapTupleData tuple;
1770 SnapshotData SnapshotDirty;
1773 * fetch target tuple
1775 * Loop here to deal with updated or busy tuples
1777 InitDirtySnapshot(SnapshotDirty);
1778 tuple.t_self = *tid;
1783 if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
1786 ItemPointerData update_ctid;
1787 TransactionId update_xmax;
1790 * If xmin isn't what we're expecting, the slot must have been
1791 * recycled and reused for an unrelated tuple. This implies that
1792 * the latest version of the row was deleted, so we need do
1793 * nothing. (Should be safe to examine xmin without getting
1794 * buffer's content lock, since xmin never changes in an existing
1797 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1800 ReleaseBuffer(buffer);
1804 /* otherwise xmin should not be dirty... */
1805 if (TransactionIdIsValid(SnapshotDirty.xmin))
1806 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
1809 * If tuple is being updated by other transaction then we have to
1810 * wait for its commit/abort.
1812 if (TransactionIdIsValid(SnapshotDirty.xmax))
1814 ReleaseBuffer(buffer);
1815 XactLockTableWait(SnapshotDirty.xmax);
1816 continue; /* loop back to repeat heap_fetch */
1820 * If tuple was inserted by our own transaction, we have to check
1821 * cmin against es_output_cid: cmin >= current CID means our
1822 * command cannot see the tuple, so we should ignore it. Without
1823 * this we are open to the "Halloween problem" of indefinitely
1824 * re-updating the same tuple. (We need not check cmax because
1825 * HeapTupleSatisfiesDirty will consider a tuple deleted by our
1826 * transaction dead, regardless of cmax.) We just checked that
1827 * priorXmax == xmin, so we can test that variable instead of
1828 * doing HeapTupleHeaderGetXmin again.
1830 if (TransactionIdIsCurrentTransactionId(priorXmax) &&
1831 HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
1833 ReleaseBuffer(buffer);
1838 * This is a live tuple, so now try to lock it.
1840 test = heap_lock_tuple(relation, &tuple, &buffer,
1841 &update_ctid, &update_xmax,
1842 estate->es_output_cid,
1844 /* We now have two pins on the buffer, get rid of one */
1845 ReleaseBuffer(buffer);
1849 case HeapTupleSelfUpdated:
1850 /* treat it as deleted; do not process */
1851 ReleaseBuffer(buffer);
1854 case HeapTupleMayBeUpdated:
1855 /* successfully locked */
1858 case HeapTupleUpdated:
1859 ReleaseBuffer(buffer);
1860 if (IsolationUsesXactSnapshot())
1862 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1863 errmsg("could not serialize access due to concurrent update")));
1864 if (!ItemPointerEquals(&update_ctid, &tuple.t_self))
1866 /* it was updated, so look at the updated version */
1867 tuple.t_self = update_ctid;
1868 /* updated row should have xmin matching this xmax */
1869 priorXmax = update_xmax;
1872 /* tuple was deleted, so give up */
1876 ReleaseBuffer(buffer);
1877 elog(ERROR, "unrecognized heap_lock_tuple status: %u",
1879 return NULL; /* keep compiler quiet */
1883 * We got tuple - now copy it for use by recheck query.
1885 copyTuple = heap_copytuple(&tuple);
1886 ReleaseBuffer(buffer);
1891 * If the referenced slot was actually empty, the latest version of
1892 * the row must have been deleted, so we need do nothing.
1894 if (tuple.t_data == NULL)
1896 ReleaseBuffer(buffer);
1901 * As above, if xmin isn't what we're expecting, do nothing.
1903 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1906 ReleaseBuffer(buffer);
1911 * If we get here, the tuple was found but failed SnapshotDirty.
1912 * Assuming the xmin is either a committed xact or our own xact (as it
1913 * certainly should be if we're trying to modify the tuple), this must
1914 * mean that the row was updated or deleted by either a committed xact
1915 * or our own xact. If it was deleted, we can ignore it; if it was
1916 * updated then chain up to the next version and repeat the whole
1919 * As above, it should be safe to examine xmax and t_ctid without the
1920 * buffer content lock, because they can't be changing.
1922 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
1924 /* deleted, so forget about it */
1925 ReleaseBuffer(buffer);
1929 /* updated, so look at the updated row */
1930 tuple.t_self = tuple.t_data->t_ctid;
1931 /* updated row should have xmin matching this xmax */
1932 priorXmax = HeapTupleHeaderGetXmax(tuple.t_data);
1933 ReleaseBuffer(buffer);
1934 /* loop back to fetch next in chain */
1938 * Return the copied tuple
1944 * EvalPlanQualInit -- initialize during creation of a plan state node
1945 * that might need to invoke EPQ processing.
1947 * Note: subplan/auxrowmarks can be NULL/NIL if they will be set later
1948 * with EvalPlanQualSetPlan.
1951 EvalPlanQualInit(EPQState *epqstate, EState *estate,
1952 Plan *subplan, List *auxrowmarks, int epqParam)
1954 /* Mark the EPQ state inactive */
1955 epqstate->estate = NULL;
1956 epqstate->planstate = NULL;
1957 epqstate->origslot = NULL;
1958 /* ... and remember data that EvalPlanQualBegin will need */
1959 epqstate->plan = subplan;
1960 epqstate->arowMarks = auxrowmarks;
1961 epqstate->epqParam = epqParam;
1965 * EvalPlanQualSetPlan -- set or change subplan of an EPQState.
1967 * We need this so that ModifyTuple can deal with multiple subplans.
1970 EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan, List *auxrowmarks)
1972 /* If we have a live EPQ query, shut it down */
1973 EvalPlanQualEnd(epqstate);
1974 /* And set/change the plan pointer */
1975 epqstate->plan = subplan;
1976 /* The rowmarks depend on the plan, too */
1977 epqstate->arowMarks = auxrowmarks;
1981 * Install one test tuple into EPQ state, or clear test tuple if tuple == NULL
1983 * NB: passed tuple must be palloc'd; it may get freed later
1986 EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
1988 EState *estate = epqstate->estate;
1993 * free old test tuple, if any, and store new tuple where relation's scan
1996 if (estate->es_epqTuple[rti - 1] != NULL)
1997 heap_freetuple(estate->es_epqTuple[rti - 1]);
1998 estate->es_epqTuple[rti - 1] = tuple;
1999 estate->es_epqTupleSet[rti - 1] = true;
2003 * Fetch back the current test tuple (if any) for the specified RTI
2006 EvalPlanQualGetTuple(EPQState *epqstate, Index rti)
2008 EState *estate = epqstate->estate;
2012 return estate->es_epqTuple[rti - 1];
2016 * Fetch the current row values for any non-locked relations that need
2017 * to be scanned by an EvalPlanQual operation. origslot must have been set
2018 * to contain the current result row (top-level row) that we need to recheck.
2021 EvalPlanQualFetchRowMarks(EPQState *epqstate)
2025 Assert(epqstate->origslot != NULL);
2027 foreach(l, epqstate->arowMarks)
2029 ExecAuxRowMark *aerm = (ExecAuxRowMark *) lfirst(l);
2030 ExecRowMark *erm = aerm->rowmark;
2033 HeapTupleData tuple;
2035 if (RowMarkRequiresRowShareLock(erm->markType))
2036 elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2038 /* clear any leftover test tuple for this rel */
2039 EvalPlanQualSetTuple(epqstate, erm->rti, NULL);
2045 Assert(erm->markType == ROW_MARK_REFERENCE);
2047 /* if child rel, must check whether it produced this row */
2048 if (erm->rti != erm->prti)
2052 datum = ExecGetJunkAttribute(epqstate->origslot,
2055 /* non-locked rels could be on the inside of outer joins */
2058 tableoid = DatumGetObjectId(datum);
2060 if (tableoid != RelationGetRelid(erm->relation))
2062 /* this child is inactive right now */
2067 /* fetch the tuple's ctid */
2068 datum = ExecGetJunkAttribute(epqstate->origslot,
2071 /* non-locked rels could be on the inside of outer joins */
2074 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
2076 /* okay, fetch the tuple */
2077 if (!heap_fetch(erm->relation, SnapshotAny, &tuple, &buffer,
2079 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2081 /* successful, copy and store tuple */
2082 EvalPlanQualSetTuple(epqstate, erm->rti,
2083 heap_copytuple(&tuple));
2084 ReleaseBuffer(buffer);
2090 Assert(erm->markType == ROW_MARK_COPY);
2092 /* fetch the whole-row Var for the relation */
2093 datum = ExecGetJunkAttribute(epqstate->origslot,
2096 /* non-locked rels could be on the inside of outer joins */
2099 td = DatumGetHeapTupleHeader(datum);
2101 /* build a temporary HeapTuple control structure */
2102 tuple.t_len = HeapTupleHeaderGetDatumLength(td);
2103 ItemPointerSetInvalid(&(tuple.t_self));
2104 tuple.t_tableOid = InvalidOid;
2107 /* copy and store tuple */
2108 EvalPlanQualSetTuple(epqstate, erm->rti,
2109 heap_copytuple(&tuple));
2115 * Fetch the next row (if any) from EvalPlanQual testing
2117 * (In practice, there should never be more than one row...)
2120 EvalPlanQualNext(EPQState *epqstate)
2122 MemoryContext oldcontext;
2123 TupleTableSlot *slot;
2125 oldcontext = MemoryContextSwitchTo(epqstate->estate->es_query_cxt);
2126 slot = ExecProcNode(epqstate->planstate);
2127 MemoryContextSwitchTo(oldcontext);
2133 * Initialize or reset an EvalPlanQual state tree
2136 EvalPlanQualBegin(EPQState *epqstate, EState *parentestate)
2138 EState *estate = epqstate->estate;
2142 /* First time through, so create a child EState */
2143 EvalPlanQualStart(epqstate, parentestate, epqstate->plan);
2148 * We already have a suitable child EPQ tree, so just reset it.
2150 int rtsize = list_length(parentestate->es_range_table);
2151 PlanState *planstate = epqstate->planstate;
2153 MemSet(estate->es_epqScanDone, 0, rtsize * sizeof(bool));
2155 /* Recopy current values of parent parameters */
2156 if (parentestate->es_plannedstmt->nParamExec > 0)
2158 int i = parentestate->es_plannedstmt->nParamExec;
2162 /* copy value if any, but not execPlan link */
2163 estate->es_param_exec_vals[i].value =
2164 parentestate->es_param_exec_vals[i].value;
2165 estate->es_param_exec_vals[i].isnull =
2166 parentestate->es_param_exec_vals[i].isnull;
2171 * Mark child plan tree as needing rescan at all scan nodes. The
2172 * first ExecProcNode will take care of actually doing the rescan.
2174 planstate->chgParam = bms_add_member(planstate->chgParam,
2175 epqstate->epqParam);
2180 * Start execution of an EvalPlanQual plan tree.
2182 * This is a cut-down version of ExecutorStart(): we copy some state from
2183 * the top-level estate rather than initializing it fresh.
2186 EvalPlanQualStart(EPQState *epqstate, EState *parentestate, Plan *planTree)
2190 MemoryContext oldcontext;
2193 rtsize = list_length(parentestate->es_range_table);
2195 epqstate->estate = estate = CreateExecutorState();
2197 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2200 * Child EPQ EStates share the parent's copy of unchanging state such as
2201 * the snapshot, rangetable, result-rel info, and external Param info.
2202 * They need their own copies of local state, including a tuple table,
2203 * es_param_exec_vals, etc.
2205 estate->es_direction = ForwardScanDirection;
2206 estate->es_snapshot = parentestate->es_snapshot;
2207 estate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
2208 estate->es_range_table = parentestate->es_range_table;
2209 estate->es_plannedstmt = parentestate->es_plannedstmt;
2210 estate->es_junkFilter = parentestate->es_junkFilter;
2211 estate->es_output_cid = parentestate->es_output_cid;
2212 estate->es_result_relations = parentestate->es_result_relations;
2213 estate->es_num_result_relations = parentestate->es_num_result_relations;
2214 estate->es_result_relation_info = parentestate->es_result_relation_info;
2215 /* es_trig_target_relations must NOT be copied */
2216 estate->es_rowMarks = parentestate->es_rowMarks;
2217 estate->es_top_eflags = parentestate->es_top_eflags;
2218 estate->es_instrument = parentestate->es_instrument;
2219 estate->es_select_into = parentestate->es_select_into;
2220 estate->es_into_oids = parentestate->es_into_oids;
2221 /* es_auxmodifytables must NOT be copied */
2224 * The external param list is simply shared from parent. The internal
2225 * param workspace has to be local state, but we copy the initial values
2226 * from the parent, so as to have access to any param values that were
2227 * already set from other parts of the parent's plan tree.
2229 estate->es_param_list_info = parentestate->es_param_list_info;
2230 if (parentestate->es_plannedstmt->nParamExec > 0)
2232 int i = parentestate->es_plannedstmt->nParamExec;
2234 estate->es_param_exec_vals = (ParamExecData *)
2235 palloc0(i * sizeof(ParamExecData));
2238 /* copy value if any, but not execPlan link */
2239 estate->es_param_exec_vals[i].value =
2240 parentestate->es_param_exec_vals[i].value;
2241 estate->es_param_exec_vals[i].isnull =
2242 parentestate->es_param_exec_vals[i].isnull;
2247 * Each EState must have its own es_epqScanDone state, but if we have
2248 * nested EPQ checks they should share es_epqTuple arrays. This allows
2249 * sub-rechecks to inherit the values being examined by an outer recheck.
2251 estate->es_epqScanDone = (bool *) palloc0(rtsize * sizeof(bool));
2252 if (parentestate->es_epqTuple != NULL)
2254 estate->es_epqTuple = parentestate->es_epqTuple;
2255 estate->es_epqTupleSet = parentestate->es_epqTupleSet;
2259 estate->es_epqTuple = (HeapTuple *)
2260 palloc0(rtsize * sizeof(HeapTuple));
2261 estate->es_epqTupleSet = (bool *)
2262 palloc0(rtsize * sizeof(bool));
2266 * Each estate also has its own tuple table.
2268 estate->es_tupleTable = NIL;
2271 * Initialize private state information for each SubPlan. We must do this
2272 * before running ExecInitNode on the main query tree, since
2273 * ExecInitSubPlan expects to be able to find these entries. Some of the
2274 * SubPlans might not be used in the part of the plan tree we intend to
2275 * run, but since it's not easy to tell which, we just initialize them
2276 * all. (However, if the subplan is headed by a ModifyTable node, then it
2277 * must be a data-modifying CTE, which we will certainly not need to
2278 * re-run, so we can skip initializing it. This is just an efficiency
2279 * hack; it won't skip data-modifying CTEs for which the ModifyTable node
2280 * is not at the top.)
2282 Assert(estate->es_subplanstates == NIL);
2283 foreach(l, parentestate->es_plannedstmt->subplans)
2285 Plan *subplan = (Plan *) lfirst(l);
2286 PlanState *subplanstate;
2288 /* Don't initialize ModifyTable subplans, per comment above */
2289 if (IsA(subplan, ModifyTable))
2290 subplanstate = NULL;
2292 subplanstate = ExecInitNode(subplan, estate, 0);
2294 estate->es_subplanstates = lappend(estate->es_subplanstates,
2299 * Initialize the private state information for all the nodes in the part
2300 * of the plan tree we need to run. This opens files, allocates storage
2301 * and leaves us ready to start processing tuples.
2303 epqstate->planstate = ExecInitNode(planTree, estate, 0);
2305 MemoryContextSwitchTo(oldcontext);
2309 * EvalPlanQualEnd -- shut down at termination of parent plan state node,
2310 * or if we are done with the current EPQ child.
2312 * This is a cut-down version of ExecutorEnd(); basically we want to do most
2313 * of the normal cleanup, but *not* close result relations (which we are
2314 * just sharing from the outer query). We do, however, have to close any
2315 * trigger target relations that got opened, since those are not shared.
2316 * (There probably shouldn't be any of the latter, but just in case...)
2319 EvalPlanQualEnd(EPQState *epqstate)
2321 EState *estate = epqstate->estate;
2322 MemoryContext oldcontext;
2326 return; /* idle, so nothing to do */
2328 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2330 ExecEndNode(epqstate->planstate);
2332 foreach(l, estate->es_subplanstates)
2334 PlanState *subplanstate = (PlanState *) lfirst(l);
2336 ExecEndNode(subplanstate);
2339 /* throw away the per-estate tuple table */
2340 ExecResetTupleTable(estate->es_tupleTable, false);
2342 /* close any trigger target relations attached to this EState */
2343 foreach(l, estate->es_trig_target_relations)
2345 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
2347 /* Close indices and then the relation itself */
2348 ExecCloseIndices(resultRelInfo);
2349 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
2352 MemoryContextSwitchTo(oldcontext);
2354 FreeExecutorState(estate);
2356 /* Mark EPQState idle */
2357 epqstate->estate = NULL;
2358 epqstate->planstate = NULL;
2359 epqstate->origslot = NULL;
2364 * Support for SELECT INTO (a/k/a CREATE TABLE AS)
2366 * We implement SELECT INTO by diverting SELECT's normal output with
2367 * a specialized DestReceiver type.
2372 DestReceiver pub; /* publicly-known function pointers */
2373 EState *estate; /* EState we are working with */
2374 Relation rel; /* Relation to write to */
2375 int hi_options; /* heap_insert performance options */
2376 BulkInsertState bistate; /* bulk insert state */
2380 * OpenIntoRel --- actually create the SELECT INTO target relation
2382 * This also replaces QueryDesc->dest with the special DestReceiver for
2383 * SELECT INTO. We assume that the correct result tuple type has already
2384 * been placed in queryDesc->tupDesc.
2387 OpenIntoRel(QueryDesc *queryDesc)
2389 IntoClause *into = queryDesc->plannedstmt->intoClause;
2390 EState *estate = queryDesc->estate;
2391 Relation intoRelationDesc;
2398 DR_intorel *myState;
2399 static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
2404 * XXX This code needs to be kept in sync with DefineRelation(). Maybe we
2405 * should try to use that function instead.
2409 * Check consistency of arguments
2411 if (into->onCommit != ONCOMMIT_NOOP
2412 && into->rel->relpersistence != RELPERSISTENCE_TEMP)
2414 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2415 errmsg("ON COMMIT can only be used on temporary tables")));
2418 * Security check: disallow creating temp tables from security-restricted
2419 * code. This is needed because calling code might not expect untrusted
2420 * tables to appear in pg_temp at the front of its search path.
2422 if (into->rel->relpersistence == RELPERSISTENCE_TEMP
2423 && InSecurityRestrictedOperation())
2425 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2426 errmsg("cannot create temporary table within security-restricted operation")));
2429 * Find namespace to create in, check its permissions
2431 intoName = into->rel->relname;
2432 namespaceId = RangeVarGetAndCheckCreationNamespace(into->rel);
2435 * Select tablespace to use. If not specified, use default tablespace
2436 * (which may in turn default to database's default).
2438 if (into->tableSpaceName)
2440 tablespaceId = get_tablespace_oid(into->tableSpaceName, false);
2444 tablespaceId = GetDefaultTablespace(into->rel->relpersistence);
2445 /* note InvalidOid is OK in this case */
2448 /* Check permissions except when using the database's default space */
2449 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
2451 AclResult aclresult;
2453 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
2456 if (aclresult != ACLCHECK_OK)
2457 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
2458 get_tablespace_name(tablespaceId));
2461 /* Parse and validate any reloptions */
2462 reloptions = transformRelOptions((Datum) 0,
2468 (void) heap_reloptions(RELKIND_RELATION, reloptions, true);
2470 /* Copy the tupdesc because heap_create_with_catalog modifies it */
2471 tupdesc = CreateTupleDescCopy(queryDesc->tupDesc);
2473 /* Now we can actually create the new relation */
2474 intoRelationId = heap_create_with_catalog(intoName,
2484 into->rel->relpersistence,
2492 allowSystemTableMods);
2493 Assert(intoRelationId != InvalidOid);
2495 FreeTupleDesc(tupdesc);
2498 * Advance command counter so that the newly-created relation's catalog
2499 * tuples will be visible to heap_open.
2501 CommandCounterIncrement();
2504 * If necessary, create a TOAST table for the INTO relation. Note that
2505 * AlterTableCreateToastTable ends with CommandCounterIncrement(), so that
2506 * the TOAST table will be visible for insertion.
2508 reloptions = transformRelOptions((Datum) 0,
2515 (void) heap_reloptions(RELKIND_TOASTVALUE, reloptions, true);
2517 AlterTableCreateToastTable(intoRelationId, reloptions);
2520 * And open the constructed table for writing.
2522 intoRelationDesc = heap_open(intoRelationId, AccessExclusiveLock);
2525 * Now replace the query's DestReceiver with one for SELECT INTO
2527 queryDesc->dest = CreateDestReceiver(DestIntoRel);
2528 myState = (DR_intorel *) queryDesc->dest;
2529 Assert(myState->pub.mydest == DestIntoRel);
2530 myState->estate = estate;
2531 myState->rel = intoRelationDesc;
2534 * We can skip WAL-logging the insertions, unless PITR or streaming
2535 * replication is in use. We can skip the FSM in any case.
2537 myState->hi_options = HEAP_INSERT_SKIP_FSM |
2538 (XLogIsNeeded() ? 0 : HEAP_INSERT_SKIP_WAL);
2539 myState->bistate = GetBulkInsertState();
2541 /* Not using WAL requires smgr_targblock be initially invalid */
2542 Assert(RelationGetTargetBlock(intoRelationDesc) == InvalidBlockNumber);
2546 * CloseIntoRel --- clean up SELECT INTO at ExecutorEnd time
2549 CloseIntoRel(QueryDesc *queryDesc)
2551 DR_intorel *myState = (DR_intorel *) queryDesc->dest;
2553 /* OpenIntoRel might never have gotten called */
2554 if (myState && myState->pub.mydest == DestIntoRel && myState->rel)
2556 FreeBulkInsertState(myState->bistate);
2558 /* If we skipped using WAL, must heap_sync before commit */
2559 if (myState->hi_options & HEAP_INSERT_SKIP_WAL)
2560 heap_sync(myState->rel);
2562 /* close rel, but keep lock until commit */
2563 heap_close(myState->rel, NoLock);
2565 myState->rel = NULL;
2570 * CreateIntoRelDestReceiver -- create a suitable DestReceiver object
2573 CreateIntoRelDestReceiver(void)
2575 DR_intorel *self = (DR_intorel *) palloc0(sizeof(DR_intorel));
2577 self->pub.receiveSlot = intorel_receive;
2578 self->pub.rStartup = intorel_startup;
2579 self->pub.rShutdown = intorel_shutdown;
2580 self->pub.rDestroy = intorel_destroy;
2581 self->pub.mydest = DestIntoRel;
2583 /* private fields will be set by OpenIntoRel */
2585 return (DestReceiver *) self;
2589 * intorel_startup --- executor startup
2592 intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
2598 * intorel_receive --- receive one tuple
2601 intorel_receive(TupleTableSlot *slot, DestReceiver *self)
2603 DR_intorel *myState = (DR_intorel *) self;
2607 * get the heap tuple out of the tuple table slot, making sure we have a
2610 tuple = ExecMaterializeSlot(slot);
2613 * force assignment of new OID (see comments in ExecInsert)
2615 if (myState->rel->rd_rel->relhasoids)
2616 HeapTupleSetOid(tuple, InvalidOid);
2618 heap_insert(myState->rel,
2620 myState->estate->es_output_cid,
2621 myState->hi_options,
2624 /* We know this is a newly created relation, so there are no indexes */
2628 * intorel_shutdown --- executor end
2631 intorel_shutdown(DestReceiver *self)
2637 * intorel_destroy --- release DestReceiver object
2640 intorel_destroy(DestReceiver *self)