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