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