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