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