PostgreSQL Source Code git master
Loading...
Searching...
No Matches
extended_stats.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * extended_stats.c
4 * POSTGRES extended statistics
5 *
6 * Generic code supporting statistics objects created via CREATE STATISTICS.
7 *
8 *
9 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
10 * Portions Copyright (c) 1994, Regents of the University of California
11 *
12 * IDENTIFICATION
13 * src/backend/statistics/extended_stats.c
14 *
15 *-------------------------------------------------------------------------
16 */
17#include "postgres.h"
18
19#include "access/detoast.h"
20#include "access/genam.h"
21#include "access/htup_details.h"
22#include "access/table.h"
23#include "catalog/indexing.h"
26#include "commands/defrem.h"
27#include "commands/progress.h"
28#include "executor/executor.h"
29#include "miscadmin.h"
30#include "nodes/nodeFuncs.h"
31#include "optimizer/optimizer.h"
32#include "parser/parsetree.h"
33#include "pgstat.h"
38#include "utils/acl.h"
39#include "utils/array.h"
40#include "utils/attoptcache.h"
41#include "utils/builtins.h"
42#include "utils/datum.h"
43#include "utils/fmgroids.h"
44#include "utils/lsyscache.h"
45#include "utils/memutils.h"
46#include "utils/rel.h"
47#include "utils/selfuncs.h"
48#include "utils/syscache.h"
49
50/*
51 * To avoid consuming too much memory during analysis and/or too much space
52 * in the resulting pg_statistic rows, we ignore varlena datums that are wider
53 * than WIDTH_THRESHOLD (after detoasting!). This is legitimate for MCV
54 * and distinct-value calculations since a wide value is unlikely to be
55 * duplicated at all, much less be a most-common value. For the same reason,
56 * ignoring wide values will not affect our estimates of histogram bin
57 * boundaries very much.
58 */
59#define WIDTH_THRESHOLD 1024
60
61/*
62 * Used internally to refer to an individual statistics object, i.e.,
63 * a pg_statistic_ext entry.
64 */
65typedef struct StatExtEntry
66{
67 Oid statOid; /* OID of pg_statistic_ext entry */
68 char *schema; /* statistics object's schema */
69 char *name; /* statistics object's name */
70 Bitmapset *columns; /* attribute numbers covered by the object */
71 List *types; /* 'char' list of enabled statistics kinds */
72 int stattarget; /* statistics target (-1 for default) */
73 List *exprs; /* expressions */
75
76
80static void statext_store(Oid statOid, bool inh,
81 MVNDistinct *ndistinct, MVDependencies *dependencies,
82 MCVList *mcv, Datum exprs, VacAttrStats **stats);
83static int statext_compute_stattarget(int stattarget,
84 int nattrs, VacAttrStats **stats);
85
86/* Information needed to analyze a single simple expression. */
87typedef struct AnlExprData
88{
89 Node *expr; /* expression to analyze */
90 VacAttrStats *vacattrstat; /* statistics attrs to analyze */
92
94 int nexprs, HeapTuple *rows, int numrows);
96static Datum expr_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
97static AnlExprData *build_expr_data(List *exprs, int stattarget);
98
100 int numrows, HeapTuple *rows,
101 VacAttrStats **stats, int stattarget);
102
103
104/*
105 * Compute requested extended stats, using the rows sampled for the plain
106 * (single-column) stats.
107 *
108 * This fetches a list of stats types from pg_statistic_ext, computes the
109 * requested stats, and serializes them back into the catalog.
110 */
111void
113 int numrows, HeapTuple *rows,
114 int natts, VacAttrStats **vacattrstats)
115{
117 ListCell *lc;
119 MemoryContext cxt;
122
123 /* Do nothing if there are no columns to analyze. */
124 if (!natts)
125 return;
126
127 /* the list of stats has to be allocated outside the memory context */
130
131 /* memory context for building each statistics object */
133 "BuildRelationExtStatistics",
136
137 /* report this phase */
138 if (statslist != NIL)
139 {
140 const int index[] = {
143 };
144 const int64 val[] = {
147 };
148
150 }
151
152 ext_cnt = 0;
153 foreach(lc, statslist)
154 {
156 MVNDistinct *ndistinct = NULL;
157 MVDependencies *dependencies = NULL;
158 MCVList *mcv = NULL;
159 Datum exprstats = (Datum) 0;
160 VacAttrStats **stats;
161 ListCell *lc2;
162 int stattarget;
164
165 /*
166 * Check if we can build these stats based on the column analyzed. If
167 * not, report this fact (except in autovacuum) and move on.
168 */
169 stats = lookup_var_attr_stats(stat->columns, stat->exprs,
170 natts, vacattrstats);
171 if (!stats)
172 {
176 errmsg("statistics object \"%s.%s\" could not be computed for relation \"%s.%s\"",
177 stat->schema, stat->name,
178 get_namespace_name(onerel->rd_rel->relnamespace),
180 errtable(onerel)));
181 continue;
182 }
183
184 /* compute statistics target for this statistics object */
185 stattarget = statext_compute_stattarget(stat->stattarget,
186 bms_num_members(stat->columns),
187 stats);
188
189 /*
190 * Don't rebuild statistics objects with statistics target set to 0
191 * (we just leave the existing values around, just like we do for
192 * regular per-column statistics).
193 */
194 if (stattarget == 0)
195 continue;
196
197 /* evaluate expressions (if the statistics object has any) */
198 data = make_build_data(onerel, stat, numrows, rows, stats, stattarget);
199
200 /* compute statistic of each requested type */
201 foreach(lc2, stat->types)
202 {
203 char t = (char) lfirst_int(lc2);
204
205 if (t == STATS_EXT_NDISTINCT)
207 else if (t == STATS_EXT_DEPENDENCIES)
208 dependencies = statext_dependencies_build(data);
209 else if (t == STATS_EXT_MCV)
210 mcv = statext_mcv_build(data, totalrows, stattarget);
211 else if (t == STATS_EXT_EXPRESSIONS)
212 {
214 int nexprs;
215
216 /* should not happen, thanks to checks when defining stats */
217 if (!stat->exprs)
218 elog(ERROR, "requested expression stats, but there are no expressions");
219
220 exprdata = build_expr_data(stat->exprs, stattarget);
221 nexprs = list_length(stat->exprs);
222
223 compute_expr_stats(onerel, exprdata, nexprs, rows, numrows);
224
226 }
227 }
228
229 /* store the statistics in the catalog */
230 statext_store(stat->statOid, inh,
231 ndistinct, dependencies, mcv, exprstats, stats);
232
233 /* for reporting progress */
235 ++ext_cnt);
236
237 /* free the data used for building this statistics object */
239 }
240
243
245
247}
248
249/*
250 * Test if the given relation has extended statistics objects.
251 */
252bool
254{
256 SysScanDesc scan;
258 bool found;
259
261
262 /*
263 * Prepare to scan pg_statistic_ext for entries having stxrelid = this
264 * rel.
265 */
270
272 NULL, 1, &skey);
273
274 found = HeapTupleIsValid(systable_getnext(scan));
275
276 systable_endscan(scan);
277
279
280 return found;
281}
282
283/*
284 * ComputeExtStatisticsRows
285 * Compute number of rows required by extended statistics on a table.
286 *
287 * Computes number of rows we need to sample to build extended statistics on a
288 * table. This only looks at statistics we can actually build - for example
289 * when analyzing only some of the columns, this will skip statistics objects
290 * that would require additional columns.
291 *
292 * See statext_compute_stattarget for details about how we compute the
293 * statistics target for a statistics object (from the object target,
294 * attribute targets and default statistics target).
295 */
296int
298 int natts, VacAttrStats **vacattrstats)
299{
301 ListCell *lc;
302 List *lstats;
303 MemoryContext cxt;
305 int result = 0;
306
307 /* If there are no columns to analyze, just return 0. */
308 if (!natts)
309 return 0;
310
312 "ComputeExtStatisticsRows",
315
318
319 foreach(lc, lstats)
320 {
322 int stattarget;
323 VacAttrStats **stats;
324 int nattrs = bms_num_members(stat->columns);
325
326 /*
327 * Check if we can build this statistics object based on the columns
328 * analyzed. If not, ignore it (don't report anything, we'll do that
329 * during the actual build BuildRelationExtStatistics).
330 */
331 stats = lookup_var_attr_stats(stat->columns, stat->exprs,
332 natts, vacattrstats);
333
334 if (!stats)
335 continue;
336
337 /*
338 * Compute statistics target, based on what's set for the statistic
339 * object itself, and for its attributes.
340 */
341 stattarget = statext_compute_stattarget(stat->stattarget,
342 nattrs, stats);
343
344 /* Use the largest value for all statistics objects. */
345 if (stattarget > result)
346 result = stattarget;
347 }
348
350
353
354 /* compute sample size based on the statistics target */
355 return (300 * result);
356}
357
358/*
359 * statext_compute_stattarget
360 * compute statistics target for an extended statistic
361 *
362 * When computing target for extended statistics objects, we consider three
363 * places where the target may be set - the statistics object itself,
364 * attributes the statistics object is defined on, and then the default
365 * statistics target.
366 *
367 * First we look at what's set for the statistics object itself, using the
368 * ALTER STATISTICS ... SET STATISTICS command. If we find a valid value
369 * there (i.e. not -1) we're done. Otherwise we look at targets set for any
370 * of the attributes the statistic is defined on, and if there are columns
371 * with defined target, we use the maximum value. We do this mostly for
372 * backwards compatibility, because this is what we did before having
373 * statistics target for extended statistics.
374 *
375 * And finally, if we still don't have a statistics target, we use the value
376 * set in default_statistics_target.
377 */
378static int
379statext_compute_stattarget(int stattarget, int nattrs, VacAttrStats **stats)
380{
381 int i;
382
383 /*
384 * If there's statistics target set for the statistics object, use it. It
385 * may be set to 0 which disables building of that statistic.
386 */
387 if (stattarget >= 0)
388 return stattarget;
389
390 /*
391 * The target for the statistics object is set to -1, in which case we
392 * look at the maximum target set for any of the attributes the object is
393 * defined on.
394 */
395 for (i = 0; i < nattrs; i++)
396 {
397 /* keep the maximum statistics target */
398 if (stats[i]->attstattarget > stattarget)
399 stattarget = stats[i]->attstattarget;
400 }
401
402 /*
403 * If the value is still negative (so neither the statistics object nor
404 * any of the columns have custom statistics target set), use the global
405 * default target.
406 */
407 if (stattarget < 0)
408 stattarget = default_statistics_target;
409
410 /* As this point we should have a valid statistics target. */
411 Assert((stattarget >= 0) && (stattarget <= MAX_STATISTICS_TARGET));
412
413 return stattarget;
414}
415
416/*
417 * statext_is_kind_built
418 * Is this stat kind built in the given pg_statistic_ext_data tuple?
419 */
420bool
422{
424
425 switch (type)
426 {
429 break;
430
433 break;
434
435 case STATS_EXT_MCV:
437 break;
438
441 break;
442
443 default:
444 elog(ERROR, "unexpected statistics type requested: %d", type);
445 }
446
447 return !heap_attisnull(htup, attnum, NULL);
448}
449
450/*
451 * Return a list (of StatExtEntry) of statistics objects for the given relation.
452 */
453static List *
455{
456 SysScanDesc scan;
458 HeapTuple htup;
459 List *result = NIL;
460 Oid relid = RelationGetRelid(rel);
461
462 /*
463 * Prepare to scan pg_statistic_ext for entries having stxrelid = this
464 * rel.
465 */
469 ObjectIdGetDatum(relid));
470
472 NULL, 1, &skey);
473
474 while (HeapTupleIsValid(htup = systable_getnext(scan)))
475 {
476 StatExtEntry *entry;
477 Datum datum;
478 bool isnull;
479 int i;
480 ArrayType *arr;
481 char *enabled;
483 List *exprs = NIL;
484
487 entry->statOid = staForm->oid;
488 entry->schema = get_namespace_name(staForm->stxnamespace);
489 entry->name = pstrdup(NameStr(staForm->stxname));
490 for (i = 0; i < staForm->stxkeys.dim1; i++)
491 {
492 entry->columns = bms_add_member(entry->columns,
493 staForm->stxkeys.values[i]);
494 }
495
497 entry->stattarget = isnull ? -1 : DatumGetInt16(datum);
498
499 /* decode the stxkind char array into a list of chars */
502 arr = DatumGetArrayTypeP(datum);
503 if (ARR_NDIM(arr) != 1 ||
504 ARR_HASNULL(arr) ||
505 ARR_ELEMTYPE(arr) != CHAROID)
506 elog(ERROR, "stxkind is not a 1-D char array");
507 enabled = (char *) ARR_DATA_PTR(arr);
508 for (i = 0; i < ARR_DIMS(arr)[0]; i++)
509 {
510 Assert((enabled[i] == STATS_EXT_NDISTINCT) ||
511 (enabled[i] == STATS_EXT_DEPENDENCIES) ||
512 (enabled[i] == STATS_EXT_MCV) ||
513 (enabled[i] == STATS_EXT_EXPRESSIONS));
514 entry->types = lappend_int(entry->types, (int) enabled[i]);
515 }
516
517 /* decode expression (if any) */
518 datum = SysCacheGetAttr(STATEXTOID, htup,
520
521 if (!isnull)
522 {
523 char *exprsString;
524
526 exprs = (List *) stringToNode(exprsString);
527
529
530 /* Expand virtual generated columns in the expressions */
531 exprs = (List *) expand_generated_columns_in_expr((Node *) exprs, rel, 1);
532
533 /*
534 * Run the expressions through eval_const_expressions. This is not
535 * just an optimization, but is necessary, because the planner
536 * will be comparing them to similarly-processed qual clauses, and
537 * may fail to detect valid matches without this. We must not use
538 * canonicalize_qual, however, since these aren't qual
539 * expressions.
540 */
541 exprs = (List *) eval_const_expressions(NULL, (Node *) exprs);
542
543 /* May as well fix opfuncids too */
544 fix_opfuncids((Node *) exprs);
545 }
546
547 entry->exprs = exprs;
548
549 result = lappend(result, entry);
550 }
551
552 systable_endscan(scan);
553
554 return result;
555}
556
557/*
558 * examine_attribute -- pre-analysis of a single column
559 *
560 * Determine whether the column is analyzable; if so, create and initialize
561 * a VacAttrStats struct for it. If not, return NULL.
562 */
563static VacAttrStats *
565{
567 VacAttrStats *stats;
568 int i;
569 bool ok;
570
571 /*
572 * Create the VacAttrStats struct.
573 */
575 stats->attstattarget = -1;
576
577 /*
578 * When analyzing an expression, believe the expression tree's type not
579 * the column datatype --- the latter might be the opckeytype storage type
580 * of the opclass, which is not interesting for our purposes. (Note: if
581 * we did anything with non-expression statistics columns, we'd need to
582 * figure out where to get the correct type info from, but for now that's
583 * not a problem.) It's not clear whether anyone will care about the
584 * typmod, but we store that too just in case.
585 */
586 stats->attrtypid = exprType(expr);
587 stats->attrtypmod = exprTypmod(expr);
588 stats->attrcollid = exprCollation(expr);
589
593 elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
595
596 /*
597 * We don't actually analyze individual attributes, so no need to set the
598 * memory context.
599 */
600 stats->anl_context = NULL;
602
603 /*
604 * The fields describing the stats->stavalues[n] element types default to
605 * the type of the data being analyzed, but the type-specific typanalyze
606 * function can change them if it wants to store something else.
607 */
608 for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
609 {
610 stats->statypid[i] = stats->attrtypid;
611 stats->statyplen[i] = stats->attrtype->typlen;
612 stats->statypbyval[i] = stats->attrtype->typbyval;
613 stats->statypalign[i] = stats->attrtype->typalign;
614 }
615
616 /*
617 * Call the type-specific typanalyze function. If none is specified, use
618 * std_typanalyze().
619 */
620 if (OidIsValid(stats->attrtype->typanalyze))
621 ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
622 PointerGetDatum(stats)));
623 else
624 ok = std_typanalyze(stats);
625
626 if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
627 {
629 pfree(stats);
630 return NULL;
631 }
632
633 return stats;
634}
635
636/*
637 * examine_expression -- pre-analysis of a single expression
638 *
639 * Determine whether the expression is analyzable; if so, create and initialize
640 * a VacAttrStats struct for it. If not, return NULL.
641 */
642static VacAttrStats *
643examine_expression(Node *expr, int stattarget)
644{
646 VacAttrStats *stats;
647 int i;
648 bool ok;
649
650 Assert(expr != NULL);
651
652 /*
653 * Create the VacAttrStats struct.
654 */
656
657 /*
658 * We can't have statistics target specified for the expression, so we
659 * could use either the default_statistics_target, or the target computed
660 * for the extended statistics. The second option seems more reasonable.
661 */
662 stats->attstattarget = stattarget;
663
664 /*
665 * When analyzing an expression, believe the expression tree's type.
666 */
667 stats->attrtypid = exprType(expr);
668 stats->attrtypmod = exprTypmod(expr);
669
670 /*
671 * We don't allow collation to be specified in CREATE STATISTICS, so we
672 * have to use the collation specified for the expression. It's possible
673 * to specify the collation in the expression "(col COLLATE "en_US")" in
674 * which case exprCollation() does the right thing.
675 */
676 stats->attrcollid = exprCollation(expr);
677
681 elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
682
684 stats->anl_context = CurrentMemoryContext; /* XXX should be using
685 * something else? */
687
688 /*
689 * The fields describing the stats->stavalues[n] element types default to
690 * the type of the data being analyzed, but the type-specific typanalyze
691 * function can change them if it wants to store something else.
692 */
693 for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
694 {
695 stats->statypid[i] = stats->attrtypid;
696 stats->statyplen[i] = stats->attrtype->typlen;
697 stats->statypbyval[i] = stats->attrtype->typbyval;
698 stats->statypalign[i] = stats->attrtype->typalign;
699 }
700
701 /*
702 * Call the type-specific typanalyze function. If none is specified, use
703 * std_typanalyze().
704 */
705 if (OidIsValid(stats->attrtype->typanalyze))
706 ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
707 PointerGetDatum(stats)));
708 else
709 ok = std_typanalyze(stats);
710
711 if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
712 {
714 pfree(stats);
715 return NULL;
716 }
717
718 return stats;
719}
720
721/*
722 * Using 'vacatts' of size 'nvacatts' as input data, return a newly-built
723 * VacAttrStats array which includes only the items corresponding to
724 * attributes indicated by 'attrs'. If we don't have all of the per-column
725 * stats available to compute the extended stats, then we return NULL to
726 * indicate to the caller that the stats should not be built.
727 */
728static VacAttrStats **
731{
732 int i = 0;
733 int x = -1;
734 int natts;
735 VacAttrStats **stats;
736 ListCell *lc;
737
738 natts = bms_num_members(attrs) + list_length(exprs);
739
740 stats = (VacAttrStats **) palloc(natts * sizeof(VacAttrStats *));
741
742 /* lookup VacAttrStats info for the requested columns (same attnum) */
743 while ((x = bms_next_member(attrs, x)) >= 0)
744 {
745 int j;
746
747 stats[i] = NULL;
748 for (j = 0; j < nvacatts; j++)
749 {
750 if (x == vacatts[j]->tupattnum)
751 {
752 stats[i] = vacatts[j];
753 break;
754 }
755 }
756
757 if (!stats[i])
758 {
759 /*
760 * Looks like stats were not gathered for one of the columns
761 * required. We'll be unable to build the extended stats without
762 * this column.
763 */
764 pfree(stats);
765 return NULL;
766 }
767
768 i++;
769 }
770
771 /* also add info for expressions */
772 foreach(lc, exprs)
773 {
774 Node *expr = (Node *) lfirst(lc);
775
776 stats[i] = examine_attribute(expr);
777
778 /*
779 * If the expression has been found as non-analyzable, give up. We
780 * will not be able to build extended stats with it.
781 */
782 if (stats[i] == NULL)
783 {
784 pfree(stats);
785 return NULL;
786 }
787
788 /*
789 * XXX We need tuple descriptor later, and we just grab it from
790 * stats[0]->tupDesc (see e.g. statext_mcv_build). But as coded
791 * examine_attribute does not set that, so just grab it from the first
792 * vacatts element.
793 */
794 stats[i]->tupDesc = vacatts[0]->tupDesc;
795
796 i++;
797 }
798
799 return stats;
800}
801
802/*
803 * statext_store
804 * Serializes the statistics and stores them into the pg_statistic_ext_data
805 * tuple.
806 */
807static void
808statext_store(Oid statOid, bool inh,
809 MVNDistinct *ndistinct, MVDependencies *dependencies,
810 MCVList *mcv, Datum exprs, VacAttrStats **stats)
811{
815 bool nulls[Natts_pg_statistic_ext_data];
816
818
819 memset(nulls, true, sizeof(nulls));
820 memset(values, 0, sizeof(values));
821
822 /* basic info */
824 nulls[Anum_pg_statistic_ext_data_stxoid - 1] = false;
825
828
829 /*
830 * Construct a new pg_statistic_ext_data tuple, replacing the calculated
831 * stats.
832 */
833 if (ndistinct != NULL)
834 {
836
839 }
840
841 if (dependencies != NULL)
842 {
844
847 }
848 if (mcv != NULL)
849 {
850 bytea *data = statext_mcv_serialize(mcv, stats);
851
854 }
855 if (exprs != (Datum) 0)
856 {
857 nulls[Anum_pg_statistic_ext_data_stxdexpr - 1] = false;
859 }
860
861 /*
862 * Delete the old tuple if it exists, and insert a new one. It's easier
863 * than trying to update or insert, based on various conditions.
864 */
865 RemoveStatisticsDataById(statOid, inh);
866
867 /* form and insert a new tuple */
870
872
874}
875
876/* initialize multi-dimensional sort */
879{
881
882 Assert(ndims >= 2);
883
885 + sizeof(SortSupportData) * ndims);
886
887 mss->ndims = ndims;
888
889 return mss;
890}
891
892/*
893 * Prepare sort support info using the given sort operator and collation
894 * at the position 'sortdim'
895 */
896void
898 Oid oper, Oid collation)
899{
900 SortSupport ssup = &mss->ssup[sortdim];
901
903 ssup->ssup_collation = collation;
904 ssup->ssup_nulls_first = false;
905
907}
908
909/* compare all the dimensions in the selected order */
910int
911multi_sort_compare(const void *a, const void *b, void *arg)
912{
914 const SortItem *ia = a;
915 const SortItem *ib = b;
916 int i;
917
918 for (i = 0; i < mss->ndims; i++)
919 {
920 int compare;
921
922 compare = ApplySortComparator(ia->values[i], ia->isnull[i],
923 ib->values[i], ib->isnull[i],
924 &mss->ssup[i]);
925
926 if (compare != 0)
927 return compare;
928 }
929
930 /* equal by default */
931 return 0;
932}
933
934/* compare selected dimension */
935int
938{
939 return ApplySortComparator(a->values[dim], a->isnull[dim],
940 b->values[dim], b->isnull[dim],
941 &mss->ssup[dim]);
942}
943
944int
946 const SortItem *a, const SortItem *b,
948{
949 int dim;
950
951 for (dim = start; dim <= end; dim++)
952 {
953 int r = ApplySortComparator(a->values[dim], a->isnull[dim],
954 b->values[dim], b->isnull[dim],
955 &mss->ssup[dim]);
956
957 if (r != 0)
958 return r;
959 }
960
961 return 0;
962}
963
964int
965compare_scalars_simple(const void *a, const void *b, void *arg)
966{
967 return compare_datums_simple(*(const Datum *) a,
968 *(const Datum *) b,
969 (SortSupport) arg);
970}
971
972int
974{
975 return ApplySortComparator(a, false, b, false, ssup);
976}
977
978/*
979 * build_attnums_array
980 * Transforms a bitmap into an array of AttrNumber values.
981 *
982 * This is used for extended statistics only, so all the attributes must be
983 * user-defined. That means offsetting by FirstLowInvalidHeapAttributeNumber
984 * is not necessary here (and when querying the bitmap).
985 */
988{
989 int i,
990 j;
991 AttrNumber *attnums;
992 int num = bms_num_members(attrs);
993
994 if (numattrs)
995 *numattrs = num;
996
997 /* build attnums from the bitmapset */
998 attnums = palloc_array(AttrNumber, num);
999 i = 0;
1000 j = -1;
1001 while ((j = bms_next_member(attrs, j)) >= 0)
1002 {
1003 int attnum = (j - nexprs);
1004
1005 /*
1006 * Make sure the bitmap contains only user-defined attributes. As
1007 * bitmaps can't contain negative values, this can be violated in two
1008 * ways. Firstly, the bitmap might contain 0 as a member, and secondly
1009 * the integer value might be larger than MaxAttrNumber.
1010 */
1013 Assert(attnum >= (-nexprs));
1014
1015 attnums[i++] = (AttrNumber) attnum;
1016
1017 /* protect against overflows */
1018 Assert(i <= num);
1019 }
1020
1021 return attnums;
1022}
1023
1024/*
1025 * build_sorted_items
1026 * build a sorted array of SortItem with values from rows
1027 *
1028 * Note: All the memory is allocated in a single chunk, so that the caller
1029 * can simply pfree the return value to release all of it.
1030 */
1031SortItem *
1034 int numattrs, AttrNumber *attnums)
1035{
1036 int i,
1037 j,
1038 nrows;
1039 int nvalues = data->numrows * numattrs;
1040 Size len;
1041 SortItem *items;
1042 Datum *values;
1043 bool *isnull;
1044 char *ptr;
1045 int *typlen;
1046
1047 /* Compute the total amount of memory we need (both items and values). */
1048 len = MAXALIGN(data->numrows * sizeof(SortItem)) +
1049 nvalues * (sizeof(Datum) + sizeof(bool));
1050
1051 /* Allocate the memory and split it into the pieces. */
1052 ptr = palloc0(len);
1053
1054 /* items to sort */
1055 items = (SortItem *) ptr;
1056 /* MAXALIGN ensures that the following Datums are suitably aligned */
1057 ptr += MAXALIGN(data->numrows * sizeof(SortItem));
1058
1059 /* values and null flags */
1060 values = (Datum *) ptr;
1061 ptr += nvalues * sizeof(Datum);
1062
1063 isnull = (bool *) ptr;
1064 ptr += nvalues * sizeof(bool);
1065
1066 /* make sure we consumed the whole buffer exactly */
1067 Assert((ptr - (char *) items) == len);
1068
1069 /* fix the pointers to Datum and bool arrays */
1070 nrows = 0;
1071 for (i = 0; i < data->numrows; i++)
1072 {
1073 items[nrows].values = &values[nrows * numattrs];
1074 items[nrows].isnull = &isnull[nrows * numattrs];
1075
1076 nrows++;
1077 }
1078
1079 /* build a local cache of typlen for all attributes */
1080 typlen = palloc_array(int, data->nattnums);
1081 for (i = 0; i < data->nattnums; i++)
1082 typlen[i] = get_typlen(data->stats[i]->attrtypid);
1083
1084 nrows = 0;
1085 for (i = 0; i < data->numrows; i++)
1086 {
1087 bool toowide = false;
1088
1089 /* load the values/null flags from sample rows */
1090 for (j = 0; j < numattrs; j++)
1091 {
1092 Datum value;
1093 bool isnull;
1094 int attlen;
1095 AttrNumber attnum = attnums[j];
1096
1097 int idx;
1098
1099 /* match attnum to the pre-calculated data */
1100 for (idx = 0; idx < data->nattnums; idx++)
1101 {
1102 if (attnum == data->attnums[idx])
1103 break;
1104 }
1105
1106 Assert(idx < data->nattnums);
1107
1108 value = data->values[idx][i];
1109 isnull = data->nulls[idx][i];
1110 attlen = typlen[idx];
1111
1112 /*
1113 * If this is a varlena value, check if it's too wide and if yes
1114 * then skip the whole item. Otherwise detoast the value.
1115 *
1116 * XXX It may happen that we've already detoasted some preceding
1117 * values for the current item. We don't bother to cleanup those
1118 * on the assumption that those are small (below WIDTH_THRESHOLD)
1119 * and will be discarded at the end of analyze.
1120 */
1121 if ((!isnull) && (attlen == -1))
1122 {
1124 {
1125 toowide = true;
1126 break;
1127 }
1128
1130 }
1131
1132 items[nrows].values[j] = value;
1133 items[nrows].isnull[j] = isnull;
1134 }
1135
1136 if (toowide)
1137 continue;
1138
1139 nrows++;
1140 }
1141
1142 /* store the actual number of items (ignoring the too-wide ones) */
1143 *nitems = nrows;
1144
1145 /* all items were too wide */
1146 if (nrows == 0)
1147 {
1148 /* everything is allocated as a single chunk */
1149 pfree(items);
1150 return NULL;
1151 }
1152
1153 /* do the sort, using the multi-sort */
1154 qsort_interruptible(items, nrows, sizeof(SortItem),
1156
1157 return items;
1158}
1159
1160/*
1161 * has_stats_of_kind
1162 * Check whether the list contains statistic of a given kind
1163 */
1164bool
1166{
1167 ListCell *l;
1168
1169 foreach(l, stats)
1170 {
1172
1173 if (stat->kind == requiredkind)
1174 return true;
1175 }
1176
1177 return false;
1178}
1179
1180/*
1181 * stat_find_expression
1182 * Search for an expression in statistics object's list of expressions.
1183 *
1184 * Returns the index of the expression in the statistics object's list of
1185 * expressions, or -1 if not found.
1186 */
1187static int
1189{
1190 ListCell *lc;
1191 int idx;
1192
1193 idx = 0;
1194 foreach(lc, stat->exprs)
1195 {
1196 Node *stat_expr = (Node *) lfirst(lc);
1197
1198 if (equal(stat_expr, expr))
1199 return idx;
1200 idx++;
1201 }
1202
1203 /* Expression not found */
1204 return -1;
1205}
1206
1207/*
1208 * stat_covers_expressions
1209 * Test whether a statistics object covers all expressions in a list.
1210 *
1211 * Returns true if all expressions are covered. If expr_idxs is non-NULL, it
1212 * is populated with the indexes of the expressions found.
1213 */
1214static bool
1217{
1218 ListCell *lc;
1219
1220 foreach(lc, exprs)
1221 {
1222 Node *expr = (Node *) lfirst(lc);
1223 int expr_idx;
1224
1226 if (expr_idx == -1)
1227 return false;
1228
1229 if (expr_idxs != NULL)
1231 }
1232
1233 /* If we reach here, all expressions are covered */
1234 return true;
1235}
1236
1237/*
1238 * choose_best_statistics
1239 * Look for and return statistics with the specified 'requiredkind' which
1240 * have keys that match at least two of the given attnums. Return NULL if
1241 * there's no match.
1242 *
1243 * The current selection criteria is very simple - we choose the statistics
1244 * object referencing the most attributes in covered (and still unestimated
1245 * clauses), breaking ties in favor of objects with fewer keys overall.
1246 *
1247 * The clause_attnums is an array of bitmaps, storing attnums for individual
1248 * clauses. A NULL element means the clause is either incompatible or already
1249 * estimated.
1250 *
1251 * XXX If multiple statistics objects tie on both criteria, then which object
1252 * is chosen depends on the order that they appear in the stats list. Perhaps
1253 * further tiebreakers are needed.
1254 */
1258 int nclauses)
1259{
1260 ListCell *lc;
1262 int best_num_matched = 2; /* goal #1: maximize */
1263 int best_match_keys = (STATS_MAX_DIMENSIONS + 1); /* goal #2: minimize */
1264
1265 foreach(lc, stats)
1266 {
1267 int i;
1271 int num_matched;
1272 int numkeys;
1273
1274 /* skip statistics that are not of the correct type */
1275 if (info->kind != requiredkind)
1276 continue;
1277
1278 /* skip statistics with mismatching inheritance flag */
1279 if (info->inherit != inh)
1280 continue;
1281
1282 /*
1283 * Collect attributes and expressions in remaining (unestimated)
1284 * clauses fully covered by this statistic object.
1285 *
1286 * We know already estimated clauses have both clause_attnums and
1287 * clause_exprs set to NULL. We leave the pointers NULL if already
1288 * estimated, or we reset them to NULL after estimating the clause.
1289 */
1290 for (i = 0; i < nclauses; i++)
1291 {
1293
1294 /* ignore incompatible/estimated clauses */
1295 if (!clause_attnums[i] && !clause_exprs[i])
1296 continue;
1297
1298 /* ignore clauses that are not covered by this object */
1299 if (!bms_is_subset(clause_attnums[i], info->keys) ||
1301 continue;
1302
1303 /* record attnums and indexes of expressions covered */
1306 }
1307
1309
1312
1313 /*
1314 * save the actual number of keys in the stats so that we can choose
1315 * the narrowest stats with the most matching keys.
1316 */
1317 numkeys = bms_num_members(info->keys) + list_length(info->exprs);
1318
1319 /*
1320 * Use this object when it increases the number of matched attributes
1321 * and expressions or when it matches the same number of attributes
1322 * and expressions but these stats have fewer keys than any previous
1323 * match.
1324 */
1327 {
1328 best_match = info;
1330 best_match_keys = numkeys;
1331 }
1332 }
1333
1334 return best_match;
1335}
1336
1337/*
1338 * statext_is_compatible_clause_internal
1339 * Determines if the clause is compatible with MCV lists.
1340 *
1341 * To be compatible, the given clause must be a combination of supported
1342 * clauses built from Vars or sub-expressions (where a sub-expression is
1343 * something that exactly matches an expression found in statistics objects).
1344 * This function recursively examines the clause and extracts any
1345 * sub-expressions that will need to be matched against statistics.
1346 *
1347 * Currently, we only support the following types of clauses:
1348 *
1349 * (a) OpExprs of the form (Var/Expr op Const), or (Const op Var/Expr), where
1350 * the op is one of ("=", "<", ">", ">=", "<=")
1351 *
1352 * (b) (Var/Expr IS [NOT] NULL)
1353 *
1354 * (c) combinations using AND/OR/NOT
1355 *
1356 * (d) ScalarArrayOpExprs of the form (Var/Expr op ANY (Const)) or
1357 * (Var/Expr op ALL (Const))
1358 *
1359 * In the future, the range of supported clauses may be expanded to more
1360 * complex cases, for example (Var op Var).
1361 *
1362 * Arguments:
1363 * clause: (sub)clause to be inspected (bare clause, not a RestrictInfo)
1364 * relid: rel that all Vars in clause must belong to
1365 * *attnums: input/output parameter collecting attribute numbers of all
1366 * mentioned Vars. Note that we do not offset the attribute numbers,
1367 * so we can't cope with system columns.
1368 * *exprs: input/output parameter collecting primitive subclauses within
1369 * the clause tree
1370 * *leakproof: input/output parameter recording the leakproofness of the
1371 * clause tree. This should be true initially, and will be set to false
1372 * if any operator function used in an OpExpr is not leakproof.
1373 *
1374 * Returns false if there is something we definitively can't handle.
1375 * On true return, we can proceed to match the *exprs against statistics.
1376 */
1377static bool
1379 Index relid, Bitmapset **attnums,
1380 List **exprs, bool *leakproof)
1381{
1382 /* Look inside any binary-compatible relabeling (as in examine_variable) */
1383 if (IsA(clause, RelabelType))
1384 clause = (Node *) ((RelabelType *) clause)->arg;
1385
1386 /* plain Var references (boolean Vars or recursive checks) */
1387 if (IsA(clause, Var))
1388 {
1389 Var *var = (Var *) clause;
1390
1391 /* Ensure var is from the correct relation */
1392 if (var->varno != relid)
1393 return false;
1394
1395 /* we also better ensure the Var is from the current level */
1396 if (var->varlevelsup > 0)
1397 return false;
1398
1399 /*
1400 * Also reject system attributes and whole-row Vars (we don't allow
1401 * stats on those).
1402 */
1404 return false;
1405
1406 /* OK, record the attnum for later permissions checks. */
1407 *attnums = bms_add_member(*attnums, var->varattno);
1408
1409 return true;
1410 }
1411
1412 /* (Var/Expr op Const) or (Const op Var/Expr) */
1413 if (is_opclause(clause))
1414 {
1415 OpExpr *expr = (OpExpr *) clause;
1417
1418 /* Only expressions with two arguments are considered compatible. */
1419 if (list_length(expr->args) != 2)
1420 return false;
1421
1422 /* Check if the expression has the right shape */
1424 return false;
1425
1426 /*
1427 * If it's not one of the supported operators ("=", "<", ">", etc.),
1428 * just ignore the clause, as it's not compatible with MCV lists.
1429 *
1430 * This uses the function for estimating selectivity, not the operator
1431 * directly (a bit awkward, but well ...).
1432 */
1433 switch (get_oprrest(expr->opno))
1434 {
1435 case F_EQSEL:
1436 case F_NEQSEL:
1437 case F_SCALARLTSEL:
1438 case F_SCALARLESEL:
1439 case F_SCALARGTSEL:
1440 case F_SCALARGESEL:
1441 /* supported, will continue with inspection of the Var/Expr */
1442 break;
1443
1444 default:
1445 /* other estimators are considered unknown/unsupported */
1446 return false;
1447 }
1448
1449 /* Check if the operator is leakproof */
1450 if (*leakproof)
1452
1453 /* Check (Var op Const) or (Const op Var) clauses by recursing. */
1454 if (IsA(clause_expr, Var))
1456 relid, attnums,
1457 exprs, leakproof);
1458
1459 /* Otherwise we have (Expr op Const) or (Const op Expr). */
1460 *exprs = lappend(*exprs, clause_expr);
1461 return true;
1462 }
1463
1464 /* Var/Expr IN Array */
1465 if (IsA(clause, ScalarArrayOpExpr))
1466 {
1467 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
1469 bool expronleft;
1470
1471 /* Only expressions with two arguments are considered compatible. */
1472 if (list_length(expr->args) != 2)
1473 return false;
1474
1475 /* Check if the expression has the right shape (one Var, one Const) */
1477 return false;
1478
1479 /* We only support Var on left, Const on right */
1480 if (!expronleft)
1481 return false;
1482
1483 /*
1484 * If it's not one of the supported operators ("=", "<", ">", etc.),
1485 * just ignore the clause, as it's not compatible with MCV lists.
1486 *
1487 * This uses the function for estimating selectivity, not the operator
1488 * directly (a bit awkward, but well ...).
1489 */
1490 switch (get_oprrest(expr->opno))
1491 {
1492 case F_EQSEL:
1493 case F_NEQSEL:
1494 case F_SCALARLTSEL:
1495 case F_SCALARLESEL:
1496 case F_SCALARGTSEL:
1497 case F_SCALARGESEL:
1498 /* supported, will continue with inspection of the Var/Expr */
1499 break;
1500
1501 default:
1502 /* other estimators are considered unknown/unsupported */
1503 return false;
1504 }
1505
1506 /* Check if the operator is leakproof */
1507 if (*leakproof)
1509
1510 /* Check Var IN Array clauses by recursing. */
1511 if (IsA(clause_expr, Var))
1513 relid, attnums,
1514 exprs, leakproof);
1515
1516 /* Otherwise we have Expr IN Array. */
1517 *exprs = lappend(*exprs, clause_expr);
1518 return true;
1519 }
1520
1521 /* AND/OR/NOT clause */
1522 if (is_andclause(clause) ||
1523 is_orclause(clause) ||
1524 is_notclause(clause))
1525 {
1526 /*
1527 * AND/OR/NOT-clauses are supported if all sub-clauses are supported
1528 *
1529 * Perhaps we could improve this by handling mixed cases, when some of
1530 * the clauses are supported and some are not. Selectivity for the
1531 * supported subclauses would be computed using extended statistics,
1532 * and the remaining clauses would be estimated using the traditional
1533 * algorithm (product of selectivities).
1534 *
1535 * It however seems overly complex, and in a way we already do that
1536 * because if we reject the whole clause as unsupported here, it will
1537 * be eventually passed to clauselist_selectivity() which does exactly
1538 * this (split into supported/unsupported clauses etc).
1539 */
1540 BoolExpr *expr = (BoolExpr *) clause;
1541 ListCell *lc;
1542
1543 foreach(lc, expr->args)
1544 {
1545 /*
1546 * If we find an incompatible clause in the arguments, treat the
1547 * whole clause as incompatible.
1548 */
1550 (Node *) lfirst(lc),
1551 relid, attnums, exprs,
1552 leakproof))
1553 return false;
1554 }
1555
1556 return true;
1557 }
1558
1559 /* Var/Expr IS NULL */
1560 if (IsA(clause, NullTest))
1561 {
1562 NullTest *nt = (NullTest *) clause;
1563
1564 /* Check Var IS NULL clauses by recursing. */
1565 if (IsA(nt->arg, Var))
1567 (Node *) (nt->arg),
1568 relid, attnums,
1569 exprs, leakproof);
1570
1571 /* Otherwise we have Expr IS NULL. */
1572 *exprs = lappend(*exprs, nt->arg);
1573 return true;
1574 }
1575
1576 /*
1577 * Treat any other expressions as bare expressions to be matched against
1578 * expressions in statistics objects.
1579 */
1580 *exprs = lappend(*exprs, clause);
1581 return true;
1582}
1583
1584/*
1585 * statext_is_compatible_clause
1586 * Determines if the clause is compatible with MCV lists.
1587 *
1588 * See statext_is_compatible_clause_internal, above, for the basic rules.
1589 * This layer deals with RestrictInfo superstructure and applies permissions
1590 * checks to verify that it's okay to examine all mentioned Vars.
1591 *
1592 * Arguments:
1593 * clause: clause to be inspected (in RestrictInfo form)
1594 * relid: rel that all Vars in clause must belong to
1595 * *attnums: input/output parameter collecting attribute numbers of all
1596 * mentioned Vars. Note that we do not offset the attribute numbers,
1597 * so we can't cope with system columns.
1598 * *exprs: input/output parameter collecting primitive subclauses within
1599 * the clause tree
1600 *
1601 * Returns false if there is something we definitively can't handle.
1602 * On true return, we can proceed to match the *exprs against statistics.
1603 */
1604static bool
1606 Bitmapset **attnums, List **exprs)
1607{
1608 RestrictInfo *rinfo;
1609 int clause_relid;
1610 bool leakproof;
1611
1612 /*
1613 * Special-case handling for bare BoolExpr AND clauses, because the
1614 * restrictinfo machinery doesn't build RestrictInfos on top of AND
1615 * clauses.
1616 */
1617 if (is_andclause(clause))
1618 {
1619 BoolExpr *expr = (BoolExpr *) clause;
1620 ListCell *lc;
1621
1622 /*
1623 * Check that each sub-clause is compatible. We expect these to be
1624 * RestrictInfos.
1625 */
1626 foreach(lc, expr->args)
1627 {
1629 relid, attnums, exprs))
1630 return false;
1631 }
1632
1633 return true;
1634 }
1635
1636 /* Otherwise it must be a RestrictInfo. */
1637 if (!IsA(clause, RestrictInfo))
1638 return false;
1639 rinfo = (RestrictInfo *) clause;
1640
1641 /* Pseudoconstants are not really interesting here. */
1642 if (rinfo->pseudoconstant)
1643 return false;
1644
1645 /* Clauses referencing other varnos are incompatible. */
1646 if (!bms_get_singleton_member(rinfo->clause_relids, &clause_relid) ||
1647 clause_relid != relid)
1648 return false;
1649
1650 /*
1651 * Check the clause, determine what attributes it references, and whether
1652 * it includes any non-leakproof operators.
1653 */
1654 leakproof = true;
1656 relid, attnums, exprs,
1657 &leakproof))
1658 return false;
1659
1660 /*
1661 * If the clause includes any non-leakproof operators, check that the user
1662 * has permission to read all required attributes, otherwise the operators
1663 * might reveal values from the MCV list that the user doesn't have
1664 * permission to see. We require all rows to be selectable --- there must
1665 * be no securityQuals from security barrier views or RLS policies. See
1666 * similar code in examine_variable(), examine_simple_variable(), and
1667 * statistic_proc_security_check().
1668 *
1669 * Note that for an inheritance child, the permission checks are performed
1670 * on the inheritance root parent, and whole-table select privilege on the
1671 * parent doesn't guarantee that the user could read all columns of the
1672 * child. Therefore we must check all referenced columns.
1673 */
1674 if (!leakproof)
1675 {
1677
1678 /*
1679 * We have to check per-column privileges. *attnums has the attnums
1680 * for individual Vars we saw, but there may also be Vars within
1681 * subexpressions in *exprs. We can use pull_varattnos() to extract
1682 * those, but there's an impedance mismatch: attnums returned by
1683 * pull_varattnos() are offset by FirstLowInvalidHeapAttributeNumber,
1684 * while attnums within *attnums aren't. Convert *attnums to the
1685 * offset style so we can combine the results.
1686 */
1689 /* Now merge attnums from *exprs into clause_attnums */
1690 if (*exprs != NIL)
1691 pull_varattnos((Node *) *exprs, relid, &clause_attnums);
1692
1693 /* Must have permission to read all rows from these columns */
1695 return false;
1696 }
1697
1698 /* If we reach here, the clause is OK */
1699 return true;
1700}
1701
1702/*
1703 * statext_mcv_clauselist_selectivity
1704 * Estimate clauses using the best multi-column statistics.
1705 *
1706 * Applies available extended (multi-column) statistics on a table. There may
1707 * be multiple applicable statistics (with respect to the clauses), in which
1708 * case we use greedy approach. In each round we select the best statistic on
1709 * a table (measured by the number of attributes extracted from the clauses
1710 * and covered by it), and compute the selectivity for the supplied clauses.
1711 * We repeat this process with the remaining clauses (if any), until none of
1712 * the available statistics can be used.
1713 *
1714 * One of the main challenges with using MCV lists is how to extrapolate the
1715 * estimate to the data not covered by the MCV list. To do that, we compute
1716 * not only the "MCV selectivity" (selectivities for MCV items matching the
1717 * supplied clauses), but also the following related selectivities:
1718 *
1719 * - simple selectivity: Computed without extended statistics, i.e. as if the
1720 * columns/clauses were independent.
1721 *
1722 * - base selectivity: Similar to simple selectivity, but is computed using
1723 * the extended statistic by adding up the base frequencies (that we compute
1724 * and store for each MCV item) of matching MCV items.
1725 *
1726 * - total selectivity: Selectivity covered by the whole MCV list.
1727 *
1728 * These are passed to mcv_combine_selectivities() which combines them to
1729 * produce a selectivity estimate that makes use of both per-column statistics
1730 * and the multi-column MCV statistics.
1731 *
1732 * 'estimatedclauses' is an input/output parameter. We set bits for the
1733 * 0-based 'clauses' indexes we estimate for and also skip clause items that
1734 * already have a bit set.
1735 */
1736static Selectivity
1738 JoinType jointype, SpecialJoinInfo *sjinfo,
1740 bool is_or)
1741{
1742 ListCell *l;
1743 Bitmapset **list_attnums; /* attnums extracted from the clause */
1744 List **list_exprs; /* expressions matched to any statistic */
1745 int listidx;
1746 Selectivity sel = (is_or) ? 0.0 : 1.0;
1748
1749 /* check if there's any stats that might be useful for us. */
1751 return sel;
1752
1754
1755 /* expressions extracted from complex expressions */
1756 list_exprs = palloc_array(List *, list_length(clauses));
1757
1758 /*
1759 * Pre-process the clauses list to extract the attnums and expressions
1760 * seen in each item. We need to determine if there are any clauses which
1761 * will be useful for selectivity estimations with extended stats. Along
1762 * the way we'll record all of the attnums and expressions for each clause
1763 * in lists which we'll reference later so we don't need to repeat the
1764 * same work again.
1765 *
1766 * We also skip clauses that we already estimated using different types of
1767 * statistics (we treat them as incompatible).
1768 */
1769 listidx = 0;
1770 foreach(l, clauses)
1771 {
1772 Node *clause = (Node *) lfirst(l);
1773 Bitmapset *attnums = NULL;
1774 List *exprs = NIL;
1775
1777 statext_is_compatible_clause(root, clause, rel->relid, &attnums, &exprs))
1778 {
1779 list_attnums[listidx] = attnums;
1780 list_exprs[listidx] = exprs;
1781 }
1782 else
1783 {
1786 }
1787
1788 listidx++;
1789 }
1790
1791 /* apply as many extended statistics as possible */
1792 while (true)
1793 {
1797
1798 /* find the best suited statistics object for these attnums */
1801 list_length(clauses));
1802
1803 /*
1804 * if no (additional) matching stats could be found then we've nothing
1805 * to do
1806 */
1807 if (!stat)
1808 break;
1809
1810 /* Ensure choose_best_statistics produced an expected stats type. */
1811 Assert(stat->kind == STATS_EXT_MCV);
1812
1813 /* now filter the clauses to be estimated using the selected MCV */
1814 stat_clauses = NIL;
1815
1816 /* record which clauses are simple (single column or expression) */
1818
1819 listidx = -1;
1820 foreach(l, clauses)
1821 {
1822 /* Increment the index before we decide if to skip the clause. */
1823 listidx++;
1824
1825 /*
1826 * Ignore clauses from which we did not extract any attnums or
1827 * expressions (this needs to be consistent with what we do in
1828 * choose_best_statistics).
1829 *
1830 * This also eliminates already estimated clauses - both those
1831 * estimated before and during applying extended statistics.
1832 *
1833 * XXX This check is needed because both bms_is_subset and
1834 * stat_covers_expressions return true for empty attnums and
1835 * expressions.
1836 */
1838 continue;
1839
1840 /*
1841 * The clause was not estimated yet, and we've extracted either
1842 * attnums or expressions from it. Ignore it if it's not fully
1843 * covered by the chosen statistics object.
1844 *
1845 * We need to check both attributes and expressions, and reject if
1846 * either is not covered.
1847 */
1848 if (!bms_is_subset(list_attnums[listidx], stat->keys) ||
1850 continue;
1851
1852 /*
1853 * Now we know the clause is compatible (we have either attnums or
1854 * expressions extracted from it), and was not estimated yet.
1855 */
1856
1857 /* record simple clauses (single column or expression) */
1858 if ((list_attnums[listidx] == NULL &&
1859 list_length(list_exprs[listidx]) == 1) ||
1860 (list_exprs[listidx] == NIL &&
1864
1865 /* add clause to list and mark it as estimated */
1868
1869 /*
1870 * Reset the pointers, so that choose_best_statistics knows this
1871 * clause was estimated and does not consider it again.
1872 */
1875
1878 }
1879
1880 if (is_or)
1881 {
1882 bool *or_matches = NULL;
1884 stat_sel = 0.0;
1886
1887 /* Load the MCV list stored in the statistics object */
1888 mcv_list = statext_mcv_load(stat->statOid, rte->inh);
1889
1890 /*
1891 * Compute the selectivity of the ORed list of clauses covered by
1892 * this statistics object by estimating each in turn and combining
1893 * them using the formula P(A OR B) = P(A) + P(B) - P(A AND B).
1894 * This allows us to use the multivariate MCV stats to better
1895 * estimate the individual terms and their overlap.
1896 *
1897 * Each time we iterate this formula, the clause "A" above is
1898 * equal to all the clauses processed so far, combined with "OR".
1899 */
1900 listidx = 0;
1901 foreach(l, stat_clauses)
1902 {
1903 Node *clause = (Node *) lfirst(l);
1906 mcv_sel,
1911 clause_sel,
1913
1914 /*
1915 * "Simple" selectivity of the next clause and its overlap
1916 * with any of the previous clauses. These are our initial
1917 * estimates of P(B) and P(A AND B), assuming independence of
1918 * columns/clauses.
1919 */
1920 simple_sel = clause_selectivity_ext(root, clause, varRelid,
1921 jointype, sjinfo, false);
1922
1924
1925 /*
1926 * New "simple" selectivity of all clauses seen so far,
1927 * assuming independence.
1928 */
1931
1932 /*
1933 * Multi-column estimate of this clause using MCV statistics,
1934 * along with base and total selectivities, and corresponding
1935 * selectivities for the overlap term P(A AND B).
1936 */
1938 clause, &or_matches,
1939 &mcv_basesel,
1942 &mcv_totalsel);
1943
1944 /*
1945 * Combine the simple and multi-column estimates.
1946 *
1947 * If this clause is a simple single-column clause, then we
1948 * just use the simple selectivity estimate for it, since the
1949 * multi-column statistics are unlikely to improve on that
1950 * (and in fact could make it worse). For the overlap, we
1951 * always make use of the multi-column statistics.
1952 */
1955 else
1957 mcv_sel,
1959 mcv_totalsel);
1960
1964 mcv_totalsel);
1965
1966 /* Factor these into the result for this statistics object */
1969
1970 listidx++;
1971 }
1972
1973 /*
1974 * Factor the result for this statistics object into the overall
1975 * result. We treat the results from each separate statistics
1976 * object as independent of one another.
1977 */
1978 sel = sel + stat_sel - sel * stat_sel;
1979 }
1980 else /* Implicitly-ANDed list of clauses */
1981 {
1983 mcv_sel,
1986 stat_sel;
1987
1988 /*
1989 * "Simple" selectivity, i.e. without any extended statistics,
1990 * essentially assuming independence of the columns/clauses.
1991 */
1993 varRelid, jointype,
1994 sjinfo, false);
1995
1996 /*
1997 * Multi-column estimate using MCV statistics, along with base and
1998 * total selectivities.
1999 */
2001 varRelid, jointype, sjinfo,
2002 rel, &mcv_basesel,
2003 &mcv_totalsel);
2004
2005 /* Combine the simple and multi-column estimates. */
2007 mcv_sel,
2009 mcv_totalsel);
2010
2011 /* Factor this into the overall result */
2012 sel *= stat_sel;
2013 }
2014 }
2015
2016 return sel;
2017}
2018
2019/*
2020 * statext_clauselist_selectivity
2021 * Estimate clauses using the best multi-column statistics.
2022 */
2025 JoinType jointype, SpecialJoinInfo *sjinfo,
2027 bool is_or)
2028{
2030
2031 /* First, try estimating clauses using a multivariate MCV list. */
2032 sel = statext_mcv_clauselist_selectivity(root, clauses, varRelid, jointype,
2033 sjinfo, rel, estimatedclauses, is_or);
2034
2035 /*
2036 * Functional dependencies only work for clauses connected by AND, so for
2037 * OR clauses we're done.
2038 */
2039 if (is_or)
2040 return sel;
2041
2042 /*
2043 * Then, apply functional dependencies on the remaining clauses by calling
2044 * dependencies_clauselist_selectivity. Pass 'estimatedclauses' so the
2045 * function can properly skip clauses already estimated above.
2046 *
2047 * The reasoning for applying dependencies last is that the more complex
2048 * stats can track more complex correlations between the attributes, and
2049 * so may be considered more reliable.
2050 *
2051 * For example, MCV list can give us an exact selectivity for values in
2052 * two columns, while functional dependencies can only provide information
2053 * about the overall strength of the dependency.
2054 */
2055 sel *= dependencies_clauselist_selectivity(root, clauses, varRelid,
2056 jointype, sjinfo, rel,
2058
2059 return sel;
2060}
2061
2062/*
2063 * examine_opclause_args
2064 * Split an operator expression's arguments into Expr and Const parts.
2065 *
2066 * Attempts to match the arguments to either (Expr op Const) or (Const op
2067 * Expr), possibly with a RelabelType on top. When the expression matches this
2068 * form, returns true, otherwise returns false.
2069 *
2070 * Optionally returns pointers to the extracted Expr/Const nodes, when passed
2071 * non-null pointers (exprp, cstp and expronleftp). The expronleftp flag
2072 * specifies on which side of the operator we found the expression node.
2073 */
2074bool
2076 bool *expronleftp)
2077{
2078 Node *expr;
2079 Const *cst;
2080 bool expronleft;
2081 Node *leftop,
2082 *rightop;
2083
2084 /* enforced by statext_is_compatible_clause_internal */
2085 Assert(list_length(args) == 2);
2086
2087 leftop = linitial(args);
2088 rightop = lsecond(args);
2089
2090 /* strip RelabelType from either side of the expression */
2091 if (IsA(leftop, RelabelType))
2092 leftop = (Node *) ((RelabelType *) leftop)->arg;
2093
2094 if (IsA(rightop, RelabelType))
2095 rightop = (Node *) ((RelabelType *) rightop)->arg;
2096
2097 if (IsA(rightop, Const))
2098 {
2099 expr = leftop;
2100 cst = (Const *) rightop;
2101 expronleft = true;
2102 }
2103 else if (IsA(leftop, Const))
2104 {
2105 expr = rightop;
2106 cst = (Const *) leftop;
2107 expronleft = false;
2108 }
2109 else
2110 return false;
2111
2112 /* return pointers to the extracted parts if requested */
2113 if (exprp)
2114 *exprp = expr;
2115
2116 if (cstp)
2117 *cstp = cst;
2118
2119 if (expronleftp)
2121
2122 return true;
2123}
2124
2125
2126/*
2127 * Compute statistics about expressions of a relation.
2128 */
2129static void
2131 HeapTuple *rows, int numrows)
2132{
2135 int ind,
2136 i;
2137
2139 "Analyze Expression",
2142
2143 for (ind = 0; ind < nexprs; ind++)
2144 {
2146 VacAttrStats *stats = thisdata->vacattrstat;
2147 Node *expr = thisdata->expr;
2148 TupleTableSlot *slot;
2149 EState *estate;
2150 ExprContext *econtext;
2151 Datum *exprvals;
2152 bool *exprnulls;
2153 ExprState *exprstate;
2154 int tcnt;
2155
2156 /* Are we still in the main context? */
2158
2159 /*
2160 * Need an EState for evaluation of expressions. Create it in the
2161 * per-expression context to be sure it gets cleaned up at the bottom
2162 * of the loop.
2163 */
2164 estate = CreateExecutorState();
2165 econtext = GetPerTupleExprContext(estate);
2166
2167 /* Set up expression evaluation state */
2168 exprstate = ExecPrepareExpr((Expr *) expr, estate);
2169
2170 /* Need a slot to hold the current heap tuple, too */
2173
2174 /* Arrange for econtext's scan tuple to be the tuple under test */
2175 econtext->ecxt_scantuple = slot;
2176
2177 /* Compute and save expression values */
2178 exprvals = (Datum *) palloc(numrows * sizeof(Datum));
2179 exprnulls = (bool *) palloc(numrows * sizeof(bool));
2180
2181 tcnt = 0;
2182 for (i = 0; i < numrows; i++)
2183 {
2184 Datum datum;
2185 bool isnull;
2186
2187 /*
2188 * Reset the per-tuple context each time, to reclaim any cruft
2189 * left behind by evaluating the statistics expressions.
2190 */
2191 ResetExprContext(econtext);
2192
2193 /* Set up for expression evaluation */
2194 ExecStoreHeapTuple(rows[i], slot, false);
2195
2196 /*
2197 * Evaluate the expression. We do this in the per-tuple context so
2198 * as not to leak memory, and then copy the result into the
2199 * context created at the beginning of this function.
2200 */
2201 datum = ExecEvalExprSwitchContext(exprstate,
2202 GetPerTupleExprContext(estate),
2203 &isnull);
2204 if (isnull)
2205 {
2206 exprvals[tcnt] = (Datum) 0;
2207 exprnulls[tcnt] = true;
2208 }
2209 else
2210 {
2211 /* Make sure we copy the data into the context. */
2213
2214 exprvals[tcnt] = datumCopy(datum,
2215 stats->attrtype->typbyval,
2216 stats->attrtype->typlen);
2217 exprnulls[tcnt] = false;
2218 }
2219
2220 tcnt++;
2221 }
2222
2223 /*
2224 * Now we can compute the statistics for the expression columns.
2225 *
2226 * XXX Unlike compute_index_stats we don't need to switch and reset
2227 * memory contexts here, because we're only computing stats for a
2228 * single expression (and not iterating over many indexes), so we just
2229 * do it in expr_context. Note that compute_stats copies the result
2230 * into stats->anl_context, so it does not disappear.
2231 */
2232 if (tcnt > 0)
2233 {
2235 get_attribute_options(onerel->rd_id, stats->tupattnum);
2236
2237 stats->exprvals = exprvals;
2238 stats->exprnulls = exprnulls;
2239 stats->rowstride = 1;
2240 stats->compute_stats(stats,
2242 tcnt,
2243 tcnt);
2244
2245 /*
2246 * If the n_distinct option is specified, it overrides the above
2247 * computation.
2248 */
2249 if (aopt != NULL && aopt->n_distinct != 0.0)
2250 stats->stadistinct = aopt->n_distinct;
2251 }
2252
2253 /* And clean up */
2255
2257 FreeExecutorState(estate);
2259 }
2260
2263}
2264
2265
2266/*
2267 * Fetch function for analyzing statistics object expressions.
2268 *
2269 * We have not bothered to construct tuples from the data, instead the data
2270 * is just in Datum arrays.
2271 */
2272static Datum
2273expr_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
2274{
2275 int i;
2276
2277 /* exprvals and exprnulls are already offset for proper column */
2278 i = rownum * stats->rowstride;
2279 *isNull = stats->exprnulls[i];
2280 return stats->exprvals[i];
2281}
2282
2283/*
2284 * Build analyze data for a list of expressions. As this is not tied
2285 * directly to a relation (table or index), we have to fake some of
2286 * the fields in examine_expression().
2287 */
2288static AnlExprData *
2289build_expr_data(List *exprs, int stattarget)
2290{
2291 int idx;
2292 int nexprs = list_length(exprs);
2294 ListCell *lc;
2295
2297
2298 idx = 0;
2299 foreach(lc, exprs)
2300 {
2301 Node *expr = (Node *) lfirst(lc);
2303
2304 thisdata->expr = expr;
2305 thisdata->vacattrstat = examine_expression(expr, stattarget);
2306 idx++;
2307 }
2308
2309 return exprdata;
2310}
2311
2312/* form an array of pg_statistic rows (per update_attstats) */
2313static Datum
2315{
2316 int exprno;
2317 Oid typOid;
2318 Relation sd;
2319
2320 ArrayBuildState *astate = NULL;
2321
2323
2324 /* lookup OID of composite type for pg_statistic */
2326 if (!OidIsValid(typOid))
2327 ereport(ERROR,
2329 errmsg("relation \"%s\" does not have a composite type",
2330 "pg_statistic")));
2331
2332 for (exprno = 0; exprno < nexprs; exprno++)
2333 {
2334 int i,
2335 k;
2336 VacAttrStats *stats = exprdata[exprno].vacattrstat;
2337
2339 bool nulls[Natts_pg_statistic];
2341
2342 if (!stats->stats_valid)
2343 {
2344 astate = accumArrayResult(astate,
2345 (Datum) 0,
2346 true,
2347 typOid,
2349 continue;
2350 }
2351
2352 /*
2353 * Construct a new pg_statistic tuple
2354 */
2355 for (i = 0; i < Natts_pg_statistic; ++i)
2356 {
2357 nulls[i] = false;
2358 }
2359
2367 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
2368 {
2369 values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
2370 }
2372 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
2373 {
2374 values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
2375 }
2377 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
2378 {
2379 values[i++] = ObjectIdGetDatum(stats->stacoll[k]); /* stacollN */
2380 }
2382 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
2383 {
2384 int nnum = stats->numnumbers[k];
2385
2386 if (nnum > 0)
2387 {
2388 int n;
2389 Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
2390 ArrayType *arry;
2391
2392 for (n = 0; n < nnum; n++)
2393 numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
2395 values[i++] = PointerGetDatum(arry); /* stanumbersN */
2396 }
2397 else
2398 {
2399 nulls[i] = true;
2400 values[i++] = (Datum) 0;
2401 }
2402 }
2404 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
2405 {
2406 if (stats->numvalues[k] > 0)
2407 {
2408 ArrayType *arry;
2409
2410 arry = construct_array(stats->stavalues[k],
2411 stats->numvalues[k],
2412 stats->statypid[k],
2413 stats->statyplen[k],
2414 stats->statypbyval[k],
2415 stats->statypalign[k]);
2416 values[i++] = PointerGetDatum(arry); /* stavaluesN */
2417 }
2418 else
2419 {
2420 nulls[i] = true;
2421 values[i++] = (Datum) 0;
2422 }
2423 }
2424
2426
2427 astate = accumArrayResult(astate,
2429 false,
2430 typOid,
2432 }
2433
2435
2436 return makeArrayResult(astate, CurrentMemoryContext);
2437}
2438
2439/*
2440 * Loads pg_statistic record from expression statistics for expression
2441 * identified by the supplied index.
2442 *
2443 * Returns the pg_statistic record found, or NULL if there is no statistics
2444 * data to use.
2445 */
2448{
2449 bool isnull;
2450 Datum value;
2451 HeapTuple htup;
2453 HeapTupleHeader td;
2455 HeapTuple tup;
2456
2459 if (!HeapTupleIsValid(htup))
2460 elog(ERROR, "cache lookup failed for statistics object %u", stxoid);
2461
2464 if (isnull)
2465 elog(ERROR,
2466 "requested statistics kind \"%c\" is not yet built for statistics object %u",
2468
2470
2472
2473 if (eah->dnulls && eah->dnulls[idx])
2474 {
2475 /* No data found for this expression, give up. */
2476 ReleaseSysCache(htup);
2477 return NULL;
2478 }
2479
2480 td = DatumGetHeapTupleHeader(eah->dvalues[idx]);
2481
2482 /* Build a temporary HeapTuple control structure */
2484 ItemPointerSetInvalid(&(tmptup.t_self));
2485 tmptup.t_tableOid = InvalidOid;
2486 tmptup.t_data = td;
2487
2489
2490 ReleaseSysCache(htup);
2491
2492 return tup;
2493}
2494
2495/*
2496 * Evaluate the expressions, so that we can use the results to build
2497 * all the requested statistics types. This matters especially for
2498 * expensive expressions, of course.
2499 */
2500static StatsBuildData *
2502 VacAttrStats **stats, int stattarget)
2503{
2504 /* evaluated expressions */
2506 char *ptr;
2507 Size len;
2508
2509 int i;
2510 int k;
2511 int idx;
2512 TupleTableSlot *slot;
2513 EState *estate;
2514 ExprContext *econtext;
2515 List *exprstates = NIL;
2516 int nkeys = bms_num_members(stat->columns) + list_length(stat->exprs);
2517 ListCell *lc;
2518
2519 /* allocate everything as a single chunk, so we can free it easily */
2520 len = MAXALIGN(sizeof(StatsBuildData));
2521 len += MAXALIGN(sizeof(AttrNumber) * nkeys); /* attnums */
2522 len += MAXALIGN(sizeof(VacAttrStats *) * nkeys); /* stats */
2523
2524 /* values */
2525 len += MAXALIGN(sizeof(Datum *) * nkeys);
2526 len += nkeys * MAXALIGN(sizeof(Datum) * numrows);
2527
2528 /* nulls */
2529 len += MAXALIGN(sizeof(bool *) * nkeys);
2530 len += nkeys * MAXALIGN(sizeof(bool) * numrows);
2531
2532 ptr = palloc(len);
2533
2534 /* set the pointers */
2535 result = (StatsBuildData *) ptr;
2536 ptr += MAXALIGN(sizeof(StatsBuildData));
2537
2538 /* attnums */
2539 result->attnums = (AttrNumber *) ptr;
2540 ptr += MAXALIGN(sizeof(AttrNumber) * nkeys);
2541
2542 /* stats */
2543 result->stats = (VacAttrStats **) ptr;
2544 ptr += MAXALIGN(sizeof(VacAttrStats *) * nkeys);
2545
2546 /* values */
2547 result->values = (Datum **) ptr;
2548 ptr += MAXALIGN(sizeof(Datum *) * nkeys);
2549
2550 /* nulls */
2551 result->nulls = (bool **) ptr;
2552 ptr += MAXALIGN(sizeof(bool *) * nkeys);
2553
2554 for (i = 0; i < nkeys; i++)
2555 {
2556 result->values[i] = (Datum *) ptr;
2557 ptr += MAXALIGN(sizeof(Datum) * numrows);
2558
2559 result->nulls[i] = (bool *) ptr;
2560 ptr += MAXALIGN(sizeof(bool) * numrows);
2561 }
2562
2563 Assert((ptr - (char *) result) == len);
2564
2565 /* we have it allocated, so let's fill the values */
2566 result->nattnums = nkeys;
2567 result->numrows = numrows;
2568
2569 /* fill the attribute info - first attributes, then expressions */
2570 idx = 0;
2571 k = -1;
2572 while ((k = bms_next_member(stat->columns, k)) >= 0)
2573 {
2574 result->attnums[idx] = k;
2575 result->stats[idx] = stats[idx];
2576
2577 idx++;
2578 }
2579
2580 k = -1;
2581 foreach(lc, stat->exprs)
2582 {
2583 Node *expr = (Node *) lfirst(lc);
2584
2585 result->attnums[idx] = k;
2586 result->stats[idx] = examine_expression(expr, stattarget);
2587
2588 idx++;
2589 k--;
2590 }
2591
2592 /* first extract values for all the regular attributes */
2593 for (i = 0; i < numrows; i++)
2594 {
2595 idx = 0;
2596 k = -1;
2597 while ((k = bms_next_member(stat->columns, k)) >= 0)
2598 {
2599 result->values[idx][i] = heap_getattr(rows[i], k,
2600 result->stats[idx]->tupDesc,
2601 &result->nulls[idx][i]);
2602
2603 idx++;
2604 }
2605 }
2606
2607 /* Need an EState for evaluation expressions. */
2608 estate = CreateExecutorState();
2609 econtext = GetPerTupleExprContext(estate);
2610
2611 /* Need a slot to hold the current heap tuple, too */
2614
2615 /* Arrange for econtext's scan tuple to be the tuple under test */
2616 econtext->ecxt_scantuple = slot;
2617
2618 /* Set up expression evaluation state */
2619 exprstates = ExecPrepareExprList(stat->exprs, estate);
2620
2621 for (i = 0; i < numrows; i++)
2622 {
2623 /*
2624 * Reset the per-tuple context each time, to reclaim any cruft left
2625 * behind by evaluating the statistics object expressions.
2626 */
2627 ResetExprContext(econtext);
2628
2629 /* Set up for expression evaluation */
2630 ExecStoreHeapTuple(rows[i], slot, false);
2631
2632 idx = bms_num_members(stat->columns);
2633 foreach(lc, exprstates)
2634 {
2635 Datum datum;
2636 bool isnull;
2637 ExprState *exprstate = (ExprState *) lfirst(lc);
2638
2639 /*
2640 * XXX This probably leaks memory. Maybe we should use
2641 * ExecEvalExprSwitchContext but then we need to copy the result
2642 * somewhere else.
2643 */
2644 datum = ExecEvalExpr(exprstate,
2645 GetPerTupleExprContext(estate),
2646 &isnull);
2647 if (isnull)
2648 {
2649 result->values[idx][i] = (Datum) 0;
2650 result->nulls[idx][i] = true;
2651 }
2652 else
2653 {
2654 result->values[idx][i] = datum;
2655 result->nulls[idx][i] = false;
2656 }
2657
2658 idx++;
2659 }
2660 }
2661
2663 FreeExecutorState(estate);
2664
2665 return result;
2666}
Datum idx(PG_FUNCTION_ARGS)
Definition _int_op.c:263
#define ARR_NDIM(a)
Definition array.h:290
#define ARR_DATA_PTR(a)
Definition array.h:322
#define DatumGetArrayTypeP(X)
Definition array.h:261
#define ARR_ELEMTYPE(a)
Definition array.h:292
#define ARR_DIMS(a)
Definition array.h:294
#define ARR_HASNULL(a)
Definition array.h:291
void deconstruct_expanded_array(ExpandedArrayHeader *eah)
ExpandedArrayHeader * DatumGetExpandedArray(Datum d)
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
ArrayType * construct_array_builtin(Datum *elems, int nelems, Oid elmtype)
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
int16 AttrNumber
Definition attnum.h:21
#define AttributeNumberIsValid(attributeNumber)
Definition attnum.h:34
#define MaxAttrNumber
Definition attnum.h:24
#define AttrNumberIsForUserDefinedAttr(attributeNumber)
Definition attnum.h:41
#define InvalidAttrNumber
Definition attnum.h:23
AttributeOpts * get_attribute_options(Oid attrelid, int attnum)
void pgstat_progress_update_param(int index, int64 val)
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
int bms_next_member(const Bitmapset *a, int prevbit)
Definition bitmapset.c:1425
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:547
void bms_free(Bitmapset *a)
Definition bitmapset.c:240
int bms_num_members(const Bitmapset *a)
Definition bitmapset.c:879
bool bms_is_member(int x, const Bitmapset *a)
Definition bitmapset.c:645
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:934
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:1036
Bitmapset * bms_offset_members(const Bitmapset *a, int offset)
Definition bitmapset.c:419
BMS_Membership bms_membership(const Bitmapset *a)
Definition bitmapset.c:900
bool bms_get_singleton_member(const Bitmapset *a, int *member)
Definition bitmapset.c:843
@ BMS_SINGLETON
Definition bitmapset.h:72
static Datum values[MAXATTR]
Definition bootstrap.c:190
#define TextDatumGetCString(d)
Definition builtins.h:99
#define NameStr(name)
Definition c.h:894
#define MAXALIGN(LEN)
Definition c.h:955
#define Assert(condition)
Definition c.h:1002
int64_t int64
Definition c.h:680
unsigned int Index
Definition c.h:757
#define OidIsValid(objectId)
Definition c.h:917
size_t Size
Definition c.h:748
uint32 result
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition clauses.c:2516
Selectivity clause_selectivity_ext(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, bool use_extended_stats)
Definition clausesel.c:684
Selectivity clauselist_selectivity_ext(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, bool use_extended_stats)
Definition clausesel.c:117
int default_statistics_target
Definition analyze.c:71
bool std_typanalyze(VacAttrStats *stats)
Definition analyze.c:1950
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition datum.c:132
MVDependencies * statext_dependencies_build(StatsBuildData *data)
bytea * statext_dependencies_serialize(MVDependencies *dependencies)
Selectivity dependencies_clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Bitmapset **estimatedclauses)
Size toast_raw_datum_size(Datum value)
Definition detoast.c:545
Datum arg
Definition elog.c:1323
int errcode(int sqlerrcode)
Definition elog.c:875
#define WARNING
Definition elog.h:37
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define ereport(elevel,...)
Definition elog.h:152
bool equal(const void *a, const void *b)
Definition equalfuncs.c:223
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition execExpr.c:765
List * ExecPrepareExprList(List *nodes, EState *estate)
Definition execExpr.c:839
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
const TupleTableSlotOps TTSOpsHeapTuple
Definition execTuples.c:85
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
void FreeExecutorState(EState *estate)
Definition execUtils.c:197
EState * CreateExecutorState(void)
Definition execUtils.c:90
#define GetPerTupleExprContext(estate)
Definition executor.h:665
#define ResetExprContext(econtext)
Definition executor.h:659
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition executor.h:401
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition executor.h:444
bool has_stats_of_kind(List *stats, char requiredkind)
static AnlExprData * build_expr_data(List *exprs, int stattarget)
static VacAttrStats ** lookup_var_attr_stats(Bitmapset *attrs, List *exprs, int nvacatts, VacAttrStats **vacatts)
int multi_sort_compare_dims(int start, int end, const SortItem *a, const SortItem *b, MultiSortSupport mss)
#define WIDTH_THRESHOLD
static bool stat_covers_expressions(StatisticExtInfo *stat, List *exprs, Bitmapset **expr_idxs)
static List * fetch_statentries_for_relation(Relation pg_statext, Relation rel)
static Datum expr_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
static Selectivity statext_mcv_clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Bitmapset **estimatedclauses, bool is_or)
int multi_sort_compare_dim(int dim, const SortItem *a, const SortItem *b, MultiSortSupport mss)
static VacAttrStats * examine_attribute(Node *expr)
StatisticExtInfo * choose_best_statistics(List *stats, char requiredkind, bool inh, Bitmapset **clause_attnums, List **clause_exprs, int nclauses)
int compare_scalars_simple(const void *a, const void *b, void *arg)
int ComputeExtStatisticsRows(Relation onerel, int natts, VacAttrStats **vacattrstats)
static StatsBuildData * make_build_data(Relation rel, StatExtEntry *stat, int numrows, HeapTuple *rows, VacAttrStats **stats, int stattarget)
static bool statext_is_compatible_clause_internal(PlannerInfo *root, Node *clause, Index relid, Bitmapset **attnums, List **exprs, bool *leakproof)
AttrNumber * build_attnums_array(Bitmapset *attrs, int nexprs, int *numattrs)
bool HasRelationExtStatistics(Relation onerel)
int compare_datums_simple(Datum a, Datum b, SortSupport ssup)
static bool statext_is_compatible_clause(PlannerInfo *root, Node *clause, Index relid, Bitmapset **attnums, List **exprs)
static void statext_store(Oid statOid, bool inh, MVNDistinct *ndistinct, MVDependencies *dependencies, MCVList *mcv, Datum exprs, VacAttrStats **stats)
bool statext_is_kind_built(HeapTuple htup, char type)
static VacAttrStats * examine_expression(Node *expr, int stattarget)
void BuildRelationExtStatistics(Relation onerel, bool inh, double totalrows, int numrows, HeapTuple *rows, int natts, VacAttrStats **vacattrstats)
Selectivity statext_clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Bitmapset **estimatedclauses, bool is_or)
SortItem * build_sorted_items(StatsBuildData *data, int *nitems, MultiSortSupport mss, int numattrs, AttrNumber *attnums)
static int stat_find_expression(StatisticExtInfo *stat, Node *expr)
static int statext_compute_stattarget(int stattarget, int nattrs, VacAttrStats **stats)
static void compute_expr_stats(Relation onerel, AnlExprData *exprdata, int nexprs, HeapTuple *rows, int numrows)
int multi_sort_compare(const void *a, const void *b, void *arg)
MultiSortSupport multi_sort_init(int ndims)
HeapTuple statext_expressions_load(Oid stxoid, bool inh, int idx)
static Datum serialize_expr_stats(AnlExprData *exprdata, int nexprs)
void multi_sort_add_dimension(MultiSortSupport mss, int sortdim, Oid oper, Oid collation)
bool examine_opclause_args(List *args, Node **exprp, Const **cstp, bool *expronleftp)
MultiSortSupportData * MultiSortSupport
#define palloc_array(type, count)
Definition fe_memutils.h:91
#define palloc0_object(type)
Definition fe_memutils.h:90
#define OidFunctionCall1(functionId, arg1)
Definition fmgr.h:726
#define DatumGetHeapTupleHeader(X)
Definition fmgr.h:296
#define PG_DETOAST_DATUM(datum)
Definition fmgr.h:240
void systable_endscan(SysScanDesc sysscan)
Definition genam.c:604
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition genam.c:515
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition genam.c:388
static int compare(const void *arg1, const void *arg2)
Definition geqo_pool.c:145
return str start
HeapTuple heap_copytuple(HeapTuple tuple)
Definition heaptuple.c:686
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition heaptuple.c:1025
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition heaptuple.c:456
Datum heap_copy_tuple_as_datum(HeapTuple tuple, TupleDesc tupleDesc)
Definition heaptuple.c:989
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1372
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
static uint32 HeapTupleHeaderGetDatumLength(const HeapTupleHeaderData *tup)
static void * GETSTRUCT(const HeapTupleData *tuple)
#define nitems(x)
Definition indent.h:31
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition indexing.c:233
long val
Definition informix.c:689
static struct @175 value
int b
Definition isn.c:74
int x
Definition isn.c:75
int a
Definition isn.c:73
int j
Definition isn.c:78
int i
Definition isn.c:77
static void ItemPointerSetInvalid(ItemPointerData *pointer)
Definition itemptr.h:184
List * lappend(List *list, void *datum)
Definition list.c:339
List * lappend_int(List *list, int datum)
Definition list.c:357
void list_free(List *list)
Definition list.c:1546
#define RowExclusiveLock
Definition lockdefs.h:38
RegProcedure get_oprrest(Oid opno)
Definition lsyscache.c:1871
RegProcedure get_opcode(Oid opno)
Definition lsyscache.c:1585
Oid get_rel_type_id(Oid relid)
Definition lsyscache.c:2293
bool get_func_leakproof(Oid funcid)
Definition lsyscache.c:2151
int16 get_typlen(Oid typid)
Definition lsyscache.c:2511
char * get_namespace_name(Oid nspid)
Definition lsyscache.c:3682
Selectivity mcv_clauselist_selectivity(PlannerInfo *root, StatisticExtInfo *stat, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Selectivity *basesel, Selectivity *totalsel)
Definition mcv.c:2043
MCVList * statext_mcv_load(Oid mvoid, bool inh)
Definition mcv.c:556
Selectivity mcv_combine_selectivities(Selectivity simple_sel, Selectivity mcv_sel, Selectivity mcv_basesel, Selectivity mcv_totalsel)
Definition mcv.c:2001
Selectivity mcv_clause_selectivity_or(PlannerInfo *root, StatisticExtInfo *stat, MCVList *mcv, Node *clause, bool **or_matches, Selectivity *basesel, Selectivity *overlap_mcvsel, Selectivity *overlap_basesel, Selectivity *totalsel)
Definition mcv.c:2120
MCVList * statext_mcv_build(StatsBuildData *data, double totalrows, int stattarget)
Definition mcv.c:178
bytea * statext_mcv_serialize(MCVList *mcvlist, VacAttrStats **stats)
Definition mcv.c:619
void MemoryContextReset(MemoryContext context)
Definition mcxt.c:406
char * pstrdup(const char *in)
Definition mcxt.c:1910
void pfree(void *pointer)
Definition mcxt.c:1619
void * palloc0(Size size)
Definition mcxt.c:1420
void * palloc(Size size)
Definition mcxt.c:1390
MemoryContext CurrentMemoryContext
Definition mcxt.c:161
void MemoryContextDelete(MemoryContext context)
Definition mcxt.c:475
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition memutils.h:160
#define AmAutoVacuumWorkerProcess()
Definition miscadmin.h:389
bytea * statext_ndistinct_serialize(MVNDistinct *ndistinct)
Definition mvdistinct.c:176
MVNDistinct * statext_ndistinct_build(double totalrows, StatsBuildData *data)
Definition mvdistinct.c:85
Oid exprType(const Node *expr)
Definition nodeFuncs.c:42
int32 exprTypmod(const Node *expr)
Definition nodeFuncs.c:304
Oid exprCollation(const Node *expr)
Definition nodeFuncs.c:826
void fix_opfuncids(Node *node)
Definition nodeFuncs.c:1859
static bool is_andclause(const void *clause)
Definition nodeFuncs.h:107
static bool is_orclause(const void *clause)
Definition nodeFuncs.h:116
static bool is_opclause(const void *clause)
Definition nodeFuncs.h:76
static bool is_notclause(const void *clause)
Definition nodeFuncs.h:125
#define IsA(nodeptr, _type_)
Definition nodes.h:162
double Selectivity
Definition nodes.h:258
JoinType
Definition nodes.h:296
static char * errmsg
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:138
Operator oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId, bool noError, int location)
Definition parse_oper.c:376
#define planner_rt_fetch(rti, root)
Definition pathnodes.h:704
int16 attnum
int16 attlen
const void size_t len
const void * data
#define lfirst(lc)
Definition pg_list.h:172
static int list_length(const List *l)
Definition pg_list.h:152
#define NIL
Definition pg_list.h:68
#define lfirst_int(lc)
Definition pg_list.h:173
#define linitial(l)
Definition pg_list.h:178
#define lsecond(l)
Definition pg_list.h:183
#define STATISTIC_NUM_SLOTS
END_CATALOG_STRUCT typedef FormData_pg_statistic_ext * Form_pg_statistic_ext
END_CATALOG_STRUCT typedef FormData_pg_type * Form_pg_type
Definition pg_type.h:265
void qsort_interruptible(void *base, size_t nel, size_t elsize, qsort_arg_comparator cmp, void *arg)
static bool DatumGetBool(Datum X)
Definition postgres.h:100
static Datum Float4GetDatum(float4 X)
Definition postgres.h:481
static Datum Int16GetDatum(int16 X)
Definition postgres.h:172
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
uint64_t Datum
Definition postgres.h:70
static Datum Int32GetDatum(int32 X)
Definition postgres.h:212
static int16 DatumGetInt16(Datum X)
Definition postgres.h:162
#define PointerGetDatum(X)
Definition postgres.h:354
#define InvalidOid
unsigned int Oid
static int fb(int x)
#define PROGRESS_ANALYZE_EXT_STATS_COMPUTED
Definition progress.h:58
#define PROGRESS_ANALYZE_PHASE
Definition progress.h:54
#define PROGRESS_ANALYZE_PHASE_COMPUTE_EXT_STATS
Definition progress.h:69
#define PROGRESS_ANALYZE_EXT_STATS_TOTAL
Definition progress.h:57
tree ctl root
Definition radixtree.h:1857
void * stringToNode(const char *str)
Definition read.c:90
#define RelationGetRelid(relation)
Definition rel.h:516
#define RelationGetDescr(relation)
Definition rel.h:542
#define RelationGetRelationName(relation)
Definition rel.h:550
int errtable(Relation rel)
Definition relcache.c:6084
Node * expand_generated_columns_in_expr(Node *node, Relation rel, int rt_index)
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition scankey.c:76
bool all_rows_selectable(PlannerInfo *root, Index varno, Bitmapset *varattnos)
Definition selfuncs.c:6415
#define CLAMP_PROBABILITY(p)
Definition selfuncs.h:63
void PrepareSortSupportFromOrderingOp(Oid orderingOp, SortSupport ssup)
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
#define STATS_MAX_DIMENSIONS
Definition statistics.h:19
void RemoveStatisticsDataById(Oid statsOid, bool inh)
Definition statscmds.c:792
#define BTEqualStrategyNumber
Definition stratnum.h:31
VacAttrStats * vacattrstat
List * args
Definition primnodes.h:954
TupleTableSlot * ecxt_scantuple
Definition execnodes.h:287
Definition pg_list.h:54
Definition nodes.h:133
Oid opno
Definition primnodes.h:835
List * args
Definition primnodes.h:853
Index relid
Definition pathnodes.h:1069
List * statlist
Definition pathnodes.h:1093
Expr * clause
Definition pathnodes.h:2901
MemoryContext ssup_cxt
Definition sortsupport.h:66
Bitmapset * columns
Bitmapset * keys
Definition pathnodes.h:1529
int32 attrtypmod
Definition vacuum.h:126
bool stats_valid
Definition vacuum.h:143
float4 stanullfrac
Definition vacuum.h:144
Form_pg_type attrtype
Definition vacuum.h:127
int16 stakind[STATISTIC_NUM_SLOTS]
Definition vacuum.h:147
int tupattnum
Definition vacuum.h:170
MemoryContext anl_context
Definition vacuum.h:129
Oid statypid[STATISTIC_NUM_SLOTS]
Definition vacuum.h:161
Oid staop[STATISTIC_NUM_SLOTS]
Definition vacuum.h:148
Oid stacoll[STATISTIC_NUM_SLOTS]
Definition vacuum.h:149
char statypalign[STATISTIC_NUM_SLOTS]
Definition vacuum.h:164
float4 * stanumbers[STATISTIC_NUM_SLOTS]
Definition vacuum.h:151
int rowstride
Definition vacuum.h:175
Oid attrtypid
Definition vacuum.h:125
int minrows
Definition vacuum.h:136
int attstattarget
Definition vacuum.h:124
int32 stawidth
Definition vacuum.h:145
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition vacuum.h:163
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition vacuum.h:162
bool * exprnulls
Definition vacuum.h:174
TupleDesc tupDesc
Definition vacuum.h:172
Datum * exprvals
Definition vacuum.h:173
int numvalues[STATISTIC_NUM_SLOTS]
Definition vacuum.h:152
Datum * stavalues[STATISTIC_NUM_SLOTS]
Definition vacuum.h:153
float4 stadistinct
Definition vacuum.h:146
int numnumbers[STATISTIC_NUM_SLOTS]
Definition vacuum.h:150
AnalyzeAttrComputeStatsFunc compute_stats
Definition vacuum.h:135
Oid attrcollid
Definition vacuum.h:128
AttrNumber varattno
Definition primnodes.h:275
int varno
Definition primnodes.h:270
Index varlevelsup
Definition primnodes.h:295
Definition type.h:97
Definition c.h:835
#define FirstLowInvalidHeapAttributeNumber
Definition sysattr.h:27
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
HeapTuple SearchSysCache2(SysCacheIdentifier cacheId, Datum key1, Datum key2)
Definition syscache.c:231
Datum SysCacheGetAttrNotNull(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition syscache.c:626
Datum SysCacheGetAttr(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition syscache.c:596
#define SearchSysCacheCopy1(cacheId, key1)
Definition syscache.h:91
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40
static ItemArray items
#define MAX_STATISTICS_TARGET
Definition vacuum.h:350
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition var.c:296
const char * type
#define stat
Definition win32_port.h:74