1/*-------------------------------------------------------------------------
4 * support routines for SYSTEM_TIME tablesample method
6 * The desire here is to produce a random sample with as many rows as possible
7 * in no more than the specified amount of time. We use a block-sampling
8 * approach. To ensure that the whole relation will be visited if necessary,
9 * we start at a randomly chosen block and then advance with a stride that
10 * is randomly chosen but is relatively prime to the relation's nblocks.
12 * Because of the time dependence, this method is necessarily unrepeatable.
13 * However, we do what we can to reduce surprising behavior by selecting
14 * the sampling pattern just once per query, much as in tsm_system_rows.
16 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
17 * Portions Copyright (c) 1994, Regents of the University of California
20 * contrib/tsm_system_time/tsm_system_time.c
22 *-------------------------------------------------------------------------
37 .
name =
"tsm_system_time",
48 double millis;
/* time limit for sampling */
53 /* these three values are not changed during a rescan: */
78 * Create a TsmRoutine descriptor for the SYSTEM_TIME method.
87 /* See notes at head of file */
102 * Sample size estimation.
113 double spc_random_page_cost;
117 /* Try to extract an estimate for the limit time spec */
122 !((
Const *) limitnode)->constisnull)
125 if (millis < 0 || isnan(millis))
127 /* Default millis if the value is bogus */
133 /* Default millis if we didn't obtain a non-null Const */
137 /* Get the planner's idea of cost per page read */
139 &spc_random_page_cost,
143 * Estimate the number of pages we can read by assuming that the cost
144 * figure is expressed in milliseconds. This is completely, unmistakably
145 * bogus, but we have to do something to produce an estimate and there's
148 if (spc_random_page_cost > 0)
149 npages = millis / spc_random_page_cost;
151 npages = millis;
/* even more bogus, but whatcha gonna do? */
153 /* Clamp to sane value */
158 /* Estimate number of tuples returned based on tuple density */
159 double density = baserel->
tuples / (double) baserel->
pages;
161 ntuples = npages * density;
165 /* For lack of data, assume one tuple per page */
169 /* Clamp to the estimated relation size */
177 * Initialize during executor setup.
183 /* Note the above leaves tsm_state->step equal to zero */
187 * Examine parameters and prepare for a sample scan.
198 if (millis < 0 || isnan(millis))
200 (
errcode(ERRCODE_INVALID_TABLESAMPLE_ARGUMENT),
201 errmsg(
"sample collection time must not be negative")));
203 sampler->
seed = seed;
207 /* start_time, lb will be initialized during first NextSampleBlock call */
208 /* we intentionally do not change nblocks/firstblock/step here */
212 * Select next block to sample.
214 * Uses linear probing algorithm for picking next block.
222 /* First call within scan? */
225 /* First scan within query? */
226 if (sampler->
step == 0)
228 /* Initialize now that we have scan descriptor */
231 /* If relation is empty, there's nothing to scan */
235 /* We only need an RNG during this setup step */
238 /* Compute nblocks/firstblock/step only once per query */
241 /* Choose random starting block within the relation */
242 /* (Actually this is the predecessor of the first block visited) */
246 /* Find relative prime as step size for linear probing */
250 /* Reinitialize lb and start_time */
255 /* If we've read all blocks in relation, we're done */
259 /* If we've used up all the allotted time, we're done */
266 * It's probably impossible for scan->rs_nblocks to decrease between scans
267 * within a query; but just in case, loop until we select a block number
268 * less than scan->rs_nblocks. We don't care if scan->rs_nblocks has
269 * increased since the first scan.
273 /* Advance lb, using uint64 arithmetic to forestall overflow */
275 }
while (sampler->
lb >= nblocks);
281 * Select next sampled tuple in current block.
283 * In block sampling, we just want to sample all the tuples in each selected
286 * When we reach end of the block, return InvalidOffsetNumber which tells
287 * SampleScan to go to next block.
297 /* Advance to next possible offset on page */
304 if (tupoffset > maxoffset)
307 sampler->
lt = tupoffset;
313 * Compute greatest common divisor of two uint32's.
331 * Pick a random value less than and relatively prime to n, if possible
339 /* Safety check to avoid infinite loop or zero result for small n. */
344 * This should only take 2 or 3 iterations as the probability of 2 numbers
345 * being relatively prime is ~61%; but just in case, we'll include a
346 * CHECK_FOR_INTERRUPTS in the loop.
352 }
while (r == 0 ||
gcd(r, n) > 1);
#define InvalidBlockNumber
Node * estimate_expression_value(PlannerInfo *root, Node *node)
double clamp_row_est(double nrows)
int errcode(int sqlerrcode)
int errmsg(const char *fmt,...)
#define ereport(elevel,...)
#define PG_RETURN_POINTER(x)
#define INSTR_TIME_SET_CURRENT(t)
#define INSTR_TIME_SUBTRACT(x, y)
#define INSTR_TIME_GET_MILLISEC(t)
if(TABLE==NULL||TABLE_index==NULL)
void * palloc0(Size size)
#define CHECK_FOR_INTERRUPTS()
#define IsA(nodeptr, _type_)
#define InvalidOffsetNumber
#define FirstOffsetNumber
#define list_make1_oid(x1)
static float8 DatumGetFloat8(Datum X)
double sampler_random_fract(pg_prng_state *randstate)
void sampler_random_init_state(uint32 seed, pg_prng_state *randstate)
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
NextSampleTuple_function NextSampleTuple
bool repeatable_across_scans
EndSampleScan_function EndSampleScan
SampleScanGetSampleSize_function SampleScanGetSampleSize
BeginSampleScan_function BeginSampleScan
NextSampleBlock_function NextSampleBlock
InitSampleScan_function InitSampleScan
bool repeatable_across_queries
Datum tsm_system_time_handler(PG_FUNCTION_ARGS)
static void system_time_samplescangetsamplesize(PlannerInfo *root, RelOptInfo *baserel, List *paramexprs, BlockNumber *pages, double *tuples)
static uint32 random_relative_prime(uint32 n, pg_prng_state *randstate)
PG_FUNCTION_INFO_V1(tsm_system_time_handler)
PG_MODULE_MAGIC_EXT(.name="tsm_system_time",.version=PG_VERSION)
static void system_time_beginsamplescan(SampleScanState *node, Datum *params, int nparams, uint32 seed)
static uint32 gcd(uint32 a, uint32 b)
static void system_time_initsamplescan(SampleScanState *node, int eflags)
static OffsetNumber system_time_nextsampletuple(SampleScanState *node, BlockNumber blockno, OffsetNumber maxoffset)
static BlockNumber system_time_nextsampleblock(SampleScanState *node, BlockNumber nblocks)