1 /*-------------------------------------------------------------------------
4 * Support routines for sample scans of relations (table sampling).
6 * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/executor/nodeSamplescan.c
13 *-------------------------------------------------------------------------
17 #include "access/hash.h"
18 #include "access/relscan.h"
19 #include "access/tsmapi.h"
20 #include "executor/executor.h"
21 #include "executor/nodeSamplescan.h"
22 #include "miscadmin.h"
24 #include "storage/predicate.h"
25 #include "utils/builtins.h"
26 #include "utils/rel.h"
27 #include "utils/tqual.h"
29 static TupleTableSlot *SampleNext(SampleScanState *node);
30 static void tablesample_init(SampleScanState *scanstate);
31 static HeapTuple tablesample_getnext(SampleScanState *scanstate);
32 static bool SampleTupleVisible(HeapTuple tuple, OffsetNumber tupoffset,
35 /* ----------------------------------------------------------------
37 * ----------------------------------------------------------------
40 /* ----------------------------------------------------------------
43 * This is a workhorse for ExecSampleScan
44 * ----------------------------------------------------------------
46 static TupleTableSlot *
47 SampleNext(SampleScanState *node)
53 * if this is first call within a scan, initialize
56 tablesample_init(node);
59 * get the next tuple, and store it in our result slot
61 tuple = tablesample_getnext(node);
63 slot = node->ss.ss_ScanTupleSlot;
66 ExecStoreBufferHeapTuple(tuple, /* tuple to store */
67 slot, /* slot to store in */
68 node->ss.ss_currentScanDesc->rs_cbuf); /* tuple's buffer */
76 * SampleRecheck -- access method routine to recheck a tuple in EvalPlanQual
79 SampleRecheck(SampleScanState *node, TupleTableSlot *slot)
82 * No need to recheck for SampleScan, since like SeqScan we don't pass any
83 * checkable keys to heap_beginscan.
88 /* ----------------------------------------------------------------
89 * ExecSampleScan(node)
91 * Scans the relation using the sampling method and returns
92 * the next qualifying tuple.
93 * We call the ExecScan() routine and pass it the appropriate
94 * access method functions.
95 * ----------------------------------------------------------------
97 static TupleTableSlot *
98 ExecSampleScan(PlanState *pstate)
100 SampleScanState *node = castNode(SampleScanState, pstate);
102 return ExecScan(&node->ss,
103 (ExecScanAccessMtd) SampleNext,
104 (ExecScanRecheckMtd) SampleRecheck);
107 /* ----------------------------------------------------------------
109 * ----------------------------------------------------------------
112 ExecInitSampleScan(SampleScan *node, EState *estate, int eflags)
114 SampleScanState *scanstate;
115 TableSampleClause *tsc = node->tablesample;
118 Assert(outerPlan(node) == NULL);
119 Assert(innerPlan(node) == NULL);
122 * create state structure
124 scanstate = makeNode(SampleScanState);
125 scanstate->ss.ps.plan = (Plan *) node;
126 scanstate->ss.ps.state = estate;
127 scanstate->ss.ps.ExecProcNode = ExecSampleScan;
130 * Miscellaneous initialization
132 * create expression context for node
134 ExecAssignExprContext(estate, &scanstate->ss.ps);
137 * open the scan relation
139 scanstate->ss.ss_currentRelation =
140 ExecOpenScanRelation(estate,
141 node->scan.scanrelid,
144 /* we won't set up the HeapScanDesc till later */
145 scanstate->ss.ss_currentScanDesc = NULL;
147 /* and create slot with appropriate rowtype */
148 ExecInitScanTupleSlot(estate, &scanstate->ss,
149 RelationGetDescr(scanstate->ss.ss_currentRelation),
150 &TTSOpsBufferHeapTuple);
153 * Initialize result type and projection.
155 ExecInitResultTypeTL(&scanstate->ss.ps);
156 ExecAssignScanProjectionInfo(&scanstate->ss);
159 * initialize child expressions
161 scanstate->ss.ps.qual =
162 ExecInitQual(node->scan.plan.qual, (PlanState *) scanstate);
164 scanstate->args = ExecInitExprList(tsc->args, (PlanState *) scanstate);
165 scanstate->repeatable =
166 ExecInitExpr(tsc->repeatable, (PlanState *) scanstate);
169 * If we don't have a REPEATABLE clause, select a random seed. We want to
170 * do this just once, since the seed shouldn't change over rescans.
172 if (tsc->repeatable == NULL)
173 scanstate->seed = random();
176 * Finally, initialize the TABLESAMPLE method handler.
178 tsm = GetTsmRoutine(tsc->tsmhandler);
179 scanstate->tsmroutine = tsm;
180 scanstate->tsm_state = NULL;
182 if (tsm->InitSampleScan)
183 tsm->InitSampleScan(scanstate, eflags);
185 /* We'll do BeginSampleScan later; we can't evaluate params yet */
186 scanstate->begun = false;
191 /* ----------------------------------------------------------------
194 * frees any storage allocated through C routines.
195 * ----------------------------------------------------------------
198 ExecEndSampleScan(SampleScanState *node)
201 * Tell sampling function that we finished the scan.
203 if (node->tsmroutine->EndSampleScan)
204 node->tsmroutine->EndSampleScan(node);
207 * Free the exprcontext
209 ExecFreeExprContext(&node->ss.ps);
212 * clean out the tuple table
214 if (node->ss.ps.ps_ResultTupleSlot)
215 ExecClearTuple(node->ss.ps.ps_ResultTupleSlot);
216 ExecClearTuple(node->ss.ss_ScanTupleSlot);
221 if (node->ss.ss_currentScanDesc)
222 heap_endscan(node->ss.ss_currentScanDesc);
225 /* ----------------------------------------------------------------
226 * ExecReScanSampleScan
228 * Rescans the relation.
230 * ----------------------------------------------------------------
233 ExecReScanSampleScan(SampleScanState *node)
235 /* Remember we need to do BeginSampleScan again (if we did it at all) */
238 ExecScanReScan(&node->ss);
243 * Initialize the TABLESAMPLE method: evaluate params and call BeginSampleScan.
246 tablesample_init(SampleScanState *scanstate)
248 TsmRoutine *tsm = scanstate->tsmroutine;
249 ExprContext *econtext = scanstate->ss.ps.ps_ExprContext;
258 params = (Datum *) palloc(list_length(scanstate->args) * sizeof(Datum));
261 foreach(arg, scanstate->args)
263 ExprState *argstate = (ExprState *) lfirst(arg);
265 params[i] = ExecEvalExprSwitchContext(argstate,
270 (errcode(ERRCODE_INVALID_TABLESAMPLE_ARGUMENT),
271 errmsg("TABLESAMPLE parameter cannot be null")));
275 if (scanstate->repeatable)
277 datum = ExecEvalExprSwitchContext(scanstate->repeatable,
282 (errcode(ERRCODE_INVALID_TABLESAMPLE_REPEAT),
283 errmsg("TABLESAMPLE REPEATABLE parameter cannot be null")));
286 * The REPEATABLE parameter has been coerced to float8 by the parser.
287 * The reason for using float8 at the SQL level is that it will
288 * produce unsurprising results both for users used to databases that
289 * accept only integers in the REPEATABLE clause and for those who
290 * might expect that REPEATABLE works like setseed() (a float in the
291 * range from -1 to 1).
293 * We use hashfloat8() to convert the supplied value into a suitable
294 * seed. For regression-testing purposes, that has the convenient
295 * property that REPEATABLE(0) gives a machine-independent result.
297 seed = DatumGetUInt32(DirectFunctionCall1(hashfloat8, datum));
301 /* Use the seed selected by ExecInitSampleScan */
302 seed = scanstate->seed;
305 /* Set default values for params that BeginSampleScan can adjust */
306 scanstate->use_bulkread = true;
307 scanstate->use_pagemode = true;
309 /* Let tablesample method do its thing */
310 tsm->BeginSampleScan(scanstate,
312 list_length(scanstate->args),
315 /* We'll use syncscan if there's no NextSampleBlock function */
316 allow_sync = (tsm->NextSampleBlock == NULL);
318 /* Now we can create or reset the HeapScanDesc */
319 if (scanstate->ss.ss_currentScanDesc == NULL)
321 scanstate->ss.ss_currentScanDesc =
322 heap_beginscan_sampling(scanstate->ss.ss_currentRelation,
323 scanstate->ss.ps.state->es_snapshot,
325 scanstate->use_bulkread,
327 scanstate->use_pagemode);
331 heap_rescan_set_params(scanstate->ss.ss_currentScanDesc, NULL,
332 scanstate->use_bulkread,
334 scanstate->use_pagemode);
339 /* And we're initialized. */
340 scanstate->begun = true;
344 * Get next tuple from TABLESAMPLE method.
346 * Note: an awful lot of this is copied-and-pasted from heapam.c. It would
347 * perhaps be better to refactor to share more code.
350 tablesample_getnext(SampleScanState *scanstate)
352 TsmRoutine *tsm = scanstate->tsmroutine;
353 HeapScanDesc scan = scanstate->ss.ss_currentScanDesc;
354 HeapTuple tuple = &(scan->rs_ctup);
355 Snapshot snapshot = scan->rs_snapshot;
356 bool pagemode = scan->rs_pageatatime;
360 OffsetNumber maxoffset;
362 if (!scan->rs_inited)
365 * return null immediately if relation is empty
367 if (scan->rs_nblocks == 0)
369 Assert(!BufferIsValid(scan->rs_cbuf));
370 tuple->t_data = NULL;
373 if (tsm->NextSampleBlock)
375 blockno = tsm->NextSampleBlock(scanstate);
376 if (!BlockNumberIsValid(blockno))
378 tuple->t_data = NULL;
383 blockno = scan->rs_startblock;
384 Assert(blockno < scan->rs_nblocks);
385 heapgetpage(scan, blockno);
386 scan->rs_inited = true;
390 /* continue from previously returned page/tuple */
391 blockno = scan->rs_cblock; /* current page */
395 * When not using pagemode, we must lock the buffer during tuple
399 LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
401 page = (Page) BufferGetPage(scan->rs_cbuf);
402 all_visible = PageIsAllVisible(page) && !snapshot->takenDuringRecovery;
403 maxoffset = PageGetMaxOffsetNumber(page);
407 OffsetNumber tupoffset;
410 CHECK_FOR_INTERRUPTS();
412 /* Ask the tablesample method which tuples to check on this page. */
413 tupoffset = tsm->NextSampleTuple(scanstate,
417 if (OffsetNumberIsValid(tupoffset))
422 /* Skip invalid tuple pointers. */
423 itemid = PageGetItemId(page, tupoffset);
424 if (!ItemIdIsNormal(itemid))
427 tuple->t_data = (HeapTupleHeader) PageGetItem(page, itemid);
428 tuple->t_len = ItemIdGetLength(itemid);
429 ItemPointerSet(&(tuple->t_self), blockno, tupoffset);
434 visible = SampleTupleVisible(tuple, tupoffset, scan);
436 /* in pagemode, heapgetpage did this for us */
438 CheckForSerializableConflictOut(visible, scan->rs_rd, tuple,
439 scan->rs_cbuf, snapshot);
443 /* Found visible tuple, return it. */
445 LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
450 /* Try next tuple from same page. */
456 * if we get here, it means we've exhausted the items on this page and
457 * it's time to move to the next.
460 LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
462 if (tsm->NextSampleBlock)
464 blockno = tsm->NextSampleBlock(scanstate);
465 Assert(!scan->rs_syncscan);
466 finished = !BlockNumberIsValid(blockno);
470 /* Without NextSampleBlock, just do a plain forward seqscan. */
472 if (blockno >= scan->rs_nblocks)
476 * Report our new scan position for synchronization purposes.
478 * Note: we do this before checking for end of scan so that the
479 * final state of the position hint is back at the start of the
480 * rel. That's not strictly necessary, but otherwise when you run
481 * the same query multiple times the starting position would shift
482 * a little bit backwards on every invocation, which is confusing.
483 * We don't guarantee any specific ordering in general, though.
485 if (scan->rs_syncscan)
486 ss_report_location(scan->rs_rd, blockno);
488 finished = (blockno == scan->rs_startblock);
492 * Reached end of scan?
496 if (BufferIsValid(scan->rs_cbuf))
497 ReleaseBuffer(scan->rs_cbuf);
498 scan->rs_cbuf = InvalidBuffer;
499 scan->rs_cblock = InvalidBlockNumber;
500 tuple->t_data = NULL;
501 scan->rs_inited = false;
505 Assert(blockno < scan->rs_nblocks);
506 heapgetpage(scan, blockno);
508 /* Re-establish state for new page */
510 LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
512 page = (Page) BufferGetPage(scan->rs_cbuf);
513 all_visible = PageIsAllVisible(page) && !snapshot->takenDuringRecovery;
514 maxoffset = PageGetMaxOffsetNumber(page);
517 /* Count successfully-fetched tuples as heap fetches */
518 pgstat_count_heap_getnext(scan->rs_rd);
520 return &(scan->rs_ctup);
524 * Check visibility of the tuple.
527 SampleTupleVisible(HeapTuple tuple, OffsetNumber tupoffset, HeapScanDesc scan)
529 if (scan->rs_pageatatime)
532 * In pageatatime mode, heapgetpage() already did visibility checks,
533 * so just look at the info it left in rs_vistuples[].
535 * We use a binary search over the known-sorted array. Note: we could
536 * save some effort if we insisted that NextSampleTuple select tuples
537 * in increasing order, but it's not clear that there would be enough
538 * gain to justify the restriction.
541 end = scan->rs_ntuples - 1;
545 int mid = (start + end) / 2;
546 OffsetNumber curoffset = scan->rs_vistuples[mid];
548 if (tupoffset == curoffset)
550 else if (tupoffset < curoffset)
560 /* Otherwise, we have to check the tuple individually. */
561 return HeapTupleSatisfiesVisibility(tuple,