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 761620 : 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 761620 : pgstat_report_query_id(queryDesc->plannedstmt->queryId, false);
135 :
136 761620 : if (ExecutorStart_hook)
137 60529 : (*ExecutorStart_hook) (queryDesc, eflags);
138 : else
139 701091 : standard_ExecutorStart(queryDesc, eflags);
140 760475 : }
141 :
142 : void
143 761620 : 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 761620 : if ((XactReadOnly || IsInParallelMode()) &&
171 36810 : !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
172 36810 : ExecCheckXactReadOnly(queryDesc->plannedstmt);
173 :
174 : /*
175 : * Build EState, switch into per-query memory context for startup.
176 : */
177 761610 : estate = CreateExecutorState();
178 761610 : queryDesc->estate = estate;
179 :
180 761610 : 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 761610 : estate->es_param_list_info = queryDesc->params;
187 :
188 761610 : if (queryDesc->plannedstmt->paramExecTypes != NIL)
189 : {
190 : int nParamExec;
191 :
192 522392 : nParamExec = list_length(queryDesc->plannedstmt->paramExecTypes);
193 522392 : estate->es_param_exec_vals = (ParamExecData *)
194 522392 : palloc0_array(ParamExecData, nParamExec);
195 : }
196 :
197 : /* We now require all callers to provide sourceText */
198 : Assert(queryDesc->sourceText != NULL);
199 761610 : estate->es_sourceText = queryDesc->sourceText;
200 :
201 : /*
202 : * Fill in the query environment, if any, from queryDesc.
203 : */
204 761610 : estate->es_queryEnv = queryDesc->queryEnv;
205 :
206 : /*
207 : * If non-read-only query, set the command ID to mark output tuples with
208 : */
209 761610 : switch (queryDesc->operation)
210 : {
211 687857 : case CMD_SELECT:
212 :
213 : /*
214 : * SELECT FOR [KEY] UPDATE/SHARE and modifying CTEs need to mark
215 : * tuples
216 : */
217 687857 : if (queryDesc->plannedstmt->rowMarks != NIL ||
218 280050 : queryDesc->plannedstmt->hasModifyingCTE)
219 407899 : 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 687857 : if (!queryDesc->plannedstmt->hasModifyingCTE)
228 687761 : eflags |= EXEC_FLAG_SKIP_TRIGGERS;
229 687857 : break;
230 :
231 73753 : case CMD_INSERT:
232 : case CMD_DELETE:
233 : case CMD_UPDATE:
234 : case CMD_MERGE:
235 73753 : estate->es_output_cid = GetCurrentCommandId(true);
236 73753 : 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 761610 : estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
248 761610 : estate->es_crosscheck_snapshot = RegisterSnapshot(queryDesc->crosscheck_snapshot);
249 761610 : estate->es_top_eflags = eflags;
250 761610 : estate->es_instrument = queryDesc->instrument_options;
251 761610 : 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 761610 : if (!(eflags & (EXEC_FLAG_SKIP_TRIGGERS | EXEC_FLAG_EXPLAIN_ONLY)))
258 72780 : AfterTriggerBeginQuery();
259 :
260 : /*
261 : * Initialize the plan state tree
262 : */
263 761610 : InitPlan(queryDesc, eflags);
264 :
265 760475 : MemoryContextSwitchTo(oldcontext);
266 760475 : }
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 754848 : ExecutorRun(QueryDesc *queryDesc,
300 : ScanDirection direction, uint64 count)
301 : {
302 754848 : if (ExecutorRun_hook)
303 58931 : (*ExecutorRun_hook) (queryDesc, direction, count);
304 : else
305 695917 : standard_ExecutorRun(queryDesc, direction, count);
306 739042 : }
307 :
308 : void
309 754848 : 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 754848 : 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 754848 : oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
333 :
334 : /* Allow instrumentation of Executor overall runtime */
335 754848 : if (queryDesc->totaltime)
336 40559 : InstrStartNode(queryDesc->totaltime);
337 :
338 : /*
339 : * extract information from the query descriptor and the query feature.
340 : */
341 754848 : operation = queryDesc->operation;
342 754848 : dest = queryDesc->dest;
343 :
344 : /*
345 : * startup tuple receiver, if we will be emitting tuples
346 : */
347 754848 : estate->es_processed = 0;
348 :
349 827277 : sendTuples = (operation == CMD_SELECT ||
350 72429 : queryDesc->plannedstmt->hasReturning);
351 :
352 754848 : if (sendTuples)
353 685621 : 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 754823 : if (!ScanDirectionIsNoMovement(direction))
368 754016 : 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 739042 : estate->es_total_processed += estate->es_processed;
380 :
381 : /*
382 : * shutdown tuple receiver, if we started it
383 : */
384 739042 : if (sendTuples)
385 671850 : dest->rShutdown(dest);
386 :
387 739042 : if (queryDesc->totaltime)
388 39135 : InstrStopNode(queryDesc->totaltime, estate->es_processed);
389 :
390 739042 : MemoryContextSwitchTo(oldcontext);
391 739042 : }
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 729404 : ExecutorFinish(QueryDesc *queryDesc)
409 : {
410 729404 : if (ExecutorFinish_hook)
411 53376 : (*ExecutorFinish_hook) (queryDesc);
412 : else
413 676028 : standard_ExecutorFinish(queryDesc);
414 728658 : }
415 :
416 : void
417 729404 : standard_ExecutorFinish(QueryDesc *queryDesc)
418 : {
419 : EState *estate;
420 : MemoryContext oldcontext;
421 :
422 : /* sanity checks */
423 : Assert(queryDesc != NULL);
424 :
425 729404 : 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 729404 : oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
435 :
436 : /* Allow instrumentation of Executor overall runtime */
437 729404 : if (queryDesc->totaltime)
438 39135 : InstrStartNode(queryDesc->totaltime);
439 :
440 : /* Run ModifyTable nodes to completion */
441 729404 : ExecPostprocessPlan(estate);
442 :
443 : /* Execute queued AFTER triggers, unless told not to */
444 729404 : if (!(estate->es_top_eflags & EXEC_FLAG_SKIP_TRIGGERS))
445 69968 : AfterTriggerEndQuery(estate);
446 :
447 728658 : if (queryDesc->totaltime)
448 38971 : InstrStopNode(queryDesc->totaltime, 0);
449 :
450 728658 : MemoryContextSwitchTo(oldcontext);
451 :
452 728658 : estate->es_finished = true;
453 728658 : }
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 742570 : ExecutorEnd(QueryDesc *queryDesc)
469 : {
470 742570 : if (ExecutorEnd_hook)
471 56266 : (*ExecutorEnd_hook) (queryDesc);
472 : else
473 686304 : standard_ExecutorEnd(queryDesc);
474 742570 : }
475 :
476 : void
477 742570 : standard_ExecutorEnd(QueryDesc *queryDesc)
478 : {
479 : EState *estate;
480 : MemoryContext oldcontext;
481 :
482 : /* sanity checks */
483 : Assert(queryDesc != NULL);
484 :
485 742570 : estate = queryDesc->estate;
486 :
487 : Assert(estate != NULL);
488 :
489 742570 : if (estate->es_parallel_workers_to_launch > 0)
490 494 : pgstat_update_parallel_workers_stats((PgStat_Counter) estate->es_parallel_workers_to_launch,
491 494 : (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 742570 : oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
505 :
506 742570 : ExecEndPlan(queryDesc->planstate, estate);
507 :
508 : /* do away with our snapshots */
509 742570 : UnregisterSnapshot(estate->es_snapshot);
510 742570 : UnregisterSnapshot(estate->es_crosscheck_snapshot);
511 :
512 : /*
513 : * Must switch out of context before destroying it
514 : */
515 742570 : MemoryContextSwitchTo(oldcontext);
516 :
517 : /*
518 : * Release EState and per-query memory context. This should release
519 : * everything the executor has allocated.
520 : */
521 742570 : FreeExecutorState(estate);
522 :
523 : /* Reset queryDesc fields that no longer point to anything */
524 742570 : queryDesc->tupDesc = NULL;
525 742570 : queryDesc->estate = NULL;
526 742570 : queryDesc->planstate = NULL;
527 742570 : queryDesc->totaltime = NULL;
528 742570 : }
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 768397 : ExecCheckPermissions(List *rangeTable, List *rteperminfos,
585 : bool ereport_on_violation)
586 : {
587 : ListCell *l;
588 768397 : 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 1547569 : foreach(l, rteperminfos)
622 : {
623 780081 : RTEPermissionInfo *perminfo = lfirst_node(RTEPermissionInfo, l);
624 :
625 : Assert(OidIsValid(perminfo->relid));
626 780081 : result = ExecCheckOneRelPerms(perminfo);
627 780081 : if (!result)
628 : {
629 909 : if (ereport_on_violation)
630 901 : aclcheck_error(ACLCHECK_NO_PRIV,
631 901 : get_relkind_objtype(get_rel_relkind(perminfo->relid)),
632 901 : get_rel_name(perminfo->relid));
633 8 : return false;
634 : }
635 : }
636 :
637 767488 : if (ExecutorCheckPerms_hook)
638 6 : result = (*ExecutorCheckPerms_hook) (rangeTable, rteperminfos,
639 : ereport_on_violation);
640 767488 : return result;
641 : }
642 :
643 : /*
644 : * ExecCheckOneRelPerms
645 : * Check access permissions for a single relation.
646 : */
647 : bool
648 796558 : ExecCheckOneRelPerms(RTEPermissionInfo *perminfo)
649 : {
650 : AclMode requiredPerms;
651 : AclMode relPerms;
652 : AclMode remainingPerms;
653 : Oid userid;
654 796558 : Oid relOid = perminfo->relid;
655 :
656 796558 : 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 1593116 : userid = OidIsValid(perminfo->checkAsUser) ?
668 796558 : 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 796558 : relPerms = pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL);
676 796558 : remainingPerms = requiredPerms & ~relPerms;
677 796558 : if (remainingPerms != 0)
678 : {
679 2035 : 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 2035 : 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 1931 : 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 1087 : 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 1738 : while ((col = bms_next_member(perminfo->selectedCols, col)) >= 0)
710 : {
711 : /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
712 1346 : AttrNumber attno = col + FirstLowInvalidHeapAttributeNumber;
713 :
714 1346 : 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 1302 : if (pg_attribute_aclcheck(relOid, attno, userid,
724 : ACL_SELECT) != ACLCHECK_OK)
725 643 : 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 1236 : if (remainingPerms & ACL_INSERT &&
735 220 : !ExecCheckPermissionsModified(relOid,
736 : userid,
737 : perminfo->insertedCols,
738 : ACL_INSERT))
739 116 : return false;
740 :
741 1120 : if (remainingPerms & ACL_UPDATE &&
742 821 : !ExecCheckPermissionsModified(relOid,
743 : userid,
744 : perminfo->updatedCols,
745 : ACL_UPDATE))
746 260 : return false;
747 : }
748 795383 : 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 1041 : ExecCheckPermissionsModified(Oid relOid, Oid userid, Bitmapset *modifiedCols,
758 : AclMode requiredPerms)
759 : {
760 1041 : 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 1041 : 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 1764 : while ((col = bms_next_member(modifiedCols, col)) >= 0)
775 : {
776 : /* bit #s are offset by FirstLowInvalidHeapAttributeNumber */
777 1099 : AttrNumber attno = col + FirstLowInvalidHeapAttributeNumber;
778 :
779 1099 : 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 1099 : if (pg_attribute_aclcheck(relOid, attno, userid,
787 : requiredPerms) != ACLCHECK_OK)
788 340 : return false;
789 : }
790 : }
791 665 : 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 36810 : 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 108346 : foreach(l, plannedstmt->permInfos)
813 : {
814 71546 : RTEPermissionInfo *perminfo = lfirst_node(RTEPermissionInfo, l);
815 :
816 71546 : if ((perminfo->requiredPerms & (~ACL_SELECT)) == 0)
817 71528 : continue;
818 :
819 18 : if (isTempNamespace(get_rel_namespace(perminfo->relid)))
820 8 : continue;
821 :
822 10 : PreventCommandIfReadOnly(CreateCommandName((Node *) plannedstmt));
823 : }
824 :
825 36800 : if (plannedstmt->commandType != CMD_SELECT || plannedstmt->hasModifyingCTE)
826 8 : PreventCommandIfParallelMode(CreateCommandName((Node *) plannedstmt));
827 36800 : }
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 761610 : InitPlan(QueryDesc *queryDesc, int eflags)
839 : {
840 761610 : CmdType operation = queryDesc->operation;
841 761610 : PlannedStmt *plannedstmt = queryDesc->plannedstmt;
842 761610 : Plan *plan = plannedstmt->planTree;
843 761610 : List *rangeTable = plannedstmt->rtable;
844 761610 : EState *estate = queryDesc->estate;
845 : PlanState *planstate;
846 : TupleDesc tupType;
847 : ListCell *l;
848 : int i;
849 :
850 : /*
851 : * Do permissions checks
852 : */
853 761610 : ExecCheckPermissions(rangeTable, plannedstmt->permInfos, true);
854 :
855 : /*
856 : * initialize the node's execution state
857 : */
858 760765 : ExecInitRangeTable(estate, rangeTable, plannedstmt->permInfos,
859 760765 : bms_copy(plannedstmt->unprunableRelids));
860 :
861 760765 : estate->es_plannedstmt = plannedstmt;
862 760765 : 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 760765 : ExecDoInitialPruning(estate);
874 :
875 : /*
876 : * Next, build the ExecRowMark array from the PlanRowMark(s), if any.
877 : */
878 760765 : if (plannedstmt->rowMarks)
879 : {
880 409190 : estate->es_rowmarks = (ExecRowMark **)
881 409190 : palloc0_array(ExecRowMark *, estate->es_range_table_size);
882 820594 : foreach(l, plannedstmt->rowMarks)
883 : {
884 411408 : PlanRowMark *rc = (PlanRowMark *) lfirst(l);
885 411408 : 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 411408 : 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 410130 : if (rte->rtekind == RTE_RELATION &&
899 409761 : !bms_is_member(rc->rti, estate->es_unpruned_relids))
900 48 : continue;
901 :
902 : /* get relation's OID (will produce InvalidOid if subquery) */
903 410082 : relid = rte->relid;
904 :
905 : /* open relation, if we need to access it for this mark type */
906 410082 : switch (rc->markType)
907 : {
908 409603 : 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 409603 : relation = ExecGetRangeTableRelation(estate, rc->rti, false);
914 409603 : break;
915 479 : case ROW_MARK_COPY:
916 : /* no physical table access is required */
917 479 : relation = NULL;
918 479 : 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 410082 : if (relation)
927 409603 : CheckValidRowMarkRel(relation, rc->markType);
928 :
929 410078 : erm = palloc_object(ExecRowMark);
930 410078 : erm->relation = relation;
931 410078 : erm->relid = relid;
932 410078 : erm->rti = rc->rti;
933 410078 : erm->prti = rc->prti;
934 410078 : erm->rowmarkId = rc->rowmarkId;
935 410078 : erm->markType = rc->markType;
936 410078 : erm->strength = rc->strength;
937 410078 : erm->waitPolicy = rc->waitPolicy;
938 410078 : erm->ermActive = false;
939 410078 : ItemPointerSetInvalid(&(erm->curCtid));
940 410078 : 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 410078 : estate->es_rowmarks[erm->rti - 1] = erm;
946 : }
947 : }
948 :
949 : /*
950 : * Initialize the executor's tuple table to empty.
951 : */
952 760761 : estate->es_tupleTable = NIL;
953 :
954 : /* signal that this EState is not used for EPQ */
955 760761 : 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 760761 : i = 1; /* subplan indices count from 1 */
964 791188 : foreach(l, plannedstmt->subplans)
965 : {
966 30427 : 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 30427 : sp_eflags = eflags
976 : & ~(EXEC_FLAG_REWIND | EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK);
977 30427 : if (bms_is_member(i, plannedstmt->rewindPlanIDs))
978 36 : sp_eflags |= EXEC_FLAG_REWIND;
979 :
980 30427 : subplanstate = ExecInitNode(subplan, estate, sp_eflags);
981 :
982 30427 : estate->es_subplanstates = lappend(estate->es_subplanstates,
983 : subplanstate);
984 :
985 30427 : 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 760761 : planstate = ExecInitNode(plan, estate, eflags);
994 :
995 : /*
996 : * Get the tuple descriptor describing the type of tuples to return.
997 : */
998 760475 : 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 760475 : if (operation == CMD_SELECT)
1005 : {
1006 687397 : bool junk_filter_needed = false;
1007 : ListCell *tlist;
1008 :
1009 1868535 : foreach(tlist, plan->targetlist)
1010 : {
1011 1597882 : TargetEntry *tle = (TargetEntry *) lfirst(tlist);
1012 :
1013 1597882 : if (tle->resjunk)
1014 : {
1015 416744 : junk_filter_needed = true;
1016 416744 : break;
1017 : }
1018 : }
1019 :
1020 687397 : if (junk_filter_needed)
1021 : {
1022 : JunkFilter *j;
1023 : TupleTableSlot *slot;
1024 :
1025 416744 : slot = ExecInitExtraTupleSlot(estate, NULL, &TTSOpsVirtual);
1026 416744 : j = ExecInitJunkFilter(planstate->plan->targetlist,
1027 : slot);
1028 416744 : estate->es_junkFilter = j;
1029 :
1030 : /* Want to return the cleaned tuple type */
1031 416744 : tupType = j->jf_cleanTupType;
1032 : }
1033 : }
1034 :
1035 760475 : queryDesc->tupDesc = tupType;
1036 760475 : queryDesc->planstate = planstate;
1037 760475 : }
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 82237 : CheckValidResultRel(ResultRelInfo *resultRelInfo, CmdType operation,
1057 : OnConflictAction onConflictAction, List *mergeActions)
1058 : {
1059 82237 : 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 82237 : switch (resultRel->rd_rel->relkind)
1067 : {
1068 81539 : 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 81539 : if (operation == CMD_MERGE)
1076 4330 : foreach_node(MergeAction, action, mergeActions)
1077 2020 : CheckCmdReplicaIdentity(resultRel, action->commandType);
1078 : else
1079 80376 : CheckCmdReplicaIdentity(resultRel, operation);
1080 :
1081 : /*
1082 : * For INSERT ON CONFLICT DO UPDATE, additionally check that the
1083 : * target relation supports UPDATE.
1084 : */
1085 81329 : if (onConflictAction == ONCONFLICT_UPDATE)
1086 776 : CheckCmdReplicaIdentity(resultRel, CMD_UPDATE);
1087 81321 : 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 82010 : }
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 409603 : CheckValidRowMarkRel(Relation rel, RowMarkType markType)
1191 : {
1192 : FdwRoutine *fdwroutine;
1193 :
1194 409603 : switch (rel->rd_rel->relkind)
1195 : {
1196 409595 : case RELKIND_RELATION:
1197 : case RELKIND_PARTITIONED_TABLE:
1198 : /* OK */
1199 409595 : 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 409599 : }
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 241607 : InitResultRelInfo(ResultRelInfo *resultRelInfo,
1263 : Relation resultRelationDesc,
1264 : Index resultRelationIndex,
1265 : ResultRelInfo *partition_root_rri,
1266 : int instrument_options)
1267 : {
1268 12321957 : MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1269 241607 : resultRelInfo->type = T_ResultRelInfo;
1270 241607 : resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1271 241607 : resultRelInfo->ri_RelationDesc = resultRelationDesc;
1272 241607 : resultRelInfo->ri_NumIndices = 0;
1273 241607 : resultRelInfo->ri_IndexRelationDescs = NULL;
1274 241607 : resultRelInfo->ri_IndexRelationInfo = NULL;
1275 241607 : resultRelInfo->ri_needLockTagTuple =
1276 241607 : IsInplaceUpdateRelation(resultRelationDesc);
1277 : /* make a copy so as not to depend on relcache info not changing... */
1278 241607 : resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1279 241607 : if (resultRelInfo->ri_TrigDesc)
1280 : {
1281 12104 : int n = resultRelInfo->ri_TrigDesc->numtriggers;
1282 :
1283 12104 : resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1284 12104 : palloc0_array(FmgrInfo, n);
1285 12104 : resultRelInfo->ri_TrigWhenExprs = (ExprState **)
1286 12104 : palloc0_array(ExprState *, n);
1287 12104 : if (instrument_options)
1288 0 : resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options, false);
1289 : }
1290 : else
1291 : {
1292 229503 : resultRelInfo->ri_TrigFunctions = NULL;
1293 229503 : resultRelInfo->ri_TrigWhenExprs = NULL;
1294 229503 : resultRelInfo->ri_TrigInstrument = NULL;
1295 : }
1296 241607 : if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1297 360 : resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1298 : else
1299 241247 : resultRelInfo->ri_FdwRoutine = NULL;
1300 :
1301 : /* The following fields are set later if needed */
1302 241607 : resultRelInfo->ri_RowIdAttNo = 0;
1303 241607 : resultRelInfo->ri_extraUpdatedCols = NULL;
1304 241607 : resultRelInfo->ri_projectNew = NULL;
1305 241607 : resultRelInfo->ri_newTupleSlot = NULL;
1306 241607 : resultRelInfo->ri_oldTupleSlot = NULL;
1307 241607 : resultRelInfo->ri_projectNewInfoValid = false;
1308 241607 : resultRelInfo->ri_FdwState = NULL;
1309 241607 : resultRelInfo->ri_usesFdwDirectModify = false;
1310 241607 : resultRelInfo->ri_CheckConstraintExprs = NULL;
1311 241607 : resultRelInfo->ri_GenVirtualNotNullConstraintExprs = NULL;
1312 241607 : resultRelInfo->ri_GeneratedExprsI = NULL;
1313 241607 : resultRelInfo->ri_GeneratedExprsU = NULL;
1314 241607 : resultRelInfo->ri_projectReturning = NULL;
1315 241607 : resultRelInfo->ri_onConflictArbiterIndexes = NIL;
1316 241607 : resultRelInfo->ri_onConflict = NULL;
1317 241607 : resultRelInfo->ri_ReturningSlot = NULL;
1318 241607 : resultRelInfo->ri_TrigOldSlot = NULL;
1319 241607 : resultRelInfo->ri_TrigNewSlot = NULL;
1320 241607 : resultRelInfo->ri_AllNullSlot = NULL;
1321 241607 : resultRelInfo->ri_MergeActions[MERGE_WHEN_MATCHED] = NIL;
1322 241607 : resultRelInfo->ri_MergeActions[MERGE_WHEN_NOT_MATCHED_BY_SOURCE] = NIL;
1323 241607 : resultRelInfo->ri_MergeActions[MERGE_WHEN_NOT_MATCHED_BY_TARGET] = NIL;
1324 241607 : resultRelInfo->ri_MergeJoinCondition = NULL;
1325 :
1326 : /*
1327 : * Only ExecInitPartitionInfo() and ExecInitPartitionDispatchInfo() pass
1328 : * non-NULL partition_root_rri. For child relations that are part of the
1329 : * initial query rather than being dynamically added by tuple routing,
1330 : * this field is filled in ExecInitModifyTable().
1331 : */
1332 241607 : resultRelInfo->ri_RootResultRelInfo = partition_root_rri;
1333 : /* Set by ExecGetRootToChildMap */
1334 241607 : resultRelInfo->ri_RootToChildMap = NULL;
1335 241607 : resultRelInfo->ri_RootToChildMapValid = false;
1336 : /* Set by ExecInitRoutingInfo */
1337 241607 : resultRelInfo->ri_PartitionTupleSlot = NULL;
1338 241607 : resultRelInfo->ri_ChildToRootMap = NULL;
1339 241607 : resultRelInfo->ri_ChildToRootMapValid = false;
1340 241607 : resultRelInfo->ri_CopyMultiInsertBuffer = NULL;
1341 241607 : }
1342 :
1343 : /*
1344 : * ExecGetTriggerResultRel
1345 : * Get a ResultRelInfo for a trigger target relation.
1346 : *
1347 : * Most of the time, triggers are fired on one of the result relations of the
1348 : * query, and so we can just return a suitable one we already made and stored
1349 : * in the es_opened_result_relations or es_tuple_routing_result_relations
1350 : * Lists.
1351 : *
1352 : * However, it is sometimes necessary to fire triggers on other relations;
1353 : * this happens mainly when an RI update trigger queues additional triggers
1354 : * on other relations, which will be processed in the context of the outer
1355 : * query. For efficiency's sake, we want to have a ResultRelInfo for those
1356 : * triggers too; that can avoid repeated re-opening of the relation. (It
1357 : * also provides a way for EXPLAIN ANALYZE to report the runtimes of such
1358 : * triggers.) So we make additional ResultRelInfo's as needed, and save them
1359 : * in es_trig_target_relations.
1360 : */
1361 : ResultRelInfo *
1362 5401 : ExecGetTriggerResultRel(EState *estate, Oid relid,
1363 : ResultRelInfo *rootRelInfo)
1364 : {
1365 : ResultRelInfo *rInfo;
1366 : ListCell *l;
1367 : Relation rel;
1368 : MemoryContext oldcontext;
1369 :
1370 : /*
1371 : * Before creating a new ResultRelInfo, check if we've already made and
1372 : * cached one for this relation. We must ensure that the given
1373 : * 'rootRelInfo' matches the one stored in the cached ResultRelInfo as
1374 : * trigger handling for partitions can result in mixed requirements for
1375 : * what ri_RootResultRelInfo is set to.
1376 : */
1377 :
1378 : /* Search through the query result relations */
1379 7278 : foreach(l, estate->es_opened_result_relations)
1380 : {
1381 6009 : rInfo = lfirst(l);
1382 6009 : if (RelationGetRelid(rInfo->ri_RelationDesc) == relid &&
1383 4394 : rInfo->ri_RootResultRelInfo == rootRelInfo)
1384 4132 : return rInfo;
1385 : }
1386 :
1387 : /*
1388 : * Search through the result relations that were created during tuple
1389 : * routing, if any.
1390 : */
1391 2005 : foreach(l, estate->es_tuple_routing_result_relations)
1392 : {
1393 756 : rInfo = (ResultRelInfo *) lfirst(l);
1394 756 : if (RelationGetRelid(rInfo->ri_RelationDesc) == relid &&
1395 491 : rInfo->ri_RootResultRelInfo == rootRelInfo)
1396 20 : return rInfo;
1397 : }
1398 :
1399 : /* Nope, but maybe we already made an extra ResultRelInfo for it */
1400 1778 : foreach(l, estate->es_trig_target_relations)
1401 : {
1402 541 : rInfo = (ResultRelInfo *) lfirst(l);
1403 541 : if (RelationGetRelid(rInfo->ri_RelationDesc) == relid &&
1404 24 : rInfo->ri_RootResultRelInfo == rootRelInfo)
1405 12 : return rInfo;
1406 : }
1407 : /* Nope, so we need a new one */
1408 :
1409 : /*
1410 : * Open the target relation's relcache entry. We assume that an
1411 : * appropriate lock is still held by the backend from whenever the trigger
1412 : * event got queued, so we need take no new lock here. Also, we need not
1413 : * recheck the relkind, so no need for CheckValidResultRel.
1414 : */
1415 1237 : rel = table_open(relid, NoLock);
1416 :
1417 : /*
1418 : * Make the new entry in the right context.
1419 : */
1420 1237 : oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1421 1237 : rInfo = makeNode(ResultRelInfo);
1422 1237 : InitResultRelInfo(rInfo,
1423 : rel,
1424 : 0, /* dummy rangetable index */
1425 : rootRelInfo,
1426 : estate->es_instrument);
1427 1237 : estate->es_trig_target_relations =
1428 1237 : lappend(estate->es_trig_target_relations, rInfo);
1429 1237 : MemoryContextSwitchTo(oldcontext);
1430 :
1431 : /*
1432 : * Currently, we don't need any index information in ResultRelInfos used
1433 : * only for triggers, so no need to call ExecOpenIndices.
1434 : */
1435 :
1436 1237 : return rInfo;
1437 : }
1438 :
1439 : /*
1440 : * Return the ancestor relations of a given leaf partition result relation
1441 : * up to and including the query's root target relation.
1442 : *
1443 : * These work much like the ones opened by ExecGetTriggerResultRel, except
1444 : * that we need to keep them in a separate list.
1445 : *
1446 : * These are closed by ExecCloseResultRelations.
1447 : */
1448 : List *
1449 202 : ExecGetAncestorResultRels(EState *estate, ResultRelInfo *resultRelInfo)
1450 : {
1451 202 : ResultRelInfo *rootRelInfo = resultRelInfo->ri_RootResultRelInfo;
1452 202 : Relation partRel = resultRelInfo->ri_RelationDesc;
1453 : Oid rootRelOid;
1454 :
1455 202 : if (!partRel->rd_rel->relispartition)
1456 0 : elog(ERROR, "cannot find ancestors of a non-partition result relation");
1457 : Assert(rootRelInfo != NULL);
1458 202 : rootRelOid = RelationGetRelid(rootRelInfo->ri_RelationDesc);
1459 202 : if (resultRelInfo->ri_ancestorResultRels == NIL)
1460 : {
1461 : ListCell *lc;
1462 158 : List *oids = get_partition_ancestors(RelationGetRelid(partRel));
1463 158 : List *ancResultRels = NIL;
1464 :
1465 202 : foreach(lc, oids)
1466 : {
1467 202 : Oid ancOid = lfirst_oid(lc);
1468 : Relation ancRel;
1469 : ResultRelInfo *rInfo;
1470 :
1471 : /*
1472 : * Ignore the root ancestor here, and use ri_RootResultRelInfo
1473 : * (below) for it instead. Also, we stop climbing up the
1474 : * hierarchy when we find the table that was mentioned in the
1475 : * query.
1476 : */
1477 202 : if (ancOid == rootRelOid)
1478 158 : break;
1479 :
1480 : /*
1481 : * All ancestors up to the root target relation must have been
1482 : * locked by the planner or AcquireExecutorLocks().
1483 : */
1484 44 : ancRel = table_open(ancOid, NoLock);
1485 44 : rInfo = makeNode(ResultRelInfo);
1486 :
1487 : /* dummy rangetable index */
1488 44 : InitResultRelInfo(rInfo, ancRel, 0, NULL,
1489 : estate->es_instrument);
1490 44 : ancResultRels = lappend(ancResultRels, rInfo);
1491 : }
1492 158 : ancResultRels = lappend(ancResultRels, rootRelInfo);
1493 158 : resultRelInfo->ri_ancestorResultRels = ancResultRels;
1494 : }
1495 :
1496 : /* We must have found some ancestor */
1497 : Assert(resultRelInfo->ri_ancestorResultRels != NIL);
1498 :
1499 202 : return resultRelInfo->ri_ancestorResultRels;
1500 : }
1501 :
1502 : /* ----------------------------------------------------------------
1503 : * ExecPostprocessPlan
1504 : *
1505 : * Give plan nodes a final chance to execute before shutdown
1506 : * ----------------------------------------------------------------
1507 : */
1508 : static void
1509 729404 : ExecPostprocessPlan(EState *estate)
1510 : {
1511 : ListCell *lc;
1512 :
1513 : /*
1514 : * Make sure nodes run forward.
1515 : */
1516 729404 : estate->es_direction = ForwardScanDirection;
1517 :
1518 : /*
1519 : * Run any secondary ModifyTable nodes to completion, in case the main
1520 : * query did not fetch all rows from them. (We do this to ensure that
1521 : * such nodes have predictable results.)
1522 : */
1523 729985 : foreach(lc, estate->es_auxmodifytables)
1524 : {
1525 581 : PlanState *ps = (PlanState *) lfirst(lc);
1526 :
1527 : for (;;)
1528 100 : {
1529 : TupleTableSlot *slot;
1530 :
1531 : /* Reset the per-output-tuple exprcontext each time */
1532 681 : ResetPerTupleExprContext(estate);
1533 :
1534 681 : slot = ExecProcNode(ps);
1535 :
1536 681 : if (TupIsNull(slot))
1537 : break;
1538 : }
1539 : }
1540 729404 : }
1541 :
1542 : /* ----------------------------------------------------------------
1543 : * ExecEndPlan
1544 : *
1545 : * Cleans up the query plan -- closes files and frees up storage
1546 : *
1547 : * NOTE: we are no longer very worried about freeing storage per se
1548 : * in this code; FreeExecutorState should be guaranteed to release all
1549 : * memory that needs to be released. What we are worried about doing
1550 : * is closing relations and dropping buffer pins. Thus, for example,
1551 : * tuple tables must be cleared or dropped to ensure pins are released.
1552 : * ----------------------------------------------------------------
1553 : */
1554 : static void
1555 742570 : ExecEndPlan(PlanState *planstate, EState *estate)
1556 : {
1557 : ListCell *l;
1558 :
1559 : /*
1560 : * shut down the node-type-specific query processing
1561 : */
1562 742570 : ExecEndNode(planstate);
1563 :
1564 : /*
1565 : * for subplans too
1566 : */
1567 772582 : foreach(l, estate->es_subplanstates)
1568 : {
1569 30012 : PlanState *subplanstate = (PlanState *) lfirst(l);
1570 :
1571 30012 : ExecEndNode(subplanstate);
1572 : }
1573 :
1574 : /*
1575 : * destroy the executor's tuple table. Actually we only care about
1576 : * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1577 : * the TupleTableSlots, since the containing memory context is about to go
1578 : * away anyway.
1579 : */
1580 742570 : ExecResetTupleTable(estate->es_tupleTable, false);
1581 :
1582 : /*
1583 : * Close any Relations that have been opened for range table entries or
1584 : * result relations.
1585 : */
1586 742570 : ExecCloseResultRelations(estate);
1587 742570 : ExecCloseRangeTableRelations(estate);
1588 742570 : }
1589 :
1590 : /*
1591 : * Close any relations that have been opened for ResultRelInfos.
1592 : */
1593 : void
1594 743770 : ExecCloseResultRelations(EState *estate)
1595 : {
1596 : ListCell *l;
1597 :
1598 : /*
1599 : * close indexes of result relation(s) if any. (Rels themselves are
1600 : * closed in ExecCloseRangeTableRelations())
1601 : *
1602 : * In addition, close the stub RTs that may be in each resultrel's
1603 : * ri_ancestorResultRels.
1604 : */
1605 818006 : foreach(l, estate->es_opened_result_relations)
1606 : {
1607 74236 : ResultRelInfo *resultRelInfo = lfirst(l);
1608 : ListCell *lc;
1609 :
1610 74236 : ExecCloseIndices(resultRelInfo);
1611 74406 : foreach(lc, resultRelInfo->ri_ancestorResultRels)
1612 : {
1613 170 : ResultRelInfo *rInfo = lfirst(lc);
1614 :
1615 : /*
1616 : * Ancestors with RTI > 0 (should only be the root ancestor) are
1617 : * closed by ExecCloseRangeTableRelations.
1618 : */
1619 170 : if (rInfo->ri_RangeTableIndex > 0)
1620 138 : continue;
1621 :
1622 32 : table_close(rInfo->ri_RelationDesc, NoLock);
1623 : }
1624 : }
1625 :
1626 : /* Close any relations that have been opened by ExecGetTriggerResultRel(). */
1627 744637 : foreach(l, estate->es_trig_target_relations)
1628 : {
1629 867 : ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
1630 :
1631 : /*
1632 : * Assert this is a "dummy" ResultRelInfo, see above. Otherwise we
1633 : * might be issuing a duplicate close against a Relation opened by
1634 : * ExecGetRangeTableRelation.
1635 : */
1636 : Assert(resultRelInfo->ri_RangeTableIndex == 0);
1637 :
1638 : /*
1639 : * Since ExecGetTriggerResultRel doesn't call ExecOpenIndices for
1640 : * these rels, we needn't call ExecCloseIndices either.
1641 : */
1642 : Assert(resultRelInfo->ri_NumIndices == 0);
1643 :
1644 867 : table_close(resultRelInfo->ri_RelationDesc, NoLock);
1645 : }
1646 743770 : }
1647 :
1648 : /*
1649 : * Close all relations opened by ExecGetRangeTableRelation().
1650 : *
1651 : * We do not release any locks we might hold on those rels.
1652 : */
1653 : void
1654 743522 : ExecCloseRangeTableRelations(EState *estate)
1655 : {
1656 : int i;
1657 :
1658 1860592 : for (i = 0; i < estate->es_range_table_size; i++)
1659 : {
1660 1117070 : if (estate->es_relations[i])
1661 754939 : table_close(estate->es_relations[i], NoLock);
1662 : }
1663 743522 : }
1664 :
1665 : /* ----------------------------------------------------------------
1666 : * ExecutePlan
1667 : *
1668 : * Processes the query plan until we have retrieved 'numberTuples' tuples,
1669 : * moving in the specified direction.
1670 : *
1671 : * Runs to completion if numberTuples is 0
1672 : * ----------------------------------------------------------------
1673 : */
1674 : static void
1675 754016 : ExecutePlan(QueryDesc *queryDesc,
1676 : CmdType operation,
1677 : bool sendTuples,
1678 : uint64 numberTuples,
1679 : ScanDirection direction,
1680 : DestReceiver *dest)
1681 : {
1682 754016 : EState *estate = queryDesc->estate;
1683 754016 : PlanState *planstate = queryDesc->planstate;
1684 : bool use_parallel_mode;
1685 : TupleTableSlot *slot;
1686 : uint64 current_tuple_count;
1687 :
1688 : /*
1689 : * initialize local variables
1690 : */
1691 754016 : current_tuple_count = 0;
1692 :
1693 : /*
1694 : * Set the direction.
1695 : */
1696 754016 : estate->es_direction = direction;
1697 :
1698 : /*
1699 : * Set up parallel mode if appropriate.
1700 : *
1701 : * Parallel mode only supports complete execution of a plan. If we've
1702 : * already partially executed it, or if the caller asks us to exit early,
1703 : * we must force the plan to run without parallelism.
1704 : */
1705 754016 : if (queryDesc->already_executed || numberTuples != 0)
1706 476855 : use_parallel_mode = false;
1707 : else
1708 277161 : use_parallel_mode = queryDesc->plannedstmt->parallelModeNeeded;
1709 754016 : queryDesc->already_executed = true;
1710 :
1711 754016 : estate->es_use_parallel_mode = use_parallel_mode;
1712 754016 : if (use_parallel_mode)
1713 502 : EnterParallelMode();
1714 :
1715 : /*
1716 : * Loop until we've processed the proper number of tuples from the plan.
1717 : */
1718 : for (;;)
1719 : {
1720 : /* Reset the per-output-tuple exprcontext */
1721 8736320 : ResetPerTupleExprContext(estate);
1722 :
1723 : /*
1724 : * Execute the plan and obtain a tuple
1725 : */
1726 8736320 : slot = ExecProcNode(planstate);
1727 :
1728 : /*
1729 : * if the tuple is null, then we assume there is nothing more to
1730 : * process so we just end the loop...
1731 : */
1732 8720547 : if (TupIsNull(slot))
1733 : break;
1734 :
1735 : /*
1736 : * If we have a junk filter, then project a new tuple with the junk
1737 : * removed.
1738 : *
1739 : * Store this new "clean" tuple in the junkfilter's resultSlot.
1740 : * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1741 : * because that tuple slot has the wrong descriptor.)
1742 : */
1743 8438004 : if (estate->es_junkFilter != NULL)
1744 577693 : slot = ExecFilterJunk(estate->es_junkFilter, slot);
1745 :
1746 : /*
1747 : * If we are supposed to send the tuple somewhere, do so. (In
1748 : * practice, this is probably always the case at this point.)
1749 : */
1750 8438004 : if (sendTuples)
1751 : {
1752 : /*
1753 : * If we are not able to send the tuple, we assume the destination
1754 : * has closed and no more tuples can be sent. If that's the case,
1755 : * end the loop.
1756 : */
1757 8438004 : if (!dest->receiveSlot(slot, dest))
1758 0 : break;
1759 : }
1760 :
1761 : /*
1762 : * Count tuples processed, if this is a SELECT. (For other operation
1763 : * types, the ModifyTable plan node must count the appropriate
1764 : * events.)
1765 : */
1766 8437996 : if (operation == CMD_SELECT)
1767 8433376 : (estate->es_processed)++;
1768 :
1769 : /*
1770 : * check our tuple count.. if we've processed the proper number then
1771 : * quit, else loop again and process more tuples. Zero numberTuples
1772 : * means no limit.
1773 : */
1774 8437996 : current_tuple_count++;
1775 8437996 : if (numberTuples && numberTuples == current_tuple_count)
1776 455692 : break;
1777 : }
1778 :
1779 : /*
1780 : * If we know we won't need to back up, we can release resources at this
1781 : * point.
1782 : */
1783 738235 : if (!(estate->es_top_eflags & EXEC_FLAG_BACKWARD))
1784 733773 : ExecShutdownNode(planstate);
1785 :
1786 738235 : if (use_parallel_mode)
1787 494 : ExitParallelMode();
1788 738235 : }
1789 :
1790 :
1791 : /*
1792 : * ExecRelCheck --- check that tuple meets check constraints for result relation
1793 : *
1794 : * Returns NULL if OK, else name of failed check constraint
1795 : */
1796 : static const char *
1797 1823 : ExecRelCheck(ResultRelInfo *resultRelInfo,
1798 : TupleTableSlot *slot, EState *estate)
1799 : {
1800 1823 : Relation rel = resultRelInfo->ri_RelationDesc;
1801 1823 : int ncheck = rel->rd_att->constr->num_check;
1802 1823 : ConstrCheck *check = rel->rd_att->constr->check;
1803 : ExprContext *econtext;
1804 : MemoryContext oldContext;
1805 :
1806 : /*
1807 : * CheckNNConstraintFetch let this pass with only a warning, but now we
1808 : * should fail rather than possibly failing to enforce an important
1809 : * constraint.
1810 : */
1811 1823 : if (ncheck != rel->rd_rel->relchecks)
1812 0 : elog(ERROR, "%d pg_constraint record(s) missing for relation \"%s\"",
1813 : rel->rd_rel->relchecks - ncheck, RelationGetRelationName(rel));
1814 :
1815 : /*
1816 : * If first time through for this result relation, build expression
1817 : * nodetrees for rel's constraint expressions. Keep them in the per-query
1818 : * memory context so they'll survive throughout the query.
1819 : */
1820 1823 : if (resultRelInfo->ri_CheckConstraintExprs == NULL)
1821 : {
1822 950 : oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1823 950 : resultRelInfo->ri_CheckConstraintExprs = palloc0_array(ExprState *, ncheck);
1824 2497 : for (int i = 0; i < ncheck; i++)
1825 : {
1826 : Expr *checkconstr;
1827 :
1828 : /* Skip not enforced constraint */
1829 1551 : if (!check[i].ccenforced)
1830 216 : continue;
1831 :
1832 1335 : checkconstr = stringToNode(check[i].ccbin);
1833 1335 : checkconstr = (Expr *) expand_generated_columns_in_expr((Node *) checkconstr, rel, 1);
1834 1331 : resultRelInfo->ri_CheckConstraintExprs[i] =
1835 1335 : ExecPrepareExpr(checkconstr, estate);
1836 : }
1837 946 : MemoryContextSwitchTo(oldContext);
1838 : }
1839 :
1840 : /*
1841 : * We will use the EState's per-tuple context for evaluating constraint
1842 : * expressions (creating it if it's not already there).
1843 : */
1844 1819 : econtext = GetPerTupleExprContext(estate);
1845 :
1846 : /* Arrange for econtext's scan tuple to be the tuple under test */
1847 1819 : econtext->ecxt_scantuple = slot;
1848 :
1849 : /* And evaluate the constraints */
1850 4227 : for (int i = 0; i < ncheck; i++)
1851 : {
1852 2716 : ExprState *checkconstr = resultRelInfo->ri_CheckConstraintExprs[i];
1853 :
1854 : /*
1855 : * NOTE: SQL specifies that a NULL result from a constraint expression
1856 : * is not to be treated as a failure. Therefore, use ExecCheck not
1857 : * ExecQual.
1858 : */
1859 2716 : if (checkconstr && !ExecCheck(checkconstr, econtext))
1860 308 : return check[i].ccname;
1861 : }
1862 :
1863 : /* NULL result means no error */
1864 1511 : return NULL;
1865 : }
1866 :
1867 : /*
1868 : * ExecPartitionCheck --- check that tuple meets the partition constraint.
1869 : *
1870 : * Returns true if it meets the partition constraint. If the constraint
1871 : * fails and we're asked to emit an error, do so and don't return; otherwise
1872 : * return false.
1873 : */
1874 : bool
1875 9619 : ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot,
1876 : EState *estate, bool emitError)
1877 : {
1878 : ExprContext *econtext;
1879 : bool success;
1880 :
1881 : /*
1882 : * If first time through, build expression state tree for the partition
1883 : * check expression. (In the corner case where the partition check
1884 : * expression is empty, ie there's a default partition and nothing else,
1885 : * we'll be fooled into executing this code each time through. But it's
1886 : * pretty darn cheap in that case, so we don't worry about it.)
1887 : */
1888 9619 : if (resultRelInfo->ri_PartitionCheckExpr == NULL)
1889 : {
1890 : /*
1891 : * Ensure that the qual tree and prepared expression are in the
1892 : * query-lifespan context.
1893 : */
1894 3445 : MemoryContext oldcxt = MemoryContextSwitchTo(estate->es_query_cxt);
1895 3445 : List *qual = RelationGetPartitionQual(resultRelInfo->ri_RelationDesc);
1896 :
1897 3445 : resultRelInfo->ri_PartitionCheckExpr = ExecPrepareCheck(qual, estate);
1898 3445 : MemoryContextSwitchTo(oldcxt);
1899 : }
1900 :
1901 : /*
1902 : * We will use the EState's per-tuple context for evaluating constraint
1903 : * expressions (creating it if it's not already there).
1904 : */
1905 9619 : econtext = GetPerTupleExprContext(estate);
1906 :
1907 : /* Arrange for econtext's scan tuple to be the tuple under test */
1908 9619 : econtext->ecxt_scantuple = slot;
1909 :
1910 : /*
1911 : * As in case of the cataloged constraints, we treat a NULL result as
1912 : * success here, not a failure.
1913 : */
1914 9619 : success = ExecCheck(resultRelInfo->ri_PartitionCheckExpr, econtext);
1915 :
1916 : /* if asked to emit error, don't actually return on failure */
1917 9619 : if (!success && emitError)
1918 134 : ExecPartitionCheckEmitError(resultRelInfo, slot, estate);
1919 :
1920 9485 : return success;
1921 : }
1922 :
1923 : /*
1924 : * ExecPartitionCheckEmitError - Form and emit an error message after a failed
1925 : * partition constraint check.
1926 : */
1927 : void
1928 166 : ExecPartitionCheckEmitError(ResultRelInfo *resultRelInfo,
1929 : TupleTableSlot *slot,
1930 : EState *estate)
1931 : {
1932 : Oid root_relid;
1933 : TupleDesc tupdesc;
1934 : char *val_desc;
1935 : Bitmapset *modifiedCols;
1936 :
1937 : /*
1938 : * If the tuple has been routed, it's been converted to the partition's
1939 : * rowtype, which might differ from the root table's. We must convert it
1940 : * back to the root table's rowtype so that val_desc in the error message
1941 : * matches the input tuple.
1942 : */
1943 166 : if (resultRelInfo->ri_RootResultRelInfo)
1944 : {
1945 13 : ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
1946 : TupleDesc old_tupdesc;
1947 : AttrMap *map;
1948 :
1949 13 : root_relid = RelationGetRelid(rootrel->ri_RelationDesc);
1950 13 : tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
1951 :
1952 13 : old_tupdesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
1953 : /* a reverse map */
1954 13 : map = build_attrmap_by_name_if_req(old_tupdesc, tupdesc, false);
1955 :
1956 : /*
1957 : * Partition-specific slot's tupdesc can't be changed, so allocate a
1958 : * new one.
1959 : */
1960 13 : if (map != NULL)
1961 5 : slot = execute_attr_map_slot(map, slot,
1962 : MakeTupleTableSlot(tupdesc, &TTSOpsVirtual, 0));
1963 13 : modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
1964 13 : ExecGetUpdatedCols(rootrel, estate));
1965 : }
1966 : else
1967 : {
1968 153 : root_relid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
1969 153 : tupdesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
1970 153 : modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
1971 153 : ExecGetUpdatedCols(resultRelInfo, estate));
1972 : }
1973 :
1974 166 : val_desc = ExecBuildSlotValueDescription(root_relid,
1975 : slot,
1976 : tupdesc,
1977 : modifiedCols,
1978 : 64);
1979 166 : ereport(ERROR,
1980 : (errcode(ERRCODE_CHECK_VIOLATION),
1981 : errmsg("new row for relation \"%s\" violates partition constraint",
1982 : RelationGetRelationName(resultRelInfo->ri_RelationDesc)),
1983 : val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
1984 : errtable(resultRelInfo->ri_RelationDesc)));
1985 : }
1986 :
1987 : /*
1988 : * ExecConstraints - check constraints of the tuple in 'slot'
1989 : *
1990 : * This checks the traditional NOT NULL and check constraints.
1991 : *
1992 : * The partition constraint is *NOT* checked.
1993 : *
1994 : * Note: 'slot' contains the tuple to check the constraints of, which may
1995 : * have been converted from the original input tuple after tuple routing.
1996 : * 'resultRelInfo' is the final result relation, after tuple routing.
1997 : */
1998 : void
1999 2847141 : ExecConstraints(ResultRelInfo *resultRelInfo,
2000 : TupleTableSlot *slot, EState *estate)
2001 : {
2002 2847141 : Relation rel = resultRelInfo->ri_RelationDesc;
2003 2847141 : TupleDesc tupdesc = RelationGetDescr(rel);
2004 2847141 : TupleConstr *constr = tupdesc->constr;
2005 : Bitmapset *modifiedCols;
2006 2847141 : List *notnull_virtual_attrs = NIL;
2007 :
2008 : Assert(constr); /* we should not be called otherwise */
2009 :
2010 : /*
2011 : * Verify not-null constraints.
2012 : *
2013 : * Not-null constraints on virtual generated columns are collected and
2014 : * checked separately below.
2015 : */
2016 2847141 : if (constr->has_not_null)
2017 : {
2018 10418928 : for (AttrNumber attnum = 1; attnum <= tupdesc->natts; attnum++)
2019 : {
2020 7575703 : Form_pg_attribute att = TupleDescAttr(tupdesc, attnum - 1);
2021 :
2022 7575703 : if (att->attnotnull && att->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
2023 60 : notnull_virtual_attrs = lappend_int(notnull_virtual_attrs, attnum);
2024 7575643 : else if (att->attnotnull && slot_attisnull(slot, attnum))
2025 209 : ReportNotNullViolationError(resultRelInfo, slot, estate, attnum);
2026 : }
2027 : }
2028 :
2029 : /*
2030 : * Verify not-null constraints on virtual generated column, if any.
2031 : */
2032 2846932 : if (notnull_virtual_attrs)
2033 : {
2034 : AttrNumber attnum;
2035 :
2036 60 : attnum = ExecRelGenVirtualNotNull(resultRelInfo, slot, estate,
2037 : notnull_virtual_attrs);
2038 60 : if (attnum != InvalidAttrNumber)
2039 28 : ReportNotNullViolationError(resultRelInfo, slot, estate, attnum);
2040 : }
2041 :
2042 : /*
2043 : * Verify check constraints.
2044 : */
2045 2846904 : if (rel->rd_rel->relchecks > 0)
2046 : {
2047 : const char *failed;
2048 :
2049 1823 : if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
2050 : {
2051 : char *val_desc;
2052 308 : Relation orig_rel = rel;
2053 :
2054 : /*
2055 : * If the tuple has been routed, it's been converted to the
2056 : * partition's rowtype, which might differ from the root table's.
2057 : * We must convert it back to the root table's rowtype so that
2058 : * val_desc shown error message matches the input tuple.
2059 : */
2060 308 : if (resultRelInfo->ri_RootResultRelInfo)
2061 : {
2062 68 : ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
2063 68 : TupleDesc old_tupdesc = RelationGetDescr(rel);
2064 : AttrMap *map;
2065 :
2066 68 : tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
2067 : /* a reverse map */
2068 68 : map = build_attrmap_by_name_if_req(old_tupdesc,
2069 : tupdesc,
2070 : false);
2071 :
2072 : /*
2073 : * Partition-specific slot's tupdesc can't be changed, so
2074 : * allocate a new one.
2075 : */
2076 68 : if (map != NULL)
2077 40 : slot = execute_attr_map_slot(map, slot,
2078 : MakeTupleTableSlot(tupdesc, &TTSOpsVirtual, 0));
2079 68 : modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
2080 68 : ExecGetUpdatedCols(rootrel, estate));
2081 68 : rel = rootrel->ri_RelationDesc;
2082 : }
2083 : else
2084 240 : modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
2085 240 : ExecGetUpdatedCols(resultRelInfo, estate));
2086 308 : val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
2087 : slot,
2088 : tupdesc,
2089 : modifiedCols,
2090 : 64);
2091 308 : ereport(ERROR,
2092 : (errcode(ERRCODE_CHECK_VIOLATION),
2093 : errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
2094 : RelationGetRelationName(orig_rel), failed),
2095 : val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2096 : errtableconstraint(orig_rel, failed)));
2097 : }
2098 : }
2099 2846592 : }
2100 :
2101 : /*
2102 : * Verify not-null constraints on virtual generated columns of the given
2103 : * tuple slot.
2104 : *
2105 : * Return value of InvalidAttrNumber means all not-null constraints on virtual
2106 : * generated columns are satisfied. A return value > 0 means a not-null
2107 : * violation happened for that attribute.
2108 : *
2109 : * notnull_virtual_attrs is the list of the attnums of virtual generated column with
2110 : * not-null constraints.
2111 : */
2112 : AttrNumber
2113 116 : ExecRelGenVirtualNotNull(ResultRelInfo *resultRelInfo, TupleTableSlot *slot,
2114 : EState *estate, List *notnull_virtual_attrs)
2115 : {
2116 116 : Relation rel = resultRelInfo->ri_RelationDesc;
2117 : ExprContext *econtext;
2118 : MemoryContext oldContext;
2119 :
2120 : /*
2121 : * We implement this by building a NullTest node for each virtual
2122 : * generated column, which we cache in resultRelInfo, and running those
2123 : * through ExecCheck().
2124 : */
2125 116 : if (resultRelInfo->ri_GenVirtualNotNullConstraintExprs == NULL)
2126 : {
2127 84 : oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
2128 84 : resultRelInfo->ri_GenVirtualNotNullConstraintExprs =
2129 84 : palloc0_array(ExprState *, list_length(notnull_virtual_attrs));
2130 :
2131 272 : foreach_int(attnum, notnull_virtual_attrs)
2132 : {
2133 104 : int i = foreach_current_index(attnum);
2134 : NullTest *nnulltest;
2135 :
2136 : /* "generated_expression IS NOT NULL" check. */
2137 104 : nnulltest = makeNode(NullTest);
2138 104 : nnulltest->arg = (Expr *) build_generation_expression(rel, attnum);
2139 104 : nnulltest->nulltesttype = IS_NOT_NULL;
2140 104 : nnulltest->argisrow = false;
2141 104 : nnulltest->location = -1;
2142 :
2143 104 : resultRelInfo->ri_GenVirtualNotNullConstraintExprs[i] =
2144 104 : ExecPrepareExpr((Expr *) nnulltest, estate);
2145 : }
2146 84 : MemoryContextSwitchTo(oldContext);
2147 : }
2148 :
2149 : /*
2150 : * We will use the EState's per-tuple context for evaluating virtual
2151 : * generated column not null constraint expressions (creating it if it's
2152 : * not already there).
2153 : */
2154 116 : econtext = GetPerTupleExprContext(estate);
2155 :
2156 : /* Arrange for econtext's scan tuple to be the tuple under test */
2157 116 : econtext->ecxt_scantuple = slot;
2158 :
2159 : /* And evaluate the check constraints for virtual generated column */
2160 288 : foreach_int(attnum, notnull_virtual_attrs)
2161 : {
2162 152 : int i = foreach_current_index(attnum);
2163 152 : ExprState *exprstate = resultRelInfo->ri_GenVirtualNotNullConstraintExprs[i];
2164 :
2165 : Assert(exprstate != NULL);
2166 152 : if (!ExecCheck(exprstate, econtext))
2167 48 : return attnum;
2168 : }
2169 :
2170 : /* InvalidAttrNumber result means no error */
2171 68 : return InvalidAttrNumber;
2172 : }
2173 :
2174 : /*
2175 : * Report a violation of a not-null constraint that was already detected.
2176 : */
2177 : static void
2178 237 : ReportNotNullViolationError(ResultRelInfo *resultRelInfo, TupleTableSlot *slot,
2179 : EState *estate, int attnum)
2180 : {
2181 : Bitmapset *modifiedCols;
2182 : char *val_desc;
2183 237 : Relation rel = resultRelInfo->ri_RelationDesc;
2184 237 : Relation orig_rel = rel;
2185 237 : TupleDesc tupdesc = RelationGetDescr(rel);
2186 237 : TupleDesc orig_tupdesc = RelationGetDescr(rel);
2187 237 : Form_pg_attribute att = TupleDescAttr(tupdesc, attnum - 1);
2188 :
2189 : Assert(attnum > 0);
2190 :
2191 : /*
2192 : * If the tuple has been routed, it's been converted to the partition's
2193 : * rowtype, which might differ from the root table's. We must convert it
2194 : * back to the root table's rowtype so that val_desc shown error message
2195 : * matches the input tuple.
2196 : */
2197 237 : if (resultRelInfo->ri_RootResultRelInfo)
2198 : {
2199 48 : ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
2200 : AttrMap *map;
2201 :
2202 48 : tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
2203 : /* a reverse map */
2204 48 : map = build_attrmap_by_name_if_req(orig_tupdesc,
2205 : tupdesc,
2206 : false);
2207 :
2208 : /*
2209 : * Partition-specific slot's tupdesc can't be changed, so allocate a
2210 : * new one.
2211 : */
2212 48 : if (map != NULL)
2213 28 : slot = execute_attr_map_slot(map, slot,
2214 : MakeTupleTableSlot(tupdesc, &TTSOpsVirtual, 0));
2215 48 : modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
2216 48 : ExecGetUpdatedCols(rootrel, estate));
2217 48 : rel = rootrel->ri_RelationDesc;
2218 : }
2219 : else
2220 189 : modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
2221 189 : ExecGetUpdatedCols(resultRelInfo, estate));
2222 :
2223 237 : val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
2224 : slot,
2225 : tupdesc,
2226 : modifiedCols,
2227 : 64);
2228 237 : ereport(ERROR,
2229 : errcode(ERRCODE_NOT_NULL_VIOLATION),
2230 : errmsg("null value in column \"%s\" of relation \"%s\" violates not-null constraint",
2231 : NameStr(att->attname),
2232 : RelationGetRelationName(orig_rel)),
2233 : val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
2234 : errtablecol(orig_rel, attnum));
2235 : }
2236 :
2237 : /*
2238 : * ExecWithCheckOptions -- check that tuple satisfies any WITH CHECK OPTIONs
2239 : * of the specified kind.
2240 : *
2241 : * Note that this needs to be called multiple times to ensure that all kinds of
2242 : * WITH CHECK OPTIONs are handled (both those from views which have the WITH
2243 : * CHECK OPTION set and from row-level security policies). See ExecInsert()
2244 : * and ExecUpdate().
2245 : */
2246 : void
2247 1609 : ExecWithCheckOptions(WCOKind kind, ResultRelInfo *resultRelInfo,
2248 : TupleTableSlot *slot, EState *estate)
2249 : {
2250 1609 : Relation rel = resultRelInfo->ri_RelationDesc;
2251 1609 : TupleDesc tupdesc = RelationGetDescr(rel);
2252 : ExprContext *econtext;
2253 : ListCell *l1,
2254 : *l2;
2255 :
2256 : /*
2257 : * We will use the EState's per-tuple context for evaluating constraint
2258 : * expressions (creating it if it's not already there).
2259 : */
2260 1609 : econtext = GetPerTupleExprContext(estate);
2261 :
2262 : /* Arrange for econtext's scan tuple to be the tuple under test */
2263 1609 : econtext->ecxt_scantuple = slot;
2264 :
2265 : /* Check each of the constraints */
2266 4438 : forboth(l1, resultRelInfo->ri_WithCheckOptions,
2267 : l2, resultRelInfo->ri_WithCheckOptionExprs)
2268 : {
2269 3179 : WithCheckOption *wco = (WithCheckOption *) lfirst(l1);
2270 3179 : ExprState *wcoExpr = (ExprState *) lfirst(l2);
2271 :
2272 : /*
2273 : * Skip any WCOs which are not the kind we are looking for at this
2274 : * time.
2275 : */
2276 3179 : if (wco->kind != kind)
2277 1912 : continue;
2278 :
2279 : /*
2280 : * WITH CHECK OPTION checks are intended to ensure that the new tuple
2281 : * is visible (in the case of a view) or that it passes the
2282 : * 'with-check' policy (in the case of row security). If the qual
2283 : * evaluates to NULL or FALSE, then the new tuple won't be included in
2284 : * the view or doesn't pass the 'with-check' policy for the table.
2285 : */
2286 1267 : if (!ExecQual(wcoExpr, econtext))
2287 : {
2288 : char *val_desc;
2289 : Bitmapset *modifiedCols;
2290 :
2291 350 : switch (wco->kind)
2292 : {
2293 : /*
2294 : * For WITH CHECK OPTIONs coming from views, we might be
2295 : * able to provide the details on the row, depending on
2296 : * the permissions on the relation (that is, if the user
2297 : * could view it directly anyway). For RLS violations, we
2298 : * don't include the data since we don't know if the user
2299 : * should be able to view the tuple as that depends on the
2300 : * USING policy.
2301 : */
2302 150 : case WCO_VIEW_CHECK:
2303 : /* See the comment in ExecConstraints(). */
2304 150 : if (resultRelInfo->ri_RootResultRelInfo)
2305 : {
2306 27 : ResultRelInfo *rootrel = resultRelInfo->ri_RootResultRelInfo;
2307 27 : TupleDesc old_tupdesc = RelationGetDescr(rel);
2308 : AttrMap *map;
2309 :
2310 27 : tupdesc = RelationGetDescr(rootrel->ri_RelationDesc);
2311 : /* a reverse map */
2312 27 : map = build_attrmap_by_name_if_req(old_tupdesc,
2313 : tupdesc,
2314 : false);
2315 :
2316 : /*
2317 : * Partition-specific slot's tupdesc can't be changed,
2318 : * so allocate a new one.
2319 : */
2320 27 : if (map != NULL)
2321 16 : slot = execute_attr_map_slot(map, slot,
2322 : MakeTupleTableSlot(tupdesc, &TTSOpsVirtual, 0));
2323 :
2324 27 : modifiedCols = bms_union(ExecGetInsertedCols(rootrel, estate),
2325 27 : ExecGetUpdatedCols(rootrel, estate));
2326 27 : rel = rootrel->ri_RelationDesc;
2327 : }
2328 : else
2329 123 : modifiedCols = bms_union(ExecGetInsertedCols(resultRelInfo, estate),
2330 123 : ExecGetUpdatedCols(resultRelInfo, estate));
2331 150 : val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
2332 : slot,
2333 : tupdesc,
2334 : modifiedCols,
2335 : 64);
2336 :
2337 150 : ereport(ERROR,
2338 : (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),
2339 : errmsg("new row violates check option for view \"%s\"",
2340 : wco->relname),
2341 : val_desc ? errdetail("Failing row contains %s.",
2342 : val_desc) : 0));
2343 : break;
2344 164 : case WCO_RLS_INSERT_CHECK:
2345 : case WCO_RLS_UPDATE_CHECK:
2346 164 : if (wco->polname != NULL)
2347 39 : ereport(ERROR,
2348 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2349 : errmsg("new row violates row-level security policy \"%s\" for table \"%s\"",
2350 : wco->polname, wco->relname)));
2351 : else
2352 125 : ereport(ERROR,
2353 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2354 : errmsg("new row violates row-level security policy for table \"%s\"",
2355 : wco->relname)));
2356 : break;
2357 16 : case WCO_RLS_MERGE_UPDATE_CHECK:
2358 : case WCO_RLS_MERGE_DELETE_CHECK:
2359 16 : if (wco->polname != NULL)
2360 0 : ereport(ERROR,
2361 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2362 : errmsg("target row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2363 : wco->polname, wco->relname)));
2364 : else
2365 16 : ereport(ERROR,
2366 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2367 : errmsg("target row violates row-level security policy (USING expression) for table \"%s\"",
2368 : wco->relname)));
2369 : break;
2370 20 : case WCO_RLS_CONFLICT_CHECK:
2371 20 : if (wco->polname != NULL)
2372 0 : ereport(ERROR,
2373 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2374 : errmsg("new row violates row-level security policy \"%s\" (USING expression) for table \"%s\"",
2375 : wco->polname, wco->relname)));
2376 : else
2377 20 : ereport(ERROR,
2378 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2379 : errmsg("new row violates row-level security policy (USING expression) for table \"%s\"",
2380 : wco->relname)));
2381 : break;
2382 0 : default:
2383 0 : elog(ERROR, "unrecognized WCO kind: %u", wco->kind);
2384 : break;
2385 : }
2386 : }
2387 : }
2388 1259 : }
2389 :
2390 : /*
2391 : * ExecBuildSlotValueDescription -- construct a string representing a tuple
2392 : *
2393 : * This is intentionally very similar to BuildIndexValueDescription, but
2394 : * unlike that function, we truncate long field values (to at most maxfieldlen
2395 : * bytes). That seems necessary here since heap field values could be very
2396 : * long, whereas index entries typically aren't so wide.
2397 : *
2398 : * Also, unlike the case with index entries, we need to be prepared to ignore
2399 : * dropped columns. We used to use the slot's tuple descriptor to decode the
2400 : * data, but the slot's descriptor doesn't identify dropped columns, so we
2401 : * now need to be passed the relation's descriptor.
2402 : *
2403 : * Note that, like BuildIndexValueDescription, if the user does not have
2404 : * permission to view any of the columns involved, a NULL is returned. Unlike
2405 : * BuildIndexValueDescription, if the user has access to view a subset of the
2406 : * column involved, that subset will be returned with a key identifying which
2407 : * columns they are.
2408 : */
2409 : char *
2410 1070 : ExecBuildSlotValueDescription(Oid reloid,
2411 : TupleTableSlot *slot,
2412 : TupleDesc tupdesc,
2413 : Bitmapset *modifiedCols,
2414 : int maxfieldlen)
2415 : {
2416 : StringInfoData buf;
2417 : StringInfoData collist;
2418 1070 : bool write_comma = false;
2419 1070 : bool write_comma_collist = false;
2420 : int i;
2421 : AclResult aclresult;
2422 1070 : bool table_perm = false;
2423 1070 : bool any_perm = false;
2424 :
2425 : /*
2426 : * Check if RLS is enabled and should be active for the relation; if so,
2427 : * then don't return anything. Otherwise, go through normal permission
2428 : * checks.
2429 : */
2430 1070 : if (check_enable_rls(reloid, InvalidOid, true) == RLS_ENABLED)
2431 0 : return NULL;
2432 :
2433 1070 : initStringInfo(&buf);
2434 :
2435 1070 : appendStringInfoChar(&buf, '(');
2436 :
2437 : /*
2438 : * Check if the user has permissions to see the row. Table-level SELECT
2439 : * allows access to all columns. If the user does not have table-level
2440 : * SELECT then we check each column and include those the user has SELECT
2441 : * rights on. Additionally, we always include columns the user provided
2442 : * data for.
2443 : */
2444 1070 : aclresult = pg_class_aclcheck(reloid, GetUserId(), ACL_SELECT);
2445 1070 : if (aclresult != ACLCHECK_OK)
2446 : {
2447 : /* Set up the buffer for the column list */
2448 40 : initStringInfo(&collist);
2449 40 : appendStringInfoChar(&collist, '(');
2450 : }
2451 : else
2452 1030 : table_perm = any_perm = true;
2453 :
2454 : /* Make sure the tuple is fully deconstructed */
2455 1070 : slot_getallattrs(slot);
2456 :
2457 3872 : for (i = 0; i < tupdesc->natts; i++)
2458 : {
2459 2802 : bool column_perm = false;
2460 : char *val;
2461 : int vallen;
2462 2802 : Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2463 :
2464 : /* ignore dropped columns */
2465 2802 : if (att->attisdropped)
2466 25 : continue;
2467 :
2468 2777 : if (!table_perm)
2469 : {
2470 : /*
2471 : * No table-level SELECT, so need to make sure they either have
2472 : * SELECT rights on the column or that they have provided the data
2473 : * for the column. If not, omit this column from the error
2474 : * message.
2475 : */
2476 156 : aclresult = pg_attribute_aclcheck(reloid, att->attnum,
2477 : GetUserId(), ACL_SELECT);
2478 156 : if (bms_is_member(att->attnum - FirstLowInvalidHeapAttributeNumber,
2479 92 : modifiedCols) || aclresult == ACLCHECK_OK)
2480 : {
2481 96 : column_perm = any_perm = true;
2482 :
2483 96 : if (write_comma_collist)
2484 56 : appendStringInfoString(&collist, ", ");
2485 : else
2486 40 : write_comma_collist = true;
2487 :
2488 96 : appendStringInfoString(&collist, NameStr(att->attname));
2489 : }
2490 : }
2491 :
2492 2777 : if (table_perm || column_perm)
2493 : {
2494 2717 : if (att->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
2495 40 : val = "virtual";
2496 2677 : else if (slot->tts_isnull[i])
2497 416 : val = "null";
2498 : else
2499 : {
2500 : Oid foutoid;
2501 : bool typisvarlena;
2502 :
2503 2261 : getTypeOutputInfo(att->atttypid,
2504 : &foutoid, &typisvarlena);
2505 2261 : val = OidOutputFunctionCall(foutoid, slot->tts_values[i]);
2506 : }
2507 :
2508 2717 : if (write_comma)
2509 1647 : appendStringInfoString(&buf, ", ");
2510 : else
2511 1070 : write_comma = true;
2512 :
2513 : /* truncate if needed */
2514 2717 : vallen = strlen(val);
2515 2717 : if (vallen <= maxfieldlen)
2516 2716 : appendBinaryStringInfo(&buf, val, vallen);
2517 : else
2518 : {
2519 1 : vallen = pg_mbcliplen(val, vallen, maxfieldlen);
2520 1 : appendBinaryStringInfo(&buf, val, vallen);
2521 1 : appendStringInfoString(&buf, "...");
2522 : }
2523 : }
2524 : }
2525 :
2526 : /* If we end up with zero columns being returned, then return NULL. */
2527 1070 : if (!any_perm)
2528 0 : return NULL;
2529 :
2530 1070 : appendStringInfoChar(&buf, ')');
2531 :
2532 1070 : if (!table_perm)
2533 : {
2534 40 : appendStringInfoString(&collist, ") = ");
2535 40 : appendBinaryStringInfo(&collist, buf.data, buf.len);
2536 :
2537 40 : return collist.data;
2538 : }
2539 :
2540 1030 : return buf.data;
2541 : }
2542 :
2543 :
2544 : /*
2545 : * ExecUpdateLockMode -- find the appropriate UPDATE tuple lock mode for a
2546 : * given ResultRelInfo
2547 : */
2548 : LockTupleMode
2549 4342 : ExecUpdateLockMode(EState *estate, ResultRelInfo *relinfo)
2550 : {
2551 : Bitmapset *keyCols;
2552 : Bitmapset *updatedCols;
2553 :
2554 : /*
2555 : * Compute lock mode to use. If columns that are part of the key have not
2556 : * been modified, then we can use a weaker lock, allowing for better
2557 : * concurrency.
2558 : */
2559 4342 : updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
2560 4342 : keyCols = RelationGetIndexAttrBitmap(relinfo->ri_RelationDesc,
2561 : INDEX_ATTR_BITMAP_KEY);
2562 :
2563 4342 : if (bms_overlap(keyCols, updatedCols))
2564 177 : return LockTupleExclusive;
2565 :
2566 4165 : return LockTupleNoKeyExclusive;
2567 : }
2568 :
2569 : /*
2570 : * ExecFindRowMark -- find the ExecRowMark struct for given rangetable index
2571 : *
2572 : * If no such struct, either return NULL or throw error depending on missing_ok
2573 : */
2574 : ExecRowMark *
2575 410060 : ExecFindRowMark(EState *estate, Index rti, bool missing_ok)
2576 : {
2577 410060 : if (rti > 0 && rti <= estate->es_range_table_size &&
2578 410060 : estate->es_rowmarks != NULL)
2579 : {
2580 410060 : ExecRowMark *erm = estate->es_rowmarks[rti - 1];
2581 :
2582 410060 : if (erm)
2583 410060 : return erm;
2584 : }
2585 0 : if (!missing_ok)
2586 0 : elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
2587 0 : return NULL;
2588 : }
2589 :
2590 : /*
2591 : * ExecBuildAuxRowMark -- create an ExecAuxRowMark struct
2592 : *
2593 : * Inputs are the underlying ExecRowMark struct and the targetlist of the
2594 : * input plan node (not planstate node!). We need the latter to find out
2595 : * the column numbers of the resjunk columns.
2596 : */
2597 : ExecAuxRowMark *
2598 410060 : ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
2599 : {
2600 410060 : ExecAuxRowMark *aerm = palloc0_object(ExecAuxRowMark);
2601 : char resname[32];
2602 :
2603 410060 : aerm->rowmark = erm;
2604 :
2605 : /* Look up the resjunk columns associated with this rowmark */
2606 410060 : if (erm->markType != ROW_MARK_COPY)
2607 : {
2608 : /* need ctid for all methods other than COPY */
2609 409601 : snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
2610 409601 : aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2611 : resname);
2612 409601 : if (!AttributeNumberIsValid(aerm->ctidAttNo))
2613 0 : elog(ERROR, "could not find junk %s column", resname);
2614 : }
2615 : else
2616 : {
2617 : /* need wholerow if COPY */
2618 459 : snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
2619 459 : aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
2620 : resname);
2621 459 : if (!AttributeNumberIsValid(aerm->wholeAttNo))
2622 0 : elog(ERROR, "could not find junk %s column", resname);
2623 : }
2624 :
2625 : /* if child rel, need tableoid */
2626 410060 : if (erm->rti != erm->prti)
2627 : {
2628 1308 : snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
2629 1308 : aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
2630 : resname);
2631 1308 : if (!AttributeNumberIsValid(aerm->toidAttNo))
2632 0 : elog(ERROR, "could not find junk %s column", resname);
2633 : }
2634 :
2635 410060 : return aerm;
2636 : }
2637 :
2638 :
2639 : /*
2640 : * EvalPlanQual logic --- recheck modified tuple(s) to see if we want to
2641 : * process the updated version under READ COMMITTED rules.
2642 : *
2643 : * See backend/executor/README for some info about how this works.
2644 : */
2645 :
2646 :
2647 : /*
2648 : * Check the updated version of a tuple to see if we want to process it under
2649 : * READ COMMITTED rules.
2650 : *
2651 : * epqstate - state for EvalPlanQual rechecking
2652 : * relation - table containing tuple
2653 : * rti - rangetable index of table containing tuple
2654 : * inputslot - tuple for processing - this can be the slot from
2655 : * EvalPlanQualSlot() for this rel, for increased efficiency.
2656 : *
2657 : * This tests whether the tuple in inputslot still matches the relevant
2658 : * quals. For that result to be useful, typically the input tuple has to be
2659 : * last row version (otherwise the result isn't particularly useful) and
2660 : * locked (otherwise the result might be out of date). That's typically
2661 : * achieved by using table_tuple_lock() with the
2662 : * TUPLE_LOCK_FLAG_FIND_LAST_VERSION flag.
2663 : *
2664 : * Returns a slot containing the new candidate update/delete tuple, or
2665 : * NULL if we determine we shouldn't process the row.
2666 : */
2667 : TupleTableSlot *
2668 145 : EvalPlanQual(EPQState *epqstate, Relation relation,
2669 : Index rti, TupleTableSlot *inputslot)
2670 : {
2671 : TupleTableSlot *slot;
2672 : TupleTableSlot *testslot;
2673 :
2674 : Assert(rti > 0);
2675 :
2676 : /*
2677 : * Need to run a recheck subquery. Initialize or reinitialize EPQ state.
2678 : */
2679 145 : EvalPlanQualBegin(epqstate);
2680 :
2681 : /*
2682 : * Callers will often use the EvalPlanQualSlot to store the tuple to avoid
2683 : * an unnecessary copy.
2684 : */
2685 145 : testslot = EvalPlanQualSlot(epqstate, relation, rti);
2686 145 : if (testslot != inputslot)
2687 6 : ExecCopySlot(testslot, inputslot);
2688 :
2689 : /*
2690 : * Mark that an EPQ tuple is available for this relation. (If there is
2691 : * more than one result relation, the others remain marked as having no
2692 : * tuple available.)
2693 : */
2694 145 : epqstate->relsubs_done[rti - 1] = false;
2695 145 : epqstate->relsubs_blocked[rti - 1] = false;
2696 :
2697 : /*
2698 : * Run the EPQ query. We assume it will return at most one tuple.
2699 : */
2700 145 : slot = EvalPlanQualNext(epqstate);
2701 :
2702 : /*
2703 : * If we got a tuple, force the slot to materialize the tuple so that it
2704 : * is not dependent on any local state in the EPQ query (in particular,
2705 : * it's highly likely that the slot contains references to any pass-by-ref
2706 : * datums that may be present in copyTuple). As with the next step, this
2707 : * is to guard against early re-use of the EPQ query.
2708 : */
2709 145 : if (!TupIsNull(slot))
2710 109 : ExecMaterializeSlot(slot);
2711 :
2712 : /*
2713 : * Clear out the test tuple, and mark that no tuple is available here.
2714 : * This is needed in case the EPQ state is re-used to test a tuple for a
2715 : * different target relation.
2716 : */
2717 145 : ExecClearTuple(testslot);
2718 145 : epqstate->relsubs_blocked[rti - 1] = true;
2719 :
2720 145 : return slot;
2721 : }
2722 :
2723 : /*
2724 : * EvalPlanQualInit -- initialize during creation of a plan state node
2725 : * that might need to invoke EPQ processing.
2726 : *
2727 : * If the caller intends to use EvalPlanQual(), resultRelations should be
2728 : * a list of RT indexes of potential target relations for EvalPlanQual(),
2729 : * and we will arrange that the other listed relations don't return any
2730 : * tuple during an EvalPlanQual() call. Otherwise resultRelations
2731 : * should be NIL.
2732 : *
2733 : * Note: subplan/auxrowmarks can be NULL/NIL if they will be set later
2734 : * with EvalPlanQualSetPlan.
2735 : */
2736 : void
2737 553776 : EvalPlanQualInit(EPQState *epqstate, EState *parentestate,
2738 : Plan *subplan, List *auxrowmarks,
2739 : int epqParam, List *resultRelations)
2740 : {
2741 553776 : Index rtsize = parentestate->es_range_table_size;
2742 :
2743 : /* initialize data not changing over EPQState's lifetime */
2744 553776 : epqstate->parentestate = parentestate;
2745 553776 : epqstate->epqParam = epqParam;
2746 553776 : epqstate->resultRelations = resultRelations;
2747 :
2748 : /*
2749 : * Allocate space to reference a slot for each potential rti - do so now
2750 : * rather than in EvalPlanQualBegin(), as done for other dynamically
2751 : * allocated resources, so EvalPlanQualSlot() can be used to hold tuples
2752 : * that *may* need EPQ later, without forcing the overhead of
2753 : * EvalPlanQualBegin().
2754 : */
2755 553776 : epqstate->tuple_table = NIL;
2756 553776 : epqstate->relsubs_slot = palloc0_array(TupleTableSlot *, rtsize);
2757 :
2758 : /* ... and remember data that EvalPlanQualBegin will need */
2759 553776 : epqstate->plan = subplan;
2760 553776 : epqstate->arowMarks = auxrowmarks;
2761 :
2762 : /* ... and mark the EPQ state inactive */
2763 553776 : epqstate->origslot = NULL;
2764 553776 : epqstate->recheckestate = NULL;
2765 553776 : epqstate->recheckplanstate = NULL;
2766 553776 : epqstate->relsubs_rowmark = NULL;
2767 553776 : epqstate->relsubs_done = NULL;
2768 553776 : epqstate->relsubs_blocked = NULL;
2769 553776 : }
2770 :
2771 : /*
2772 : * EvalPlanQualSetPlan -- set or change subplan of an EPQState.
2773 : *
2774 : * We used to need this so that ModifyTable could deal with multiple subplans.
2775 : * It could now be refactored out of existence.
2776 : */
2777 : void
2778 73298 : EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan, List *auxrowmarks)
2779 : {
2780 : /* If we have a live EPQ query, shut it down */
2781 73298 : EvalPlanQualEnd(epqstate);
2782 : /* And set/change the plan pointer */
2783 73298 : epqstate->plan = subplan;
2784 : /* The rowmarks depend on the plan, too */
2785 73298 : epqstate->arowMarks = auxrowmarks;
2786 73298 : }
2787 :
2788 : /*
2789 : * Return, and create if necessary, a slot for an EPQ test tuple.
2790 : *
2791 : * Note this only requires EvalPlanQualInit() to have been called,
2792 : * EvalPlanQualBegin() is not necessary.
2793 : */
2794 : TupleTableSlot *
2795 483041 : EvalPlanQualSlot(EPQState *epqstate,
2796 : Relation relation, Index rti)
2797 : {
2798 : TupleTableSlot **slot;
2799 :
2800 : Assert(relation);
2801 : Assert(rti > 0 && rti <= epqstate->parentestate->es_range_table_size);
2802 483041 : slot = &epqstate->relsubs_slot[rti - 1];
2803 :
2804 483041 : if (*slot == NULL)
2805 : {
2806 : MemoryContext oldcontext;
2807 :
2808 406547 : oldcontext = MemoryContextSwitchTo(epqstate->parentestate->es_query_cxt);
2809 406547 : *slot = table_slot_create(relation, &epqstate->tuple_table);
2810 406547 : MemoryContextSwitchTo(oldcontext);
2811 : }
2812 :
2813 483041 : return *slot;
2814 : }
2815 :
2816 : /*
2817 : * Fetch the current row value for a non-locked relation, identified by rti,
2818 : * that needs to be scanned by an EvalPlanQual operation. origslot must have
2819 : * been set to contain the current result row (top-level row) that we need to
2820 : * recheck. Returns true if a substitution tuple was found, false if not.
2821 : */
2822 : bool
2823 22 : EvalPlanQualFetchRowMark(EPQState *epqstate, Index rti, TupleTableSlot *slot)
2824 : {
2825 22 : ExecAuxRowMark *earm = epqstate->relsubs_rowmark[rti - 1];
2826 : ExecRowMark *erm;
2827 : Datum datum;
2828 : bool isNull;
2829 :
2830 : Assert(earm != NULL);
2831 : Assert(epqstate->origslot != NULL);
2832 :
2833 22 : erm = earm->rowmark;
2834 :
2835 22 : if (RowMarkRequiresRowShareLock(erm->markType))
2836 0 : elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2837 :
2838 : /* if child rel, must check whether it produced this row */
2839 22 : if (erm->rti != erm->prti)
2840 : {
2841 : Oid tableoid;
2842 :
2843 0 : datum = ExecGetJunkAttribute(epqstate->origslot,
2844 0 : earm->toidAttNo,
2845 : &isNull);
2846 : /* non-locked rels could be on the inside of outer joins */
2847 0 : if (isNull)
2848 0 : return false;
2849 :
2850 0 : tableoid = DatumGetObjectId(datum);
2851 :
2852 : Assert(OidIsValid(erm->relid));
2853 0 : if (tableoid != erm->relid)
2854 : {
2855 : /* this child is inactive right now */
2856 0 : return false;
2857 : }
2858 : }
2859 :
2860 22 : if (erm->markType == ROW_MARK_REFERENCE)
2861 : {
2862 : Assert(erm->relation != NULL);
2863 :
2864 : /* fetch the tuple's ctid */
2865 13 : datum = ExecGetJunkAttribute(epqstate->origslot,
2866 13 : earm->ctidAttNo,
2867 : &isNull);
2868 : /* non-locked rels could be on the inside of outer joins */
2869 13 : if (isNull)
2870 0 : return false;
2871 :
2872 : /* fetch requests on foreign tables must be passed to their FDW */
2873 13 : if (erm->relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2874 : {
2875 : FdwRoutine *fdwroutine;
2876 0 : bool updated = false;
2877 :
2878 0 : fdwroutine = GetFdwRoutineForRelation(erm->relation, false);
2879 : /* this should have been checked already, but let's be safe */
2880 0 : if (fdwroutine->RefetchForeignRow == NULL)
2881 0 : ereport(ERROR,
2882 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2883 : errmsg("cannot lock rows in foreign table \"%s\"",
2884 : RelationGetRelationName(erm->relation))));
2885 :
2886 0 : fdwroutine->RefetchForeignRow(epqstate->recheckestate,
2887 : erm,
2888 : datum,
2889 : slot,
2890 : &updated);
2891 0 : if (TupIsNull(slot))
2892 0 : elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2893 :
2894 : /*
2895 : * Ideally we'd insist on updated == false here, but that assumes
2896 : * that FDWs can track that exactly, which they might not be able
2897 : * to. So just ignore the flag.
2898 : */
2899 0 : return true;
2900 : }
2901 : else
2902 : {
2903 : /* ordinary table, fetch the tuple */
2904 13 : if (!table_tuple_fetch_row_version(erm->relation,
2905 13 : (ItemPointer) DatumGetPointer(datum),
2906 : SnapshotAny, slot))
2907 0 : elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2908 13 : return true;
2909 : }
2910 : }
2911 : else
2912 : {
2913 : Assert(erm->markType == ROW_MARK_COPY);
2914 :
2915 : /* fetch the whole-row Var for the relation */
2916 9 : datum = ExecGetJunkAttribute(epqstate->origslot,
2917 9 : earm->wholeAttNo,
2918 : &isNull);
2919 : /* non-locked rels could be on the inside of outer joins */
2920 9 : if (isNull)
2921 0 : return false;
2922 :
2923 9 : ExecStoreHeapTupleDatum(datum, slot);
2924 9 : return true;
2925 : }
2926 : }
2927 :
2928 : /*
2929 : * Fetch the next row (if any) from EvalPlanQual testing
2930 : *
2931 : * (In practice, there should never be more than one row...)
2932 : */
2933 : TupleTableSlot *
2934 179 : EvalPlanQualNext(EPQState *epqstate)
2935 : {
2936 : MemoryContext oldcontext;
2937 : TupleTableSlot *slot;
2938 :
2939 179 : oldcontext = MemoryContextSwitchTo(epqstate->recheckestate->es_query_cxt);
2940 179 : slot = ExecProcNode(epqstate->recheckplanstate);
2941 179 : MemoryContextSwitchTo(oldcontext);
2942 :
2943 179 : return slot;
2944 : }
2945 :
2946 : /*
2947 : * Initialize or reset an EvalPlanQual state tree
2948 : */
2949 : void
2950 213 : EvalPlanQualBegin(EPQState *epqstate)
2951 : {
2952 213 : EState *parentestate = epqstate->parentestate;
2953 213 : EState *recheckestate = epqstate->recheckestate;
2954 :
2955 213 : if (recheckestate == NULL)
2956 : {
2957 : /* First time through, so create a child EState */
2958 134 : EvalPlanQualStart(epqstate, epqstate->plan);
2959 : }
2960 : else
2961 : {
2962 : /*
2963 : * We already have a suitable child EPQ tree, so just reset it.
2964 : */
2965 79 : Index rtsize = parentestate->es_range_table_size;
2966 79 : PlanState *rcplanstate = epqstate->recheckplanstate;
2967 :
2968 : /*
2969 : * Reset the relsubs_done[] flags to equal relsubs_blocked[], so that
2970 : * the EPQ run will never attempt to fetch tuples from blocked target
2971 : * relations.
2972 : */
2973 79 : memcpy(epqstate->relsubs_done, epqstate->relsubs_blocked,
2974 : rtsize * sizeof(bool));
2975 :
2976 : /* Recopy current values of parent parameters */
2977 79 : if (parentestate->es_plannedstmt->paramExecTypes != NIL)
2978 : {
2979 : int i;
2980 :
2981 : /*
2982 : * Force evaluation of any InitPlan outputs that could be needed
2983 : * by the subplan, just in case they got reset since
2984 : * EvalPlanQualStart (see comments therein).
2985 : */
2986 79 : ExecSetParamPlanMulti(rcplanstate->plan->extParam,
2987 79 : GetPerTupleExprContext(parentestate));
2988 :
2989 79 : i = list_length(parentestate->es_plannedstmt->paramExecTypes);
2990 :
2991 169 : while (--i >= 0)
2992 : {
2993 : /* copy value if any, but not execPlan link */
2994 90 : recheckestate->es_param_exec_vals[i].value =
2995 90 : parentestate->es_param_exec_vals[i].value;
2996 90 : recheckestate->es_param_exec_vals[i].isnull =
2997 90 : parentestate->es_param_exec_vals[i].isnull;
2998 : }
2999 : }
3000 :
3001 : /*
3002 : * Mark child plan tree as needing rescan at all scan nodes. The
3003 : * first ExecProcNode will take care of actually doing the rescan.
3004 : */
3005 79 : rcplanstate->chgParam = bms_add_member(rcplanstate->chgParam,
3006 : epqstate->epqParam);
3007 : }
3008 213 : }
3009 :
3010 : /*
3011 : * Start execution of an EvalPlanQual plan tree.
3012 : *
3013 : * This is a cut-down version of ExecutorStart(): we copy some state from
3014 : * the top-level estate rather than initializing it fresh.
3015 : */
3016 : static void
3017 134 : EvalPlanQualStart(EPQState *epqstate, Plan *planTree)
3018 : {
3019 134 : EState *parentestate = epqstate->parentestate;
3020 134 : Index rtsize = parentestate->es_range_table_size;
3021 : EState *rcestate;
3022 : MemoryContext oldcontext;
3023 : ListCell *l;
3024 :
3025 134 : epqstate->recheckestate = rcestate = CreateExecutorState();
3026 :
3027 134 : oldcontext = MemoryContextSwitchTo(rcestate->es_query_cxt);
3028 :
3029 : /* signal that this is an EState for executing EPQ */
3030 134 : rcestate->es_epq_active = epqstate;
3031 :
3032 : /*
3033 : * Child EPQ EStates share the parent's copy of unchanging state such as
3034 : * the snapshot, rangetable, and external Param info. They need their own
3035 : * copies of local state, including a tuple table, es_param_exec_vals,
3036 : * result-rel info, etc.
3037 : */
3038 134 : rcestate->es_direction = ForwardScanDirection;
3039 134 : rcestate->es_snapshot = parentestate->es_snapshot;
3040 134 : rcestate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
3041 134 : rcestate->es_range_table = parentestate->es_range_table;
3042 134 : rcestate->es_range_table_size = parentestate->es_range_table_size;
3043 134 : rcestate->es_relations = parentestate->es_relations;
3044 134 : rcestate->es_rowmarks = parentestate->es_rowmarks;
3045 134 : rcestate->es_rteperminfos = parentestate->es_rteperminfos;
3046 134 : rcestate->es_plannedstmt = parentestate->es_plannedstmt;
3047 134 : rcestate->es_junkFilter = parentestate->es_junkFilter;
3048 134 : rcestate->es_output_cid = parentestate->es_output_cid;
3049 134 : rcestate->es_queryEnv = parentestate->es_queryEnv;
3050 :
3051 : /*
3052 : * ResultRelInfos needed by subplans are initialized from scratch when the
3053 : * subplans themselves are initialized.
3054 : */
3055 134 : rcestate->es_result_relations = NULL;
3056 : /* es_trig_target_relations must NOT be copied */
3057 134 : rcestate->es_top_eflags = parentestate->es_top_eflags;
3058 134 : rcestate->es_instrument = parentestate->es_instrument;
3059 : /* es_auxmodifytables must NOT be copied */
3060 :
3061 : /*
3062 : * The external param list is simply shared from parent. The internal
3063 : * param workspace has to be local state, but we copy the initial values
3064 : * from the parent, so as to have access to any param values that were
3065 : * already set from other parts of the parent's plan tree.
3066 : */
3067 134 : rcestate->es_param_list_info = parentestate->es_param_list_info;
3068 134 : if (parentestate->es_plannedstmt->paramExecTypes != NIL)
3069 : {
3070 : int i;
3071 :
3072 : /*
3073 : * Force evaluation of any InitPlan outputs that could be needed by
3074 : * the subplan. (With more complexity, maybe we could postpone this
3075 : * till the subplan actually demands them, but it doesn't seem worth
3076 : * the trouble; this is a corner case already, since usually the
3077 : * InitPlans would have been evaluated before reaching EvalPlanQual.)
3078 : *
3079 : * This will not touch output params of InitPlans that occur somewhere
3080 : * within the subplan tree, only those that are attached to the
3081 : * ModifyTable node or above it and are referenced within the subplan.
3082 : * That's OK though, because the planner would only attach such
3083 : * InitPlans to a lower-level SubqueryScan node, and EPQ execution
3084 : * will not descend into a SubqueryScan.
3085 : *
3086 : * The EState's per-output-tuple econtext is sufficiently short-lived
3087 : * for this, since it should get reset before there is any chance of
3088 : * doing EvalPlanQual again.
3089 : */
3090 134 : ExecSetParamPlanMulti(planTree->extParam,
3091 134 : GetPerTupleExprContext(parentestate));
3092 :
3093 : /* now make the internal param workspace ... */
3094 134 : i = list_length(parentestate->es_plannedstmt->paramExecTypes);
3095 134 : rcestate->es_param_exec_vals = palloc0_array(ParamExecData, i);
3096 : /* ... and copy down all values, whether really needed or not */
3097 323 : while (--i >= 0)
3098 : {
3099 : /* copy value if any, but not execPlan link */
3100 189 : rcestate->es_param_exec_vals[i].value =
3101 189 : parentestate->es_param_exec_vals[i].value;
3102 189 : rcestate->es_param_exec_vals[i].isnull =
3103 189 : parentestate->es_param_exec_vals[i].isnull;
3104 : }
3105 : }
3106 :
3107 : /*
3108 : * Copy es_unpruned_relids so that pruned relations are ignored by
3109 : * ExecInitLockRows() and ExecInitModifyTable() when initializing the plan
3110 : * trees below.
3111 : */
3112 134 : rcestate->es_unpruned_relids = parentestate->es_unpruned_relids;
3113 :
3114 : /*
3115 : * Also make the PartitionPruneInfo and the results of pruning available.
3116 : * These need to match exactly so that we initialize all the same Append
3117 : * and MergeAppend subplans as the parent did.
3118 : */
3119 134 : rcestate->es_part_prune_infos = parentestate->es_part_prune_infos;
3120 134 : rcestate->es_part_prune_states = parentestate->es_part_prune_states;
3121 134 : rcestate->es_part_prune_results = parentestate->es_part_prune_results;
3122 :
3123 : /* We'll also borrow the es_partition_directory from the parent state */
3124 134 : rcestate->es_partition_directory = parentestate->es_partition_directory;
3125 :
3126 : /*
3127 : * Initialize private state information for each SubPlan. We must do this
3128 : * before running ExecInitNode on the main query tree, since
3129 : * ExecInitSubPlan expects to be able to find these entries. Some of the
3130 : * SubPlans might not be used in the part of the plan tree we intend to
3131 : * run, but since it's not easy to tell which, we just initialize them
3132 : * all.
3133 : */
3134 : Assert(rcestate->es_subplanstates == NIL);
3135 166 : foreach(l, parentestate->es_plannedstmt->subplans)
3136 : {
3137 32 : Plan *subplan = (Plan *) lfirst(l);
3138 : PlanState *subplanstate;
3139 :
3140 32 : subplanstate = ExecInitNode(subplan, rcestate, 0);
3141 32 : rcestate->es_subplanstates = lappend(rcestate->es_subplanstates,
3142 : subplanstate);
3143 : }
3144 :
3145 : /*
3146 : * Build an RTI indexed array of rowmarks, so that
3147 : * EvalPlanQualFetchRowMark() can efficiently access the to be fetched
3148 : * rowmark.
3149 : */
3150 134 : epqstate->relsubs_rowmark = palloc0_array(ExecAuxRowMark *, rtsize);
3151 151 : foreach(l, epqstate->arowMarks)
3152 : {
3153 17 : ExecAuxRowMark *earm = (ExecAuxRowMark *) lfirst(l);
3154 :
3155 17 : epqstate->relsubs_rowmark[earm->rowmark->rti - 1] = earm;
3156 : }
3157 :
3158 : /*
3159 : * Initialize per-relation EPQ tuple states. Result relations, if any,
3160 : * get marked as blocked; others as not-fetched.
3161 : */
3162 134 : epqstate->relsubs_done = palloc_array(bool, rtsize);
3163 134 : epqstate->relsubs_blocked = palloc0_array(bool, rtsize);
3164 :
3165 268 : foreach(l, epqstate->resultRelations)
3166 : {
3167 134 : int rtindex = lfirst_int(l);
3168 :
3169 : Assert(rtindex > 0 && rtindex <= rtsize);
3170 134 : epqstate->relsubs_blocked[rtindex - 1] = true;
3171 : }
3172 :
3173 134 : memcpy(epqstate->relsubs_done, epqstate->relsubs_blocked,
3174 : rtsize * sizeof(bool));
3175 :
3176 : /*
3177 : * Initialize the private state information for all the nodes in the part
3178 : * of the plan tree we need to run. This opens files, allocates storage
3179 : * and leaves us ready to start processing tuples.
3180 : */
3181 134 : epqstate->recheckplanstate = ExecInitNode(planTree, rcestate, 0);
3182 :
3183 134 : MemoryContextSwitchTo(oldcontext);
3184 134 : }
3185 :
3186 : /*
3187 : * EvalPlanQualEnd -- shut down at termination of parent plan state node,
3188 : * or if we are done with the current EPQ child.
3189 : *
3190 : * This is a cut-down version of ExecutorEnd(); basically we want to do most
3191 : * of the normal cleanup, but *not* close result relations (which we are
3192 : * just sharing from the outer query). We do, however, have to close any
3193 : * result and trigger target relations that got opened, since those are not
3194 : * shared. (There probably shouldn't be any of the latter, but just in
3195 : * case...)
3196 : */
3197 : void
3198 628736 : EvalPlanQualEnd(EPQState *epqstate)
3199 : {
3200 628736 : EState *estate = epqstate->recheckestate;
3201 : Index rtsize;
3202 : MemoryContext oldcontext;
3203 : ListCell *l;
3204 :
3205 628736 : rtsize = epqstate->parentestate->es_range_table_size;
3206 :
3207 : /*
3208 : * We may have a tuple table, even if EPQ wasn't started, because we allow
3209 : * use of EvalPlanQualSlot() without calling EvalPlanQualBegin().
3210 : */
3211 628736 : if (epqstate->tuple_table != NIL)
3212 : {
3213 406383 : memset(epqstate->relsubs_slot, 0,
3214 : rtsize * sizeof(TupleTableSlot *));
3215 406383 : ExecResetTupleTable(epqstate->tuple_table, true);
3216 406383 : epqstate->tuple_table = NIL;
3217 : }
3218 :
3219 : /* EPQ wasn't started, nothing further to do */
3220 628736 : if (estate == NULL)
3221 628610 : return;
3222 :
3223 126 : oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3224 :
3225 126 : ExecEndNode(epqstate->recheckplanstate);
3226 :
3227 155 : foreach(l, estate->es_subplanstates)
3228 : {
3229 29 : PlanState *subplanstate = (PlanState *) lfirst(l);
3230 :
3231 29 : ExecEndNode(subplanstate);
3232 : }
3233 :
3234 : /* throw away the per-estate tuple table, some node may have used it */
3235 126 : ExecResetTupleTable(estate->es_tupleTable, false);
3236 :
3237 : /* Close any result and trigger target relations attached to this EState */
3238 126 : ExecCloseResultRelations(estate);
3239 :
3240 126 : MemoryContextSwitchTo(oldcontext);
3241 :
3242 : /*
3243 : * NULLify the partition directory before freeing the executor state.
3244 : * Since EvalPlanQualStart() just borrowed the parent EState's directory,
3245 : * we'd better leave it up to the parent to delete it.
3246 : */
3247 126 : estate->es_partition_directory = NULL;
3248 :
3249 126 : FreeExecutorState(estate);
3250 :
3251 : /* Mark EPQState idle */
3252 126 : epqstate->origslot = NULL;
3253 126 : epqstate->recheckestate = NULL;
3254 126 : epqstate->recheckplanstate = NULL;
3255 126 : epqstate->relsubs_rowmark = NULL;
3256 126 : epqstate->relsubs_done = NULL;
3257 126 : epqstate->relsubs_blocked = NULL;
3258 : }
|