1 /*-------------------------------------------------------------------------
4 * Routines to support direct tid scans of relations
6 * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/executor/nodeTidscan.c
13 *-------------------------------------------------------------------------
18 * ExecTidScan scans a relation using tids
19 * ExecInitTidScan creates and initializes state info.
20 * ExecReScanTidScan rescans the tid relation.
21 * ExecEndTidScan releases all storage.
25 #include "access/sysattr.h"
26 #include "catalog/pg_type.h"
27 #include "executor/execdebug.h"
28 #include "executor/nodeTidscan.h"
29 #include "optimizer/clauses.h"
30 #include "storage/bufmgr.h"
31 #include "utils/array.h"
32 #include "utils/rel.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;
58 ItemPointerData *tidList;
64 * We silently discard any TIDs that are out of range at the time of scan
65 * start. (Since we hold at least AccessShareLock on the table, it won't
66 * be possible for someone to truncate away the blocks we intend to
69 nblocks = RelationGetNumberOfBlocks(tidstate->ss.ss_currentRelation);
72 * We initialize the array with enough slots for the case that all quals
73 * are simple OpExprs or CurrentOfExprs. If there are any
74 * ScalarArrayOpExprs, we may have to enlarge the array.
76 numAllocTids = list_length(evalList);
77 tidList = (ItemPointerData *)
78 palloc(numAllocTids * sizeof(ItemPointerData));
80 tidstate->tss_isCurrentOf = false;
84 ExprState *exstate = (ExprState *) lfirst(l);
85 Expr *expr = exstate->expr;
89 if (is_opclause(expr))
91 FuncExprState *fexstate = (FuncExprState *) exstate;
95 arg1 = get_leftop(expr);
96 arg2 = get_rightop(expr);
98 exstate = (ExprState *) lsecond(fexstate->args);
99 else if (IsCTIDVar(arg2))
100 exstate = (ExprState *) linitial(fexstate->args);
102 elog(ERROR, "could not identify CTID variable");
104 itemptr = (ItemPointer)
105 DatumGetPointer(ExecEvalExprSwitchContext(exstate,
110 ItemPointerIsValid(itemptr) &&
111 ItemPointerGetBlockNumber(itemptr) < nblocks)
113 if (numTids >= numAllocTids)
116 tidList = (ItemPointerData *)
118 numAllocTids * sizeof(ItemPointerData));
120 tidList[numTids++] = *itemptr;
123 else if (expr && IsA(expr, ScalarArrayOpExpr))
125 ScalarArrayOpExprState *saexstate = (ScalarArrayOpExprState *) exstate;
127 ArrayType *itemarray;
133 exstate = (ExprState *) lsecond(saexstate->fxprstate.args);
134 arraydatum = ExecEvalExprSwitchContext(exstate,
140 itemarray = DatumGetArrayTypeP(arraydatum);
141 deconstruct_array(itemarray,
142 TIDOID, SizeOfIptrData, false, 's',
143 &ipdatums, &ipnulls, &ndatums);
144 if (numTids + ndatums > numAllocTids)
146 numAllocTids = numTids + ndatums;
147 tidList = (ItemPointerData *)
149 numAllocTids * sizeof(ItemPointerData));
151 for (i = 0; i < ndatums; i++)
155 itemptr = (ItemPointer) DatumGetPointer(ipdatums[i]);
156 if (ItemPointerIsValid(itemptr) &&
157 ItemPointerGetBlockNumber(itemptr) < nblocks)
158 tidList[numTids++] = *itemptr;
164 else if (expr && IsA(expr, CurrentOfExpr))
166 CurrentOfExpr *cexpr = (CurrentOfExpr *) expr;
167 ItemPointerData cursor_tid;
169 if (execCurrentOf(cexpr, econtext,
170 RelationGetRelid(tidstate->ss.ss_currentRelation),
173 if (numTids >= numAllocTids)
176 tidList = (ItemPointerData *)
178 numAllocTids * sizeof(ItemPointerData));
180 tidList[numTids++] = cursor_tid;
181 tidstate->tss_isCurrentOf = true;
185 elog(ERROR, "could not identify CTID expression");
189 * Sort the array of TIDs into order, and eliminate duplicates.
190 * Eliminating duplicates is necessary since we want OR semantics across
191 * the list. Sorting makes it easier to detect duplicates, and as a bonus
192 * ensures that we will visit the heap in the most efficient way.
199 /* CurrentOfExpr could never appear OR'd with something else */
200 Assert(!tidstate->tss_isCurrentOf);
202 qsort((void *) tidList, numTids, sizeof(ItemPointerData),
205 for (i = 1; i < numTids; i++)
207 if (!ItemPointerEquals(&tidList[lastTid], &tidList[i]))
208 tidList[++lastTid] = tidList[i];
210 numTids = lastTid + 1;
213 tidstate->tss_TidList = tidList;
214 tidstate->tss_NumTids = numTids;
215 tidstate->tss_TidPtr = -1;
219 * qsort comparator for ItemPointerData items
222 itemptr_comparator(const void *a, const void *b)
224 const ItemPointerData *ipa = (const ItemPointerData *) a;
225 const ItemPointerData *ipb = (const ItemPointerData *) b;
226 BlockNumber ba = ItemPointerGetBlockNumber(ipa);
227 BlockNumber bb = ItemPointerGetBlockNumber(ipb);
228 OffsetNumber oa = ItemPointerGetOffsetNumber(ipa);
229 OffsetNumber ob = ItemPointerGetOffsetNumber(ipb);
242 /* ----------------------------------------------------------------
245 * Retrieve a tuple from the TidScan node's currentRelation
246 * using the tids in the TidScanState information.
248 * ----------------------------------------------------------------
250 static TupleTableSlot *
251 TidNext(TidScanState *node)
254 ScanDirection direction;
256 Relation heapRelation;
258 TupleTableSlot *slot;
259 Buffer buffer = InvalidBuffer;
260 ItemPointerData *tidList;
265 * extract necessary information from tid scan node
267 estate = node->ss.ps.state;
268 direction = estate->es_direction;
269 snapshot = estate->es_snapshot;
270 heapRelation = node->ss.ss_currentRelation;
271 slot = node->ss.ss_ScanTupleSlot;
274 * First time through, compute the list of TIDs to be visited
276 if (node->tss_TidList == NULL)
279 tidList = node->tss_TidList;
280 numTids = node->tss_NumTids;
282 tuple = &(node->tss_htup);
285 * Initialize or advance scan position, depending on direction.
287 bBackward = ScanDirectionIsBackward(direction);
290 if (node->tss_TidPtr < 0)
292 /* initialize for backward scan */
293 node->tss_TidPtr = numTids - 1;
300 if (node->tss_TidPtr < 0)
302 /* initialize for forward scan */
303 node->tss_TidPtr = 0;
309 while (node->tss_TidPtr >= 0 && node->tss_TidPtr < numTids)
311 tuple->t_self = tidList[node->tss_TidPtr];
314 * For WHERE CURRENT OF, the tuple retrieved from the cursor might
315 * since have been updated; if so, we should fetch the version that is
316 * current according to our snapshot.
318 if (node->tss_isCurrentOf)
319 heap_get_latest_tid(heapRelation, snapshot, &tuple->t_self);
321 if (heap_fetch(heapRelation, snapshot, tuple, &buffer, false, NULL))
324 * store the scanned tuple in the scan tuple slot of the scan
325 * state. Eventually we will only do this and not return a tuple.
326 * Note: we pass 'false' because tuples returned by amgetnext are
327 * pointers onto disk pages and were not created with palloc() and
328 * so should not be pfree()'d.
330 ExecStoreTuple(tuple, /* tuple to store */
331 slot, /* slot to store in */
332 buffer, /* buffer associated with tuple */
333 false); /* don't pfree */
336 * At this point we have an extra pin on the buffer, because
337 * ExecStoreTuple incremented the pin count. Drop our local pin.
339 ReleaseBuffer(buffer);
343 /* Bad TID or failed snapshot qual; try next */
351 * if we get here it means the tid scan failed so we are at the end of the
354 return ExecClearTuple(slot);
358 * TidRecheck -- access method routine to recheck a tuple in EvalPlanQual
361 TidRecheck(TidScanState *node, TupleTableSlot *slot)
364 * XXX shouldn't we check here to make sure tuple matches TID list? In
365 * runtime-key case this is not certain, is it? However, in the WHERE
366 * CURRENT OF case it might not match anyway ...
372 /* ----------------------------------------------------------------
375 * Scans the relation using tids and returns
376 * the next qualifying tuple in the direction specified.
377 * We call the ExecScan() routine and pass it the appropriate
378 * access method functions.
381 * -- the "cursor" maintained by the AMI is positioned at the tuple
382 * returned previously.
385 * -- the relation indicated is opened for scanning so that the
386 * "cursor" is positioned before the first qualifying tuple.
388 * ----------------------------------------------------------------
391 ExecTidScan(TidScanState *node)
393 return ExecScan(&node->ss,
394 (ExecScanAccessMtd) TidNext,
395 (ExecScanRecheckMtd) TidRecheck);
398 /* ----------------------------------------------------------------
399 * ExecReScanTidScan(node)
400 * ----------------------------------------------------------------
403 ExecReScanTidScan(TidScanState *node)
405 if (node->tss_TidList)
406 pfree(node->tss_TidList);
407 node->tss_TidList = NULL;
408 node->tss_NumTids = 0;
409 node->tss_TidPtr = -1;
411 ExecScanReScan(&node->ss);
414 /* ----------------------------------------------------------------
417 * Releases any storage allocated through C routines.
419 * ----------------------------------------------------------------
422 ExecEndTidScan(TidScanState *node)
425 * Free the exprcontext
427 ExecFreeExprContext(&node->ss.ps);
430 * clear out tuple table slots
432 ExecClearTuple(node->ss.ps.ps_ResultTupleSlot);
433 ExecClearTuple(node->ss.ss_ScanTupleSlot);
436 * close the heap relation.
438 ExecCloseScanRelation(node->ss.ss_currentRelation);
441 /* ----------------------------------------------------------------
444 * Initializes the tid scan's state information, creates
445 * scan keys, and opens the base and tid relations.
448 * node: TidNode node produced by the planner.
449 * estate: the execution state initialized in InitPlan.
450 * ----------------------------------------------------------------
453 ExecInitTidScan(TidScan *node, EState *estate, int eflags)
455 TidScanState *tidstate;
456 Relation currentRelation;
459 * create state structure
461 tidstate = makeNode(TidScanState);
462 tidstate->ss.ps.plan = (Plan *) node;
463 tidstate->ss.ps.state = estate;
466 * Miscellaneous initialization
468 * create expression context for node
470 ExecAssignExprContext(estate, &tidstate->ss.ps);
472 tidstate->ss.ps.ps_TupFromTlist = false;
475 * initialize child expressions
477 tidstate->ss.ps.targetlist = (List *)
478 ExecInitExpr((Expr *) node->scan.plan.targetlist,
479 (PlanState *) tidstate);
480 tidstate->ss.ps.qual = (List *)
481 ExecInitExpr((Expr *) node->scan.plan.qual,
482 (PlanState *) tidstate);
484 tidstate->tss_tidquals = (List *)
485 ExecInitExpr((Expr *) node->tidquals,
486 (PlanState *) tidstate);
489 * tuple table initialization
491 ExecInitResultTupleSlot(estate, &tidstate->ss.ps);
492 ExecInitScanTupleSlot(estate, &tidstate->ss);
495 * mark tid list as not computed yet
497 tidstate->tss_TidList = NULL;
498 tidstate->tss_NumTids = 0;
499 tidstate->tss_TidPtr = -1;
502 * open the base relation and acquire appropriate lock on it.
504 currentRelation = ExecOpenScanRelation(estate, node->scan.scanrelid, eflags);
506 tidstate->ss.ss_currentRelation = currentRelation;
507 tidstate->ss.ss_currentScanDesc = NULL; /* no heap scan here */
510 * get the scan type from the relation descriptor.
512 ExecAssignScanType(&tidstate->ss, RelationGetDescr(currentRelation));
515 * Initialize result tuple type and projection info.
517 ExecAssignResultTypeFromTL(&tidstate->ss.ps);
518 ExecAssignScanProjectionInfo(&tidstate->ss);