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