]> granicus.if.org Git - postgresql/blob - src/backend/executor/execScan.c
Fix typo in C comment.
[postgresql] / src / backend / executor / execScan.c
1 /*-------------------------------------------------------------------------
2  *
3  * execScan.c
4  *        This code provides support for generalized relation scans. ExecScan
5  *        is passed a node and a pointer to a function to "do the right thing"
6  *        and return a tuple from the relation. ExecScan then does the tedious
7  *        stuff - checking the qualification and projecting the tuple
8  *        appropriately.
9  *
10  * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
11  * Portions Copyright (c) 1994, Regents of the University of California
12  *
13  *
14  * IDENTIFICATION
15  *        src/backend/executor/execScan.c
16  *
17  *-------------------------------------------------------------------------
18  */
19 #include "postgres.h"
20
21 #include "executor/executor.h"
22 #include "miscadmin.h"
23 #include "utils/memutils.h"
24
25
26 static bool tlist_matches_tupdesc(PlanState *ps, List *tlist, Index varno, TupleDesc tupdesc);
27
28
29 /*
30  * ExecScanFetch -- fetch next potential tuple
31  *
32  * This routine is concerned with substituting a test tuple if we are
33  * inside an EvalPlanQual recheck.  If we aren't, just execute
34  * the access method's next-tuple routine.
35  */
36 static inline TupleTableSlot *
37 ExecScanFetch(ScanState *node,
38                           ExecScanAccessMtd accessMtd,
39                           ExecScanRecheckMtd recheckMtd)
40 {
41         EState     *estate = node->ps.state;
42
43         if (estate->es_epqTuple != NULL)
44         {
45                 /*
46                  * We are inside an EvalPlanQual recheck.  Return the test tuple if
47                  * one is available, after rechecking any access-method-specific
48                  * conditions.
49                  */
50                 Index           scanrelid = ((Scan *) node->ps.plan)->scanrelid;
51
52                 Assert(scanrelid > 0);
53                 if (estate->es_epqTupleSet[scanrelid - 1])
54                 {
55                         TupleTableSlot *slot = node->ss_ScanTupleSlot;
56
57                         /* Return empty slot if we already returned a tuple */
58                         if (estate->es_epqScanDone[scanrelid - 1])
59                                 return ExecClearTuple(slot);
60                         /* Else mark to remember that we shouldn't return more */
61                         estate->es_epqScanDone[scanrelid - 1] = true;
62
63                         /* Return empty slot if we haven't got a test tuple */
64                         if (estate->es_epqTuple[scanrelid - 1] == NULL)
65                                 return ExecClearTuple(slot);
66
67                         /* Store test tuple in the plan node's scan slot */
68                         ExecStoreTuple(estate->es_epqTuple[scanrelid - 1],
69                                                    slot, InvalidBuffer, false);
70
71                         /* Check if it meets the access-method conditions */
72                         if (!(*recheckMtd) (node, slot))
73                                 ExecClearTuple(slot);   /* would not be returned by scan */
74
75                         return slot;
76                 }
77         }
78
79         /*
80          * Run the node-type-specific access method function to get the next tuple
81          */
82         return (*accessMtd) (node);
83 }
84
85 /* ----------------------------------------------------------------
86  *              ExecScan
87  *
88  *              Scans the relation using the 'access method' indicated and
89  *              returns the next qualifying tuple in the direction specified
90  *              in the global variable ExecDirection.
91  *              The access method returns the next tuple and ExecScan() is
92  *              responsible for checking the tuple returned against the qual-clause.
93  *
94  *              A 'recheck method' must also be provided that can check an
95  *              arbitrary tuple of the relation against any qual conditions
96  *              that are implemented internal to the access method.
97  *
98  *              Conditions:
99  *                -- the "cursor" maintained by the AMI is positioned at the tuple
100  *                       returned previously.
101  *
102  *              Initial States:
103  *                -- the relation indicated is opened for scanning so that the
104  *                       "cursor" is positioned before the first qualifying tuple.
105  * ----------------------------------------------------------------
106  */
107 TupleTableSlot *
108 ExecScan(ScanState *node,
109                  ExecScanAccessMtd accessMtd,   /* function returning a tuple */
110                  ExecScanRecheckMtd recheckMtd)
111 {
112         ExprContext *econtext;
113         List       *qual;
114         ProjectionInfo *projInfo;
115         ExprDoneCond isDone;
116         TupleTableSlot *resultSlot;
117
118         /*
119          * Fetch data from node
120          */
121         qual = node->ps.qual;
122         projInfo = node->ps.ps_ProjInfo;
123         econtext = node->ps.ps_ExprContext;
124
125         /*
126          * If we have neither a qual to check nor a projection to do, just skip
127          * all the overhead and return the raw scan tuple.
128          */
129         if (!qual && !projInfo)
130         {
131                 ResetExprContext(econtext);
132                 return ExecScanFetch(node, accessMtd, recheckMtd);
133         }
134
135         /*
136          * Check to see if we're still projecting out tuples from a previous scan
137          * tuple (because there is a function-returning-set in the projection
138          * expressions).  If so, try to project another one.
139          */
140         if (node->ps.ps_TupFromTlist)
141         {
142                 Assert(projInfo);               /* can't get here if not projecting */
143                 resultSlot = ExecProject(projInfo, &isDone);
144                 if (isDone == ExprMultipleResult)
145                         return resultSlot;
146                 /* Done with that source tuple... */
147                 node->ps.ps_TupFromTlist = false;
148         }
149
150         /*
151          * Reset per-tuple memory context to free any expression evaluation
152          * storage allocated in the previous tuple cycle.  Note this can't happen
153          * until we're done projecting out tuples from a scan tuple.
154          */
155         ResetExprContext(econtext);
156
157         /*
158          * get a tuple from the access method.  Loop until we obtain a tuple that
159          * passes the qualification.
160          */
161         for (;;)
162         {
163                 TupleTableSlot *slot;
164
165                 CHECK_FOR_INTERRUPTS();
166
167                 slot = ExecScanFetch(node, accessMtd, recheckMtd);
168
169                 /*
170                  * if the slot returned by the accessMtd contains NULL, then it means
171                  * there is nothing more to scan so we just return an empty slot,
172                  * being careful to use the projection result slot so it has correct
173                  * tupleDesc.
174                  */
175                 if (TupIsNull(slot))
176                 {
177                         if (projInfo)
178                                 return ExecClearTuple(projInfo->pi_slot);
179                         else
180                                 return slot;
181                 }
182
183                 /*
184                  * place the current tuple into the expr context
185                  */
186                 econtext->ecxt_scantuple = slot;
187
188                 /*
189                  * check that the current tuple satisfies the qual-clause
190                  *
191                  * check for non-nil qual here to avoid a function call to ExecQual()
192                  * when the qual is nil ... saves only a few cycles, but they add up
193                  * ...
194                  */
195                 if (!qual || ExecQual(qual, econtext, false))
196                 {
197                         /*
198                          * Found a satisfactory scan tuple.
199                          */
200                         if (projInfo)
201                         {
202                                 /*
203                                  * Form a projection tuple, store it in the result tuple slot
204                                  * and return it --- unless we find we can project no tuples
205                                  * from this scan tuple, in which case continue scan.
206                                  */
207                                 resultSlot = ExecProject(projInfo, &isDone);
208                                 if (isDone != ExprEndResult)
209                                 {
210                                         node->ps.ps_TupFromTlist = (isDone == ExprMultipleResult);
211                                         return resultSlot;
212                                 }
213                         }
214                         else
215                         {
216                                 /*
217                                  * Here, we aren't projecting, so just return scan tuple.
218                                  */
219                                 return slot;
220                         }
221                 }
222                 else
223                         InstrCountFiltered1(node, 1);
224
225                 /*
226                  * Tuple fails qual, so free per-tuple memory and try again.
227                  */
228                 ResetExprContext(econtext);
229         }
230 }
231
232 /*
233  * ExecAssignScanProjectionInfo
234  *              Set up projection info for a scan node, if necessary.
235  *
236  * We can avoid a projection step if the requested tlist exactly matches
237  * the underlying tuple type.  If so, we just set ps_ProjInfo to NULL.
238  * Note that this case occurs not only for simple "SELECT * FROM ...", but
239  * also in most cases where there are joins or other processing nodes above
240  * the scan node, because the planner will preferentially generate a matching
241  * tlist.
242  *
243  * ExecAssignScanType must have been called already.
244  */
245 void
246 ExecAssignScanProjectionInfo(ScanState *node)
247 {
248         Scan       *scan = (Scan *) node->ps.plan;
249         Index           varno;
250
251         /* Vars in an index-only scan's tlist should be INDEX_VAR */
252         if (IsA(scan, IndexOnlyScan))
253                 varno = INDEX_VAR;
254         else
255                 varno = scan->scanrelid;
256
257         if (tlist_matches_tupdesc(&node->ps,
258                                                           scan->plan.targetlist,
259                                                           varno,
260                                                           node->ss_ScanTupleSlot->tts_tupleDescriptor))
261                 node->ps.ps_ProjInfo = NULL;
262         else
263                 ExecAssignProjectionInfo(&node->ps,
264                                                                  node->ss_ScanTupleSlot->tts_tupleDescriptor);
265 }
266
267 static bool
268 tlist_matches_tupdesc(PlanState *ps, List *tlist, Index varno, TupleDesc tupdesc)
269 {
270         int                     numattrs = tupdesc->natts;
271         int                     attrno;
272         bool            hasoid;
273         ListCell   *tlist_item = list_head(tlist);
274
275         /* Check the tlist attributes */
276         for (attrno = 1; attrno <= numattrs; attrno++)
277         {
278                 Form_pg_attribute att_tup = tupdesc->attrs[attrno - 1];
279                 Var                *var;
280
281                 if (tlist_item == NULL)
282                         return false;           /* tlist too short */
283                 var = (Var *) ((TargetEntry *) lfirst(tlist_item))->expr;
284                 if (!var || !IsA(var, Var))
285                         return false;           /* tlist item not a Var */
286                 /* if these Asserts fail, planner messed up */
287                 Assert(var->varno == varno);
288                 Assert(var->varlevelsup == 0);
289                 if (var->varattno != attrno)
290                         return false;           /* out of order */
291                 if (att_tup->attisdropped)
292                         return false;           /* table contains dropped columns */
293
294                 /*
295                  * Note: usually the Var's type should match the tupdesc exactly, but
296                  * in situations involving unions of columns that have different
297                  * typmods, the Var may have come from above the union and hence have
298                  * typmod -1.  This is a legitimate situation since the Var still
299                  * describes the column, just not as exactly as the tupdesc does. We
300                  * could change the planner to prevent it, but it'd then insert
301                  * projection steps just to convert from specific typmod to typmod -1,
302                  * which is pretty silly.
303                  */
304                 if (var->vartype != att_tup->atttypid ||
305                         (var->vartypmod != att_tup->atttypmod &&
306                          var->vartypmod != -1))
307                         return false;           /* type mismatch */
308
309                 tlist_item = lnext(tlist_item);
310         }
311
312         if (tlist_item)
313                 return false;                   /* tlist too long */
314
315         /*
316          * If the plan context requires a particular hasoid setting, then that has
317          * to match, too.
318          */
319         if (ExecContextForcesOids(ps, &hasoid) &&
320                 hasoid != tupdesc->tdhasoid)
321                 return false;
322
323         return true;
324 }
325
326 /*
327  * ExecScanReScan
328  *
329  * This must be called within the ReScan function of any plan node type
330  * that uses ExecScan().
331  */
332 void
333 ExecScanReScan(ScanState *node)
334 {
335         EState     *estate = node->ps.state;
336
337         /* Stop projecting any tuples from SRFs in the targetlist */
338         node->ps.ps_TupFromTlist = false;
339
340         /* Rescan EvalPlanQual tuple if we're inside an EvalPlanQual recheck */
341         if (estate->es_epqScanDone != NULL)
342         {
343                 Index           scanrelid = ((Scan *) node->ps.plan)->scanrelid;
344
345                 Assert(scanrelid > 0);
346
347                 estate->es_epqScanDone[scanrelid - 1] = false;
348         }
349 }