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