PostgreSQL Source Code git master
Loading...
Searching...
No Matches
extended_stats.c File Reference
#include "postgres.h"
#include "access/detoast.h"
#include "access/genam.h"
#include "access/htup_details.h"
#include "access/table.h"
#include "catalog/indexing.h"
#include "catalog/pg_statistic_ext.h"
#include "catalog/pg_statistic_ext_data.h"
#include "commands/defrem.h"
#include "commands/progress.h"
#include "executor/executor.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "parser/parsetree.h"
#include "pgstat.h"
#include "postmaster/autovacuum.h"
#include "rewrite/rewriteHandler.h"
#include "statistics/extended_stats_internal.h"
#include "statistics/statistics.h"
#include "utils/acl.h"
#include "utils/array.h"
#include "utils/attoptcache.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/selfuncs.h"
#include "utils/syscache.h"
Include dependency graph for extended_stats.c:

Go to the source code of this file.

Data Structures

struct  StatExtEntry
 
struct  AnlExprData
 

Macros

#define WIDTH_THRESHOLD   1024
 

Typedefs

typedef struct StatExtEntry StatExtEntry
 
typedef struct AnlExprData AnlExprData
 

Functions

static Listfetch_statentries_for_relation (Relation pg_statext, Relation rel)
 
static VacAttrStats ** lookup_var_attr_stats (Bitmapset *attrs, List *exprs, int nvacatts, VacAttrStats **vacatts)
 
static void statext_store (Oid statOid, bool inh, MVNDistinct *ndistinct, MVDependencies *dependencies, MCVList *mcv, Datum exprs, VacAttrStats **stats)
 
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)
 
static Datum serialize_expr_stats (AnlExprData *exprdata, int nexprs)
 
static Datum expr_fetch_func (VacAttrStatsP stats, int rownum, bool *isNull)
 
static AnlExprDatabuild_expr_data (List *exprs, int stattarget)
 
static StatsBuildDatamake_build_data (Relation rel, StatExtEntry *stat, int numrows, HeapTuple *rows, VacAttrStats **stats, int stattarget)
 
void BuildRelationExtStatistics (Relation onerel, bool inh, double totalrows, int numrows, HeapTuple *rows, int natts, VacAttrStats **vacattrstats)
 
bool HasRelationExtStatistics (Relation onerel)
 
int ComputeExtStatisticsRows (Relation onerel, int natts, VacAttrStats **vacattrstats)
 
bool statext_is_kind_built (HeapTuple htup, char type)
 
static VacAttrStatsexamine_attribute (Node *expr)
 
static VacAttrStatsexamine_expression (Node *expr, int stattarget)
 
MultiSortSupport multi_sort_init (int ndims)
 
void multi_sort_add_dimension (MultiSortSupport mss, int sortdim, Oid oper, Oid collation)
 
int multi_sort_compare (const void *a, const void *b, void *arg)
 
int multi_sort_compare_dim (int dim, const SortItem *a, const SortItem *b, MultiSortSupport mss)
 
int multi_sort_compare_dims (int start, int end, const SortItem *a, const SortItem *b, MultiSortSupport mss)
 
int compare_scalars_simple (const void *a, const void *b, void *arg)
 
int compare_datums_simple (Datum a, Datum b, SortSupport ssup)
 
AttrNumberbuild_attnums_array (Bitmapset *attrs, int nexprs, int *numattrs)
 
SortItembuild_sorted_items (StatsBuildData *data, int *nitems, MultiSortSupport mss, int numattrs, AttrNumber *attnums)
 
bool has_stats_of_kind (List *stats, char requiredkind)
 
static int stat_find_expression (StatisticExtInfo *stat, Node *expr)
 
static bool stat_covers_expressions (StatisticExtInfo *stat, List *exprs, Bitmapset **expr_idxs)
 
StatisticExtInfochoose_best_statistics (List *stats, char requiredkind, bool inh, Bitmapset **clause_attnums, List **clause_exprs, int nclauses)
 
static bool statext_is_compatible_clause_internal (PlannerInfo *root, Node *clause, Index relid, Bitmapset **attnums, List **exprs, bool *leakproof)
 
static bool statext_is_compatible_clause (PlannerInfo *root, Node *clause, Index relid, Bitmapset **attnums, List **exprs)
 
static Selectivity statext_mcv_clauselist_selectivity (PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Bitmapset **estimatedclauses, bool is_or)
 
Selectivity statext_clauselist_selectivity (PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Bitmapset **estimatedclauses, bool is_or)
 
bool examine_opclause_args (List *args, Node **exprp, Const **cstp, bool *expronleftp)
 
HeapTuple statext_expressions_load (Oid stxoid, bool inh, int idx)
 

Macro Definition Documentation

◆ WIDTH_THRESHOLD

#define WIDTH_THRESHOLD   1024

Definition at line 59 of file extended_stats.c.

Typedef Documentation

◆ AnlExprData

◆ StatExtEntry

Function Documentation

◆ build_attnums_array()

AttrNumber * build_attnums_array ( Bitmapset attrs,
int  nexprs,
int numattrs 
)

Definition at line 987 of file extended_stats.c.

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}
int16 AttrNumber
Definition attnum.h:21
#define AttributeNumberIsValid(attributeNumber)
Definition attnum.h:34
#define MaxAttrNumber
Definition attnum.h:24
int bms_next_member(const Bitmapset *a, int prevbit)
Definition bitmapset.c:1425
int bms_num_members(const Bitmapset *a)
Definition bitmapset.c:879
#define Assert(condition)
Definition c.h:1002
#define palloc_array(type, count)
Definition fe_memutils.h:91
int j
Definition isn.c:78
int i
Definition isn.c:77
int16 attnum
static int fb(int x)

References Assert, attnum, AttributeNumberIsValid, bms_next_member(), bms_num_members(), fb(), i, j, MaxAttrNumber, and palloc_array.

◆ build_expr_data()

static AnlExprData * build_expr_data ( List exprs,
int  stattarget 
)
static

Definition at line 2289 of file extended_stats.c.

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}
Datum idx(PG_FUNCTION_ARGS)
Definition _int_op.c:263
static VacAttrStats * examine_expression(Node *expr, int stattarget)
void * palloc0(Size size)
Definition mcxt.c:1420
#define lfirst(lc)
Definition pg_list.h:172
static int list_length(const List *l)
Definition pg_list.h:152
Definition nodes.h:133

References examine_expression(), AnlExprData::expr, fb(), idx(), lfirst, list_length(), and palloc0().

Referenced by BuildRelationExtStatistics().

◆ build_sorted_items()

SortItem * build_sorted_items ( StatsBuildData data,
int nitems,
MultiSortSupport  mss,
int  numattrs,
AttrNumber attnums 
)

Definition at line 1032 of file extended_stats.c.

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}
static Datum values[MAXATTR]
Definition bootstrap.c:190
#define MAXALIGN(LEN)
Definition c.h:955
size_t Size
Definition c.h:748
Size toast_raw_datum_size(Datum value)
Definition detoast.c:545
#define WIDTH_THRESHOLD
int multi_sort_compare(const void *a, const void *b, void *arg)
#define PG_DETOAST_DATUM(datum)
Definition fmgr.h:240
#define nitems(x)
Definition indent.h:31
static struct @175 value
int16 get_typlen(Oid typid)
Definition lsyscache.c:2511
void pfree(void *pointer)
Definition mcxt.c:1619
int16 attlen
const void size_t len
const void * data
void qsort_interruptible(void *base, size_t nel, size_t elsize, qsort_arg_comparator cmp, void *arg)
uint64_t Datum
Definition postgres.h:70
#define PointerGetDatum(X)
Definition postgres.h:354
static ItemArray items

References Assert, attlen, attnum, data, fb(), get_typlen(), i, idx(), items, j, len, MAXALIGN, multi_sort_compare(), nitems, palloc0(), palloc_array, pfree(), PG_DETOAST_DATUM, PointerGetDatum, qsort_interruptible(), toast_raw_datum_size(), value, values, and WIDTH_THRESHOLD.

Referenced by dependency_degree(), and statext_mcv_build().

◆ BuildRelationExtStatistics()

void BuildRelationExtStatistics ( Relation  onerel,
bool  inh,
double  totalrows,
int  numrows,
HeapTuple rows,
int  natts,
VacAttrStats **  vacattrstats 
)

Definition at line 112 of file extended_stats.c.

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}
void pgstat_progress_update_param(int index, int64 val)
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
int64_t int64
Definition c.h:680
MVDependencies * statext_dependencies_build(StatsBuildData *data)
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
static AnlExprData * build_expr_data(List *exprs, int stattarget)
static VacAttrStats ** lookup_var_attr_stats(Bitmapset *attrs, List *exprs, int nvacatts, VacAttrStats **vacatts)
static List * fetch_statentries_for_relation(Relation pg_statext, Relation rel)
static StatsBuildData * make_build_data(Relation rel, StatExtEntry *stat, int numrows, HeapTuple *rows, VacAttrStats **stats, int stattarget)
static void statext_store(Oid statOid, bool inh, MVNDistinct *ndistinct, MVDependencies *dependencies, MCVList *mcv, Datum exprs, VacAttrStats **stats)
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)
static Datum serialize_expr_stats(AnlExprData *exprdata, int nexprs)
long val
Definition informix.c:689
void list_free(List *list)
Definition list.c:1546
#define RowExclusiveLock
Definition lockdefs.h:38
char * get_namespace_name(Oid nspid)
Definition lsyscache.c:3682
MCVList * statext_mcv_build(StatsBuildData *data, double totalrows, int stattarget)
Definition mcv.c:178
void MemoryContextReset(MemoryContext context)
Definition mcxt.c:406
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
MVNDistinct * statext_ndistinct_build(double totalrows, StatsBuildData *data)
Definition mvdistinct.c:85
static char * errmsg
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:138
#define NIL
Definition pg_list.h:68
#define lfirst_int(lc)
Definition pg_list.h:173
#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
#define RelationGetRelationName(relation)
Definition rel.h:550
int errtable(Relation rel)
Definition relcache.c:6084
Definition pg_list.h:54
Definition type.h:97
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, AmAutoVacuumWorkerProcess, bms_num_members(), build_expr_data(), compute_expr_stats(), CurrentMemoryContext, data, elog, ereport, errcode(), errmsg, ERROR, errtable(), fb(), fetch_statentries_for_relation(), get_namespace_name(), lfirst, lfirst_int, list_free(), list_length(), lookup_var_attr_stats(), make_build_data(), MemoryContextDelete(), MemoryContextReset(), MemoryContextSwitchTo(), NIL, pgstat_progress_update_multi_param(), pgstat_progress_update_param(), PROGRESS_ANALYZE_EXT_STATS_COMPUTED, PROGRESS_ANALYZE_EXT_STATS_TOTAL, PROGRESS_ANALYZE_PHASE, PROGRESS_ANALYZE_PHASE_COMPUTE_EXT_STATS, RelationGetRelationName, RowExclusiveLock, serialize_expr_stats(), statext_compute_stattarget(), statext_dependencies_build(), statext_mcv_build(), statext_ndistinct_build(), statext_store(), table_close(), table_open(), val, and WARNING.

Referenced by do_analyze_rel().

◆ choose_best_statistics()

StatisticExtInfo * choose_best_statistics ( List stats,
char  requiredkind,
bool  inh,
Bitmapset **  clause_attnums,
List **  clause_exprs,
int  nclauses 
)

Definition at line 1256 of file extended_stats.c.

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}
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:547
void bms_free(Bitmapset *a)
Definition bitmapset.c:240
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:1036
static bool stat_covers_expressions(StatisticExtInfo *stat, List *exprs, Bitmapset **expr_idxs)
#define STATS_MAX_DIMENSIONS
Definition statistics.h:19
Bitmapset * keys
Definition pathnodes.h:1529

References bms_add_members(), bms_free(), bms_is_subset(), bms_num_members(), StatisticExtInfo::exprs, fb(), i, StatisticExtInfo::inherit, StatisticExtInfo::keys, StatisticExtInfo::kind, lfirst, list_length(), stat_covers_expressions(), and STATS_MAX_DIMENSIONS.

Referenced by statext_mcv_clauselist_selectivity().

◆ compare_datums_simple()

int compare_datums_simple ( Datum  a,
Datum  b,
SortSupport  ssup 
)

Definition at line 973 of file extended_stats.c.

974{
975 return ApplySortComparator(a, false, b, false, ssup);
976}
int b
Definition isn.c:74
int a
Definition isn.c:73
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)

References a, ApplySortComparator(), and b.

Referenced by compare_scalars_simple(), and statext_mcv_serialize().

◆ compare_scalars_simple()

int compare_scalars_simple ( const void a,
const void b,
void arg 
)

Definition at line 965 of file extended_stats.c.

966{
967 return compare_datums_simple(*(const Datum *) a,
968 *(const Datum *) b,
969 (SortSupport) arg);
970}
Datum arg
Definition elog.c:1323
int compare_datums_simple(Datum a, Datum b, SortSupport ssup)

References a, arg, b, and compare_datums_simple().

Referenced by statext_mcv_serialize().

◆ compute_expr_stats()

static void compute_expr_stats ( Relation  onerel,
AnlExprData exprdata,
int  nexprs,
HeapTuple rows,
int  numrows 
)
static

Definition at line 2130 of file extended_stats.c.

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}
AttributeOpts * get_attribute_options(Oid attrelid, int attnum)
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition datum.c:132
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition execExpr.c:765
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 ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition executor.h:444
static Datum expr_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
void * palloc(Size size)
Definition mcxt.c:1390
#define RelationGetDescr(relation)
Definition rel.h:542
TupleTableSlot * ecxt_scantuple
Definition execnodes.h:287
Form_pg_type attrtype
Definition vacuum.h:127
int tupattnum
Definition vacuum.h:170
int rowstride
Definition vacuum.h:175
bool * exprnulls
Definition vacuum.h:174
Datum * exprvals
Definition vacuum.h:173
float4 stadistinct
Definition vacuum.h:146
AnalyzeAttrComputeStatsFunc compute_stats
Definition vacuum.h:135

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, VacAttrStats::attrtype, VacAttrStats::compute_stats, CreateExecutorState(), CurrentMemoryContext, datumCopy(), ExprContext::ecxt_scantuple, ExecDropSingleTupleTableSlot(), ExecEvalExprSwitchContext(), ExecPrepareExpr(), ExecStoreHeapTuple(), expr_fetch_func(), VacAttrStats::exprnulls, VacAttrStats::exprvals, fb(), FreeExecutorState(), get_attribute_options(), GetPerTupleExprContext, i, MakeSingleTupleTableSlot(), MemoryContextDelete(), MemoryContextReset(), MemoryContextSwitchTo(), palloc(), RelationGetDescr, ResetExprContext, VacAttrStats::rowstride, VacAttrStats::stadistinct, TTSOpsHeapTuple, and VacAttrStats::tupattnum.

Referenced by BuildRelationExtStatistics().

◆ ComputeExtStatisticsRows()

int ComputeExtStatisticsRows ( Relation  onerel,
int  natts,
VacAttrStats **  vacattrstats 
)

Definition at line 297 of file extended_stats.c.

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}
uint32 result

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, bms_num_members(), CurrentMemoryContext, fb(), fetch_statentries_for_relation(), lfirst, lookup_var_attr_stats(), MemoryContextDelete(), MemoryContextSwitchTo(), result, RowExclusiveLock, statext_compute_stattarget(), table_close(), and table_open().

Referenced by do_analyze_rel().

◆ examine_attribute()

static VacAttrStats * examine_attribute ( Node expr)
static

Definition at line 564 of file extended_stats.c.

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}
#define InvalidAttrNumber
Definition attnum.h:23
#define OidIsValid(objectId)
Definition c.h:917
bool std_typanalyze(VacAttrStats *stats)
Definition analyze.c:1950
#define palloc0_object(type)
Definition fe_memutils.h:90
#define OidFunctionCall1(functionId, arg1)
Definition fmgr.h:726
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1372
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
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
#define STATISTIC_NUM_SLOTS
END_CATALOG_STRUCT typedef FormData_pg_type * Form_pg_type
Definition pg_type.h:265
static bool DatumGetBool(Datum X)
Definition postgres.h:100
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
int32 attrtypmod
Definition vacuum.h:126
MemoryContext anl_context
Definition vacuum.h:129
Oid statypid[STATISTIC_NUM_SLOTS]
Definition vacuum.h:161
char statypalign[STATISTIC_NUM_SLOTS]
Definition vacuum.h:164
Oid attrtypid
Definition vacuum.h:125
int minrows
Definition vacuum.h:136
int attstattarget
Definition vacuum.h:124
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition vacuum.h:163
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition vacuum.h:162
Oid attrcollid
Definition vacuum.h:128
#define SearchSysCacheCopy1(cacheId, key1)
Definition syscache.h:91

References VacAttrStats::anl_context, VacAttrStats::attrcollid, VacAttrStats::attrtype, VacAttrStats::attrtypid, VacAttrStats::attrtypmod, VacAttrStats::attstattarget, VacAttrStats::compute_stats, DatumGetBool(), elog, ERROR, exprCollation(), exprType(), exprTypmod(), fb(), Form_pg_type, GETSTRUCT(), heap_freetuple(), HeapTupleIsValid, i, InvalidAttrNumber, VacAttrStats::minrows, ObjectIdGetDatum(), OidFunctionCall1, OidIsValid, palloc0_object, pfree(), PointerGetDatum, SearchSysCacheCopy1, STATISTIC_NUM_SLOTS, VacAttrStats::statypalign, VacAttrStats::statypbyval, VacAttrStats::statypid, VacAttrStats::statyplen, std_typanalyze(), and VacAttrStats::tupattnum.

Referenced by lookup_var_attr_stats().

◆ examine_expression()

static VacAttrStats * examine_expression ( Node expr,
int  stattarget 
)
static

Definition at line 643 of file extended_stats.c.

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}

References VacAttrStats::anl_context, Assert, VacAttrStats::attrcollid, VacAttrStats::attrtype, VacAttrStats::attrtypid, VacAttrStats::attrtypmod, VacAttrStats::attstattarget, VacAttrStats::compute_stats, CurrentMemoryContext, DatumGetBool(), elog, ERROR, exprCollation(), exprType(), exprTypmod(), fb(), Form_pg_type, GETSTRUCT(), heap_freetuple(), HeapTupleIsValid, i, InvalidAttrNumber, VacAttrStats::minrows, ObjectIdGetDatum(), OidFunctionCall1, OidIsValid, palloc0_object, pfree(), PointerGetDatum, SearchSysCacheCopy1, STATISTIC_NUM_SLOTS, VacAttrStats::statypalign, VacAttrStats::statypbyval, VacAttrStats::statypid, VacAttrStats::statyplen, std_typanalyze(), and VacAttrStats::tupattnum.

Referenced by build_expr_data(), and make_build_data().

◆ examine_opclause_args()

bool examine_opclause_args ( List args,
Node **  exprp,
Const **  cstp,
bool expronleftp 
)

Definition at line 2075 of file extended_stats.c.

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}
#define IsA(nodeptr, _type_)
Definition nodes.h:162
#define linitial(l)
Definition pg_list.h:178
#define lsecond(l)
Definition pg_list.h:183

References arg, Assert, fb(), IsA, linitial, list_length(), and lsecond.

Referenced by mcv_get_match_bitmap(), and statext_is_compatible_clause_internal().

◆ expr_fetch_func()

static Datum expr_fetch_func ( VacAttrStatsP  stats,
int  rownum,
bool isNull 
)
static

Definition at line 2273 of file extended_stats.c.

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}

References VacAttrStats::exprnulls, VacAttrStats::exprvals, i, and VacAttrStats::rowstride.

Referenced by compute_expr_stats().

◆ fetch_statentries_for_relation()

static List * fetch_statentries_for_relation ( Relation  pg_statext,
Relation  rel 
)
static

Definition at line 454 of file extended_stats.c.

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}
#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
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:934
#define TextDatumGetCString(d)
Definition builtins.h:99
#define NameStr(name)
Definition c.h:894
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition clauses.c:2516
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
List * lappend(List *list, void *datum)
Definition list.c:339
List * lappend_int(List *list, int datum)
Definition list.c:357
char * pstrdup(const char *in)
Definition mcxt.c:1910
void fix_opfuncids(Node *node)
Definition nodeFuncs.c:1859
END_CATALOG_STRUCT typedef FormData_pg_statistic_ext * Form_pg_statistic_ext
static int16 DatumGetInt16(Datum X)
Definition postgres.h:162
unsigned int Oid
void * stringToNode(const char *str)
Definition read.c:90
#define RelationGetRelid(relation)
Definition rel.h:516
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
#define BTEqualStrategyNumber
Definition stratnum.h:31
Bitmapset * columns
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

References ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_NDIM, Assert, bms_add_member(), BTEqualStrategyNumber, StatExtEntry::columns, DatumGetArrayTypeP, DatumGetInt16(), elog, ERROR, eval_const_expressions(), expand_generated_columns_in_expr(), StatExtEntry::exprs, fb(), fix_opfuncids(), Form_pg_statistic_ext, get_namespace_name(), GETSTRUCT(), HeapTupleIsValid, i, lappend(), lappend_int(), StatExtEntry::name, NameStr, NIL, ObjectIdGetDatum(), palloc0_object, pfree(), pstrdup(), RelationGetRelid, result, ScanKeyInit(), StatExtEntry::schema, StatExtEntry::statOid, StatExtEntry::stattarget, stringToNode(), SysCacheGetAttr(), SysCacheGetAttrNotNull(), systable_beginscan(), systable_endscan(), systable_getnext(), TextDatumGetCString, and StatExtEntry::types.

Referenced by BuildRelationExtStatistics(), and ComputeExtStatisticsRows().

◆ has_stats_of_kind()

bool has_stats_of_kind ( List stats,
char  requiredkind 
)

Definition at line 1165 of file extended_stats.c.

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}

References fb(), and lfirst.

Referenced by dependencies_clauselist_selectivity(), and statext_mcv_clauselist_selectivity().

◆ HasRelationExtStatistics()

bool HasRelationExtStatistics ( Relation  onerel)

Definition at line 253 of file extended_stats.c.

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}

References BTEqualStrategyNumber, fb(), HeapTupleIsValid, ObjectIdGetDatum(), RelationGetRelid, RowExclusiveLock, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), and table_open().

Referenced by postgresImportForeignStatistics().

◆ lookup_var_attr_stats()

static VacAttrStats ** lookup_var_attr_stats ( Bitmapset attrs,
List exprs,
int  nvacatts,
VacAttrStats **  vacatts 
)
static

Definition at line 729 of file extended_stats.c.

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}
static VacAttrStats * examine_attribute(Node *expr)
int x
Definition isn.c:75
TupleDesc tupDesc
Definition vacuum.h:172

References bms_next_member(), bms_num_members(), examine_attribute(), fb(), i, j, lfirst, list_length(), palloc(), pfree(), VacAttrStats::tupDesc, and x.

Referenced by BuildRelationExtStatistics(), and ComputeExtStatisticsRows().

◆ make_build_data()

static StatsBuildData * make_build_data ( Relation  rel,
StatExtEntry stat,
int  numrows,
HeapTuple rows,
VacAttrStats **  stats,
int  stattarget 
)
static

Definition at line 2501 of file extended_stats.c.

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}
List * ExecPrepareExprList(List *nodes, EState *estate)
Definition execExpr.c:839
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition executor.h:401
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)

References Assert, bms_next_member(), bms_num_members(), CreateExecutorState(), ExprContext::ecxt_scantuple, examine_expression(), ExecDropSingleTupleTableSlot(), ExecEvalExpr(), ExecPrepareExprList(), ExecStoreHeapTuple(), fb(), FreeExecutorState(), GetPerTupleExprContext, heap_getattr(), i, idx(), len, lfirst, list_length(), MakeSingleTupleTableSlot(), MAXALIGN, NIL, palloc(), RelationGetDescr, ResetExprContext, result, and TTSOpsHeapTuple.

Referenced by BuildRelationExtStatistics().

◆ multi_sort_add_dimension()

void multi_sort_add_dimension ( MultiSortSupport  mss,
int  sortdim,
Oid  oper,
Oid  collation 
)

Definition at line 897 of file extended_stats.c.

899{
900 SortSupport ssup = &mss->ssup[sortdim];
901
903 ssup->ssup_collation = collation;
904 ssup->ssup_nulls_first = false;
905
907}
Operator oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId, bool noError, int location)
Definition parse_oper.c:376
void PrepareSortSupportFromOrderingOp(Oid orderingOp, SortSupport ssup)
MemoryContext ssup_cxt
Definition sortsupport.h:66

References CurrentMemoryContext, fb(), oper(), PrepareSortSupportFromOrderingOp(), SortSupportData::ssup_collation, SortSupportData::ssup_cxt, and SortSupportData::ssup_nulls_first.

Referenced by build_mss(), dependency_degree(), and ndistinct_for_combination().

◆ multi_sort_compare()

int multi_sort_compare ( const void a,
const void b,
void arg 
)

Definition at line 911 of file extended_stats.c.

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}
MultiSortSupportData * MultiSortSupport
static int compare(const void *arg1, const void *arg2)
Definition geqo_pool.c:145

References a, ApplySortComparator(), arg, b, compare(), fb(), and i.

Referenced by build_distinct_groups(), build_sorted_items(), count_distinct_groups(), ndistinct_for_combination(), and statext_mcv_build().

◆ multi_sort_compare_dim()

int multi_sort_compare_dim ( int  dim,
const SortItem a,
const SortItem b,
MultiSortSupport  mss 
)

Definition at line 936 of file extended_stats.c.

938{
939 return ApplySortComparator(a->values[dim], a->isnull[dim],
940 b->values[dim], b->isnull[dim],
941 &mss->ssup[dim]);
942}

References a, ApplySortComparator(), b, and fb().

Referenced by dependency_degree().

◆ multi_sort_compare_dims()

int multi_sort_compare_dims ( int  start,
int  end,
const SortItem a,
const SortItem b,
MultiSortSupport  mss 
)

Definition at line 945 of file extended_stats.c.

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}
return str start

References a, ApplySortComparator(), b, fb(), and start.

Referenced by dependency_degree().

◆ multi_sort_init()

MultiSortSupport multi_sort_init ( int  ndims)

Definition at line 878 of file extended_stats.c.

879{
881
882 Assert(ndims >= 2);
883
885 + sizeof(SortSupportData) * ndims);
886
887 mss->ndims = ndims;
888
889 return mss;
890}

References Assert, fb(), and palloc0().

Referenced by build_mss(), dependency_degree(), and ndistinct_for_combination().

◆ serialize_expr_stats()

static Datum serialize_expr_stats ( AnlExprData exprdata,
int  nexprs 
)
static

Definition at line 2314 of file extended_stats.c.

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}
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)
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition heaptuple.c:1025
Datum heap_copy_tuple_as_datum(HeapTuple tuple, TupleDesc tupleDesc)
Definition heaptuple.c:989
Oid get_rel_type_id(Oid relid)
Definition lsyscache.c:2293
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 Int32GetDatum(int32 X)
Definition postgres.h:212
#define InvalidOid
bool stats_valid
Definition vacuum.h:143
float4 stanullfrac
Definition vacuum.h:144
int16 stakind[STATISTIC_NUM_SLOTS]
Definition vacuum.h:147
Oid staop[STATISTIC_NUM_SLOTS]
Definition vacuum.h:148
Oid stacoll[STATISTIC_NUM_SLOTS]
Definition vacuum.h:149
float4 * stanumbers[STATISTIC_NUM_SLOTS]
Definition vacuum.h:151
int32 stawidth
Definition vacuum.h:145
int numvalues[STATISTIC_NUM_SLOTS]
Definition vacuum.h:152
Datum * stavalues[STATISTIC_NUM_SLOTS]
Definition vacuum.h:153
int numnumbers[STATISTIC_NUM_SLOTS]
Definition vacuum.h:150

References accumArrayResult(), BoolGetDatum(), construct_array(), construct_array_builtin(), CurrentMemoryContext, ereport, errcode(), errmsg, ERROR, fb(), Float4GetDatum(), get_rel_type_id(), heap_copy_tuple_as_datum(), heap_form_tuple(), i, Int16GetDatum(), Int32GetDatum(), InvalidAttrNumber, InvalidOid, makeArrayResult(), VacAttrStats::numnumbers, VacAttrStats::numvalues, ObjectIdGetDatum(), OidIsValid, palloc(), PointerGetDatum, RelationGetDescr, RowExclusiveLock, VacAttrStats::stacoll, VacAttrStats::stadistinct, VacAttrStats::stakind, VacAttrStats::stanullfrac, VacAttrStats::stanumbers, VacAttrStats::staop, STATISTIC_NUM_SLOTS, VacAttrStats::stats_valid, VacAttrStats::statypalign, VacAttrStats::statypbyval, VacAttrStats::statypid, VacAttrStats::statyplen, VacAttrStats::stavalues, VacAttrStats::stawidth, table_close(), table_open(), and values.

Referenced by BuildRelationExtStatistics().

◆ stat_covers_expressions()

static bool stat_covers_expressions ( StatisticExtInfo stat,
List exprs,
Bitmapset **  expr_idxs 
)
static

Definition at line 1215 of file extended_stats.c.

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}
static int stat_find_expression(StatisticExtInfo *stat, Node *expr)

References bms_add_member(), fb(), lfirst, and stat_find_expression().

Referenced by choose_best_statistics(), and statext_mcv_clauselist_selectivity().

◆ stat_find_expression()

static int stat_find_expression ( StatisticExtInfo stat,
Node expr 
)
static

Definition at line 1188 of file extended_stats.c.

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}
bool equal(const void *a, const void *b)
Definition equalfuncs.c:223

References equal(), fb(), idx(), and lfirst.

Referenced by stat_covers_expressions().

◆ statext_clauselist_selectivity()

Selectivity statext_clauselist_selectivity ( PlannerInfo root,
List clauses,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo,
RelOptInfo rel,
Bitmapset **  estimatedclauses,
bool  is_or 
)

Definition at line 2024 of file extended_stats.c.

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}
Selectivity dependencies_clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Bitmapset **estimatedclauses)
static Selectivity statext_mcv_clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Bitmapset **estimatedclauses, bool is_or)
double Selectivity
Definition nodes.h:258
tree ctl root
Definition radixtree.h:1857

References dependencies_clauselist_selectivity(), fb(), root, and statext_mcv_clauselist_selectivity().

Referenced by clauselist_selectivity_ext(), and clauselist_selectivity_or().

◆ statext_compute_stattarget()

static int statext_compute_stattarget ( int  stattarget,
int  nattrs,
VacAttrStats **  stats 
)
static

Definition at line 379 of file extended_stats.c.

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}
int default_statistics_target
Definition analyze.c:71
#define MAX_STATISTICS_TARGET
Definition vacuum.h:350

References Assert, VacAttrStats::attstattarget, default_statistics_target, i, and MAX_STATISTICS_TARGET.

Referenced by BuildRelationExtStatistics(), and ComputeExtStatisticsRows().

◆ statext_expressions_load()

HeapTuple statext_expressions_load ( Oid  stxoid,
bool  inh,
int  idx 
)

Definition at line 2447 of file extended_stats.c.

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}
void deconstruct_expanded_array(ExpandedArrayHeader *eah)
ExpandedArrayHeader * DatumGetExpandedArray(Datum d)
#define DatumGetHeapTupleHeader(X)
Definition fmgr.h:296
HeapTuple heap_copytuple(HeapTuple tuple)
Definition heaptuple.c:686
static uint32 HeapTupleHeaderGetDatumLength(const HeapTupleHeaderData *tup)
static void ItemPointerSetInvalid(ItemPointerData *pointer)
Definition itemptr.h:184
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
HeapTuple SearchSysCache2(SysCacheIdentifier cacheId, Datum key1, Datum key2)
Definition syscache.c:231

References BoolGetDatum(), DatumGetExpandedArray(), DatumGetHeapTupleHeader, deconstruct_expanded_array(), elog, ERROR, fb(), heap_copytuple(), HeapTupleHeaderGetDatumLength(), HeapTupleIsValid, idx(), InvalidOid, ItemPointerSetInvalid(), ObjectIdGetDatum(), ReleaseSysCache(), SearchSysCache2(), SysCacheGetAttr(), and value.

Referenced by examine_variable().

◆ statext_is_compatible_clause()

static bool statext_is_compatible_clause ( PlannerInfo root,
Node clause,
Index  relid,
Bitmapset **  attnums,
List **  exprs 
)
static

Definition at line 1605 of file extended_stats.c.

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}
Bitmapset * bms_offset_members(const Bitmapset *a, int offset)
Definition bitmapset.c:419
bool bms_get_singleton_member(const Bitmapset *a, int *member)
Definition bitmapset.c:843
static bool statext_is_compatible_clause_internal(PlannerInfo *root, Node *clause, Index relid, Bitmapset **attnums, List **exprs, bool *leakproof)
static bool statext_is_compatible_clause(PlannerInfo *root, Node *clause, Index relid, Bitmapset **attnums, List **exprs)
static bool is_andclause(const void *clause)
Definition nodeFuncs.h:107
bool all_rows_selectable(PlannerInfo *root, Index varno, Bitmapset *varattnos)
Definition selfuncs.c:6415
List * args
Definition primnodes.h:954
Expr * clause
Definition pathnodes.h:2901
#define FirstLowInvalidHeapAttributeNumber
Definition sysattr.h:27
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition var.c:296

References all_rows_selectable(), BoolExpr::args, bms_get_singleton_member(), bms_offset_members(), RestrictInfo::clause, fb(), FirstLowInvalidHeapAttributeNumber, is_andclause(), IsA, lfirst, NIL, pull_varattnos(), root, statext_is_compatible_clause(), and statext_is_compatible_clause_internal().

Referenced by statext_is_compatible_clause(), and statext_mcv_clauselist_selectivity().

◆ statext_is_compatible_clause_internal()

static bool statext_is_compatible_clause_internal ( PlannerInfo root,
Node clause,
Index  relid,
Bitmapset **  attnums,
List **  exprs,
bool leakproof 
)
static

Definition at line 1378 of file extended_stats.c.

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}
#define AttrNumberIsForUserDefinedAttr(attributeNumber)
Definition attnum.h:41
bool examine_opclause_args(List *args, Node **exprp, Const **cstp, bool *expronleftp)
RegProcedure get_oprrest(Oid opno)
Definition lsyscache.c:1871
RegProcedure get_opcode(Oid opno)
Definition lsyscache.c:1585
bool get_func_leakproof(Oid funcid)
Definition lsyscache.c:2151
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
Oid opno
Definition primnodes.h:835
List * args
Definition primnodes.h:853
AttrNumber varattno
Definition primnodes.h:275
int varno
Definition primnodes.h:270
Index varlevelsup
Definition primnodes.h:295

References arg, OpExpr::args, ScalarArrayOpExpr::args, BoolExpr::args, AttrNumberIsForUserDefinedAttr, bms_add_member(), examine_opclause_args(), fb(), get_func_leakproof(), get_opcode(), get_oprrest(), is_andclause(), is_notclause(), is_opclause(), is_orclause(), IsA, lappend(), lfirst, list_length(), OpExpr::opno, ScalarArrayOpExpr::opno, root, statext_is_compatible_clause_internal(), Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by statext_is_compatible_clause(), and statext_is_compatible_clause_internal().

◆ statext_is_kind_built()

bool statext_is_kind_built ( HeapTuple  htup,
char  type 
)

Definition at line 421 of file extended_stats.c.

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}
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition heaptuple.c:456
const char * type

References attnum, elog, ERROR, fb(), heap_attisnull(), and type.

Referenced by get_relation_statistics_worker().

◆ statext_mcv_clauselist_selectivity()

static Selectivity statext_mcv_clauselist_selectivity ( PlannerInfo root,
List clauses,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo,
RelOptInfo rel,
Bitmapset **  estimatedclauses,
bool  is_or 
)
static

Definition at line 1737 of file extended_stats.c.

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}
bool bms_is_member(int x, const Bitmapset *a)
Definition bitmapset.c:645
BMS_Membership bms_membership(const Bitmapset *a)
Definition bitmapset.c:900
@ BMS_SINGLETON
Definition bitmapset.h:72
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
bool has_stats_of_kind(List *stats, char requiredkind)
StatisticExtInfo * choose_best_statistics(List *stats, char requiredkind, bool inh, Bitmapset **clause_attnums, List **clause_exprs, int nclauses)
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
#define planner_rt_fetch(rti, root)
Definition pathnodes.h:704
#define CLAMP_PROBABILITY(p)
Definition selfuncs.h:63
Index relid
Definition pathnodes.h:1069
List * statlist
Definition pathnodes.h:1093
#define stat
Definition win32_port.h:74

References Assert, bms_add_member(), bms_free(), bms_is_member(), bms_is_subset(), bms_membership(), BMS_SINGLETON, choose_best_statistics(), CLAMP_PROBABILITY, clause_selectivity_ext(), clauselist_selectivity_ext(), fb(), has_stats_of_kind(), lappend(), lfirst, list_free(), list_length(), mcv_clause_selectivity_or(), mcv_clauselist_selectivity(), mcv_combine_selectivities(), NIL, palloc_array, planner_rt_fetch, RelOptInfo::relid, root, stat, stat_covers_expressions(), statext_is_compatible_clause(), statext_mcv_load(), and RelOptInfo::statlist.

Referenced by statext_clauselist_selectivity().

◆ statext_store()

static void statext_store ( Oid  statOid,
bool  inh,
MVNDistinct ndistinct,
MVDependencies dependencies,
MCVList mcv,
Datum  exprs,
VacAttrStats **  stats 
)
static

Definition at line 808 of file extended_stats.c.

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}
bytea * statext_dependencies_serialize(MVDependencies *dependencies)
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition indexing.c:233
bytea * statext_mcv_serialize(MCVList *mcvlist, VacAttrStats **stats)
Definition mcv.c:619
bytea * statext_ndistinct_serialize(MVNDistinct *ndistinct)
Definition mvdistinct.c:176
void RemoveStatisticsDataById(Oid statsOid, bool inh)
Definition statscmds.c:792
Definition c.h:835

References BoolGetDatum(), CatalogTupleInsert(), data, fb(), heap_form_tuple(), heap_freetuple(), ObjectIdGetDatum(), PointerGetDatum, RelationGetDescr, RemoveStatisticsDataById(), RowExclusiveLock, statext_dependencies_serialize(), statext_mcv_serialize(), statext_ndistinct_serialize(), table_close(), table_open(), and values.

Referenced by BuildRelationExtStatistics().