* get_variable_numdistinct * Estimate the number of distinct values of a variable. * * vardata: results of examine_variable * *isdefault: set to true if the result is a default rather than based on * anything meaningful. * * NB: be careful to produce a positive integral result, since callers may * compare the result to exact integer counts, or might divide by it. */
| 5849 | * compare the result to exact integer counts, or might divide by it. |
| 5850 | */ |
| 5851 | double |
| 5852 | get_variable_numdistinct(VariableStatData *vardata, bool *isdefault) |
| 5853 | { |
| 5854 | double stadistinct; |
| 5855 | double stanullfrac = 0.0; |
| 5856 | double ntuples; |
| 5857 | |
| 5858 | *isdefault = false; |
| 5859 | |
| 5860 | /** |
| 5861 | * If we have an estimate from the primary key, then that is the most accurate value. |
| 5862 | */ |
| 5863 | if (gp_statistics_use_fkeys && |
| 5864 | vardata->numdistinctFromPrimaryKey > 0.0) |
| 5865 | { |
| 5866 | return vardata->numdistinctFromPrimaryKey; |
| 5867 | } |
| 5868 | |
| 5869 | /* |
| 5870 | * Determine the stadistinct value to use. There are cases where we can |
| 5871 | * get an estimate even without a pg_statistic entry, or can get a better |
| 5872 | * value than is in pg_statistic. Grab stanullfrac too if we can find it |
| 5873 | * (otherwise, assume no nulls, for lack of any better idea). |
| 5874 | */ |
| 5875 | if (HeapTupleIsValid(vardata->statsTuple)) |
| 5876 | { |
| 5877 | /* Use the pg_statistic entry */ |
| 5878 | Form_pg_statistic stats; |
| 5879 | |
| 5880 | stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple); |
| 5881 | stadistinct = stats->stadistinct; |
| 5882 | stanullfrac = stats->stanullfrac; |
| 5883 | } |
| 5884 | else if (vardata->vartype == BOOLOID) |
| 5885 | { |
| 5886 | /* |
| 5887 | * Special-case boolean columns: presumably, two distinct values. |
| 5888 | * |
| 5889 | * Are there any other datatypes we should wire in special estimates |
| 5890 | * for? |
| 5891 | */ |
| 5892 | stadistinct = 2.0; |
| 5893 | } |
| 5894 | else if (vardata->rel && vardata->rel->rtekind == RTE_VALUES) |
| 5895 | { |
| 5896 | /* |
| 5897 | * If the Var represents a column of a VALUES RTE, assume it's unique. |
| 5898 | * This could of course be very wrong, but it should tend to be true |
| 5899 | * in well-written queries. We could consider examining the VALUES' |
| 5900 | * contents to get some real statistics; but that only works if the |
| 5901 | * entries are all constants, and it would be pretty expensive anyway. |
| 5902 | */ |
| 5903 | stadistinct = -1.0; /* unique (and all non null) */ |
| 5904 | } |
| 5905 | else |
| 5906 | { |
| 5907 | /* |
| 5908 | * We don't keep statistics for system columns, but in some cases we |
no test coverage detected