OSDN Git Service

Disallow SELECT FOR UPDATE/SHARE on sequences.
[pg-rex/syncrep.git] / src / backend / executor / execMain.c
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-2011, 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/reloptions.h"
41 #include "access/sysattr.h"
42 #include "access/transam.h"
43 #include "access/xact.h"
44 #include "catalog/heap.h"
45 #include "catalog/namespace.h"
46 #include "catalog/toasting.h"
47 #include "commands/tablespace.h"
48 #include "commands/trigger.h"
49 #include "executor/execdebug.h"
50 #include "executor/instrument.h"
51 #include "miscadmin.h"
52 #include "optimizer/clauses.h"
53 #include "parser/parse_clause.h"
54 #include "parser/parsetree.h"
55 #include "storage/bufmgr.h"
56 #include "storage/lmgr.h"
57 #include "storage/smgr.h"
58 #include "tcop/utility.h"
59 #include "utils/acl.h"
60 #include "utils/lsyscache.h"
61 #include "utils/memutils.h"
62 #include "utils/snapmgr.h"
63 #include "utils/tqual.h"
64
65
66 /* Hooks for plugins to get control in ExecutorStart/Run/Finish/End */
67 ExecutorStart_hook_type ExecutorStart_hook = NULL;
68 ExecutorRun_hook_type ExecutorRun_hook = NULL;
69 ExecutorFinish_hook_type ExecutorFinish_hook = NULL;
70 ExecutorEnd_hook_type ExecutorEnd_hook = NULL;
71
72 /* Hook for plugin to get control in ExecCheckRTPerms() */
73 ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL;
74
75 /* decls for local routines only used within this module */
76 static void InitPlan(QueryDesc *queryDesc, int eflags);
77 static void CheckValidRowMarkRel(Relation rel, RowMarkType markType);
78 static void ExecPostprocessPlan(EState *estate);
79 static void ExecEndPlan(PlanState *planstate, EState *estate);
80 static void ExecutePlan(EState *estate, PlanState *planstate,
81                         CmdType operation,
82                         bool sendTuples,
83                         long numberTuples,
84                         ScanDirection direction,
85                         DestReceiver *dest);
86 static bool ExecCheckRTEPerms(RangeTblEntry *rte);
87 static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
88 static void EvalPlanQualStart(EPQState *epqstate, EState *parentestate,
89                                   Plan *planTree);
90 static void OpenIntoRel(QueryDesc *queryDesc);
91 static void CloseIntoRel(QueryDesc *queryDesc);
92 static void intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
93 static void intorel_receive(TupleTableSlot *slot, DestReceiver *self);
94 static void intorel_shutdown(DestReceiver *self);
95 static void intorel_destroy(DestReceiver *self);
96
97 /* end of local decls */
98
99
100 /* ----------------------------------------------------------------
101  *              ExecutorStart
102  *
103  *              This routine must be called at the beginning of any execution of any
104  *              query plan
105  *
106  * Takes a QueryDesc previously created by CreateQueryDesc (which is separate
107  * only because some places use QueryDescs for utility commands).  The tupDesc
108  * field of the QueryDesc is filled in to describe the tuples that will be
109  * returned, and the internal fields (estate and planstate) are set up.
110  *
111  * eflags contains flag bits as described in executor.h.
112  *
113  * NB: the CurrentMemoryContext when this is called will become the parent
114  * of the per-query context used for this Executor invocation.
115  *
116  * We provide a function hook variable that lets loadable plugins
117  * get control when ExecutorStart is called.  Such a plugin would
118  * normally call standard_ExecutorStart().
119  *
120  * ----------------------------------------------------------------
121  */
122 void
123 ExecutorStart(QueryDesc *queryDesc, int eflags)
124 {
125         if (ExecutorStart_hook)
126                 (*ExecutorStart_hook) (queryDesc, eflags);
127         else
128                 standard_ExecutorStart(queryDesc, eflags);
129 }
130
131 void
132 standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
133 {
134         EState     *estate;
135         MemoryContext oldcontext;
136
137         /* sanity checks: queryDesc must not be started already */
138         Assert(queryDesc != NULL);
139         Assert(queryDesc->estate == NULL);
140
141         /*
142          * If the transaction is read-only, we need to check if any writes are
143          * planned to non-temporary tables.  EXPLAIN is considered read-only.
144          */
145         if (XactReadOnly && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
146                 ExecCheckXactReadOnly(queryDesc->plannedstmt);
147
148         /*
149          * Build EState, switch into per-query memory context for startup.
150          */
151         estate = CreateExecutorState();
152         queryDesc->estate = estate;
153
154         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
155
156         /*
157          * Fill in external parameters, if any, from queryDesc; and allocate
158          * workspace for internal parameters
159          */
160         estate->es_param_list_info = queryDesc->params;
161
162         if (queryDesc->plannedstmt->nParamExec > 0)
163                 estate->es_param_exec_vals = (ParamExecData *)
164                         palloc0(queryDesc->plannedstmt->nParamExec * sizeof(ParamExecData));
165
166         /*
167          * If non-read-only query, set the command ID to mark output tuples with
168          */
169         switch (queryDesc->operation)
170         {
171                 case CMD_SELECT:
172
173                         /*
174                          * SELECT INTO, SELECT FOR UPDATE/SHARE and modifying CTEs need to
175                          * mark tuples
176                          */
177                         if (queryDesc->plannedstmt->intoClause != NULL ||
178                                 queryDesc->plannedstmt->rowMarks != NIL ||
179                                 queryDesc->plannedstmt->hasModifyingCTE)
180                                 estate->es_output_cid = GetCurrentCommandId(true);
181
182                         /*
183                          * A SELECT without modifying CTEs can't possibly queue triggers,
184                          * so force skip-triggers mode. This is just a marginal efficiency
185                          * hack, since AfterTriggerBeginQuery/AfterTriggerEndQuery aren't
186                          * all that expensive, but we might as well do it.
187                          */
188                         if (!queryDesc->plannedstmt->hasModifyingCTE)
189                                 eflags |= EXEC_FLAG_SKIP_TRIGGERS;
190                         break;
191
192                 case CMD_INSERT:
193                 case CMD_DELETE:
194                 case CMD_UPDATE:
195                         estate->es_output_cid = GetCurrentCommandId(true);
196                         break;
197
198                 default:
199                         elog(ERROR, "unrecognized operation code: %d",
200                                  (int) queryDesc->operation);
201                         break;
202         }
203
204         /*
205          * Copy other important information into the EState
206          */
207         estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
208         estate->es_crosscheck_snapshot = RegisterSnapshot(queryDesc->crosscheck_snapshot);
209         estate->es_top_eflags = eflags;
210         estate->es_instrument = queryDesc->instrument_options;
211
212         /*
213          * Initialize the plan state tree
214          */
215         InitPlan(queryDesc, eflags);
216
217         /*
218          * Set up an AFTER-trigger statement context, unless told not to, or
219          * unless it's EXPLAIN-only mode (when ExecutorFinish won't be called).
220          */
221         if (!(eflags & (EXEC_FLAG_SKIP_TRIGGERS | EXEC_FLAG_EXPLAIN_ONLY)))
222                 AfterTriggerBeginQuery();
223
224         MemoryContextSwitchTo(oldcontext);
225 }
226
227 /* ----------------------------------------------------------------
228  *              ExecutorRun
229  *
230  *              This is the main routine of the executor module. It accepts
231  *              the query descriptor from the traffic cop and executes the
232  *              query plan.
233  *
234  *              ExecutorStart must have been called already.
235  *
236  *              If direction is NoMovementScanDirection then nothing is done
237  *              except to start up/shut down the destination.  Otherwise,
238  *              we retrieve up to 'count' tuples in the specified direction.
239  *
240  *              Note: count = 0 is interpreted as no portal limit, i.e., run to
241  *              completion.
242  *
243  *              There is no return value, but output tuples (if any) are sent to
244  *              the destination receiver specified in the QueryDesc; and the number
245  *              of tuples processed at the top level can be found in
246  *              estate->es_processed.
247  *
248  *              We provide a function hook variable that lets loadable plugins
249  *              get control when ExecutorRun is called.  Such a plugin would
250  *              normally call standard_ExecutorRun().
251  *
252  * ----------------------------------------------------------------
253  */
254 void
255 ExecutorRun(QueryDesc *queryDesc,
256                         ScanDirection direction, long count)
257 {
258         if (ExecutorRun_hook)
259                 (*ExecutorRun_hook) (queryDesc, direction, count);
260         else
261                 standard_ExecutorRun(queryDesc, direction, count);
262 }
263
264 void
265 standard_ExecutorRun(QueryDesc *queryDesc,
266                                          ScanDirection direction, long count)
267 {
268         EState     *estate;
269         CmdType         operation;
270         DestReceiver *dest;
271         bool            sendTuples;
272         MemoryContext oldcontext;
273
274         /* sanity checks */
275         Assert(queryDesc != NULL);
276
277         estate = queryDesc->estate;
278
279         Assert(estate != NULL);
280         Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
281
282         /*
283          * Switch into per-query memory context
284          */
285         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
286
287         /* Allow instrumentation of Executor overall runtime */
288         if (queryDesc->totaltime)
289                 InstrStartNode(queryDesc->totaltime);
290
291         /*
292          * extract information from the query descriptor and the query feature.
293          */
294         operation = queryDesc->operation;
295         dest = queryDesc->dest;
296
297         /*
298          * startup tuple receiver, if we will be emitting tuples
299          */
300         estate->es_processed = 0;
301         estate->es_lastoid = InvalidOid;
302
303         sendTuples = (operation == CMD_SELECT ||
304                                   queryDesc->plannedstmt->hasReturning);
305
306         if (sendTuples)
307                 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
308
309         /*
310          * run plan
311          */
312         if (!ScanDirectionIsNoMovement(direction))
313                 ExecutePlan(estate,
314                                         queryDesc->planstate,
315                                         operation,
316                                         sendTuples,
317                                         count,
318                                         direction,
319                                         dest);
320
321         /*
322          * shutdown tuple receiver, if we started it
323          */
324         if (sendTuples)
325                 (*dest->rShutdown) (dest);
326
327         if (queryDesc->totaltime)
328                 InstrStopNode(queryDesc->totaltime, estate->es_processed);
329
330         MemoryContextSwitchTo(oldcontext);
331 }
332
333 /* ----------------------------------------------------------------
334  *              ExecutorFinish
335  *
336  *              This routine must be called after the last ExecutorRun call.
337  *              It performs cleanup such as firing AFTER triggers.      It is
338  *              separate from ExecutorEnd because EXPLAIN ANALYZE needs to
339  *              include these actions in the total runtime.
340  *
341  *              We provide a function hook variable that lets loadable plugins
342  *              get control when ExecutorFinish is called.      Such a plugin would
343  *              normally call standard_ExecutorFinish().
344  *
345  * ----------------------------------------------------------------
346  */
347 void
348 ExecutorFinish(QueryDesc *queryDesc)
349 {
350         if (ExecutorFinish_hook)
351                 (*ExecutorFinish_hook) (queryDesc);
352         else
353                 standard_ExecutorFinish(queryDesc);
354 }
355
356 void
357 standard_ExecutorFinish(QueryDesc *queryDesc)
358 {
359         EState     *estate;
360         MemoryContext oldcontext;
361
362         /* sanity checks */
363         Assert(queryDesc != NULL);
364
365         estate = queryDesc->estate;
366
367         Assert(estate != NULL);
368         Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
369
370         /* This should be run once and only once per Executor instance */
371         Assert(!estate->es_finished);
372
373         /* Switch into per-query memory context */
374         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
375
376         /* Allow instrumentation of Executor overall runtime */
377         if (queryDesc->totaltime)
378                 InstrStartNode(queryDesc->totaltime);
379
380         /* Run ModifyTable nodes to completion */
381         ExecPostprocessPlan(estate);
382
383         /* Execute queued AFTER triggers, unless told not to */
384         if (!(estate->es_top_eflags & EXEC_FLAG_SKIP_TRIGGERS))
385                 AfterTriggerEndQuery(estate);
386
387         if (queryDesc->totaltime)
388                 InstrStopNode(queryDesc->totaltime, 0);
389
390         MemoryContextSwitchTo(oldcontext);
391
392         estate->es_finished = true;
393 }
394
395 /* ----------------------------------------------------------------
396  *              ExecutorEnd
397  *
398  *              This routine must be called at the end of execution of any
399  *              query plan
400  *
401  *              We provide a function hook variable that lets loadable plugins
402  *              get control when ExecutorEnd is called.  Such a plugin would
403  *              normally call standard_ExecutorEnd().
404  *
405  * ----------------------------------------------------------------
406  */
407 void
408 ExecutorEnd(QueryDesc *queryDesc)
409 {
410         if (ExecutorEnd_hook)
411                 (*ExecutorEnd_hook) (queryDesc);
412         else
413                 standard_ExecutorEnd(queryDesc);
414 }
415
416 void
417 standard_ExecutorEnd(QueryDesc *queryDesc)
418 {
419         EState     *estate;
420         MemoryContext oldcontext;
421
422         /* sanity checks */
423         Assert(queryDesc != NULL);
424
425         estate = queryDesc->estate;
426
427         Assert(estate != NULL);
428
429         /*
430          * Check that ExecutorFinish was called, unless in EXPLAIN-only mode. This
431          * Assert is needed because ExecutorFinish is new as of 9.1, and callers
432          * might forget to call it.
433          */
434         Assert(estate->es_finished ||
435                    (estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
436
437         /*
438          * Switch into per-query memory context to run ExecEndPlan
439          */
440         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
441
442         ExecEndPlan(queryDesc->planstate, estate);
443
444         /*
445          * Close the SELECT INTO relation if any
446          */
447         if (estate->es_select_into)
448                 CloseIntoRel(queryDesc);
449
450         /* do away with our snapshots */
451         UnregisterSnapshot(estate->es_snapshot);
452         UnregisterSnapshot(estate->es_crosscheck_snapshot);
453
454         /*
455          * Must switch out of context before destroying it
456          */
457         MemoryContextSwitchTo(oldcontext);
458
459         /*
460          * Release EState and per-query memory context.  This should release
461          * everything the executor has allocated.
462          */
463         FreeExecutorState(estate);
464
465         /* Reset queryDesc fields that no longer point to anything */
466         queryDesc->tupDesc = NULL;
467         queryDesc->estate = NULL;
468         queryDesc->planstate = NULL;
469         queryDesc->totaltime = NULL;
470 }
471
472 /* ----------------------------------------------------------------
473  *              ExecutorRewind
474  *
475  *              This routine may be called on an open queryDesc to rewind it
476  *              to the start.
477  * ----------------------------------------------------------------
478  */
479 void
480 ExecutorRewind(QueryDesc *queryDesc)
481 {
482         EState     *estate;
483         MemoryContext oldcontext;
484
485         /* sanity checks */
486         Assert(queryDesc != NULL);
487
488         estate = queryDesc->estate;
489
490         Assert(estate != NULL);
491
492         /* It's probably not sensible to rescan updating queries */
493         Assert(queryDesc->operation == CMD_SELECT);
494
495         /*
496          * Switch into per-query memory context
497          */
498         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
499
500         /*
501          * rescan plan
502          */
503         ExecReScan(queryDesc->planstate);
504
505         MemoryContextSwitchTo(oldcontext);
506 }
507
508
509 /*
510  * ExecCheckRTPerms
511  *              Check access permissions for all relations listed in a range table.
512  *
513  * Returns true if permissions are adequate.  Otherwise, throws an appropriate
514  * error if ereport_on_violation is true, or simply returns false otherwise.
515  */
516 bool
517 ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
518 {
519         ListCell   *l;
520         bool            result = true;
521
522         foreach(l, rangeTable)
523         {
524                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
525
526                 result = ExecCheckRTEPerms(rte);
527                 if (!result)
528                 {
529                         Assert(rte->rtekind == RTE_RELATION);
530                         if (ereport_on_violation)
531                                 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
532                                                            get_rel_name(rte->relid));
533                         return false;
534                 }
535         }
536
537         if (ExecutorCheckPerms_hook)
538                 result = (*ExecutorCheckPerms_hook) (rangeTable,
539                                                                                          ereport_on_violation);
540         return result;
541 }
542
543 /*
544  * ExecCheckRTEPerms
545  *              Check access permissions for a single RTE.
546  */
547 static bool
548 ExecCheckRTEPerms(RangeTblEntry *rte)
549 {
550         AclMode         requiredPerms;
551         AclMode         relPerms;
552         AclMode         remainingPerms;
553         Oid                     relOid;
554         Oid                     userid;
555         Bitmapset  *tmpset;
556         int                     col;
557
558         /*
559          * Only plain-relation RTEs need to be checked here.  Function RTEs are
560          * checked by init_fcache when the function is prepared for execution.
561          * Join, subquery, and special RTEs need no checks.
562          */
563         if (rte->rtekind != RTE_RELATION)
564                 return true;
565
566         /*
567          * No work if requiredPerms is empty.
568          */
569         requiredPerms = rte->requiredPerms;
570         if (requiredPerms == 0)
571                 return true;
572
573         relOid = rte->relid;
574
575         /*
576          * userid to check as: current user unless we have a setuid indication.
577          *
578          * Note: GetUserId() is presently fast enough that there's no harm in
579          * calling it separately for each RTE.  If that stops being true, we could
580          * call it once in ExecCheckRTPerms and pass the userid down from there.
581          * But for now, no need for the extra clutter.
582          */
583         userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
584
585         /*
586          * We must have *all* the requiredPerms bits, but some of the bits can be
587          * satisfied from column-level rather than relation-level permissions.
588          * First, remove any bits that are satisfied by relation permissions.
589          */
590         relPerms = pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL);
591         remainingPerms = requiredPerms & ~relPerms;
592         if (remainingPerms != 0)
593         {
594                 /*
595                  * If we lack any permissions that exist only as relation permissions,
596                  * we can fail straight away.
597                  */
598                 if (remainingPerms & ~(ACL_SELECT | ACL_INSERT | ACL_UPDATE))
599                         return false;
600
601                 /*
602                  * Check to see if we have the needed privileges at column level.
603                  *
604                  * Note: failures just report a table-level error; it would be nicer
605                  * to report a column-level error if we have some but not all of the
606                  * column privileges.
607                  */
608                 if (remainingPerms & ACL_SELECT)
609                 {
610                         /*
611                          * When the query doesn't explicitly reference any columns (for
612                          * example, SELECT COUNT(*) FROM table), allow the query if we
613                          * have SELECT on any column of the rel, as per SQL spec.
614                          */
615                         if (bms_is_empty(rte->selectedCols))
616                         {
617                                 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
618                                                                                           ACLMASK_ANY) != ACLCHECK_OK)
619                                         return false;
620                         }
621
622                         tmpset = bms_copy(rte->selectedCols);
623                         while ((col = bms_first_member(tmpset)) >= 0)
624                         {
625                                 /* remove the column number offset */
626                                 col += FirstLowInvalidHeapAttributeNumber;
627                                 if (col == InvalidAttrNumber)
628                                 {
629                                         /* Whole-row reference, must have priv on all cols */
630                                         if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
631                                                                                                   ACLMASK_ALL) != ACLCHECK_OK)
632                                                 return false;
633                                 }
634                                 else
635                                 {
636                                         if (pg_attribute_aclcheck(relOid, col, userid,
637                                                                                           ACL_SELECT) != ACLCHECK_OK)
638                                                 return false;
639                                 }
640                         }
641                         bms_free(tmpset);
642                 }
643
644                 /*
645                  * Basically the same for the mod columns, with either INSERT or
646                  * UPDATE privilege as specified by remainingPerms.
647                  */
648                 remainingPerms &= ~ACL_SELECT;
649                 if (remainingPerms != 0)
650                 {
651                         /*
652                          * When the query doesn't explicitly change any columns, allow the
653                          * query if we have permission on any column of the rel.  This is
654                          * to handle SELECT FOR UPDATE as well as possible corner cases in
655                          * INSERT and UPDATE.
656                          */
657                         if (bms_is_empty(rte->modifiedCols))
658                         {
659                                 if (pg_attribute_aclcheck_all(relOid, userid, remainingPerms,
660                                                                                           ACLMASK_ANY) != ACLCHECK_OK)
661                                         return false;
662                         }
663
664                         tmpset = bms_copy(rte->modifiedCols);
665                         while ((col = bms_first_member(tmpset)) >= 0)
666                         {
667                                 /* remove the column number offset */
668                                 col += FirstLowInvalidHeapAttributeNumber;
669                                 if (col == InvalidAttrNumber)
670                                 {
671                                         /* whole-row reference can't happen here */
672                                         elog(ERROR, "whole-row update is not implemented");
673                                 }
674                                 else
675                                 {
676                                         if (pg_attribute_aclcheck(relOid, col, userid,
677                                                                                           remainingPerms) != ACLCHECK_OK)
678                                                 return false;
679                                 }
680                         }
681                         bms_free(tmpset);
682                 }
683         }
684         return true;
685 }
686
687 /*
688  * Check that the query does not imply any writes to non-temp tables.
689  *
690  * Note: in a Hot Standby slave this would need to reject writes to temp
691  * tables as well; but an HS slave can't have created any temp tables
692  * in the first place, so no need to check that.
693  */
694 static void
695 ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
696 {
697         ListCell   *l;
698
699         /*
700          * CREATE TABLE AS or SELECT INTO?
701          *
702          * XXX should we allow this if the destination is temp?  Considering that
703          * it would still require catalog changes, probably not.
704          */
705         if (plannedstmt->intoClause != NULL)
706                 PreventCommandIfReadOnly(CreateCommandTag((Node *) plannedstmt));
707
708         /* Fail if write permissions are requested on any non-temp table */
709         foreach(l, plannedstmt->rtable)
710         {
711                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
712
713                 if (rte->rtekind != RTE_RELATION)
714                         continue;
715
716                 if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
717                         continue;
718
719                 if (isTempNamespace(get_rel_namespace(rte->relid)))
720                         continue;
721
722                 PreventCommandIfReadOnly(CreateCommandTag((Node *) plannedstmt));
723         }
724 }
725
726
727 /* ----------------------------------------------------------------
728  *              InitPlan
729  *
730  *              Initializes the query plan: open files, allocate storage
731  *              and start up the rule manager
732  * ----------------------------------------------------------------
733  */
734 static void
735 InitPlan(QueryDesc *queryDesc, int eflags)
736 {
737         CmdType         operation = queryDesc->operation;
738         PlannedStmt *plannedstmt = queryDesc->plannedstmt;
739         Plan       *plan = plannedstmt->planTree;
740         List       *rangeTable = plannedstmt->rtable;
741         EState     *estate = queryDesc->estate;
742         PlanState  *planstate;
743         TupleDesc       tupType;
744         ListCell   *l;
745         int                     i;
746
747         /*
748          * Do permissions checks
749          */
750         ExecCheckRTPerms(rangeTable, true);
751
752         /*
753          * initialize the node's execution state
754          */
755         estate->es_range_table = rangeTable;
756         estate->es_plannedstmt = plannedstmt;
757
758         /*
759          * initialize result relation stuff, and open/lock the result rels.
760          *
761          * We must do this before initializing the plan tree, else we might try to
762          * do a lock upgrade if a result rel is also a source rel.
763          */
764         if (plannedstmt->resultRelations)
765         {
766                 List       *resultRelations = plannedstmt->resultRelations;
767                 int                     numResultRelations = list_length(resultRelations);
768                 ResultRelInfo *resultRelInfos;
769                 ResultRelInfo *resultRelInfo;
770
771                 resultRelInfos = (ResultRelInfo *)
772                         palloc(numResultRelations * sizeof(ResultRelInfo));
773                 resultRelInfo = resultRelInfos;
774                 foreach(l, resultRelations)
775                 {
776                         Index           resultRelationIndex = lfirst_int(l);
777                         Oid                     resultRelationOid;
778                         Relation        resultRelation;
779
780                         resultRelationOid = getrelid(resultRelationIndex, rangeTable);
781                         resultRelation = heap_open(resultRelationOid, RowExclusiveLock);
782                         InitResultRelInfo(resultRelInfo,
783                                                           resultRelation,
784                                                           resultRelationIndex,
785                                                           estate->es_instrument);
786                         resultRelInfo++;
787                 }
788                 estate->es_result_relations = resultRelInfos;
789                 estate->es_num_result_relations = numResultRelations;
790                 /* es_result_relation_info is NULL except when within ModifyTable */
791                 estate->es_result_relation_info = NULL;
792         }
793         else
794         {
795                 /*
796                  * if no result relation, then set state appropriately
797                  */
798                 estate->es_result_relations = NULL;
799                 estate->es_num_result_relations = 0;
800                 estate->es_result_relation_info = NULL;
801         }
802
803         /*
804          * Similarly, we have to lock relations selected FOR UPDATE/FOR SHARE
805          * before we initialize the plan tree, else we'd be risking lock upgrades.
806          * While we are at it, build the ExecRowMark list.
807          */
808         estate->es_rowMarks = NIL;
809         foreach(l, plannedstmt->rowMarks)
810         {
811                 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
812                 Oid                     relid;
813                 Relation        relation;
814                 ExecRowMark *erm;
815
816                 /* ignore "parent" rowmarks; they are irrelevant at runtime */
817                 if (rc->isParent)
818                         continue;
819
820                 switch (rc->markType)
821                 {
822                         case ROW_MARK_EXCLUSIVE:
823                         case ROW_MARK_SHARE:
824                                 relid = getrelid(rc->rti, rangeTable);
825                                 relation = heap_open(relid, RowShareLock);
826                                 break;
827                         case ROW_MARK_REFERENCE:
828                                 relid = getrelid(rc->rti, rangeTable);
829                                 relation = heap_open(relid, AccessShareLock);
830                                 break;
831                         case ROW_MARK_COPY:
832                                 /* there's no real table here ... */
833                                 relation = NULL;
834                                 break;
835                         default:
836                                 elog(ERROR, "unrecognized markType: %d", rc->markType);
837                                 relation = NULL;        /* keep compiler quiet */
838                                 break;
839                 }
840
841                 /* Check that relation is a legal target for marking */
842                 if (relation)
843                         CheckValidRowMarkRel(relation, rc->markType);
844
845                 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
846                 erm->relation = relation;
847                 erm->rti = rc->rti;
848                 erm->prti = rc->prti;
849                 erm->rowmarkId = rc->rowmarkId;
850                 erm->markType = rc->markType;
851                 erm->noWait = rc->noWait;
852                 ItemPointerSetInvalid(&(erm->curCtid));
853                 estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
854         }
855
856         /*
857          * Detect whether we're doing SELECT INTO.  If so, set the es_into_oids
858          * flag appropriately so that the plan tree will be initialized with the
859          * correct tuple descriptors.  (Other SELECT INTO stuff comes later.)
860          */
861         estate->es_select_into = false;
862         if (operation == CMD_SELECT && plannedstmt->intoClause != NULL)
863         {
864                 estate->es_select_into = true;
865                 estate->es_into_oids = interpretOidsOption(plannedstmt->intoClause->options);
866         }
867
868         /*
869          * Initialize the executor's tuple table to empty.
870          */
871         estate->es_tupleTable = NIL;
872         estate->es_trig_tuple_slot = NULL;
873         estate->es_trig_oldtup_slot = NULL;
874
875         /* mark EvalPlanQual not active */
876         estate->es_epqTuple = NULL;
877         estate->es_epqTupleSet = NULL;
878         estate->es_epqScanDone = NULL;
879
880         /*
881          * Initialize private state information for each SubPlan.  We must do this
882          * before running ExecInitNode on the main query tree, since
883          * ExecInitSubPlan expects to be able to find these entries.
884          */
885         Assert(estate->es_subplanstates == NIL);
886         i = 1;                                          /* subplan indices count from 1 */
887         foreach(l, plannedstmt->subplans)
888         {
889                 Plan       *subplan = (Plan *) lfirst(l);
890                 PlanState  *subplanstate;
891                 int                     sp_eflags;
892
893                 /*
894                  * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
895                  * it is a parameterless subplan (not initplan), we suggest that it be
896                  * prepared to handle REWIND efficiently; otherwise there is no need.
897                  */
898                 sp_eflags = eflags & EXEC_FLAG_EXPLAIN_ONLY;
899                 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
900                         sp_eflags |= EXEC_FLAG_REWIND;
901
902                 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
903
904                 estate->es_subplanstates = lappend(estate->es_subplanstates,
905                                                                                    subplanstate);
906
907                 i++;
908         }
909
910         /*
911          * Initialize the private state information for all the nodes in the query
912          * tree.  This opens files, allocates storage and leaves us ready to start
913          * processing tuples.
914          */
915         planstate = ExecInitNode(plan, estate, eflags);
916
917         /*
918          * Get the tuple descriptor describing the type of tuples to return. (this
919          * is especially important if we are creating a relation with "SELECT
920          * INTO")
921          */
922         tupType = ExecGetResultType(planstate);
923
924         /*
925          * Initialize the junk filter if needed.  SELECT queries need a filter if
926          * there are any junk attrs in the top-level tlist.
927          */
928         if (operation == CMD_SELECT)
929         {
930                 bool            junk_filter_needed = false;
931                 ListCell   *tlist;
932
933                 foreach(tlist, plan->targetlist)
934                 {
935                         TargetEntry *tle = (TargetEntry *) lfirst(tlist);
936
937                         if (tle->resjunk)
938                         {
939                                 junk_filter_needed = true;
940                                 break;
941                         }
942                 }
943
944                 if (junk_filter_needed)
945                 {
946                         JunkFilter *j;
947
948                         j = ExecInitJunkFilter(planstate->plan->targetlist,
949                                                                    tupType->tdhasoid,
950                                                                    ExecInitExtraTupleSlot(estate));
951                         estate->es_junkFilter = j;
952
953                         /* Want to return the cleaned tuple type */
954                         tupType = j->jf_cleanTupType;
955                 }
956         }
957
958         queryDesc->tupDesc = tupType;
959         queryDesc->planstate = planstate;
960
961         /*
962          * If doing SELECT INTO, initialize the "into" relation.  We must wait
963          * till now so we have the "clean" result tuple type to create the new
964          * table from.
965          *
966          * If EXPLAIN, skip creating the "into" relation.
967          */
968         if (estate->es_select_into && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
969                 OpenIntoRel(queryDesc);
970 }
971
972 /*
973  * Check that a proposed result relation is a legal target for the operation
974  *
975  * In most cases parser and/or planner should have noticed this already, but
976  * let's make sure.  In the view case we do need a test here, because if the
977  * view wasn't rewritten by a rule, it had better have an INSTEAD trigger.
978  *
979  * Note: when changing this function, you probably also need to look at
980  * CheckValidRowMarkRel.
981  */
982 void
983 CheckValidResultRel(Relation resultRel, CmdType operation)
984 {
985         TriggerDesc *trigDesc = resultRel->trigdesc;
986
987         switch (resultRel->rd_rel->relkind)
988         {
989                 case RELKIND_RELATION:
990                         /* OK */
991                         break;
992                 case RELKIND_SEQUENCE:
993                         ereport(ERROR,
994                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
995                                          errmsg("cannot change sequence \"%s\"",
996                                                         RelationGetRelationName(resultRel))));
997                         break;
998                 case RELKIND_TOASTVALUE:
999                         ereport(ERROR,
1000                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1001                                          errmsg("cannot change TOAST relation \"%s\"",
1002                                                         RelationGetRelationName(resultRel))));
1003                         break;
1004                 case RELKIND_VIEW:
1005                         switch (operation)
1006                         {
1007                                 case CMD_INSERT:
1008                                         if (!trigDesc || !trigDesc->trig_insert_instead_row)
1009                                                 ereport(ERROR,
1010                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1011                                                    errmsg("cannot insert into view \"%s\"",
1012                                                                   RelationGetRelationName(resultRel)),
1013                                                    errhint("You need an unconditional ON INSERT DO INSTEAD rule or an INSTEAD OF INSERT trigger.")));
1014                                         break;
1015                                 case CMD_UPDATE:
1016                                         if (!trigDesc || !trigDesc->trig_update_instead_row)
1017                                                 ereport(ERROR,
1018                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1019                                                    errmsg("cannot update view \"%s\"",
1020                                                                   RelationGetRelationName(resultRel)),
1021                                                    errhint("You need an unconditional ON UPDATE DO INSTEAD rule or an INSTEAD OF UPDATE trigger.")));
1022                                         break;
1023                                 case CMD_DELETE:
1024                                         if (!trigDesc || !trigDesc->trig_delete_instead_row)
1025                                                 ereport(ERROR,
1026                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1027                                                    errmsg("cannot delete from view \"%s\"",
1028                                                                   RelationGetRelationName(resultRel)),
1029                                                    errhint("You need an unconditional ON DELETE DO INSTEAD rule or an INSTEAD OF DELETE trigger.")));
1030                                         break;
1031                                 default:
1032                                         elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1033                                         break;
1034                         }
1035                         break;
1036                 case RELKIND_FOREIGN_TABLE:
1037                         ereport(ERROR,
1038                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1039                                          errmsg("cannot change foreign table \"%s\"",
1040                                                         RelationGetRelationName(resultRel))));
1041                         break;
1042                 default:
1043                         ereport(ERROR,
1044                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1045                                          errmsg("cannot change relation \"%s\"",
1046                                                         RelationGetRelationName(resultRel))));
1047                         break;
1048         }
1049 }
1050
1051 /*
1052  * Check that a proposed rowmark target relation is a legal target
1053  *
1054  * In most cases parser and/or planner should have noticed this already, but
1055  * they don't cover all cases.
1056  */
1057 static void
1058 CheckValidRowMarkRel(Relation rel, RowMarkType markType)
1059 {
1060         switch (rel->rd_rel->relkind)
1061         {
1062                 case RELKIND_RELATION:
1063                         /* OK */
1064                         break;
1065                 case RELKIND_SEQUENCE:
1066                         /* Must disallow this because we don't vacuum sequences */
1067                         ereport(ERROR,
1068                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1069                                          errmsg("cannot lock rows in sequence \"%s\"",
1070                                                         RelationGetRelationName(rel))));
1071                         break;
1072                 case RELKIND_TOASTVALUE:
1073                         /* We could allow this, but there seems no good reason to */
1074                         ereport(ERROR,
1075                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1076                                          errmsg("cannot lock rows in TOAST relation \"%s\"",
1077                                                         RelationGetRelationName(rel))));
1078                         break;
1079                 case RELKIND_VIEW:
1080                         /* Should not get here */
1081                         ereport(ERROR,
1082                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1083                                          errmsg("cannot lock rows in view \"%s\"",
1084                                                         RelationGetRelationName(rel))));
1085                         break;
1086                 case RELKIND_FOREIGN_TABLE:
1087                         /* Perhaps we can support this someday, but not today */
1088                         ereport(ERROR,
1089                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1090                                          errmsg("cannot lock rows in foreign table \"%s\"",
1091                                                         RelationGetRelationName(rel))));
1092                         break;
1093                 default:
1094                         ereport(ERROR,
1095                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1096                                          errmsg("cannot lock rows in relation \"%s\"",
1097                                                         RelationGetRelationName(rel))));
1098                         break;
1099         }
1100 }
1101
1102 /*
1103  * Initialize ResultRelInfo data for one result relation
1104  *
1105  * Caution: before Postgres 9.1, this function included the relkind checking
1106  * that's now in CheckValidResultRel, and it also did ExecOpenIndices if
1107  * appropriate.  Be sure callers cover those needs.
1108  */
1109 void
1110 InitResultRelInfo(ResultRelInfo *resultRelInfo,
1111                                   Relation resultRelationDesc,
1112                                   Index resultRelationIndex,
1113                                   int instrument_options)
1114 {
1115         MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1116         resultRelInfo->type = T_ResultRelInfo;
1117         resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1118         resultRelInfo->ri_RelationDesc = resultRelationDesc;
1119         resultRelInfo->ri_NumIndices = 0;
1120         resultRelInfo->ri_IndexRelationDescs = NULL;
1121         resultRelInfo->ri_IndexRelationInfo = NULL;
1122         /* make a copy so as not to depend on relcache info not changing... */
1123         resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1124         if (resultRelInfo->ri_TrigDesc)
1125         {
1126                 int                     n = resultRelInfo->ri_TrigDesc->numtriggers;
1127
1128                 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1129                         palloc0(n * sizeof(FmgrInfo));
1130                 resultRelInfo->ri_TrigWhenExprs = (List **)
1131                         palloc0(n * sizeof(List *));
1132                 if (instrument_options)
1133                         resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options);
1134         }
1135         else
1136         {
1137                 resultRelInfo->ri_TrigFunctions = NULL;
1138                 resultRelInfo->ri_TrigWhenExprs = NULL;
1139                 resultRelInfo->ri_TrigInstrument = NULL;
1140         }
1141         resultRelInfo->ri_ConstraintExprs = NULL;
1142         resultRelInfo->ri_junkFilter = NULL;
1143         resultRelInfo->ri_projectReturning = NULL;
1144 }
1145
1146 /*
1147  *              ExecGetTriggerResultRel
1148  *
1149  * Get a ResultRelInfo for a trigger target relation.  Most of the time,
1150  * triggers are fired on one of the result relations of the query, and so
1151  * we can just return a member of the es_result_relations array.  (Note: in
1152  * self-join situations there might be multiple members with the same OID;
1153  * if so it doesn't matter which one we pick.)  However, it is sometimes
1154  * necessary to fire triggers on other relations; this happens mainly when an
1155  * RI update trigger queues additional triggers on other relations, which will
1156  * be processed in the context of the outer query.      For efficiency's sake,
1157  * we want to have a ResultRelInfo for those triggers too; that can avoid
1158  * repeated re-opening of the relation.  (It also provides a way for EXPLAIN
1159  * ANALYZE to report the runtimes of such triggers.)  So we make additional
1160  * ResultRelInfo's as needed, and save them in es_trig_target_relations.
1161  */
1162 ResultRelInfo *
1163 ExecGetTriggerResultRel(EState *estate, Oid relid)
1164 {
1165         ResultRelInfo *rInfo;
1166         int                     nr;
1167         ListCell   *l;
1168         Relation        rel;
1169         MemoryContext oldcontext;
1170
1171         /* First, search through the query result relations */
1172         rInfo = estate->es_result_relations;
1173         nr = estate->es_num_result_relations;
1174         while (nr > 0)
1175         {
1176                 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1177                         return rInfo;
1178                 rInfo++;
1179                 nr--;
1180         }
1181         /* Nope, but maybe we already made an extra ResultRelInfo for it */
1182         foreach(l, estate->es_trig_target_relations)
1183         {
1184                 rInfo = (ResultRelInfo *) lfirst(l);
1185                 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1186                         return rInfo;
1187         }
1188         /* Nope, so we need a new one */
1189
1190         /*
1191          * Open the target relation's relcache entry.  We assume that an
1192          * appropriate lock is still held by the backend from whenever the trigger
1193          * event got queued, so we need take no new lock here.  Also, we need not
1194          * recheck the relkind, so no need for CheckValidResultRel.
1195          */
1196         rel = heap_open(relid, NoLock);
1197
1198         /*
1199          * Make the new entry in the right context.
1200          */
1201         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1202         rInfo = makeNode(ResultRelInfo);
1203         InitResultRelInfo(rInfo,
1204                                           rel,
1205                                           0,            /* dummy rangetable index */
1206                                           estate->es_instrument);
1207         estate->es_trig_target_relations =
1208                 lappend(estate->es_trig_target_relations, rInfo);
1209         MemoryContextSwitchTo(oldcontext);
1210
1211         /*
1212          * Currently, we don't need any index information in ResultRelInfos used
1213          * only for triggers, so no need to call ExecOpenIndices.
1214          */
1215
1216         return rInfo;
1217 }
1218
1219 /*
1220  *              ExecContextForcesOids
1221  *
1222  * This is pretty grotty: when doing INSERT, UPDATE, or SELECT INTO,
1223  * we need to ensure that result tuples have space for an OID iff they are
1224  * going to be stored into a relation that has OIDs.  In other contexts
1225  * we are free to choose whether to leave space for OIDs in result tuples
1226  * (we generally don't want to, but we do if a physical-tlist optimization
1227  * is possible).  This routine checks the plan context and returns TRUE if the
1228  * choice is forced, FALSE if the choice is not forced.  In the TRUE case,
1229  * *hasoids is set to the required value.
1230  *
1231  * One reason this is ugly is that all plan nodes in the plan tree will emit
1232  * tuples with space for an OID, though we really only need the topmost node
1233  * to do so.  However, node types like Sort don't project new tuples but just
1234  * return their inputs, and in those cases the requirement propagates down
1235  * to the input node.  Eventually we might make this code smart enough to
1236  * recognize how far down the requirement really goes, but for now we just
1237  * make all plan nodes do the same thing if the top level forces the choice.
1238  *
1239  * We assume that if we are generating tuples for INSERT or UPDATE,
1240  * estate->es_result_relation_info is already set up to describe the target
1241  * relation.  Note that in an UPDATE that spans an inheritance tree, some of
1242  * the target relations may have OIDs and some not.  We have to make the
1243  * decisions on a per-relation basis as we initialize each of the subplans of
1244  * the ModifyTable node, so ModifyTable has to set es_result_relation_info
1245  * while initializing each subplan.
1246  *
1247  * SELECT INTO is even uglier, because we don't have the INTO relation's
1248  * descriptor available when this code runs; we have to look aside at a
1249  * flag set by InitPlan().
1250  */
1251 bool
1252 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
1253 {
1254         ResultRelInfo *ri = planstate->state->es_result_relation_info;
1255
1256         if (ri != NULL)
1257         {
1258                 Relation        rel = ri->ri_RelationDesc;
1259
1260                 if (rel != NULL)
1261                 {
1262                         *hasoids = rel->rd_rel->relhasoids;
1263                         return true;
1264                 }
1265         }
1266
1267         if (planstate->state->es_select_into)
1268         {
1269                 *hasoids = planstate->state->es_into_oids;
1270                 return true;
1271         }
1272
1273         return false;
1274 }
1275
1276 /* ----------------------------------------------------------------
1277  *              ExecPostprocessPlan
1278  *
1279  *              Give plan nodes a final chance to execute before shutdown
1280  * ----------------------------------------------------------------
1281  */
1282 static void
1283 ExecPostprocessPlan(EState *estate)
1284 {
1285         ListCell   *lc;
1286
1287         /*
1288          * Make sure nodes run forward.
1289          */
1290         estate->es_direction = ForwardScanDirection;
1291
1292         /*
1293          * Run any secondary ModifyTable nodes to completion, in case the main
1294          * query did not fetch all rows from them.      (We do this to ensure that
1295          * such nodes have predictable results.)
1296          */
1297         foreach(lc, estate->es_auxmodifytables)
1298         {
1299                 PlanState  *ps = (PlanState *) lfirst(lc);
1300
1301                 for (;;)
1302                 {
1303                         TupleTableSlot *slot;
1304
1305                         /* Reset the per-output-tuple exprcontext each time */
1306                         ResetPerTupleExprContext(estate);
1307
1308                         slot = ExecProcNode(ps);
1309
1310                         if (TupIsNull(slot))
1311                                 break;
1312                 }
1313         }
1314 }
1315
1316 /* ----------------------------------------------------------------
1317  *              ExecEndPlan
1318  *
1319  *              Cleans up the query plan -- closes files and frees up storage
1320  *
1321  * NOTE: we are no longer very worried about freeing storage per se
1322  * in this code; FreeExecutorState should be guaranteed to release all
1323  * memory that needs to be released.  What we are worried about doing
1324  * is closing relations and dropping buffer pins.  Thus, for example,
1325  * tuple tables must be cleared or dropped to ensure pins are released.
1326  * ----------------------------------------------------------------
1327  */
1328 static void
1329 ExecEndPlan(PlanState *planstate, EState *estate)
1330 {
1331         ResultRelInfo *resultRelInfo;
1332         int                     i;
1333         ListCell   *l;
1334
1335         /*
1336          * shut down the node-type-specific query processing
1337          */
1338         ExecEndNode(planstate);
1339
1340         /*
1341          * for subplans too
1342          */
1343         foreach(l, estate->es_subplanstates)
1344         {
1345                 PlanState  *subplanstate = (PlanState *) lfirst(l);
1346
1347                 ExecEndNode(subplanstate);
1348         }
1349
1350         /*
1351          * destroy the executor's tuple table.  Actually we only care about
1352          * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1353          * the TupleTableSlots, since the containing memory context is about to go
1354          * away anyway.
1355          */
1356         ExecResetTupleTable(estate->es_tupleTable, false);
1357
1358         /*
1359          * close the result relation(s) if any, but hold locks until xact commit.
1360          */
1361         resultRelInfo = estate->es_result_relations;
1362         for (i = estate->es_num_result_relations; i > 0; i--)
1363         {
1364                 /* Close indices and then the relation itself */
1365                 ExecCloseIndices(resultRelInfo);
1366                 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1367                 resultRelInfo++;
1368         }
1369
1370         /*
1371          * likewise close any trigger target relations
1372          */
1373         foreach(l, estate->es_trig_target_relations)
1374         {
1375                 resultRelInfo = (ResultRelInfo *) lfirst(l);
1376                 /* Close indices and then the relation itself */
1377                 ExecCloseIndices(resultRelInfo);
1378                 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1379         }
1380
1381         /*
1382          * close any relations selected FOR UPDATE/FOR SHARE, again keeping locks
1383          */
1384         foreach(l, estate->es_rowMarks)
1385         {
1386                 ExecRowMark *erm = (ExecRowMark *) lfirst(l);
1387
1388                 if (erm->relation)
1389                         heap_close(erm->relation, NoLock);
1390         }
1391 }
1392
1393 /* ----------------------------------------------------------------
1394  *              ExecutePlan
1395  *
1396  *              Processes the query plan until we have processed 'numberTuples' tuples,
1397  *              moving in the specified direction.
1398  *
1399  *              Runs to completion if numberTuples is 0
1400  *
1401  * Note: the ctid attribute is a 'junk' attribute that is removed before the
1402  * user can see it
1403  * ----------------------------------------------------------------
1404  */
1405 static void
1406 ExecutePlan(EState *estate,
1407                         PlanState *planstate,
1408                         CmdType operation,
1409                         bool sendTuples,
1410                         long numberTuples,
1411                         ScanDirection direction,
1412                         DestReceiver *dest)
1413 {
1414         TupleTableSlot *slot;
1415         long            current_tuple_count;
1416
1417         /*
1418          * initialize local variables
1419          */
1420         current_tuple_count = 0;
1421
1422         /*
1423          * Set the direction.
1424          */
1425         estate->es_direction = direction;
1426
1427         /*
1428          * Loop until we've processed the proper number of tuples from the plan.
1429          */
1430         for (;;)
1431         {
1432                 /* Reset the per-output-tuple exprcontext */
1433                 ResetPerTupleExprContext(estate);
1434
1435                 /*
1436                  * Execute the plan and obtain a tuple
1437                  */
1438                 slot = ExecProcNode(planstate);
1439
1440                 /*
1441                  * if the tuple is null, then we assume there is nothing more to
1442                  * process so we just end the loop...
1443                  */
1444                 if (TupIsNull(slot))
1445                         break;
1446
1447                 /*
1448                  * If we have a junk filter, then project a new tuple with the junk
1449                  * removed.
1450                  *
1451                  * Store this new "clean" tuple in the junkfilter's resultSlot.
1452                  * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1453                  * because that tuple slot has the wrong descriptor.)
1454                  */
1455                 if (estate->es_junkFilter != NULL)
1456                         slot = ExecFilterJunk(estate->es_junkFilter, slot);
1457
1458                 /*
1459                  * If we are supposed to send the tuple somewhere, do so. (In
1460                  * practice, this is probably always the case at this point.)
1461                  */
1462                 if (sendTuples)
1463                         (*dest->receiveSlot) (slot, dest);
1464
1465                 /*
1466                  * Count tuples processed, if this is a SELECT.  (For other operation
1467                  * types, the ModifyTable plan node must count the appropriate
1468                  * events.)
1469                  */
1470                 if (operation == CMD_SELECT)
1471                         (estate->es_processed)++;
1472
1473                 /*
1474                  * check our tuple count.. if we've processed the proper number then
1475                  * quit, else loop again and process more tuples.  Zero numberTuples
1476                  * means no limit.
1477                  */
1478                 current_tuple_count++;
1479                 if (numberTuples && numberTuples == current_tuple_count)
1480                         break;
1481         }
1482 }
1483
1484
1485 /*
1486  * ExecRelCheck --- check that tuple meets constraints for result relation
1487  */
1488 static const char *
1489 ExecRelCheck(ResultRelInfo *resultRelInfo,
1490                          TupleTableSlot *slot, EState *estate)
1491 {
1492         Relation        rel = resultRelInfo->ri_RelationDesc;
1493         int                     ncheck = rel->rd_att->constr->num_check;
1494         ConstrCheck *check = rel->rd_att->constr->check;
1495         ExprContext *econtext;
1496         MemoryContext oldContext;
1497         List       *qual;
1498         int                     i;
1499
1500         /*
1501          * If first time through for this result relation, build expression
1502          * nodetrees for rel's constraint expressions.  Keep them in the per-query
1503          * memory context so they'll survive throughout the query.
1504          */
1505         if (resultRelInfo->ri_ConstraintExprs == NULL)
1506         {
1507                 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1508                 resultRelInfo->ri_ConstraintExprs =
1509                         (List **) palloc(ncheck * sizeof(List *));
1510                 for (i = 0; i < ncheck; i++)
1511                 {
1512                         /* ExecQual wants implicit-AND form */
1513                         qual = make_ands_implicit(stringToNode(check[i].ccbin));
1514                         resultRelInfo->ri_ConstraintExprs[i] = (List *)
1515                                 ExecPrepareExpr((Expr *) qual, estate);
1516                 }
1517                 MemoryContextSwitchTo(oldContext);
1518         }
1519
1520         /*
1521          * We will use the EState's per-tuple context for evaluating constraint
1522          * expressions (creating it if it's not already there).
1523          */
1524         econtext = GetPerTupleExprContext(estate);
1525
1526         /* Arrange for econtext's scan tuple to be the tuple under test */
1527         econtext->ecxt_scantuple = slot;
1528
1529         /* And evaluate the constraints */
1530         for (i = 0; i < ncheck; i++)
1531         {
1532                 qual = resultRelInfo->ri_ConstraintExprs[i];
1533
1534                 /*
1535                  * NOTE: SQL92 specifies that a NULL result from a constraint
1536                  * expression is not to be treated as a failure.  Therefore, tell
1537                  * ExecQual to return TRUE for NULL.
1538                  */
1539                 if (!ExecQual(qual, econtext, true))
1540                         return check[i].ccname;
1541         }
1542
1543         /* NULL result means no error */
1544         return NULL;
1545 }
1546
1547 void
1548 ExecConstraints(ResultRelInfo *resultRelInfo,
1549                                 TupleTableSlot *slot, EState *estate)
1550 {
1551         Relation        rel = resultRelInfo->ri_RelationDesc;
1552         TupleConstr *constr = rel->rd_att->constr;
1553
1554         Assert(constr);
1555
1556         if (constr->has_not_null)
1557         {
1558                 int                     natts = rel->rd_att->natts;
1559                 int                     attrChk;
1560
1561                 for (attrChk = 1; attrChk <= natts; attrChk++)
1562                 {
1563                         if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1564                                 slot_attisnull(slot, attrChk))
1565                                 ereport(ERROR,
1566                                                 (errcode(ERRCODE_NOT_NULL_VIOLATION),
1567                                                  errmsg("null value in column \"%s\" violates not-null constraint",
1568                                                 NameStr(rel->rd_att->attrs[attrChk - 1]->attname))));
1569                 }
1570         }
1571
1572         if (constr->num_check > 0)
1573         {
1574                 const char *failed;
1575
1576                 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1577                         ereport(ERROR,
1578                                         (errcode(ERRCODE_CHECK_VIOLATION),
1579                                          errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1580                                                         RelationGetRelationName(rel), failed)));
1581         }
1582 }
1583
1584
1585 /*
1586  * ExecFindRowMark -- find the ExecRowMark struct for given rangetable index
1587  */
1588 ExecRowMark *
1589 ExecFindRowMark(EState *estate, Index rti)
1590 {
1591         ListCell   *lc;
1592
1593         foreach(lc, estate->es_rowMarks)
1594         {
1595                 ExecRowMark *erm = (ExecRowMark *) lfirst(lc);
1596
1597                 if (erm->rti == rti)
1598                         return erm;
1599         }
1600         elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
1601         return NULL;                            /* keep compiler quiet */
1602 }
1603
1604 /*
1605  * ExecBuildAuxRowMark -- create an ExecAuxRowMark struct
1606  *
1607  * Inputs are the underlying ExecRowMark struct and the targetlist of the
1608  * input plan node (not planstate node!).  We need the latter to find out
1609  * the column numbers of the resjunk columns.
1610  */
1611 ExecAuxRowMark *
1612 ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
1613 {
1614         ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
1615         char            resname[32];
1616
1617         aerm->rowmark = erm;
1618
1619         /* Look up the resjunk columns associated with this rowmark */
1620         if (erm->relation)
1621         {
1622                 Assert(erm->markType != ROW_MARK_COPY);
1623
1624                 /* if child rel, need tableoid */
1625                 if (erm->rti != erm->prti)
1626                 {
1627                         snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
1628                         aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
1629                                                                                                                    resname);
1630                         if (!AttributeNumberIsValid(aerm->toidAttNo))
1631                                 elog(ERROR, "could not find junk %s column", resname);
1632                 }
1633
1634                 /* always need ctid for real relations */
1635                 snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
1636                 aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
1637                                                                                                            resname);
1638                 if (!AttributeNumberIsValid(aerm->ctidAttNo))
1639                         elog(ERROR, "could not find junk %s column", resname);
1640         }
1641         else
1642         {
1643                 Assert(erm->markType == ROW_MARK_COPY);
1644
1645                 snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
1646                 aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
1647                                                                                                                 resname);
1648                 if (!AttributeNumberIsValid(aerm->wholeAttNo))
1649                         elog(ERROR, "could not find junk %s column", resname);
1650         }
1651
1652         return aerm;
1653 }
1654
1655
1656 /*
1657  * EvalPlanQual logic --- recheck modified tuple(s) to see if we want to
1658  * process the updated version under READ COMMITTED rules.
1659  *
1660  * See backend/executor/README for some info about how this works.
1661  */
1662
1663
1664 /*
1665  * Check a modified tuple to see if we want to process its updated version
1666  * under READ COMMITTED rules.
1667  *
1668  *      estate - outer executor state data
1669  *      epqstate - state for EvalPlanQual rechecking
1670  *      relation - table containing tuple
1671  *      rti - rangetable index of table containing tuple
1672  *      *tid - t_ctid from the outdated tuple (ie, next updated version)
1673  *      priorXmax - t_xmax from the outdated tuple
1674  *
1675  * *tid is also an output parameter: it's modified to hold the TID of the
1676  * latest version of the tuple (note this may be changed even on failure)
1677  *
1678  * Returns a slot containing the new candidate update/delete tuple, or
1679  * NULL if we determine we shouldn't process the row.
1680  */
1681 TupleTableSlot *
1682 EvalPlanQual(EState *estate, EPQState *epqstate,
1683                          Relation relation, Index rti,
1684                          ItemPointer tid, TransactionId priorXmax)
1685 {
1686         TupleTableSlot *slot;
1687         HeapTuple       copyTuple;
1688
1689         Assert(rti > 0);
1690
1691         /*
1692          * Get and lock the updated version of the row; if fail, return NULL.
1693          */
1694         copyTuple = EvalPlanQualFetch(estate, relation, LockTupleExclusive,
1695                                                                   tid, priorXmax);
1696
1697         if (copyTuple == NULL)
1698                 return NULL;
1699
1700         /*
1701          * For UPDATE/DELETE we have to return tid of actual row we're executing
1702          * PQ for.
1703          */
1704         *tid = copyTuple->t_self;
1705
1706         /*
1707          * Need to run a recheck subquery.      Initialize or reinitialize EPQ state.
1708          */
1709         EvalPlanQualBegin(epqstate, estate);
1710
1711         /*
1712          * Free old test tuple, if any, and store new tuple where relation's scan
1713          * node will see it
1714          */
1715         EvalPlanQualSetTuple(epqstate, rti, copyTuple);
1716
1717         /*
1718          * Fetch any non-locked source rows
1719          */
1720         EvalPlanQualFetchRowMarks(epqstate);
1721
1722         /*
1723          * Run the EPQ query.  We assume it will return at most one tuple.
1724          */
1725         slot = EvalPlanQualNext(epqstate);
1726
1727         /*
1728          * If we got a tuple, force the slot to materialize the tuple so that it
1729          * is not dependent on any local state in the EPQ query (in particular,
1730          * it's highly likely that the slot contains references to any pass-by-ref
1731          * datums that may be present in copyTuple).  As with the next step, this
1732          * is to guard against early re-use of the EPQ query.
1733          */
1734         if (!TupIsNull(slot))
1735                 (void) ExecMaterializeSlot(slot);
1736
1737         /*
1738          * Clear out the test tuple.  This is needed in case the EPQ query is
1739          * re-used to test a tuple for a different relation.  (Not clear that can
1740          * really happen, but let's be safe.)
1741          */
1742         EvalPlanQualSetTuple(epqstate, rti, NULL);
1743
1744         return slot;
1745 }
1746
1747 /*
1748  * Fetch a copy of the newest version of an outdated tuple
1749  *
1750  *      estate - executor state data
1751  *      relation - table containing tuple
1752  *      lockmode - requested tuple lock mode
1753  *      *tid - t_ctid from the outdated tuple (ie, next updated version)
1754  *      priorXmax - t_xmax from the outdated tuple
1755  *
1756  * Returns a palloc'd copy of the newest tuple version, or NULL if we find
1757  * that there is no newest version (ie, the row was deleted not updated).
1758  * If successful, we have locked the newest tuple version, so caller does not
1759  * need to worry about it changing anymore.
1760  *
1761  * Note: properly, lockmode should be declared as enum LockTupleMode,
1762  * but we use "int" to avoid having to include heapam.h in executor.h.
1763  */
1764 HeapTuple
1765 EvalPlanQualFetch(EState *estate, Relation relation, int lockmode,
1766                                   ItemPointer tid, TransactionId priorXmax)
1767 {
1768         HeapTuple       copyTuple = NULL;
1769         HeapTupleData tuple;
1770         SnapshotData SnapshotDirty;
1771
1772         /*
1773          * fetch target tuple
1774          *
1775          * Loop here to deal with updated or busy tuples
1776          */
1777         InitDirtySnapshot(SnapshotDirty);
1778         tuple.t_self = *tid;
1779         for (;;)
1780         {
1781                 Buffer          buffer;
1782
1783                 if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
1784                 {
1785                         HTSU_Result test;
1786                         ItemPointerData update_ctid;
1787                         TransactionId update_xmax;
1788
1789                         /*
1790                          * If xmin isn't what we're expecting, the slot must have been
1791                          * recycled and reused for an unrelated tuple.  This implies that
1792                          * the latest version of the row was deleted, so we need do
1793                          * nothing.  (Should be safe to examine xmin without getting
1794                          * buffer's content lock, since xmin never changes in an existing
1795                          * tuple.)
1796                          */
1797                         if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1798                                                                          priorXmax))
1799                         {
1800                                 ReleaseBuffer(buffer);
1801                                 return NULL;
1802                         }
1803
1804                         /* otherwise xmin should not be dirty... */
1805                         if (TransactionIdIsValid(SnapshotDirty.xmin))
1806                                 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
1807
1808                         /*
1809                          * If tuple is being updated by other transaction then we have to
1810                          * wait for its commit/abort.
1811                          */
1812                         if (TransactionIdIsValid(SnapshotDirty.xmax))
1813                         {
1814                                 ReleaseBuffer(buffer);
1815                                 XactLockTableWait(SnapshotDirty.xmax);
1816                                 continue;               /* loop back to repeat heap_fetch */
1817                         }
1818
1819                         /*
1820                          * If tuple was inserted by our own transaction, we have to check
1821                          * cmin against es_output_cid: cmin >= current CID means our
1822                          * command cannot see the tuple, so we should ignore it.  Without
1823                          * this we are open to the "Halloween problem" of indefinitely
1824                          * re-updating the same tuple. (We need not check cmax because
1825                          * HeapTupleSatisfiesDirty will consider a tuple deleted by our
1826                          * transaction dead, regardless of cmax.)  We just checked that
1827                          * priorXmax == xmin, so we can test that variable instead of
1828                          * doing HeapTupleHeaderGetXmin again.
1829                          */
1830                         if (TransactionIdIsCurrentTransactionId(priorXmax) &&
1831                                 HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
1832                         {
1833                                 ReleaseBuffer(buffer);
1834                                 return NULL;
1835                         }
1836
1837                         /*
1838                          * This is a live tuple, so now try to lock it.
1839                          */
1840                         test = heap_lock_tuple(relation, &tuple, &buffer,
1841                                                                    &update_ctid, &update_xmax,
1842                                                                    estate->es_output_cid,
1843                                                                    lockmode, false);
1844                         /* We now have two pins on the buffer, get rid of one */
1845                         ReleaseBuffer(buffer);
1846
1847                         switch (test)
1848                         {
1849                                 case HeapTupleSelfUpdated:
1850                                         /* treat it as deleted; do not process */
1851                                         ReleaseBuffer(buffer);
1852                                         return NULL;
1853
1854                                 case HeapTupleMayBeUpdated:
1855                                         /* successfully locked */
1856                                         break;
1857
1858                                 case HeapTupleUpdated:
1859                                         ReleaseBuffer(buffer);
1860                                         if (IsolationUsesXactSnapshot())
1861                                                 ereport(ERROR,
1862                                                                 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1863                                                                  errmsg("could not serialize access due to concurrent update")));
1864                                         if (!ItemPointerEquals(&update_ctid, &tuple.t_self))
1865                                         {
1866                                                 /* it was updated, so look at the updated version */
1867                                                 tuple.t_self = update_ctid;
1868                                                 /* updated row should have xmin matching this xmax */
1869                                                 priorXmax = update_xmax;
1870                                                 continue;
1871                                         }
1872                                         /* tuple was deleted, so give up */
1873                                         return NULL;
1874
1875                                 default:
1876                                         ReleaseBuffer(buffer);
1877                                         elog(ERROR, "unrecognized heap_lock_tuple status: %u",
1878                                                  test);
1879                                         return NULL;    /* keep compiler quiet */
1880                         }
1881
1882                         /*
1883                          * We got tuple - now copy it for use by recheck query.
1884                          */
1885                         copyTuple = heap_copytuple(&tuple);
1886                         ReleaseBuffer(buffer);
1887                         break;
1888                 }
1889
1890                 /*
1891                  * If the referenced slot was actually empty, the latest version of
1892                  * the row must have been deleted, so we need do nothing.
1893                  */
1894                 if (tuple.t_data == NULL)
1895                 {
1896                         ReleaseBuffer(buffer);
1897                         return NULL;
1898                 }
1899
1900                 /*
1901                  * As above, if xmin isn't what we're expecting, do nothing.
1902                  */
1903                 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1904                                                                  priorXmax))
1905                 {
1906                         ReleaseBuffer(buffer);
1907                         return NULL;
1908                 }
1909
1910                 /*
1911                  * If we get here, the tuple was found but failed SnapshotDirty.
1912                  * Assuming the xmin is either a committed xact or our own xact (as it
1913                  * certainly should be if we're trying to modify the tuple), this must
1914                  * mean that the row was updated or deleted by either a committed xact
1915                  * or our own xact.  If it was deleted, we can ignore it; if it was
1916                  * updated then chain up to the next version and repeat the whole
1917                  * process.
1918                  *
1919                  * As above, it should be safe to examine xmax and t_ctid without the
1920                  * buffer content lock, because they can't be changing.
1921                  */
1922                 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
1923                 {
1924                         /* deleted, so forget about it */
1925                         ReleaseBuffer(buffer);
1926                         return NULL;
1927                 }
1928
1929                 /* updated, so look at the updated row */
1930                 tuple.t_self = tuple.t_data->t_ctid;
1931                 /* updated row should have xmin matching this xmax */
1932                 priorXmax = HeapTupleHeaderGetXmax(tuple.t_data);
1933                 ReleaseBuffer(buffer);
1934                 /* loop back to fetch next in chain */
1935         }
1936
1937         /*
1938          * Return the copied tuple
1939          */
1940         return copyTuple;
1941 }
1942
1943 /*
1944  * EvalPlanQualInit -- initialize during creation of a plan state node
1945  * that might need to invoke EPQ processing.
1946  *
1947  * Note: subplan/auxrowmarks can be NULL/NIL if they will be set later
1948  * with EvalPlanQualSetPlan.
1949  */
1950 void
1951 EvalPlanQualInit(EPQState *epqstate, EState *estate,
1952                                  Plan *subplan, List *auxrowmarks, int epqParam)
1953 {
1954         /* Mark the EPQ state inactive */
1955         epqstate->estate = NULL;
1956         epqstate->planstate = NULL;
1957         epqstate->origslot = NULL;
1958         /* ... and remember data that EvalPlanQualBegin will need */
1959         epqstate->plan = subplan;
1960         epqstate->arowMarks = auxrowmarks;
1961         epqstate->epqParam = epqParam;
1962 }
1963
1964 /*
1965  * EvalPlanQualSetPlan -- set or change subplan of an EPQState.
1966  *
1967  * We need this so that ModifyTuple can deal with multiple subplans.
1968  */
1969 void
1970 EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan, List *auxrowmarks)
1971 {
1972         /* If we have a live EPQ query, shut it down */
1973         EvalPlanQualEnd(epqstate);
1974         /* And set/change the plan pointer */
1975         epqstate->plan = subplan;
1976         /* The rowmarks depend on the plan, too */
1977         epqstate->arowMarks = auxrowmarks;
1978 }
1979
1980 /*
1981  * Install one test tuple into EPQ state, or clear test tuple if tuple == NULL
1982  *
1983  * NB: passed tuple must be palloc'd; it may get freed later
1984  */
1985 void
1986 EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
1987 {
1988         EState     *estate = epqstate->estate;
1989
1990         Assert(rti > 0);
1991
1992         /*
1993          * free old test tuple, if any, and store new tuple where relation's scan
1994          * node will see it
1995          */
1996         if (estate->es_epqTuple[rti - 1] != NULL)
1997                 heap_freetuple(estate->es_epqTuple[rti - 1]);
1998         estate->es_epqTuple[rti - 1] = tuple;
1999         estate->es_epqTupleSet[rti - 1] = true;
2000 }
2001
2002 /*
2003  * Fetch back the current test tuple (if any) for the specified RTI
2004  */
2005 HeapTuple
2006 EvalPlanQualGetTuple(EPQState *epqstate, Index rti)
2007 {
2008         EState     *estate = epqstate->estate;
2009
2010         Assert(rti > 0);
2011
2012         return estate->es_epqTuple[rti - 1];
2013 }
2014
2015 /*
2016  * Fetch the current row values for any non-locked relations that need
2017  * to be scanned by an EvalPlanQual operation.  origslot must have been set
2018  * to contain the current result row (top-level row) that we need to recheck.
2019  */
2020 void
2021 EvalPlanQualFetchRowMarks(EPQState *epqstate)
2022 {
2023         ListCell   *l;
2024
2025         Assert(epqstate->origslot != NULL);
2026
2027         foreach(l, epqstate->arowMarks)
2028         {
2029                 ExecAuxRowMark *aerm = (ExecAuxRowMark *) lfirst(l);
2030                 ExecRowMark *erm = aerm->rowmark;
2031                 Datum           datum;
2032                 bool            isNull;
2033                 HeapTupleData tuple;
2034
2035                 if (RowMarkRequiresRowShareLock(erm->markType))
2036                         elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2037
2038                 /* clear any leftover test tuple for this rel */
2039                 EvalPlanQualSetTuple(epqstate, erm->rti, NULL);
2040
2041                 if (erm->relation)
2042                 {
2043                         Buffer          buffer;
2044
2045                         Assert(erm->markType == ROW_MARK_REFERENCE);
2046
2047                         /* if child rel, must check whether it produced this row */
2048                         if (erm->rti != erm->prti)
2049                         {
2050                                 Oid                     tableoid;
2051
2052                                 datum = ExecGetJunkAttribute(epqstate->origslot,
2053                                                                                          aerm->toidAttNo,
2054                                                                                          &isNull);
2055                                 /* non-locked rels could be on the inside of outer joins */
2056                                 if (isNull)
2057                                         continue;
2058                                 tableoid = DatumGetObjectId(datum);
2059
2060                                 if (tableoid != RelationGetRelid(erm->relation))
2061                                 {
2062                                         /* this child is inactive right now */
2063                                         continue;
2064                                 }
2065                         }
2066
2067                         /* fetch the tuple's ctid */
2068                         datum = ExecGetJunkAttribute(epqstate->origslot,
2069                                                                                  aerm->ctidAttNo,
2070                                                                                  &isNull);
2071                         /* non-locked rels could be on the inside of outer joins */
2072                         if (isNull)
2073                                 continue;
2074                         tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
2075
2076                         /* okay, fetch the tuple */
2077                         if (!heap_fetch(erm->relation, SnapshotAny, &tuple, &buffer,
2078                                                         false, NULL))
2079                                 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2080
2081                         /* successful, copy and store tuple */
2082                         EvalPlanQualSetTuple(epqstate, erm->rti,
2083                                                                  heap_copytuple(&tuple));
2084                         ReleaseBuffer(buffer);
2085                 }
2086                 else
2087                 {
2088                         HeapTupleHeader td;
2089
2090                         Assert(erm->markType == ROW_MARK_COPY);
2091
2092                         /* fetch the whole-row Var for the relation */
2093                         datum = ExecGetJunkAttribute(epqstate->origslot,
2094                                                                                  aerm->wholeAttNo,
2095                                                                                  &isNull);
2096                         /* non-locked rels could be on the inside of outer joins */
2097                         if (isNull)
2098                                 continue;
2099                         td = DatumGetHeapTupleHeader(datum);
2100
2101                         /* build a temporary HeapTuple control structure */
2102                         tuple.t_len = HeapTupleHeaderGetDatumLength(td);
2103                         ItemPointerSetInvalid(&(tuple.t_self));
2104                         tuple.t_tableOid = InvalidOid;
2105                         tuple.t_data = td;
2106
2107                         /* copy and store tuple */
2108                         EvalPlanQualSetTuple(epqstate, erm->rti,
2109                                                                  heap_copytuple(&tuple));
2110                 }
2111         }
2112 }
2113
2114 /*
2115  * Fetch the next row (if any) from EvalPlanQual testing
2116  *
2117  * (In practice, there should never be more than one row...)
2118  */
2119 TupleTableSlot *
2120 EvalPlanQualNext(EPQState *epqstate)
2121 {
2122         MemoryContext oldcontext;
2123         TupleTableSlot *slot;
2124
2125         oldcontext = MemoryContextSwitchTo(epqstate->estate->es_query_cxt);
2126         slot = ExecProcNode(epqstate->planstate);
2127         MemoryContextSwitchTo(oldcontext);
2128
2129         return slot;
2130 }
2131
2132 /*
2133  * Initialize or reset an EvalPlanQual state tree
2134  */
2135 void
2136 EvalPlanQualBegin(EPQState *epqstate, EState *parentestate)
2137 {
2138         EState     *estate = epqstate->estate;
2139
2140         if (estate == NULL)
2141         {
2142                 /* First time through, so create a child EState */
2143                 EvalPlanQualStart(epqstate, parentestate, epqstate->plan);
2144         }
2145         else
2146         {
2147                 /*
2148                  * We already have a suitable child EPQ tree, so just reset it.
2149                  */
2150                 int                     rtsize = list_length(parentestate->es_range_table);
2151                 PlanState  *planstate = epqstate->planstate;
2152
2153                 MemSet(estate->es_epqScanDone, 0, rtsize * sizeof(bool));
2154
2155                 /* Recopy current values of parent parameters */
2156                 if (parentestate->es_plannedstmt->nParamExec > 0)
2157                 {
2158                         int                     i = parentestate->es_plannedstmt->nParamExec;
2159
2160                         while (--i >= 0)
2161                         {
2162                                 /* copy value if any, but not execPlan link */
2163                                 estate->es_param_exec_vals[i].value =
2164                                         parentestate->es_param_exec_vals[i].value;
2165                                 estate->es_param_exec_vals[i].isnull =
2166                                         parentestate->es_param_exec_vals[i].isnull;
2167                         }
2168                 }
2169
2170                 /*
2171                  * Mark child plan tree as needing rescan at all scan nodes.  The
2172                  * first ExecProcNode will take care of actually doing the rescan.
2173                  */
2174                 planstate->chgParam = bms_add_member(planstate->chgParam,
2175                                                                                          epqstate->epqParam);
2176         }
2177 }
2178
2179 /*
2180  * Start execution of an EvalPlanQual plan tree.
2181  *
2182  * This is a cut-down version of ExecutorStart(): we copy some state from
2183  * the top-level estate rather than initializing it fresh.
2184  */
2185 static void
2186 EvalPlanQualStart(EPQState *epqstate, EState *parentestate, Plan *planTree)
2187 {
2188         EState     *estate;
2189         int                     rtsize;
2190         MemoryContext oldcontext;
2191         ListCell   *l;
2192
2193         rtsize = list_length(parentestate->es_range_table);
2194
2195         epqstate->estate = estate = CreateExecutorState();
2196
2197         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2198
2199         /*
2200          * Child EPQ EStates share the parent's copy of unchanging state such as
2201          * the snapshot, rangetable, result-rel info, and external Param info.
2202          * They need their own copies of local state, including a tuple table,
2203          * es_param_exec_vals, etc.
2204          */
2205         estate->es_direction = ForwardScanDirection;
2206         estate->es_snapshot = parentestate->es_snapshot;
2207         estate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
2208         estate->es_range_table = parentestate->es_range_table;
2209         estate->es_plannedstmt = parentestate->es_plannedstmt;
2210         estate->es_junkFilter = parentestate->es_junkFilter;
2211         estate->es_output_cid = parentestate->es_output_cid;
2212         estate->es_result_relations = parentestate->es_result_relations;
2213         estate->es_num_result_relations = parentestate->es_num_result_relations;
2214         estate->es_result_relation_info = parentestate->es_result_relation_info;
2215         /* es_trig_target_relations must NOT be copied */
2216         estate->es_rowMarks = parentestate->es_rowMarks;
2217         estate->es_top_eflags = parentestate->es_top_eflags;
2218         estate->es_instrument = parentestate->es_instrument;
2219         estate->es_select_into = parentestate->es_select_into;
2220         estate->es_into_oids = parentestate->es_into_oids;
2221         /* es_auxmodifytables must NOT be copied */
2222
2223         /*
2224          * The external param list is simply shared from parent.  The internal
2225          * param workspace has to be local state, but we copy the initial values
2226          * from the parent, so as to have access to any param values that were
2227          * already set from other parts of the parent's plan tree.
2228          */
2229         estate->es_param_list_info = parentestate->es_param_list_info;
2230         if (parentestate->es_plannedstmt->nParamExec > 0)
2231         {
2232                 int                     i = parentestate->es_plannedstmt->nParamExec;
2233
2234                 estate->es_param_exec_vals = (ParamExecData *)
2235                         palloc0(i * sizeof(ParamExecData));
2236                 while (--i >= 0)
2237                 {
2238                         /* copy value if any, but not execPlan link */
2239                         estate->es_param_exec_vals[i].value =
2240                                 parentestate->es_param_exec_vals[i].value;
2241                         estate->es_param_exec_vals[i].isnull =
2242                                 parentestate->es_param_exec_vals[i].isnull;
2243                 }
2244         }
2245
2246         /*
2247          * Each EState must have its own es_epqScanDone state, but if we have
2248          * nested EPQ checks they should share es_epqTuple arrays.      This allows
2249          * sub-rechecks to inherit the values being examined by an outer recheck.
2250          */
2251         estate->es_epqScanDone = (bool *) palloc0(rtsize * sizeof(bool));
2252         if (parentestate->es_epqTuple != NULL)
2253         {
2254                 estate->es_epqTuple = parentestate->es_epqTuple;
2255                 estate->es_epqTupleSet = parentestate->es_epqTupleSet;
2256         }
2257         else
2258         {
2259                 estate->es_epqTuple = (HeapTuple *)
2260                         palloc0(rtsize * sizeof(HeapTuple));
2261                 estate->es_epqTupleSet = (bool *)
2262                         palloc0(rtsize * sizeof(bool));
2263         }
2264
2265         /*
2266          * Each estate also has its own tuple table.
2267          */
2268         estate->es_tupleTable = NIL;
2269
2270         /*
2271          * Initialize private state information for each SubPlan.  We must do this
2272          * before running ExecInitNode on the main query tree, since
2273          * ExecInitSubPlan expects to be able to find these entries. Some of the
2274          * SubPlans might not be used in the part of the plan tree we intend to
2275          * run, but since it's not easy to tell which, we just initialize them
2276          * all.  (However, if the subplan is headed by a ModifyTable node, then it
2277          * must be a data-modifying CTE, which we will certainly not need to
2278          * re-run, so we can skip initializing it.      This is just an efficiency
2279          * hack; it won't skip data-modifying CTEs for which the ModifyTable node
2280          * is not at the top.)
2281          */
2282         Assert(estate->es_subplanstates == NIL);
2283         foreach(l, parentestate->es_plannedstmt->subplans)
2284         {
2285                 Plan       *subplan = (Plan *) lfirst(l);
2286                 PlanState  *subplanstate;
2287
2288                 /* Don't initialize ModifyTable subplans, per comment above */
2289                 if (IsA(subplan, ModifyTable))
2290                         subplanstate = NULL;
2291                 else
2292                         subplanstate = ExecInitNode(subplan, estate, 0);
2293
2294                 estate->es_subplanstates = lappend(estate->es_subplanstates,
2295                                                                                    subplanstate);
2296         }
2297
2298         /*
2299          * Initialize the private state information for all the nodes in the part
2300          * of the plan tree we need to run.  This opens files, allocates storage
2301          * and leaves us ready to start processing tuples.
2302          */
2303         epqstate->planstate = ExecInitNode(planTree, estate, 0);
2304
2305         MemoryContextSwitchTo(oldcontext);
2306 }
2307
2308 /*
2309  * EvalPlanQualEnd -- shut down at termination of parent plan state node,
2310  * or if we are done with the current EPQ child.
2311  *
2312  * This is a cut-down version of ExecutorEnd(); basically we want to do most
2313  * of the normal cleanup, but *not* close result relations (which we are
2314  * just sharing from the outer query).  We do, however, have to close any
2315  * trigger target relations that got opened, since those are not shared.
2316  * (There probably shouldn't be any of the latter, but just in case...)
2317  */
2318 void
2319 EvalPlanQualEnd(EPQState *epqstate)
2320 {
2321         EState     *estate = epqstate->estate;
2322         MemoryContext oldcontext;
2323         ListCell   *l;
2324
2325         if (estate == NULL)
2326                 return;                                 /* idle, so nothing to do */
2327
2328         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2329
2330         ExecEndNode(epqstate->planstate);
2331
2332         foreach(l, estate->es_subplanstates)
2333         {
2334                 PlanState  *subplanstate = (PlanState *) lfirst(l);
2335
2336                 ExecEndNode(subplanstate);
2337         }
2338
2339         /* throw away the per-estate tuple table */
2340         ExecResetTupleTable(estate->es_tupleTable, false);
2341
2342         /* close any trigger target relations attached to this EState */
2343         foreach(l, estate->es_trig_target_relations)
2344         {
2345                 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
2346
2347                 /* Close indices and then the relation itself */
2348                 ExecCloseIndices(resultRelInfo);
2349                 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
2350         }
2351
2352         MemoryContextSwitchTo(oldcontext);
2353
2354         FreeExecutorState(estate);
2355
2356         /* Mark EPQState idle */
2357         epqstate->estate = NULL;
2358         epqstate->planstate = NULL;
2359         epqstate->origslot = NULL;
2360 }
2361
2362
2363 /*
2364  * Support for SELECT INTO (a/k/a CREATE TABLE AS)
2365  *
2366  * We implement SELECT INTO by diverting SELECT's normal output with
2367  * a specialized DestReceiver type.
2368  */
2369
2370 typedef struct
2371 {
2372         DestReceiver pub;                       /* publicly-known function pointers */
2373         EState     *estate;                     /* EState we are working with */
2374         Relation        rel;                    /* Relation to write to */
2375         int                     hi_options;             /* heap_insert performance options */
2376         BulkInsertState bistate;        /* bulk insert state */
2377 } DR_intorel;
2378
2379 /*
2380  * OpenIntoRel --- actually create the SELECT INTO target relation
2381  *
2382  * This also replaces QueryDesc->dest with the special DestReceiver for
2383  * SELECT INTO.  We assume that the correct result tuple type has already
2384  * been placed in queryDesc->tupDesc.
2385  */
2386 static void
2387 OpenIntoRel(QueryDesc *queryDesc)
2388 {
2389         IntoClause *into = queryDesc->plannedstmt->intoClause;
2390         EState     *estate = queryDesc->estate;
2391         Relation        intoRelationDesc;
2392         char       *intoName;
2393         Oid                     namespaceId;
2394         Oid                     tablespaceId;
2395         Datum           reloptions;
2396         Oid                     intoRelationId;
2397         TupleDesc       tupdesc;
2398         DR_intorel *myState;
2399         static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
2400
2401         Assert(into);
2402
2403         /*
2404          * XXX This code needs to be kept in sync with DefineRelation(). Maybe we
2405          * should try to use that function instead.
2406          */
2407
2408         /*
2409          * Check consistency of arguments
2410          */
2411         if (into->onCommit != ONCOMMIT_NOOP
2412                 && into->rel->relpersistence != RELPERSISTENCE_TEMP)
2413                 ereport(ERROR,
2414                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2415                                  errmsg("ON COMMIT can only be used on temporary tables")));
2416
2417         /*
2418          * Security check: disallow creating temp tables from security-restricted
2419          * code.  This is needed because calling code might not expect untrusted
2420          * tables to appear in pg_temp at the front of its search path.
2421          */
2422         if (into->rel->relpersistence == RELPERSISTENCE_TEMP
2423                 && InSecurityRestrictedOperation())
2424                 ereport(ERROR,
2425                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2426                                  errmsg("cannot create temporary table within security-restricted operation")));
2427
2428         /*
2429          * Find namespace to create in, check its permissions
2430          */
2431         intoName = into->rel->relname;
2432         namespaceId = RangeVarGetAndCheckCreationNamespace(into->rel);
2433
2434         /*
2435          * Select tablespace to use.  If not specified, use default tablespace
2436          * (which may in turn default to database's default).
2437          */
2438         if (into->tableSpaceName)
2439         {
2440                 tablespaceId = get_tablespace_oid(into->tableSpaceName, false);
2441         }
2442         else
2443         {
2444                 tablespaceId = GetDefaultTablespace(into->rel->relpersistence);
2445                 /* note InvalidOid is OK in this case */
2446         }
2447
2448         /* Check permissions except when using the database's default space */
2449         if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
2450         {
2451                 AclResult       aclresult;
2452
2453                 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
2454                                                                                    ACL_CREATE);
2455
2456                 if (aclresult != ACLCHECK_OK)
2457                         aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
2458                                                    get_tablespace_name(tablespaceId));
2459         }
2460
2461         /* Parse and validate any reloptions */
2462         reloptions = transformRelOptions((Datum) 0,
2463                                                                          into->options,
2464                                                                          NULL,
2465                                                                          validnsps,
2466                                                                          true,
2467                                                                          false);
2468         (void) heap_reloptions(RELKIND_RELATION, reloptions, true);
2469
2470         /* Copy the tupdesc because heap_create_with_catalog modifies it */
2471         tupdesc = CreateTupleDescCopy(queryDesc->tupDesc);
2472
2473         /* Now we can actually create the new relation */
2474         intoRelationId = heap_create_with_catalog(intoName,
2475                                                                                           namespaceId,
2476                                                                                           tablespaceId,
2477                                                                                           InvalidOid,
2478                                                                                           InvalidOid,
2479                                                                                           InvalidOid,
2480                                                                                           GetUserId(),
2481                                                                                           tupdesc,
2482                                                                                           NIL,
2483                                                                                           RELKIND_RELATION,
2484                                                                                           into->rel->relpersistence,
2485                                                                                           false,
2486                                                                                           false,
2487                                                                                           true,
2488                                                                                           0,
2489                                                                                           into->onCommit,
2490                                                                                           reloptions,
2491                                                                                           true,
2492                                                                                           allowSystemTableMods);
2493         Assert(intoRelationId != InvalidOid);
2494
2495         FreeTupleDesc(tupdesc);
2496
2497         /*
2498          * Advance command counter so that the newly-created relation's catalog
2499          * tuples will be visible to heap_open.
2500          */
2501         CommandCounterIncrement();
2502
2503         /*
2504          * If necessary, create a TOAST table for the INTO relation. Note that
2505          * AlterTableCreateToastTable ends with CommandCounterIncrement(), so that
2506          * the TOAST table will be visible for insertion.
2507          */
2508         reloptions = transformRelOptions((Datum) 0,
2509                                                                          into->options,
2510                                                                          "toast",
2511                                                                          validnsps,
2512                                                                          true,
2513                                                                          false);
2514
2515         (void) heap_reloptions(RELKIND_TOASTVALUE, reloptions, true);
2516
2517         AlterTableCreateToastTable(intoRelationId, reloptions);
2518
2519         /*
2520          * And open the constructed table for writing.
2521          */
2522         intoRelationDesc = heap_open(intoRelationId, AccessExclusiveLock);
2523
2524         /*
2525          * Now replace the query's DestReceiver with one for SELECT INTO
2526          */
2527         queryDesc->dest = CreateDestReceiver(DestIntoRel);
2528         myState = (DR_intorel *) queryDesc->dest;
2529         Assert(myState->pub.mydest == DestIntoRel);
2530         myState->estate = estate;
2531         myState->rel = intoRelationDesc;
2532
2533         /*
2534          * We can skip WAL-logging the insertions, unless PITR or streaming
2535          * replication is in use. We can skip the FSM in any case.
2536          */
2537         myState->hi_options = HEAP_INSERT_SKIP_FSM |
2538                 (XLogIsNeeded() ? 0 : HEAP_INSERT_SKIP_WAL);
2539         myState->bistate = GetBulkInsertState();
2540
2541         /* Not using WAL requires smgr_targblock be initially invalid */
2542         Assert(RelationGetTargetBlock(intoRelationDesc) == InvalidBlockNumber);
2543 }
2544
2545 /*
2546  * CloseIntoRel --- clean up SELECT INTO at ExecutorEnd time
2547  */
2548 static void
2549 CloseIntoRel(QueryDesc *queryDesc)
2550 {
2551         DR_intorel *myState = (DR_intorel *) queryDesc->dest;
2552
2553         /* OpenIntoRel might never have gotten called */
2554         if (myState && myState->pub.mydest == DestIntoRel && myState->rel)
2555         {
2556                 FreeBulkInsertState(myState->bistate);
2557
2558                 /* If we skipped using WAL, must heap_sync before commit */
2559                 if (myState->hi_options & HEAP_INSERT_SKIP_WAL)
2560                         heap_sync(myState->rel);
2561
2562                 /* close rel, but keep lock until commit */
2563                 heap_close(myState->rel, NoLock);
2564
2565                 myState->rel = NULL;
2566         }
2567 }
2568
2569 /*
2570  * CreateIntoRelDestReceiver -- create a suitable DestReceiver object
2571  */
2572 DestReceiver *
2573 CreateIntoRelDestReceiver(void)
2574 {
2575         DR_intorel *self = (DR_intorel *) palloc0(sizeof(DR_intorel));
2576
2577         self->pub.receiveSlot = intorel_receive;
2578         self->pub.rStartup = intorel_startup;
2579         self->pub.rShutdown = intorel_shutdown;
2580         self->pub.rDestroy = intorel_destroy;
2581         self->pub.mydest = DestIntoRel;
2582
2583         /* private fields will be set by OpenIntoRel */
2584
2585         return (DestReceiver *) self;
2586 }
2587
2588 /*
2589  * intorel_startup --- executor startup
2590  */
2591 static void
2592 intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
2593 {
2594         /* no-op */
2595 }
2596
2597 /*
2598  * intorel_receive --- receive one tuple
2599  */
2600 static void
2601 intorel_receive(TupleTableSlot *slot, DestReceiver *self)
2602 {
2603         DR_intorel *myState = (DR_intorel *) self;
2604         HeapTuple       tuple;
2605
2606         /*
2607          * get the heap tuple out of the tuple table slot, making sure we have a
2608          * writable copy
2609          */
2610         tuple = ExecMaterializeSlot(slot);
2611
2612         /*
2613          * force assignment of new OID (see comments in ExecInsert)
2614          */
2615         if (myState->rel->rd_rel->relhasoids)
2616                 HeapTupleSetOid(tuple, InvalidOid);
2617
2618         heap_insert(myState->rel,
2619                                 tuple,
2620                                 myState->estate->es_output_cid,
2621                                 myState->hi_options,
2622                                 myState->bistate);
2623
2624         /* We know this is a newly created relation, so there are no indexes */
2625 }
2626
2627 /*
2628  * intorel_shutdown --- executor end
2629  */
2630 static void
2631 intorel_shutdown(DestReceiver *self)
2632 {
2633         /* no-op */
2634 }
2635
2636 /*
2637  * intorel_destroy --- release DestReceiver object
2638  */
2639 static void
2640 intorel_destroy(DestReceiver *self)
2641 {
2642         pfree(self);
2643 }