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