1 /*-------------------------------------------------------------------------
4 * Support routines for sample scans of relations (table sampling).
6 * Portions Copyright (c) 1996-2017, 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 void InitScanRelation(SampleScanState *node, EState *estate, int eflags);
30 static TupleTableSlot *SampleNext(SampleScanState *node);
31 static void tablesample_init(SampleScanState *scanstate);
32 static HeapTuple tablesample_getnext(SampleScanState *scanstate);
33 static bool SampleTupleVisible(HeapTuple tuple, OffsetNumber tupoffset,
36 /* ----------------------------------------------------------------
38 * ----------------------------------------------------------------
41 /* ----------------------------------------------------------------
44 * This is a workhorse for ExecSampleScan
45 * ----------------------------------------------------------------
47 static TupleTableSlot *
48 SampleNext(SampleScanState *node)
54 * if this is first call within a scan, initialize
57 tablesample_init(node);
60 * get the next tuple, and store it in our result slot
62 tuple = tablesample_getnext(node);
64 slot = node->ss.ss_ScanTupleSlot;
67 ExecStoreTuple(tuple, /* tuple to store */
68 slot, /* slot to store in */
69 node->ss.ss_currentScanDesc->rs_cbuf, /* tuple's buffer */
70 false); /* don't pfree this pointer */
78 * SampleRecheck -- access method routine to recheck a tuple in EvalPlanQual
81 SampleRecheck(SampleScanState *node, TupleTableSlot *slot)
84 * No need to recheck for SampleScan, since like SeqScan we don't pass any
85 * checkable keys to heap_beginscan.
90 /* ----------------------------------------------------------------
91 * ExecSampleScan(node)
93 * Scans the relation using the sampling method and returns
94 * the next qualifying tuple.
95 * We call the ExecScan() routine and pass it the appropriate
96 * access method functions.
97 * ----------------------------------------------------------------
100 ExecSampleScan(SampleScanState *node)
102 return ExecScan((ScanState *) node,
103 (ExecScanAccessMtd) SampleNext,
104 (ExecScanRecheckMtd) SampleRecheck);
107 /* ----------------------------------------------------------------
110 * Set up to access the scan relation.
111 * ----------------------------------------------------------------
114 InitScanRelation(SampleScanState *node, EState *estate, int eflags)
116 Relation currentRelation;
119 * get the relation object id from the relid'th entry in the range table,
120 * open that relation and acquire appropriate lock on it.
122 currentRelation = ExecOpenScanRelation(estate,
123 ((SampleScan *) node->ss.ps.plan)->scan.scanrelid,
126 node->ss.ss_currentRelation = currentRelation;
128 /* we won't set up the HeapScanDesc till later */
129 node->ss.ss_currentScanDesc = NULL;
131 /* and report the scan tuple slot's rowtype */
132 ExecAssignScanType(&node->ss, RelationGetDescr(currentRelation));
136 /* ----------------------------------------------------------------
138 * ----------------------------------------------------------------
141 ExecInitSampleScan(SampleScan *node, EState *estate, int eflags)
143 SampleScanState *scanstate;
144 TableSampleClause *tsc = node->tablesample;
147 Assert(outerPlan(node) == NULL);
148 Assert(innerPlan(node) == NULL);
151 * create state structure
153 scanstate = makeNode(SampleScanState);
154 scanstate->ss.ps.plan = (Plan *) node;
155 scanstate->ss.ps.state = estate;
158 * Miscellaneous initialization
160 * create expression context for node
162 ExecAssignExprContext(estate, &scanstate->ss.ps);
165 * initialize child expressions
167 scanstate->ss.ps.qual =
168 ExecInitQual(node->scan.plan.qual, (PlanState *) scanstate);
170 scanstate->args = ExecInitExprList(tsc->args, (PlanState *) scanstate);
171 scanstate->repeatable =
172 ExecInitExpr(tsc->repeatable, (PlanState *) scanstate);
175 * tuple table initialization
177 ExecInitResultTupleSlot(estate, &scanstate->ss.ps);
178 ExecInitScanTupleSlot(estate, &scanstate->ss);
181 * initialize scan relation
183 InitScanRelation(scanstate, estate, eflags);
186 * Initialize result tuple type and projection info.
188 ExecAssignResultTypeFromTL(&scanstate->ss.ps);
189 ExecAssignScanProjectionInfo(&scanstate->ss);
192 * If we don't have a REPEATABLE clause, select a random seed. We want to
193 * do this just once, since the seed shouldn't change over rescans.
195 if (tsc->repeatable == NULL)
196 scanstate->seed = random();
199 * Finally, initialize the TABLESAMPLE method handler.
201 tsm = GetTsmRoutine(tsc->tsmhandler);
202 scanstate->tsmroutine = tsm;
203 scanstate->tsm_state = NULL;
205 if (tsm->InitSampleScan)
206 tsm->InitSampleScan(scanstate, eflags);
208 /* We'll do BeginSampleScan later; we can't evaluate params yet */
209 scanstate->begun = false;
214 /* ----------------------------------------------------------------
217 * frees any storage allocated through C routines.
218 * ----------------------------------------------------------------
221 ExecEndSampleScan(SampleScanState *node)
224 * Tell sampling function that we finished the scan.
226 if (node->tsmroutine->EndSampleScan)
227 node->tsmroutine->EndSampleScan(node);
230 * Free the exprcontext
232 ExecFreeExprContext(&node->ss.ps);
235 * clean out the tuple table
237 ExecClearTuple(node->ss.ps.ps_ResultTupleSlot);
238 ExecClearTuple(node->ss.ss_ScanTupleSlot);
243 if (node->ss.ss_currentScanDesc)
244 heap_endscan(node->ss.ss_currentScanDesc);
247 * close the heap relation.
249 ExecCloseScanRelation(node->ss.ss_currentRelation);
252 /* ----------------------------------------------------------------
253 * ExecReScanSampleScan
255 * Rescans the relation.
257 * ----------------------------------------------------------------
260 ExecReScanSampleScan(SampleScanState *node)
262 /* Remember we need to do BeginSampleScan again (if we did it at all) */
265 ExecScanReScan(&node->ss);
270 * Initialize the TABLESAMPLE method: evaluate params and call BeginSampleScan.
273 tablesample_init(SampleScanState *scanstate)
275 TsmRoutine *tsm = scanstate->tsmroutine;
276 ExprContext *econtext = scanstate->ss.ps.ps_ExprContext;
285 params = (Datum *) palloc(list_length(scanstate->args) * sizeof(Datum));
288 foreach(arg, scanstate->args)
290 ExprState *argstate = (ExprState *) lfirst(arg);
292 params[i] = ExecEvalExprSwitchContext(argstate,
297 (errcode(ERRCODE_INVALID_TABLESAMPLE_ARGUMENT),
298 errmsg("TABLESAMPLE parameter cannot be null")));
302 if (scanstate->repeatable)
304 datum = ExecEvalExprSwitchContext(scanstate->repeatable,
309 (errcode(ERRCODE_INVALID_TABLESAMPLE_REPEAT),
310 errmsg("TABLESAMPLE REPEATABLE parameter cannot be null")));
313 * The REPEATABLE parameter has been coerced to float8 by the parser.
314 * The reason for using float8 at the SQL level is that it will
315 * produce unsurprising results both for users used to databases that
316 * accept only integers in the REPEATABLE clause and for those who
317 * might expect that REPEATABLE works like setseed() (a float in the
318 * range from -1 to 1).
320 * We use hashfloat8() to convert the supplied value into a suitable
321 * seed. For regression-testing purposes, that has the convenient
322 * property that REPEATABLE(0) gives a machine-independent result.
324 seed = DatumGetUInt32(DirectFunctionCall1(hashfloat8, datum));
328 /* Use the seed selected by ExecInitSampleScan */
329 seed = scanstate->seed;
332 /* Set default values for params that BeginSampleScan can adjust */
333 scanstate->use_bulkread = true;
334 scanstate->use_pagemode = true;
336 /* Let tablesample method do its thing */
337 tsm->BeginSampleScan(scanstate,
339 list_length(scanstate->args),
342 /* We'll use syncscan if there's no NextSampleBlock function */
343 allow_sync = (tsm->NextSampleBlock == NULL);
345 /* Now we can create or reset the HeapScanDesc */
346 if (scanstate->ss.ss_currentScanDesc == NULL)
348 scanstate->ss.ss_currentScanDesc =
349 heap_beginscan_sampling(scanstate->ss.ss_currentRelation,
350 scanstate->ss.ps.state->es_snapshot,
352 scanstate->use_bulkread,
354 scanstate->use_pagemode);
358 heap_rescan_set_params(scanstate->ss.ss_currentScanDesc, NULL,
359 scanstate->use_bulkread,
361 scanstate->use_pagemode);
366 /* And we're initialized. */
367 scanstate->begun = true;
371 * Get next tuple from TABLESAMPLE method.
373 * Note: an awful lot of this is copied-and-pasted from heapam.c. It would
374 * perhaps be better to refactor to share more code.
377 tablesample_getnext(SampleScanState *scanstate)
379 TsmRoutine *tsm = scanstate->tsmroutine;
380 HeapScanDesc scan = scanstate->ss.ss_currentScanDesc;
381 HeapTuple tuple = &(scan->rs_ctup);
382 Snapshot snapshot = scan->rs_snapshot;
383 bool pagemode = scan->rs_pageatatime;
387 OffsetNumber maxoffset;
389 if (!scan->rs_inited)
392 * return null immediately if relation is empty
394 if (scan->rs_nblocks == 0)
396 Assert(!BufferIsValid(scan->rs_cbuf));
397 tuple->t_data = NULL;
400 if (tsm->NextSampleBlock)
402 blockno = tsm->NextSampleBlock(scanstate);
403 if (!BlockNumberIsValid(blockno))
405 tuple->t_data = NULL;
410 blockno = scan->rs_startblock;
411 Assert(blockno < scan->rs_nblocks);
412 heapgetpage(scan, blockno);
413 scan->rs_inited = true;
417 /* continue from previously returned page/tuple */
418 blockno = scan->rs_cblock; /* current page */
422 * When not using pagemode, we must lock the buffer during tuple
426 LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
428 page = (Page) BufferGetPage(scan->rs_cbuf);
429 all_visible = PageIsAllVisible(page) && !snapshot->takenDuringRecovery;
430 maxoffset = PageGetMaxOffsetNumber(page);
434 OffsetNumber tupoffset;
437 CHECK_FOR_INTERRUPTS();
439 /* Ask the tablesample method which tuples to check on this page. */
440 tupoffset = tsm->NextSampleTuple(scanstate,
444 if (OffsetNumberIsValid(tupoffset))
449 /* Skip invalid tuple pointers. */
450 itemid = PageGetItemId(page, tupoffset);
451 if (!ItemIdIsNormal(itemid))
454 tuple->t_data = (HeapTupleHeader) PageGetItem(page, itemid);
455 tuple->t_len = ItemIdGetLength(itemid);
456 ItemPointerSet(&(tuple->t_self), blockno, tupoffset);
461 visible = SampleTupleVisible(tuple, tupoffset, scan);
463 /* in pagemode, heapgetpage did this for us */
465 CheckForSerializableConflictOut(visible, scan->rs_rd, tuple,
466 scan->rs_cbuf, snapshot);
470 /* Found visible tuple, return it. */
472 LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
477 /* Try next tuple from same page. */
483 * if we get here, it means we've exhausted the items on this page and
484 * it's time to move to the next.
487 LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
489 if (tsm->NextSampleBlock)
491 blockno = tsm->NextSampleBlock(scanstate);
492 Assert(!scan->rs_syncscan);
493 finished = !BlockNumberIsValid(blockno);
497 /* Without NextSampleBlock, just do a plain forward seqscan. */
499 if (blockno >= scan->rs_nblocks)
503 * Report our new scan position for synchronization purposes.
505 * Note: we do this before checking for end of scan so that the
506 * final state of the position hint is back at the start of the
507 * rel. That's not strictly necessary, but otherwise when you run
508 * the same query multiple times the starting position would shift
509 * a little bit backwards on every invocation, which is confusing.
510 * We don't guarantee any specific ordering in general, though.
512 if (scan->rs_syncscan)
513 ss_report_location(scan->rs_rd, blockno);
515 finished = (blockno == scan->rs_startblock);
519 * Reached end of scan?
523 if (BufferIsValid(scan->rs_cbuf))
524 ReleaseBuffer(scan->rs_cbuf);
525 scan->rs_cbuf = InvalidBuffer;
526 scan->rs_cblock = InvalidBlockNumber;
527 tuple->t_data = NULL;
528 scan->rs_inited = false;
532 Assert(blockno < scan->rs_nblocks);
533 heapgetpage(scan, blockno);
535 /* Re-establish state for new page */
537 LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
539 page = (Page) BufferGetPage(scan->rs_cbuf);
540 all_visible = PageIsAllVisible(page) && !snapshot->takenDuringRecovery;
541 maxoffset = PageGetMaxOffsetNumber(page);
544 /* Count successfully-fetched tuples as heap fetches */
545 pgstat_count_heap_getnext(scan->rs_rd);
547 return &(scan->rs_ctup);
551 * Check visibility of the tuple.
554 SampleTupleVisible(HeapTuple tuple, OffsetNumber tupoffset, HeapScanDesc scan)
556 if (scan->rs_pageatatime)
559 * In pageatatime mode, heapgetpage() already did visibility checks,
560 * so just look at the info it left in rs_vistuples[].
562 * We use a binary search over the known-sorted array. Note: we could
563 * save some effort if we insisted that NextSampleTuple select tuples
564 * in increasing order, but it's not clear that there would be enough
565 * gain to justify the restriction.
568 end = scan->rs_ntuples - 1;
572 int mid = (start + end) / 2;
573 OffsetNumber curoffset = scan->rs_vistuples[mid];
575 if (tupoffset == curoffset)
577 else if (tupoffset < curoffset)
587 /* Otherwise, we have to check the tuple individually. */
588 return HeapTupleSatisfiesVisibility(tuple,