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