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-2005, PostgreSQL Global Development Group
14
* Portions Copyright (c) 1994, Regents of the University of California
18
* $PostgreSQL: pgsql/src/backend/utils/adt/selfuncs.c,v 1.169.4.4 2005-04-01 20:32:09 tgl Exp $
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 (Query *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 call convention for a join estimator (oprjoin function) is similar
59
* except that varRelid is not needed, and instead the join type is
62
* Selectivity oprjoin (Query *root,
67
* float8 oprjoin (internal, oid, internal, int2);
69
* (We deliberately make the SQL signature different to facilitate
79
#include "access/heapam.h"
80
#include "access/nbtree.h"
81
#include "access/tuptoaster.h"
82
#include "catalog/catname.h"
83
#include "catalog/pg_namespace.h"
84
#include "catalog/pg_opclass.h"
85
#include "catalog/pg_operator.h"
86
#include "catalog/pg_proc.h"
87
#include "catalog/pg_statistic.h"
88
#include "catalog/pg_type.h"
89
#include "mb/pg_wchar.h"
90
#include "nodes/makefuncs.h"
91
#include "optimizer/clauses.h"
92
#include "optimizer/cost.h"
93
#include "optimizer/pathnode.h"
94
#include "optimizer/paths.h"
95
#include "optimizer/plancat.h"
96
#include "optimizer/prep.h"
97
#include "optimizer/restrictinfo.h"
98
#include "optimizer/tlist.h"
99
#include "optimizer/var.h"
100
#include "parser/parse_expr.h"
101
#include "parser/parse_func.h"
102
#include "parser/parse_oper.h"
103
#include "parser/parsetree.h"
104
#include "utils/builtins.h"
105
#include "utils/date.h"
106
#include "utils/datum.h"
107
#include "utils/int8.h"
108
#include "utils/lsyscache.h"
109
#include "utils/pg_locale.h"
110
#include "utils/selfuncs.h"
111
#include "utils/syscache.h"
114
/* Return data from examine_variable and friends */
117
Node *var; /* the Var or expression tree */
118
RelOptInfo *rel; /* Relation, or NULL if not identifiable */
119
HeapTuple statsTuple; /* pg_statistic tuple, or NULL if none */
120
/* NB: if statsTuple!=NULL, it must be freed when caller is done */
121
Oid vartype; /* exposed type of expression */
122
Oid atttype; /* type to pass to get_attstatsslot */
123
int32 atttypmod; /* typmod to pass to get_attstatsslot */
124
bool isunique; /* true if matched to a unique index */
127
#define ReleaseVariableStats(vardata) \
129
if (HeapTupleIsValid((vardata).statsTuple)) \
130
ReleaseSysCache((vardata).statsTuple); \
134
static bool convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue,
135
Datum lobound, Datum hibound, Oid boundstypid,
136
double *scaledlobound, double *scaledhibound);
137
static double convert_numeric_to_scalar(Datum value, Oid typid);
138
static void convert_string_to_scalar(unsigned char *value,
140
unsigned char *lobound,
141
double *scaledlobound,
142
unsigned char *hibound,
143
double *scaledhibound);
144
static void convert_bytea_to_scalar(Datum value,
147
double *scaledlobound,
149
double *scaledhibound);
150
static double convert_one_string_to_scalar(unsigned char *value,
151
int rangelo, int rangehi);
152
static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
153
int rangelo, int rangehi);
154
static unsigned char *convert_string_datum(Datum value, Oid typid);
155
static double convert_timevalue_to_scalar(Datum value, Oid typid);
156
static bool get_restriction_variable(Query *root, List *args, int varRelid,
157
VariableStatData *vardata, Node **other,
159
static void get_join_variables(Query *root, List *args,
160
VariableStatData *vardata1,
161
VariableStatData *vardata2);
162
static void examine_variable(Query *root, Node *node, int varRelid,
163
VariableStatData *vardata);
164
static double get_variable_numdistinct(VariableStatData *vardata);
165
static bool get_variable_maximum(Query *root, VariableStatData *vardata,
166
Oid sortop, Datum *max);
167
static Selectivity prefix_selectivity(Query *root, VariableStatData *vardata,
168
Oid opclass, Const *prefix);
169
static Selectivity pattern_selectivity(Const *patt, Pattern_Type ptype);
170
static Datum string_to_datum(const char *str, Oid datatype);
171
static Const *string_to_const(const char *str, Oid datatype);
172
static Const *string_to_bytea_const(const char *str, size_t str_len);
176
* eqsel - Selectivity of "=" for any data types.
178
* Note: this routine is also used to estimate selectivity for some
179
* operators that are not "=" but have comparable selectivity behavior,
180
* such as "~=" (geometric approximate-match). Even for "=", we must
181
* keep in mind that the left and right datatypes may differ.
184
eqsel(PG_FUNCTION_ARGS)
186
Query *root = (Query *) PG_GETARG_POINTER(0);
187
Oid operator = PG_GETARG_OID(1);
188
List *args = (List *) PG_GETARG_POINTER(2);
189
int varRelid = PG_GETARG_INT32(3);
190
VariableStatData vardata;
200
* If expression is not variable = something or something = variable,
201
* then punt and return a default estimate.
203
if (!get_restriction_variable(root, args, varRelid,
204
&vardata, &other, &varonleft))
205
PG_RETURN_FLOAT8(DEFAULT_EQ_SEL);
208
* If the something is a NULL constant, assume operator is strict and
209
* return zero, ie, operator will never return TRUE.
211
if (IsA(other, Const) &&
212
((Const *) other)->constisnull)
214
ReleaseVariableStats(vardata);
215
PG_RETURN_FLOAT8(0.0);
218
if (HeapTupleIsValid(vardata.statsTuple))
220
Form_pg_statistic stats;
222
stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
224
if (IsA(other, Const))
226
/* Variable is being compared to a known non-null constant */
227
Datum constval = ((Const *) other)->constvalue;
232
* Is the constant "=" to any of the column's most common
233
* values? (Although the given operator may not really be
234
* "=", we will assume that seeing whether it returns TRUE is
235
* an appropriate test. If you don't like this, maybe you
236
* shouldn't be using eqsel for your operator...)
238
if (get_attstatsslot(vardata.statsTuple,
239
vardata.atttype, vardata.atttypmod,
240
STATISTIC_KIND_MCV, InvalidOid,
242
&numbers, &nnumbers))
246
fmgr_info(get_opcode(operator), &eqproc);
248
for (i = 0; i < nvalues; i++)
250
/* be careful to apply operator right way 'round */
252
match = DatumGetBool(FunctionCall2(&eqproc,
256
match = DatumGetBool(FunctionCall2(&eqproc,
265
/* no most-common-value info available */
268
i = nvalues = nnumbers = 0;
274
* Constant is "=" to this common value. We know
275
* selectivity exactly (or as exactly as VACUUM could
276
* calculate it, anyway).
283
* Comparison is against a constant that is neither NULL
284
* nor any of the common values. Its selectivity cannot
287
double sumcommon = 0.0;
288
double otherdistinct;
290
for (i = 0; i < nnumbers; i++)
291
sumcommon += numbers[i];
292
selec = 1.0 - sumcommon - stats->stanullfrac;
293
CLAMP_PROBABILITY(selec);
296
* and in fact it's probably a good deal less. We
297
* approximate that all the not-common values share this
298
* remaining fraction equally, so we divide by the number
299
* of other distinct values.
301
otherdistinct = get_variable_numdistinct(&vardata)
303
if (otherdistinct > 1)
304
selec /= otherdistinct;
307
* Another cross-check: selectivity shouldn't be estimated
308
* as more than the least common "most common value".
310
if (nnumbers > 0 && selec > numbers[nnumbers - 1])
311
selec = numbers[nnumbers - 1];
314
free_attstatsslot(vardata.atttype, values, nvalues,
322
* Search is for a value that we do not know a priori, but we
323
* will assume it is not NULL. Estimate the selectivity as
324
* non-null fraction divided by number of distinct values, so
325
* that we get a result averaged over all possible values
326
* whether common or uncommon. (Essentially, we are assuming
327
* that the not-yet-known comparison value is equally likely
328
* to be any of the possible values, regardless of their
329
* frequency in the table. Is that a good idea?)
331
selec = 1.0 - stats->stanullfrac;
332
ndistinct = get_variable_numdistinct(&vardata);
337
* Cross-check: selectivity should never be estimated as more
338
* than the most common value's.
340
if (get_attstatsslot(vardata.statsTuple,
341
vardata.atttype, vardata.atttypmod,
342
STATISTIC_KIND_MCV, InvalidOid,
344
&numbers, &nnumbers))
346
if (nnumbers > 0 && selec > numbers[0])
348
free_attstatsslot(vardata.atttype, NULL, 0, numbers, nnumbers);
355
* No VACUUM ANALYZE stats available, so make a guess using
356
* estimated number of distinct values and assuming they are
357
* equally common. (The guess is unlikely to be very good, but we
358
* do know a few special cases.)
360
selec = 1.0 / get_variable_numdistinct(&vardata);
363
ReleaseVariableStats(vardata);
365
/* result should be in range, but make sure... */
366
CLAMP_PROBABILITY(selec);
368
PG_RETURN_FLOAT8((float8) selec);
372
* neqsel - Selectivity of "!=" for any data types.
374
* This routine is also used for some operators that are not "!="
375
* but have comparable selectivity behavior. See above comments
379
neqsel(PG_FUNCTION_ARGS)
381
Query *root = (Query *) PG_GETARG_POINTER(0);
382
Oid operator = PG_GETARG_OID(1);
383
List *args = (List *) PG_GETARG_POINTER(2);
384
int varRelid = PG_GETARG_INT32(3);
389
* We want 1 - eqsel() where the equality operator is the one
390
* associated with this != operator, that is, its negator.
392
eqop = get_negator(operator);
395
result = DatumGetFloat8(DirectFunctionCall4(eqsel,
396
PointerGetDatum(root),
397
ObjectIdGetDatum(eqop),
398
PointerGetDatum(args),
399
Int32GetDatum(varRelid)));
403
/* Use default selectivity (should we raise an error instead?) */
404
result = DEFAULT_EQ_SEL;
406
result = 1.0 - result;
407
PG_RETURN_FLOAT8(result);
411
* scalarineqsel - Selectivity of "<", "<=", ">", ">=" for scalars.
413
* This is the guts of both scalarltsel and scalargtsel. The caller has
414
* commuted the clause, if necessary, so that we can treat the variable as
415
* being on the left. The caller must also make sure that the other side
416
* of the clause is a non-null Const, and dissect same into a value and
419
* This routine works for any datatype (or pair of datatypes) known to
420
* convert_to_scalar(). If it is applied to some other datatype,
421
* it will return a default estimate.
424
scalarineqsel(Query *root, Oid operator, bool isgt,
425
VariableStatData *vardata, Datum constval, Oid consttype)
427
Form_pg_statistic stats;
439
if (!HeapTupleIsValid(vardata->statsTuple))
441
/* no stats available, so default result */
442
return DEFAULT_INEQ_SEL;
444
stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
446
fmgr_info(get_opcode(operator), &opproc);
449
* If we have most-common-values info, add up the fractions of the MCV
450
* entries that satisfy MCV OP CONST. These fractions contribute
451
* directly to the result selectivity. Also add up the total fraction
452
* represented by MCV entries.
457
if (get_attstatsslot(vardata->statsTuple,
458
vardata->atttype, vardata->atttypmod,
459
STATISTIC_KIND_MCV, InvalidOid,
461
&numbers, &nnumbers))
463
for (i = 0; i < nvalues; i++)
465
if (DatumGetBool(FunctionCall2(&opproc,
468
mcv_selec += numbers[i];
469
sumcommon += numbers[i];
471
free_attstatsslot(vardata->atttype, values, nvalues,
476
* If there is a histogram, determine which bin the constant falls in,
477
* and compute the resulting contribution to selectivity.
479
* Someday, VACUUM might store more than one histogram per rel/att,
480
* corresponding to more than one possible sort ordering defined for
481
* the column type. However, to make that work we will need to figure
482
* out which staop to search for --- it's not necessarily the one we
483
* have at hand! (For example, we might have a '<=' operator rather
484
* than the '<' operator that will appear in staop.) For now, assume
485
* that whatever appears in pg_statistic is sorted the same way our
486
* operator sorts, or the reverse way if isgt is TRUE.
490
if (get_attstatsslot(vardata->statsTuple,
491
vardata->atttype, vardata->atttypmod,
492
STATISTIC_KIND_HISTOGRAM, InvalidOid,
501
ltcmp = DatumGetBool(FunctionCall2(&opproc,
508
/* Constant is below lower histogram boundary. */
514
* Scan to find proper location. This could be made
515
* faster by using a binary-search method, but it's
516
* probably not worth the trouble for typical histogram
519
for (i = 1; i < nvalues; i++)
521
ltcmp = DatumGetBool(FunctionCall2(&opproc,
531
/* Constant is above upper histogram boundary. */
542
* We have values[i-1] < constant < values[i].
544
* Convert the constant and the two nearest bin boundary
545
* values to a uniform comparison scale, and do a
546
* linear interpolation within this bin.
548
if (convert_to_scalar(constval, consttype, &val,
549
values[i - 1], values[i],
555
/* cope if bin boundaries appear identical */
560
else if (val >= high)
564
binfrac = (val - low) / (high - low);
567
* Watch out for the possibility that we got a
568
* NaN or Infinity from the division. This
569
* can happen despite the previous checks, if
570
* for example "low" is -Infinity.
572
if (isnan(binfrac) ||
573
binfrac < 0.0 || binfrac > 1.0)
580
* Ideally we'd produce an error here, on the
581
* grounds that the given operator shouldn't have
582
* scalarXXsel registered as its selectivity func
583
* unless we can deal with its operand types. But
584
* currently, all manner of stuff is invoking
585
* scalarXXsel, so give a default estimate until
592
* Now, compute the overall selectivity across the
593
* values represented by the histogram. We have i-1
594
* full bins and binfrac partial bin below the
597
histfrac = (double) (i - 1) + binfrac;
598
histfrac /= (double) (nvalues - 1);
603
* Now histfrac = fraction of histogram entries below the
606
* Account for "<" vs ">"
608
hist_selec = isgt ? (1.0 - histfrac) : histfrac;
611
* The histogram boundaries are only approximate to begin
612
* with, and may well be out of date anyway. Therefore, don't
613
* believe extremely small or large selectivity estimates.
615
if (hist_selec < 0.0001)
617
else if (hist_selec > 0.9999)
621
free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
625
* Now merge the results from the MCV and histogram calculations,
626
* realizing that the histogram covers only the non-null values that
627
* are not listed in MCV.
629
selec = 1.0 - stats->stanullfrac - sumcommon;
631
if (hist_selec > 0.0)
636
* If no histogram but there are values not accounted for by MCV,
637
* arbitrarily assume half of them will match.
644
/* result should be in range, but make sure... */
645
CLAMP_PROBABILITY(selec);
651
* scalarltsel - Selectivity of "<" (also "<=") for scalars.
654
scalarltsel(PG_FUNCTION_ARGS)
656
Query *root = (Query *) PG_GETARG_POINTER(0);
657
Oid operator = PG_GETARG_OID(1);
658
List *args = (List *) PG_GETARG_POINTER(2);
659
int varRelid = PG_GETARG_INT32(3);
660
VariableStatData vardata;
669
* If expression is not variable op something or something op
670
* variable, then punt and return a default estimate.
672
if (!get_restriction_variable(root, args, varRelid,
673
&vardata, &other, &varonleft))
674
PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
677
* Can't do anything useful if the something is not a constant,
680
if (!IsA(other, Const))
682
ReleaseVariableStats(vardata);
683
PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
687
* If the constant is NULL, assume operator is strict and return zero,
688
* ie, operator will never return TRUE.
690
if (((Const *) other)->constisnull)
692
ReleaseVariableStats(vardata);
693
PG_RETURN_FLOAT8(0.0);
695
constval = ((Const *) other)->constvalue;
696
consttype = ((Const *) other)->consttype;
699
* Force the var to be on the left to simplify logic in scalarineqsel.
703
/* we have var < other */
708
/* we have other < var, commute to make var > other */
709
operator = get_commutator(operator);
712
/* Use default selectivity (should we raise an error instead?) */
713
ReleaseVariableStats(vardata);
714
PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
719
selec = scalarineqsel(root, operator, isgt, &vardata, constval, consttype);
721
ReleaseVariableStats(vardata);
723
PG_RETURN_FLOAT8((float8) selec);
727
* scalargtsel - Selectivity of ">" (also ">=") for integers.
730
scalargtsel(PG_FUNCTION_ARGS)
732
Query *root = (Query *) PG_GETARG_POINTER(0);
733
Oid operator = PG_GETARG_OID(1);
734
List *args = (List *) PG_GETARG_POINTER(2);
735
int varRelid = PG_GETARG_INT32(3);
736
VariableStatData vardata;
745
* If expression is not variable op something or something op
746
* variable, then punt and return a default estimate.
748
if (!get_restriction_variable(root, args, varRelid,
749
&vardata, &other, &varonleft))
750
PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
753
* Can't do anything useful if the something is not a constant,
756
if (!IsA(other, Const))
758
ReleaseVariableStats(vardata);
759
PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
763
* If the constant is NULL, assume operator is strict and return zero,
764
* ie, operator will never return TRUE.
766
if (((Const *) other)->constisnull)
768
ReleaseVariableStats(vardata);
769
PG_RETURN_FLOAT8(0.0);
771
constval = ((Const *) other)->constvalue;
772
consttype = ((Const *) other)->consttype;
775
* Force the var to be on the left to simplify logic in scalarineqsel.
779
/* we have var > other */
784
/* we have other > var, commute to make var < other */
785
operator = get_commutator(operator);
788
/* Use default selectivity (should we raise an error instead?) */
789
ReleaseVariableStats(vardata);
790
PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
795
selec = scalarineqsel(root, operator, isgt, &vardata, constval, consttype);
797
ReleaseVariableStats(vardata);
799
PG_RETURN_FLOAT8((float8) selec);
803
* patternsel - Generic code for pattern-match selectivity.
806
patternsel(PG_FUNCTION_ARGS, Pattern_Type ptype)
808
Query *root = (Query *) PG_GETARG_POINTER(0);
811
Oid operator = PG_GETARG_OID(1);
813
List *args = (List *) PG_GETARG_POINTER(2);
814
int varRelid = PG_GETARG_INT32(3);
815
VariableStatData vardata;
822
Pattern_Prefix_Status pstatus;
824
Const *prefix = NULL;
829
* If expression is not variable op constant, then punt and return a
832
if (!get_restriction_variable(root, args, varRelid,
833
&vardata, &other, &varonleft))
834
return DEFAULT_MATCH_SEL;
835
if (!varonleft || !IsA(other, Const))
837
ReleaseVariableStats(vardata);
838
return DEFAULT_MATCH_SEL;
842
* If the constant is NULL, assume operator is strict and return zero,
843
* ie, operator will never return TRUE.
845
if (((Const *) other)->constisnull)
847
ReleaseVariableStats(vardata);
850
constval = ((Const *) other)->constvalue;
851
consttype = ((Const *) other)->consttype;
854
* The right-hand const is type text or bytea for all supported
855
* operators. We do not expect to see binary-compatible types here,
856
* since const-folding should have relabeled the const to exactly
857
* match the operator's declared type.
859
if (consttype != TEXTOID && consttype != BYTEAOID)
861
ReleaseVariableStats(vardata);
862
return DEFAULT_MATCH_SEL;
866
* Similarly, the exposed type of the left-hand side should be one
867
* of those we know. (Do not look at vardata.atttype, which might be
868
* something binary-compatible but different.) We can use it to choose
869
* the index opclass from which we must draw the comparison operators.
871
* NOTE: It would be more correct to use the PATTERN opclasses than the
872
* simple ones, but at the moment ANALYZE will not generate statistics
873
* for the PATTERN operators. But our results are so approximate
874
* anyway that it probably hardly matters.
876
vartype = vardata.vartype;
881
opclass = TEXT_BTREE_OPS_OID;
884
opclass = VARCHAR_BTREE_OPS_OID;
887
opclass = BPCHAR_BTREE_OPS_OID;
890
opclass = NAME_BTREE_OPS_OID;
893
opclass = BYTEA_BTREE_OPS_OID;
896
ReleaseVariableStats(vardata);
897
return DEFAULT_MATCH_SEL;
900
/* divide pattern into fixed prefix and remainder */
901
patt = (Const *) other;
902
pstatus = pattern_fixed_prefix(patt, ptype, &prefix, &rest);
905
* If necessary, coerce the prefix constant to the right type. (The
906
* "rest" constant need not be changed.)
908
if (prefix && prefix->consttype != vartype)
912
switch (prefix->consttype)
915
prefixstr = DatumGetCString(DirectFunctionCall1(textout,
916
prefix->constvalue));
919
prefixstr = DatumGetCString(DirectFunctionCall1(byteaout,
920
prefix->constvalue));
923
elog(ERROR, "unrecognized consttype: %u",
925
ReleaseVariableStats(vardata);
926
return DEFAULT_MATCH_SEL;
928
prefix = string_to_const(prefixstr, vartype);
932
if (pstatus == Pattern_Prefix_Exact)
935
* Pattern specifies an exact match, so pretend operator is '='
937
Oid eqopr = get_opclass_member(opclass, InvalidOid,
938
BTEqualStrategyNumber);
941
if (eqopr == InvalidOid)
942
elog(ERROR, "no = operator for opclass %u", opclass);
943
eqargs = list_make2(vardata.var, prefix);
944
result = DatumGetFloat8(DirectFunctionCall4(eqsel,
945
PointerGetDatum(root),
946
ObjectIdGetDatum(eqopr),
947
PointerGetDatum(eqargs),
948
Int32GetDatum(varRelid)));
953
* Not exact-match pattern. We estimate selectivity of the fixed
954
* prefix and remainder of pattern separately, then combine the
957
Selectivity prefixsel;
961
if (pstatus == Pattern_Prefix_Partial)
962
prefixsel = prefix_selectivity(root, &vardata, opclass, prefix);
965
restsel = pattern_selectivity(rest, ptype);
966
selec = prefixsel * restsel;
967
/* result should be in range, but make sure... */
968
CLAMP_PROBABILITY(selec);
974
pfree(DatumGetPointer(prefix->constvalue));
978
ReleaseVariableStats(vardata);
984
* regexeqsel - Selectivity of regular-expression pattern match.
987
regexeqsel(PG_FUNCTION_ARGS)
989
PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex));
993
* icregexeqsel - Selectivity of case-insensitive regex match.
996
icregexeqsel(PG_FUNCTION_ARGS)
998
PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex_IC));
1002
* likesel - Selectivity of LIKE pattern match.
1005
likesel(PG_FUNCTION_ARGS)
1007
PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like));
1011
* iclikesel - Selectivity of ILIKE pattern match.
1014
iclikesel(PG_FUNCTION_ARGS)
1016
PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like_IC));
1020
* regexnesel - Selectivity of regular-expression pattern non-match.
1023
regexnesel(PG_FUNCTION_ARGS)
1027
result = patternsel(fcinfo, Pattern_Type_Regex);
1028
result = 1.0 - result;
1029
PG_RETURN_FLOAT8(result);
1033
* icregexnesel - Selectivity of case-insensitive regex non-match.
1036
icregexnesel(PG_FUNCTION_ARGS)
1040
result = patternsel(fcinfo, Pattern_Type_Regex_IC);
1041
result = 1.0 - result;
1042
PG_RETURN_FLOAT8(result);
1046
* nlikesel - Selectivity of LIKE pattern non-match.
1049
nlikesel(PG_FUNCTION_ARGS)
1053
result = patternsel(fcinfo, Pattern_Type_Like);
1054
result = 1.0 - result;
1055
PG_RETURN_FLOAT8(result);
1059
* icnlikesel - Selectivity of ILIKE pattern non-match.
1062
icnlikesel(PG_FUNCTION_ARGS)
1066
result = patternsel(fcinfo, Pattern_Type_Like_IC);
1067
result = 1.0 - result;
1068
PG_RETURN_FLOAT8(result);
1072
* booltestsel - Selectivity of BooleanTest Node.
1075
booltestsel(Query *root, BoolTestType booltesttype, Node *arg,
1076
int varRelid, JoinType jointype)
1078
VariableStatData vardata;
1081
examine_variable(root, arg, varRelid, &vardata);
1083
if (HeapTupleIsValid(vardata.statsTuple))
1085
Form_pg_statistic stats;
1092
stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1093
freq_null = stats->stanullfrac;
1095
if (get_attstatsslot(vardata.statsTuple,
1096
vardata.atttype, vardata.atttypmod,
1097
STATISTIC_KIND_MCV, InvalidOid,
1099
&numbers, &nnumbers)
1106
* Get first MCV frequency and derive frequency for true.
1108
if (DatumGetBool(values[0]))
1109
freq_true = numbers[0];
1111
freq_true = 1.0 - numbers[0] - freq_null;
1114
* Next derive frequency for false. Then use these as
1115
* appropriate to derive frequency for each case.
1117
freq_false = 1.0 - freq_true - freq_null;
1119
switch (booltesttype)
1122
/* select only NULL values */
1125
case IS_NOT_UNKNOWN:
1126
/* select non-NULL values */
1127
selec = 1.0 - freq_null;
1130
/* select only TRUE values */
1134
/* select non-TRUE values */
1135
selec = 1.0 - freq_true;
1138
/* select only FALSE values */
1142
/* select non-FALSE values */
1143
selec = 1.0 - freq_false;
1146
elog(ERROR, "unrecognized booltesttype: %d",
1147
(int) booltesttype);
1148
selec = 0.0; /* Keep compiler quiet */
1152
free_attstatsslot(vardata.atttype, values, nvalues,
1158
* No most-common-value info available. Still have null
1159
* fraction information, so use it for IS [NOT] UNKNOWN.
1160
* Otherwise adjust for null fraction and assume an even split
1161
* for boolean tests.
1163
switch (booltesttype)
1168
* Use freq_null directly.
1172
case IS_NOT_UNKNOWN:
1175
* Select not unknown (not null) values. Calculate
1178
selec = 1.0 - freq_null;
1184
selec = (1.0 - freq_null) / 2.0;
1187
elog(ERROR, "unrecognized booltesttype: %d",
1188
(int) booltesttype);
1189
selec = 0.0; /* Keep compiler quiet */
1197
* If we can't get variable statistics for the argument, perhaps
1198
* clause_selectivity can do something with it. We ignore the
1199
* possibility of a NULL value when using clause_selectivity, and
1200
* just assume the value is either TRUE or FALSE.
1202
switch (booltesttype)
1205
selec = DEFAULT_UNK_SEL;
1207
case IS_NOT_UNKNOWN:
1208
selec = DEFAULT_NOT_UNK_SEL;
1212
selec = (double) clause_selectivity(root, arg,
1213
varRelid, jointype);
1217
selec = 1.0 - (double) clause_selectivity(root, arg,
1218
varRelid, jointype);
1221
elog(ERROR, "unrecognized booltesttype: %d",
1222
(int) booltesttype);
1223
selec = 0.0; /* Keep compiler quiet */
1228
ReleaseVariableStats(vardata);
1230
/* result should be in range, but make sure... */
1231
CLAMP_PROBABILITY(selec);
1233
return (Selectivity) selec;
1237
* nulltestsel - Selectivity of NullTest Node.
1240
nulltestsel(Query *root, NullTestType nulltesttype, Node *arg, int varRelid)
1242
VariableStatData vardata;
1245
examine_variable(root, arg, varRelid, &vardata);
1247
if (HeapTupleIsValid(vardata.statsTuple))
1249
Form_pg_statistic stats;
1252
stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1253
freq_null = stats->stanullfrac;
1255
switch (nulltesttype)
1260
* Use freq_null directly.
1267
* Select not unknown (not null) values. Calculate from
1270
selec = 1.0 - freq_null;
1273
elog(ERROR, "unrecognized nulltesttype: %d",
1274
(int) nulltesttype);
1275
return (Selectivity) 0; /* keep compiler quiet */
1281
* No VACUUM ANALYZE stats available, so make a guess
1283
switch (nulltesttype)
1286
selec = DEFAULT_UNK_SEL;
1289
selec = DEFAULT_NOT_UNK_SEL;
1292
elog(ERROR, "unrecognized nulltesttype: %d",
1293
(int) nulltesttype);
1294
return (Selectivity) 0; /* keep compiler quiet */
1298
ReleaseVariableStats(vardata);
1300
/* result should be in range, but make sure... */
1301
CLAMP_PROBABILITY(selec);
1303
return (Selectivity) selec;
1307
* eqjoinsel - Join selectivity of "="
1310
eqjoinsel(PG_FUNCTION_ARGS)
1312
Query *root = (Query *) PG_GETARG_POINTER(0);
1313
Oid operator = PG_GETARG_OID(1);
1314
List *args = (List *) PG_GETARG_POINTER(2);
1315
JoinType jointype = (JoinType) PG_GETARG_INT16(3);
1317
VariableStatData vardata1;
1318
VariableStatData vardata2;
1321
Form_pg_statistic stats1 = NULL;
1322
Form_pg_statistic stats2 = NULL;
1323
bool have_mcvs1 = false;
1324
Datum *values1 = NULL;
1326
float4 *numbers1 = NULL;
1328
bool have_mcvs2 = false;
1329
Datum *values2 = NULL;
1331
float4 *numbers2 = NULL;
1334
get_join_variables(root, args, &vardata1, &vardata2);
1336
nd1 = get_variable_numdistinct(&vardata1);
1337
nd2 = get_variable_numdistinct(&vardata2);
1339
if (HeapTupleIsValid(vardata1.statsTuple))
1341
stats1 = (Form_pg_statistic) GETSTRUCT(vardata1.statsTuple);
1342
have_mcvs1 = get_attstatsslot(vardata1.statsTuple,
1347
&values1, &nvalues1,
1348
&numbers1, &nnumbers1);
1351
if (HeapTupleIsValid(vardata2.statsTuple))
1353
stats2 = (Form_pg_statistic) GETSTRUCT(vardata2.statsTuple);
1354
have_mcvs2 = get_attstatsslot(vardata2.statsTuple,
1359
&values2, &nvalues2,
1360
&numbers2, &nnumbers2);
1363
if (have_mcvs1 && have_mcvs2)
1366
* We have most-common-value lists for both relations. Run
1367
* through the lists to see which MCVs actually join to each other
1368
* with the given operator. This allows us to determine the exact
1369
* join selectivity for the portion of the relations represented
1370
* by the MCV lists. We still have to estimate for the remaining
1371
* population, but in a skewed distribution this gives us a big
1372
* leg up in accuracy. For motivation see the analysis in Y.
1373
* Ioannidis and S. Christodoulakis, "On the propagation of errors
1374
* in the size of join results", Technical Report 1018, Computer
1375
* Science Dept., University of Wisconsin, Madison, March 1991
1376
* (available from ftp.cs.wisc.edu).
1381
double nullfrac1 = stats1->stanullfrac;
1382
double nullfrac2 = stats2->stanullfrac;
1383
double matchprodfreq,
1395
fmgr_info(get_opcode(operator), &eqproc);
1396
hasmatch1 = (bool *) palloc0(nvalues1 * sizeof(bool));
1397
hasmatch2 = (bool *) palloc0(nvalues2 * sizeof(bool));
1400
* If we are doing any variant of JOIN_IN, pretend all the values
1401
* of the righthand relation are unique (ie, act as if it's been
1404
* NOTE: it might seem that we should unique-ify the lefthand input
1405
* when considering JOIN_REVERSE_IN. But this is not so, because
1406
* the join clause we've been handed has not been commuted from
1407
* the way the parser originally wrote it. We know that the
1408
* unique side of the IN clause is *always* on the right.
1410
* NOTE: it would be dangerous to try to be smart about JOIN_LEFT or
1411
* JOIN_RIGHT here, because we do not have enough information to
1412
* determine which var is really on which side of the join.
1413
* Perhaps someday we should pass in more information.
1415
if (jointype == JOIN_IN ||
1416
jointype == JOIN_REVERSE_IN ||
1417
jointype == JOIN_UNIQUE_INNER ||
1418
jointype == JOIN_UNIQUE_OUTER)
1420
float4 oneovern = 1.0 / nd2;
1422
for (i = 0; i < nvalues2; i++)
1423
numbers2[i] = oneovern;
1424
nullfrac2 = oneovern;
1428
* Note we assume that each MCV will match at most one member of
1429
* the other MCV list. If the operator isn't really equality,
1430
* there could be multiple matches --- but we don't look for them,
1431
* both for speed and because the math wouldn't add up...
1433
matchprodfreq = 0.0;
1435
for (i = 0; i < nvalues1; i++)
1439
for (j = 0; j < nvalues2; j++)
1443
if (DatumGetBool(FunctionCall2(&eqproc,
1447
hasmatch1[i] = hasmatch2[j] = true;
1448
matchprodfreq += numbers1[i] * numbers2[j];
1454
CLAMP_PROBABILITY(matchprodfreq);
1455
/* Sum up frequencies of matched and unmatched MCVs */
1456
matchfreq1 = unmatchfreq1 = 0.0;
1457
for (i = 0; i < nvalues1; i++)
1460
matchfreq1 += numbers1[i];
1462
unmatchfreq1 += numbers1[i];
1464
CLAMP_PROBABILITY(matchfreq1);
1465
CLAMP_PROBABILITY(unmatchfreq1);
1466
matchfreq2 = unmatchfreq2 = 0.0;
1467
for (i = 0; i < nvalues2; i++)
1470
matchfreq2 += numbers2[i];
1472
unmatchfreq2 += numbers2[i];
1474
CLAMP_PROBABILITY(matchfreq2);
1475
CLAMP_PROBABILITY(unmatchfreq2);
1480
* Compute total frequency of non-null values that are not in the
1483
otherfreq1 = 1.0 - nullfrac1 - matchfreq1 - unmatchfreq1;
1484
otherfreq2 = 1.0 - nullfrac2 - matchfreq2 - unmatchfreq2;
1485
CLAMP_PROBABILITY(otherfreq1);
1486
CLAMP_PROBABILITY(otherfreq2);
1489
* We can estimate the total selectivity from the point of view of
1490
* relation 1 as: the known selectivity for matched MCVs, plus
1491
* unmatched MCVs that are assumed to match against random members
1492
* of relation 2's non-MCV population, plus non-MCV values that
1493
* are assumed to match against random members of relation 2's
1494
* unmatched MCVs plus non-MCV values.
1496
totalsel1 = matchprodfreq;
1498
totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - nvalues2);
1500
totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
1502
/* Same estimate from the point of view of relation 2. */
1503
totalsel2 = matchprodfreq;
1505
totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - nvalues1);
1507
totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
1511
* Use the smaller of the two estimates. This can be justified in
1512
* essentially the same terms as given below for the no-stats
1513
* case: to a first approximation, we are estimating from the
1514
* point of view of the relation with smaller nd.
1516
selec = (totalsel1 < totalsel2) ? totalsel1 : totalsel2;
1521
* We do not have MCV lists for both sides. Estimate the join
1522
* selectivity as MIN(1/nd1,1/nd2)*(1-nullfrac1)*(1-nullfrac2).
1523
* This is plausible if we assume that the join operator is strict
1524
* and the non-null values are about equally distributed: a given
1525
* non-null tuple of rel1 will join to either zero or
1526
* N2*(1-nullfrac2)/nd2 rows of rel2, so total join rows are at
1527
* most N1*(1-nullfrac1)*N2*(1-nullfrac2)/nd2 giving a join
1528
* selectivity of not more than (1-nullfrac1)*(1-nullfrac2)/nd2.
1529
* By the same logic it is not more than
1530
* (1-nullfrac1)*(1-nullfrac2)/nd1, so the expression with MIN()
1531
* is an upper bound. Using the MIN() means we estimate from the
1532
* point of view of the relation with smaller nd (since the larger
1533
* nd is determining the MIN). It is reasonable to assume that
1534
* most tuples in this rel will have join partners, so the bound
1535
* is probably reasonably tight and should be taken as-is.
1537
* XXX Can we be smarter if we have an MCV list for just one side? It
1538
* seems that if we assume equal distribution for the other side,
1539
* we end up with the same answer anyway.
1541
double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
1542
double nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
1544
selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
1552
free_attstatsslot(vardata1.atttype, values1, nvalues1,
1553
numbers1, nnumbers1);
1555
free_attstatsslot(vardata2.atttype, values2, nvalues2,
1556
numbers2, nnumbers2);
1558
ReleaseVariableStats(vardata1);
1559
ReleaseVariableStats(vardata2);
1561
CLAMP_PROBABILITY(selec);
1563
PG_RETURN_FLOAT8((float8) selec);
1567
* neqjoinsel - Join selectivity of "!="
1570
neqjoinsel(PG_FUNCTION_ARGS)
1572
Query *root = (Query *) PG_GETARG_POINTER(0);
1573
Oid operator = PG_GETARG_OID(1);
1574
List *args = (List *) PG_GETARG_POINTER(2);
1575
JoinType jointype = (JoinType) PG_GETARG_INT16(3);
1580
* We want 1 - eqjoinsel() where the equality operator is the one
1581
* associated with this != operator, that is, its negator.
1583
eqop = get_negator(operator);
1586
result = DatumGetFloat8(DirectFunctionCall4(eqjoinsel,
1587
PointerGetDatum(root),
1588
ObjectIdGetDatum(eqop),
1589
PointerGetDatum(args),
1590
Int16GetDatum(jointype)));
1594
/* Use default selectivity (should we raise an error instead?) */
1595
result = DEFAULT_EQ_SEL;
1597
result = 1.0 - result;
1598
PG_RETURN_FLOAT8(result);
1602
* scalarltjoinsel - Join selectivity of "<" and "<=" for scalars
1605
scalarltjoinsel(PG_FUNCTION_ARGS)
1607
PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1611
* scalargtjoinsel - Join selectivity of ">" and ">=" for scalars
1614
scalargtjoinsel(PG_FUNCTION_ARGS)
1616
PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
1620
* regexeqjoinsel - Join selectivity of regular-expression pattern match.
1623
regexeqjoinsel(PG_FUNCTION_ARGS)
1625
PG_RETURN_FLOAT8(DEFAULT_MATCH_SEL);
1629
* icregexeqjoinsel - Join selectivity of case-insensitive regex match.
1632
icregexeqjoinsel(PG_FUNCTION_ARGS)
1634
PG_RETURN_FLOAT8(DEFAULT_MATCH_SEL);
1638
* likejoinsel - Join selectivity of LIKE pattern match.
1641
likejoinsel(PG_FUNCTION_ARGS)
1643
PG_RETURN_FLOAT8(DEFAULT_MATCH_SEL);
1647
* iclikejoinsel - Join selectivity of ILIKE pattern match.
1650
iclikejoinsel(PG_FUNCTION_ARGS)
1652
PG_RETURN_FLOAT8(DEFAULT_MATCH_SEL);
1656
* regexnejoinsel - Join selectivity of regex non-match.
1659
regexnejoinsel(PG_FUNCTION_ARGS)
1663
result = DatumGetFloat8(regexeqjoinsel(fcinfo));
1664
result = 1.0 - result;
1665
PG_RETURN_FLOAT8(result);
1669
* icregexnejoinsel - Join selectivity of case-insensitive regex non-match.
1672
icregexnejoinsel(PG_FUNCTION_ARGS)
1676
result = DatumGetFloat8(icregexeqjoinsel(fcinfo));
1677
result = 1.0 - result;
1678
PG_RETURN_FLOAT8(result);
1682
* nlikejoinsel - Join selectivity of LIKE pattern non-match.
1685
nlikejoinsel(PG_FUNCTION_ARGS)
1689
result = DatumGetFloat8(likejoinsel(fcinfo));
1690
result = 1.0 - result;
1691
PG_RETURN_FLOAT8(result);
1695
* icnlikejoinsel - Join selectivity of ILIKE pattern non-match.
1698
icnlikejoinsel(PG_FUNCTION_ARGS)
1702
result = DatumGetFloat8(iclikejoinsel(fcinfo));
1703
result = 1.0 - result;
1704
PG_RETURN_FLOAT8(result);
1708
* mergejoinscansel - Scan selectivity of merge join.
1710
* A merge join will stop as soon as it exhausts either input stream.
1711
* Therefore, if we can estimate the ranges of both input variables,
1712
* we can estimate how much of the input will actually be read. This
1713
* can have a considerable impact on the cost when using indexscans.
1715
* clause should be a clause already known to be mergejoinable.
1717
* *leftscan is set to the fraction of the left-hand variable expected
1718
* to be scanned (0 to 1), and similarly *rightscan for the right-hand
1722
mergejoinscansel(Query *root, Node *clause,
1723
Selectivity *leftscan,
1724
Selectivity *rightscan)
1728
VariableStatData leftvar,
1744
/* Set default results if we can't figure anything out. */
1745
*leftscan = *rightscan = 1.0;
1747
/* Deconstruct the merge clause */
1748
if (!is_opclause(clause))
1749
return; /* shouldn't happen */
1750
opno = ((OpExpr *) clause)->opno;
1751
left = get_leftop((Expr *) clause);
1752
right = get_rightop((Expr *) clause);
1754
return; /* shouldn't happen */
1756
/* Look for stats for the inputs */
1757
examine_variable(root, left, 0, &leftvar);
1758
examine_variable(root, right, 0, &rightvar);
1760
/* Get the direct input types of the operator */
1761
lefttype = exprType(left);
1762
righttype = exprType(right);
1764
/* Verify mergejoinability and get left and right "<" operators */
1765
if (!op_mergejoinable(opno,
1768
goto fail; /* shouldn't happen */
1770
/* Try to get maximum values of both inputs */
1771
if (!get_variable_maximum(root, &leftvar, lsortop, &leftmax))
1772
goto fail; /* no max available from stats */
1774
if (!get_variable_maximum(root, &rightvar, rsortop, &rightmax))
1775
goto fail; /* no max available from stats */
1777
/* Look up the "left < right" and "left > right" operators */
1778
op_mergejoin_crossops(opno, <op, >op, NULL, NULL);
1780
/* Look up the "left <= right" operator */
1781
leop = get_negator(gtop);
1782
if (!OidIsValid(leop))
1783
goto fail; /* insufficient info in catalogs */
1785
/* Look up the "right > left" operator */
1786
revgtop = get_commutator(ltop);
1787
if (!OidIsValid(revgtop))
1788
goto fail; /* insufficient info in catalogs */
1790
/* Look up the "right <= left" operator */
1791
revleop = get_negator(revgtop);
1792
if (!OidIsValid(revleop))
1793
goto fail; /* insufficient info in catalogs */
1796
* Now, the fraction of the left variable that will be scanned is the
1797
* fraction that's <= the right-side maximum value. But only believe
1798
* non-default estimates, else stick with our 1.0.
1800
selec = scalarineqsel(root, leop, false, &leftvar,
1801
rightmax, righttype);
1802
if (selec != DEFAULT_INEQ_SEL)
1805
/* And similarly for the right variable. */
1806
selec = scalarineqsel(root, revleop, false, &rightvar,
1808
if (selec != DEFAULT_INEQ_SEL)
1812
* Only one of the two fractions can really be less than 1.0; believe
1813
* the smaller estimate and reset the other one to exactly 1.0. If we
1814
* get exactly equal estimates (as can easily happen with self-joins),
1817
if (*leftscan > *rightscan)
1819
else if (*leftscan < *rightscan)
1822
*leftscan = *rightscan = 1.0;
1825
ReleaseVariableStats(leftvar);
1826
ReleaseVariableStats(rightvar);
1831
* Helper routine for estimate_num_groups: add an item to a list of
1832
* GroupVarInfos, but only if it's not known equal to any of the existing
1837
Node *var; /* might be an expression, not just a Var */
1838
RelOptInfo *rel; /* relation it belongs to */
1839
double ndistinct; /* # distinct values */
1843
add_unique_group_var(Query *root, List *varinfos,
1844
Node *var, VariableStatData *vardata)
1846
GroupVarInfo *varinfo;
1850
ndistinct = get_variable_numdistinct(vardata);
1852
/* cannot use foreach here because of possible list_delete */
1853
lc = list_head(varinfos);
1856
varinfo = (GroupVarInfo *) lfirst(lc);
1858
/* must advance lc before list_delete possibly pfree's it */
1861
/* Drop exact duplicates */
1862
if (equal(var, varinfo->var))
1866
* Drop known-equal vars, but only if they belong to different
1867
* relations (see comments for estimate_num_groups)
1869
if (vardata->rel != varinfo->rel &&
1870
exprs_known_equal(root, var, varinfo->var))
1872
if (varinfo->ndistinct <= ndistinct)
1874
/* Keep older item, forget new one */
1879
/* Delete the older item */
1880
varinfos = list_delete_ptr(varinfos, varinfo);
1885
varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
1888
varinfo->rel = vardata->rel;
1889
varinfo->ndistinct = ndistinct;
1890
varinfos = lappend(varinfos, varinfo);
1895
* estimate_num_groups - Estimate number of groups in a grouped query
1897
* Given a query having a GROUP BY clause, estimate how many groups there
1898
* will be --- ie, the number of distinct combinations of the GROUP BY
1901
* This routine is also used to estimate the number of rows emitted by
1902
* a DISTINCT filtering step; that is an isomorphic problem. (Note:
1903
* actually, we only use it for DISTINCT when there's no grouping or
1904
* aggregation ahead of the DISTINCT.)
1908
* groupExprs - list of expressions being grouped by
1909
* input_rows - number of rows estimated to arrive at the group/unique
1912
* Given the lack of any cross-correlation statistics in the system, it's
1913
* impossible to do anything really trustworthy with GROUP BY conditions
1914
* involving multiple Vars. We should however avoid assuming the worst
1915
* case (all possible cross-product terms actually appear as groups) since
1916
* very often the grouped-by Vars are highly correlated. Our current approach
1918
* 1. Reduce the given expressions to a list of unique Vars used. For
1919
* example, GROUP BY a, a + b is treated the same as GROUP BY a, b.
1920
* It is clearly correct not to count the same Var more than once.
1921
* It is also reasonable to treat f(x) the same as x: f() cannot
1922
* increase the number of distinct values (unless it is volatile,
1923
* which we consider unlikely for grouping), but it probably won't
1924
* reduce the number of distinct values much either.
1925
* As a special case, if a GROUP BY expression can be matched to an
1926
* expressional index for which we have statistics, then we treat the
1927
* whole expression as though it were just a Var.
1928
* 2. If the list contains Vars of different relations that are known equal
1929
* due to equijoin clauses, then drop all but one of the Vars from each
1930
* known-equal set, keeping the one with smallest estimated # of values
1931
* (since the extra values of the others can't appear in joined rows).
1932
* Note the reason we only consider Vars of different relations is that
1933
* if we considered ones of the same rel, we'd be double-counting the
1934
* restriction selectivity of the equality in the next step.
1935
* 3. For Vars within a single source rel, we multiply together the numbers
1936
* of values, clamp to the number of rows in the rel (divided by 10 if
1937
* more than one Var), and then multiply by the selectivity of the
1938
* restriction clauses for that rel. When there's more than one Var,
1939
* the initial product is probably too high (it's the worst case) but
1940
* clamping to a fraction of the rel's rows seems to be a helpful
1941
* heuristic for not letting the estimate get out of hand. (The factor
1942
* of 10 is derived from pre-Postgres-7.4 practice.) Multiplying
1943
* by the restriction selectivity is effectively assuming that the
1944
* restriction clauses are independent of the grouping, which is a crummy
1945
* assumption, but it's hard to do better.
1946
* 4. If there are Vars from multiple rels, we repeat step 3 for each such
1947
* rel, and multiply the results together.
1948
* Note that rels not containing grouped Vars are ignored completely, as are
1949
* join clauses other than the equijoin clauses used in step 2. Such rels
1950
* cannot increase the number of groups, and we assume such clauses do not
1951
* reduce the number either (somewhat bogus, but we don't have the info to
1955
estimate_num_groups(Query *root, List *groupExprs, double input_rows)
1957
List *varinfos = NIL;
1961
/* We should not be called unless query has GROUP BY (or DISTINCT) */
1962
Assert(groupExprs != NIL);
1965
* Steps 1/2: find the unique Vars used, treating an expression as a Var
1966
* if we can find stats for it. For each one, record the statistical
1967
* estimate of number of distinct values (total in its table, without
1968
* regard for filtering).
1970
foreach(l, groupExprs)
1972
Node *groupexpr = (Node *) lfirst(l);
1973
VariableStatData vardata;
1978
* If examine_variable is able to deduce anything about the GROUP BY
1979
* expression, treat it as a single variable even if it's really more
1982
examine_variable(root, groupexpr, 0, &vardata);
1983
if (vardata.statsTuple != NULL || vardata.isunique)
1985
varinfos = add_unique_group_var(root, varinfos,
1986
groupexpr, &vardata);
1987
ReleaseVariableStats(vardata);
1990
ReleaseVariableStats(vardata);
1993
* Else pull out the component Vars
1995
varshere = pull_var_clause(groupexpr, false);
1998
* If we find any variable-free GROUP BY item, then either it is a
1999
* constant (and we can ignore it) or it contains a volatile
2000
* function; in the latter case we punt and assume that each input
2001
* row will yield a distinct group.
2003
if (varshere == NIL)
2005
if (contain_volatile_functions(groupexpr))
2011
* Else add variables to varinfos list
2013
foreach(l2, varshere)
2015
Node *var = (Node *) lfirst(l2);
2017
examine_variable(root, var, 0, &vardata);
2018
varinfos = add_unique_group_var(root, varinfos, var, &vardata);
2019
ReleaseVariableStats(vardata);
2023
/* If now no Vars, we must have an all-constant GROUP BY list. */
2024
if (varinfos == NIL)
2028
* Steps 3/4: group Vars by relation and estimate total numdistinct.
2030
* For each iteration of the outer loop, we process the frontmost Var in
2031
* varinfos, plus all other Vars in the same relation. We remove
2032
* these Vars from the newvarinfos list for the next iteration. This
2033
* is the easiest way to group Vars of same rel together.
2039
GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
2040
RelOptInfo *rel = varinfo1->rel;
2041
double reldistinct = varinfo1->ndistinct;
2042
double relmaxndistinct = reldistinct;
2043
int relvarcount = 1;
2044
List *newvarinfos = NIL;
2047
* Get the product of numdistinct estimates of the Vars for this rel.
2048
* Also, construct new varinfos list of remaining Vars.
2050
for_each_cell(l, lnext(list_head(varinfos)))
2052
GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
2054
if (varinfo2->rel == varinfo1->rel)
2056
reldistinct *= varinfo2->ndistinct;
2057
if (relmaxndistinct < varinfo2->ndistinct)
2058
relmaxndistinct = varinfo2->ndistinct;
2063
/* not time to process varinfo2 yet */
2064
newvarinfos = lcons(varinfo2, newvarinfos);
2069
* Sanity check --- don't divide by zero if empty relation.
2071
Assert(rel->reloptkind == RELOPT_BASEREL);
2072
if (rel->tuples > 0)
2075
* Clamp to size of rel, or size of rel / 10 if multiple Vars.
2076
* The fudge factor is because the Vars are probably correlated
2077
* but we don't know by how much. We should never clamp to less
2078
* than the largest ndistinct value for any of the Vars, though,
2079
* since there will surely be at least that many groups.
2081
double clamp = rel->tuples;
2083
if (relvarcount > 1)
2086
if (clamp < relmaxndistinct)
2088
clamp = relmaxndistinct;
2089
/* for sanity in case some ndistinct is too large: */
2090
if (clamp > rel->tuples)
2091
clamp = rel->tuples;
2094
if (reldistinct > clamp)
2095
reldistinct = clamp;
2098
* Multiply by restriction selectivity.
2100
reldistinct *= rel->rows / rel->tuples;
2103
* Update estimate of total distinct groups.
2105
numdistinct *= reldistinct;
2108
varinfos = newvarinfos;
2109
} while (varinfos != NIL);
2111
numdistinct = ceil(numdistinct);
2113
/* Guard against out-of-range answers */
2114
if (numdistinct > input_rows)
2115
numdistinct = input_rows;
2116
if (numdistinct < 1.0)
2123
* Estimate hash bucketsize fraction (ie, number of entries in a bucket
2124
* divided by total tuples in relation) if the specified expression is used
2127
* XXX This is really pretty bogus since we're effectively assuming that the
2128
* distribution of hash keys will be the same after applying restriction
2129
* clauses as it was in the underlying relation. However, we are not nearly
2130
* smart enough to figure out how the restrict clauses might change the
2131
* distribution, so this will have to do for now.
2133
* We are passed the number of buckets the executor will use for the given
2134
* input relation. If the data were perfectly distributed, with the same
2135
* number of tuples going into each available bucket, then the bucketsize
2136
* fraction would be 1/nbuckets. But this happy state of affairs will occur
2137
* only if (a) there are at least nbuckets distinct data values, and (b)
2138
* we have a not-too-skewed data distribution. Otherwise the buckets will
2139
* be nonuniformly occupied. If the other relation in the join has a key
2140
* distribution similar to this one's, then the most-loaded buckets are
2141
* exactly those that will be probed most often. Therefore, the "average"
2142
* bucket size for costing purposes should really be taken as something close
2143
* to the "worst case" bucket size. We try to estimate this by adjusting the
2144
* fraction if there are too few distinct data values, and then scaling up
2145
* by the ratio of the most common value's frequency to the average frequency.
2147
* If no statistics are available, use a default estimate of 0.1. This will
2148
* discourage use of a hash rather strongly if the inner relation is large,
2149
* which is what we want. We do not want to hash unless we know that the
2150
* inner rel is well-dispersed (or the alternatives seem much worse).
2153
estimate_hash_bucketsize(Query *root, Node *hashkey, int nbuckets)
2155
VariableStatData vardata;
2164
examine_variable(root, hashkey, 0, &vardata);
2166
/* Get number of distinct values and fraction that are null */
2167
ndistinct = get_variable_numdistinct(&vardata);
2169
if (HeapTupleIsValid(vardata.statsTuple))
2171
Form_pg_statistic stats;
2173
stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
2174
stanullfrac = stats->stanullfrac;
2179
* Believe a default ndistinct only if it came from stats.
2180
* Otherwise punt and return 0.1, per comments above.
2182
if (ndistinct == DEFAULT_NUM_DISTINCT)
2184
ReleaseVariableStats(vardata);
2185
return (Selectivity) 0.1;
2191
/* Compute avg freq of all distinct data values in raw relation */
2192
avgfreq = (1.0 - stanullfrac) / ndistinct;
2195
* Adjust ndistinct to account for restriction clauses. Observe we
2196
* are assuming that the data distribution is affected uniformly by
2197
* the restriction clauses!
2199
* XXX Possibly better way, but much more expensive: multiply by
2200
* selectivity of rel's restriction clauses that mention the target
2204
ndistinct *= vardata.rel->rows / vardata.rel->tuples;
2207
* Initial estimate of bucketsize fraction is 1/nbuckets as long as
2208
* the number of buckets is less than the expected number of distinct
2209
* values; otherwise it is 1/ndistinct.
2211
if (ndistinct > (double) nbuckets)
2212
estfract = 1.0 / (double) nbuckets;
2214
estfract = 1.0 / ndistinct;
2217
* Look up the frequency of the most common value, if available.
2221
if (HeapTupleIsValid(vardata.statsTuple))
2223
if (get_attstatsslot(vardata.statsTuple,
2224
vardata.atttype, vardata.atttypmod,
2225
STATISTIC_KIND_MCV, InvalidOid,
2226
NULL, NULL, &numbers, &nnumbers))
2229
* The first MCV stat is for the most common value.
2232
mcvfreq = numbers[0];
2233
free_attstatsslot(vardata.atttype, NULL, 0,
2239
* Adjust estimated bucketsize upward to account for skewed
2242
if (avgfreq > 0.0 && mcvfreq > avgfreq)
2243
estfract *= mcvfreq / avgfreq;
2246
* Clamp bucketsize to sane range (the above adjustment could easily
2247
* produce an out-of-range result). We set the lower bound a little
2248
* above zero, since zero isn't a very sane result.
2250
if (estfract < 1.0e-6)
2252
else if (estfract > 1.0)
2255
ReleaseVariableStats(vardata);
2257
return (Selectivity) estfract;
2261
/*-------------------------------------------------------------------------
2265
*-------------------------------------------------------------------------
2270
* Convert non-NULL values of the indicated types to the comparison
2271
* scale needed by scalarltsel()/scalargtsel().
2272
* Returns "true" if successful.
2274
* XXX this routine is a hack: ideally we should look up the conversion
2275
* subroutines in pg_type.
2277
* All numeric datatypes are simply converted to their equivalent
2278
* "double" values. (NUMERIC values that are outside the range of "double"
2279
* are clamped to +/- HUGE_VAL.)
2281
* String datatypes are converted by convert_string_to_scalar(),
2282
* which is explained below. The reason why this routine deals with
2283
* three values at a time, not just one, is that we need it for strings.
2285
* The bytea datatype is just enough different from strings that it has
2286
* to be treated separately.
2288
* The several datatypes representing absolute times are all converted
2289
* to Timestamp, which is actually a double, and then we just use that
2290
* double value. Note this will give correct results even for the "special"
2291
* values of Timestamp, since those are chosen to compare correctly;
2292
* see timestamp_cmp.
2294
* The several datatypes representing relative times (intervals) are all
2295
* converted to measurements expressed in seconds.
2298
convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue,
2299
Datum lobound, Datum hibound, Oid boundstypid,
2300
double *scaledlobound, double *scaledhibound)
2303
* Both the valuetypid and the boundstypid should exactly match
2304
* the declared input type(s) of the operator we are invoked for,
2305
* so we just error out if either is not recognized.
2307
* XXX The histogram we are interpolating between points of could belong
2308
* to a column that's only binary-compatible with the declared type.
2309
* In essence we are assuming that the semantics of binary-compatible
2310
* types are enough alike that we can use a histogram generated with one
2311
* type's operators to estimate selectivity for the other's. This is
2312
* outright wrong in some cases --- in particular signed versus unsigned
2313
* interpretation could trip us up. But it's useful enough in the
2314
* majority of cases that we do it anyway. Should think about more
2315
* rigorous ways to do it.
2320
* Built-in numeric types
2331
case REGPROCEDUREOID:
2333
case REGOPERATOROID:
2336
*scaledvalue = convert_numeric_to_scalar(value, valuetypid);
2337
*scaledlobound = convert_numeric_to_scalar(lobound, boundstypid);
2338
*scaledhibound = convert_numeric_to_scalar(hibound, boundstypid);
2342
* Built-in string types
2350
unsigned char *valstr = convert_string_datum(value, valuetypid);
2351
unsigned char *lostr = convert_string_datum(lobound, boundstypid);
2352
unsigned char *histr = convert_string_datum(hibound, boundstypid);
2354
convert_string_to_scalar(valstr, scaledvalue,
2355
lostr, scaledlobound,
2356
histr, scaledhibound);
2364
* Built-in bytea type
2368
convert_bytea_to_scalar(value, scaledvalue,
2369
lobound, scaledlobound,
2370
hibound, scaledhibound);
2375
* Built-in time types
2378
case TIMESTAMPTZOID:
2386
*scaledvalue = convert_timevalue_to_scalar(value, valuetypid);
2387
*scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid);
2388
*scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid);
2392
* Built-in network types
2397
*scaledvalue = convert_network_to_scalar(value, valuetypid);
2398
*scaledlobound = convert_network_to_scalar(lobound, boundstypid);
2399
*scaledhibound = convert_network_to_scalar(hibound, boundstypid);
2402
/* Don't know how to convert */
2407
* Do convert_to_scalar()'s work for any numeric data type.
2410
convert_numeric_to_scalar(Datum value, Oid typid)
2415
return (double) DatumGetBool(value);
2417
return (double) DatumGetInt16(value);
2419
return (double) DatumGetInt32(value);
2421
return (double) DatumGetInt64(value);
2423
return (double) DatumGetFloat4(value);
2425
return (double) DatumGetFloat8(value);
2427
/* Note: out-of-range values will be clamped to +-HUGE_VAL */
2429
DatumGetFloat8(DirectFunctionCall1(numeric_float8_no_overflow,
2433
case REGPROCEDUREOID:
2435
case REGOPERATOROID:
2438
/* we can treat OIDs as integers... */
2439
return (double) DatumGetObjectId(value);
2443
* Can't get here unless someone tries to use scalarltsel/scalargtsel
2444
* on an operator with one numeric and one non-numeric operand.
2446
elog(ERROR, "unsupported type: %u", typid);
2451
* Do convert_to_scalar()'s work for any character-string data type.
2453
* String datatypes are converted to a scale that ranges from 0 to 1,
2454
* where we visualize the bytes of the string as fractional digits.
2456
* We do not want the base to be 256, however, since that tends to
2457
* generate inflated selectivity estimates; few databases will have
2458
* occurrences of all 256 possible byte values at each position.
2459
* Instead, use the smallest and largest byte values seen in the bounds
2460
* as the estimated range for each byte, after some fudging to deal with
2461
* the fact that we probably aren't going to see the full range that way.
2463
* An additional refinement is that we discard any common prefix of the
2464
* three strings before computing the scaled values. This allows us to
2465
* "zoom in" when we encounter a narrow data range. An example is a phone
2466
* number database where all the values begin with the same area code.
2467
* (Actually, the bounds will be adjacent histogram-bin-boundary values,
2468
* so this is more likely to happen than you might think.)
2471
convert_string_to_scalar(unsigned char *value,
2472
double *scaledvalue,
2473
unsigned char *lobound,
2474
double *scaledlobound,
2475
unsigned char *hibound,
2476
double *scaledhibound)
2480
unsigned char *sptr;
2482
rangelo = rangehi = hibound[0];
2483
for (sptr = lobound; *sptr; sptr++)
2485
if (rangelo > *sptr)
2487
if (rangehi < *sptr)
2490
for (sptr = hibound; *sptr; sptr++)
2492
if (rangelo > *sptr)
2494
if (rangehi < *sptr)
2497
/* If range includes any upper-case ASCII chars, make it include all */
2498
if (rangelo <= 'Z' && rangehi >= 'A')
2505
/* Ditto lower-case */
2506
if (rangelo <= 'z' && rangehi >= 'a')
2514
if (rangelo <= '9' && rangehi >= '0')
2523
* If range includes less than 10 chars, assume we have not got enough
2524
* data, and make it include regular ASCII set.
2526
if (rangehi - rangelo < 9)
2533
* Now strip any common prefix of the three strings.
2537
if (*lobound != *hibound || *lobound != *value)
2539
lobound++, hibound++, value++;
2543
* Now we can do the conversions.
2545
*scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
2546
*scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
2547
*scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
2551
convert_one_string_to_scalar(unsigned char *value, int rangelo, int rangehi)
2553
int slen = strlen((char *) value);
2559
return 0.0; /* empty string has scalar value 0 */
2562
* Since base is at least 10, need not consider more than about 20
2568
/* Convert initial characters to fraction */
2569
base = rangehi - rangelo + 1;
2578
else if (ch > rangehi)
2580
num += ((double) (ch - rangelo)) / denom;
2588
* Convert a string-type Datum into a palloc'd, null-terminated string.
2590
* When using a non-C locale, we must pass the string through strxfrm()
2591
* before continuing, so as to generate correct locale-specific results.
2593
static unsigned char *
2594
convert_string_datum(Datum value, Oid typid)
2601
val = (char *) palloc(2);
2602
val[0] = DatumGetChar(value);
2609
char *str = (char *) VARDATA(DatumGetPointer(value));
2610
int strlength = VARSIZE(DatumGetPointer(value)) - VARHDRSZ;
2612
val = (char *) palloc(strlength + 1);
2613
memcpy(val, str, strlength);
2614
val[strlength] = '\0';
2619
NameData *nm = (NameData *) DatumGetPointer(value);
2621
val = pstrdup(NameStr(*nm));
2627
* Can't get here unless someone tries to use scalarltsel on
2628
* an operator with one string and one non-string operand.
2630
elog(ERROR, "unsupported type: %u", typid);
2634
if (!lc_collate_is_c())
2641
* Note: originally we guessed at a suitable output buffer size,
2642
* and only needed to call strxfrm twice if our guess was too
2643
* small. However, it seems that some versions of Solaris have
2644
* buggy strxfrm that can write past the specified buffer length
2645
* in that scenario. So, do it the dumb way for portability.
2647
* Yet other systems (e.g., glibc) sometimes return a smaller value
2648
* from the second call than the first; thus the Assert must be <=
2649
* not == as you'd expect. Can't any of these people program
2650
* their way out of a paper bag?
2652
xfrmlen = strxfrm(NULL, val, 0);
2653
xfrmstr = (char *) palloc(xfrmlen + 1);
2654
xfrmlen2 = strxfrm(xfrmstr, val, xfrmlen + 1);
2655
Assert(xfrmlen2 <= xfrmlen);
2660
return (unsigned char *) val;
2664
* Do convert_to_scalar()'s work for any bytea data type.
2666
* Very similar to convert_string_to_scalar except we can't assume
2667
* null-termination and therefore pass explicit lengths around.
2669
* Also, assumptions about likely "normal" ranges of characters have been
2670
* removed - a data range of 0..255 is always used, for now. (Perhaps
2671
* someday we will add information about actual byte data range to
2675
convert_bytea_to_scalar(Datum value,
2676
double *scaledvalue,
2678
double *scaledlobound,
2680
double *scaledhibound)
2684
valuelen = VARSIZE(DatumGetPointer(value)) - VARHDRSZ,
2685
loboundlen = VARSIZE(DatumGetPointer(lobound)) - VARHDRSZ,
2686
hiboundlen = VARSIZE(DatumGetPointer(hibound)) - VARHDRSZ,
2689
unsigned char *valstr = (unsigned char *) VARDATA(DatumGetPointer(value)),
2690
*lostr = (unsigned char *) VARDATA(DatumGetPointer(lobound)),
2691
*histr = (unsigned char *) VARDATA(DatumGetPointer(hibound));
2694
* Assume bytea data is uniformly distributed across all byte values.
2700
* Now strip any common prefix of the three strings.
2702
minlen = Min(Min(valuelen, loboundlen), hiboundlen);
2703
for (i = 0; i < minlen; i++)
2705
if (*lostr != *histr || *lostr != *valstr)
2707
lostr++, histr++, valstr++;
2708
loboundlen--, hiboundlen--, valuelen--;
2712
* Now we can do the conversions.
2714
*scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
2715
*scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
2716
*scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
2720
convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
2721
int rangelo, int rangehi)
2728
return 0.0; /* empty string has scalar value 0 */
2731
* Since base is 256, need not consider more than about 10 chars (even
2732
* this many seems like overkill)
2737
/* Convert initial characters to fraction */
2738
base = rangehi - rangelo + 1;
2741
while (valuelen-- > 0)
2747
else if (ch > rangehi)
2749
num += ((double) (ch - rangelo)) / denom;
2757
* Do convert_to_scalar()'s work for any timevalue data type.
2760
convert_timevalue_to_scalar(Datum value, Oid typid)
2765
return DatumGetTimestamp(value);
2766
case TIMESTAMPTZOID:
2767
return DatumGetTimestampTz(value);
2769
return DatumGetTimestamp(DirectFunctionCall1(abstime_timestamp,
2772
return DatumGetTimestamp(DirectFunctionCall1(date_timestamp,
2776
Interval *interval = DatumGetIntervalP(value);
2779
* Convert the month part of Interval to days using
2780
* assumed average month length of 365.25/12.0 days. Not
2781
* too accurate, but plenty good enough for our purposes.
2783
#ifdef HAVE_INT64_TIMESTAMP
2784
return (interval->time + (interval->month * ((365.25 / 12.0) * 86400000000.0)));
2786
return interval->time +
2787
interval ->month * (365.25 / 12.0 * 24.0 * 60.0 * 60.0);
2791
#ifdef HAVE_INT64_TIMESTAMP
2792
return (DatumGetRelativeTime(value) * 1000000.0);
2794
return DatumGetRelativeTime(value);
2798
TimeInterval interval = DatumGetTimeInterval(value);
2800
#ifdef HAVE_INT64_TIMESTAMP
2801
if (interval->status != 0)
2802
return ((interval->data[1] - interval->data[0]) *1000000.0);
2804
if (interval->status != 0)
2805
return interval->data[1] - interval->data[0];
2807
return 0; /* for lack of a better idea */
2810
return DatumGetTimeADT(value);
2813
TimeTzADT *timetz = DatumGetTimeTzADTP(value);
2815
/* use GMT-equivalent time */
2816
#ifdef HAVE_INT64_TIMESTAMP
2817
return (double) (timetz->time + (timetz->zone * 1000000.0));
2819
return (double) (timetz->time + timetz->zone);
2825
* Can't get here unless someone tries to use scalarltsel/scalargtsel
2826
* on an operator with one timevalue and one non-timevalue operand.
2828
elog(ERROR, "unsupported type: %u", typid);
2834
* get_restriction_variable
2835
* Examine the args of a restriction clause to see if it's of the
2836
* form (variable op pseudoconstant) or (pseudoconstant op variable),
2837
* where "variable" could be either a Var or an expression in vars of a
2838
* single relation. If so, extract information about the variable,
2839
* and also indicate which side it was on and the other argument.
2843
* args: clause argument list
2844
* varRelid: see specs for restriction selectivity functions
2846
* Outputs: (these are valid only if TRUE is returned)
2847
* *vardata: gets information about variable (see examine_variable)
2848
* *other: gets other clause argument, aggressively reduced to a constant
2849
* *varonleft: set TRUE if variable is on the left, FALSE if on the right
2851
* Returns TRUE if a variable is identified, otherwise FALSE.
2853
* Note: if there are Vars on both sides of the clause, we must fail, because
2854
* callers are expecting that the other side will act like a pseudoconstant.
2857
get_restriction_variable(Query *root, List *args, int varRelid,
2858
VariableStatData *vardata, Node **other,
2863
VariableStatData rdata;
2865
/* Fail if not a binary opclause (probably shouldn't happen) */
2866
if (list_length(args) != 2)
2869
left = (Node *) linitial(args);
2870
right = (Node *) lsecond(args);
2873
* Examine both sides. Note that when varRelid is nonzero, Vars of
2874
* other relations will be treated as pseudoconstants.
2876
examine_variable(root, left, varRelid, vardata);
2877
examine_variable(root, right, varRelid, &rdata);
2880
* If one side is a variable and the other not, we win.
2882
if (vardata->rel && rdata.rel == NULL)
2885
*other = estimate_expression_value(rdata.var);
2886
/* Assume we need no ReleaseVariableStats(rdata) here */
2890
if (vardata->rel == NULL && rdata.rel)
2893
*other = estimate_expression_value(vardata->var);
2894
/* Assume we need no ReleaseVariableStats(*vardata) here */
2899
/* Ooops, clause has wrong structure (probably var op var) */
2900
ReleaseVariableStats(*vardata);
2901
ReleaseVariableStats(rdata);
2907
* get_join_variables
2908
* Apply examine_variable() to each side of a join clause.
2911
get_join_variables(Query *root, List *args,
2912
VariableStatData *vardata1, VariableStatData *vardata2)
2917
if (list_length(args) != 2)
2918
elog(ERROR, "join operator should take two arguments");
2920
left = (Node *) linitial(args);
2921
right = (Node *) lsecond(args);
2923
examine_variable(root, left, 0, vardata1);
2924
examine_variable(root, right, 0, vardata2);
2929
* Try to look up statistical data about an expression.
2930
* Fill in a VariableStatData struct to describe the expression.
2934
* node: the expression tree to examine
2935
* varRelid: see specs for restriction selectivity functions
2937
* Outputs: *vardata is filled as follows:
2938
* var: the input expression (with any binary relabeling stripped, if
2939
* it is or contains a variable; but otherwise the type is preserved)
2940
* rel: RelOptInfo for relation containing variable; NULL if expression
2941
* contains no Vars (NOTE this could point to a RelOptInfo of a
2942
* subquery, not one in the current query).
2943
* statsTuple: the pg_statistic entry for the variable, if one exists;
2945
* vartype: exposed type of the expression; this should always match
2946
* the declared input type of the operator we are estimating for.
2947
* atttype, atttypmod: type data to pass to get_attstatsslot(). This is
2948
* commonly the same as the exposed type of the variable argument,
2949
* but can be different in binary-compatible-type cases.
2951
* Caller is responsible for doing ReleaseVariableStats() before exiting.
2954
examine_variable(Query *root, Node *node, int varRelid,
2955
VariableStatData *vardata)
2961
/* Make sure we don't return dangling pointers in vardata */
2962
MemSet(vardata, 0, sizeof(VariableStatData));
2964
/* Save the exposed type of the expression */
2965
vardata->vartype = exprType(node);
2967
/* Look inside any binary-compatible relabeling */
2969
if (IsA(node, RelabelType))
2970
basenode = (Node *) ((RelabelType *) node)->arg;
2974
/* Fast path for a simple Var */
2976
if (IsA(basenode, Var) &&
2977
(varRelid == 0 || varRelid == ((Var *) basenode)->varno))
2979
Var *var = (Var *) basenode;
2982
vardata->var = basenode; /* return Var without relabeling */
2983
vardata->rel = find_base_rel(root, var->varno);
2984
vardata->atttype = var->vartype;
2985
vardata->atttypmod = var->vartypmod;
2987
relid = getrelid(var->varno, root->rtable);
2989
if (OidIsValid(relid))
2991
vardata->statsTuple = SearchSysCache(STATRELATT,
2992
ObjectIdGetDatum(relid),
2993
Int16GetDatum(var->varattno),
2999
* XXX This means the Var comes from a JOIN or sub-SELECT.
3000
* Later add code to dig down into the join etc and see if we
3001
* can trace the variable to something with stats. (But
3002
* beware of sub-SELECTs with DISTINCT/GROUP BY/etc. Perhaps
3003
* there are no cases where this would really be useful,
3004
* because we'd have flattened the subselect if it is??)
3012
* Okay, it's a more complicated expression. Determine variable
3013
* membership. Note that when varRelid isn't zero, only vars of that
3014
* relation are considered "real" vars.
3016
varnos = pull_varnos(basenode);
3020
switch (bms_membership(varnos))
3023
/* No Vars at all ... must be pseudo-constant clause */
3026
if (varRelid == 0 || bms_is_member(varRelid, varnos))
3028
onerel = find_base_rel(root,
3029
(varRelid ? varRelid : bms_singleton_member(varnos)));
3030
vardata->rel = onerel;
3031
node = basenode; /* strip any relabeling */
3033
/* else treat it as a constant */
3038
/* treat it as a variable of a join relation */
3039
vardata->rel = find_join_rel(root, varnos);
3040
node = basenode; /* strip any relabeling */
3042
else if (bms_is_member(varRelid, varnos))
3044
/* ignore the vars belonging to other relations */
3045
vardata->rel = find_base_rel(root, varRelid);
3046
node = basenode; /* strip any relabeling */
3047
/* note: no point in expressional-index search here */
3049
/* else treat it as a constant */
3055
vardata->var = node;
3056
vardata->atttype = exprType(node);
3057
vardata->atttypmod = exprTypmod(node);
3062
* We have an expression in vars of a single relation. Try to
3063
* match it to expressional index columns, in hopes of finding
3066
* XXX it's conceivable that there are multiple matches with
3067
* different index opclasses; if so, we need to pick one that
3068
* matches the operator we are estimating for. FIXME later.
3072
foreach(ilist, onerel->indexlist)
3074
IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
3075
ListCell *indexpr_item;
3078
indexpr_item = list_head(index->indexprs);
3079
if (indexpr_item == NULL)
3080
continue; /* no expressions here... */
3083
* Ignore partial indexes since they probably don't reflect
3084
* whole-relation statistics. Possibly reconsider this later.
3089
for (pos = 0; pos < index->ncolumns; pos++)
3091
if (index->indexkeys[pos] == 0)
3095
if (indexpr_item == NULL)
3096
elog(ERROR, "too few entries in indexprs list");
3097
indexkey = (Node *) lfirst(indexpr_item);
3098
if (indexkey && IsA(indexkey, RelabelType))
3099
indexkey = (Node *) ((RelabelType *) indexkey)->arg;
3100
if (equal(node, indexkey))
3103
* Found a match ... is it a unique index? Tests
3104
* here should match has_unique_index().
3106
if (index->unique &&
3107
index->ncolumns == 1 &&
3108
index->indpred == NIL)
3109
vardata->isunique = true;
3110
/* Has it got stats? */
3111
vardata->statsTuple = SearchSysCache(STATRELATT,
3112
ObjectIdGetDatum(index->indexoid),
3113
Int16GetDatum(pos + 1),
3115
if (vardata->statsTuple)
3118
indexpr_item = lnext(indexpr_item);
3121
if (vardata->statsTuple)
3128
* get_variable_numdistinct
3129
* Estimate the number of distinct values of a variable.
3131
* vardata: results of examine_variable
3133
* NB: be careful to produce an integral result, since callers may compare
3134
* the result to exact integer counts.
3137
get_variable_numdistinct(VariableStatData *vardata)
3143
* Determine the stadistinct value to use. There are cases where we
3144
* can get an estimate even without a pg_statistic entry, or can get a
3145
* better value than is in pg_statistic.
3147
if (HeapTupleIsValid(vardata->statsTuple))
3149
/* Use the pg_statistic entry */
3150
Form_pg_statistic stats;
3152
stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
3153
stadistinct = stats->stadistinct;
3155
else if (vardata->vartype == BOOLOID)
3158
* Special-case boolean columns: presumably, two distinct values.
3160
* Are there any other datatypes we should wire in special estimates
3168
* We don't keep statistics for system columns, but in some cases
3169
* we can infer distinctness anyway.
3171
if (vardata->var && IsA(vardata->var, Var))
3173
switch (((Var *) vardata->var)->varattno)
3175
case ObjectIdAttributeNumber:
3176
case SelfItemPointerAttributeNumber:
3177
stadistinct = -1.0; /* unique */
3179
case TableOidAttributeNumber:
3180
stadistinct = 1.0; /* only 1 value */
3183
stadistinct = 0.0; /* means "unknown" */
3188
stadistinct = 0.0; /* means "unknown" */
3191
* XXX consider using estimate_num_groups on expressions?
3196
* If there is a unique index for the variable, assume it is unique no
3197
* matter what pg_statistic says (the statistics could be out of
3198
* date). Can skip search if we already think it's unique.
3200
if (stadistinct != -1.0)
3202
if (vardata->isunique)
3204
else if (vardata->var && IsA(vardata->var, Var) &&
3206
has_unique_index(vardata->rel,
3207
((Var *) vardata->var)->varattno))
3212
* If we had an absolute estimate, use that.
3214
if (stadistinct > 0.0)
3218
* Otherwise we need to get the relation size; punt if not available.
3220
if (vardata->rel == NULL)
3221
return DEFAULT_NUM_DISTINCT;
3222
ntuples = vardata->rel->tuples;
3224
return DEFAULT_NUM_DISTINCT;
3227
* If we had a relative estimate, use that.
3229
if (stadistinct < 0.0)
3230
return floor((-stadistinct * ntuples) + 0.5);
3233
* With no data, estimate ndistinct = ntuples if the table is small,
3236
if (ntuples < DEFAULT_NUM_DISTINCT)
3239
return DEFAULT_NUM_DISTINCT;
3243
* get_variable_maximum
3244
* Estimate the maximum value of the specified variable.
3245
* If successful, store value in *max and return TRUE.
3246
* If no data available, return FALSE.
3248
* sortop is the "<" comparison operator to use. (To extract the
3249
* minimum instead of the maximum, just pass the ">" operator instead.)
3252
get_variable_maximum(Query *root, VariableStatData *vardata,
3253
Oid sortop, Datum *max)
3256
bool have_max = false;
3257
Form_pg_statistic stats;
3264
if (!HeapTupleIsValid(vardata->statsTuple))
3266
/* no stats available, so default result */
3269
stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
3271
get_typlenbyval(vardata->atttype, &typLen, &typByVal);
3274
* If there is a histogram, grab the last or first value as
3277
* If there is a histogram that is sorted with some other operator than
3278
* the one we want, fail --- this suggests that there is data we can't
3281
if (get_attstatsslot(vardata->statsTuple,
3282
vardata->atttype, vardata->atttypmod,
3283
STATISTIC_KIND_HISTOGRAM, sortop,
3289
tmax = datumCopy(values[nvalues - 1], typByVal, typLen);
3292
free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
3296
Oid rsortop = get_commutator(sortop);
3298
if (OidIsValid(rsortop) &&
3299
get_attstatsslot(vardata->statsTuple,
3300
vardata->atttype, vardata->atttypmod,
3301
STATISTIC_KIND_HISTOGRAM, rsortop,
3307
tmax = datumCopy(values[0], typByVal, typLen);
3310
free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
3312
else if (get_attstatsslot(vardata->statsTuple,
3313
vardata->atttype, vardata->atttypmod,
3314
STATISTIC_KIND_HISTOGRAM, InvalidOid,
3318
free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
3324
* If we have most-common-values info, look for a large MCV. This is
3325
* needed even if we also have a histogram, since the histogram
3326
* excludes the MCVs. However, usually the MCVs will not be the
3327
* extreme values, so avoid unnecessary data copying.
3329
if (get_attstatsslot(vardata->statsTuple,
3330
vardata->atttype, vardata->atttypmod,
3331
STATISTIC_KIND_MCV, InvalidOid,
3335
bool large_mcv = false;
3338
fmgr_info(get_opcode(sortop), &opproc);
3340
for (i = 0; i < nvalues; i++)
3345
large_mcv = have_max = true;
3347
else if (DatumGetBool(FunctionCall2(&opproc, tmax, values[i])))
3354
tmax = datumCopy(tmax, typByVal, typLen);
3355
free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
3363
/*-------------------------------------------------------------------------
3365
* Pattern analysis functions
3367
* These routines support analysis of LIKE and regular-expression patterns
3368
* by the planner/optimizer. It's important that they agree with the
3369
* regular-expression code in backend/regex/ and the LIKE code in
3370
* backend/utils/adt/like.c.
3372
* Note that the prefix-analysis functions are called from
3373
* backend/optimizer/path/indxpath.c as well as from routines in this file.
3375
*-------------------------------------------------------------------------
3379
* Extract the fixed prefix, if any, for a pattern.
3381
* *prefix is set to a palloc'd prefix string (in the form of a Const node),
3382
* or to NULL if no fixed prefix exists for the pattern.
3383
* *rest is set to a palloc'd Const representing the remainder of the pattern
3384
* after the portion describing the fixed prefix.
3385
* Each of these has the same type (TEXT or BYTEA) as the given pattern Const.
3387
* The return value distinguishes no fixed prefix, a partial prefix,
3388
* or an exact-match-only pattern.
3391
static Pattern_Prefix_Status
3392
like_fixed_prefix(Const *patt_const, bool case_insensitive,
3393
Const **prefix_const, Const **rest_const)
3399
Oid typeid = patt_const->consttype;
3403
/* the right-hand const is type text or bytea */
3404
Assert(typeid == BYTEAOID || typeid == TEXTOID);
3406
if (typeid == BYTEAOID && case_insensitive)
3408
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3409
errmsg("case insensitive matching not supported on type bytea")));
3411
if (typeid != BYTEAOID)
3413
patt = DatumGetCString(DirectFunctionCall1(textout, patt_const->constvalue));
3414
pattlen = strlen(patt);
3418
bytea *bstr = DatumGetByteaP(patt_const->constvalue);
3420
pattlen = VARSIZE(bstr) - VARHDRSZ;
3423
patt = (char *) palloc(pattlen);
3424
memcpy(patt, VARDATA(bstr), pattlen);
3429
if ((Pointer) bstr != DatumGetPointer(patt_const->constvalue))
3433
match = palloc(pattlen + 1);
3435
for (pos = 0; pos < pattlen; pos++)
3437
/* % and _ are wildcard characters in LIKE */
3438
if (patt[pos] == '%' ||
3442
/* Backslash escapes the next character */
3443
if (patt[pos] == '\\')
3446
if (patt[pos] == '\0' && typeid != BYTEAOID)
3451
* XXX I suspect isalpha() is not an adequately locale-sensitive
3452
* test for characters that can vary under case folding?
3454
if (case_insensitive && isalpha((unsigned char) patt[pos]))
3458
* NOTE: this code used to think that %% meant a literal %, but
3459
* textlike() itself does not think that, and the SQL92 spec
3460
* doesn't say any such thing either.
3462
match[match_pos++] = patt[pos];
3465
match[match_pos] = '\0';
3468
if (typeid != BYTEAOID)
3470
*prefix_const = string_to_const(match, typeid);
3471
*rest_const = string_to_const(rest, typeid);
3475
*prefix_const = string_to_bytea_const(match, match_pos);
3476
*rest_const = string_to_bytea_const(rest, pattlen - pos);
3483
/* in LIKE, an empty pattern is an exact match! */
3485
return Pattern_Prefix_Exact; /* reached end of pattern, so
3489
return Pattern_Prefix_Partial;
3491
return Pattern_Prefix_None;
3494
static Pattern_Prefix_Status
3495
regex_fixed_prefix(Const *patt_const, bool case_insensitive,
3496
Const **prefix_const, Const **rest_const)
3506
Oid typeid = patt_const->consttype;
3509
* Should be unnecessary, there are no bytea regex operators defined.
3510
* As such, it should be noted that the rest of this function has *not*
3511
* been made safe for binary (possibly NULL containing) strings.
3513
if (typeid == BYTEAOID)
3515
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3516
errmsg("regular-expression matching not supported on type bytea")));
3518
/* the right-hand const is type text for all of these */
3519
patt = DatumGetCString(DirectFunctionCall1(textout, patt_const->constvalue));
3521
/* Pattern must be anchored left */
3526
*prefix_const = NULL;
3527
*rest_const = string_to_const(rest, typeid);
3529
return Pattern_Prefix_None;
3533
* If unquoted | is present at paren level 0 in pattern, then there
3534
* are multiple alternatives for the start of the string.
3537
for (pos = 1; patt[pos]; pos++)
3539
if (patt[pos] == '|' && paren_depth == 0)
3543
*prefix_const = NULL;
3544
*rest_const = string_to_const(rest, typeid);
3546
return Pattern_Prefix_None;
3548
else if (patt[pos] == '(')
3550
else if (patt[pos] == ')' && paren_depth > 0)
3552
else if (patt[pos] == '\\')
3554
/* backslash quotes the next character */
3556
if (patt[pos] == '\0')
3561
/* OK, allocate space for pattern */
3562
match = palloc(strlen(patt) + 1);
3563
prev_match_pos = match_pos = 0;
3565
/* note start at pos 1 to skip leading ^ */
3566
for (prev_pos = pos = 1; patt[pos]; )
3571
* Check for characters that indicate multiple possible matches
3572
* here. XXX I suspect isalpha() is not an adequately
3573
* locale-sensitive test for characters that can vary under case
3576
if (patt[pos] == '.' ||
3580
(case_insensitive && isalpha((unsigned char) patt[pos])))
3584
* In AREs, backslash followed by alphanumeric is an escape, not
3585
* a quoted character. Must treat it as having multiple possible
3588
if (patt[pos] == '\\' && isalnum((unsigned char) patt[pos + 1]))
3592
* Check for quantifiers. Except for +, this means the preceding
3593
* character is optional, so we must remove it from the prefix
3596
if (patt[pos] == '*' ||
3600
match_pos = prev_match_pos;
3604
if (patt[pos] == '+')
3609
if (patt[pos] == '\\')
3611
/* backslash quotes the next character */
3613
if (patt[pos] == '\0')
3616
/* save position in case we need to back up on next loop cycle */
3617
prev_match_pos = match_pos;
3619
/* must use encoding-aware processing here */
3620
len = pg_mblen(&patt[pos]);
3621
memcpy(&match[match_pos], &patt[pos], len);
3626
match[match_pos] = '\0';
3629
if (patt[pos] == '$' && patt[pos + 1] == '\0')
3631
rest = &patt[pos + 1];
3633
*prefix_const = string_to_const(match, typeid);
3634
*rest_const = string_to_const(rest, typeid);
3639
return Pattern_Prefix_Exact; /* pattern specifies exact match */
3642
*prefix_const = string_to_const(match, typeid);
3643
*rest_const = string_to_const(rest, typeid);
3649
return Pattern_Prefix_Partial;
3651
return Pattern_Prefix_None;
3654
Pattern_Prefix_Status
3655
pattern_fixed_prefix(Const *patt, Pattern_Type ptype,
3656
Const **prefix, Const **rest)
3658
Pattern_Prefix_Status result;
3662
case Pattern_Type_Like:
3663
result = like_fixed_prefix(patt, false, prefix, rest);
3665
case Pattern_Type_Like_IC:
3666
result = like_fixed_prefix(patt, true, prefix, rest);
3668
case Pattern_Type_Regex:
3669
result = regex_fixed_prefix(patt, false, prefix, rest);
3671
case Pattern_Type_Regex_IC:
3672
result = regex_fixed_prefix(patt, true, prefix, rest);
3675
elog(ERROR, "unrecognized ptype: %d", (int) ptype);
3676
result = Pattern_Prefix_None; /* keep compiler quiet */
3683
* Estimate the selectivity of a fixed prefix for a pattern match.
3685
* A fixed prefix "foo" is estimated as the selectivity of the expression
3686
* "variable >= 'foo' AND variable < 'fop'" (see also indxqual.c).
3688
* We use the >= and < operators from the specified btree opclass to do the
3689
* estimation. The given variable and Const must be of the associated
3692
* XXX Note: we make use of the upper bound to estimate operator selectivity
3693
* even if the locale is such that we cannot rely on the upper-bound string.
3694
* The selectivity only needs to be approximately right anyway, so it seems
3695
* more useful to use the upper-bound code than not.
3698
prefix_selectivity(Query *root, VariableStatData *vardata,
3699
Oid opclass, Const *prefixcon)
3701
Selectivity prefixsel;
3704
Const *greaterstrcon;
3706
cmpopr = get_opclass_member(opclass, InvalidOid,
3707
BTGreaterEqualStrategyNumber);
3708
if (cmpopr == InvalidOid)
3709
elog(ERROR, "no >= operator for opclass %u", opclass);
3710
cmpargs = list_make2(vardata->var, prefixcon);
3711
/* Assume scalargtsel is appropriate for all supported types */
3712
prefixsel = DatumGetFloat8(DirectFunctionCall4(scalargtsel,
3713
PointerGetDatum(root),
3714
ObjectIdGetDatum(cmpopr),
3715
PointerGetDatum(cmpargs),
3719
* If we can create a string larger than the prefix, say
3723
greaterstrcon = make_greater_string(prefixcon);
3728
cmpopr = get_opclass_member(opclass, InvalidOid,
3729
BTLessStrategyNumber);
3730
if (cmpopr == InvalidOid)
3731
elog(ERROR, "no < operator for opclass %u", opclass);
3732
cmpargs = list_make2(vardata->var, greaterstrcon);
3733
/* Assume scalarltsel is appropriate for all supported types */
3734
topsel = DatumGetFloat8(DirectFunctionCall4(scalarltsel,
3735
PointerGetDatum(root),
3736
ObjectIdGetDatum(cmpopr),
3737
PointerGetDatum(cmpargs),
3741
* Merge the two selectivities in the same way as for a range
3742
* query (see clauselist_selectivity()).
3744
prefixsel = topsel + prefixsel - 1.0;
3746
/* Adjust for double-exclusion of NULLs */
3747
prefixsel += nulltestsel(root, IS_NULL, vardata->var, 0);
3750
* A zero or slightly negative prefixsel should be converted into
3751
* a small positive value; we probably are dealing with a very
3752
* tight range and got a bogus result due to roundoff errors.
3753
* However, if prefixsel is very negative, then we probably have
3754
* default selectivity estimates on one or both sides of the
3755
* range. In that case, insert a not-so-wildly-optimistic default
3758
if (prefixsel <= 0.0)
3760
if (prefixsel < -0.01)
3763
* No data available --- use a default estimate that is
3764
* small, but not real small.
3771
* It's just roundoff error; use a small positive value
3773
prefixsel = 1.0e-10;
3783
* Estimate the selectivity of a pattern of the specified type.
3784
* Note that any fixed prefix of the pattern will have been removed already.
3786
* For now, we use a very simplistic approach: fixed characters reduce the
3787
* selectivity a good deal, character ranges reduce it a little,
3788
* wildcards (such as % for LIKE or .* for regex) increase it.
3791
#define FIXED_CHAR_SEL 0.20 /* about 1/5 */
3792
#define CHAR_RANGE_SEL 0.25
3793
#define ANY_CHAR_SEL 0.9 /* not 1, since it won't match
3795
#define FULL_WILDCARD_SEL 5.0
3796
#define PARTIAL_WILDCARD_SEL 2.0
3799
like_selectivity(Const *patt_const, bool case_insensitive)
3801
Selectivity sel = 1.0;
3804
Oid typeid = patt_const->consttype;
3808
/* the right-hand const is type text or bytea */
3809
Assert(typeid == BYTEAOID || typeid == TEXTOID);
3811
if (typeid == BYTEAOID && case_insensitive)
3813
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3814
errmsg("case insensitive matching not supported on type bytea")));
3816
if (typeid != BYTEAOID)
3818
patt = DatumGetCString(DirectFunctionCall1(textout, patt_const->constvalue));
3819
pattlen = strlen(patt);
3823
bytea *bstr = DatumGetByteaP(patt_const->constvalue);
3825
pattlen = VARSIZE(bstr) - VARHDRSZ;
3828
patt = (char *) palloc(pattlen);
3829
memcpy(patt, VARDATA(bstr), pattlen);
3834
if ((Pointer) bstr != DatumGetPointer(patt_const->constvalue))
3837
/* patt should never be NULL in practice */
3838
Assert(patt != NULL);
3840
/* Skip any leading %; it's already factored into initial sel */
3841
start = (*patt == '%') ? 1 : 0;
3842
for (pos = start; pos < pattlen; pos++)
3844
/* % and _ are wildcard characters in LIKE */
3845
if (patt[pos] == '%')
3846
sel *= FULL_WILDCARD_SEL;
3847
else if (patt[pos] == '_')
3848
sel *= ANY_CHAR_SEL;
3849
else if (patt[pos] == '\\')
3851
/* Backslash quotes the next character */
3853
if (patt[pos] == '\0' && typeid != BYTEAOID)
3855
sel *= FIXED_CHAR_SEL;
3858
sel *= FIXED_CHAR_SEL;
3860
/* Could get sel > 1 if multiple wildcards */
3867
regex_selectivity_sub(char *patt, int pattlen, bool case_insensitive)
3869
Selectivity sel = 1.0;
3870
int paren_depth = 0;
3871
int paren_pos = 0; /* dummy init to keep compiler quiet */
3874
for (pos = 0; pos < pattlen; pos++)
3876
if (patt[pos] == '(')
3878
if (paren_depth == 0)
3879
paren_pos = pos; /* remember start of parenthesized item */
3882
else if (patt[pos] == ')' && paren_depth > 0)
3885
if (paren_depth == 0)
3886
sel *= regex_selectivity_sub(patt + (paren_pos + 1),
3887
pos - (paren_pos + 1),
3890
else if (patt[pos] == '|' && paren_depth == 0)
3893
* If unquoted | is present at paren level 0 in pattern, we
3894
* have multiple alternatives; sum their probabilities.
3896
sel += regex_selectivity_sub(patt + (pos + 1),
3897
pattlen - (pos + 1),
3899
break; /* rest of pattern is now processed */
3901
else if (patt[pos] == '[')
3903
bool negclass = false;
3905
if (patt[++pos] == '^')
3910
if (patt[pos] == ']') /* ']' at start of class is not
3913
while (pos < pattlen && patt[pos] != ']')
3915
if (paren_depth == 0)
3916
sel *= (negclass ? (1.0 - CHAR_RANGE_SEL) : CHAR_RANGE_SEL);
3918
else if (patt[pos] == '.')
3920
if (paren_depth == 0)
3921
sel *= ANY_CHAR_SEL;
3923
else if (patt[pos] == '*' ||
3927
/* Ought to be smarter about quantifiers... */
3928
if (paren_depth == 0)
3929
sel *= PARTIAL_WILDCARD_SEL;
3931
else if (patt[pos] == '{')
3933
while (pos < pattlen && patt[pos] != '}')
3935
if (paren_depth == 0)
3936
sel *= PARTIAL_WILDCARD_SEL;
3938
else if (patt[pos] == '\\')
3940
/* backslash quotes the next character */
3944
if (paren_depth == 0)
3945
sel *= FIXED_CHAR_SEL;
3949
if (paren_depth == 0)
3950
sel *= FIXED_CHAR_SEL;
3953
/* Could get sel > 1 if multiple wildcards */
3960
regex_selectivity(Const *patt_const, bool case_insensitive)
3965
Oid typeid = patt_const->consttype;
3968
* Should be unnecessary, there are no bytea regex operators defined.
3969
* As such, it should be noted that the rest of this function has *not*
3970
* been made safe for binary (possibly NULL containing) strings.
3972
if (typeid == BYTEAOID)
3974
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3975
errmsg("regular-expression matching not supported on type bytea")));
3977
/* the right-hand const is type text for all of these */
3978
patt = DatumGetCString(DirectFunctionCall1(textout, patt_const->constvalue));
3979
pattlen = strlen(patt);
3981
/* If patt doesn't end with $, consider it to have a trailing wildcard */
3982
if (pattlen > 0 && patt[pattlen - 1] == '$' &&
3983
(pattlen == 1 || patt[pattlen - 2] != '\\'))
3985
/* has trailing $ */
3986
sel = regex_selectivity_sub(patt, pattlen - 1, case_insensitive);
3991
sel = regex_selectivity_sub(patt, pattlen, case_insensitive);
3992
sel *= FULL_WILDCARD_SEL;
4000
pattern_selectivity(Const *patt, Pattern_Type ptype)
4006
case Pattern_Type_Like:
4007
result = like_selectivity(patt, false);
4009
case Pattern_Type_Like_IC:
4010
result = like_selectivity(patt, true);
4012
case Pattern_Type_Regex:
4013
result = regex_selectivity(patt, false);
4015
case Pattern_Type_Regex_IC:
4016
result = regex_selectivity(patt, true);
4019
elog(ERROR, "unrecognized ptype: %d", (int) ptype);
4020
result = 1.0; /* keep compiler quiet */
4028
* Try to generate a string greater than the given string or any
4029
* string it is a prefix of. If successful, return a palloc'd string
4030
* in the form of a Const pointer; else return NULL.
4032
* The key requirement here is that given a prefix string, say "foo",
4033
* we must be able to generate another string "fop" that is greater
4034
* than all strings "foobar" starting with "foo".
4036
* If we max out the righthand byte, truncate off the last character
4037
* and start incrementing the next. For example, if "z" were the last
4038
* character in the sort order, then we could produce "foo" as a
4039
* string greater than "fonz".
4041
* This could be rather slow in the worst case, but in most cases we
4042
* won't have to try more than one or two strings before succeeding.
4044
* NOTE: at present this assumes we are in the C locale, so that simple
4045
* bytewise comparison applies. However, we might be in a multibyte
4046
* encoding such as UTF-8, so we do have to watch out for generating
4047
* invalid encoding sequences.
4050
make_greater_string(const Const *str_const)
4052
Oid datatype = str_const->consttype;
4056
/* Get the string and a modifiable copy */
4057
if (datatype == NAMEOID)
4059
workstr = DatumGetCString(DirectFunctionCall1(nameout,
4060
str_const->constvalue));
4061
len = strlen(workstr);
4063
else if (datatype == BYTEAOID)
4065
bytea *bstr = DatumGetByteaP(str_const->constvalue);
4067
len = VARSIZE(bstr) - VARHDRSZ;
4070
workstr = (char *) palloc(len);
4071
memcpy(workstr, VARDATA(bstr), len);
4076
if ((Pointer) bstr != DatumGetPointer(str_const->constvalue))
4081
workstr = DatumGetCString(DirectFunctionCall1(textout,
4082
str_const->constvalue));
4083
len = strlen(workstr);
4088
unsigned char *lastchar = (unsigned char *) (workstr + len - 1);
4089
unsigned char savelastchar = *lastchar;
4092
* Try to generate a larger string by incrementing the last byte.
4094
while (*lastchar < (unsigned char) 255)
4096
Const *workstr_const;
4100
if (datatype != BYTEAOID)
4102
/* do not generate invalid encoding sequences */
4103
if (!pg_verifymbstr((const unsigned char *) workstr,
4106
workstr_const = string_to_const(workstr, datatype);
4109
workstr_const = string_to_bytea_const(workstr, len);
4112
return workstr_const;
4115
/* restore last byte so we don't confuse pg_mbcliplen */
4116
*lastchar = savelastchar;
4119
* Truncate off the last character, which might be more than 1
4120
* byte, depending on the character encoding.
4122
if (datatype != BYTEAOID && pg_database_encoding_max_length() > 1)
4123
len = pg_mbcliplen((const unsigned char *) workstr, len, len - 1);
4127
if (datatype != BYTEAOID)
4128
workstr[len] = '\0';
4132
if (workstr != NULL)
4139
* Generate a Datum of the appropriate type from a C string.
4140
* Note that all of the supported types are pass-by-ref, so the
4141
* returned value should be pfree'd if no longer needed.
4144
string_to_datum(const char *str, Oid datatype)
4146
Assert(str != NULL);
4149
* We cheat a little by assuming that textin() will do for bpchar and
4150
* varchar constants too...
4152
if (datatype == NAMEOID)
4153
return DirectFunctionCall1(namein, CStringGetDatum(str));
4154
else if (datatype == BYTEAOID)
4155
return DirectFunctionCall1(byteain, CStringGetDatum(str));
4157
return DirectFunctionCall1(textin, CStringGetDatum(str));
4161
* Generate a Const node of the appropriate type from a C string.
4164
string_to_const(const char *str, Oid datatype)
4166
Datum conval = string_to_datum(str, datatype);
4168
return makeConst(datatype, ((datatype == NAMEOID) ? NAMEDATALEN : -1),
4169
conval, false, false);
4173
* Generate a Const node of bytea type from a binary C string and a length.
4176
string_to_bytea_const(const char *str, size_t str_len)
4178
bytea *bstr = palloc(VARHDRSZ + str_len);
4181
memcpy(VARDATA(bstr), str, str_len);
4182
VARATT_SIZEP(bstr) = VARHDRSZ + str_len;
4183
conval = PointerGetDatum(bstr);
4185
return makeConst(BYTEAOID, -1, conval, false, false);
4188
/*-------------------------------------------------------------------------
4190
* Index cost estimation functions
4192
* genericcostestimate is a general-purpose estimator for use when we
4193
* don't have any better idea about how to estimate. Index-type-specific
4194
* knowledge can be incorporated in the type-specific routines.
4196
*-------------------------------------------------------------------------
4200
genericcostestimate(Query *root, RelOptInfo *rel,
4201
IndexOptInfo *index, List *indexQuals,
4202
Cost *indexStartupCost,
4203
Cost *indexTotalCost,
4204
Selectivity *indexSelectivity,
4205
double *indexCorrelation)
4207
double numIndexTuples;
4208
double numIndexPages;
4209
QualCost index_qual_cost;
4210
double qual_op_cost;
4211
double qual_arg_cost;
4212
List *selectivityQuals;
4215
* If the index is partial, AND the index predicate with the
4216
* explicitly given indexquals to produce a more accurate idea of the
4217
* index selectivity. This may produce redundant clauses. We get rid
4218
* of exact duplicates in the code below. We expect that most cases
4219
* of partial redundancy (such as "x < 4" from the qual and "x < 5"
4220
* from the predicate) will be recognized and handled correctly by
4221
* clauselist_selectivity(). This assumption is somewhat fragile,
4222
* since it depends on pred_test() and clauselist_selectivity() having
4223
* similar capabilities, and there are certainly many cases where we
4224
* will end up with a too-low selectivity estimate. This will bias
4225
* the system in favor of using partial indexes where possible, which
4226
* is not necessarily a bad thing. But it'd be nice to do better
4229
* Note that index->indpred and indexQuals are both in implicit-AND form,
4230
* so ANDing them together just takes merging the lists. However,
4231
* eliminating duplicates is a bit trickier because indexQuals
4232
* contains RestrictInfo nodes and the indpred does not. It is okay
4233
* to pass a mixed list to clauselist_selectivity, but we have to work
4234
* a bit to generate a list without logical duplicates. (We could
4235
* just list_union indpred and strippedQuals, but then we'd not get
4236
* caching of per-qual selectivity estimates.)
4238
if (index->indpred != NIL)
4240
List *strippedQuals;
4241
List *predExtraQuals;
4243
strippedQuals = get_actual_clauses(indexQuals);
4244
predExtraQuals = list_difference(index->indpred, strippedQuals);
4245
selectivityQuals = list_concat(predExtraQuals, indexQuals);
4248
selectivityQuals = indexQuals;
4250
/* Estimate the fraction of main-table tuples that will be visited */
4251
*indexSelectivity = clauselist_selectivity(root, selectivityQuals,
4256
* Estimate the number of tuples that will be visited. We do it in
4257
* this rather peculiar-looking way in order to get the right answer
4258
* for partial indexes. We can bound the number of tuples by the
4259
* index size, in any case.
4261
numIndexTuples = *indexSelectivity * rel->tuples;
4263
if (numIndexTuples > index->tuples)
4264
numIndexTuples = index->tuples;
4267
* Always estimate at least one tuple is touched, even when
4268
* indexSelectivity estimate is tiny.
4270
if (numIndexTuples < 1.0)
4271
numIndexTuples = 1.0;
4274
* Estimate the number of index pages that will be retrieved.
4276
* For all currently-supported index types, the first page of the index
4277
* is a metadata page, and we should figure on fetching that plus a
4278
* pro-rated fraction of the remaining pages.
4280
if (index->pages > 1 && index->tuples > 0)
4282
numIndexPages = (numIndexTuples / index->tuples) * (index->pages - 1);
4283
numIndexPages += 1; /* count the metapage too */
4284
numIndexPages = ceil(numIndexPages);
4287
numIndexPages = 1.0;
4290
* Compute the index access cost.
4292
* Disk cost: our generic assumption is that the index pages will be read
4293
* sequentially, so they have cost 1.0 each, not random_page_cost.
4295
*indexTotalCost = numIndexPages;
4298
* CPU cost: any complex expressions in the indexquals will need to be
4299
* evaluated once at the start of the scan to reduce them to runtime
4300
* keys to pass to the index AM (see nodeIndexscan.c). We model the
4301
* per-tuple CPU costs as cpu_index_tuple_cost plus one
4302
* cpu_operator_cost per indexqual operator.
4304
* Note: this neglects the possible costs of rechecking lossy operators
4305
* and OR-clause expressions. Detecting that that might be needed
4306
* seems more expensive than it's worth, though, considering all the
4307
* other inaccuracies here ...
4309
cost_qual_eval(&index_qual_cost, indexQuals);
4310
qual_op_cost = cpu_operator_cost * list_length(indexQuals);
4311
qual_arg_cost = index_qual_cost.startup +
4312
index_qual_cost.per_tuple - qual_op_cost;
4313
if (qual_arg_cost < 0) /* just in case... */
4315
*indexStartupCost = qual_arg_cost;
4316
*indexTotalCost += qual_arg_cost;
4317
*indexTotalCost += numIndexTuples * (cpu_index_tuple_cost + qual_op_cost);
4320
* Generic assumption about index correlation: there isn't any.
4322
*indexCorrelation = 0.0;
4327
btcostestimate(PG_FUNCTION_ARGS)
4329
Query *root = (Query *) PG_GETARG_POINTER(0);
4330
RelOptInfo *rel = (RelOptInfo *) PG_GETARG_POINTER(1);
4331
IndexOptInfo *index = (IndexOptInfo *) PG_GETARG_POINTER(2);
4332
List *indexQuals = (List *) PG_GETARG_POINTER(3);
4333
Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(4);
4334
Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(5);
4335
Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(6);
4336
double *indexCorrelation = (double *) PG_GETARG_POINTER(7);
4341
genericcostestimate(root, rel, index, indexQuals,
4342
indexStartupCost, indexTotalCost,
4343
indexSelectivity, indexCorrelation);
4346
* If we can get an estimate of the first column's ordering
4347
* correlation C from pg_statistic, estimate the index correlation as
4348
* C for a single- column index, or C * 0.75 for multiple columns.
4349
* (The idea here is that multiple columns dilute the importance of
4350
* the first column's ordering, but don't negate it entirely. Before
4351
* 8.0 we divided the correlation by the number of columns, but that
4352
* seems too strong.)
4354
if (index->indexkeys[0] != 0)
4356
/* Simple variable --- look to stats for the underlying table */
4357
relid = getrelid(rel->relid, root->rtable);
4358
Assert(relid != InvalidOid);
4359
colnum = index->indexkeys[0];
4363
/* Expression --- maybe there are stats for the index itself */
4364
relid = index->indexoid;
4368
tuple = SearchSysCache(STATRELATT,
4369
ObjectIdGetDatum(relid),
4370
Int16GetDatum(colnum),
4373
if (HeapTupleIsValid(tuple))
4380
/* XXX this code would break with different storage type */
4381
get_atttypetypmod(relid, colnum, &typid, &typmod);
4383
if (get_attstatsslot(tuple, typid, typmod,
4384
STATISTIC_KIND_CORRELATION,
4386
NULL, NULL, &numbers, &nnumbers))
4388
double varCorrelation;
4390
Assert(nnumbers == 1);
4391
varCorrelation = numbers[0];
4393
if (index->ncolumns > 1)
4394
*indexCorrelation = varCorrelation * 0.75;
4396
*indexCorrelation = varCorrelation;
4398
free_attstatsslot(typid, NULL, 0, numbers, nnumbers);
4400
ReleaseSysCache(tuple);
4407
rtcostestimate(PG_FUNCTION_ARGS)
4409
Query *root = (Query *) PG_GETARG_POINTER(0);
4410
RelOptInfo *rel = (RelOptInfo *) PG_GETARG_POINTER(1);
4411
IndexOptInfo *index = (IndexOptInfo *) PG_GETARG_POINTER(2);
4412
List *indexQuals = (List *) PG_GETARG_POINTER(3);
4413
Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(4);
4414
Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(5);
4415
Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(6);
4416
double *indexCorrelation = (double *) PG_GETARG_POINTER(7);
4418
genericcostestimate(root, rel, index, indexQuals,
4419
indexStartupCost, indexTotalCost,
4420
indexSelectivity, indexCorrelation);
4426
hashcostestimate(PG_FUNCTION_ARGS)
4428
Query *root = (Query *) PG_GETARG_POINTER(0);
4429
RelOptInfo *rel = (RelOptInfo *) PG_GETARG_POINTER(1);
4430
IndexOptInfo *index = (IndexOptInfo *) PG_GETARG_POINTER(2);
4431
List *indexQuals = (List *) PG_GETARG_POINTER(3);
4432
Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(4);
4433
Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(5);
4434
Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(6);
4435
double *indexCorrelation = (double *) PG_GETARG_POINTER(7);
4437
genericcostestimate(root, rel, index, indexQuals,
4438
indexStartupCost, indexTotalCost,
4439
indexSelectivity, indexCorrelation);
4445
gistcostestimate(PG_FUNCTION_ARGS)
4447
Query *root = (Query *) PG_GETARG_POINTER(0);
4448
RelOptInfo *rel = (RelOptInfo *) PG_GETARG_POINTER(1);
4449
IndexOptInfo *index = (IndexOptInfo *) PG_GETARG_POINTER(2);
4450
List *indexQuals = (List *) PG_GETARG_POINTER(3);
4451
Cost *indexStartupCost = (Cost *) PG_GETARG_POINTER(4);
4452
Cost *indexTotalCost = (Cost *) PG_GETARG_POINTER(5);
4453
Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(6);
4454
double *indexCorrelation = (double *) PG_GETARG_POINTER(7);
4456
genericcostestimate(root, rel, index, indexQuals,
4457
indexStartupCost, indexTotalCost,
4458
indexSelectivity, indexCorrelation);