1
/*-------------------------------------------------------------------------
4
* Selectivity functions and index cost estimation functions for
5
* standard operators and index access methods.
7
* Selectivity routines are registered in the pg_operator catalog
8
* in the "oprrest" and "oprjoin" attributes.
10
* Index cost functions are registered in the pg_am catalog
11
* in the "amcostestimate" attribute.
13
* Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
14
* Portions Copyright (c) 1994, Regents of the University of California
18
* src/backend/utils/adt/selfuncs.c
20
*-------------------------------------------------------------------------
24
* Operator selectivity estimation functions are called to estimate the
25
* selectivity of WHERE clauses whose top-level operator is their operator.
26
* We divide the problem into two cases:
27
* Restriction clause estimation: the clause involves vars of just
29
* Join clause estimation: the clause involves vars of multiple rels.
30
* Join selectivity estimation is far more difficult and usually less accurate
31
* than restriction estimation.
33
* When dealing with the inner scan of a nestloop join, we consider the
34
* join's joinclauses as restriction clauses for the inner relation, and
35
* treat vars of the outer relation as parameters (a/k/a constants of unknown
36
* values). So, restriction estimators need to be able to accept an argument
37
* telling which relation is to be treated as the variable.
39
* The call convention for a restriction estimator (oprrest function) is
41
* Selectivity oprrest (PlannerInfo *root,
46
* root: general information about the query (rtable and RelOptInfo lists
47
* are particularly important for the estimator).
48
* operator: OID of the specific operator in question.
49
* args: argument list from the operator clause.
50
* varRelid: if not zero, the relid (rtable index) of the relation to
51
* be treated as the variable relation. May be zero if the args list
52
* is known to contain vars of only one relation.
54
* This is represented at the SQL level (in pg_proc) as
56
* float8 oprrest (internal, oid, internal, int4);
58
* The result is a selectivity, that is, a fraction (0 to 1) of the rows
59
* of the relation that are expected to produce a TRUE result for the
62
* The call convention for a join estimator (oprjoin function) is similar
63
* except that varRelid is not needed, and instead join information is
66
* Selectivity oprjoin (PlannerInfo *root,
70
* SpecialJoinInfo *sjinfo);
72
* float8 oprjoin (internal, oid, internal, int2, internal);
74
* (Before Postgres 8.4, join estimators had only the first four of these
75
* parameters. That signature is still allowed, but deprecated.) The
76
* relationship between jointype and sjinfo is explained in the comments for
77
* clause_selectivity() --- the short version is that jointype is usually
78
* best ignored in favor of examining sjinfo.
80
* Join selectivity for regular inner and outer joins is defined as the
81
* fraction (0 to 1) of the cross product of the relations that is expected
82
* to produce a TRUE result for the given operator. For both semi and anti
83
* joins, however, the selectivity is defined as the fraction of the left-hand
84
* side relation's rows that are expected to have a match (ie, at least one
85
* row with a TRUE result) in the right-hand side.
94
#include "access/gin.h"
95
#include "access/sysattr.h"
96
#include "catalog/index.h"
97
#include "catalog/pg_collation.h"
98
#include "catalog/pg_opfamily.h"
99
#include "catalog/pg_statistic.h"
100
#include "catalog/pg_type.h"
101
#include "executor/executor.h"
102
#include "mb/pg_wchar.h"
103
#include "nodes/makefuncs.h"
104
#include "nodes/nodeFuncs.h"
105
#include "optimizer/clauses.h"
106
#include "optimizer/cost.h"
107
#include "optimizer/pathnode.h"
108
#include "optimizer/paths.h"
109
#include "optimizer/plancat.h"
110
#include "optimizer/predtest.h"
111
#include "optimizer/restrictinfo.h"
112
#include "optimizer/var.h"
113
#include "parser/parse_coerce.h"
114
#include "parser/parsetree.h"
115
#include "utils/builtins.h"
116
#include "utils/bytea.h"
117
#include "utils/date.h"
118
#include "utils/datum.h"
119
#include "utils/fmgroids.h"
120
#include "utils/lsyscache.h"
121
#include "utils/nabstime.h"
122
#include "utils/pg_locale.h"
123
#include "utils/selfuncs.h"
124
#include "utils/spccache.h"
125
#include "utils/syscache.h"
126
#include "utils/tqual.h"
129
/* Hooks for plugins to get control when we ask for stats */
130
get_relation_stats_hook_type get_relation_stats_hook = NULL;
131
get_index_stats_hook_type get_index_stats_hook = NULL;
133
static double var_eq_const(VariableStatData *vardata, Oid operator,
134
Datum constval, bool constisnull,
136
static double var_eq_non_const(VariableStatData *vardata, Oid operator,
139
static double ineq_histogram_selectivity(PlannerInfo *root,
140
VariableStatData *vardata,
141
FmgrInfo *opproc, bool isgt,
142
Datum constval, Oid consttype);
143
static double eqjoinsel_inner(Oid operator,
144
VariableStatData *vardata1, VariableStatData *vardata2);
145
static double eqjoinsel_semi(Oid operator,
146
VariableStatData *vardata1, VariableStatData *vardata2);
147
static bool convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue,
148
Datum lobound, Datum hibound, Oid boundstypid,
149
double *scaledlobound, double *scaledhibound);
150
static double convert_numeric_to_scalar(Datum value, Oid typid);
151
static void convert_string_to_scalar(char *value,
154
double *scaledlobound,
156
double *scaledhibound);
157
static void convert_bytea_to_scalar(Datum value,
160
double *scaledlobound,
162
double *scaledhibound);
163
static double convert_one_string_to_scalar(char *value,
164
int rangelo, int rangehi);
165
static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
166
int rangelo, int rangehi);
167
static char *convert_string_datum(Datum value, Oid typid);
168
static double convert_timevalue_to_scalar(Datum value, Oid typid);
169
static bool get_variable_range(PlannerInfo *root, VariableStatData *vardata,
170
Oid sortop, Datum *min, Datum *max);
171
static bool get_actual_variable_range(PlannerInfo *root,
172
VariableStatData *vardata,
174
Datum *min, Datum *max);
175
static Selectivity prefix_selectivity(PlannerInfo *root,
176
VariableStatData *vardata,
177
Oid vartype, Oid opfamily, Const *prefixcon);
178
static Selectivity pattern_selectivity(Const *patt, Pattern_Type ptype);
179
static Datum string_to_datum(const char *str, Oid datatype);
180
static Const *string_to_const(const char *str, Oid datatype);
181
static Const *string_to_bytea_const(const char *str, size_t str_len);
185
* eqsel - Selectivity of "=" for any data types.
187
* Note: this routine is also used to estimate selectivity for some
188
* operators that are not "=" but have comparable selectivity behavior,
189
* such as "~=" (geometric approximate-match). Even for "=", we must
190
* keep in mind that the left and right datatypes may differ.
193
eqsel(PG_FUNCTION_ARGS)
195
PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
196
Oid operator = PG_GETARG_OID(1);
197
List *args = (List *) PG_GETARG_POINTER(2);
198
int varRelid = PG_GETARG_INT32(3);
199
VariableStatData vardata;
205
* If expression is not variable = something or something = variable, then
206
* punt and return a default estimate.
208
if (!get_restriction_variable(root, args, varRelid,
209
&vardata, &other, &varonleft))
210
PG_RETURN_FLOAT8(DEFAULT_EQ_SEL);
213
* We can do a lot better if the something is a constant. (Note: the
214
* Const might result from estimation rather than being a simple constant
217
if (IsA(other, Const))
218
selec = var_eq_const(&vardata, operator,
219
((Const *) other)->constvalue,
220
((Const *) other)->constisnull,
223
selec = var_eq_non_const(&vardata, operator, other,
226
ReleaseVariableStats(vardata);
228
PG_RETURN_FLOAT8((float8) selec);
232
* var_eq_const --- eqsel for var = const case
234
* This is split out so that some other estimation functions can use it.
237
var_eq_const(VariableStatData *vardata, Oid operator,
238
Datum constval, bool constisnull,
244
* If the constant is NULL, assume operator is strict and return zero, ie,
245
* operator will never return TRUE.
251
* If we matched the var to a unique index, assume there is exactly one
252
* match regardless of anything else. (This is slightly bogus, since the
253
* index's equality operator might be different from ours, but it's more
254
* likely to be right than ignoring the information.)
256
if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
257
return 1.0 / vardata->rel->tuples;
259
if (HeapTupleIsValid(vardata->statsTuple))
261
Form_pg_statistic stats;
269
stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
272
* Is the constant "=" to any of the column's most common values?
273
* (Although the given operator may not really be "=", we will assume
274
* that seeing whether it returns TRUE is an appropriate test. If you
275
* don't like this, maybe you shouldn't be using eqsel for your
278
if (get_attstatsslot(vardata->statsTuple,
279
vardata->atttype, vardata->atttypmod,
280
STATISTIC_KIND_MCV, InvalidOid,
283
&numbers, &nnumbers))
287
fmgr_info(get_opcode(operator), &eqproc);
289
for (i = 0; i < nvalues; i++)
291
/* be careful to apply operator right way 'round */
293
match = DatumGetBool(FunctionCall2Coll(&eqproc,
294
DEFAULT_COLLATION_OID,
298
match = DatumGetBool(FunctionCall2Coll(&eqproc,
299
DEFAULT_COLLATION_OID,
308
/* no most-common-value info available */
311
i = nvalues = nnumbers = 0;
317
* Constant is "=" to this common value. We know selectivity
318
* exactly (or as exactly as ANALYZE could calculate it, anyway).
325
* Comparison is against a constant that is neither NULL nor any
326
* of the common values. Its selectivity cannot be more than
329
double sumcommon = 0.0;
330
double otherdistinct;
332
for (i = 0; i < nnumbers; i++)
333
sumcommon += numbers[i];
334
selec = 1.0 - sumcommon - stats->stanullfrac;
335
CLAMP_PROBABILITY(selec);
338
* and in fact it's probably a good deal less. We approximate that
339
* all the not-common values share this remaining fraction
340
* equally, so we divide by the number of other distinct values.
342
otherdistinct = get_variable_numdistinct(vardata) - nnumbers;
343
if (otherdistinct > 1)
344
selec /= otherdistinct;
347
* Another cross-check: selectivity shouldn't be estimated as more
348
* than the least common "most common value".
350
if (nnumbers > 0 && selec > numbers[nnumbers - 1])
351
selec = numbers[nnumbers - 1];
354
free_attstatsslot(vardata->atttype, values, nvalues,
360
* No ANALYZE stats available, so make a guess using estimated number
361
* of distinct values and assuming they are equally common. (The guess
362
* is unlikely to be very good, but we do know a few special cases.)
364
selec = 1.0 / get_variable_numdistinct(vardata);
367
/* result should be in range, but make sure... */
368
CLAMP_PROBABILITY(selec);
374
* var_eq_non_const --- eqsel for var = something-other-than-const case
377
var_eq_non_const(VariableStatData *vardata, Oid operator,
384
* If we matched the var to a unique index, assume there is exactly one
385
* match regardless of anything else. (This is slightly bogus, since the
386
* index's equality operator might be different from ours, but it's more
387
* likely to be right than ignoring the information.)
389
if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
390
return 1.0 / vardata->rel->tuples;
392
if (HeapTupleIsValid(vardata->statsTuple))
394
Form_pg_statistic stats;
399
stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
402
* Search is for a value that we do not know a priori, but we will
403
* assume it is not NULL. Estimate the selectivity as non-null
404
* fraction divided by number of distinct values, so that we get a
405
* result averaged over all possible values whether common or
406
* uncommon. (Essentially, we are assuming that the not-yet-known
407
* comparison value is equally likely to be any of the possible
408
* values, regardless of their frequency in the table. Is that a good
411
selec = 1.0 - stats->stanullfrac;
412
ndistinct = get_variable_numdistinct(vardata);
417
* Cross-check: selectivity should never be estimated as more than the
418
* most common value's.
420
if (get_attstatsslot(vardata->statsTuple,
421
vardata->atttype, vardata->atttypmod,
422
STATISTIC_KIND_MCV, InvalidOid,
425
&numbers, &nnumbers))
427
if (nnumbers > 0 && selec > numbers[0])
429
free_attstatsslot(vardata->atttype, NULL, 0, numbers, nnumbers);
435
* No ANALYZE stats available, so make a guess using estimated number
436
* of distinct values and assuming they are equally common. (The guess
437
* is unlikely to be very good, but we do know a few special cases.)
439
selec = 1.0 / get_variable_numdistinct(vardata);
442
/* result should be in range, but make sure... */
443
CLAMP_PROBABILITY(selec);
449
* neqsel - Selectivity of "!=" for any data types.
451
* This routine is also used for some operators that are not "!="
452
* but have comparable selectivity behavior. See above comments
456
neqsel(PG_FUNCTION_ARGS)
458
PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
459
Oid operator = PG_GETARG_OID(1);
460
List *args = (List *) PG_GETARG_POINTER(2);
461
int varRelid = PG_GETARG_INT32(3);
466
* We want 1 - eqsel() where the equality operator is the one associated
467
* with this != operator, that is, its negator.
469
eqop = get_negator(operator);
472
result = DatumGetFloat8(DirectFunctionCall4(eqsel,
473
PointerGetDatum(root),
474
ObjectIdGetDatum(eqop),
475
PointerGetDatum(args),
476
Int32GetDatum(varRelid)));
480
/* Use default selectivity (should we raise an error instead?) */
481
result = DEFAULT_EQ_SEL;
483
result = 1.0 - result;
484
PG_RETURN_FLOAT8(result);
488
* scalarineqsel - Selectivity of "<", "<=", ">", ">=" for scalars.
490
* This is the guts of both scalarltsel and scalargtsel. The caller has
491
* commuted the clause, if necessary, so that we can treat the variable as
492
* being on the left. The caller must also make sure that the other side
493
* of the clause is a non-null Const, and dissect same into a value and
496
* This routine works for any datatype (or pair of datatypes) known to
497
* convert_to_scalar(). If it is applied to some other datatype,
498
* it will return a default estimate.
501
scalarineqsel(PlannerInfo *root, Oid operator, bool isgt,
502
VariableStatData *vardata, Datum constval, Oid consttype)
504
Form_pg_statistic stats;
511
if (!HeapTupleIsValid(vardata->statsTuple))
513
/* no stats available, so default result */
514
return DEFAULT_INEQ_SEL;
516
stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
518
fmgr_info(get_opcode(operator), &opproc);
521
* If we have most-common-values info, add up the fractions of the MCV
522
* entries that satisfy MCV OP CONST. These fractions contribute directly
523
* to the result selectivity. Also add up the total fraction represented
526
mcv_selec = mcv_selectivity(vardata, &opproc, constval, true,
530
* If there is a histogram, determine which bin the constant falls in, and
531
* compute the resulting contribution to selectivity.
533
hist_selec = ineq_histogram_selectivity(root, vardata, &opproc, isgt,
534
constval, consttype);
537
* Now merge the results from the MCV and histogram calculations,
538
* realizing that the histogram covers only the non-null values that are
541
selec = 1.0 - stats->stanullfrac - sumcommon;
543
if (hist_selec >= 0.0)
548
* If no histogram but there are values not accounted for by MCV,
549
* arbitrarily assume half of them will match.
556
/* result should be in range, but make sure... */
557
CLAMP_PROBABILITY(selec);
563
* mcv_selectivity - Examine the MCV list for selectivity estimates
565
* Determine the fraction of the variable's MCV population that satisfies
566
* the predicate (VAR OP CONST), or (CONST OP VAR) if !varonleft. Also
567
* compute the fraction of the total column population represented by the MCV
568
* list. This code will work for any boolean-returning predicate operator.
570
* The function result is the MCV selectivity, and the fraction of the
571
* total population is returned into *sumcommonp. Zeroes are returned
572
* if there is no MCV list.
575
mcv_selectivity(VariableStatData *vardata, FmgrInfo *opproc,
576
Datum constval, bool varonleft,
590
if (HeapTupleIsValid(vardata->statsTuple) &&
591
get_attstatsslot(vardata->statsTuple,
592
vardata->atttype, vardata->atttypmod,
593
STATISTIC_KIND_MCV, InvalidOid,
596
&numbers, &nnumbers))
598
for (i = 0; i < nvalues; i++)
601
DatumGetBool(FunctionCall2Coll(opproc,
602
DEFAULT_COLLATION_OID,
605
DatumGetBool(FunctionCall2Coll(opproc,
606
DEFAULT_COLLATION_OID,
609
mcv_selec += numbers[i];
610
sumcommon += numbers[i];
612
free_attstatsslot(vardata->atttype, values, nvalues,
616
*sumcommonp = sumcommon;
621
* histogram_selectivity - Examine the histogram for selectivity estimates
623
* Determine the fraction of the variable's histogram entries that satisfy
624
* the predicate (VAR OP CONST), or (CONST OP VAR) if !varonleft.
626
* This code will work for any boolean-returning predicate operator, whether
627
* or not it has anything to do with the histogram sort operator. We are
628
* essentially using the histogram just as a representative sample. However,
629
* small histograms are unlikely to be all that representative, so the caller
630
* should be prepared to fall back on some other estimation approach when the
631
* histogram is missing or very small. It may also be prudent to combine this
632
* approach with another one when the histogram is small.
634
* If the actual histogram size is not at least min_hist_size, we won't bother
635
* to do the calculation at all. Also, if the n_skip parameter is > 0, we
636
* ignore the first and last n_skip histogram elements, on the grounds that
637
* they are outliers and hence not very representative. Typical values for
638
* these parameters are 10 and 1.
640
* The function result is the selectivity, or -1 if there is no histogram
641
* or it's smaller than min_hist_size.
643
* The output parameter *hist_size receives the actual histogram size,
644
* or zero if no histogram. Callers may use this number to decide how
645
* much faith to put in the function result.
647
* Note that the result disregards both the most-common-values (if any) and
648
* null entries. The caller is expected to combine this result with
649
* statistics for those portions of the column population. It may also be
650
* prudent to clamp the result range, ie, disbelieve exact 0 or 1 outputs.
653
histogram_selectivity(VariableStatData *vardata, FmgrInfo *opproc,
654
Datum constval, bool varonleft,
655
int min_hist_size, int n_skip,
662
/* check sanity of parameters */
664
Assert(min_hist_size > 2 * n_skip);
666
if (HeapTupleIsValid(vardata->statsTuple) &&
667
get_attstatsslot(vardata->statsTuple,
668
vardata->atttype, vardata->atttypmod,
669
STATISTIC_KIND_HISTOGRAM, InvalidOid,
674
*hist_size = nvalues;
675
if (nvalues >= min_hist_size)
680
for (i = n_skip; i < nvalues - n_skip; i++)
683
DatumGetBool(FunctionCall2Coll(opproc,
684
DEFAULT_COLLATION_OID,
687
DatumGetBool(FunctionCall2Coll(opproc,
688
DEFAULT_COLLATION_OID,
693
result = ((double) nmatch) / ((double) (nvalues - 2 * n_skip));
697
free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
709
* ineq_histogram_selectivity - Examine the histogram for scalarineqsel
711
* Determine the fraction of the variable's histogram population that
712
* satisfies the inequality condition, ie, VAR < CONST or VAR > CONST.
714
* Returns -1 if there is no histogram (valid results will always be >= 0).
716
* Note that the result disregards both the most-common-values (if any) and
717
* null entries. The caller is expected to combine this result with
718
* statistics for those portions of the column population.
721
ineq_histogram_selectivity(PlannerInfo *root,
722
VariableStatData *vardata,
723
FmgrInfo *opproc, bool isgt,
724
Datum constval, Oid consttype)
734
* Someday, ANALYZE might store more than one histogram per rel/att,
735
* corresponding to more than one possible sort ordering defined for the
736
* column type. However, to make that work we will need to figure out
737
* which staop to search for --- it's not necessarily the one we have at
738
* hand! (For example, we might have a '<=' operator rather than the '<'
739
* operator that will appear in staop.) For now, assume that whatever
740
* appears in pg_statistic is sorted the same way our operator sorts, or
741
* the reverse way if isgt is TRUE.
743
if (HeapTupleIsValid(vardata->statsTuple) &&
744
get_attstatsslot(vardata->statsTuple,
745
vardata->atttype, vardata->atttypmod,
746
STATISTIC_KIND_HISTOGRAM, InvalidOid,
754
* Use binary search to find proper location, ie, the first slot
755
* at which the comparison fails. (If the given operator isn't
756
* actually sort-compatible with the histogram, you'll get garbage
757
* results ... but probably not any more garbage-y than you would
758
* from the old linear search.)
760
* If the binary search accesses the first or last histogram
761
* entry, we try to replace that endpoint with the true column min
762
* or max as found by get_actual_variable_range(). This
763
* ameliorates misestimates when the min or max is moving as a
764
* result of changes since the last ANALYZE. Note that this could
765
* result in effectively including MCVs into the histogram that
766
* weren't there before, but we don't try to correct for that.
769
int lobound = 0; /* first possible slot to search */
770
int hibound = nvalues; /* last+1 slot to search */
771
bool have_end = false;
774
* If there are only two histogram entries, we'll want up-to-date
775
* values for both. (If there are more than two, we need at most
776
* one of them to be updated, so we deal with that within the
780
have_end = get_actual_variable_range(root,
786
while (lobound < hibound)
788
int probe = (lobound + hibound) / 2;
792
* If we find ourselves about to compare to the first or last
793
* histogram entry, first try to replace it with the actual
794
* current min or max (unless we already did so above).
796
if (probe == 0 && nvalues > 2)
797
have_end = get_actual_variable_range(root,
802
else if (probe == nvalues - 1 && nvalues > 2)
803
have_end = get_actual_variable_range(root,
809
ltcmp = DatumGetBool(FunctionCall2Coll(opproc,
810
DEFAULT_COLLATION_OID,
823
/* Constant is below lower histogram boundary. */
826
else if (lobound >= nvalues)
828
/* Constant is above upper histogram boundary. */
840
* We have values[i-1] <= constant <= values[i].
842
* Convert the constant and the two nearest bin boundary
843
* values to a uniform comparison scale, and do a linear
844
* interpolation within this bin.
846
if (convert_to_scalar(constval, consttype, &val,
847
values[i - 1], values[i],
853
/* cope if bin boundaries appear identical */
858
else if (val >= high)
862
binfrac = (val - low) / (high - low);
865
* Watch out for the possibility that we got a NaN or
866
* Infinity from the division. This can happen
867
* despite the previous checks, if for example "low"
870
if (isnan(binfrac) ||
871
binfrac < 0.0 || binfrac > 1.0)
878
* Ideally we'd produce an error here, on the grounds that
879
* the given operator shouldn't have scalarXXsel
880
* registered as its selectivity func unless we can deal
881
* with its operand types. But currently, all manner of
882
* stuff is invoking scalarXXsel, so give a default
883
* estimate until that can be fixed.
889
* Now, compute the overall selectivity across the values
890
* represented by the histogram. We have i-1 full bins and
891
* binfrac partial bin below the constant.
893
histfrac = (double) (i - 1) + binfrac;
894
histfrac /= (double) (nvalues - 1);
898
* Now histfrac = fraction of histogram entries below the
901
* Account for "<" vs ">"
903
hist_selec = isgt ? (1.0 - histfrac) : histfrac;
906
* The histogram boundaries are only approximate to begin with,
907
* and may well be out of date anyway. Therefore, don't believe
908
* extremely small or large selectivity estimates --- unless we
909
* got actual current endpoint values from the table.
912
CLAMP_PROBABILITY(hist_selec);
915
if (hist_selec < 0.0001)
917
else if (hist_selec > 0.9999)
922
free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
929
* scalarltsel - Selectivity of "<" (also "<=") for scalars.
932
scalarltsel(PG_FUNCTION_ARGS)
934
PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
935
Oid operator = PG_GETARG_OID(1);
936
List *args = (List *) PG_GETARG_POINTER(2);
937
int varRelid = PG_GETARG_INT32(3);
938
VariableStatData vardata;
947
* If expression is not variable op something or something op variable,
948
* then punt and return a default estimate.
950
if (!get_restriction_variable(root, args, varRelid,
951
&vardata, &other, &varonleft))
952
PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
955
* Can't do anything useful if the something is not a constant, either.
957
if (!IsA(other, Const))
959
ReleaseVariableStats(vardata);
960
PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
964
* If the constant is NULL, assume operator is strict and return zero, ie,
965
* operator will never return TRUE.
967
if (((Const *) other)->constisnull)
969
ReleaseVariableStats(vardata);
970
PG_RETURN_FLOAT8(0.0);
972
constval = ((Const *) other)->constvalue;
973
consttype = ((Const *) other)->consttype;
976
* Force the var to be on the left to simplify logic in scalarineqsel.
980
/* we have var < other */
985
/* we have other < var, commute to make var > other */
986
operator = get_commutator(operator);
989
/* Use default selectivity (should we raise an error instead?) */
990
ReleaseVariableStats(vardata);
991
PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
996
selec = scalarineqsel(root, operator, isgt, &vardata, constval, consttype);
998
ReleaseVariableStats(vardata);
1000
PG_RETURN_FLOAT8((float8) selec);
1004
* scalargtsel - Selectivity of ">" (also ">=") for integers.
1007
scalargtsel(PG_FUNCTION_ARGS)
1009
PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
1010
Oid operator = PG_GETARG_OID(1);
1011
List *args = (List *) PG_GETARG_POINTER(2);
1012
int varRelid = PG_GETARG_INT32(3);
1013
VariableStatData vardata;
1022
* If expression is not variable op something or something op variable,
1023
* then punt and return a default estimate.
1025
if (!get_restriction_variable(root, args, varRelid,
1026
&vardata, &other, &varonleft))
1027
PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1030
* Can't do anything useful if the something is not a constant, either.
1032
if (!IsA(other, Const))
1034
ReleaseVariableStats(vardata);
1035
PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1039
* If the constant is NULL, assume operator is strict and return zero, ie,
1040
* operator will never return TRUE.
1042
if (((Const *) other)->constisnull)
1044
ReleaseVariableStats(vardata);
1045
PG_RETURN_FLOAT8(0.0);
1047
constval = ((Const *) other)->constvalue;
1048
consttype = ((Const *) other)->consttype;
1051
* Force the var to be on the left to simplify logic in scalarineqsel.
1055
/* we have var > other */
1060
/* we have other > var, commute to make var < other */
1061
operator = get_commutator(operator);
1064
/* Use default selectivity (should we raise an error instead?) */
1065
ReleaseVariableStats(vardata);
1066
PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1071
selec = scalarineqsel(root, operator, isgt, &vardata, constval, consttype);
1073
ReleaseVariableStats(vardata);
1075
PG_RETURN_FLOAT8((float8) selec);
1079
* patternsel - Generic code for pattern-match selectivity.
1082
patternsel(PG_FUNCTION_ARGS, Pattern_Type ptype, bool negate)
1084
PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
1085
Oid operator = PG_GETARG_OID(1);
1086
List *args = (List *) PG_GETARG_POINTER(2);
1087
int varRelid = PG_GETARG_INT32(3);
1088
VariableStatData vardata;
1095
Pattern_Prefix_Status pstatus;
1097
Const *prefix = NULL;
1102
* If this is for a NOT LIKE or similar operator, get the corresponding
1103
* positive-match operator and work with that. Set result to the correct
1104
* default estimate, too.
1108
operator = get_negator(operator);
1109
if (!OidIsValid(operator))
1110
elog(ERROR, "patternsel called for operator without a negator");
1111
result = 1.0 - DEFAULT_MATCH_SEL;
1115
result = DEFAULT_MATCH_SEL;
1119
* If expression is not variable op constant, then punt and return a
1122
if (!get_restriction_variable(root, args, varRelid,
1123
&vardata, &other, &varonleft))
1125
if (!varonleft || !IsA(other, Const))
1127
ReleaseVariableStats(vardata);
1132
* If the constant is NULL, assume operator is strict and return zero, ie,
1133
* operator will never return TRUE. (It's zero even for a negator op.)
1135
if (((Const *) other)->constisnull)
1137
ReleaseVariableStats(vardata);
1140
constval = ((Const *) other)->constvalue;
1141
consttype = ((Const *) other)->consttype;
1144
* The right-hand const is type text or bytea for all supported operators.
1145
* We do not expect to see binary-compatible types here, since
1146
* const-folding should have relabeled the const to exactly match the
1147
* operator's declared type.
1149
if (consttype != TEXTOID && consttype != BYTEAOID)
1151
ReleaseVariableStats(vardata);
1156
* Similarly, the exposed type of the left-hand side should be one of
1157
* those we know. (Do not look at vardata.atttype, which might be
1158
* something binary-compatible but different.) We can use it to choose
1159
* the index opfamily from which we must draw the comparison operators.
1161
* NOTE: It would be more correct to use the PATTERN opfamilies than the
1162
* simple ones, but at the moment ANALYZE will not generate statistics for
1163
* the PATTERN operators. But our results are so approximate anyway that
1164
* it probably hardly matters.
1166
vartype = vardata.vartype;
1171
opfamily = TEXT_BTREE_FAM_OID;
1174
opfamily = BPCHAR_BTREE_FAM_OID;
1177
opfamily = NAME_BTREE_FAM_OID;
1180
opfamily = BYTEA_BTREE_FAM_OID;
1183
ReleaseVariableStats(vardata);
1188
* Divide pattern into fixed prefix and remainder. XXX we have to assume
1189
* default collation here, because we don't have access to the actual
1190
* input collation for the operator. FIXME ...
1192
patt = (Const *) other;
1193
pstatus = pattern_fixed_prefix(patt, ptype, DEFAULT_COLLATION_OID,
1197
* If necessary, coerce the prefix constant to the right type. (The "rest"
1198
* constant need not be changed.)
1200
if (prefix && prefix->consttype != vartype)
1204
switch (prefix->consttype)
1207
prefixstr = TextDatumGetCString(prefix->constvalue);
1210
prefixstr = DatumGetCString(DirectFunctionCall1(byteaout,
1211
prefix->constvalue));
1214
elog(ERROR, "unrecognized consttype: %u",
1216
ReleaseVariableStats(vardata);
1219
prefix = string_to_const(prefixstr, vartype);
1223
if (pstatus == Pattern_Prefix_Exact)
1226
* Pattern specifies an exact match, so pretend operator is '='
1228
Oid eqopr = get_opfamily_member(opfamily, vartype, vartype,
1229
BTEqualStrategyNumber);
1231
if (eqopr == InvalidOid)
1232
elog(ERROR, "no = operator for opfamily %u", opfamily);
1233
result = var_eq_const(&vardata, eqopr, prefix->constvalue,
1239
* Not exact-match pattern. If we have a sufficiently large
1240
* histogram, estimate selectivity for the histogram part of the
1241
* population by counting matches in the histogram. If not, estimate
1242
* selectivity of the fixed prefix and remainder of pattern
1243
* separately, then combine the two to get an estimate of the
1244
* selectivity for the part of the column population represented by
1245
* the histogram. (For small histograms, we combine these
1248
* We then add up data for any most-common-values values; these are
1249
* not in the histogram population, and we can get exact answers for
1250
* them by applying the pattern operator, so there's no reason to
1251
* approximate. (If the MCVs cover a significant part of the total
1252
* population, this gives us a big leg up in accuracy.)
1261
/* Try to use the histogram entries to get selectivity */
1262
fmgr_info(get_opcode(operator), &opproc);
1264
selec = histogram_selectivity(&vardata, &opproc, constval, true,
1267
/* If not at least 100 entries, use the heuristic method */
1268
if (hist_size < 100)
1270
Selectivity heursel;
1271
Selectivity prefixsel;
1272
Selectivity restsel;
1274
if (pstatus == Pattern_Prefix_Partial)
1275
prefixsel = prefix_selectivity(root, &vardata, vartype,
1279
restsel = pattern_selectivity(rest, ptype);
1280
heursel = prefixsel * restsel;
1282
if (selec < 0) /* fewer than 10 histogram entries? */
1287
* For histogram sizes from 10 to 100, we combine the
1288
* histogram and heuristic selectivities, putting increasingly
1289
* more trust in the histogram for larger sizes.
1291
double hist_weight = hist_size / 100.0;
1293
selec = selec * hist_weight + heursel * (1.0 - hist_weight);
1297
/* In any case, don't believe extremely small or large estimates. */
1300
else if (selec > 0.9999)
1304
* If we have most-common-values info, add up the fractions of the MCV
1305
* entries that satisfy MCV OP PATTERN. These fractions contribute
1306
* directly to the result selectivity. Also add up the total fraction
1307
* represented by MCV entries.
1309
mcv_selec = mcv_selectivity(&vardata, &opproc, constval, true,
1312
if (HeapTupleIsValid(vardata.statsTuple))
1313
nullfrac = ((Form_pg_statistic) GETSTRUCT(vardata.statsTuple))->stanullfrac;
1318
* Now merge the results from the MCV and histogram calculations,
1319
* realizing that the histogram covers only the non-null values that
1320
* are not listed in MCV.
1322
selec *= 1.0 - nullfrac - sumcommon;
1325
/* result should be in range, but make sure... */
1326
CLAMP_PROBABILITY(selec);
1332
pfree(DatumGetPointer(prefix->constvalue));
1336
ReleaseVariableStats(vardata);
1338
return negate ? (1.0 - result) : result;
1342
* regexeqsel - Selectivity of regular-expression pattern match.
1345
regexeqsel(PG_FUNCTION_ARGS)
1347
PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex, false));
1351
* icregexeqsel - Selectivity of case-insensitive regex match.
1354
icregexeqsel(PG_FUNCTION_ARGS)
1356
PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex_IC, false));
1360
* likesel - Selectivity of LIKE pattern match.
1363
likesel(PG_FUNCTION_ARGS)
1365
PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like, false));
1369
* iclikesel - Selectivity of ILIKE pattern match.
1372
iclikesel(PG_FUNCTION_ARGS)
1374
PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like_IC, false));
1378
* regexnesel - Selectivity of regular-expression pattern non-match.
1381
regexnesel(PG_FUNCTION_ARGS)
1383
PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex, true));
1387
* icregexnesel - Selectivity of case-insensitive regex non-match.
1390
icregexnesel(PG_FUNCTION_ARGS)
1392
PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex_IC, true));
1396
* nlikesel - Selectivity of LIKE pattern non-match.
1399
nlikesel(PG_FUNCTION_ARGS)
1401
PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like, true));
1405
* icnlikesel - Selectivity of ILIKE pattern non-match.
1408
icnlikesel(PG_FUNCTION_ARGS)
1410
PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like_IC, true));
1414
* booltestsel - Selectivity of BooleanTest Node.
1417
booltestsel(PlannerInfo *root, BoolTestType booltesttype, Node *arg,
1418
int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1420
VariableStatData vardata;
1423
examine_variable(root, arg, varRelid, &vardata);
1425
if (HeapTupleIsValid(vardata.statsTuple))
1427
Form_pg_statistic stats;
1434
stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1435
freq_null = stats->stanullfrac;
1437
if (get_attstatsslot(vardata.statsTuple,
1438
vardata.atttype, vardata.atttypmod,
1439
STATISTIC_KIND_MCV, InvalidOid,
1442
&numbers, &nnumbers)
1449
* Get first MCV frequency and derive frequency for true.
1451
if (DatumGetBool(values[0]))
1452
freq_true = numbers[0];
1454
freq_true = 1.0 - numbers[0] - freq_null;
1457
* Next derive frequency for false. Then use these as appropriate
1458
* to derive frequency for each case.
1460
freq_false = 1.0 - freq_true - freq_null;
1462
switch (booltesttype)
1465
/* select only NULL values */
1468
case IS_NOT_UNKNOWN:
1469
/* select non-NULL values */
1470
selec = 1.0 - freq_null;
1473
/* select only TRUE values */
1477
/* select non-TRUE values */
1478
selec = 1.0 - freq_true;
1481
/* select only FALSE values */
1485
/* select non-FALSE values */
1486
selec = 1.0 - freq_false;
1489
elog(ERROR, "unrecognized booltesttype: %d",
1490
(int) booltesttype);
1491
selec = 0.0; /* Keep compiler quiet */
1495
free_attstatsslot(vardata.atttype, values, nvalues,
1501
* No most-common-value info available. Still have null fraction
1502
* information, so use it for IS [NOT] UNKNOWN. Otherwise adjust
1503
* for null fraction and assume an even split for boolean tests.
1505
switch (booltesttype)
1510
* Use freq_null directly.
1514
case IS_NOT_UNKNOWN:
1517
* Select not unknown (not null) values. Calculate from
1520
selec = 1.0 - freq_null;
1526
selec = (1.0 - freq_null) / 2.0;
1529
elog(ERROR, "unrecognized booltesttype: %d",
1530
(int) booltesttype);
1531
selec = 0.0; /* Keep compiler quiet */
1539
* If we can't get variable statistics for the argument, perhaps
1540
* clause_selectivity can do something with it. We ignore the
1541
* possibility of a NULL value when using clause_selectivity, and just
1542
* assume the value is either TRUE or FALSE.
1544
switch (booltesttype)
1547
selec = DEFAULT_UNK_SEL;
1549
case IS_NOT_UNKNOWN:
1550
selec = DEFAULT_NOT_UNK_SEL;
1554
selec = (double) clause_selectivity(root, arg,
1560
selec = 1.0 - (double) clause_selectivity(root, arg,
1565
elog(ERROR, "unrecognized booltesttype: %d",
1566
(int) booltesttype);
1567
selec = 0.0; /* Keep compiler quiet */
1572
ReleaseVariableStats(vardata);
1574
/* result should be in range, but make sure... */
1575
CLAMP_PROBABILITY(selec);
1577
return (Selectivity) selec;
1581
* nulltestsel - Selectivity of NullTest Node.
1584
nulltestsel(PlannerInfo *root, NullTestType nulltesttype, Node *arg,
1585
int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1587
VariableStatData vardata;
1590
examine_variable(root, arg, varRelid, &vardata);
1592
if (HeapTupleIsValid(vardata.statsTuple))
1594
Form_pg_statistic stats;
1597
stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1598
freq_null = stats->stanullfrac;
1600
switch (nulltesttype)
1605
* Use freq_null directly.
1612
* Select not unknown (not null) values. Calculate from
1615
selec = 1.0 - freq_null;
1618
elog(ERROR, "unrecognized nulltesttype: %d",
1619
(int) nulltesttype);
1620
return (Selectivity) 0; /* keep compiler quiet */
1626
* No ANALYZE stats available, so make a guess
1628
switch (nulltesttype)
1631
selec = DEFAULT_UNK_SEL;
1634
selec = DEFAULT_NOT_UNK_SEL;
1637
elog(ERROR, "unrecognized nulltesttype: %d",
1638
(int) nulltesttype);
1639
return (Selectivity) 0; /* keep compiler quiet */
1643
ReleaseVariableStats(vardata);
1645
/* result should be in range, but make sure... */
1646
CLAMP_PROBABILITY(selec);
1648
return (Selectivity) selec;
1652
* strip_array_coercion - strip binary-compatible relabeling from an array expr
1654
* For array values, the parser normally generates ArrayCoerceExpr conversions,
1655
* but it seems possible that RelabelType might show up. Also, the planner
1656
* is not currently tense about collapsing stacked ArrayCoerceExpr nodes,
1657
* so we need to be ready to deal with more than one level.
1660
strip_array_coercion(Node *node)
1664
if (node && IsA(node, ArrayCoerceExpr) &&
1665
((ArrayCoerceExpr *) node)->elemfuncid == InvalidOid)
1667
node = (Node *) ((ArrayCoerceExpr *) node)->arg;
1669
else if (node && IsA(node, RelabelType))
1671
/* We don't really expect this case, but may as well cope */
1672
node = (Node *) ((RelabelType *) node)->arg;
1681
* scalararraysel - Selectivity of ScalarArrayOpExpr Node.
1684
scalararraysel(PlannerInfo *root,
1685
ScalarArrayOpExpr *clause,
1686
bool is_join_clause,
1689
SpecialJoinInfo *sjinfo)
1691
Oid operator = clause->opno;
1692
bool useOr = clause->useOr;
1695
Oid nominal_element_type;
1696
Oid nominal_element_collation;
1697
RegProcedure oprsel;
1698
FmgrInfo oprselproc;
1702
* First, look up the underlying operator's selectivity estimator. Punt if
1703
* it hasn't got one.
1706
oprsel = get_oprjoin(operator);
1708
oprsel = get_oprrest(operator);
1710
return (Selectivity) 0.5;
1711
fmgr_info(oprsel, &oprselproc);
1713
/* deconstruct the expression */
1714
Assert(list_length(clause->args) == 2);
1715
leftop = (Node *) linitial(clause->args);
1716
rightop = (Node *) lsecond(clause->args);
1718
/* get nominal (after relabeling) element type of rightop */
1719
nominal_element_type = get_base_element_type(exprType(rightop));
1720
if (!OidIsValid(nominal_element_type))
1721
return (Selectivity) 0.5; /* probably shouldn't happen */
1722
/* get nominal collation, too, for generating constants */
1723
nominal_element_collation = exprCollation(rightop);
1725
/* look through any binary-compatible relabeling of rightop */
1726
rightop = strip_array_coercion(rightop);
1729
* We consider three cases:
1731
* 1. rightop is an Array constant: deconstruct the array, apply the
1732
* operator's selectivity function for each array element, and merge the
1733
* results in the same way that clausesel.c does for AND/OR combinations.
1735
* 2. rightop is an ARRAY[] construct: apply the operator's selectivity
1736
* function for each element of the ARRAY[] construct, and merge.
1738
* 3. otherwise, make a guess ...
1740
if (rightop && IsA(rightop, Const))
1742
Datum arraydatum = ((Const *) rightop)->constvalue;
1743
bool arrayisnull = ((Const *) rightop)->constisnull;
1744
ArrayType *arrayval;
1753
if (arrayisnull) /* qual can't succeed if null array */
1754
return (Selectivity) 0.0;
1755
arrayval = DatumGetArrayTypeP(arraydatum);
1756
get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
1757
&elmlen, &elmbyval, &elmalign);
1758
deconstruct_array(arrayval,
1759
ARR_ELEMTYPE(arrayval),
1760
elmlen, elmbyval, elmalign,
1761
&elem_values, &elem_nulls, &num_elems);
1762
s1 = useOr ? 0.0 : 1.0;
1763
for (i = 0; i < num_elems; i++)
1768
args = list_make2(leftop,
1769
makeConst(nominal_element_type,
1771
nominal_element_collation,
1777
s2 = DatumGetFloat8(FunctionCall5(&oprselproc,
1778
PointerGetDatum(root),
1779
ObjectIdGetDatum(operator),
1780
PointerGetDatum(args),
1781
Int16GetDatum(jointype),
1782
PointerGetDatum(sjinfo)));
1784
s2 = DatumGetFloat8(FunctionCall4(&oprselproc,
1785
PointerGetDatum(root),
1786
ObjectIdGetDatum(operator),
1787
PointerGetDatum(args),
1788
Int32GetDatum(varRelid)));
1790
s1 = s1 + s2 - s1 * s2;
1795
else if (rightop && IsA(rightop, ArrayExpr) &&
1796
!((ArrayExpr *) rightop)->multidims)
1798
ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
1803
get_typlenbyval(arrayexpr->element_typeid,
1804
&elmlen, &elmbyval);
1805
s1 = useOr ? 0.0 : 1.0;
1806
foreach(l, arrayexpr->elements)
1808
Node *elem = (Node *) lfirst(l);
1813
* Theoretically, if elem isn't of nominal_element_type we should
1814
* insert a RelabelType, but it seems unlikely that any operator
1815
* estimation function would really care ...
1817
args = list_make2(leftop, elem);
1819
s2 = DatumGetFloat8(FunctionCall5(&oprselproc,
1820
PointerGetDatum(root),
1821
ObjectIdGetDatum(operator),
1822
PointerGetDatum(args),
1823
Int16GetDatum(jointype),
1824
PointerGetDatum(sjinfo)));
1826
s2 = DatumGetFloat8(FunctionCall4(&oprselproc,
1827
PointerGetDatum(root),
1828
ObjectIdGetDatum(operator),
1829
PointerGetDatum(args),
1830
Int32GetDatum(varRelid)));
1832
s1 = s1 + s2 - s1 * s2;
1839
CaseTestExpr *dummyexpr;
1845
* We need a dummy rightop to pass to the operator selectivity
1846
* routine. It can be pretty much anything that doesn't look like a
1847
* constant; CaseTestExpr is a convenient choice.
1849
dummyexpr = makeNode(CaseTestExpr);
1850
dummyexpr->typeId = nominal_element_type;
1851
dummyexpr->typeMod = -1;
1852
dummyexpr->collation = clause->inputcollid;
1853
args = list_make2(leftop, dummyexpr);
1855
s2 = DatumGetFloat8(FunctionCall5(&oprselproc,
1856
PointerGetDatum(root),
1857
ObjectIdGetDatum(operator),
1858
PointerGetDatum(args),
1859
Int16GetDatum(jointype),
1860
PointerGetDatum(sjinfo)));
1862
s2 = DatumGetFloat8(FunctionCall4(&oprselproc,
1863
PointerGetDatum(root),
1864
ObjectIdGetDatum(operator),
1865
PointerGetDatum(args),
1866
Int32GetDatum(varRelid)));
1867
s1 = useOr ? 0.0 : 1.0;
1870
* Arbitrarily assume 10 elements in the eventual array value (see
1871
* also estimate_array_length)
1873
for (i = 0; i < 10; i++)
1876
s1 = s1 + s2 - s1 * s2;
1882
/* result should be in range, but make sure... */
1883
CLAMP_PROBABILITY(s1);
1889
* Estimate number of elements in the array yielded by an expression.
1891
* It's important that this agree with scalararraysel.
1894
estimate_array_length(Node *arrayexpr)
1896
/* look through any binary-compatible relabeling of arrayexpr */
1897
arrayexpr = strip_array_coercion(arrayexpr);
1899
if (arrayexpr && IsA(arrayexpr, Const))
1901
Datum arraydatum = ((Const *) arrayexpr)->constvalue;
1902
bool arrayisnull = ((Const *) arrayexpr)->constisnull;
1903
ArrayType *arrayval;
1907
arrayval = DatumGetArrayTypeP(arraydatum);
1908
return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
1910
else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
1911
!((ArrayExpr *) arrayexpr)->multidims)
1913
return list_length(((ArrayExpr *) arrayexpr)->elements);
1917
/* default guess --- see also scalararraysel */
1923
* rowcomparesel - Selectivity of RowCompareExpr Node.
1925
* We estimate RowCompare selectivity by considering just the first (high
1926
* order) columns, which makes it equivalent to an ordinary OpExpr. While
1927
* this estimate could be refined by considering additional columns, it
1928
* seems unlikely that we could do a lot better without multi-column
1932
rowcomparesel(PlannerInfo *root,
1933
RowCompareExpr *clause,
1934
int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
1937
Oid opno = linitial_oid(clause->opnos);
1939
bool is_join_clause;
1941
/* Build equivalent arg list for single operator */
1942
opargs = list_make2(linitial(clause->largs), linitial(clause->rargs));
1945
* Decide if it's a join clause. This should match clausesel.c's
1946
* treat_as_join_clause(), except that we intentionally consider only the
1947
* leading columns and not the rest of the clause.
1952
* Caller is forcing restriction mode (eg, because we are examining an
1953
* inner indexscan qual).
1955
is_join_clause = false;
1957
else if (sjinfo == NULL)
1960
* It must be a restriction clause, since it's being evaluated at a
1963
is_join_clause = false;
1968
* Otherwise, it's a join if there's more than one relation used.
1970
is_join_clause = (NumRelids((Node *) opargs) > 1);
1975
/* Estimate selectivity for a join clause. */
1976
s1 = join_selectivity(root, opno,
1983
/* Estimate selectivity for a restriction clause. */
1984
s1 = restriction_selectivity(root, opno,
1993
* eqjoinsel - Join selectivity of "="
1996
eqjoinsel(PG_FUNCTION_ARGS)
1998
PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
1999
Oid operator = PG_GETARG_OID(1);
2000
List *args = (List *) PG_GETARG_POINTER(2);
2003
JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2005
SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
2007
VariableStatData vardata1;
2008
VariableStatData vardata2;
2009
bool join_is_reversed;
2011
get_join_variables(root, args, sjinfo,
2012
&vardata1, &vardata2, &join_is_reversed);
2014
switch (sjinfo->jointype)
2019
selec = eqjoinsel_inner(operator, &vardata1, &vardata2);
2023
if (!join_is_reversed)
2024
selec = eqjoinsel_semi(operator, &vardata1, &vardata2);
2026
selec = eqjoinsel_semi(get_commutator(operator),
2027
&vardata2, &vardata1);
2030
/* other values not expected here */
2031
elog(ERROR, "unrecognized join type: %d",
2032
(int) sjinfo->jointype);
2033
selec = 0; /* keep compiler quiet */
2037
ReleaseVariableStats(vardata1);
2038
ReleaseVariableStats(vardata2);
2040
CLAMP_PROBABILITY(selec);
2042
PG_RETURN_FLOAT8((float8) selec);
2046
* eqjoinsel_inner --- eqjoinsel for normal inner join
2048
* We also use this for LEFT/FULL outer joins; it's not presently clear
2049
* that it's worth trying to distinguish them here.
2052
eqjoinsel_inner(Oid operator,
2053
VariableStatData *vardata1, VariableStatData *vardata2)
2058
Form_pg_statistic stats1 = NULL;
2059
Form_pg_statistic stats2 = NULL;
2060
bool have_mcvs1 = false;
2061
Datum *values1 = NULL;
2063
float4 *numbers1 = NULL;
2065
bool have_mcvs2 = false;
2066
Datum *values2 = NULL;
2068
float4 *numbers2 = NULL;
2071
nd1 = get_variable_numdistinct(vardata1);
2072
nd2 = get_variable_numdistinct(vardata2);
2074
if (HeapTupleIsValid(vardata1->statsTuple))
2076
stats1 = (Form_pg_statistic) GETSTRUCT(vardata1->statsTuple);
2077
have_mcvs1 = get_attstatsslot(vardata1->statsTuple,
2079
vardata1->atttypmod,
2083
&values1, &nvalues1,
2084
&numbers1, &nnumbers1);
2087
if (HeapTupleIsValid(vardata2->statsTuple))
2089
stats2 = (Form_pg_statistic) GETSTRUCT(vardata2->statsTuple);
2090
have_mcvs2 = get_attstatsslot(vardata2->statsTuple,
2092
vardata2->atttypmod,
2096
&values2, &nvalues2,
2097
&numbers2, &nnumbers2);
2100
if (have_mcvs1 && have_mcvs2)
2103
* We have most-common-value lists for both relations. Run through
2104
* the lists to see which MCVs actually join to each other with the
2105
* given operator. This allows us to determine the exact join
2106
* selectivity for the portion of the relations represented by the MCV
2107
* lists. We still have to estimate for the remaining population, but
2108
* in a skewed distribution this gives us a big leg up in accuracy.
2109
* For motivation see the analysis in Y. Ioannidis and S.
2110
* Christodoulakis, "On the propagation of errors in the size of join
2111
* results", Technical Report 1018, Computer Science Dept., University
2112
* of Wisconsin, Madison, March 1991 (available from ftp.cs.wisc.edu).
2117
double nullfrac1 = stats1->stanullfrac;
2118
double nullfrac2 = stats2->stanullfrac;
2119
double matchprodfreq,
2131
fmgr_info(get_opcode(operator), &eqproc);
2132
hasmatch1 = (bool *) palloc0(nvalues1 * sizeof(bool));
2133
hasmatch2 = (bool *) palloc0(nvalues2 * sizeof(bool));
2136
* Note we assume that each MCV will match at most one member of the
2137
* other MCV list. If the operator isn't really equality, there could
2138
* be multiple matches --- but we don't look for them, both for speed
2139
* and because the math wouldn't add up...
2141
matchprodfreq = 0.0;
2143
for (i = 0; i < nvalues1; i++)
2147
for (j = 0; j < nvalues2; j++)
2151
if (DatumGetBool(FunctionCall2Coll(&eqproc,
2152
DEFAULT_COLLATION_OID,
2156
hasmatch1[i] = hasmatch2[j] = true;
2157
matchprodfreq += numbers1[i] * numbers2[j];
2163
CLAMP_PROBABILITY(matchprodfreq);
2164
/* Sum up frequencies of matched and unmatched MCVs */
2165
matchfreq1 = unmatchfreq1 = 0.0;
2166
for (i = 0; i < nvalues1; i++)
2169
matchfreq1 += numbers1[i];
2171
unmatchfreq1 += numbers1[i];
2173
CLAMP_PROBABILITY(matchfreq1);
2174
CLAMP_PROBABILITY(unmatchfreq1);
2175
matchfreq2 = unmatchfreq2 = 0.0;
2176
for (i = 0; i < nvalues2; i++)
2179
matchfreq2 += numbers2[i];
2181
unmatchfreq2 += numbers2[i];
2183
CLAMP_PROBABILITY(matchfreq2);
2184
CLAMP_PROBABILITY(unmatchfreq2);
2189
* Compute total frequency of non-null values that are not in the MCV
2192
otherfreq1 = 1.0 - nullfrac1 - matchfreq1 - unmatchfreq1;
2193
otherfreq2 = 1.0 - nullfrac2 - matchfreq2 - unmatchfreq2;
2194
CLAMP_PROBABILITY(otherfreq1);
2195
CLAMP_PROBABILITY(otherfreq2);
2198
* We can estimate the total selectivity from the point of view of
2199
* relation 1 as: the known selectivity for matched MCVs, plus
2200
* unmatched MCVs that are assumed to match against random members of
2201
* relation 2's non-MCV population, plus non-MCV values that are
2202
* assumed to match against random members of relation 2's unmatched
2203
* MCVs plus non-MCV values.
2205
totalsel1 = matchprodfreq;
2207
totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - nvalues2);
2209
totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
2211
/* Same estimate from the point of view of relation 2. */
2212
totalsel2 = matchprodfreq;
2214
totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - nvalues1);
2216
totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
2220
* Use the smaller of the two estimates. This can be justified in
2221
* essentially the same terms as given below for the no-stats case: to
2222
* a first approximation, we are estimating from the point of view of
2223
* the relation with smaller nd.
2225
selec = (totalsel1 < totalsel2) ? totalsel1 : totalsel2;
2230
* We do not have MCV lists for both sides. Estimate the join
2231
* selectivity as MIN(1/nd1,1/nd2)*(1-nullfrac1)*(1-nullfrac2). This
2232
* is plausible if we assume that the join operator is strict and the
2233
* non-null values are about equally distributed: a given non-null
2234
* tuple of rel1 will join to either zero or N2*(1-nullfrac2)/nd2 rows
2235
* of rel2, so total join rows are at most
2236
* N1*(1-nullfrac1)*N2*(1-nullfrac2)/nd2 giving a join selectivity of
2237
* not more than (1-nullfrac1)*(1-nullfrac2)/nd2. By the same logic it
2238
* is not more than (1-nullfrac1)*(1-nullfrac2)/nd1, so the expression
2239
* with MIN() is an upper bound. Using the MIN() means we estimate
2240
* from the point of view of the relation with smaller nd (since the
2241
* larger nd is determining the MIN). It is reasonable to assume that
2242
* most tuples in this rel will have join partners, so the bound is
2243
* probably reasonably tight and should be taken as-is.
2245
* XXX Can we be smarter if we have an MCV list for just one side? It
2246
* seems that if we assume equal distribution for the other side, we
2247
* end up with the same answer anyway.
2249
* An additional hack we use here is to clamp the nd1 and nd2 values
2250
* to not more than what we are estimating the input relation sizes to
2251
* be, providing a crude correction for the selectivity of restriction
2252
* clauses on those relations. (We don't do that in the other path
2253
* since there we are comparing the nd values to stats for the whole
2256
double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2257
double nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
2260
nd1 = Min(nd1, vardata1->rel->rows);
2262
nd2 = Min(nd2, vardata2->rel->rows);
2264
selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
2272
free_attstatsslot(vardata1->atttype, values1, nvalues1,
2273
numbers1, nnumbers1);
2275
free_attstatsslot(vardata2->atttype, values2, nvalues2,
2276
numbers2, nnumbers2);
2282
* eqjoinsel_semi --- eqjoinsel for semi join
2284
* (Also used for anti join, which we are supposed to estimate the same way.)
2285
* Caller has ensured that vardata1 is the LHS variable.
2288
eqjoinsel_semi(Oid operator,
2289
VariableStatData *vardata1, VariableStatData *vardata2)
2294
Form_pg_statistic stats1 = NULL;
2295
bool have_mcvs1 = false;
2296
Datum *values1 = NULL;
2298
float4 *numbers1 = NULL;
2300
bool have_mcvs2 = false;
2301
Datum *values2 = NULL;
2303
float4 *numbers2 = NULL;
2306
nd1 = get_variable_numdistinct(vardata1);
2307
nd2 = get_variable_numdistinct(vardata2);
2309
if (HeapTupleIsValid(vardata1->statsTuple))
2311
stats1 = (Form_pg_statistic) GETSTRUCT(vardata1->statsTuple);
2312
have_mcvs1 = get_attstatsslot(vardata1->statsTuple,
2314
vardata1->atttypmod,
2318
&values1, &nvalues1,
2319
&numbers1, &nnumbers1);
2322
if (HeapTupleIsValid(vardata2->statsTuple))
2324
have_mcvs2 = get_attstatsslot(vardata2->statsTuple,
2326
vardata2->atttypmod,
2330
&values2, &nvalues2,
2331
&numbers2, &nnumbers2);
2334
if (have_mcvs1 && have_mcvs2 && OidIsValid(operator))
2337
* We have most-common-value lists for both relations. Run through
2338
* the lists to see which MCVs actually join to each other with the
2339
* given operator. This allows us to determine the exact join
2340
* selectivity for the portion of the relations represented by the MCV
2341
* lists. We still have to estimate for the remaining population, but
2342
* in a skewed distribution this gives us a big leg up in accuracy.
2347
double nullfrac1 = stats1->stanullfrac;
2354
fmgr_info(get_opcode(operator), &eqproc);
2355
hasmatch1 = (bool *) palloc0(nvalues1 * sizeof(bool));
2356
hasmatch2 = (bool *) palloc0(nvalues2 * sizeof(bool));
2359
* Note we assume that each MCV will match at most one member of the
2360
* other MCV list. If the operator isn't really equality, there could
2361
* be multiple matches --- but we don't look for them, both for speed
2362
* and because the math wouldn't add up...
2365
for (i = 0; i < nvalues1; i++)
2369
for (j = 0; j < nvalues2; j++)
2373
if (DatumGetBool(FunctionCall2Coll(&eqproc,
2374
DEFAULT_COLLATION_OID,
2378
hasmatch1[i] = hasmatch2[j] = true;
2384
/* Sum up frequencies of matched MCVs */
2386
for (i = 0; i < nvalues1; i++)
2389
matchfreq1 += numbers1[i];
2391
CLAMP_PROBABILITY(matchfreq1);
2396
* Now we need to estimate the fraction of relation 1 that has at
2397
* least one join partner. We know for certain that the matched MCVs
2398
* do, so that gives us a lower bound, but we're really in the dark
2399
* about everything else. Our crude approach is: if nd1 <= nd2 then
2400
* assume all non-null rel1 rows have join partners, else assume for
2401
* the uncertain rows that a fraction nd2/nd1 have join partners. We
2402
* can discount the known-matched MCVs from the distinct-values counts
2403
* before doing the division.
2405
* Crude as the above is, it's completely useless if we don't have
2406
* reliable ndistinct values for both sides. Hence, if either nd1
2407
* or nd2 is default, punt and assume half of the uncertain rows
2408
* have join partners.
2410
if (nd1 != DEFAULT_NUM_DISTINCT && nd2 != DEFAULT_NUM_DISTINCT)
2414
if (nd1 <= nd2 || nd2 <= 0)
2415
uncertainfrac = 1.0;
2417
uncertainfrac = nd2 / nd1;
2420
uncertainfrac = 0.5;
2421
uncertain = 1.0 - matchfreq1 - nullfrac1;
2422
CLAMP_PROBABILITY(uncertain);
2423
selec = matchfreq1 + uncertainfrac * uncertain;
2428
* Without MCV lists for both sides, we can only use the heuristic
2431
double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2433
if (nd1 != DEFAULT_NUM_DISTINCT && nd2 != DEFAULT_NUM_DISTINCT)
2436
nd1 = Min(nd1, vardata1->rel->rows);
2438
nd2 = Min(nd2, vardata2->rel->rows);
2440
if (nd1 <= nd2 || nd2 <= 0)
2441
selec = 1.0 - nullfrac1;
2443
selec = (nd2 / nd1) * (1.0 - nullfrac1);
2446
selec = 0.5 * (1.0 - nullfrac1);
2450
free_attstatsslot(vardata1->atttype, values1, nvalues1,
2451
numbers1, nnumbers1);
2453
free_attstatsslot(vardata2->atttype, values2, nvalues2,
2454
numbers2, nnumbers2);
2460
* neqjoinsel - Join selectivity of "!="
2463
neqjoinsel(PG_FUNCTION_ARGS)
2465
PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2466
Oid operator = PG_GETARG_OID(1);
2467
List *args = (List *) PG_GETARG_POINTER(2);
2468
JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2469
SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
2474
* We want 1 - eqjoinsel() where the equality operator is the one
2475
* associated with this != operator, that is, its negator.
2477
eqop = get_negator(operator);
2480
result = DatumGetFloat8(DirectFunctionCall5(eqjoinsel,
2481
PointerGetDatum(root),
2482
ObjectIdGetDatum(eqop),
2483
PointerGetDatum(args),
2484
Int16GetDatum(jointype),
2485
PointerGetDatum(sjinfo)));
2489
/* Use default selectivity (should we raise an error instead?) */
2490
result = DEFAULT_EQ_SEL;
2492
result = 1.0 - result;
2493
PG_RETURN_FLOAT8(result);
2497
* scalarltjoinsel - Join selectivity of "<" and "<=" for scalars
2500
scalarltjoinsel(PG_FUNCTION_ARGS)
2502
PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
2506
* scalargtjoinsel - Join selectivity of ">" and ">=" for scalars
2509
scalargtjoinsel(PG_FUNCTION_ARGS)
2511
PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
2515
* patternjoinsel - Generic code for pattern-match join selectivity.
2518
patternjoinsel(PG_FUNCTION_ARGS, Pattern_Type ptype, bool negate)
2520
/* For the moment we just punt. */
2521
return negate ? (1.0 - DEFAULT_MATCH_SEL) : DEFAULT_MATCH_SEL;
2525
* regexeqjoinsel - Join selectivity of regular-expression pattern match.
2528
regexeqjoinsel(PG_FUNCTION_ARGS)
2530
PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Regex, false));
2534
* icregexeqjoinsel - Join selectivity of case-insensitive regex match.
2537
icregexeqjoinsel(PG_FUNCTION_ARGS)
2539
PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Regex_IC, false));
2543
* likejoinsel - Join selectivity of LIKE pattern match.
2546
likejoinsel(PG_FUNCTION_ARGS)
2548
PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Like, false));
2552
* iclikejoinsel - Join selectivity of ILIKE pattern match.
2555
iclikejoinsel(PG_FUNCTION_ARGS)
2557
PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Like_IC, false));
2561
* regexnejoinsel - Join selectivity of regex non-match.
2564
regexnejoinsel(PG_FUNCTION_ARGS)
2566
PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Regex, true));
2570
* icregexnejoinsel - Join selectivity of case-insensitive regex non-match.
2573
icregexnejoinsel(PG_FUNCTION_ARGS)
2575
PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Regex_IC, true));
2579
* nlikejoinsel - Join selectivity of LIKE pattern non-match.
2582
nlikejoinsel(PG_FUNCTION_ARGS)
2584
PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Like, true));
2588
* icnlikejoinsel - Join selectivity of ILIKE pattern non-match.
2591
icnlikejoinsel(PG_FUNCTION_ARGS)
2593
PG_RETURN_FLOAT8(patternjoinsel(fcinfo, Pattern_Type_Like_IC, true));
2597
* mergejoinscansel - Scan selectivity of merge join.
2599
* A merge join will stop as soon as it exhausts either input stream.
2600
* Therefore, if we can estimate the ranges of both input variables,
2601
* we can estimate how much of the input will actually be read. This
2602
* can have a considerable impact on the cost when using indexscans.
2604
* Also, we can estimate how much of each input has to be read before the
2605
* first join pair is found, which will affect the join's startup time.
2607
* clause should be a clause already known to be mergejoinable. opfamily,
2608
* strategy, and nulls_first specify the sort ordering being used.
2611
* *leftstart is set to the fraction of the left-hand variable expected
2612
* to be scanned before the first join pair is found (0 to 1).
2613
* *leftend is set to the fraction of the left-hand variable expected
2614
* to be scanned before the join terminates (0 to 1).
2615
* *rightstart, *rightend similarly for the right-hand variable.
2618
mergejoinscansel(PlannerInfo *root, Node *clause,
2619
Oid opfamily, int strategy, bool nulls_first,
2620
Selectivity *leftstart, Selectivity *leftend,
2621
Selectivity *rightstart, Selectivity *rightend)
2625
VariableStatData leftvar,
2646
/* Set default results if we can't figure anything out. */
2647
/* XXX should default "start" fraction be a bit more than 0? */
2648
*leftstart = *rightstart = 0.0;
2649
*leftend = *rightend = 1.0;
2651
/* Deconstruct the merge clause */
2652
if (!is_opclause(clause))
2653
return; /* shouldn't happen */
2654
opno = ((OpExpr *) clause)->opno;
2655
left = get_leftop((Expr *) clause);
2656
right = get_rightop((Expr *) clause);
2658
return; /* shouldn't happen */
2660
/* Look for stats for the inputs */
2661
examine_variable(root, left, 0, &leftvar);
2662
examine_variable(root, right, 0, &rightvar);
2664
/* Extract the operator's declared left/right datatypes */
2665
get_op_opfamily_properties(opno, opfamily, false,
2669
Assert(op_strategy == BTEqualStrategyNumber);
2672
* Look up the various operators we need. If we don't find them all, it
2673
* probably means the opfamily is broken, but we just fail silently.
2675
* Note: we expect that pg_statistic histograms will be sorted by the '<'
2676
* operator, regardless of which sort direction we are considering.
2680
case BTLessStrategyNumber:
2682
if (op_lefttype == op_righttype)
2685
ltop = get_opfamily_member(opfamily,
2686
op_lefttype, op_righttype,
2687
BTLessStrategyNumber);
2688
leop = get_opfamily_member(opfamily,
2689
op_lefttype, op_righttype,
2690
BTLessEqualStrategyNumber);
2700
ltop = get_opfamily_member(opfamily,
2701
op_lefttype, op_righttype,
2702
BTLessStrategyNumber);
2703
leop = get_opfamily_member(opfamily,
2704
op_lefttype, op_righttype,
2705
BTLessEqualStrategyNumber);
2706
lsortop = get_opfamily_member(opfamily,
2707
op_lefttype, op_lefttype,
2708
BTLessStrategyNumber);
2709
rsortop = get_opfamily_member(opfamily,
2710
op_righttype, op_righttype,
2711
BTLessStrategyNumber);
2714
revltop = get_opfamily_member(opfamily,
2715
op_righttype, op_lefttype,
2716
BTLessStrategyNumber);
2717
revleop = get_opfamily_member(opfamily,
2718
op_righttype, op_lefttype,
2719
BTLessEqualStrategyNumber);
2722
case BTGreaterStrategyNumber:
2723
/* descending-order case */
2725
if (op_lefttype == op_righttype)
2728
ltop = get_opfamily_member(opfamily,
2729
op_lefttype, op_righttype,
2730
BTGreaterStrategyNumber);
2731
leop = get_opfamily_member(opfamily,
2732
op_lefttype, op_righttype,
2733
BTGreaterEqualStrategyNumber);
2736
lstatop = get_opfamily_member(opfamily,
2737
op_lefttype, op_lefttype,
2738
BTLessStrategyNumber);
2745
ltop = get_opfamily_member(opfamily,
2746
op_lefttype, op_righttype,
2747
BTGreaterStrategyNumber);
2748
leop = get_opfamily_member(opfamily,
2749
op_lefttype, op_righttype,
2750
BTGreaterEqualStrategyNumber);
2751
lsortop = get_opfamily_member(opfamily,
2752
op_lefttype, op_lefttype,
2753
BTGreaterStrategyNumber);
2754
rsortop = get_opfamily_member(opfamily,
2755
op_righttype, op_righttype,
2756
BTGreaterStrategyNumber);
2757
lstatop = get_opfamily_member(opfamily,
2758
op_lefttype, op_lefttype,
2759
BTLessStrategyNumber);
2760
rstatop = get_opfamily_member(opfamily,
2761
op_righttype, op_righttype,
2762
BTLessStrategyNumber);
2763
revltop = get_opfamily_member(opfamily,
2764
op_righttype, op_lefttype,
2765
BTGreaterStrategyNumber);
2766
revleop = get_opfamily_member(opfamily,
2767
op_righttype, op_lefttype,
2768
BTGreaterEqualStrategyNumber);
2772
goto fail; /* shouldn't get here */
2775
if (!OidIsValid(lsortop) ||
2776
!OidIsValid(rsortop) ||
2777
!OidIsValid(lstatop) ||
2778
!OidIsValid(rstatop) ||
2779
!OidIsValid(ltop) ||
2780
!OidIsValid(leop) ||
2781
!OidIsValid(revltop) ||
2782
!OidIsValid(revleop))
2783
goto fail; /* insufficient info in catalogs */
2785
/* Try to get ranges of both inputs */
2788
if (!get_variable_range(root, &leftvar, lstatop,
2789
&leftmin, &leftmax))
2790
goto fail; /* no range available from stats */
2791
if (!get_variable_range(root, &rightvar, rstatop,
2792
&rightmin, &rightmax))
2793
goto fail; /* no range available from stats */
2797
/* need to swap the max and min */
2798
if (!get_variable_range(root, &leftvar, lstatop,
2799
&leftmax, &leftmin))
2800
goto fail; /* no range available from stats */
2801
if (!get_variable_range(root, &rightvar, rstatop,
2802
&rightmax, &rightmin))
2803
goto fail; /* no range available from stats */
2807
* Now, the fraction of the left variable that will be scanned is the
2808
* fraction that's <= the right-side maximum value. But only believe
2809
* non-default estimates, else stick with our 1.0.
2811
selec = scalarineqsel(root, leop, isgt, &leftvar,
2812
rightmax, op_righttype);
2813
if (selec != DEFAULT_INEQ_SEL)
2816
/* And similarly for the right variable. */
2817
selec = scalarineqsel(root, revleop, isgt, &rightvar,
2818
leftmax, op_lefttype);
2819
if (selec != DEFAULT_INEQ_SEL)
2823
* Only one of the two "end" fractions can really be less than 1.0;
2824
* believe the smaller estimate and reset the other one to exactly 1.0. If
2825
* we get exactly equal estimates (as can easily happen with self-joins),
2828
if (*leftend > *rightend)
2830
else if (*leftend < *rightend)
2833
*leftend = *rightend = 1.0;
2836
* Also, the fraction of the left variable that will be scanned before the
2837
* first join pair is found is the fraction that's < the right-side
2838
* minimum value. But only believe non-default estimates, else stick with
2841
selec = scalarineqsel(root, ltop, isgt, &leftvar,
2842
rightmin, op_righttype);
2843
if (selec != DEFAULT_INEQ_SEL)
2846
/* And similarly for the right variable. */
2847
selec = scalarineqsel(root, revltop, isgt, &rightvar,
2848
leftmin, op_lefttype);
2849
if (selec != DEFAULT_INEQ_SEL)
2850
*rightstart = selec;
2853
* Only one of the two "start" fractions can really be more than zero;
2854
* believe the larger estimate and reset the other one to exactly 0.0. If
2855
* we get exactly equal estimates (as can easily happen with self-joins),
2858
if (*leftstart < *rightstart)
2860
else if (*leftstart > *rightstart)
2863
*leftstart = *rightstart = 0.0;
2866
* If the sort order is nulls-first, we're going to have to skip over any
2867
* nulls too. These would not have been counted by scalarineqsel, and we
2868
* can safely add in this fraction regardless of whether we believe
2869
* scalarineqsel's results or not. But be sure to clamp the sum to 1.0!
2873
Form_pg_statistic stats;
2875
if (HeapTupleIsValid(leftvar.statsTuple))
2877
stats = (Form_pg_statistic) GETSTRUCT(leftvar.statsTuple);
2878
*leftstart += stats->stanullfrac;
2879
CLAMP_PROBABILITY(*leftstart);
2880
*leftend += stats->stanullfrac;
2881
CLAMP_PROBABILITY(*leftend);
2883
if (HeapTupleIsValid(rightvar.statsTuple))
2885
stats = (Form_pg_statistic) GETSTRUCT(rightvar.statsTuple);
2886
*rightstart += stats->stanullfrac;
2887
CLAMP_PROBABILITY(*rightstart);
2888
*rightend += stats->stanullfrac;
2889
CLAMP_PROBABILITY(*rightend);
2893
/* Disbelieve start >= end, just in case that can happen */
2894
if (*leftstart >= *leftend)
2899
if (*rightstart >= *rightend)
2906
ReleaseVariableStats(leftvar);
2907
ReleaseVariableStats(rightvar);
2912
* Helper routine for estimate_num_groups: add an item to a list of
2913
* GroupVarInfos, but only if it's not known equal to any of the existing
2918
Node *var; /* might be an expression, not just a Var */
2919
RelOptInfo *rel; /* relation it belongs to */
2920
double ndistinct; /* # distinct values */
2924
add_unique_group_var(PlannerInfo *root, List *varinfos,
2925
Node *var, VariableStatData *vardata)
2927
GroupVarInfo *varinfo;
2931
ndistinct = get_variable_numdistinct(vardata);
2933
/* cannot use foreach here because of possible list_delete */
2934
lc = list_head(varinfos);
2937
varinfo = (GroupVarInfo *) lfirst(lc);
2939
/* must advance lc before list_delete possibly pfree's it */
2942
/* Drop exact duplicates */
2943
if (equal(var, varinfo->var))
2947
* Drop known-equal vars, but only if they belong to different
2948
* relations (see comments for estimate_num_groups)
2950
if (vardata->rel != varinfo->rel &&
2951
exprs_known_equal(root, var, varinfo->var))
2953
if (varinfo->ndistinct <= ndistinct)
2955
/* Keep older item, forget new one */
2960
/* Delete the older item */
2961
varinfos = list_delete_ptr(varinfos, varinfo);
2966
varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
2969
varinfo->rel = vardata->rel;
2970
varinfo->ndistinct = ndistinct;
2971
varinfos = lappend(varinfos, varinfo);
2976
* estimate_num_groups - Estimate number of groups in a grouped query
2978
* Given a query having a GROUP BY clause, estimate how many groups there
2979
* will be --- ie, the number of distinct combinations of the GROUP BY
2982
* This routine is also used to estimate the number of rows emitted by
2983
* a DISTINCT filtering step; that is an isomorphic problem. (Note:
2984
* actually, we only use it for DISTINCT when there's no grouping or
2985
* aggregation ahead of the DISTINCT.)
2989
* groupExprs - list of expressions being grouped by
2990
* input_rows - number of rows estimated to arrive at the group/unique
2993
* Given the lack of any cross-correlation statistics in the system, it's
2994
* impossible to do anything really trustworthy with GROUP BY conditions
2995
* involving multiple Vars. We should however avoid assuming the worst
2996
* case (all possible cross-product terms actually appear as groups) since
2997
* very often the grouped-by Vars are highly correlated. Our current approach
2999
* 1. Expressions yielding boolean are assumed to contribute two groups,
3000
* independently of their content, and are ignored in the subsequent
3001
* steps. This is mainly because tests like "col IS NULL" break the
3002
* heuristic used in step 2 especially badly.
3003
* 2. Reduce the given expressions to a list of unique Vars used. For
3004
* example, GROUP BY a, a + b is treated the same as GROUP BY a, b.
3005
* It is clearly correct not to count the same Var more than once.
3006
* It is also reasonable to treat f(x) the same as x: f() cannot
3007
* increase the number of distinct values (unless it is volatile,
3008
* which we consider unlikely for grouping), but it probably won't
3009
* reduce the number of distinct values much either.
3010
* As a special case, if a GROUP BY expression can be matched to an
3011
* expressional index for which we have statistics, then we treat the
3012
* whole expression as though it were just a Var.
3013
* 3. If the list contains Vars of different relations that are known equal
3014
* due to equivalence classes, then drop all but one of the Vars from each
3015
* known-equal set, keeping the one with smallest estimated # of values
3016
* (since the extra values of the others can't appear in joined rows).
3017
* Note the reason we only consider Vars of different relations is that
3018
* if we considered ones of the same rel, we'd be double-counting the
3019
* restriction selectivity of the equality in the next step.
3020
* 4. For Vars within a single source rel, we multiply together the numbers
3021
* of values, clamp to the number of rows in the rel (divided by 10 if
3022
* more than one Var), and then multiply by the selectivity of the
3023
* restriction clauses for that rel. When there's more than one Var,
3024
* the initial product is probably too high (it's the worst case) but
3025
* clamping to a fraction of the rel's rows seems to be a helpful
3026
* heuristic for not letting the estimate get out of hand. (The factor
3027
* of 10 is derived from pre-Postgres-7.4 practice.) Multiplying
3028
* by the restriction selectivity is effectively assuming that the
3029
* restriction clauses are independent of the grouping, which is a crummy
3030
* assumption, but it's hard to do better.
3031
* 5. If there are Vars from multiple rels, we repeat step 4 for each such
3032
* rel, and multiply the results together.
3033
* Note that rels not containing grouped Vars are ignored completely, as are
3034
* join clauses. Such rels cannot increase the number of groups, and we
3035
* assume such clauses do not reduce the number either (somewhat bogus,
3036
* but we don't have the info to do better).
3039
estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows)
3041
List *varinfos = NIL;
3045
/* We should not be called unless query has GROUP BY (or DISTINCT) */
3046
Assert(groupExprs != NIL);
3049
* Count groups derived from boolean grouping expressions. For other
3050
* expressions, find the unique Vars used, treating an expression as a Var
3051
* if we can find stats for it. For each one, record the statistical
3052
* estimate of number of distinct values (total in its table, without
3053
* regard for filtering).
3057
foreach(l, groupExprs)
3059
Node *groupexpr = (Node *) lfirst(l);
3060
VariableStatData vardata;
3064
/* Short-circuit for expressions returning boolean */
3065
if (exprType(groupexpr) == BOOLOID)
3072
* If examine_variable is able to deduce anything about the GROUP BY
3073
* expression, treat it as a single variable even if it's really more
3076
examine_variable(root, groupexpr, 0, &vardata);
3077
if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
3079
varinfos = add_unique_group_var(root, varinfos,
3080
groupexpr, &vardata);
3081
ReleaseVariableStats(vardata);
3084
ReleaseVariableStats(vardata);
3087
* Else pull out the component Vars. Handle PlaceHolderVars by
3088
* recursing into their arguments (effectively assuming that the
3089
* PlaceHolderVar doesn't change the number of groups, which boils
3090
* down to ignoring the possible addition of nulls to the result set).
3092
varshere = pull_var_clause(groupexpr, PVC_RECURSE_PLACEHOLDERS);
3095
* If we find any variable-free GROUP BY item, then either it is a
3096
* constant (and we can ignore it) or it contains a volatile function;
3097
* in the latter case we punt and assume that each input row will
3098
* yield a distinct group.
3100
if (varshere == NIL)
3102
if (contain_volatile_functions(groupexpr))
3108
* Else add variables to varinfos list
3110
foreach(l2, varshere)
3112
Node *var = (Node *) lfirst(l2);
3114
examine_variable(root, var, 0, &vardata);
3115
varinfos = add_unique_group_var(root, varinfos, var, &vardata);
3116
ReleaseVariableStats(vardata);
3121
* If now no Vars, we must have an all-constant or all-boolean GROUP BY
3124
if (varinfos == NIL)
3126
/* Guard against out-of-range answers */
3127
if (numdistinct > input_rows)
3128
numdistinct = input_rows;
3133
* Group Vars by relation and estimate total numdistinct.
3135
* For each iteration of the outer loop, we process the frontmost Var in
3136
* varinfos, plus all other Vars in the same relation. We remove these
3137
* Vars from the newvarinfos list for the next iteration. This is the
3138
* easiest way to group Vars of same rel together.
3142
GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
3143
RelOptInfo *rel = varinfo1->rel;
3144
double reldistinct = varinfo1->ndistinct;
3145
double relmaxndistinct = reldistinct;
3146
int relvarcount = 1;
3147
List *newvarinfos = NIL;
3150
* Get the product of numdistinct estimates of the Vars for this rel.
3151
* Also, construct new varinfos list of remaining Vars.
3153
for_each_cell(l, lnext(list_head(varinfos)))
3155
GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3157
if (varinfo2->rel == varinfo1->rel)
3159
reldistinct *= varinfo2->ndistinct;
3160
if (relmaxndistinct < varinfo2->ndistinct)
3161
relmaxndistinct = varinfo2->ndistinct;
3166
/* not time to process varinfo2 yet */
3167
newvarinfos = lcons(varinfo2, newvarinfos);
3172
* Sanity check --- don't divide by zero if empty relation.
3174
Assert(rel->reloptkind == RELOPT_BASEREL);
3175
if (rel->tuples > 0)
3178
* Clamp to size of rel, or size of rel / 10 if multiple Vars. The
3179
* fudge factor is because the Vars are probably correlated but we
3180
* don't know by how much. We should never clamp to less than the
3181
* largest ndistinct value for any of the Vars, though, since
3182
* there will surely be at least that many groups.
3184
double clamp = rel->tuples;
3186
if (relvarcount > 1)
3189
if (clamp < relmaxndistinct)
3191
clamp = relmaxndistinct;
3192
/* for sanity in case some ndistinct is too large: */
3193
if (clamp > rel->tuples)
3194
clamp = rel->tuples;
3197
if (reldistinct > clamp)
3198
reldistinct = clamp;
3201
* Multiply by restriction selectivity.
3203
reldistinct *= rel->rows / rel->tuples;
3206
* Update estimate of total distinct groups.
3208
numdistinct *= reldistinct;
3211
varinfos = newvarinfos;
3212
} while (varinfos != NIL);
3214
numdistinct = ceil(numdistinct);
3216
/* Guard against out-of-range answers */
3217
if (numdistinct > input_rows)
3218
numdistinct = input_rows;
3219
if (numdistinct < 1.0)
3226
* Estimate hash bucketsize fraction (ie, number of entries in a bucket
3227
* divided by total tuples in relation) if the specified expression is used
3230
* XXX This is really pretty bogus since we're effectively assuming that the
3231
* distribution of hash keys will be the same after applying restriction
3232
* clauses as it was in the underlying relation. However, we are not nearly
3233
* smart enough to figure out how the restrict clauses might change the
3234
* distribution, so this will have to do for now.
3236
* We are passed the number of buckets the executor will use for the given
3237
* input relation. If the data were perfectly distributed, with the same
3238
* number of tuples going into each available bucket, then the bucketsize
3239
* fraction would be 1/nbuckets. But this happy state of affairs will occur
3240
* only if (a) there are at least nbuckets distinct data values, and (b)
3241
* we have a not-too-skewed data distribution. Otherwise the buckets will
3242
* be nonuniformly occupied. If the other relation in the join has a key
3243
* distribution similar to this one's, then the most-loaded buckets are
3244
* exactly those that will be probed most often. Therefore, the "average"
3245
* bucket size for costing purposes should really be taken as something close
3246
* to the "worst case" bucket size. We try to estimate this by adjusting the
3247
* fraction if there are too few distinct data values, and then scaling up
3248
* by the ratio of the most common value's frequency to the average frequency.
3250
* If no statistics are available, use a default estimate of 0.1. This will
3251
* discourage use of a hash rather strongly if the inner relation is large,
3252
* which is what we want. We do not want to hash unless we know that the
3253
* inner rel is well-dispersed (or the alternatives seem much worse).
3256
estimate_hash_bucketsize(PlannerInfo *root, Node *hashkey, double nbuckets)
3258
VariableStatData vardata;
3267
examine_variable(root, hashkey, 0, &vardata);
3269
/* Get number of distinct values and fraction that are null */
3270
ndistinct = get_variable_numdistinct(&vardata);
3272
if (HeapTupleIsValid(vardata.statsTuple))
3274
Form_pg_statistic stats;
3276
stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
3277
stanullfrac = stats->stanullfrac;
3282
* Believe a default ndistinct only if it came from stats. Otherwise
3283
* punt and return 0.1, per comments above.
3285
if (ndistinct == DEFAULT_NUM_DISTINCT)
3287
ReleaseVariableStats(vardata);
3288
return (Selectivity) 0.1;
3294
/* Compute avg freq of all distinct data values in raw relation */
3295
avgfreq = (1.0 - stanullfrac) / ndistinct;
3298
* Adjust ndistinct to account for restriction clauses. Observe we are
3299
* assuming that the data distribution is affected uniformly by the
3300
* restriction clauses!
3302
* XXX Possibly better way, but much more expensive: multiply by
3303
* selectivity of rel's restriction clauses that mention the target Var.
3306
ndistinct *= vardata.rel->rows / vardata.rel->tuples;
3309
* Initial estimate of bucketsize fraction is 1/nbuckets as long as the
3310
* number of buckets is less than the expected number of distinct values;
3311
* otherwise it is 1/ndistinct.
3313
if (ndistinct > nbuckets)
3314
estfract = 1.0 / nbuckets;
3316
estfract = 1.0 / ndistinct;
3319
* Look up the frequency of the most common value, if available.
3323
if (HeapTupleIsValid(vardata.statsTuple))
3325
if (get_attstatsslot(vardata.statsTuple,
3326
vardata.atttype, vardata.atttypmod,
3327
STATISTIC_KIND_MCV, InvalidOid,
3330
&numbers, &nnumbers))
3333
* The first MCV stat is for the most common value.
3336
mcvfreq = numbers[0];
3337
free_attstatsslot(vardata.atttype, NULL, 0,
3343
* Adjust estimated bucketsize upward to account for skewed distribution.
3345
if (avgfreq > 0.0 && mcvfreq > avgfreq)
3346
estfract *= mcvfreq / avgfreq;
3349
* Clamp bucketsize to sane range (the above adjustment could easily
3350
* produce an out-of-range result). We set the lower bound a little above
3351
* zero, since zero isn't a very sane result.
3353
if (estfract < 1.0e-6)
3355
else if (estfract > 1.0)
3358
ReleaseVariableStats(vardata);
3360
return (Selectivity) estfract;
3364
/*-------------------------------------------------------------------------
3368
*-------------------------------------------------------------------------
3373
* Convert non-NULL values of the indicated types to the comparison
3374
* scale needed by scalarineqsel().
3375
* Returns "true" if successful.
3377
* XXX this routine is a hack: ideally we should look up the conversion
3378
* subroutines in pg_type.
3380
* All numeric datatypes are simply converted to their equivalent
3381
* "double" values. (NUMERIC values that are outside the range of "double"
3382
* are clamped to +/- HUGE_VAL.)
3384
* String datatypes are converted by convert_string_to_scalar(),
3385
* which is explained below. The reason why this routine deals with
3386
* three values at a time, not just one, is that we need it for strings.
3388
* The bytea datatype is just enough different from strings that it has
3389
* to be treated separately.
3391
* The several datatypes representing absolute times are all converted
3392
* to Timestamp, which is actually a double, and then we just use that
3393
* double value. Note this will give correct results even for the "special"
3394
* values of Timestamp, since those are chosen to compare correctly;
3395
* see timestamp_cmp.
3397
* The several datatypes representing relative times (intervals) are all
3398
* converted to measurements expressed in seconds.
3401
convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue,
3402
Datum lobound, Datum hibound, Oid boundstypid,
3403
double *scaledlobound, double *scaledhibound)
3406
* Both the valuetypid and the boundstypid should exactly match the
3407
* declared input type(s) of the operator we are invoked for, so we just
3408
* error out if either is not recognized.
3410
* XXX The histogram we are interpolating between points of could belong
3411
* to a column that's only binary-compatible with the declared type. In
3412
* essence we are assuming that the semantics of binary-compatible types
3413
* are enough alike that we can use a histogram generated with one type's
3414
* operators to estimate selectivity for the other's. This is outright
3415
* wrong in some cases --- in particular signed versus unsigned
3416
* interpretation could trip us up. But it's useful enough in the
3417
* majority of cases that we do it anyway. Should think about more
3418
* rigorous ways to do it.
3423
* Built-in numeric types
3434
case REGPROCEDUREOID:
3436
case REGOPERATOROID:
3440
case REGDICTIONARYOID:
3441
*scaledvalue = convert_numeric_to_scalar(value, valuetypid);
3442
*scaledlobound = convert_numeric_to_scalar(lobound, boundstypid);
3443
*scaledhibound = convert_numeric_to_scalar(hibound, boundstypid);
3447
* Built-in string types
3455
char *valstr = convert_string_datum(value, valuetypid);
3456
char *lostr = convert_string_datum(lobound, boundstypid);
3457
char *histr = convert_string_datum(hibound, boundstypid);
3459
convert_string_to_scalar(valstr, scaledvalue,
3460
lostr, scaledlobound,
3461
histr, scaledhibound);
3469
* Built-in bytea type
3473
convert_bytea_to_scalar(value, scaledvalue,
3474
lobound, scaledlobound,
3475
hibound, scaledhibound);
3480
* Built-in time types
3483
case TIMESTAMPTZOID:
3491
*scaledvalue = convert_timevalue_to_scalar(value, valuetypid);
3492
*scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid);
3493
*scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid);
3497
* Built-in network types
3502
*scaledvalue = convert_network_to_scalar(value, valuetypid);
3503
*scaledlobound = convert_network_to_scalar(lobound, boundstypid);
3504
*scaledhibound = convert_network_to_scalar(hibound, boundstypid);
3507
/* Don't know how to convert */
3508
*scaledvalue = *scaledlobound = *scaledhibound = 0;
3513
* Do convert_to_scalar()'s work for any numeric data type.
3516
convert_numeric_to_scalar(Datum value, Oid typid)
3521
return (double) DatumGetBool(value);
3523
return (double) DatumGetInt16(value);
3525
return (double) DatumGetInt32(value);
3527
return (double) DatumGetInt64(value);
3529
return (double) DatumGetFloat4(value);
3531
return (double) DatumGetFloat8(value);
3533
/* Note: out-of-range values will be clamped to +-HUGE_VAL */
3535
DatumGetFloat8(DirectFunctionCall1(numeric_float8_no_overflow,
3539
case REGPROCEDUREOID:
3541
case REGOPERATOROID:
3545
case REGDICTIONARYOID:
3546
/* we can treat OIDs as integers... */
3547
return (double) DatumGetObjectId(value);
3551
* Can't get here unless someone tries to use scalarltsel/scalargtsel on
3552
* an operator with one numeric and one non-numeric operand.
3554
elog(ERROR, "unsupported type: %u", typid);
3559
* Do convert_to_scalar()'s work for any character-string data type.
3561
* String datatypes are converted to a scale that ranges from 0 to 1,
3562
* where we visualize the bytes of the string as fractional digits.
3564
* We do not want the base to be 256, however, since that tends to
3565
* generate inflated selectivity estimates; few databases will have
3566
* occurrences of all 256 possible byte values at each position.
3567
* Instead, use the smallest and largest byte values seen in the bounds
3568
* as the estimated range for each byte, after some fudging to deal with
3569
* the fact that we probably aren't going to see the full range that way.
3571
* An additional refinement is that we discard any common prefix of the
3572
* three strings before computing the scaled values. This allows us to
3573
* "zoom in" when we encounter a narrow data range. An example is a phone
3574
* number database where all the values begin with the same area code.
3575
* (Actually, the bounds will be adjacent histogram-bin-boundary values,
3576
* so this is more likely to happen than you might think.)
3579
convert_string_to_scalar(char *value,
3580
double *scaledvalue,
3582
double *scaledlobound,
3584
double *scaledhibound)
3590
rangelo = rangehi = (unsigned char) hibound[0];
3591
for (sptr = lobound; *sptr; sptr++)
3593
if (rangelo > (unsigned char) *sptr)
3594
rangelo = (unsigned char) *sptr;
3595
if (rangehi < (unsigned char) *sptr)
3596
rangehi = (unsigned char) *sptr;
3598
for (sptr = hibound; *sptr; sptr++)
3600
if (rangelo > (unsigned char) *sptr)
3601
rangelo = (unsigned char) *sptr;
3602
if (rangehi < (unsigned char) *sptr)
3603
rangehi = (unsigned char) *sptr;
3605
/* If range includes any upper-case ASCII chars, make it include all */
3606
if (rangelo <= 'Z' && rangehi >= 'A')
3613
/* Ditto lower-case */
3614
if (rangelo <= 'z' && rangehi >= 'a')
3622
if (rangelo <= '9' && rangehi >= '0')
3631
* If range includes less than 10 chars, assume we have not got enough
3632
* data, and make it include regular ASCII set.
3634
if (rangehi - rangelo < 9)
3641
* Now strip any common prefix of the three strings.
3645
if (*lobound != *hibound || *lobound != *value)
3647
lobound++, hibound++, value++;
3651
* Now we can do the conversions.
3653
*scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
3654
*scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
3655
*scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
3659
convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
3661
int slen = strlen(value);
3667
return 0.0; /* empty string has scalar value 0 */
3670
* Since base is at least 10, need not consider more than about 20 chars
3675
/* Convert initial characters to fraction */
3676
base = rangehi - rangelo + 1;
3681
int ch = (unsigned char) *value++;
3685
else if (ch > rangehi)
3687
num += ((double) (ch - rangelo)) / denom;
3695
* Convert a string-type Datum into a palloc'd, null-terminated string.
3697
* When using a non-C locale, we must pass the string through strxfrm()
3698
* before continuing, so as to generate correct locale-specific results.
3701
convert_string_datum(Datum value, Oid typid)
3708
val = (char *) palloc(2);
3709
val[0] = DatumGetChar(value);
3715
val = TextDatumGetCString(value);
3719
NameData *nm = (NameData *) DatumGetPointer(value);
3721
val = pstrdup(NameStr(*nm));
3727
* Can't get here unless someone tries to use scalarltsel on an
3728
* operator with one string and one non-string operand.
3730
elog(ERROR, "unsupported type: %u", typid);
3734
if (!lc_collate_is_c(DEFAULT_COLLATION_OID))
3741
* Note: originally we guessed at a suitable output buffer size, and
3742
* only needed to call strxfrm twice if our guess was too small.
3743
* However, it seems that some versions of Solaris have buggy strxfrm
3744
* that can write past the specified buffer length in that scenario.
3745
* So, do it the dumb way for portability.
3747
* Yet other systems (e.g., glibc) sometimes return a smaller value
3748
* from the second call than the first; thus the Assert must be <= not
3749
* == as you'd expect. Can't any of these people program their way
3750
* out of a paper bag?
3752
* XXX: strxfrm doesn't support UTF-8 encoding on Win32, it can return
3753
* bogus data or set an error. This is not really a problem unless it
3754
* crashes since it will only give an estimation error and nothing
3757
#if _MSC_VER == 1400 /* VS.Net 2005 */
3761
* http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?
3762
* FeedbackID=99694 */
3766
xfrmlen = strxfrm(x, val, 0);
3769
xfrmlen = strxfrm(NULL, val, 0);
3774
* On Windows, strxfrm returns INT_MAX when an error occurs. Instead
3775
* of trying to allocate this much memory (and fail), just return the
3776
* original string unmodified as if we were in the C locale.
3778
if (xfrmlen == INT_MAX)
3781
xfrmstr = (char *) palloc(xfrmlen + 1);
3782
xfrmlen2 = strxfrm(xfrmstr, val, xfrmlen + 1);
3783
Assert(xfrmlen2 <= xfrmlen);
3792
* Do convert_to_scalar()'s work for any bytea data type.
3794
* Very similar to convert_string_to_scalar except we can't assume
3795
* null-termination and therefore pass explicit lengths around.
3797
* Also, assumptions about likely "normal" ranges of characters have been
3798
* removed - a data range of 0..255 is always used, for now. (Perhaps
3799
* someday we will add information about actual byte data range to
3803
convert_bytea_to_scalar(Datum value,
3804
double *scaledvalue,
3806
double *scaledlobound,
3808
double *scaledhibound)
3812
valuelen = VARSIZE(DatumGetPointer(value)) - VARHDRSZ,
3813
loboundlen = VARSIZE(DatumGetPointer(lobound)) - VARHDRSZ,
3814
hiboundlen = VARSIZE(DatumGetPointer(hibound)) - VARHDRSZ,
3817
unsigned char *valstr = (unsigned char *) VARDATA(DatumGetPointer(value)),
3818
*lostr = (unsigned char *) VARDATA(DatumGetPointer(lobound)),
3819
*histr = (unsigned char *) VARDATA(DatumGetPointer(hibound));
3822
* Assume bytea data is uniformly distributed across all byte values.
3828
* Now strip any common prefix of the three strings.
3830
minlen = Min(Min(valuelen, loboundlen), hiboundlen);
3831
for (i = 0; i < minlen; i++)
3833
if (*lostr != *histr || *lostr != *valstr)
3835
lostr++, histr++, valstr++;
3836
loboundlen--, hiboundlen--, valuelen--;
3840
* Now we can do the conversions.
3842
*scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
3843
*scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
3844
*scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
3848
convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
3849
int rangelo, int rangehi)
3856
return 0.0; /* empty string has scalar value 0 */
3859
* Since base is 256, need not consider more than about 10 chars (even
3860
* this many seems like overkill)
3865
/* Convert initial characters to fraction */
3866
base = rangehi - rangelo + 1;
3869
while (valuelen-- > 0)
3875
else if (ch > rangehi)
3877
num += ((double) (ch - rangelo)) / denom;
3885
* Do convert_to_scalar()'s work for any timevalue data type.
3888
convert_timevalue_to_scalar(Datum value, Oid typid)
3893
return DatumGetTimestamp(value);
3894
case TIMESTAMPTZOID:
3895
return DatumGetTimestampTz(value);
3897
return DatumGetTimestamp(DirectFunctionCall1(abstime_timestamp,
3900
return date2timestamp_no_overflow(DatumGetDateADT(value));
3903
Interval *interval = DatumGetIntervalP(value);
3906
* Convert the month part of Interval to days using assumed
3907
* average month length of 365.25/12.0 days. Not too
3908
* accurate, but plenty good enough for our purposes.
3910
#ifdef HAVE_INT64_TIMESTAMP
3911
return interval->time + interval->day * (double) USECS_PER_DAY +
3912
interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
3914
return interval->time + interval->day * SECS_PER_DAY +
3915
interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * (double) SECS_PER_DAY);
3919
#ifdef HAVE_INT64_TIMESTAMP
3920
return (DatumGetRelativeTime(value) * 1000000.0);
3922
return DatumGetRelativeTime(value);
3926
TimeInterval tinterval = DatumGetTimeInterval(value);
3928
#ifdef HAVE_INT64_TIMESTAMP
3929
if (tinterval->status != 0)
3930
return ((tinterval->data[1] - tinterval->data[0]) * 1000000.0);
3932
if (tinterval->status != 0)
3933
return tinterval->data[1] - tinterval->data[0];
3935
return 0; /* for lack of a better idea */
3938
return DatumGetTimeADT(value);
3941
TimeTzADT *timetz = DatumGetTimeTzADTP(value);
3943
/* use GMT-equivalent time */
3944
#ifdef HAVE_INT64_TIMESTAMP
3945
return (double) (timetz->time + (timetz->zone * 1000000.0));
3947
return (double) (timetz->time + timetz->zone);
3953
* Can't get here unless someone tries to use scalarltsel/scalargtsel on
3954
* an operator with one timevalue and one non-timevalue operand.
3956
elog(ERROR, "unsupported type: %u", typid);
3962
* get_restriction_variable
3963
* Examine the args of a restriction clause to see if it's of the
3964
* form (variable op pseudoconstant) or (pseudoconstant op variable),
3965
* where "variable" could be either a Var or an expression in vars of a
3966
* single relation. If so, extract information about the variable,
3967
* and also indicate which side it was on and the other argument.
3970
* root: the planner info
3971
* args: clause argument list
3972
* varRelid: see specs for restriction selectivity functions
3974
* Outputs: (these are valid only if TRUE is returned)
3975
* *vardata: gets information about variable (see examine_variable)
3976
* *other: gets other clause argument, aggressively reduced to a constant
3977
* *varonleft: set TRUE if variable is on the left, FALSE if on the right
3979
* Returns TRUE if a variable is identified, otherwise FALSE.
3981
* Note: if there are Vars on both sides of the clause, we must fail, because
3982
* callers are expecting that the other side will act like a pseudoconstant.
3985
get_restriction_variable(PlannerInfo *root, List *args, int varRelid,
3986
VariableStatData *vardata, Node **other,
3991
VariableStatData rdata;
3993
/* Fail if not a binary opclause (probably shouldn't happen) */
3994
if (list_length(args) != 2)
3997
left = (Node *) linitial(args);
3998
right = (Node *) lsecond(args);
4001
* Examine both sides. Note that when varRelid is nonzero, Vars of other
4002
* relations will be treated as pseudoconstants.
4004
examine_variable(root, left, varRelid, vardata);
4005
examine_variable(root, right, varRelid, &rdata);
4008
* If one side is a variable and the other not, we win.
4010
if (vardata->rel && rdata.rel == NULL)
4013
*other = estimate_expression_value(root, rdata.var);
4014
/* Assume we need no ReleaseVariableStats(rdata) here */
4018
if (vardata->rel == NULL && rdata.rel)
4021
*other = estimate_expression_value(root, vardata->var);
4022
/* Assume we need no ReleaseVariableStats(*vardata) here */
4027
/* Ooops, clause has wrong structure (probably var op var) */
4028
ReleaseVariableStats(*vardata);
4029
ReleaseVariableStats(rdata);
4035
* get_join_variables
4036
* Apply examine_variable() to each side of a join clause.
4037
* Also, attempt to identify whether the join clause has the same
4038
* or reversed sense compared to the SpecialJoinInfo.
4040
* We consider the join clause "normal" if it is "lhs_var OP rhs_var",
4041
* or "reversed" if it is "rhs_var OP lhs_var". In complicated cases
4042
* where we can't tell for sure, we default to assuming it's normal.
4045
get_join_variables(PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo,
4046
VariableStatData *vardata1, VariableStatData *vardata2,
4047
bool *join_is_reversed)
4052
if (list_length(args) != 2)
4053
elog(ERROR, "join operator should take two arguments");
4055
left = (Node *) linitial(args);
4056
right = (Node *) lsecond(args);
4058
examine_variable(root, left, 0, vardata1);
4059
examine_variable(root, right, 0, vardata2);
4061
if (vardata1->rel &&
4062
bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4063
*join_is_reversed = true; /* var1 is on RHS */
4064
else if (vardata2->rel &&
4065
bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4066
*join_is_reversed = true; /* var2 is on LHS */
4068
*join_is_reversed = false;
4073
* Try to look up statistical data about an expression.
4074
* Fill in a VariableStatData struct to describe the expression.
4077
* root: the planner info
4078
* node: the expression tree to examine
4079
* varRelid: see specs for restriction selectivity functions
4081
* Outputs: *vardata is filled as follows:
4082
* var: the input expression (with any binary relabeling stripped, if
4083
* it is or contains a variable; but otherwise the type is preserved)
4084
* rel: RelOptInfo for relation containing variable; NULL if expression
4085
* contains no Vars (NOTE this could point to a RelOptInfo of a
4086
* subquery, not one in the current query).
4087
* statsTuple: the pg_statistic entry for the variable, if one exists;
4089
* freefunc: pointer to a function to release statsTuple with.
4090
* vartype: exposed type of the expression; this should always match
4091
* the declared input type of the operator we are estimating for.
4092
* atttype, atttypmod: type data to pass to get_attstatsslot(). This is
4093
* commonly the same as the exposed type of the variable argument,
4094
* but can be different in binary-compatible-type cases.
4095
* isunique: TRUE if we were able to match the var to a unique index,
4096
* implying its values are unique for this query.
4098
* Caller is responsible for doing ReleaseVariableStats() before exiting.
4101
examine_variable(PlannerInfo *root, Node *node, int varRelid,
4102
VariableStatData *vardata)
4108
/* Make sure we don't return dangling pointers in vardata */
4109
MemSet(vardata, 0, sizeof(VariableStatData));
4111
/* Save the exposed type of the expression */
4112
vardata->vartype = exprType(node);
4114
/* Look inside any binary-compatible relabeling */
4116
if (IsA(node, RelabelType))
4117
basenode = (Node *) ((RelabelType *) node)->arg;
4121
/* Fast path for a simple Var */
4123
if (IsA(basenode, Var) &&
4124
(varRelid == 0 || varRelid == ((Var *) basenode)->varno))
4126
Var *var = (Var *) basenode;
4129
vardata->var = basenode; /* return Var without relabeling */
4130
vardata->rel = find_base_rel(root, var->varno);
4131
vardata->atttype = var->vartype;
4132
vardata->atttypmod = var->vartypmod;
4133
vardata->isunique = has_unique_index(vardata->rel, var->varattno);
4135
rte = root->simple_rte_array[var->varno];
4137
if (get_relation_stats_hook &&
4138
(*get_relation_stats_hook) (root, rte, var->varattno, vardata))
4141
* The hook took control of acquiring a stats tuple. If it did
4142
* supply a tuple, it'd better have supplied a freefunc.
4144
if (HeapTupleIsValid(vardata->statsTuple) &&
4146
elog(ERROR, "no function provided to release variable stats with");
4148
else if (rte->rtekind == RTE_RELATION)
4150
vardata->statsTuple = SearchSysCache3(STATRELATTINH,
4151
ObjectIdGetDatum(rte->relid),
4152
Int16GetDatum(var->varattno),
4153
BoolGetDatum(rte->inh));
4154
vardata->freefunc = ReleaseSysCache;
4159
* XXX This means the Var comes from a JOIN or sub-SELECT. Later
4160
* add code to dig down into the join etc and see if we can trace
4161
* the variable to something with stats. (But beware of
4162
* sub-SELECTs with DISTINCT/GROUP BY/etc. Perhaps there are no
4163
* cases where this would really be useful, because we'd have
4164
* flattened the subselect if it is??)
4172
* Okay, it's a more complicated expression. Determine variable
4173
* membership. Note that when varRelid isn't zero, only vars of that
4174
* relation are considered "real" vars.
4176
varnos = pull_varnos(basenode);
4180
switch (bms_membership(varnos))
4183
/* No Vars at all ... must be pseudo-constant clause */
4186
if (varRelid == 0 || bms_is_member(varRelid, varnos))
4188
onerel = find_base_rel(root,
4189
(varRelid ? varRelid : bms_singleton_member(varnos)));
4190
vardata->rel = onerel;
4191
node = basenode; /* strip any relabeling */
4193
/* else treat it as a constant */
4198
/* treat it as a variable of a join relation */
4199
vardata->rel = find_join_rel(root, varnos);
4200
node = basenode; /* strip any relabeling */
4202
else if (bms_is_member(varRelid, varnos))
4204
/* ignore the vars belonging to other relations */
4205
vardata->rel = find_base_rel(root, varRelid);
4206
node = basenode; /* strip any relabeling */
4207
/* note: no point in expressional-index search here */
4209
/* else treat it as a constant */
4215
vardata->var = node;
4216
vardata->atttype = exprType(node);
4217
vardata->atttypmod = exprTypmod(node);
4222
* We have an expression in vars of a single relation. Try to match
4223
* it to expressional index columns, in hopes of finding some
4226
* XXX it's conceivable that there are multiple matches with different
4227
* index opfamilies; if so, we need to pick one that matches the
4228
* operator we are estimating for. FIXME later.
4232
foreach(ilist, onerel->indexlist)
4234
IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
4235
ListCell *indexpr_item;
4238
indexpr_item = list_head(index->indexprs);
4239
if (indexpr_item == NULL)
4240
continue; /* no expressions here... */
4242
for (pos = 0; pos < index->ncolumns; pos++)
4244
if (index->indexkeys[pos] == 0)
4248
if (indexpr_item == NULL)
4249
elog(ERROR, "too few entries in indexprs list");
4250
indexkey = (Node *) lfirst(indexpr_item);
4251
if (indexkey && IsA(indexkey, RelabelType))
4252
indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4253
if (equal(node, indexkey))
4256
* Found a match ... is it a unique index? Tests here
4257
* should match has_unique_index().
4259
if (index->unique &&
4260
index->ncolumns == 1 &&
4261
(index->indpred == NIL || index->predOK))
4262
vardata->isunique = true;
4265
* Has it got stats? We only consider stats for
4266
* non-partial indexes, since partial indexes probably
4267
* don't reflect whole-relation statistics; the above
4268
* check for uniqueness is the only info we take from
4271
* An index stats hook, however, must make its own
4272
* decisions about what to do with partial indexes.
4274
if (get_index_stats_hook &&
4275
(*get_index_stats_hook) (root, index->indexoid,
4279
* The hook took control of acquiring a stats
4280
* tuple. If it did supply a tuple, it'd better
4281
* have supplied a freefunc.
4283
if (HeapTupleIsValid(vardata->statsTuple) &&
4285
elog(ERROR, "no function provided to release variable stats with");
4287
else if (index->indpred == NIL)
4289
vardata->statsTuple =
4290
SearchSysCache3(STATRELATTINH,
4291
ObjectIdGetDatum(index->indexoid),
4292
Int16GetDatum(pos + 1),
4293
BoolGetDatum(false));
4294
vardata->freefunc = ReleaseSysCache;
4296
if (vardata->statsTuple)
4299
indexpr_item = lnext(indexpr_item);
4302
if (vardata->statsTuple)
4309
* get_variable_numdistinct
4310
* Estimate the number of distinct values of a variable.
4312
* vardata: results of examine_variable
4314
* NB: be careful to produce an integral result, since callers may compare
4315
* the result to exact integer counts.
4318
get_variable_numdistinct(VariableStatData *vardata)
4324
* Determine the stadistinct value to use. There are cases where we can
4325
* get an estimate even without a pg_statistic entry, or can get a better
4326
* value than is in pg_statistic.
4328
if (HeapTupleIsValid(vardata->statsTuple))
4330
/* Use the pg_statistic entry */
4331
Form_pg_statistic stats;
4333
stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
4334
stadistinct = stats->stadistinct;
4336
else if (vardata->vartype == BOOLOID)
4339
* Special-case boolean columns: presumably, two distinct values.
4341
* Are there any other datatypes we should wire in special estimates
4349
* We don't keep statistics for system columns, but in some cases we
4350
* can infer distinctness anyway.
4352
if (vardata->var && IsA(vardata->var, Var))
4354
switch (((Var *) vardata->var)->varattno)
4356
case ObjectIdAttributeNumber:
4357
case SelfItemPointerAttributeNumber:
4358
stadistinct = -1.0; /* unique */
4360
case TableOidAttributeNumber:
4361
stadistinct = 1.0; /* only 1 value */
4364
stadistinct = 0.0; /* means "unknown" */
4369
stadistinct = 0.0; /* means "unknown" */
4372
* XXX consider using estimate_num_groups on expressions?
4377
* If there is a unique index for the variable, assume it is unique no
4378
* matter what pg_statistic says; the statistics could be out of date, or
4379
* we might have found a partial unique index that proves the var is
4380
* unique for this query.
4382
if (vardata->isunique)
4386
* If we had an absolute estimate, use that.
4388
if (stadistinct > 0.0)
4392
* Otherwise we need to get the relation size; punt if not available.
4394
if (vardata->rel == NULL)
4395
return DEFAULT_NUM_DISTINCT;
4396
ntuples = vardata->rel->tuples;
4398
return DEFAULT_NUM_DISTINCT;
4401
* If we had a relative estimate, use that.
4403
if (stadistinct < 0.0)
4404
return floor((-stadistinct * ntuples) + 0.5);
4407
* With no data, estimate ndistinct = ntuples if the table is small, else
4410
if (ntuples < DEFAULT_NUM_DISTINCT)
4413
return DEFAULT_NUM_DISTINCT;
4417
* get_variable_range
4418
* Estimate the minimum and maximum value of the specified variable.
4419
* If successful, store values in *min and *max, and return TRUE.
4420
* If no data available, return FALSE.
4422
* sortop is the "<" comparison operator to use. This should generally
4423
* be "<" not ">", as only the former is likely to be found in pg_statistic.
4426
get_variable_range(PlannerInfo *root, VariableStatData *vardata, Oid sortop,
4427
Datum *min, Datum *max)
4431
bool have_data = false;
4439
* XXX It's very tempting to try to use the actual column min and max, if
4440
* we can get them relatively-cheaply with an index probe. However, since
4441
* this function is called many times during join planning, that could
4442
* have unpleasant effects on planning speed. Need more investigation
4443
* before enabling this.
4446
if (get_actual_variable_range(root, vardata, sortop, min, max))
4450
if (!HeapTupleIsValid(vardata->statsTuple))
4452
/* no stats available, so default result */
4456
get_typlenbyval(vardata->atttype, &typLen, &typByVal);
4459
* If there is a histogram, grab the first and last values.
4461
* If there is a histogram that is sorted with some other operator than
4462
* the one we want, fail --- this suggests that there is data we can't
4465
if (get_attstatsslot(vardata->statsTuple,
4466
vardata->atttype, vardata->atttypmod,
4467
STATISTIC_KIND_HISTOGRAM, sortop,
4474
tmin = datumCopy(values[0], typByVal, typLen);
4475
tmax = datumCopy(values[nvalues - 1], typByVal, typLen);
4478
free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
4480
else if (get_attstatsslot(vardata->statsTuple,
4481
vardata->atttype, vardata->atttypmod,
4482
STATISTIC_KIND_HISTOGRAM, InvalidOid,
4487
free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
4492
* If we have most-common-values info, look for extreme MCVs. This is
4493
* needed even if we also have a histogram, since the histogram excludes
4494
* the MCVs. However, usually the MCVs will not be the extreme values, so
4495
* avoid unnecessary data copying.
4497
if (get_attstatsslot(vardata->statsTuple,
4498
vardata->atttype, vardata->atttypmod,
4499
STATISTIC_KIND_MCV, InvalidOid,
4504
bool tmin_is_mcv = false;
4505
bool tmax_is_mcv = false;
4508
fmgr_info(get_opcode(sortop), &opproc);
4510
for (i = 0; i < nvalues; i++)
4514
tmin = tmax = values[i];
4515
tmin_is_mcv = tmax_is_mcv = have_data = true;
4518
if (DatumGetBool(FunctionCall2Coll(&opproc,
4519
DEFAULT_COLLATION_OID,
4525
if (DatumGetBool(FunctionCall2Coll(&opproc,
4526
DEFAULT_COLLATION_OID,
4534
tmin = datumCopy(tmin, typByVal, typLen);
4536
tmax = datumCopy(tmax, typByVal, typLen);
4537
free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
4547
* get_actual_variable_range
4548
* Attempt to identify the current *actual* minimum and/or maximum
4549
* of the specified variable, by looking for a suitable btree index
4550
* and fetching its low and/or high values.
4551
* If successful, store values in *min and *max, and return TRUE.
4552
* (Either pointer can be NULL if that endpoint isn't needed.)
4553
* If no data available, return FALSE.
4555
* sortop is the "<" comparison operator to use.
4558
get_actual_variable_range(PlannerInfo *root, VariableStatData *vardata,
4560
Datum *min, Datum *max)
4562
bool have_data = false;
4563
RelOptInfo *rel = vardata->rel;
4567
/* No hope if no relation or it doesn't have indexes */
4568
if (rel == NULL || rel->indexlist == NIL)
4570
/* If it has indexes it must be a plain relation */
4571
rte = root->simple_rte_array[rel->relid];
4572
Assert(rte->rtekind == RTE_RELATION);
4574
/* Search through the indexes to see if any match our problem */
4575
foreach(lc, rel->indexlist)
4577
IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
4578
ScanDirection indexscandir;
4580
/* Ignore non-btree indexes */
4581
if (index->relam != BTREE_AM_OID)
4585
* Ignore partial indexes --- we only want stats that cover the entire
4588
if (index->indpred != NIL)
4592
* The index list might include hypothetical indexes inserted by a
4593
* get_relation_info hook --- don't try to access them.
4595
if (index->hypothetical)
4599
* The first index column must match the desired variable and sort
4600
* operator --- but we can use a descending-order index.
4602
if (!match_index_to_operand(vardata->var, 0, index))
4604
switch (get_op_opfamily_strategy(sortop, index->sortopfamily[0]))
4606
case BTLessStrategyNumber:
4607
if (index->reverse_sort[0])
4608
indexscandir = BackwardScanDirection;
4610
indexscandir = ForwardScanDirection;
4612
case BTGreaterStrategyNumber:
4613
if (index->reverse_sort[0])
4614
indexscandir = ForwardScanDirection;
4616
indexscandir = BackwardScanDirection;
4619
/* index doesn't match the sortop */
4624
* Found a suitable index to extract data from. We'll need an EState
4625
* and a bunch of other infrastructure.
4629
ExprContext *econtext;
4630
MemoryContext tmpcontext;
4631
MemoryContext oldcontext;
4634
IndexInfo *indexInfo;
4635
TupleTableSlot *slot;
4638
ScanKeyData scankeys[1];
4639
IndexScanDesc index_scan;
4641
Datum values[INDEX_MAX_KEYS];
4642
bool isnull[INDEX_MAX_KEYS];
4644
estate = CreateExecutorState();
4645
econtext = GetPerTupleExprContext(estate);
4646
/* Make sure any cruft is generated in the econtext's memory */
4647
tmpcontext = econtext->ecxt_per_tuple_memory;
4648
oldcontext = MemoryContextSwitchTo(tmpcontext);
4651
* Open the table and index so we can read from them. We should
4652
* already have at least AccessShareLock on the table, but not
4653
* necessarily on the index.
4655
heapRel = heap_open(rte->relid, NoLock);
4656
indexRel = index_open(index->indexoid, AccessShareLock);
4658
/* extract index key information from the index's pg_index info */
4659
indexInfo = BuildIndexInfo(indexRel);
4661
/* some other stuff */
4662
slot = MakeSingleTupleTableSlot(RelationGetDescr(heapRel));
4663
econtext->ecxt_scantuple = slot;
4664
get_typlenbyval(vardata->atttype, &typLen, &typByVal);
4666
/* set up an IS NOT NULL scan key so that we ignore nulls */
4667
ScanKeyEntryInitialize(&scankeys[0],
4668
SK_ISNULL | SK_SEARCHNOTNULL,
4669
1, /* index col to scan */
4670
InvalidStrategy, /* no strategy */
4671
InvalidOid, /* no strategy subtype */
4672
InvalidOid, /* no collation */
4673
InvalidOid, /* no reg proc for this */
4674
(Datum) 0); /* constant */
4678
/* If min is requested ... */
4681
index_scan = index_beginscan(heapRel, indexRel, SnapshotNow,
4683
index_rescan(index_scan, scankeys, 1, NULL, 0);
4685
/* Fetch first tuple in sortop's direction */
4686
if ((tup = index_getnext(index_scan,
4687
indexscandir)) != NULL)
4689
/* Extract the index column values from the heap tuple */
4690
ExecStoreTuple(tup, slot, InvalidBuffer, false);
4691
FormIndexDatum(indexInfo, slot, estate,
4694
/* Shouldn't have got a null, but be careful */
4696
elog(ERROR, "found unexpected null value in index \"%s\"",
4697
RelationGetRelationName(indexRel));
4699
/* Copy the index column value out to caller's context */
4700
MemoryContextSwitchTo(oldcontext);
4701
*min = datumCopy(values[0], typByVal, typLen);
4702
MemoryContextSwitchTo(tmpcontext);
4707
index_endscan(index_scan);
4710
/* If max is requested, and we didn't find the index is empty */
4711
if (max && have_data)
4713
index_scan = index_beginscan(heapRel, indexRel, SnapshotNow,
4715
index_rescan(index_scan, scankeys, 1, NULL, 0);
4717
/* Fetch first tuple in reverse direction */
4718
if ((tup = index_getnext(index_scan,
4719
-indexscandir)) != NULL)
4721
/* Extract the index column values from the heap tuple */
4722
ExecStoreTuple(tup, slot, InvalidBuffer, false);
4723
FormIndexDatum(indexInfo, slot, estate,
4726
/* Shouldn't have got a null, but be careful */
4728
elog(ERROR, "found unexpected null value in index \"%s\"",
4729
RelationGetRelationName(indexRel));
4731
/* Copy the index column value out to caller's context */
4732
MemoryContextSwitchTo(oldcontext);
4733
*max = datumCopy(values[0], typByVal, typLen);
4734
MemoryContextSwitchTo(tmpcontext);
4739
index_endscan(index_scan);
4742
/* Clean everything up */
4743
ExecDropSingleTupleTableSlot(slot);
4745
index_close(indexRel, AccessShareLock);
4746
heap_close(heapRel, NoLock);
4748
MemoryContextSwitchTo(oldcontext);
4749
FreeExecutorState(estate);
4751
/* And we're done */
4760
/*-------------------------------------------------------------------------
4762
* Pattern analysis functions
4764
* These routines support analysis of LIKE and regular-expression patterns
4765
* by the planner/optimizer. It's important that they agree with the
4766
* regular-expression code in backend/regex/ and the LIKE code in
4767
* backend/utils/adt/like.c. Also, the computation of the fixed prefix
4768
* must be conservative: if we report a string longer than the true fixed
4769
* prefix, the query may produce actually wrong answers, rather than just
4770
* getting a bad selectivity estimate!
4772
* Note that the prefix-analysis functions are called from
4773
* backend/optimizer/path/indxpath.c as well as from routines in this file.
4775
*-------------------------------------------------------------------------
4779
* Check whether char is a letter (and, hence, subject to case-folding)
4781
* In multibyte character sets, we can't use isalpha, and it does not seem
4782
* worth trying to convert to wchar_t to use iswalpha. Instead, just assume
4783
* any multibyte char is potentially case-varying.
4786
pattern_char_isalpha(char c, bool is_multibyte,
4787
pg_locale_t locale, bool locale_is_c)
4790
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
4791
else if (is_multibyte && IS_HIGHBIT_SET(c))
4793
#ifdef HAVE_LOCALE_T
4795
return isalpha_l((unsigned char) c, locale);
4798
return isalpha((unsigned char) c);
4802
* Extract the fixed prefix, if any, for a pattern.
4804
* *prefix is set to a palloc'd prefix string (in the form of a Const node),
4805
* or to NULL if no fixed prefix exists for the pattern.
4806
* *rest is set to a palloc'd Const representing the remainder of the pattern
4807
* after the portion describing the fixed prefix.
4808
* Each of these has the same type (TEXT or BYTEA) as the given pattern Const.
4810
* The return value distinguishes no fixed prefix, a partial prefix,
4811
* or an exact-match-only pattern.
4814
static Pattern_Prefix_Status
4815
like_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation,
4816
Const **prefix_const, Const **rest_const)
4822
Oid typeid = patt_const->consttype;
4825
bool is_multibyte = (pg_database_encoding_max_length() > 1);
4826
pg_locale_t locale = 0;
4827
bool locale_is_c = false;
4829
/* the right-hand const is type text or bytea */
4830
Assert(typeid == BYTEAOID || typeid == TEXTOID);
4832
if (case_insensitive)
4834
if (typeid == BYTEAOID)
4836
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4837
errmsg("case insensitive matching not supported on type bytea")));
4839
/* If case-insensitive, we need locale info */
4840
if (lc_ctype_is_c(collation))
4842
else if (collation != DEFAULT_COLLATION_OID)
4844
if (!OidIsValid(collation))
4847
* This typically means that the parser could not resolve a
4848
* conflict of implicit collations, so report it that way.
4851
(errcode(ERRCODE_INDETERMINATE_COLLATION),
4852
errmsg("could not determine which collation to use for ILIKE"),
4853
errhint("Use the COLLATE clause to set the collation explicitly.")));
4855
locale = pg_newlocale_from_collation(collation);
4859
if (typeid != BYTEAOID)
4861
patt = TextDatumGetCString(patt_const->constvalue);
4862
pattlen = strlen(patt);
4866
bytea *bstr = DatumGetByteaP(patt_const->constvalue);
4868
pattlen = VARSIZE(bstr) - VARHDRSZ;
4869
patt = (char *) palloc(pattlen);
4870
memcpy(patt, VARDATA(bstr), pattlen);
4871
if ((Pointer) bstr != DatumGetPointer(patt_const->constvalue))
4875
match = palloc(pattlen + 1);
4877
for (pos = 0; pos < pattlen; pos++)
4879
/* % and _ are wildcard characters in LIKE */
4880
if (patt[pos] == '%' ||
4884
/* Backslash escapes the next character */
4885
if (patt[pos] == '\\')
4892
/* Stop if case-varying character (it's sort of a wildcard) */
4893
if (case_insensitive &&
4894
pattern_char_isalpha(patt[pos], is_multibyte, locale, locale_is_c))
4897
match[match_pos++] = patt[pos];
4900
match[match_pos] = '\0';
4903
if (typeid != BYTEAOID)
4905
*prefix_const = string_to_const(match, typeid);
4906
*rest_const = string_to_const(rest, typeid);
4910
*prefix_const = string_to_bytea_const(match, match_pos);
4911
*rest_const = string_to_bytea_const(rest, pattlen - pos);
4917
/* in LIKE, an empty pattern is an exact match! */
4919
return Pattern_Prefix_Exact; /* reached end of pattern, so exact */
4922
return Pattern_Prefix_Partial;
4924
return Pattern_Prefix_None;
4927
static Pattern_Prefix_Status
4928
regex_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation,
4929
Const **prefix_const, Const **rest_const)
4936
bool have_leading_paren;
4939
Oid typeid = patt_const->consttype;
4940
bool is_multibyte = (pg_database_encoding_max_length() > 1);
4941
pg_locale_t locale = 0;
4942
bool locale_is_c = false;
4945
* Should be unnecessary, there are no bytea regex operators defined. As
4946
* such, it should be noted that the rest of this function has *not* been
4947
* made safe for binary (possibly NULL containing) strings.
4949
if (typeid == BYTEAOID)
4951
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4952
errmsg("regular-expression matching not supported on type bytea")));
4954
if (case_insensitive)
4956
/* If case-insensitive, we need locale info */
4957
if (lc_ctype_is_c(collation))
4959
else if (collation != DEFAULT_COLLATION_OID)
4961
if (!OidIsValid(collation))
4964
* This typically means that the parser could not resolve a
4965
* conflict of implicit collations, so report it that way.
4968
(errcode(ERRCODE_INDETERMINATE_COLLATION),
4969
errmsg("could not determine which collation to use for regular expression"),
4970
errhint("Use the COLLATE clause to set the collation explicitly.")));
4972
locale = pg_newlocale_from_collation(collation);
4976
/* the right-hand const is type text for all of these */
4977
patt = TextDatumGetCString(patt_const->constvalue);
4980
* Check for ARE director prefix. It's worth our trouble to recognize
4981
* this because similar_escape() used to use it, and some other code might
4982
* still use it, to force ARE mode.
4985
if (strncmp(patt, "***:", 4) == 0)
4988
/* Pattern must be anchored left */
4989
if (patt[pos] != '^')
4993
*prefix_const = NULL;
4994
*rest_const = string_to_const(rest, typeid);
4996
return Pattern_Prefix_None;
5001
* If '|' is present in pattern, then there may be multiple alternatives
5002
* for the start of the string. (There are cases where this isn't so, for
5003
* instance if the '|' is inside parens, but detecting that reliably is
5006
if (strchr(patt + pos, '|') != NULL)
5010
*prefix_const = NULL;
5011
*rest_const = string_to_const(rest, typeid);
5013
return Pattern_Prefix_None;
5016
/* OK, allocate space for pattern */
5017
match = palloc(strlen(patt) + 1);
5018
prev_match_pos = match_pos = 0;
5021
* We special-case the syntax '^(...)$' because psql uses it. But beware:
5022
* sequences beginning "(?" are not what they seem, unless they're "(?:".
5023
* (We must recognize that because of similar_escape().)
5025
have_leading_paren = false;
5026
if (patt[pos] == '(' &&
5027
(patt[pos + 1] != '?' || patt[pos + 2] == ':'))
5029
have_leading_paren = true;
5030
pos += (patt[pos + 1] != '?' ? 1 : 3);
5033
/* Scan remainder of pattern */
5040
* Check for characters that indicate multiple possible matches here.
5041
* Also, drop out at ')' or '$' so the termination test works right.
5043
if (patt[pos] == '.' ||
5051
/* Stop if case-varying character (it's sort of a wildcard) */
5052
if (case_insensitive &&
5053
pattern_char_isalpha(patt[pos], is_multibyte, locale, locale_is_c))
5057
* Check for quantifiers. Except for +, this means the preceding
5058
* character is optional, so we must remove it from the prefix too!
5060
if (patt[pos] == '*' ||
5064
match_pos = prev_match_pos;
5068
if (patt[pos] == '+')
5075
* Normally, backslash quotes the next character. But in AREs,
5076
* backslash followed by alphanumeric is an escape, not a quoted
5077
* character. Must treat it as having multiple possible matches.
5078
* Note: since only ASCII alphanumerics are escapes, we don't have to
5079
* be paranoid about multibyte or collations here.
5081
if (patt[pos] == '\\')
5083
if (isalnum((unsigned char) patt[pos + 1]))
5086
if (patt[pos] == '\0')
5089
/* save position in case we need to back up on next loop cycle */
5090
prev_match_pos = match_pos;
5092
/* must use encoding-aware processing here */
5093
len = pg_mblen(&patt[pos]);
5094
memcpy(&match[match_pos], &patt[pos], len);
5099
match[match_pos] = '\0';
5102
if (have_leading_paren && patt[pos] == ')')
5105
if (patt[pos] == '$' && patt[pos + 1] == '\0')
5107
rest = &patt[pos + 1];
5109
*prefix_const = string_to_const(match, typeid);
5110
*rest_const = string_to_const(rest, typeid);
5115
return Pattern_Prefix_Exact; /* pattern specifies exact match */
5118
*prefix_const = string_to_const(match, typeid);
5119
*rest_const = string_to_const(rest, typeid);
5125
return Pattern_Prefix_Partial;
5127
return Pattern_Prefix_None;
5130
Pattern_Prefix_Status
5131
pattern_fixed_prefix(Const *patt, Pattern_Type ptype, Oid collation,
5132
Const **prefix, Const **rest)
5134
Pattern_Prefix_Status result;
5138
case Pattern_Type_Like:
5139
result = like_fixed_prefix(patt, false, collation, prefix, rest);
5141
case Pattern_Type_Like_IC:
5142
result = like_fixed_prefix(patt, true, collation, prefix, rest);
5144
case Pattern_Type_Regex:
5145
result = regex_fixed_prefix(patt, false, collation, prefix, rest);
5147
case Pattern_Type_Regex_IC:
5148
result = regex_fixed_prefix(patt, true, collation, prefix, rest);
5151
elog(ERROR, "unrecognized ptype: %d", (int) ptype);
5152
result = Pattern_Prefix_None; /* keep compiler quiet */
5159
* Estimate the selectivity of a fixed prefix for a pattern match.
5161
* A fixed prefix "foo" is estimated as the selectivity of the expression
5162
* "variable >= 'foo' AND variable < 'fop'" (see also indxpath.c).
5164
* The selectivity estimate is with respect to the portion of the column
5165
* population represented by the histogram --- the caller must fold this
5166
* together with info about MCVs and NULLs.
5168
* We use the >= and < operators from the specified btree opfamily to do the
5169
* estimation. The given variable and Const must be of the associated
5172
* XXX Note: we make use of the upper bound to estimate operator selectivity
5173
* even if the locale is such that we cannot rely on the upper-bound string.
5174
* The selectivity only needs to be approximately right anyway, so it seems
5175
* more useful to use the upper-bound code than not.
5178
prefix_selectivity(PlannerInfo *root, VariableStatData *vardata,
5179
Oid vartype, Oid opfamily, Const *prefixcon)
5181
Selectivity prefixsel;
5184
Const *greaterstrcon;
5187
cmpopr = get_opfamily_member(opfamily, vartype, vartype,
5188
BTGreaterEqualStrategyNumber);
5189
if (cmpopr == InvalidOid)
5190
elog(ERROR, "no >= operator for opfamily %u", opfamily);
5191
fmgr_info(get_opcode(cmpopr), &opproc);
5193
prefixsel = ineq_histogram_selectivity(root, vardata, &opproc, true,
5194
prefixcon->constvalue,
5195
prefixcon->consttype);
5197
if (prefixsel < 0.0)
5199
/* No histogram is present ... return a suitable default estimate */
5200
return DEFAULT_MATCH_SEL;
5204
* If we can create a string larger than the prefix, say
5208
cmpopr = get_opfamily_member(opfamily, vartype, vartype,
5209
BTLessStrategyNumber);
5210
if (cmpopr == InvalidOid)
5211
elog(ERROR, "no < operator for opfamily %u", opfamily);
5212
fmgr_info(get_opcode(cmpopr), &opproc);
5213
greaterstrcon = make_greater_string(prefixcon, &opproc,
5214
DEFAULT_COLLATION_OID);
5219
topsel = ineq_histogram_selectivity(root, vardata, &opproc, false,
5220
greaterstrcon->constvalue,
5221
greaterstrcon->consttype);
5223
/* ineq_histogram_selectivity worked before, it shouldn't fail now */
5224
Assert(topsel >= 0.0);
5227
* Merge the two selectivities in the same way as for a range query
5228
* (see clauselist_selectivity()). Note that we don't need to worry
5229
* about double-exclusion of nulls, since ineq_histogram_selectivity
5230
* doesn't count those anyway.
5232
prefixsel = topsel + prefixsel - 1.0;
5236
* If the prefix is long then the two bounding values might be too close
5237
* together for the histogram to distinguish them usefully, resulting in a
5238
* zero estimate (plus or minus roundoff error). To avoid returning a
5239
* ridiculously small estimate, compute the estimated selectivity for
5240
* "variable = 'foo'", and clamp to that. (Obviously, the resultant
5241
* estimate should be at least that.)
5243
* We apply this even if we couldn't make a greater string. That case
5244
* suggests that the prefix is near the maximum possible, and thus
5245
* probably off the end of the histogram, and thus we probably got a very
5246
* small estimate from the >= condition; so we still need to clamp.
5248
cmpopr = get_opfamily_member(opfamily, vartype, vartype,
5249
BTEqualStrategyNumber);
5250
if (cmpopr == InvalidOid)
5251
elog(ERROR, "no = operator for opfamily %u", opfamily);
5252
eq_sel = var_eq_const(vardata, cmpopr, prefixcon->constvalue,
5255
prefixsel = Max(prefixsel, eq_sel);
5262
* Estimate the selectivity of a pattern of the specified type.
5263
* Note that any fixed prefix of the pattern will have been removed already.
5265
* For now, we use a very simplistic approach: fixed characters reduce the
5266
* selectivity a good deal, character ranges reduce it a little,
5267
* wildcards (such as % for LIKE or .* for regex) increase it.
5270
#define FIXED_CHAR_SEL 0.20 /* about 1/5 */
5271
#define CHAR_RANGE_SEL 0.25
5272
#define ANY_CHAR_SEL 0.9 /* not 1, since it won't match end-of-string */
5273
#define FULL_WILDCARD_SEL 5.0
5274
#define PARTIAL_WILDCARD_SEL 2.0
5277
like_selectivity(Const *patt_const, bool case_insensitive)
5279
Selectivity sel = 1.0;
5281
Oid typeid = patt_const->consttype;
5285
/* the right-hand const is type text or bytea */
5286
Assert(typeid == BYTEAOID || typeid == TEXTOID);
5288
if (typeid == BYTEAOID && case_insensitive)
5290
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5291
errmsg("case insensitive matching not supported on type bytea")));
5293
if (typeid != BYTEAOID)
5295
patt = TextDatumGetCString(patt_const->constvalue);
5296
pattlen = strlen(patt);
5300
bytea *bstr = DatumGetByteaP(patt_const->constvalue);
5302
pattlen = VARSIZE(bstr) - VARHDRSZ;
5303
patt = (char *) palloc(pattlen);
5304
memcpy(patt, VARDATA(bstr), pattlen);
5305
if ((Pointer) bstr != DatumGetPointer(patt_const->constvalue))
5309
/* Skip any leading wildcard; it's already factored into initial sel */
5310
for (pos = 0; pos < pattlen; pos++)
5312
if (patt[pos] != '%' && patt[pos] != '_')
5316
for (; pos < pattlen; pos++)
5318
/* % and _ are wildcard characters in LIKE */
5319
if (patt[pos] == '%')
5320
sel *= FULL_WILDCARD_SEL;
5321
else if (patt[pos] == '_')
5322
sel *= ANY_CHAR_SEL;
5323
else if (patt[pos] == '\\')
5325
/* Backslash quotes the next character */
5329
sel *= FIXED_CHAR_SEL;
5332
sel *= FIXED_CHAR_SEL;
5334
/* Could get sel > 1 if multiple wildcards */
5343
regex_selectivity_sub(char *patt, int pattlen, bool case_insensitive)
5345
Selectivity sel = 1.0;
5346
int paren_depth = 0;
5347
int paren_pos = 0; /* dummy init to keep compiler quiet */
5350
for (pos = 0; pos < pattlen; pos++)
5352
if (patt[pos] == '(')
5354
if (paren_depth == 0)
5355
paren_pos = pos; /* remember start of parenthesized item */
5358
else if (patt[pos] == ')' && paren_depth > 0)
5361
if (paren_depth == 0)
5362
sel *= regex_selectivity_sub(patt + (paren_pos + 1),
5363
pos - (paren_pos + 1),
5366
else if (patt[pos] == '|' && paren_depth == 0)
5369
* If unquoted | is present at paren level 0 in pattern, we have
5370
* multiple alternatives; sum their probabilities.
5372
sel += regex_selectivity_sub(patt + (pos + 1),
5373
pattlen - (pos + 1),
5375
break; /* rest of pattern is now processed */
5377
else if (patt[pos] == '[')
5379
bool negclass = false;
5381
if (patt[++pos] == '^')
5386
if (patt[pos] == ']') /* ']' at start of class is not
5389
while (pos < pattlen && patt[pos] != ']')
5391
if (paren_depth == 0)
5392
sel *= (negclass ? (1.0 - CHAR_RANGE_SEL) : CHAR_RANGE_SEL);
5394
else if (patt[pos] == '.')
5396
if (paren_depth == 0)
5397
sel *= ANY_CHAR_SEL;
5399
else if (patt[pos] == '*' ||
5403
/* Ought to be smarter about quantifiers... */
5404
if (paren_depth == 0)
5405
sel *= PARTIAL_WILDCARD_SEL;
5407
else if (patt[pos] == '{')
5409
while (pos < pattlen && patt[pos] != '}')
5411
if (paren_depth == 0)
5412
sel *= PARTIAL_WILDCARD_SEL;
5414
else if (patt[pos] == '\\')
5416
/* backslash quotes the next character */
5420
if (paren_depth == 0)
5421
sel *= FIXED_CHAR_SEL;
5425
if (paren_depth == 0)
5426
sel *= FIXED_CHAR_SEL;
5429
/* Could get sel > 1 if multiple wildcards */
5436
regex_selectivity(Const *patt_const, bool case_insensitive)
5441
Oid typeid = patt_const->consttype;
5444
* Should be unnecessary, there are no bytea regex operators defined. As
5445
* such, it should be noted that the rest of this function has *not* been
5446
* made safe for binary (possibly NULL containing) strings.
5448
if (typeid == BYTEAOID)
5450
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5451
errmsg("regular-expression matching not supported on type bytea")));
5453
/* the right-hand const is type text for all of these */
5454
patt = TextDatumGetCString(patt_const->constvalue);
5455
pattlen = strlen(patt);
5457
/* If patt doesn't end with $, consider it to have a trailing wildcard */
5458
if (pattlen > 0 && patt[pattlen - 1] == '$' &&
5459
(pattlen == 1 || patt[pattlen - 2] != '\\'))
5461
/* has trailing $ */
5462
sel = regex_selectivity_sub(patt, pattlen - 1, case_insensitive);
5467
sel = regex_selectivity_sub(patt, pattlen, case_insensitive);
5468
sel *= FULL_WILDCARD_SEL;
5476
pattern_selectivity(Const *patt, Pattern_Type ptype)
5482
case Pattern_Type_Like:
5483
result = like_selectivity(patt, false);
5485
case Pattern_Type_Like_IC:
5486
result = like_selectivity(patt, true);
5488
case Pattern_Type_Regex:
5489
result = regex_selectivity(patt, false);
5491
case Pattern_Type_Regex_IC:
5492
result = regex_selectivity(patt, true);
5495
elog(ERROR, "unrecognized ptype: %d", (int) ptype);
5496
result = 1.0; /* keep compiler quiet */
5504
* Try to generate a string greater than the given string or any
5505
* string it is a prefix of. If successful, return a palloc'd string
5506
* in the form of a Const node; else return NULL.
5508
* The caller must provide the appropriate "less than" comparison function
5509
* for testing the strings, along with the collation to use.
5511
* The key requirement here is that given a prefix string, say "foo",
5512
* we must be able to generate another string "fop" that is greater than
5513
* all strings "foobar" starting with "foo". We can test that we have
5514
* generated a string greater than the prefix string, but in non-C collations
5515
* that is not a bulletproof guarantee that an extension of the string might
5516
* not sort after it; an example is that "foo " is less than "foo!", but it
5517
* is not clear that a "dictionary" sort ordering will consider "foo!" less
5518
* than "foo bar". CAUTION: Therefore, this function should be used only for
5519
* estimation purposes when working in a non-C collation.
5521
* To try to catch most cases where an extended string might otherwise sort
5522
* before the result value, we determine which of the strings "Z", "z", "y",
5523
* and "9" is seen as largest by the collation, and append that to the given
5524
* prefix before trying to find a string that compares as larger.
5526
* If we max out the righthand byte, truncate off the last character
5527
* and start incrementing the next. For example, if "z" were the last
5528
* character in the sort order, then we could produce "foo" as a
5529
* string greater than "fonz".
5531
* This could be rather slow in the worst case, but in most cases we
5532
* won't have to try more than one or two strings before succeeding.
5535
make_greater_string(const Const *str_const, FmgrInfo *ltproc, Oid collation)
5537
Oid datatype = str_const->consttype;
5541
text *cmptxt = NULL;
5544
* Get a modifiable copy of the prefix string in C-string format, and set
5545
* up the string we will compare to as a Datum. In C locale this can just
5546
* be the given prefix string, otherwise we need to add a suffix. Types
5547
* NAME and BYTEA sort bytewise so they don't need a suffix either.
5549
if (datatype == NAMEOID)
5551
workstr = DatumGetCString(DirectFunctionCall1(nameout,
5552
str_const->constvalue));
5553
len = strlen(workstr);
5554
cmpstr = str_const->constvalue;
5556
else if (datatype == BYTEAOID)
5558
bytea *bstr = DatumGetByteaP(str_const->constvalue);
5560
len = VARSIZE(bstr) - VARHDRSZ;
5561
workstr = (char *) palloc(len);
5562
memcpy(workstr, VARDATA(bstr), len);
5563
if ((Pointer) bstr != DatumGetPointer(str_const->constvalue))
5565
cmpstr = str_const->constvalue;
5569
workstr = TextDatumGetCString(str_const->constvalue);
5570
len = strlen(workstr);
5571
if (lc_collate_is_c(collation) || len == 0)
5572
cmpstr = str_const->constvalue;
5575
/* If first time through, determine the suffix to use */
5576
static char suffixchar = 0;
5577
static Oid suffixcollation = 0;
5579
if (!suffixchar || suffixcollation != collation)
5584
if (varstr_cmp(best, 1, "z", 1, collation) < 0)
5586
if (varstr_cmp(best, 1, "y", 1, collation) < 0)
5588
if (varstr_cmp(best, 1, "9", 1, collation) < 0)
5591
suffixcollation = collation;
5594
/* And build the string to compare to */
5595
cmptxt = (text *) palloc(VARHDRSZ + len + 1);
5596
SET_VARSIZE(cmptxt, VARHDRSZ + len + 1);
5597
memcpy(VARDATA(cmptxt), workstr, len);
5598
*(VARDATA(cmptxt) + len) = suffixchar;
5599
cmpstr = PointerGetDatum(cmptxt);
5605
unsigned char *lastchar = (unsigned char *) (workstr + len - 1);
5606
unsigned char savelastchar = *lastchar;
5609
* Try to generate a larger string by incrementing the last byte.
5611
while (*lastchar < (unsigned char) 255)
5613
Const *workstr_const;
5617
if (datatype != BYTEAOID)
5619
/* do not generate invalid encoding sequences */
5620
if (!pg_verifymbstr(workstr, len, true))
5622
workstr_const = string_to_const(workstr, datatype);
5625
workstr_const = string_to_bytea_const(workstr, len);
5627
if (DatumGetBool(FunctionCall2Coll(ltproc,
5630
workstr_const->constvalue)))
5632
/* Successfully made a string larger than cmpstr */
5636
return workstr_const;
5639
/* No good, release unusable value and try again */
5640
pfree(DatumGetPointer(workstr_const->constvalue));
5641
pfree(workstr_const);
5644
/* restore last byte so we don't confuse pg_mbcliplen */
5645
*lastchar = savelastchar;
5648
* Truncate off the last character, which might be more than 1 byte,
5649
* depending on the character encoding.
5651
if (datatype != BYTEAOID && pg_database_encoding_max_length() > 1)
5652
len = pg_mbcliplen(workstr, len, len - 1);
5656
if (datatype != BYTEAOID)
5657
workstr[len] = '\0';
5669
* Generate a Datum of the appropriate type from a C string.
5670
* Note that all of the supported types are pass-by-ref, so the
5671
* returned value should be pfree'd if no longer needed.
5674
string_to_datum(const char *str, Oid datatype)
5676
Assert(str != NULL);
5679
* We cheat a little by assuming that CStringGetTextDatum() will do for
5680
* bpchar and varchar constants too...
5682
if (datatype == NAMEOID)
5683
return DirectFunctionCall1(namein, CStringGetDatum(str));
5684
else if (datatype == BYTEAOID)
5685
return DirectFunctionCall1(byteain, CStringGetDatum(str));
5687
return CStringGetTextDatum(str);
5691
* Generate a Const node of the appropriate type from a C string.
5694
string_to_const(const char *str, Oid datatype)
5696
Datum conval = string_to_datum(str, datatype);
5701
* We only need to support a few datatypes here, so hard-wire properties
5702
* instead of incurring the expense of catalog lookups.
5709
collation = DEFAULT_COLLATION_OID;
5714
collation = InvalidOid;
5715
constlen = NAMEDATALEN;
5719
collation = InvalidOid;
5724
elog(ERROR, "unexpected datatype in string_to_const: %u",
5729
return makeConst(datatype, -1, collation, constlen,
5730
conval, false, false);
5734
* Generate a Const node of bytea type from a binary C string and a length.
5737
string_to_bytea_const(const char *str, size_t str_len)
5739
bytea *bstr = palloc(VARHDRSZ + str_len);
5742
memcpy(VARDATA(bstr), str, str_len);
5743
SET_VARSIZE(bstr, VARHDRSZ + str_len);
5744
conval = PointerGetDatum(bstr);
5746
return makeConst(BYTEAOID, -1, InvalidOid, -1, conval, false, false);
5749
/*-------------------------------------------------------------------------
5751
* Index cost estimation functions
5753
* genericcostestimate is a general-purpose estimator for use when we
5754
* don't have any better idea about how to estimate. Index-type-specific
5755
* knowledge can be incorporated in the type-specific routines.
5757
* One bit of index-type-specific knowledge we can relatively easily use
5758
* in genericcostestimate is the estimate of the number of index tuples
5759
* visited. If numIndexTuples is not 0 then it is used as the estimate,
5760
* otherwise we compute a generic estimate.
5762
*-------------------------------------------------------------------------
5766
genericcostestimate(PlannerInfo *root,
5767
IndexOptInfo *index,
5769
List *indexOrderBys,
5770
RelOptInfo *outer_rel,
5771
double numIndexTuples,
5772
Cost *indexStartupCost,
5773
Cost *indexTotalCost,
5774
Selectivity *indexSelectivity,
5775
double *indexCorrelation)
5777
double numIndexPages;
5778
double num_sa_scans;
5779
double num_outer_scans;
5781
QualCost index_qual_cost;
5782
double qual_op_cost;
5783
double qual_arg_cost;
5784
double spc_random_page_cost;
5785
List *selectivityQuals;
5789
* If the index is partial, AND the index predicate with the explicitly
5790
* given indexquals to produce a more accurate idea of the index
5791
* selectivity. However, we need to be careful not to insert redundant
5792
* clauses, because clauselist_selectivity() is easily fooled into
5793
* computing a too-low selectivity estimate. Our approach is to add
5794
* only the index predicate clause(s) that cannot be proven to be implied
5795
* by the given indexquals. This successfully handles cases such as a
5796
* qual "x = 42" used with a partial index "WHERE x >= 40 AND x < 50".
5797
* There are many other cases where we won't detect redundancy, leading
5798
* to a too-low selectivity estimate, which will bias the system in favor
5799
* of using partial indexes where possible. That is not necessarily bad
5802
* Note that indexQuals contains RestrictInfo nodes while the indpred
5803
* does not. This is OK for both predicate_implied_by() and
5804
* clauselist_selectivity().
5807
if (index->indpred != NIL)
5809
List *predExtraQuals = NIL;
5811
foreach(l, index->indpred)
5813
Node *predQual = (Node *) lfirst(l);
5814
List *oneQual = list_make1(predQual);
5816
if (!predicate_implied_by(oneQual, indexQuals))
5817
predExtraQuals = list_concat(predExtraQuals, oneQual);
5819
/* list_concat avoids modifying the passed-in indexQuals list */
5820
selectivityQuals = list_concat(predExtraQuals, indexQuals);
5823
selectivityQuals = indexQuals;
5826
* Check for ScalarArrayOpExpr index quals, and estimate the number of
5827
* index scans that will be performed.
5830
foreach(l, indexQuals)
5832
RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
5834
if (IsA(rinfo->clause, ScalarArrayOpExpr))
5836
ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
5837
int alength = estimate_array_length(lsecond(saop->args));
5840
num_sa_scans *= alength;
5844
/* Estimate the fraction of main-table tuples that will be visited */
5845
*indexSelectivity = clauselist_selectivity(root, selectivityQuals,
5851
* If caller didn't give us an estimate, estimate the number of index
5852
* tuples that will be visited. We do it in this rather peculiar-looking
5853
* way in order to get the right answer for partial indexes.
5855
if (numIndexTuples <= 0.0)
5857
numIndexTuples = *indexSelectivity * index->rel->tuples;
5860
* The above calculation counts all the tuples visited across all
5861
* scans induced by ScalarArrayOpExpr nodes. We want to consider the
5862
* average per-indexscan number, so adjust. This is a handy place to
5863
* round to integer, too. (If caller supplied tuple estimate, it's
5864
* responsible for handling these considerations.)
5866
numIndexTuples = rint(numIndexTuples / num_sa_scans);
5870
* We can bound the number of tuples by the index size in any case. Also,
5871
* always estimate at least one tuple is touched, even when
5872
* indexSelectivity estimate is tiny.
5874
if (numIndexTuples > index->tuples)
5875
numIndexTuples = index->tuples;
5876
if (numIndexTuples < 1.0)
5877
numIndexTuples = 1.0;
5880
* Estimate the number of index pages that will be retrieved.
5882
* We use the simplistic method of taking a pro-rata fraction of the total
5883
* number of index pages. In effect, this counts only leaf pages and not
5884
* any overhead such as index metapage or upper tree levels. In practice
5885
* this seems a better approximation than charging for access to the upper
5886
* levels, perhaps because those tend to stay in cache under load.
5888
if (index->pages > 1 && index->tuples > 1)
5889
numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
5891
numIndexPages = 1.0;
5893
/* fetch estimated page cost for schema containing index */
5894
get_tablespace_page_costs(index->reltablespace,
5895
&spc_random_page_cost,
5899
* Now compute the disk access costs.
5901
* The above calculations are all per-index-scan. However, if we are in a
5902
* nestloop inner scan, we can expect the scan to be repeated (with
5903
* different search keys) for each row of the outer relation. Likewise,
5904
* ScalarArrayOpExpr quals result in multiple index scans. This creates
5905
* the potential for cache effects to reduce the number of disk page
5906
* fetches needed. We want to estimate the average per-scan I/O cost in
5907
* the presence of caching.
5909
* We use the Mackert-Lohman formula (see costsize.c for details) to
5910
* estimate the total number of page fetches that occur. While this
5911
* wasn't what it was designed for, it seems a reasonable model anyway.
5912
* Note that we are counting pages not tuples anymore, so we take N = T =
5913
* index size, as if there were one "tuple" per page.
5915
if (outer_rel != NULL && outer_rel->rows > 1)
5917
num_outer_scans = outer_rel->rows;
5918
num_scans = num_sa_scans * num_outer_scans;
5922
num_outer_scans = 1;
5923
num_scans = num_sa_scans;
5928
double pages_fetched;
5930
/* total page fetches ignoring cache effects */
5931
pages_fetched = numIndexPages * num_scans;
5933
/* use Mackert and Lohman formula to adjust for cache effects */
5934
pages_fetched = index_pages_fetched(pages_fetched,
5936
(double) index->pages,
5940
* Now compute the total disk access cost, and then report a pro-rated
5941
* share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
5942
* since that's internal to the indexscan.)
5944
*indexTotalCost = (pages_fetched * spc_random_page_cost)
5950
* For a single index scan, we just charge spc_random_page_cost per
5953
*indexTotalCost = numIndexPages * spc_random_page_cost;
5957
* A difficulty with the leaf-pages-only cost approach is that for small
5958
* selectivities (eg, single index tuple fetched) all indexes will look
5959
* equally attractive because we will estimate exactly 1 leaf page to be
5960
* fetched. All else being equal, we should prefer physically smaller
5961
* indexes over larger ones. (An index might be smaller because it is
5962
* partial or because it contains fewer columns; presumably the other
5963
* columns in the larger index aren't useful to the query, or the larger
5964
* index would have better selectivity.)
5966
* We can deal with this by adding a very small "fudge factor" that
5967
* depends on the index size. The fudge factor used here is one
5968
* spc_random_page_cost per 100000 index pages, which should be small
5969
* enough to not alter index-vs-seqscan decisions, but will prevent
5970
* indexes of different sizes from looking exactly equally attractive.
5972
*indexTotalCost += index->pages * spc_random_page_cost / 100000.0;
5975
* CPU cost: any complex expressions in the indexquals will need to be
5976
* evaluated once at the start of the scan to reduce them to runtime keys
5977
* to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
5978
* CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
5979
* indexqual operator. Because we have numIndexTuples as a per-scan
5980
* number, we have to multiply by num_sa_scans to get the correct result
5981
* for ScalarArrayOpExpr cases. Similarly add in costs for any index
5982
* ORDER BY expressions.
5984
* Note: this neglects the possible costs of rechecking lossy operators
5985
* and OR-clause expressions. Detecting that that might be needed seems
5986
* more expensive than it's worth, though, considering all the other
5987
* inaccuracies here ...
5989
cost_qual_eval(&index_qual_cost, indexQuals, root);
5990
qual_arg_cost = index_qual_cost.startup + index_qual_cost.per_tuple;
5991
cost_qual_eval(&index_qual_cost, indexOrderBys, root);
5992
qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
5993
qual_op_cost = cpu_operator_cost *
5994
(list_length(indexQuals) + list_length(indexOrderBys));
5995
qual_arg_cost -= qual_op_cost;
5996
if (qual_arg_cost < 0) /* just in case... */
5999
*indexStartupCost = qual_arg_cost;
6000
*indexTotalCost += qual_arg_cost;
6001
*indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
6004
* We also add a CPU-cost component to represent the general costs of
6005
* starting an indexscan, such as analysis of btree index keys and initial
6006
* tree descent. This is estimated at 100x cpu_operator_cost, which is a
6007
* bit arbitrary but seems the right order of magnitude. (As noted above,
6008
* we don't charge any I/O for touching upper tree levels, but charging
6009
* nothing at all has been found too optimistic.)
6011
* Although this is startup cost with respect to any one scan, we add it
6012
* to the "total" cost component because it's only very interesting in the
6013
* many-ScalarArrayOpExpr-scan case, and there it will be paid over the
6014
* life of the scan node.
6016
*indexTotalCost += num_sa_scans * 100.0 * cpu_operator_cost;
6019
* Generic assumption about index correlation: there isn't any.
6021
*indexCorrelation = 0.0;
6026
btcostestimate(PG_FUNCTION_ARGS)
6028
PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
6029
IndexOptInfo *index = (IndexOptInfo *) PG_GETARG_POINTER(1);
6030
List *indexQuals = (List *) PG_GETARG_POINTER(2);
6031
List *indexOrderBys = (List *) PG_GETARG_POINTER(3);
6032
RelOptInfo *outer_rel = (RelOptInfo *) PG_GETARG_POINTER(4);
6033
Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(5);
6034
Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(6);
6035
Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(7);
6036
double *indexCorrelation = (double *) PG_GETARG_POINTER(8);
6039
VariableStatData vardata;
6040
double numIndexTuples;
6041
List *indexBoundQuals;
6045
bool found_is_null_op;
6046
double num_sa_scans;
6050
* For a btree scan, only leading '=' quals plus inequality quals for the
6051
* immediately next attribute contribute to index selectivity (these are
6052
* the "boundary quals" that determine the starting and stopping points of
6053
* the index scan). Additional quals can suppress visits to the heap, so
6054
* it's OK to count them in indexSelectivity, but they should not count
6055
* for estimating numIndexTuples. So we must examine the given indexQuals
6056
* to find out which ones count as boundary quals. We rely on the
6057
* knowledge that they are given in index column order.
6059
* For a RowCompareExpr, we consider only the first column, just as
6060
* rowcomparesel() does.
6062
* If there's a ScalarArrayOpExpr in the quals, we'll actually perform N
6063
* index scans not one, but the ScalarArrayOpExpr's operator can be
6064
* considered to act the same as it normally does.
6066
indexBoundQuals = NIL;
6070
found_is_null_op = false;
6072
foreach(l, indexQuals)
6074
RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
6080
bool is_null_op = false;
6082
Assert(IsA(rinfo, RestrictInfo));
6083
clause = rinfo->clause;
6084
if (IsA(clause, OpExpr))
6086
leftop = get_leftop(clause);
6087
rightop = get_rightop(clause);
6088
clause_op = ((OpExpr *) clause)->opno;
6090
else if (IsA(clause, RowCompareExpr))
6092
RowCompareExpr *rc = (RowCompareExpr *) clause;
6094
leftop = (Node *) linitial(rc->largs);
6095
rightop = (Node *) linitial(rc->rargs);
6096
clause_op = linitial_oid(rc->opnos);
6098
else if (IsA(clause, ScalarArrayOpExpr))
6100
ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6102
leftop = (Node *) linitial(saop->args);
6103
rightop = (Node *) lsecond(saop->args);
6104
clause_op = saop->opno;
6107
else if (IsA(clause, NullTest))
6109
NullTest *nt = (NullTest *) clause;
6111
leftop = (Node *) nt->arg;
6113
clause_op = InvalidOid;
6114
if (nt->nulltesttype == IS_NULL)
6116
found_is_null_op = true;
6122
elog(ERROR, "unsupported indexqual type: %d",
6123
(int) nodeTag(clause));
6124
continue; /* keep compiler quiet */
6126
if (match_index_to_operand(leftop, indexcol, index))
6128
/* clause_op is correct */
6130
else if (match_index_to_operand(rightop, indexcol, index))
6132
/* Must flip operator to get the opfamily member */
6133
clause_op = get_commutator(clause_op);
6137
/* Must be past the end of quals for indexcol, try next */
6139
break; /* done if no '=' qual for indexcol */
6142
if (match_index_to_operand(leftop, indexcol, index))
6144
/* clause_op is correct */
6146
else if (match_index_to_operand(rightop, indexcol, index))
6148
/* Must flip operator to get the opfamily member */
6149
clause_op = get_commutator(clause_op);
6153
/* No quals for new indexcol, so we are done */
6157
/* check for equality operator */
6158
if (OidIsValid(clause_op))
6160
op_strategy = get_op_opfamily_strategy(clause_op,
6161
index->opfamily[indexcol]);
6162
Assert(op_strategy != 0); /* not a member of opfamily?? */
6163
if (op_strategy == BTEqualStrategyNumber)
6166
else if (is_null_op)
6168
/* IS NULL is like = for purposes of selectivity determination */
6171
/* count up number of SA scans induced by indexBoundQuals only */
6172
if (IsA(clause, ScalarArrayOpExpr))
6174
ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6175
int alength = estimate_array_length(lsecond(saop->args));
6178
num_sa_scans *= alength;
6180
indexBoundQuals = lappend(indexBoundQuals, rinfo);
6184
* If index is unique and we found an '=' clause for each column, we can
6185
* just assume numIndexTuples = 1 and skip the expensive
6186
* clauselist_selectivity calculations. However, a ScalarArrayOp or
6187
* NullTest invalidates that theory, even though it sets eqQualHere.
6189
if (index->unique &&
6190
indexcol == index->ncolumns - 1 &&
6194
numIndexTuples = 1.0;
6197
Selectivity btreeSelectivity;
6199
btreeSelectivity = clauselist_selectivity(root, indexBoundQuals,
6203
numIndexTuples = btreeSelectivity * index->rel->tuples;
6206
* As in genericcostestimate(), we have to adjust for any
6207
* ScalarArrayOpExpr quals included in indexBoundQuals, and then round
6210
numIndexTuples = rint(numIndexTuples / num_sa_scans);
6213
genericcostestimate(root, index, indexQuals, indexOrderBys,
6214
outer_rel, numIndexTuples,
6215
indexStartupCost, indexTotalCost,
6216
indexSelectivity, indexCorrelation);
6219
* If we can get an estimate of the first column's ordering correlation C
6220
* from pg_statistic, estimate the index correlation as C for a
6221
* single-column index, or C * 0.75 for multiple columns. (The idea here
6222
* is that multiple columns dilute the importance of the first column's
6223
* ordering, but don't negate it entirely. Before 8.0 we divided the
6224
* correlation by the number of columns, but that seems too strong.)
6226
* We can skip all this if we found a ScalarArrayOpExpr, because then the
6227
* call must be for a bitmap index scan, and the caller isn't going to
6228
* care what the index correlation is.
6233
MemSet(&vardata, 0, sizeof(vardata));
6235
if (index->indexkeys[0] != 0)
6237
/* Simple variable --- look to stats for the underlying table */
6238
RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
6240
Assert(rte->rtekind == RTE_RELATION);
6242
Assert(relid != InvalidOid);
6243
colnum = index->indexkeys[0];
6245
if (get_relation_stats_hook &&
6246
(*get_relation_stats_hook) (root, rte, colnum, &vardata))
6249
* The hook took control of acquiring a stats tuple. If it did
6250
* supply a tuple, it'd better have supplied a freefunc.
6252
if (HeapTupleIsValid(vardata.statsTuple) &&
6254
elog(ERROR, "no function provided to release variable stats with");
6258
vardata.statsTuple = SearchSysCache3(STATRELATTINH,
6259
ObjectIdGetDatum(relid),
6260
Int16GetDatum(colnum),
6261
BoolGetDatum(rte->inh));
6262
vardata.freefunc = ReleaseSysCache;
6267
/* Expression --- maybe there are stats for the index itself */
6268
relid = index->indexoid;
6271
if (get_index_stats_hook &&
6272
(*get_index_stats_hook) (root, relid, colnum, &vardata))
6275
* The hook took control of acquiring a stats tuple. If it did
6276
* supply a tuple, it'd better have supplied a freefunc.
6278
if (HeapTupleIsValid(vardata.statsTuple) &&
6280
elog(ERROR, "no function provided to release variable stats with");
6284
vardata.statsTuple = SearchSysCache3(STATRELATTINH,
6285
ObjectIdGetDatum(relid),
6286
Int16GetDatum(colnum),
6287
BoolGetDatum(false));
6288
vardata.freefunc = ReleaseSysCache;
6292
if (HeapTupleIsValid(vardata.statsTuple))
6298
sortop = get_opfamily_member(index->opfamily[0],
6299
index->opcintype[0],
6300
index->opcintype[0],
6301
BTLessStrategyNumber);
6302
if (OidIsValid(sortop) &&
6303
get_attstatsslot(vardata.statsTuple, InvalidOid, 0,
6304
STATISTIC_KIND_CORRELATION,
6308
&numbers, &nnumbers))
6310
double varCorrelation;
6312
Assert(nnumbers == 1);
6313
varCorrelation = numbers[0];
6315
if (index->reverse_sort[0])
6316
varCorrelation = -varCorrelation;
6318
if (index->ncolumns > 1)
6319
*indexCorrelation = varCorrelation * 0.75;
6321
*indexCorrelation = varCorrelation;
6323
free_attstatsslot(InvalidOid, NULL, 0, numbers, nnumbers);
6327
ReleaseVariableStats(vardata);
6333
hashcostestimate(PG_FUNCTION_ARGS)
6335
PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
6336
IndexOptInfo *index = (IndexOptInfo *) PG_GETARG_POINTER(1);
6337
List *indexQuals = (List *) PG_GETARG_POINTER(2);
6338
List *indexOrderBys = (List *) PG_GETARG_POINTER(3);
6339
RelOptInfo *outer_rel = (RelOptInfo *) PG_GETARG_POINTER(4);
6340
Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(5);
6341
Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(6);
6342
Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(7);
6343
double *indexCorrelation = (double *) PG_GETARG_POINTER(8);
6345
genericcostestimate(root, index, indexQuals, indexOrderBys, outer_rel, 0.0,
6346
indexStartupCost, indexTotalCost,
6347
indexSelectivity, indexCorrelation);
6353
gistcostestimate(PG_FUNCTION_ARGS)
6355
PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
6356
IndexOptInfo *index = (IndexOptInfo *) PG_GETARG_POINTER(1);
6357
List *indexQuals = (List *) PG_GETARG_POINTER(2);
6358
List *indexOrderBys = (List *) PG_GETARG_POINTER(3);
6359
RelOptInfo *outer_rel = (RelOptInfo *) PG_GETARG_POINTER(4);
6360
Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(5);
6361
Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(6);
6362
Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(7);
6363
double *indexCorrelation = (double *) PG_GETARG_POINTER(8);
6365
genericcostestimate(root, index, indexQuals, indexOrderBys, outer_rel, 0.0,
6366
indexStartupCost, indexTotalCost,
6367
indexSelectivity, indexCorrelation);
6372
/* Find the index column matching "op"; return its index, or -1 if no match */
6374
find_index_column(Node *op, IndexOptInfo *index)
6378
for (i = 0; i < index->ncolumns; i++)
6380
if (match_index_to_operand(op, i, index))
6388
* GIN has search behavior completely different from other index types
6391
gincostestimate(PG_FUNCTION_ARGS)
6393
PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
6394
IndexOptInfo *index = (IndexOptInfo *) PG_GETARG_POINTER(1);
6395
List *indexQuals = (List *) PG_GETARG_POINTER(2);
6396
List *indexOrderBys = (List *) PG_GETARG_POINTER(3);
6397
RelOptInfo *outer_rel = (RelOptInfo *) PG_GETARG_POINTER(4);
6398
Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(5);
6399
Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(6);
6400
Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(7);
6401
double *indexCorrelation = (double *) PG_GETARG_POINTER(8);
6403
List *selectivityQuals;
6404
double numPages = index->pages,
6405
numTuples = index->tuples;
6406
double numEntryPages,
6410
bool haveFullScan = false;
6411
double partialEntriesInQuals = 0.0;
6412
double searchEntriesInQuals = 0.0;
6413
double exactEntriesInQuals = 0.0;
6414
double entryPagesFetched,
6416
dataPagesFetchedBySel;
6417
double qual_op_cost,
6419
spc_random_page_cost,
6421
QualCost index_qual_cost;
6423
GinStatsData ginStats;
6426
* Obtain statistic information from the meta page
6428
indexRel = index_open(index->indexoid, AccessShareLock);
6429
ginGetStats(indexRel, &ginStats);
6430
index_close(indexRel, AccessShareLock);
6432
numEntryPages = ginStats.nEntryPages;
6433
numDataPages = ginStats.nDataPages;
6434
numPendingPages = ginStats.nPendingPages;
6435
numEntries = ginStats.nEntries;
6438
* nPendingPages can be trusted, but the other fields are as of the last
6439
* VACUUM. Scale them by the ratio numPages / nTotalPages to account for
6440
* growth since then. If the fields are zero (implying no VACUUM at all,
6441
* and an index created pre-9.1), assume all pages are entry pages.
6443
if (ginStats.nTotalPages == 0 || ginStats.nEntryPages == 0)
6445
numEntryPages = numPages;
6447
numEntries = numTuples; /* bogus, but no other info available */
6451
double scale = numPages / ginStats.nTotalPages;
6453
numEntryPages = ceil(numEntryPages * scale);
6454
numDataPages = ceil(numDataPages * scale);
6455
numEntries = ceil(numEntries * scale);
6456
/* ensure we didn't round up too much */
6457
numEntryPages = Min(numEntryPages, numPages);
6458
numDataPages = Min(numDataPages, numPages - numEntryPages);
6461
/* In an empty index, numEntries could be zero. Avoid divide-by-zero */
6466
* Include predicate in selectivityQuals (should match
6467
* genericcostestimate)
6469
if (index->indpred != NIL)
6471
List *predExtraQuals = NIL;
6473
foreach(l, index->indpred)
6475
Node *predQual = (Node *) lfirst(l);
6476
List *oneQual = list_make1(predQual);
6478
if (!predicate_implied_by(oneQual, indexQuals))
6479
predExtraQuals = list_concat(predExtraQuals, oneQual);
6481
/* list_concat avoids modifying the passed-in indexQuals list */
6482
selectivityQuals = list_concat(predExtraQuals, indexQuals);
6485
selectivityQuals = indexQuals;
6487
/* Estimate the fraction of main-table tuples that will be visited */
6488
*indexSelectivity = clauselist_selectivity(root, selectivityQuals,
6493
/* fetch estimated page cost for schema containing index */
6494
get_tablespace_page_costs(index->reltablespace,
6495
&spc_random_page_cost,
6499
* Generic assumption about index correlation: there isn't any.
6501
*indexCorrelation = 0.0;
6504
* Examine quals to estimate number of search entries & partial matches
6506
foreach(l, indexQuals)
6508
RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
6519
bool *partial_matches = NULL;
6520
Pointer *extra_data = NULL;
6521
bool *nullFlags = NULL;
6522
int32 searchMode = GIN_SEARCH_MODE_DEFAULT;
6525
Assert(IsA(rinfo, RestrictInfo));
6526
clause = rinfo->clause;
6527
Assert(IsA(clause, OpExpr));
6528
leftop = get_leftop(clause);
6529
rightop = get_rightop(clause);
6530
clause_op = ((OpExpr *) clause)->opno;
6532
if ((indexcol = find_index_column(leftop, index)) >= 0)
6536
else if ((indexcol = find_index_column(rightop, index)) >= 0)
6539
clause_op = get_commutator(clause_op);
6543
elog(ERROR, "could not match index to operand");
6544
operand = NULL; /* keep compiler quiet */
6547
if (IsA(operand, RelabelType))
6548
operand = (Node *) ((RelabelType *) operand)->arg;
6551
* It's impossible to call extractQuery method for unknown operand. So
6552
* unless operand is a Const we can't do much; just assume there will
6553
* be one ordinary search entry from the operand at runtime.
6555
if (!IsA(operand, Const))
6557
searchEntriesInQuals++;
6561
/* If Const is null, there can be no matches */
6562
if (((Const *) operand)->constisnull)
6564
*indexStartupCost = 0;
6565
*indexTotalCost = 0;
6566
*indexSelectivity = 0;
6571
* Get the operator's strategy number and declared input data types
6572
* within the index opfamily. (We don't need the latter, but we use
6573
* get_op_opfamily_properties because it will throw error if it fails
6574
* to find a matching pg_amop entry.)
6576
get_op_opfamily_properties(clause_op, index->opfamily[indexcol], false,
6577
&strategy_op, &lefttype, &righttype);
6580
* GIN always uses the "default" support functions, which are those
6581
* with lefttype == righttype == the opclass' opcintype (see
6582
* IndexSupportInitialize in relcache.c).
6584
extractProcOid = get_opfamily_proc(index->opfamily[indexcol],
6585
index->opcintype[indexcol],
6586
index->opcintype[indexcol],
6587
GIN_EXTRACTQUERY_PROC);
6589
if (!OidIsValid(extractProcOid))
6591
/* should not happen; throw same error as index_getprocinfo */
6592
elog(ERROR, "missing support function %d for attribute %d of index \"%s\"",
6593
GIN_EXTRACTQUERY_PROC, indexcol + 1,
6594
get_rel_name(index->indexoid));
6597
OidFunctionCall7(extractProcOid,
6598
((Const *) operand)->constvalue,
6599
PointerGetDatum(&nentries),
6600
UInt16GetDatum(strategy_op),
6601
PointerGetDatum(&partial_matches),
6602
PointerGetDatum(&extra_data),
6603
PointerGetDatum(&nullFlags),
6604
PointerGetDatum(&searchMode));
6606
if (nentries <= 0 && searchMode == GIN_SEARCH_MODE_DEFAULT)
6608
/* No match is possible */
6609
*indexStartupCost = 0;
6610
*indexTotalCost = 0;
6611
*indexSelectivity = 0;
6618
for (i = 0; i < nentries; i++)
6621
* For partial match we haven't any information to estimate
6622
* number of matched entries in index, so, we just estimate it
6625
if (partial_matches && partial_matches[i])
6626
partialEntriesInQuals += 100;
6628
exactEntriesInQuals++;
6630
searchEntriesInQuals++;
6634
if (searchMode == GIN_SEARCH_MODE_INCLUDE_EMPTY)
6636
/* Treat "include empty" like an exact-match item */
6637
exactEntriesInQuals++;
6638
searchEntriesInQuals++;
6640
else if (searchMode != GIN_SEARCH_MODE_DEFAULT)
6642
/* It's GIN_SEARCH_MODE_ALL */
6643
haveFullScan = true;
6647
if (haveFullScan || indexQuals == NIL)
6650
* Full index scan will be required. We treat this as if every key in
6651
* the index had been listed in the query; is that reasonable?
6653
searchEntriesInQuals = numEntries;
6656
/* Will we have more than one iteration of a nestloop scan? */
6657
if (outer_rel != NULL && outer_rel->rows > 1)
6658
num_scans = outer_rel->rows;
6663
* cost to begin scan, first of all, pay attention to pending list.
6665
entryPagesFetched = numPendingPages;
6668
* Estimate number of entry pages read. We need to do
6669
* searchEntriesInQuals searches. Use a power function as it should be,
6670
* but tuples on leaf pages usually is much greater. Here we include all
6671
* searches in entry tree, including search of first entry in partial
6674
entryPagesFetched += ceil(searchEntriesInQuals * rint(pow(numEntryPages, 0.15)));
6677
* Add an estimate of entry pages read by partial match algorithm. It's a
6678
* scan over leaf pages in entry tree. We haven't any useful stats here,
6679
* so estimate it as proportion.
6681
entryPagesFetched += ceil(numEntryPages * partialEntriesInQuals / numEntries);
6684
* Partial match algorithm reads all data pages before doing actual scan,
6685
* so it's a startup cost. Again, we havn't any useful stats here, so,
6686
* estimate it as proportion
6688
dataPagesFetched = ceil(numDataPages * partialEntriesInQuals / numEntries);
6690
/* calculate cache effects */
6691
if (num_scans > 1 || searchEntriesInQuals > 1)
6693
entryPagesFetched = index_pages_fetched(entryPagesFetched,
6694
(BlockNumber) numEntryPages,
6695
numEntryPages, root);
6696
dataPagesFetched = index_pages_fetched(dataPagesFetched,
6697
(BlockNumber) numDataPages,
6698
numDataPages, root);
6702
* Here we use random page cost because logically-close pages could be far
6705
*indexStartupCost = (entryPagesFetched + dataPagesFetched) * spc_random_page_cost;
6707
/* cost to scan data pages for each exact (non-partial) matched entry */
6708
dataPagesFetched = ceil(numDataPages * exactEntriesInQuals / numEntries);
6711
* Estimate number of data pages read, using selectivity estimation and
6712
* capacity of data page.
6714
dataPagesFetchedBySel = ceil(*indexSelectivity *
6715
(numTuples / (BLCKSZ / SizeOfIptrData)));
6717
if (dataPagesFetchedBySel > dataPagesFetched)
6720
* At least one of entries is very frequent and, unfortunately, we
6721
* couldn't get statistic about entries (only tsvector has such
6722
* statistics). So, we obviously have too small estimation of pages
6723
* fetched from data tree. Re-estimate it from known capacity of data
6726
dataPagesFetched = dataPagesFetchedBySel;
6730
dataPagesFetched = index_pages_fetched(dataPagesFetched,
6731
(BlockNumber) numDataPages,
6732
numDataPages, root);
6733
*indexTotalCost = *indexStartupCost +
6734
dataPagesFetched * spc_random_page_cost;
6737
* Add on index qual eval costs, much as in genericcostestimate
6739
cost_qual_eval(&index_qual_cost, indexQuals, root);
6740
qual_arg_cost = index_qual_cost.startup + index_qual_cost.per_tuple;
6741
cost_qual_eval(&index_qual_cost, indexOrderBys, root);
6742
qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
6743
qual_op_cost = cpu_operator_cost *
6744
(list_length(indexQuals) + list_length(indexOrderBys));
6745
qual_arg_cost -= qual_op_cost;
6746
if (qual_arg_cost < 0) /* just in case... */
6749
*indexStartupCost += qual_arg_cost;
6750
*indexTotalCost += qual_arg_cost;
6751
*indexTotalCost += (numTuples * *indexSelectivity) * (cpu_index_tuple_cost + qual_op_cost);