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