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.51 2006/10/04 00:29:53 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 /* If we are being passed an outer tuple, save it for runtime key calc */
380 if (exprCtxt != NULL)
381 node->ss.ps.ps_ExprContext->ecxt_outertuple =
382 exprCtxt->ecxt_outertuple;
384 /* If this is re-scanning of PlanQual ... */
385 if (estate->es_evTuple != NULL &&
386 estate->es_evTuple[scanrelid - 1] != NULL)
388 estate->es_evTupleNull[scanrelid - 1] = false;
392 if (node->tss_TidList)
393 pfree(node->tss_TidList);
394 node->tss_TidList = NULL;
395 node->tss_NumTids = 0;
396 node->tss_TidPtr = -1;
399 /* ----------------------------------------------------------------
402 * Releases any storage allocated through C routines.
404 * ----------------------------------------------------------------
407 ExecEndTidScan(TidScanState *node)
410 * Free the exprcontext
412 ExecFreeExprContext(&node->ss.ps);
415 * clear out tuple table slots
417 ExecClearTuple(node->ss.ps.ps_ResultTupleSlot);
418 ExecClearTuple(node->ss.ss_ScanTupleSlot);
421 * close the heap relation.
423 ExecCloseScanRelation(node->ss.ss_currentRelation);
426 /* ----------------------------------------------------------------
429 * Marks scan position by marking the current tid.
431 * ----------------------------------------------------------------
434 ExecTidMarkPos(TidScanState *node)
436 node->tss_MarkTidPtr = node->tss_TidPtr;
439 /* ----------------------------------------------------------------
442 * Restores scan position by restoring the current tid.
445 * XXX Assumes previously marked scan position belongs to current tid
446 * ----------------------------------------------------------------
449 ExecTidRestrPos(TidScanState *node)
451 node->tss_TidPtr = node->tss_MarkTidPtr;
454 /* ----------------------------------------------------------------
457 * Initializes the tid scan's state information, creates
458 * scan keys, and opens the base and tid relations.
461 * node: TidNode node produced by the planner.
462 * estate: the execution state initialized in InitPlan.
463 * ----------------------------------------------------------------
466 ExecInitTidScan(TidScan *node, EState *estate, int eflags)
468 TidScanState *tidstate;
469 Relation currentRelation;
472 * create state structure
474 tidstate = makeNode(TidScanState);
475 tidstate->ss.ps.plan = (Plan *) node;
476 tidstate->ss.ps.state = estate;
479 * Miscellaneous initialization
481 * create expression context for node
483 ExecAssignExprContext(estate, &tidstate->ss.ps);
486 * initialize child expressions
488 tidstate->ss.ps.targetlist = (List *)
489 ExecInitExpr((Expr *) node->scan.plan.targetlist,
490 (PlanState *) tidstate);
491 tidstate->ss.ps.qual = (List *)
492 ExecInitExpr((Expr *) node->scan.plan.qual,
493 (PlanState *) tidstate);
495 tidstate->tss_tidquals = (List *)
496 ExecInitExpr((Expr *) node->tidquals,
497 (PlanState *) tidstate);
499 #define TIDSCAN_NSLOTS 2
502 * tuple table initialization
504 ExecInitResultTupleSlot(estate, &tidstate->ss.ps);
505 ExecInitScanTupleSlot(estate, &tidstate->ss);
508 * mark tid list as not computed yet
510 tidstate->tss_TidList = NULL;
511 tidstate->tss_NumTids = 0;
512 tidstate->tss_TidPtr = -1;
515 * open the base relation and acquire appropriate lock on it.
517 currentRelation = ExecOpenScanRelation(estate, node->scan.scanrelid);
519 tidstate->ss.ss_currentRelation = currentRelation;
520 tidstate->ss.ss_currentScanDesc = NULL; /* no heap scan here */
523 * get the scan type from the relation descriptor.
525 ExecAssignScanType(&tidstate->ss, RelationGetDescr(currentRelation));
528 * Initialize result tuple type and projection info.
530 ExecAssignResultTypeFromTL(&tidstate->ss.ps);
531 ExecAssignScanProjectionInfo(&tidstate->ss);
540 ExecCountSlotsTidScan(TidScan *node)
542 return ExecCountSlotsNode(outerPlan((Plan *) node)) +
543 ExecCountSlotsNode(innerPlan((Plan *) node)) + TIDSCAN_NSLOTS;