1 /*-------------------------------------------------------------------------
4 * Routines to support direct tid scans of relations
6 * Portions Copyright (c) 1996-2006, 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.50 2006/07/14 14:52:19 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
64 * quals are simple OpExprs. If there's any ScalarArrayOpExprs,
65 * we may have to enlarge the array.
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
158 * across the list. Sorting makes it easier to detect duplicates,
159 * and as a bonus ensures that we will visit the heap in the most
167 qsort((void *) tidList, numTids, sizeof(ItemPointerData),
170 for (i = 1; i < numTids; i++)
172 if (!ItemPointerEquals(&tidList[lastTid], &tidList[i]))
173 tidList[++lastTid] = tidList[i];
175 numTids = lastTid + 1;
178 tidstate->tss_TidList = tidList;
179 tidstate->tss_NumTids = numTids;
180 tidstate->tss_TidPtr = -1;
184 * qsort comparator for ItemPointerData items
187 itemptr_comparator(const void *a, const void *b)
189 const ItemPointerData *ipa = (const ItemPointerData *) a;
190 const ItemPointerData *ipb = (const ItemPointerData *) b;
191 BlockNumber ba = ItemPointerGetBlockNumber(ipa);
192 BlockNumber bb = ItemPointerGetBlockNumber(ipb);
193 OffsetNumber oa = ItemPointerGetOffsetNumber(ipa);
194 OffsetNumber ob = ItemPointerGetOffsetNumber(ipb);
207 /* ----------------------------------------------------------------
210 * Retrieve a tuple from the TidScan node's currentRelation
211 * using the tids in the TidScanState information.
213 * ----------------------------------------------------------------
215 static TupleTableSlot *
216 TidNext(TidScanState *node)
219 ScanDirection direction;
221 Relation heapRelation;
223 TupleTableSlot *slot;
225 Buffer buffer = InvalidBuffer;
226 ItemPointerData *tidList;
231 * extract necessary information from tid scan node
233 estate = node->ss.ps.state;
234 direction = estate->es_direction;
235 snapshot = estate->es_snapshot;
236 heapRelation = node->ss.ss_currentRelation;
237 slot = node->ss.ss_ScanTupleSlot;
238 scanrelid = ((TidScan *) node->ss.ps.plan)->scan.scanrelid;
241 * Check if we are evaluating PlanQual for tuple of this relation.
242 * Additional checking is not good, but no other way for now. We could
243 * introduce new nodes for this case and handle TidScan --> NewNode
244 * switching in Init/ReScan plan...
246 if (estate->es_evTuple != NULL &&
247 estate->es_evTuple[scanrelid - 1] != NULL)
249 if (estate->es_evTupleNull[scanrelid - 1])
250 return ExecClearTuple(slot);
253 * XXX shouldn't we check here to make sure tuple matches TID list? In
254 * runtime-key case this is not certain, is it?
257 ExecStoreTuple(estate->es_evTuple[scanrelid - 1],
258 slot, InvalidBuffer, false);
260 /* Flag for the next call that no more tuples */
261 estate->es_evTupleNull[scanrelid - 1] = true;
266 * First time through, compute the list of TIDs to be visited
268 if (node->tss_TidList == NULL)
271 tidList = node->tss_TidList;
272 numTids = node->tss_NumTids;
274 tuple = &(node->tss_htup);
277 * Initialize or advance scan position, depending on direction.
279 bBackward = ScanDirectionIsBackward(direction);
282 if (node->tss_TidPtr < 0)
284 /* initialize for backward scan */
285 node->tss_TidPtr = numTids - 1;
292 if (node->tss_TidPtr < 0)
294 /* initialize for forward scan */
295 node->tss_TidPtr = 0;
301 while (node->tss_TidPtr >= 0 && node->tss_TidPtr < numTids)
303 tuple->t_self = tidList[node->tss_TidPtr];
304 if (heap_fetch(heapRelation, snapshot, tuple, &buffer, false, NULL))
307 * store the scanned tuple in the scan tuple slot of the scan
308 * state. Eventually we will only do this and not return a tuple.
309 * Note: we pass 'false' because tuples returned by amgetnext are
310 * pointers onto disk pages and were not created with palloc() and
311 * so should not be pfree()'d.
313 ExecStoreTuple(tuple, /* tuple to store */
314 slot, /* slot to store in */
315 buffer, /* buffer associated with tuple */
316 false); /* don't pfree */
319 * At this point we have an extra pin on the buffer, because
320 * ExecStoreTuple incremented the pin count. Drop our local pin.
322 ReleaseBuffer(buffer);
326 /* Bad TID or failed snapshot qual; try next */
334 * if we get here it means the tid scan failed so we are at the end of the
337 return ExecClearTuple(slot);
340 /* ----------------------------------------------------------------
343 * Scans the relation using tids and returns
344 * the next qualifying tuple in the direction specified.
345 * It calls ExecScan() and passes it the access methods which returns
346 * the next tuple using the tids.
349 * -- the "cursor" maintained by the AMI is positioned at the tuple
350 * returned previously.
353 * -- the relation indicated is opened for scanning so that the
354 * "cursor" is positioned before the first qualifying tuple.
356 * ----------------------------------------------------------------
359 ExecTidScan(TidScanState *node)
362 * use TidNext as access method
364 return ExecScan(&node->ss, (ExecScanAccessMtd) TidNext);
367 /* ----------------------------------------------------------------
368 * ExecTidReScan(node)
369 * ----------------------------------------------------------------
372 ExecTidReScan(TidScanState *node, ExprContext *exprCtxt)
377 estate = node->ss.ps.state;
378 scanrelid = ((TidScan *) node->ss.ps.plan)->scan.scanrelid;
380 /* If we are being passed an outer tuple, save it for runtime key calc */
381 if (exprCtxt != NULL)
382 node->ss.ps.ps_ExprContext->ecxt_outertuple =
383 exprCtxt->ecxt_outertuple;
385 /* If this is re-scanning of PlanQual ... */
386 if (estate->es_evTuple != NULL &&
387 estate->es_evTuple[scanrelid - 1] != NULL)
389 estate->es_evTupleNull[scanrelid - 1] = false;
393 if (node->tss_TidList)
394 pfree(node->tss_TidList);
395 node->tss_TidList = NULL;
396 node->tss_NumTids = 0;
397 node->tss_TidPtr = -1;
400 /* ----------------------------------------------------------------
403 * Releases any storage allocated through C routines.
405 * ----------------------------------------------------------------
408 ExecEndTidScan(TidScanState *node)
411 * Free the exprcontext
413 ExecFreeExprContext(&node->ss.ps);
416 * clear out tuple table slots
418 ExecClearTuple(node->ss.ps.ps_ResultTupleSlot);
419 ExecClearTuple(node->ss.ss_ScanTupleSlot);
422 * close the heap relation.
424 ExecCloseScanRelation(node->ss.ss_currentRelation);
427 /* ----------------------------------------------------------------
430 * Marks scan position by marking the current tid.
432 * ----------------------------------------------------------------
435 ExecTidMarkPos(TidScanState *node)
437 node->tss_MarkTidPtr = node->tss_TidPtr;
440 /* ----------------------------------------------------------------
443 * Restores scan position by restoring the current tid.
446 * XXX Assumes previously marked scan position belongs to current tid
447 * ----------------------------------------------------------------
450 ExecTidRestrPos(TidScanState *node)
452 node->tss_TidPtr = node->tss_MarkTidPtr;
455 /* ----------------------------------------------------------------
458 * Initializes the tid scan's state information, creates
459 * scan keys, and opens the base and tid relations.
462 * node: TidNode node produced by the planner.
463 * estate: the execution state initialized in InitPlan.
464 * ----------------------------------------------------------------
467 ExecInitTidScan(TidScan *node, EState *estate, int eflags)
469 TidScanState *tidstate;
470 Relation currentRelation;
473 * create state structure
475 tidstate = makeNode(TidScanState);
476 tidstate->ss.ps.plan = (Plan *) node;
477 tidstate->ss.ps.state = estate;
480 * Miscellaneous initialization
482 * create expression context for node
484 ExecAssignExprContext(estate, &tidstate->ss.ps);
487 * initialize child expressions
489 tidstate->ss.ps.targetlist = (List *)
490 ExecInitExpr((Expr *) node->scan.plan.targetlist,
491 (PlanState *) tidstate);
492 tidstate->ss.ps.qual = (List *)
493 ExecInitExpr((Expr *) node->scan.plan.qual,
494 (PlanState *) tidstate);
496 tidstate->tss_tidquals = (List *)
497 ExecInitExpr((Expr *) node->tidquals,
498 (PlanState *) tidstate);
500 #define TIDSCAN_NSLOTS 2
503 * tuple table initialization
505 ExecInitResultTupleSlot(estate, &tidstate->ss.ps);
506 ExecInitScanTupleSlot(estate, &tidstate->ss);
509 * mark tid list as not computed yet
511 tidstate->tss_TidList = NULL;
512 tidstate->tss_NumTids = 0;
513 tidstate->tss_TidPtr = -1;
516 * open the base relation and acquire appropriate lock on it.
518 currentRelation = ExecOpenScanRelation(estate, node->scan.scanrelid);
520 tidstate->ss.ss_currentRelation = currentRelation;
521 tidstate->ss.ss_currentScanDesc = NULL; /* no heap scan here */
524 * get the scan type from the relation descriptor.
526 ExecAssignScanType(&tidstate->ss, RelationGetDescr(currentRelation));
529 * Initialize result tuple type and projection info.
531 ExecAssignResultTypeFromTL(&tidstate->ss.ps);
532 ExecAssignScanProjectionInfo(&tidstate->ss);
541 ExecCountSlotsTidScan(TidScan *node)
543 return ExecCountSlotsNode(outerPlan((Plan *) node)) +
544 ExecCountSlotsNode(innerPlan((Plan *) node)) + TIDSCAN_NSLOTS;