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