OSDN Git Service

Revisit AlterTableCreateToastTable's API once again, hoping to make it what
[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  *      ExecutorEnd()
10  *
11  *      The old ExecutorMain() has been replaced by ExecutorStart(),
12  *      ExecutorRun() and ExecutorEnd()
13  *
14  *      These three procedures are the external interfaces to the executor.
15  *      In each case, the query descriptor is required as an argument.
16  *
17  *      ExecutorStart() must be called at the beginning of execution of any
18  *      query plan and ExecutorEnd() should always be called at the end of
19  *      execution of a plan.
20  *
21  *      ExecutorRun accepts direction and count arguments that specify whether
22  *      the plan is to be executed forwards, backwards, and for how many tuples.
23  *
24  * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
25  * Portions Copyright (c) 1994, Regents of the University of California
26  *
27  *
28  * IDENTIFICATION
29  *        $PostgreSQL: pgsql/src/backend/executor/execMain.c,v 1.326 2009/06/11 20:46:11 tgl Exp $
30  *
31  *-------------------------------------------------------------------------
32  */
33 #include "postgres.h"
34
35 #include "access/heapam.h"
36 #include "access/reloptions.h"
37 #include "access/sysattr.h"
38 #include "access/transam.h"
39 #include "access/xact.h"
40 #include "catalog/heap.h"
41 #include "catalog/namespace.h"
42 #include "catalog/toasting.h"
43 #include "commands/tablespace.h"
44 #include "commands/trigger.h"
45 #include "executor/execdebug.h"
46 #include "executor/instrument.h"
47 #include "executor/nodeSubplan.h"
48 #include "miscadmin.h"
49 #include "nodes/nodeFuncs.h"
50 #include "optimizer/clauses.h"
51 #include "parser/parse_clause.h"
52 #include "parser/parsetree.h"
53 #include "storage/bufmgr.h"
54 #include "storage/lmgr.h"
55 #include "storage/smgr.h"
56 #include "utils/acl.h"
57 #include "utils/builtins.h"
58 #include "utils/lsyscache.h"
59 #include "utils/memutils.h"
60 #include "utils/snapmgr.h"
61 #include "utils/tqual.h"
62
63
64 /* Hooks for plugins to get control in ExecutorStart/Run/End() */
65 ExecutorStart_hook_type ExecutorStart_hook = NULL;
66 ExecutorRun_hook_type ExecutorRun_hook = NULL;
67 ExecutorEnd_hook_type ExecutorEnd_hook = NULL;
68
69 typedef struct evalPlanQual
70 {
71         Index           rti;
72         EState     *estate;
73         PlanState  *planstate;
74         struct evalPlanQual *next;      /* stack of active PlanQual plans */
75         struct evalPlanQual *free;      /* list of free PlanQual plans */
76 } evalPlanQual;
77
78 /* decls for local routines only used within this module */
79 static void InitPlan(QueryDesc *queryDesc, int eflags);
80 static void ExecCheckPlanOutput(Relation resultRel, List *targetList);
81 static void ExecEndPlan(PlanState *planstate, EState *estate);
82 static void ExecutePlan(EState *estate, PlanState *planstate,
83                         CmdType operation,
84                         long numberTuples,
85                         ScanDirection direction,
86                         DestReceiver *dest);
87 static void ExecSelect(TupleTableSlot *slot,
88                    DestReceiver *dest, EState *estate);
89 static void ExecInsert(TupleTableSlot *slot, ItemPointer tupleid,
90                    TupleTableSlot *planSlot,
91                    DestReceiver *dest, EState *estate);
92 static void ExecDelete(ItemPointer tupleid,
93                    TupleTableSlot *planSlot,
94                    DestReceiver *dest, EState *estate);
95 static void ExecUpdate(TupleTableSlot *slot, ItemPointer tupleid,
96                    TupleTableSlot *planSlot,
97                    DestReceiver *dest, EState *estate);
98 static void ExecProcessReturning(ProjectionInfo *projectReturning,
99                                          TupleTableSlot *tupleSlot,
100                                          TupleTableSlot *planSlot,
101                                          DestReceiver *dest);
102 static TupleTableSlot *EvalPlanQualNext(EState *estate);
103 static void EndEvalPlanQual(EState *estate);
104 static void ExecCheckRTPerms(List *rangeTable);
105 static void ExecCheckRTEPerms(RangeTblEntry *rte);
106 static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
107 static void EvalPlanQualStart(evalPlanQual *epq, EState *estate,
108                                   evalPlanQual *priorepq);
109 static void EvalPlanQualStop(evalPlanQual *epq);
110 static void OpenIntoRel(QueryDesc *queryDesc);
111 static void CloseIntoRel(QueryDesc *queryDesc);
112 static void intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
113 static void intorel_receive(TupleTableSlot *slot, DestReceiver *self);
114 static void intorel_shutdown(DestReceiver *self);
115 static void intorel_destroy(DestReceiver *self);
116
117 /* end of local decls */
118
119
120 /* ----------------------------------------------------------------
121  *              ExecutorStart
122  *
123  *              This routine must be called at the beginning of any execution of any
124  *              query plan
125  *
126  * Takes a QueryDesc previously created by CreateQueryDesc (it's not real
127  * clear why we bother to separate the two functions, but...).  The tupDesc
128  * field of the QueryDesc is filled in to describe the tuples that will be
129  * returned, and the internal fields (estate and planstate) are set up.
130  *
131  * eflags contains flag bits as described in executor.h.
132  *
133  * NB: the CurrentMemoryContext when this is called will become the parent
134  * of the per-query context used for this Executor invocation.
135  *
136  * We provide a function hook variable that lets loadable plugins
137  * get control when ExecutorStart is called.  Such a plugin would
138  * normally call standard_ExecutorStart().
139  *
140  * ----------------------------------------------------------------
141  */
142 void
143 ExecutorStart(QueryDesc *queryDesc, int eflags)
144 {
145         if (ExecutorStart_hook)
146                 (*ExecutorStart_hook) (queryDesc, eflags);
147         else
148                 standard_ExecutorStart(queryDesc, eflags);
149 }
150
151 void
152 standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
153 {
154         EState     *estate;
155         MemoryContext oldcontext;
156
157         /* sanity checks: queryDesc must not be started already */
158         Assert(queryDesc != NULL);
159         Assert(queryDesc->estate == NULL);
160
161         /*
162          * If the transaction is read-only, we need to check if any writes are
163          * planned to non-temporary tables.  EXPLAIN is considered read-only.
164          */
165         if (XactReadOnly && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
166                 ExecCheckXactReadOnly(queryDesc->plannedstmt);
167
168         /*
169          * Build EState, switch into per-query memory context for startup.
170          */
171         estate = CreateExecutorState();
172         queryDesc->estate = estate;
173
174         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
175
176         /*
177          * Fill in parameters, if any, from queryDesc
178          */
179         estate->es_param_list_info = queryDesc->params;
180
181         if (queryDesc->plannedstmt->nParamExec > 0)
182                 estate->es_param_exec_vals = (ParamExecData *)
183                         palloc0(queryDesc->plannedstmt->nParamExec * sizeof(ParamExecData));
184
185         /*
186          * If non-read-only query, set the command ID to mark output tuples with
187          */
188         switch (queryDesc->operation)
189         {
190                 case CMD_SELECT:
191                         /* SELECT INTO and SELECT FOR UPDATE/SHARE need to mark tuples */
192                         if (queryDesc->plannedstmt->intoClause != NULL ||
193                                 queryDesc->plannedstmt->rowMarks != NIL)
194                                 estate->es_output_cid = GetCurrentCommandId(true);
195                         break;
196
197                 case CMD_INSERT:
198                 case CMD_DELETE:
199                 case CMD_UPDATE:
200                         estate->es_output_cid = GetCurrentCommandId(true);
201                         break;
202
203                 default:
204                         elog(ERROR, "unrecognized operation code: %d",
205                                  (int) queryDesc->operation);
206                         break;
207         }
208
209         /*
210          * Copy other important information into the EState
211          */
212         estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
213         estate->es_crosscheck_snapshot = RegisterSnapshot(queryDesc->crosscheck_snapshot);
214         estate->es_instrument = queryDesc->doInstrument;
215
216         /*
217          * Initialize the plan state tree
218          */
219         InitPlan(queryDesc, eflags);
220
221         MemoryContextSwitchTo(oldcontext);
222 }
223
224 /* ----------------------------------------------------------------
225  *              ExecutorRun
226  *
227  *              This is the main routine of the executor module. It accepts
228  *              the query descriptor from the traffic cop and executes the
229  *              query plan.
230  *
231  *              ExecutorStart must have been called already.
232  *
233  *              If direction is NoMovementScanDirection then nothing is done
234  *              except to start up/shut down the destination.  Otherwise,
235  *              we retrieve up to 'count' tuples in the specified direction.
236  *
237  *              Note: count = 0 is interpreted as no portal limit, i.e., run to
238  *              completion.
239  *
240  *              There is no return value, but output tuples (if any) are sent to
241  *              the destination receiver specified in the QueryDesc; and the number
242  *              of tuples processed at the top level can be found in
243  *              estate->es_processed.
244  *
245  *              We provide a function hook variable that lets loadable plugins
246  *              get control when ExecutorRun is called.  Such a plugin would
247  *              normally call standard_ExecutorRun().
248  *
249  * ----------------------------------------------------------------
250  */
251 void
252 ExecutorRun(QueryDesc *queryDesc,
253                         ScanDirection direction, long count)
254 {
255         if (ExecutorRun_hook)
256                 (*ExecutorRun_hook) (queryDesc, direction, count);
257         else
258                 standard_ExecutorRun(queryDesc, direction, count);
259 }
260
261 void
262 standard_ExecutorRun(QueryDesc *queryDesc,
263                                          ScanDirection direction, long count)
264 {
265         EState     *estate;
266         CmdType         operation;
267         DestReceiver *dest;
268         bool            sendTuples;
269         MemoryContext oldcontext;
270
271         /* sanity checks */
272         Assert(queryDesc != NULL);
273
274         estate = queryDesc->estate;
275
276         Assert(estate != NULL);
277
278         /*
279          * Switch into per-query memory context
280          */
281         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
282
283         /* Allow instrumentation of ExecutorRun overall runtime */
284         if (queryDesc->totaltime)
285                 InstrStartNode(queryDesc->totaltime);
286
287         /*
288          * extract information from the query descriptor and the query feature.
289          */
290         operation = queryDesc->operation;
291         dest = queryDesc->dest;
292
293         /*
294          * startup tuple receiver, if we will be emitting tuples
295          */
296         estate->es_processed = 0;
297         estate->es_lastoid = InvalidOid;
298
299         sendTuples = (operation == CMD_SELECT ||
300                                   queryDesc->plannedstmt->returningLists);
301
302         if (sendTuples)
303                 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
304
305         /*
306          * run plan
307          */
308         if (!ScanDirectionIsNoMovement(direction))
309                 ExecutePlan(estate,
310                                         queryDesc->planstate,
311                                         operation,
312                                         count,
313                                         direction,
314                                         dest);
315
316         /*
317          * shutdown tuple receiver, if we started it
318          */
319         if (sendTuples)
320                 (*dest->rShutdown) (dest);
321
322         if (queryDesc->totaltime)
323                 InstrStopNode(queryDesc->totaltime, estate->es_processed);
324
325         MemoryContextSwitchTo(oldcontext);
326 }
327
328 /* ----------------------------------------------------------------
329  *              ExecutorEnd
330  *
331  *              This routine must be called at the end of execution of any
332  *              query plan
333  *
334  *              We provide a function hook variable that lets loadable plugins
335  *              get control when ExecutorEnd is called.  Such a plugin would
336  *              normally call standard_ExecutorEnd().
337  *
338  * ----------------------------------------------------------------
339  */
340 void
341 ExecutorEnd(QueryDesc *queryDesc)
342 {
343         if (ExecutorEnd_hook)
344                 (*ExecutorEnd_hook) (queryDesc);
345         else
346                 standard_ExecutorEnd(queryDesc);
347 }
348
349 void
350 standard_ExecutorEnd(QueryDesc *queryDesc)
351 {
352         EState     *estate;
353         MemoryContext oldcontext;
354
355         /* sanity checks */
356         Assert(queryDesc != NULL);
357
358         estate = queryDesc->estate;
359
360         Assert(estate != NULL);
361
362         /*
363          * Switch into per-query memory context to run ExecEndPlan
364          */
365         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
366
367         ExecEndPlan(queryDesc->planstate, estate);
368
369         /*
370          * Close the SELECT INTO relation if any
371          */
372         if (estate->es_select_into)
373                 CloseIntoRel(queryDesc);
374
375         /* do away with our snapshots */
376         UnregisterSnapshot(estate->es_snapshot);
377         UnregisterSnapshot(estate->es_crosscheck_snapshot);
378
379         /*
380          * Must switch out of context before destroying it
381          */
382         MemoryContextSwitchTo(oldcontext);
383
384         /*
385          * Release EState and per-query memory context.  This should release
386          * everything the executor has allocated.
387          */
388         FreeExecutorState(estate);
389
390         /* Reset queryDesc fields that no longer point to anything */
391         queryDesc->tupDesc = NULL;
392         queryDesc->estate = NULL;
393         queryDesc->planstate = NULL;
394         queryDesc->totaltime = NULL;
395 }
396
397 /* ----------------------------------------------------------------
398  *              ExecutorRewind
399  *
400  *              This routine may be called on an open queryDesc to rewind it
401  *              to the start.
402  * ----------------------------------------------------------------
403  */
404 void
405 ExecutorRewind(QueryDesc *queryDesc)
406 {
407         EState     *estate;
408         MemoryContext oldcontext;
409
410         /* sanity checks */
411         Assert(queryDesc != NULL);
412
413         estate = queryDesc->estate;
414
415         Assert(estate != NULL);
416
417         /* It's probably not sensible to rescan updating queries */
418         Assert(queryDesc->operation == CMD_SELECT);
419
420         /*
421          * Switch into per-query memory context
422          */
423         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
424
425         /*
426          * rescan plan
427          */
428         ExecReScan(queryDesc->planstate, NULL);
429
430         MemoryContextSwitchTo(oldcontext);
431 }
432
433
434 /*
435  * ExecCheckRTPerms
436  *              Check access permissions for all relations listed in a range table.
437  */
438 static void
439 ExecCheckRTPerms(List *rangeTable)
440 {
441         ListCell   *l;
442
443         foreach(l, rangeTable)
444         {
445                 ExecCheckRTEPerms((RangeTblEntry *) lfirst(l));
446         }
447 }
448
449 /*
450  * ExecCheckRTEPerms
451  *              Check access permissions for a single RTE.
452  */
453 static void
454 ExecCheckRTEPerms(RangeTblEntry *rte)
455 {
456         AclMode         requiredPerms;
457         AclMode         relPerms;
458         AclMode         remainingPerms;
459         Oid                     relOid;
460         Oid                     userid;
461         Bitmapset  *tmpset;
462         int                     col;
463
464         /*
465          * Only plain-relation RTEs need to be checked here.  Function RTEs are
466          * checked by init_fcache when the function is prepared for execution.
467          * Join, subquery, and special RTEs need no checks.
468          */
469         if (rte->rtekind != RTE_RELATION)
470                 return;
471
472         /*
473          * No work if requiredPerms is empty.
474          */
475         requiredPerms = rte->requiredPerms;
476         if (requiredPerms == 0)
477                 return;
478
479         relOid = rte->relid;
480
481         /*
482          * userid to check as: current user unless we have a setuid indication.
483          *
484          * Note: GetUserId() is presently fast enough that there's no harm in
485          * calling it separately for each RTE.  If that stops being true, we could
486          * call it once in ExecCheckRTPerms and pass the userid down from there.
487          * But for now, no need for the extra clutter.
488          */
489         userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
490
491         /*
492          * We must have *all* the requiredPerms bits, but some of the bits can be
493          * satisfied from column-level rather than relation-level permissions.
494          * First, remove any bits that are satisfied by relation permissions.
495          */
496         relPerms = pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL);
497         remainingPerms = requiredPerms & ~relPerms;
498         if (remainingPerms != 0)
499         {
500                 /*
501                  * If we lack any permissions that exist only as relation permissions,
502                  * we can fail straight away.
503                  */
504                 if (remainingPerms & ~(ACL_SELECT | ACL_INSERT | ACL_UPDATE))
505                         aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
506                                                    get_rel_name(relOid));
507
508                 /*
509                  * Check to see if we have the needed privileges at column level.
510                  *
511                  * Note: failures just report a table-level error; it would be nicer
512                  * to report a column-level error if we have some but not all of the
513                  * column privileges.
514                  */
515                 if (remainingPerms & ACL_SELECT)
516                 {
517                         /*
518                          * When the query doesn't explicitly reference any columns (for
519                          * example, SELECT COUNT(*) FROM table), allow the query if we
520                          * have SELECT on any column of the rel, as per SQL spec.
521                          */
522                         if (bms_is_empty(rte->selectedCols))
523                         {
524                                 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
525                                                                                           ACLMASK_ANY) != ACLCHECK_OK)
526                                         aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
527                                                                    get_rel_name(relOid));
528                         }
529
530                         tmpset = bms_copy(rte->selectedCols);
531                         while ((col = bms_first_member(tmpset)) >= 0)
532                         {
533                                 /* remove the column number offset */
534                                 col += FirstLowInvalidHeapAttributeNumber;
535                                 if (col == InvalidAttrNumber)
536                                 {
537                                         /* Whole-row reference, must have priv on all cols */
538                                         if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
539                                                                                                   ACLMASK_ALL) != ACLCHECK_OK)
540                                                 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
541                                                                            get_rel_name(relOid));
542                                 }
543                                 else
544                                 {
545                                         if (pg_attribute_aclcheck(relOid, col, userid, ACL_SELECT)
546                                                 != ACLCHECK_OK)
547                                                 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
548                                                                            get_rel_name(relOid));
549                                 }
550                         }
551                         bms_free(tmpset);
552                 }
553
554                 /*
555                  * Basically the same for the mod columns, with either INSERT or
556                  * UPDATE privilege as specified by remainingPerms.
557                  */
558                 remainingPerms &= ~ACL_SELECT;
559                 if (remainingPerms != 0)
560                 {
561                         /*
562                          * When the query doesn't explicitly change any columns, allow the
563                          * query if we have permission on any column of the rel.  This is
564                          * to handle SELECT FOR UPDATE as well as possible corner cases in
565                          * INSERT and UPDATE.
566                          */
567                         if (bms_is_empty(rte->modifiedCols))
568                         {
569                                 if (pg_attribute_aclcheck_all(relOid, userid, remainingPerms,
570                                                                                           ACLMASK_ANY) != ACLCHECK_OK)
571                                         aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
572                                                                    get_rel_name(relOid));
573                         }
574
575                         tmpset = bms_copy(rte->modifiedCols);
576                         while ((col = bms_first_member(tmpset)) >= 0)
577                         {
578                                 /* remove the column number offset */
579                                 col += FirstLowInvalidHeapAttributeNumber;
580                                 if (col == InvalidAttrNumber)
581                                 {
582                                         /* whole-row reference can't happen here */
583                                         elog(ERROR, "whole-row update is not implemented");
584                                 }
585                                 else
586                                 {
587                                         if (pg_attribute_aclcheck(relOid, col, userid, remainingPerms)
588                                                 != ACLCHECK_OK)
589                                                 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
590                                                                            get_rel_name(relOid));
591                                 }
592                         }
593                         bms_free(tmpset);
594                 }
595         }
596 }
597
598 /*
599  * Check that the query does not imply any writes to non-temp tables.
600  */
601 static void
602 ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
603 {
604         ListCell   *l;
605
606         /*
607          * CREATE TABLE AS or SELECT INTO?
608          *
609          * XXX should we allow this if the destination is temp?
610          */
611         if (plannedstmt->intoClause != NULL)
612                 goto fail;
613
614         /* Fail if write permissions are requested on any non-temp table */
615         foreach(l, plannedstmt->rtable)
616         {
617                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
618
619                 if (rte->rtekind != RTE_RELATION)
620                         continue;
621
622                 if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
623                         continue;
624
625                 if (isTempNamespace(get_rel_namespace(rte->relid)))
626                         continue;
627
628                 goto fail;
629         }
630
631         return;
632
633 fail:
634         ereport(ERROR,
635                         (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
636                          errmsg("transaction is read-only")));
637 }
638
639
640 /* ----------------------------------------------------------------
641  *              InitPlan
642  *
643  *              Initializes the query plan: open files, allocate storage
644  *              and start up the rule manager
645  * ----------------------------------------------------------------
646  */
647 static void
648 InitPlan(QueryDesc *queryDesc, int eflags)
649 {
650         CmdType         operation = queryDesc->operation;
651         PlannedStmt *plannedstmt = queryDesc->plannedstmt;
652         Plan       *plan = plannedstmt->planTree;
653         List       *rangeTable = plannedstmt->rtable;
654         EState     *estate = queryDesc->estate;
655         PlanState  *planstate;
656         TupleDesc       tupType;
657         ListCell   *l;
658         int                     i;
659
660         /*
661          * Do permissions checks
662          */
663         ExecCheckRTPerms(rangeTable);
664
665         /*
666          * initialize the node's execution state
667          */
668         estate->es_range_table = rangeTable;
669
670         /*
671          * initialize result relation stuff
672          */
673         if (plannedstmt->resultRelations)
674         {
675                 List       *resultRelations = plannedstmt->resultRelations;
676                 int                     numResultRelations = list_length(resultRelations);
677                 ResultRelInfo *resultRelInfos;
678                 ResultRelInfo *resultRelInfo;
679
680                 resultRelInfos = (ResultRelInfo *)
681                         palloc(numResultRelations * sizeof(ResultRelInfo));
682                 resultRelInfo = resultRelInfos;
683                 foreach(l, resultRelations)
684                 {
685                         Index           resultRelationIndex = lfirst_int(l);
686                         Oid                     resultRelationOid;
687                         Relation        resultRelation;
688
689                         resultRelationOid = getrelid(resultRelationIndex, rangeTable);
690                         resultRelation = heap_open(resultRelationOid, RowExclusiveLock);
691                         InitResultRelInfo(resultRelInfo,
692                                                           resultRelation,
693                                                           resultRelationIndex,
694                                                           operation,
695                                                           estate->es_instrument);
696                         resultRelInfo++;
697                 }
698                 estate->es_result_relations = resultRelInfos;
699                 estate->es_num_result_relations = numResultRelations;
700                 /* Initialize to first or only result rel */
701                 estate->es_result_relation_info = resultRelInfos;
702         }
703         else
704         {
705                 /*
706                  * if no result relation, then set state appropriately
707                  */
708                 estate->es_result_relations = NULL;
709                 estate->es_num_result_relations = 0;
710                 estate->es_result_relation_info = NULL;
711         }
712
713         /*
714          * Detect whether we're doing SELECT INTO.  If so, set the es_into_oids
715          * flag appropriately so that the plan tree will be initialized with the
716          * correct tuple descriptors.  (Other SELECT INTO stuff comes later.)
717          */
718         estate->es_select_into = false;
719         if (operation == CMD_SELECT && plannedstmt->intoClause != NULL)
720         {
721                 estate->es_select_into = true;
722                 estate->es_into_oids = interpretOidsOption(plannedstmt->intoClause->options);
723         }
724
725         /*
726          * Have to lock relations selected FOR UPDATE/FOR SHARE before we
727          * initialize the plan tree, else we'd be doing a lock upgrade. While we
728          * are at it, build the ExecRowMark list.
729          */
730         estate->es_rowMarks = NIL;
731         foreach(l, plannedstmt->rowMarks)
732         {
733                 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
734                 Oid                     relid;
735                 Relation        relation;
736                 ExecRowMark *erm;
737
738                 /* ignore "parent" rowmarks; they are irrelevant at runtime */
739                 if (rc->isParent)
740                         continue;
741
742                 relid = getrelid(rc->rti, rangeTable);
743                 relation = heap_open(relid, RowShareLock);
744                 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
745                 erm->relation = relation;
746                 erm->rti = rc->rti;
747                 erm->prti = rc->prti;
748                 erm->forUpdate = rc->forUpdate;
749                 erm->noWait = rc->noWait;
750                 /* We'll locate the junk attrs below */
751                 erm->ctidAttNo = InvalidAttrNumber;
752                 erm->toidAttNo = InvalidAttrNumber;
753                 ItemPointerSetInvalid(&(erm->curCtid));
754                 estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
755         }
756
757         /*
758          * Initialize the executor "tuple" table.  We need slots for all the plan
759          * nodes, plus possibly output slots for the junkfilter(s). At this point
760          * we aren't sure if we need junkfilters, so just add slots for them
761          * unconditionally.  Also, if it's not a SELECT, set up a slot for use for
762          * trigger output tuples.  Also, one for RETURNING-list evaluation.
763          */
764         {
765                 int                     nSlots;
766
767                 /* Slots for the main plan tree */
768                 nSlots = ExecCountSlotsNode(plan);
769                 /* Add slots for subplans and initplans */
770                 foreach(l, plannedstmt->subplans)
771                 {
772                         Plan       *subplan = (Plan *) lfirst(l);
773
774                         nSlots += ExecCountSlotsNode(subplan);
775                 }
776                 /* Add slots for junkfilter(s) */
777                 if (plannedstmt->resultRelations != NIL)
778                         nSlots += list_length(plannedstmt->resultRelations);
779                 else
780                         nSlots += 1;
781                 if (operation != CMD_SELECT)
782                         nSlots++;                       /* for es_trig_tuple_slot */
783                 if (plannedstmt->returningLists)
784                         nSlots++;                       /* for RETURNING projection */
785
786                 estate->es_tupleTable = ExecCreateTupleTable(nSlots);
787
788                 if (operation != CMD_SELECT)
789                         estate->es_trig_tuple_slot =
790                                 ExecAllocTableSlot(estate->es_tupleTable);
791         }
792
793         /* mark EvalPlanQual not active */
794         estate->es_plannedstmt = plannedstmt;
795         estate->es_evalPlanQual = NULL;
796         estate->es_evTupleNull = NULL;
797         estate->es_evTuple = NULL;
798         estate->es_useEvalPlan = false;
799
800         /*
801          * Initialize private state information for each SubPlan.  We must do this
802          * before running ExecInitNode on the main query tree, since
803          * ExecInitSubPlan expects to be able to find these entries.
804          */
805         Assert(estate->es_subplanstates == NIL);
806         i = 1;                                          /* subplan indices count from 1 */
807         foreach(l, plannedstmt->subplans)
808         {
809                 Plan       *subplan = (Plan *) lfirst(l);
810                 PlanState  *subplanstate;
811                 int                     sp_eflags;
812
813                 /*
814                  * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
815                  * it is a parameterless subplan (not initplan), we suggest that it be
816                  * prepared to handle REWIND efficiently; otherwise there is no need.
817                  */
818                 sp_eflags = eflags & EXEC_FLAG_EXPLAIN_ONLY;
819                 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
820                         sp_eflags |= EXEC_FLAG_REWIND;
821
822                 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
823
824                 estate->es_subplanstates = lappend(estate->es_subplanstates,
825                                                                                    subplanstate);
826
827                 i++;
828         }
829
830         /*
831          * Initialize the private state information for all the nodes in the query
832          * tree.  This opens files, allocates storage and leaves us ready to start
833          * processing tuples.
834          */
835         planstate = ExecInitNode(plan, estate, eflags);
836
837         /*
838          * Get the tuple descriptor describing the type of tuples to return. (this
839          * is especially important if we are creating a relation with "SELECT
840          * INTO")
841          */
842         tupType = ExecGetResultType(planstate);
843
844         /*
845          * Initialize the junk filter if needed.  SELECT and INSERT queries need a
846          * filter if there are any junk attrs in the tlist.  UPDATE and DELETE
847          * always need a filter, since there's always a junk 'ctid' attribute
848          * present --- no need to look first.
849          *
850          * This section of code is also a convenient place to verify that the
851          * output of an INSERT or UPDATE matches the target table(s).
852          */
853         {
854                 bool            junk_filter_needed = false;
855                 ListCell   *tlist;
856
857                 switch (operation)
858                 {
859                         case CMD_SELECT:
860                         case CMD_INSERT:
861                                 foreach(tlist, plan->targetlist)
862                                 {
863                                         TargetEntry *tle = (TargetEntry *) lfirst(tlist);
864
865                                         if (tle->resjunk)
866                                         {
867                                                 junk_filter_needed = true;
868                                                 break;
869                                         }
870                                 }
871                                 break;
872                         case CMD_UPDATE:
873                         case CMD_DELETE:
874                                 junk_filter_needed = true;
875                                 break;
876                         default:
877                                 break;
878                 }
879
880                 if (junk_filter_needed)
881                 {
882                         /*
883                          * If there are multiple result relations, each one needs its own
884                          * junk filter.  Note this is only possible for UPDATE/DELETE, so
885                          * we can't be fooled by some needing a filter and some not.
886                          */
887                         if (list_length(plannedstmt->resultRelations) > 1)
888                         {
889                                 PlanState **appendplans;
890                                 int                     as_nplans;
891                                 ResultRelInfo *resultRelInfo;
892
893                                 /* Top plan had better be an Append here. */
894                                 Assert(IsA(plan, Append));
895                                 Assert(((Append *) plan)->isTarget);
896                                 Assert(IsA(planstate, AppendState));
897                                 appendplans = ((AppendState *) planstate)->appendplans;
898                                 as_nplans = ((AppendState *) planstate)->as_nplans;
899                                 Assert(as_nplans == estate->es_num_result_relations);
900                                 resultRelInfo = estate->es_result_relations;
901                                 for (i = 0; i < as_nplans; i++)
902                                 {
903                                         PlanState  *subplan = appendplans[i];
904                                         JunkFilter *j;
905
906                                         if (operation == CMD_UPDATE)
907                                                 ExecCheckPlanOutput(resultRelInfo->ri_RelationDesc,
908                                                                                         subplan->plan->targetlist);
909
910                                         j = ExecInitJunkFilter(subplan->plan->targetlist,
911                                                         resultRelInfo->ri_RelationDesc->rd_att->tdhasoid,
912                                                                   ExecAllocTableSlot(estate->es_tupleTable));
913
914                                         /*
915                                          * Since it must be UPDATE/DELETE, there had better be a
916                                          * "ctid" junk attribute in the tlist ... but ctid could
917                                          * be at a different resno for each result relation. We
918                                          * look up the ctid resnos now and save them in the
919                                          * junkfilters.
920                                          */
921                                         j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
922                                         if (!AttributeNumberIsValid(j->jf_junkAttNo))
923                                                 elog(ERROR, "could not find junk ctid column");
924                                         resultRelInfo->ri_junkFilter = j;
925                                         resultRelInfo++;
926                                 }
927
928                                 /*
929                                  * Set active junkfilter too; at this point ExecInitAppend has
930                                  * already selected an active result relation...
931                                  */
932                                 estate->es_junkFilter =
933                                         estate->es_result_relation_info->ri_junkFilter;
934
935                                 /*
936                                  * We currently can't support rowmarks in this case, because
937                                  * the associated junk CTIDs might have different resnos in
938                                  * different subplans.
939                                  */
940                                 if (estate->es_rowMarks)
941                                         ereport(ERROR,
942                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
943                                                          errmsg("SELECT FOR UPDATE/SHARE is not supported within a query with multiple result relations")));
944                         }
945                         else
946                         {
947                                 /* Normal case with just one JunkFilter */
948                                 JunkFilter *j;
949
950                                 if (operation == CMD_INSERT || operation == CMD_UPDATE)
951                                         ExecCheckPlanOutput(estate->es_result_relation_info->ri_RelationDesc,
952                                                                                 planstate->plan->targetlist);
953
954                                 j = ExecInitJunkFilter(planstate->plan->targetlist,
955                                                                            tupType->tdhasoid,
956                                                                   ExecAllocTableSlot(estate->es_tupleTable));
957                                 estate->es_junkFilter = j;
958                                 if (estate->es_result_relation_info)
959                                         estate->es_result_relation_info->ri_junkFilter = j;
960
961                                 if (operation == CMD_SELECT)
962                                 {
963                                         /* For SELECT, want to return the cleaned tuple type */
964                                         tupType = j->jf_cleanTupType;
965                                 }
966                                 else if (operation == CMD_UPDATE || operation == CMD_DELETE)
967                                 {
968                                         /* For UPDATE/DELETE, find the ctid junk attr now */
969                                         j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
970                                         if (!AttributeNumberIsValid(j->jf_junkAttNo))
971                                                 elog(ERROR, "could not find junk ctid column");
972                                 }
973
974                                 /* For SELECT FOR UPDATE/SHARE, find the junk attrs now */
975                                 foreach(l, estate->es_rowMarks)
976                                 {
977                                         ExecRowMark *erm = (ExecRowMark *) lfirst(l);
978                                         char            resname[32];
979
980                                         /* always need the ctid */
981                                         snprintf(resname, sizeof(resname), "ctid%u",
982                                                          erm->prti);
983                                         erm->ctidAttNo = ExecFindJunkAttribute(j, resname);
984                                         if (!AttributeNumberIsValid(erm->ctidAttNo))
985                                                 elog(ERROR, "could not find junk \"%s\" column",
986                                                          resname);
987                                         /* if child relation, need tableoid too */
988                                         if (erm->rti != erm->prti)
989                                         {
990                                                 snprintf(resname, sizeof(resname), "tableoid%u",
991                                                                  erm->prti);
992                                                 erm->toidAttNo = ExecFindJunkAttribute(j, resname);
993                                                 if (!AttributeNumberIsValid(erm->toidAttNo))
994                                                         elog(ERROR, "could not find junk \"%s\" column",
995                                                                  resname);
996                                         }
997                                 }
998                         }
999                 }
1000                 else
1001                 {
1002                         if (operation == CMD_INSERT)
1003                                 ExecCheckPlanOutput(estate->es_result_relation_info->ri_RelationDesc,
1004                                                                         planstate->plan->targetlist);
1005
1006                         estate->es_junkFilter = NULL;
1007                         if (estate->es_rowMarks)
1008                                 elog(ERROR, "SELECT FOR UPDATE/SHARE, but no junk columns");
1009                 }
1010         }
1011
1012         /*
1013          * Initialize RETURNING projections if needed.
1014          */
1015         if (plannedstmt->returningLists)
1016         {
1017                 TupleTableSlot *slot;
1018                 ExprContext *econtext;
1019                 ResultRelInfo *resultRelInfo;
1020
1021                 /*
1022                  * We set QueryDesc.tupDesc to be the RETURNING rowtype in this case.
1023                  * We assume all the sublists will generate the same output tupdesc.
1024                  */
1025                 tupType = ExecTypeFromTL((List *) linitial(plannedstmt->returningLists),
1026                                                                  false);
1027
1028                 /* Set up a slot for the output of the RETURNING projection(s) */
1029                 slot = ExecAllocTableSlot(estate->es_tupleTable);
1030                 ExecSetSlotDescriptor(slot, tupType);
1031                 /* Need an econtext too */
1032                 econtext = CreateExprContext(estate);
1033
1034                 /*
1035                  * Build a projection for each result rel.      Note that any SubPlans in
1036                  * the RETURNING lists get attached to the topmost plan node.
1037                  */
1038                 Assert(list_length(plannedstmt->returningLists) == estate->es_num_result_relations);
1039                 resultRelInfo = estate->es_result_relations;
1040                 foreach(l, plannedstmt->returningLists)
1041                 {
1042                         List       *rlist = (List *) lfirst(l);
1043                         List       *rliststate;
1044
1045                         rliststate = (List *) ExecInitExpr((Expr *) rlist, planstate);
1046                         resultRelInfo->ri_projectReturning =
1047                                 ExecBuildProjectionInfo(rliststate, econtext, slot,
1048                                                                          resultRelInfo->ri_RelationDesc->rd_att);
1049                         resultRelInfo++;
1050                 }
1051         }
1052
1053         queryDesc->tupDesc = tupType;
1054         queryDesc->planstate = planstate;
1055
1056         /*
1057          * If doing SELECT INTO, initialize the "into" relation.  We must wait
1058          * till now so we have the "clean" result tuple type to create the new
1059          * table from.
1060          *
1061          * If EXPLAIN, skip creating the "into" relation.
1062          */
1063         if (estate->es_select_into && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
1064                 OpenIntoRel(queryDesc);
1065 }
1066
1067 /*
1068  * Initialize ResultRelInfo data for one result relation
1069  */
1070 void
1071 InitResultRelInfo(ResultRelInfo *resultRelInfo,
1072                                   Relation resultRelationDesc,
1073                                   Index resultRelationIndex,
1074                                   CmdType operation,
1075                                   bool doInstrument)
1076 {
1077         /*
1078          * Check valid relkind ... parser and/or planner should have noticed this
1079          * already, but let's make sure.
1080          */
1081         switch (resultRelationDesc->rd_rel->relkind)
1082         {
1083                 case RELKIND_RELATION:
1084                         /* OK */
1085                         break;
1086                 case RELKIND_SEQUENCE:
1087                         ereport(ERROR,
1088                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1089                                          errmsg("cannot change sequence \"%s\"",
1090                                                         RelationGetRelationName(resultRelationDesc))));
1091                         break;
1092                 case RELKIND_TOASTVALUE:
1093                         ereport(ERROR,
1094                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1095                                          errmsg("cannot change TOAST relation \"%s\"",
1096                                                         RelationGetRelationName(resultRelationDesc))));
1097                         break;
1098                 case RELKIND_VIEW:
1099                         ereport(ERROR,
1100                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1101                                          errmsg("cannot change view \"%s\"",
1102                                                         RelationGetRelationName(resultRelationDesc))));
1103                         break;
1104                 default:
1105                         ereport(ERROR,
1106                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1107                                          errmsg("cannot change relation \"%s\"",
1108                                                         RelationGetRelationName(resultRelationDesc))));
1109                         break;
1110         }
1111
1112         /* OK, fill in the node */
1113         MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1114         resultRelInfo->type = T_ResultRelInfo;
1115         resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1116         resultRelInfo->ri_RelationDesc = resultRelationDesc;
1117         resultRelInfo->ri_NumIndices = 0;
1118         resultRelInfo->ri_IndexRelationDescs = NULL;
1119         resultRelInfo->ri_IndexRelationInfo = NULL;
1120         /* make a copy so as not to depend on relcache info not changing... */
1121         resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1122         if (resultRelInfo->ri_TrigDesc)
1123         {
1124                 int                     n = resultRelInfo->ri_TrigDesc->numtriggers;
1125
1126                 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1127                         palloc0(n * sizeof(FmgrInfo));
1128                 if (doInstrument)
1129                         resultRelInfo->ri_TrigInstrument = InstrAlloc(n);
1130                 else
1131                         resultRelInfo->ri_TrigInstrument = NULL;
1132         }
1133         else
1134         {
1135                 resultRelInfo->ri_TrigFunctions = NULL;
1136                 resultRelInfo->ri_TrigInstrument = NULL;
1137         }
1138         resultRelInfo->ri_ConstraintExprs = NULL;
1139         resultRelInfo->ri_junkFilter = NULL;
1140         resultRelInfo->ri_projectReturning = NULL;
1141
1142         /*
1143          * If there are indices on the result relation, open them and save
1144          * descriptors in the result relation info, so that we can add new index
1145          * entries for the tuples we add/update.  We need not do this for a
1146          * DELETE, however, since deletion doesn't affect indexes.
1147          */
1148         if (resultRelationDesc->rd_rel->relhasindex &&
1149                 operation != CMD_DELETE)
1150                 ExecOpenIndices(resultRelInfo);
1151 }
1152
1153 /*
1154  * Verify that the tuples to be produced by INSERT or UPDATE match the
1155  * target relation's rowtype
1156  *
1157  * We do this to guard against stale plans.  If plan invalidation is
1158  * functioning properly then we should never get a failure here, but better
1159  * safe than sorry.  Note that this is called after we have obtained lock
1160  * on the target rel, so the rowtype can't change underneath us.
1161  *
1162  * The plan output is represented by its targetlist, because that makes
1163  * handling the dropped-column case easier.
1164  */
1165 static void
1166 ExecCheckPlanOutput(Relation resultRel, List *targetList)
1167 {
1168         TupleDesc       resultDesc = RelationGetDescr(resultRel);
1169         int                     attno = 0;
1170         ListCell   *lc;
1171
1172         foreach(lc, targetList)
1173         {
1174                 TargetEntry *tle = (TargetEntry *) lfirst(lc);
1175                 Form_pg_attribute attr;
1176
1177                 if (tle->resjunk)
1178                         continue;                       /* ignore junk tlist items */
1179
1180                 if (attno >= resultDesc->natts)
1181                         ereport(ERROR,
1182                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1183                                          errmsg("table row type and query-specified row type do not match"),
1184                                          errdetail("Query has too many columns.")));
1185                 attr = resultDesc->attrs[attno++];
1186
1187                 if (!attr->attisdropped)
1188                 {
1189                         /* Normal case: demand type match */
1190                         if (exprType((Node *) tle->expr) != attr->atttypid)
1191                                 ereport(ERROR,
1192                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1193                                                  errmsg("table row type and query-specified row type do not match"),
1194                                                  errdetail("Table has type %s at ordinal position %d, but query expects %s.",
1195                                                                    format_type_be(attr->atttypid),
1196                                                                    attno,
1197                                                          format_type_be(exprType((Node *) tle->expr)))));
1198                 }
1199                 else
1200                 {
1201                         /*
1202                          * For a dropped column, we can't check atttypid (it's likely 0).
1203                          * In any case the planner has most likely inserted an INT4 null.
1204                          * What we insist on is just *some* NULL constant.
1205                          */
1206                         if (!IsA(tle->expr, Const) ||
1207                                 !((Const *) tle->expr)->constisnull)
1208                                 ereport(ERROR,
1209                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1210                                                  errmsg("table row type and query-specified row type do not match"),
1211                                                  errdetail("Query provides a value for a dropped column at ordinal position %d.",
1212                                                                    attno)));
1213                 }
1214         }
1215         if (attno != resultDesc->natts)
1216                 ereport(ERROR,
1217                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1218                   errmsg("table row type and query-specified row type do not match"),
1219                                  errdetail("Query has too few columns.")));
1220 }
1221
1222 /*
1223  *              ExecGetTriggerResultRel
1224  *
1225  * Get a ResultRelInfo for a trigger target relation.  Most of the time,
1226  * triggers are fired on one of the result relations of the query, and so
1227  * we can just return a member of the es_result_relations array.  (Note: in
1228  * self-join situations there might be multiple members with the same OID;
1229  * if so it doesn't matter which one we pick.)  However, it is sometimes
1230  * necessary to fire triggers on other relations; this happens mainly when an
1231  * RI update trigger queues additional triggers on other relations, which will
1232  * be processed in the context of the outer query.      For efficiency's sake,
1233  * we want to have a ResultRelInfo for those triggers too; that can avoid
1234  * repeated re-opening of the relation.  (It also provides a way for EXPLAIN
1235  * ANALYZE to report the runtimes of such triggers.)  So we make additional
1236  * ResultRelInfo's as needed, and save them in es_trig_target_relations.
1237  */
1238 ResultRelInfo *
1239 ExecGetTriggerResultRel(EState *estate, Oid relid)
1240 {
1241         ResultRelInfo *rInfo;
1242         int                     nr;
1243         ListCell   *l;
1244         Relation        rel;
1245         MemoryContext oldcontext;
1246
1247         /* First, search through the query result relations */
1248         rInfo = estate->es_result_relations;
1249         nr = estate->es_num_result_relations;
1250         while (nr > 0)
1251         {
1252                 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1253                         return rInfo;
1254                 rInfo++;
1255                 nr--;
1256         }
1257         /* Nope, but maybe we already made an extra ResultRelInfo for it */
1258         foreach(l, estate->es_trig_target_relations)
1259         {
1260                 rInfo = (ResultRelInfo *) lfirst(l);
1261                 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1262                         return rInfo;
1263         }
1264         /* Nope, so we need a new one */
1265
1266         /*
1267          * Open the target relation's relcache entry.  We assume that an
1268          * appropriate lock is still held by the backend from whenever the trigger
1269          * event got queued, so we need take no new lock here.
1270          */
1271         rel = heap_open(relid, NoLock);
1272
1273         /*
1274          * Make the new entry in the right context.  Currently, we don't need any
1275          * index information in ResultRelInfos used only for triggers, so tell
1276          * InitResultRelInfo it's a DELETE.
1277          */
1278         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1279         rInfo = makeNode(ResultRelInfo);
1280         InitResultRelInfo(rInfo,
1281                                           rel,
1282                                           0,            /* dummy rangetable index */
1283                                           CMD_DELETE,
1284                                           estate->es_instrument);
1285         estate->es_trig_target_relations =
1286                 lappend(estate->es_trig_target_relations, rInfo);
1287         MemoryContextSwitchTo(oldcontext);
1288
1289         return rInfo;
1290 }
1291
1292 /*
1293  *              ExecContextForcesOids
1294  *
1295  * This is pretty grotty: when doing INSERT, UPDATE, or SELECT INTO,
1296  * we need to ensure that result tuples have space for an OID iff they are
1297  * going to be stored into a relation that has OIDs.  In other contexts
1298  * we are free to choose whether to leave space for OIDs in result tuples
1299  * (we generally don't want to, but we do if a physical-tlist optimization
1300  * is possible).  This routine checks the plan context and returns TRUE if the
1301  * choice is forced, FALSE if the choice is not forced.  In the TRUE case,
1302  * *hasoids is set to the required value.
1303  *
1304  * One reason this is ugly is that all plan nodes in the plan tree will emit
1305  * tuples with space for an OID, though we really only need the topmost node
1306  * to do so.  However, node types like Sort don't project new tuples but just
1307  * return their inputs, and in those cases the requirement propagates down
1308  * to the input node.  Eventually we might make this code smart enough to
1309  * recognize how far down the requirement really goes, but for now we just
1310  * make all plan nodes do the same thing if the top level forces the choice.
1311  *
1312  * We assume that estate->es_result_relation_info is already set up to
1313  * describe the target relation.  Note that in an UPDATE that spans an
1314  * inheritance tree, some of the target relations may have OIDs and some not.
1315  * We have to make the decisions on a per-relation basis as we initialize
1316  * each of the child plans of the topmost Append plan.
1317  *
1318  * SELECT INTO is even uglier, because we don't have the INTO relation's
1319  * descriptor available when this code runs; we have to look aside at a
1320  * flag set by InitPlan().
1321  */
1322 bool
1323 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
1324 {
1325         if (planstate->state->es_select_into)
1326         {
1327                 *hasoids = planstate->state->es_into_oids;
1328                 return true;
1329         }
1330         else
1331         {
1332                 ResultRelInfo *ri = planstate->state->es_result_relation_info;
1333
1334                 if (ri != NULL)
1335                 {
1336                         Relation        rel = ri->ri_RelationDesc;
1337
1338                         if (rel != NULL)
1339                         {
1340                                 *hasoids = rel->rd_rel->relhasoids;
1341                                 return true;
1342                         }
1343                 }
1344         }
1345
1346         return false;
1347 }
1348
1349 /* ----------------------------------------------------------------
1350  *              ExecEndPlan
1351  *
1352  *              Cleans up the query plan -- closes files and frees up storage
1353  *
1354  * NOTE: we are no longer very worried about freeing storage per se
1355  * in this code; FreeExecutorState should be guaranteed to release all
1356  * memory that needs to be released.  What we are worried about doing
1357  * is closing relations and dropping buffer pins.  Thus, for example,
1358  * tuple tables must be cleared or dropped to ensure pins are released.
1359  * ----------------------------------------------------------------
1360  */
1361 static void
1362 ExecEndPlan(PlanState *planstate, EState *estate)
1363 {
1364         ResultRelInfo *resultRelInfo;
1365         int                     i;
1366         ListCell   *l;
1367
1368         /*
1369          * shut down any PlanQual processing we were doing
1370          */
1371         if (estate->es_evalPlanQual != NULL)
1372                 EndEvalPlanQual(estate);
1373
1374         /*
1375          * shut down the node-type-specific query processing
1376          */
1377         ExecEndNode(planstate);
1378
1379         /*
1380          * for subplans too
1381          */
1382         foreach(l, estate->es_subplanstates)
1383         {
1384                 PlanState  *subplanstate = (PlanState *) lfirst(l);
1385
1386                 ExecEndNode(subplanstate);
1387         }
1388
1389         /*
1390          * destroy the executor "tuple" table.
1391          */
1392         ExecDropTupleTable(estate->es_tupleTable, true);
1393         estate->es_tupleTable = NULL;
1394
1395         /*
1396          * close the result relation(s) if any, but hold locks until xact commit.
1397          */
1398         resultRelInfo = estate->es_result_relations;
1399         for (i = estate->es_num_result_relations; i > 0; i--)
1400         {
1401                 /* Close indices and then the relation itself */
1402                 ExecCloseIndices(resultRelInfo);
1403                 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1404                 resultRelInfo++;
1405         }
1406
1407         /*
1408          * likewise close any trigger target relations
1409          */
1410         foreach(l, estate->es_trig_target_relations)
1411         {
1412                 resultRelInfo = (ResultRelInfo *) lfirst(l);
1413                 /* Close indices and then the relation itself */
1414                 ExecCloseIndices(resultRelInfo);
1415                 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1416         }
1417
1418         /*
1419          * close any relations selected FOR UPDATE/FOR SHARE, again keeping locks
1420          */
1421         foreach(l, estate->es_rowMarks)
1422         {
1423                 ExecRowMark *erm = lfirst(l);
1424
1425                 heap_close(erm->relation, NoLock);
1426         }
1427 }
1428
1429 /* ----------------------------------------------------------------
1430  *              ExecutePlan
1431  *
1432  *              Processes the query plan until we have processed 'numberTuples' tuples,
1433  *              moving in the specified direction.
1434  *
1435  *              Runs to completion if numberTuples is 0
1436  *
1437  * Note: the ctid attribute is a 'junk' attribute that is removed before the
1438  * user can see it
1439  * ----------------------------------------------------------------
1440  */
1441 static void
1442 ExecutePlan(EState *estate,
1443                         PlanState *planstate,
1444                         CmdType operation,
1445                         long numberTuples,
1446                         ScanDirection direction,
1447                         DestReceiver *dest)
1448 {
1449         JunkFilter *junkfilter;
1450         TupleTableSlot *planSlot;
1451         TupleTableSlot *slot;
1452         ItemPointer tupleid = NULL;
1453         ItemPointerData tuple_ctid;
1454         long            current_tuple_count;
1455
1456         /*
1457          * initialize local variables
1458          */
1459         current_tuple_count = 0;
1460
1461         /*
1462          * Set the direction.
1463          */
1464         estate->es_direction = direction;
1465
1466         /*
1467          * Process BEFORE EACH STATEMENT triggers
1468          */
1469         switch (operation)
1470         {
1471                 case CMD_UPDATE:
1472                         ExecBSUpdateTriggers(estate, estate->es_result_relation_info);
1473                         break;
1474                 case CMD_DELETE:
1475                         ExecBSDeleteTriggers(estate, estate->es_result_relation_info);
1476                         break;
1477                 case CMD_INSERT:
1478                         ExecBSInsertTriggers(estate, estate->es_result_relation_info);
1479                         break;
1480                 default:
1481                         /* do nothing */
1482                         break;
1483         }
1484
1485         /*
1486          * Loop until we've processed the proper number of tuples from the plan.
1487          */
1488         for (;;)
1489         {
1490                 /* Reset the per-output-tuple exprcontext */
1491                 ResetPerTupleExprContext(estate);
1492
1493                 /*
1494                  * Execute the plan and obtain a tuple
1495                  */
1496 lnext:  ;
1497                 if (estate->es_useEvalPlan)
1498                 {
1499                         planSlot = EvalPlanQualNext(estate);
1500                         if (TupIsNull(planSlot))
1501                                 planSlot = ExecProcNode(planstate);
1502                 }
1503                 else
1504                         planSlot = ExecProcNode(planstate);
1505
1506                 /*
1507                  * if the tuple is null, then we assume there is nothing more to
1508                  * process so we just end the loop...
1509                  */
1510                 if (TupIsNull(planSlot))
1511                         break;
1512                 slot = planSlot;
1513
1514                 /*
1515                  * If we have a junk filter, then project a new tuple with the junk
1516                  * removed.
1517                  *
1518                  * Store this new "clean" tuple in the junkfilter's resultSlot.
1519                  * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1520                  * because that tuple slot has the wrong descriptor.)
1521                  *
1522                  * But first, extract all the junk information we need.
1523                  */
1524                 if ((junkfilter = estate->es_junkFilter) != NULL)
1525                 {
1526                         /*
1527                          * Process any FOR UPDATE or FOR SHARE locking requested.
1528                          */
1529                         if (estate->es_rowMarks != NIL)
1530                         {
1531                                 ListCell   *l;
1532
1533                 lmark:  ;
1534                                 foreach(l, estate->es_rowMarks)
1535                                 {
1536                                         ExecRowMark *erm = lfirst(l);
1537                                         Datum           datum;
1538                                         bool            isNull;
1539                                         HeapTupleData tuple;
1540                                         Buffer          buffer;
1541                                         ItemPointerData update_ctid;
1542                                         TransactionId update_xmax;
1543                                         TupleTableSlot *newSlot;
1544                                         LockTupleMode lockmode;
1545                                         HTSU_Result test;
1546
1547                                         /* if child rel, must check whether it produced this row */
1548                                         if (erm->rti != erm->prti)
1549                                         {
1550                                                 Oid                     tableoid;
1551
1552                                                 datum = ExecGetJunkAttribute(slot,
1553                                                                                                          erm->toidAttNo,
1554                                                                                                          &isNull);
1555                                                 /* shouldn't ever get a null result... */
1556                                                 if (isNull)
1557                                                         elog(ERROR, "tableoid is NULL");
1558                                                 tableoid = DatumGetObjectId(datum);
1559
1560                                                 if (tableoid != RelationGetRelid(erm->relation))
1561                                                 {
1562                                                         /* this child is inactive right now */
1563                                                         ItemPointerSetInvalid(&(erm->curCtid));
1564                                                         continue;
1565                                                 }
1566                                         }
1567
1568                                         /* okay, fetch the tuple by ctid */
1569                                         datum = ExecGetJunkAttribute(slot,
1570                                                                                                  erm->ctidAttNo,
1571                                                                                                  &isNull);
1572                                         /* shouldn't ever get a null result... */
1573                                         if (isNull)
1574                                                 elog(ERROR, "ctid is NULL");
1575                                         tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1576
1577                                         if (erm->forUpdate)
1578                                                 lockmode = LockTupleExclusive;
1579                                         else
1580                                                 lockmode = LockTupleShared;
1581
1582                                         test = heap_lock_tuple(erm->relation, &tuple, &buffer,
1583                                                                                    &update_ctid, &update_xmax,
1584                                                                                    estate->es_output_cid,
1585                                                                                    lockmode, erm->noWait);
1586                                         ReleaseBuffer(buffer);
1587                                         switch (test)
1588                                         {
1589                                                 case HeapTupleSelfUpdated:
1590                                                         /* treat it as deleted; do not process */
1591                                                         goto lnext;
1592
1593                                                 case HeapTupleMayBeUpdated:
1594                                                         break;
1595
1596                                                 case HeapTupleUpdated:
1597                                                         if (IsXactIsoLevelSerializable)
1598                                                                 ereport(ERROR,
1599                                                                  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1600                                                                   errmsg("could not serialize access due to concurrent update")));
1601                                                         if (!ItemPointerEquals(&update_ctid,
1602                                                                                                    &tuple.t_self))
1603                                                         {
1604                                                                 /* updated, so look at updated version */
1605                                                                 newSlot = EvalPlanQual(estate,
1606                                                                                                            erm->rti,
1607                                                                                                            &update_ctid,
1608                                                                                                            update_xmax);
1609                                                                 if (!TupIsNull(newSlot))
1610                                                                 {
1611                                                                         slot = planSlot = newSlot;
1612                                                                         estate->es_useEvalPlan = true;
1613                                                                         goto lmark;
1614                                                                 }
1615                                                         }
1616
1617                                                         /*
1618                                                          * if tuple was deleted or PlanQual failed for
1619                                                          * updated tuple - we must not return this tuple!
1620                                                          */
1621                                                         goto lnext;
1622
1623                                                 default:
1624                                                         elog(ERROR, "unrecognized heap_lock_tuple status: %u",
1625                                                                  test);
1626                                         }
1627
1628                                         /* Remember tuple TID for WHERE CURRENT OF */
1629                                         erm->curCtid = tuple.t_self;
1630                                 }
1631                         }
1632
1633                         /*
1634                          * extract the 'ctid' junk attribute.
1635                          */
1636                         if (operation == CMD_UPDATE || operation == CMD_DELETE)
1637                         {
1638                                 Datum           datum;
1639                                 bool            isNull;
1640
1641                                 datum = ExecGetJunkAttribute(slot, junkfilter->jf_junkAttNo,
1642                                                                                          &isNull);
1643                                 /* shouldn't ever get a null result... */
1644                                 if (isNull)
1645                                         elog(ERROR, "ctid is NULL");
1646
1647                                 tupleid = (ItemPointer) DatumGetPointer(datum);
1648                                 tuple_ctid = *tupleid;  /* make sure we don't free the ctid!! */
1649                                 tupleid = &tuple_ctid;
1650                         }
1651
1652                         /*
1653                          * Create a new "clean" tuple with all junk attributes removed. We
1654                          * don't need to do this for DELETE, however (there will in fact
1655                          * be no non-junk attributes in a DELETE!)
1656                          */
1657                         if (operation != CMD_DELETE)
1658                                 slot = ExecFilterJunk(junkfilter, slot);
1659                 }
1660
1661                 /*
1662                  * now that we have a tuple, do the appropriate thing with it.. either
1663                  * send it to the output destination, add it to a relation someplace,
1664                  * delete it from a relation, or modify some of its attributes.
1665                  */
1666                 switch (operation)
1667                 {
1668                         case CMD_SELECT:
1669                                 ExecSelect(slot, dest, estate);
1670                                 break;
1671
1672                         case CMD_INSERT:
1673                                 ExecInsert(slot, tupleid, planSlot, dest, estate);
1674                                 break;
1675
1676                         case CMD_DELETE:
1677                                 ExecDelete(tupleid, planSlot, dest, estate);
1678                                 break;
1679
1680                         case CMD_UPDATE:
1681                                 ExecUpdate(slot, tupleid, planSlot, dest, estate);
1682                                 break;
1683
1684                         default:
1685                                 elog(ERROR, "unrecognized operation code: %d",
1686                                          (int) operation);
1687                                 break;
1688                 }
1689
1690                 /*
1691                  * check our tuple count.. if we've processed the proper number then
1692                  * quit, else loop again and process more tuples.  Zero numberTuples
1693                  * means no limit.
1694                  */
1695                 current_tuple_count++;
1696                 if (numberTuples && numberTuples == current_tuple_count)
1697                         break;
1698         }
1699
1700         /*
1701          * Process AFTER EACH STATEMENT triggers
1702          */
1703         switch (operation)
1704         {
1705                 case CMD_UPDATE:
1706                         ExecASUpdateTriggers(estate, estate->es_result_relation_info);
1707                         break;
1708                 case CMD_DELETE:
1709                         ExecASDeleteTriggers(estate, estate->es_result_relation_info);
1710                         break;
1711                 case CMD_INSERT:
1712                         ExecASInsertTriggers(estate, estate->es_result_relation_info);
1713                         break;
1714                 default:
1715                         /* do nothing */
1716                         break;
1717         }
1718 }
1719
1720 /* ----------------------------------------------------------------
1721  *              ExecSelect
1722  *
1723  *              SELECTs are easy.. we just pass the tuple to the appropriate
1724  *              output function.
1725  * ----------------------------------------------------------------
1726  */
1727 static void
1728 ExecSelect(TupleTableSlot *slot,
1729                    DestReceiver *dest,
1730                    EState *estate)
1731 {
1732         (*dest->receiveSlot) (slot, dest);
1733         IncrRetrieved();
1734         (estate->es_processed)++;
1735 }
1736
1737 /* ----------------------------------------------------------------
1738  *              ExecInsert
1739  *
1740  *              INSERTs are trickier.. we have to insert the tuple into
1741  *              the base relation and insert appropriate tuples into the
1742  *              index relations.
1743  * ----------------------------------------------------------------
1744  */
1745 static void
1746 ExecInsert(TupleTableSlot *slot,
1747                    ItemPointer tupleid,
1748                    TupleTableSlot *planSlot,
1749                    DestReceiver *dest,
1750                    EState *estate)
1751 {
1752         HeapTuple       tuple;
1753         ResultRelInfo *resultRelInfo;
1754         Relation        resultRelationDesc;
1755         Oid                     newId;
1756
1757         /*
1758          * get the heap tuple out of the tuple table slot, making sure we have a
1759          * writable copy
1760          */
1761         tuple = ExecMaterializeSlot(slot);
1762
1763         /*
1764          * get information on the (current) result relation
1765          */
1766         resultRelInfo = estate->es_result_relation_info;
1767         resultRelationDesc = resultRelInfo->ri_RelationDesc;
1768
1769         /*
1770          * If the result relation has OIDs, force the tuple's OID to zero so that
1771          * heap_insert will assign a fresh OID.  Usually the OID already will be
1772          * zero at this point, but there are corner cases where the plan tree can
1773          * return a tuple extracted literally from some table with the same
1774          * rowtype.
1775          *
1776          * XXX if we ever wanted to allow users to assign their own OIDs to new
1777          * rows, this'd be the place to do it.  For the moment, we make a point of
1778          * doing this before calling triggers, so that a user-supplied trigger
1779          * could hack the OID if desired.
1780          */
1781         if (resultRelationDesc->rd_rel->relhasoids)
1782                 HeapTupleSetOid(tuple, InvalidOid);
1783
1784         /* BEFORE ROW INSERT Triggers */
1785         if (resultRelInfo->ri_TrigDesc &&
1786                 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1787         {
1788                 HeapTuple       newtuple;
1789
1790                 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1791
1792                 if (newtuple == NULL)   /* "do nothing" */
1793                         return;
1794
1795                 if (newtuple != tuple)  /* modified by Trigger(s) */
1796                 {
1797                         /*
1798                          * Put the modified tuple into a slot for convenience of routines
1799                          * below.  We assume the tuple was allocated in per-tuple memory
1800                          * context, and therefore will go away by itself. The tuple table
1801                          * slot should not try to clear it.
1802                          */
1803                         TupleTableSlot *newslot = estate->es_trig_tuple_slot;
1804
1805                         if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
1806                                 ExecSetSlotDescriptor(newslot, slot->tts_tupleDescriptor);
1807                         ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
1808                         slot = newslot;
1809                         tuple = newtuple;
1810                 }
1811         }
1812
1813         /*
1814          * Check the constraints of the tuple
1815          */
1816         if (resultRelationDesc->rd_att->constr)
1817                 ExecConstraints(resultRelInfo, slot, estate);
1818
1819         /*
1820          * insert the tuple
1821          *
1822          * Note: heap_insert returns the tid (location) of the new tuple in the
1823          * t_self field.
1824          */
1825         newId = heap_insert(resultRelationDesc, tuple,
1826                                                 estate->es_output_cid, 0, NULL);
1827
1828         IncrAppended();
1829         (estate->es_processed)++;
1830         estate->es_lastoid = newId;
1831         setLastTid(&(tuple->t_self));
1832
1833         /*
1834          * insert index entries for tuple
1835          */
1836         if (resultRelInfo->ri_NumIndices > 0)
1837                 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1838
1839         /* AFTER ROW INSERT Triggers */
1840         ExecARInsertTriggers(estate, resultRelInfo, tuple);
1841
1842         /* Process RETURNING if present */
1843         if (resultRelInfo->ri_projectReturning)
1844                 ExecProcessReturning(resultRelInfo->ri_projectReturning,
1845                                                          slot, planSlot, dest);
1846 }
1847
1848 /* ----------------------------------------------------------------
1849  *              ExecDelete
1850  *
1851  *              DELETE is like UPDATE, except that we delete the tuple and no
1852  *              index modifications are needed
1853  * ----------------------------------------------------------------
1854  */
1855 static void
1856 ExecDelete(ItemPointer tupleid,
1857                    TupleTableSlot *planSlot,
1858                    DestReceiver *dest,
1859                    EState *estate)
1860 {
1861         ResultRelInfo *resultRelInfo;
1862         Relation        resultRelationDesc;
1863         HTSU_Result result;
1864         ItemPointerData update_ctid;
1865         TransactionId update_xmax;
1866
1867         /*
1868          * get information on the (current) result relation
1869          */
1870         resultRelInfo = estate->es_result_relation_info;
1871         resultRelationDesc = resultRelInfo->ri_RelationDesc;
1872
1873         /* BEFORE ROW DELETE Triggers */
1874         if (resultRelInfo->ri_TrigDesc &&
1875                 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1876         {
1877                 bool            dodelete;
1878
1879                 dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid);
1880
1881                 if (!dodelete)                  /* "do nothing" */
1882                         return;
1883         }
1884
1885         /*
1886          * delete the tuple
1887          *
1888          * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
1889          * the row to be deleted is visible to that snapshot, and throw a can't-
1890          * serialize error if not.      This is a special-case behavior needed for
1891          * referential integrity updates in serializable transactions.
1892          */
1893 ldelete:;
1894         result = heap_delete(resultRelationDesc, tupleid,
1895                                                  &update_ctid, &update_xmax,
1896                                                  estate->es_output_cid,
1897                                                  estate->es_crosscheck_snapshot,
1898                                                  true /* wait for commit */ );
1899         switch (result)
1900         {
1901                 case HeapTupleSelfUpdated:
1902                         /* already deleted by self; nothing to do */
1903                         return;
1904
1905                 case HeapTupleMayBeUpdated:
1906                         break;
1907
1908                 case HeapTupleUpdated:
1909                         if (IsXactIsoLevelSerializable)
1910                                 ereport(ERROR,
1911                                                 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1912                                                  errmsg("could not serialize access due to concurrent update")));
1913                         else if (!ItemPointerEquals(tupleid, &update_ctid))
1914                         {
1915                                 TupleTableSlot *epqslot;
1916
1917                                 epqslot = EvalPlanQual(estate,
1918                                                                            resultRelInfo->ri_RangeTableIndex,
1919                                                                            &update_ctid,
1920                                                                            update_xmax);
1921                                 if (!TupIsNull(epqslot))
1922                                 {
1923                                         *tupleid = update_ctid;
1924                                         goto ldelete;
1925                                 }
1926                         }
1927                         /* tuple already deleted; nothing to do */
1928                         return;
1929
1930                 default:
1931                         elog(ERROR, "unrecognized heap_delete status: %u", result);
1932                         return;
1933         }
1934
1935         IncrDeleted();
1936         (estate->es_processed)++;
1937
1938         /*
1939          * Note: Normally one would think that we have to delete index tuples
1940          * associated with the heap tuple now...
1941          *
1942          * ... but in POSTGRES, we have no need to do this because VACUUM will
1943          * take care of it later.  We can't delete index tuples immediately
1944          * anyway, since the tuple is still visible to other transactions.
1945          */
1946
1947         /* AFTER ROW DELETE Triggers */
1948         ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1949
1950         /* Process RETURNING if present */
1951         if (resultRelInfo->ri_projectReturning)
1952         {
1953                 /*
1954                  * We have to put the target tuple into a slot, which means first we
1955                  * gotta fetch it.      We can use the trigger tuple slot.
1956                  */
1957                 TupleTableSlot *slot = estate->es_trig_tuple_slot;
1958                 HeapTupleData deltuple;
1959                 Buffer          delbuffer;
1960
1961                 deltuple.t_self = *tupleid;
1962                 if (!heap_fetch(resultRelationDesc, SnapshotAny,
1963                                                 &deltuple, &delbuffer, false, NULL))
1964                         elog(ERROR, "failed to fetch deleted tuple for DELETE RETURNING");
1965
1966                 if (slot->tts_tupleDescriptor != RelationGetDescr(resultRelationDesc))
1967                         ExecSetSlotDescriptor(slot, RelationGetDescr(resultRelationDesc));
1968                 ExecStoreTuple(&deltuple, slot, InvalidBuffer, false);
1969
1970                 ExecProcessReturning(resultRelInfo->ri_projectReturning,
1971                                                          slot, planSlot, dest);
1972
1973                 ExecClearTuple(slot);
1974                 ReleaseBuffer(delbuffer);
1975         }
1976 }
1977
1978 /* ----------------------------------------------------------------
1979  *              ExecUpdate
1980  *
1981  *              note: we can't run UPDATE queries with transactions
1982  *              off because UPDATEs are actually INSERTs and our
1983  *              scan will mistakenly loop forever, updating the tuple
1984  *              it just inserted..      This should be fixed but until it
1985  *              is, we don't want to get stuck in an infinite loop
1986  *              which corrupts your database..
1987  * ----------------------------------------------------------------
1988  */
1989 static void
1990 ExecUpdate(TupleTableSlot *slot,
1991                    ItemPointer tupleid,
1992                    TupleTableSlot *planSlot,
1993                    DestReceiver *dest,
1994                    EState *estate)
1995 {
1996         HeapTuple       tuple;
1997         ResultRelInfo *resultRelInfo;
1998         Relation        resultRelationDesc;
1999         HTSU_Result result;
2000         ItemPointerData update_ctid;
2001         TransactionId update_xmax;
2002
2003         /*
2004          * abort the operation if not running transactions
2005          */
2006         if (IsBootstrapProcessingMode())
2007                 elog(ERROR, "cannot UPDATE during bootstrap");
2008
2009         /*
2010          * get the heap tuple out of the tuple table slot, making sure we have a
2011          * writable copy
2012          */
2013         tuple = ExecMaterializeSlot(slot);
2014
2015         /*
2016          * get information on the (current) result relation
2017          */
2018         resultRelInfo = estate->es_result_relation_info;
2019         resultRelationDesc = resultRelInfo->ri_RelationDesc;
2020
2021         /* BEFORE ROW UPDATE Triggers */
2022         if (resultRelInfo->ri_TrigDesc &&
2023                 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
2024         {
2025                 HeapTuple       newtuple;
2026
2027                 newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
2028                                                                                 tupleid, tuple);
2029
2030                 if (newtuple == NULL)   /* "do nothing" */
2031                         return;
2032
2033                 if (newtuple != tuple)  /* modified by Trigger(s) */
2034                 {
2035                         /*
2036                          * Put the modified tuple into a slot for convenience of routines
2037                          * below.  We assume the tuple was allocated in per-tuple memory
2038                          * context, and therefore will go away by itself. The tuple table
2039                          * slot should not try to clear it.
2040                          */
2041                         TupleTableSlot *newslot = estate->es_trig_tuple_slot;
2042
2043                         if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
2044                                 ExecSetSlotDescriptor(newslot, slot->tts_tupleDescriptor);
2045                         ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
2046                         slot = newslot;
2047                         tuple = newtuple;
2048                 }
2049         }
2050
2051         /*
2052          * Check the constraints of the tuple
2053          *
2054          * If we generate a new candidate tuple after EvalPlanQual testing, we
2055          * must loop back here and recheck constraints.  (We don't need to redo
2056          * triggers, however.  If there are any BEFORE triggers then trigger.c
2057          * will have done heap_lock_tuple to lock the correct tuple, so there's no
2058          * need to do them again.)
2059          */
2060 lreplace:;
2061         if (resultRelationDesc->rd_att->constr)
2062                 ExecConstraints(resultRelInfo, slot, estate);
2063
2064         /*
2065          * replace the heap tuple
2066          *
2067          * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
2068          * the row to be updated is visible to that snapshot, and throw a can't-
2069          * serialize error if not.      This is a special-case behavior needed for
2070          * referential integrity updates in serializable transactions.
2071          */
2072         result = heap_update(resultRelationDesc, tupleid, tuple,
2073                                                  &update_ctid, &update_xmax,
2074                                                  estate->es_output_cid,
2075                                                  estate->es_crosscheck_snapshot,
2076                                                  true /* wait for commit */ );
2077         switch (result)
2078         {
2079                 case HeapTupleSelfUpdated:
2080                         /* already deleted by self; nothing to do */
2081                         return;
2082
2083                 case HeapTupleMayBeUpdated:
2084                         break;
2085
2086                 case HeapTupleUpdated:
2087                         if (IsXactIsoLevelSerializable)
2088                                 ereport(ERROR,
2089                                                 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2090                                                  errmsg("could not serialize access due to concurrent update")));
2091                         else if (!ItemPointerEquals(tupleid, &update_ctid))
2092                         {
2093                                 TupleTableSlot *epqslot;
2094
2095                                 epqslot = EvalPlanQual(estate,
2096                                                                            resultRelInfo->ri_RangeTableIndex,
2097                                                                            &update_ctid,
2098                                                                            update_xmax);
2099                                 if (!TupIsNull(epqslot))
2100                                 {
2101                                         *tupleid = update_ctid;
2102                                         slot = ExecFilterJunk(estate->es_junkFilter, epqslot);
2103                                         tuple = ExecMaterializeSlot(slot);
2104                                         goto lreplace;
2105                                 }
2106                         }
2107                         /* tuple already deleted; nothing to do */
2108                         return;
2109
2110                 default:
2111                         elog(ERROR, "unrecognized heap_update status: %u", result);
2112                         return;
2113         }
2114
2115         IncrReplaced();
2116         (estate->es_processed)++;
2117
2118         /*
2119          * Note: instead of having to update the old index tuples associated with
2120          * the heap tuple, all we do is form and insert new index tuples. This is
2121          * because UPDATEs are actually DELETEs and INSERTs, and index tuple
2122          * deletion is done later by VACUUM (see notes in ExecDelete).  All we do
2123          * here is insert new index tuples.  -cim 9/27/89
2124          */
2125
2126         /*
2127          * insert index entries for tuple
2128          *
2129          * Note: heap_update returns the tid (location) of the new tuple in the
2130          * t_self field.
2131          *
2132          * If it's a HOT update, we mustn't insert new index entries.
2133          */
2134         if (resultRelInfo->ri_NumIndices > 0 && !HeapTupleIsHeapOnly(tuple))
2135                 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
2136
2137         /* AFTER ROW UPDATE Triggers */
2138         ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
2139
2140         /* Process RETURNING if present */
2141         if (resultRelInfo->ri_projectReturning)
2142                 ExecProcessReturning(resultRelInfo->ri_projectReturning,
2143                                                          slot, planSlot, dest);
2144 }
2145
2146 /*
2147  * ExecRelCheck --- check that tuple meets constraints for result relation
2148  */
2149 static const char *
2150 ExecRelCheck(ResultRelInfo *resultRelInfo,
2151                          TupleTableSlot *slot, EState *estate)
2152 {
2153         Relation        rel = resultRelInfo->ri_RelationDesc;
2154         int                     ncheck = rel->rd_att->constr->num_check;
2155         ConstrCheck *check = rel->rd_att->constr->check;
2156         ExprContext *econtext;
2157         MemoryContext oldContext;
2158         List       *qual;
2159         int                     i;
2160
2161         /*
2162          * If first time through for this result relation, build expression
2163          * nodetrees for rel's constraint expressions.  Keep them in the per-query
2164          * memory context so they'll survive throughout the query.
2165          */
2166         if (resultRelInfo->ri_ConstraintExprs == NULL)
2167         {
2168                 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
2169                 resultRelInfo->ri_ConstraintExprs =
2170                         (List **) palloc(ncheck * sizeof(List *));
2171                 for (i = 0; i < ncheck; i++)
2172                 {
2173                         /* ExecQual wants implicit-AND form */
2174                         qual = make_ands_implicit(stringToNode(check[i].ccbin));
2175                         resultRelInfo->ri_ConstraintExprs[i] = (List *)
2176                                 ExecPrepareExpr((Expr *) qual, estate);
2177                 }
2178                 MemoryContextSwitchTo(oldContext);
2179         }
2180
2181         /*
2182          * We will use the EState's per-tuple context for evaluating constraint
2183          * expressions (creating it if it's not already there).
2184          */
2185         econtext = GetPerTupleExprContext(estate);
2186
2187         /* Arrange for econtext's scan tuple to be the tuple under test */
2188         econtext->ecxt_scantuple = slot;
2189
2190         /* And evaluate the constraints */
2191         for (i = 0; i < ncheck; i++)
2192         {
2193                 qual = resultRelInfo->ri_ConstraintExprs[i];
2194
2195                 /*
2196                  * NOTE: SQL92 specifies that a NULL result from a constraint
2197                  * expression is not to be treated as a failure.  Therefore, tell
2198                  * ExecQual to return TRUE for NULL.
2199                  */
2200                 if (!ExecQual(qual, econtext, true))
2201                         return check[i].ccname;
2202         }
2203
2204         /* NULL result means no error */
2205         return NULL;
2206 }
2207
2208 void
2209 ExecConstraints(ResultRelInfo *resultRelInfo,
2210                                 TupleTableSlot *slot, EState *estate)
2211 {
2212         Relation        rel = resultRelInfo->ri_RelationDesc;
2213         TupleConstr *constr = rel->rd_att->constr;
2214
2215         Assert(constr);
2216
2217         if (constr->has_not_null)
2218         {
2219                 int                     natts = rel->rd_att->natts;
2220                 int                     attrChk;
2221
2222                 for (attrChk = 1; attrChk <= natts; attrChk++)
2223                 {
2224                         if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
2225                                 slot_attisnull(slot, attrChk))
2226                                 ereport(ERROR,
2227                                                 (errcode(ERRCODE_NOT_NULL_VIOLATION),
2228                                                  errmsg("null value in column \"%s\" violates not-null constraint",
2229                                                 NameStr(rel->rd_att->attrs[attrChk - 1]->attname))));
2230                 }
2231         }
2232
2233         if (constr->num_check > 0)
2234         {
2235                 const char *failed;
2236
2237                 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
2238                         ereport(ERROR,
2239                                         (errcode(ERRCODE_CHECK_VIOLATION),
2240                                          errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
2241                                                         RelationGetRelationName(rel), failed)));
2242         }
2243 }
2244
2245 /*
2246  * ExecProcessReturning --- evaluate a RETURNING list and send to dest
2247  *
2248  * projectReturning: RETURNING projection info for current result rel
2249  * tupleSlot: slot holding tuple actually inserted/updated/deleted
2250  * planSlot: slot holding tuple returned by top plan node
2251  * dest: where to send the output
2252  */
2253 static void
2254 ExecProcessReturning(ProjectionInfo *projectReturning,
2255                                          TupleTableSlot *tupleSlot,
2256                                          TupleTableSlot *planSlot,
2257                                          DestReceiver *dest)
2258 {
2259         ExprContext *econtext = projectReturning->pi_exprContext;
2260         TupleTableSlot *retSlot;
2261
2262         /*
2263          * Reset per-tuple memory context to free any expression evaluation
2264          * storage allocated in the previous cycle.
2265          */
2266         ResetExprContext(econtext);
2267
2268         /* Make tuple and any needed join variables available to ExecProject */
2269         econtext->ecxt_scantuple = tupleSlot;
2270         econtext->ecxt_outertuple = planSlot;
2271
2272         /* Compute the RETURNING expressions */
2273         retSlot = ExecProject(projectReturning, NULL);
2274
2275         /* Send to dest */
2276         (*dest->receiveSlot) (retSlot, dest);
2277
2278         ExecClearTuple(retSlot);
2279 }
2280
2281 /*
2282  * Check a modified tuple to see if we want to process its updated version
2283  * under READ COMMITTED rules.
2284  *
2285  * See backend/executor/README for some info about how this works.
2286  *
2287  *      estate - executor state data
2288  *      rti - rangetable index of table containing tuple
2289  *      *tid - t_ctid from the outdated tuple (ie, next updated version)
2290  *      priorXmax - t_xmax from the outdated tuple
2291  *
2292  * *tid is also an output parameter: it's modified to hold the TID of the
2293  * latest version of the tuple (note this may be changed even on failure)
2294  *
2295  * Returns a slot containing the new candidate update/delete tuple, or
2296  * NULL if we determine we shouldn't process the row.
2297  */
2298 TupleTableSlot *
2299 EvalPlanQual(EState *estate, Index rti,
2300                          ItemPointer tid, TransactionId priorXmax)
2301 {
2302         evalPlanQual *epq;
2303         EState     *epqstate;
2304         Relation        relation;
2305         HeapTupleData tuple;
2306         HeapTuple       copyTuple = NULL;
2307         SnapshotData SnapshotDirty;
2308         bool            endNode;
2309
2310         Assert(rti != 0);
2311
2312         /*
2313          * find relation containing target tuple
2314          */
2315         if (estate->es_result_relation_info != NULL &&
2316                 estate->es_result_relation_info->ri_RangeTableIndex == rti)
2317                 relation = estate->es_result_relation_info->ri_RelationDesc;
2318         else
2319         {
2320                 ListCell   *l;
2321
2322                 relation = NULL;
2323                 foreach(l, estate->es_rowMarks)
2324                 {
2325                         ExecRowMark *erm = lfirst(l);
2326
2327                         if (erm->rti == rti)
2328                         {
2329                                 relation = erm->relation;
2330                                 break;
2331                         }
2332                 }
2333                 if (relation == NULL)
2334                         elog(ERROR, "could not find RowMark for RT index %u", rti);
2335         }
2336
2337         /*
2338          * fetch tid tuple
2339          *
2340          * Loop here to deal with updated or busy tuples
2341          */
2342         InitDirtySnapshot(SnapshotDirty);
2343         tuple.t_self = *tid;
2344         for (;;)
2345         {
2346                 Buffer          buffer;
2347
2348                 if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
2349                 {
2350                         /*
2351                          * If xmin isn't what we're expecting, the slot must have been
2352                          * recycled and reused for an unrelated tuple.  This implies that
2353                          * the latest version of the row was deleted, so we need do
2354                          * nothing.  (Should be safe to examine xmin without getting
2355                          * buffer's content lock, since xmin never changes in an existing
2356                          * tuple.)
2357                          */
2358                         if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2359                                                                          priorXmax))
2360                         {
2361                                 ReleaseBuffer(buffer);
2362                                 return NULL;
2363                         }
2364
2365                         /* otherwise xmin should not be dirty... */
2366                         if (TransactionIdIsValid(SnapshotDirty.xmin))
2367                                 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
2368
2369                         /*
2370                          * If tuple is being updated by other transaction then we have to
2371                          * wait for its commit/abort.
2372                          */
2373                         if (TransactionIdIsValid(SnapshotDirty.xmax))
2374                         {
2375                                 ReleaseBuffer(buffer);
2376                                 XactLockTableWait(SnapshotDirty.xmax);
2377                                 continue;               /* loop back to repeat heap_fetch */
2378                         }
2379
2380                         /*
2381                          * If tuple was inserted by our own transaction, we have to check
2382                          * cmin against es_output_cid: cmin >= current CID means our
2383                          * command cannot see the tuple, so we should ignore it.  Without
2384                          * this we are open to the "Halloween problem" of indefinitely
2385                          * re-updating the same tuple. (We need not check cmax because
2386                          * HeapTupleSatisfiesDirty will consider a tuple deleted by our
2387                          * transaction dead, regardless of cmax.)  We just checked that
2388                          * priorXmax == xmin, so we can test that variable instead of
2389                          * doing HeapTupleHeaderGetXmin again.
2390                          */
2391                         if (TransactionIdIsCurrentTransactionId(priorXmax) &&
2392                                 HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
2393                         {
2394                                 ReleaseBuffer(buffer);
2395                                 return NULL;
2396                         }
2397
2398                         /*
2399                          * We got tuple - now copy it for use by recheck query.
2400                          */
2401                         copyTuple = heap_copytuple(&tuple);
2402                         ReleaseBuffer(buffer);
2403                         break;
2404                 }
2405
2406                 /*
2407                  * If the referenced slot was actually empty, the latest version of
2408                  * the row must have been deleted, so we need do nothing.
2409                  */
2410                 if (tuple.t_data == NULL)
2411                 {
2412                         ReleaseBuffer(buffer);
2413                         return NULL;
2414                 }
2415
2416                 /*
2417                  * As above, if xmin isn't what we're expecting, do nothing.
2418                  */
2419                 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2420                                                                  priorXmax))
2421                 {
2422                         ReleaseBuffer(buffer);
2423                         return NULL;
2424                 }
2425
2426                 /*
2427                  * If we get here, the tuple was found but failed SnapshotDirty.
2428                  * Assuming the xmin is either a committed xact or our own xact (as it
2429                  * certainly should be if we're trying to modify the tuple), this must
2430                  * mean that the row was updated or deleted by either a committed xact
2431                  * or our own xact.  If it was deleted, we can ignore it; if it was
2432                  * updated then chain up to the next version and repeat the whole
2433                  * test.
2434                  *
2435                  * As above, it should be safe to examine xmax and t_ctid without the
2436                  * buffer content lock, because they can't be changing.
2437                  */
2438                 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
2439                 {
2440                         /* deleted, so forget about it */
2441                         ReleaseBuffer(buffer);
2442                         return NULL;
2443                 }
2444
2445                 /* updated, so look at the updated row */
2446                 tuple.t_self = tuple.t_data->t_ctid;
2447                 /* updated row should have xmin matching this xmax */
2448                 priorXmax = HeapTupleHeaderGetXmax(tuple.t_data);
2449                 ReleaseBuffer(buffer);
2450                 /* loop back to fetch next in chain */
2451         }
2452
2453         /*
2454          * For UPDATE/DELETE we have to return tid of actual row we're executing
2455          * PQ for.
2456          */
2457         *tid = tuple.t_self;
2458
2459         /*
2460          * Need to run a recheck subquery.      Find or create a PQ stack entry.
2461          */
2462         epq = estate->es_evalPlanQual;
2463         endNode = true;
2464
2465         if (epq != NULL && epq->rti == 0)
2466         {
2467                 /* Top PQ stack entry is idle, so re-use it */
2468                 Assert(!(estate->es_useEvalPlan) && epq->next == NULL);
2469                 epq->rti = rti;
2470                 endNode = false;
2471         }
2472
2473         /*
2474          * If this is request for another RTE - Ra, - then we have to check wasn't
2475          * PlanQual requested for Ra already and if so then Ra' row was updated
2476          * again and we have to re-start old execution for Ra and forget all what
2477          * we done after Ra was suspended. Cool? -:))
2478          */
2479         if (epq != NULL && epq->rti != rti &&
2480                 epq->estate->es_evTuple[rti - 1] != NULL)
2481         {
2482                 do
2483                 {
2484                         evalPlanQual *oldepq;
2485
2486                         /* stop execution */
2487                         EvalPlanQualStop(epq);
2488                         /* pop previous PlanQual from the stack */
2489                         oldepq = epq->next;
2490                         Assert(oldepq && oldepq->rti != 0);
2491                         /* push current PQ to freePQ stack */
2492                         oldepq->free = epq;
2493                         epq = oldepq;
2494                         estate->es_evalPlanQual = epq;
2495                 } while (epq->rti != rti);
2496         }
2497
2498         /*
2499          * If we are requested for another RTE then we have to suspend execution
2500          * of current PlanQual and start execution for new one.
2501          */
2502         if (epq == NULL || epq->rti != rti)
2503         {
2504                 /* try to reuse plan used previously */
2505                 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
2506
2507                 if (newepq == NULL)             /* first call or freePQ stack is empty */
2508                 {
2509                         newepq = (evalPlanQual *) palloc0(sizeof(evalPlanQual));
2510                         newepq->free = NULL;
2511                         newepq->estate = NULL;
2512                         newepq->planstate = NULL;
2513                 }
2514                 else
2515                 {
2516                         /* recycle previously used PlanQual */
2517                         Assert(newepq->estate == NULL);
2518                         epq->free = NULL;
2519                 }
2520                 /* push current PQ to the stack */
2521                 newepq->next = epq;
2522                 epq = newepq;
2523                 estate->es_evalPlanQual = epq;
2524                 epq->rti = rti;
2525                 endNode = false;
2526         }
2527
2528         Assert(epq->rti == rti);
2529
2530         /*
2531          * Ok - we're requested for the same RTE.  Unfortunately we still have to
2532          * end and restart execution of the plan, because ExecReScan wouldn't
2533          * ensure that upper plan nodes would reset themselves.  We could make
2534          * that work if insertion of the target tuple were integrated with the
2535          * Param mechanism somehow, so that the upper plan nodes know that their
2536          * children's outputs have changed.
2537          *
2538          * Note that the stack of free evalPlanQual nodes is quite useless at the
2539          * moment, since it only saves us from pallocing/releasing the
2540          * evalPlanQual nodes themselves.  But it will be useful once we implement
2541          * ReScan instead of end/restart for re-using PlanQual nodes.
2542          */
2543         if (endNode)
2544         {
2545                 /* stop execution */
2546                 EvalPlanQualStop(epq);
2547         }
2548
2549         /*
2550          * Initialize new recheck query.
2551          *
2552          * Note: if we were re-using PlanQual plans via ExecReScan, we'd need to
2553          * instead copy down changeable state from the top plan (including
2554          * es_result_relation_info, es_junkFilter) and reset locally changeable
2555          * state in the epq (including es_param_exec_vals, es_evTupleNull).
2556          */
2557         EvalPlanQualStart(epq, estate, epq->next);
2558
2559         /*
2560          * free old RTE' tuple, if any, and store target tuple where relation's
2561          * scan node will see it
2562          */
2563         epqstate = epq->estate;
2564         if (epqstate->es_evTuple[rti - 1] != NULL)
2565                 heap_freetuple(epqstate->es_evTuple[rti - 1]);
2566         epqstate->es_evTuple[rti - 1] = copyTuple;
2567
2568         return EvalPlanQualNext(estate);
2569 }
2570
2571 static TupleTableSlot *
2572 EvalPlanQualNext(EState *estate)
2573 {
2574         evalPlanQual *epq = estate->es_evalPlanQual;
2575         MemoryContext oldcontext;
2576         TupleTableSlot *slot;
2577
2578         Assert(epq->rti != 0);
2579
2580 lpqnext:;
2581         oldcontext = MemoryContextSwitchTo(epq->estate->es_query_cxt);
2582         slot = ExecProcNode(epq->planstate);
2583         MemoryContextSwitchTo(oldcontext);
2584
2585         /*
2586          * No more tuples for this PQ. Continue previous one.
2587          */
2588         if (TupIsNull(slot))
2589         {
2590                 evalPlanQual *oldepq;
2591
2592                 /* stop execution */
2593                 EvalPlanQualStop(epq);
2594                 /* pop old PQ from the stack */
2595                 oldepq = epq->next;
2596                 if (oldepq == NULL)
2597                 {
2598                         /* this is the first (oldest) PQ - mark as free */
2599                         epq->rti = 0;
2600                         estate->es_useEvalPlan = false;
2601                         /* and continue Query execution */
2602                         return NULL;
2603                 }
2604                 Assert(oldepq->rti != 0);
2605                 /* push current PQ to freePQ stack */
2606                 oldepq->free = epq;
2607                 epq = oldepq;
2608                 estate->es_evalPlanQual = epq;
2609                 goto lpqnext;
2610         }
2611
2612         return slot;
2613 }
2614
2615 static void
2616 EndEvalPlanQual(EState *estate)
2617 {
2618         evalPlanQual *epq = estate->es_evalPlanQual;
2619
2620         if (epq->rti == 0)                      /* plans already shutdowned */
2621         {
2622                 Assert(epq->next == NULL);
2623                 return;
2624         }
2625
2626         for (;;)
2627         {
2628                 evalPlanQual *oldepq;
2629
2630                 /* stop execution */
2631                 EvalPlanQualStop(epq);
2632                 /* pop old PQ from the stack */
2633                 oldepq = epq->next;
2634                 if (oldepq == NULL)
2635                 {
2636                         /* this is the first (oldest) PQ - mark as free */
2637                         epq->rti = 0;
2638                         estate->es_useEvalPlan = false;
2639                         break;
2640                 }
2641                 Assert(oldepq->rti != 0);
2642                 /* push current PQ to freePQ stack */
2643                 oldepq->free = epq;
2644                 epq = oldepq;
2645                 estate->es_evalPlanQual = epq;
2646         }
2647 }
2648
2649 /*
2650  * Start execution of one level of PlanQual.
2651  *
2652  * This is a cut-down version of ExecutorStart(): we copy some state from
2653  * the top-level estate rather than initializing it fresh.
2654  */
2655 static void
2656 EvalPlanQualStart(evalPlanQual *epq, EState *estate, evalPlanQual *priorepq)
2657 {
2658         EState     *epqstate;
2659         int                     rtsize;
2660         MemoryContext oldcontext;
2661         ListCell   *l;
2662
2663         rtsize = list_length(estate->es_range_table);
2664
2665         epq->estate = epqstate = CreateExecutorState();
2666
2667         oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2668
2669         /*
2670          * The epqstates share the top query's copy of unchanging state such as
2671          * the snapshot, rangetable, result-rel info, and external Param info.
2672          * They need their own copies of local state, including a tuple table,
2673          * es_param_exec_vals, etc.
2674          */
2675         epqstate->es_direction = ForwardScanDirection;
2676         epqstate->es_snapshot = estate->es_snapshot;
2677         epqstate->es_crosscheck_snapshot = estate->es_crosscheck_snapshot;
2678         epqstate->es_range_table = estate->es_range_table;
2679         epqstate->es_output_cid = estate->es_output_cid;
2680         epqstate->es_result_relations = estate->es_result_relations;
2681         epqstate->es_num_result_relations = estate->es_num_result_relations;
2682         epqstate->es_result_relation_info = estate->es_result_relation_info;
2683         epqstate->es_junkFilter = estate->es_junkFilter;
2684         /* es_trig_target_relations must NOT be copied */
2685         epqstate->es_param_list_info = estate->es_param_list_info;
2686         if (estate->es_plannedstmt->nParamExec > 0)
2687                 epqstate->es_param_exec_vals = (ParamExecData *)
2688                         palloc0(estate->es_plannedstmt->nParamExec * sizeof(ParamExecData));
2689         epqstate->es_rowMarks = estate->es_rowMarks;
2690         epqstate->es_instrument = estate->es_instrument;
2691         epqstate->es_select_into = estate->es_select_into;
2692         epqstate->es_into_oids = estate->es_into_oids;
2693         epqstate->es_plannedstmt = estate->es_plannedstmt;
2694
2695         /*
2696          * Each epqstate must have its own es_evTupleNull state, but all the stack
2697          * entries share es_evTuple state.      This allows sub-rechecks to inherit
2698          * the value being examined by an outer recheck.
2699          */
2700         epqstate->es_evTupleNull = (bool *) palloc0(rtsize * sizeof(bool));
2701         if (priorepq == NULL)
2702                 /* first PQ stack entry */
2703                 epqstate->es_evTuple = (HeapTuple *)
2704                         palloc0(rtsize * sizeof(HeapTuple));
2705         else
2706                 /* later stack entries share the same storage */
2707                 epqstate->es_evTuple = priorepq->estate->es_evTuple;
2708
2709         /*
2710          * Create sub-tuple-table; we needn't redo the CountSlots work though.
2711          */
2712         epqstate->es_tupleTable =
2713                 ExecCreateTupleTable(estate->es_tupleTable->size);
2714
2715         /*
2716          * Initialize private state information for each SubPlan.  We must do this
2717          * before running ExecInitNode on the main query tree, since
2718          * ExecInitSubPlan expects to be able to find these entries.
2719          */
2720         Assert(epqstate->es_subplanstates == NIL);
2721         foreach(l, estate->es_plannedstmt->subplans)
2722         {
2723                 Plan       *subplan = (Plan *) lfirst(l);
2724                 PlanState  *subplanstate;
2725
2726                 subplanstate = ExecInitNode(subplan, epqstate, 0);
2727
2728                 epqstate->es_subplanstates = lappend(epqstate->es_subplanstates,
2729                                                                                          subplanstate);
2730         }
2731
2732         /*
2733          * Initialize the private state information for all the nodes in the query
2734          * tree.  This opens files, allocates storage and leaves us ready to start
2735          * processing tuples.
2736          */
2737         epq->planstate = ExecInitNode(estate->es_plannedstmt->planTree, epqstate, 0);
2738
2739         MemoryContextSwitchTo(oldcontext);
2740 }
2741
2742 /*
2743  * End execution of one level of PlanQual.
2744  *
2745  * This is a cut-down version of ExecutorEnd(); basically we want to do most
2746  * of the normal cleanup, but *not* close result relations (which we are
2747  * just sharing from the outer query).  We do, however, have to close any
2748  * trigger target relations that got opened, since those are not shared.
2749  */
2750 static void
2751 EvalPlanQualStop(evalPlanQual *epq)
2752 {
2753         EState     *epqstate = epq->estate;
2754         MemoryContext oldcontext;
2755         ListCell   *l;
2756
2757         oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2758
2759         ExecEndNode(epq->planstate);
2760
2761         foreach(l, epqstate->es_subplanstates)
2762         {
2763                 PlanState  *subplanstate = (PlanState *) lfirst(l);
2764
2765                 ExecEndNode(subplanstate);
2766         }
2767
2768         ExecDropTupleTable(epqstate->es_tupleTable, true);
2769         epqstate->es_tupleTable = NULL;
2770
2771         if (epqstate->es_evTuple[epq->rti - 1] != NULL)
2772         {
2773                 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
2774                 epqstate->es_evTuple[epq->rti - 1] = NULL;
2775         }
2776
2777         foreach(l, epqstate->es_trig_target_relations)
2778         {
2779                 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
2780
2781                 /* Close indices and then the relation itself */
2782                 ExecCloseIndices(resultRelInfo);
2783                 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
2784         }
2785
2786         MemoryContextSwitchTo(oldcontext);
2787
2788         FreeExecutorState(epqstate);
2789
2790         epq->estate = NULL;
2791         epq->planstate = NULL;
2792 }
2793
2794 /*
2795  * ExecGetActivePlanTree --- get the active PlanState tree from a QueryDesc
2796  *
2797  * Ordinarily this is just the one mentioned in the QueryDesc, but if we
2798  * are looking at a row returned by the EvalPlanQual machinery, we need
2799  * to look at the subsidiary state instead.
2800  */
2801 PlanState *
2802 ExecGetActivePlanTree(QueryDesc *queryDesc)
2803 {
2804         EState     *estate = queryDesc->estate;
2805
2806         if (estate && estate->es_useEvalPlan && estate->es_evalPlanQual != NULL)
2807                 return estate->es_evalPlanQual->planstate;
2808         else
2809                 return queryDesc->planstate;
2810 }
2811
2812
2813 /*
2814  * Support for SELECT INTO (a/k/a CREATE TABLE AS)
2815  *
2816  * We implement SELECT INTO by diverting SELECT's normal output with
2817  * a specialized DestReceiver type.
2818  */
2819
2820 typedef struct
2821 {
2822         DestReceiver pub;                       /* publicly-known function pointers */
2823         EState     *estate;                     /* EState we are working with */
2824         Relation        rel;                    /* Relation to write to */
2825         int                     hi_options;             /* heap_insert performance options */
2826         BulkInsertState bistate;        /* bulk insert state */
2827 } DR_intorel;
2828
2829 /*
2830  * OpenIntoRel --- actually create the SELECT INTO target relation
2831  *
2832  * This also replaces QueryDesc->dest with the special DestReceiver for
2833  * SELECT INTO.  We assume that the correct result tuple type has already
2834  * been placed in queryDesc->tupDesc.
2835  */
2836 static void
2837 OpenIntoRel(QueryDesc *queryDesc)
2838 {
2839         IntoClause *into = queryDesc->plannedstmt->intoClause;
2840         EState     *estate = queryDesc->estate;
2841         Relation        intoRelationDesc;
2842         char       *intoName;
2843         Oid                     namespaceId;
2844         Oid                     tablespaceId;
2845         Datum           reloptions;
2846         AclResult       aclresult;
2847         Oid                     intoRelationId;
2848         TupleDesc       tupdesc;
2849         DR_intorel *myState;
2850         static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
2851
2852         Assert(into);
2853
2854         /*
2855          * Check consistency of arguments
2856          */
2857         if (into->onCommit != ONCOMMIT_NOOP && !into->rel->istemp)
2858                 ereport(ERROR,
2859                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2860                                  errmsg("ON COMMIT can only be used on temporary tables")));
2861
2862         /*
2863          * Find namespace to create in, check its permissions
2864          */
2865         intoName = into->rel->relname;
2866         namespaceId = RangeVarGetCreationNamespace(into->rel);
2867
2868         aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
2869                                                                           ACL_CREATE);
2870         if (aclresult != ACLCHECK_OK)
2871                 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2872                                            get_namespace_name(namespaceId));
2873
2874         /*
2875          * Select tablespace to use.  If not specified, use default tablespace
2876          * (which may in turn default to database's default).
2877          */
2878         if (into->tableSpaceName)
2879         {
2880                 tablespaceId = get_tablespace_oid(into->tableSpaceName);
2881                 if (!OidIsValid(tablespaceId))
2882                         ereport(ERROR,
2883                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
2884                                          errmsg("tablespace \"%s\" does not exist",
2885                                                         into->tableSpaceName)));
2886         }
2887         else
2888         {
2889                 tablespaceId = GetDefaultTablespace(into->rel->istemp);
2890                 /* note InvalidOid is OK in this case */
2891         }
2892
2893         /* Check permissions except when using the database's default space */
2894         if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
2895         {
2896                 AclResult       aclresult;
2897
2898                 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
2899                                                                                    ACL_CREATE);
2900
2901                 if (aclresult != ACLCHECK_OK)
2902                         aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
2903                                                    get_tablespace_name(tablespaceId));
2904         }
2905
2906         /* Parse and validate any reloptions */
2907         reloptions = transformRelOptions((Datum) 0,
2908                                                                          into->options,
2909                                                                          NULL,
2910                                                                          validnsps,
2911                                                                          true,
2912                                                                          false);
2913         (void) heap_reloptions(RELKIND_RELATION, reloptions, true);
2914
2915         /* Copy the tupdesc because heap_create_with_catalog modifies it */
2916         tupdesc = CreateTupleDescCopy(queryDesc->tupDesc);
2917
2918         /* Now we can actually create the new relation */
2919         intoRelationId = heap_create_with_catalog(intoName,
2920                                                                                           namespaceId,
2921                                                                                           tablespaceId,
2922                                                                                           InvalidOid,
2923                                                                                           GetUserId(),
2924                                                                                           tupdesc,
2925                                                                                           NIL,
2926                                                                                           RELKIND_RELATION,
2927                                                                                           false,
2928                                                                                           true,
2929                                                                                           0,
2930                                                                                           into->onCommit,
2931                                                                                           reloptions,
2932                                                                                           allowSystemTableMods);
2933
2934         FreeTupleDesc(tupdesc);
2935
2936         /*
2937          * Advance command counter so that the newly-created relation's catalog
2938          * tuples will be visible to heap_open.
2939          */
2940         CommandCounterIncrement();
2941
2942         /*
2943          * If necessary, create a TOAST table for the INTO relation. Note that
2944          * AlterTableCreateToastTable ends with CommandCounterIncrement(), so that
2945          * the TOAST table will be visible for insertion.
2946          */
2947         reloptions = transformRelOptions((Datum) 0,
2948                                                                          into->options,
2949                                                                          "toast",
2950                                                                          validnsps,
2951                                                                          true,
2952                                                                          false);
2953
2954         (void) heap_reloptions(RELKIND_TOASTVALUE, reloptions, true);
2955
2956         AlterTableCreateToastTable(intoRelationId, InvalidOid, reloptions, false);
2957
2958         /*
2959          * And open the constructed table for writing.
2960          */
2961         intoRelationDesc = heap_open(intoRelationId, AccessExclusiveLock);
2962
2963         /*
2964          * Now replace the query's DestReceiver with one for SELECT INTO
2965          */
2966         queryDesc->dest = CreateDestReceiver(DestIntoRel);
2967         myState = (DR_intorel *) queryDesc->dest;
2968         Assert(myState->pub.mydest == DestIntoRel);
2969         myState->estate = estate;
2970         myState->rel = intoRelationDesc;
2971
2972         /*
2973          * We can skip WAL-logging the insertions, unless PITR is in use.  We can
2974          * skip the FSM in any case.
2975          */
2976         myState->hi_options = HEAP_INSERT_SKIP_FSM |
2977                 (XLogArchivingActive() ? 0 : HEAP_INSERT_SKIP_WAL);
2978         myState->bistate = GetBulkInsertState();
2979
2980         /* Not using WAL requires rd_targblock be initially invalid */
2981         Assert(intoRelationDesc->rd_targblock == InvalidBlockNumber);
2982 }
2983
2984 /*
2985  * CloseIntoRel --- clean up SELECT INTO at ExecutorEnd time
2986  */
2987 static void
2988 CloseIntoRel(QueryDesc *queryDesc)
2989 {
2990         DR_intorel *myState = (DR_intorel *) queryDesc->dest;
2991
2992         /* OpenIntoRel might never have gotten called */
2993         if (myState && myState->pub.mydest == DestIntoRel && myState->rel)
2994         {
2995                 FreeBulkInsertState(myState->bistate);
2996
2997                 /* If we skipped using WAL, must heap_sync before commit */
2998                 if (myState->hi_options & HEAP_INSERT_SKIP_WAL)
2999                         heap_sync(myState->rel);
3000
3001                 /* close rel, but keep lock until commit */
3002                 heap_close(myState->rel, NoLock);
3003
3004                 myState->rel = NULL;
3005         }
3006 }
3007
3008 /*
3009  * CreateIntoRelDestReceiver -- create a suitable DestReceiver object
3010  */
3011 DestReceiver *
3012 CreateIntoRelDestReceiver(void)
3013 {
3014         DR_intorel *self = (DR_intorel *) palloc0(sizeof(DR_intorel));
3015
3016         self->pub.receiveSlot = intorel_receive;
3017         self->pub.rStartup = intorel_startup;
3018         self->pub.rShutdown = intorel_shutdown;
3019         self->pub.rDestroy = intorel_destroy;
3020         self->pub.mydest = DestIntoRel;
3021
3022         /* private fields will be set by OpenIntoRel */
3023
3024         return (DestReceiver *) self;
3025 }
3026
3027 /*
3028  * intorel_startup --- executor startup
3029  */
3030 static void
3031 intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
3032 {
3033         /* no-op */
3034 }
3035
3036 /*
3037  * intorel_receive --- receive one tuple
3038  */
3039 static void
3040 intorel_receive(TupleTableSlot *slot, DestReceiver *self)
3041 {
3042         DR_intorel *myState = (DR_intorel *) self;
3043         HeapTuple       tuple;
3044
3045         /*
3046          * get the heap tuple out of the tuple table slot, making sure we have a
3047          * writable copy
3048          */
3049         tuple = ExecMaterializeSlot(slot);
3050
3051         /*
3052          * force assignment of new OID (see comments in ExecInsert)
3053          */
3054         if (myState->rel->rd_rel->relhasoids)
3055                 HeapTupleSetOid(tuple, InvalidOid);
3056
3057         heap_insert(myState->rel,
3058                                 tuple,
3059                                 myState->estate->es_output_cid,
3060                                 myState->hi_options,
3061                                 myState->bistate);
3062
3063         /* We know this is a newly created relation, so there are no indexes */
3064
3065         IncrAppended();
3066 }
3067
3068 /*
3069  * intorel_shutdown --- executor end
3070  */
3071 static void
3072 intorel_shutdown(DestReceiver *self)
3073 {
3074         /* no-op */
3075 }
3076
3077 /*
3078  * intorel_destroy --- release DestReceiver object
3079  */
3080 static void
3081 intorel_destroy(DestReceiver *self)
3082 {
3083         pfree(self);
3084 }