1 /*-------------------------------------------------------------------------
4 * top level executor interface routines
11 * The old ExecutorMain() has been replaced by ExecutorStart(),
12 * ExecutorRun() and ExecutorEnd()
14 * These three procedures are the external interfaces to the executor.
15 * In each case, the query descriptor is required as an argument.
17 * ExecutorStart() must be called at the beginning of execution of any
18 * query plan and ExecutorEnd() should always be called at the end of
19 * execution of a plan.
21 * ExecutorRun accepts direction and count arguments that specify whether
22 * the plan is to be executed forwards, backwards, and for how many tuples.
24 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
25 * Portions Copyright (c) 1994, Regents of the University of California
29 * $PostgreSQL: pgsql/src/backend/executor/execMain.c,v 1.337 2009/12/11 18:14:43 tgl Exp $
31 *-------------------------------------------------------------------------
35 #include "access/reloptions.h"
36 #include "access/sysattr.h"
37 #include "access/transam.h"
38 #include "access/xact.h"
39 #include "catalog/heap.h"
40 #include "catalog/namespace.h"
41 #include "catalog/toasting.h"
42 #include "commands/tablespace.h"
43 #include "commands/trigger.h"
44 #include "executor/execdebug.h"
45 #include "executor/instrument.h"
46 #include "miscadmin.h"
47 #include "optimizer/clauses.h"
48 #include "parser/parse_clause.h"
49 #include "parser/parsetree.h"
50 #include "storage/bufmgr.h"
51 #include "storage/lmgr.h"
52 #include "utils/acl.h"
53 #include "utils/lsyscache.h"
54 #include "utils/memutils.h"
55 #include "utils/snapmgr.h"
56 #include "utils/tqual.h"
59 /* Hooks for plugins to get control in ExecutorStart/Run/End() */
60 ExecutorStart_hook_type ExecutorStart_hook = NULL;
61 ExecutorRun_hook_type ExecutorRun_hook = NULL;
62 ExecutorEnd_hook_type ExecutorEnd_hook = NULL;
64 /* decls for local routines only used within this module */
65 static void InitPlan(QueryDesc *queryDesc, int eflags);
66 static void ExecEndPlan(PlanState *planstate, EState *estate);
67 static void ExecutePlan(EState *estate, PlanState *planstate,
71 ScanDirection direction,
73 static void ExecCheckRTPerms(List *rangeTable);
74 static void ExecCheckRTEPerms(RangeTblEntry *rte);
75 static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
76 static void EvalPlanQualStart(EPQState *epqstate, EState *parentestate,
78 static void OpenIntoRel(QueryDesc *queryDesc);
79 static void CloseIntoRel(QueryDesc *queryDesc);
80 static void intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
81 static void intorel_receive(TupleTableSlot *slot, DestReceiver *self);
82 static void intorel_shutdown(DestReceiver *self);
83 static void intorel_destroy(DestReceiver *self);
85 /* end of local decls */
88 /* ----------------------------------------------------------------
91 * This routine must be called at the beginning of any execution of any
94 * Takes a QueryDesc previously created by CreateQueryDesc (it's not real
95 * clear why we bother to separate the two functions, but...). The tupDesc
96 * field of the QueryDesc is filled in to describe the tuples that will be
97 * returned, and the internal fields (estate and planstate) are set up.
99 * eflags contains flag bits as described in executor.h.
101 * NB: the CurrentMemoryContext when this is called will become the parent
102 * of the per-query context used for this Executor invocation.
104 * We provide a function hook variable that lets loadable plugins
105 * get control when ExecutorStart is called. Such a plugin would
106 * normally call standard_ExecutorStart().
108 * ----------------------------------------------------------------
111 ExecutorStart(QueryDesc *queryDesc, int eflags)
113 if (ExecutorStart_hook)
114 (*ExecutorStart_hook) (queryDesc, eflags);
116 standard_ExecutorStart(queryDesc, eflags);
120 standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
123 MemoryContext oldcontext;
125 /* sanity checks: queryDesc must not be started already */
126 Assert(queryDesc != NULL);
127 Assert(queryDesc->estate == NULL);
130 * If the transaction is read-only, we need to check if any writes are
131 * planned to non-temporary tables. EXPLAIN is considered read-only.
133 if (XactReadOnly && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
134 ExecCheckXactReadOnly(queryDesc->plannedstmt);
137 * Build EState, switch into per-query memory context for startup.
139 estate = CreateExecutorState();
140 queryDesc->estate = estate;
142 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
145 * Fill in external parameters, if any, from queryDesc; and allocate
146 * workspace for internal parameters
148 estate->es_param_list_info = queryDesc->params;
150 if (queryDesc->plannedstmt->nParamExec > 0)
151 estate->es_param_exec_vals = (ParamExecData *)
152 palloc0(queryDesc->plannedstmt->nParamExec * sizeof(ParamExecData));
155 * If non-read-only query, set the command ID to mark output tuples with
157 switch (queryDesc->operation)
160 /* SELECT INTO and SELECT FOR UPDATE/SHARE need to mark tuples */
161 if (queryDesc->plannedstmt->intoClause != NULL ||
162 queryDesc->plannedstmt->rowMarks != NIL)
163 estate->es_output_cid = GetCurrentCommandId(true);
169 estate->es_output_cid = GetCurrentCommandId(true);
173 elog(ERROR, "unrecognized operation code: %d",
174 (int) queryDesc->operation);
179 * Copy other important information into the EState
181 estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
182 estate->es_crosscheck_snapshot = RegisterSnapshot(queryDesc->crosscheck_snapshot);
183 estate->es_instrument = queryDesc->doInstrument;
186 * Initialize the plan state tree
188 InitPlan(queryDesc, eflags);
190 MemoryContextSwitchTo(oldcontext);
193 /* ----------------------------------------------------------------
196 * This is the main routine of the executor module. It accepts
197 * the query descriptor from the traffic cop and executes the
200 * ExecutorStart must have been called already.
202 * If direction is NoMovementScanDirection then nothing is done
203 * except to start up/shut down the destination. Otherwise,
204 * we retrieve up to 'count' tuples in the specified direction.
206 * Note: count = 0 is interpreted as no portal limit, i.e., run to
209 * There is no return value, but output tuples (if any) are sent to
210 * the destination receiver specified in the QueryDesc; and the number
211 * of tuples processed at the top level can be found in
212 * estate->es_processed.
214 * We provide a function hook variable that lets loadable plugins
215 * get control when ExecutorRun is called. Such a plugin would
216 * normally call standard_ExecutorRun().
218 * ----------------------------------------------------------------
221 ExecutorRun(QueryDesc *queryDesc,
222 ScanDirection direction, long count)
224 if (ExecutorRun_hook)
225 (*ExecutorRun_hook) (queryDesc, direction, count);
227 standard_ExecutorRun(queryDesc, direction, count);
231 standard_ExecutorRun(QueryDesc *queryDesc,
232 ScanDirection direction, long count)
238 MemoryContext oldcontext;
241 Assert(queryDesc != NULL);
243 estate = queryDesc->estate;
245 Assert(estate != NULL);
248 * Switch into per-query memory context
250 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
252 /* Allow instrumentation of ExecutorRun overall runtime */
253 if (queryDesc->totaltime)
254 InstrStartNode(queryDesc->totaltime);
257 * extract information from the query descriptor and the query feature.
259 operation = queryDesc->operation;
260 dest = queryDesc->dest;
263 * startup tuple receiver, if we will be emitting tuples
265 estate->es_processed = 0;
266 estate->es_lastoid = InvalidOid;
268 sendTuples = (operation == CMD_SELECT ||
269 queryDesc->plannedstmt->hasReturning);
272 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
277 if (!ScanDirectionIsNoMovement(direction))
279 queryDesc->planstate,
287 * shutdown tuple receiver, if we started it
290 (*dest->rShutdown) (dest);
292 if (queryDesc->totaltime)
293 InstrStopNode(queryDesc->totaltime, estate->es_processed);
295 MemoryContextSwitchTo(oldcontext);
298 /* ----------------------------------------------------------------
301 * This routine must be called at the end of execution of any
304 * We provide a function hook variable that lets loadable plugins
305 * get control when ExecutorEnd is called. Such a plugin would
306 * normally call standard_ExecutorEnd().
308 * ----------------------------------------------------------------
311 ExecutorEnd(QueryDesc *queryDesc)
313 if (ExecutorEnd_hook)
314 (*ExecutorEnd_hook) (queryDesc);
316 standard_ExecutorEnd(queryDesc);
320 standard_ExecutorEnd(QueryDesc *queryDesc)
323 MemoryContext oldcontext;
326 Assert(queryDesc != NULL);
328 estate = queryDesc->estate;
330 Assert(estate != NULL);
333 * Switch into per-query memory context to run ExecEndPlan
335 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
337 ExecEndPlan(queryDesc->planstate, estate);
340 * Close the SELECT INTO relation if any
342 if (estate->es_select_into)
343 CloseIntoRel(queryDesc);
345 /* do away with our snapshots */
346 UnregisterSnapshot(estate->es_snapshot);
347 UnregisterSnapshot(estate->es_crosscheck_snapshot);
350 * Must switch out of context before destroying it
352 MemoryContextSwitchTo(oldcontext);
355 * Release EState and per-query memory context. This should release
356 * everything the executor has allocated.
358 FreeExecutorState(estate);
360 /* Reset queryDesc fields that no longer point to anything */
361 queryDesc->tupDesc = NULL;
362 queryDesc->estate = NULL;
363 queryDesc->planstate = NULL;
364 queryDesc->totaltime = NULL;
367 /* ----------------------------------------------------------------
370 * This routine may be called on an open queryDesc to rewind it
372 * ----------------------------------------------------------------
375 ExecutorRewind(QueryDesc *queryDesc)
378 MemoryContext oldcontext;
381 Assert(queryDesc != NULL);
383 estate = queryDesc->estate;
385 Assert(estate != NULL);
387 /* It's probably not sensible to rescan updating queries */
388 Assert(queryDesc->operation == CMD_SELECT);
391 * Switch into per-query memory context
393 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
398 ExecReScan(queryDesc->planstate, NULL);
400 MemoryContextSwitchTo(oldcontext);
406 * Check access permissions for all relations listed in a range table.
409 ExecCheckRTPerms(List *rangeTable)
413 foreach(l, rangeTable)
415 ExecCheckRTEPerms((RangeTblEntry *) lfirst(l));
421 * Check access permissions for a single RTE.
424 ExecCheckRTEPerms(RangeTblEntry *rte)
426 AclMode requiredPerms;
428 AclMode remainingPerms;
435 * Only plain-relation RTEs need to be checked here. Function RTEs are
436 * checked by init_fcache when the function is prepared for execution.
437 * Join, subquery, and special RTEs need no checks.
439 if (rte->rtekind != RTE_RELATION)
443 * No work if requiredPerms is empty.
445 requiredPerms = rte->requiredPerms;
446 if (requiredPerms == 0)
452 * userid to check as: current user unless we have a setuid indication.
454 * Note: GetUserId() is presently fast enough that there's no harm in
455 * calling it separately for each RTE. If that stops being true, we could
456 * call it once in ExecCheckRTPerms and pass the userid down from there.
457 * But for now, no need for the extra clutter.
459 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
462 * We must have *all* the requiredPerms bits, but some of the bits can be
463 * satisfied from column-level rather than relation-level permissions.
464 * First, remove any bits that are satisfied by relation permissions.
466 relPerms = pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL);
467 remainingPerms = requiredPerms & ~relPerms;
468 if (remainingPerms != 0)
471 * If we lack any permissions that exist only as relation permissions,
472 * we can fail straight away.
474 if (remainingPerms & ~(ACL_SELECT | ACL_INSERT | ACL_UPDATE))
475 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
476 get_rel_name(relOid));
479 * Check to see if we have the needed privileges at column level.
481 * Note: failures just report a table-level error; it would be nicer
482 * to report a column-level error if we have some but not all of the
485 if (remainingPerms & ACL_SELECT)
488 * When the query doesn't explicitly reference any columns (for
489 * example, SELECT COUNT(*) FROM table), allow the query if we
490 * have SELECT on any column of the rel, as per SQL spec.
492 if (bms_is_empty(rte->selectedCols))
494 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
495 ACLMASK_ANY) != ACLCHECK_OK)
496 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
497 get_rel_name(relOid));
500 tmpset = bms_copy(rte->selectedCols);
501 while ((col = bms_first_member(tmpset)) >= 0)
503 /* remove the column number offset */
504 col += FirstLowInvalidHeapAttributeNumber;
505 if (col == InvalidAttrNumber)
507 /* Whole-row reference, must have priv on all cols */
508 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
509 ACLMASK_ALL) != ACLCHECK_OK)
510 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
511 get_rel_name(relOid));
515 if (pg_attribute_aclcheck(relOid, col, userid, ACL_SELECT)
517 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
518 get_rel_name(relOid));
525 * Basically the same for the mod columns, with either INSERT or
526 * UPDATE privilege as specified by remainingPerms.
528 remainingPerms &= ~ACL_SELECT;
529 if (remainingPerms != 0)
532 * When the query doesn't explicitly change any columns, allow the
533 * query if we have permission on any column of the rel. This is
534 * to handle SELECT FOR UPDATE as well as possible corner cases in
537 if (bms_is_empty(rte->modifiedCols))
539 if (pg_attribute_aclcheck_all(relOid, userid, remainingPerms,
540 ACLMASK_ANY) != ACLCHECK_OK)
541 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
542 get_rel_name(relOid));
545 tmpset = bms_copy(rte->modifiedCols);
546 while ((col = bms_first_member(tmpset)) >= 0)
548 /* remove the column number offset */
549 col += FirstLowInvalidHeapAttributeNumber;
550 if (col == InvalidAttrNumber)
552 /* whole-row reference can't happen here */
553 elog(ERROR, "whole-row update is not implemented");
557 if (pg_attribute_aclcheck(relOid, col, userid, remainingPerms)
559 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
560 get_rel_name(relOid));
569 * Check that the query does not imply any writes to non-temp tables.
572 ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
577 * CREATE TABLE AS or SELECT INTO?
579 * XXX should we allow this if the destination is temp?
581 if (plannedstmt->intoClause != NULL)
584 /* Fail if write permissions are requested on any non-temp table */
585 foreach(l, plannedstmt->rtable)
587 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
589 if (rte->rtekind != RTE_RELATION)
592 if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
595 if (isTempNamespace(get_rel_namespace(rte->relid)))
605 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
606 errmsg("transaction is read-only")));
610 /* ----------------------------------------------------------------
613 * Initializes the query plan: open files, allocate storage
614 * and start up the rule manager
615 * ----------------------------------------------------------------
618 InitPlan(QueryDesc *queryDesc, int eflags)
620 CmdType operation = queryDesc->operation;
621 PlannedStmt *plannedstmt = queryDesc->plannedstmt;
622 Plan *plan = plannedstmt->planTree;
623 List *rangeTable = plannedstmt->rtable;
624 EState *estate = queryDesc->estate;
625 PlanState *planstate;
631 * Do permissions checks
633 ExecCheckRTPerms(rangeTable);
636 * initialize the node's execution state
638 estate->es_range_table = rangeTable;
639 estate->es_plannedstmt = plannedstmt;
642 * initialize result relation stuff, and open/lock the result rels.
644 * We must do this before initializing the plan tree, else we might
645 * try to do a lock upgrade if a result rel is also a source rel.
647 if (plannedstmt->resultRelations)
649 List *resultRelations = plannedstmt->resultRelations;
650 int numResultRelations = list_length(resultRelations);
651 ResultRelInfo *resultRelInfos;
652 ResultRelInfo *resultRelInfo;
654 resultRelInfos = (ResultRelInfo *)
655 palloc(numResultRelations * sizeof(ResultRelInfo));
656 resultRelInfo = resultRelInfos;
657 foreach(l, resultRelations)
659 Index resultRelationIndex = lfirst_int(l);
660 Oid resultRelationOid;
661 Relation resultRelation;
663 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
664 resultRelation = heap_open(resultRelationOid, RowExclusiveLock);
665 InitResultRelInfo(resultRelInfo,
669 estate->es_instrument);
672 estate->es_result_relations = resultRelInfos;
673 estate->es_num_result_relations = numResultRelations;
674 /* es_result_relation_info is NULL except when within ModifyTable */
675 estate->es_result_relation_info = NULL;
680 * if no result relation, then set state appropriately
682 estate->es_result_relations = NULL;
683 estate->es_num_result_relations = 0;
684 estate->es_result_relation_info = NULL;
688 * Similarly, we have to lock relations selected FOR UPDATE/FOR SHARE
689 * before we initialize the plan tree, else we'd be risking lock
690 * upgrades. While we are at it, build the ExecRowMark list.
692 estate->es_rowMarks = NIL;
693 foreach(l, plannedstmt->rowMarks)
695 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
700 /* ignore "parent" rowmarks; they are irrelevant at runtime */
704 switch (rc->markType)
706 case ROW_MARK_EXCLUSIVE:
708 relid = getrelid(rc->rti, rangeTable);
709 relation = heap_open(relid, RowShareLock);
711 case ROW_MARK_REFERENCE:
712 relid = getrelid(rc->rti, rangeTable);
713 relation = heap_open(relid, AccessShareLock);
716 /* there's no real table here ... */
720 elog(ERROR, "unrecognized markType: %d", rc->markType);
721 relation = NULL; /* keep compiler quiet */
725 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
726 erm->relation = relation;
728 erm->prti = rc->prti;
729 erm->markType = rc->markType;
730 erm->noWait = rc->noWait;
731 erm->ctidAttNo = rc->ctidAttNo;
732 erm->toidAttNo = rc->toidAttNo;
733 erm->wholeAttNo = rc->wholeAttNo;
734 ItemPointerSetInvalid(&(erm->curCtid));
735 estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
739 * Detect whether we're doing SELECT INTO. If so, set the es_into_oids
740 * flag appropriately so that the plan tree will be initialized with the
741 * correct tuple descriptors. (Other SELECT INTO stuff comes later.)
743 estate->es_select_into = false;
744 if (operation == CMD_SELECT && plannedstmt->intoClause != NULL)
746 estate->es_select_into = true;
747 estate->es_into_oids = interpretOidsOption(plannedstmt->intoClause->options);
751 * Initialize the executor's tuple table to empty.
753 estate->es_tupleTable = NIL;
754 estate->es_trig_tuple_slot = NULL;
755 estate->es_trig_oldtup_slot = NULL;
757 /* mark EvalPlanQual not active */
758 estate->es_epqTuple = NULL;
759 estate->es_epqTupleSet = NULL;
760 estate->es_epqScanDone = NULL;
763 * Initialize private state information for each SubPlan. We must do this
764 * before running ExecInitNode on the main query tree, since
765 * ExecInitSubPlan expects to be able to find these entries.
767 Assert(estate->es_subplanstates == NIL);
768 i = 1; /* subplan indices count from 1 */
769 foreach(l, plannedstmt->subplans)
771 Plan *subplan = (Plan *) lfirst(l);
772 PlanState *subplanstate;
776 * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
777 * it is a parameterless subplan (not initplan), we suggest that it be
778 * prepared to handle REWIND efficiently; otherwise there is no need.
780 sp_eflags = eflags & EXEC_FLAG_EXPLAIN_ONLY;
781 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
782 sp_eflags |= EXEC_FLAG_REWIND;
784 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
786 estate->es_subplanstates = lappend(estate->es_subplanstates,
793 * Initialize the private state information for all the nodes in the query
794 * tree. This opens files, allocates storage and leaves us ready to start
797 planstate = ExecInitNode(plan, estate, eflags);
800 * Get the tuple descriptor describing the type of tuples to return. (this
801 * is especially important if we are creating a relation with "SELECT
804 tupType = ExecGetResultType(planstate);
807 * Initialize the junk filter if needed. SELECT queries need a
808 * filter if there are any junk attrs in the top-level tlist.
810 if (operation == CMD_SELECT)
812 bool junk_filter_needed = false;
815 foreach(tlist, plan->targetlist)
817 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
821 junk_filter_needed = true;
826 if (junk_filter_needed)
830 j = ExecInitJunkFilter(planstate->plan->targetlist,
832 ExecInitExtraTupleSlot(estate));
833 estate->es_junkFilter = j;
835 /* Want to return the cleaned tuple type */
836 tupType = j->jf_cleanTupType;
840 queryDesc->tupDesc = tupType;
841 queryDesc->planstate = planstate;
844 * If doing SELECT INTO, initialize the "into" relation. We must wait
845 * till now so we have the "clean" result tuple type to create the new
848 * If EXPLAIN, skip creating the "into" relation.
850 if (estate->es_select_into && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
851 OpenIntoRel(queryDesc);
855 * Initialize ResultRelInfo data for one result relation
858 InitResultRelInfo(ResultRelInfo *resultRelInfo,
859 Relation resultRelationDesc,
860 Index resultRelationIndex,
865 * Check valid relkind ... parser and/or planner should have noticed this
866 * already, but let's make sure.
868 switch (resultRelationDesc->rd_rel->relkind)
870 case RELKIND_RELATION:
873 case RELKIND_SEQUENCE:
875 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
876 errmsg("cannot change sequence \"%s\"",
877 RelationGetRelationName(resultRelationDesc))));
879 case RELKIND_TOASTVALUE:
881 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
882 errmsg("cannot change TOAST relation \"%s\"",
883 RelationGetRelationName(resultRelationDesc))));
887 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
888 errmsg("cannot change view \"%s\"",
889 RelationGetRelationName(resultRelationDesc))));
893 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
894 errmsg("cannot change relation \"%s\"",
895 RelationGetRelationName(resultRelationDesc))));
899 /* OK, fill in the node */
900 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
901 resultRelInfo->type = T_ResultRelInfo;
902 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
903 resultRelInfo->ri_RelationDesc = resultRelationDesc;
904 resultRelInfo->ri_NumIndices = 0;
905 resultRelInfo->ri_IndexRelationDescs = NULL;
906 resultRelInfo->ri_IndexRelationInfo = NULL;
907 /* make a copy so as not to depend on relcache info not changing... */
908 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
909 if (resultRelInfo->ri_TrigDesc)
911 int n = resultRelInfo->ri_TrigDesc->numtriggers;
913 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
914 palloc0(n * sizeof(FmgrInfo));
915 resultRelInfo->ri_TrigWhenExprs = (List **)
916 palloc0(n * sizeof(List *));
918 resultRelInfo->ri_TrigInstrument = InstrAlloc(n);
920 resultRelInfo->ri_TrigInstrument = NULL;
924 resultRelInfo->ri_TrigFunctions = NULL;
925 resultRelInfo->ri_TrigWhenExprs = NULL;
926 resultRelInfo->ri_TrigInstrument = NULL;
928 resultRelInfo->ri_ConstraintExprs = NULL;
929 resultRelInfo->ri_junkFilter = NULL;
930 resultRelInfo->ri_projectReturning = NULL;
933 * If there are indices on the result relation, open them and save
934 * descriptors in the result relation info, so that we can add new index
935 * entries for the tuples we add/update. We need not do this for a
936 * DELETE, however, since deletion doesn't affect indexes.
938 if (resultRelationDesc->rd_rel->relhasindex &&
939 operation != CMD_DELETE)
940 ExecOpenIndices(resultRelInfo);
944 * ExecGetTriggerResultRel
946 * Get a ResultRelInfo for a trigger target relation. Most of the time,
947 * triggers are fired on one of the result relations of the query, and so
948 * we can just return a member of the es_result_relations array. (Note: in
949 * self-join situations there might be multiple members with the same OID;
950 * if so it doesn't matter which one we pick.) However, it is sometimes
951 * necessary to fire triggers on other relations; this happens mainly when an
952 * RI update trigger queues additional triggers on other relations, which will
953 * be processed in the context of the outer query. For efficiency's sake,
954 * we want to have a ResultRelInfo for those triggers too; that can avoid
955 * repeated re-opening of the relation. (It also provides a way for EXPLAIN
956 * ANALYZE to report the runtimes of such triggers.) So we make additional
957 * ResultRelInfo's as needed, and save them in es_trig_target_relations.
960 ExecGetTriggerResultRel(EState *estate, Oid relid)
962 ResultRelInfo *rInfo;
966 MemoryContext oldcontext;
968 /* First, search through the query result relations */
969 rInfo = estate->es_result_relations;
970 nr = estate->es_num_result_relations;
973 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
978 /* Nope, but maybe we already made an extra ResultRelInfo for it */
979 foreach(l, estate->es_trig_target_relations)
981 rInfo = (ResultRelInfo *) lfirst(l);
982 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
985 /* Nope, so we need a new one */
988 * Open the target relation's relcache entry. We assume that an
989 * appropriate lock is still held by the backend from whenever the trigger
990 * event got queued, so we need take no new lock here.
992 rel = heap_open(relid, NoLock);
995 * Make the new entry in the right context. Currently, we don't need any
996 * index information in ResultRelInfos used only for triggers, so tell
997 * InitResultRelInfo it's a DELETE.
999 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1000 rInfo = makeNode(ResultRelInfo);
1001 InitResultRelInfo(rInfo,
1003 0, /* dummy rangetable index */
1005 estate->es_instrument);
1006 estate->es_trig_target_relations =
1007 lappend(estate->es_trig_target_relations, rInfo);
1008 MemoryContextSwitchTo(oldcontext);
1014 * ExecContextForcesOids
1016 * This is pretty grotty: when doing INSERT, UPDATE, or SELECT INTO,
1017 * we need to ensure that result tuples have space for an OID iff they are
1018 * going to be stored into a relation that has OIDs. In other contexts
1019 * we are free to choose whether to leave space for OIDs in result tuples
1020 * (we generally don't want to, but we do if a physical-tlist optimization
1021 * is possible). This routine checks the plan context and returns TRUE if the
1022 * choice is forced, FALSE if the choice is not forced. In the TRUE case,
1023 * *hasoids is set to the required value.
1025 * One reason this is ugly is that all plan nodes in the plan tree will emit
1026 * tuples with space for an OID, though we really only need the topmost node
1027 * to do so. However, node types like Sort don't project new tuples but just
1028 * return their inputs, and in those cases the requirement propagates down
1029 * to the input node. Eventually we might make this code smart enough to
1030 * recognize how far down the requirement really goes, but for now we just
1031 * make all plan nodes do the same thing if the top level forces the choice.
1033 * We assume that if we are generating tuples for INSERT or UPDATE,
1034 * estate->es_result_relation_info is already set up to describe the target
1035 * relation. Note that in an UPDATE that spans an inheritance tree, some of
1036 * the target relations may have OIDs and some not. We have to make the
1037 * decisions on a per-relation basis as we initialize each of the subplans of
1038 * the ModifyTable node, so ModifyTable has to set es_result_relation_info
1039 * while initializing each subplan.
1041 * SELECT INTO is even uglier, because we don't have the INTO relation's
1042 * descriptor available when this code runs; we have to look aside at a
1043 * flag set by InitPlan().
1046 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
1048 ResultRelInfo *ri = planstate->state->es_result_relation_info;
1052 Relation rel = ri->ri_RelationDesc;
1056 *hasoids = rel->rd_rel->relhasoids;
1061 if (planstate->state->es_select_into)
1063 *hasoids = planstate->state->es_into_oids;
1070 /* ----------------------------------------------------------------
1073 * Cleans up the query plan -- closes files and frees up storage
1075 * NOTE: we are no longer very worried about freeing storage per se
1076 * in this code; FreeExecutorState should be guaranteed to release all
1077 * memory that needs to be released. What we are worried about doing
1078 * is closing relations and dropping buffer pins. Thus, for example,
1079 * tuple tables must be cleared or dropped to ensure pins are released.
1080 * ----------------------------------------------------------------
1083 ExecEndPlan(PlanState *planstate, EState *estate)
1085 ResultRelInfo *resultRelInfo;
1090 * shut down the node-type-specific query processing
1092 ExecEndNode(planstate);
1097 foreach(l, estate->es_subplanstates)
1099 PlanState *subplanstate = (PlanState *) lfirst(l);
1101 ExecEndNode(subplanstate);
1105 * destroy the executor's tuple table. Actually we only care about
1106 * releasing buffer pins and tupdesc refcounts; there's no need to
1107 * pfree the TupleTableSlots, since the containing memory context
1108 * is about to go away anyway.
1110 ExecResetTupleTable(estate->es_tupleTable, false);
1113 * close the result relation(s) if any, but hold locks until xact commit.
1115 resultRelInfo = estate->es_result_relations;
1116 for (i = estate->es_num_result_relations; i > 0; i--)
1118 /* Close indices and then the relation itself */
1119 ExecCloseIndices(resultRelInfo);
1120 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1125 * likewise close any trigger target relations
1127 foreach(l, estate->es_trig_target_relations)
1129 resultRelInfo = (ResultRelInfo *) lfirst(l);
1130 /* Close indices and then the relation itself */
1131 ExecCloseIndices(resultRelInfo);
1132 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1136 * close any relations selected FOR UPDATE/FOR SHARE, again keeping locks
1138 foreach(l, estate->es_rowMarks)
1140 ExecRowMark *erm = (ExecRowMark *) lfirst(l);
1143 heap_close(erm->relation, NoLock);
1147 /* ----------------------------------------------------------------
1150 * Processes the query plan until we have processed 'numberTuples' tuples,
1151 * moving in the specified direction.
1153 * Runs to completion if numberTuples is 0
1155 * Note: the ctid attribute is a 'junk' attribute that is removed before the
1157 * ----------------------------------------------------------------
1160 ExecutePlan(EState *estate,
1161 PlanState *planstate,
1165 ScanDirection direction,
1168 TupleTableSlot *slot;
1169 long current_tuple_count;
1172 * initialize local variables
1174 current_tuple_count = 0;
1177 * Set the direction.
1179 estate->es_direction = direction;
1182 * Loop until we've processed the proper number of tuples from the plan.
1186 /* Reset the per-output-tuple exprcontext */
1187 ResetPerTupleExprContext(estate);
1190 * Execute the plan and obtain a tuple
1192 slot = ExecProcNode(planstate);
1195 * if the tuple is null, then we assume there is nothing more to
1196 * process so we just end the loop...
1198 if (TupIsNull(slot))
1202 * If we have a junk filter, then project a new tuple with the junk
1205 * Store this new "clean" tuple in the junkfilter's resultSlot.
1206 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1207 * because that tuple slot has the wrong descriptor.)
1209 if (estate->es_junkFilter != NULL)
1210 slot = ExecFilterJunk(estate->es_junkFilter, slot);
1213 * If we are supposed to send the tuple somewhere, do so.
1214 * (In practice, this is probably always the case at this point.)
1217 (*dest->receiveSlot) (slot, dest);
1220 * Count tuples processed, if this is a SELECT. (For other operation
1221 * types, the ModifyTable plan node must count the appropriate
1224 if (operation == CMD_SELECT)
1225 (estate->es_processed)++;
1228 * check our tuple count.. if we've processed the proper number then
1229 * quit, else loop again and process more tuples. Zero numberTuples
1232 current_tuple_count++;
1233 if (numberTuples && numberTuples == current_tuple_count)
1240 * ExecRelCheck --- check that tuple meets constraints for result relation
1243 ExecRelCheck(ResultRelInfo *resultRelInfo,
1244 TupleTableSlot *slot, EState *estate)
1246 Relation rel = resultRelInfo->ri_RelationDesc;
1247 int ncheck = rel->rd_att->constr->num_check;
1248 ConstrCheck *check = rel->rd_att->constr->check;
1249 ExprContext *econtext;
1250 MemoryContext oldContext;
1255 * If first time through for this result relation, build expression
1256 * nodetrees for rel's constraint expressions. Keep them in the per-query
1257 * memory context so they'll survive throughout the query.
1259 if (resultRelInfo->ri_ConstraintExprs == NULL)
1261 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1262 resultRelInfo->ri_ConstraintExprs =
1263 (List **) palloc(ncheck * sizeof(List *));
1264 for (i = 0; i < ncheck; i++)
1266 /* ExecQual wants implicit-AND form */
1267 qual = make_ands_implicit(stringToNode(check[i].ccbin));
1268 resultRelInfo->ri_ConstraintExprs[i] = (List *)
1269 ExecPrepareExpr((Expr *) qual, estate);
1271 MemoryContextSwitchTo(oldContext);
1275 * We will use the EState's per-tuple context for evaluating constraint
1276 * expressions (creating it if it's not already there).
1278 econtext = GetPerTupleExprContext(estate);
1280 /* Arrange for econtext's scan tuple to be the tuple under test */
1281 econtext->ecxt_scantuple = slot;
1283 /* And evaluate the constraints */
1284 for (i = 0; i < ncheck; i++)
1286 qual = resultRelInfo->ri_ConstraintExprs[i];
1289 * NOTE: SQL92 specifies that a NULL result from a constraint
1290 * expression is not to be treated as a failure. Therefore, tell
1291 * ExecQual to return TRUE for NULL.
1293 if (!ExecQual(qual, econtext, true))
1294 return check[i].ccname;
1297 /* NULL result means no error */
1302 ExecConstraints(ResultRelInfo *resultRelInfo,
1303 TupleTableSlot *slot, EState *estate)
1305 Relation rel = resultRelInfo->ri_RelationDesc;
1306 TupleConstr *constr = rel->rd_att->constr;
1310 if (constr->has_not_null)
1312 int natts = rel->rd_att->natts;
1315 for (attrChk = 1; attrChk <= natts; attrChk++)
1317 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1318 slot_attisnull(slot, attrChk))
1320 (errcode(ERRCODE_NOT_NULL_VIOLATION),
1321 errmsg("null value in column \"%s\" violates not-null constraint",
1322 NameStr(rel->rd_att->attrs[attrChk - 1]->attname))));
1326 if (constr->num_check > 0)
1330 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1332 (errcode(ERRCODE_CHECK_VIOLATION),
1333 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1334 RelationGetRelationName(rel), failed)));
1340 * EvalPlanQual logic --- recheck modified tuple(s) to see if we want to
1341 * process the updated version under READ COMMITTED rules.
1343 * See backend/executor/README for some info about how this works.
1348 * Check a modified tuple to see if we want to process its updated version
1349 * under READ COMMITTED rules.
1351 * estate - outer executor state data
1352 * epqstate - state for EvalPlanQual rechecking
1353 * relation - table containing tuple
1354 * rti - rangetable index of table containing tuple
1355 * *tid - t_ctid from the outdated tuple (ie, next updated version)
1356 * priorXmax - t_xmax from the outdated tuple
1358 * *tid is also an output parameter: it's modified to hold the TID of the
1359 * latest version of the tuple (note this may be changed even on failure)
1361 * Returns a slot containing the new candidate update/delete tuple, or
1362 * NULL if we determine we shouldn't process the row.
1365 EvalPlanQual(EState *estate, EPQState *epqstate,
1366 Relation relation, Index rti,
1367 ItemPointer tid, TransactionId priorXmax)
1369 TupleTableSlot *slot;
1370 HeapTuple copyTuple;
1375 * Get and lock the updated version of the row; if fail, return NULL.
1377 copyTuple = EvalPlanQualFetch(estate, relation, LockTupleExclusive,
1380 if (copyTuple == NULL)
1384 * For UPDATE/DELETE we have to return tid of actual row we're executing
1387 *tid = copyTuple->t_self;
1390 * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
1392 EvalPlanQualBegin(epqstate, estate);
1395 * Free old test tuple, if any, and store new tuple where relation's
1396 * scan node will see it
1398 EvalPlanQualSetTuple(epqstate, rti, copyTuple);
1401 * Fetch any non-locked source rows
1403 EvalPlanQualFetchRowMarks(epqstate);
1406 * Run the EPQ query. We assume it will return at most one tuple.
1408 slot = EvalPlanQualNext(epqstate);
1411 * If we got a tuple, force the slot to materialize the tuple so that
1412 * it is not dependent on any local state in the EPQ query (in particular,
1413 * it's highly likely that the slot contains references to any pass-by-ref
1414 * datums that may be present in copyTuple). As with the next step,
1415 * this is to guard against early re-use of the EPQ query.
1417 if (!TupIsNull(slot))
1418 (void) ExecMaterializeSlot(slot);
1421 * Clear out the test tuple. This is needed in case the EPQ query
1422 * is re-used to test a tuple for a different relation. (Not clear
1423 * that can really happen, but let's be safe.)
1425 EvalPlanQualSetTuple(epqstate, rti, NULL);
1431 * Fetch a copy of the newest version of an outdated tuple
1433 * estate - executor state data
1434 * relation - table containing tuple
1435 * lockmode - requested tuple lock mode
1436 * *tid - t_ctid from the outdated tuple (ie, next updated version)
1437 * priorXmax - t_xmax from the outdated tuple
1439 * Returns a palloc'd copy of the newest tuple version, or NULL if we find
1440 * that there is no newest version (ie, the row was deleted not updated).
1441 * If successful, we have locked the newest tuple version, so caller does not
1442 * need to worry about it changing anymore.
1444 * Note: properly, lockmode should be declared as enum LockTupleMode,
1445 * but we use "int" to avoid having to include heapam.h in executor.h.
1448 EvalPlanQualFetch(EState *estate, Relation relation, int lockmode,
1449 ItemPointer tid, TransactionId priorXmax)
1451 HeapTuple copyTuple = NULL;
1452 HeapTupleData tuple;
1453 SnapshotData SnapshotDirty;
1456 * fetch target tuple
1458 * Loop here to deal with updated or busy tuples
1460 InitDirtySnapshot(SnapshotDirty);
1461 tuple.t_self = *tid;
1466 if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
1469 ItemPointerData update_ctid;
1470 TransactionId update_xmax;
1473 * If xmin isn't what we're expecting, the slot must have been
1474 * recycled and reused for an unrelated tuple. This implies that
1475 * the latest version of the row was deleted, so we need do
1476 * nothing. (Should be safe to examine xmin without getting
1477 * buffer's content lock, since xmin never changes in an existing
1480 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1483 ReleaseBuffer(buffer);
1487 /* otherwise xmin should not be dirty... */
1488 if (TransactionIdIsValid(SnapshotDirty.xmin))
1489 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
1492 * If tuple is being updated by other transaction then we have to
1493 * wait for its commit/abort.
1495 if (TransactionIdIsValid(SnapshotDirty.xmax))
1497 ReleaseBuffer(buffer);
1498 XactLockTableWait(SnapshotDirty.xmax);
1499 continue; /* loop back to repeat heap_fetch */
1503 * If tuple was inserted by our own transaction, we have to check
1504 * cmin against es_output_cid: cmin >= current CID means our
1505 * command cannot see the tuple, so we should ignore it. Without
1506 * this we are open to the "Halloween problem" of indefinitely
1507 * re-updating the same tuple. (We need not check cmax because
1508 * HeapTupleSatisfiesDirty will consider a tuple deleted by our
1509 * transaction dead, regardless of cmax.) We just checked that
1510 * priorXmax == xmin, so we can test that variable instead of
1511 * doing HeapTupleHeaderGetXmin again.
1513 if (TransactionIdIsCurrentTransactionId(priorXmax) &&
1514 HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
1516 ReleaseBuffer(buffer);
1521 * This is a live tuple, so now try to lock it.
1523 test = heap_lock_tuple(relation, &tuple, &buffer,
1524 &update_ctid, &update_xmax,
1525 estate->es_output_cid,
1527 /* We now have two pins on the buffer, get rid of one */
1528 ReleaseBuffer(buffer);
1532 case HeapTupleSelfUpdated:
1533 /* treat it as deleted; do not process */
1534 ReleaseBuffer(buffer);
1537 case HeapTupleMayBeUpdated:
1538 /* successfully locked */
1541 case HeapTupleUpdated:
1542 ReleaseBuffer(buffer);
1543 if (IsXactIsoLevelSerializable)
1545 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1546 errmsg("could not serialize access due to concurrent update")));
1547 if (!ItemPointerEquals(&update_ctid, &tuple.t_self))
1549 /* it was updated, so look at the updated version */
1550 tuple.t_self = update_ctid;
1553 /* tuple was deleted, so give up */
1557 ReleaseBuffer(buffer);
1558 elog(ERROR, "unrecognized heap_lock_tuple status: %u",
1560 return NULL; /* keep compiler quiet */
1564 * We got tuple - now copy it for use by recheck query.
1566 copyTuple = heap_copytuple(&tuple);
1567 ReleaseBuffer(buffer);
1572 * If the referenced slot was actually empty, the latest version of
1573 * the row must have been deleted, so we need do nothing.
1575 if (tuple.t_data == NULL)
1577 ReleaseBuffer(buffer);
1582 * As above, if xmin isn't what we're expecting, do nothing.
1584 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1587 ReleaseBuffer(buffer);
1592 * If we get here, the tuple was found but failed SnapshotDirty.
1593 * Assuming the xmin is either a committed xact or our own xact (as it
1594 * certainly should be if we're trying to modify the tuple), this must
1595 * mean that the row was updated or deleted by either a committed xact
1596 * or our own xact. If it was deleted, we can ignore it; if it was
1597 * updated then chain up to the next version and repeat the whole
1600 * As above, it should be safe to examine xmax and t_ctid without the
1601 * buffer content lock, because they can't be changing.
1603 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
1605 /* deleted, so forget about it */
1606 ReleaseBuffer(buffer);
1610 /* updated, so look at the updated row */
1611 tuple.t_self = tuple.t_data->t_ctid;
1612 /* updated row should have xmin matching this xmax */
1613 priorXmax = HeapTupleHeaderGetXmax(tuple.t_data);
1614 ReleaseBuffer(buffer);
1615 /* loop back to fetch next in chain */
1619 * Return the copied tuple
1625 * EvalPlanQualInit -- initialize during creation of a plan state node
1626 * that might need to invoke EPQ processing.
1627 * Note: subplan can be NULL if it will be set later with EvalPlanQualSetPlan.
1630 EvalPlanQualInit(EPQState *epqstate, EState *estate,
1631 Plan *subplan, int epqParam)
1633 /* Mark the EPQ state inactive */
1634 epqstate->estate = NULL;
1635 epqstate->planstate = NULL;
1636 epqstate->origslot = NULL;
1637 /* ... and remember data that EvalPlanQualBegin will need */
1638 epqstate->plan = subplan;
1639 epqstate->rowMarks = NIL;
1640 epqstate->epqParam = epqParam;
1644 * EvalPlanQualSetPlan -- set or change subplan of an EPQState.
1646 * We need this so that ModifyTuple can deal with multiple subplans.
1649 EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan)
1651 /* If we have a live EPQ query, shut it down */
1652 EvalPlanQualEnd(epqstate);
1653 /* And set/change the plan pointer */
1654 epqstate->plan = subplan;
1658 * EvalPlanQualAddRowMark -- add an ExecRowMark that EPQ needs to handle.
1660 * Currently, only non-locking RowMarks are supported.
1663 EvalPlanQualAddRowMark(EPQState *epqstate, ExecRowMark *erm)
1665 if (RowMarkRequiresRowShareLock(erm->markType))
1666 elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
1667 epqstate->rowMarks = lappend(epqstate->rowMarks, erm);
1671 * Install one test tuple into EPQ state, or clear test tuple if tuple == NULL
1673 * NB: passed tuple must be palloc'd; it may get freed later
1676 EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
1678 EState *estate = epqstate->estate;
1683 * free old test tuple, if any, and store new tuple where relation's
1684 * scan node will see it
1686 if (estate->es_epqTuple[rti - 1] != NULL)
1687 heap_freetuple(estate->es_epqTuple[rti - 1]);
1688 estate->es_epqTuple[rti - 1] = tuple;
1689 estate->es_epqTupleSet[rti - 1] = true;
1693 * Fetch back the current test tuple (if any) for the specified RTI
1696 EvalPlanQualGetTuple(EPQState *epqstate, Index rti)
1698 EState *estate = epqstate->estate;
1702 return estate->es_epqTuple[rti - 1];
1706 * Fetch the current row values for any non-locked relations that need
1707 * to be scanned by an EvalPlanQual operation. origslot must have been set
1708 * to contain the current result row (top-level row) that we need to recheck.
1711 EvalPlanQualFetchRowMarks(EPQState *epqstate)
1715 Assert(epqstate->origslot != NULL);
1717 foreach(l, epqstate->rowMarks)
1719 ExecRowMark *erm = (ExecRowMark *) lfirst(l);
1722 HeapTupleData tuple;
1724 /* clear any leftover test tuple for this rel */
1725 EvalPlanQualSetTuple(epqstate, erm->rti, NULL);
1731 Assert(erm->markType == ROW_MARK_REFERENCE);
1733 /* if child rel, must check whether it produced this row */
1734 if (erm->rti != erm->prti)
1738 datum = ExecGetJunkAttribute(epqstate->origslot,
1741 /* non-locked rels could be on the inside of outer joins */
1744 tableoid = DatumGetObjectId(datum);
1746 if (tableoid != RelationGetRelid(erm->relation))
1748 /* this child is inactive right now */
1753 /* fetch the tuple's ctid */
1754 datum = ExecGetJunkAttribute(epqstate->origslot,
1757 /* non-locked rels could be on the inside of outer joins */
1760 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1762 /* okay, fetch the tuple */
1763 if (!heap_fetch(erm->relation, SnapshotAny, &tuple, &buffer,
1765 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
1767 /* successful, copy and store tuple */
1768 EvalPlanQualSetTuple(epqstate, erm->rti,
1769 heap_copytuple(&tuple));
1770 ReleaseBuffer(buffer);
1776 Assert(erm->markType == ROW_MARK_COPY);
1778 /* fetch the whole-row Var for the relation */
1779 datum = ExecGetJunkAttribute(epqstate->origslot,
1782 /* non-locked rels could be on the inside of outer joins */
1785 td = DatumGetHeapTupleHeader(datum);
1787 /* build a temporary HeapTuple control structure */
1788 tuple.t_len = HeapTupleHeaderGetDatumLength(td);
1789 ItemPointerSetInvalid(&(tuple.t_self));
1790 tuple.t_tableOid = InvalidOid;
1793 /* copy and store tuple */
1794 EvalPlanQualSetTuple(epqstate, erm->rti,
1795 heap_copytuple(&tuple));
1801 * Fetch the next row (if any) from EvalPlanQual testing
1803 * (In practice, there should never be more than one row...)
1806 EvalPlanQualNext(EPQState *epqstate)
1808 MemoryContext oldcontext;
1809 TupleTableSlot *slot;
1811 oldcontext = MemoryContextSwitchTo(epqstate->estate->es_query_cxt);
1812 slot = ExecProcNode(epqstate->planstate);
1813 MemoryContextSwitchTo(oldcontext);
1819 * Initialize or reset an EvalPlanQual state tree
1822 EvalPlanQualBegin(EPQState *epqstate, EState *parentestate)
1824 EState *estate = epqstate->estate;
1828 /* First time through, so create a child EState */
1829 EvalPlanQualStart(epqstate, parentestate, epqstate->plan);
1834 * We already have a suitable child EPQ tree, so just reset it.
1836 int rtsize = list_length(parentestate->es_range_table);
1837 PlanState *planstate = epqstate->planstate;
1839 MemSet(estate->es_epqScanDone, 0, rtsize * sizeof(bool));
1841 /* Recopy current values of parent parameters */
1842 if (parentestate->es_plannedstmt->nParamExec > 0)
1844 int i = parentestate->es_plannedstmt->nParamExec;
1848 /* copy value if any, but not execPlan link */
1849 estate->es_param_exec_vals[i].value =
1850 parentestate->es_param_exec_vals[i].value;
1851 estate->es_param_exec_vals[i].isnull =
1852 parentestate->es_param_exec_vals[i].isnull;
1857 * Mark child plan tree as needing rescan at all scan nodes. The
1858 * first ExecProcNode will take care of actually doing the rescan.
1860 planstate->chgParam = bms_add_member(planstate->chgParam,
1861 epqstate->epqParam);
1866 * Start execution of an EvalPlanQual plan tree.
1868 * This is a cut-down version of ExecutorStart(): we copy some state from
1869 * the top-level estate rather than initializing it fresh.
1872 EvalPlanQualStart(EPQState *epqstate, EState *parentestate, Plan *planTree)
1876 MemoryContext oldcontext;
1879 rtsize = list_length(parentestate->es_range_table);
1881 epqstate->estate = estate = CreateExecutorState();
1883 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1886 * Child EPQ EStates share the parent's copy of unchanging state such as
1887 * the snapshot, rangetable, result-rel info, and external Param info.
1888 * They need their own copies of local state, including a tuple table,
1889 * es_param_exec_vals, etc.
1891 estate->es_direction = ForwardScanDirection;
1892 estate->es_snapshot = parentestate->es_snapshot;
1893 estate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
1894 estate->es_range_table = parentestate->es_range_table;
1895 estate->es_plannedstmt = parentestate->es_plannedstmt;
1896 estate->es_junkFilter = parentestate->es_junkFilter;
1897 estate->es_output_cid = parentestate->es_output_cid;
1898 estate->es_result_relations = parentestate->es_result_relations;
1899 estate->es_num_result_relations = parentestate->es_num_result_relations;
1900 estate->es_result_relation_info = parentestate->es_result_relation_info;
1901 /* es_trig_target_relations must NOT be copied */
1902 estate->es_rowMarks = parentestate->es_rowMarks;
1903 estate->es_instrument = parentestate->es_instrument;
1904 estate->es_select_into = parentestate->es_select_into;
1905 estate->es_into_oids = parentestate->es_into_oids;
1908 * The external param list is simply shared from parent. The internal
1909 * param workspace has to be local state, but we copy the initial values
1910 * from the parent, so as to have access to any param values that were
1911 * already set from other parts of the parent's plan tree.
1913 estate->es_param_list_info = parentestate->es_param_list_info;
1914 if (parentestate->es_plannedstmt->nParamExec > 0)
1916 int i = parentestate->es_plannedstmt->nParamExec;
1918 estate->es_param_exec_vals = (ParamExecData *)
1919 palloc0(i * sizeof(ParamExecData));
1922 /* copy value if any, but not execPlan link */
1923 estate->es_param_exec_vals[i].value =
1924 parentestate->es_param_exec_vals[i].value;
1925 estate->es_param_exec_vals[i].isnull =
1926 parentestate->es_param_exec_vals[i].isnull;
1931 * Each EState must have its own es_epqScanDone state, but if we have
1932 * nested EPQ checks they should share es_epqTuple arrays. This allows
1933 * sub-rechecks to inherit the values being examined by an outer recheck.
1935 estate->es_epqScanDone = (bool *) palloc0(rtsize * sizeof(bool));
1936 if (parentestate->es_epqTuple != NULL)
1938 estate->es_epqTuple = parentestate->es_epqTuple;
1939 estate->es_epqTupleSet = parentestate->es_epqTupleSet;
1943 estate->es_epqTuple = (HeapTuple *)
1944 palloc0(rtsize * sizeof(HeapTuple));
1945 estate->es_epqTupleSet = (bool *)
1946 palloc0(rtsize * sizeof(bool));
1950 * Each estate also has its own tuple table.
1952 estate->es_tupleTable = NIL;
1955 * Initialize private state information for each SubPlan. We must do this
1956 * before running ExecInitNode on the main query tree, since
1957 * ExecInitSubPlan expects to be able to find these entries.
1958 * Some of the SubPlans might not be used in the part of the plan tree
1959 * we intend to run, but since it's not easy to tell which, we just
1960 * initialize them all.
1962 Assert(estate->es_subplanstates == NIL);
1963 foreach(l, parentestate->es_plannedstmt->subplans)
1965 Plan *subplan = (Plan *) lfirst(l);
1966 PlanState *subplanstate;
1968 subplanstate = ExecInitNode(subplan, estate, 0);
1970 estate->es_subplanstates = lappend(estate->es_subplanstates,
1975 * Initialize the private state information for all the nodes in the
1976 * part of the plan tree we need to run. This opens files, allocates
1977 * storage and leaves us ready to start processing tuples.
1979 epqstate->planstate = ExecInitNode(planTree, estate, 0);
1981 MemoryContextSwitchTo(oldcontext);
1985 * EvalPlanQualEnd -- shut down at termination of parent plan state node,
1986 * or if we are done with the current EPQ child.
1988 * This is a cut-down version of ExecutorEnd(); basically we want to do most
1989 * of the normal cleanup, but *not* close result relations (which we are
1990 * just sharing from the outer query). We do, however, have to close any
1991 * trigger target relations that got opened, since those are not shared.
1992 * (There probably shouldn't be any of the latter, but just in case...)
1995 EvalPlanQualEnd(EPQState *epqstate)
1997 EState *estate = epqstate->estate;
1998 MemoryContext oldcontext;
2002 return; /* idle, so nothing to do */
2004 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2006 ExecEndNode(epqstate->planstate);
2008 foreach(l, estate->es_subplanstates)
2010 PlanState *subplanstate = (PlanState *) lfirst(l);
2012 ExecEndNode(subplanstate);
2015 /* throw away the per-estate tuple table */
2016 ExecResetTupleTable(estate->es_tupleTable, false);
2018 /* close any trigger target relations attached to this EState */
2019 foreach(l, estate->es_trig_target_relations)
2021 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
2023 /* Close indices and then the relation itself */
2024 ExecCloseIndices(resultRelInfo);
2025 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
2028 MemoryContextSwitchTo(oldcontext);
2030 FreeExecutorState(estate);
2032 /* Mark EPQState idle */
2033 epqstate->estate = NULL;
2034 epqstate->planstate = NULL;
2035 epqstate->origslot = NULL;
2040 * Support for SELECT INTO (a/k/a CREATE TABLE AS)
2042 * We implement SELECT INTO by diverting SELECT's normal output with
2043 * a specialized DestReceiver type.
2048 DestReceiver pub; /* publicly-known function pointers */
2049 EState *estate; /* EState we are working with */
2050 Relation rel; /* Relation to write to */
2051 int hi_options; /* heap_insert performance options */
2052 BulkInsertState bistate; /* bulk insert state */
2056 * OpenIntoRel --- actually create the SELECT INTO target relation
2058 * This also replaces QueryDesc->dest with the special DestReceiver for
2059 * SELECT INTO. We assume that the correct result tuple type has already
2060 * been placed in queryDesc->tupDesc.
2063 OpenIntoRel(QueryDesc *queryDesc)
2065 IntoClause *into = queryDesc->plannedstmt->intoClause;
2066 EState *estate = queryDesc->estate;
2067 Relation intoRelationDesc;
2072 AclResult aclresult;
2075 DR_intorel *myState;
2076 static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
2081 * XXX This code needs to be kept in sync with DefineRelation().
2082 * Maybe we should try to use that function instead.
2086 * Check consistency of arguments
2088 if (into->onCommit != ONCOMMIT_NOOP && !into->rel->istemp)
2090 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2091 errmsg("ON COMMIT can only be used on temporary tables")));
2094 * Security check: disallow creating temp tables from security-restricted
2095 * code. This is needed because calling code might not expect untrusted
2096 * tables to appear in pg_temp at the front of its search path.
2098 if (into->rel->istemp && InSecurityRestrictedOperation())
2100 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2101 errmsg("cannot create temporary table within security-restricted operation")));
2104 * Find namespace to create in, check its permissions
2106 intoName = into->rel->relname;
2107 namespaceId = RangeVarGetCreationNamespace(into->rel);
2109 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
2111 if (aclresult != ACLCHECK_OK)
2112 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2113 get_namespace_name(namespaceId));
2116 * Select tablespace to use. If not specified, use default tablespace
2117 * (which may in turn default to database's default).
2119 if (into->tableSpaceName)
2121 tablespaceId = get_tablespace_oid(into->tableSpaceName);
2122 if (!OidIsValid(tablespaceId))
2124 (errcode(ERRCODE_UNDEFINED_OBJECT),
2125 errmsg("tablespace \"%s\" does not exist",
2126 into->tableSpaceName)));
2130 tablespaceId = GetDefaultTablespace(into->rel->istemp);
2131 /* note InvalidOid is OK in this case */
2134 /* Check permissions except when using the database's default space */
2135 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
2137 AclResult aclresult;
2139 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
2142 if (aclresult != ACLCHECK_OK)
2143 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
2144 get_tablespace_name(tablespaceId));
2147 /* Parse and validate any reloptions */
2148 reloptions = transformRelOptions((Datum) 0,
2154 (void) heap_reloptions(RELKIND_RELATION, reloptions, true);
2156 /* Copy the tupdesc because heap_create_with_catalog modifies it */
2157 tupdesc = CreateTupleDescCopy(queryDesc->tupDesc);
2159 /* Now we can actually create the new relation */
2160 intoRelationId = heap_create_with_catalog(intoName,
2175 allowSystemTableMods);
2177 FreeTupleDesc(tupdesc);
2180 * Advance command counter so that the newly-created relation's catalog
2181 * tuples will be visible to heap_open.
2183 CommandCounterIncrement();
2186 * If necessary, create a TOAST table for the INTO relation. Note that
2187 * AlterTableCreateToastTable ends with CommandCounterIncrement(), so that
2188 * the TOAST table will be visible for insertion.
2190 reloptions = transformRelOptions((Datum) 0,
2197 (void) heap_reloptions(RELKIND_TOASTVALUE, reloptions, true);
2199 AlterTableCreateToastTable(intoRelationId, InvalidOid, reloptions, false);
2202 * And open the constructed table for writing.
2204 intoRelationDesc = heap_open(intoRelationId, AccessExclusiveLock);
2207 * Now replace the query's DestReceiver with one for SELECT INTO
2209 queryDesc->dest = CreateDestReceiver(DestIntoRel);
2210 myState = (DR_intorel *) queryDesc->dest;
2211 Assert(myState->pub.mydest == DestIntoRel);
2212 myState->estate = estate;
2213 myState->rel = intoRelationDesc;
2216 * We can skip WAL-logging the insertions, unless PITR is in use. We can
2217 * skip the FSM in any case.
2219 myState->hi_options = HEAP_INSERT_SKIP_FSM |
2220 (XLogArchivingActive() ? 0 : HEAP_INSERT_SKIP_WAL);
2221 myState->bistate = GetBulkInsertState();
2223 /* Not using WAL requires rd_targblock be initially invalid */
2224 Assert(intoRelationDesc->rd_targblock == InvalidBlockNumber);
2228 * CloseIntoRel --- clean up SELECT INTO at ExecutorEnd time
2231 CloseIntoRel(QueryDesc *queryDesc)
2233 DR_intorel *myState = (DR_intorel *) queryDesc->dest;
2235 /* OpenIntoRel might never have gotten called */
2236 if (myState && myState->pub.mydest == DestIntoRel && myState->rel)
2238 FreeBulkInsertState(myState->bistate);
2240 /* If we skipped using WAL, must heap_sync before commit */
2241 if (myState->hi_options & HEAP_INSERT_SKIP_WAL)
2242 heap_sync(myState->rel);
2244 /* close rel, but keep lock until commit */
2245 heap_close(myState->rel, NoLock);
2247 myState->rel = NULL;
2252 * CreateIntoRelDestReceiver -- create a suitable DestReceiver object
2255 CreateIntoRelDestReceiver(void)
2257 DR_intorel *self = (DR_intorel *) palloc0(sizeof(DR_intorel));
2259 self->pub.receiveSlot = intorel_receive;
2260 self->pub.rStartup = intorel_startup;
2261 self->pub.rShutdown = intorel_shutdown;
2262 self->pub.rDestroy = intorel_destroy;
2263 self->pub.mydest = DestIntoRel;
2265 /* private fields will be set by OpenIntoRel */
2267 return (DestReceiver *) self;
2271 * intorel_startup --- executor startup
2274 intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
2280 * intorel_receive --- receive one tuple
2283 intorel_receive(TupleTableSlot *slot, DestReceiver *self)
2285 DR_intorel *myState = (DR_intorel *) self;
2289 * get the heap tuple out of the tuple table slot, making sure we have a
2292 tuple = ExecMaterializeSlot(slot);
2295 * force assignment of new OID (see comments in ExecInsert)
2297 if (myState->rel->rd_rel->relhasoids)
2298 HeapTupleSetOid(tuple, InvalidOid);
2300 heap_insert(myState->rel,
2302 myState->estate->es_output_cid,
2303 myState->hi_options,
2306 /* We know this is a newly created relation, so there are no indexes */
2310 * intorel_shutdown --- executor end
2313 intorel_shutdown(DestReceiver *self)
2319 * intorel_destroy --- release DestReceiver object
2322 intorel_destroy(DestReceiver *self)