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