1 /*-------------------------------------------------------------------------
4 * Routines to support direct tid scans of relations
6 * Portions Copyright (c) 1996-2018, 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 "miscadmin.h"
30 #include "optimizer/clauses.h"
31 #include "storage/bufmgr.h"
32 #include "utils/array.h"
33 #include "utils/rel.h"
36 #define IsCTIDVar(node) \
39 ((Var *) (node))->varattno == SelfItemPointerAttributeNumber && \
40 ((Var *) (node))->varlevelsup == 0)
42 /* one element in tss_tidexprs */
43 typedef struct TidExpr
45 ExprState *exprstate; /* ExprState for a TID-yielding subexpr */
46 bool isarray; /* if true, it yields tid[] not just tid */
47 CurrentOfExpr *cexpr; /* alternatively, we can have CURRENT OF */
50 static void TidExprListCreate(TidScanState *tidstate);
51 static void TidListEval(TidScanState *tidstate);
52 static int itemptr_comparator(const void *a, const void *b);
53 static TupleTableSlot *TidNext(TidScanState *node);
57 * Extract the qual subexpressions that yield TIDs to search for,
58 * and compile them into ExprStates if they're ordinary expressions.
60 * CURRENT OF is a special case that we can't compile usefully;
61 * just drop it into the TidExpr list as-is.
64 TidExprListCreate(TidScanState *tidstate)
66 TidScan *node = (TidScan *) tidstate->ss.ps.plan;
69 tidstate->tss_tidexprs = NIL;
70 tidstate->tss_isCurrentOf = false;
72 foreach(l, node->tidquals)
74 Expr *expr = (Expr *) lfirst(l);
75 TidExpr *tidexpr = (TidExpr *) palloc0(sizeof(TidExpr));
77 if (is_opclause(expr))
82 arg1 = get_leftop(expr);
83 arg2 = get_rightop(expr);
85 tidexpr->exprstate = ExecInitExpr((Expr *) arg2,
87 else if (IsCTIDVar(arg2))
88 tidexpr->exprstate = ExecInitExpr((Expr *) arg1,
91 elog(ERROR, "could not identify CTID variable");
92 tidexpr->isarray = false;
94 else if (expr && IsA(expr, ScalarArrayOpExpr))
96 ScalarArrayOpExpr *saex = (ScalarArrayOpExpr *) expr;
98 Assert(IsCTIDVar(linitial(saex->args)));
99 tidexpr->exprstate = ExecInitExpr(lsecond(saex->args),
101 tidexpr->isarray = true;
103 else if (expr && IsA(expr, CurrentOfExpr))
105 CurrentOfExpr *cexpr = (CurrentOfExpr *) expr;
107 tidexpr->cexpr = cexpr;
108 tidstate->tss_isCurrentOf = true;
111 elog(ERROR, "could not identify CTID expression");
113 tidstate->tss_tidexprs = lappend(tidstate->tss_tidexprs, tidexpr);
116 /* CurrentOfExpr could never appear OR'd with something else */
117 Assert(list_length(tidstate->tss_tidexprs) == 1 ||
118 !tidstate->tss_isCurrentOf);
122 * Compute the list of TIDs to be visited, by evaluating the expressions
125 * (The result is actually an array, not a list.)
128 TidListEval(TidScanState *tidstate)
130 ExprContext *econtext = tidstate->ss.ps.ps_ExprContext;
132 ItemPointerData *tidList;
138 * We silently discard any TIDs that are out of range at the time of scan
139 * start. (Since we hold at least AccessShareLock on the table, it won't
140 * be possible for someone to truncate away the blocks we intend to
143 nblocks = RelationGetNumberOfBlocks(tidstate->ss.ss_currentRelation);
146 * We initialize the array with enough slots for the case that all quals
147 * are simple OpExprs or CurrentOfExprs. If there are any
148 * ScalarArrayOpExprs, we may have to enlarge the array.
150 numAllocTids = list_length(tidstate->tss_tidexprs);
151 tidList = (ItemPointerData *)
152 palloc(numAllocTids * sizeof(ItemPointerData));
155 foreach(l, tidstate->tss_tidexprs)
157 TidExpr *tidexpr = (TidExpr *) lfirst(l);
161 if (tidexpr->exprstate && !tidexpr->isarray)
163 itemptr = (ItemPointer)
164 DatumGetPointer(ExecEvalExprSwitchContext(tidexpr->exprstate,
168 ItemPointerIsValid(itemptr) &&
169 ItemPointerGetBlockNumber(itemptr) < nblocks)
171 if (numTids >= numAllocTids)
174 tidList = (ItemPointerData *)
176 numAllocTids * sizeof(ItemPointerData));
178 tidList[numTids++] = *itemptr;
181 else if (tidexpr->exprstate && tidexpr->isarray)
184 ArrayType *itemarray;
190 arraydatum = ExecEvalExprSwitchContext(tidexpr->exprstate,
195 itemarray = DatumGetArrayTypeP(arraydatum);
196 deconstruct_array(itemarray,
197 TIDOID, sizeof(ItemPointerData), false, 's',
198 &ipdatums, &ipnulls, &ndatums);
199 if (numTids + ndatums > numAllocTids)
201 numAllocTids = numTids + ndatums;
202 tidList = (ItemPointerData *)
204 numAllocTids * sizeof(ItemPointerData));
206 for (i = 0; i < ndatums; i++)
210 itemptr = (ItemPointer) DatumGetPointer(ipdatums[i]);
211 if (ItemPointerIsValid(itemptr) &&
212 ItemPointerGetBlockNumber(itemptr) < nblocks)
213 tidList[numTids++] = *itemptr;
221 ItemPointerData cursor_tid;
223 Assert(tidexpr->cexpr);
224 if (execCurrentOf(tidexpr->cexpr, econtext,
225 RelationGetRelid(tidstate->ss.ss_currentRelation),
228 if (numTids >= numAllocTids)
231 tidList = (ItemPointerData *)
233 numAllocTids * sizeof(ItemPointerData));
235 tidList[numTids++] = cursor_tid;
241 * Sort the array of TIDs into order, and eliminate duplicates.
242 * Eliminating duplicates is necessary since we want OR semantics across
243 * the list. Sorting makes it easier to detect duplicates, and as a bonus
244 * ensures that we will visit the heap in the most efficient way.
251 /* CurrentOfExpr could never appear OR'd with something else */
252 Assert(!tidstate->tss_isCurrentOf);
254 qsort((void *) tidList, numTids, sizeof(ItemPointerData),
257 for (i = 1; i < numTids; i++)
259 if (!ItemPointerEquals(&tidList[lastTid], &tidList[i]))
260 tidList[++lastTid] = tidList[i];
262 numTids = lastTid + 1;
265 tidstate->tss_TidList = tidList;
266 tidstate->tss_NumTids = numTids;
267 tidstate->tss_TidPtr = -1;
271 * qsort comparator for ItemPointerData items
274 itemptr_comparator(const void *a, const void *b)
276 const ItemPointerData *ipa = (const ItemPointerData *) a;
277 const ItemPointerData *ipb = (const ItemPointerData *) b;
278 BlockNumber ba = ItemPointerGetBlockNumber(ipa);
279 BlockNumber bb = ItemPointerGetBlockNumber(ipb);
280 OffsetNumber oa = ItemPointerGetOffsetNumber(ipa);
281 OffsetNumber ob = ItemPointerGetOffsetNumber(ipb);
294 /* ----------------------------------------------------------------
297 * Retrieve a tuple from the TidScan node's currentRelation
298 * using the tids in the TidScanState information.
300 * ----------------------------------------------------------------
302 static TupleTableSlot *
303 TidNext(TidScanState *node)
306 ScanDirection direction;
308 Relation heapRelation;
310 TupleTableSlot *slot;
311 Buffer buffer = InvalidBuffer;
312 ItemPointerData *tidList;
317 * extract necessary information from tid scan node
319 estate = node->ss.ps.state;
320 direction = estate->es_direction;
321 snapshot = estate->es_snapshot;
322 heapRelation = node->ss.ss_currentRelation;
323 slot = node->ss.ss_ScanTupleSlot;
326 * First time through, compute the list of TIDs to be visited
328 if (node->tss_TidList == NULL)
331 tidList = node->tss_TidList;
332 numTids = node->tss_NumTids;
335 * We use node->tss_htup as the tuple pointer; note this can't just be a
336 * local variable here, as the scan tuple slot will keep a pointer to it.
338 tuple = &(node->tss_htup);
341 * Initialize or advance scan position, depending on direction.
343 bBackward = ScanDirectionIsBackward(direction);
346 if (node->tss_TidPtr < 0)
348 /* initialize for backward scan */
349 node->tss_TidPtr = numTids - 1;
356 if (node->tss_TidPtr < 0)
358 /* initialize for forward scan */
359 node->tss_TidPtr = 0;
365 while (node->tss_TidPtr >= 0 && node->tss_TidPtr < numTids)
367 tuple->t_self = tidList[node->tss_TidPtr];
370 * For WHERE CURRENT OF, the tuple retrieved from the cursor might
371 * since have been updated; if so, we should fetch the version that is
372 * current according to our snapshot.
374 if (node->tss_isCurrentOf)
375 heap_get_latest_tid(heapRelation, snapshot, &tuple->t_self);
377 if (heap_fetch(heapRelation, snapshot, tuple, &buffer, false, NULL))
380 * store the scanned tuple in the scan tuple slot of the scan
381 * state. Eventually we will only do this and not return a tuple.
382 * Note: we pass 'false' because tuples returned by amgetnext are
383 * pointers onto disk pages and were not created with palloc() and
384 * so should not be pfree()'d.
386 ExecStoreTuple(tuple, /* tuple to store */
387 slot, /* slot to store in */
388 buffer, /* buffer associated with tuple */
389 false); /* don't pfree */
392 * At this point we have an extra pin on the buffer, because
393 * ExecStoreTuple incremented the pin count. Drop our local pin.
395 ReleaseBuffer(buffer);
399 /* Bad TID or failed snapshot qual; try next */
405 CHECK_FOR_INTERRUPTS();
409 * if we get here it means the tid scan failed so we are at the end of the
412 return ExecClearTuple(slot);
416 * TidRecheck -- access method routine to recheck a tuple in EvalPlanQual
419 TidRecheck(TidScanState *node, TupleTableSlot *slot)
422 * XXX shouldn't we check here to make sure tuple matches TID list? In
423 * runtime-key case this is not certain, is it? However, in the WHERE
424 * CURRENT OF case it might not match anyway ...
430 /* ----------------------------------------------------------------
433 * Scans the relation using tids and returns
434 * the next qualifying tuple in the direction specified.
435 * We call the ExecScan() routine and pass it the appropriate
436 * access method functions.
439 * -- the "cursor" maintained by the AMI is positioned at the tuple
440 * returned previously.
443 * -- the relation indicated is opened for scanning so that the
444 * "cursor" is positioned before the first qualifying tuple.
446 * ----------------------------------------------------------------
448 static TupleTableSlot *
449 ExecTidScan(PlanState *pstate)
451 TidScanState *node = castNode(TidScanState, pstate);
453 return ExecScan(&node->ss,
454 (ExecScanAccessMtd) TidNext,
455 (ExecScanRecheckMtd) TidRecheck);
458 /* ----------------------------------------------------------------
459 * ExecReScanTidScan(node)
460 * ----------------------------------------------------------------
463 ExecReScanTidScan(TidScanState *node)
465 if (node->tss_TidList)
466 pfree(node->tss_TidList);
467 node->tss_TidList = NULL;
468 node->tss_NumTids = 0;
469 node->tss_TidPtr = -1;
471 ExecScanReScan(&node->ss);
474 /* ----------------------------------------------------------------
477 * Releases any storage allocated through C routines.
479 * ----------------------------------------------------------------
482 ExecEndTidScan(TidScanState *node)
485 * Free the exprcontext
487 ExecFreeExprContext(&node->ss.ps);
490 * clear out tuple table slots
492 ExecClearTuple(node->ss.ps.ps_ResultTupleSlot);
493 ExecClearTuple(node->ss.ss_ScanTupleSlot);
496 * close the heap relation.
498 ExecCloseScanRelation(node->ss.ss_currentRelation);
501 /* ----------------------------------------------------------------
504 * Initializes the tid scan's state information, creates
505 * scan keys, and opens the base and tid relations.
508 * node: TidNode node produced by the planner.
509 * estate: the execution state initialized in InitPlan.
510 * ----------------------------------------------------------------
513 ExecInitTidScan(TidScan *node, EState *estate, int eflags)
515 TidScanState *tidstate;
516 Relation currentRelation;
519 * create state structure
521 tidstate = makeNode(TidScanState);
522 tidstate->ss.ps.plan = (Plan *) node;
523 tidstate->ss.ps.state = estate;
524 tidstate->ss.ps.ExecProcNode = ExecTidScan;
527 * Miscellaneous initialization
529 * create expression context for node
531 ExecAssignExprContext(estate, &tidstate->ss.ps);
534 * mark tid list as not computed yet
536 tidstate->tss_TidList = NULL;
537 tidstate->tss_NumTids = 0;
538 tidstate->tss_TidPtr = -1;
541 * open the base relation and acquire appropriate lock on it.
543 currentRelation = ExecOpenScanRelation(estate, node->scan.scanrelid, eflags);
545 tidstate->ss.ss_currentRelation = currentRelation;
546 tidstate->ss.ss_currentScanDesc = NULL; /* no heap scan here */
549 * get the scan type from the relation descriptor.
551 ExecInitScanTupleSlot(estate, &tidstate->ss,
552 RelationGetDescr(currentRelation));
555 * Initialize result slot, type and projection.
557 ExecInitResultTupleSlotTL(estate, &tidstate->ss.ps);
558 ExecAssignScanProjectionInfo(&tidstate->ss);
561 * initialize child expressions
563 tidstate->ss.ps.qual =
564 ExecInitQual(node->scan.plan.qual, (PlanState *) tidstate);
566 TidExprListCreate(tidstate);