PostgreSQL Source Code git master
execMain.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * execMain.c
4 * top level executor interface routines
5 *
6 * INTERFACE ROUTINES
7 * ExecutorStart()
8 * ExecutorRun()
9 * ExecutorFinish()
10 * ExecutorEnd()
11 *
12 * These four procedures are the external interface to the executor.
13 * In each case, the query descriptor is required as an argument.
14 *
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).
18 *
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).
24 *
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.
28 *
29 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
30 * Portions Copyright (c) 1994, Regents of the University of California
31 *
32 *
33 * IDENTIFICATION
34 * src/backend/executor/execMain.c
35 *
36 *-------------------------------------------------------------------------
37 */
38#include "postgres.h"
39
40#include "access/sysattr.h"
41#include "access/table.h"
42#include "access/tableam.h"
43#include "access/xact.h"
44#include "catalog/namespace.h"
45#include "catalog/partition.h"
46#include "commands/matview.h"
47#include "commands/trigger.h"
48#include "executor/executor.h"
51#include "foreign/fdwapi.h"
52#include "mb/pg_wchar.h"
53#include "miscadmin.h"
54#include "nodes/queryjumble.h"
56#include "pgstat.h"
58#include "tcop/utility.h"
59#include "utils/acl.h"
61#include "utils/lsyscache.h"
62#include "utils/partcache.h"
63#include "utils/rls.h"
64#include "utils/snapmgr.h"
65
66
67/* Hooks for plugins to get control in ExecutorStart/Run/Finish/End */
72
73/* Hook for plugin to get control in ExecCheckPermissions() */
75
76/* decls for local routines only used within this module */
77static void InitPlan(QueryDesc *queryDesc, int eflags);
78static void CheckValidRowMarkRel(Relation rel, RowMarkType markType);
79static void ExecPostprocessPlan(EState *estate);
80static void ExecEndPlan(PlanState *planstate, EState *estate);
81static void ExecutePlan(QueryDesc *queryDesc,
82 CmdType operation,
83 bool sendTuples,
84 uint64 numberTuples,
85 ScanDirection direction,
87static bool ExecCheckOneRelPerms(RTEPermissionInfo *perminfo);
88static bool ExecCheckPermissionsModified(Oid relOid, Oid userid,
89 Bitmapset *modifiedCols,
90 AclMode requiredPerms);
91static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
92static void EvalPlanQualStart(EPQState *epqstate, Plan *planTree);
93static void ReportNotNullViolationError(ResultRelInfo *resultRelInfo,
94 TupleTableSlot *slot,
95 EState *estate, int attnum);
96
97/* end of local decls */
98
99
100/* ----------------------------------------------------------------
101 * ExecutorStart
102 *
103 * This routine must be called at the beginning of any execution of any
104 * query plan
105 *
106 * Takes a QueryDesc previously created by CreateQueryDesc (which is separate
107 * only because some places use QueryDescs for utility commands). The tupDesc
108 * field of the QueryDesc is filled in to describe the tuples that will be
109 * returned, and the internal fields (estate and planstate) are set up.
110 *
111 * eflags contains flag bits as described in executor.h.
112 *
113 * NB: the CurrentMemoryContext when this is called will become the parent
114 * of the per-query context used for this Executor invocation.
115 *
116 * We provide a function hook variable that lets loadable plugins
117 * get control when ExecutorStart is called. Such a plugin would
118 * normally call standard_ExecutorStart().
119 *
120 * ----------------------------------------------------------------
121 */
122void
123ExecutorStart(QueryDesc *queryDesc, int eflags)
124{
125 /*
126 * In some cases (e.g. an EXECUTE statement or an execute message with the
127 * extended query protocol) the query_id won't be reported, so do it now.
128 *
129 * Note that it's harmless to report the query_id multiple times, as the
130 * call will be ignored if the top level query_id has already been
131 * reported.
132 */
133 pgstat_report_query_id(queryDesc->plannedstmt->queryId, false);
134
136 (*ExecutorStart_hook) (queryDesc, eflags);
137 else
138 standard_ExecutorStart(queryDesc, eflags);
139}
140
141void
142standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
143{
144 EState *estate;
145 MemoryContext oldcontext;
146
147 /* sanity checks: queryDesc must not be started already */
148 Assert(queryDesc != NULL);
149 Assert(queryDesc->estate == NULL);
150
151 /* caller must ensure the query's snapshot is active */
152 Assert(GetActiveSnapshot() == queryDesc->snapshot);
153
154 /*
155 * If the transaction is read-only, we need to check if any writes are
156 * planned to non-temporary tables. EXPLAIN is considered read-only.
157 *
158 * Don't allow writes in parallel mode. Supporting UPDATE and DELETE
159 * would require (a) storing the combo CID hash in shared memory, rather
160 * than synchronizing it just once at the start of parallelism, and (b) an
161 * alternative to heap_update()'s reliance on xmax for mutual exclusion.
162 * INSERT may have no such troubles, but we forbid it to simplify the
163 * checks.
164 *
165 * We have lower-level defenses in CommandCounterIncrement and elsewhere
166 * against performing unsafe operations in parallel mode, but this gives a
167 * more user-friendly error message.
168 */
169 if ((XactReadOnly || IsInParallelMode()) &&
170 !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
172
173 /*
174 * Build EState, switch into per-query memory context for startup.
175 */
176 estate = CreateExecutorState();
177 queryDesc->estate = estate;
178
179 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
180
181 /*
182 * Fill in external parameters, if any, from queryDesc; and allocate
183 * workspace for internal parameters
184 */
185 estate->es_param_list_info = queryDesc->params;
186
187 if (queryDesc->plannedstmt->paramExecTypes != NIL)
188 {
189 int nParamExec;
190
191 nParamExec = list_length(queryDesc->plannedstmt->paramExecTypes);
193 palloc0(nParamExec * sizeof(ParamExecData));
194 }
195
196 /* We now require all callers to provide sourceText */
197 Assert(queryDesc->sourceText != NULL);
198 estate->es_sourceText = queryDesc->sourceText;
199
200 /*
201 * Fill in the query environment, if any, from queryDesc.
202 */
203 estate->es_queryEnv = queryDesc->queryEnv;
204
205 /*
206 * If non-read-only query, set the command ID to mark output tuples with
207 */
208 switch (queryDesc->operation)
209 {
210 case CMD_SELECT:
211
212 /*
213 * SELECT FOR [KEY] UPDATE/SHARE and modifying CTEs need to mark
214 * tuples
215 */
216 if (queryDesc->plannedstmt->rowMarks != NIL ||
217 queryDesc->plannedstmt->hasModifyingCTE)
218 estate->es_output_cid = GetCurrentCommandId(true);
219
220 /*
221 * A SELECT without modifying CTEs can't possibly queue triggers,
222 * so force skip-triggers mode. This is just a marginal efficiency
223 * hack, since AfterTriggerBeginQuery/AfterTriggerEndQuery aren't
224 * all that expensive, but we might as well do it.
225 */
226 if (!queryDesc->plannedstmt->hasModifyingCTE)
227 eflags |= EXEC_FLAG_SKIP_TRIGGERS;
228 break;
229
230 case CMD_INSERT:
231 case CMD_DELETE:
232 case CMD_UPDATE:
233 case CMD_MERGE:
234 estate->es_output_cid = GetCurrentCommandId(true);
235 break;
236
237 default:
238 elog(ERROR, "unrecognized operation code: %d",
239 (int) queryDesc->operation);
240 break;
241 }
242
243 /*
244 * Copy other important information into the EState
245 */
246 estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
248 estate->es_top_eflags = eflags;
249 estate->es_instrument = queryDesc->instrument_options;
250 estate->es_jit_flags = queryDesc->plannedstmt->jitFlags;
251
252 /*
253 * Set up an AFTER-trigger statement context, unless told not to, or
254 * unless it's EXPLAIN-only mode (when ExecutorFinish won't be called).
255 */
258
259 /*
260 * Initialize the plan state tree
261 */
262 InitPlan(queryDesc, eflags);
263
264 MemoryContextSwitchTo(oldcontext);
265}
266
267/* ----------------------------------------------------------------
268 * ExecutorRun
269 *
270 * This is the main routine of the executor module. It accepts
271 * the query descriptor from the traffic cop and executes the
272 * query plan.
273 *
274 * ExecutorStart must have been called already.
275 *
276 * If direction is NoMovementScanDirection then nothing is done
277 * except to start up/shut down the destination. Otherwise,
278 * we retrieve up to 'count' tuples in the specified direction.
279 *
280 * Note: count = 0 is interpreted as no portal limit, i.e., run to
281 * completion. Also note that the count limit is only applied to
282 * retrieved tuples, not for instance to those inserted/updated/deleted
283 * by a ModifyTable plan node.
284 *
285 * There is no return value, but output tuples (if any) are sent to
286 * the destination receiver specified in the QueryDesc; and the number
287 * of tuples processed at the top level can be found in
288 * estate->es_processed. The total number of tuples processed in all
289 * the ExecutorRun calls can be found in estate->es_total_processed.
290 *
291 * We provide a function hook variable that lets loadable plugins
292 * get control when ExecutorRun is called. Such a plugin would
293 * normally call standard_ExecutorRun().
294 *
295 * ----------------------------------------------------------------
296 */
297void
299 ScanDirection direction, uint64 count)
300{
302 (*ExecutorRun_hook) (queryDesc, direction, count);
303 else
304 standard_ExecutorRun(queryDesc, direction, count);
305}
306
307void
309 ScanDirection direction, uint64 count)
310{
311 EState *estate;
312 CmdType operation;
314 bool sendTuples;
315 MemoryContext oldcontext;
316
317 /* sanity checks */
318 Assert(queryDesc != NULL);
319
320 estate = queryDesc->estate;
321
322 Assert(estate != NULL);
324
325 /* caller must ensure the query's snapshot is active */
327
328 /*
329 * Switch into per-query memory context
330 */
331 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
332
333 /* Allow instrumentation of Executor overall runtime */
334 if (queryDesc->totaltime)
335 InstrStartNode(queryDesc->totaltime);
336
337 /*
338 * extract information from the query descriptor and the query feature.
339 */
340 operation = queryDesc->operation;
341 dest = queryDesc->dest;
342
343 /*
344 * startup tuple receiver, if we will be emitting tuples
345 */
346 estate->es_processed = 0;
347
348 sendTuples = (operation == CMD_SELECT ||
349 queryDesc->plannedstmt->hasReturning);
350
351 if (sendTuples)
352 dest->rStartup(dest, operation, queryDesc->tupDesc);
353
354 /*
355 * Run plan, unless direction is NoMovement.
356 *
357 * Note: pquery.c selects NoMovement if a prior call already reached
358 * end-of-data in the user-specified fetch direction. This is important
359 * because various parts of the executor can misbehave if called again
360 * after reporting EOF. For example, heapam.c would actually restart a
361 * heapscan and return all its data afresh. There is also some doubt
362 * about whether a parallel plan would operate properly if an additional,
363 * necessarily non-parallel execution request occurs after completing a
364 * parallel execution. (That case should work, but it's untested.)
365 */
366 if (!ScanDirectionIsNoMovement(direction))
367 ExecutePlan(queryDesc,
368 operation,
369 sendTuples,
370 count,
371 direction,
372 dest);
373
374 /*
375 * Update es_total_processed to keep track of the number of tuples
376 * processed across multiple ExecutorRun() calls.
377 */
378 estate->es_total_processed += estate->es_processed;
379
380 /*
381 * shutdown tuple receiver, if we started it
382 */
383 if (sendTuples)
384 dest->rShutdown(dest);
385
386 if (queryDesc->totaltime)
387 InstrStopNode(queryDesc->totaltime, estate->es_processed);
388
389 MemoryContextSwitchTo(oldcontext);
390}
391
392/* ----------------------------------------------------------------
393 * ExecutorFinish
394 *
395 * This routine must be called after the last ExecutorRun call.
396 * It performs cleanup such as firing AFTER triggers. It is
397 * separate from ExecutorEnd because EXPLAIN ANALYZE needs to
398 * include these actions in the total runtime.
399 *
400 * We provide a function hook variable that lets loadable plugins
401 * get control when ExecutorFinish is called. Such a plugin would
402 * normally call standard_ExecutorFinish().
403 *
404 * ----------------------------------------------------------------
405 */
406void
408{
410 (*ExecutorFinish_hook) (queryDesc);
411 else
412 standard_ExecutorFinish(queryDesc);
413}
414
415void
417{
418 EState *estate;
419 MemoryContext oldcontext;
420
421 /* sanity checks */
422 Assert(queryDesc != NULL);
423
424 estate = queryDesc->estate;
425
426 Assert(estate != NULL);
428
429 /* This should be run once and only once per Executor instance */
430 Assert(!estate->es_finished);
431
432 /* Switch into per-query memory context */
433 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
434
435 /* Allow instrumentation of Executor overall runtime */
436 if (queryDesc->totaltime)
437 InstrStartNode(queryDesc->totaltime);
438
439 /* Run ModifyTable nodes to completion */
440 ExecPostprocessPlan(estate);
441
442 /* Execute queued AFTER triggers, unless told not to */
443 if (!(estate->es_top_eflags & EXEC_FLAG_SKIP_TRIGGERS))
444 AfterTriggerEndQuery(estate);
445
446 if (queryDesc->totaltime)
447 InstrStopNode(queryDesc->totaltime, 0);
448
449 MemoryContextSwitchTo(oldcontext);
450
451 estate->es_finished = true;
452}
453
454/* ----------------------------------------------------------------
455 * ExecutorEnd
456 *
457 * This routine must be called at the end of execution of any
458 * query plan
459 *
460 * We provide a function hook variable that lets loadable plugins
461 * get control when ExecutorEnd is called. Such a plugin would
462 * normally call standard_ExecutorEnd().
463 *
464 * ----------------------------------------------------------------
465 */
466void
468{
470 (*ExecutorEnd_hook) (queryDesc);
471 else
472 standard_ExecutorEnd(queryDesc);
473}
474
475void
477{
478 EState *estate;
479 MemoryContext oldcontext;
480
481 /* sanity checks */
482 Assert(queryDesc != NULL);
483
484 estate = queryDesc->estate;
485
486 Assert(estate != NULL);
487
488 if (estate->es_parallel_workers_to_launch > 0)
491
492 /*
493 * Check that ExecutorFinish was called, unless in EXPLAIN-only mode. This
494 * Assert is needed because ExecutorFinish is new as of 9.1, and callers
495 * might forget to call it.
496 */
497 Assert(estate->es_finished ||
499
500 /*
501 * Switch into per-query memory context to run ExecEndPlan
502 */
503 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
504
505 ExecEndPlan(queryDesc->planstate, estate);
506
507 /* do away with our snapshots */
510
511 /*
512 * Must switch out of context before destroying it
513 */
514 MemoryContextSwitchTo(oldcontext);
515
516 /*
517 * Release EState and per-query memory context. This should release
518 * everything the executor has allocated.
519 */
520 FreeExecutorState(estate);
521
522 /* Reset queryDesc fields that no longer point to anything */
523 queryDesc->tupDesc = NULL;
524 queryDesc->estate = NULL;
525 queryDesc->planstate = NULL;
526 queryDesc->totaltime = NULL;
527}
528
529/* ----------------------------------------------------------------
530 * ExecutorRewind
531 *
532 * This routine may be called on an open queryDesc to rewind it
533 * to the start.
534 * ----------------------------------------------------------------
535 */
536void
538{
539 EState *estate;
540 MemoryContext oldcontext;
541
542 /* sanity checks */
543 Assert(queryDesc != NULL);
544
545 estate = queryDesc->estate;
546
547 Assert(estate != NULL);
548
549 /* It's probably not sensible to rescan updating queries */
550 Assert(queryDesc->operation == CMD_SELECT);
551
552 /*
553 * Switch into per-query memory context
554 */
555 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
556
557 /*
558 * rescan plan
559 */
560 ExecReScan(queryDesc->planstate);
561
562 MemoryContextSwitchTo(oldcontext);
563}
564
565
566/*
567 * ExecCheckPermissions
568 * Check access permissions of relations mentioned in a query
569 *
570 * Returns true if permissions are adequate. Otherwise, throws an appropriate
571 * error if ereport_on_violation is true, or simply returns false otherwise.
572 *
573 * Note that this does NOT address row-level security policies (aka: RLS). If
574 * rows will be returned to the user as a result of this permission check
575 * passing, then RLS also needs to be consulted (and check_enable_rls()).
576 *
577 * See rewrite/rowsecurity.c.
578 *
579 * NB: rangeTable is no longer used by us, but kept around for the hooks that
580 * might still want to look at the RTEs.
581 */
582bool
583ExecCheckPermissions(List *rangeTable, List *rteperminfos,
584 bool ereport_on_violation)
585{
586 ListCell *l;
587 bool result = true;
588
589#ifdef USE_ASSERT_CHECKING
590 Bitmapset *indexset = NULL;
591
592 /* Check that rteperminfos is consistent with rangeTable */
593 foreach(l, rangeTable)
594 {
596
597 if (rte->perminfoindex != 0)
598 {
599 /* Sanity checks */
600
601 /*
602 * Only relation RTEs and subquery RTEs that were once relation
603 * RTEs (views) have their perminfoindex set.
604 */
605 Assert(rte->rtekind == RTE_RELATION ||
606 (rte->rtekind == RTE_SUBQUERY &&
607 rte->relkind == RELKIND_VIEW));
608
609 (void) getRTEPermissionInfo(rteperminfos, rte);
610 /* Many-to-one mapping not allowed */
611 Assert(!bms_is_member(rte->perminfoindex, indexset));
612 indexset = bms_add_member(indexset, rte->perminfoindex);
613 }
614 }
615
616 /* All rteperminfos are referenced */
617 Assert(bms_num_members(indexset) == list_length(rteperminfos));
618#endif
619
620 foreach(l, rteperminfos)
621 {
623
624 Assert(OidIsValid(perminfo->relid));
625 result = ExecCheckOneRelPerms(perminfo);
626 if (!result)
627 {
628 if (ereport_on_violation)
631 get_rel_name(perminfo->relid));
632 return false;
633 }
634 }
635
637 result = (*ExecutorCheckPerms_hook) (rangeTable, rteperminfos,
638 ereport_on_violation);
639 return result;
640}
641
642/*
643 * ExecCheckOneRelPerms
644 * Check access permissions for a single relation.
645 */
646static bool
648{
649 AclMode requiredPerms;
650 AclMode relPerms;
651 AclMode remainingPerms;
652 Oid userid;
653 Oid relOid = perminfo->relid;
654
655 requiredPerms = perminfo->requiredPerms;
656 Assert(requiredPerms != 0);
657
658 /*
659 * userid to check as: current user unless we have a setuid indication.
660 *
661 * Note: GetUserId() is presently fast enough that there's no harm in
662 * calling it separately for each relation. If that stops being true, we
663 * could call it once in ExecCheckPermissions and pass the userid down
664 * from there. But for now, no need for the extra clutter.
665 */
666 userid = OidIsValid(perminfo->checkAsUser) ?
667 perminfo->checkAsUser : GetUserId();
668
669 /*
670 * We must have *all* the requiredPerms bits, but some of the bits can be
671 * satisfied from column-level rather than relation-level permissions.
672 * First, remove any bits that are satisfied by relation permissions.
673 */
674 relPerms = pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL);
675 remainingPerms = requiredPerms & ~relPerms;
676 if (remainingPerms != 0)
677 {
678 int col = -1;
679
680 /*
681 * If we lack any permissions that exist only as relation permissions,
682 * we can fail straight away.
683 */
684 if (remainingPerms & ~(ACL_SELECT | ACL_INSERT | ACL_UPDATE))
685 return false;
686
687 /*
688 * Check to see if we have the needed privileges at column level.
689 *
690 * Note: failures just report a table-level error; it would be nicer
691 * to report a column-level error if we have some but not all of the
692 * column privileges.
693 */
694 if (remainingPerms & ACL_SELECT)
695 {
696 /*
697 * When the query doesn't explicitly reference any columns (for
698 * example, SELECT COUNT(*) FROM table), allow the query if we
699 * have SELECT on any column of the rel, as per SQL spec.
700 */
701 if (bms_is_empty(perminfo->selectedCols))
702 {
703 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
705 return false;
706 }
707
708 while ((col = bms_next_member(perminfo->selectedCols, col)) >= 0)
709 {
710 /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
712
713 if (attno == InvalidAttrNumber)
714 {
715 /* Whole-row reference, must have priv on all cols */
716 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
718 return false;
719 }
720 else
721 {
722 if (pg_attribute_aclcheck(relOid, attno, userid,
724 return false;
725 }
726 }
727 }
728
729 /*
730 * Basically the same for the mod columns, for both INSERT and UPDATE
731 * privilege as specified by remainingPerms.
732 */
733 if (remainingPerms & ACL_INSERT &&
735 userid,
736 perminfo->insertedCols,
737 ACL_INSERT))
738 return false;
739
740 if (remainingPerms & ACL_UPDATE &&
742 userid,
743 perminfo->updatedCols,
744 ACL_UPDATE))
745 return false;
746 }
747 return true;
748}
749
750/*
751 * ExecCheckPermissionsModified
752 * Check INSERT or UPDATE access permissions for a single relation (these
753 * are processed uniformly).
754 */
755static bool
756ExecCheckPermissionsModified(Oid relOid, Oid userid, Bitmapset *modifiedCols,
757 AclMode requiredPerms)
758{
759 int col = -1;
760
761 /*
762 * When the query doesn't explicitly update any columns, allow the query
763 * if we have permission on any column of the rel. This is to handle
764 * SELECT FOR UPDATE as well as possible corner cases in UPDATE.
765 */
766 if (bms_is_empty(modifiedCols))
767 {
768 if (pg_attribute_aclcheck_all(relOid, userid, requiredPerms,
770 return false;
771 }
772
773 while ((col = bms_next_member(modifiedCols, col)) >= 0)
774 {
775 /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
777
778 if (attno == InvalidAttrNumber)
779 {
780 /* whole-row reference can't happen here */
781 elog(ERROR, "whole-row update is not implemented");
782 }
783 else
784 {
785 if (pg_attribute_aclcheck(relOid, attno, userid,
786 requiredPerms) != ACLCHECK_OK)
787 return false;
788 }
789 }
790 return true;
791}
792
793/*
794 * Check that the query does not imply any writes to non-temp tables;
795 * unless we're in parallel mode, in which case don't even allow writes
796 * to temp tables.
797 *
798 * Note: in a Hot Standby this would need to reject writes to temp
799 * tables just as we do in parallel mode; but an HS standby can't have created
800 * any temp tables in the first place, so no need to check that.
801 */
802static void
804{
805 ListCell *l;
806
807 /*
808 * Fail if write permissions are requested in parallel mode for table
809 * (temp or non-temp), otherwise fail for any non-temp table.
810 */
811 foreach(l, plannedstmt->permInfos)
812 {
814
815 if ((perminfo->requiredPerms & (~ACL_SELECT)) == 0)
816 continue;
817
819 continue;
820
822 }
823
824 if (plannedstmt->commandType != CMD_SELECT || plannedstmt->hasModifyingCTE)
826}
827
828
829/* ----------------------------------------------------------------
830 * InitPlan
831 *
832 * Initializes the query plan: open files, allocate storage
833 * and start up the rule manager
834 * ----------------------------------------------------------------
835 */
836static void
837InitPlan(QueryDesc *queryDesc, int eflags)
838{
839 CmdType operation = queryDesc->operation;
840 PlannedStmt *plannedstmt = queryDesc->plannedstmt;
841 Plan *plan = plannedstmt->planTree;
842 List *rangeTable = plannedstmt->rtable;
843 EState *estate = queryDesc->estate;
844 PlanState *planstate;
845 TupleDesc tupType;
846 ListCell *l;
847 int i;
848
849 /*
850 * Do permissions checks
851 */
852 ExecCheckPermissions(rangeTable, plannedstmt->permInfos, true);
853
854 /*
855 * initialize the node's execution state
856 */
857 ExecInitRangeTable(estate, rangeTable, plannedstmt->permInfos,
858 bms_copy(plannedstmt->unprunableRelids));
859
860 estate->es_plannedstmt = plannedstmt;
861 estate->es_part_prune_infos = plannedstmt->partPruneInfos;
862
863 /*
864 * Perform runtime "initial" pruning to identify which child subplans,
865 * corresponding to the children of plan nodes that contain
866 * PartitionPruneInfo such as Append, will not be executed. The results,
867 * which are bitmapsets of indexes of the child subplans that will be
868 * executed, are saved in es_part_prune_results. These results correspond
869 * to each PartitionPruneInfo entry, and the es_part_prune_results list is
870 * parallel to es_part_prune_infos.
871 */
872 ExecDoInitialPruning(estate);
873
874 /*
875 * Next, build the ExecRowMark array from the PlanRowMark(s), if any.
876 */
877 if (plannedstmt->rowMarks)
878 {
879 estate->es_rowmarks = (ExecRowMark **)
880 palloc0(estate->es_range_table_size * sizeof(ExecRowMark *));
881 foreach(l, plannedstmt->rowMarks)
882 {
883 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
884 Oid relid;
885 Relation relation;
886 ExecRowMark *erm;
887
888 /*
889 * Ignore "parent" rowmarks, because they are irrelevant at
890 * runtime. Also ignore the rowmarks belonging to child tables
891 * that have been pruned in ExecDoInitialPruning().
892 */
893 if (rc->isParent ||
894 !bms_is_member(rc->rti, estate->es_unpruned_relids))
895 continue;
896
897 /* get relation's OID (will produce InvalidOid if subquery) */
898 relid = exec_rt_fetch(rc->rti, estate)->relid;
899
900 /* open relation, if we need to access it for this mark type */
901 switch (rc->markType)
902 {
905 case ROW_MARK_SHARE:
908 relation = ExecGetRangeTableRelation(estate, rc->rti, false);
909 break;
910 case ROW_MARK_COPY:
911 /* no physical table access is required */
912 relation = NULL;
913 break;
914 default:
915 elog(ERROR, "unrecognized markType: %d", rc->markType);
916 relation = NULL; /* keep compiler quiet */
917 break;
918 }
919
920 /* Check that relation is a legal target for marking */
921 if (relation)
922 CheckValidRowMarkRel(relation, rc->markType);
923
924 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
925 erm->relation = relation;
926 erm->relid = relid;
927 erm->rti = rc->rti;
928 erm->prti = rc->prti;
929 erm->rowmarkId = rc->rowmarkId;
930 erm->markType = rc->markType;
931 erm->strength = rc->strength;
932 erm->waitPolicy = rc->waitPolicy;
933 erm->ermActive = false;
935 erm->ermExtra = NULL;
936
937 Assert(erm->rti > 0 && erm->rti <= estate->es_range_table_size &&
938 estate->es_rowmarks[erm->rti - 1] == NULL);
939
940 estate->es_rowmarks[erm->rti - 1] = erm;
941 }
942 }
943
944 /*
945 * Initialize the executor's tuple table to empty.
946 */
947 estate->es_tupleTable = NIL;
948
949 /* signal that this EState is not used for EPQ */
950 estate->es_epq_active = NULL;
951
952 /*
953 * Initialize private state information for each SubPlan. We must do this
954 * before running ExecInitNode on the main query tree, since
955 * ExecInitSubPlan expects to be able to find these entries.
956 */
957 Assert(estate->es_subplanstates == NIL);
958 i = 1; /* subplan indices count from 1 */
959 foreach(l, plannedstmt->subplans)
960 {
961 Plan *subplan = (Plan *) lfirst(l);
962 PlanState *subplanstate;
963 int sp_eflags;
964
965 /*
966 * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
967 * it is a parameterless subplan (not initplan), we suggest that it be
968 * prepared to handle REWIND efficiently; otherwise there is no need.
969 */
970 sp_eflags = eflags
972 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
973 sp_eflags |= EXEC_FLAG_REWIND;
974
975 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
976
977 estate->es_subplanstates = lappend(estate->es_subplanstates,
978 subplanstate);
979
980 i++;
981 }
982
983 /*
984 * Initialize the private state information for all the nodes in the query
985 * tree. This opens files, allocates storage and leaves us ready to start
986 * processing tuples.
987 */
988 planstate = ExecInitNode(plan, estate, eflags);
989
990 /*
991 * Get the tuple descriptor describing the type of tuples to return.
992 */
993 tupType = ExecGetResultType(planstate);
994
995 /*
996 * Initialize the junk filter if needed. SELECT queries need a filter if
997 * there are any junk attrs in the top-level tlist.
998 */
999 if (operation == CMD_SELECT)
1000 {
1001 bool junk_filter_needed = false;
1002 ListCell *tlist;
1003
1004 foreach(tlist, plan->targetlist)
1005 {
1006 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
1007
1008 if (tle->resjunk)
1009 {
1010 junk_filter_needed = true;
1011 break;
1012 }
1013 }
1014
1015 if (junk_filter_needed)
1016 {
1017 JunkFilter *j;
1018 TupleTableSlot *slot;
1019
1020 slot = ExecInitExtraTupleSlot(estate, NULL, &TTSOpsVirtual);
1021 j = ExecInitJunkFilter(planstate->plan->targetlist,
1022 slot);
1023 estate->es_junkFilter = j;
1024
1025 /* Want to return the cleaned tuple type */
1026 tupType = j->jf_cleanTupType;
1027 }
1028 }
1029
1030 queryDesc->tupDesc = tupType;
1031 queryDesc->planstate = planstate;
1032}
1033
1034/*
1035 * Check that a proposed result relation is a legal target for the operation
1036 *
1037 * Generally the parser and/or planner should have noticed any such mistake
1038 * already, but let's make sure.
1039 *
1040 * For MERGE, mergeActions is the list of actions that may be performed. The
1041 * result relation is required to support every action, regardless of whether
1042 * or not they are all executed.
1043 *
1044 * Note: when changing this function, you probably also need to look at
1045 * CheckValidRowMarkRel.
1046 */
1047void
1049 List *mergeActions)
1050{
1051 Relation resultRel = resultRelInfo->ri_RelationDesc;
1052 FdwRoutine *fdwroutine;
1053
1054 /* Expect a fully-formed ResultRelInfo from InitResultRelInfo(). */
1055 Assert(resultRelInfo->ri_needLockTagTuple ==
1056 IsInplaceUpdateRelation(resultRel));
1057
1058 switch (resultRel->rd_rel->relkind)
1059 {
1060 case RELKIND_RELATION:
1061 case RELKIND_PARTITIONED_TABLE:
1062 CheckCmdReplicaIdentity(resultRel, operation);
1063 break;
1064 case RELKIND_SEQUENCE:
1065 ereport(ERROR,
1066 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1067 errmsg("cannot change sequence \"%s\"",
1068 RelationGetRelationName(resultRel))));
1069 break;
1070 case RELKIND_TOASTVALUE:
1071 ereport(ERROR,
1072 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1073 errmsg("cannot change TOAST relation \"%s\"",
1074 RelationGetRelationName(resultRel))));
1075 break;
1076 case RELKIND_VIEW:
1077
1078 /*
1079 * Okay only if there's a suitable INSTEAD OF trigger. Otherwise,
1080 * complain, but omit errdetail because we haven't got the
1081 * information handy (and given that it really shouldn't happen,
1082 * it's not worth great exertion to get).
1083 */
1084 if (!view_has_instead_trigger(resultRel, operation, mergeActions))
1085 error_view_not_updatable(resultRel, operation, mergeActions,
1086 NULL);
1087 break;
1088 case RELKIND_MATVIEW:
1090 ereport(ERROR,
1091 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1092 errmsg("cannot change materialized view \"%s\"",
1093 RelationGetRelationName(resultRel))));
1094 break;
1095 case RELKIND_FOREIGN_TABLE:
1096 /* Okay only if the FDW supports it */
1097 fdwroutine = resultRelInfo->ri_FdwRoutine;
1098 switch (operation)
1099 {
1100 case CMD_INSERT:
1101 if (fdwroutine->ExecForeignInsert == NULL)
1102 ereport(ERROR,
1103 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1104 errmsg("cannot insert into foreign table \"%s\"",
1105 RelationGetRelationName(resultRel))));
1106 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1107 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_INSERT)) == 0)
1108 ereport(ERROR,
1109 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1110 errmsg("foreign table \"%s\" does not allow inserts",
1111 RelationGetRelationName(resultRel))));
1112 break;
1113 case CMD_UPDATE:
1114 if (fdwroutine->ExecForeignUpdate == NULL)
1115 ereport(ERROR,
1116 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1117 errmsg("cannot update foreign table \"%s\"",
1118 RelationGetRelationName(resultRel))));
1119 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1120 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_UPDATE)) == 0)
1121 ereport(ERROR,
1122 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1123 errmsg("foreign table \"%s\" does not allow updates",
1124 RelationGetRelationName(resultRel))));
1125 break;
1126 case CMD_DELETE:
1127 if (fdwroutine->ExecForeignDelete == NULL)
1128 ereport(ERROR,
1129 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1130 errmsg("cannot delete from foreign table \"%s\"",
1131 RelationGetRelationName(resultRel))));
1132 if (fdwroutine->IsForeignRelUpdatable != NULL &&
1133 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_DELETE)) == 0)
1134 ereport(ERROR,
1135 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1136 errmsg("foreign table \"%s\" does not allow deletes",
1137 RelationGetRelationName(resultRel))));
1138 break;
1139 default:
1140 elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1141 break;
1142 }
1143 break;
1144 default:
1145 ereport(ERROR,
1146 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1147 errmsg("cannot change relation \"%s\"",
1148 RelationGetRelationName(resultRel))));
1149 break;
1150 }
1151}
1152
1153/*
1154 * Check that a proposed rowmark target relation is a legal target
1155 *
1156 * In most cases parser and/or planner should have noticed this already, but
1157 * they don't cover all cases.
1158 */
1159static void
1161{
1162 FdwRoutine *fdwroutine;
1163
1164 switch (rel->rd_rel->relkind)
1165 {
1166 case RELKIND_RELATION:
1167 case RELKIND_PARTITIONED_TABLE:
1168 /* OK */
1169 break;
1170 case RELKIND_SEQUENCE:
1171 /* Must disallow this because we don't vacuum sequences */
1172 ereport(ERROR,
1173 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1174 errmsg("cannot lock rows in sequence \"%s\"",
1176 break;
1177 case RELKIND_TOASTVALUE:
1178 /* We could allow this, but there seems no good reason to */
1179 ereport(ERROR,
1180 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1181 errmsg("cannot lock rows in TOAST relation \"%s\"",
1183 break;
1184 case RELKIND_VIEW:
1185 /* Should not get here; planner should have expanded the view */
1186 ereport(ERROR,
1187 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1188 errmsg("cannot lock rows in view \"%s\"",
1190 break;
1191 case RELKIND_MATVIEW:
1192 /* Allow referencing a matview, but not actual locking clauses */
1193 if (markType != ROW_MARK_REFERENCE)
1194 ereport(ERROR,
1195 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1196 errmsg("cannot lock rows in materialized view \"%s\"",
1198 break;
1199 case RELKIND_FOREIGN_TABLE:
1200 /* Okay only if the FDW supports it */
1201 fdwroutine = GetFdwRoutineForRelation(rel, false);
1202 if (fdwroutine->RefetchForeignRow == NULL)
1203 ereport(ERROR,
1204 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1205 errmsg("cannot lock rows in foreign table \"%s\"",
1207 break;
1208 default:
1209 ereport(ERROR,
1210 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1211 errmsg("cannot lock rows in relation \"%s\"",
1213 break;
1214 }
1215}
1216
1217/*
1218 * Initialize ResultRelInfo data for one result relation
1219 *
1220 * Caution: before Postgres 9.1, this function included the relkind checking
1221 * that's now in CheckValidResultRel, and it also did ExecOpenIndices if
1222 * appropriate. Be sure callers cover those needs.
1223 */
1224void
1226 Relation resultRelationDesc,
1227 Index resultRelationIndex,
1228 ResultRelInfo *partition_root_rri,
1229 int instrument_options)
1230{
1231 MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1232 resultRelInfo->type = T_ResultRelInfo;
1233 resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1234 resultRelInfo->ri_RelationDesc = resultRelationDesc;
1235 resultRelInfo->ri_NumIndices = 0;
1236 resultRelInfo->ri_IndexRelationDescs = NULL;
1237 resultRelInfo->ri_IndexRelationInfo = NULL;
1238 resultRelInfo->ri_needLockTagTuple =
1239 IsInplaceUpdateRelation(resultRelationDesc);
1240 /* make a copy so as not to depend on relcache info not changing... */
1241 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1242 if (resultRelInfo->ri_TrigDesc)
1243 {
1244 int n = resultRelInfo->ri_TrigDesc->numtriggers;
1245
1246 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1247 palloc0(n * sizeof(FmgrInfo));
1248 resultRelInfo->ri_TrigWhenExprs = (ExprState **)
1249 palloc0(n * sizeof(ExprState *));
1250 if (instrument_options)
1251 resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options, false);
1252 }
1253 else
1254 {
1255 resultRelInfo->ri_TrigFunctions = NULL;
1256 resultRelInfo->ri_TrigWhenExprs = NULL;
1257 resultRelInfo->ri_TrigInstrument = NULL;
1258 }
1259 if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1260 resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1261 else
1262 resultRelInfo->ri_FdwRoutine = NULL;
1263
1264 /* The following fields are set later if needed */
1265 resultRelInfo->ri_RowIdAttNo = 0;
1266 resultRelInfo->ri_extraUpdatedCols = NULL;
1267 resultRelInfo->ri_projectNew = NULL;
1268 resultRelInfo->ri_newTupleSlot = NULL;
1269 resultRelInfo->ri_oldTupleSlot = NULL;
1270 resultRelInfo->ri_projectNewInfoValid = false;
1271 resultRelInfo->ri_FdwState = NULL;
1272 resultRelInfo->ri_usesFdwDirectModify = false;
1273 resultRelInfo->ri_CheckConstraintExprs = NULL;
1274 resultRelInfo->ri_GenVirtualNotNullConstraintExprs = NULL;
1275 resultRelInfo->ri_GeneratedExprsI = NULL;
1276 resultRelInfo->ri_GeneratedExprsU = NULL;
1277 resultRelInfo->ri_projectReturning = NULL;
1278 resultRelInfo->ri_onConflictArbiterIndexes = NIL;
1279 resultRelInfo->ri_onConflict = NULL;
1280 resultRelInfo->ri_ReturningSlot = NULL;
1281 resultRelInfo->ri_TrigOldSlot = NULL;
1282 resultRelInfo->ri_TrigNewSlot = NULL;
1283 resultRelInfo->ri_AllNullSlot = NULL;
1284 resultRelInfo->ri_MergeActions[MERGE_WHEN_MATCHED] = NIL;
1287 resultRelInfo->ri_MergeJoinCondition = NULL;
1288
1289 /*
1290 * Only ExecInitPartitionInfo() and ExecInitPartitionDispatchInfo() pass
1291 * non-NULL partition_root_rri. For child relations that are part of the
1292 * initial query rather than being dynamically added by tuple routing,
1293 * this field is filled in ExecInitModifyTable().
1294 */
1295 resultRelInfo->ri_RootResultRelInfo = partition_root_rri;
1296 /* Set by ExecGetRootToChildMap */
1297 resultRelInfo->ri_RootToChildMap = NULL;
1298 resultRelInfo->ri_RootToChildMapValid = false;
1299 /* Set by ExecInitRoutingInfo */
1300 resultRelInfo->ri_PartitionTupleSlot = NULL;
1301 resultRelInfo->ri_ChildToRootMap = NULL;
1302 resultRelInfo->ri_ChildToRootMapValid = false;
1303 resultRelInfo->ri_CopyMultiInsertBuffer = NULL;
1304}
1305
1306/*
1307 * ExecGetTriggerResultRel
1308 * Get a ResultRelInfo for a trigger target relation.
1309 *
1310 * Most of the time, triggers are fired on one of the result relations of the
1311 * query, and so we can just return a member of the es_result_relations array,
1312 * or the es_tuple_routing_result_relations list (if any). (Note: in self-join
1313 * situations there might be multiple members with the same OID; if so it
1314 * doesn't matter which one we pick.)
1315 *
1316 * However, it is sometimes necessary to fire triggers on other relations;
1317 * this happens mainly when an RI update trigger queues additional triggers
1318 * on other relations, which will be processed in the context of the outer
1319 * query. For efficiency's sake, we want to have a ResultRelInfo for those
1320 * triggers too; that can avoid repeated re-opening of the relation. (It
1321 * also provides a way for EXPLAIN ANALYZE to report the runtimes of such
1322 * triggers.) So we make additional ResultRelInfo's as needed, and save them
1323 * in es_trig_target_relations.
1324 */
1327 ResultRelInfo *rootRelInfo)
1328{
1329 ResultRelInfo *rInfo;
1330 ListCell *l;
1331 Relation rel;
1332 MemoryContext oldcontext;
1333
1334 /* Search through the query result relations */
1335 foreach(l, estate->es_opened_result_relations)
1336 {
1337 rInfo = lfirst(l);
1338 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1339 return rInfo;
1340 }
1341
1342 /*
1343 * Search through the result relations that were created during tuple
1344 * routing, if any.
1345 */
1346 foreach(l, estate->es_tuple_routing_result_relations)
1347 {
1348 rInfo = (ResultRelInfo *) lfirst(l);
1349 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1350 return rInfo;
1351 }
1352
1353 /* Nope, but maybe we already made an extra ResultRelInfo for it */
1354 foreach(l, estate->es_trig_target_relations)
1355 {
1356 rInfo = (ResultRelInfo *) lfirst(l);
1357 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1358 return rInfo;
1359 }
1360 /* Nope, so we need a new one */
1361
1362 /*
1363 * Open the target relation's relcache entry. We assume that an
1364 * appropriate lock is still held by the backend from whenever the trigger
1365 * event got queued, so we need take no new lock here. Also, we need not
1366 * recheck the relkind, so no need for CheckValidResultRel.
1367 */
1368 rel = table_open(relid, NoLock);
1369
1370 /*
1371 * Make the new entry in the right context.
1372 */
1373 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1374 rInfo = makeNode(ResultRelInfo);
1375 InitResultRelInfo(rInfo,
1376 rel,
1377 0, /* dummy rangetable index */
1378 rootRelInfo,
1379 estate->es_instrument);
1380 estate->es_trig_target_relations =
1381 lappend(estate->es_trig_target_relations, rInfo);
1382 MemoryContextSwitchTo(oldcontext);
1383
1384 /*
1385 * Currently, we don't need any index information in ResultRelInfos used
1386 * only for triggers, so no need to call ExecOpenIndices.
1387 */
1388
1389 return rInfo;
1390}
1391
1392/*
1393 * Return the ancestor relations of a given leaf partition result relation
1394 * up to and including the query's root target relation.
1395 *
1396 * These work much like the ones opened by ExecGetTriggerResultRel, except
1397 * that we need to keep them in a separate list.
1398 *
1399 * These are closed by ExecCloseResultRelations.
1400 */
1401List *
1403{
1404 ResultRelInfo *rootRelInfo = resultRelInfo->ri_RootResultRelInfo;
1405 Relation partRel = resultRelInfo->ri_RelationDesc;
1406 Oid rootRelOid;
1407
1408 if (!partRel->rd_rel->relispartition)
1409 elog(ERROR, "cannot find ancestors of a non-partition result relation");
1410 Assert(rootRelInfo != NULL);
1411 rootRelOid = RelationGetRelid(rootRelInfo->ri_RelationDesc);
1412 if (resultRelInfo->ri_ancestorResultRels == NIL)
1413 {
1414 ListCell *lc;
1416 List *ancResultRels = NIL;
1417
1418 foreach(lc, oids)
1419 {
1420 Oid ancOid = lfirst_oid(lc);
1421 Relation ancRel;
1422 ResultRelInfo *rInfo;
1423
1424 /*
1425 * Ignore the root ancestor here, and use ri_RootResultRelInfo
1426 * (below) for it instead. Also, we stop climbing up the
1427 * hierarchy when we find the table that was mentioned in the
1428 * query.
1429 */
1430 if (ancOid == rootRelOid)
1431 break;
1432
1433 /*
1434 * All ancestors up to the root target relation must have been
1435 * locked by the planner or AcquireExecutorLocks().
1436 */
1437 ancRel = table_open(ancOid, NoLock);
1438 rInfo = makeNode(ResultRelInfo);
1439
1440 /* dummy rangetable index */
1441 InitResultRelInfo(rInfo, ancRel, 0, NULL,
1442 estate->es_instrument);
1443 ancResultRels = lappend(ancResultRels, rInfo);
1444 }
1445 ancResultRels = lappend(ancResultRels, rootRelInfo);
1446 resultRelInfo->ri_ancestorResultRels = ancResultRels;
1447 }
1448
1449 /* We must have found some ancestor */
1450 Assert(resultRelInfo->ri_ancestorResultRels != NIL);
1451
1452 return resultRelInfo->ri_ancestorResultRels;
1453}
1454
1455/* ----------------------------------------------------------------
1456 * ExecPostprocessPlan
1457 *
1458 * Give plan nodes a final chance to execute before shutdown
1459 * ----------------------------------------------------------------
1460 */
1461static void
1463{
1464 ListCell *lc;
1465
1466 /*
1467 * Make sure nodes run forward.
1468 */
1470
1471 /*
1472 * Run any secondary ModifyTable nodes to completion, in case the main
1473 * query did not fetch all rows from them. (We do this to ensure that
1474 * such nodes have predictable results.)
1475 */
1476 foreach(lc, estate->es_auxmodifytables)
1477 {
1478 PlanState *ps = (PlanState *) lfirst(lc);
1479
1480 for (;;)
1481 {
1482 TupleTableSlot *slot;
1483
1484 /* Reset the per-output-tuple exprcontext each time */
1486
1487 slot = ExecProcNode(ps);
1488
1489 if (TupIsNull(slot))
1490 break;
1491 }
1492 }
1493}
1494
1495/* ----------------------------------------------------------------
1496 * ExecEndPlan
1497 *
1498 * Cleans up the query plan -- closes files and frees up storage
1499 *
1500 * NOTE: we are no longer very worried about freeing storage per se
1501 * in this code; FreeExecutorState should be guaranteed to release all
1502 * memory that needs to be released. What we are worried about doing
1503 * is closing relations and dropping buffer pins. Thus, for example,
1504 * tuple tables must be cleared or dropped to ensure pins are released.
1505 * ----------------------------------------------------------------
1506 */
1507static void
1508ExecEndPlan(PlanState *planstate, EState *estate)
1509{
1510 ListCell *l;
1511
1512 /*
1513 * shut down the node-type-specific query processing
1514 */
1515 ExecEndNode(planstate);
1516
1517 /*
1518 * for subplans too
1519 */
1520 foreach(l, estate->es_subplanstates)
1521 {
1522 PlanState *subplanstate = (PlanState *) lfirst(l);
1523
1524 ExecEndNode(subplanstate);
1525 }
1526
1527 /*
1528 * destroy the executor's tuple table. Actually we only care about
1529 * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1530 * the TupleTableSlots, since the containing memory context is about to go
1531 * away anyway.
1532 */
1533 ExecResetTupleTable(estate->es_tupleTable, false);
1534
1535 /*
1536 * Close any Relations that have been opened for range table entries or
1537 * result relations.
1538 */
1541}
1542
1543/*
1544 * Close any relations that have been opened for ResultRelInfos.
1545 */
1546void
1548{
1549 ListCell *l;
1550
1551 /*
1552 * close indexes of result relation(s) if any. (Rels themselves are
1553 * closed in ExecCloseRangeTableRelations())
1554 *
1555 * In addition, close the stub RTs that may be in each resultrel's
1556 * ri_ancestorResultRels.
1557 */
1558 foreach(l, estate->es_opened_result_relations)
1559 {
1560 ResultRelInfo *resultRelInfo = lfirst(l);
1561 ListCell *lc;
1562
1563 ExecCloseIndices(resultRelInfo);
1564 foreach(lc, resultRelInfo->ri_ancestorResultRels)
1565 {
1566 ResultRelInfo *rInfo = lfirst(lc);
1567
1568 /*
1569 * Ancestors with RTI > 0 (should only be the root ancestor) are
1570 * closed by ExecCloseRangeTableRelations.
1571 */
1572 if (rInfo->ri_RangeTableIndex > 0)
1573 continue;
1574
1576 }
1577 }
1578
1579 /* Close any relations that have been opened by ExecGetTriggerResultRel(). */
1580 foreach(l, estate->es_trig_target_relations)
1581 {
1582 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
1583
1584 /*
1585 * Assert this is a "dummy" ResultRelInfo, see above. Otherwise we
1586 * might be issuing a duplicate close against a Relation opened by
1587 * ExecGetRangeTableRelation.
1588 */
1589 Assert(resultRelInfo->ri_RangeTableIndex == 0);
1590
1591 /*
1592 * Since ExecGetTriggerResultRel doesn't call ExecOpenIndices for
1593 * these rels, we needn't call ExecCloseIndices either.
1594 */
1595 Assert(resultRelInfo->ri_NumIndices == 0);
1596
1597 table_close(resultRelInfo->ri_RelationDesc, NoLock);
1598 }
1599}
1600
1601/*
1602 * Close all relations opened by ExecGetRangeTableRelation().
1603 *
1604 * We do not release any locks we might hold on those rels.
1605 */
1606void
1608{
1609 int i;
1610
1611 for (i = 0; i < estate->es_range_table_size; i++)
1612 {
1613 if (estate->es_relations[i])
1614 table_close(estate->es_relations[i], NoLock);
1615 }
1616}
1617
1618/* ----------------------------------------------------------------
1619 * ExecutePlan
1620 *
1621 * Processes the query plan until we have retrieved 'numberTuples' tuples,
1622 * moving in the specified direction.
1623 *
1624 * Runs to completion if numberTuples is 0
1625 * ----------------------------------------------------------------
1626 */
1627static void
1629 CmdType operation,
1630 bool sendTuples,
1631 uint64 numberTuples,
1632 ScanDirection direction,
1634{
1635 EState *estate = queryDesc->estate;
1636 PlanState *planstate = queryDesc->planstate;
1637 bool use_parallel_mode;
1638 TupleTableSlot *slot;
1639 uint64 current_tuple_count;
1640
1641 /*
1642 * initialize local variables
1643 */
1644 current_tuple_count = 0;
1645
1646 /*
1647 * Set the direction.
1648 */
1649 estate->es_direction = direction;
1650
1651 /*
1652 * Set up parallel mode if appropriate.
1653 *
1654 * Parallel mode only supports complete execution of a plan. If we've
1655 * already partially executed it, or if the caller asks us to exit early,
1656 * we must force the plan to run without parallelism.
1657 */
1658 if (queryDesc->already_executed || numberTuples != 0)
1659 use_parallel_mode = false;
1660 else
1661 use_parallel_mode = queryDesc->plannedstmt->parallelModeNeeded;
1662 queryDesc->already_executed = true;
1663
1664 estate->es_use_parallel_mode = use_parallel_mode;
1665 if (use_parallel_mode)
1667
1668 /*
1669 * Loop until we've processed the proper number of tuples from the plan.
1670 */
1671 for (;;)
1672 {
1673 /* Reset the per-output-tuple exprcontext */
1675
1676 /*
1677 * Execute the plan and obtain a tuple
1678 */
1679 slot = ExecProcNode(planstate);
1680
1681 /*
1682 * if the tuple is null, then we assume there is nothing more to
1683 * process so we just end the loop...
1684 */
1685 if (TupIsNull(slot))
1686 break;
1687
1688 /*
1689 * If we have a junk filter, then project a new tuple with the junk
1690 * removed.
1691 *
1692 * Store this new "clean" tuple in the junkfilter's resultSlot.
1693 * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1694 * because that tuple slot has the wrong descriptor.)
1695 */
1696 if (estate->es_junkFilter != NULL)
1697 slot = ExecFilterJunk(estate->es_junkFilter, slot);
1698
1699 /*
1700 * If we are supposed to send the tuple somewhere, do so. (In
1701 * practice, this is probably always the case at this point.)
1702 */
1703 if (sendTuples)
1704 {
1705 /*
1706 * If we are not able to send the tuple, we assume the destination
1707 * has closed and no more tuples can be sent. If that's the case,
1708 * end the loop.
1709 */
1710 if (!dest->receiveSlot(slot, dest))
1711 break;
1712 }
1713
1714 /*
1715 * Count tuples processed, if this is a SELECT. (For other operation
1716 * types, the ModifyTable plan node must count the appropriate
1717 * events.)
1718 */
1719 if (operation == CMD_SELECT)
1720 (estate->es_processed)++;
1721
1722 /*
1723 * check our tuple count.. if we've processed the proper number then
1724 * quit, else loop again and process more tuples. Zero numberTuples
1725 * means no limit.
1726 */
1727 current_tuple_count++;
1728 if (numberTuples && numberTuples == current_tuple_count)
1729 break;
1730 }
1731
1732 /*
1733 * If we know we won't need to back up, we can release resources at this
1734 * point.
1735 */
1736 if (!(estate->es_top_eflags & EXEC_FLAG_BACKWARD))
1737 ExecShutdownNode(planstate);
1738
1739 if (use_parallel_mode)
1741}
1742
1743
1744/*
1745 * ExecRelCheck --- check that tuple meets check constraints for result relation
1746 *
1747 * Returns NULL if OK, else name of failed check constraint
1748 */
1749static const char *
1751 TupleTableSlot *slot, EState *estate)
1752{
1753 Relation rel = resultRelInfo->ri_RelationDesc;
1754 int ncheck = rel->rd_att->constr->num_check;
1755 ConstrCheck *check = rel->rd_att->constr->check;
1756 ExprContext *econtext;
1757 MemoryContext oldContext;
1758
1759 /*
1760 * CheckNNConstraintFetch let this pass with only a warning, but now we
1761 * should fail rather than possibly failing to enforce an important
1762 * constraint.
1763 */
1764 if (ncheck != rel->rd_rel->relchecks)
1765 elog(ERROR, "%d pg_constraint record(s) missing for relation \"%s\"",
1766 rel->rd_rel->relchecks - ncheck, RelationGetRelationName(rel));
1767
1768 /*
1769 * If first time through for this result relation, build expression
1770 * nodetrees for rel's constraint expressions. Keep them in the per-query
1771 * memory context so they'll survive throughout the query.
1772 */
1773 if (resultRelInfo->ri_CheckConstraintExprs == NULL)
1774 {
1775 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1776 resultRelInfo->ri_CheckConstraintExprs = palloc0_array(ExprState *, ncheck);
1777 for (int i = 0; i < ncheck; i++)
1778 {
1779 Expr *checkconstr;
1780
1781 /* Skip not enforced constraint */
1782 if (!check[i].ccenforced)
1783 continue;
1784
1785 checkconstr = stringToNode(check[i].ccbin);
1786 checkconstr = (Expr *) expand_generated_columns_in_expr((Node *) checkconstr, rel, 1);
1787 resultRelInfo->ri_CheckConstraintExprs[i] =
1788 ExecPrepareExpr(checkconstr, estate);
1789 }
1790 MemoryContextSwitchTo(oldContext);
1791 }
1792
1793 /*
1794 * We will use the EState's per-tuple context for evaluating constraint
1795 * expressions (creating it if it's not already there).
1796 */
1797 econtext = GetPerTupleExprContext(estate);
1798
1799 /* Arrange for econtext's scan tuple to be the tuple under test */
1800 econtext->ecxt_scantuple = slot;
1801
1802 /* And evaluate the constraints */
1803 for (int i = 0; i < ncheck; i++)
1804 {
1805 ExprState *checkconstr = resultRelInfo->ri_CheckConstraintExprs[i];
1806
1807 /*
1808 * NOTE: SQL specifies that a NULL result from a constraint expression
1809 * is not to be treated as a failure. Therefore, use ExecCheck not
1810 * ExecQual.
1811 */
1812 if (checkconstr && !ExecCheck(checkconstr, econtext))
1813 return check[i].ccname;
1814 }
1815
1816 /* NULL result means no error */
1817 return NULL;
1818}
1819
1820/*
1821 * ExecPartitionCheck --- check that tuple meets the partition constraint.
1822 *
1823 * Returns true if it meets the partition constraint. If the constraint
1824 * fails and we're asked to emit an error, do so and don't return; otherwise
1825 * return false.
1826 */
1827bool
1829 EState *estate, bool emitError)
1830{
1831 ExprContext *econtext;
1832 bool success;
1833
1834 /*
1835 * If first time through, build expression state tree for the partition
1836 * check expression. (In the corner case where the partition check
1837 * expression is empty, ie there's a default partition and nothing else,
1838 * we'll be fooled into executing this code each time through. But it's
1839 * pretty darn cheap in that case, so we don't worry about it.)
1840 */
1841 if (resultRelInfo->ri_PartitionCheckExpr == NULL)
1842 {
1843 /*
1844 * Ensure that the qual tree and prepared expression are in the
1845 * query-lifespan context.
1846 */
1848 List *qual = RelationGetPartitionQual(resultRelInfo->ri_RelationDesc);
1849
1850 resultRelInfo->ri_PartitionCheckExpr = ExecPrepareCheck(qual, estate);
1851 MemoryContextSwitchTo(oldcxt);
1852 }
1853
1854 /*
1855 * We will use the EState's per-tuple context for evaluating constraint
1856 * expressions (creating it if it's not already there).
1857 */
1858 econtext = GetPerTupleExprContext(estate);
1859
1860 /* Arrange for econtext's scan tuple to be the tuple under test */
1861 econtext->ecxt_scantuple = slot;
1862
1863 /*
1864 * As in case of the cataloged constraints, we treat a NULL result as
1865 * success here, not a failure.
1866 */
1867 success = ExecCheck(resultRelInfo->ri_PartitionCheckExpr, econtext);
1868
1869 /* if asked to emit error, don't actually return on failure */
1870 if (!success && emitError)
1871 ExecPartitionCheckEmitError(resultRelInfo, slot, estate);
1872
1873 return success;
1874}
1875
1876/*
1877 * ExecPartitionCheckEmitError - Form and emit an error message after a failed
1878 * partition constraint check.
1879 */
1880void
1882 TupleTableSlot *slot,
1883 EState *estate)
1884{
1885 Oid root_relid;
1886 TupleDesc tupdesc;
1887 char *val_desc;
1888 Bitmapset *modifiedCols;
1889
1890 /*
1891 * If the tuple has been routed, it's been converted to the partition's
1892 * rowtype, which might differ from the root table's. We must convert it
1893 * back to the root table's rowtype so that val_desc in the error message
1894 * matches the input tuple.
1895 */
1896 if (resultRelInfo->ri_RootResultRelInfo)
1897 {
1898 ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
1899 TupleDesc old_tupdesc;
1900 AttrMap *map;
1901
1902 root_relid = RelationGetRelid(rootrel->ri_RelationDesc);
1903 tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
1904
1905 old_tupdesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
1906 /* a reverse map */
1907 map = build_attrmap_by_name_if_req(old_tupdesc, tupdesc, false);
1908
1909 /*
1910 * Partition-specific slot's tupdesc can't be changed, so allocate a
1911 * new one.
1912 */
1913 if (map != NULL)
1914 slot = execute_attr_map_slot(map, slot,
1916 modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
1917 ExecGetUpdatedCols(rootrel, estate));
1918 }
1919 else
1920 {
1921 root_relid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
1922 tupdesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
1923 modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
1924 ExecGetUpdatedCols(resultRelInfo, estate));
1925 }
1926
1927 val_desc = ExecBuildSlotValueDescription(root_relid,
1928 slot,
1929 tupdesc,
1930 modifiedCols,
1931 64);
1932 ereport(ERROR,
1933 (errcode(ERRCODE_CHECK_VIOLATION),
1934 errmsg("new row for relation \"%s\" violates partition constraint",
1936 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1937 errtable(resultRelInfo->ri_RelationDesc)));
1938}
1939
1940/*
1941 * ExecConstraints - check constraints of the tuple in 'slot'
1942 *
1943 * This checks the traditional NOT NULL and check constraints.
1944 *
1945 * The partition constraint is *NOT* checked.
1946 *
1947 * Note: 'slot' contains the tuple to check the constraints of, which may
1948 * have been converted from the original input tuple after tuple routing.
1949 * 'resultRelInfo' is the final result relation, after tuple routing.
1950 */
1951void
1953 TupleTableSlot *slot, EState *estate)
1954{
1955 Relation rel = resultRelInfo->ri_RelationDesc;
1956 TupleDesc tupdesc = RelationGetDescr(rel);
1957 TupleConstr *constr = tupdesc->constr;
1958 Bitmapset *modifiedCols;
1959 List *notnull_virtual_attrs = NIL;
1960
1961 Assert(constr); /* we should not be called otherwise */
1962
1963 /*
1964 * Verify not-null constraints.
1965 *
1966 * Not-null constraints on virtual generated columns are collected and
1967 * checked separately below.
1968 */
1969 if (constr->has_not_null)
1970 {
1971 for (AttrNumber attnum = 1; attnum <= tupdesc->natts; attnum++)
1972 {
1973 Form_pg_attribute att = TupleDescAttr(tupdesc, attnum - 1);
1974
1975 if (att->attnotnull && att->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
1976 notnull_virtual_attrs = lappend_int(notnull_virtual_attrs, attnum);
1977 else if (att->attnotnull && slot_attisnull(slot, attnum))
1978 ReportNotNullViolationError(resultRelInfo, slot, estate, attnum);
1979 }
1980 }
1981
1982 /*
1983 * Verify not-null constraints on virtual generated column, if any.
1984 */
1985 if (notnull_virtual_attrs)
1986 {
1988
1989 attnum = ExecRelGenVirtualNotNull(resultRelInfo, slot, estate,
1990 notnull_virtual_attrs);
1992 ReportNotNullViolationError(resultRelInfo, slot, estate, attnum);
1993 }
1994
1995 /*
1996 * Verify check constraints.
1997 */
1998 if (rel->rd_rel->relchecks > 0)
1999 {
2000 const char *failed;
2001
2002 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
2003 {
2004 char *val_desc;
2005 Relation orig_rel = rel;
2006
2007 /*
2008 * If the tuple has been routed, it's been converted to the
2009 * partition's rowtype, which might differ from the root table's.
2010 * We must convert it back to the root table's rowtype so that
2011 * val_desc shown error message matches the input tuple.
2012 */
2013 if (resultRelInfo->ri_RootResultRelInfo)
2014 {
2015 ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
2016 TupleDesc old_tupdesc = RelationGetDescr(rel);
2017 AttrMap *map;
2018
2019 tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
2020 /* a reverse map */
2021 map = build_attrmap_by_name_if_req(old_tupdesc,
2022 tupdesc,
2023 false);
2024
2025 /*
2026 * Partition-specific slot's tupdesc can't be changed, so
2027 * allocate a new one.
2028 */
2029 if (map != NULL)
2030 slot = execute_attr_map_slot(map, slot,
2032 modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
2033 ExecGetUpdatedCols(rootrel, estate));
2034 rel = rootrel->ri_RelationDesc;
2035 }
2036 else
2037 modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
2038 ExecGetUpdatedCols(resultRelInfo, estate));
2040 slot,
2041 tupdesc,
2042 modifiedCols,
2043 64);
2044 ereport(ERROR,
2045 (errcode(ERRCODE_CHECK_VIOLATION),
2046 errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
2047 RelationGetRelationName(orig_rel), failed),
2048 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2049 errtableconstraint(orig_rel, failed)));
2050 }
2051 }
2052}
2053
2054/*
2055 * Verify not-null constraints on virtual generated columns of the given
2056 * tuple slot.
2057 *
2058 * Return value of InvalidAttrNumber means all not-null constraints on virtual
2059 * generated columns are satisfied. A return value > 0 means a not-null
2060 * violation happened for that attribute.
2061 *
2062 * notnull_virtual_attrs is the list of the attnums of virtual generated column with
2063 * not-null constraints.
2064 */
2067 EState *estate, List *notnull_virtual_attrs)
2068{
2069 Relation rel = resultRelInfo->ri_RelationDesc;
2070 ExprContext *econtext;
2071 MemoryContext oldContext;
2072
2073 /*
2074 * We implement this by building a NullTest node for each virtual
2075 * generated column, which we cache in resultRelInfo, and running those
2076 * through ExecCheck().
2077 */
2078 if (resultRelInfo->ri_GenVirtualNotNullConstraintExprs == NULL)
2079 {
2080 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
2082 palloc0_array(ExprState *, list_length(notnull_virtual_attrs));
2083
2084 foreach_int(attnum, notnull_virtual_attrs)
2085 {
2087 NullTest *nnulltest;
2088
2089 /* "generated_expression IS NOT NULL" check. */
2090 nnulltest = makeNode(NullTest);
2091 nnulltest->arg = (Expr *) build_generation_expression(rel, attnum);
2092 nnulltest->nulltesttype = IS_NOT_NULL;
2093 nnulltest->argisrow = false;
2094 nnulltest->location = -1;
2095
2096 resultRelInfo->ri_GenVirtualNotNullConstraintExprs[i] =
2097 ExecPrepareExpr((Expr *) nnulltest, estate);
2098 }
2099 MemoryContextSwitchTo(oldContext);
2100 }
2101
2102 /*
2103 * We will use the EState's per-tuple context for evaluating virtual
2104 * generated column not null constraint expressions (creating it if it's
2105 * not already there).
2106 */
2107 econtext = GetPerTupleExprContext(estate);
2108
2109 /* Arrange for econtext's scan tuple to be the tuple under test */
2110 econtext->ecxt_scantuple = slot;
2111
2112 /* And evaluate the check constraints for virtual generated column */
2113 foreach_int(attnum, notnull_virtual_attrs)
2114 {
2116 ExprState *exprstate = resultRelInfo->ri_GenVirtualNotNullConstraintExprs[i];
2117
2118 Assert(exprstate != NULL);
2119 if (!ExecCheck(exprstate, econtext))
2120 return attnum;
2121 }
2122
2123 /* InvalidAttrNumber result means no error */
2124 return InvalidAttrNumber;
2125}
2126
2127/*
2128 * Report a violation of a not-null constraint that was already detected.
2129 */
2130static void
2132 EState *estate, int attnum)
2133{
2134 Bitmapset *modifiedCols;
2135 char *val_desc;
2136 Relation rel = resultRelInfo->ri_RelationDesc;
2137 Relation orig_rel = rel;
2138 TupleDesc tupdesc = RelationGetDescr(rel);
2139 TupleDesc orig_tupdesc = RelationGetDescr(rel);
2140 Form_pg_attribute att = TupleDescAttr(tupdesc, attnum - 1);
2141
2142 Assert(attnum > 0);
2143
2144 /*
2145 * If the tuple has been routed, it's been converted to the partition's
2146 * rowtype, which might differ from the root table's. We must convert it
2147 * back to the root table's rowtype so that val_desc shown error message
2148 * matches the input tuple.
2149 */
2150 if (resultRelInfo->ri_RootResultRelInfo)
2151 {
2152 ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
2153 AttrMap *map;
2154
2155 tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
2156 /* a reverse map */
2157 map = build_attrmap_by_name_if_req(orig_tupdesc,
2158 tupdesc,
2159 false);
2160
2161 /*
2162 * Partition-specific slot's tupdesc can't be changed, so allocate a
2163 * new one.
2164 */
2165 if (map != NULL)
2166 slot = execute_attr_map_slot(map, slot,
2168 modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
2169 ExecGetUpdatedCols(rootrel, estate));
2170 rel = rootrel->ri_RelationDesc;
2171 }
2172 else
2173 modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
2174 ExecGetUpdatedCols(resultRelInfo, estate));
2175
2177 slot,
2178 tupdesc,
2179 modifiedCols,
2180 64);
2181 ereport(ERROR,
2182 errcode(ERRCODE_NOT_NULL_VIOLATION),
2183 errmsg("null value in column \"%s\" of relation \"%s\" violates not-null constraint",
2184 NameStr(att->attname),
2185 RelationGetRelationName(orig_rel)),
2186 val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2187 errtablecol(orig_rel, attnum));
2188}
2189
2190/*
2191 * ExecWithCheckOptions -- check that tuple satisfies any WITH CHECK OPTIONs
2192 * of the specified kind.
2193 *
2194 * Note that this needs to be called multiple times to ensure that all kinds of
2195 * WITH CHECK OPTIONs are handled (both those from views which have the WITH
2196 * CHECK OPTION set and from row-level security policies). See ExecInsert()
2197 * and ExecUpdate().
2198 */
2199void
2201 TupleTableSlot *slot, EState *estate)
2202{
2203 Relation rel = resultRelInfo->ri_RelationDesc;
2204 TupleDesc tupdesc = RelationGetDescr(rel);
2205 ExprContext *econtext;
2206 ListCell *l1,
2207 *l2;
2208
2209 /*
2210 * We will use the EState's per-tuple context for evaluating constraint
2211 * expressions (creating it if it's not already there).
2212 */
2213 econtext = GetPerTupleExprContext(estate);
2214
2215 /* Arrange for econtext's scan tuple to be the tuple under test */
2216 econtext->ecxt_scantuple = slot;
2217
2218 /* Check each of the constraints */
2219 forboth(l1, resultRelInfo->ri_WithCheckOptions,
2220 l2, resultRelInfo->ri_WithCheckOptionExprs)
2221 {
2222 WithCheckOption *wco = (WithCheckOption *) lfirst(l1);
2223 ExprState *wcoExpr = (ExprState *) lfirst(l2);
2224
2225 /*
2226 * Skip any WCOs which are not the kind we are looking for at this
2227 * time.
2228 */
2229 if (wco->kind != kind)
2230 continue;
2231
2232 /*
2233 * WITH CHECK OPTION checks are intended to ensure that the new tuple
2234 * is visible (in the case of a view) or that it passes the
2235 * 'with-check' policy (in the case of row security). If the qual
2236 * evaluates to NULL or FALSE, then the new tuple won't be included in
2237 * the view or doesn't pass the 'with-check' policy for the table.
2238 */
2239 if (!ExecQual(wcoExpr, econtext))
2240 {
2241 char *val_desc;
2242 Bitmapset *modifiedCols;
2243
2244 switch (wco->kind)
2245 {
2246 /*
2247 * For WITH CHECK OPTIONs coming from views, we might be
2248 * able to provide the details on the row, depending on
2249 * the permissions on the relation (that is, if the user
2250 * could view it directly anyway). For RLS violations, we
2251 * don't include the data since we don't know if the user
2252 * should be able to view the tuple as that depends on the
2253 * USING policy.
2254 */
2255 case WCO_VIEW_CHECK:
2256 /* See the comment in ExecConstraints(). */
2257 if (resultRelInfo->ri_RootResultRelInfo)
2258 {
2259 ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
2260 TupleDesc old_tupdesc = RelationGetDescr(rel);
2261 AttrMap *map;
2262
2263 tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
2264 /* a reverse map */
2265 map = build_attrmap_by_name_if_req(old_tupdesc,
2266 tupdesc,
2267 false);
2268
2269 /*
2270 * Partition-specific slot's tupdesc can't be changed,
2271 * so allocate a new one.
2272 */
2273 if (map != NULL)
2274 slot = execute_attr_map_slot(map, slot,
2276
2277 modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
2278 ExecGetUpdatedCols(rootrel, estate));
2279 rel = rootrel->ri_RelationDesc;
2280 }
2281 else
2282 modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
2283 ExecGetUpdatedCols(resultRelInfo, estate));
2285 slot,
2286 tupdesc,
2287 modifiedCols,
2288 64);
2289
2290 ereport(ERROR,
2291 (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),
2292 errmsg("new row violates check option for view \"%s\"",
2293 wco->relname),
2294 val_desc ? errdetail("Failing row contains %s.",
2295 val_desc) : 0));
2296 break;
2299 if (wco->polname != NULL)
2300 ereport(ERROR,
2301 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2302 errmsg("new row violates row-level security policy \"%s\" for table \"%s\"",
2303 wco->polname, wco->relname)));
2304 else
2305 ereport(ERROR,
2306 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2307 errmsg("new row violates row-level security policy for table \"%s\"",
2308 wco->relname)));
2309 break;
2312 if (wco->polname != NULL)
2313 ereport(ERROR,
2314 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2315 errmsg("target row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2316 wco->polname, wco->relname)));
2317 else
2318 ereport(ERROR,
2319 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2320 errmsg("target row violates row-level security policy (USING expression) for table \"%s\"",
2321 wco->relname)));
2322 break;
2324 if (wco->polname != NULL)
2325 ereport(ERROR,
2326 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2327 errmsg("new row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2328 wco->polname, wco->relname)));
2329 else
2330 ereport(ERROR,
2331 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2332 errmsg("new row violates row-level security policy (USING expression) for table \"%s\"",
2333 wco->relname)));
2334 break;
2335 default:
2336 elog(ERROR, "unrecognized WCO kind: %u", wco->kind);
2337 break;
2338 }
2339 }
2340 }
2341}
2342
2343/*
2344 * ExecBuildSlotValueDescription -- construct a string representing a tuple
2345 *
2346 * This is intentionally very similar to BuildIndexValueDescription, but
2347 * unlike that function, we truncate long field values (to at most maxfieldlen
2348 * bytes). That seems necessary here since heap field values could be very
2349 * long, whereas index entries typically aren't so wide.
2350 *
2351 * Also, unlike the case with index entries, we need to be prepared to ignore
2352 * dropped columns. We used to use the slot's tuple descriptor to decode the
2353 * data, but the slot's descriptor doesn't identify dropped columns, so we
2354 * now need to be passed the relation's descriptor.
2355 *
2356 * Note that, like BuildIndexValueDescription, if the user does not have
2357 * permission to view any of the columns involved, a NULL is returned. Unlike
2358 * BuildIndexValueDescription, if the user has access to view a subset of the
2359 * column involved, that subset will be returned with a key identifying which
2360 * columns they are.
2361 */
2362char *
2364 TupleTableSlot *slot,
2365 TupleDesc tupdesc,
2366 Bitmapset *modifiedCols,
2367 int maxfieldlen)
2368{
2370 StringInfoData collist;
2371 bool write_comma = false;
2372 bool write_comma_collist = false;
2373 int i;
2374 AclResult aclresult;
2375 bool table_perm = false;
2376 bool any_perm = false;
2377
2378 /*
2379 * Check if RLS is enabled and should be active for the relation; if so,
2380 * then don't return anything. Otherwise, go through normal permission
2381 * checks.
2382 */
2383 if (check_enable_rls(reloid, InvalidOid, true) == RLS_ENABLED)
2384 return NULL;
2385
2387
2389
2390 /*
2391 * Check if the user has permissions to see the row. Table-level SELECT
2392 * allows access to all columns. If the user does not have table-level
2393 * SELECT then we check each column and include those the user has SELECT
2394 * rights on. Additionally, we always include columns the user provided
2395 * data for.
2396 */
2397 aclresult = pg_class_aclcheck(reloid, GetUserId(), ACL_SELECT);
2398 if (aclresult != ACLCHECK_OK)
2399 {
2400 /* Set up the buffer for the column list */
2401 initStringInfo(&collist);
2402 appendStringInfoChar(&collist, '(');
2403 }
2404 else
2405 table_perm = any_perm = true;
2406
2407 /* Make sure the tuple is fully deconstructed */
2408 slot_getallattrs(slot);
2409
2410 for (i = 0; i < tupdesc->natts; i++)
2411 {
2412 bool column_perm = false;
2413 char *val;
2414 int vallen;
2415 Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2416
2417 /* ignore dropped columns */
2418 if (att->attisdropped)
2419 continue;
2420
2421 if (!table_perm)
2422 {
2423 /*
2424 * No table-level SELECT, so need to make sure they either have
2425 * SELECT rights on the column or that they have provided the data
2426 * for the column. If not, omit this column from the error
2427 * message.
2428 */
2429 aclresult = pg_attribute_aclcheck(reloid, att->attnum,
2432 modifiedCols) || aclresult == ACLCHECK_OK)
2433 {
2434 column_perm = any_perm = true;
2435
2436 if (write_comma_collist)
2437 appendStringInfoString(&collist, ", ");
2438 else
2439 write_comma_collist = true;
2440
2441 appendStringInfoString(&collist, NameStr(att->attname));
2442 }
2443 }
2444
2445 if (table_perm || column_perm)
2446 {
2447 if (att->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
2448 val = "virtual";
2449 else if (slot->tts_isnull[i])
2450 val = "null";
2451 else
2452 {
2453 Oid foutoid;
2454 bool typisvarlena;
2455
2456 getTypeOutputInfo(att->atttypid,
2457 &foutoid, &typisvarlena);
2458 val = OidOutputFunctionCall(foutoid, slot->tts_values[i]);
2459 }
2460
2461 if (write_comma)
2463 else
2464 write_comma = true;
2465
2466 /* truncate if needed */
2467 vallen = strlen(val);
2468 if (vallen <= maxfieldlen)
2469 appendBinaryStringInfo(&buf, val, vallen);
2470 else
2471 {
2472 vallen = pg_mbcliplen(val, vallen, maxfieldlen);
2473 appendBinaryStringInfo(&buf, val, vallen);
2474 appendStringInfoString(&buf, "...");
2475 }
2476 }
2477 }
2478
2479 /* If we end up with zero columns being returned, then return NULL. */
2480 if (!any_perm)
2481 return NULL;
2482
2484
2485 if (!table_perm)
2486 {
2487 appendStringInfoString(&collist, ") = ");
2488 appendBinaryStringInfo(&collist, buf.data, buf.len);
2489
2490 return collist.data;
2491 }
2492
2493 return buf.data;
2494}
2495
2496
2497/*
2498 * ExecUpdateLockMode -- find the appropriate UPDATE tuple lock mode for a
2499 * given ResultRelInfo
2500 */
2503{
2504 Bitmapset *keyCols;
2505 Bitmapset *updatedCols;
2506
2507 /*
2508 * Compute lock mode to use. If columns that are part of the key have not
2509 * been modified, then we can use a weaker lock, allowing for better
2510 * concurrency.
2511 */
2512 updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
2515
2516 if (bms_overlap(keyCols, updatedCols))
2517 return LockTupleExclusive;
2518
2520}
2521
2522/*
2523 * ExecFindRowMark -- find the ExecRowMark struct for given rangetable index
2524 *
2525 * If no such struct, either return NULL or throw error depending on missing_ok
2526 */
2528ExecFindRowMark(EState *estate, Index rti, bool missing_ok)
2529{
2530 if (rti > 0 && rti <= estate->es_range_table_size &&
2531 estate->es_rowmarks != NULL)
2532 {
2533 ExecRowMark *erm = estate->es_rowmarks[rti - 1];
2534
2535 if (erm)
2536 return erm;
2537 }
2538 if (!missing_ok)
2539 elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2540 return NULL;
2541}
2542
2543/*
2544 * ExecBuildAuxRowMark -- create an ExecAuxRowMark struct
2545 *
2546 * Inputs are the underlying ExecRowMark struct and the targetlist of the
2547 * input plan node (not planstate node!). We need the latter to find out
2548 * the column numbers of the resjunk columns.
2549 */
2552{
2554 char resname[32];
2555
2556 aerm->rowmark = erm;
2557
2558 /* Look up the resjunk columns associated with this rowmark */
2559 if (erm->markType != ROW_MARK_COPY)
2560 {
2561 /* need ctid for all methods other than COPY */
2562 snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
2563 aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2564 resname);
2566 elog(ERROR, "could not find junk %s column", resname);
2567 }
2568 else
2569 {
2570 /* need wholerow if COPY */
2571 snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
2572 aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
2573 resname);
2575 elog(ERROR, "could not find junk %s column", resname);
2576 }
2577
2578 /* if child rel, need tableoid */
2579 if (erm->rti != erm->prti)
2580 {
2581 snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
2582 aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2583 resname);
2585 elog(ERROR, "could not find junk %s column", resname);
2586 }
2587
2588 return aerm;
2589}
2590
2591
2592/*
2593 * EvalPlanQual logic --- recheck modified tuple(s) to see if we want to
2594 * process the updated version under READ COMMITTED rules.
2595 *
2596 * See backend/executor/README for some info about how this works.
2597 */
2598
2599
2600/*
2601 * Check the updated version of a tuple to see if we want to process it under
2602 * READ COMMITTED rules.
2603 *
2604 * epqstate - state for EvalPlanQual rechecking
2605 * relation - table containing tuple
2606 * rti - rangetable index of table containing tuple
2607 * inputslot - tuple for processing - this can be the slot from
2608 * EvalPlanQualSlot() for this rel, for increased efficiency.
2609 *
2610 * This tests whether the tuple in inputslot still matches the relevant
2611 * quals. For that result to be useful, typically the input tuple has to be
2612 * last row version (otherwise the result isn't particularly useful) and
2613 * locked (otherwise the result might be out of date). That's typically
2614 * achieved by using table_tuple_lock() with the
2615 * TUPLE_LOCK_FLAG_FIND_LAST_VERSION flag.
2616 *
2617 * Returns a slot containing the new candidate update/delete tuple, or
2618 * NULL if we determine we shouldn't process the row.
2619 */
2621EvalPlanQual(EPQState *epqstate, Relation relation,
2622 Index rti, TupleTableSlot *inputslot)
2623{
2624 TupleTableSlot *slot;
2625 TupleTableSlot *testslot;
2626
2627 Assert(rti > 0);
2628
2629 /*
2630 * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
2631 */
2632 EvalPlanQualBegin(epqstate);
2633
2634 /*
2635 * Callers will often use the EvalPlanQualSlot to store the tuple to avoid
2636 * an unnecessary copy.
2637 */
2638 testslot = EvalPlanQualSlot(epqstate, relation, rti);
2639 if (testslot != inputslot)
2640 ExecCopySlot(testslot, inputslot);
2641
2642 /*
2643 * Mark that an EPQ tuple is available for this relation. (If there is
2644 * more than one result relation, the others remain marked as having no
2645 * tuple available.)
2646 */
2647 epqstate->relsubs_done[rti - 1] = false;
2648 epqstate->relsubs_blocked[rti - 1] = false;
2649
2650 /*
2651 * Run the EPQ query. We assume it will return at most one tuple.
2652 */
2653 slot = EvalPlanQualNext(epqstate);
2654
2655 /*
2656 * If we got a tuple, force the slot to materialize the tuple so that it
2657 * is not dependent on any local state in the EPQ query (in particular,
2658 * it's highly likely that the slot contains references to any pass-by-ref
2659 * datums that may be present in copyTuple). As with the next step, this
2660 * is to guard against early re-use of the EPQ query.
2661 */
2662 if (!TupIsNull(slot))
2663 ExecMaterializeSlot(slot);
2664
2665 /*
2666 * Clear out the test tuple, and mark that no tuple is available here.
2667 * This is needed in case the EPQ state is re-used to test a tuple for a
2668 * different target relation.
2669 */
2670 ExecClearTuple(testslot);
2671 epqstate->relsubs_blocked[rti - 1] = true;
2672
2673 return slot;
2674}
2675
2676/*
2677 * EvalPlanQualInit -- initialize during creation of a plan state node
2678 * that might need to invoke EPQ processing.
2679 *
2680 * If the caller intends to use EvalPlanQual(), resultRelations should be
2681 * a list of RT indexes of potential target relations for EvalPlanQual(),
2682 * and we will arrange that the other listed relations don't return any
2683 * tuple during an EvalPlanQual() call. Otherwise resultRelations
2684 * should be NIL.
2685 *
2686 * Note: subplan/auxrowmarks can be NULL/NIL if they will be set later
2687 * with EvalPlanQualSetPlan.
2688 */
2689void
2690EvalPlanQualInit(EPQState *epqstate, EState *parentestate,
2691 Plan *subplan, List *auxrowmarks,
2692 int epqParam, List *resultRelations)
2693{
2694 Index rtsize = parentestate->es_range_table_size;
2695
2696 /* initialize data not changing over EPQState's lifetime */
2697 epqstate->parentestate = parentestate;
2698 epqstate->epqParam = epqParam;
2699 epqstate->resultRelations = resultRelations;
2700
2701 /*
2702 * Allocate space to reference a slot for each potential rti - do so now
2703 * rather than in EvalPlanQualBegin(), as done for other dynamically
2704 * allocated resources, so EvalPlanQualSlot() can be used to hold tuples
2705 * that *may* need EPQ later, without forcing the overhead of
2706 * EvalPlanQualBegin().
2707 */
2708 epqstate->tuple_table = NIL;
2709 epqstate->relsubs_slot = (TupleTableSlot **)
2710 palloc0(rtsize * sizeof(TupleTableSlot *));
2711
2712 /* ... and remember data that EvalPlanQualBegin will need */
2713 epqstate->plan = subplan;
2714 epqstate->arowMarks = auxrowmarks;
2715
2716 /* ... and mark the EPQ state inactive */
2717 epqstate->origslot = NULL;
2718 epqstate->recheckestate = NULL;
2719 epqstate->recheckplanstate = NULL;
2720 epqstate->relsubs_rowmark = NULL;
2721 epqstate->relsubs_done = NULL;
2722 epqstate->relsubs_blocked = NULL;
2723}
2724
2725/*
2726 * EvalPlanQualSetPlan -- set or change subplan of an EPQState.
2727 *
2728 * We used to need this so that ModifyTable could deal with multiple subplans.
2729 * It could now be refactored out of existence.
2730 */
2731void
2732EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan, List *auxrowmarks)
2733{
2734 /* If we have a live EPQ query, shut it down */
2735 EvalPlanQualEnd(epqstate);
2736 /* And set/change the plan pointer */
2737 epqstate->plan = subplan;
2738 /* The rowmarks depend on the plan, too */
2739 epqstate->arowMarks = auxrowmarks;
2740}
2741
2742/*
2743 * Return, and create if necessary, a slot for an EPQ test tuple.
2744 *
2745 * Note this only requires EvalPlanQualInit() to have been called,
2746 * EvalPlanQualBegin() is not necessary.
2747 */
2750 Relation relation, Index rti)
2751{
2752 TupleTableSlot **slot;
2753
2754 Assert(relation);
2755 Assert(rti > 0 && rti <= epqstate->parentestate->es_range_table_size);
2756 slot = &epqstate->relsubs_slot[rti - 1];
2757
2758 if (*slot == NULL)
2759 {
2760 MemoryContext oldcontext;
2761
2762 oldcontext = MemoryContextSwitchTo(epqstate->parentestate->es_query_cxt);
2763 *slot = table_slot_create(relation, &epqstate->tuple_table);
2764 MemoryContextSwitchTo(oldcontext);
2765 }
2766
2767 return *slot;
2768}
2769
2770/*
2771 * Fetch the current row value for a non-locked relation, identified by rti,
2772 * that needs to be scanned by an EvalPlanQual operation. origslot must have
2773 * been set to contain the current result row (top-level row) that we need to
2774 * recheck. Returns true if a substitution tuple was found, false if not.
2775 */
2776bool
2778{
2779 ExecAuxRowMark *earm = epqstate->relsubs_rowmark[rti - 1];
2780 ExecRowMark *erm;
2781 Datum datum;
2782 bool isNull;
2783
2784 Assert(earm != NULL);
2785 Assert(epqstate->origslot != NULL);
2786
2787 erm = earm->rowmark;
2788
2790 elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2791
2792 /* if child rel, must check whether it produced this row */
2793 if (erm->rti != erm->prti)
2794 {
2795 Oid tableoid;
2796
2797 datum = ExecGetJunkAttribute(epqstate->origslot,
2798 earm->toidAttNo,
2799 &isNull);
2800 /* non-locked rels could be on the inside of outer joins */
2801 if (isNull)
2802 return false;
2803
2804 tableoid = DatumGetObjectId(datum);
2805
2806 Assert(OidIsValid(erm->relid));
2807 if (tableoid != erm->relid)
2808 {
2809 /* this child is inactive right now */
2810 return false;
2811 }
2812 }
2813
2814 if (erm->markType == ROW_MARK_REFERENCE)
2815 {
2816 Assert(erm->relation != NULL);
2817
2818 /* fetch the tuple's ctid */
2819 datum = ExecGetJunkAttribute(epqstate->origslot,
2820 earm->ctidAttNo,
2821 &isNull);
2822 /* non-locked rels could be on the inside of outer joins */
2823 if (isNull)
2824 return false;
2825
2826 /* fetch requests on foreign tables must be passed to their FDW */
2827 if (erm->relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2828 {
2829 FdwRoutine *fdwroutine;
2830 bool updated = false;
2831
2832 fdwroutine = GetFdwRoutineForRelation(erm->relation, false);
2833 /* this should have been checked already, but let's be safe */
2834 if (fdwroutine->RefetchForeignRow == NULL)
2835 ereport(ERROR,
2836 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2837 errmsg("cannot lock rows in foreign table \"%s\"",
2839
2840 fdwroutine->RefetchForeignRow(epqstate->recheckestate,
2841 erm,
2842 datum,
2843 slot,
2844 &updated);
2845 if (TupIsNull(slot))
2846 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2847
2848 /*
2849 * Ideally we'd insist on updated == false here, but that assumes
2850 * that FDWs can track that exactly, which they might not be able
2851 * to. So just ignore the flag.
2852 */
2853 return true;
2854 }
2855 else
2856 {
2857 /* ordinary table, fetch the tuple */
2860 SnapshotAny, slot))
2861 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2862 return true;
2863 }
2864 }
2865 else
2866 {
2867 Assert(erm->markType == ROW_MARK_COPY);
2868
2869 /* fetch the whole-row Var for the relation */
2870 datum = ExecGetJunkAttribute(epqstate->origslot,
2871 earm->wholeAttNo,
2872 &isNull);
2873 /* non-locked rels could be on the inside of outer joins */
2874 if (isNull)
2875 return false;
2876
2877 ExecStoreHeapTupleDatum(datum, slot);
2878 return true;
2879 }
2880}
2881
2882/*
2883 * Fetch the next row (if any) from EvalPlanQual testing
2884 *
2885 * (In practice, there should never be more than one row...)
2886 */
2889{
2890 MemoryContext oldcontext;
2891 TupleTableSlot *slot;
2892
2893 oldcontext = MemoryContextSwitchTo(epqstate->recheckestate->es_query_cxt);
2894 slot = ExecProcNode(epqstate->recheckplanstate);
2895 MemoryContextSwitchTo(oldcontext);
2896
2897 return slot;
2898}
2899
2900/*
2901 * Initialize or reset an EvalPlanQual state tree
2902 */
2903void
2905{
2906 EState *parentestate = epqstate->parentestate;
2907 EState *recheckestate = epqstate->recheckestate;
2908
2909 if (recheckestate == NULL)
2910 {
2911 /* First time through, so create a child EState */
2912 EvalPlanQualStart(epqstate, epqstate->plan);
2913 }
2914 else
2915 {
2916 /*
2917 * We already have a suitable child EPQ tree, so just reset it.
2918 */
2919 Index rtsize = parentestate->es_range_table_size;
2920 PlanState *rcplanstate = epqstate->recheckplanstate;
2921
2922 /*
2923 * Reset the relsubs_done[] flags to equal relsubs_blocked[], so that
2924 * the EPQ run will never attempt to fetch tuples from blocked target
2925 * relations.
2926 */
2927 memcpy(epqstate->relsubs_done, epqstate->relsubs_blocked,
2928 rtsize * sizeof(bool));
2929
2930 /* Recopy current values of parent parameters */
2931 if (parentestate->es_plannedstmt->paramExecTypes != NIL)
2932 {
2933 int i;
2934
2935 /*
2936 * Force evaluation of any InitPlan outputs that could be needed
2937 * by the subplan, just in case they got reset since
2938 * EvalPlanQualStart (see comments therein).
2939 */
2940 ExecSetParamPlanMulti(rcplanstate->plan->extParam,
2941 GetPerTupleExprContext(parentestate));
2942
2943 i = list_length(parentestate->es_plannedstmt->paramExecTypes);
2944
2945 while (--i >= 0)
2946 {
2947 /* copy value if any, but not execPlan link */
2948 recheckestate->es_param_exec_vals[i].value =
2949 parentestate->es_param_exec_vals[i].value;
2950 recheckestate->es_param_exec_vals[i].isnull =
2951 parentestate->es_param_exec_vals[i].isnull;
2952 }
2953 }
2954
2955 /*
2956 * Mark child plan tree as needing rescan at all scan nodes. The
2957 * first ExecProcNode will take care of actually doing the rescan.
2958 */
2959 rcplanstate->chgParam = bms_add_member(rcplanstate->chgParam,
2960 epqstate->epqParam);
2961 }
2962}
2963
2964/*
2965 * Start execution of an EvalPlanQual plan tree.
2966 *
2967 * This is a cut-down version of ExecutorStart(): we copy some state from
2968 * the top-level estate rather than initializing it fresh.
2969 */
2970static void
2971EvalPlanQualStart(EPQState *epqstate, Plan *planTree)
2972{
2973 EState *parentestate = epqstate->parentestate;
2974 Index rtsize = parentestate->es_range_table_size;
2975 EState *rcestate;
2976 MemoryContext oldcontext;
2977 ListCell *l;
2978
2979 epqstate->recheckestate = rcestate = CreateExecutorState();
2980
2981 oldcontext = MemoryContextSwitchTo(rcestate->es_query_cxt);
2982
2983 /* signal that this is an EState for executing EPQ */
2984 rcestate->es_epq_active = epqstate;
2985
2986 /*
2987 * Child EPQ EStates share the parent's copy of unchanging state such as
2988 * the snapshot, rangetable, and external Param info. They need their own
2989 * copies of local state, including a tuple table, es_param_exec_vals,
2990 * result-rel info, etc.
2991 */
2993 rcestate->es_snapshot = parentestate->es_snapshot;
2994 rcestate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
2995 rcestate->es_range_table = parentestate->es_range_table;
2996 rcestate->es_range_table_size = parentestate->es_range_table_size;
2997 rcestate->es_relations = parentestate->es_relations;
2998 rcestate->es_rowmarks = parentestate->es_rowmarks;
2999 rcestate->es_rteperminfos = parentestate->es_rteperminfos;
3000 rcestate->es_plannedstmt = parentestate->es_plannedstmt;
3001 rcestate->es_junkFilter = parentestate->es_junkFilter;
3002 rcestate->es_output_cid = parentestate->es_output_cid;
3003 rcestate->es_queryEnv = parentestate->es_queryEnv;
3004
3005 /*
3006 * ResultRelInfos needed by subplans are initialized from scratch when the
3007 * subplans themselves are initialized.
3008 */
3009 rcestate->es_result_relations = NULL;
3010 /* es_trig_target_relations must NOT be copied */
3011 rcestate->es_top_eflags = parentestate->es_top_eflags;
3012 rcestate->es_instrument = parentestate->es_instrument;
3013 /* es_auxmodifytables must NOT be copied */
3014
3015 /*
3016 * The external param list is simply shared from parent. The internal
3017 * param workspace has to be local state, but we copy the initial values
3018 * from the parent, so as to have access to any param values that were
3019 * already set from other parts of the parent's plan tree.
3020 */
3021 rcestate->es_param_list_info = parentestate->es_param_list_info;
3022 if (parentestate->es_plannedstmt->paramExecTypes != NIL)
3023 {
3024 int i;
3025
3026 /*
3027 * Force evaluation of any InitPlan outputs that could be needed by
3028 * the subplan. (With more complexity, maybe we could postpone this
3029 * till the subplan actually demands them, but it doesn't seem worth
3030 * the trouble; this is a corner case already, since usually the
3031 * InitPlans would have been evaluated before reaching EvalPlanQual.)
3032 *
3033 * This will not touch output params of InitPlans that occur somewhere
3034 * within the subplan tree, only those that are attached to the
3035 * ModifyTable node or above it and are referenced within the subplan.
3036 * That's OK though, because the planner would only attach such
3037 * InitPlans to a lower-level SubqueryScan node, and EPQ execution
3038 * will not descend into a SubqueryScan.
3039 *
3040 * The EState's per-output-tuple econtext is sufficiently short-lived
3041 * for this, since it should get reset before there is any chance of
3042 * doing EvalPlanQual again.
3043 */
3045 GetPerTupleExprContext(parentestate));
3046
3047 /* now make the internal param workspace ... */
3048 i = list_length(parentestate->es_plannedstmt->paramExecTypes);
3049 rcestate->es_param_exec_vals = (ParamExecData *)
3050 palloc0(i * sizeof(ParamExecData));
3051 /* ... and copy down all values, whether really needed or not */
3052 while (--i >= 0)
3053 {
3054 /* copy value if any, but not execPlan link */
3055 rcestate->es_param_exec_vals[i].value =
3056 parentestate->es_param_exec_vals[i].value;
3057 rcestate->es_param_exec_vals[i].isnull =
3058 parentestate->es_param_exec_vals[i].isnull;
3059 }
3060 }
3061
3062 /*
3063 * Copy es_unpruned_relids so that pruned relations are ignored by
3064 * ExecInitLockRows() and ExecInitModifyTable() when initializing the plan
3065 * trees below.
3066 */
3067 rcestate->es_unpruned_relids = parentestate->es_unpruned_relids;
3068
3069 /*
3070 * Initialize private state information for each SubPlan. We must do this
3071 * before running ExecInitNode on the main query tree, since
3072 * ExecInitSubPlan expects to be able to find these entries. Some of the
3073 * SubPlans might not be used in the part of the plan tree we intend to
3074 * run, but since it's not easy to tell which, we just initialize them
3075 * all.
3076 */
3077 Assert(rcestate->es_subplanstates == NIL);
3078 foreach(l, parentestate->es_plannedstmt->subplans)
3079 {
3080 Plan *subplan = (Plan *) lfirst(l);
3081 PlanState *subplanstate;
3082
3083 subplanstate = ExecInitNode(subplan, rcestate, 0);
3084 rcestate->es_subplanstates = lappend(rcestate->es_subplanstates,
3085 subplanstate);
3086 }
3087
3088 /*
3089 * Build an RTI indexed array of rowmarks, so that
3090 * EvalPlanQualFetchRowMark() can efficiently access the to be fetched
3091 * rowmark.
3092 */
3093 epqstate->relsubs_rowmark = (ExecAuxRowMark **)
3094 palloc0(rtsize * sizeof(ExecAuxRowMark *));
3095 foreach(l, epqstate->arowMarks)
3096 {
3097 ExecAuxRowMark *earm = (ExecAuxRowMark *) lfirst(l);
3098
3099 epqstate->relsubs_rowmark[earm->rowmark->rti - 1] = earm;
3100 }
3101
3102 /*
3103 * Initialize per-relation EPQ tuple states. Result relations, if any,
3104 * get marked as blocked; others as not-fetched.
3105 */
3106 epqstate->relsubs_done = palloc_array(bool, rtsize);
3107 epqstate->relsubs_blocked = palloc0_array(bool, rtsize);
3108
3109 foreach(l, epqstate->resultRelations)
3110 {
3111 int rtindex = lfirst_int(l);
3112
3113 Assert(rtindex > 0 && rtindex <= rtsize);
3114 epqstate->relsubs_blocked[rtindex - 1] = true;
3115 }
3116
3117 memcpy(epqstate->relsubs_done, epqstate->relsubs_blocked,
3118 rtsize * sizeof(bool));
3119
3120 /*
3121 * Initialize the private state information for all the nodes in the part
3122 * of the plan tree we need to run. This opens files, allocates storage
3123 * and leaves us ready to start processing tuples.
3124 */
3125 epqstate->recheckplanstate = ExecInitNode(planTree, rcestate, 0);
3126
3127 MemoryContextSwitchTo(oldcontext);
3128}
3129
3130/*
3131 * EvalPlanQualEnd -- shut down at termination of parent plan state node,
3132 * or if we are done with the current EPQ child.
3133 *
3134 * This is a cut-down version of ExecutorEnd(); basically we want to do most
3135 * of the normal cleanup, but *not* close result relations (which we are
3136 * just sharing from the outer query). We do, however, have to close any
3137 * result and trigger target relations that got opened, since those are not
3138 * shared. (There probably shouldn't be any of the latter, but just in
3139 * case...)
3140 */
3141void
3143{
3144 EState *estate = epqstate->recheckestate;
3145 Index rtsize;
3146 MemoryContext oldcontext;
3147 ListCell *l;
3148
3149 rtsize = epqstate->parentestate->es_range_table_size;
3150
3151 /*
3152 * We may have a tuple table, even if EPQ wasn't started, because we allow
3153 * use of EvalPlanQualSlot() without calling EvalPlanQualBegin().
3154 */
3155 if (epqstate->tuple_table != NIL)
3156 {
3157 memset(epqstate->relsubs_slot, 0,
3158 rtsize * sizeof(TupleTableSlot *));
3159 ExecResetTupleTable(epqstate->tuple_table, true);
3160 epqstate->tuple_table = NIL;
3161 }
3162
3163 /* EPQ wasn't started, nothing further to do */
3164 if (estate == NULL)
3165 return;
3166
3167 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3168
3169 ExecEndNode(epqstate->recheckplanstate);
3170
3171 foreach(l, estate->es_subplanstates)
3172 {
3173 PlanState *subplanstate = (PlanState *) lfirst(l);
3174
3175 ExecEndNode(subplanstate);
3176 }
3177
3178 /* throw away the per-estate tuple table, some node may have used it */
3179 ExecResetTupleTable(estate->es_tupleTable, false);
3180
3181 /* Close any result and trigger target relations attached to this EState */
3183
3184 MemoryContextSwitchTo(oldcontext);
3185
3186 FreeExecutorState(estate);
3187
3188 /* Mark EPQState idle */
3189 epqstate->origslot = NULL;
3190 epqstate->recheckestate = NULL;
3191 epqstate->recheckplanstate = NULL;
3192 epqstate->relsubs_rowmark = NULL;
3193 epqstate->relsubs_done = NULL;
3194 epqstate->relsubs_blocked = NULL;
3195}
AclResult
Definition: acl.h:182
@ ACLCHECK_NO_PRIV
Definition: acl.h:184
@ ACLCHECK_OK
Definition: acl.h:183
@ ACLMASK_ANY
Definition: acl.h:177
@ ACLMASK_ALL
Definition: acl.h:176
AclResult pg_attribute_aclcheck_all(Oid table_oid, Oid roleid, AclMode mode, AclMaskHow how)
Definition: aclchk.c:3895
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2639
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:3853
AclMode pg_class_aclmask(Oid table_oid, Oid roleid, AclMode mask, AclMaskHow how)
Definition: aclchk.c:3257
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4024
AttrMap * build_attrmap_by_name_if_req(TupleDesc indesc, TupleDesc outdesc, bool missing_ok)
Definition: attmap.c:261
int16 AttrNumber
Definition: attnum.h:21
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
#define InvalidAttrNumber
Definition: attnum.h:23
void pgstat_report_query_id(uint64 query_id, bool force)
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1306
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:751
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:251
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:582
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:122
#define bms_is_empty(a)
Definition: bitmapset.h:118
#define NameStr(name)
Definition: c.h:717
uint64_t uint64
Definition: c.h:503
unsigned int Index
Definition: c.h:585
#define MemSet(start, val, len)
Definition: c.h:991
#define OidIsValid(objectId)
Definition: c.h:746
bool IsInplaceUpdateRelation(Relation relation)
Definition: catalog.c:183
int errdetail(const char *fmt,...)
Definition: elog.c:1204
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
#define ereport(elevel,...)
Definition: elog.h:149
void ExecReScan(PlanState *node)
Definition: execAmi.c:77
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition: execExpr.c:765
bool ExecCheck(ExprState *state, ExprContext *econtext)
Definition: execExpr.c:872
ExprState * ExecPrepareCheck(List *qual, EState *estate)
Definition: execExpr.c:816
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:238
TupleTableSlot * ExecFilterJunk(JunkFilter *junkfilter, TupleTableSlot *slot)
Definition: execJunk.c:247
AttrNumber ExecFindJunkAttributeInTlist(List *targetlist, const char *attrName)
Definition: execJunk.c:222
JunkFilter * ExecInitJunkFilter(List *targetList, TupleTableSlot *slot)
Definition: execJunk.c:60
static void EvalPlanQualStart(EPQState *epqstate, Plan *planTree)
Definition: execMain.c:2971
static void ReportNotNullViolationError(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, int attnum)
Definition: execMain.c:2131
LockTupleMode ExecUpdateLockMode(EState *estate, ResultRelInfo *relinfo)
Definition: execMain.c:2502
ExecRowMark * ExecFindRowMark(EState *estate, Index rti, bool missing_ok)
Definition: execMain.c:2528
ExecAuxRowMark * ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
Definition: execMain.c:2551
ExecutorEnd_hook_type ExecutorEnd_hook
Definition: execMain.c:71
ResultRelInfo * ExecGetTriggerResultRel(EState *estate, Oid relid, ResultRelInfo *rootRelInfo)
Definition: execMain.c:1326
void CheckValidResultRel(ResultRelInfo *resultRelInfo, CmdType operation, List *mergeActions)
Definition: execMain.c:1048
TupleTableSlot * EvalPlanQualSlot(EPQState *epqstate, Relation relation, Index rti)
Definition: execMain.c:2749
void EvalPlanQualBegin(EPQState *epqstate)
Definition: execMain.c:2904
ExecutorFinish_hook_type ExecutorFinish_hook
Definition: execMain.c:70
char * ExecBuildSlotValueDescription(Oid reloid, TupleTableSlot *slot, TupleDesc tupdesc, Bitmapset *modifiedCols, int maxfieldlen)
Definition: execMain.c:2363
static bool ExecCheckOneRelPerms(RTEPermissionInfo *perminfo)
Definition: execMain.c:647
bool ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool emitError)
Definition: execMain.c:1828
static void ExecEndPlan(PlanState *planstate, EState *estate)
Definition: execMain.c:1508
ExecutorStart_hook_type ExecutorStart_hook
Definition: execMain.c:68
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:467
void EvalPlanQualInit(EPQState *epqstate, EState *parentestate, Plan *subplan, List *auxrowmarks, int epqParam, List *resultRelations)
Definition: execMain.c:2690
void ExecWithCheckOptions(WCOKind kind, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:2200
ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook
Definition: execMain.c:74
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, ResultRelInfo *partition_root_rri, int instrument_options)
Definition: execMain.c:1225
void standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:142
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:407
static void CheckValidRowMarkRel(Relation rel, RowMarkType markType)
Definition: execMain.c:1160
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:3142
static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
Definition: execMain.c:803
void EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan, List *auxrowmarks)
Definition: execMain.c:2732
void ExecutorRewind(QueryDesc *queryDesc)
Definition: execMain.c:537
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:123
AttrNumber ExecRelGenVirtualNotNull(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, List *notnull_virtual_attrs)
Definition: execMain.c:2066
TupleTableSlot * EvalPlanQual(EPQState *epqstate, Relation relation, Index rti, TupleTableSlot *inputslot)
Definition: execMain.c:2621
bool EvalPlanQualFetchRowMark(EPQState *epqstate, Index rti, TupleTableSlot *slot)
Definition: execMain.c:2777
static bool ExecCheckPermissionsModified(Oid relOid, Oid userid, Bitmapset *modifiedCols, AclMode requiredPerms)
Definition: execMain.c:756
ExecutorRun_hook_type ExecutorRun_hook
Definition: execMain.c:69
static void ExecPostprocessPlan(EState *estate)
Definition: execMain.c:1462
static const char * ExecRelCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1750
static void ExecutePlan(QueryDesc *queryDesc, CmdType operation, bool sendTuples, uint64 numberTuples, ScanDirection direction, DestReceiver *dest)
Definition: execMain.c:1628
void ExecCloseResultRelations(EState *estate)
Definition: execMain.c:1547
void standard_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count)
Definition: execMain.c:308
void standard_ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:476
void ExecCloseRangeTableRelations(EState *estate)
Definition: execMain.c:1607
void ExecPartitionCheckEmitError(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1881
void ExecConstraints(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1952
static void InitPlan(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:837
bool ExecCheckPermissions(List *rangeTable, List *rteperminfos, bool ereport_on_violation)
Definition: execMain.c:583
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count)
Definition: execMain.c:298
List * ExecGetAncestorResultRels(EState *estate, ResultRelInfo *resultRelInfo)
Definition: execMain.c:1402
TupleTableSlot * EvalPlanQualNext(EPQState *epqstate)
Definition: execMain.c:2888
void standard_ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:416
void ExecDoInitialPruning(EState *estate)
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:562
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:142
void ExecShutdownNode(PlanState *node)
Definition: execProcnode.c:772
void CheckCmdReplicaIdentity(Relation rel, CmdType cmd)
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:1380
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:84
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:2020
void ExecStoreHeapTupleDatum(Datum data, TupleTableSlot *slot)
Definition: execTuples.c:1795
TupleTableSlot * MakeTupleTableSlot(TupleDesc tupleDesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1301
TupleDesc ExecGetResultType(PlanState *planstate)
Definition: execUtils.c:495
Relation ExecGetRangeTableRelation(EState *estate, Index rti, bool isResultRel)
Definition: execUtils.c:825
Bitmapset * ExecGetInsertedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1361
void ExecInitRangeTable(EState *estate, List *rangeTable, List *permInfos, Bitmapset *unpruned_relids)
Definition: execUtils.c:773
Bitmapset * ExecGetUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1382
void FreeExecutorState(EState *estate)
Definition: execUtils.c:192
Bitmapset * ExecGetAllUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1418
EState * CreateExecutorState(void)
Definition: execUtils.c:88
#define EXEC_FLAG_BACKWARD
Definition: executor.h:68
#define EXEC_FLAG_REWIND
Definition: executor.h:67
#define ResetPerTupleExprContext(estate)
Definition: executor.h:659
#define GetPerTupleExprContext(estate)
Definition: executor.h:650
void(* ExecutorFinish_hook_type)(QueryDesc *queryDesc)
Definition: executor.h:85
static RangeTblEntry * exec_rt_fetch(Index rti, EState *estate)
Definition: executor.h:691
void(* ExecutorRun_hook_type)(QueryDesc *queryDesc, ScanDirection direction, uint64 count)
Definition: executor.h:79
void(* ExecutorStart_hook_type)(QueryDesc *queryDesc, int eflags)
Definition: executor.h:75
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:513
bool(* ExecutorCheckPerms_hook_type)(List *rangeTable, List *rtePermInfos, bool ereport_on_violation)
Definition: executor.h:93
void(* ExecutorEnd_hook_type)(QueryDesc *queryDesc)
Definition: executor.h:89
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:308
#define EXEC_FLAG_SKIP_TRIGGERS
Definition: executor.h:70
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:65
static Datum ExecGetJunkAttribute(TupleTableSlot *slot, AttrNumber attno, bool *isNull)
Definition: executor.h:221
#define EXEC_FLAG_MARK
Definition: executor.h:69
#define palloc_array(type, count)
Definition: fe_memutils.h:76
#define palloc0_array(type, count)
Definition: fe_memutils.h:77
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1763
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:443
Assert(PointerIsAligned(start, uint64))
struct parser_state ps
long val
Definition: informix.c:689
static bool success
Definition: initdb.c:187
Instrumentation * InstrAlloc(int n, int instrument_options, bool async_mode)
Definition: instrument.c:31
void InstrStartNode(Instrumentation *instr)
Definition: instrument.c:68
void InstrStopNode(Instrumentation *instr, double nTuples)
Definition: instrument.c:84
int j
Definition: isn.c:78
int i
Definition: isn.c:77
static void ItemPointerSetInvalid(ItemPointerData *pointer)
Definition: itemptr.h:184
List * lappend(List *list, void *datum)
Definition: list.c:339
List * lappend_int(List *list, int datum)
Definition: list.c:357
#define NoLock
Definition: lockdefs.h:34
LockTupleMode
Definition: lockoptions.h:50
@ LockTupleExclusive
Definition: lockoptions.h:58
@ LockTupleNoKeyExclusive
Definition: lockoptions.h:56
char * get_rel_name(Oid relid)
Definition: lsyscache.c:2068
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:3047
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:2143
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:2092
bool MatViewIncrementalMaintenanceIsEnabled(void)
Definition: matview.c:963
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:1084
void * palloc0(Size size)
Definition: mcxt.c:1351
void * palloc(Size size)
Definition: mcxt.c:1321
Oid GetUserId(void)
Definition: miscinit.c:520
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3649
void ExecSetParamPlanMulti(const Bitmapset *params, ExprContext *econtext)
Definition: nodeSubplan.c:1276
CmdType
Definition: nodes.h:269
@ CMD_MERGE
Definition: nodes.h:275
@ CMD_INSERT
Definition: nodes.h:273
@ CMD_DELETE
Definition: nodes.h:274
@ CMD_UPDATE
Definition: nodes.h:272
@ CMD_SELECT
Definition: nodes.h:271
#define makeNode(_type_)
Definition: nodes.h:161
ObjectType get_relkind_objtype(char relkind)
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
RTEPermissionInfo * getRTEPermissionInfo(List *rteperminfos, RangeTblEntry *rte)
WCOKind
Definition: parsenodes.h:1372
@ WCO_RLS_MERGE_UPDATE_CHECK
Definition: parsenodes.h:1377
@ WCO_RLS_CONFLICT_CHECK
Definition: parsenodes.h:1376
@ WCO_RLS_INSERT_CHECK
Definition: parsenodes.h:1374
@ WCO_VIEW_CHECK
Definition: parsenodes.h:1373
@ WCO_RLS_UPDATE_CHECK
Definition: parsenodes.h:1375
@ WCO_RLS_MERGE_DELETE_CHECK
Definition: parsenodes.h:1378
uint64 AclMode
Definition: parsenodes.h:74
#define ACL_INSERT
Definition: parsenodes.h:76
#define ACL_UPDATE
Definition: parsenodes.h:78
@ RTE_SUBQUERY
Definition: parsenodes.h:1027
@ RTE_RELATION
Definition: parsenodes.h:1026
#define ACL_SELECT
Definition: parsenodes.h:77
List * RelationGetPartitionQual(Relation rel)
Definition: partcache.c:277
List * get_partition_ancestors(Oid relid)
Definition: partition.c:134
int16 attnum
Definition: pg_attribute.h:74
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:202
#define lfirst(lc)
Definition: pg_list.h:172
#define lfirst_node(type, lc)
Definition: pg_list.h:176
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:518
#define foreach_current_index(var_or_cell)
Definition: pg_list.h:403
#define lfirst_int(lc)
Definition: pg_list.h:173
#define lfirst_oid(lc)
Definition: pg_list.h:174
#define foreach_int(var, lst)
Definition: pg_list.h:470
#define plan(x)
Definition: pg_regress.c:161
static char * buf
Definition: pg_test_fsync.c:72
int64 PgStat_Counter
Definition: pgstat.h:65
void pgstat_update_parallel_workers_stats(PgStat_Counter workers_to_launch, PgStat_Counter workers_launched)
#define RowMarkRequiresRowShareLock(marktype)
Definition: plannodes.h:1487
RowMarkType
Definition: plannodes.h:1478
@ ROW_MARK_COPY
Definition: plannodes.h:1484
@ ROW_MARK_REFERENCE
Definition: plannodes.h:1483
@ ROW_MARK_SHARE
Definition: plannodes.h:1481
@ ROW_MARK_EXCLUSIVE
Definition: plannodes.h:1479
@ ROW_MARK_NOKEYEXCLUSIVE
Definition: plannodes.h:1480
@ ROW_MARK_KEYSHARE
Definition: plannodes.h:1482
#define snprintf
Definition: port.h:239
uintptr_t Datum
Definition: postgres.h:69
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:247
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:317
#define InvalidOid
Definition: postgres_ext.h:35
unsigned int Oid
Definition: postgres_ext.h:30
@ IS_NOT_NULL
Definition: primnodes.h:1957
@ MERGE_WHEN_NOT_MATCHED_BY_TARGET
Definition: primnodes.h:2003
@ MERGE_WHEN_NOT_MATCHED_BY_SOURCE
Definition: primnodes.h:2002
@ MERGE_WHEN_MATCHED
Definition: primnodes.h:2001
void * stringToNode(const char *str)
Definition: read.c:90
#define RelationGetRelid(relation)
Definition: rel.h:516
#define RelationGetDescr(relation)
Definition: rel.h:542
#define RelationGetRelationName(relation)
Definition: rel.h:550
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:6103
int errtablecol(Relation rel, int attnum)
Definition: relcache.c:6066
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition: relcache.c:5303
int errtable(Relation rel)
Definition: relcache.c:6049
@ INDEX_ATTR_BITMAP_KEY
Definition: relcache.h:69
bool view_has_instead_trigger(Relation view, CmdType event, List *mergeActionList)
Node * build_generation_expression(Relation rel, int attrno)
void error_view_not_updatable(Relation view, CmdType command, List *mergeActionList, const char *detail)
Node * expand_generated_columns_in_expr(Node *node, Relation rel, int rt_index)
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition: rls.c:52
@ RLS_ENABLED
Definition: rls.h:45
#define ScanDirectionIsNoMovement(direction)
Definition: sdir.h:57
ScanDirection
Definition: sdir.h:25
@ ForwardScanDirection
Definition: sdir.h:28
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:853
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:811
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:787
#define SnapshotAny
Definition: snapmgr.h:33
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
Definition: stringinfo.c:281
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:230
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:242
void initStringInfo(StringInfo str)
Definition: stringinfo.c:97
Definition: attmap.h:35
char * ccname
Definition: tupdesc.h:30
ExecAuxRowMark ** relsubs_rowmark
Definition: execnodes.h:1331
TupleTableSlot * origslot
Definition: execnodes.h:1319
TupleTableSlot ** relsubs_slot
Definition: execnodes.h:1303
Plan * plan
Definition: execnodes.h:1310
int epqParam
Definition: execnodes.h:1293
bool * relsubs_blocked
Definition: execnodes.h:1347
EState * parentestate
Definition: execnodes.h:1292
EState * recheckestate
Definition: execnodes.h:1324
PlanState * recheckplanstate
Definition: execnodes.h:1349
List * resultRelations
Definition: execnodes.h:1294
List * arowMarks
Definition: execnodes.h:1311
List * tuple_table
Definition: execnodes.h:1302
bool * relsubs_done
Definition: execnodes.h:1338
uint64 es_processed
Definition: execnodes.h:710
List * es_part_prune_infos
Definition: execnodes.h:666
struct ExecRowMark ** es_rowmarks
Definition: execnodes.h:662
int es_parallel_workers_to_launch
Definition: execnodes.h:742
List * es_tuple_routing_result_relations
Definition: execnodes.h:694
int es_top_eflags
Definition: execnodes.h:715
int es_instrument
Definition: execnodes.h:716
PlannedStmt * es_plannedstmt
Definition: execnodes.h:665
QueryEnvironment * es_queryEnv
Definition: execnodes.h:703
ResultRelInfo ** es_result_relations
Definition: execnodes.h:681
ParamExecData * es_param_exec_vals
Definition: execnodes.h:701
uint64 es_total_processed
Definition: execnodes.h:712
List * es_range_table
Definition: execnodes.h:658
List * es_rteperminfos
Definition: execnodes.h:664
Bitmapset * es_unpruned_relids
Definition: execnodes.h:669
ParamListInfo es_param_list_info
Definition: execnodes.h:700
bool es_finished
Definition: execnodes.h:717
MemoryContext es_query_cxt
Definition: execnodes.h:706
List * es_tupleTable
Definition: execnodes.h:708
ScanDirection es_direction
Definition: execnodes.h:655
struct EPQState * es_epq_active
Definition: execnodes.h:738
List * es_trig_target_relations
Definition: execnodes.h:697
int es_jit_flags
Definition: execnodes.h:759
List * es_opened_result_relations
Definition: execnodes.h:684
bool es_use_parallel_mode
Definition: execnodes.h:740
Relation * es_relations
Definition: execnodes.h:660
List * es_subplanstates
Definition: execnodes.h:721
int es_parallel_workers_launched
Definition: execnodes.h:744
CommandId es_output_cid
Definition: execnodes.h:678
Index es_range_table_size
Definition: execnodes.h:659
const char * es_sourceText
Definition: execnodes.h:673
Snapshot es_snapshot
Definition: execnodes.h:656
List * es_auxmodifytables
Definition: execnodes.h:723
JunkFilter * es_junkFilter
Definition: execnodes.h:675
Snapshot es_crosscheck_snapshot
Definition: execnodes.h:657
AttrNumber wholeAttNo
Definition: execnodes.h:820
ExecRowMark * rowmark
Definition: execnodes.h:817
AttrNumber toidAttNo
Definition: execnodes.h:819
AttrNumber ctidAttNo
Definition: execnodes.h:818
Index rowmarkId
Definition: execnodes.h:797
ItemPointerData curCtid
Definition: execnodes.h:802
LockClauseStrength strength
Definition: execnodes.h:799
Index rti
Definition: execnodes.h:795
bool ermActive
Definition: execnodes.h:801
Index prti
Definition: execnodes.h:796
Relation relation
Definition: execnodes.h:793
LockWaitPolicy waitPolicy
Definition: execnodes.h:800
void * ermExtra
Definition: execnodes.h:803
RowMarkType markType
Definition: execnodes.h:798
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:267
ExecForeignInsert_function ExecForeignInsert
Definition: fdwapi.h:232
ExecForeignUpdate_function ExecForeignUpdate
Definition: fdwapi.h:235
RefetchForeignRow_function RefetchForeignRow
Definition: fdwapi.h:248
ExecForeignDelete_function ExecForeignDelete
Definition: fdwapi.h:236
IsForeignRelUpdatable_function IsForeignRelUpdatable
Definition: fdwapi.h:240
Definition: fmgr.h:57
Definition: pg_list.h:54
Definition: nodes.h:135
NullTestType nulltesttype
Definition: primnodes.h:1964
ParseLoc location
Definition: primnodes.h:1967
Expr * arg
Definition: primnodes.h:1963
bool isnull
Definition: params.h:150
Datum value
Definition: params.h:149
LockClauseStrength strength
Definition: plannodes.h:1543
Index prti
Definition: plannodes.h:1535
RowMarkType markType
Definition: plannodes.h:1539
LockWaitPolicy waitPolicy
Definition: plannodes.h:1545
bool isParent
Definition: plannodes.h:1547
Index rowmarkId
Definition: plannodes.h:1537
Plan * plan
Definition: execnodes.h:1156
Bitmapset * chgParam
Definition: execnodes.h:1188
Bitmapset * extParam
Definition: plannodes.h:222
List * targetlist
Definition: plannodes.h:202
struct Plan * planTree
Definition: plannodes.h:83
bool hasModifyingCTE
Definition: plannodes.h:65
List * permInfos
Definition: plannodes.h:102
List * rowMarks
Definition: plannodes.h:120
int jitFlags
Definition: plannodes.h:80
Bitmapset * rewindPlanIDs
Definition: plannodes.h:117
bool hasReturning
Definition: plannodes.h:62
List * subplans
Definition: plannodes.h:114
Bitmapset * unprunableRelids
Definition: plannodes.h:97
CmdType commandType
Definition: plannodes.h:53
List * rtable
Definition: plannodes.h:91
List * partPruneInfos
Definition: plannodes.h:88
List * paramExecTypes
Definition: plannodes.h:129
bool parallelModeNeeded
Definition: plannodes.h:77
uint64 queryId
Definition: plannodes.h:56
const char * sourceText
Definition: execdesc.h:38
ParamListInfo params
Definition: execdesc.h:42
DestReceiver * dest
Definition: execdesc.h:41
int instrument_options
Definition: execdesc.h:44
EState * estate
Definition: execdesc.h:48
CmdType operation
Definition: execdesc.h:36
Snapshot snapshot
Definition: execdesc.h:39
bool already_executed
Definition: execdesc.h:52
PlannedStmt * plannedstmt
Definition: execdesc.h:37
struct Instrumentation * totaltime
Definition: execdesc.h:55
QueryEnvironment * queryEnv
Definition: execdesc.h:43
TupleDesc tupDesc
Definition: execdesc.h:47
Snapshot crosscheck_snapshot
Definition: execdesc.h:40
PlanState * planstate
Definition: execdesc.h:49
Bitmapset * selectedCols
Definition: parsenodes.h:1307
AclMode requiredPerms
Definition: parsenodes.h:1305
Bitmapset * insertedCols
Definition: parsenodes.h:1308
Bitmapset * updatedCols
Definition: parsenodes.h:1309
RTEKind rtekind
Definition: parsenodes.h:1061
TriggerDesc * trigdesc
Definition: rel.h:117
TupleDesc rd_att
Definition: rel.h:112
Form_pg_class rd_rel
Definition: rel.h:111
TupleConversionMap * ri_RootToChildMap
Definition: execnodes.h:600
ExprState ** ri_CheckConstraintExprs
Definition: execnodes.h:549
TupleTableSlot * ri_PartitionTupleSlot
Definition: execnodes.h:615
bool ri_projectNewInfoValid
Definition: execnodes.h:503
OnConflictSetState * ri_onConflict
Definition: execnodes.h:577
int ri_NumIndices
Definition: execnodes.h:477
List * ri_onConflictArbiterIndexes
Definition: execnodes.h:574
struct ResultRelInfo * ri_RootResultRelInfo
Definition: execnodes.h:614
ExprState * ri_PartitionCheckExpr
Definition: execnodes.h:586
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:518
ExprState * ri_MergeJoinCondition
Definition: execnodes.h:583
bool ri_needLockTagTuple
Definition: execnodes.h:506
Relation ri_RelationDesc
Definition: execnodes.h:474
RelationPtr ri_IndexRelationDescs
Definition: execnodes.h:480
TupleTableSlot * ri_ReturningSlot
Definition: execnodes.h:521
List * ri_WithCheckOptions
Definition: execnodes.h:543
TupleTableSlot * ri_oldTupleSlot
Definition: execnodes.h:501
bool ri_RootToChildMapValid
Definition: execnodes.h:601
struct CopyMultiInsertBuffer * ri_CopyMultiInsertBuffer
Definition: execnodes.h:618
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:509
TupleTableSlot * ri_AllNullSlot
Definition: execnodes.h:524
ExprState ** ri_GenVirtualNotNullConstraintExprs
Definition: execnodes.h:555
Bitmapset * ri_extraUpdatedCols
Definition: execnodes.h:492
Index ri_RangeTableIndex
Definition: execnodes.h:471
ExprState ** ri_GeneratedExprsI
Definition: execnodes.h:560
TupleConversionMap * ri_ChildToRootMap
Definition: execnodes.h:594
void * ri_FdwState
Definition: execnodes.h:530
bool ri_ChildToRootMapValid
Definition: execnodes.h:595
List * ri_MergeActions[NUM_MERGE_MATCH_KINDS]
Definition: execnodes.h:580
List * ri_ancestorResultRels
Definition: execnodes.h:624
TupleTableSlot * ri_newTupleSlot
Definition: execnodes.h:499
List * ri_WithCheckOptionExprs
Definition: execnodes.h:546
ProjectionInfo * ri_projectNew
Definition: execnodes.h:497
NodeTag type
Definition: execnodes.h:468
ProjectionInfo * ri_projectReturning
Definition: execnodes.h:571
ExprState ** ri_GeneratedExprsU
Definition: execnodes.h:561
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:527
ExprState ** ri_TrigWhenExprs
Definition: execnodes.h:515
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:512
bool ri_usesFdwDirectModify
Definition: execnodes.h:533
AttrNumber ri_RowIdAttNo
Definition: execnodes.h:489
IndexInfo ** ri_IndexRelationInfo
Definition: execnodes.h:483
TupleTableSlot * ri_TrigNewSlot
Definition: execnodes.h:523
TupleTableSlot * ri_TrigOldSlot
Definition: execnodes.h:522
int numtriggers
Definition: reltrigger.h:50
bool has_not_null
Definition: tupdesc.h:45
ConstrCheck * check
Definition: tupdesc.h:41
uint16 num_check
Definition: tupdesc.h:44
TupleConstr * constr
Definition: tupdesc.h:141
bool * tts_isnull
Definition: tuptable.h:127
Datum * tts_values
Definition: tuptable.h:125
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:92
static bool table_tuple_fetch_row_version(Relation rel, ItemPointer tid, Snapshot snapshot, TupleTableSlot *slot)
Definition: tableam.h:1248
TriggerDesc * CopyTriggerDesc(TriggerDesc *trigdesc)
Definition: trigger.c:2090
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:5073
void AfterTriggerBeginQuery(void)
Definition: trigger.c:5053
TupleTableSlot * execute_attr_map_slot(AttrMap *attrMap, TupleTableSlot *in_slot, TupleTableSlot *out_slot)
Definition: tupconvert.c:192
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:160
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:458
#define TupIsNull(slot)
Definition: tuptable.h:310
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:372
static TupleTableSlot * ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
Definition: tuptable.h:525
static void ExecMaterializeSlot(TupleTableSlot *slot)
Definition: tuptable.h:476
static bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition: tuptable.h:385
void PreventCommandIfReadOnly(const char *cmdname)
Definition: utility.c:404
void PreventCommandIfParallelMode(const char *cmdname)
Definition: utility.c:422
static const char * CreateCommandName(Node *parsetree)
Definition: utility.h:103
void ExitParallelMode(void)
Definition: xact.c:1064
void EnterParallelMode(void)
Definition: xact.c:1051
bool XactReadOnly
Definition: xact.c:82
bool IsInParallelMode(void)
Definition: xact.c:1089
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:829