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