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-2012, 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 "mb/pg_wchar.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/builtins.h"
61 #include "utils/lsyscache.h"
62 #include "utils/memutils.h"
63 #include "utils/snapmgr.h"
64 #include "utils/tqual.h"
67 /* Hooks for plugins to get control in ExecutorStart/Run/Finish/End */
68 ExecutorStart_hook_type ExecutorStart_hook = NULL;
69 ExecutorRun_hook_type ExecutorRun_hook = NULL;
70 ExecutorFinish_hook_type ExecutorFinish_hook = NULL;
71 ExecutorEnd_hook_type ExecutorEnd_hook = NULL;
73 /* Hook for plugin to get control in ExecCheckRTPerms() */
74 ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL;
76 /* decls for local routines only used within this module */
77 static void InitPlan(QueryDesc *queryDesc, int eflags);
78 static void CheckValidRowMarkRel(Relation rel, RowMarkType markType);
79 static void ExecPostprocessPlan(EState *estate);
80 static void ExecEndPlan(PlanState *planstate, EState *estate);
81 static void ExecutePlan(EState *estate, PlanState *planstate,
85 ScanDirection direction,
87 static bool ExecCheckRTEPerms(RangeTblEntry *rte);
88 static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
89 static char *ExecBuildSlotValueDescription(TupleTableSlot *slot,
91 static void EvalPlanQualStart(EPQState *epqstate, EState *parentestate,
93 static void OpenIntoRel(QueryDesc *queryDesc);
94 static void CloseIntoRel(QueryDesc *queryDesc);
95 static void intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
96 static void intorel_receive(TupleTableSlot *slot, DestReceiver *self);
97 static void intorel_shutdown(DestReceiver *self);
98 static void intorel_destroy(DestReceiver *self);
100 /* end of local decls */
103 /* ----------------------------------------------------------------
106 * This routine must be called at the beginning of any execution of any
109 * Takes a QueryDesc previously created by CreateQueryDesc (which is separate
110 * only because some places use QueryDescs for utility commands). The tupDesc
111 * field of the QueryDesc is filled in to describe the tuples that will be
112 * returned, and the internal fields (estate and planstate) are set up.
114 * eflags contains flag bits as described in executor.h.
116 * NB: the CurrentMemoryContext when this is called will become the parent
117 * of the per-query context used for this Executor invocation.
119 * We provide a function hook variable that lets loadable plugins
120 * get control when ExecutorStart is called. Such a plugin would
121 * normally call standard_ExecutorStart().
123 * ----------------------------------------------------------------
126 ExecutorStart(QueryDesc *queryDesc, int eflags)
128 if (ExecutorStart_hook)
129 (*ExecutorStart_hook) (queryDesc, eflags);
131 standard_ExecutorStart(queryDesc, eflags);
135 standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
138 MemoryContext oldcontext;
140 /* sanity checks: queryDesc must not be started already */
141 Assert(queryDesc != NULL);
142 Assert(queryDesc->estate == NULL);
145 * If the transaction is read-only, we need to check if any writes are
146 * planned to non-temporary tables. EXPLAIN is considered read-only.
148 if (XactReadOnly && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
149 ExecCheckXactReadOnly(queryDesc->plannedstmt);
152 * Build EState, switch into per-query memory context for startup.
154 estate = CreateExecutorState();
155 queryDesc->estate = estate;
157 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
160 * Fill in external parameters, if any, from queryDesc; and allocate
161 * workspace for internal parameters
163 estate->es_param_list_info = queryDesc->params;
165 if (queryDesc->plannedstmt->nParamExec > 0)
166 estate->es_param_exec_vals = (ParamExecData *)
167 palloc0(queryDesc->plannedstmt->nParamExec * sizeof(ParamExecData));
170 * If non-read-only query, set the command ID to mark output tuples with
172 switch (queryDesc->operation)
177 * SELECT INTO, SELECT FOR UPDATE/SHARE and modifying CTEs need to
180 if (queryDesc->plannedstmt->intoClause != NULL ||
181 queryDesc->plannedstmt->rowMarks != NIL ||
182 queryDesc->plannedstmt->hasModifyingCTE)
183 estate->es_output_cid = GetCurrentCommandId(true);
186 * A SELECT without modifying CTEs can't possibly queue triggers,
187 * so force skip-triggers mode. This is just a marginal efficiency
188 * hack, since AfterTriggerBeginQuery/AfterTriggerEndQuery aren't
189 * all that expensive, but we might as well do it.
191 if (!queryDesc->plannedstmt->hasModifyingCTE)
192 eflags |= EXEC_FLAG_SKIP_TRIGGERS;
198 estate->es_output_cid = GetCurrentCommandId(true);
202 elog(ERROR, "unrecognized operation code: %d",
203 (int) queryDesc->operation);
208 * Copy other important information into the EState
210 estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
211 estate->es_crosscheck_snapshot = RegisterSnapshot(queryDesc->crosscheck_snapshot);
212 estate->es_top_eflags = eflags;
213 estate->es_instrument = queryDesc->instrument_options;
216 * Initialize the plan state tree
218 InitPlan(queryDesc, eflags);
221 * Set up an AFTER-trigger statement context, unless told not to, or
222 * unless it's EXPLAIN-only mode (when ExecutorFinish won't be called).
224 if (!(eflags & (EXEC_FLAG_SKIP_TRIGGERS | EXEC_FLAG_EXPLAIN_ONLY)))
225 AfterTriggerBeginQuery();
227 MemoryContextSwitchTo(oldcontext);
230 /* ----------------------------------------------------------------
233 * This is the main routine of the executor module. It accepts
234 * the query descriptor from the traffic cop and executes the
237 * ExecutorStart must have been called already.
239 * If direction is NoMovementScanDirection then nothing is done
240 * except to start up/shut down the destination. Otherwise,
241 * we retrieve up to 'count' tuples in the specified direction.
243 * Note: count = 0 is interpreted as no portal limit, i.e., run to
246 * There is no return value, but output tuples (if any) are sent to
247 * the destination receiver specified in the QueryDesc; and the number
248 * of tuples processed at the top level can be found in
249 * estate->es_processed.
251 * We provide a function hook variable that lets loadable plugins
252 * get control when ExecutorRun is called. Such a plugin would
253 * normally call standard_ExecutorRun().
255 * ----------------------------------------------------------------
258 ExecutorRun(QueryDesc *queryDesc,
259 ScanDirection direction, long count)
261 if (ExecutorRun_hook)
262 (*ExecutorRun_hook) (queryDesc, direction, count);
264 standard_ExecutorRun(queryDesc, direction, count);
268 standard_ExecutorRun(QueryDesc *queryDesc,
269 ScanDirection direction, long count)
275 MemoryContext oldcontext;
278 Assert(queryDesc != NULL);
280 estate = queryDesc->estate;
282 Assert(estate != NULL);
283 Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
286 * Switch into per-query memory context
288 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
290 /* Allow instrumentation of Executor overall runtime */
291 if (queryDesc->totaltime)
292 InstrStartNode(queryDesc->totaltime);
295 * extract information from the query descriptor and the query feature.
297 operation = queryDesc->operation;
298 dest = queryDesc->dest;
301 * startup tuple receiver, if we will be emitting tuples
303 estate->es_processed = 0;
304 estate->es_lastoid = InvalidOid;
306 sendTuples = (operation == CMD_SELECT ||
307 queryDesc->plannedstmt->hasReturning);
310 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
313 * if it's CREATE TABLE AS ... WITH NO DATA, skip plan execution
315 if (estate->es_select_into &&
316 queryDesc->plannedstmt->intoClause->skipData)
317 direction = NoMovementScanDirection;
322 if (!ScanDirectionIsNoMovement(direction))
324 queryDesc->planstate,
332 * shutdown tuple receiver, if we started it
335 (*dest->rShutdown) (dest);
337 if (queryDesc->totaltime)
338 InstrStopNode(queryDesc->totaltime, estate->es_processed);
340 MemoryContextSwitchTo(oldcontext);
343 /* ----------------------------------------------------------------
346 * This routine must be called after the last ExecutorRun call.
347 * It performs cleanup such as firing AFTER triggers. It is
348 * separate from ExecutorEnd because EXPLAIN ANALYZE needs to
349 * include these actions in the total runtime.
351 * We provide a function hook variable that lets loadable plugins
352 * get control when ExecutorFinish is called. Such a plugin would
353 * normally call standard_ExecutorFinish().
355 * ----------------------------------------------------------------
358 ExecutorFinish(QueryDesc *queryDesc)
360 if (ExecutorFinish_hook)
361 (*ExecutorFinish_hook) (queryDesc);
363 standard_ExecutorFinish(queryDesc);
367 standard_ExecutorFinish(QueryDesc *queryDesc)
370 MemoryContext oldcontext;
373 Assert(queryDesc != NULL);
375 estate = queryDesc->estate;
377 Assert(estate != NULL);
378 Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
380 /* This should be run once and only once per Executor instance */
381 Assert(!estate->es_finished);
383 /* Switch into per-query memory context */
384 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
386 /* Allow instrumentation of Executor overall runtime */
387 if (queryDesc->totaltime)
388 InstrStartNode(queryDesc->totaltime);
390 /* Run ModifyTable nodes to completion */
391 ExecPostprocessPlan(estate);
393 /* Execute queued AFTER triggers, unless told not to */
394 if (!(estate->es_top_eflags & EXEC_FLAG_SKIP_TRIGGERS))
395 AfterTriggerEndQuery(estate);
397 if (queryDesc->totaltime)
398 InstrStopNode(queryDesc->totaltime, 0);
400 MemoryContextSwitchTo(oldcontext);
402 estate->es_finished = true;
405 /* ----------------------------------------------------------------
408 * This routine must be called at the end of execution of any
411 * We provide a function hook variable that lets loadable plugins
412 * get control when ExecutorEnd is called. Such a plugin would
413 * normally call standard_ExecutorEnd().
415 * ----------------------------------------------------------------
418 ExecutorEnd(QueryDesc *queryDesc)
420 if (ExecutorEnd_hook)
421 (*ExecutorEnd_hook) (queryDesc);
423 standard_ExecutorEnd(queryDesc);
427 standard_ExecutorEnd(QueryDesc *queryDesc)
430 MemoryContext oldcontext;
433 Assert(queryDesc != NULL);
435 estate = queryDesc->estate;
437 Assert(estate != NULL);
440 * Check that ExecutorFinish was called, unless in EXPLAIN-only mode. This
441 * Assert is needed because ExecutorFinish is new as of 9.1, and callers
442 * might forget to call it.
444 Assert(estate->es_finished ||
445 (estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
448 * Switch into per-query memory context to run ExecEndPlan
450 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
452 ExecEndPlan(queryDesc->planstate, estate);
455 * Close the SELECT INTO relation if any
457 if (estate->es_select_into)
458 CloseIntoRel(queryDesc);
460 /* do away with our snapshots */
461 UnregisterSnapshot(estate->es_snapshot);
462 UnregisterSnapshot(estate->es_crosscheck_snapshot);
465 * Must switch out of context before destroying it
467 MemoryContextSwitchTo(oldcontext);
470 * Release EState and per-query memory context. This should release
471 * everything the executor has allocated.
473 FreeExecutorState(estate);
475 /* Reset queryDesc fields that no longer point to anything */
476 queryDesc->tupDesc = NULL;
477 queryDesc->estate = NULL;
478 queryDesc->planstate = NULL;
479 queryDesc->totaltime = NULL;
482 /* ----------------------------------------------------------------
485 * This routine may be called on an open queryDesc to rewind it
487 * ----------------------------------------------------------------
490 ExecutorRewind(QueryDesc *queryDesc)
493 MemoryContext oldcontext;
496 Assert(queryDesc != NULL);
498 estate = queryDesc->estate;
500 Assert(estate != NULL);
502 /* It's probably not sensible to rescan updating queries */
503 Assert(queryDesc->operation == CMD_SELECT);
506 * Switch into per-query memory context
508 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
513 ExecReScan(queryDesc->planstate);
515 MemoryContextSwitchTo(oldcontext);
521 * Check access permissions for all relations listed in a range table.
523 * Returns true if permissions are adequate. Otherwise, throws an appropriate
524 * error if ereport_on_violation is true, or simply returns false otherwise.
527 ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
532 foreach(l, rangeTable)
534 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
536 result = ExecCheckRTEPerms(rte);
539 Assert(rte->rtekind == RTE_RELATION);
540 if (ereport_on_violation)
541 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
542 get_rel_name(rte->relid));
547 if (ExecutorCheckPerms_hook)
548 result = (*ExecutorCheckPerms_hook) (rangeTable,
549 ereport_on_violation);
555 * Check access permissions for a single RTE.
558 ExecCheckRTEPerms(RangeTblEntry *rte)
560 AclMode requiredPerms;
562 AclMode remainingPerms;
569 * Only plain-relation RTEs need to be checked here. Function RTEs are
570 * checked by init_fcache when the function is prepared for execution.
571 * Join, subquery, and special RTEs need no checks.
573 if (rte->rtekind != RTE_RELATION)
577 * No work if requiredPerms is empty.
579 requiredPerms = rte->requiredPerms;
580 if (requiredPerms == 0)
586 * userid to check as: current user unless we have a setuid indication.
588 * Note: GetUserId() is presently fast enough that there's no harm in
589 * calling it separately for each RTE. If that stops being true, we could
590 * call it once in ExecCheckRTPerms and pass the userid down from there.
591 * But for now, no need for the extra clutter.
593 userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
596 * We must have *all* the requiredPerms bits, but some of the bits can be
597 * satisfied from column-level rather than relation-level permissions.
598 * First, remove any bits that are satisfied by relation permissions.
600 relPerms = pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL);
601 remainingPerms = requiredPerms & ~relPerms;
602 if (remainingPerms != 0)
605 * If we lack any permissions that exist only as relation permissions,
606 * we can fail straight away.
608 if (remainingPerms & ~(ACL_SELECT | ACL_INSERT | ACL_UPDATE))
612 * Check to see if we have the needed privileges at column level.
614 * Note: failures just report a table-level error; it would be nicer
615 * to report a column-level error if we have some but not all of the
618 if (remainingPerms & ACL_SELECT)
621 * When the query doesn't explicitly reference any columns (for
622 * example, SELECT COUNT(*) FROM table), allow the query if we
623 * have SELECT on any column of the rel, as per SQL spec.
625 if (bms_is_empty(rte->selectedCols))
627 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
628 ACLMASK_ANY) != ACLCHECK_OK)
632 tmpset = bms_copy(rte->selectedCols);
633 while ((col = bms_first_member(tmpset)) >= 0)
635 /* remove the column number offset */
636 col += FirstLowInvalidHeapAttributeNumber;
637 if (col == InvalidAttrNumber)
639 /* Whole-row reference, must have priv on all cols */
640 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
641 ACLMASK_ALL) != ACLCHECK_OK)
646 if (pg_attribute_aclcheck(relOid, col, userid,
647 ACL_SELECT) != ACLCHECK_OK)
655 * Basically the same for the mod columns, with either INSERT or
656 * UPDATE privilege as specified by remainingPerms.
658 remainingPerms &= ~ACL_SELECT;
659 if (remainingPerms != 0)
662 * When the query doesn't explicitly change any columns, allow the
663 * query if we have permission on any column of the rel. This is
664 * to handle SELECT FOR UPDATE as well as possible corner cases in
667 if (bms_is_empty(rte->modifiedCols))
669 if (pg_attribute_aclcheck_all(relOid, userid, remainingPerms,
670 ACLMASK_ANY) != ACLCHECK_OK)
674 tmpset = bms_copy(rte->modifiedCols);
675 while ((col = bms_first_member(tmpset)) >= 0)
677 /* remove the column number offset */
678 col += FirstLowInvalidHeapAttributeNumber;
679 if (col == InvalidAttrNumber)
681 /* whole-row reference can't happen here */
682 elog(ERROR, "whole-row update is not implemented");
686 if (pg_attribute_aclcheck(relOid, col, userid,
687 remainingPerms) != ACLCHECK_OK)
698 * Check that the query does not imply any writes to non-temp tables.
700 * Note: in a Hot Standby slave this would need to reject writes to temp
701 * tables as well; but an HS slave can't have created any temp tables
702 * in the first place, so no need to check that.
705 ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
710 * CREATE TABLE AS or SELECT INTO?
712 * XXX should we allow this if the destination is temp? Considering that
713 * it would still require catalog changes, probably not.
715 if (plannedstmt->intoClause != NULL)
716 PreventCommandIfReadOnly(CreateCommandTag((Node *) plannedstmt));
718 /* Fail if write permissions are requested on any non-temp table */
719 foreach(l, plannedstmt->rtable)
721 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
723 if (rte->rtekind != RTE_RELATION)
726 if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
729 if (isTempNamespace(get_rel_namespace(rte->relid)))
732 PreventCommandIfReadOnly(CreateCommandTag((Node *) plannedstmt));
737 /* ----------------------------------------------------------------
740 * Initializes the query plan: open files, allocate storage
741 * and start up the rule manager
742 * ----------------------------------------------------------------
745 InitPlan(QueryDesc *queryDesc, int eflags)
747 CmdType operation = queryDesc->operation;
748 PlannedStmt *plannedstmt = queryDesc->plannedstmt;
749 Plan *plan = plannedstmt->planTree;
750 List *rangeTable = plannedstmt->rtable;
751 EState *estate = queryDesc->estate;
752 PlanState *planstate;
758 * Do permissions checks
760 ExecCheckRTPerms(rangeTable, true);
763 * initialize the node's execution state
765 estate->es_range_table = rangeTable;
766 estate->es_plannedstmt = plannedstmt;
769 * initialize result relation stuff, and open/lock the result rels.
771 * We must do this before initializing the plan tree, else we might try to
772 * do a lock upgrade if a result rel is also a source rel.
774 if (plannedstmt->resultRelations)
776 List *resultRelations = plannedstmt->resultRelations;
777 int numResultRelations = list_length(resultRelations);
778 ResultRelInfo *resultRelInfos;
779 ResultRelInfo *resultRelInfo;
781 resultRelInfos = (ResultRelInfo *)
782 palloc(numResultRelations * sizeof(ResultRelInfo));
783 resultRelInfo = resultRelInfos;
784 foreach(l, resultRelations)
786 Index resultRelationIndex = lfirst_int(l);
787 Oid resultRelationOid;
788 Relation resultRelation;
790 resultRelationOid = getrelid(resultRelationIndex, rangeTable);
791 resultRelation = heap_open(resultRelationOid, RowExclusiveLock);
792 InitResultRelInfo(resultRelInfo,
795 estate->es_instrument);
798 estate->es_result_relations = resultRelInfos;
799 estate->es_num_result_relations = numResultRelations;
800 /* es_result_relation_info is NULL except when within ModifyTable */
801 estate->es_result_relation_info = NULL;
806 * if no result relation, then set state appropriately
808 estate->es_result_relations = NULL;
809 estate->es_num_result_relations = 0;
810 estate->es_result_relation_info = NULL;
814 * Similarly, we have to lock relations selected FOR UPDATE/FOR SHARE
815 * before we initialize the plan tree, else we'd be risking lock upgrades.
816 * While we are at it, build the ExecRowMark list.
818 estate->es_rowMarks = NIL;
819 foreach(l, plannedstmt->rowMarks)
821 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
826 /* ignore "parent" rowmarks; they are irrelevant at runtime */
830 switch (rc->markType)
832 case ROW_MARK_EXCLUSIVE:
834 relid = getrelid(rc->rti, rangeTable);
835 relation = heap_open(relid, RowShareLock);
837 case ROW_MARK_REFERENCE:
838 relid = getrelid(rc->rti, rangeTable);
839 relation = heap_open(relid, AccessShareLock);
842 /* there's no real table here ... */
846 elog(ERROR, "unrecognized markType: %d", rc->markType);
847 relation = NULL; /* keep compiler quiet */
851 /* Check that relation is a legal target for marking */
853 CheckValidRowMarkRel(relation, rc->markType);
855 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
856 erm->relation = relation;
858 erm->prti = rc->prti;
859 erm->rowmarkId = rc->rowmarkId;
860 erm->markType = rc->markType;
861 erm->noWait = rc->noWait;
862 ItemPointerSetInvalid(&(erm->curCtid));
863 estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
867 * Detect whether we're doing SELECT INTO. If so, set the es_into_oids
868 * flag appropriately so that the plan tree will be initialized with the
869 * correct tuple descriptors. (Other SELECT INTO stuff comes later.)
871 estate->es_select_into = false;
872 if (operation == CMD_SELECT && plannedstmt->intoClause != NULL)
874 estate->es_select_into = true;
875 estate->es_into_oids = interpretOidsOption(plannedstmt->intoClause->options);
879 * Initialize the executor's tuple table to empty.
881 estate->es_tupleTable = NIL;
882 estate->es_trig_tuple_slot = NULL;
883 estate->es_trig_oldtup_slot = NULL;
884 estate->es_trig_newtup_slot = NULL;
886 /* mark EvalPlanQual not active */
887 estate->es_epqTuple = NULL;
888 estate->es_epqTupleSet = NULL;
889 estate->es_epqScanDone = NULL;
892 * Initialize private state information for each SubPlan. We must do this
893 * before running ExecInitNode on the main query tree, since
894 * ExecInitSubPlan expects to be able to find these entries.
896 Assert(estate->es_subplanstates == NIL);
897 i = 1; /* subplan indices count from 1 */
898 foreach(l, plannedstmt->subplans)
900 Plan *subplan = (Plan *) lfirst(l);
901 PlanState *subplanstate;
905 * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
906 * it is a parameterless subplan (not initplan), we suggest that it be
907 * prepared to handle REWIND efficiently; otherwise there is no need.
909 sp_eflags = eflags & EXEC_FLAG_EXPLAIN_ONLY;
910 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
911 sp_eflags |= EXEC_FLAG_REWIND;
913 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
915 estate->es_subplanstates = lappend(estate->es_subplanstates,
922 * Initialize the private state information for all the nodes in the query
923 * tree. This opens files, allocates storage and leaves us ready to start
926 planstate = ExecInitNode(plan, estate, eflags);
929 * Get the tuple descriptor describing the type of tuples to return. (this
930 * is especially important if we are creating a relation with "SELECT
933 tupType = ExecGetResultType(planstate);
936 * Initialize the junk filter if needed. SELECT queries need a filter if
937 * there are any junk attrs in the top-level tlist.
939 if (operation == CMD_SELECT)
941 bool junk_filter_needed = false;
944 foreach(tlist, plan->targetlist)
946 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
950 junk_filter_needed = true;
955 if (junk_filter_needed)
959 j = ExecInitJunkFilter(planstate->plan->targetlist,
961 ExecInitExtraTupleSlot(estate));
962 estate->es_junkFilter = j;
964 /* Want to return the cleaned tuple type */
965 tupType = j->jf_cleanTupType;
969 queryDesc->tupDesc = tupType;
970 queryDesc->planstate = planstate;
973 * If doing SELECT INTO, initialize the "into" relation. We must wait
974 * till now so we have the "clean" result tuple type to create the new
977 * If EXPLAIN, skip creating the "into" relation.
979 if (estate->es_select_into && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
980 OpenIntoRel(queryDesc);
984 * Check that a proposed result relation is a legal target for the operation
986 * In most cases parser and/or planner should have noticed this already, but
987 * let's make sure. In the view case we do need a test here, because if the
988 * view wasn't rewritten by a rule, it had better have an INSTEAD trigger.
990 * Note: when changing this function, you probably also need to look at
991 * CheckValidRowMarkRel.
994 CheckValidResultRel(Relation resultRel, CmdType operation)
996 TriggerDesc *trigDesc = resultRel->trigdesc;
998 switch (resultRel->rd_rel->relkind)
1000 case RELKIND_RELATION:
1003 case RELKIND_SEQUENCE:
1005 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1006 errmsg("cannot change sequence \"%s\"",
1007 RelationGetRelationName(resultRel))));
1009 case RELKIND_TOASTVALUE:
1011 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1012 errmsg("cannot change TOAST relation \"%s\"",
1013 RelationGetRelationName(resultRel))));
1019 if (!trigDesc || !trigDesc->trig_insert_instead_row)
1021 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1022 errmsg("cannot insert into view \"%s\"",
1023 RelationGetRelationName(resultRel)),
1024 errhint("You need an unconditional ON INSERT DO INSTEAD rule or an INSTEAD OF INSERT trigger.")));
1027 if (!trigDesc || !trigDesc->trig_update_instead_row)
1029 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1030 errmsg("cannot update view \"%s\"",
1031 RelationGetRelationName(resultRel)),
1032 errhint("You need an unconditional ON UPDATE DO INSTEAD rule or an INSTEAD OF UPDATE trigger.")));
1035 if (!trigDesc || !trigDesc->trig_delete_instead_row)
1037 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1038 errmsg("cannot delete from view \"%s\"",
1039 RelationGetRelationName(resultRel)),
1040 errhint("You need an unconditional ON DELETE DO INSTEAD rule or an INSTEAD OF DELETE trigger.")));
1043 elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1047 case RELKIND_FOREIGN_TABLE:
1049 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1050 errmsg("cannot change foreign table \"%s\"",
1051 RelationGetRelationName(resultRel))));
1055 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1056 errmsg("cannot change relation \"%s\"",
1057 RelationGetRelationName(resultRel))));
1063 * Check that a proposed rowmark target relation is a legal target
1065 * In most cases parser and/or planner should have noticed this already, but
1066 * they don't cover all cases.
1069 CheckValidRowMarkRel(Relation rel, RowMarkType markType)
1071 switch (rel->rd_rel->relkind)
1073 case RELKIND_RELATION:
1076 case RELKIND_SEQUENCE:
1077 /* Must disallow this because we don't vacuum sequences */
1079 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1080 errmsg("cannot lock rows in sequence \"%s\"",
1081 RelationGetRelationName(rel))));
1083 case RELKIND_TOASTVALUE:
1084 /* We could allow this, but there seems no good reason to */
1086 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1087 errmsg("cannot lock rows in TOAST relation \"%s\"",
1088 RelationGetRelationName(rel))));
1091 /* Should not get here */
1093 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1094 errmsg("cannot lock rows in view \"%s\"",
1095 RelationGetRelationName(rel))));
1097 case RELKIND_FOREIGN_TABLE:
1098 /* Perhaps we can support this someday, but not today */
1100 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1101 errmsg("cannot lock rows in foreign table \"%s\"",
1102 RelationGetRelationName(rel))));
1106 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1107 errmsg("cannot lock rows in relation \"%s\"",
1108 RelationGetRelationName(rel))));
1114 * Initialize ResultRelInfo data for one result relation
1116 * Caution: before Postgres 9.1, this function included the relkind checking
1117 * that's now in CheckValidResultRel, and it also did ExecOpenIndices if
1118 * appropriate. Be sure callers cover those needs.
1121 InitResultRelInfo(ResultRelInfo *resultRelInfo,
1122 Relation resultRelationDesc,
1123 Index resultRelationIndex,
1124 int instrument_options)
1126 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1127 resultRelInfo->type = T_ResultRelInfo;
1128 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1129 resultRelInfo->ri_RelationDesc = resultRelationDesc;
1130 resultRelInfo->ri_NumIndices = 0;
1131 resultRelInfo->ri_IndexRelationDescs = NULL;
1132 resultRelInfo->ri_IndexRelationInfo = NULL;
1133 /* make a copy so as not to depend on relcache info not changing... */
1134 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1135 if (resultRelInfo->ri_TrigDesc)
1137 int n = resultRelInfo->ri_TrigDesc->numtriggers;
1139 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1140 palloc0(n * sizeof(FmgrInfo));
1141 resultRelInfo->ri_TrigWhenExprs = (List **)
1142 palloc0(n * sizeof(List *));
1143 if (instrument_options)
1144 resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options);
1148 resultRelInfo->ri_TrigFunctions = NULL;
1149 resultRelInfo->ri_TrigWhenExprs = NULL;
1150 resultRelInfo->ri_TrigInstrument = NULL;
1152 resultRelInfo->ri_ConstraintExprs = NULL;
1153 resultRelInfo->ri_junkFilter = NULL;
1154 resultRelInfo->ri_projectReturning = NULL;
1158 * ExecGetTriggerResultRel
1160 * Get a ResultRelInfo for a trigger target relation. Most of the time,
1161 * triggers are fired on one of the result relations of the query, and so
1162 * we can just return a member of the es_result_relations array. (Note: in
1163 * self-join situations there might be multiple members with the same OID;
1164 * if so it doesn't matter which one we pick.) However, it is sometimes
1165 * necessary to fire triggers on other relations; this happens mainly when an
1166 * RI update trigger queues additional triggers on other relations, which will
1167 * be processed in the context of the outer query. For efficiency's sake,
1168 * we want to have a ResultRelInfo for those triggers too; that can avoid
1169 * repeated re-opening of the relation. (It also provides a way for EXPLAIN
1170 * ANALYZE to report the runtimes of such triggers.) So we make additional
1171 * ResultRelInfo's as needed, and save them in es_trig_target_relations.
1174 ExecGetTriggerResultRel(EState *estate, Oid relid)
1176 ResultRelInfo *rInfo;
1180 MemoryContext oldcontext;
1182 /* First, search through the query result relations */
1183 rInfo = estate->es_result_relations;
1184 nr = estate->es_num_result_relations;
1187 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1192 /* Nope, but maybe we already made an extra ResultRelInfo for it */
1193 foreach(l, estate->es_trig_target_relations)
1195 rInfo = (ResultRelInfo *) lfirst(l);
1196 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1199 /* Nope, so we need a new one */
1202 * Open the target relation's relcache entry. We assume that an
1203 * appropriate lock is still held by the backend from whenever the trigger
1204 * event got queued, so we need take no new lock here. Also, we need not
1205 * recheck the relkind, so no need for CheckValidResultRel.
1207 rel = heap_open(relid, NoLock);
1210 * Make the new entry in the right context.
1212 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1213 rInfo = makeNode(ResultRelInfo);
1214 InitResultRelInfo(rInfo,
1216 0, /* dummy rangetable index */
1217 estate->es_instrument);
1218 estate->es_trig_target_relations =
1219 lappend(estate->es_trig_target_relations, rInfo);
1220 MemoryContextSwitchTo(oldcontext);
1223 * Currently, we don't need any index information in ResultRelInfos used
1224 * only for triggers, so no need to call ExecOpenIndices.
1231 * ExecContextForcesOids
1233 * This is pretty grotty: when doing INSERT, UPDATE, or SELECT INTO,
1234 * we need to ensure that result tuples have space for an OID iff they are
1235 * going to be stored into a relation that has OIDs. In other contexts
1236 * we are free to choose whether to leave space for OIDs in result tuples
1237 * (we generally don't want to, but we do if a physical-tlist optimization
1238 * is possible). This routine checks the plan context and returns TRUE if the
1239 * choice is forced, FALSE if the choice is not forced. In the TRUE case,
1240 * *hasoids is set to the required value.
1242 * One reason this is ugly is that all plan nodes in the plan tree will emit
1243 * tuples with space for an OID, though we really only need the topmost node
1244 * to do so. However, node types like Sort don't project new tuples but just
1245 * return their inputs, and in those cases the requirement propagates down
1246 * to the input node. Eventually we might make this code smart enough to
1247 * recognize how far down the requirement really goes, but for now we just
1248 * make all plan nodes do the same thing if the top level forces the choice.
1250 * We assume that if we are generating tuples for INSERT or UPDATE,
1251 * estate->es_result_relation_info is already set up to describe the target
1252 * relation. Note that in an UPDATE that spans an inheritance tree, some of
1253 * the target relations may have OIDs and some not. We have to make the
1254 * decisions on a per-relation basis as we initialize each of the subplans of
1255 * the ModifyTable node, so ModifyTable has to set es_result_relation_info
1256 * while initializing each subplan.
1258 * SELECT INTO is even uglier, because we don't have the INTO relation's
1259 * descriptor available when this code runs; we have to look aside at a
1260 * flag set by InitPlan().
1263 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
1265 ResultRelInfo *ri = planstate->state->es_result_relation_info;
1269 Relation rel = ri->ri_RelationDesc;
1273 *hasoids = rel->rd_rel->relhasoids;
1278 if (planstate->state->es_select_into)
1280 *hasoids = planstate->state->es_into_oids;
1287 /* ----------------------------------------------------------------
1288 * ExecPostprocessPlan
1290 * Give plan nodes a final chance to execute before shutdown
1291 * ----------------------------------------------------------------
1294 ExecPostprocessPlan(EState *estate)
1299 * Make sure nodes run forward.
1301 estate->es_direction = ForwardScanDirection;
1304 * Run any secondary ModifyTable nodes to completion, in case the main
1305 * query did not fetch all rows from them. (We do this to ensure that
1306 * such nodes have predictable results.)
1308 foreach(lc, estate->es_auxmodifytables)
1310 PlanState *ps = (PlanState *) lfirst(lc);
1314 TupleTableSlot *slot;
1316 /* Reset the per-output-tuple exprcontext each time */
1317 ResetPerTupleExprContext(estate);
1319 slot = ExecProcNode(ps);
1321 if (TupIsNull(slot))
1327 /* ----------------------------------------------------------------
1330 * Cleans up the query plan -- closes files and frees up storage
1332 * NOTE: we are no longer very worried about freeing storage per se
1333 * in this code; FreeExecutorState should be guaranteed to release all
1334 * memory that needs to be released. What we are worried about doing
1335 * is closing relations and dropping buffer pins. Thus, for example,
1336 * tuple tables must be cleared or dropped to ensure pins are released.
1337 * ----------------------------------------------------------------
1340 ExecEndPlan(PlanState *planstate, EState *estate)
1342 ResultRelInfo *resultRelInfo;
1347 * shut down the node-type-specific query processing
1349 ExecEndNode(planstate);
1354 foreach(l, estate->es_subplanstates)
1356 PlanState *subplanstate = (PlanState *) lfirst(l);
1358 ExecEndNode(subplanstate);
1362 * destroy the executor's tuple table. Actually we only care about
1363 * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1364 * the TupleTableSlots, since the containing memory context is about to go
1367 ExecResetTupleTable(estate->es_tupleTable, false);
1370 * close the result relation(s) if any, but hold locks until xact commit.
1372 resultRelInfo = estate->es_result_relations;
1373 for (i = estate->es_num_result_relations; i > 0; i--)
1375 /* Close indices and then the relation itself */
1376 ExecCloseIndices(resultRelInfo);
1377 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1382 * likewise close any trigger target relations
1384 foreach(l, estate->es_trig_target_relations)
1386 resultRelInfo = (ResultRelInfo *) lfirst(l);
1387 /* Close indices and then the relation itself */
1388 ExecCloseIndices(resultRelInfo);
1389 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1393 * close any relations selected FOR UPDATE/FOR SHARE, again keeping locks
1395 foreach(l, estate->es_rowMarks)
1397 ExecRowMark *erm = (ExecRowMark *) lfirst(l);
1400 heap_close(erm->relation, NoLock);
1404 /* ----------------------------------------------------------------
1407 * Processes the query plan until we have processed 'numberTuples' tuples,
1408 * moving in the specified direction.
1410 * Runs to completion if numberTuples is 0
1412 * Note: the ctid attribute is a 'junk' attribute that is removed before the
1414 * ----------------------------------------------------------------
1417 ExecutePlan(EState *estate,
1418 PlanState *planstate,
1422 ScanDirection direction,
1425 TupleTableSlot *slot;
1426 long current_tuple_count;
1429 * initialize local variables
1431 current_tuple_count = 0;
1434 * Set the direction.
1436 estate->es_direction = direction;
1439 * Loop until we've processed the proper number of tuples from the plan.
1443 /* Reset the per-output-tuple exprcontext */
1444 ResetPerTupleExprContext(estate);
1447 * Execute the plan and obtain a tuple
1449 slot = ExecProcNode(planstate);
1452 * if the tuple is null, then we assume there is nothing more to
1453 * process so we just end the loop...
1455 if (TupIsNull(slot))
1459 * If we have a junk filter, then project a new tuple with the junk
1462 * Store this new "clean" tuple in the junkfilter's resultSlot.
1463 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1464 * because that tuple slot has the wrong descriptor.)
1466 if (estate->es_junkFilter != NULL)
1467 slot = ExecFilterJunk(estate->es_junkFilter, slot);
1470 * If we are supposed to send the tuple somewhere, do so. (In
1471 * practice, this is probably always the case at this point.)
1474 (*dest->receiveSlot) (slot, dest);
1477 * Count tuples processed, if this is a SELECT. (For other operation
1478 * types, the ModifyTable plan node must count the appropriate
1481 if (operation == CMD_SELECT)
1482 (estate->es_processed)++;
1485 * check our tuple count.. if we've processed the proper number then
1486 * quit, else loop again and process more tuples. Zero numberTuples
1489 current_tuple_count++;
1490 if (numberTuples && numberTuples == current_tuple_count)
1497 * ExecRelCheck --- check that tuple meets constraints for result relation
1500 ExecRelCheck(ResultRelInfo *resultRelInfo,
1501 TupleTableSlot *slot, EState *estate)
1503 Relation rel = resultRelInfo->ri_RelationDesc;
1504 int ncheck = rel->rd_att->constr->num_check;
1505 ConstrCheck *check = rel->rd_att->constr->check;
1506 ExprContext *econtext;
1507 MemoryContext oldContext;
1512 * If first time through for this result relation, build expression
1513 * nodetrees for rel's constraint expressions. Keep them in the per-query
1514 * memory context so they'll survive throughout the query.
1516 if (resultRelInfo->ri_ConstraintExprs == NULL)
1518 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1519 resultRelInfo->ri_ConstraintExprs =
1520 (List **) palloc(ncheck * sizeof(List *));
1521 for (i = 0; i < ncheck; i++)
1523 /* ExecQual wants implicit-AND form */
1524 qual = make_ands_implicit(stringToNode(check[i].ccbin));
1525 resultRelInfo->ri_ConstraintExprs[i] = (List *)
1526 ExecPrepareExpr((Expr *) qual, estate);
1528 MemoryContextSwitchTo(oldContext);
1532 * We will use the EState's per-tuple context for evaluating constraint
1533 * expressions (creating it if it's not already there).
1535 econtext = GetPerTupleExprContext(estate);
1537 /* Arrange for econtext's scan tuple to be the tuple under test */
1538 econtext->ecxt_scantuple = slot;
1540 /* And evaluate the constraints */
1541 for (i = 0; i < ncheck; i++)
1543 qual = resultRelInfo->ri_ConstraintExprs[i];
1546 * NOTE: SQL92 specifies that a NULL result from a constraint
1547 * expression is not to be treated as a failure. Therefore, tell
1548 * ExecQual to return TRUE for NULL.
1550 if (!ExecQual(qual, econtext, true))
1551 return check[i].ccname;
1554 /* NULL result means no error */
1559 ExecConstraints(ResultRelInfo *resultRelInfo,
1560 TupleTableSlot *slot, EState *estate)
1562 Relation rel = resultRelInfo->ri_RelationDesc;
1563 TupleConstr *constr = rel->rd_att->constr;
1567 if (constr->has_not_null)
1569 int natts = rel->rd_att->natts;
1572 for (attrChk = 1; attrChk <= natts; attrChk++)
1574 if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1575 slot_attisnull(slot, attrChk))
1577 (errcode(ERRCODE_NOT_NULL_VIOLATION),
1578 errmsg("null value in column \"%s\" violates not-null constraint",
1579 NameStr(rel->rd_att->attrs[attrChk - 1]->attname)),
1580 errdetail("Failing row contains %s.",
1581 ExecBuildSlotValueDescription(slot, 64))));
1585 if (constr->num_check > 0)
1589 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1591 (errcode(ERRCODE_CHECK_VIOLATION),
1592 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1593 RelationGetRelationName(rel), failed),
1594 errdetail("Failing row contains %s.",
1595 ExecBuildSlotValueDescription(slot, 64))));
1600 * ExecBuildSlotValueDescription -- construct a string representing a tuple
1602 * This is intentionally very similar to BuildIndexValueDescription, but
1603 * unlike that function, we truncate long field values. That seems necessary
1604 * here since heap field values could be very long, whereas index entries
1605 * typically aren't so wide.
1608 ExecBuildSlotValueDescription(TupleTableSlot *slot, int maxfieldlen)
1611 TupleDesc tupdesc = slot->tts_tupleDescriptor;
1614 /* Make sure the tuple is fully deconstructed */
1615 slot_getallattrs(slot);
1617 initStringInfo(&buf);
1619 appendStringInfoChar(&buf, '(');
1621 for (i = 0; i < tupdesc->natts; i++)
1626 if (slot->tts_isnull[i])
1633 getTypeOutputInfo(tupdesc->attrs[i]->atttypid,
1634 &foutoid, &typisvarlena);
1635 val = OidOutputFunctionCall(foutoid, slot->tts_values[i]);
1639 appendStringInfoString(&buf, ", ");
1641 /* truncate if needed */
1642 vallen = strlen(val);
1643 if (vallen <= maxfieldlen)
1644 appendStringInfoString(&buf, val);
1647 vallen = pg_mbcliplen(val, vallen, maxfieldlen);
1648 appendBinaryStringInfo(&buf, val, vallen);
1649 appendStringInfoString(&buf, "...");
1653 appendStringInfoChar(&buf, ')');
1660 * ExecFindRowMark -- find the ExecRowMark struct for given rangetable index
1663 ExecFindRowMark(EState *estate, Index rti)
1667 foreach(lc, estate->es_rowMarks)
1669 ExecRowMark *erm = (ExecRowMark *) lfirst(lc);
1671 if (erm->rti == rti)
1674 elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
1675 return NULL; /* keep compiler quiet */
1679 * ExecBuildAuxRowMark -- create an ExecAuxRowMark struct
1681 * Inputs are the underlying ExecRowMark struct and the targetlist of the
1682 * input plan node (not planstate node!). We need the latter to find out
1683 * the column numbers of the resjunk columns.
1686 ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
1688 ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
1691 aerm->rowmark = erm;
1693 /* Look up the resjunk columns associated with this rowmark */
1696 Assert(erm->markType != ROW_MARK_COPY);
1698 /* if child rel, need tableoid */
1699 if (erm->rti != erm->prti)
1701 snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
1702 aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
1704 if (!AttributeNumberIsValid(aerm->toidAttNo))
1705 elog(ERROR, "could not find junk %s column", resname);
1708 /* always need ctid for real relations */
1709 snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
1710 aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
1712 if (!AttributeNumberIsValid(aerm->ctidAttNo))
1713 elog(ERROR, "could not find junk %s column", resname);
1717 Assert(erm->markType == ROW_MARK_COPY);
1719 snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
1720 aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
1722 if (!AttributeNumberIsValid(aerm->wholeAttNo))
1723 elog(ERROR, "could not find junk %s column", resname);
1731 * EvalPlanQual logic --- recheck modified tuple(s) to see if we want to
1732 * process the updated version under READ COMMITTED rules.
1734 * See backend/executor/README for some info about how this works.
1739 * Check a modified tuple to see if we want to process its updated version
1740 * under READ COMMITTED rules.
1742 * estate - outer executor state data
1743 * epqstate - state for EvalPlanQual rechecking
1744 * relation - table containing tuple
1745 * rti - rangetable index of table containing tuple
1746 * *tid - t_ctid from the outdated tuple (ie, next updated version)
1747 * priorXmax - t_xmax from the outdated tuple
1749 * *tid is also an output parameter: it's modified to hold the TID of the
1750 * latest version of the tuple (note this may be changed even on failure)
1752 * Returns a slot containing the new candidate update/delete tuple, or
1753 * NULL if we determine we shouldn't process the row.
1756 EvalPlanQual(EState *estate, EPQState *epqstate,
1757 Relation relation, Index rti,
1758 ItemPointer tid, TransactionId priorXmax)
1760 TupleTableSlot *slot;
1761 HeapTuple copyTuple;
1766 * Get and lock the updated version of the row; if fail, return NULL.
1768 copyTuple = EvalPlanQualFetch(estate, relation, LockTupleExclusive,
1771 if (copyTuple == NULL)
1775 * For UPDATE/DELETE we have to return tid of actual row we're executing
1778 *tid = copyTuple->t_self;
1781 * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
1783 EvalPlanQualBegin(epqstate, estate);
1786 * Free old test tuple, if any, and store new tuple where relation's scan
1789 EvalPlanQualSetTuple(epqstate, rti, copyTuple);
1792 * Fetch any non-locked source rows
1794 EvalPlanQualFetchRowMarks(epqstate);
1797 * Run the EPQ query. We assume it will return at most one tuple.
1799 slot = EvalPlanQualNext(epqstate);
1802 * If we got a tuple, force the slot to materialize the tuple so that it
1803 * is not dependent on any local state in the EPQ query (in particular,
1804 * it's highly likely that the slot contains references to any pass-by-ref
1805 * datums that may be present in copyTuple). As with the next step, this
1806 * is to guard against early re-use of the EPQ query.
1808 if (!TupIsNull(slot))
1809 (void) ExecMaterializeSlot(slot);
1812 * Clear out the test tuple. This is needed in case the EPQ query is
1813 * re-used to test a tuple for a different relation. (Not clear that can
1814 * really happen, but let's be safe.)
1816 EvalPlanQualSetTuple(epqstate, rti, NULL);
1822 * Fetch a copy of the newest version of an outdated tuple
1824 * estate - executor state data
1825 * relation - table containing tuple
1826 * lockmode - requested tuple lock mode
1827 * *tid - t_ctid from the outdated tuple (ie, next updated version)
1828 * priorXmax - t_xmax from the outdated tuple
1830 * Returns a palloc'd copy of the newest tuple version, or NULL if we find
1831 * that there is no newest version (ie, the row was deleted not updated).
1832 * If successful, we have locked the newest tuple version, so caller does not
1833 * need to worry about it changing anymore.
1835 * Note: properly, lockmode should be declared as enum LockTupleMode,
1836 * but we use "int" to avoid having to include heapam.h in executor.h.
1839 EvalPlanQualFetch(EState *estate, Relation relation, int lockmode,
1840 ItemPointer tid, TransactionId priorXmax)
1842 HeapTuple copyTuple = NULL;
1843 HeapTupleData tuple;
1844 SnapshotData SnapshotDirty;
1847 * fetch target tuple
1849 * Loop here to deal with updated or busy tuples
1851 InitDirtySnapshot(SnapshotDirty);
1852 tuple.t_self = *tid;
1857 if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
1860 ItemPointerData update_ctid;
1861 TransactionId update_xmax;
1864 * If xmin isn't what we're expecting, the slot must have been
1865 * recycled and reused for an unrelated tuple. This implies that
1866 * the latest version of the row was deleted, so we need do
1867 * nothing. (Should be safe to examine xmin without getting
1868 * buffer's content lock, since xmin never changes in an existing
1871 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1874 ReleaseBuffer(buffer);
1878 /* otherwise xmin should not be dirty... */
1879 if (TransactionIdIsValid(SnapshotDirty.xmin))
1880 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
1883 * If tuple is being updated by other transaction then we have to
1884 * wait for its commit/abort.
1886 if (TransactionIdIsValid(SnapshotDirty.xmax))
1888 ReleaseBuffer(buffer);
1889 XactLockTableWait(SnapshotDirty.xmax);
1890 continue; /* loop back to repeat heap_fetch */
1894 * If tuple was inserted by our own transaction, we have to check
1895 * cmin against es_output_cid: cmin >= current CID means our
1896 * command cannot see the tuple, so we should ignore it. Without
1897 * this we are open to the "Halloween problem" of indefinitely
1898 * re-updating the same tuple. (We need not check cmax because
1899 * HeapTupleSatisfiesDirty will consider a tuple deleted by our
1900 * transaction dead, regardless of cmax.) We just checked that
1901 * priorXmax == xmin, so we can test that variable instead of
1902 * doing HeapTupleHeaderGetXmin again.
1904 if (TransactionIdIsCurrentTransactionId(priorXmax) &&
1905 HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
1907 ReleaseBuffer(buffer);
1912 * This is a live tuple, so now try to lock it.
1914 test = heap_lock_tuple(relation, &tuple, &buffer,
1915 &update_ctid, &update_xmax,
1916 estate->es_output_cid,
1918 /* We now have two pins on the buffer, get rid of one */
1919 ReleaseBuffer(buffer);
1923 case HeapTupleSelfUpdated:
1924 /* treat it as deleted; do not process */
1925 ReleaseBuffer(buffer);
1928 case HeapTupleMayBeUpdated:
1929 /* successfully locked */
1932 case HeapTupleUpdated:
1933 ReleaseBuffer(buffer);
1934 if (IsolationUsesXactSnapshot())
1936 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1937 errmsg("could not serialize access due to concurrent update")));
1938 if (!ItemPointerEquals(&update_ctid, &tuple.t_self))
1940 /* it was updated, so look at the updated version */
1941 tuple.t_self = update_ctid;
1942 /* updated row should have xmin matching this xmax */
1943 priorXmax = update_xmax;
1946 /* tuple was deleted, so give up */
1950 ReleaseBuffer(buffer);
1951 elog(ERROR, "unrecognized heap_lock_tuple status: %u",
1953 return NULL; /* keep compiler quiet */
1957 * We got tuple - now copy it for use by recheck query.
1959 copyTuple = heap_copytuple(&tuple);
1960 ReleaseBuffer(buffer);
1965 * If the referenced slot was actually empty, the latest version of
1966 * the row must have been deleted, so we need do nothing.
1968 if (tuple.t_data == NULL)
1970 ReleaseBuffer(buffer);
1975 * As above, if xmin isn't what we're expecting, do nothing.
1977 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1980 ReleaseBuffer(buffer);
1985 * If we get here, the tuple was found but failed SnapshotDirty.
1986 * Assuming the xmin is either a committed xact or our own xact (as it
1987 * certainly should be if we're trying to modify the tuple), this must
1988 * mean that the row was updated or deleted by either a committed xact
1989 * or our own xact. If it was deleted, we can ignore it; if it was
1990 * updated then chain up to the next version and repeat the whole
1993 * As above, it should be safe to examine xmax and t_ctid without the
1994 * buffer content lock, because they can't be changing.
1996 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
1998 /* deleted, so forget about it */
1999 ReleaseBuffer(buffer);
2003 /* updated, so look at the updated row */
2004 tuple.t_self = tuple.t_data->t_ctid;
2005 /* updated row should have xmin matching this xmax */
2006 priorXmax = HeapTupleHeaderGetXmax(tuple.t_data);
2007 ReleaseBuffer(buffer);
2008 /* loop back to fetch next in chain */
2012 * Return the copied tuple
2018 * EvalPlanQualInit -- initialize during creation of a plan state node
2019 * that might need to invoke EPQ processing.
2021 * Note: subplan/auxrowmarks can be NULL/NIL if they will be set later
2022 * with EvalPlanQualSetPlan.
2025 EvalPlanQualInit(EPQState *epqstate, EState *estate,
2026 Plan *subplan, List *auxrowmarks, int epqParam)
2028 /* Mark the EPQ state inactive */
2029 epqstate->estate = NULL;
2030 epqstate->planstate = NULL;
2031 epqstate->origslot = NULL;
2032 /* ... and remember data that EvalPlanQualBegin will need */
2033 epqstate->plan = subplan;
2034 epqstate->arowMarks = auxrowmarks;
2035 epqstate->epqParam = epqParam;
2039 * EvalPlanQualSetPlan -- set or change subplan of an EPQState.
2041 * We need this so that ModifyTuple can deal with multiple subplans.
2044 EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan, List *auxrowmarks)
2046 /* If we have a live EPQ query, shut it down */
2047 EvalPlanQualEnd(epqstate);
2048 /* And set/change the plan pointer */
2049 epqstate->plan = subplan;
2050 /* The rowmarks depend on the plan, too */
2051 epqstate->arowMarks = auxrowmarks;
2055 * Install one test tuple into EPQ state, or clear test tuple if tuple == NULL
2057 * NB: passed tuple must be palloc'd; it may get freed later
2060 EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
2062 EState *estate = epqstate->estate;
2067 * free old test tuple, if any, and store new tuple where relation's scan
2070 if (estate->es_epqTuple[rti - 1] != NULL)
2071 heap_freetuple(estate->es_epqTuple[rti - 1]);
2072 estate->es_epqTuple[rti - 1] = tuple;
2073 estate->es_epqTupleSet[rti - 1] = true;
2077 * Fetch back the current test tuple (if any) for the specified RTI
2080 EvalPlanQualGetTuple(EPQState *epqstate, Index rti)
2082 EState *estate = epqstate->estate;
2086 return estate->es_epqTuple[rti - 1];
2090 * Fetch the current row values for any non-locked relations that need
2091 * to be scanned by an EvalPlanQual operation. origslot must have been set
2092 * to contain the current result row (top-level row) that we need to recheck.
2095 EvalPlanQualFetchRowMarks(EPQState *epqstate)
2099 Assert(epqstate->origslot != NULL);
2101 foreach(l, epqstate->arowMarks)
2103 ExecAuxRowMark *aerm = (ExecAuxRowMark *) lfirst(l);
2104 ExecRowMark *erm = aerm->rowmark;
2107 HeapTupleData tuple;
2109 if (RowMarkRequiresRowShareLock(erm->markType))
2110 elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2112 /* clear any leftover test tuple for this rel */
2113 EvalPlanQualSetTuple(epqstate, erm->rti, NULL);
2119 Assert(erm->markType == ROW_MARK_REFERENCE);
2121 /* if child rel, must check whether it produced this row */
2122 if (erm->rti != erm->prti)
2126 datum = ExecGetJunkAttribute(epqstate->origslot,
2129 /* non-locked rels could be on the inside of outer joins */
2132 tableoid = DatumGetObjectId(datum);
2134 if (tableoid != RelationGetRelid(erm->relation))
2136 /* this child is inactive right now */
2141 /* fetch the tuple's ctid */
2142 datum = ExecGetJunkAttribute(epqstate->origslot,
2145 /* non-locked rels could be on the inside of outer joins */
2148 tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
2150 /* okay, fetch the tuple */
2151 if (!heap_fetch(erm->relation, SnapshotAny, &tuple, &buffer,
2153 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2155 /* successful, copy and store tuple */
2156 EvalPlanQualSetTuple(epqstate, erm->rti,
2157 heap_copytuple(&tuple));
2158 ReleaseBuffer(buffer);
2164 Assert(erm->markType == ROW_MARK_COPY);
2166 /* fetch the whole-row Var for the relation */
2167 datum = ExecGetJunkAttribute(epqstate->origslot,
2170 /* non-locked rels could be on the inside of outer joins */
2173 td = DatumGetHeapTupleHeader(datum);
2175 /* build a temporary HeapTuple control structure */
2176 tuple.t_len = HeapTupleHeaderGetDatumLength(td);
2177 ItemPointerSetInvalid(&(tuple.t_self));
2178 tuple.t_tableOid = InvalidOid;
2181 /* copy and store tuple */
2182 EvalPlanQualSetTuple(epqstate, erm->rti,
2183 heap_copytuple(&tuple));
2189 * Fetch the next row (if any) from EvalPlanQual testing
2191 * (In practice, there should never be more than one row...)
2194 EvalPlanQualNext(EPQState *epqstate)
2196 MemoryContext oldcontext;
2197 TupleTableSlot *slot;
2199 oldcontext = MemoryContextSwitchTo(epqstate->estate->es_query_cxt);
2200 slot = ExecProcNode(epqstate->planstate);
2201 MemoryContextSwitchTo(oldcontext);
2207 * Initialize or reset an EvalPlanQual state tree
2210 EvalPlanQualBegin(EPQState *epqstate, EState *parentestate)
2212 EState *estate = epqstate->estate;
2216 /* First time through, so create a child EState */
2217 EvalPlanQualStart(epqstate, parentestate, epqstate->plan);
2222 * We already have a suitable child EPQ tree, so just reset it.
2224 int rtsize = list_length(parentestate->es_range_table);
2225 PlanState *planstate = epqstate->planstate;
2227 MemSet(estate->es_epqScanDone, 0, rtsize * sizeof(bool));
2229 /* Recopy current values of parent parameters */
2230 if (parentestate->es_plannedstmt->nParamExec > 0)
2232 int i = parentestate->es_plannedstmt->nParamExec;
2236 /* copy value if any, but not execPlan link */
2237 estate->es_param_exec_vals[i].value =
2238 parentestate->es_param_exec_vals[i].value;
2239 estate->es_param_exec_vals[i].isnull =
2240 parentestate->es_param_exec_vals[i].isnull;
2245 * Mark child plan tree as needing rescan at all scan nodes. The
2246 * first ExecProcNode will take care of actually doing the rescan.
2248 planstate->chgParam = bms_add_member(planstate->chgParam,
2249 epqstate->epqParam);
2254 * Start execution of an EvalPlanQual plan tree.
2256 * This is a cut-down version of ExecutorStart(): we copy some state from
2257 * the top-level estate rather than initializing it fresh.
2260 EvalPlanQualStart(EPQState *epqstate, EState *parentestate, Plan *planTree)
2264 MemoryContext oldcontext;
2267 rtsize = list_length(parentestate->es_range_table);
2269 epqstate->estate = estate = CreateExecutorState();
2271 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2274 * Child EPQ EStates share the parent's copy of unchanging state such as
2275 * the snapshot, rangetable, result-rel info, and external Param info.
2276 * They need their own copies of local state, including a tuple table,
2277 * es_param_exec_vals, etc.
2279 estate->es_direction = ForwardScanDirection;
2280 estate->es_snapshot = parentestate->es_snapshot;
2281 estate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
2282 estate->es_range_table = parentestate->es_range_table;
2283 estate->es_plannedstmt = parentestate->es_plannedstmt;
2284 estate->es_junkFilter = parentestate->es_junkFilter;
2285 estate->es_output_cid = parentestate->es_output_cid;
2286 estate->es_result_relations = parentestate->es_result_relations;
2287 estate->es_num_result_relations = parentestate->es_num_result_relations;
2288 estate->es_result_relation_info = parentestate->es_result_relation_info;
2289 /* es_trig_target_relations must NOT be copied */
2290 estate->es_rowMarks = parentestate->es_rowMarks;
2291 estate->es_top_eflags = parentestate->es_top_eflags;
2292 estate->es_instrument = parentestate->es_instrument;
2293 estate->es_select_into = parentestate->es_select_into;
2294 estate->es_into_oids = parentestate->es_into_oids;
2295 /* es_auxmodifytables must NOT be copied */
2298 * The external param list is simply shared from parent. The internal
2299 * param workspace has to be local state, but we copy the initial values
2300 * from the parent, so as to have access to any param values that were
2301 * already set from other parts of the parent's plan tree.
2303 estate->es_param_list_info = parentestate->es_param_list_info;
2304 if (parentestate->es_plannedstmt->nParamExec > 0)
2306 int i = parentestate->es_plannedstmt->nParamExec;
2308 estate->es_param_exec_vals = (ParamExecData *)
2309 palloc0(i * sizeof(ParamExecData));
2312 /* copy value if any, but not execPlan link */
2313 estate->es_param_exec_vals[i].value =
2314 parentestate->es_param_exec_vals[i].value;
2315 estate->es_param_exec_vals[i].isnull =
2316 parentestate->es_param_exec_vals[i].isnull;
2321 * Each EState must have its own es_epqScanDone state, but if we have
2322 * nested EPQ checks they should share es_epqTuple arrays. This allows
2323 * sub-rechecks to inherit the values being examined by an outer recheck.
2325 estate->es_epqScanDone = (bool *) palloc0(rtsize * sizeof(bool));
2326 if (parentestate->es_epqTuple != NULL)
2328 estate->es_epqTuple = parentestate->es_epqTuple;
2329 estate->es_epqTupleSet = parentestate->es_epqTupleSet;
2333 estate->es_epqTuple = (HeapTuple *)
2334 palloc0(rtsize * sizeof(HeapTuple));
2335 estate->es_epqTupleSet = (bool *)
2336 palloc0(rtsize * sizeof(bool));
2340 * Each estate also has its own tuple table.
2342 estate->es_tupleTable = NIL;
2345 * Initialize private state information for each SubPlan. We must do this
2346 * before running ExecInitNode on the main query tree, since
2347 * ExecInitSubPlan expects to be able to find these entries. Some of the
2348 * SubPlans might not be used in the part of the plan tree we intend to
2349 * run, but since it's not easy to tell which, we just initialize them
2350 * all. (However, if the subplan is headed by a ModifyTable node, then it
2351 * must be a data-modifying CTE, which we will certainly not need to
2352 * re-run, so we can skip initializing it. This is just an efficiency
2353 * hack; it won't skip data-modifying CTEs for which the ModifyTable node
2354 * is not at the top.)
2356 Assert(estate->es_subplanstates == NIL);
2357 foreach(l, parentestate->es_plannedstmt->subplans)
2359 Plan *subplan = (Plan *) lfirst(l);
2360 PlanState *subplanstate;
2362 /* Don't initialize ModifyTable subplans, per comment above */
2363 if (IsA(subplan, ModifyTable))
2364 subplanstate = NULL;
2366 subplanstate = ExecInitNode(subplan, estate, 0);
2368 estate->es_subplanstates = lappend(estate->es_subplanstates,
2373 * Initialize the private state information for all the nodes in the part
2374 * of the plan tree we need to run. This opens files, allocates storage
2375 * and leaves us ready to start processing tuples.
2377 epqstate->planstate = ExecInitNode(planTree, estate, 0);
2379 MemoryContextSwitchTo(oldcontext);
2383 * EvalPlanQualEnd -- shut down at termination of parent plan state node,
2384 * or if we are done with the current EPQ child.
2386 * This is a cut-down version of ExecutorEnd(); basically we want to do most
2387 * of the normal cleanup, but *not* close result relations (which we are
2388 * just sharing from the outer query). We do, however, have to close any
2389 * trigger target relations that got opened, since those are not shared.
2390 * (There probably shouldn't be any of the latter, but just in case...)
2393 EvalPlanQualEnd(EPQState *epqstate)
2395 EState *estate = epqstate->estate;
2396 MemoryContext oldcontext;
2400 return; /* idle, so nothing to do */
2402 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2404 ExecEndNode(epqstate->planstate);
2406 foreach(l, estate->es_subplanstates)
2408 PlanState *subplanstate = (PlanState *) lfirst(l);
2410 ExecEndNode(subplanstate);
2413 /* throw away the per-estate tuple table */
2414 ExecResetTupleTable(estate->es_tupleTable, false);
2416 /* close any trigger target relations attached to this EState */
2417 foreach(l, estate->es_trig_target_relations)
2419 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
2421 /* Close indices and then the relation itself */
2422 ExecCloseIndices(resultRelInfo);
2423 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
2426 MemoryContextSwitchTo(oldcontext);
2428 FreeExecutorState(estate);
2430 /* Mark EPQState idle */
2431 epqstate->estate = NULL;
2432 epqstate->planstate = NULL;
2433 epqstate->origslot = NULL;
2438 * Support for SELECT INTO (a/k/a CREATE TABLE AS)
2440 * We implement SELECT INTO by diverting SELECT's normal output with
2441 * a specialized DestReceiver type.
2446 DestReceiver pub; /* publicly-known function pointers */
2447 EState *estate; /* EState we are working with */
2448 Relation rel; /* Relation to write to */
2449 int hi_options; /* heap_insert performance options */
2450 BulkInsertState bistate; /* bulk insert state */
2454 * OpenIntoRel --- actually create the SELECT INTO target relation
2456 * This also replaces QueryDesc->dest with the special DestReceiver for
2457 * SELECT INTO. We assume that the correct result tuple type has already
2458 * been placed in queryDesc->tupDesc.
2461 OpenIntoRel(QueryDesc *queryDesc)
2463 IntoClause *into = queryDesc->plannedstmt->intoClause;
2464 EState *estate = queryDesc->estate;
2465 TupleDesc intoTupDesc = queryDesc->tupDesc;
2466 Relation intoRelationDesc;
2472 DR_intorel *myState;
2475 static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
2480 * XXX This code needs to be kept in sync with DefineRelation(). Maybe we
2481 * should try to use that function instead.
2485 * Check consistency of arguments
2487 if (into->onCommit != ONCOMMIT_NOOP
2488 && into->rel->relpersistence != RELPERSISTENCE_TEMP)
2490 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2491 errmsg("ON COMMIT can only be used on temporary tables")));
2494 AclResult aclresult;
2497 for (i = 0; i < intoTupDesc->natts; i++)
2499 Oid atttypid = intoTupDesc->attrs[i]->atttypid;
2501 aclresult = pg_type_aclcheck(atttypid, GetUserId(), ACL_USAGE);
2502 if (aclresult != ACLCHECK_OK)
2503 aclcheck_error(aclresult, ACL_KIND_TYPE,
2504 format_type_be(atttypid));
2509 * If a column name list was specified in CREATE TABLE AS, override the
2510 * column names derived from the query. (Too few column names are OK, too
2511 * many are not.) It would probably be all right to scribble directly on
2512 * the query's result tupdesc, but let's be safe and make a copy.
2518 intoTupDesc = CreateTupleDescCopy(intoTupDesc);
2520 foreach(lc, into->colNames)
2522 char *colname = strVal(lfirst(lc));
2524 if (attnum > intoTupDesc->natts)
2526 (errcode(ERRCODE_SYNTAX_ERROR),
2527 errmsg("CREATE TABLE AS specifies too many column names")));
2528 namestrcpy(&(intoTupDesc->attrs[attnum - 1]->attname), colname);
2534 * Find namespace to create in, check its permissions
2536 intoName = into->rel->relname;
2537 namespaceId = RangeVarGetAndCheckCreationNamespace(into->rel);
2538 RangeVarAdjustRelationPersistence(into->rel, namespaceId);
2541 * Security check: disallow creating temp tables from security-restricted
2542 * code. This is needed because calling code might not expect untrusted
2543 * tables to appear in pg_temp at the front of its search path.
2545 if (into->rel->relpersistence == RELPERSISTENCE_TEMP
2546 && InSecurityRestrictedOperation())
2548 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2549 errmsg("cannot create temporary table within security-restricted operation")));
2552 * Select tablespace to use. If not specified, use default tablespace
2553 * (which may in turn default to database's default).
2555 if (into->tableSpaceName)
2557 tablespaceId = get_tablespace_oid(into->tableSpaceName, false);
2561 tablespaceId = GetDefaultTablespace(into->rel->relpersistence);
2562 /* note InvalidOid is OK in this case */
2565 /* Check permissions except when using the database's default space */
2566 if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
2568 AclResult aclresult;
2570 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
2573 if (aclresult != ACLCHECK_OK)
2574 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
2575 get_tablespace_name(tablespaceId));
2578 /* Parse and validate any reloptions */
2579 reloptions = transformRelOptions((Datum) 0,
2585 (void) heap_reloptions(RELKIND_RELATION, reloptions, true);
2587 /* Now we can actually create the new relation */
2588 intoRelationId = heap_create_with_catalog(intoName,
2598 into->rel->relpersistence,
2606 allowSystemTableMods);
2607 Assert(intoRelationId != InvalidOid);
2610 * Advance command counter so that the newly-created relation's catalog
2611 * tuples will be visible to heap_open.
2613 CommandCounterIncrement();
2616 * If necessary, create a TOAST table for the INTO relation. Note that
2617 * AlterTableCreateToastTable ends with CommandCounterIncrement(), so that
2618 * the TOAST table will be visible for insertion.
2620 reloptions = transformRelOptions((Datum) 0,
2627 (void) heap_reloptions(RELKIND_TOASTVALUE, reloptions, true);
2629 AlterTableCreateToastTable(intoRelationId, reloptions);
2632 * And open the constructed table for writing.
2634 intoRelationDesc = heap_open(intoRelationId, AccessExclusiveLock);
2637 * Check INSERT permission on the constructed table.
2639 rte = makeNode(RangeTblEntry);
2640 rte->rtekind = RTE_RELATION;
2641 rte->relid = intoRelationId;
2642 rte->relkind = RELKIND_RELATION;
2643 rte->requiredPerms = ACL_INSERT;
2645 for (attnum = 1; attnum <= intoTupDesc->natts; attnum++)
2646 rte->modifiedCols = bms_add_member(rte->modifiedCols,
2647 attnum - FirstLowInvalidHeapAttributeNumber);
2649 ExecCheckRTPerms(list_make1(rte), true);
2652 * Now replace the query's DestReceiver with one for SELECT INTO
2654 queryDesc->dest = CreateDestReceiver(DestIntoRel);
2655 myState = (DR_intorel *) queryDesc->dest;
2656 Assert(myState->pub.mydest == DestIntoRel);
2657 myState->estate = estate;
2658 myState->rel = intoRelationDesc;
2661 * We can skip WAL-logging the insertions, unless PITR or streaming
2662 * replication is in use. We can skip the FSM in any case.
2664 myState->hi_options = HEAP_INSERT_SKIP_FSM |
2665 (XLogIsNeeded() ? 0 : HEAP_INSERT_SKIP_WAL);
2666 myState->bistate = GetBulkInsertState();
2668 /* Not using WAL requires smgr_targblock be initially invalid */
2669 Assert(RelationGetTargetBlock(intoRelationDesc) == InvalidBlockNumber);
2673 * CloseIntoRel --- clean up SELECT INTO at ExecutorEnd time
2676 CloseIntoRel(QueryDesc *queryDesc)
2678 DR_intorel *myState = (DR_intorel *) queryDesc->dest;
2680 /* OpenIntoRel might never have gotten called */
2681 if (myState && myState->pub.mydest == DestIntoRel && myState->rel)
2683 FreeBulkInsertState(myState->bistate);
2685 /* If we skipped using WAL, must heap_sync before commit */
2686 if (myState->hi_options & HEAP_INSERT_SKIP_WAL)
2687 heap_sync(myState->rel);
2689 /* close rel, but keep lock until commit */
2690 heap_close(myState->rel, NoLock);
2692 myState->rel = NULL;
2697 * CreateIntoRelDestReceiver -- create a suitable DestReceiver object
2700 CreateIntoRelDestReceiver(void)
2702 DR_intorel *self = (DR_intorel *) palloc0(sizeof(DR_intorel));
2704 self->pub.receiveSlot = intorel_receive;
2705 self->pub.rStartup = intorel_startup;
2706 self->pub.rShutdown = intorel_shutdown;
2707 self->pub.rDestroy = intorel_destroy;
2708 self->pub.mydest = DestIntoRel;
2710 /* private fields will be set by OpenIntoRel */
2712 return (DestReceiver *) self;
2716 * intorel_startup --- executor startup
2719 intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
2725 * intorel_receive --- receive one tuple
2728 intorel_receive(TupleTableSlot *slot, DestReceiver *self)
2730 DR_intorel *myState = (DR_intorel *) self;
2734 * get the heap tuple out of the tuple table slot, making sure we have a
2737 tuple = ExecMaterializeSlot(slot);
2740 * force assignment of new OID (see comments in ExecInsert)
2742 if (myState->rel->rd_rel->relhasoids)
2743 HeapTupleSetOid(tuple, InvalidOid);
2745 heap_insert(myState->rel,
2747 myState->estate->es_output_cid,
2748 myState->hi_options,
2751 /* We know this is a newly created relation, so there are no indexes */
2755 * intorel_shutdown --- executor end
2758 intorel_shutdown(DestReceiver *self)
2764 * intorel_destroy --- release DestReceiver object
2767 intorel_destroy(DestReceiver *self)