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