Header And Logo

PostgreSQL
| The world's most advanced open source database.

array_typanalyze.c

Go to the documentation of this file.
00001 /*-------------------------------------------------------------------------
00002  *
00003  * array_typanalyze.c
00004  *    Functions for gathering statistics from array columns
00005  *
00006  * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
00007  * Portions Copyright (c) 1994, Regents of the University of California
00008  *
00009  *
00010  * IDENTIFICATION
00011  *    src/backend/utils/adt/array_typanalyze.c
00012  *
00013  *-------------------------------------------------------------------------
00014  */
00015 #include "postgres.h"
00016 
00017 #include "access/tuptoaster.h"
00018 #include "catalog/pg_collation.h"
00019 #include "commands/vacuum.h"
00020 #include "utils/array.h"
00021 #include "utils/datum.h"
00022 #include "utils/lsyscache.h"
00023 #include "utils/typcache.h"
00024 
00025 
00026 /*
00027  * To avoid consuming too much memory, IO and CPU load during analysis, and/or
00028  * too much space in the resulting pg_statistic rows, we ignore arrays that
00029  * are wider than ARRAY_WIDTH_THRESHOLD (after detoasting!).  Note that this
00030  * number is considerably more than the similar WIDTH_THRESHOLD limit used
00031  * in analyze.c's standard typanalyze code.
00032  */
00033 #define ARRAY_WIDTH_THRESHOLD 0x10000
00034 
00035 /* Extra data for compute_array_stats function */
00036 typedef struct
00037 {
00038     /* Information about array element type */
00039     Oid         type_id;        /* element type's OID */
00040     Oid         eq_opr;         /* default equality operator's OID */
00041     bool        typbyval;       /* physical properties of element type */
00042     int16       typlen;
00043     char        typalign;
00044 
00045     /*
00046      * Lookup data for element type's comparison and hash functions (these are
00047      * in the type's typcache entry, which we expect to remain valid over the
00048      * lifespan of the ANALYZE run)
00049      */
00050     FmgrInfo   *cmp;
00051     FmgrInfo   *hash;
00052 
00053     /* Saved state from std_typanalyze() */
00054     AnalyzeAttrComputeStatsFunc std_compute_stats;
00055     void       *std_extra_data;
00056 } ArrayAnalyzeExtraData;
00057 
00058 /*
00059  * While compute_array_stats is running, we keep a pointer to the extra data
00060  * here for use by assorted subroutines.  compute_array_stats doesn't
00061  * currently need to be re-entrant, so avoiding this is not worth the extra
00062  * notational cruft that would be needed.
00063  */
00064 static ArrayAnalyzeExtraData *array_extra_data;
00065 
00066 /* A hash table entry for the Lossy Counting algorithm */
00067 typedef struct
00068 {
00069     Datum       key;            /* This is 'e' from the LC algorithm. */
00070     int         frequency;      /* This is 'f'. */
00071     int         delta;          /* And this is 'delta'. */
00072     int         last_container; /* For de-duplication of array elements. */
00073 } TrackItem;
00074 
00075 /* A hash table entry for distinct-elements counts */
00076 typedef struct
00077 {
00078     int         count;          /* Count of distinct elements in an array */
00079     int         frequency;      /* Number of arrays seen with this count */
00080 } DECountItem;
00081 
00082 static void compute_array_stats(VacAttrStats *stats,
00083            AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows);
00084 static void prune_element_hashtable(HTAB *elements_tab, int b_current);
00085 static uint32 element_hash(const void *key, Size keysize);
00086 static int  element_match(const void *key1, const void *key2, Size keysize);
00087 static int  element_compare(const void *key1, const void *key2);
00088 static int  trackitem_compare_frequencies_desc(const void *e1, const void *e2);
00089 static int  trackitem_compare_element(const void *e1, const void *e2);
00090 static int  countitem_compare_count(const void *e1, const void *e2);
00091 
00092 
00093 /*
00094  * array_typanalyze -- typanalyze function for array columns
00095  */
00096 Datum
00097 array_typanalyze(PG_FUNCTION_ARGS)
00098 {
00099     VacAttrStats *stats = (VacAttrStats *) PG_GETARG_POINTER(0);
00100     Oid         element_typeid;
00101     TypeCacheEntry *typentry;
00102     ArrayAnalyzeExtraData *extra_data;
00103 
00104     /*
00105      * Call the standard typanalyze function.  It may fail to find needed
00106      * operators, in which case we also can't do anything, so just fail.
00107      */
00108     if (!std_typanalyze(stats))
00109         PG_RETURN_BOOL(false);
00110 
00111     /*
00112      * Check attribute data type is a varlena array (or a domain over one).
00113      */
00114     element_typeid = get_base_element_type(stats->attrtypid);
00115     if (!OidIsValid(element_typeid))
00116         elog(ERROR, "array_typanalyze was invoked for non-array type %u",
00117              stats->attrtypid);
00118 
00119     /*
00120      * Gather information about the element type.  If we fail to find
00121      * something, return leaving the state from std_typanalyze() in place.
00122      */
00123     typentry = lookup_type_cache(element_typeid,
00124                                  TYPECACHE_EQ_OPR |
00125                                  TYPECACHE_CMP_PROC_FINFO |
00126                                  TYPECACHE_HASH_PROC_FINFO);
00127 
00128     if (!OidIsValid(typentry->eq_opr) ||
00129         !OidIsValid(typentry->cmp_proc_finfo.fn_oid) ||
00130         !OidIsValid(typentry->hash_proc_finfo.fn_oid))
00131         PG_RETURN_BOOL(true);
00132 
00133     /* Store our findings for use by compute_array_stats() */
00134     extra_data = (ArrayAnalyzeExtraData *) palloc(sizeof(ArrayAnalyzeExtraData));
00135     extra_data->type_id = typentry->type_id;
00136     extra_data->eq_opr = typentry->eq_opr;
00137     extra_data->typbyval = typentry->typbyval;
00138     extra_data->typlen = typentry->typlen;
00139     extra_data->typalign = typentry->typalign;
00140     extra_data->cmp = &typentry->cmp_proc_finfo;
00141     extra_data->hash = &typentry->hash_proc_finfo;
00142 
00143     /* Save old compute_stats and extra_data for scalar statistics ... */
00144     extra_data->std_compute_stats = stats->compute_stats;
00145     extra_data->std_extra_data = stats->extra_data;
00146 
00147     /* ... and replace with our info */
00148     stats->compute_stats = compute_array_stats;
00149     stats->extra_data = extra_data;
00150 
00151     /*
00152      * Note we leave stats->minrows set as std_typanalyze set it.  Should it
00153      * be increased for array analysis purposes?
00154      */
00155 
00156     PG_RETURN_BOOL(true);
00157 }
00158 
00159 /*
00160  * compute_array_stats() -- compute statistics for a array column
00161  *
00162  * This function computes statistics useful for determining selectivity of
00163  * the array operators <@, &&, and @>.  It is invoked by ANALYZE via the
00164  * compute_stats hook after sample rows have been collected.
00165  *
00166  * We also invoke the standard compute_stats function, which will compute
00167  * "scalar" statistics relevant to the btree-style array comparison operators.
00168  * However, exact duplicates of an entire array may be rare despite many
00169  * arrays sharing individual elements.  This especially afflicts long arrays,
00170  * which are also liable to lack all scalar statistics due to the low
00171  * WIDTH_THRESHOLD used in analyze.c.  So, in addition to the standard stats,
00172  * we find the most common array elements and compute a histogram of distinct
00173  * element counts.
00174  *
00175  * The algorithm used is Lossy Counting, as proposed in the paper "Approximate
00176  * frequency counts over data streams" by G. S. Manku and R. Motwani, in
00177  * Proceedings of the 28th International Conference on Very Large Data Bases,
00178  * Hong Kong, China, August 2002, section 4.2. The paper is available at
00179  * http://www.vldb.org/conf/2002/S10P03.pdf
00180  *
00181  * The Lossy Counting (aka LC) algorithm goes like this:
00182  * Let s be the threshold frequency for an item (the minimum frequency we
00183  * are interested in) and epsilon the error margin for the frequency. Let D
00184  * be a set of triples (e, f, delta), where e is an element value, f is that
00185  * element's frequency (actually, its current occurrence count) and delta is
00186  * the maximum error in f. We start with D empty and process the elements in
00187  * batches of size w. (The batch size is also known as "bucket size" and is
00188  * equal to 1/epsilon.) Let the current batch number be b_current, starting
00189  * with 1. For each element e we either increment its f count, if it's
00190  * already in D, or insert a new triple into D with values (e, 1, b_current
00191  * - 1). After processing each batch we prune D, by removing from it all
00192  * elements with f + delta <= b_current.  After the algorithm finishes we
00193  * suppress all elements from D that do not satisfy f >= (s - epsilon) * N,
00194  * where N is the total number of elements in the input.  We emit the
00195  * remaining elements with estimated frequency f/N.  The LC paper proves
00196  * that this algorithm finds all elements with true frequency at least s,
00197  * and that no frequency is overestimated or is underestimated by more than
00198  * epsilon.  Furthermore, given reasonable assumptions about the input
00199  * distribution, the required table size is no more than about 7 times w.
00200  *
00201  * In the absence of a principled basis for other particular values, we
00202  * follow ts_typanalyze() and use parameters s = 0.07/K, epsilon = s/10.
00203  * But we leave out the correction for stopwords, which do not apply to
00204  * arrays.  These parameters give bucket width w = K/0.007 and maximum
00205  * expected hashtable size of about 1000 * K.
00206  *
00207  * Elements may repeat within an array.  Since duplicates do not change the
00208  * behavior of <@, && or @>, we want to count each element only once per
00209  * array.  Therefore, we store in the finished pg_statistic entry each
00210  * element's frequency as the fraction of all non-null rows that contain it.
00211  * We divide the raw counts by nonnull_cnt to get those figures.
00212  */
00213 static void
00214 compute_array_stats(VacAttrStats *stats, AnalyzeAttrFetchFunc fetchfunc,
00215                     int samplerows, double totalrows)
00216 {
00217     ArrayAnalyzeExtraData *extra_data;
00218     int         num_mcelem;
00219     int         null_cnt = 0;
00220     int         null_elem_cnt = 0;
00221     int         analyzed_rows = 0;
00222 
00223     /* This is D from the LC algorithm. */
00224     HTAB       *elements_tab;
00225     HASHCTL     elem_hash_ctl;
00226     HASH_SEQ_STATUS scan_status;
00227 
00228     /* This is the current bucket number from the LC algorithm */
00229     int         b_current;
00230 
00231     /* This is 'w' from the LC algorithm */
00232     int         bucket_width;
00233     int         array_no;
00234     int64       element_no;
00235     TrackItem  *item;
00236     int         slot_idx;
00237     HTAB       *count_tab;
00238     HASHCTL     count_hash_ctl;
00239     DECountItem *count_item;
00240 
00241     extra_data = (ArrayAnalyzeExtraData *) stats->extra_data;
00242 
00243     /*
00244      * Invoke analyze.c's standard analysis function to create scalar-style
00245      * stats for the column.  It will expect its own extra_data pointer, so
00246      * temporarily install that.
00247      */
00248     stats->extra_data = extra_data->std_extra_data;
00249     (*extra_data->std_compute_stats) (stats, fetchfunc, samplerows, totalrows);
00250     stats->extra_data = extra_data;
00251 
00252     /*
00253      * Set up static pointer for use by subroutines.  We wait till here in
00254      * case std_compute_stats somehow recursively invokes us (probably not
00255      * possible, but ...)
00256      */
00257     array_extra_data = extra_data;
00258 
00259     /*
00260      * We want statistics_target * 10 elements in the MCELEM array. This
00261      * multiplier is pretty arbitrary, but is meant to reflect the fact that
00262      * the number of individual elements tracked in pg_statistic ought to be
00263      * more than the number of values for a simple scalar column.
00264      */
00265     num_mcelem = stats->attr->attstattarget * 10;
00266 
00267     /*
00268      * We set bucket width equal to num_mcelem / 0.007 as per the comment
00269      * above.
00270      */
00271     bucket_width = num_mcelem * 1000 / 7;
00272 
00273     /*
00274      * Create the hashtable. It will be in local memory, so we don't need to
00275      * worry about overflowing the initial size. Also we don't need to pay any
00276      * attention to locking and memory management.
00277      */
00278     MemSet(&elem_hash_ctl, 0, sizeof(elem_hash_ctl));
00279     elem_hash_ctl.keysize = sizeof(Datum);
00280     elem_hash_ctl.entrysize = sizeof(TrackItem);
00281     elem_hash_ctl.hash = element_hash;
00282     elem_hash_ctl.match = element_match;
00283     elem_hash_ctl.hcxt = CurrentMemoryContext;
00284     elements_tab = hash_create("Analyzed elements table",
00285                                num_mcelem,
00286                                &elem_hash_ctl,
00287                     HASH_ELEM | HASH_FUNCTION | HASH_COMPARE | HASH_CONTEXT);
00288 
00289     /* hashtable for array distinct elements counts */
00290     MemSet(&count_hash_ctl, 0, sizeof(count_hash_ctl));
00291     count_hash_ctl.keysize = sizeof(int);
00292     count_hash_ctl.entrysize = sizeof(DECountItem);
00293     count_hash_ctl.hash = tag_hash;
00294     count_hash_ctl.hcxt = CurrentMemoryContext;
00295     count_tab = hash_create("Array distinct element count table",
00296                             64,
00297                             &count_hash_ctl,
00298                             HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
00299 
00300     /* Initialize counters. */
00301     b_current = 1;
00302     element_no = 0;
00303 
00304     /* Loop over the arrays. */
00305     for (array_no = 0; array_no < samplerows; array_no++)
00306     {
00307         Datum       value;
00308         bool        isnull;
00309         ArrayType  *array;
00310         int         num_elems;
00311         Datum      *elem_values;
00312         bool       *elem_nulls;
00313         bool        null_present;
00314         int         j;
00315         int64       prev_element_no = element_no;
00316         int         distinct_count;
00317         bool        count_item_found;
00318 
00319         vacuum_delay_point();
00320 
00321         value = fetchfunc(stats, array_no, &isnull);
00322         if (isnull)
00323         {
00324             /* array is null, just count that */
00325             null_cnt++;
00326             continue;
00327         }
00328 
00329         /* Skip too-large values. */
00330         if (toast_raw_datum_size(value) > ARRAY_WIDTH_THRESHOLD)
00331             continue;
00332         else
00333             analyzed_rows++;
00334 
00335         /*
00336          * Now detoast the array if needed, and deconstruct into datums.
00337          */
00338         array = DatumGetArrayTypeP(value);
00339 
00340         Assert(ARR_ELEMTYPE(array) == extra_data->type_id);
00341         deconstruct_array(array,
00342                           extra_data->type_id,
00343                           extra_data->typlen,
00344                           extra_data->typbyval,
00345                           extra_data->typalign,
00346                           &elem_values, &elem_nulls, &num_elems);
00347 
00348         /*
00349          * We loop through the elements in the array and add them to our
00350          * tracking hashtable.
00351          */
00352         null_present = false;
00353         for (j = 0; j < num_elems; j++)
00354         {
00355             Datum       elem_value;
00356             bool        found;
00357 
00358             /* No null element processing other than flag setting here */
00359             if (elem_nulls[j])
00360             {
00361                 null_present = true;
00362                 continue;
00363             }
00364 
00365             /* Lookup current element in hashtable, adding it if new */
00366             elem_value = elem_values[j];
00367             item = (TrackItem *) hash_search(elements_tab,
00368                                              (const void *) &elem_value,
00369                                              HASH_ENTER, &found);
00370 
00371             if (found)
00372             {
00373                 /* The element value is already on the tracking list */
00374 
00375                 /*
00376                  * The operators we assist ignore duplicate array elements, so
00377                  * count a given distinct element only once per array.
00378                  */
00379                 if (item->last_container == array_no)
00380                     continue;
00381 
00382                 item->frequency++;
00383                 item->last_container = array_no;
00384             }
00385             else
00386             {
00387                 /* Initialize new tracking list element */
00388 
00389                 /*
00390                  * If element type is pass-by-reference, we must copy it into
00391                  * palloc'd space, so that we can release the array below.
00392                  * (We do this so that the space needed for element values is
00393                  * limited by the size of the hashtable; if we kept all the
00394                  * array values around, it could be much more.)
00395                  */
00396                 item->key = datumCopy(elem_value,
00397                                       extra_data->typbyval,
00398                                       extra_data->typlen);
00399 
00400                 item->frequency = 1;
00401                 item->delta = b_current - 1;
00402                 item->last_container = array_no;
00403             }
00404 
00405             /* element_no is the number of elements processed (ie N) */
00406             element_no++;
00407 
00408             /* We prune the D structure after processing each bucket */
00409             if (element_no % bucket_width == 0)
00410             {
00411                 prune_element_hashtable(elements_tab, b_current);
00412                 b_current++;
00413             }
00414         }
00415 
00416         /* Count null element presence once per array. */
00417         if (null_present)
00418             null_elem_cnt++;
00419 
00420         /* Update frequency of the particular array distinct element count. */
00421         distinct_count = (int) (element_no - prev_element_no);
00422         count_item = (DECountItem *) hash_search(count_tab, &distinct_count,
00423                                                  HASH_ENTER,
00424                                                  &count_item_found);
00425 
00426         if (count_item_found)
00427             count_item->frequency++;
00428         else
00429             count_item->frequency = 1;
00430 
00431         /* Free memory allocated while detoasting. */
00432         if (PointerGetDatum(array) != value)
00433             pfree(array);
00434         pfree(elem_values);
00435         pfree(elem_nulls);
00436     }
00437 
00438     /* Skip pg_statistic slots occupied by standard statistics */
00439     slot_idx = 0;
00440     while (slot_idx < STATISTIC_NUM_SLOTS && stats->stakind[slot_idx] != 0)
00441         slot_idx++;
00442     if (slot_idx > STATISTIC_NUM_SLOTS - 2)
00443         elog(ERROR, "insufficient pg_statistic slots for array stats");
00444 
00445     /* We can only compute real stats if we found some non-null values. */
00446     if (analyzed_rows > 0)
00447     {
00448         int         nonnull_cnt = analyzed_rows;
00449         int         count_items_count;
00450         int         i;
00451         TrackItem **sort_table;
00452         int         track_len;
00453         int64       cutoff_freq;
00454         int64       minfreq,
00455                     maxfreq;
00456 
00457         /*
00458          * We assume the standard stats code already took care of setting
00459          * stats_valid, stanullfrac, stawidth, stadistinct.  We'd have to
00460          * re-compute those values if we wanted to not store the standard
00461          * stats.
00462          */
00463 
00464         /*
00465          * Construct an array of the interesting hashtable items, that is,
00466          * those meeting the cutoff frequency (s - epsilon)*N.  Also identify
00467          * the minimum and maximum frequencies among these items.
00468          *
00469          * Since epsilon = s/10 and bucket_width = 1/epsilon, the cutoff
00470          * frequency is 9*N / bucket_width.
00471          */
00472         cutoff_freq = 9 * element_no / bucket_width;
00473 
00474         i = hash_get_num_entries(elements_tab); /* surely enough space */
00475         sort_table = (TrackItem **) palloc(sizeof(TrackItem *) * i);
00476 
00477         hash_seq_init(&scan_status, elements_tab);
00478         track_len = 0;
00479         minfreq = element_no;
00480         maxfreq = 0;
00481         while ((item = (TrackItem *) hash_seq_search(&scan_status)) != NULL)
00482         {
00483             if (item->frequency > cutoff_freq)
00484             {
00485                 sort_table[track_len++] = item;
00486                 minfreq = Min(minfreq, item->frequency);
00487                 maxfreq = Max(maxfreq, item->frequency);
00488             }
00489         }
00490         Assert(track_len <= i);
00491 
00492         /* emit some statistics for debug purposes */
00493         elog(DEBUG3, "compute_array_stats: target # mces = %d, "
00494              "bucket width = %d, "
00495              "# elements = " INT64_FORMAT ", hashtable size = %d, "
00496              "usable entries = %d",
00497              num_mcelem, bucket_width, element_no, i, track_len);
00498 
00499         /*
00500          * If we obtained more elements than we really want, get rid of those
00501          * with least frequencies.  The easiest way is to qsort the array into
00502          * descending frequency order and truncate the array.
00503          */
00504         if (num_mcelem < track_len)
00505         {
00506             qsort(sort_table, track_len, sizeof(TrackItem *),
00507                   trackitem_compare_frequencies_desc);
00508             /* reset minfreq to the smallest frequency we're keeping */
00509             minfreq = sort_table[num_mcelem - 1]->frequency;
00510         }
00511         else
00512             num_mcelem = track_len;
00513 
00514         /* Generate MCELEM slot entry */
00515         if (num_mcelem > 0)
00516         {
00517             MemoryContext old_context;
00518             Datum      *mcelem_values;
00519             float4     *mcelem_freqs;
00520 
00521             /*
00522              * We want to store statistics sorted on the element value using
00523              * the element type's default comparison function.  This permits
00524              * fast binary searches in selectivity estimation functions.
00525              */
00526             qsort(sort_table, num_mcelem, sizeof(TrackItem *),
00527                   trackitem_compare_element);
00528 
00529             /* Must copy the target values into anl_context */
00530             old_context = MemoryContextSwitchTo(stats->anl_context);
00531 
00532             /*
00533              * We sorted statistics on the element value, but we want to be
00534              * able to find the minimal and maximal frequencies without going
00535              * through all the values.  We also want the frequency of null
00536              * elements.  Store these three values at the end of mcelem_freqs.
00537              */
00538             mcelem_values = (Datum *) palloc(num_mcelem * sizeof(Datum));
00539             mcelem_freqs = (float4 *) palloc((num_mcelem + 3) * sizeof(float4));
00540 
00541             /*
00542              * See comments above about use of nonnull_cnt as the divisor for
00543              * the final frequency estimates.
00544              */
00545             for (i = 0; i < num_mcelem; i++)
00546             {
00547                 TrackItem  *item = sort_table[i];
00548 
00549                 mcelem_values[i] = datumCopy(item->key,
00550                                              extra_data->typbyval,
00551                                              extra_data->typlen);
00552                 mcelem_freqs[i] = (double) item->frequency /
00553                     (double) nonnull_cnt;
00554             }
00555             mcelem_freqs[i++] = (double) minfreq / (double) nonnull_cnt;
00556             mcelem_freqs[i++] = (double) maxfreq / (double) nonnull_cnt;
00557             mcelem_freqs[i++] = (double) null_elem_cnt / (double) nonnull_cnt;
00558 
00559             MemoryContextSwitchTo(old_context);
00560 
00561             stats->stakind[slot_idx] = STATISTIC_KIND_MCELEM;
00562             stats->staop[slot_idx] = extra_data->eq_opr;
00563             stats->stanumbers[slot_idx] = mcelem_freqs;
00564             /* See above comment about extra stanumber entries */
00565             stats->numnumbers[slot_idx] = num_mcelem + 3;
00566             stats->stavalues[slot_idx] = mcelem_values;
00567             stats->numvalues[slot_idx] = num_mcelem;
00568             /* We are storing values of element type */
00569             stats->statypid[slot_idx] = extra_data->type_id;
00570             stats->statyplen[slot_idx] = extra_data->typlen;
00571             stats->statypbyval[slot_idx] = extra_data->typbyval;
00572             stats->statypalign[slot_idx] = extra_data->typalign;
00573             slot_idx++;
00574         }
00575 
00576         /* Generate DECHIST slot entry */
00577         count_items_count = hash_get_num_entries(count_tab);
00578         if (count_items_count > 0)
00579         {
00580             int         num_hist = stats->attr->attstattarget;
00581             DECountItem **sorted_count_items;
00582             int         j;
00583             int         delta;
00584             int64       frac;
00585             float4     *hist;
00586 
00587             /* num_hist must be at least 2 for the loop below to work */
00588             num_hist = Max(num_hist, 2);
00589 
00590             /*
00591              * Create an array of DECountItem pointers, and sort them into
00592              * increasing count order.
00593              */
00594             sorted_count_items = (DECountItem **)
00595                 palloc(sizeof(DECountItem *) * count_items_count);
00596             hash_seq_init(&scan_status, count_tab);
00597             j = 0;
00598             while ((count_item = (DECountItem *) hash_seq_search(&scan_status)) != NULL)
00599             {
00600                 sorted_count_items[j++] = count_item;
00601             }
00602             qsort(sorted_count_items, count_items_count,
00603                   sizeof(DECountItem *), countitem_compare_count);
00604 
00605             /*
00606              * Prepare to fill stanumbers with the histogram, followed by the
00607              * average count.  This array must be stored in anl_context.
00608              */
00609             hist = (float4 *)
00610                 MemoryContextAlloc(stats->anl_context,
00611                                    sizeof(float4) * (num_hist + 1));
00612             hist[num_hist] = (double) element_no / (double) nonnull_cnt;
00613 
00614             /*----------
00615              * Construct the histogram of distinct-element counts (DECs).
00616              *
00617              * The object of this loop is to copy the min and max DECs to
00618              * hist[0] and hist[num_hist - 1], along with evenly-spaced DECs
00619              * in between (where "evenly-spaced" is with reference to the
00620              * whole input population of arrays).  If we had a complete sorted
00621              * array of DECs, one per analyzed row, the i'th hist value would
00622              * come from DECs[i * (analyzed_rows - 1) / (num_hist - 1)]
00623              * (compare the histogram-making loop in compute_scalar_stats()).
00624              * But instead of that we have the sorted_count_items[] array,
00625              * which holds unique DEC values with their frequencies (that is,
00626              * a run-length-compressed version of the full array).  So we
00627              * control advancing through sorted_count_items[] with the
00628              * variable "frac", which is defined as (x - y) * (num_hist - 1),
00629              * where x is the index in the notional DECs array corresponding
00630              * to the start of the next sorted_count_items[] element's run,
00631              * and y is the index in DECs from which we should take the next
00632              * histogram value.  We have to advance whenever x <= y, that is
00633              * frac <= 0.  The x component is the sum of the frequencies seen
00634              * so far (up through the current sorted_count_items[] element),
00635              * and of course y * (num_hist - 1) = i * (analyzed_rows - 1),
00636              * per the subscript calculation above.  (The subscript calculation
00637              * implies dropping any fractional part of y; in this formulation
00638              * that's handled by not advancing until frac reaches 1.)
00639              *
00640              * Even though frac has a bounded range, it could overflow int32
00641              * when working with very large statistics targets, so we do that
00642              * math in int64.
00643              *----------
00644              */
00645             delta = analyzed_rows - 1;
00646             j = 0;              /* current index in sorted_count_items */
00647             /* Initialize frac for sorted_count_items[0]; y is initially 0 */
00648             frac = (int64) sorted_count_items[0]->frequency * (num_hist - 1);
00649             for (i = 0; i < num_hist; i++)
00650             {
00651                 while (frac <= 0)
00652                 {
00653                     /* Advance, and update x component of frac */
00654                     j++;
00655                     frac += (int64) sorted_count_items[j]->frequency * (num_hist - 1);
00656                 }
00657                 hist[i] = sorted_count_items[j]->count;
00658                 frac -= delta;  /* update y for upcoming i increment */
00659             }
00660             Assert(j == count_items_count - 1);
00661 
00662             stats->stakind[slot_idx] = STATISTIC_KIND_DECHIST;
00663             stats->staop[slot_idx] = extra_data->eq_opr;
00664             stats->stanumbers[slot_idx] = hist;
00665             stats->numnumbers[slot_idx] = num_hist + 1;
00666             slot_idx++;
00667         }
00668     }
00669 
00670     /*
00671      * We don't need to bother cleaning up any of our temporary palloc's. The
00672      * hashtable should also go away, as it used a child memory context.
00673      */
00674 }
00675 
00676 /*
00677  * A function to prune the D structure from the Lossy Counting algorithm.
00678  * Consult compute_tsvector_stats() for wider explanation.
00679  */
00680 static void
00681 prune_element_hashtable(HTAB *elements_tab, int b_current)
00682 {
00683     HASH_SEQ_STATUS scan_status;
00684     TrackItem  *item;
00685 
00686     hash_seq_init(&scan_status, elements_tab);
00687     while ((item = (TrackItem *) hash_seq_search(&scan_status)) != NULL)
00688     {
00689         if (item->frequency + item->delta <= b_current)
00690         {
00691             Datum       value = item->key;
00692 
00693             if (hash_search(elements_tab, (const void *) &item->key,
00694                             HASH_REMOVE, NULL) == NULL)
00695                 elog(ERROR, "hash table corrupted");
00696             /* We should free memory if element is not passed by value */
00697             if (!array_extra_data->typbyval)
00698                 pfree(DatumGetPointer(value));
00699         }
00700     }
00701 }
00702 
00703 /*
00704  * Hash function for elements.
00705  *
00706  * We use the element type's default hash opclass, and the default collation
00707  * if the type is collation-sensitive.
00708  */
00709 static uint32
00710 element_hash(const void *key, Size keysize)
00711 {
00712     Datum       d = *((const Datum *) key);
00713     Datum       h;
00714 
00715     h = FunctionCall1Coll(array_extra_data->hash, DEFAULT_COLLATION_OID, d);
00716     return DatumGetUInt32(h);
00717 }
00718 
00719 /*
00720  * Matching function for elements, to be used in hashtable lookups.
00721  */
00722 static int
00723 element_match(const void *key1, const void *key2, Size keysize)
00724 {
00725     /* The keysize parameter is superfluous here */
00726     return element_compare(key1, key2);
00727 }
00728 
00729 /*
00730  * Comparison function for elements.
00731  *
00732  * We use the element type's default btree opclass, and the default collation
00733  * if the type is collation-sensitive.
00734  *
00735  * XXX consider using SortSupport infrastructure
00736  */
00737 static int
00738 element_compare(const void *key1, const void *key2)
00739 {
00740     Datum       d1 = *((const Datum *) key1);
00741     Datum       d2 = *((const Datum *) key2);
00742     Datum       c;
00743 
00744     c = FunctionCall2Coll(array_extra_data->cmp, DEFAULT_COLLATION_OID, d1, d2);
00745     return DatumGetInt32(c);
00746 }
00747 
00748 /*
00749  * qsort() comparator for sorting TrackItems by frequencies (descending sort)
00750  */
00751 static int
00752 trackitem_compare_frequencies_desc(const void *e1, const void *e2)
00753 {
00754     const TrackItem *const * t1 = (const TrackItem *const *) e1;
00755     const TrackItem *const * t2 = (const TrackItem *const *) e2;
00756 
00757     return (*t2)->frequency - (*t1)->frequency;
00758 }
00759 
00760 /*
00761  * qsort() comparator for sorting TrackItems by element values
00762  */
00763 static int
00764 trackitem_compare_element(const void *e1, const void *e2)
00765 {
00766     const TrackItem *const * t1 = (const TrackItem *const *) e1;
00767     const TrackItem *const * t2 = (const TrackItem *const *) e2;
00768 
00769     return element_compare(&(*t1)->key, &(*t2)->key);
00770 }
00771 
00772 /*
00773  * qsort() comparator for sorting DECountItems by count
00774  */
00775 static int
00776 countitem_compare_count(const void *e1, const void *e2)
00777 {
00778     const DECountItem *const * t1 = (const DECountItem *const *) e1;
00779     const DECountItem *const * t2 = (const DECountItem *const *) e2;
00780 
00781     if ((*t1)->count < (*t2)->count)
00782         return -1;
00783     else if ((*t1)->count == (*t2)->count)
00784         return 0;
00785     else
00786         return 1;
00787 }