1 /*-------------------------------------------------------------------------
4 * Routines to support direct tid scans of relations
6 * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/executor/nodeTidscan.c,v 1.53 2007/01/05 22:19:28 momjian Exp $
13 *-------------------------------------------------------------------------
18 * ExecTidScan scans a relation using tids
19 * ExecInitTidScan creates and initializes state info.
20 * ExecTidReScan rescans the tid relation.
21 * ExecEndTidScan releases all storage.
22 * ExecTidMarkPos marks scan position.
23 * ExecTidRestrPos restores scan position.
27 #include "access/heapam.h"
28 #include "catalog/pg_type.h"
29 #include "executor/execdebug.h"
30 #include "executor/nodeTidscan.h"
31 #include "optimizer/clauses.h"
32 #include "utils/array.h"
35 #define IsCTIDVar(node) \
38 ((Var *) (node))->varattno == SelfItemPointerAttributeNumber && \
39 ((Var *) (node))->varlevelsup == 0)
41 static void TidListCreate(TidScanState *tidstate);
42 static int itemptr_comparator(const void *a, const void *b);
43 static TupleTableSlot *TidNext(TidScanState *node);
47 * Compute the list of TIDs to be visited, by evaluating the expressions
50 * (The result is actually an array, not a list.)
53 TidListCreate(TidScanState *tidstate)
55 List *evalList = tidstate->tss_tidquals;
56 ExprContext *econtext = tidstate->ss.ps.ps_ExprContext;
57 ItemPointerData *tidList;
63 * We initialize the array with enough slots for the case that all quals
64 * are simple OpExprs. If there's any ScalarArrayOpExprs, we may have to
67 numAllocTids = list_length(evalList);
68 tidList = (ItemPointerData *)
69 palloc(numAllocTids * sizeof(ItemPointerData));
74 ExprState *exstate = (ExprState *) lfirst(l);
75 Expr *expr = exstate->expr;
79 if (is_opclause(expr))
81 FuncExprState *fexstate = (FuncExprState *) exstate;
85 arg1 = get_leftop(expr);
86 arg2 = get_rightop(expr);
88 exstate = (ExprState *) lsecond(fexstate->args);
89 else if (IsCTIDVar(arg2))
90 exstate = (ExprState *) linitial(fexstate->args);
92 elog(ERROR, "could not identify CTID variable");
94 itemptr = (ItemPointer)
95 DatumGetPointer(ExecEvalExprSwitchContext(exstate,
99 if (!isNull && ItemPointerIsValid(itemptr))
101 if (numTids >= numAllocTids)
104 tidList = (ItemPointerData *)
106 numAllocTids * sizeof(ItemPointerData));
108 tidList[numTids++] = *itemptr;
111 else if (expr && IsA(expr, ScalarArrayOpExpr))
113 ScalarArrayOpExprState *saexstate = (ScalarArrayOpExprState *) exstate;
115 ArrayType *itemarray;
121 exstate = (ExprState *) lsecond(saexstate->fxprstate.args);
122 arraydatum = ExecEvalExprSwitchContext(exstate,
128 itemarray = DatumGetArrayTypeP(arraydatum);
129 deconstruct_array(itemarray,
130 TIDOID, SizeOfIptrData, false, 's',
131 &ipdatums, &ipnulls, &ndatums);
132 if (numTids + ndatums > numAllocTids)
134 numAllocTids = numTids + ndatums;
135 tidList = (ItemPointerData *)
137 numAllocTids * sizeof(ItemPointerData));
139 for (i = 0; i < ndatums; i++)
143 itemptr = (ItemPointer) DatumGetPointer(ipdatums[i]);
144 if (ItemPointerIsValid(itemptr))
145 tidList[numTids++] = *itemptr;
152 elog(ERROR, "could not identify CTID expression");
156 * Sort the array of TIDs into order, and eliminate duplicates.
157 * Eliminating duplicates is necessary since we want OR semantics across
158 * the list. Sorting makes it easier to detect duplicates, and as a bonus
159 * ensures that we will visit the heap in the most efficient way.
166 qsort((void *) tidList, numTids, sizeof(ItemPointerData),
169 for (i = 1; i < numTids; i++)
171 if (!ItemPointerEquals(&tidList[lastTid], &tidList[i]))
172 tidList[++lastTid] = tidList[i];
174 numTids = lastTid + 1;
177 tidstate->tss_TidList = tidList;
178 tidstate->tss_NumTids = numTids;
179 tidstate->tss_TidPtr = -1;
183 * qsort comparator for ItemPointerData items
186 itemptr_comparator(const void *a, const void *b)
188 const ItemPointerData *ipa = (const ItemPointerData *) a;
189 const ItemPointerData *ipb = (const ItemPointerData *) b;
190 BlockNumber ba = ItemPointerGetBlockNumber(ipa);
191 BlockNumber bb = ItemPointerGetBlockNumber(ipb);
192 OffsetNumber oa = ItemPointerGetOffsetNumber(ipa);
193 OffsetNumber ob = ItemPointerGetOffsetNumber(ipb);
206 /* ----------------------------------------------------------------
209 * Retrieve a tuple from the TidScan node's currentRelation
210 * using the tids in the TidScanState information.
212 * ----------------------------------------------------------------
214 static TupleTableSlot *
215 TidNext(TidScanState *node)
218 ScanDirection direction;
220 Relation heapRelation;
222 TupleTableSlot *slot;
224 Buffer buffer = InvalidBuffer;
225 ItemPointerData *tidList;
230 * extract necessary information from tid scan node
232 estate = node->ss.ps.state;
233 direction = estate->es_direction;
234 snapshot = estate->es_snapshot;
235 heapRelation = node->ss.ss_currentRelation;
236 slot = node->ss.ss_ScanTupleSlot;
237 scanrelid = ((TidScan *) node->ss.ps.plan)->scan.scanrelid;
240 * Check if we are evaluating PlanQual for tuple of this relation.
241 * Additional checking is not good, but no other way for now. We could
242 * introduce new nodes for this case and handle TidScan --> NewNode
243 * switching in Init/ReScan plan...
245 if (estate->es_evTuple != NULL &&
246 estate->es_evTuple[scanrelid - 1] != NULL)
248 if (estate->es_evTupleNull[scanrelid - 1])
249 return ExecClearTuple(slot);
252 * XXX shouldn't we check here to make sure tuple matches TID list? In
253 * runtime-key case this is not certain, is it?
256 ExecStoreTuple(estate->es_evTuple[scanrelid - 1],
257 slot, InvalidBuffer, false);
259 /* Flag for the next call that no more tuples */
260 estate->es_evTupleNull[scanrelid - 1] = true;
265 * First time through, compute the list of TIDs to be visited
267 if (node->tss_TidList == NULL)
270 tidList = node->tss_TidList;
271 numTids = node->tss_NumTids;
273 tuple = &(node->tss_htup);
276 * Initialize or advance scan position, depending on direction.
278 bBackward = ScanDirectionIsBackward(direction);
281 if (node->tss_TidPtr < 0)
283 /* initialize for backward scan */
284 node->tss_TidPtr = numTids - 1;
291 if (node->tss_TidPtr < 0)
293 /* initialize for forward scan */
294 node->tss_TidPtr = 0;
300 while (node->tss_TidPtr >= 0 && node->tss_TidPtr < numTids)
302 tuple->t_self = tidList[node->tss_TidPtr];
303 if (heap_fetch(heapRelation, snapshot, tuple, &buffer, false, NULL))
306 * store the scanned tuple in the scan tuple slot of the scan
307 * state. Eventually we will only do this and not return a tuple.
308 * Note: we pass 'false' because tuples returned by amgetnext are
309 * pointers onto disk pages and were not created with palloc() and
310 * so should not be pfree()'d.
312 ExecStoreTuple(tuple, /* tuple to store */
313 slot, /* slot to store in */
314 buffer, /* buffer associated with tuple */
315 false); /* don't pfree */
318 * At this point we have an extra pin on the buffer, because
319 * ExecStoreTuple incremented the pin count. Drop our local pin.
321 ReleaseBuffer(buffer);
325 /* Bad TID or failed snapshot qual; try next */
333 * if we get here it means the tid scan failed so we are at the end of the
336 return ExecClearTuple(slot);
339 /* ----------------------------------------------------------------
342 * Scans the relation using tids and returns
343 * the next qualifying tuple in the direction specified.
344 * It calls ExecScan() and passes it the access methods which returns
345 * the next tuple using the tids.
348 * -- the "cursor" maintained by the AMI is positioned at the tuple
349 * returned previously.
352 * -- the relation indicated is opened for scanning so that the
353 * "cursor" is positioned before the first qualifying tuple.
355 * ----------------------------------------------------------------
358 ExecTidScan(TidScanState *node)
361 * use TidNext as access method
363 return ExecScan(&node->ss, (ExecScanAccessMtd) TidNext);
366 /* ----------------------------------------------------------------
367 * ExecTidReScan(node)
368 * ----------------------------------------------------------------
371 ExecTidReScan(TidScanState *node, ExprContext *exprCtxt)
376 estate = node->ss.ps.state;
377 scanrelid = ((TidScan *) node->ss.ps.plan)->scan.scanrelid;
379 node->ss.ps.ps_TupFromTlist = false;
381 /* If we are being passed an outer tuple, save it for runtime key calc */
382 if (exprCtxt != NULL)
383 node->ss.ps.ps_ExprContext->ecxt_outertuple =
384 exprCtxt->ecxt_outertuple;
386 /* If this is re-scanning of PlanQual ... */
387 if (estate->es_evTuple != NULL &&
388 estate->es_evTuple[scanrelid - 1] != NULL)
390 estate->es_evTupleNull[scanrelid - 1] = false;
394 if (node->tss_TidList)
395 pfree(node->tss_TidList);
396 node->tss_TidList = NULL;
397 node->tss_NumTids = 0;
398 node->tss_TidPtr = -1;
401 /* ----------------------------------------------------------------
404 * Releases any storage allocated through C routines.
406 * ----------------------------------------------------------------
409 ExecEndTidScan(TidScanState *node)
412 * Free the exprcontext
414 ExecFreeExprContext(&node->ss.ps);
417 * clear out tuple table slots
419 ExecClearTuple(node->ss.ps.ps_ResultTupleSlot);
420 ExecClearTuple(node->ss.ss_ScanTupleSlot);
423 * close the heap relation.
425 ExecCloseScanRelation(node->ss.ss_currentRelation);
428 /* ----------------------------------------------------------------
431 * Marks scan position by marking the current tid.
433 * ----------------------------------------------------------------
436 ExecTidMarkPos(TidScanState *node)
438 node->tss_MarkTidPtr = node->tss_TidPtr;
441 /* ----------------------------------------------------------------
444 * Restores scan position by restoring the current tid.
447 * XXX Assumes previously marked scan position belongs to current tid
448 * ----------------------------------------------------------------
451 ExecTidRestrPos(TidScanState *node)
453 node->tss_TidPtr = node->tss_MarkTidPtr;
456 /* ----------------------------------------------------------------
459 * Initializes the tid scan's state information, creates
460 * scan keys, and opens the base and tid relations.
463 * node: TidNode node produced by the planner.
464 * estate: the execution state initialized in InitPlan.
465 * ----------------------------------------------------------------
468 ExecInitTidScan(TidScan *node, EState *estate, int eflags)
470 TidScanState *tidstate;
471 Relation currentRelation;
474 * create state structure
476 tidstate = makeNode(TidScanState);
477 tidstate->ss.ps.plan = (Plan *) node;
478 tidstate->ss.ps.state = estate;
481 * Miscellaneous initialization
483 * create expression context for node
485 ExecAssignExprContext(estate, &tidstate->ss.ps);
487 tidstate->ss.ps.ps_TupFromTlist = false;
490 * initialize child expressions
492 tidstate->ss.ps.targetlist = (List *)
493 ExecInitExpr((Expr *) node->scan.plan.targetlist,
494 (PlanState *) tidstate);
495 tidstate->ss.ps.qual = (List *)
496 ExecInitExpr((Expr *) node->scan.plan.qual,
497 (PlanState *) tidstate);
499 tidstate->tss_tidquals = (List *)
500 ExecInitExpr((Expr *) node->tidquals,
501 (PlanState *) tidstate);
503 #define TIDSCAN_NSLOTS 2
506 * tuple table initialization
508 ExecInitResultTupleSlot(estate, &tidstate->ss.ps);
509 ExecInitScanTupleSlot(estate, &tidstate->ss);
512 * mark tid list as not computed yet
514 tidstate->tss_TidList = NULL;
515 tidstate->tss_NumTids = 0;
516 tidstate->tss_TidPtr = -1;
519 * open the base relation and acquire appropriate lock on it.
521 currentRelation = ExecOpenScanRelation(estate, node->scan.scanrelid);
523 tidstate->ss.ss_currentRelation = currentRelation;
524 tidstate->ss.ss_currentScanDesc = NULL; /* no heap scan here */
527 * get the scan type from the relation descriptor.
529 ExecAssignScanType(&tidstate->ss, RelationGetDescr(currentRelation));
532 * Initialize result tuple type and projection info.
534 ExecAssignResultTypeFromTL(&tidstate->ss.ps);
535 ExecAssignScanProjectionInfo(&tidstate->ss);
544 ExecCountSlotsTidScan(TidScan *node)
546 return ExecCountSlotsNode(outerPlan((Plan *) node)) +
547 ExecCountSlotsNode(innerPlan((Plan *) node)) + TIDSCAN_NSLOTS;