LCOV - code coverage report
Current view: top level - src/backend/executor - nodeTidscan.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 156 172 90.7 %
Date: 2020-06-05 19:06:29 Functions: 8 9 88.9 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * nodeTidscan.c
       4             :  *    Routines to support direct tid scans of relations
       5             :  *
       6             :  * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/executor/nodeTidscan.c
      12             :  *
      13             :  *-------------------------------------------------------------------------
      14             :  */
      15             : /*
      16             :  * INTERFACE ROUTINES
      17             :  *
      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.
      22             :  */
      23             : #include "postgres.h"
      24             : 
      25             : #include "access/sysattr.h"
      26             : #include "access/tableam.h"
      27             : #include "catalog/pg_type.h"
      28             : #include "executor/execdebug.h"
      29             : #include "executor/nodeTidscan.h"
      30             : #include "lib/qunique.h"
      31             : #include "miscadmin.h"
      32             : #include "nodes/nodeFuncs.h"
      33             : #include "storage/bufmgr.h"
      34             : #include "utils/array.h"
      35             : #include "utils/rel.h"
      36             : 
      37             : 
      38             : #define IsCTIDVar(node)  \
      39             :     ((node) != NULL && \
      40             :      IsA((node), Var) && \
      41             :      ((Var *) (node))->varattno == SelfItemPointerAttributeNumber && \
      42             :      ((Var *) (node))->varlevelsup == 0)
      43             : 
      44             : /* one element in tss_tidexprs */
      45             : typedef struct TidExpr
      46             : {
      47             :     ExprState  *exprstate;      /* ExprState for a TID-yielding subexpr */
      48             :     bool        isarray;        /* if true, it yields tid[] not just tid */
      49             :     CurrentOfExpr *cexpr;       /* alternatively, we can have CURRENT OF */
      50             : } TidExpr;
      51             : 
      52             : static void TidExprListCreate(TidScanState *tidstate);
      53             : static void TidListEval(TidScanState *tidstate);
      54             : static int  itemptr_comparator(const void *a, const void *b);
      55             : static TupleTableSlot *TidNext(TidScanState *node);
      56             : 
      57             : 
      58             : /*
      59             :  * Extract the qual subexpressions that yield TIDs to search for,
      60             :  * and compile them into ExprStates if they're ordinary expressions.
      61             :  *
      62             :  * CURRENT OF is a special case that we can't compile usefully;
      63             :  * just drop it into the TidExpr list as-is.
      64             :  */
      65             : static void
      66         472 : TidExprListCreate(TidScanState *tidstate)
      67             : {
      68         472 :     TidScan    *node = (TidScan *) tidstate->ss.ps.plan;
      69             :     ListCell   *l;
      70             : 
      71         472 :     tidstate->tss_tidexprs = NIL;
      72         472 :     tidstate->tss_isCurrentOf = false;
      73             : 
      74         960 :     foreach(l, node->tidquals)
      75             :     {
      76         488 :         Expr       *expr = (Expr *) lfirst(l);
      77         488 :         TidExpr    *tidexpr = (TidExpr *) palloc0(sizeof(TidExpr));
      78             : 
      79         488 :         if (is_opclause(expr))
      80             :         {
      81             :             Node       *arg1;
      82             :             Node       *arg2;
      83             : 
      84         178 :             arg1 = get_leftop(expr);
      85         178 :             arg2 = get_rightop(expr);
      86         178 :             if (IsCTIDVar(arg1))
      87         154 :                 tidexpr->exprstate = ExecInitExpr((Expr *) arg2,
      88             :                                                   &tidstate->ss.ps);
      89          24 :             else if (IsCTIDVar(arg2))
      90          24 :                 tidexpr->exprstate = ExecInitExpr((Expr *) arg1,
      91             :                                                   &tidstate->ss.ps);
      92             :             else
      93           0 :                 elog(ERROR, "could not identify CTID variable");
      94         178 :             tidexpr->isarray = false;
      95             :         }
      96         310 :         else if (expr && IsA(expr, ScalarArrayOpExpr))
      97          20 :         {
      98          20 :             ScalarArrayOpExpr *saex = (ScalarArrayOpExpr *) expr;
      99             : 
     100             :             Assert(IsCTIDVar(linitial(saex->args)));
     101          20 :             tidexpr->exprstate = ExecInitExpr(lsecond(saex->args),
     102             :                                               &tidstate->ss.ps);
     103          20 :             tidexpr->isarray = true;
     104             :         }
     105         290 :         else if (expr && IsA(expr, CurrentOfExpr))
     106         290 :         {
     107         290 :             CurrentOfExpr *cexpr = (CurrentOfExpr *) expr;
     108             : 
     109         290 :             tidexpr->cexpr = cexpr;
     110         290 :             tidstate->tss_isCurrentOf = true;
     111             :         }
     112             :         else
     113           0 :             elog(ERROR, "could not identify CTID expression");
     114             : 
     115         488 :         tidstate->tss_tidexprs = lappend(tidstate->tss_tidexprs, tidexpr);
     116             :     }
     117             : 
     118             :     /* CurrentOfExpr could never appear OR'd with something else */
     119             :     Assert(list_length(tidstate->tss_tidexprs) == 1 ||
     120             :            !tidstate->tss_isCurrentOf);
     121         472 : }
     122             : 
     123             : /*
     124             :  * Compute the list of TIDs to be visited, by evaluating the expressions
     125             :  * for them.
     126             :  *
     127             :  * (The result is actually an array, not a list.)
     128             :  */
     129             : static void
     130         412 : TidListEval(TidScanState *tidstate)
     131             : {
     132         412 :     ExprContext *econtext = tidstate->ss.ps.ps_ExprContext;
     133             :     TableScanDesc scan;
     134             :     ItemPointerData *tidList;
     135             :     int         numAllocTids;
     136             :     int         numTids;
     137             :     ListCell   *l;
     138             : 
     139             :     /*
     140             :      * Start scan on-demand - initializing a scan isn't free (e.g. heap stats
     141             :      * the size of the table), so it makes sense to delay that until needed -
     142             :      * the node might never get executed.
     143             :      */
     144         412 :     if (tidstate->ss.ss_currentScanDesc == NULL)
     145         408 :         tidstate->ss.ss_currentScanDesc =
     146         408 :             table_beginscan_tid(tidstate->ss.ss_currentRelation,
     147         408 :                                 tidstate->ss.ps.state->es_snapshot);
     148         412 :     scan = tidstate->ss.ss_currentScanDesc;
     149             : 
     150             :     /*
     151             :      * We initialize the array with enough slots for the case that all quals
     152             :      * are simple OpExprs or CurrentOfExprs.  If there are any
     153             :      * ScalarArrayOpExprs, we may have to enlarge the array.
     154             :      */
     155         412 :     numAllocTids = list_length(tidstate->tss_tidexprs);
     156             :     tidList = (ItemPointerData *)
     157         412 :         palloc(numAllocTids * sizeof(ItemPointerData));
     158         412 :     numTids = 0;
     159             : 
     160         792 :     foreach(l, tidstate->tss_tidexprs)
     161             :     {
     162         420 :         TidExpr    *tidexpr = (TidExpr *) lfirst(l);
     163             :         ItemPointer itemptr;
     164             :         bool        isNull;
     165             : 
     166         420 :         if (tidexpr->exprstate && !tidexpr->isarray)
     167             :         {
     168         150 :             itemptr = (ItemPointer)
     169         150 :                 DatumGetPointer(ExecEvalExprSwitchContext(tidexpr->exprstate,
     170             :                                                           econtext,
     171             :                                                           &isNull));
     172         150 :             if (isNull)
     173           0 :                 continue;
     174             : 
     175             :             /*
     176             :              * We silently discard any TIDs that the AM considers invalid
     177             :              * (E.g. for heap, they could be out of range at the time of scan
     178             :              * start.  Since we hold at least AccessShareLock on the table, it
     179             :              * won't be possible for someone to truncate away the blocks we
     180             :              * intend to visit.).
     181             :              */
     182         150 :             if (!table_tuple_tid_valid(scan, itemptr))
     183           0 :                 continue;
     184             : 
     185         150 :             if (numTids >= numAllocTids)
     186             :             {
     187           4 :                 numAllocTids *= 2;
     188             :                 tidList = (ItemPointerData *)
     189           4 :                     repalloc(tidList,
     190             :                              numAllocTids * sizeof(ItemPointerData));
     191             :             }
     192         150 :             tidList[numTids++] = *itemptr;
     193             :         }
     194         270 :         else if (tidexpr->exprstate && tidexpr->isarray)
     195          16 :         {
     196             :             Datum       arraydatum;
     197             :             ArrayType  *itemarray;
     198             :             Datum      *ipdatums;
     199             :             bool       *ipnulls;
     200             :             int         ndatums;
     201             :             int         i;
     202             : 
     203          16 :             arraydatum = ExecEvalExprSwitchContext(tidexpr->exprstate,
     204             :                                                    econtext,
     205             :                                                    &isNull);
     206          16 :             if (isNull)
     207           0 :                 continue;
     208          16 :             itemarray = DatumGetArrayTypeP(arraydatum);
     209          16 :             deconstruct_array(itemarray,
     210             :                               TIDOID, sizeof(ItemPointerData), false, TYPALIGN_SHORT,
     211             :                               &ipdatums, &ipnulls, &ndatums);
     212          16 :             if (numTids + ndatums > numAllocTids)
     213             :             {
     214          12 :                 numAllocTids = numTids + ndatums;
     215             :                 tidList = (ItemPointerData *)
     216          12 :                     repalloc(tidList,
     217             :                              numAllocTids * sizeof(ItemPointerData));
     218             :             }
     219          48 :             for (i = 0; i < ndatums; i++)
     220             :             {
     221          32 :                 if (ipnulls[i])
     222           0 :                     continue;
     223             : 
     224          32 :                 itemptr = (ItemPointer) DatumGetPointer(ipdatums[i]);
     225             : 
     226          32 :                 if (!table_tuple_tid_valid(scan, itemptr))
     227           0 :                     continue;
     228             : 
     229          32 :                 tidList[numTids++] = *itemptr;
     230             :             }
     231          16 :             pfree(ipdatums);
     232          16 :             pfree(ipnulls);
     233             :         }
     234             :         else
     235             :         {
     236             :             ItemPointerData cursor_tid;
     237             : 
     238             :             Assert(tidexpr->cexpr);
     239         214 :             if (execCurrentOf(tidexpr->cexpr, econtext,
     240         254 :                               RelationGetRelid(tidstate->ss.ss_currentRelation),
     241             :                               &cursor_tid))
     242             :             {
     243         180 :                 if (numTids >= numAllocTids)
     244             :                 {
     245           0 :                     numAllocTids *= 2;
     246             :                     tidList = (ItemPointerData *)
     247           0 :                         repalloc(tidList,
     248             :                                  numAllocTids * sizeof(ItemPointerData));
     249             :                 }
     250         180 :                 tidList[numTids++] = cursor_tid;
     251             :             }
     252             :         }
     253             :     }
     254             : 
     255             :     /*
     256             :      * Sort the array of TIDs into order, and eliminate duplicates.
     257             :      * Eliminating duplicates is necessary since we want OR semantics across
     258             :      * the list.  Sorting makes it easier to detect duplicates, and as a bonus
     259             :      * ensures that we will visit the heap in the most efficient way.
     260             :      */
     261         372 :     if (numTids > 1)
     262             :     {
     263             :         /* CurrentOfExpr could never appear OR'd with something else */
     264             :         Assert(!tidstate->tss_isCurrentOf);
     265             : 
     266          20 :         qsort((void *) tidList, numTids, sizeof(ItemPointerData),
     267             :               itemptr_comparator);
     268          20 :         numTids = qunique(tidList, numTids, sizeof(ItemPointerData),
     269             :                           itemptr_comparator);
     270             :     }
     271             : 
     272         372 :     tidstate->tss_TidList = tidList;
     273         372 :     tidstate->tss_NumTids = numTids;
     274         372 :     tidstate->tss_TidPtr = -1;
     275         372 : }
     276             : 
     277             : /*
     278             :  * qsort comparator for ItemPointerData items
     279             :  */
     280             : static int
     281          52 : itemptr_comparator(const void *a, const void *b)
     282             : {
     283          52 :     const ItemPointerData *ipa = (const ItemPointerData *) a;
     284          52 :     const ItemPointerData *ipb = (const ItemPointerData *) b;
     285          52 :     BlockNumber ba = ItemPointerGetBlockNumber(ipa);
     286          52 :     BlockNumber bb = ItemPointerGetBlockNumber(ipb);
     287          52 :     OffsetNumber oa = ItemPointerGetOffsetNumber(ipa);
     288          52 :     OffsetNumber ob = ItemPointerGetOffsetNumber(ipb);
     289             : 
     290          52 :     if (ba < bb)
     291           0 :         return -1;
     292          52 :     if (ba > bb)
     293           0 :         return 1;
     294          52 :     if (oa < ob)
     295          16 :         return -1;
     296          36 :     if (oa > ob)
     297          36 :         return 1;
     298           0 :     return 0;
     299             : }
     300             : 
     301             : /* ----------------------------------------------------------------
     302             :  *      TidNext
     303             :  *
     304             :  *      Retrieve a tuple from the TidScan node's currentRelation
     305             :  *      using the tids in the TidScanState information.
     306             :  *
     307             :  * ----------------------------------------------------------------
     308             :  */
     309             : static TupleTableSlot *
     310         752 : TidNext(TidScanState *node)
     311             : {
     312             :     EState     *estate;
     313             :     ScanDirection direction;
     314             :     Snapshot    snapshot;
     315             :     TableScanDesc scan;
     316             :     Relation    heapRelation;
     317             :     TupleTableSlot *slot;
     318             :     ItemPointerData *tidList;
     319             :     int         numTids;
     320             :     bool        bBackward;
     321             : 
     322             :     /*
     323             :      * extract necessary information from tid scan node
     324             :      */
     325         752 :     estate = node->ss.ps.state;
     326         752 :     direction = estate->es_direction;
     327         752 :     snapshot = estate->es_snapshot;
     328         752 :     heapRelation = node->ss.ss_currentRelation;
     329         752 :     slot = node->ss.ss_ScanTupleSlot;
     330             : 
     331             :     /*
     332             :      * First time through, compute the list of TIDs to be visited
     333             :      */
     334         752 :     if (node->tss_TidList == NULL)
     335         412 :         TidListEval(node);
     336             : 
     337         712 :     scan = node->ss.ss_currentScanDesc;
     338         712 :     tidList = node->tss_TidList;
     339         712 :     numTids = node->tss_NumTids;
     340             : 
     341             :     /*
     342             :      * Initialize or advance scan position, depending on direction.
     343             :      */
     344         712 :     bBackward = ScanDirectionIsBackward(direction);
     345         712 :     if (bBackward)
     346             :     {
     347           4 :         if (node->tss_TidPtr < 0)
     348             :         {
     349             :             /* initialize for backward scan */
     350           0 :             node->tss_TidPtr = numTids - 1;
     351             :         }
     352             :         else
     353           4 :             node->tss_TidPtr--;
     354             :     }
     355             :     else
     356             :     {
     357         708 :         if (node->tss_TidPtr < 0)
     358             :         {
     359             :             /* initialize for forward scan */
     360         372 :             node->tss_TidPtr = 0;
     361             :         }
     362             :         else
     363         336 :             node->tss_TidPtr++;
     364             :     }
     365             : 
     366         730 :     while (node->tss_TidPtr >= 0 && node->tss_TidPtr < numTids)
     367             :     {
     368         362 :         ItemPointerData tid = tidList[node->tss_TidPtr];
     369             : 
     370             :         /*
     371             :          * For WHERE CURRENT OF, the tuple retrieved from the cursor might
     372             :          * since have been updated; if so, we should fetch the version that is
     373             :          * current according to our snapshot.
     374             :          */
     375         362 :         if (node->tss_isCurrentOf)
     376         180 :             table_tuple_get_latest_tid(scan, &tid);
     377             : 
     378         362 :         if (table_tuple_fetch_row_version(heapRelation, &tid, snapshot, slot))
     379         344 :             return slot;
     380             : 
     381             :         /* Bad TID or failed snapshot qual; try next */
     382          18 :         if (bBackward)
     383           0 :             node->tss_TidPtr--;
     384             :         else
     385          18 :             node->tss_TidPtr++;
     386             : 
     387          18 :         CHECK_FOR_INTERRUPTS();
     388             :     }
     389             : 
     390             :     /*
     391             :      * if we get here it means the tid scan failed so we are at the end of the
     392             :      * scan..
     393             :      */
     394         368 :     return ExecClearTuple(slot);
     395             : }
     396             : 
     397             : /*
     398             :  * TidRecheck -- access method routine to recheck a tuple in EvalPlanQual
     399             :  */
     400             : static bool
     401           0 : TidRecheck(TidScanState *node, TupleTableSlot *slot)
     402             : {
     403             :     /*
     404             :      * XXX shouldn't we check here to make sure tuple matches TID list? In
     405             :      * runtime-key case this is not certain, is it?  However, in the WHERE
     406             :      * CURRENT OF case it might not match anyway ...
     407             :      */
     408           0 :     return true;
     409             : }
     410             : 
     411             : 
     412             : /* ----------------------------------------------------------------
     413             :  *      ExecTidScan(node)
     414             :  *
     415             :  *      Scans the relation using tids and returns
     416             :  *         the next qualifying tuple in the direction specified.
     417             :  *      We call the ExecScan() routine and pass it the appropriate
     418             :  *      access method functions.
     419             :  *
     420             :  *      Conditions:
     421             :  *        -- the "cursor" maintained by the AMI is positioned at the tuple
     422             :  *           returned previously.
     423             :  *
     424             :  *      Initial States:
     425             :  *        -- the relation indicated is opened for scanning so that the
     426             :  *           "cursor" is positioned before the first qualifying tuple.
     427             :  *        -- tss_TidPtr is -1.
     428             :  * ----------------------------------------------------------------
     429             :  */
     430             : static TupleTableSlot *
     431         740 : ExecTidScan(PlanState *pstate)
     432             : {
     433         740 :     TidScanState *node = castNode(TidScanState, pstate);
     434             : 
     435         740 :     return ExecScan(&node->ss,
     436             :                     (ExecScanAccessMtd) TidNext,
     437             :                     (ExecScanRecheckMtd) TidRecheck);
     438             : }
     439             : 
     440             : /* ----------------------------------------------------------------
     441             :  *      ExecReScanTidScan(node)
     442             :  * ----------------------------------------------------------------
     443             :  */
     444             : void
     445          12 : ExecReScanTidScan(TidScanState *node)
     446             : {
     447          12 :     if (node->tss_TidList)
     448           4 :         pfree(node->tss_TidList);
     449          12 :     node->tss_TidList = NULL;
     450          12 :     node->tss_NumTids = 0;
     451          12 :     node->tss_TidPtr = -1;
     452             : 
     453             :     /* not really necessary, but seems good form */
     454          12 :     if (node->ss.ss_currentScanDesc)
     455           4 :         table_rescan(node->ss.ss_currentScanDesc, NULL);
     456             : 
     457          12 :     ExecScanReScan(&node->ss);
     458          12 : }
     459             : 
     460             : /* ----------------------------------------------------------------
     461             :  *      ExecEndTidScan
     462             :  *
     463             :  *      Releases any storage allocated through C routines.
     464             :  *      Returns nothing.
     465             :  * ----------------------------------------------------------------
     466             :  */
     467             : void
     468         394 : ExecEndTidScan(TidScanState *node)
     469             : {
     470         394 :     if (node->ss.ss_currentScanDesc)
     471         362 :         table_endscan(node->ss.ss_currentScanDesc);
     472             : 
     473             :     /*
     474             :      * Free the exprcontext
     475             :      */
     476         394 :     ExecFreeExprContext(&node->ss.ps);
     477             : 
     478             :     /*
     479             :      * clear out tuple table slots
     480             :      */
     481         394 :     if (node->ss.ps.ps_ResultTupleSlot)
     482         388 :         ExecClearTuple(node->ss.ps.ps_ResultTupleSlot);
     483         394 :     ExecClearTuple(node->ss.ss_ScanTupleSlot);
     484         394 : }
     485             : 
     486             : /* ----------------------------------------------------------------
     487             :  *      ExecInitTidScan
     488             :  *
     489             :  *      Initializes the tid scan's state information, creates
     490             :  *      scan keys, and opens the base and tid relations.
     491             :  *
     492             :  *      Parameters:
     493             :  *        node: TidScan node produced by the planner.
     494             :  *        estate: the execution state initialized in InitPlan.
     495             :  * ----------------------------------------------------------------
     496             :  */
     497             : TidScanState *
     498         472 : ExecInitTidScan(TidScan *node, EState *estate, int eflags)
     499             : {
     500             :     TidScanState *tidstate;
     501             :     Relation    currentRelation;
     502             : 
     503             :     /*
     504             :      * create state structure
     505             :      */
     506         472 :     tidstate = makeNode(TidScanState);
     507         472 :     tidstate->ss.ps.plan = (Plan *) node;
     508         472 :     tidstate->ss.ps.state = estate;
     509         472 :     tidstate->ss.ps.ExecProcNode = ExecTidScan;
     510             : 
     511             :     /*
     512             :      * Miscellaneous initialization
     513             :      *
     514             :      * create expression context for node
     515             :      */
     516         472 :     ExecAssignExprContext(estate, &tidstate->ss.ps);
     517             : 
     518             :     /*
     519             :      * mark tid list as not computed yet
     520             :      */
     521         472 :     tidstate->tss_TidList = NULL;
     522         472 :     tidstate->tss_NumTids = 0;
     523         472 :     tidstate->tss_TidPtr = -1;
     524             : 
     525             :     /*
     526             :      * open the scan relation
     527             :      */
     528         472 :     currentRelation = ExecOpenScanRelation(estate, node->scan.scanrelid, eflags);
     529             : 
     530         472 :     tidstate->ss.ss_currentRelation = currentRelation;
     531         472 :     tidstate->ss.ss_currentScanDesc = NULL; /* no heap scan here */
     532             : 
     533             :     /*
     534             :      * get the scan type from the relation descriptor.
     535             :      */
     536         472 :     ExecInitScanTupleSlot(estate, &tidstate->ss,
     537             :                           RelationGetDescr(currentRelation),
     538             :                           table_slot_callbacks(currentRelation));
     539             : 
     540             :     /*
     541             :      * Initialize result type and projection.
     542             :      */
     543         472 :     ExecInitResultTypeTL(&tidstate->ss.ps);
     544         472 :     ExecAssignScanProjectionInfo(&tidstate->ss);
     545             : 
     546             :     /*
     547             :      * initialize child expressions
     548             :      */
     549         472 :     tidstate->ss.ps.qual =
     550         472 :         ExecInitQual(node->scan.plan.qual, (PlanState *) tidstate);
     551             : 
     552         472 :     TidExprListCreate(tidstate);
     553             : 
     554             :     /*
     555             :      * all done.
     556             :      */
     557         472 :     return tidstate;
     558             : }

Generated by: LCOV version 1.13