42 #include "utils/fmgroids.h"
58 #define WIDTH_THRESHOLD 1024
133 "BuildRelationExtStatistics",
138 if (statslist !=
NIL)
140 const int index[] = {
144 const int64
val[] = {
153 foreach(lc, statslist)
170 natts, vacattrstats);
175 (
errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
176 errmsg(
"statistics object \"%s.%s\" could not be computed for relation \"%s.%s\"",
201 foreach(lc2,
stat->types)
205 if (t == STATS_EXT_NDISTINCT)
207 else if (t == STATS_EXT_DEPENDENCIES)
209 else if (t == STATS_EXT_MCV)
211 else if (t == STATS_EXT_EXPRESSIONS)
218 elog(
ERROR,
"requested expression stats, but there are no expressions");
233 ndistinct, dependencies, mcv, exprstats, stats);
280 "ComputeExtStatisticsRows",
300 natts, vacattrstats);
313 if (stattarget > result)
323 return (300 * result);
363 for (
i = 0;
i < nattrs;
i++)
366 if (stats[
i]->attstattarget > stattarget)
395 case STATS_EXT_NDISTINCT:
396 attnum = Anum_pg_statistic_ext_data_stxdndistinct;
399 case STATS_EXT_DEPENDENCIES:
400 attnum = Anum_pg_statistic_ext_data_stxddependencies;
404 attnum = Anum_pg_statistic_ext_data_stxdmcv;
407 case STATS_EXT_EXPRESSIONS:
408 attnum = Anum_pg_statistic_ext_data_stxdexpr;
412 elog(
ERROR,
"unexpected statistics type requested: %d",
type);
434 Anum_pg_statistic_ext_stxrelid,
457 for (
i = 0;
i < staForm->stxkeys.dim1;
i++)
460 staForm->stxkeys.values[
i]);
463 datum =
SysCacheGetAttr(STATEXTOID, htup, Anum_pg_statistic_ext_stxstattarget, &isnull);
468 Anum_pg_statistic_ext_stxkind);
473 elog(
ERROR,
"stxkind is not a 1-D char array");
477 Assert((enabled[
i] == STATS_EXT_NDISTINCT) ||
478 (enabled[
i] == STATS_EXT_DEPENDENCIES) ||
479 (enabled[
i] == STATS_EXT_MCV) ||
480 (enabled[
i] == STATS_EXT_EXPRESSIONS));
486 Anum_pg_statistic_ext_stxexprs, &isnull);
511 entry->
exprs = exprs;
513 result =
lappend(result, entry);
712 for (
j = 0;
j < nvacatts;
j++)
714 if (
x == vacatts[
j]->tupattnum)
716 stats[
i] = vacatts[
j];
769 bool nulls[Natts_pg_statistic_ext_data];
773 memset(nulls,
true,
sizeof(nulls));
778 nulls[Anum_pg_statistic_ext_data_stxoid - 1] =
false;
781 nulls[Anum_pg_statistic_ext_data_stxdinherit - 1] =
false;
787 if (ndistinct != NULL)
791 nulls[Anum_pg_statistic_ext_data_stxdndistinct - 1] = (
data == NULL);
795 if (dependencies != NULL)
799 nulls[Anum_pg_statistic_ext_data_stxddependencies - 1] = (
data == NULL);
806 nulls[Anum_pg_statistic_ext_data_stxdmcv - 1] = (
data == NULL);
809 if (exprs != (
Datum) 0)
811 nulls[Anum_pg_statistic_ext_data_stxdexpr - 1] =
false;
812 values[Anum_pg_statistic_ext_data_stxdexpr - 1] = exprs;
894 b->values[dim],
b->isnull[dim],
905 for (dim =
start; dim <= end; dim++)
908 b->values[dim],
b->isnull[dim],
994 int nvalues =
data->numrows * numattrs;
1014 ptr += nvalues *
sizeof(
Datum);
1016 isnull = (
bool *) ptr;
1017 ptr += nvalues *
sizeof(
bool);
1024 for (
i = 0;
i <
data->numrows;
i++)
1027 items[nrows].isnull = &isnull[nrows * numattrs];
1033 typlen = (
int *)
palloc(
sizeof(
int) *
data->nattnums);
1034 for (
i = 0;
i <
data->nattnums;
i++)
1038 for (
i = 0;
i <
data->numrows;
i++)
1040 bool toowide =
false;
1043 for (
j = 0;
j < numattrs;
j++)
1059 Assert(idx < data->nattnums);
1074 if ((!isnull) && (
attlen == -1))
1086 items[nrows].isnull[
j] = isnull;
1126 if (
stat->kind == requiredkind)
1147 foreach(lc,
stat->exprs)
1151 if (
equal(stat_expr, expr))
1182 if (expr_idxs != NULL)
1215 int best_num_matched = 2;
1228 if (info->
kind != requiredkind)
1243 for (
i = 0;
i < nclauses;
i++)
1248 if (!clause_attnums[
i] && !clause_exprs[
i])
1278 if (num_matched > best_num_matched ||
1279 (num_matched == best_num_matched && numkeys < best_match_keys))
1282 best_num_matched = num_matched;
1283 best_match_keys = numkeys;
1339 Var *var = (
Var *) clause;
1342 if (var->
varno != relid)
1410 if (rte->securityQuals !=
NIL &&
1415 if (
IsA(clause_expr,
Var))
1417 relid, attnums, exprs);
1420 *exprs =
lappend(*exprs, clause_expr);
1477 if (rte->securityQuals !=
NIL &&
1482 if (
IsA(clause_expr,
Var))
1484 relid, attnums, exprs);
1487 *exprs =
lappend(*exprs, clause_expr);
1513 foreach(lc, expr->
args)
1521 relid, attnums, exprs))
1536 relid, attnums, exprs);
1547 *exprs =
lappend(*exprs, clause);
1595 foreach(lc, expr->
args)
1598 relid, attnums, exprs))
1611 if (rinfo->pseudoconstant)
1616 clause_relid != relid)
1621 relid, attnums, exprs))
1759 list_attnums[listidx] = attnums;
1760 list_exprs[listidx] = exprs;
1764 list_attnums[listidx] = NULL;
1765 list_exprs[listidx] =
NIL;
1780 list_attnums, list_exprs,
1797 simple_clauses = NULL;
1817 if (!list_attnums[listidx] && !list_exprs[listidx])
1838 if ((list_attnums[listidx] == NULL &&
1840 (list_exprs[listidx] ==
NIL &&
1854 list_attnums[listidx] = NULL;
1857 list_exprs[listidx] = NULL;
1862 bool *or_matches = NULL;
1881 foreach(l, stat_clauses)
1901 jointype, sjinfo,
false);
1903 overlap_simple_sel = simple_or_sel * simple_sel;
1909 simple_or_sel += simple_sel - overlap_simple_sel;
1918 clause, &or_matches,
1934 clause_sel = simple_sel;
1947 stat_sel += clause_sel - overlap_sel;
1958 sel = sel + stat_sel - sel * stat_sel;
1981 varRelid, jointype, sjinfo,
2013 sjinfo, rel, estimatedclauses, is_or);
2036 jointype, sjinfo, rel,
2079 expr = (
Node *) leftop;
2080 cst = (
Const *) rightop;
2085 expr = (
Node *) rightop;
2086 cst = (
Const *) leftop;
2100 *expronleftp = expronleft;
2120 "Analyze Expression",
2160 exprnulls = (
bool *)
palloc(numrows *
sizeof(
bool));
2163 for (
i = 0;
i < numrows;
i++)
2187 exprvals[tcnt] = (
Datum) 0;
2188 exprnulls[tcnt] =
true;
2198 exprnulls[tcnt] =
false;
2285 thisdata->
expr = expr;
2309 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
2310 errmsg(
"relation \"%s\" does not have a composite type",
2313 for (exprno = 0; exprno < nexprs; exprno++)
2320 bool nulls[Natts_pg_statistic];
2336 for (
i = 0;
i < Natts_pg_statistic; ++
i)
2347 i = Anum_pg_statistic_stakind1 - 1;
2352 i = Anum_pg_statistic_staop1 - 1;
2357 i = Anum_pg_statistic_stacoll1 - 1;
2362 i = Anum_pg_statistic_stanumbers1 - 1;
2373 for (n = 0; n < nnum; n++)
2384 i = Anum_pg_statistic_stavalues1 - 1;
2438 elog(
ERROR,
"cache lookup failed for statistics object %u", stxoid);
2441 Anum_pg_statistic_ext_data_stxdexpr, &isnull);
2444 "requested statistics kind \"%c\" is not yet built for statistics object %u",
2445 STATS_EXT_EXPRESSIONS, stxoid);
2522 result->
nulls = (
bool **) ptr;
2523 ptr +=
MAXALIGN(
sizeof(
bool *) * nkeys);
2525 for (
i = 0;
i < nkeys;
i++)
2530 result->
nulls[
i] = (
bool *) ptr;
2531 ptr +=
MAXALIGN(
sizeof(
bool) * numrows);
2552 foreach(lc,
stat->exprs)
2564 for (
i = 0;
i < numrows;
i++)
2592 for (
i = 0;
i < numrows;
i++)
2604 foreach(lc, exprstates)
Datum idx(PG_FUNCTION_ARGS)
AclResult pg_attribute_aclcheck_all(Oid table_oid, Oid roleid, AclMode mode, AclMaskHow how)
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
#define DatumGetArrayTypeP(X)
ExpandedArrayHeader * DatumGetExpandedArray(Datum d)
void deconstruct_expanded_array(ExpandedArrayHeader *eah)
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
ArrayType * construct_array_builtin(Datum *elems, int nelems, Oid elmtype)
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
#define AttributeNumberIsValid(attributeNumber)
#define AttrNumberIsForUserDefinedAttr(attributeNumber)
#define InvalidAttrNumber
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)
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
void bms_free(Bitmapset *a)
int bms_num_members(const Bitmapset *a)
bool bms_is_member(int x, const Bitmapset *a)
Bitmapset * bms_add_member(Bitmapset *a, int x)
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
BMS_Membership bms_membership(const Bitmapset *a)
bool bms_get_singleton_member(const Bitmapset *a, int *member)
static Datum values[MAXATTR]
#define TextDatumGetCString(d)
#define Assert(condition)
#define OidIsValid(objectId)
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Selectivity clause_selectivity_ext(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, bool use_extended_stats)
Selectivity clauselist_selectivity_ext(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, bool use_extended_stats)
int default_statistics_target
bool std_typanalyze(VacAttrStats *stats)
Datum datumCopy(Datum value, bool typByVal, int typLen)
bytea * statext_dependencies_serialize(MVDependencies *dependencies)
Selectivity dependencies_clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Bitmapset **estimatedclauses)
MVDependencies * statext_dependencies_build(StatsBuildData *data)
Size toast_raw_datum_size(Datum value)
int errcode(int sqlerrcode)
int errmsg(const char *fmt,...)
#define ereport(elevel,...)
bool equal(const void *a, const void *b)
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
List * ExecPrepareExprList(List *nodes, EState *estate)
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
const TupleTableSlotOps TTSOpsHeapTuple
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
EState * CreateExecutorState(void)
void FreeExecutorState(EState *estate)
#define GetPerTupleExprContext(estate)
#define ResetExprContext(econtext)
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
bool has_stats_of_kind(List *stats, char requiredkind)
static AnlExprData * build_expr_data(List *exprs, int stattarget)
int multi_sort_compare_dims(int start, int end, const SortItem *a, const SortItem *b, MultiSortSupport mss)
static bool stat_covers_expressions(StatisticExtInfo *stat, List *exprs, Bitmapset **expr_idxs)
StatisticExtInfo * choose_best_statistics(List *stats, char requiredkind, bool inh, Bitmapset **clause_attnums, List **clause_exprs, int nclauses)
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)
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)
struct AnlExprData AnlExprData
SortItem * build_sorted_items(StatsBuildData *data, int *nitems, MultiSortSupport mss, int numattrs, AttrNumber *attnums)
static bool statext_is_compatible_clause_internal(PlannerInfo *root, Node *clause, Index relid, Bitmapset **attnums, List **exprs)
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 VacAttrStats ** lookup_var_attr_stats(Relation rel, Bitmapset *attrs, List *exprs, int nvacatts, VacAttrStats **vacatts)
static List * fetch_statentries_for_relation(Relation pg_statext, Oid relid)
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)
void BuildRelationExtStatistics(Relation onerel, bool inh, double totalrows, int numrows, HeapTuple *rows, int natts, VacAttrStats **vacattrstats)
static VacAttrStats * examine_attribute(Node *expr)
Selectivity statext_clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Bitmapset **estimatedclauses, bool is_or)
AttrNumber * build_attnums_array(Bitmapset *attrs, int nexprs, int *numattrs)
static void compute_expr_stats(Relation onerel, double totalrows, AnlExprData *exprdata, int nexprs, HeapTuple *rows, int numrows)
static int stat_find_expression(StatisticExtInfo *stat, Node *expr)
static int statext_compute_stattarget(int stattarget, int nattrs, VacAttrStats **stats)
int multi_sort_compare(const void *a, const void *b, void *arg)
MultiSortSupport multi_sort_init(int ndims)
static VacAttrStats * examine_expression(Node *expr, int stattarget)
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)
struct StatExtEntry StatExtEntry
MultiSortSupportData * MultiSortSupport
#define OidFunctionCall1(functionId, arg1)
#define DatumGetHeapTupleHeader(X)
#define PG_DETOAST_DATUM(datum)
void systable_endscan(SysScanDesc sysscan)
HeapTuple systable_getnext(SysScanDesc sysscan)
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
static int compare(const void *arg1, const void *arg2)
HeapTuple heap_copytuple(HeapTuple tuple)
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Datum heap_copy_tuple_as_datum(HeapTuple tuple, TupleDesc tupleDesc)
void heap_freetuple(HeapTuple htup)
#define HeapTupleIsValid(tuple)
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
#define HeapTupleHeaderGetDatumLength(tup)
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
static void ItemPointerSetInvalid(ItemPointerData *pointer)
List * lappend(List *list, void *datum)
List * lappend_int(List *list, int datum)
void list_free(List *list)
RegProcedure get_oprrest(Oid opno)
char * get_namespace_name(Oid nspid)
RegProcedure get_opcode(Oid opno)
Oid get_rel_type_id(Oid relid)
bool get_func_leakproof(Oid funcid)
int16 get_typlen(Oid typid)
Selectivity mcv_clauselist_selectivity(PlannerInfo *root, StatisticExtInfo *stat, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Selectivity *basesel, Selectivity *totalsel)
Selectivity mcv_combine_selectivities(Selectivity simple_sel, Selectivity mcv_sel, Selectivity mcv_basesel, Selectivity mcv_totalsel)
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)
MCVList * statext_mcv_load(Oid mvoid, bool inh)
MCVList * statext_mcv_build(StatsBuildData *data, double totalrows, int stattarget)
bytea * statext_mcv_serialize(MCVList *mcvlist, VacAttrStats **stats)
void MemoryContextReset(MemoryContext context)
char * pstrdup(const char *in)
void pfree(void *pointer)
void * palloc0(Size size)
MemoryContext CurrentMemoryContext
void MemoryContextDelete(MemoryContext context)
#define AllocSetContextCreate
#define ALLOCSET_DEFAULT_SIZES
#define AmAutoVacuumWorkerProcess()
bytea * statext_ndistinct_serialize(MVNDistinct *ndistinct)
MVNDistinct * statext_ndistinct_build(double totalrows, StatsBuildData *data)
Oid exprType(const Node *expr)
int32 exprTypmod(const Node *expr)
Oid exprCollation(const Node *expr)
void fix_opfuncids(Node *node)
static bool is_andclause(const void *clause)
static bool is_orclause(const void *clause)
static bool is_opclause(const void *clause)
static bool is_notclause(const void *clause)
#define IsA(nodeptr, _type_)
Operator oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId, bool noError, int location)
#define planner_rt_fetch(rti, root)
static int list_length(const List *l)
#define STATISTIC_NUM_SLOTS
FormData_pg_statistic_ext * Form_pg_statistic_ext
FormData_pg_type * Form_pg_type
void qsort_interruptible(void *base, size_t nel, size_t elsize, qsort_arg_comparator cmp, void *arg)
static bool DatumGetBool(Datum X)
static Datum PointerGetDatum(const void *X)
static Datum Float4GetDatum(float4 X)
static Datum Int16GetDatum(int16 X)
static Datum BoolGetDatum(bool X)
static Datum ObjectIdGetDatum(Oid X)
static Datum Int32GetDatum(int32 X)
static int16 DatumGetInt16(Datum X)
#define PROGRESS_ANALYZE_EXT_STATS_COMPUTED
#define PROGRESS_ANALYZE_PHASE
#define PROGRESS_ANALYZE_PHASE_COMPUTE_EXT_STATS
#define PROGRESS_ANALYZE_EXT_STATS_TOTAL
MemoryContextSwitchTo(old_ctx)
void * stringToNode(const char *str)
#define RelationGetRelid(relation)
#define RelationGetDescr(relation)
#define RelationGetRelationName(relation)
int errtable(Relation rel)
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
#define CLAMP_PROBABILITY(p)
void PrepareSortSupportFromOrderingOp(Oid orderingOp, SortSupport ssup)
struct SortSupportData SortSupportData
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
#define STATS_MAX_DIMENSIONS
void RemoveStatisticsDataById(Oid statsOid, bool inh)
#define BTEqualStrategyNumber
VacAttrStats * vacattrstat
TupleTableSlot * ecxt_scantuple
SortSupportData ssup[FLEXIBLE_ARRAY_MEMBER]
int16 stakind[STATISTIC_NUM_SLOTS]
MemoryContext anl_context
Oid statypid[STATISTIC_NUM_SLOTS]
Oid staop[STATISTIC_NUM_SLOTS]
Oid stacoll[STATISTIC_NUM_SLOTS]
char statypalign[STATISTIC_NUM_SLOTS]
float4 * stanumbers[STATISTIC_NUM_SLOTS]
bool statypbyval[STATISTIC_NUM_SLOTS]
int16 statyplen[STATISTIC_NUM_SLOTS]
int numvalues[STATISTIC_NUM_SLOTS]
Datum * stavalues[STATISTIC_NUM_SLOTS]
int numnumbers[STATISTIC_NUM_SLOTS]
AnalyzeAttrComputeStatsFunc compute_stats
#define FirstLowInvalidHeapAttributeNumber
void ReleaseSysCache(HeapTuple tuple)
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
#define SearchSysCacheCopy1(cacheId, key1)
void table_close(Relation relation, LOCKMODE lockmode)
Relation table_open(Oid relationId, LOCKMODE lockmode)
#define MAX_STATISTICS_TARGET
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)