~vcs-imports/mammoth-replicator/trunk

« back to all changes in this revision

Viewing changes to src/backend/utils/adt/selfuncs.c

  • Committer: alvherre
  • Date: 2005-12-16 21:24:52 UTC
  • Revision ID: svn-v4:db760fc0-0f08-0410-9d63-cc6633f64896:trunk:1
Initial import of the REL8_0_3 sources from the Pgsql CVS repository.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*-------------------------------------------------------------------------
 
2
 *
 
3
 * selfuncs.c
 
4
 *        Selectivity functions and index cost estimation functions for
 
5
 *        standard operators and index access methods.
 
6
 *
 
7
 *        Selectivity routines are registered in the pg_operator catalog
 
8
 *        in the "oprrest" and "oprjoin" attributes.
 
9
 *
 
10
 *        Index cost functions are registered in the pg_am catalog
 
11
 *        in the "amcostestimate" attribute.
 
12
 *
 
13
 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
 
14
 * Portions Copyright (c) 1994, Regents of the University of California
 
15
 *
 
16
 *
 
17
 * IDENTIFICATION
 
18
 *        $PostgreSQL: pgsql/src/backend/utils/adt/selfuncs.c,v 1.169.4.4 2005-04-01 20:32:09 tgl Exp $
 
19
 *
 
20
 *-------------------------------------------------------------------------
 
21
 */
 
22
 
 
23
/*----------
 
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
 
28
 *                      one relation.
 
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.
 
32
 *
 
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.
 
38
 *
 
39
 * The call convention for a restriction estimator (oprrest function) is
 
40
 *
 
41
 *              Selectivity oprrest (Query *root,
 
42
 *                                                       Oid operator,
 
43
 *                                                       List *args,
 
44
 *                                                       int varRelid);
 
45
 *
 
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.
 
53
 *
 
54
 * This is represented at the SQL level (in pg_proc) as
 
55
 *
 
56
 *              float8 oprrest (internal, oid, internal, int4);
 
57
 *
 
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
 
60
 * supplied:
 
61
 *
 
62
 *              Selectivity oprjoin (Query *root,
 
63
 *                                                       Oid operator,
 
64
 *                                                       List *args,
 
65
 *                                                       JoinType jointype);
 
66
 *
 
67
 *              float8 oprjoin (internal, oid, internal, int2);
 
68
 *
 
69
 * (We deliberately make the SQL signature different to facilitate
 
70
 * catching errors.)
 
71
 *----------
 
72
 */
 
73
 
 
74
#include "postgres.h"
 
75
 
 
76
#include <ctype.h>
 
77
#include <math.h>
 
78
 
 
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"
 
112
 
 
113
 
 
114
/* Return data from examine_variable and friends */
 
115
typedef struct
 
116
{
 
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 */
 
125
} VariableStatData;
 
126
 
 
127
#define ReleaseVariableStats(vardata)  \
 
128
        do { \
 
129
                if (HeapTupleIsValid((vardata).statsTuple)) \
 
130
                        ReleaseSysCache((vardata).statsTuple); \
 
131
        } while(0)
 
132
 
 
133
 
 
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,
 
139
                                                 double *scaledvalue,
 
140
                                                 unsigned char *lobound,
 
141
                                                 double *scaledlobound,
 
142
                                                 unsigned char *hibound,
 
143
                                                 double *scaledhibound);
 
144
static void convert_bytea_to_scalar(Datum value,
 
145
                                                double *scaledvalue,
 
146
                                                Datum lobound,
 
147
                                                double *scaledlobound,
 
148
                                                Datum hibound,
 
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,
 
158
                                                 bool *varonleft);
 
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);
 
173
 
 
174
 
 
175
/*
 
176
 *              eqsel                   - Selectivity of "=" for any data types.
 
177
 *
 
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.
 
182
 */
 
183
Datum
 
184
eqsel(PG_FUNCTION_ARGS)
 
185
{
 
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;
 
191
        Node       *other;
 
192
        bool            varonleft;
 
193
        Datum      *values;
 
194
        int                     nvalues;
 
195
        float4     *numbers;
 
196
        int                     nnumbers;
 
197
        double          selec;
 
198
 
 
199
        /*
 
200
         * If expression is not variable = something or something = variable,
 
201
         * then punt and return a default estimate.
 
202
         */
 
203
        if (!get_restriction_variable(root, args, varRelid,
 
204
                                                                  &vardata, &other, &varonleft))
 
205
                PG_RETURN_FLOAT8(DEFAULT_EQ_SEL);
 
206
 
 
207
        /*
 
208
         * If the something is a NULL constant, assume operator is strict and
 
209
         * return zero, ie, operator will never return TRUE.
 
210
         */
 
211
        if (IsA(other, Const) &&
 
212
                ((Const *) other)->constisnull)
 
213
        {
 
214
                ReleaseVariableStats(vardata);
 
215
                PG_RETURN_FLOAT8(0.0);
 
216
        }
 
217
 
 
218
        if (HeapTupleIsValid(vardata.statsTuple))
 
219
        {
 
220
                Form_pg_statistic stats;
 
221
 
 
222
                stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
 
223
 
 
224
                if (IsA(other, Const))
 
225
                {
 
226
                        /* Variable is being compared to a known non-null constant */
 
227
                        Datum           constval = ((Const *) other)->constvalue;
 
228
                        bool            match = false;
 
229
                        int                     i;
 
230
 
 
231
                        /*
 
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...)
 
237
                         */
 
238
                        if (get_attstatsslot(vardata.statsTuple,
 
239
                                                                 vardata.atttype, vardata.atttypmod,
 
240
                                                                 STATISTIC_KIND_MCV, InvalidOid,
 
241
                                                                 &values, &nvalues,
 
242
                                                                 &numbers, &nnumbers))
 
243
                        {
 
244
                                FmgrInfo        eqproc;
 
245
 
 
246
                                fmgr_info(get_opcode(operator), &eqproc);
 
247
 
 
248
                                for (i = 0; i < nvalues; i++)
 
249
                                {
 
250
                                        /* be careful to apply operator right way 'round */
 
251
                                        if (varonleft)
 
252
                                                match = DatumGetBool(FunctionCall2(&eqproc,
 
253
                                                                                                                   values[i],
 
254
                                                                                                                   constval));
 
255
                                        else
 
256
                                                match = DatumGetBool(FunctionCall2(&eqproc,
 
257
                                                                                                                   constval,
 
258
                                                                                                                   values[i]));
 
259
                                        if (match)
 
260
                                                break;
 
261
                                }
 
262
                        }
 
263
                        else
 
264
                        {
 
265
                                /* no most-common-value info available */
 
266
                                values = NULL;
 
267
                                numbers = NULL;
 
268
                                i = nvalues = nnumbers = 0;
 
269
                        }
 
270
 
 
271
                        if (match)
 
272
                        {
 
273
                                /*
 
274
                                 * Constant is "=" to this common value.  We know
 
275
                                 * selectivity exactly (or as exactly as VACUUM could
 
276
                                 * calculate it, anyway).
 
277
                                 */
 
278
                                selec = numbers[i];
 
279
                        }
 
280
                        else
 
281
                        {
 
282
                                /*
 
283
                                 * Comparison is against a constant that is neither NULL
 
284
                                 * nor any of the common values.  Its selectivity cannot
 
285
                                 * be more than this:
 
286
                                 */
 
287
                                double          sumcommon = 0.0;
 
288
                                double          otherdistinct;
 
289
 
 
290
                                for (i = 0; i < nnumbers; i++)
 
291
                                        sumcommon += numbers[i];
 
292
                                selec = 1.0 - sumcommon - stats->stanullfrac;
 
293
                                CLAMP_PROBABILITY(selec);
 
294
 
 
295
                                /*
 
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.
 
300
                                 */
 
301
                                otherdistinct = get_variable_numdistinct(&vardata)
 
302
                                        - nnumbers;
 
303
                                if (otherdistinct > 1)
 
304
                                        selec /= otherdistinct;
 
305
 
 
306
                                /*
 
307
                                 * Another cross-check: selectivity shouldn't be estimated
 
308
                                 * as more than the least common "most common value".
 
309
                                 */
 
310
                                if (nnumbers > 0 && selec > numbers[nnumbers - 1])
 
311
                                        selec = numbers[nnumbers - 1];
 
312
                        }
 
313
 
 
314
                        free_attstatsslot(vardata.atttype, values, nvalues,
 
315
                                                          numbers, nnumbers);
 
316
                }
 
317
                else
 
318
                {
 
319
                        double          ndistinct;
 
320
 
 
321
                        /*
 
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?)
 
330
                         */
 
331
                        selec = 1.0 - stats->stanullfrac;
 
332
                        ndistinct = get_variable_numdistinct(&vardata);
 
333
                        if (ndistinct > 1)
 
334
                                selec /= ndistinct;
 
335
 
 
336
                        /*
 
337
                         * Cross-check: selectivity should never be estimated as more
 
338
                         * than the most common value's.
 
339
                         */
 
340
                        if (get_attstatsslot(vardata.statsTuple,
 
341
                                                                 vardata.atttype, vardata.atttypmod,
 
342
                                                                 STATISTIC_KIND_MCV, InvalidOid,
 
343
                                                                 NULL, NULL,
 
344
                                                                 &numbers, &nnumbers))
 
345
                        {
 
346
                                if (nnumbers > 0 && selec > numbers[0])
 
347
                                        selec = numbers[0];
 
348
                                free_attstatsslot(vardata.atttype, NULL, 0, numbers, nnumbers);
 
349
                        }
 
350
                }
 
351
        }
 
352
        else
 
353
        {
 
354
                /*
 
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.)
 
359
                 */
 
360
                selec = 1.0 / get_variable_numdistinct(&vardata);
 
361
        }
 
362
 
 
363
        ReleaseVariableStats(vardata);
 
364
 
 
365
        /* result should be in range, but make sure... */
 
366
        CLAMP_PROBABILITY(selec);
 
367
 
 
368
        PG_RETURN_FLOAT8((float8) selec);
 
369
}
 
370
 
 
371
/*
 
372
 *              neqsel                  - Selectivity of "!=" for any data types.
 
373
 *
 
374
 * This routine is also used for some operators that are not "!="
 
375
 * but have comparable selectivity behavior.  See above comments
 
376
 * for eqsel().
 
377
 */
 
378
Datum
 
379
neqsel(PG_FUNCTION_ARGS)
 
380
{
 
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);
 
385
        Oid                     eqop;
 
386
        float8          result;
 
387
 
 
388
        /*
 
389
         * We want 1 - eqsel() where the equality operator is the one
 
390
         * associated with this != operator, that is, its negator.
 
391
         */
 
392
        eqop = get_negator(operator);
 
393
        if (eqop)
 
394
        {
 
395
                result = DatumGetFloat8(DirectFunctionCall4(eqsel,
 
396
                                                                                                        PointerGetDatum(root),
 
397
                                                                                                  ObjectIdGetDatum(eqop),
 
398
                                                                                                        PointerGetDatum(args),
 
399
                                                                                           Int32GetDatum(varRelid)));
 
400
        }
 
401
        else
 
402
        {
 
403
                /* Use default selectivity (should we raise an error instead?) */
 
404
                result = DEFAULT_EQ_SEL;
 
405
        }
 
406
        result = 1.0 - result;
 
407
        PG_RETURN_FLOAT8(result);
 
408
}
 
409
 
 
410
/*
 
411
 *      scalarineqsel           - Selectivity of "<", "<=", ">", ">=" for scalars.
 
412
 *
 
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
 
417
 * datatype.
 
418
 *
 
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.
 
422
 */
 
423
static double
 
424
scalarineqsel(Query *root, Oid operator, bool isgt,
 
425
                          VariableStatData *vardata, Datum constval, Oid consttype)
 
426
{
 
427
        Form_pg_statistic stats;
 
428
        FmgrInfo        opproc;
 
429
        Datum      *values;
 
430
        int                     nvalues;
 
431
        float4     *numbers;
 
432
        int                     nnumbers;
 
433
        double          mcv_selec,
 
434
                                hist_selec,
 
435
                                sumcommon;
 
436
        double          selec;
 
437
        int                     i;
 
438
 
 
439
        if (!HeapTupleIsValid(vardata->statsTuple))
 
440
        {
 
441
                /* no stats available, so default result */
 
442
                return DEFAULT_INEQ_SEL;
 
443
        }
 
444
        stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
 
445
 
 
446
        fmgr_info(get_opcode(operator), &opproc);
 
447
 
 
448
        /*
 
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.
 
453
         */
 
454
        mcv_selec = 0.0;
 
455
        sumcommon = 0.0;
 
456
 
 
457
        if (get_attstatsslot(vardata->statsTuple,
 
458
                                                 vardata->atttype, vardata->atttypmod,
 
459
                                                 STATISTIC_KIND_MCV, InvalidOid,
 
460
                                                 &values, &nvalues,
 
461
                                                 &numbers, &nnumbers))
 
462
        {
 
463
                for (i = 0; i < nvalues; i++)
 
464
                {
 
465
                        if (DatumGetBool(FunctionCall2(&opproc,
 
466
                                                                                   values[i],
 
467
                                                                                   constval)))
 
468
                                mcv_selec += numbers[i];
 
469
                        sumcommon += numbers[i];
 
470
                }
 
471
                free_attstatsslot(vardata->atttype, values, nvalues,
 
472
                                                  numbers, nnumbers);
 
473
        }
 
474
 
 
475
        /*
 
476
         * If there is a histogram, determine which bin the constant falls in,
 
477
         * and compute the resulting contribution to selectivity.
 
478
         *
 
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.
 
487
         */
 
488
        hist_selec = 0.0;
 
489
 
 
490
        if (get_attstatsslot(vardata->statsTuple,
 
491
                                                 vardata->atttype, vardata->atttypmod,
 
492
                                                 STATISTIC_KIND_HISTOGRAM, InvalidOid,
 
493
                                                 &values, &nvalues,
 
494
                                                 NULL, NULL))
 
495
        {
 
496
                if (nvalues > 1)
 
497
                {
 
498
                        double          histfrac;
 
499
                        bool            ltcmp;
 
500
 
 
501
                        ltcmp = DatumGetBool(FunctionCall2(&opproc,
 
502
                                                                                           values[0],
 
503
                                                                                           constval));
 
504
                        if (isgt)
 
505
                                ltcmp = !ltcmp;
 
506
                        if (!ltcmp)
 
507
                        {
 
508
                                /* Constant is below lower histogram boundary. */
 
509
                                histfrac = 0.0;
 
510
                        }
 
511
                        else
 
512
                        {
 
513
                                /*
 
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
 
517
                                 * sizes.
 
518
                                 */
 
519
                                for (i = 1; i < nvalues; i++)
 
520
                                {
 
521
                                        ltcmp = DatumGetBool(FunctionCall2(&opproc,
 
522
                                                                                                           values[i],
 
523
                                                                                                           constval));
 
524
                                        if (isgt)
 
525
                                                ltcmp = !ltcmp;
 
526
                                        if (!ltcmp)
 
527
                                                break;
 
528
                                }
 
529
                                if (i >= nvalues)
 
530
                                {
 
531
                                        /* Constant is above upper histogram boundary. */
 
532
                                        histfrac = 1.0;
 
533
                                }
 
534
                                else
 
535
                                {
 
536
                                        double          val,
 
537
                                                                high,
 
538
                                                                low;
 
539
                                        double          binfrac;
 
540
 
 
541
                                        /*
 
542
                                         * We have values[i-1] < constant < values[i].
 
543
                                         *
 
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.
 
547
                                         */
 
548
                                        if (convert_to_scalar(constval, consttype, &val,
 
549
                                                                                  values[i - 1], values[i],
 
550
                                                                                  vardata->vartype,
 
551
                                                                                  &low, &high))
 
552
                                        {
 
553
                                                if (high <= low)
 
554
                                                {
 
555
                                                        /* cope if bin boundaries appear identical */
 
556
                                                        binfrac = 0.5;
 
557
                                                }
 
558
                                                else if (val <= low)
 
559
                                                        binfrac = 0.0;
 
560
                                                else if (val >= high)
 
561
                                                        binfrac = 1.0;
 
562
                                                else
 
563
                                                {
 
564
                                                        binfrac = (val - low) / (high - low);
 
565
 
 
566
                                                        /*
 
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.
 
571
                                                         */
 
572
                                                        if (isnan(binfrac) ||
 
573
                                                                binfrac < 0.0 || binfrac > 1.0)
 
574
                                                                binfrac = 0.5;
 
575
                                                }
 
576
                                        }
 
577
                                        else
 
578
                                        {
 
579
                                                /*
 
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
 
586
                                                 * that can be fixed.
 
587
                                                 */
 
588
                                                binfrac = 0.5;
 
589
                                        }
 
590
 
 
591
                                        /*
 
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
 
595
                                         * constant.
 
596
                                         */
 
597
                                        histfrac = (double) (i - 1) + binfrac;
 
598
                                        histfrac /= (double) (nvalues - 1);
 
599
                                }
 
600
                        }
 
601
 
 
602
                        /*
 
603
                         * Now histfrac = fraction of histogram entries below the
 
604
                         * constant.
 
605
                         *
 
606
                         * Account for "<" vs ">"
 
607
                         */
 
608
                        hist_selec = isgt ? (1.0 - histfrac) : histfrac;
 
609
 
 
610
                        /*
 
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.
 
614
                         */
 
615
                        if (hist_selec < 0.0001)
 
616
                                hist_selec = 0.0001;
 
617
                        else if (hist_selec > 0.9999)
 
618
                                hist_selec = 0.9999;
 
619
                }
 
620
 
 
621
                free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
 
622
        }
 
623
 
 
624
        /*
 
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.
 
628
         */
 
629
        selec = 1.0 - stats->stanullfrac - sumcommon;
 
630
 
 
631
        if (hist_selec > 0.0)
 
632
                selec *= hist_selec;
 
633
        else
 
634
        {
 
635
                /*
 
636
                 * If no histogram but there are values not accounted for by MCV,
 
637
                 * arbitrarily assume half of them will match.
 
638
                 */
 
639
                selec *= 0.5;
 
640
        }
 
641
 
 
642
        selec += mcv_selec;
 
643
 
 
644
        /* result should be in range, but make sure... */
 
645
        CLAMP_PROBABILITY(selec);
 
646
 
 
647
        return selec;
 
648
}
 
649
 
 
650
/*
 
651
 *              scalarltsel             - Selectivity of "<" (also "<=") for scalars.
 
652
 */
 
653
Datum
 
654
scalarltsel(PG_FUNCTION_ARGS)
 
655
{
 
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;
 
661
        Node       *other;
 
662
        bool            varonleft;
 
663
        Datum           constval;
 
664
        Oid                     consttype;
 
665
        bool            isgt;
 
666
        double          selec;
 
667
 
 
668
        /*
 
669
         * If expression is not variable op something or something op
 
670
         * variable, then punt and return a default estimate.
 
671
         */
 
672
        if (!get_restriction_variable(root, args, varRelid,
 
673
                                                                  &vardata, &other, &varonleft))
 
674
                PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
 
675
 
 
676
        /*
 
677
         * Can't do anything useful if the something is not a constant,
 
678
         * either.
 
679
         */
 
680
        if (!IsA(other, Const))
 
681
        {
 
682
                ReleaseVariableStats(vardata);
 
683
                PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
 
684
        }
 
685
 
 
686
        /*
 
687
         * If the constant is NULL, assume operator is strict and return zero,
 
688
         * ie, operator will never return TRUE.
 
689
         */
 
690
        if (((Const *) other)->constisnull)
 
691
        {
 
692
                ReleaseVariableStats(vardata);
 
693
                PG_RETURN_FLOAT8(0.0);
 
694
        }
 
695
        constval = ((Const *) other)->constvalue;
 
696
        consttype = ((Const *) other)->consttype;
 
697
 
 
698
        /*
 
699
         * Force the var to be on the left to simplify logic in scalarineqsel.
 
700
         */
 
701
        if (varonleft)
 
702
        {
 
703
                /* we have var < other */
 
704
                isgt = false;
 
705
        }
 
706
        else
 
707
        {
 
708
                /* we have other < var, commute to make var > other */
 
709
                operator = get_commutator(operator);
 
710
                if (!operator)
 
711
                {
 
712
                        /* Use default selectivity (should we raise an error instead?) */
 
713
                        ReleaseVariableStats(vardata);
 
714
                        PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
 
715
                }
 
716
                isgt = true;
 
717
        }
 
718
 
 
719
        selec = scalarineqsel(root, operator, isgt, &vardata, constval, consttype);
 
720
 
 
721
        ReleaseVariableStats(vardata);
 
722
 
 
723
        PG_RETURN_FLOAT8((float8) selec);
 
724
}
 
725
 
 
726
/*
 
727
 *              scalargtsel             - Selectivity of ">" (also ">=") for integers.
 
728
 */
 
729
Datum
 
730
scalargtsel(PG_FUNCTION_ARGS)
 
731
{
 
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;
 
737
        Node       *other;
 
738
        bool            varonleft;
 
739
        Datum           constval;
 
740
        Oid                     consttype;
 
741
        bool            isgt;
 
742
        double          selec;
 
743
 
 
744
        /*
 
745
         * If expression is not variable op something or something op
 
746
         * variable, then punt and return a default estimate.
 
747
         */
 
748
        if (!get_restriction_variable(root, args, varRelid,
 
749
                                                                  &vardata, &other, &varonleft))
 
750
                PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
 
751
 
 
752
        /*
 
753
         * Can't do anything useful if the something is not a constant,
 
754
         * either.
 
755
         */
 
756
        if (!IsA(other, Const))
 
757
        {
 
758
                ReleaseVariableStats(vardata);
 
759
                PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
 
760
        }
 
761
 
 
762
        /*
 
763
         * If the constant is NULL, assume operator is strict and return zero,
 
764
         * ie, operator will never return TRUE.
 
765
         */
 
766
        if (((Const *) other)->constisnull)
 
767
        {
 
768
                ReleaseVariableStats(vardata);
 
769
                PG_RETURN_FLOAT8(0.0);
 
770
        }
 
771
        constval = ((Const *) other)->constvalue;
 
772
        consttype = ((Const *) other)->consttype;
 
773
 
 
774
        /*
 
775
         * Force the var to be on the left to simplify logic in scalarineqsel.
 
776
         */
 
777
        if (varonleft)
 
778
        {
 
779
                /* we have var > other */
 
780
                isgt = true;
 
781
        }
 
782
        else
 
783
        {
 
784
                /* we have other > var, commute to make var < other */
 
785
                operator = get_commutator(operator);
 
786
                if (!operator)
 
787
                {
 
788
                        /* Use default selectivity (should we raise an error instead?) */
 
789
                        ReleaseVariableStats(vardata);
 
790
                        PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
 
791
                }
 
792
                isgt = false;
 
793
        }
 
794
 
 
795
        selec = scalarineqsel(root, operator, isgt, &vardata, constval, consttype);
 
796
 
 
797
        ReleaseVariableStats(vardata);
 
798
 
 
799
        PG_RETURN_FLOAT8((float8) selec);
 
800
}
 
801
 
 
802
/*
 
803
 * patternsel                   - Generic code for pattern-match selectivity.
 
804
 */
 
805
static double
 
806
patternsel(PG_FUNCTION_ARGS, Pattern_Type ptype)
 
807
{
 
808
        Query      *root = (Query *) PG_GETARG_POINTER(0);
 
809
 
 
810
#ifdef NOT_USED
 
811
        Oid                     operator = PG_GETARG_OID(1);
 
812
#endif
 
813
        List       *args = (List *) PG_GETARG_POINTER(2);
 
814
        int                     varRelid = PG_GETARG_INT32(3);
 
815
        VariableStatData vardata;
 
816
        Node       *other;
 
817
        bool            varonleft;
 
818
        Datum           constval;
 
819
        Oid                     consttype;
 
820
        Oid                     vartype;
 
821
        Oid                     opclass;
 
822
        Pattern_Prefix_Status pstatus;
 
823
        Const      *patt = NULL;
 
824
        Const      *prefix = NULL;
 
825
        Const      *rest = NULL;
 
826
        double          result;
 
827
 
 
828
        /*
 
829
         * If expression is not variable op constant, then punt and return a
 
830
         * default estimate.
 
831
         */
 
832
        if (!get_restriction_variable(root, args, varRelid,
 
833
                                                                  &vardata, &other, &varonleft))
 
834
                return DEFAULT_MATCH_SEL;
 
835
        if (!varonleft || !IsA(other, Const))
 
836
        {
 
837
                ReleaseVariableStats(vardata);
 
838
                return DEFAULT_MATCH_SEL;
 
839
        }
 
840
 
 
841
        /*
 
842
         * If the constant is NULL, assume operator is strict and return zero,
 
843
         * ie, operator will never return TRUE.
 
844
         */
 
845
        if (((Const *) other)->constisnull)
 
846
        {
 
847
                ReleaseVariableStats(vardata);
 
848
                return 0.0;
 
849
        }
 
850
        constval = ((Const *) other)->constvalue;
 
851
        consttype = ((Const *) other)->consttype;
 
852
 
 
853
        /*
 
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.
 
858
         */
 
859
        if (consttype != TEXTOID && consttype != BYTEAOID)
 
860
        {
 
861
                ReleaseVariableStats(vardata);
 
862
                return DEFAULT_MATCH_SEL;
 
863
        }
 
864
 
 
865
        /*
 
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.
 
870
         *
 
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.
 
875
         */
 
876
        vartype = vardata.vartype;
 
877
 
 
878
        switch (vartype)
 
879
        {
 
880
                case TEXTOID:
 
881
                        opclass = TEXT_BTREE_OPS_OID;
 
882
                        break;
 
883
                case VARCHAROID:
 
884
                        opclass = VARCHAR_BTREE_OPS_OID;
 
885
                        break;
 
886
                case BPCHAROID:
 
887
                        opclass = BPCHAR_BTREE_OPS_OID;
 
888
                        break;
 
889
                case NAMEOID:
 
890
                        opclass = NAME_BTREE_OPS_OID;
 
891
                        break;
 
892
                case BYTEAOID:
 
893
                        opclass = BYTEA_BTREE_OPS_OID;
 
894
                        break;
 
895
                default:
 
896
                        ReleaseVariableStats(vardata);
 
897
                        return DEFAULT_MATCH_SEL;
 
898
        }
 
899
 
 
900
        /* divide pattern into fixed prefix and remainder */
 
901
        patt = (Const *) other;
 
902
        pstatus = pattern_fixed_prefix(patt, ptype, &prefix, &rest);
 
903
 
 
904
        /*
 
905
         * If necessary, coerce the prefix constant to the right type. (The
 
906
         * "rest" constant need not be changed.)
 
907
         */
 
908
        if (prefix && prefix->consttype != vartype)
 
909
        {
 
910
                char       *prefixstr;
 
911
 
 
912
                switch (prefix->consttype)
 
913
                {
 
914
                        case TEXTOID:
 
915
                                prefixstr = DatumGetCString(DirectFunctionCall1(textout,
 
916
                                                                                                        prefix->constvalue));
 
917
                                break;
 
918
                        case BYTEAOID:
 
919
                                prefixstr = DatumGetCString(DirectFunctionCall1(byteaout,
 
920
                                                                                                        prefix->constvalue));
 
921
                                break;
 
922
                        default:
 
923
                                elog(ERROR, "unrecognized consttype: %u",
 
924
                                         prefix->consttype);
 
925
                                ReleaseVariableStats(vardata);
 
926
                                return DEFAULT_MATCH_SEL;
 
927
                }
 
928
                prefix = string_to_const(prefixstr, vartype);
 
929
                pfree(prefixstr);
 
930
        }
 
931
 
 
932
        if (pstatus == Pattern_Prefix_Exact)
 
933
        {
 
934
                /*
 
935
                 * Pattern specifies an exact match, so pretend operator is '='
 
936
                 */
 
937
                Oid                     eqopr = get_opclass_member(opclass, InvalidOid,
 
938
                                                                                           BTEqualStrategyNumber);
 
939
                List       *eqargs;
 
940
 
 
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)));
 
949
        }
 
950
        else
 
951
        {
 
952
                /*
 
953
                 * Not exact-match pattern.  We estimate selectivity of the fixed
 
954
                 * prefix and remainder of pattern separately, then combine the
 
955
                 * two.
 
956
                 */
 
957
                Selectivity prefixsel;
 
958
                Selectivity restsel;
 
959
                Selectivity selec;
 
960
 
 
961
                if (pstatus == Pattern_Prefix_Partial)
 
962
                        prefixsel = prefix_selectivity(root, &vardata, opclass, prefix);
 
963
                else
 
964
                        prefixsel = 1.0;
 
965
                restsel = pattern_selectivity(rest, ptype);
 
966
                selec = prefixsel * restsel;
 
967
                /* result should be in range, but make sure... */
 
968
                CLAMP_PROBABILITY(selec);
 
969
                result = selec;
 
970
        }
 
971
 
 
972
        if (prefix)
 
973
        {
 
974
                pfree(DatumGetPointer(prefix->constvalue));
 
975
                pfree(prefix);
 
976
        }
 
977
 
 
978
        ReleaseVariableStats(vardata);
 
979
 
 
980
        return result;
 
981
}
 
982
 
 
983
/*
 
984
 *              regexeqsel              - Selectivity of regular-expression pattern match.
 
985
 */
 
986
Datum
 
987
regexeqsel(PG_FUNCTION_ARGS)
 
988
{
 
989
        PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex));
 
990
}
 
991
 
 
992
/*
 
993
 *              icregexeqsel    - Selectivity of case-insensitive regex match.
 
994
 */
 
995
Datum
 
996
icregexeqsel(PG_FUNCTION_ARGS)
 
997
{
 
998
        PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Regex_IC));
 
999
}
 
1000
 
 
1001
/*
 
1002
 *              likesel                 - Selectivity of LIKE pattern match.
 
1003
 */
 
1004
Datum
 
1005
likesel(PG_FUNCTION_ARGS)
 
1006
{
 
1007
        PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like));
 
1008
}
 
1009
 
 
1010
/*
 
1011
 *              iclikesel                       - Selectivity of ILIKE pattern match.
 
1012
 */
 
1013
Datum
 
1014
iclikesel(PG_FUNCTION_ARGS)
 
1015
{
 
1016
        PG_RETURN_FLOAT8(patternsel(fcinfo, Pattern_Type_Like_IC));
 
1017
}
 
1018
 
 
1019
/*
 
1020
 *              regexnesel              - Selectivity of regular-expression pattern non-match.
 
1021
 */
 
1022
Datum
 
1023
regexnesel(PG_FUNCTION_ARGS)
 
1024
{
 
1025
        double          result;
 
1026
 
 
1027
        result = patternsel(fcinfo, Pattern_Type_Regex);
 
1028
        result = 1.0 - result;
 
1029
        PG_RETURN_FLOAT8(result);
 
1030
}
 
1031
 
 
1032
/*
 
1033
 *              icregexnesel    - Selectivity of case-insensitive regex non-match.
 
1034
 */
 
1035
Datum
 
1036
icregexnesel(PG_FUNCTION_ARGS)
 
1037
{
 
1038
        double          result;
 
1039
 
 
1040
        result = patternsel(fcinfo, Pattern_Type_Regex_IC);
 
1041
        result = 1.0 - result;
 
1042
        PG_RETURN_FLOAT8(result);
 
1043
}
 
1044
 
 
1045
/*
 
1046
 *              nlikesel                - Selectivity of LIKE pattern non-match.
 
1047
 */
 
1048
Datum
 
1049
nlikesel(PG_FUNCTION_ARGS)
 
1050
{
 
1051
        double          result;
 
1052
 
 
1053
        result = patternsel(fcinfo, Pattern_Type_Like);
 
1054
        result = 1.0 - result;
 
1055
        PG_RETURN_FLOAT8(result);
 
1056
}
 
1057
 
 
1058
/*
 
1059
 *              icnlikesel              - Selectivity of ILIKE pattern non-match.
 
1060
 */
 
1061
Datum
 
1062
icnlikesel(PG_FUNCTION_ARGS)
 
1063
{
 
1064
        double          result;
 
1065
 
 
1066
        result = patternsel(fcinfo, Pattern_Type_Like_IC);
 
1067
        result = 1.0 - result;
 
1068
        PG_RETURN_FLOAT8(result);
 
1069
}
 
1070
 
 
1071
/*
 
1072
 *              booltestsel             - Selectivity of BooleanTest Node.
 
1073
 */
 
1074
Selectivity
 
1075
booltestsel(Query *root, BoolTestType booltesttype, Node *arg,
 
1076
                        int varRelid, JoinType jointype)
 
1077
{
 
1078
        VariableStatData vardata;
 
1079
        double          selec;
 
1080
 
 
1081
        examine_variable(root, arg, varRelid, &vardata);
 
1082
 
 
1083
        if (HeapTupleIsValid(vardata.statsTuple))
 
1084
        {
 
1085
                Form_pg_statistic stats;
 
1086
                double          freq_null;
 
1087
                Datum      *values;
 
1088
                int                     nvalues;
 
1089
                float4     *numbers;
 
1090
                int                     nnumbers;
 
1091
 
 
1092
                stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
 
1093
                freq_null = stats->stanullfrac;
 
1094
 
 
1095
                if (get_attstatsslot(vardata.statsTuple,
 
1096
                                                         vardata.atttype, vardata.atttypmod,
 
1097
                                                         STATISTIC_KIND_MCV, InvalidOid,
 
1098
                                                         &values, &nvalues,
 
1099
                                                         &numbers, &nnumbers)
 
1100
                        && nnumbers > 0)
 
1101
                {
 
1102
                        double          freq_true;
 
1103
                        double          freq_false;
 
1104
 
 
1105
                        /*
 
1106
                         * Get first MCV frequency and derive frequency for true.
 
1107
                         */
 
1108
                        if (DatumGetBool(values[0]))
 
1109
                                freq_true = numbers[0];
 
1110
                        else
 
1111
                                freq_true = 1.0 - numbers[0] - freq_null;
 
1112
 
 
1113
                        /*
 
1114
                         * Next derive frequency for false. Then use these as
 
1115
                         * appropriate to derive frequency for each case.
 
1116
                         */
 
1117
                        freq_false = 1.0 - freq_true - freq_null;
 
1118
 
 
1119
                        switch (booltesttype)
 
1120
                        {
 
1121
                                case IS_UNKNOWN:
 
1122
                                        /* select only NULL values */
 
1123
                                        selec = freq_null;
 
1124
                                        break;
 
1125
                                case IS_NOT_UNKNOWN:
 
1126
                                        /* select non-NULL values */
 
1127
                                        selec = 1.0 - freq_null;
 
1128
                                        break;
 
1129
                                case IS_TRUE:
 
1130
                                        /* select only TRUE values */
 
1131
                                        selec = freq_true;
 
1132
                                        break;
 
1133
                                case IS_NOT_TRUE:
 
1134
                                        /* select non-TRUE values */
 
1135
                                        selec = 1.0 - freq_true;
 
1136
                                        break;
 
1137
                                case IS_FALSE:
 
1138
                                        /* select only FALSE values */
 
1139
                                        selec = freq_false;
 
1140
                                        break;
 
1141
                                case IS_NOT_FALSE:
 
1142
                                        /* select non-FALSE values */
 
1143
                                        selec = 1.0 - freq_false;
 
1144
                                        break;
 
1145
                                default:
 
1146
                                        elog(ERROR, "unrecognized booltesttype: %d",
 
1147
                                                 (int) booltesttype);
 
1148
                                        selec = 0.0;    /* Keep compiler quiet */
 
1149
                                        break;
 
1150
                        }
 
1151
 
 
1152
                        free_attstatsslot(vardata.atttype, values, nvalues,
 
1153
                                                          numbers, nnumbers);
 
1154
                }
 
1155
                else
 
1156
                {
 
1157
                        /*
 
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.
 
1162
                         */
 
1163
                        switch (booltesttype)
 
1164
                        {
 
1165
                                case IS_UNKNOWN:
 
1166
 
 
1167
                                        /*
 
1168
                                         * Use freq_null directly.
 
1169
                                         */
 
1170
                                        selec = freq_null;
 
1171
                                        break;
 
1172
                                case IS_NOT_UNKNOWN:
 
1173
 
 
1174
                                        /*
 
1175
                                         * Select not unknown (not null) values. Calculate
 
1176
                                         * from freq_null.
 
1177
                                         */
 
1178
                                        selec = 1.0 - freq_null;
 
1179
                                        break;
 
1180
                                case IS_TRUE:
 
1181
                                case IS_NOT_TRUE:
 
1182
                                case IS_FALSE:
 
1183
                                case IS_NOT_FALSE:
 
1184
                                        selec = (1.0 - freq_null) / 2.0;
 
1185
                                        break;
 
1186
                                default:
 
1187
                                        elog(ERROR, "unrecognized booltesttype: %d",
 
1188
                                                 (int) booltesttype);
 
1189
                                        selec = 0.0;    /* Keep compiler quiet */
 
1190
                                        break;
 
1191
                        }
 
1192
                }
 
1193
        }
 
1194
        else
 
1195
        {
 
1196
                /*
 
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.
 
1201
                 */
 
1202
                switch (booltesttype)
 
1203
                {
 
1204
                        case IS_UNKNOWN:
 
1205
                                selec = DEFAULT_UNK_SEL;
 
1206
                                break;
 
1207
                        case IS_NOT_UNKNOWN:
 
1208
                                selec = DEFAULT_NOT_UNK_SEL;
 
1209
                                break;
 
1210
                        case IS_TRUE:
 
1211
                        case IS_NOT_FALSE:
 
1212
                                selec = (double) clause_selectivity(root, arg,
 
1213
                                                                                                        varRelid, jointype);
 
1214
                                break;
 
1215
                        case IS_FALSE:
 
1216
                        case IS_NOT_TRUE:
 
1217
                                selec = 1.0 - (double) clause_selectivity(root, arg,
 
1218
                                                                                                         varRelid, jointype);
 
1219
                                break;
 
1220
                        default:
 
1221
                                elog(ERROR, "unrecognized booltesttype: %d",
 
1222
                                         (int) booltesttype);
 
1223
                                selec = 0.0;    /* Keep compiler quiet */
 
1224
                                break;
 
1225
                }
 
1226
        }
 
1227
 
 
1228
        ReleaseVariableStats(vardata);
 
1229
 
 
1230
        /* result should be in range, but make sure... */
 
1231
        CLAMP_PROBABILITY(selec);
 
1232
 
 
1233
        return (Selectivity) selec;
 
1234
}
 
1235
 
 
1236
/*
 
1237
 *              nulltestsel             - Selectivity of NullTest Node.
 
1238
 */
 
1239
Selectivity
 
1240
nulltestsel(Query *root, NullTestType nulltesttype, Node *arg, int varRelid)
 
1241
{
 
1242
        VariableStatData vardata;
 
1243
        double          selec;
 
1244
 
 
1245
        examine_variable(root, arg, varRelid, &vardata);
 
1246
 
 
1247
        if (HeapTupleIsValid(vardata.statsTuple))
 
1248
        {
 
1249
                Form_pg_statistic stats;
 
1250
                double          freq_null;
 
1251
 
 
1252
                stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
 
1253
                freq_null = stats->stanullfrac;
 
1254
 
 
1255
                switch (nulltesttype)
 
1256
                {
 
1257
                        case IS_NULL:
 
1258
 
 
1259
                                /*
 
1260
                                 * Use freq_null directly.
 
1261
                                 */
 
1262
                                selec = freq_null;
 
1263
                                break;
 
1264
                        case IS_NOT_NULL:
 
1265
 
 
1266
                                /*
 
1267
                                 * Select not unknown (not null) values. Calculate from
 
1268
                                 * freq_null.
 
1269
                                 */
 
1270
                                selec = 1.0 - freq_null;
 
1271
                                break;
 
1272
                        default:
 
1273
                                elog(ERROR, "unrecognized nulltesttype: %d",
 
1274
                                         (int) nulltesttype);
 
1275
                                return (Selectivity) 0; /* keep compiler quiet */
 
1276
                }
 
1277
        }
 
1278
        else
 
1279
        {
 
1280
                /*
 
1281
                 * No VACUUM ANALYZE stats available, so make a guess
 
1282
                 */
 
1283
                switch (nulltesttype)
 
1284
                {
 
1285
                        case IS_NULL:
 
1286
                                selec = DEFAULT_UNK_SEL;
 
1287
                                break;
 
1288
                        case IS_NOT_NULL:
 
1289
                                selec = DEFAULT_NOT_UNK_SEL;
 
1290
                                break;
 
1291
                        default:
 
1292
                                elog(ERROR, "unrecognized nulltesttype: %d",
 
1293
                                         (int) nulltesttype);
 
1294
                                return (Selectivity) 0; /* keep compiler quiet */
 
1295
                }
 
1296
        }
 
1297
 
 
1298
        ReleaseVariableStats(vardata);
 
1299
 
 
1300
        /* result should be in range, but make sure... */
 
1301
        CLAMP_PROBABILITY(selec);
 
1302
 
 
1303
        return (Selectivity) selec;
 
1304
}
 
1305
 
 
1306
/*
 
1307
 *              eqjoinsel               - Join selectivity of "="
 
1308
 */
 
1309
Datum
 
1310
eqjoinsel(PG_FUNCTION_ARGS)
 
1311
{
 
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);
 
1316
        double          selec;
 
1317
        VariableStatData vardata1;
 
1318
        VariableStatData vardata2;
 
1319
        double          nd1;
 
1320
        double          nd2;
 
1321
        Form_pg_statistic stats1 = NULL;
 
1322
        Form_pg_statistic stats2 = NULL;
 
1323
        bool            have_mcvs1 = false;
 
1324
        Datum      *values1 = NULL;
 
1325
        int                     nvalues1 = 0;
 
1326
        float4     *numbers1 = NULL;
 
1327
        int                     nnumbers1 = 0;
 
1328
        bool            have_mcvs2 = false;
 
1329
        Datum      *values2 = NULL;
 
1330
        int                     nvalues2 = 0;
 
1331
        float4     *numbers2 = NULL;
 
1332
        int                     nnumbers2 = 0;
 
1333
 
 
1334
        get_join_variables(root, args, &vardata1, &vardata2);
 
1335
 
 
1336
        nd1 = get_variable_numdistinct(&vardata1);
 
1337
        nd2 = get_variable_numdistinct(&vardata2);
 
1338
 
 
1339
        if (HeapTupleIsValid(vardata1.statsTuple))
 
1340
        {
 
1341
                stats1 = (Form_pg_statistic) GETSTRUCT(vardata1.statsTuple);
 
1342
                have_mcvs1 = get_attstatsslot(vardata1.statsTuple,
 
1343
                                                                          vardata1.atttype,
 
1344
                                                                          vardata1.atttypmod,
 
1345
                                                                          STATISTIC_KIND_MCV,
 
1346
                                                                          InvalidOid,
 
1347
                                                                          &values1, &nvalues1,
 
1348
                                                                          &numbers1, &nnumbers1);
 
1349
        }
 
1350
 
 
1351
        if (HeapTupleIsValid(vardata2.statsTuple))
 
1352
        {
 
1353
                stats2 = (Form_pg_statistic) GETSTRUCT(vardata2.statsTuple);
 
1354
                have_mcvs2 = get_attstatsslot(vardata2.statsTuple,
 
1355
                                                                          vardata2.atttype,
 
1356
                                                                          vardata2.atttypmod,
 
1357
                                                                          STATISTIC_KIND_MCV,
 
1358
                                                                          InvalidOid,
 
1359
                                                                          &values2, &nvalues2,
 
1360
                                                                          &numbers2, &nnumbers2);
 
1361
        }
 
1362
 
 
1363
        if (have_mcvs1 && have_mcvs2)
 
1364
        {
 
1365
                /*
 
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).
 
1377
                 */
 
1378
                FmgrInfo        eqproc;
 
1379
                bool       *hasmatch1;
 
1380
                bool       *hasmatch2;
 
1381
                double          nullfrac1 = stats1->stanullfrac;
 
1382
                double          nullfrac2 = stats2->stanullfrac;
 
1383
                double          matchprodfreq,
 
1384
                                        matchfreq1,
 
1385
                                        matchfreq2,
 
1386
                                        unmatchfreq1,
 
1387
                                        unmatchfreq2,
 
1388
                                        otherfreq1,
 
1389
                                        otherfreq2,
 
1390
                                        totalsel1,
 
1391
                                        totalsel2;
 
1392
                int                     i,
 
1393
                                        nmatches;
 
1394
 
 
1395
                fmgr_info(get_opcode(operator), &eqproc);
 
1396
                hasmatch1 = (bool *) palloc0(nvalues1 * sizeof(bool));
 
1397
                hasmatch2 = (bool *) palloc0(nvalues2 * sizeof(bool));
 
1398
 
 
1399
                /*
 
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
 
1402
                 * DISTINCT'd).
 
1403
                 *
 
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.
 
1409
                 *
 
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.
 
1414
                 */
 
1415
                if (jointype == JOIN_IN ||
 
1416
                        jointype == JOIN_REVERSE_IN ||
 
1417
                        jointype == JOIN_UNIQUE_INNER ||
 
1418
                        jointype == JOIN_UNIQUE_OUTER)
 
1419
                {
 
1420
                        float4          oneovern = 1.0 / nd2;
 
1421
 
 
1422
                        for (i = 0; i < nvalues2; i++)
 
1423
                                numbers2[i] = oneovern;
 
1424
                        nullfrac2 = oneovern;
 
1425
                }
 
1426
 
 
1427
                /*
 
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...
 
1432
                 */
 
1433
                matchprodfreq = 0.0;
 
1434
                nmatches = 0;
 
1435
                for (i = 0; i < nvalues1; i++)
 
1436
                {
 
1437
                        int                     j;
 
1438
 
 
1439
                        for (j = 0; j < nvalues2; j++)
 
1440
                        {
 
1441
                                if (hasmatch2[j])
 
1442
                                        continue;
 
1443
                                if (DatumGetBool(FunctionCall2(&eqproc,
 
1444
                                                                                           values1[i],
 
1445
                                                                                           values2[j])))
 
1446
                                {
 
1447
                                        hasmatch1[i] = hasmatch2[j] = true;
 
1448
                                        matchprodfreq += numbers1[i] * numbers2[j];
 
1449
                                        nmatches++;
 
1450
                                        break;
 
1451
                                }
 
1452
                        }
 
1453
                }
 
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++)
 
1458
                {
 
1459
                        if (hasmatch1[i])
 
1460
                                matchfreq1 += numbers1[i];
 
1461
                        else
 
1462
                                unmatchfreq1 += numbers1[i];
 
1463
                }
 
1464
                CLAMP_PROBABILITY(matchfreq1);
 
1465
                CLAMP_PROBABILITY(unmatchfreq1);
 
1466
                matchfreq2 = unmatchfreq2 = 0.0;
 
1467
                for (i = 0; i < nvalues2; i++)
 
1468
                {
 
1469
                        if (hasmatch2[i])
 
1470
                                matchfreq2 += numbers2[i];
 
1471
                        else
 
1472
                                unmatchfreq2 += numbers2[i];
 
1473
                }
 
1474
                CLAMP_PROBABILITY(matchfreq2);
 
1475
                CLAMP_PROBABILITY(unmatchfreq2);
 
1476
                pfree(hasmatch1);
 
1477
                pfree(hasmatch2);
 
1478
 
 
1479
                /*
 
1480
                 * Compute total frequency of non-null values that are not in the
 
1481
                 * MCV lists.
 
1482
                 */
 
1483
                otherfreq1 = 1.0 - nullfrac1 - matchfreq1 - unmatchfreq1;
 
1484
                otherfreq2 = 1.0 - nullfrac2 - matchfreq2 - unmatchfreq2;
 
1485
                CLAMP_PROBABILITY(otherfreq1);
 
1486
                CLAMP_PROBABILITY(otherfreq2);
 
1487
 
 
1488
                /*
 
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.
 
1495
                 */
 
1496
                totalsel1 = matchprodfreq;
 
1497
                if (nd2 > nvalues2)
 
1498
                        totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - nvalues2);
 
1499
                if (nd2 > nmatches)
 
1500
                        totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
 
1501
                                (nd2 - nmatches);
 
1502
                /* Same estimate from the point of view of relation 2. */
 
1503
                totalsel2 = matchprodfreq;
 
1504
                if (nd1 > nvalues1)
 
1505
                        totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - nvalues1);
 
1506
                if (nd1 > nmatches)
 
1507
                        totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
 
1508
                                (nd1 - nmatches);
 
1509
 
 
1510
                /*
 
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.
 
1515
                 */
 
1516
                selec = (totalsel1 < totalsel2) ? totalsel1 : totalsel2;
 
1517
        }
 
1518
        else
 
1519
        {
 
1520
                /*
 
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.
 
1536
                 *
 
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.
 
1540
                 */
 
1541
                double          nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
 
1542
                double          nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
 
1543
 
 
1544
                selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
 
1545
                if (nd1 > nd2)
 
1546
                        selec /= nd1;
 
1547
                else
 
1548
                        selec /= nd2;
 
1549
        }
 
1550
 
 
1551
        if (have_mcvs1)
 
1552
                free_attstatsslot(vardata1.atttype, values1, nvalues1,
 
1553
                                                  numbers1, nnumbers1);
 
1554
        if (have_mcvs2)
 
1555
                free_attstatsslot(vardata2.atttype, values2, nvalues2,
 
1556
                                                  numbers2, nnumbers2);
 
1557
 
 
1558
        ReleaseVariableStats(vardata1);
 
1559
        ReleaseVariableStats(vardata2);
 
1560
 
 
1561
        CLAMP_PROBABILITY(selec);
 
1562
 
 
1563
        PG_RETURN_FLOAT8((float8) selec);
 
1564
}
 
1565
 
 
1566
/*
 
1567
 *              neqjoinsel              - Join selectivity of "!="
 
1568
 */
 
1569
Datum
 
1570
neqjoinsel(PG_FUNCTION_ARGS)
 
1571
{
 
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);
 
1576
        Oid                     eqop;
 
1577
        float8          result;
 
1578
 
 
1579
        /*
 
1580
         * We want 1 - eqjoinsel() where the equality operator is the one
 
1581
         * associated with this != operator, that is, its negator.
 
1582
         */
 
1583
        eqop = get_negator(operator);
 
1584
        if (eqop)
 
1585
        {
 
1586
                result = DatumGetFloat8(DirectFunctionCall4(eqjoinsel,
 
1587
                                                                                                        PointerGetDatum(root),
 
1588
                                                                                                  ObjectIdGetDatum(eqop),
 
1589
                                                                                                        PointerGetDatum(args),
 
1590
                                                                                           Int16GetDatum(jointype)));
 
1591
        }
 
1592
        else
 
1593
        {
 
1594
                /* Use default selectivity (should we raise an error instead?) */
 
1595
                result = DEFAULT_EQ_SEL;
 
1596
        }
 
1597
        result = 1.0 - result;
 
1598
        PG_RETURN_FLOAT8(result);
 
1599
}
 
1600
 
 
1601
/*
 
1602
 *              scalarltjoinsel - Join selectivity of "<" and "<=" for scalars
 
1603
 */
 
1604
Datum
 
1605
scalarltjoinsel(PG_FUNCTION_ARGS)
 
1606
{
 
1607
        PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
 
1608
}
 
1609
 
 
1610
/*
 
1611
 *              scalargtjoinsel - Join selectivity of ">" and ">=" for scalars
 
1612
 */
 
1613
Datum
 
1614
scalargtjoinsel(PG_FUNCTION_ARGS)
 
1615
{
 
1616
        PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
 
1617
}
 
1618
 
 
1619
/*
 
1620
 *              regexeqjoinsel  - Join selectivity of regular-expression pattern match.
 
1621
 */
 
1622
Datum
 
1623
regexeqjoinsel(PG_FUNCTION_ARGS)
 
1624
{
 
1625
        PG_RETURN_FLOAT8(DEFAULT_MATCH_SEL);
 
1626
}
 
1627
 
 
1628
/*
 
1629
 *              icregexeqjoinsel        - Join selectivity of case-insensitive regex match.
 
1630
 */
 
1631
Datum
 
1632
icregexeqjoinsel(PG_FUNCTION_ARGS)
 
1633
{
 
1634
        PG_RETURN_FLOAT8(DEFAULT_MATCH_SEL);
 
1635
}
 
1636
 
 
1637
/*
 
1638
 *              likejoinsel                     - Join selectivity of LIKE pattern match.
 
1639
 */
 
1640
Datum
 
1641
likejoinsel(PG_FUNCTION_ARGS)
 
1642
{
 
1643
        PG_RETURN_FLOAT8(DEFAULT_MATCH_SEL);
 
1644
}
 
1645
 
 
1646
/*
 
1647
 *              iclikejoinsel                   - Join selectivity of ILIKE pattern match.
 
1648
 */
 
1649
Datum
 
1650
iclikejoinsel(PG_FUNCTION_ARGS)
 
1651
{
 
1652
        PG_RETURN_FLOAT8(DEFAULT_MATCH_SEL);
 
1653
}
 
1654
 
 
1655
/*
 
1656
 *              regexnejoinsel  - Join selectivity of regex non-match.
 
1657
 */
 
1658
Datum
 
1659
regexnejoinsel(PG_FUNCTION_ARGS)
 
1660
{
 
1661
        float8          result;
 
1662
 
 
1663
        result = DatumGetFloat8(regexeqjoinsel(fcinfo));
 
1664
        result = 1.0 - result;
 
1665
        PG_RETURN_FLOAT8(result);
 
1666
}
 
1667
 
 
1668
/*
 
1669
 *              icregexnejoinsel        - Join selectivity of case-insensitive regex non-match.
 
1670
 */
 
1671
Datum
 
1672
icregexnejoinsel(PG_FUNCTION_ARGS)
 
1673
{
 
1674
        float8          result;
 
1675
 
 
1676
        result = DatumGetFloat8(icregexeqjoinsel(fcinfo));
 
1677
        result = 1.0 - result;
 
1678
        PG_RETURN_FLOAT8(result);
 
1679
}
 
1680
 
 
1681
/*
 
1682
 *              nlikejoinsel            - Join selectivity of LIKE pattern non-match.
 
1683
 */
 
1684
Datum
 
1685
nlikejoinsel(PG_FUNCTION_ARGS)
 
1686
{
 
1687
        float8          result;
 
1688
 
 
1689
        result = DatumGetFloat8(likejoinsel(fcinfo));
 
1690
        result = 1.0 - result;
 
1691
        PG_RETURN_FLOAT8(result);
 
1692
}
 
1693
 
 
1694
/*
 
1695
 *              icnlikejoinsel          - Join selectivity of ILIKE pattern non-match.
 
1696
 */
 
1697
Datum
 
1698
icnlikejoinsel(PG_FUNCTION_ARGS)
 
1699
{
 
1700
        float8          result;
 
1701
 
 
1702
        result = DatumGetFloat8(iclikejoinsel(fcinfo));
 
1703
        result = 1.0 - result;
 
1704
        PG_RETURN_FLOAT8(result);
 
1705
}
 
1706
 
 
1707
/*
 
1708
 * mergejoinscansel                     - Scan selectivity of merge join.
 
1709
 *
 
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.
 
1714
 *
 
1715
 * clause should be a clause already known to be mergejoinable.
 
1716
 *
 
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
 
1719
 * variable.
 
1720
 */
 
1721
void
 
1722
mergejoinscansel(Query *root, Node *clause,
 
1723
                                 Selectivity *leftscan,
 
1724
                                 Selectivity *rightscan)
 
1725
{
 
1726
        Node       *left,
 
1727
                           *right;
 
1728
        VariableStatData leftvar,
 
1729
                                rightvar;
 
1730
        Oid                     lefttype,
 
1731
                                righttype;
 
1732
        Oid                     opno,
 
1733
                                lsortop,
 
1734
                                rsortop,
 
1735
                                ltop,
 
1736
                                gtop,
 
1737
                                leop,
 
1738
                                revgtop,
 
1739
                                revleop;
 
1740
        Datum           leftmax,
 
1741
                                rightmax;
 
1742
        double          selec;
 
1743
 
 
1744
        /* Set default results if we can't figure anything out. */
 
1745
        *leftscan = *rightscan = 1.0;
 
1746
 
 
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);
 
1753
        if (!right)
 
1754
                return;                                 /* shouldn't happen */
 
1755
 
 
1756
        /* Look for stats for the inputs */
 
1757
        examine_variable(root, left, 0, &leftvar);
 
1758
        examine_variable(root, right, 0, &rightvar);
 
1759
 
 
1760
        /* Get the direct input types of the operator */
 
1761
        lefttype = exprType(left);
 
1762
        righttype = exprType(right);
 
1763
 
 
1764
        /* Verify mergejoinability and get left and right "<" operators */
 
1765
        if (!op_mergejoinable(opno,
 
1766
                                                  &lsortop,
 
1767
                                                  &rsortop))
 
1768
                goto fail;                              /* shouldn't happen */
 
1769
 
 
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 */
 
1773
 
 
1774
        if (!get_variable_maximum(root, &rightvar, rsortop, &rightmax))
 
1775
                goto fail;                              /* no max available from stats */
 
1776
 
 
1777
        /* Look up the "left < right" and "left > right" operators */
 
1778
        op_mergejoin_crossops(opno, &ltop, &gtop, NULL, NULL);
 
1779
 
 
1780
        /* Look up the "left <= right" operator */
 
1781
        leop = get_negator(gtop);
 
1782
        if (!OidIsValid(leop))
 
1783
                goto fail;                              /* insufficient info in catalogs */
 
1784
 
 
1785
        /* Look up the "right > left" operator */
 
1786
        revgtop = get_commutator(ltop);
 
1787
        if (!OidIsValid(revgtop))
 
1788
                goto fail;                              /* insufficient info in catalogs */
 
1789
 
 
1790
        /* Look up the "right <= left" operator */
 
1791
        revleop = get_negator(revgtop);
 
1792
        if (!OidIsValid(revleop))
 
1793
                goto fail;                              /* insufficient info in catalogs */
 
1794
 
 
1795
        /*
 
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.
 
1799
         */
 
1800
        selec = scalarineqsel(root, leop, false, &leftvar,
 
1801
                                                  rightmax, righttype);
 
1802
        if (selec != DEFAULT_INEQ_SEL)
 
1803
                *leftscan = selec;
 
1804
 
 
1805
        /* And similarly for the right variable. */
 
1806
        selec = scalarineqsel(root, revleop, false, &rightvar,
 
1807
                                                  leftmax, lefttype);
 
1808
        if (selec != DEFAULT_INEQ_SEL)
 
1809
                *rightscan = selec;
 
1810
 
 
1811
        /*
 
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),
 
1815
         * believe neither.
 
1816
         */
 
1817
        if (*leftscan > *rightscan)
 
1818
                *leftscan = 1.0;
 
1819
        else if (*leftscan < *rightscan)
 
1820
                *rightscan = 1.0;
 
1821
        else
 
1822
                *leftscan = *rightscan = 1.0;
 
1823
 
 
1824
fail:
 
1825
        ReleaseVariableStats(leftvar);
 
1826
        ReleaseVariableStats(rightvar);
 
1827
}
 
1828
 
 
1829
 
 
1830
/*
 
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
 
1833
 * entries.
 
1834
 */
 
1835
typedef struct
 
1836
{
 
1837
        Node       *var;                /* might be an expression, not just a Var */
 
1838
        RelOptInfo *rel;                /* relation it belongs to */
 
1839
        double          ndistinct;      /* # distinct values */
 
1840
} GroupVarInfo;
 
1841
 
 
1842
static List *
 
1843
add_unique_group_var(Query *root, List *varinfos,
 
1844
                                         Node *var, VariableStatData *vardata)
 
1845
{
 
1846
        GroupVarInfo *varinfo;
 
1847
        double          ndistinct;
 
1848
        ListCell   *lc;
 
1849
 
 
1850
        ndistinct = get_variable_numdistinct(vardata);
 
1851
 
 
1852
        /* cannot use foreach here because of possible list_delete */
 
1853
        lc = list_head(varinfos);
 
1854
        while (lc)
 
1855
        {
 
1856
                varinfo = (GroupVarInfo *) lfirst(lc);
 
1857
 
 
1858
                /* must advance lc before list_delete possibly pfree's it */
 
1859
                lc = lnext(lc);
 
1860
 
 
1861
                /* Drop exact duplicates */
 
1862
                if (equal(var, varinfo->var))
 
1863
                        return varinfos;
 
1864
 
 
1865
                /*
 
1866
                 * Drop known-equal vars, but only if they belong to different
 
1867
                 * relations (see comments for estimate_num_groups)
 
1868
                 */
 
1869
                if (vardata->rel != varinfo->rel &&
 
1870
                        exprs_known_equal(root, var, varinfo->var))
 
1871
                {
 
1872
                        if (varinfo->ndistinct <= ndistinct)
 
1873
                        {
 
1874
                                /* Keep older item, forget new one */
 
1875
                                return varinfos;
 
1876
                        }
 
1877
                        else
 
1878
                        {
 
1879
                                /* Delete the older item */
 
1880
                                varinfos = list_delete_ptr(varinfos, varinfo);
 
1881
                        }
 
1882
                }
 
1883
        }
 
1884
 
 
1885
        varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
 
1886
 
 
1887
        varinfo->var = var;
 
1888
        varinfo->rel = vardata->rel;
 
1889
        varinfo->ndistinct = ndistinct;
 
1890
        varinfos = lappend(varinfos, varinfo);
 
1891
        return varinfos;
 
1892
}
 
1893
 
 
1894
/*
 
1895
 * estimate_num_groups          - Estimate number of groups in a grouped query
 
1896
 *
 
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
 
1899
 * expressions.
 
1900
 *
 
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.)
 
1905
 *
 
1906
 * Inputs:
 
1907
 *      root - the query
 
1908
 *      groupExprs - list of expressions being grouped by
 
1909
 *      input_rows - number of rows estimated to arrive at the group/unique
 
1910
 *              filter step
 
1911
 *
 
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
 
1917
 * is as follows:
 
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
 
1952
 * do better).
 
1953
 */
 
1954
double
 
1955
estimate_num_groups(Query *root, List *groupExprs, double input_rows)
 
1956
{
 
1957
        List       *varinfos = NIL;
 
1958
        double          numdistinct;
 
1959
        ListCell   *l;
 
1960
 
 
1961
        /* We should not be called unless query has GROUP BY (or DISTINCT) */
 
1962
        Assert(groupExprs != NIL);
 
1963
 
 
1964
        /*
 
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).
 
1969
         */
 
1970
        foreach(l, groupExprs)
 
1971
        {
 
1972
                Node       *groupexpr = (Node *) lfirst(l);
 
1973
                VariableStatData vardata;
 
1974
                List       *varshere;
 
1975
                ListCell   *l2;
 
1976
 
 
1977
                /*
 
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
 
1980
                 * complicated.
 
1981
                 */
 
1982
                examine_variable(root, groupexpr, 0, &vardata);
 
1983
                if (vardata.statsTuple != NULL || vardata.isunique)
 
1984
                {
 
1985
                        varinfos = add_unique_group_var(root, varinfos,
 
1986
                                                                                        groupexpr, &vardata);
 
1987
                        ReleaseVariableStats(vardata);
 
1988
                        continue;
 
1989
                }
 
1990
                ReleaseVariableStats(vardata);
 
1991
 
 
1992
                /*
 
1993
                 * Else pull out the component Vars
 
1994
                 */
 
1995
                varshere = pull_var_clause(groupexpr, false);
 
1996
 
 
1997
                /*
 
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.
 
2002
                 */
 
2003
                if (varshere == NIL)
 
2004
                {
 
2005
                        if (contain_volatile_functions(groupexpr))
 
2006
                                return input_rows;
 
2007
                        continue;
 
2008
                }
 
2009
 
 
2010
                /*
 
2011
                 * Else add variables to varinfos list
 
2012
                 */
 
2013
                foreach(l2, varshere)
 
2014
                {
 
2015
                        Node       *var = (Node *) lfirst(l2);
 
2016
 
 
2017
                        examine_variable(root, var, 0, &vardata);
 
2018
                        varinfos = add_unique_group_var(root, varinfos, var, &vardata);
 
2019
                        ReleaseVariableStats(vardata);
 
2020
                }
 
2021
        }
 
2022
 
 
2023
        /* If now no Vars, we must have an all-constant GROUP BY list. */
 
2024
        if (varinfos == NIL)
 
2025
                return 1.0;
 
2026
 
 
2027
        /*
 
2028
         * Steps 3/4: group Vars by relation and estimate total numdistinct.
 
2029
         *
 
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.
 
2034
         */
 
2035
        numdistinct = 1.0;
 
2036
 
 
2037
        do
 
2038
        {
 
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;
 
2045
 
 
2046
                /*
 
2047
                 * Get the product of numdistinct estimates of the Vars for this rel.
 
2048
                 * Also, construct new varinfos list of remaining Vars.
 
2049
                 */
 
2050
                for_each_cell(l, lnext(list_head(varinfos)))
 
2051
                {
 
2052
                        GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
 
2053
 
 
2054
                        if (varinfo2->rel == varinfo1->rel)
 
2055
                        {
 
2056
                                reldistinct *= varinfo2->ndistinct;
 
2057
                                if (relmaxndistinct < varinfo2->ndistinct)
 
2058
                                        relmaxndistinct = varinfo2->ndistinct;
 
2059
                                relvarcount++;
 
2060
                        }
 
2061
                        else
 
2062
                        {
 
2063
                                /* not time to process varinfo2 yet */
 
2064
                                newvarinfos = lcons(varinfo2, newvarinfos);
 
2065
                        }
 
2066
                }
 
2067
 
 
2068
                /*
 
2069
                 * Sanity check --- don't divide by zero if empty relation.
 
2070
                 */
 
2071
                Assert(rel->reloptkind == RELOPT_BASEREL);
 
2072
                if (rel->tuples > 0)
 
2073
                {
 
2074
                        /*
 
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.
 
2080
                         */
 
2081
                        double          clamp = rel->tuples;
 
2082
 
 
2083
                        if (relvarcount > 1)
 
2084
                        {
 
2085
                                clamp *= 0.1;
 
2086
                                if (clamp < relmaxndistinct)
 
2087
                                {
 
2088
                                        clamp = relmaxndistinct;
 
2089
                                        /* for sanity in case some ndistinct is too large: */
 
2090
                                        if (clamp > rel->tuples)
 
2091
                                                clamp = rel->tuples;
 
2092
                                }
 
2093
                        }
 
2094
                        if (reldistinct > clamp)
 
2095
                                reldistinct = clamp;
 
2096
 
 
2097
                        /*
 
2098
                         * Multiply by restriction selectivity.
 
2099
                         */
 
2100
                        reldistinct *= rel->rows / rel->tuples;
 
2101
 
 
2102
                        /*
 
2103
                         * Update estimate of total distinct groups.
 
2104
                         */
 
2105
                        numdistinct *= reldistinct;
 
2106
                }
 
2107
 
 
2108
                varinfos = newvarinfos;
 
2109
        } while (varinfos != NIL);
 
2110
 
 
2111
        numdistinct = ceil(numdistinct);
 
2112
 
 
2113
        /* Guard against out-of-range answers */
 
2114
        if (numdistinct > input_rows)
 
2115
                numdistinct = input_rows;
 
2116
        if (numdistinct < 1.0)
 
2117
                numdistinct = 1.0;
 
2118
 
 
2119
        return numdistinct;
 
2120
}
 
2121
 
 
2122
/*
 
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
 
2125
 * as a hash key.
 
2126
 *
 
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.
 
2132
 *
 
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.
 
2146
 *
 
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).
 
2151
 */
 
2152
Selectivity
 
2153
estimate_hash_bucketsize(Query *root, Node *hashkey, int nbuckets)
 
2154
{
 
2155
        VariableStatData vardata;
 
2156
        double          estfract,
 
2157
                                ndistinct,
 
2158
                                stanullfrac,
 
2159
                                mcvfreq,
 
2160
                                avgfreq;
 
2161
        float4     *numbers;
 
2162
        int                     nnumbers;
 
2163
 
 
2164
        examine_variable(root, hashkey, 0, &vardata);
 
2165
 
 
2166
        /* Get number of distinct values and fraction that are null */
 
2167
        ndistinct = get_variable_numdistinct(&vardata);
 
2168
 
 
2169
        if (HeapTupleIsValid(vardata.statsTuple))
 
2170
        {
 
2171
                Form_pg_statistic stats;
 
2172
 
 
2173
                stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
 
2174
                stanullfrac = stats->stanullfrac;
 
2175
        }
 
2176
        else
 
2177
        {
 
2178
                /*
 
2179
                 * Believe a default ndistinct only if it came from stats.
 
2180
                 * Otherwise punt and return 0.1, per comments above.
 
2181
                 */
 
2182
                if (ndistinct == DEFAULT_NUM_DISTINCT)
 
2183
                {
 
2184
                        ReleaseVariableStats(vardata);
 
2185
                        return (Selectivity) 0.1;
 
2186
                }
 
2187
 
 
2188
                stanullfrac = 0.0;
 
2189
        }
 
2190
 
 
2191
        /* Compute avg freq of all distinct data values in raw relation */
 
2192
        avgfreq = (1.0 - stanullfrac) / ndistinct;
 
2193
 
 
2194
        /*
 
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!
 
2198
         *
 
2199
         * XXX Possibly better way, but much more expensive: multiply by
 
2200
         * selectivity of rel's restriction clauses that mention the target
 
2201
         * Var.
 
2202
         */
 
2203
        if (vardata.rel)
 
2204
                ndistinct *= vardata.rel->rows / vardata.rel->tuples;
 
2205
 
 
2206
        /*
 
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.
 
2210
         */
 
2211
        if (ndistinct > (double) nbuckets)
 
2212
                estfract = 1.0 / (double) nbuckets;
 
2213
        else
 
2214
                estfract = 1.0 / ndistinct;
 
2215
 
 
2216
        /*
 
2217
         * Look up the frequency of the most common value, if available.
 
2218
         */
 
2219
        mcvfreq = 0.0;
 
2220
 
 
2221
        if (HeapTupleIsValid(vardata.statsTuple))
 
2222
        {
 
2223
                if (get_attstatsslot(vardata.statsTuple,
 
2224
                                                         vardata.atttype, vardata.atttypmod,
 
2225
                                                         STATISTIC_KIND_MCV, InvalidOid,
 
2226
                                                         NULL, NULL, &numbers, &nnumbers))
 
2227
                {
 
2228
                        /*
 
2229
                         * The first MCV stat is for the most common value.
 
2230
                         */
 
2231
                        if (nnumbers > 0)
 
2232
                                mcvfreq = numbers[0];
 
2233
                        free_attstatsslot(vardata.atttype, NULL, 0,
 
2234
                                                          numbers, nnumbers);
 
2235
                }
 
2236
        }
 
2237
 
 
2238
        /*
 
2239
         * Adjust estimated bucketsize upward to account for skewed
 
2240
         * distribution.
 
2241
         */
 
2242
        if (avgfreq > 0.0 && mcvfreq > avgfreq)
 
2243
                estfract *= mcvfreq / avgfreq;
 
2244
 
 
2245
        /*
 
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.
 
2249
         */
 
2250
        if (estfract < 1.0e-6)
 
2251
                estfract = 1.0e-6;
 
2252
        else if (estfract > 1.0)
 
2253
                estfract = 1.0;
 
2254
 
 
2255
        ReleaseVariableStats(vardata);
 
2256
 
 
2257
        return (Selectivity) estfract;
 
2258
}
 
2259
 
 
2260
 
 
2261
/*-------------------------------------------------------------------------
 
2262
 *
 
2263
 * Support routines
 
2264
 *
 
2265
 *-------------------------------------------------------------------------
 
2266
 */
 
2267
 
 
2268
/*
 
2269
 * convert_to_scalar
 
2270
 *        Convert non-NULL values of the indicated types to the comparison
 
2271
 *        scale needed by scalarltsel()/scalargtsel().
 
2272
 *        Returns "true" if successful.
 
2273
 *
 
2274
 * XXX this routine is a hack: ideally we should look up the conversion
 
2275
 * subroutines in pg_type.
 
2276
 *
 
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.)
 
2280
 *
 
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.
 
2284
 *
 
2285
 * The bytea datatype is just enough different from strings that it has
 
2286
 * to be treated separately.
 
2287
 *
 
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.
 
2293
 *
 
2294
 * The several datatypes representing relative times (intervals) are all
 
2295
 * converted to measurements expressed in seconds.
 
2296
 */
 
2297
static bool
 
2298
convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue,
 
2299
                                  Datum lobound, Datum hibound, Oid boundstypid,
 
2300
                                  double *scaledlobound, double *scaledhibound)
 
2301
{
 
2302
        /*
 
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.
 
2306
         *
 
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.
 
2316
         */
 
2317
        switch (valuetypid)
 
2318
        {
 
2319
                        /*
 
2320
                         * Built-in numeric types
 
2321
                         */
 
2322
                case BOOLOID:
 
2323
                case INT2OID:
 
2324
                case INT4OID:
 
2325
                case INT8OID:
 
2326
                case FLOAT4OID:
 
2327
                case FLOAT8OID:
 
2328
                case NUMERICOID:
 
2329
                case OIDOID:
 
2330
                case REGPROCOID:
 
2331
                case REGPROCEDUREOID:
 
2332
                case REGOPEROID:
 
2333
                case REGOPERATOROID:
 
2334
                case REGCLASSOID:
 
2335
                case REGTYPEOID:
 
2336
                        *scaledvalue = convert_numeric_to_scalar(value, valuetypid);
 
2337
                        *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid);
 
2338
                        *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid);
 
2339
                        return true;
 
2340
 
 
2341
                        /*
 
2342
                         * Built-in string types
 
2343
                         */
 
2344
                case CHAROID:
 
2345
                case BPCHAROID:
 
2346
                case VARCHAROID:
 
2347
                case TEXTOID:
 
2348
                case NAMEOID:
 
2349
                        {
 
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);
 
2353
 
 
2354
                                convert_string_to_scalar(valstr, scaledvalue,
 
2355
                                                                                 lostr, scaledlobound,
 
2356
                                                                                 histr, scaledhibound);
 
2357
                                pfree(valstr);
 
2358
                                pfree(lostr);
 
2359
                                pfree(histr);
 
2360
                                return true;
 
2361
                        }
 
2362
 
 
2363
                        /*
 
2364
                         * Built-in bytea type
 
2365
                         */
 
2366
                case BYTEAOID:
 
2367
                        {
 
2368
                                convert_bytea_to_scalar(value, scaledvalue,
 
2369
                                                                                lobound, scaledlobound,
 
2370
                                                                                hibound, scaledhibound);
 
2371
                                return true;
 
2372
                        }
 
2373
 
 
2374
                        /*
 
2375
                         * Built-in time types
 
2376
                         */
 
2377
                case TIMESTAMPOID:
 
2378
                case TIMESTAMPTZOID:
 
2379
                case ABSTIMEOID:
 
2380
                case DATEOID:
 
2381
                case INTERVALOID:
 
2382
                case RELTIMEOID:
 
2383
                case TINTERVALOID:
 
2384
                case TIMEOID:
 
2385
                case TIMETZOID:
 
2386
                        *scaledvalue = convert_timevalue_to_scalar(value, valuetypid);
 
2387
                        *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid);
 
2388
                        *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid);
 
2389
                        return true;
 
2390
 
 
2391
                        /*
 
2392
                         * Built-in network types
 
2393
                         */
 
2394
                case INETOID:
 
2395
                case CIDROID:
 
2396
                case MACADDROID:
 
2397
                        *scaledvalue = convert_network_to_scalar(value, valuetypid);
 
2398
                        *scaledlobound = convert_network_to_scalar(lobound, boundstypid);
 
2399
                        *scaledhibound = convert_network_to_scalar(hibound, boundstypid);
 
2400
                        return true;
 
2401
        }
 
2402
        /* Don't know how to convert */
 
2403
        return false;
 
2404
}
 
2405
 
 
2406
/*
 
2407
 * Do convert_to_scalar()'s work for any numeric data type.
 
2408
 */
 
2409
static double
 
2410
convert_numeric_to_scalar(Datum value, Oid typid)
 
2411
{
 
2412
        switch (typid)
 
2413
        {
 
2414
                case BOOLOID:
 
2415
                        return (double) DatumGetBool(value);
 
2416
                case INT2OID:
 
2417
                        return (double) DatumGetInt16(value);
 
2418
                case INT4OID:
 
2419
                        return (double) DatumGetInt32(value);
 
2420
                case INT8OID:
 
2421
                        return (double) DatumGetInt64(value);
 
2422
                case FLOAT4OID:
 
2423
                        return (double) DatumGetFloat4(value);
 
2424
                case FLOAT8OID:
 
2425
                        return (double) DatumGetFloat8(value);
 
2426
                case NUMERICOID:
 
2427
                        /* Note: out-of-range values will be clamped to +-HUGE_VAL */
 
2428
                        return (double)
 
2429
                                DatumGetFloat8(DirectFunctionCall1(numeric_float8_no_overflow,
 
2430
                                                                                                   value));
 
2431
                case OIDOID:
 
2432
                case REGPROCOID:
 
2433
                case REGPROCEDUREOID:
 
2434
                case REGOPEROID:
 
2435
                case REGOPERATOROID:
 
2436
                case REGCLASSOID:
 
2437
                case REGTYPEOID:
 
2438
                        /* we can treat OIDs as integers... */
 
2439
                        return (double) DatumGetObjectId(value);
 
2440
        }
 
2441
 
 
2442
        /*
 
2443
         * Can't get here unless someone tries to use scalarltsel/scalargtsel
 
2444
         * on an operator with one numeric and one non-numeric operand.
 
2445
         */
 
2446
        elog(ERROR, "unsupported type: %u", typid);
 
2447
        return 0;
 
2448
}
 
2449
 
 
2450
/*
 
2451
 * Do convert_to_scalar()'s work for any character-string data type.
 
2452
 *
 
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.
 
2455
 *
 
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.
 
2462
 *
 
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.)
 
2469
 */
 
2470
static void
 
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)
 
2477
{
 
2478
        int                     rangelo,
 
2479
                                rangehi;
 
2480
        unsigned char *sptr;
 
2481
 
 
2482
        rangelo = rangehi = hibound[0];
 
2483
        for (sptr = lobound; *sptr; sptr++)
 
2484
        {
 
2485
                if (rangelo > *sptr)
 
2486
                        rangelo = *sptr;
 
2487
                if (rangehi < *sptr)
 
2488
                        rangehi = *sptr;
 
2489
        }
 
2490
        for (sptr = hibound; *sptr; sptr++)
 
2491
        {
 
2492
                if (rangelo > *sptr)
 
2493
                        rangelo = *sptr;
 
2494
                if (rangehi < *sptr)
 
2495
                        rangehi = *sptr;
 
2496
        }
 
2497
        /* If range includes any upper-case ASCII chars, make it include all */
 
2498
        if (rangelo <= 'Z' && rangehi >= 'A')
 
2499
        {
 
2500
                if (rangelo > 'A')
 
2501
                        rangelo = 'A';
 
2502
                if (rangehi < 'Z')
 
2503
                        rangehi = 'Z';
 
2504
        }
 
2505
        /* Ditto lower-case */
 
2506
        if (rangelo <= 'z' && rangehi >= 'a')
 
2507
        {
 
2508
                if (rangelo > 'a')
 
2509
                        rangelo = 'a';
 
2510
                if (rangehi < 'z')
 
2511
                        rangehi = 'z';
 
2512
        }
 
2513
        /* Ditto digits */
 
2514
        if (rangelo <= '9' && rangehi >= '0')
 
2515
        {
 
2516
                if (rangelo > '0')
 
2517
                        rangelo = '0';
 
2518
                if (rangehi < '9')
 
2519
                        rangehi = '9';
 
2520
        }
 
2521
 
 
2522
        /*
 
2523
         * If range includes less than 10 chars, assume we have not got enough
 
2524
         * data, and make it include regular ASCII set.
 
2525
         */
 
2526
        if (rangehi - rangelo < 9)
 
2527
        {
 
2528
                rangelo = ' ';
 
2529
                rangehi = 127;
 
2530
        }
 
2531
 
 
2532
        /*
 
2533
         * Now strip any common prefix of the three strings.
 
2534
         */
 
2535
        while (*lobound)
 
2536
        {
 
2537
                if (*lobound != *hibound || *lobound != *value)
 
2538
                        break;
 
2539
                lobound++, hibound++, value++;
 
2540
        }
 
2541
 
 
2542
        /*
 
2543
         * Now we can do the conversions.
 
2544
         */
 
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);
 
2548
}
 
2549
 
 
2550
static double
 
2551
convert_one_string_to_scalar(unsigned char *value, int rangelo, int rangehi)
 
2552
{
 
2553
        int                     slen = strlen((char *) value);
 
2554
        double          num,
 
2555
                                denom,
 
2556
                                base;
 
2557
 
 
2558
        if (slen <= 0)
 
2559
                return 0.0;                             /* empty string has scalar value 0 */
 
2560
 
 
2561
        /*
 
2562
         * Since base is at least 10, need not consider more than about 20
 
2563
         * chars
 
2564
         */
 
2565
        if (slen > 20)
 
2566
                slen = 20;
 
2567
 
 
2568
        /* Convert initial characters to fraction */
 
2569
        base = rangehi - rangelo + 1;
 
2570
        num = 0.0;
 
2571
        denom = base;
 
2572
        while (slen-- > 0)
 
2573
        {
 
2574
                int                     ch = *value++;
 
2575
 
 
2576
                if (ch < rangelo)
 
2577
                        ch = rangelo - 1;
 
2578
                else if (ch > rangehi)
 
2579
                        ch = rangehi + 1;
 
2580
                num += ((double) (ch - rangelo)) / denom;
 
2581
                denom *= base;
 
2582
        }
 
2583
 
 
2584
        return num;
 
2585
}
 
2586
 
 
2587
/*
 
2588
 * Convert a string-type Datum into a palloc'd, null-terminated string.
 
2589
 *
 
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.
 
2592
 */
 
2593
static unsigned char *
 
2594
convert_string_datum(Datum value, Oid typid)
 
2595
{
 
2596
        char       *val;
 
2597
 
 
2598
        switch (typid)
 
2599
        {
 
2600
                case CHAROID:
 
2601
                        val = (char *) palloc(2);
 
2602
                        val[0] = DatumGetChar(value);
 
2603
                        val[1] = '\0';
 
2604
                        break;
 
2605
                case BPCHAROID:
 
2606
                case VARCHAROID:
 
2607
                case TEXTOID:
 
2608
                        {
 
2609
                                char       *str = (char *) VARDATA(DatumGetPointer(value));
 
2610
                                int                     strlength = VARSIZE(DatumGetPointer(value)) - VARHDRSZ;
 
2611
 
 
2612
                                val = (char *) palloc(strlength + 1);
 
2613
                                memcpy(val, str, strlength);
 
2614
                                val[strlength] = '\0';
 
2615
                                break;
 
2616
                        }
 
2617
                case NAMEOID:
 
2618
                        {
 
2619
                                NameData   *nm = (NameData *) DatumGetPointer(value);
 
2620
 
 
2621
                                val = pstrdup(NameStr(*nm));
 
2622
                                break;
 
2623
                        }
 
2624
                default:
 
2625
 
 
2626
                        /*
 
2627
                         * Can't get here unless someone tries to use scalarltsel on
 
2628
                         * an operator with one string and one non-string operand.
 
2629
                         */
 
2630
                        elog(ERROR, "unsupported type: %u", typid);
 
2631
                        return NULL;
 
2632
        }
 
2633
 
 
2634
        if (!lc_collate_is_c())
 
2635
        {
 
2636
                char       *xfrmstr;
 
2637
                size_t          xfrmlen;
 
2638
                size_t          xfrmlen2;
 
2639
 
 
2640
                /*
 
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.
 
2646
                 *
 
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?
 
2651
                 */
 
2652
                xfrmlen = strxfrm(NULL, val, 0);
 
2653
                xfrmstr = (char *) palloc(xfrmlen + 1);
 
2654
                xfrmlen2 = strxfrm(xfrmstr, val, xfrmlen + 1);
 
2655
                Assert(xfrmlen2 <= xfrmlen);
 
2656
                pfree(val);
 
2657
                val = xfrmstr;
 
2658
        }
 
2659
 
 
2660
        return (unsigned char *) val;
 
2661
}
 
2662
 
 
2663
/*
 
2664
 * Do convert_to_scalar()'s work for any bytea data type.
 
2665
 *
 
2666
 * Very similar to convert_string_to_scalar except we can't assume
 
2667
 * null-termination and therefore pass explicit lengths around.
 
2668
 *
 
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
 
2672
 * pg_statistic.)
 
2673
 */
 
2674
static void
 
2675
convert_bytea_to_scalar(Datum value,
 
2676
                                                double *scaledvalue,
 
2677
                                                Datum lobound,
 
2678
                                                double *scaledlobound,
 
2679
                                                Datum hibound,
 
2680
                                                double *scaledhibound)
 
2681
{
 
2682
        int                     rangelo,
 
2683
                                rangehi,
 
2684
                                valuelen = VARSIZE(DatumGetPointer(value)) - VARHDRSZ,
 
2685
                                loboundlen = VARSIZE(DatumGetPointer(lobound)) - VARHDRSZ,
 
2686
                                hiboundlen = VARSIZE(DatumGetPointer(hibound)) - VARHDRSZ,
 
2687
                                i,
 
2688
                                minlen;
 
2689
        unsigned char *valstr = (unsigned char *) VARDATA(DatumGetPointer(value)),
 
2690
                           *lostr = (unsigned char *) VARDATA(DatumGetPointer(lobound)),
 
2691
                           *histr = (unsigned char *) VARDATA(DatumGetPointer(hibound));
 
2692
 
 
2693
        /*
 
2694
         * Assume bytea data is uniformly distributed across all byte values.
 
2695
         */
 
2696
        rangelo = 0;
 
2697
        rangehi = 255;
 
2698
 
 
2699
        /*
 
2700
         * Now strip any common prefix of the three strings.
 
2701
         */
 
2702
        minlen = Min(Min(valuelen, loboundlen), hiboundlen);
 
2703
        for (i = 0; i < minlen; i++)
 
2704
        {
 
2705
                if (*lostr != *histr || *lostr != *valstr)
 
2706
                        break;
 
2707
                lostr++, histr++, valstr++;
 
2708
                loboundlen--, hiboundlen--, valuelen--;
 
2709
        }
 
2710
 
 
2711
        /*
 
2712
         * Now we can do the conversions.
 
2713
         */
 
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);
 
2717
}
 
2718
 
 
2719
static double
 
2720
convert_one_bytea_to_scalar(unsigned char *value, int valuelen,
 
2721
                                                        int rangelo, int rangehi)
 
2722
{
 
2723
        double          num,
 
2724
                                denom,
 
2725
                                base;
 
2726
 
 
2727
        if (valuelen <= 0)
 
2728
                return 0.0;                             /* empty string has scalar value 0 */
 
2729
 
 
2730
        /*
 
2731
         * Since base is 256, need not consider more than about 10 chars (even
 
2732
         * this many seems like overkill)
 
2733
         */
 
2734
        if (valuelen > 10)
 
2735
                valuelen = 10;
 
2736
 
 
2737
        /* Convert initial characters to fraction */
 
2738
        base = rangehi - rangelo + 1;
 
2739
        num = 0.0;
 
2740
        denom = base;
 
2741
        while (valuelen-- > 0)
 
2742
        {
 
2743
                int                     ch = *value++;
 
2744
 
 
2745
                if (ch < rangelo)
 
2746
                        ch = rangelo - 1;
 
2747
                else if (ch > rangehi)
 
2748
                        ch = rangehi + 1;
 
2749
                num += ((double) (ch - rangelo)) / denom;
 
2750
                denom *= base;
 
2751
        }
 
2752
 
 
2753
        return num;
 
2754
}
 
2755
 
 
2756
/*
 
2757
 * Do convert_to_scalar()'s work for any timevalue data type.
 
2758
 */
 
2759
static double
 
2760
convert_timevalue_to_scalar(Datum value, Oid typid)
 
2761
{
 
2762
        switch (typid)
 
2763
        {
 
2764
                case TIMESTAMPOID:
 
2765
                        return DatumGetTimestamp(value);
 
2766
                case TIMESTAMPTZOID:
 
2767
                        return DatumGetTimestampTz(value);
 
2768
                case ABSTIMEOID:
 
2769
                        return DatumGetTimestamp(DirectFunctionCall1(abstime_timestamp,
 
2770
                                                                                                                 value));
 
2771
                case DATEOID:
 
2772
                        return DatumGetTimestamp(DirectFunctionCall1(date_timestamp,
 
2773
                                                                                                                 value));
 
2774
                case INTERVALOID:
 
2775
                        {
 
2776
                                Interval   *interval = DatumGetIntervalP(value);
 
2777
 
 
2778
                                /*
 
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.
 
2782
                                 */
 
2783
#ifdef HAVE_INT64_TIMESTAMP
 
2784
                                return (interval->time + (interval->month * ((365.25 / 12.0) * 86400000000.0)));
 
2785
#else
 
2786
                                return interval->time +
 
2787
                                interval  ->month * (365.25 / 12.0 * 24.0 * 60.0 * 60.0);
 
2788
#endif
 
2789
                        }
 
2790
                case RELTIMEOID:
 
2791
#ifdef HAVE_INT64_TIMESTAMP
 
2792
                        return (DatumGetRelativeTime(value) * 1000000.0);
 
2793
#else
 
2794
                        return DatumGetRelativeTime(value);
 
2795
#endif
 
2796
                case TINTERVALOID:
 
2797
                        {
 
2798
                                TimeInterval interval = DatumGetTimeInterval(value);
 
2799
 
 
2800
#ifdef HAVE_INT64_TIMESTAMP
 
2801
                                if (interval->status != 0)
 
2802
                                        return ((interval->data[1] - interval->data[0]) *1000000.0);
 
2803
#else
 
2804
                                if (interval->status != 0)
 
2805
                                        return interval->data[1] - interval->data[0];
 
2806
#endif
 
2807
                                return 0;               /* for lack of a better idea */
 
2808
                        }
 
2809
                case TIMEOID:
 
2810
                        return DatumGetTimeADT(value);
 
2811
                case TIMETZOID:
 
2812
                        {
 
2813
                                TimeTzADT  *timetz = DatumGetTimeTzADTP(value);
 
2814
 
 
2815
                                /* use GMT-equivalent time */
 
2816
#ifdef HAVE_INT64_TIMESTAMP
 
2817
                                return (double) (timetz->time + (timetz->zone * 1000000.0));
 
2818
#else
 
2819
                                return (double) (timetz->time + timetz->zone);
 
2820
#endif
 
2821
                        }
 
2822
        }
 
2823
 
 
2824
        /*
 
2825
         * Can't get here unless someone tries to use scalarltsel/scalargtsel
 
2826
         * on an operator with one timevalue and one non-timevalue operand.
 
2827
         */
 
2828
        elog(ERROR, "unsupported type: %u", typid);
 
2829
        return 0;
 
2830
}
 
2831
 
 
2832
 
 
2833
/*
 
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.
 
2840
 *
 
2841
 * Inputs:
 
2842
 *      root: the Query
 
2843
 *      args: clause argument list
 
2844
 *      varRelid: see specs for restriction selectivity functions
 
2845
 *
 
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
 
2850
 *
 
2851
 * Returns TRUE if a variable is identified, otherwise FALSE.
 
2852
 *
 
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.
 
2855
 */
 
2856
static bool
 
2857
get_restriction_variable(Query *root, List *args, int varRelid,
 
2858
                                                 VariableStatData *vardata, Node **other,
 
2859
                                                 bool *varonleft)
 
2860
{
 
2861
        Node       *left,
 
2862
                           *right;
 
2863
        VariableStatData rdata;
 
2864
 
 
2865
        /* Fail if not a binary opclause (probably shouldn't happen) */
 
2866
        if (list_length(args) != 2)
 
2867
                return false;
 
2868
 
 
2869
        left = (Node *) linitial(args);
 
2870
        right = (Node *) lsecond(args);
 
2871
 
 
2872
        /*
 
2873
         * Examine both sides.  Note that when varRelid is nonzero, Vars of
 
2874
         * other relations will be treated as pseudoconstants.
 
2875
         */
 
2876
        examine_variable(root, left, varRelid, vardata);
 
2877
        examine_variable(root, right, varRelid, &rdata);
 
2878
 
 
2879
        /*
 
2880
         * If one side is a variable and the other not, we win.
 
2881
         */
 
2882
        if (vardata->rel && rdata.rel == NULL)
 
2883
        {
 
2884
                *varonleft = true;
 
2885
                *other = estimate_expression_value(rdata.var);
 
2886
                /* Assume we need no ReleaseVariableStats(rdata) here */
 
2887
                return true;
 
2888
        }
 
2889
 
 
2890
        if (vardata->rel == NULL && rdata.rel)
 
2891
        {
 
2892
                *varonleft = false;
 
2893
                *other = estimate_expression_value(vardata->var);
 
2894
                /* Assume we need no ReleaseVariableStats(*vardata) here */
 
2895
                *vardata = rdata;
 
2896
                return true;
 
2897
        }
 
2898
 
 
2899
        /* Ooops, clause has wrong structure (probably var op var) */
 
2900
        ReleaseVariableStats(*vardata);
 
2901
        ReleaseVariableStats(rdata);
 
2902
 
 
2903
        return false;
 
2904
}
 
2905
 
 
2906
/*
 
2907
 * get_join_variables
 
2908
 *              Apply examine_variable() to each side of a join clause.
 
2909
 */
 
2910
static void
 
2911
get_join_variables(Query *root, List *args,
 
2912
                                   VariableStatData *vardata1, VariableStatData *vardata2)
 
2913
{
 
2914
        Node       *left,
 
2915
                           *right;
 
2916
 
 
2917
        if (list_length(args) != 2)
 
2918
                elog(ERROR, "join operator should take two arguments");
 
2919
 
 
2920
        left = (Node *) linitial(args);
 
2921
        right = (Node *) lsecond(args);
 
2922
 
 
2923
        examine_variable(root, left, 0, vardata1);
 
2924
        examine_variable(root, right, 0, vardata2);
 
2925
}
 
2926
 
 
2927
/*
 
2928
 * examine_variable
 
2929
 *              Try to look up statistical data about an expression.
 
2930
 *              Fill in a VariableStatData struct to describe the expression.
 
2931
 *
 
2932
 * Inputs:
 
2933
 *      root: the Query
 
2934
 *      node: the expression tree to examine
 
2935
 *      varRelid: see specs for restriction selectivity functions
 
2936
 *
 
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;
 
2944
 *              otherwise NULL.
 
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.
 
2950
 *
 
2951
 * Caller is responsible for doing ReleaseVariableStats() before exiting.
 
2952
 */
 
2953
static void
 
2954
examine_variable(Query *root, Node *node, int varRelid,
 
2955
                                 VariableStatData *vardata)
 
2956
{
 
2957
        Node       *basenode;
 
2958
        Relids          varnos;
 
2959
        RelOptInfo *onerel;
 
2960
 
 
2961
        /* Make sure we don't return dangling pointers in vardata */
 
2962
        MemSet(vardata, 0, sizeof(VariableStatData));
 
2963
 
 
2964
        /* Save the exposed type of the expression */
 
2965
        vardata->vartype = exprType(node);
 
2966
 
 
2967
        /* Look inside any binary-compatible relabeling */
 
2968
 
 
2969
        if (IsA(node, RelabelType))
 
2970
                basenode = (Node *) ((RelabelType *) node)->arg;
 
2971
        else
 
2972
                basenode = node;
 
2973
 
 
2974
        /* Fast path for a simple Var */
 
2975
 
 
2976
        if (IsA(basenode, Var) &&
 
2977
                (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
 
2978
        {
 
2979
                Var                *var = (Var *) basenode;
 
2980
                Oid                     relid;
 
2981
 
 
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;
 
2986
 
 
2987
                relid = getrelid(var->varno, root->rtable);
 
2988
 
 
2989
                if (OidIsValid(relid))
 
2990
                {
 
2991
                        vardata->statsTuple = SearchSysCache(STATRELATT,
 
2992
                                                                                                 ObjectIdGetDatum(relid),
 
2993
                                                                                        Int16GetDatum(var->varattno),
 
2994
                                                                                                 0, 0);
 
2995
                }
 
2996
                else
 
2997
                {
 
2998
                        /*
 
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??)
 
3005
                         */
 
3006
                }
 
3007
 
 
3008
                return;
 
3009
        }
 
3010
 
 
3011
        /*
 
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.
 
3015
         */
 
3016
        varnos = pull_varnos(basenode);
 
3017
 
 
3018
        onerel = NULL;
 
3019
 
 
3020
        switch (bms_membership(varnos))
 
3021
        {
 
3022
                case BMS_EMPTY_SET:
 
3023
                        /* No Vars at all ... must be pseudo-constant clause */
 
3024
                        break;
 
3025
                case BMS_SINGLETON:
 
3026
                        if (varRelid == 0 || bms_is_member(varRelid, varnos))
 
3027
                        {
 
3028
                                onerel = find_base_rel(root,
 
3029
                                   (varRelid ? varRelid : bms_singleton_member(varnos)));
 
3030
                                vardata->rel = onerel;
 
3031
                                node = basenode; /* strip any relabeling */
 
3032
                        }
 
3033
                        /* else treat it as a constant */
 
3034
                        break;
 
3035
                case BMS_MULTIPLE:
 
3036
                        if (varRelid == 0)
 
3037
                        {
 
3038
                                /* treat it as a variable of a join relation */
 
3039
                                vardata->rel = find_join_rel(root, varnos);
 
3040
                                node = basenode; /* strip any relabeling */
 
3041
                        }
 
3042
                        else if (bms_is_member(varRelid, varnos))
 
3043
                        {
 
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 */
 
3048
                        }
 
3049
                        /* else treat it as a constant */
 
3050
                        break;
 
3051
        }
 
3052
 
 
3053
        bms_free(varnos);
 
3054
 
 
3055
        vardata->var = node;
 
3056
        vardata->atttype = exprType(node);
 
3057
        vardata->atttypmod = exprTypmod(node);
 
3058
 
 
3059
        if (onerel)
 
3060
        {
 
3061
                /*
 
3062
                 * We have an expression in vars of a single relation.  Try to
 
3063
                 * match it to expressional index columns, in hopes of finding
 
3064
                 * some statistics.
 
3065
                 *
 
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.
 
3069
                 */
 
3070
                ListCell   *ilist;
 
3071
 
 
3072
                foreach(ilist, onerel->indexlist)
 
3073
                {
 
3074
                        IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
 
3075
                        ListCell   *indexpr_item;
 
3076
                        int                     pos;
 
3077
 
 
3078
                        indexpr_item = list_head(index->indexprs);
 
3079
                        if (indexpr_item == NULL)
 
3080
                                continue;               /* no expressions here... */
 
3081
 
 
3082
                        /*
 
3083
                         * Ignore partial indexes since they probably don't reflect
 
3084
                         * whole-relation statistics.  Possibly reconsider this later.
 
3085
                         */
 
3086
                        if (index->indpred)
 
3087
                                continue;
 
3088
 
 
3089
                        for (pos = 0; pos < index->ncolumns; pos++)
 
3090
                        {
 
3091
                                if (index->indexkeys[pos] == 0)
 
3092
                                {
 
3093
                                        Node       *indexkey;
 
3094
 
 
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))
 
3101
                                        {
 
3102
                                                /*
 
3103
                                                 * Found a match ... is it a unique index? Tests
 
3104
                                                 * here should match has_unique_index().
 
3105
                                                 */
 
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),
 
3114
                                                                                                                         0, 0);
 
3115
                                                if (vardata->statsTuple)
 
3116
                                                        break;
 
3117
                                        }
 
3118
                                        indexpr_item = lnext(indexpr_item);
 
3119
                                }
 
3120
                        }
 
3121
                        if (vardata->statsTuple)
 
3122
                                break;
 
3123
                }
 
3124
        }
 
3125
}
 
3126
 
 
3127
/*
 
3128
 * get_variable_numdistinct
 
3129
 *        Estimate the number of distinct values of a variable.
 
3130
 *
 
3131
 * vardata: results of examine_variable
 
3132
 *
 
3133
 * NB: be careful to produce an integral result, since callers may compare
 
3134
 * the result to exact integer counts.
 
3135
 */
 
3136
static double
 
3137
get_variable_numdistinct(VariableStatData *vardata)
 
3138
{
 
3139
        double          stadistinct;
 
3140
        double          ntuples;
 
3141
 
 
3142
        /*
 
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.
 
3146
         */
 
3147
        if (HeapTupleIsValid(vardata->statsTuple))
 
3148
        {
 
3149
                /* Use the pg_statistic entry */
 
3150
                Form_pg_statistic stats;
 
3151
 
 
3152
                stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
 
3153
                stadistinct = stats->stadistinct;
 
3154
        }
 
3155
        else if (vardata->vartype == BOOLOID)
 
3156
        {
 
3157
                /*
 
3158
                 * Special-case boolean columns: presumably, two distinct values.
 
3159
                 *
 
3160
                 * Are there any other datatypes we should wire in special estimates
 
3161
                 * for?
 
3162
                 */
 
3163
                stadistinct = 2.0;
 
3164
        }
 
3165
        else
 
3166
        {
 
3167
                /*
 
3168
                 * We don't keep statistics for system columns, but in some cases
 
3169
                 * we can infer distinctness anyway.
 
3170
                 */
 
3171
                if (vardata->var && IsA(vardata->var, Var))
 
3172
                {
 
3173
                        switch (((Var *) vardata->var)->varattno)
 
3174
                        {
 
3175
                                case ObjectIdAttributeNumber:
 
3176
                                case SelfItemPointerAttributeNumber:
 
3177
                                        stadistinct = -1.0; /* unique */
 
3178
                                        break;
 
3179
                                case TableOidAttributeNumber:
 
3180
                                        stadistinct = 1.0;      /* only 1 value */
 
3181
                                        break;
 
3182
                                default:
 
3183
                                        stadistinct = 0.0;      /* means "unknown" */
 
3184
                                        break;
 
3185
                        }
 
3186
                }
 
3187
                else
 
3188
                        stadistinct = 0.0;      /* means "unknown" */
 
3189
 
 
3190
                /*
 
3191
                 * XXX consider using estimate_num_groups on expressions?
 
3192
                 */
 
3193
        }
 
3194
 
 
3195
        /*
 
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.
 
3199
         */
 
3200
        if (stadistinct != -1.0)
 
3201
        {
 
3202
                if (vardata->isunique)
 
3203
                        stadistinct = -1.0;
 
3204
                else if (vardata->var && IsA(vardata->var, Var) &&
 
3205
                                 vardata->rel &&
 
3206
                                 has_unique_index(vardata->rel,
 
3207
                                                                  ((Var *) vardata->var)->varattno))
 
3208
                        stadistinct = -1.0;
 
3209
        }
 
3210
 
 
3211
        /*
 
3212
         * If we had an absolute estimate, use that.
 
3213
         */
 
3214
        if (stadistinct > 0.0)
 
3215
                return stadistinct;
 
3216
 
 
3217
        /*
 
3218
         * Otherwise we need to get the relation size; punt if not available.
 
3219
         */
 
3220
        if (vardata->rel == NULL)
 
3221
                return DEFAULT_NUM_DISTINCT;
 
3222
        ntuples = vardata->rel->tuples;
 
3223
        if (ntuples <= 0.0)
 
3224
                return DEFAULT_NUM_DISTINCT;
 
3225
 
 
3226
        /*
 
3227
         * If we had a relative estimate, use that.
 
3228
         */
 
3229
        if (stadistinct < 0.0)
 
3230
                return floor((-stadistinct * ntuples) + 0.5);
 
3231
 
 
3232
        /*
 
3233
         * With no data, estimate ndistinct = ntuples if the table is small,
 
3234
         * else use default.
 
3235
         */
 
3236
        if (ntuples < DEFAULT_NUM_DISTINCT)
 
3237
                return ntuples;
 
3238
 
 
3239
        return DEFAULT_NUM_DISTINCT;
 
3240
}
 
3241
 
 
3242
/*
 
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.
 
3247
 *
 
3248
 * sortop is the "<" comparison operator to use.  (To extract the
 
3249
 * minimum instead of the maximum, just pass the ">" operator instead.)
 
3250
 */
 
3251
static bool
 
3252
get_variable_maximum(Query *root, VariableStatData *vardata,
 
3253
                                         Oid sortop, Datum *max)
 
3254
{
 
3255
        Datum           tmax = 0;
 
3256
        bool            have_max = false;
 
3257
        Form_pg_statistic stats;
 
3258
        int16           typLen;
 
3259
        bool            typByVal;
 
3260
        Datum      *values;
 
3261
        int                     nvalues;
 
3262
        int                     i;
 
3263
 
 
3264
        if (!HeapTupleIsValid(vardata->statsTuple))
 
3265
        {
 
3266
                /* no stats available, so default result */
 
3267
                return false;
 
3268
        }
 
3269
        stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
 
3270
 
 
3271
        get_typlenbyval(vardata->atttype, &typLen, &typByVal);
 
3272
 
 
3273
        /*
 
3274
         * If there is a histogram, grab the last or first value as
 
3275
         * appropriate.
 
3276
         *
 
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
 
3279
         * use.
 
3280
         */
 
3281
        if (get_attstatsslot(vardata->statsTuple,
 
3282
                                                 vardata->atttype, vardata->atttypmod,
 
3283
                                                 STATISTIC_KIND_HISTOGRAM, sortop,
 
3284
                                                 &values, &nvalues,
 
3285
                                                 NULL, NULL))
 
3286
        {
 
3287
                if (nvalues > 0)
 
3288
                {
 
3289
                        tmax = datumCopy(values[nvalues - 1], typByVal, typLen);
 
3290
                        have_max = true;
 
3291
                }
 
3292
                free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
 
3293
        }
 
3294
        else
 
3295
        {
 
3296
                Oid                     rsortop = get_commutator(sortop);
 
3297
 
 
3298
                if (OidIsValid(rsortop) &&
 
3299
                        get_attstatsslot(vardata->statsTuple,
 
3300
                                                         vardata->atttype, vardata->atttypmod,
 
3301
                                                         STATISTIC_KIND_HISTOGRAM, rsortop,
 
3302
                                                         &values, &nvalues,
 
3303
                                                         NULL, NULL))
 
3304
                {
 
3305
                        if (nvalues > 0)
 
3306
                        {
 
3307
                                tmax = datumCopy(values[0], typByVal, typLen);
 
3308
                                have_max = true;
 
3309
                        }
 
3310
                        free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
 
3311
                }
 
3312
                else if (get_attstatsslot(vardata->statsTuple,
 
3313
                                                                  vardata->atttype, vardata->atttypmod,
 
3314
                                                                  STATISTIC_KIND_HISTOGRAM, InvalidOid,
 
3315
                                                                  &values, &nvalues,
 
3316
                                                                  NULL, NULL))
 
3317
                {
 
3318
                        free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
 
3319
                        return false;
 
3320
                }
 
3321
        }
 
3322
 
 
3323
        /*
 
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.
 
3328
         */
 
3329
        if (get_attstatsslot(vardata->statsTuple,
 
3330
                                                 vardata->atttype, vardata->atttypmod,
 
3331
                                                 STATISTIC_KIND_MCV, InvalidOid,
 
3332
                                                 &values, &nvalues,
 
3333
                                                 NULL, NULL))
 
3334
        {
 
3335
                bool            large_mcv = false;
 
3336
                FmgrInfo        opproc;
 
3337
 
 
3338
                fmgr_info(get_opcode(sortop), &opproc);
 
3339
 
 
3340
                for (i = 0; i < nvalues; i++)
 
3341
                {
 
3342
                        if (!have_max)
 
3343
                        {
 
3344
                                tmax = values[i];
 
3345
                                large_mcv = have_max = true;
 
3346
                        }
 
3347
                        else if (DatumGetBool(FunctionCall2(&opproc, tmax, values[i])))
 
3348
                        {
 
3349
                                tmax = values[i];
 
3350
                                large_mcv = true;
 
3351
                        }
 
3352
                }
 
3353
                if (large_mcv)
 
3354
                        tmax = datumCopy(tmax, typByVal, typLen);
 
3355
                free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
 
3356
        }
 
3357
 
 
3358
        *max = tmax;
 
3359
        return have_max;
 
3360
}
 
3361
 
 
3362
 
 
3363
/*-------------------------------------------------------------------------
 
3364
 *
 
3365
 * Pattern analysis functions
 
3366
 *
 
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.
 
3371
 *
 
3372
 * Note that the prefix-analysis functions are called from
 
3373
 * backend/optimizer/path/indxpath.c as well as from routines in this file.
 
3374
 *
 
3375
 *-------------------------------------------------------------------------
 
3376
 */
 
3377
 
 
3378
/*
 
3379
 * Extract the fixed prefix, if any, for a pattern.
 
3380
 *
 
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.
 
3386
 *
 
3387
 * The return value distinguishes no fixed prefix, a partial prefix,
 
3388
 * or an exact-match-only pattern.
 
3389
 */
 
3390
 
 
3391
static Pattern_Prefix_Status
 
3392
like_fixed_prefix(Const *patt_const, bool case_insensitive,
 
3393
                                  Const **prefix_const, Const **rest_const)
 
3394
{
 
3395
        char       *match;
 
3396
        char       *patt;
 
3397
        int                     pattlen;
 
3398
        char       *rest;
 
3399
        Oid                     typeid = patt_const->consttype;
 
3400
        int                     pos,
 
3401
                                match_pos;
 
3402
 
 
3403
        /* the right-hand const is type text or bytea */
 
3404
        Assert(typeid == BYTEAOID || typeid == TEXTOID);
 
3405
 
 
3406
        if (typeid == BYTEAOID && case_insensitive)
 
3407
                ereport(ERROR,
 
3408
                                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 
3409
                errmsg("case insensitive matching not supported on type bytea")));
 
3410
 
 
3411
        if (typeid != BYTEAOID)
 
3412
        {
 
3413
                patt = DatumGetCString(DirectFunctionCall1(textout, patt_const->constvalue));
 
3414
                pattlen = strlen(patt);
 
3415
        }
 
3416
        else
 
3417
        {
 
3418
                bytea      *bstr = DatumGetByteaP(patt_const->constvalue);
 
3419
 
 
3420
                pattlen = VARSIZE(bstr) - VARHDRSZ;
 
3421
                if (pattlen > 0)
 
3422
                {
 
3423
                        patt = (char *) palloc(pattlen);
 
3424
                        memcpy(patt, VARDATA(bstr), pattlen);
 
3425
                }
 
3426
                else
 
3427
                        patt = NULL;
 
3428
 
 
3429
                if ((Pointer) bstr != DatumGetPointer(patt_const->constvalue))
 
3430
                        pfree(bstr);
 
3431
        }
 
3432
 
 
3433
        match = palloc(pattlen + 1);
 
3434
        match_pos = 0;
 
3435
        for (pos = 0; pos < pattlen; pos++)
 
3436
        {
 
3437
                /* % and _ are wildcard characters in LIKE */
 
3438
                if (patt[pos] == '%' ||
 
3439
                        patt[pos] == '_')
 
3440
                        break;
 
3441
 
 
3442
                /* Backslash escapes the next character */
 
3443
                if (patt[pos] == '\\')
 
3444
                {
 
3445
                        pos++;
 
3446
                        if (patt[pos] == '\0' && typeid != BYTEAOID)
 
3447
                                break;
 
3448
                }
 
3449
 
 
3450
                /*
 
3451
                 * XXX I suspect isalpha() is not an adequately locale-sensitive
 
3452
                 * test for characters that can vary under case folding?
 
3453
                 */
 
3454
                if (case_insensitive && isalpha((unsigned char) patt[pos]))
 
3455
                        break;
 
3456
 
 
3457
                /*
 
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.
 
3461
                 */
 
3462
                match[match_pos++] = patt[pos];
 
3463
        }
 
3464
 
 
3465
        match[match_pos] = '\0';
 
3466
        rest = &patt[pos];
 
3467
 
 
3468
        if (typeid != BYTEAOID)
 
3469
        {
 
3470
                *prefix_const = string_to_const(match, typeid);
 
3471
                *rest_const = string_to_const(rest, typeid);
 
3472
        }
 
3473
        else
 
3474
        {
 
3475
                *prefix_const = string_to_bytea_const(match, match_pos);
 
3476
                *rest_const = string_to_bytea_const(rest, pattlen - pos);
 
3477
        }
 
3478
 
 
3479
        if (patt != NULL)
 
3480
                pfree(patt);
 
3481
        pfree(match);
 
3482
 
 
3483
        /* in LIKE, an empty pattern is an exact match! */
 
3484
        if (pos == pattlen)
 
3485
                return Pattern_Prefix_Exact;    /* reached end of pattern, so
 
3486
                                                                                 * exact */
 
3487
 
 
3488
        if (match_pos > 0)
 
3489
                return Pattern_Prefix_Partial;
 
3490
 
 
3491
        return Pattern_Prefix_None;
 
3492
}
 
3493
 
 
3494
static Pattern_Prefix_Status
 
3495
regex_fixed_prefix(Const *patt_const, bool case_insensitive,
 
3496
                                   Const **prefix_const, Const **rest_const)
 
3497
{
 
3498
        char       *match;
 
3499
        int                     pos,
 
3500
                                match_pos,
 
3501
                                prev_pos,
 
3502
                                prev_match_pos,
 
3503
                                paren_depth;
 
3504
        char       *patt;
 
3505
        char       *rest;
 
3506
        Oid                     typeid = patt_const->consttype;
 
3507
 
 
3508
        /*
 
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.
 
3512
         */
 
3513
        if (typeid == BYTEAOID)
 
3514
                ereport(ERROR,
 
3515
                                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 
3516
                                 errmsg("regular-expression matching not supported on type bytea")));
 
3517
 
 
3518
        /* the right-hand const is type text for all of these */
 
3519
        patt = DatumGetCString(DirectFunctionCall1(textout, patt_const->constvalue));
 
3520
 
 
3521
        /* Pattern must be anchored left */
 
3522
        if (patt[0] != '^')
 
3523
        {
 
3524
                rest = patt;
 
3525
 
 
3526
                *prefix_const = NULL;
 
3527
                *rest_const = string_to_const(rest, typeid);
 
3528
 
 
3529
                return Pattern_Prefix_None;
 
3530
        }
 
3531
 
 
3532
        /*
 
3533
         * If unquoted | is present at paren level 0 in pattern, then there
 
3534
         * are multiple alternatives for the start of the string.
 
3535
         */
 
3536
        paren_depth = 0;
 
3537
        for (pos = 1; patt[pos]; pos++)
 
3538
        {
 
3539
                if (patt[pos] == '|' && paren_depth == 0)
 
3540
                {
 
3541
                        rest = patt;
 
3542
 
 
3543
                        *prefix_const = NULL;
 
3544
                        *rest_const = string_to_const(rest, typeid);
 
3545
 
 
3546
                        return Pattern_Prefix_None;
 
3547
                }
 
3548
                else if (patt[pos] == '(')
 
3549
                        paren_depth++;
 
3550
                else if (patt[pos] == ')' && paren_depth > 0)
 
3551
                        paren_depth--;
 
3552
                else if (patt[pos] == '\\')
 
3553
                {
 
3554
                        /* backslash quotes the next character */
 
3555
                        pos++;
 
3556
                        if (patt[pos] == '\0')
 
3557
                                break;
 
3558
                }
 
3559
        }
 
3560
 
 
3561
        /* OK, allocate space for pattern */
 
3562
        match = palloc(strlen(patt) + 1);
 
3563
        prev_match_pos = match_pos = 0;
 
3564
 
 
3565
        /* note start at pos 1 to skip leading ^ */
 
3566
        for (prev_pos = pos = 1; patt[pos]; )
 
3567
        {
 
3568
                int             len;
 
3569
 
 
3570
                /*
 
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
 
3574
                 * folding?
 
3575
                 */
 
3576
                if (patt[pos] == '.' ||
 
3577
                        patt[pos] == '(' ||
 
3578
                        patt[pos] == '[' ||
 
3579
                        patt[pos] == '$' ||
 
3580
                        (case_insensitive && isalpha((unsigned char) patt[pos])))
 
3581
                        break;
 
3582
 
 
3583
                /*
 
3584
                 * In AREs, backslash followed by alphanumeric is an escape, not
 
3585
                 * a quoted character.  Must treat it as having multiple possible
 
3586
                 * matches.
 
3587
                 */
 
3588
                if (patt[pos] == '\\' && isalnum((unsigned char) patt[pos + 1]))
 
3589
                        break;
 
3590
 
 
3591
                /*
 
3592
                 * Check for quantifiers.  Except for +, this means the preceding
 
3593
                 * character is optional, so we must remove it from the prefix
 
3594
                 * too!
 
3595
                 */
 
3596
                if (patt[pos] == '*' ||
 
3597
                        patt[pos] == '?' ||
 
3598
                        patt[pos] == '{')
 
3599
                {
 
3600
                        match_pos = prev_match_pos;
 
3601
                        pos = prev_pos;
 
3602
                        break;
 
3603
                }
 
3604
                if (patt[pos] == '+')
 
3605
                {
 
3606
                        pos = prev_pos;
 
3607
                        break;
 
3608
                }
 
3609
                if (patt[pos] == '\\')
 
3610
                {
 
3611
                        /* backslash quotes the next character */
 
3612
                        pos++;
 
3613
                        if (patt[pos] == '\0')
 
3614
                                break;
 
3615
                }
 
3616
                /* save position in case we need to back up on next loop cycle */
 
3617
                prev_match_pos = match_pos;
 
3618
                prev_pos = pos;
 
3619
                /* must use encoding-aware processing here */
 
3620
                len = pg_mblen(&patt[pos]);
 
3621
                memcpy(&match[match_pos], &patt[pos], len);
 
3622
                match_pos += len;
 
3623
                pos += len;
 
3624
        }
 
3625
 
 
3626
        match[match_pos] = '\0';
 
3627
        rest = &patt[pos];
 
3628
 
 
3629
        if (patt[pos] == '$' && patt[pos + 1] == '\0')
 
3630
        {
 
3631
                rest = &patt[pos + 1];
 
3632
 
 
3633
                *prefix_const = string_to_const(match, typeid);
 
3634
                *rest_const = string_to_const(rest, typeid);
 
3635
 
 
3636
                pfree(patt);
 
3637
                pfree(match);
 
3638
 
 
3639
                return Pattern_Prefix_Exact;    /* pattern specifies exact match */
 
3640
        }
 
3641
 
 
3642
        *prefix_const = string_to_const(match, typeid);
 
3643
        *rest_const = string_to_const(rest, typeid);
 
3644
 
 
3645
        pfree(patt);
 
3646
        pfree(match);
 
3647
 
 
3648
        if (match_pos > 0)
 
3649
                return Pattern_Prefix_Partial;
 
3650
 
 
3651
        return Pattern_Prefix_None;
 
3652
}
 
3653
 
 
3654
Pattern_Prefix_Status
 
3655
pattern_fixed_prefix(Const *patt, Pattern_Type ptype,
 
3656
                                         Const **prefix, Const **rest)
 
3657
{
 
3658
        Pattern_Prefix_Status result;
 
3659
 
 
3660
        switch (ptype)
 
3661
        {
 
3662
                case Pattern_Type_Like:
 
3663
                        result = like_fixed_prefix(patt, false, prefix, rest);
 
3664
                        break;
 
3665
                case Pattern_Type_Like_IC:
 
3666
                        result = like_fixed_prefix(patt, true, prefix, rest);
 
3667
                        break;
 
3668
                case Pattern_Type_Regex:
 
3669
                        result = regex_fixed_prefix(patt, false, prefix, rest);
 
3670
                        break;
 
3671
                case Pattern_Type_Regex_IC:
 
3672
                        result = regex_fixed_prefix(patt, true, prefix, rest);
 
3673
                        break;
 
3674
                default:
 
3675
                        elog(ERROR, "unrecognized ptype: %d", (int) ptype);
 
3676
                        result = Pattern_Prefix_None;           /* keep compiler quiet */
 
3677
                        break;
 
3678
        }
 
3679
        return result;
 
3680
}
 
3681
 
 
3682
/*
 
3683
 * Estimate the selectivity of a fixed prefix for a pattern match.
 
3684
 *
 
3685
 * A fixed prefix "foo" is estimated as the selectivity of the expression
 
3686
 * "variable >= 'foo' AND variable < 'fop'" (see also indxqual.c).
 
3687
 *
 
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
 
3690
 * datatype.
 
3691
 *
 
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.
 
3696
 */
 
3697
static Selectivity
 
3698
prefix_selectivity(Query *root, VariableStatData *vardata,
 
3699
                                   Oid opclass, Const *prefixcon)
 
3700
{
 
3701
        Selectivity prefixsel;
 
3702
        Oid                     cmpopr;
 
3703
        List       *cmpargs;
 
3704
        Const      *greaterstrcon;
 
3705
 
 
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),
 
3716
                                                                                                   Int32GetDatum(0)));
 
3717
 
 
3718
        /*-------
 
3719
         * If we can create a string larger than the prefix, say
 
3720
         *      "x < greaterstr".
 
3721
         *-------
 
3722
         */
 
3723
        greaterstrcon = make_greater_string(prefixcon);
 
3724
        if (greaterstrcon)
 
3725
        {
 
3726
                Selectivity topsel;
 
3727
 
 
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),
 
3738
                                                                                                        Int32GetDatum(0)));
 
3739
 
 
3740
                /*
 
3741
                 * Merge the two selectivities in the same way as for a range
 
3742
                 * query (see clauselist_selectivity()).
 
3743
                 */
 
3744
                prefixsel = topsel + prefixsel - 1.0;
 
3745
 
 
3746
                /* Adjust for double-exclusion of NULLs */
 
3747
                prefixsel += nulltestsel(root, IS_NULL, vardata->var, 0);
 
3748
 
 
3749
                /*
 
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
 
3756
                 * estimate.
 
3757
                 */
 
3758
                if (prefixsel <= 0.0)
 
3759
                {
 
3760
                        if (prefixsel < -0.01)
 
3761
                        {
 
3762
                                /*
 
3763
                                 * No data available --- use a default estimate that is
 
3764
                                 * small, but not real small.
 
3765
                                 */
 
3766
                                prefixsel = 0.005;
 
3767
                        }
 
3768
                        else
 
3769
                        {
 
3770
                                /*
 
3771
                                 * It's just roundoff error; use a small positive value
 
3772
                                 */
 
3773
                                prefixsel = 1.0e-10;
 
3774
                        }
 
3775
                }
 
3776
        }
 
3777
 
 
3778
        return prefixsel;
 
3779
}
 
3780
 
 
3781
 
 
3782
/*
 
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.
 
3785
 *
 
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.
 
3789
 */
 
3790
 
 
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
 
3794
                                                                 * end-of-string */
 
3795
#define FULL_WILDCARD_SEL 5.0
 
3796
#define PARTIAL_WILDCARD_SEL 2.0
 
3797
 
 
3798
static Selectivity
 
3799
like_selectivity(Const *patt_const, bool case_insensitive)
 
3800
{
 
3801
        Selectivity sel = 1.0;
 
3802
        int                     pos;
 
3803
        int                     start;
 
3804
        Oid                     typeid = patt_const->consttype;
 
3805
        char       *patt;
 
3806
        int                     pattlen;
 
3807
 
 
3808
        /* the right-hand const is type text or bytea */
 
3809
        Assert(typeid == BYTEAOID || typeid == TEXTOID);
 
3810
 
 
3811
        if (typeid == BYTEAOID && case_insensitive)
 
3812
                ereport(ERROR,
 
3813
                                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 
3814
                errmsg("case insensitive matching not supported on type bytea")));
 
3815
 
 
3816
        if (typeid != BYTEAOID)
 
3817
        {
 
3818
                patt = DatumGetCString(DirectFunctionCall1(textout, patt_const->constvalue));
 
3819
                pattlen = strlen(patt);
 
3820
        }
 
3821
        else
 
3822
        {
 
3823
                bytea      *bstr = DatumGetByteaP(patt_const->constvalue);
 
3824
 
 
3825
                pattlen = VARSIZE(bstr) - VARHDRSZ;
 
3826
                if (pattlen > 0)
 
3827
                {
 
3828
                        patt = (char *) palloc(pattlen);
 
3829
                        memcpy(patt, VARDATA(bstr), pattlen);
 
3830
                }
 
3831
                else
 
3832
                        patt = NULL;
 
3833
 
 
3834
                if ((Pointer) bstr != DatumGetPointer(patt_const->constvalue))
 
3835
                        pfree(bstr);
 
3836
        }
 
3837
        /* patt should never be NULL in practice */
 
3838
        Assert(patt != NULL);
 
3839
 
 
3840
        /* Skip any leading %; it's already factored into initial sel */
 
3841
        start = (*patt == '%') ? 1 : 0;
 
3842
        for (pos = start; pos < pattlen; pos++)
 
3843
        {
 
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] == '\\')
 
3850
                {
 
3851
                        /* Backslash quotes the next character */
 
3852
                        pos++;
 
3853
                        if (patt[pos] == '\0' && typeid != BYTEAOID)
 
3854
                                break;
 
3855
                        sel *= FIXED_CHAR_SEL;
 
3856
                }
 
3857
                else
 
3858
                        sel *= FIXED_CHAR_SEL;
 
3859
        }
 
3860
        /* Could get sel > 1 if multiple wildcards */
 
3861
        if (sel > 1.0)
 
3862
                sel = 1.0;
 
3863
        return sel;
 
3864
}
 
3865
 
 
3866
static Selectivity
 
3867
regex_selectivity_sub(char *patt, int pattlen, bool case_insensitive)
 
3868
{
 
3869
        Selectivity sel = 1.0;
 
3870
        int                     paren_depth = 0;
 
3871
        int                     paren_pos = 0;  /* dummy init to keep compiler quiet */
 
3872
        int                     pos;
 
3873
 
 
3874
        for (pos = 0; pos < pattlen; pos++)
 
3875
        {
 
3876
                if (patt[pos] == '(')
 
3877
                {
 
3878
                        if (paren_depth == 0)
 
3879
                                paren_pos = pos;        /* remember start of parenthesized item */
 
3880
                        paren_depth++;
 
3881
                }
 
3882
                else if (patt[pos] == ')' && paren_depth > 0)
 
3883
                {
 
3884
                        paren_depth--;
 
3885
                        if (paren_depth == 0)
 
3886
                                sel *= regex_selectivity_sub(patt + (paren_pos + 1),
 
3887
                                                                                         pos - (paren_pos + 1),
 
3888
                                                                                         case_insensitive);
 
3889
                }
 
3890
                else if (patt[pos] == '|' && paren_depth == 0)
 
3891
                {
 
3892
                        /*
 
3893
                         * If unquoted | is present at paren level 0 in pattern, we
 
3894
                         * have multiple alternatives; sum their probabilities.
 
3895
                         */
 
3896
                        sel += regex_selectivity_sub(patt + (pos + 1),
 
3897
                                                                                 pattlen - (pos + 1),
 
3898
                                                                                 case_insensitive);
 
3899
                        break;                          /* rest of pattern is now processed */
 
3900
                }
 
3901
                else if (patt[pos] == '[')
 
3902
                {
 
3903
                        bool            negclass = false;
 
3904
 
 
3905
                        if (patt[++pos] == '^')
 
3906
                        {
 
3907
                                negclass = true;
 
3908
                                pos++;
 
3909
                        }
 
3910
                        if (patt[pos] == ']')           /* ']' at start of class is not
 
3911
                                                                                 * special */
 
3912
                                pos++;
 
3913
                        while (pos < pattlen && patt[pos] != ']')
 
3914
                                pos++;
 
3915
                        if (paren_depth == 0)
 
3916
                                sel *= (negclass ? (1.0 - CHAR_RANGE_SEL) : CHAR_RANGE_SEL);
 
3917
                }
 
3918
                else if (patt[pos] == '.')
 
3919
                {
 
3920
                        if (paren_depth == 0)
 
3921
                                sel *= ANY_CHAR_SEL;
 
3922
                }
 
3923
                else if (patt[pos] == '*' ||
 
3924
                                 patt[pos] == '?' ||
 
3925
                                 patt[pos] == '+')
 
3926
                {
 
3927
                        /* Ought to be smarter about quantifiers... */
 
3928
                        if (paren_depth == 0)
 
3929
                                sel *= PARTIAL_WILDCARD_SEL;
 
3930
                }
 
3931
                else if (patt[pos] == '{')
 
3932
                {
 
3933
                        while (pos < pattlen && patt[pos] != '}')
 
3934
                                pos++;
 
3935
                        if (paren_depth == 0)
 
3936
                                sel *= PARTIAL_WILDCARD_SEL;
 
3937
                }
 
3938
                else if (patt[pos] == '\\')
 
3939
                {
 
3940
                        /* backslash quotes the next character */
 
3941
                        pos++;
 
3942
                        if (pos >= pattlen)
 
3943
                                break;
 
3944
                        if (paren_depth == 0)
 
3945
                                sel *= FIXED_CHAR_SEL;
 
3946
                }
 
3947
                else
 
3948
                {
 
3949
                        if (paren_depth == 0)
 
3950
                                sel *= FIXED_CHAR_SEL;
 
3951
                }
 
3952
        }
 
3953
        /* Could get sel > 1 if multiple wildcards */
 
3954
        if (sel > 1.0)
 
3955
                sel = 1.0;
 
3956
        return sel;
 
3957
}
 
3958
 
 
3959
static Selectivity
 
3960
regex_selectivity(Const *patt_const, bool case_insensitive)
 
3961
{
 
3962
        Selectivity sel;
 
3963
        char       *patt;
 
3964
        int                     pattlen;
 
3965
        Oid                     typeid = patt_const->consttype;
 
3966
 
 
3967
        /*
 
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.
 
3971
         */
 
3972
        if (typeid == BYTEAOID)
 
3973
                ereport(ERROR,
 
3974
                                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 
3975
                                 errmsg("regular-expression matching not supported on type bytea")));
 
3976
 
 
3977
        /* the right-hand const is type text for all of these */
 
3978
        patt = DatumGetCString(DirectFunctionCall1(textout, patt_const->constvalue));
 
3979
        pattlen = strlen(patt);
 
3980
 
 
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] != '\\'))
 
3984
        {
 
3985
                /* has trailing $ */
 
3986
                sel = regex_selectivity_sub(patt, pattlen - 1, case_insensitive);
 
3987
        }
 
3988
        else
 
3989
        {
 
3990
                /* no trailing $ */
 
3991
                sel = regex_selectivity_sub(patt, pattlen, case_insensitive);
 
3992
                sel *= FULL_WILDCARD_SEL;
 
3993
                if (sel > 1.0)
 
3994
                        sel = 1.0;
 
3995
        }
 
3996
        return sel;
 
3997
}
 
3998
 
 
3999
static Selectivity
 
4000
pattern_selectivity(Const *patt, Pattern_Type ptype)
 
4001
{
 
4002
        Selectivity result;
 
4003
 
 
4004
        switch (ptype)
 
4005
        {
 
4006
                case Pattern_Type_Like:
 
4007
                        result = like_selectivity(patt, false);
 
4008
                        break;
 
4009
                case Pattern_Type_Like_IC:
 
4010
                        result = like_selectivity(patt, true);
 
4011
                        break;
 
4012
                case Pattern_Type_Regex:
 
4013
                        result = regex_selectivity(patt, false);
 
4014
                        break;
 
4015
                case Pattern_Type_Regex_IC:
 
4016
                        result = regex_selectivity(patt, true);
 
4017
                        break;
 
4018
                default:
 
4019
                        elog(ERROR, "unrecognized ptype: %d", (int) ptype);
 
4020
                        result = 1.0;           /* keep compiler quiet */
 
4021
                        break;
 
4022
        }
 
4023
        return result;
 
4024
}
 
4025
 
 
4026
 
 
4027
/*
 
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.
 
4031
 *
 
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".
 
4035
 *
 
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".
 
4040
 *
 
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.
 
4043
 *
 
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.
 
4048
 */
 
4049
Const *
 
4050
make_greater_string(const Const *str_const)
 
4051
{
 
4052
        Oid                     datatype = str_const->consttype;
 
4053
        char       *workstr;
 
4054
        int                     len;
 
4055
 
 
4056
        /* Get the string and a modifiable copy */
 
4057
        if (datatype == NAMEOID)
 
4058
        {
 
4059
                workstr = DatumGetCString(DirectFunctionCall1(nameout,
 
4060
                                                                                                 str_const->constvalue));
 
4061
                len = strlen(workstr);
 
4062
        }
 
4063
        else if (datatype == BYTEAOID)
 
4064
        {
 
4065
                bytea      *bstr = DatumGetByteaP(str_const->constvalue);
 
4066
 
 
4067
                len = VARSIZE(bstr) - VARHDRSZ;
 
4068
                if (len > 0)
 
4069
                {
 
4070
                        workstr = (char *) palloc(len);
 
4071
                        memcpy(workstr, VARDATA(bstr), len);
 
4072
                }
 
4073
                else
 
4074
                        workstr = NULL;
 
4075
 
 
4076
                if ((Pointer) bstr != DatumGetPointer(str_const->constvalue))
 
4077
                        pfree(bstr);
 
4078
        }
 
4079
        else
 
4080
        {
 
4081
                workstr = DatumGetCString(DirectFunctionCall1(textout,
 
4082
                                                                                                 str_const->constvalue));
 
4083
                len = strlen(workstr);
 
4084
        }
 
4085
 
 
4086
        while (len > 0)
 
4087
        {
 
4088
                unsigned char *lastchar = (unsigned char *) (workstr + len - 1);
 
4089
                unsigned char savelastchar = *lastchar;
 
4090
 
 
4091
                /*
 
4092
                 * Try to generate a larger string by incrementing the last byte.
 
4093
                 */
 
4094
                while (*lastchar < (unsigned char) 255)
 
4095
                {
 
4096
                        Const      *workstr_const;
 
4097
 
 
4098
                        (*lastchar)++;
 
4099
 
 
4100
                        if (datatype != BYTEAOID)
 
4101
                        {
 
4102
                                /* do not generate invalid encoding sequences */
 
4103
                                if (!pg_verifymbstr((const unsigned char *) workstr,
 
4104
                                                                        len, true))
 
4105
                                        continue;
 
4106
                                workstr_const = string_to_const(workstr, datatype);
 
4107
                        }
 
4108
                        else
 
4109
                                workstr_const = string_to_bytea_const(workstr, len);
 
4110
 
 
4111
                        pfree(workstr);
 
4112
                        return workstr_const;
 
4113
                }
 
4114
 
 
4115
                /* restore last byte so we don't confuse pg_mbcliplen */
 
4116
                *lastchar = savelastchar;
 
4117
 
 
4118
                /*
 
4119
                 * Truncate off the last character, which might be more than 1
 
4120
                 * byte, depending on the character encoding.
 
4121
                 */
 
4122
                if (datatype != BYTEAOID && pg_database_encoding_max_length() > 1)
 
4123
                        len = pg_mbcliplen((const unsigned char *) workstr, len, len - 1);
 
4124
                else
 
4125
                        len -= 1;
 
4126
 
 
4127
                if (datatype != BYTEAOID)
 
4128
                        workstr[len] = '\0';
 
4129
        }
 
4130
 
 
4131
        /* Failed... */
 
4132
        if (workstr != NULL)
 
4133
                pfree(workstr);
 
4134
 
 
4135
        return NULL;
 
4136
}
 
4137
 
 
4138
/*
 
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.
 
4142
 */
 
4143
static Datum
 
4144
string_to_datum(const char *str, Oid datatype)
 
4145
{
 
4146
        Assert(str != NULL);
 
4147
 
 
4148
        /*
 
4149
         * We cheat a little by assuming that textin() will do for bpchar and
 
4150
         * varchar constants too...
 
4151
         */
 
4152
        if (datatype == NAMEOID)
 
4153
                return DirectFunctionCall1(namein, CStringGetDatum(str));
 
4154
        else if (datatype == BYTEAOID)
 
4155
                return DirectFunctionCall1(byteain, CStringGetDatum(str));
 
4156
        else
 
4157
                return DirectFunctionCall1(textin, CStringGetDatum(str));
 
4158
}
 
4159
 
 
4160
/*
 
4161
 * Generate a Const node of the appropriate type from a C string.
 
4162
 */
 
4163
static Const *
 
4164
string_to_const(const char *str, Oid datatype)
 
4165
{
 
4166
        Datum           conval = string_to_datum(str, datatype);
 
4167
 
 
4168
        return makeConst(datatype, ((datatype == NAMEOID) ? NAMEDATALEN : -1),
 
4169
                                         conval, false, false);
 
4170
}
 
4171
 
 
4172
/*
 
4173
 * Generate a Const node of bytea type from a binary C string and a length.
 
4174
 */
 
4175
static Const *
 
4176
string_to_bytea_const(const char *str, size_t str_len)
 
4177
{
 
4178
        bytea      *bstr = palloc(VARHDRSZ + str_len);
 
4179
        Datum           conval;
 
4180
 
 
4181
        memcpy(VARDATA(bstr), str, str_len);
 
4182
        VARATT_SIZEP(bstr) = VARHDRSZ + str_len;
 
4183
        conval = PointerGetDatum(bstr);
 
4184
 
 
4185
        return makeConst(BYTEAOID, -1, conval, false, false);
 
4186
}
 
4187
 
 
4188
/*-------------------------------------------------------------------------
 
4189
 *
 
4190
 * Index cost estimation functions
 
4191
 *
 
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.
 
4195
 *
 
4196
 *-------------------------------------------------------------------------
 
4197
 */
 
4198
 
 
4199
static void
 
4200
genericcostestimate(Query *root, RelOptInfo *rel,
 
4201
                                        IndexOptInfo *index, List *indexQuals,
 
4202
                                        Cost *indexStartupCost,
 
4203
                                        Cost *indexTotalCost,
 
4204
                                        Selectivity *indexSelectivity,
 
4205
                                        double *indexCorrelation)
 
4206
{
 
4207
        double          numIndexTuples;
 
4208
        double          numIndexPages;
 
4209
        QualCost        index_qual_cost;
 
4210
        double          qual_op_cost;
 
4211
        double          qual_arg_cost;
 
4212
        List       *selectivityQuals;
 
4213
 
 
4214
        /*
 
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
 
4227
         * someday.
 
4228
         *
 
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.)
 
4237
         */
 
4238
        if (index->indpred != NIL)
 
4239
        {
 
4240
                List       *strippedQuals;
 
4241
                List       *predExtraQuals;
 
4242
 
 
4243
                strippedQuals = get_actual_clauses(indexQuals);
 
4244
                predExtraQuals = list_difference(index->indpred, strippedQuals);
 
4245
                selectivityQuals = list_concat(predExtraQuals, indexQuals);
 
4246
        }
 
4247
        else
 
4248
                selectivityQuals = indexQuals;
 
4249
 
 
4250
        /* Estimate the fraction of main-table tuples that will be visited */
 
4251
        *indexSelectivity = clauselist_selectivity(root, selectivityQuals,
 
4252
                                                                                           rel->relid,
 
4253
                                                                                           JOIN_INNER);
 
4254
 
 
4255
        /*
 
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.
 
4260
         */
 
4261
        numIndexTuples = *indexSelectivity * rel->tuples;
 
4262
 
 
4263
        if (numIndexTuples > index->tuples)
 
4264
                numIndexTuples = index->tuples;
 
4265
 
 
4266
        /*
 
4267
         * Always estimate at least one tuple is touched, even when
 
4268
         * indexSelectivity estimate is tiny.
 
4269
         */
 
4270
        if (numIndexTuples < 1.0)
 
4271
                numIndexTuples = 1.0;
 
4272
 
 
4273
        /*
 
4274
         * Estimate the number of index pages that will be retrieved.
 
4275
         *
 
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.
 
4279
         */
 
4280
        if (index->pages > 1 && index->tuples > 0)
 
4281
        {
 
4282
                numIndexPages = (numIndexTuples / index->tuples) * (index->pages - 1);
 
4283
                numIndexPages += 1;             /* count the metapage too */
 
4284
                numIndexPages = ceil(numIndexPages);
 
4285
        }
 
4286
        else
 
4287
                numIndexPages = 1.0;
 
4288
 
 
4289
        /*
 
4290
         * Compute the index access cost.
 
4291
         *
 
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.
 
4294
         */
 
4295
        *indexTotalCost = numIndexPages;
 
4296
 
 
4297
        /*
 
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.
 
4303
         *
 
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 ...
 
4308
         */
 
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... */
 
4314
                qual_arg_cost = 0;
 
4315
        *indexStartupCost = qual_arg_cost;
 
4316
        *indexTotalCost += qual_arg_cost;
 
4317
        *indexTotalCost += numIndexTuples * (cpu_index_tuple_cost + qual_op_cost);
 
4318
 
 
4319
        /*
 
4320
         * Generic assumption about index correlation: there isn't any.
 
4321
         */
 
4322
        *indexCorrelation = 0.0;
 
4323
}
 
4324
 
 
4325
 
 
4326
Datum
 
4327
btcostestimate(PG_FUNCTION_ARGS)
 
4328
{
 
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);
 
4337
        Oid                     relid;
 
4338
        AttrNumber      colnum;
 
4339
        HeapTuple       tuple;
 
4340
 
 
4341
        genericcostestimate(root, rel, index, indexQuals,
 
4342
                                                indexStartupCost, indexTotalCost,
 
4343
                                                indexSelectivity, indexCorrelation);
 
4344
 
 
4345
        /*
 
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.)
 
4353
         */
 
4354
        if (index->indexkeys[0] != 0)
 
4355
        {
 
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];
 
4360
        }
 
4361
        else
 
4362
        {
 
4363
                /* Expression --- maybe there are stats for the index itself */
 
4364
                relid = index->indexoid;
 
4365
                colnum = 1;
 
4366
        }
 
4367
 
 
4368
        tuple = SearchSysCache(STATRELATT,
 
4369
                                                   ObjectIdGetDatum(relid),
 
4370
                                                   Int16GetDatum(colnum),
 
4371
                                                   0, 0);
 
4372
 
 
4373
        if (HeapTupleIsValid(tuple))
 
4374
        {
 
4375
                Oid                     typid;
 
4376
                int32           typmod;
 
4377
                float4     *numbers;
 
4378
                int                     nnumbers;
 
4379
 
 
4380
                /* XXX this code would break with different storage type */
 
4381
                get_atttypetypmod(relid, colnum, &typid, &typmod);
 
4382
 
 
4383
                if (get_attstatsslot(tuple, typid, typmod,
 
4384
                                                         STATISTIC_KIND_CORRELATION,
 
4385
                                                         index->ordering[0],
 
4386
                                                         NULL, NULL, &numbers, &nnumbers))
 
4387
                {
 
4388
                        double          varCorrelation;
 
4389
 
 
4390
                        Assert(nnumbers == 1);
 
4391
                        varCorrelation = numbers[0];
 
4392
 
 
4393
                        if (index->ncolumns > 1)
 
4394
                                *indexCorrelation = varCorrelation * 0.75;
 
4395
                        else
 
4396
                                *indexCorrelation = varCorrelation;
 
4397
 
 
4398
                        free_attstatsslot(typid, NULL, 0, numbers, nnumbers);
 
4399
                }
 
4400
                ReleaseSysCache(tuple);
 
4401
        }
 
4402
 
 
4403
        PG_RETURN_VOID();
 
4404
}
 
4405
 
 
4406
Datum
 
4407
rtcostestimate(PG_FUNCTION_ARGS)
 
4408
{
 
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);
 
4417
 
 
4418
        genericcostestimate(root, rel, index, indexQuals,
 
4419
                                                indexStartupCost, indexTotalCost,
 
4420
                                                indexSelectivity, indexCorrelation);
 
4421
 
 
4422
        PG_RETURN_VOID();
 
4423
}
 
4424
 
 
4425
Datum
 
4426
hashcostestimate(PG_FUNCTION_ARGS)
 
4427
{
 
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);
 
4436
 
 
4437
        genericcostestimate(root, rel, index, indexQuals,
 
4438
                                                indexStartupCost, indexTotalCost,
 
4439
                                                indexSelectivity, indexCorrelation);
 
4440
 
 
4441
        PG_RETURN_VOID();
 
4442
}
 
4443
 
 
4444
Datum
 
4445
gistcostestimate(PG_FUNCTION_ARGS)
 
4446
{
 
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);
 
4455
 
 
4456
        genericcostestimate(root, rel, index, indexQuals,
 
4457
                                                indexStartupCost, indexTotalCost,
 
4458
                                                indexSelectivity, indexCorrelation);
 
4459
 
 
4460
        PG_RETURN_VOID();
 
4461
}