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