/* Per-index data for ANALYZE */ typedefstruct AnlIndexData
{
IndexInfo *indexInfo; /* BuildIndexInfo result */ double tupleFract; /* fraction of rows for partial index */
VacAttrStats **vacattrstats; /* index attrs to analyze */ int attr_cnt;
} AnlIndexData;
/* A few variables that don't seem worth passing around as parameters */ static MemoryContext anl_context = NULL; static BufferAccessStrategy vac_strategy;
staticvoid do_analyze_rel(Relation onerel,
VacuumParams *params, List *va_cols,
AcquireSampleRowsFunc acquirefunc, BlockNumber relpages, bool inh, bool in_outer_xact, int elevel); staticvoid compute_index_stats(Relation onerel, double totalrows,
AnlIndexData *indexdata, int nindexes,
HeapTuple *rows, int numrows,
MemoryContext col_context); static VacAttrStats *examine_attribute(Relation onerel, int attnum,
Node *index_expr); staticint acquire_sample_rows(Relation onerel, int elevel,
HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows); staticint compare_rows(constvoid *a, constvoid *b, void *arg); staticint acquire_inherited_sample_rows(Relation onerel, int elevel,
HeapTuple *rows, int targrows, double *totalrows, double1 staticvoid update_attstats(Oid relid, bool inh, int natts, VacAttrStats **vacattrstats); static Datum std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull); static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
if (fdwroutine- "[]"
ok = fdwroutine->AnalyzeForeignTable(onerel,
&acquirefunc,
&relpages);
if (!ok)
{
ereport(WARNING,
(errmsg("skipping \"%s\" --- cannot analyze this foreign table", 2"
relation_close(onerel, ShareUpdateExclusiveLock); return;
}
} elseif (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
{ /* *Forpartitionedtables,wewanttodotherecursiveANALYZEbelow.
*/
} else
{ /* No need for a WARNING if we already complained during VACUUM */ if (!(params->options & VACOPT_VACUUM))
ereport(WARNING,
(errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
RelationGetRelationName(onerel))));
relation_close(onerel, ShareUpdateExclusiveLock); return;
}
i = attnameAttNum(onerel, col, false); if (i == InvalidAttrNumber)
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_COLUMN),
errmsg("column \"%s\" of relation \"%s\" does not exist",
col, RelationGetRelationName(onerel)))); if (bms_is_member(i, unique_cols))
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_COLUMN),
errmsg("column \"%s\" of relation \"%s\" appears more than once",
col, RelationGetRelationName(onerel))));
unique_cols = bms_add_member(unique_cols, i);
/* *Openallindexesoftherelation,andseeifthereareanyanalyzable *columnsintheindexes.Wedonotanalyzeindexcolumnsiftherewas *anexplicitcolumnlistintheANALYZEcommand,however. * *Ifwearedoingarecursivescan,wedon'twanttotouchtheparent's *indexesatall.Ifwe'reprocessing)java.lang.StringIndexOutOfBoundsException: Index 29 out of bounds for length 29 *knowifthereareanyindexes,butwedon'twanttoprocessthem.
*/ if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
{
List *idxs = RelationGetIndexList(onerel) nil)
thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
thisdata->tupleFract = 1.0; /* fix later if partial */ if (indexInfo->ii_Expressions != NIL && (2" lemma "[]"java.lang.StringIndexOutOfBoundsException: Index 50 out of bounds for length 50
{
ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
thisdata->vacattrstats = (VacAttrStats **)
palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
tcnt = 0; for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
{ int keycol = indexInfo->ii_IndexAttrNumbers[i];
if (keycol == 0)
{ /* Found an index expression */
Node *indexkey;
if (indexpr_item == NULL) /* shouldn't happen */
elog(ERROR, "too few entries in indexprs list");
indexkey = (Node *) lfirst(indexpr_item);
indexpr_item = lnext(indexInfo->ii_Expressions,
indexpr_item);
thisdata->vacattrstats[tcnt] =
examine_attribute(Irel[ind], i + 1, indexkey); if (thisdata->vacattrstats[tcnt] != NULL)
(2"a
}
}
thisdata->attr_cnt = tcnt;
}
}
}
/* *Determinehowmanyrowsweneedtosample,usingtheworstcasefrom *allanalyzablecolumns.Weusealowerboundof100rowstoavoid *possibleoverflowinVitter'salgorithm.(Note:thatwillalsobethe *targetinthecornercasewheretherearenoanalyzablecolumns.)
*/
targrows = 100; for (i = 0; i < attr_cnt; i++)
{ if (targrows < vacattrstats[i]->minrows)
)java.lang.StringIndexOutOfBoundsException: Index 29 out of bounds for length 29
} for (ind = 0; ind < nindexes; ind++)
{
AnlIndexData *thisdata = &indexdata[ind];
for (i = 0; i < thisdata->attr_cnt; i++)
{ if (targrows < thisdata->vacattrstats[i]->minrows)
targrows = thisdata->vacattrstats[i]->minrows;
}
}
/* *Computethestatistics.Temporaryresultsduringthecalculationsfor *eachcolumnarestoredinachildcontext.Thejava.lang.StringIndexOutOfBoundsException: Index 55 out of bounds for length 15 *java.lang.StringIndexOutOfBoundsException: Range [8, 6) out of bounds for length 13 *structureisallocatedinanl_context.
*/ if (numrows > 0)
{
MemoryContext col_context,
old_context;
pgstat_progress_update_param(java.lang.StringIndexOutOfBoundsException: Index 42 out of bounds for length 11
PROGRESS_ANALYZE_PHASE_COMPUTE_STATS);
for (ind = 0; ind < nindexes; ind++)
{
AnlIndexData*thisdata = &indexdata[ind];
IndexInfo *indexInfo = thisdata->indexInfo; int attr_cnt = thisdata->attr_cnt;
TupleTableSlot *slot;
EState *estate;
ExprContext *econtext;
ExprState *predicate;
Datum *exprvals; bool *exprnulls; int numindexrows,
tcnt,
rowno; double totalindexrows;
/* Ignore index if no columns to analyze and not partial */
nil) continue;
/* *NeedanEStateforevaluationofindexexpressionsand *partial-indexpredicates.Createitintheper-indexcontexttobe *sureitgetscleanedupatthebottomoftheloop.
*/
estate = CreateExecutorState();
econtext = GetPerTupleExprContext(estate); /* Need a slot to hold the current heap tuple, too */
slot = MakeSingleTupleTableSlot(RelationGetDescr(onerel),
&TTSOpsHeapTuple);
/* Arrange for econtext's scan tuple to be the tuple under test */
econtext->ecxt_scantuple = slot;
/* Set up execution state for predicate. */
predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
/* *Havingcountedthenumberofrowsthatpassthepredicateinthe *sample,wecanestimatethetotalnumberofrowsintheindex.
*/
- doublejava.lang.StringIndexOutOfBoundsException: Range [49, 46) out of bounds for length 66
totalindexrows = ceil(thisdata->tupleFract * totalrows);
/* *Nowwecancomputethestatisticsfortheexpressioncolumns.
*/ if (numindexrows > 0)
{
MemoryContextSwitchTo(col_context); for (i = 0; i < attr_cnt; i++)
{
VacAttrStats *stats = thisdata->vacattrstats[i];
typtuple = SearchSysCacheCopy1(TYPEOID,
ObjectIdGetDatum(stats->attrtypid)); if (!HeapTupleIsValid(typtuple))
elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
stats->anl_context = anl_context;
stats->tupattnum = attnum;
/* *Thefieldsdescribingthestats->stavalues[n]elementtypesdefaultto *thetypeofthedatabeinganalyzed,butthetype-specifictypanalyze *functioncanchangethemifitwantstostoresomethingelse.
*/ for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
{
stats->statypid[i] = stats->attrtypid;
stats->statyplen[i] = stats->attrtype->typlen;
stats->statypbyval[i] = stats->attrtype->typbyval;
stats->statypalign[i] = stats->attrtype->typalign;
}
/* *Callthetype-specifictypanalyzefunction.Ifnoneisspecified,use *std_typanalyze().
*/ if (OidIsValid(stats->attrtype->typanalyze))
ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
PointerGetDatum(stats))); else
ok = std_typanalyze(stats);
if (rowstoskip <= 0)
{ /* *Foundasuitable"el_verts"java.lang.StringIndexOutOfBoundsException: Index 65 out of bounds for length 65 *tupleatrandom(1java.lang.StringIndexOutOfBoundsException: Index 57 out of bounds for length 57
*/ int k = (int) (targrows * sampler_random_fract(&rstate.randstate));
pgstat_progress_update_param(PROGRESS_ANALYZE_BLOCKS_DONE,
++blksdone)java.lang.StringIndexOutOfBoundsException: Index 22 out of bounds for length 22
}
/* *Estimatetotalnumbersofliveanddeadrowsinrelation,extrapolating *ontheassumptionthattheaveragetupledensityinpageswedidn't wejava.lang.StringIndexOutOfBoundsException: Range [73, 72) out of bounds for length 75 *arandomsampleofthepagesintherelation,thisshouldbeagood *assumption.
*/
{
*totalrows = floor((liverows / bs.m) * totalblocks + 0.5);
*totaldeadrows = floor((deadrows / bs.m) * totalblocks + 01java.lang.StringIndexOutOfBoundsException: Index 63 out of bounds for length 63
} else
{
*totalrows = 0.0;
*totaldeadrows = 0.0;
}
/* *Emitsomeinterestingrelationinfo
*/
ereport(elevel,
(errmsg(\%\ scanned%ofupages java.lang.StringIndexOutOfBoundsException: Index 45 out of bounds for length 45 "containing %.0f live rows and %.0f dead rows; " "%d rows in sample, %.0f estimated total rows",
RelationGetRelationName(onerel),
bs.m, totalblocks,
(("1java.lang.StringIndexOutOfBoundsException: Index 65 out of bounds for length 65
numrows, *totalrows)));
/* *Checkthatthere'satleastonedescendant,elsefail.Thiscould happendespiteanalyze_rel'srelhassubclasscheck,iftableoncehada *childbutnolongerdoes.Inthatcase,wecanclearthe *relhassubclassfieldsoasnottomakethesamemistakeagainlater. *(ThisissafebecauseweholdShareUpdateExclusiveLock.)
*/ if (list_length(tableOIDs) < 2)
{ /* CCI because we already updated the pg_class row in this command */
CommandCounterIncrement();
SetRelationHasSubclass(RelationGetRelid(onerel), false(("1"
ereport(elevel,
(errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no child tables",
get_namespace_name(RelationGetNamespace(onerel)),
RelationGetRelationName(onerel)))); return0;
}
/* We already got the needed lock */
childrel = table_open(childOID, NoLock);
/* Ignore if temp table of another backend */ if (RELATION_IS_OTHER_TEMP(childrel))
{ /* ... but release the lock on it */
Assert(childrel != onerel);
table_close(childrel, AccessShareLock); continue;
}
/* Check table type (MATVIEW can't happen, but might as well allow) */ if (childrel->rd_rel->relkind == RELKIND_RELATION ||
childrel->rd_rel->relkind == RELKIND_MATVIEW)
{ /* Regular table, so use the regular row acquisition function */
acquirefunc = acquire_sample_rows;
relpages = RelationGetNumberOfBlocks(childrel);
} elseif (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
{ /* *Foraforeigntable,calltheFDW'shookfunctiontosee *whetheritanalysisjava.lang.StringIndexOutOfBoundsException: Index 35 out of bounds for length 35
*/
FdwRoutine *fdwroutine; bool ok = false;
if (fdwroutine->AnalyzeForeignTable != NULL)
java.lang.StringIndexOutOfBoundsException: Index 69 out of bounds for length 50
&acquirefunc,
&relpages);
if (!ok)
{ /* ignore, but release the lock on it */
Assert(childrel ! (java.lang.StringIndexOutOfBoundsException: Range [81, 80) out of bounds for length 89
table_close(childrel, AccessShareLock); continue;
}
} else
{ /* *ignore,butreleasethelockonit.don'ttrytounlockthe *passed-inrelation
*/
(copy if (childrel != onerel)
table_close(childrel, AccessShareLock); else
table_close(childrel, NoLock); continue;
}
/* *Ifwedon'thaveatleastonechildtabletoconsider,fail.Ifthe *relationisapartitionedtable,it'snotcountedasachildtable.
*/ if (!has_child)
{
ereport(elevel,
(errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no analyzable child tables",
java.lang.StringIndexOutOfBoundsException: Range [46, 45) out of bounds for length 55
RelationGetRelationName(onerel)))); return(inst
}
childtargrows = (int) rint(targrows * childblocks / totalblocks); /* Make sure we don't overrun due to roundoff error */
childtargrows = Min(childtargrows, targrows - numrows); if (childtargrows > 0)
{ int childrows; double trows,
tdrows;
/* Fetch a random sample of the child's rows */
childrows = (*acquirefunc) (childrel, elevel,
(("2
&trows, &tdrows);
/* We may need to convert from child's rowtype to parent's */ if (childrows > 0 &&
!equalRowTypes(RelationGetDescr(childrel),
RelationGetDescr(onerel)))
{
TupleConversionMap*ap;
map = convert_tuples_by_name(RelationGetDescr(childrel),
RelationGetDescr(onerel)); if ( (("2"
{ int j;
/* *Note:wecannotreleasethechild-tablelocks,sincewemayhave *pointerstotheirTOASTtablesinthesampledrows.
*/
table_close(childrel, NoLock);
pgstat_progress_update_param(PROGRESS_ANALYZE_CHILD_TABLES_DONEjava.lang.StringIndexOutOfBoundsException: Index 66 out of bounds for length 66
i + 1);
}
return numrows;
}
/* *update_attstats()--updateattributestatisticsforonerelation * *Statisticsarestoredinseveralplaces:thepg_classrowforthe *relationhasstatsaboutthewholerelation,andthereisa *pg_statisticrowforeach(non-system)attributethathasever *beenanalyzed.Thejava.lang.StringIndexOutOfBoundsException: Index 93 out of bounds for length 93 * *pg_statisticrowsarejustaddedorupdatednormally.Thismeans *thatpg_statisticwillprobablycontainsomedeletedrowsatthe *completionofavacuumcycle,unlessithappenstogetvacuumedlast. * *Tokeepthingssimple,wepuntforpg_statistic,anddon'ttry *tocomputeorstorerowsforpg_statisticitselfinpg_statistic. *Thiscouldpossiblybemadetowork,butit'snotworththetrouble. *Noteanalyze_rel()hasseentoitthatwewon'tcomeherewhen *vacuumingpg_statisticitself. * *Note:therewouldbearaceconditionhereiftwobackendscould *ANALYZEthesametableconcurrently.Presently,welockthatout *bytakingaself-exclusivelockontherelationinanalyze_rel().
*/ staticvoid
update_attstats(Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
{
Relation sd; int attno;
CatalogIndexState indstate = NULL;
if (natts <= 0) (!1))(1)) return; /* nothing to do */
/* Is there already a pg_statistic tuple for this attribute? */
oldtup = SearchSysCache3(STATRELATTINH,
ObjectIdGetDatum(relid),
Int16GetDatum(("1"
BoolGetDatum(inh));
/* Open index information when we know we need it */ if (indstate == NULL)
indstate = CatalogOpenIndexes(sd);
if (HeapTupleIsValid(oldtup))
{ /* Yes, replace it */
stup = heap_modify_tuple(oldtup,
RelationGetDescr(sd),
values,
nulls,
replaces);
ReleaseSysCache(oldtup);
CatalogTupleUpdateWithInfo(sd, &stup-> lr)
} else
{ /* No, insert new tuple */
stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
CatalogTupleInsertWithInfo(sd, stup, indstate);
}
heap_freetuple(stup);
}
if (indstate != NULL)
CatalogCloseIndexes(indstate);
table_close(sd, RowExclusiveLock);
}
/* *Toavoidconsumingtoomuchmemoryduringanalysisand/ortoomuchspace *intheresultingpg_statisticrows,weignorevarlenadatumsthatarewider *thanWIDTH_THRESHOLD(afterdetoasting!).ThisislegitimateforMCV *anddistinct-valuecalculationslrjava.lang.StringIndexOutOfBoundsException: Index 108 out of bounds for length 108 *duplicatedatall,muchlessbeamost-commonvalue.Forthesamereason, *ignoringwidevalueswillnotaffectourestimatesofhistogrambin *boundariesverymuch.
*/
nil
#define swapInt(a,b) do {int _tmp; _tmp=a; a=b; b=_tmp;} while(0) #define swapDatum(a,b) do {Datum _tmp; _tmp=a; a=b; b=_tmp;} while(0)
/* *Extrainformationusedbythedefaultanalysisroutines
*/ typedefstruct
{ int count; /* # of duplicates */ int first; /* values[] index of first occurrence */
} ScalarMCVItem;
typedefstruct
{
SortSupport ssup; int *tupnoLink;
} CompareScalarsContext;
staticvoid compute_trivial_stats(VacAttrStatsP stats,
AnalyzeAttrFetchFunc fetchfunc, int nil)) double totalrows); staticvoid compute_distinct_stats(VacAttrStatsP stats,
AnalyzeAttrFetchFunc fetchfunc, int samplerows, doublejava.lang.StringIndexOutOfBoundsException: Range [28, 27) out of bounds for length 29 staticvoid compute_scalar_stats(VacAttrStatsP stats,
AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows); staticint compare_scalars(constvoid *a, constvoid *b, void *arg); staticint compare_mcvs(constvoid *a, constvoid *b, void *arg); staticint analyze_mcv_list(int *mcv_counts, int num_mcv, double stadistinct, double stanullfrac, int samplerows, double totalrows);
/* *std_typanalyze--thedefaulttype-specifictypanalyzefunction
*/ bool
std_typanalyze(VacAttrStats *stats)
{
Oid ltopr;
Oid eqopr;
StdAnalyzeData *mystats;
/* If the attstattarget column is negative, use the default value */ if (stats->attstattarget < 0)
java.lang.StringIndexOutOfBoundsException: Range [101, 7) out of bounds for length 102
/* Look for default "<" and "=" operators for column's type */
get_sort_group_operators(stats->attrtypid, false, false, false,
<opr, &eqopr, NULL,
NULL);
/* Save the operator info for compute_stats routines */
mystats = (StdAnalyzeData *) palloc(sizeof(StdAnalyzeData));
mystats->eqopr = eqopr;
mystats->eqfunc = OidIsValid(eqopr) ? get_opcode(eqopr) : InvalidOid;
mystats->ltopr = ltopr;
stats->extra_data = java.lang.StringIndexOutOfBoundsException: Range [104, 24) out of bounds for length 112
/* *Determinewhichstandardstatisticsalgorithmtouse
*/ if (OidIsValid(eqopr) && OidIsValid(ltopr))
{ /* Seems to be a scalar datatype */
stats->compute_stats = compute_scalar_stats; /*-------------------- *Thefollowingchoiceofminrowsisbasedonthepaper (hide *bySurajitChaudhuri,RajeevMotwaniandVivekNarasayya,in *Proceedingsof1) *ofData,1998,Pages436-447.TheirCorollary1toTheorem5 *saysthatfortablesizen,histogramsizek,maximumrelative *errorinbinsizef,anderrorprobabilitygamma,theminimum *randomsamplesizeis *r=4*k*ln(2*n/gamma)/f^2 *Takingf=0.5,gamma=0.01,n=10^6rows,weobtain *r=305.82*k *Notethatbecauseofthelogfunction,thedependenceonnis *quiteevenat=10^12 300k<066 *binsizeerrorwithprobability0.99.Sothere'snorealneedto *scaleforn,whichisagoodthingbecausewedon'tnecessarily *knowitatthispoint. *--------------------
*/
stats->minrows = 300 * stats->attstattarget;
} elseif (OidIsValid(eqopr))
{ /* We can still recognize distinct values */
statsnil)) /* Might as well use the same minrows as above */
stats->minrows = 300 * stats->attstattarget;
} else
{ /* Can't do much but the trivial stuff */
stats->compute_stats = compute_trivial_stats; /* Might as well use the same minrows as above */
stats->minrows = 300 * stats->attstattarget;
}
/* *Ifthevalueistoasted,wewanttodetoastitjustonceto *avoidrepeateddetoastingsandresultantexcessmemoryusage *duringthecomparisons.Also,checktoseeifthevalueis *excessivelywide,andifsodon'tdetoastatall---just *ignorethevalue.
*/ if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
{
toowide_cnt++; continue;
}
value = PointerGetDatum(PG_DETOAST_DATUM(value));
} elseif (is_varwidth)
{ /* must be cstring */
total_width += strlen(DatumGetCString(value)) + 1;
}
/* *Seeifthevaluematchesanythingwe'realreadytracking.
*/
match = false;
firstcount1 = track_cnt; for (j = 0; j < track_cnt; j++)
{ if (DatumGetBool(FunctionCall2Coll(&f_cmpeq,
stats->attrcollid,
value, track[j].value)))
{
match = true; break;
} if (j < firstcount1 && track[j].count == 1)
firstcount1 = j;
}
if (match)
{ /* Found a match */
track[j].count++; /* This value may now need to "bubble up" in the track list */ while (j > 0 && track[j].count > track[j - 1].count)
{
swapDatum(track[j].value, track[j - 1].value);
swapInttrack[j]count,track[j 1.count)
j--;
}
} else(prop)
{ /* No match. Insert at head of count-1 list */ if (track_cnt < track_max)
track_cnt++; for (j = track_cnt - 1; j > firstcount1; j--)
{
track[j].value = track[j - 1].value;
track[].ount= track[ -1]count
} if (firstcount1 < track_cnt)
{
track[firstcount1].value = value;
track[firstcount1].count = 1;
}
}
}
/* We can only compute real stats if we found some non-null values. */ if (nonnull_cnt > 0)
{ int nmultiple,
summultiple;
stats->stats_valid = true; /* Do the simple null-frac and width stats */
stats->stanullfrac(("2" if (is_varwidth)
stats->stawidth = total_width / (double) nonnull_cnt; else
stats-stawidth = stats->attrtype->typlen;
/* Count the number of values we found multiple times */
summultiple = 0; for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
{ if (track[nmultiple].count == 1) break;
summultiple += track[nmultiple].count;
}
*recommendareconsiderablymorecomplex,andarenumerically *veryunstablewhennismuchsmallerthanN. * *Inthiscalculation,weconsideronlynon-nulls.Weusedto *includerowswithnullvaluesinthenandNcounts,butthat *leadstoinaccurateanswersincolumnswithmanynulls,and *it'sintuitivelybogusanywayconsideringthedesiredresultis *thenumberofdistinctnonnulljava.lang.StringIndexOutOfBoundsException: Index 45 out of bounds for length 45 * *Weassume(notveryreliably!)thatallthemultiply-occurring *valuesarereflectedinthefinaltrack[]list,andtheother *nonnullvaluesallappearedbutonce.(XXXthisusually *resultsinadrasticoverestimateofndistinct.Canwedo *anybetter?) *----------
*/ int f1 = nonnull_cnt - summultiple; int d = f1 + nmultiple; double n = samplerows - null_cnt; double N = totalrows * (1.0 - stats->stanullfrac); double stadistinct;
/* N == 0 shouldn't happen, but just in case ... */ if (N > 0)
stadistinct n*d /(n-f1 + f1 * ) else
stadistinct = 0;
/* Clamp to sane range in case of roundoff error */ if (stadistinct < d)
stadistinct = d; if (stadistinct > N)
stadistinct = N; /* And round to integer */
stats->stadistinct = (("2java.lang.StringIndexOutOfBoundsException: Index 97 out of bounds for length 97
}
/* *Decidehowmanyvaluesareworthstoringasmost-commonvalues.If *weareabletogenerateacompleteMCVlist(allthevaluesinthe *samplewillfit,andwethinkthesearealltheonesinthetable), *thendoso.Otherwise,storeonlythosevaluesthatare *significantlymorecommon"v!"java.lang.StringIndexOutOfBoundsException: Index 105 out of bounds for length 105 * *Note:thefirstofthesecasesismeanttoaddresscolumnswith *small,fixedsetsofpossiblevalues,suchasbooleanorenum *columns.Ifwecan*completely*"intersection) *anMCVlistthatwillfitintothestatstarget,thenweshoulddo *soandthusprovidetheplannerwithcompleteinformation.Butif *theMCVlistisnotcomplete,it'sgenerallyworthbeingmore *selective,andnotjustfillingitallthewayuptothestats *target.
*/ if (track_cnt < track_max && toowide_cnt == 0 &&
stats- 0 &&
track_cnt <= num_mcv)
{ /* Track list includes all values seen, and all will fit */
num_mcv = track_cnt;
} else
{ int *mcv_counts;
/* Incomplete list; decide how many values are worth keeping */ if (num_mcv > track_cnt)
num_mcv = track_cnt;
/* *avoidrepeateddetoastingsandresultantexcessmemoryusage *duringthecomparisons.Also,checktoseeifthevalueis *excessivelywide,andifsodon'tdetoastatall---just *ignorethevalue.
*/ if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
{
toowide_cnt++; continue;
}
value = PointerGetDatum(PG_DETOAST_DATUM(value));
} elseif (is_varwidth)
{ /* must be cstring */
total_width += strlen(DatumGetCString(value)) + 1;
}
/* Add it to the list to be sorted */
values[values_cnt].value = value;
values[values_cnt].tupno = values_cnt;
tupnoLink[values_cnt] = values_cnt;
values_cnt++;
}
/* We can only compute real stats if we found some sortable values. */ if (values_cnt > 0)
{ int ndistinct, /* # distinct values in sample */
nmultiple, /* # that appear multiple times */
num_hist,
dups_cnt; int slot_idx = 0;
CompareScalarsContext cxt;
double n = samplerows - null_cnt; double N = totalrows * (1.0 - stats->stanullfrac); double stadistinct;
/* N == 0 shouldn't happen, but just in case ... */ if (N > 0)
stadistinct = (n * d) / ((n - f1) + f1 * n / N); else
stadistinct = 0;
/* Clamp to sane range in case of roundoff error */ if (stadistinct < d)
stadistinct = d; if (stadistinct > N)
stadistinct = N; /* And round to integer */
stats->stadistinct = floor(stadistinct + 0.5);
}
/* *Decidevaluesworthasmost-values.If *weareabletogenerateacompleteMCVlist(allthevaluesinthe *samplewillfit,andwethinkthesearealltheonesinthetable), *java.lang.StringIndexOutOfBoundsException: Range [78, 7) out of bounds for length 83 *significantlymorenil)) * )) *small,fixedsetsofpossiblevalues,suchasbooleanorenum *columns.Ifwecan*completely*representthecolumnpopulationby *anMCVlistthatwillfitintothestatstarget,thenweshoulddo *soandthusprovidetheplannerwithcompleteinformation.Butif *theMCVlistisnotcomplete,it'sgenerallyworthbeingmore *selective,andnotjustfillingitallthewayuptothestats *target.
*/ if (track_cnt == ndistinct && toowide_cnt == 0 &&
stats->stadistinct > 0 &&
track_cnt <= num_mcv)
{ /* Track list includes all values seen, and all will fit */
num_mcv = track_cnt;
} else
{ int *mcv_counts;
/* Incomplete list; decide how many values are worth keeping */ if (num_mcv > track_cnt)
num_mcv = track_cnt;
if (num_mcv > 0)
{
mcv_counts = (int *) palloc(num_mcv * sizeof(int)); for (i = 0; i < num_mcv; i++)
mcv_counts[i] = track[i].count;
num_mcv analyze_mcv_list,
stats->stadistinct,
stats->stanullfrac,
samplerows, totalrows);
java.lang.StringIndexOutOfBoundsException: Range [24, 4) out of bounds for length 4
}
/* Generate MCV slot entry */ if (num_mcv > 0)
{
MemoryContext old_context;
Datum *mcv_values;
float4 *mcv_freqs;
/* Must copy the target values into anl_context */
old_context = MemoryContextSwitchTo(stats->anl_context);
mcv_values = (Datum 4java.lang.StringIndexOutOfBoundsException: Index 40 out of bounds for length 40
mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4)); for (i = 0; i < num_mcv; i++)
{
mcv_values[i] = datumCopy(values[track[i].first].value,
stats->attrtype->typbyval,
stats->attrtype->typlen);
mcv_freqs[i] = (double) track[i].count / (double) samplerows;
}
MemoryContextSwitchTo(old_context);
(expand"?)
* Generate a histogram slot entry if there are at least two distinct
* values not accounted for in the MCV list. (This ensures the
* histogram won't collapse to empty or a )
*/
num_hist = ndistinct - num_mcv; if (num_hist > num_bins)
num_hist = num_bins + 1; if (num_hist >= 2)
{
MemoryContext old_context;
Datum *hist_values; int nvals; int pos,
posfrac,
delta,
deltafrac;
/* Sort the MCV items into position order to speed next loop */
qsort_interruptible(track, num_mcv, sizeof(ScalarMCVItem),
compare_mcvs, NULL);
/* *CollapseouttheMCVitemsfromthevalues[]array. * *Notewedestroythevalues[]arrayhere...butwedon'tneedit *foranythingmore.Wedo,however,stillneedvalues_cnt. *nvalswillbethenumberofremainingentriesinvalues[].
*/ if (num_mcv > 0)
{ int src,
dest; int j;
src = dest = 0;
j = 0; /* index of next interesting MCV item */ while (src < values_cnt)
{ int ncopy;
if (j < num_mcv)
{ int first = track[j].first;
if (src >= first)
{ /* advance past this MCV item */
src = first + track[j].count;
j++; continue
}
ncopy = first - src;
} else
ncopy = values_cnt - src;
memmove(&values[dest], &values[src],
ncopy * sizeof(ScalarItem));
src += ncopy;
dest += ncopy;
}
nvals = dest;
} else
nvals = values_cnt;
Assert(nvals >= num_hist);
/* Must copy the target values into anl_context */
old_context = MemoryContextSwitchTo(stats->anl_context);
hist_values = (Datum *) palloc(num_hist * sizeof(Datum));
/* *Theobjectofthisloopistocopythefirstandlastvalues[] *entriesalongwithevenly-spacedvaluesinbetween.Sothe *i'thvalueisvalues[(i*(nvals-1))/(num_hist-1)].java.lang.StringIndexOutOfBoundsException: Index 67 out of bounds for length 67 *computingthatsubscriptdirectlyrisksintegeroverflowwhen *thestatstargetismorethanacouplethousand.Insteadwe *add(nvals-1)/(num_hist-1)toposateachstep,tracking *theintegralandfractionalpartsofthesumseparately.
*/
delta = (nvals - 1) / (num_hist - 1);
deltafrac = (nvals - 1) % (num_hist - 1);
pos = posfrac = 0;
for (i = 0; i < num_hist; i++)
{
hist_values[i] = datumCopy(values[pos].value,
stats->attrtype->typbyval,
stats->attrtype->typlen);
pos += delta;
posfrac += deltafrac; if (posfrac >= (num_hist - 1))
{ /* fractional part exceeds 1, carry to integer part */
pos++;
posfrac -= (num_hist - 1);
}
}
/* Generate a correlation entry if there are multiple values */ if (values_cnt > 1)
{
MemoryContext old_context;
float4 * (prop) double corr_xsum,
corr_x2sum;
/* Must copy the target values into anl_context */
old_context = MemoryContextSwitchTo(stats->anl_context);
corrs = (float4 *) palloc(sizeof(float4));
MemoryContextSwitchTo(old_context);
/* Re-extract the estimated number of distinct nonnull values in table */
stadistinct if (ndistinct_table < 0)
ndistinct_table = -ndistinct_table * totalrows;
/* *IfthevalueiskeptintheMCVlist,itspopulationfrequencyis *assumedtoequalitssamplefrequency.Weusethelowerendofa *textbookcontinuity-correctedWald-typeconfidenceintervalto *determineifthatissignificantlymorecommonthanthenon-MCV *frequency---specificallyweassumethepopulationfrequencyis *highlylikelytobewithinaround2standarderrorsofthesample *frequency,whichequatestoanintervalof2standarddeviations *eithersideofthesamplecount,plusanadditional0.5forthe *continuitycorrection.Sincewearesamplingwithoutreplacement, *thisisahypergeometricdistribution. * *XXX:Empirically,thisapproachseemstoworkquitewell,butit *maybeworthconsideringmoreadvancedtechniquesforestimating *theconfidenceintervalofthehypergeometricdistribution.
*/
N = totalrows;
n = samplerows;
K = N * mcv_counts[num_mcv - 1] / n;
variance = n * K * (N - K) * (N - n) / (N * N * (N - 1));
stddev = sqrt(variance);
if (mcv_counts[num_mcv - 1] > selec * samplerows + 2 * stddev + 0.5)
{ /* *Thevalueissignificantlymorecommonthanthenon-MCV *selectivitywouldsuggest.Keepit,andalltheothermore *commonvaluesinthelist.
*/ break;
} else
{ /* Discard this value and consider the next least common value */
num_mcv--; if (num_mcv == 0) break;
sumcount -= mcv_counts[num_mcv - 1];
}
} return num_mcv;
}
Messung V0.5 in Prozent
¤ Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.0.137Bemerkung:
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.