Coverage Report

Created: 2026-12-01 07:00

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/postgres/src/backend/statistics/dependencies.c
Line
Count
Source
1
/*-------------------------------------------------------------------------
2
 *
3
 * dependencies.c
4
 *    POSTGRES functional dependencies
5
 *
6
 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7
 * Portions Copyright (c) 1994, Regents of the University of California
8
 *
9
 * IDENTIFICATION
10
 *    src/backend/statistics/dependencies.c
11
 *
12
 *-------------------------------------------------------------------------
13
 */
14
#include "postgres.h"
15
16
#include "access/htup_details.h"
17
#include "catalog/pg_statistic_ext.h"
18
#include "catalog/pg_statistic_ext_data.h"
19
#include "nodes/nodeFuncs.h"
20
#include "optimizer/clauses.h"
21
#include "optimizer/optimizer.h"
22
#include "parser/parsetree.h"
23
#include "statistics/extended_stats_internal.h"
24
#include "utils/fmgroids.h"
25
#include "utils/lsyscache.h"
26
#include "utils/memutils.h"
27
#include "utils/selfuncs.h"
28
#include "utils/syscache.h"
29
#include "utils/typcache.h"
30
31
/* size of the struct header fields (magic, type, ndeps) */
32
0
#define SizeOfHeader    (3 * sizeof(uint32))
33
34
/* size of a serialized dependency (degree, natts, atts) */
35
#define SizeOfItem(natts) \
36
0
  (sizeof(double) + sizeof(AttrNumber) * (1 + (natts)))
37
38
/* minimal size of a dependency (with two attributes) */
39
0
#define MinSizeOfItem SizeOfItem(2)
40
41
/* minimal size of dependencies, when all deps are minimal */
42
#define MinSizeOfItems(ndeps) \
43
0
  (SizeOfHeader + (ndeps) * MinSizeOfItem)
44
45
/*
46
 * Internal state for DependencyGenerator of dependencies. Dependencies are similar to
47
 * k-permutations of n elements, except that the order does not matter for the
48
 * first (k-1) elements. That is, (a,b=>c) and (b,a=>c) are equivalent.
49
 */
50
typedef struct DependencyGeneratorData
51
{
52
  int     k;        /* size of the dependency */
53
  int     n;        /* number of possible attributes */
54
  int     current;    /* next dependency to return (index) */
55
  AttrNumber  ndependencies;  /* number of dependencies generated */
56
  AttrNumber *dependencies; /* array of pre-generated dependencies  */
57
} DependencyGeneratorData;
58
59
typedef DependencyGeneratorData *DependencyGenerator;
60
61
static void generate_dependencies_recurse(DependencyGenerator state,
62
                      int index, AttrNumber start, AttrNumber *current);
63
static void generate_dependencies(DependencyGenerator state);
64
static DependencyGenerator DependencyGenerator_init(int n, int k);
65
static void DependencyGenerator_free(DependencyGenerator state);
66
static AttrNumber *DependencyGenerator_next(DependencyGenerator state);
67
static double dependency_degree(StatsBuildData *data, int k, AttrNumber *dependency);
68
static bool dependency_is_fully_matched(MVDependency *dependency,
69
                    Bitmapset *attnums);
70
static bool dependency_is_compatible_clause(Node *clause, Index relid,
71
                      AttrNumber *attnum);
72
static bool dependency_is_compatible_expression(Node *clause, Index relid,
73
                        List *statlist, Node **stat_expr_p);
74
static MVDependency *find_strongest_dependency(MVDependencies **dependencies,
75
                         int ndependencies, Bitmapset *attnums);
76
static Selectivity clauselist_apply_dependencies(PlannerInfo *root, List *clauses,
77
                         int varRelid, JoinType jointype,
78
                         SpecialJoinInfo *sjinfo,
79
                         MVDependency **dependencies,
80
                         int ndependencies,
81
                         AttrNumber *list_attnums,
82
                         Bitmapset **estimatedclauses);
83
84
static void
85
generate_dependencies_recurse(DependencyGenerator state, int index,
86
                AttrNumber start, AttrNumber *current)
87
0
{
88
  /*
89
   * The generator handles the first (k-1) elements differently from the
90
   * last element.
91
   */
92
0
  if (index < (state->k - 1))
93
0
  {
94
0
    AttrNumber  i;
95
96
    /*
97
     * The first (k-1) values have to be in ascending order, which we
98
     * generate recursively.
99
     */
100
101
0
    for (i = start; i < state->n; i++)
102
0
    {
103
0
      current[index] = i;
104
0
      generate_dependencies_recurse(state, (index + 1), (i + 1), current);
105
0
    }
106
0
  }
107
0
  else
108
0
  {
109
0
    int     i;
110
111
    /*
112
     * the last element is the implied value, which does not respect the
113
     * ascending order. We just need to check that the value is not in the
114
     * first (k-1) elements.
115
     */
116
117
0
    for (i = 0; i < state->n; i++)
118
0
    {
119
0
      int     j;
120
0
      bool    match = false;
121
122
0
      current[index] = i;
123
124
0
      for (j = 0; j < index; j++)
125
0
      {
126
0
        if (current[j] == i)
127
0
        {
128
0
          match = true;
129
0
          break;
130
0
        }
131
0
      }
132
133
      /*
134
       * If the value is not found in the first part of the dependency,
135
       * we're done.
136
       */
137
0
      if (!match)
138
0
      {
139
0
        state->dependencies = repalloc_array(state->dependencies,
140
0
                           AttrNumber,
141
0
                           state->k * (state->ndependencies + 1));
142
0
        memcpy(&state->dependencies[(state->k * state->ndependencies)],
143
0
             current, state->k * sizeof(AttrNumber));
144
0
        state->ndependencies++;
145
0
      }
146
0
    }
147
0
  }
148
0
}
149
150
/* generate all dependencies (k-permutations of n elements) */
151
static void
152
generate_dependencies(DependencyGenerator state)
153
0
{
154
0
  AttrNumber *current = palloc0_array(AttrNumber, state->k);
155
156
0
  generate_dependencies_recurse(state, 0, 0, current);
157
158
0
  pfree(current);
159
0
}
160
161
/*
162
 * initialize the DependencyGenerator of variations, and prebuild the variations
163
 *
164
 * This pre-builds all the variations. We could also generate them in
165
 * DependencyGenerator_next(), but this seems simpler.
166
 */
167
static DependencyGenerator
168
DependencyGenerator_init(int n, int k)
169
0
{
170
0
  DependencyGenerator state;
171
172
0
  Assert((n >= k) && (k > 0));
173
174
  /* allocate the DependencyGenerator state */
175
0
  state = palloc0_object(DependencyGeneratorData);
176
0
  state->dependencies = palloc_array(AttrNumber, k);
177
178
0
  state->ndependencies = 0;
179
0
  state->current = 0;
180
0
  state->k = k;
181
0
  state->n = n;
182
183
  /* now actually pre-generate all the variations */
184
0
  generate_dependencies(state);
185
186
0
  return state;
187
0
}
188
189
/* free the DependencyGenerator state */
190
static void
191
DependencyGenerator_free(DependencyGenerator state)
192
0
{
193
0
  pfree(state->dependencies);
194
0
  pfree(state);
195
0
}
196
197
/* generate next combination */
198
static AttrNumber *
199
DependencyGenerator_next(DependencyGenerator state)
200
0
{
201
0
  if (state->current == state->ndependencies)
202
0
    return NULL;
203
204
0
  return &state->dependencies[state->k * state->current++];
205
0
}
206
207
208
/*
209
 * validates functional dependency on the data
210
 *
211
 * An actual work horse of detecting functional dependencies. Given a variation
212
 * of k attributes, it checks that the first (k-1) are sufficient to determine
213
 * the last one.
214
 */
215
static double
216
dependency_degree(StatsBuildData *data, int k, AttrNumber *dependency)
217
0
{
218
0
  int     i,
219
0
        nitems;
220
0
  MultiSortSupport mss;
221
0
  SortItem   *items;
222
0
  AttrNumber *attnums_dep;
223
224
  /* counters valid within a group */
225
0
  int     group_size = 0;
226
0
  int     n_violations = 0;
227
228
  /* total number of rows supporting (consistent with) the dependency */
229
0
  int     n_supporting_rows = 0;
230
231
  /* Make sure we have at least two input attributes. */
232
0
  Assert(k >= 2);
233
234
  /* sort info for all attributes columns */
235
0
  mss = multi_sort_init(k);
236
237
  /*
238
   * Translate the array of indexes to regular attnums for the dependency
239
   * (we will need this to identify the columns in StatsBuildData).
240
   */
241
0
  attnums_dep = palloc_array(AttrNumber, k);
242
0
  for (i = 0; i < k; i++)
243
0
    attnums_dep[i] = data->attnums[dependency[i]];
244
245
  /*
246
   * Verify the dependency (a,b,...)->z, using a rather simple algorithm:
247
   *
248
   * (a) sort the data lexicographically
249
   *
250
   * (b) split the data into groups by first (k-1) columns
251
   *
252
   * (c) for each group count different values in the last column
253
   *
254
   * We use the column data types' default sort operators and collations;
255
   * perhaps at some point it'd be worth using column-specific collations?
256
   */
257
258
  /* prepare the sort function for the dimensions */
259
0
  for (i = 0; i < k; i++)
260
0
  {
261
0
    VacAttrStats *colstat = data->stats[dependency[i]];
262
0
    TypeCacheEntry *type;
263
264
0
    type = lookup_type_cache(colstat->attrtypid, TYPECACHE_LT_OPR);
265
0
    if (type->lt_opr == InvalidOid) /* shouldn't happen */
266
0
      elog(ERROR, "cache lookup failed for ordering operator for type %u",
267
0
         colstat->attrtypid);
268
269
    /* prepare the sort function for this dimension */
270
0
    multi_sort_add_dimension(mss, i, type->lt_opr, colstat->attrcollid);
271
0
  }
272
273
  /*
274
   * build an array of SortItem(s) sorted using the multi-sort support
275
   *
276
   * XXX This relies on all stats entries pointing to the same tuple
277
   * descriptor.  For now that assumption holds, but it might change in the
278
   * future for example if we support statistics on multiple tables.
279
   */
280
0
  items = build_sorted_items(data, &nitems, mss, k, attnums_dep);
281
282
  /*
283
   * Walk through the sorted array, split it into rows according to the
284
   * first (k-1) columns. If there's a single value in the last column, we
285
   * count the group as 'supporting' the functional dependency. Otherwise we
286
   * count it as contradicting.
287
   */
288
289
  /* start with the first row forming a group */
290
0
  group_size = 1;
291
292
  /* loop 1 beyond the end of the array so that we count the final group */
293
0
  for (i = 1; i <= nitems; i++)
294
0
  {
295
    /*
296
     * Check if the group ended, which may be either because we processed
297
     * all the items (i==nitems), or because the i-th item is not equal to
298
     * the preceding one.
299
     */
300
0
    if (i == nitems ||
301
0
      multi_sort_compare_dims(0, k - 2, &items[i - 1], &items[i], mss) != 0)
302
0
    {
303
      /*
304
       * If no violations were found in the group then track the rows of
305
       * the group as supporting the functional dependency.
306
       */
307
0
      if (n_violations == 0)
308
0
        n_supporting_rows += group_size;
309
310
      /* Reset counters for the new group */
311
0
      n_violations = 0;
312
0
      group_size = 1;
313
0
      continue;
314
0
    }
315
    /* first columns match, but the last one does not (so contradicting) */
316
0
    else if (multi_sort_compare_dim(k - 1, &items[i - 1], &items[i], mss) != 0)
317
0
      n_violations++;
318
319
0
    group_size++;
320
0
  }
321
322
  /* Compute the 'degree of validity' as (supporting/total). */
323
0
  return (n_supporting_rows * 1.0 / data->numrows);
324
0
}
325
326
/*
327
 * detects functional dependencies between groups of columns
328
 *
329
 * Generates all possible subsets of columns (variations) and computes
330
 * the degree of validity for each one. For example when creating statistics
331
 * on three columns (a,b,c) there are 9 possible dependencies
332
 *
333
 *     two columns        three columns
334
 *     -----------        -------------
335
 *     (a) -> b         (a,b) -> c
336
 *     (a) -> c         (a,c) -> b
337
 *     (b) -> a         (b,c) -> a
338
 *     (b) -> c
339
 *     (c) -> a
340
 *     (c) -> b
341
 */
342
MVDependencies *
343
statext_dependencies_build(StatsBuildData *data)
344
0
{
345
0
  int     i,
346
0
        k;
347
348
  /* result */
349
0
  MVDependencies *dependencies = NULL;
350
0
  MemoryContext cxt;
351
352
0
  Assert(data->nattnums >= 2);
353
354
  /* tracks memory allocated by dependency_degree calls */
355
0
  cxt = AllocSetContextCreate(CurrentMemoryContext,
356
0
                "dependency_degree cxt",
357
0
                ALLOCSET_DEFAULT_SIZES);
358
359
  /*
360
   * We'll try build functional dependencies starting from the smallest ones
361
   * covering just 2 columns, to the largest ones, covering all columns
362
   * included in the statistics object.  We start from the smallest ones
363
   * because we want to be able to skip already implied ones.
364
   */
365
0
  for (k = 2; k <= data->nattnums; k++)
366
0
  {
367
0
    AttrNumber *dependency; /* array with k elements */
368
369
    /* prepare a DependencyGenerator of variation */
370
0
    DependencyGenerator DependencyGenerator = DependencyGenerator_init(data->nattnums, k);
371
372
    /* generate all possible variations of k values (out of n) */
373
0
    while ((dependency = DependencyGenerator_next(DependencyGenerator)))
374
0
    {
375
0
      double    degree;
376
0
      MVDependency *d;
377
0
      MemoryContext oldcxt;
378
379
      /* release memory used by dependency degree calculation */
380
0
      oldcxt = MemoryContextSwitchTo(cxt);
381
382
      /* compute how valid the dependency seems */
383
0
      degree = dependency_degree(data, k, dependency);
384
385
0
      MemoryContextSwitchTo(oldcxt);
386
0
      MemoryContextReset(cxt);
387
388
      /*
389
       * if the dependency seems entirely invalid, don't store it
390
       */
391
0
      if (degree == 0.0)
392
0
        continue;
393
394
0
      d = (MVDependency *) palloc0(offsetof(MVDependency, attributes)
395
0
                     + k * sizeof(AttrNumber));
396
397
      /* copy the dependency (and keep the indexes into stxkeys) */
398
0
      d->degree = degree;
399
0
      d->nattributes = k;
400
0
      for (i = 0; i < k; i++)
401
0
        d->attributes[i] = data->attnums[dependency[i]];
402
403
      /* initialize the list of dependencies */
404
0
      if (dependencies == NULL)
405
0
      {
406
0
        dependencies = palloc0_object(MVDependencies);
407
408
0
        dependencies->magic = STATS_DEPS_MAGIC;
409
0
        dependencies->type = STATS_DEPS_TYPE_BASIC;
410
0
        dependencies->ndeps = 0;
411
0
      }
412
413
0
      dependencies->ndeps++;
414
0
      dependencies = (MVDependencies *) repalloc(dependencies,
415
0
                             offsetof(MVDependencies, deps)
416
0
                             + dependencies->ndeps * sizeof(MVDependency *));
417
418
0
      dependencies->deps[dependencies->ndeps - 1] = d;
419
0
    }
420
421
    /*
422
     * we're done with variations of k elements, so free the
423
     * DependencyGenerator
424
     */
425
0
    DependencyGenerator_free(DependencyGenerator);
426
0
  }
427
428
0
  MemoryContextDelete(cxt);
429
430
0
  return dependencies;
431
0
}
432
433
434
/*
435
 * Serialize list of dependencies into a bytea value.
436
 */
437
bytea *
438
statext_dependencies_serialize(MVDependencies *dependencies)
439
0
{
440
0
  bytea    *output;
441
0
  char     *tmp;
442
0
  Size    len;
443
444
  /* we need to store ndeps, with a number of attributes for each one */
445
0
  len = VARHDRSZ + SizeOfHeader;
446
447
  /* and also include space for the actual attribute numbers and degrees */
448
0
  for (uint32 i = 0; i < dependencies->ndeps; i++)
449
0
    len += SizeOfItem(dependencies->deps[i]->nattributes);
450
451
0
  output = (bytea *) palloc0(len);
452
0
  SET_VARSIZE(output, len);
453
454
0
  tmp = VARDATA(output);
455
456
  /* Store the base struct values (magic, type, ndeps) */
457
0
  memcpy(tmp, &dependencies->magic, sizeof(uint32));
458
0
  tmp += sizeof(uint32);
459
0
  memcpy(tmp, &dependencies->type, sizeof(uint32));
460
0
  tmp += sizeof(uint32);
461
0
  memcpy(tmp, &dependencies->ndeps, sizeof(uint32));
462
0
  tmp += sizeof(uint32);
463
464
  /* store number of attributes and attribute numbers for each dependency */
465
0
  for (uint32 i = 0; i < dependencies->ndeps; i++)
466
0
  {
467
0
    MVDependency *d = dependencies->deps[i];
468
469
0
    memcpy(tmp, &d->degree, sizeof(double));
470
0
    tmp += sizeof(double);
471
472
0
    memcpy(tmp, &d->nattributes, sizeof(AttrNumber));
473
0
    tmp += sizeof(AttrNumber);
474
475
0
    memcpy(tmp, d->attributes, sizeof(AttrNumber) * d->nattributes);
476
0
    tmp += sizeof(AttrNumber) * d->nattributes;
477
478
    /* protect against overflow */
479
0
    Assert(tmp <= ((char *) output + len));
480
0
  }
481
482
  /* make sure we've produced exactly the right amount of data */
483
0
  Assert(tmp == ((char *) output + len));
484
485
0
  return output;
486
0
}
487
488
/*
489
 * Reads serialized dependencies into MVDependencies structure.
490
 */
491
MVDependencies *
492
statext_dependencies_deserialize(bytea *data)
493
0
{
494
0
  Size    min_expected_size;
495
0
  MVDependencies *dependencies;
496
0
  char     *tmp;
497
498
0
  if (data == NULL)
499
0
    return NULL;
500
501
0
  if (VARSIZE_ANY_EXHDR(data) < SizeOfHeader)
502
0
    elog(ERROR, "invalid MVDependencies size %zu (expected at least %zu)",
503
0
       VARSIZE_ANY_EXHDR(data), SizeOfHeader);
504
505
  /* read the MVDependencies header */
506
0
  dependencies = palloc0_object(MVDependencies);
507
508
  /* initialize pointer to the data part (skip the varlena header) */
509
0
  tmp = VARDATA_ANY(data);
510
511
  /* read the header fields and perform basic sanity checks */
512
0
  memcpy(&dependencies->magic, tmp, sizeof(uint32));
513
0
  tmp += sizeof(uint32);
514
0
  memcpy(&dependencies->type, tmp, sizeof(uint32));
515
0
  tmp += sizeof(uint32);
516
0
  memcpy(&dependencies->ndeps, tmp, sizeof(uint32));
517
0
  tmp += sizeof(uint32);
518
519
0
  if (dependencies->magic != STATS_DEPS_MAGIC)
520
0
    elog(ERROR, "invalid dependency magic %d (expected %d)",
521
0
       dependencies->magic, STATS_DEPS_MAGIC);
522
523
0
  if (dependencies->type != STATS_DEPS_TYPE_BASIC)
524
0
    elog(ERROR, "invalid dependency type %d (expected %d)",
525
0
       dependencies->type, STATS_DEPS_TYPE_BASIC);
526
527
0
  if (dependencies->ndeps == 0)
528
0
    elog(ERROR, "invalid zero-length item array in MVDependencies");
529
530
  /* what minimum bytea size do we expect for those parameters */
531
0
  min_expected_size = MinSizeOfItems(dependencies->ndeps);
532
533
0
  if (VARSIZE_ANY_EXHDR(data) < min_expected_size)
534
0
    elog(ERROR, "invalid dependencies size %zu (expected at least %zu)",
535
0
       VARSIZE_ANY_EXHDR(data), min_expected_size);
536
537
  /* allocate space for the MCV items */
538
0
  dependencies = repalloc(dependencies, offsetof(MVDependencies, deps)
539
0
              + (dependencies->ndeps * sizeof(MVDependency *)));
540
541
0
  for (uint32 i = 0; i < dependencies->ndeps; i++)
542
0
  {
543
0
    double    degree;
544
0
    AttrNumber  k;
545
0
    MVDependency *d;
546
547
    /* degree of validity */
548
0
    memcpy(&degree, tmp, sizeof(double));
549
0
    tmp += sizeof(double);
550
551
    /* number of attributes */
552
0
    memcpy(&k, tmp, sizeof(AttrNumber));
553
0
    tmp += sizeof(AttrNumber);
554
555
    /* is the number of attributes valid? */
556
0
    Assert((k >= 2) && (k <= STATS_MAX_DIMENSIONS));
557
558
    /* now that we know the number of attributes, allocate the dependency */
559
0
    d = (MVDependency *) palloc0(offsetof(MVDependency, attributes)
560
0
                   + (k * sizeof(AttrNumber)));
561
562
0
    d->degree = degree;
563
0
    d->nattributes = k;
564
565
    /* copy attribute numbers */
566
0
    memcpy(d->attributes, tmp, sizeof(AttrNumber) * d->nattributes);
567
0
    tmp += sizeof(AttrNumber) * d->nattributes;
568
569
0
    dependencies->deps[i] = d;
570
571
    /* still within the bytea */
572
0
    Assert(tmp <= ((char *) data + VARSIZE_ANY(data)));
573
0
  }
574
575
  /* we should have consumed the whole bytea exactly */
576
0
  Assert(tmp == ((char *) data + VARSIZE_ANY(data)));
577
578
0
  return dependencies;
579
0
}
580
581
/*
582
 * Free allocations of a MVDependencies.
583
 */
584
void
585
statext_dependencies_free(MVDependencies *dependencies)
586
0
{
587
0
  for (uint32 i = 0; i < dependencies->ndeps; i++)
588
0
    pfree(dependencies->deps[i]);
589
0
  pfree(dependencies);
590
0
}
591
592
/*
593
 * Validate a set of MVDependencies against the extended statistics object
594
 * definition.
595
 *
596
 * Every MVDependencies must be checked to ensure that the attnums in the
597
 * attributes list correspond to attnums/expressions defined by the
598
 * extended statistics object.
599
 *
600
 * Positive attnums are attributes which must be found in the stxkeys, while
601
 * negative attnums correspond to an expression number, no attribute number
602
 * can be below (0 - numexprs).
603
 */
604
bool
605
statext_dependencies_validate(const MVDependencies *dependencies,
606
                const int2vector *stxkeys,
607
                int numexprs, int elevel)
608
0
{
609
0
  int     attnum_expr_lowbound = 0 - numexprs;
610
611
  /* Scan through each dependency entry */
612
0
  for (uint32 i = 0; i < dependencies->ndeps; i++)
613
0
  {
614
0
    const MVDependency *dep = dependencies->deps[i];
615
616
    /*
617
     * Cross-check each attribute in a dependency entry with the extended
618
     * stats object definition.
619
     */
620
0
    for (int j = 0; j < dep->nattributes; j++)
621
0
    {
622
0
      AttrNumber  attnum = dep->attributes[j];
623
0
      bool    ok = false;
624
625
0
      if (attnum > 0)
626
0
      {
627
        /* attribute number in stxkeys */
628
0
        for (int k = 0; k < stxkeys->dim1; k++)
629
0
        {
630
0
          if (attnum == stxkeys->values[k])
631
0
          {
632
0
            ok = true;
633
0
            break;
634
0
          }
635
0
        }
636
0
      }
637
0
      else if ((attnum < 0) && (attnum >= attnum_expr_lowbound))
638
0
      {
639
        /* attribute number for an expression */
640
0
        ok = true;
641
0
      }
642
643
0
      if (!ok)
644
0
      {
645
0
        ereport(elevel,
646
0
            (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
647
0
             errmsg("could not validate \"%s\" object: invalid attribute number %d found",
648
0
                "pg_dependencies", attnum)));
649
0
        return false;
650
0
      }
651
0
    }
652
0
  }
653
654
0
  return true;
655
0
}
656
657
/*
658
 * dependency_is_fully_matched
659
 *    checks that a functional dependency is fully matched given clauses on
660
 *    attributes (assuming the clauses are suitable equality clauses)
661
 */
662
static bool
663
dependency_is_fully_matched(MVDependency *dependency, Bitmapset *attnums)
664
0
{
665
0
  int     j;
666
667
  /*
668
   * Check that the dependency actually is fully covered by clauses. We have
669
   * to translate all attribute numbers, as those are referenced
670
   */
671
0
  for (j = 0; j < dependency->nattributes; j++)
672
0
  {
673
0
    int     attnum = dependency->attributes[j];
674
675
0
    if (!bms_is_member(attnum, attnums))
676
0
      return false;
677
0
  }
678
679
0
  return true;
680
0
}
681
682
/*
683
 * statext_dependencies_load
684
 *    Load the functional dependencies for the indicated pg_statistic_ext tuple
685
 */
686
MVDependencies *
687
statext_dependencies_load(Oid mvoid, bool inh)
688
0
{
689
0
  MVDependencies *result;
690
0
  bool    isnull;
691
0
  Datum   deps;
692
0
  HeapTuple htup;
693
694
0
  htup = SearchSysCache2(STATEXTDATASTXOID,
695
0
               ObjectIdGetDatum(mvoid),
696
0
               BoolGetDatum(inh));
697
0
  if (!HeapTupleIsValid(htup))
698
0
    elog(ERROR, "cache lookup failed for statistics object %u", mvoid);
699
700
0
  deps = SysCacheGetAttr(STATEXTDATASTXOID, htup,
701
0
               Anum_pg_statistic_ext_data_stxddependencies, &isnull);
702
0
  if (isnull)
703
0
    elog(ERROR,
704
0
       "requested statistics kind \"%c\" is not yet built for statistics object %u",
705
0
       STATS_EXT_DEPENDENCIES, mvoid);
706
707
0
  result = statext_dependencies_deserialize(DatumGetByteaPP(deps));
708
709
0
  ReleaseSysCache(htup);
710
711
0
  return result;
712
0
}
713
714
/*
715
 * dependency_is_compatible_clause
716
 *    Determines if the clause is compatible with functional dependencies
717
 *
718
 * Only clauses that have the form of equality to a pseudoconstant, or can be
719
 * interpreted that way, are currently accepted.  Furthermore the variable
720
 * part of the clause must be a simple Var belonging to the specified
721
 * relation, whose attribute number we return in *attnum on success.
722
 */
723
static bool
724
dependency_is_compatible_clause(Node *clause, Index relid, AttrNumber *attnum)
725
0
{
726
0
  Var      *var;
727
0
  Node     *clause_expr;
728
729
0
  if (IsA(clause, RestrictInfo))
730
0
  {
731
0
    RestrictInfo *rinfo = (RestrictInfo *) clause;
732
733
    /* Pseudoconstants are not interesting (they couldn't contain a Var) */
734
0
    if (rinfo->pseudoconstant)
735
0
      return false;
736
737
    /* Clauses referencing multiple, or no, varnos are incompatible */
738
0
    if (bms_membership(rinfo->clause_relids) != BMS_SINGLETON)
739
0
      return false;
740
741
0
    clause = (Node *) rinfo->clause;
742
0
  }
743
744
0
  if (is_opclause(clause))
745
0
  {
746
    /* If it's an opclause, check for Var = Const or Const = Var. */
747
0
    OpExpr     *expr = (OpExpr *) clause;
748
749
    /* Only expressions with two arguments are candidates. */
750
0
    if (list_length(expr->args) != 2)
751
0
      return false;
752
753
    /* Make sure non-selected argument is a pseudoconstant. */
754
0
    if (is_pseudo_constant_clause(lsecond(expr->args)))
755
0
      clause_expr = linitial(expr->args);
756
0
    else if (is_pseudo_constant_clause(linitial(expr->args)))
757
0
      clause_expr = lsecond(expr->args);
758
0
    else
759
0
      return false;
760
761
    /*
762
     * If it's not an "=" operator, just ignore the clause, as it's not
763
     * compatible with functional dependencies.
764
     *
765
     * This uses the function for estimating selectivity, not the operator
766
     * directly (a bit awkward, but well ...).
767
     *
768
     * XXX this is pretty dubious; probably it'd be better to check btree
769
     * or hash opclass membership, so as not to be fooled by custom
770
     * selectivity functions, and to be more consistent with decisions
771
     * elsewhere in the planner.
772
     */
773
0
    if (get_oprrest(expr->opno) != F_EQSEL)
774
0
      return false;
775
776
    /* OK to proceed with checking "var" */
777
0
  }
778
0
  else if (IsA(clause, ScalarArrayOpExpr))
779
0
  {
780
    /* If it's a scalar array operator, check for Var IN Const. */
781
0
    ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
782
783
    /*
784
     * Reject ALL() variant, we only care about ANY/IN.
785
     *
786
     * XXX Maybe we should check if all the values are the same, and allow
787
     * ALL in that case? Doesn't seem very practical, though.
788
     */
789
0
    if (!expr->useOr)
790
0
      return false;
791
792
    /* Only expressions with two arguments are candidates. */
793
0
    if (list_length(expr->args) != 2)
794
0
      return false;
795
796
    /*
797
     * We know it's always (Var IN Const), so we assume the var is the
798
     * first argument, and pseudoconstant is the second one.
799
     */
800
0
    if (!is_pseudo_constant_clause(lsecond(expr->args)))
801
0
      return false;
802
803
0
    clause_expr = linitial(expr->args);
804
805
    /*
806
     * If it's not an "=" operator, just ignore the clause, as it's not
807
     * compatible with functional dependencies. The operator is identified
808
     * simply by looking at which function it uses to estimate
809
     * selectivity. That's a bit strange, but it's what other similar
810
     * places do.
811
     */
812
0
    if (get_oprrest(expr->opno) != F_EQSEL)
813
0
      return false;
814
815
    /* OK to proceed with checking "var" */
816
0
  }
817
0
  else if (is_orclause(clause))
818
0
  {
819
0
    BoolExpr   *bool_expr = (BoolExpr *) clause;
820
0
    ListCell   *lc;
821
822
    /* start with no attribute number */
823
0
    *attnum = InvalidAttrNumber;
824
825
0
    foreach(lc, bool_expr->args)
826
0
    {
827
0
      AttrNumber  clause_attnum;
828
829
      /*
830
       * Had we found incompatible clause in the arguments, treat the
831
       * whole clause as incompatible.
832
       */
833
0
      if (!dependency_is_compatible_clause((Node *) lfirst(lc),
834
0
                         relid, &clause_attnum))
835
0
        return false;
836
837
0
      if (*attnum == InvalidAttrNumber)
838
0
        *attnum = clause_attnum;
839
840
      /* ensure all the variables are the same (same attnum) */
841
0
      if (*attnum != clause_attnum)
842
0
        return false;
843
0
    }
844
845
    /* the Var is already checked by the recursive call */
846
0
    return true;
847
0
  }
848
0
  else if (is_notclause(clause))
849
0
  {
850
    /*
851
     * "NOT x" can be interpreted as "x = false", so get the argument and
852
     * proceed with seeing if it's a suitable Var.
853
     */
854
0
    clause_expr = (Node *) get_notclausearg(clause);
855
0
  }
856
0
  else
857
0
  {
858
    /*
859
     * A boolean expression "x" can be interpreted as "x = true", so
860
     * proceed with seeing if it's a suitable Var.
861
     */
862
0
    clause_expr = clause;
863
0
  }
864
865
  /*
866
   * We may ignore any RelabelType node above the operand.  (There won't be
867
   * more than one, since eval_const_expressions has been applied already.)
868
   */
869
0
  if (IsA(clause_expr, RelabelType))
870
0
    clause_expr = (Node *) ((RelabelType *) clause_expr)->arg;
871
872
  /* We only support plain Vars for now */
873
0
  if (!IsA(clause_expr, Var))
874
0
    return false;
875
876
  /* OK, we know we have a Var */
877
0
  var = (Var *) clause_expr;
878
879
  /* Ensure Var is from the correct relation */
880
0
  if (var->varno != relid)
881
0
    return false;
882
883
  /* We also better ensure the Var is from the current level */
884
0
  if (var->varlevelsup != 0)
885
0
    return false;
886
887
  /* Also ignore system attributes (we don't allow stats on those) */
888
0
  if (!AttrNumberIsForUserDefinedAttr(var->varattno))
889
0
    return false;
890
891
0
  *attnum = var->varattno;
892
0
  return true;
893
0
}
894
895
/*
896
 * find_strongest_dependency
897
 *    find the strongest dependency on the attributes
898
 *
899
 * When applying functional dependencies, we start with the strongest
900
 * dependencies. That is, we select the dependency that:
901
 *
902
 * (a) has all attributes covered by equality clauses
903
 *
904
 * (b) has the most attributes
905
 *
906
 * (c) has the highest degree of validity
907
 *
908
 * This guarantees that we eliminate the most redundant conditions first
909
 * (see the comment in dependencies_clauselist_selectivity).
910
 */
911
static MVDependency *
912
find_strongest_dependency(MVDependencies **dependencies, int ndependencies,
913
              Bitmapset *attnums)
914
0
{
915
0
  MVDependency *strongest = NULL;
916
917
  /* number of attnums in clauses */
918
0
  int     nattnums = bms_num_members(attnums);
919
920
  /*
921
   * Iterate over the MVDependency items and find the strongest one from the
922
   * fully-matched dependencies. We do the cheap checks first, before
923
   * matching it against the attnums.
924
   */
925
0
  for (int i = 0; i < ndependencies; i++)
926
0
  {
927
0
    for (uint32 j = 0; j < dependencies[i]->ndeps; j++)
928
0
    {
929
0
      MVDependency *dependency = dependencies[i]->deps[j];
930
931
      /*
932
       * Skip dependencies referencing more attributes than available
933
       * clauses, as those can't be fully matched.
934
       */
935
0
      if (dependency->nattributes > nattnums)
936
0
        continue;
937
938
0
      if (strongest)
939
0
      {
940
        /* skip dependencies on fewer attributes than the strongest. */
941
0
        if (dependency->nattributes < strongest->nattributes)
942
0
          continue;
943
944
        /* also skip weaker dependencies when attribute count matches */
945
0
        if (strongest->nattributes == dependency->nattributes &&
946
0
          strongest->degree > dependency->degree)
947
0
          continue;
948
0
      }
949
950
      /*
951
       * this dependency is stronger, but we must still check that it's
952
       * fully matched to these attnums. We perform this check last as
953
       * it's slightly more expensive than the previous checks.
954
       */
955
0
      if (dependency_is_fully_matched(dependency, attnums))
956
0
        strongest = dependency; /* save new best match */
957
0
    }
958
0
  }
959
960
0
  return strongest;
961
0
}
962
963
/*
964
 * clauselist_apply_dependencies
965
 *    Apply the specified functional dependencies to a list of clauses and
966
 *    return the estimated selectivity of the clauses that are compatible
967
 *    with any of the given dependencies.
968
 *
969
 * This will estimate all not-already-estimated clauses that are compatible
970
 * with functional dependencies, and which have an attribute mentioned by any
971
 * of the given dependencies (either as an implying or implied attribute).
972
 *
973
 * Given (lists of) clauses on attributes (a,b) and a functional dependency
974
 * (a=>b), the per-column selectivities P(a) and P(b) are notionally combined
975
 * using the formula
976
 *
977
 *    P(a,b) = f * P(a) + (1-f) * P(a) * P(b)
978
 *
979
 * where 'f' is the degree of dependency.  This reflects the fact that we
980
 * expect a fraction f of all rows to be consistent with the dependency
981
 * (a=>b), and so have a selectivity of P(a), while the remaining rows are
982
 * treated as independent.
983
 *
984
 * In practice, we use a slightly modified version of this formula, which uses
985
 * a selectivity of Min(P(a), P(b)) for the dependent rows, since the result
986
 * should obviously not exceed either column's individual selectivity.  I.e.,
987
 * we actually combine selectivities using the formula
988
 *
989
 *    P(a,b) = f * Min(P(a), P(b)) + (1-f) * P(a) * P(b)
990
 *
991
 * This can make quite a difference if the specific values matching the
992
 * clauses are not consistent with the functional dependency.
993
 */
994
static Selectivity
995
clauselist_apply_dependencies(PlannerInfo *root, List *clauses,
996
                int varRelid, JoinType jointype,
997
                SpecialJoinInfo *sjinfo,
998
                MVDependency **dependencies, int ndependencies,
999
                AttrNumber *list_attnums,
1000
                Bitmapset **estimatedclauses)
1001
0
{
1002
0
  Bitmapset  *attnums;
1003
0
  int     i;
1004
0
  int     j;
1005
0
  int     nattrs;
1006
0
  Selectivity *attr_sel;
1007
0
  int     attidx;
1008
0
  int     listidx;
1009
0
  ListCell   *l;
1010
0
  Selectivity s1;
1011
1012
  /*
1013
   * Extract the attnums of all implying and implied attributes from all the
1014
   * given dependencies.  Each of these attributes is expected to have at
1015
   * least 1 not-already-estimated compatible clause that we will estimate
1016
   * here.
1017
   */
1018
0
  attnums = NULL;
1019
0
  for (i = 0; i < ndependencies; i++)
1020
0
  {
1021
0
    for (j = 0; j < dependencies[i]->nattributes; j++)
1022
0
    {
1023
0
      AttrNumber  attnum = dependencies[i]->attributes[j];
1024
1025
0
      attnums = bms_add_member(attnums, attnum);
1026
0
    }
1027
0
  }
1028
1029
  /*
1030
   * Compute per-column selectivity estimates for each of these attributes,
1031
   * and mark all the corresponding clauses as estimated.
1032
   */
1033
0
  nattrs = bms_num_members(attnums);
1034
0
  attr_sel = palloc_array(Selectivity, nattrs);
1035
1036
0
  attidx = 0;
1037
0
  i = -1;
1038
0
  while ((i = bms_next_member(attnums, i)) >= 0)
1039
0
  {
1040
0
    List     *attr_clauses = NIL;
1041
0
    Selectivity simple_sel;
1042
1043
0
    listidx = -1;
1044
0
    foreach(l, clauses)
1045
0
    {
1046
0
      Node     *clause = (Node *) lfirst(l);
1047
1048
0
      listidx++;
1049
0
      if (list_attnums[listidx] == i)
1050
0
      {
1051
0
        attr_clauses = lappend(attr_clauses, clause);
1052
0
        *estimatedclauses = bms_add_member(*estimatedclauses, listidx);
1053
0
      }
1054
0
    }
1055
1056
0
    simple_sel = clauselist_selectivity_ext(root, attr_clauses, varRelid,
1057
0
                        jointype, sjinfo, false);
1058
0
    attr_sel[attidx++] = simple_sel;
1059
0
  }
1060
1061
  /*
1062
   * Now combine these selectivities using the dependency information.  For
1063
   * chains of dependencies such as a -> b -> c, the b -> c dependency will
1064
   * come before the a -> b dependency in the array, so we traverse the
1065
   * array backwards to ensure such chains are computed in the right order.
1066
   *
1067
   * As explained above, pairs of selectivities are combined using the
1068
   * formula
1069
   *
1070
   * P(a,b) = f * Min(P(a), P(b)) + (1-f) * P(a) * P(b)
1071
   *
1072
   * to ensure that the combined selectivity is never greater than either
1073
   * individual selectivity.
1074
   *
1075
   * Where multiple dependencies apply (e.g., a -> b -> c), we use
1076
   * conditional probabilities to compute the overall result as follows:
1077
   *
1078
   * P(a,b,c) = P(c|a,b) * P(a,b) = P(c|a,b) * P(b|a) * P(a)
1079
   *
1080
   * so we replace the selectivities of all implied attributes with
1081
   * conditional probabilities, that are conditional on all their implying
1082
   * attributes.  The selectivities of all other non-implied attributes are
1083
   * left as they are.
1084
   */
1085
0
  for (i = ndependencies - 1; i >= 0; i--)
1086
0
  {
1087
0
    MVDependency *dependency = dependencies[i];
1088
0
    AttrNumber  attnum;
1089
0
    Selectivity s2;
1090
0
    double    f;
1091
1092
    /* Selectivity of all the implying attributes */
1093
0
    s1 = 1.0;
1094
0
    for (j = 0; j < dependency->nattributes - 1; j++)
1095
0
    {
1096
0
      attnum = dependency->attributes[j];
1097
0
      attidx = bms_member_index(attnums, attnum);
1098
0
      s1 *= attr_sel[attidx];
1099
0
    }
1100
1101
    /* Original selectivity of the implied attribute */
1102
0
    attnum = dependency->attributes[j];
1103
0
    attidx = bms_member_index(attnums, attnum);
1104
0
    s2 = attr_sel[attidx];
1105
1106
    /*
1107
     * Replace s2 with the conditional probability s2 given s1, computed
1108
     * using the formula P(b|a) = P(a,b) / P(a), which simplifies to
1109
     *
1110
     * P(b|a) = f * Min(P(a), P(b)) / P(a) + (1-f) * P(b)
1111
     *
1112
     * where P(a) = s1, the selectivity of the implying attributes, and
1113
     * P(b) = s2, the selectivity of the implied attribute.
1114
     */
1115
0
    f = dependency->degree;
1116
1117
0
    if (s1 <= s2)
1118
0
      attr_sel[attidx] = f + (1 - f) * s2;
1119
0
    else
1120
0
      attr_sel[attidx] = f * s2 / s1 + (1 - f) * s2;
1121
0
  }
1122
1123
  /*
1124
   * The overall selectivity of all the clauses on all these attributes is
1125
   * then the product of all the original (non-implied) probabilities and
1126
   * the new conditional (implied) probabilities.
1127
   */
1128
0
  s1 = 1.0;
1129
0
  for (i = 0; i < nattrs; i++)
1130
0
    s1 *= attr_sel[i];
1131
1132
0
  CLAMP_PROBABILITY(s1);
1133
1134
0
  pfree(attr_sel);
1135
0
  bms_free(attnums);
1136
1137
0
  return s1;
1138
0
}
1139
1140
/*
1141
 * dependency_is_compatible_expression
1142
 *    Determines if the expression is compatible with functional dependencies
1143
 *
1144
 * Similar to dependency_is_compatible_clause, but doesn't enforce that the
1145
 * expression is a simple Var.  On success, return the matching statistics
1146
 * expression into *stat_expr_p.
1147
 */
1148
static bool
1149
dependency_is_compatible_expression(Node *clause, Index relid, List *statlist, Node **stat_expr_p)
1150
0
{
1151
0
  ListCell   *lc,
1152
0
         *lc2;
1153
0
  Node     *clause_expr;
1154
1155
0
  if (IsA(clause, RestrictInfo))
1156
0
  {
1157
0
    RestrictInfo *rinfo = (RestrictInfo *) clause;
1158
1159
    /* Pseudoconstants are not interesting (they couldn't contain a Var) */
1160
0
    if (rinfo->pseudoconstant)
1161
0
      return false;
1162
1163
    /* Clauses referencing multiple, or no, varnos are incompatible */
1164
0
    if (bms_membership(rinfo->clause_relids) != BMS_SINGLETON)
1165
0
      return false;
1166
1167
0
    clause = (Node *) rinfo->clause;
1168
0
  }
1169
1170
0
  if (is_opclause(clause))
1171
0
  {
1172
    /* If it's an opclause, check for Var = Const or Const = Var. */
1173
0
    OpExpr     *opexpr = (OpExpr *) clause;
1174
1175
    /* Only expressions with two arguments are candidates. */
1176
0
    if (list_length(opexpr->args) != 2)
1177
0
      return false;
1178
1179
    /* Make sure non-selected argument is a pseudoconstant. */
1180
0
    if (is_pseudo_constant_clause(lsecond(opexpr->args)))
1181
0
      clause_expr = linitial(opexpr->args);
1182
0
    else if (is_pseudo_constant_clause(linitial(opexpr->args)))
1183
0
      clause_expr = lsecond(opexpr->args);
1184
0
    else
1185
0
      return false;
1186
1187
    /*
1188
     * If it's not an "=" operator, just ignore the clause, as it's not
1189
     * compatible with functional dependencies.
1190
     *
1191
     * This uses the function for estimating selectivity, not the operator
1192
     * directly (a bit awkward, but well ...).
1193
     *
1194
     * XXX this is pretty dubious; probably it'd be better to check btree
1195
     * or hash opclass membership, so as not to be fooled by custom
1196
     * selectivity functions, and to be more consistent with decisions
1197
     * elsewhere in the planner.
1198
     */
1199
0
    if (get_oprrest(opexpr->opno) != F_EQSEL)
1200
0
      return false;
1201
1202
    /* OK to proceed with checking "var" */
1203
0
  }
1204
0
  else if (IsA(clause, ScalarArrayOpExpr))
1205
0
  {
1206
    /* If it's a scalar array operator, check for Var IN Const. */
1207
0
    ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
1208
1209
    /*
1210
     * Reject ALL() variant, we only care about ANY/IN.
1211
     *
1212
     * FIXME Maybe we should check if all the values are the same, and
1213
     * allow ALL in that case? Doesn't seem very practical, though.
1214
     */
1215
0
    if (!expr->useOr)
1216
0
      return false;
1217
1218
    /* Only expressions with two arguments are candidates. */
1219
0
    if (list_length(expr->args) != 2)
1220
0
      return false;
1221
1222
    /*
1223
     * We know it's always (Var IN Const), so we assume the var is the
1224
     * first argument, and pseudoconstant is the second one.
1225
     */
1226
0
    if (!is_pseudo_constant_clause(lsecond(expr->args)))
1227
0
      return false;
1228
1229
0
    clause_expr = linitial(expr->args);
1230
1231
    /*
1232
     * If it's not an "=" operator, just ignore the clause, as it's not
1233
     * compatible with functional dependencies. The operator is identified
1234
     * simply by looking at which function it uses to estimate
1235
     * selectivity. That's a bit strange, but it's what other similar
1236
     * places do.
1237
     */
1238
0
    if (get_oprrest(expr->opno) != F_EQSEL)
1239
0
      return false;
1240
1241
    /* OK to proceed with checking "var" */
1242
0
  }
1243
0
  else if (is_orclause(clause))
1244
0
  {
1245
0
    BoolExpr   *bool_expr = (BoolExpr *) clause;
1246
1247
    /* start with no expression (we'll use the first match) */
1248
0
    *stat_expr_p = NULL;
1249
1250
0
    foreach(lc, bool_expr->args)
1251
0
    {
1252
0
      Node     *or_expr = NULL;
1253
1254
      /*
1255
       * Had we found incompatible expression in the arguments, treat
1256
       * the whole expression as incompatible.
1257
       */
1258
0
      if (!dependency_is_compatible_expression((Node *) lfirst(lc), relid,
1259
0
                           statlist, &or_expr))
1260
0
        return false;
1261
1262
0
      if (*stat_expr_p == NULL)
1263
0
        *stat_expr_p = or_expr;
1264
1265
      /* ensure all the expressions are the same */
1266
0
      if (!equal(or_expr, *stat_expr_p))
1267
0
        return false;
1268
0
    }
1269
1270
    /* the expression is already checked by the recursive call */
1271
0
    return true;
1272
0
  }
1273
0
  else if (is_notclause(clause))
1274
0
  {
1275
    /*
1276
     * "NOT x" can be interpreted as "x = false", so get the argument and
1277
     * proceed with seeing if it's a suitable Var.
1278
     */
1279
0
    clause_expr = (Node *) get_notclausearg(clause);
1280
0
  }
1281
0
  else
1282
0
  {
1283
    /*
1284
     * A boolean expression "x" can be interpreted as "x = true", so
1285
     * proceed with seeing if it's a suitable Var.
1286
     */
1287
0
    clause_expr = clause;
1288
0
  }
1289
1290
  /*
1291
   * We may ignore any RelabelType node above the operand.  (There won't be
1292
   * more than one, since eval_const_expressions has been applied already.)
1293
   */
1294
0
  if (IsA(clause_expr, RelabelType))
1295
0
    clause_expr = (Node *) ((RelabelType *) clause_expr)->arg;
1296
1297
  /*
1298
   * Search for a matching statistics expression.
1299
   */
1300
0
  foreach(lc, statlist)
1301
0
  {
1302
0
    StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc);
1303
1304
    /* ignore stats without dependencies */
1305
0
    if (info->kind != STATS_EXT_DEPENDENCIES)
1306
0
      continue;
1307
1308
0
    foreach(lc2, info->exprs)
1309
0
    {
1310
0
      Node     *stat_expr = (Node *) lfirst(lc2);
1311
1312
0
      if (equal(clause_expr, stat_expr))
1313
0
      {
1314
0
        *stat_expr_p = stat_expr;
1315
0
        return true;
1316
0
      }
1317
0
    }
1318
0
  }
1319
1320
0
  return false;
1321
0
}
1322
1323
/*
1324
 * dependencies_clauselist_selectivity
1325
 *    Return the estimated selectivity of (a subset of) the given clauses
1326
 *    using functional dependency statistics, or 1.0 if no useful functional
1327
 *    dependency statistic exists.
1328
 *
1329
 * 'estimatedclauses' is an input/output argument that gets a bit set
1330
 * corresponding to the (zero-based) list index of each clause that is included
1331
 * in the estimated selectivity.
1332
 *
1333
 * Given equality clauses on attributes (a,b) we find the strongest dependency
1334
 * between them, i.e. either (a=>b) or (b=>a). Assuming (a=>b) is the selected
1335
 * dependency, we then combine the per-clause selectivities using the formula
1336
 *
1337
 *     P(a,b) = f * P(a) + (1-f) * P(a) * P(b)
1338
 *
1339
 * where 'f' is the degree of the dependency.  (Actually we use a slightly
1340
 * modified version of this formula -- see clauselist_apply_dependencies()).
1341
 *
1342
 * With clauses on more than two attributes, the dependencies are applied
1343
 * recursively, starting with the widest/strongest dependencies. For example
1344
 * P(a,b,c) is first split like this:
1345
 *
1346
 *     P(a,b,c) = f * P(a,b) + (1-f) * P(a,b) * P(c)
1347
 *
1348
 * assuming (a,b=>c) is the strongest dependency.
1349
 */
1350
Selectivity
1351
dependencies_clauselist_selectivity(PlannerInfo *root,
1352
                  List *clauses,
1353
                  int varRelid,
1354
                  JoinType jointype,
1355
                  SpecialJoinInfo *sjinfo,
1356
                  RelOptInfo *rel,
1357
                  Bitmapset **estimatedclauses)
1358
0
{
1359
0
  Selectivity s1 = 1.0;
1360
0
  ListCell   *l;
1361
0
  Bitmapset  *clauses_attnums = NULL;
1362
0
  AttrNumber *list_attnums;
1363
0
  int     listidx;
1364
0
  MVDependencies **func_dependencies;
1365
0
  int     nfunc_dependencies;
1366
0
  int     total_ndeps;
1367
0
  MVDependency **dependencies;
1368
0
  int     ndependencies;
1369
0
  AttrNumber  attnum_offset;
1370
0
  RangeTblEntry *rte = planner_rt_fetch(rel->relid, root);
1371
1372
  /* unique expressions */
1373
0
  Node    **unique_exprs;
1374
0
  int     unique_exprs_cnt;
1375
1376
  /* check if there's any stats that might be useful for us. */
1377
0
  if (!has_stats_of_kind(rel->statlist, STATS_EXT_DEPENDENCIES))
1378
0
    return 1.0;
1379
1380
0
  list_attnums = palloc_array(AttrNumber, list_length(clauses));
1381
1382
  /*
1383
   * We allocate space as if every clause was a unique expression, although
1384
   * that's probably overkill. Some will be simple column references that
1385
   * we'll translate to attnums, and there might be duplicates. But it's
1386
   * easier and cheaper to just do one allocation than repalloc later.
1387
   */
1388
0
  unique_exprs = palloc_array(Node *, list_length(clauses));
1389
0
  unique_exprs_cnt = 0;
1390
1391
  /*
1392
   * Pre-process the clauses list to extract the attnums seen in each item.
1393
   * We need to determine if there's any clauses which will be useful for
1394
   * dependency selectivity estimations. Along the way we'll record all of
1395
   * the attnums for each clause in a list which we'll reference later so we
1396
   * don't need to repeat the same work again. We'll also keep track of all
1397
   * attnums seen.
1398
   *
1399
   * We also skip clauses that we already estimated using different types of
1400
   * statistics (we treat them as incompatible).
1401
   *
1402
   * To handle expressions, we assign them negative attnums, as if it was a
1403
   * system attribute (this is fine, as we only allow extended stats on user
1404
   * attributes). And then we offset everything by the number of
1405
   * expressions, so that we can store the values in a bitmapset.
1406
   */
1407
0
  listidx = 0;
1408
0
  foreach(l, clauses)
1409
0
  {
1410
0
    Node     *clause = (Node *) lfirst(l);
1411
0
    AttrNumber  attnum;
1412
0
    Node     *expr = NULL;
1413
1414
    /* ignore clause by default */
1415
0
    list_attnums[listidx] = InvalidAttrNumber;
1416
1417
0
    if (!bms_is_member(listidx, *estimatedclauses))
1418
0
    {
1419
      /*
1420
       * If it's a simple column reference, just extract the attnum. If
1421
       * it's an expression, assign a negative attnum as if it was a
1422
       * system attribute.
1423
       */
1424
0
      if (dependency_is_compatible_clause(clause, rel->relid, &attnum))
1425
0
      {
1426
0
        list_attnums[listidx] = attnum;
1427
0
      }
1428
0
      else if (dependency_is_compatible_expression(clause, rel->relid,
1429
0
                             rel->statlist,
1430
0
                             &expr))
1431
0
      {
1432
        /* special attnum assigned to this expression */
1433
0
        attnum = InvalidAttrNumber;
1434
1435
0
        Assert(expr != NULL);
1436
1437
        /* If the expression is duplicate, use the same attnum. */
1438
0
        for (int i = 0; i < unique_exprs_cnt; i++)
1439
0
        {
1440
0
          if (equal(unique_exprs[i], expr))
1441
0
          {
1442
            /* negative attribute number to expression */
1443
0
            attnum = -(i + 1);
1444
0
            break;
1445
0
          }
1446
0
        }
1447
1448
        /* not found in the list, so add it */
1449
0
        if (attnum == InvalidAttrNumber)
1450
0
        {
1451
0
          unique_exprs[unique_exprs_cnt++] = expr;
1452
1453
          /* after incrementing the value, to get -1, -2, ... */
1454
0
          attnum = (-unique_exprs_cnt);
1455
0
        }
1456
1457
        /* remember which attnum was assigned to this clause */
1458
0
        list_attnums[listidx] = attnum;
1459
0
      }
1460
0
    }
1461
1462
0
    listidx++;
1463
0
  }
1464
1465
0
  Assert(listidx == list_length(clauses));
1466
1467
  /*
1468
   * How much we need to offset the attnums? If there are no expressions,
1469
   * then no offset is needed. Otherwise we need to offset enough for the
1470
   * lowest value (-unique_exprs_cnt) to become 1.
1471
   */
1472
0
  if (unique_exprs_cnt > 0)
1473
0
    attnum_offset = (unique_exprs_cnt + 1);
1474
0
  else
1475
0
    attnum_offset = 0;
1476
1477
  /*
1478
   * Now that we know how many expressions there are, we can offset the
1479
   * values just enough to build the bitmapset.
1480
   */
1481
0
  for (int i = 0; i < list_length(clauses); i++)
1482
0
  {
1483
0
    AttrNumber  attnum;
1484
1485
    /* ignore incompatible or already estimated clauses */
1486
0
    if (list_attnums[i] == InvalidAttrNumber)
1487
0
      continue;
1488
1489
    /* make sure the attnum is in the expected range */
1490
0
    Assert(list_attnums[i] >= (-unique_exprs_cnt));
1491
0
    Assert(list_attnums[i] <= MaxHeapAttributeNumber);
1492
1493
    /* make sure the attnum is positive (valid AttrNumber) */
1494
0
    attnum = list_attnums[i] + attnum_offset;
1495
1496
    /*
1497
     * Remember the offset attnum, both for attributes and expressions.
1498
     * We'll pass list_attnums to clauselist_apply_dependencies, which
1499
     * uses it to identify clauses in a bitmap. We could also pass the
1500
     * offset, but this is more convenient.
1501
     */
1502
0
    list_attnums[i] = attnum;
1503
1504
0
    clauses_attnums = bms_add_member(clauses_attnums, attnum);
1505
0
  }
1506
1507
  /*
1508
   * If there's not at least two distinct attnums and expressions, then
1509
   * reject the whole list of clauses. We must return 1.0 so the calling
1510
   * function's selectivity is unaffected.
1511
   */
1512
0
  if (bms_membership(clauses_attnums) != BMS_MULTIPLE)
1513
0
  {
1514
0
    bms_free(clauses_attnums);
1515
0
    pfree(list_attnums);
1516
0
    return 1.0;
1517
0
  }
1518
1519
  /*
1520
   * Load all functional dependencies matching at least two parameters. We
1521
   * can simply consider all dependencies at once, without having to search
1522
   * for the best statistics object.
1523
   *
1524
   * To not waste cycles and memory, we deserialize dependencies only for
1525
   * statistics that match at least two attributes. The array is allocated
1526
   * with the assumption that all objects match - we could grow the array to
1527
   * make it just the right size, but it's likely wasteful anyway thanks to
1528
   * moving the freed chunks to freelists etc.
1529
   */
1530
0
  func_dependencies = palloc_array(MVDependencies *, list_length(rel->statlist));
1531
0
  nfunc_dependencies = 0;
1532
0
  total_ndeps = 0;
1533
1534
0
  foreach(l, rel->statlist)
1535
0
  {
1536
0
    StatisticExtInfo *stat = (StatisticExtInfo *) lfirst(l);
1537
0
    int     nmatched;
1538
0
    int     nexprs;
1539
0
    int     k;
1540
0
    MVDependencies *deps;
1541
1542
    /* skip statistics that are not of the correct type */
1543
0
    if (stat->kind != STATS_EXT_DEPENDENCIES)
1544
0
      continue;
1545
1546
    /* skip statistics with mismatching stxdinherit value */
1547
0
    if (stat->inherit != rte->inh)
1548
0
      continue;
1549
1550
    /*
1551
     * Count matching attributes - we have to undo the attnum offsets. The
1552
     * input attribute numbers are not offset (expressions are not
1553
     * included in stat->keys, so it's not necessary). But we need to
1554
     * offset it before checking against clauses_attnums.
1555
     */
1556
0
    nmatched = 0;
1557
0
    k = -1;
1558
0
    while ((k = bms_next_member(stat->keys, k)) >= 0)
1559
0
    {
1560
0
      AttrNumber  attnum = (AttrNumber) k;
1561
1562
      /* skip expressions */
1563
0
      if (!AttrNumberIsForUserDefinedAttr(attnum))
1564
0
        continue;
1565
1566
      /* apply the same offset as above */
1567
0
      attnum += attnum_offset;
1568
1569
0
      if (bms_is_member(attnum, clauses_attnums))
1570
0
        nmatched++;
1571
0
    }
1572
1573
    /* count matching expressions */
1574
0
    nexprs = 0;
1575
0
    for (int i = 0; i < unique_exprs_cnt; i++)
1576
0
    {
1577
0
      ListCell   *lc;
1578
1579
0
      foreach(lc, stat->exprs)
1580
0
      {
1581
0
        Node     *stat_expr = (Node *) lfirst(lc);
1582
1583
        /* try to match it */
1584
0
        if (equal(stat_expr, unique_exprs[i]))
1585
0
          nexprs++;
1586
0
      }
1587
0
    }
1588
1589
    /*
1590
     * Skip objects matching fewer than two attributes/expressions from
1591
     * clauses.
1592
     */
1593
0
    if (nmatched + nexprs < 2)
1594
0
      continue;
1595
1596
0
    deps = statext_dependencies_load(stat->statOid, rte->inh);
1597
1598
    /*
1599
     * The expressions may be represented by different attnums in the
1600
     * stats, we need to remap them to be consistent with the clauses.
1601
     * That will make the later steps (e.g. picking the strongest item and
1602
     * so on) much simpler and cheaper, because it won't need to care
1603
     * about the offset at all.
1604
     *
1605
     * When we're at it, we can ignore dependencies that are not fully
1606
     * matched by clauses (i.e. referencing attributes or expressions that
1607
     * are not in the clauses).
1608
     *
1609
     * We have to do this for all statistics, as long as there are any
1610
     * expressions - we need to shift the attnums in all dependencies.
1611
     *
1612
     * XXX Maybe we should do this always, because it also eliminates some
1613
     * of the dependencies early. It might be cheaper than having to walk
1614
     * the longer list in find_strongest_dependency later, especially as
1615
     * we need to do that repeatedly?
1616
     *
1617
     * XXX We have to do this even when there are no expressions in
1618
     * clauses, otherwise find_strongest_dependency may fail for stats
1619
     * with expressions (due to lookup of negative value in bitmap). So we
1620
     * need to at least filter out those dependencies. Maybe we could do
1621
     * it in a cheaper way (if there are no expr clauses, we can just
1622
     * discard all negative attnums without any lookups).
1623
     */
1624
0
    if (unique_exprs_cnt > 0 || stat->exprs != NIL)
1625
0
    {
1626
0
      uint32    ndeps = 0;
1627
1628
0
      for (uint32 i = 0; i < deps->ndeps; i++)
1629
0
      {
1630
0
        bool    skip = false;
1631
0
        MVDependency *dep = deps->deps[i];
1632
1633
0
        for (int j = 0; j < dep->nattributes; j++)
1634
0
        {
1635
0
          int     idx;
1636
0
          Node     *expr;
1637
0
          AttrNumber  unique_attnum = InvalidAttrNumber;
1638
0
          AttrNumber  attnum;
1639
1640
          /* undo the per-statistics offset */
1641
0
          attnum = dep->attributes[j];
1642
1643
          /*
1644
           * For regular attributes we can simply check if it
1645
           * matches any clause. If there's no matching clause, we
1646
           * can just ignore it. We need to offset the attnum
1647
           * though.
1648
           */
1649
0
          if (AttrNumberIsForUserDefinedAttr(attnum))
1650
0
          {
1651
0
            dep->attributes[j] = attnum + attnum_offset;
1652
1653
0
            if (!bms_is_member(dep->attributes[j], clauses_attnums))
1654
0
            {
1655
0
              skip = true;
1656
0
              break;
1657
0
            }
1658
1659
0
            continue;
1660
0
          }
1661
1662
          /*
1663
           * the attnum should be a valid system attnum (-1, -2,
1664
           * ...)
1665
           */
1666
0
          Assert(AttributeNumberIsValid(attnum));
1667
1668
          /*
1669
           * For expressions, we need to do two translations. First
1670
           * we have to translate the negative attnum to index in
1671
           * the list of expressions (in the statistics object).
1672
           * Then we need to see if there's a matching clause. The
1673
           * index of the unique expression determines the attnum
1674
           * (and we offset it).
1675
           */
1676
0
          idx = -(1 + attnum);
1677
1678
          /* Is the expression index is valid? */
1679
0
          Assert((idx >= 0) && (idx < list_length(stat->exprs)));
1680
1681
0
          expr = (Node *) list_nth(stat->exprs, idx);
1682
1683
          /* try to find the expression in the unique list */
1684
0
          for (int m = 0; m < unique_exprs_cnt; m++)
1685
0
          {
1686
            /*
1687
             * found a matching unique expression, use the attnum
1688
             * (derived from index of the unique expression)
1689
             */
1690
0
            if (equal(unique_exprs[m], expr))
1691
0
            {
1692
0
              unique_attnum = -(m + 1) + attnum_offset;
1693
0
              break;
1694
0
            }
1695
0
          }
1696
1697
          /*
1698
           * Found no matching expression, so we can simply skip
1699
           * this dependency, because there's no chance it will be
1700
           * fully covered.
1701
           */
1702
0
          if (unique_attnum == InvalidAttrNumber)
1703
0
          {
1704
0
            skip = true;
1705
0
            break;
1706
0
          }
1707
1708
          /* otherwise remap it to the new attnum */
1709
0
          dep->attributes[j] = unique_attnum;
1710
0
        }
1711
1712
        /* if found a matching dependency, keep it */
1713
0
        if (!skip)
1714
0
        {
1715
          /* maybe we've skipped something earlier, so move it */
1716
0
          if (ndeps != i)
1717
0
            deps->deps[ndeps] = deps->deps[i];
1718
1719
0
          ndeps++;
1720
0
        }
1721
0
      }
1722
1723
0
      deps->ndeps = ndeps;
1724
0
    }
1725
1726
    /*
1727
     * It's possible we've removed all dependencies, in which case we
1728
     * don't bother adding it to the list.
1729
     */
1730
0
    if (deps->ndeps > 0)
1731
0
    {
1732
0
      func_dependencies[nfunc_dependencies] = deps;
1733
0
      total_ndeps += deps->ndeps;
1734
0
      nfunc_dependencies++;
1735
0
    }
1736
0
  }
1737
1738
  /* if no matching stats could be found then we've nothing to do */
1739
0
  if (nfunc_dependencies == 0)
1740
0
  {
1741
0
    pfree(func_dependencies);
1742
0
    bms_free(clauses_attnums);
1743
0
    pfree(list_attnums);
1744
0
    pfree(unique_exprs);
1745
0
    return 1.0;
1746
0
  }
1747
1748
  /*
1749
   * Work out which dependencies we can apply, starting with the
1750
   * widest/strongest ones, and proceeding to smaller/weaker ones.
1751
   */
1752
0
  dependencies = palloc_array(MVDependency *, total_ndeps);
1753
0
  ndependencies = 0;
1754
1755
0
  while (true)
1756
0
  {
1757
0
    MVDependency *dependency;
1758
0
    AttrNumber  attnum;
1759
1760
    /* the widest/strongest dependency, fully matched by clauses */
1761
0
    dependency = find_strongest_dependency(func_dependencies,
1762
0
                         nfunc_dependencies,
1763
0
                         clauses_attnums);
1764
0
    if (!dependency)
1765
0
      break;
1766
1767
0
    dependencies[ndependencies++] = dependency;
1768
1769
    /* Ignore dependencies using this implied attribute in later loops */
1770
0
    attnum = dependency->attributes[dependency->nattributes - 1];
1771
0
    clauses_attnums = bms_del_member(clauses_attnums, attnum);
1772
0
  }
1773
1774
  /*
1775
   * If we found applicable dependencies, use them to estimate all
1776
   * compatible clauses on attributes that they refer to.
1777
   */
1778
0
  if (ndependencies != 0)
1779
0
    s1 = clauselist_apply_dependencies(root, clauses, varRelid, jointype,
1780
0
                       sjinfo, dependencies, ndependencies,
1781
0
                       list_attnums, estimatedclauses);
1782
1783
  /* free deserialized functional dependencies (and then the array) */
1784
0
  for (int i = 0; i < nfunc_dependencies; i++)
1785
0
    pfree(func_dependencies[i]);
1786
1787
0
  pfree(dependencies);
1788
0
  pfree(func_dependencies);
1789
0
  bms_free(clauses_attnums);
1790
0
  pfree(list_attnums);
1791
0
  pfree(unique_exprs);
1792
1793
0
  return s1;
1794
0
}