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