PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
ts_typanalyze.c File Reference
#include "postgres.h"
#include "access/hash.h"
#include "catalog/pg_operator.h"
#include "commands/vacuum.h"
#include "tsearch/ts_type.h"
#include "utils/builtins.h"
Include dependency graph for ts_typanalyze.c:

Go to the source code of this file.

Data Structures

struct  LexemeHashKey
 
struct  TrackItem
 

Functions

static void compute_tsvector_stats (VacAttrStats *stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
 
static void prune_lexemes_hashtable (HTAB *lexemes_tab, int b_current)
 
static uint32 lexeme_hash (const void *key, Size keysize)
 
static int lexeme_match (const void *key1, const void *key2, Size keysize)
 
static int lexeme_compare (const void *key1, const void *key2)
 
static int trackitem_compare_frequencies_desc (const void *e1, const void *e2)
 
static int trackitem_compare_lexemes (const void *e1, const void *e2)
 
Datum ts_typanalyze (PG_FUNCTION_ARGS)
 

Function Documentation

static void compute_tsvector_stats ( VacAttrStats stats,
AnalyzeAttrFetchFunc  fetchfunc,
int  samplerows,
double  totalrows 
)
static

Definition at line 139 of file ts_typanalyze.c.

References VacAttrStats::anl_context, ARRPTR, Assert, VacAttrStats::attr, cstring_to_text_with_len(), CurrentMemoryContext, DatumGetPointer, DatumGetTSVector, DEBUG3, TrackItem::delta, elog, HASHCTL::entrysize, TrackItem::frequency, HASHCTL::hash, HASH_COMPARE, HASH_CONTEXT, hash_create(), HASH_ELEM, HASH_ENTER, HASH_FUNCTION, hash_get_num_entries(), hash_search(), hash_seq_init(), hash_seq_search(), HASHCTL::hcxt, i, TrackItem::key, HASHCTL::keysize, WordEntry::len, LexemeHashKey::length, LexemeHashKey::lexeme, lexeme_hash(), lexeme_match(), HASHCTL::match, Max, MemoryContextSwitchTo(), MemSet, Min, NULL, VacAttrStats::numnumbers, VacAttrStats::numvalues, palloc(), PointerGetDatum, WordEntry::pos, prune_lexemes_hashtable(), qsort, TSVectorData::size, VacAttrStats::stadistinct, VacAttrStats::stakind, VacAttrStats::stanullfrac, VacAttrStats::stanumbers, VacAttrStats::staop, STATISTIC_KIND_MCELEM, VacAttrStats::stats_valid, VacAttrStats::statypalign, VacAttrStats::statypbyval, VacAttrStats::statypid, VacAttrStats::statyplen, VacAttrStats::stavalues, VacAttrStats::stawidth, STRPTR, TextEqualOperator, TEXTOID, trackitem_compare_frequencies_desc(), trackitem_compare_lexemes(), vacuum_delay_point(), value, and VARSIZE_ANY.

Referenced by ts_typanalyze().

143 {
144  int num_mcelem;
145  int null_cnt = 0;
146  double total_width = 0;
147 
148  /* This is D from the LC algorithm. */
149  HTAB *lexemes_tab;
150  HASHCTL hash_ctl;
151  HASH_SEQ_STATUS scan_status;
152 
153  /* This is the current bucket number from the LC algorithm */
154  int b_current;
155 
156  /* This is 'w' from the LC algorithm */
157  int bucket_width;
158  int vector_no,
159  lexeme_no;
160  LexemeHashKey hash_key;
161  TrackItem *item;
162 
163  /*
164  * We want statistics_target * 10 lexemes in the MCELEM array. This
165  * multiplier is pretty arbitrary, but is meant to reflect the fact that
166  * the number of individual lexeme values tracked in pg_statistic ought to
167  * be more than the number of values for a simple scalar column.
168  */
169  num_mcelem = stats->attr->attstattarget * 10;
170 
171  /*
172  * We set bucket width equal to (num_mcelem + 10) / 0.007 as per the
173  * comment above.
174  */
175  bucket_width = (num_mcelem + 10) * 1000 / 7;
176 
177  /*
178  * Create the hashtable. It will be in local memory, so we don't need to
179  * worry about overflowing the initial size. Also we don't need to pay any
180  * attention to locking and memory management.
181  */
182  MemSet(&hash_ctl, 0, sizeof(hash_ctl));
183  hash_ctl.keysize = sizeof(LexemeHashKey);
184  hash_ctl.entrysize = sizeof(TrackItem);
185  hash_ctl.hash = lexeme_hash;
186  hash_ctl.match = lexeme_match;
187  hash_ctl.hcxt = CurrentMemoryContext;
188  lexemes_tab = hash_create("Analyzed lexemes table",
189  num_mcelem,
190  &hash_ctl,
192 
193  /* Initialize counters. */
194  b_current = 1;
195  lexeme_no = 0;
196 
197  /* Loop over the tsvectors. */
198  for (vector_no = 0; vector_no < samplerows; vector_no++)
199  {
200  Datum value;
201  bool isnull;
202  TSVector vector;
203  WordEntry *curentryptr;
204  char *lexemesptr;
205  int j;
206 
208 
209  value = fetchfunc(stats, vector_no, &isnull);
210 
211  /*
212  * Check for null/nonnull.
213  */
214  if (isnull)
215  {
216  null_cnt++;
217  continue;
218  }
219 
220  /*
221  * Add up widths for average-width calculation. Since it's a
222  * tsvector, we know it's varlena. As in the regular
223  * compute_minimal_stats function, we use the toasted width for this
224  * calculation.
225  */
226  total_width += VARSIZE_ANY(DatumGetPointer(value));
227 
228  /*
229  * Now detoast the tsvector if needed.
230  */
231  vector = DatumGetTSVector(value);
232 
233  /*
234  * We loop through the lexemes in the tsvector and add them to our
235  * tracking hashtable. Note: the hashtable entries will point into
236  * the (detoasted) tsvector value, therefore we cannot free that
237  * storage until we're done.
238  */
239  lexemesptr = STRPTR(vector);
240  curentryptr = ARRPTR(vector);
241  for (j = 0; j < vector->size; j++)
242  {
243  bool found;
244 
245  /* Construct a hash key */
246  hash_key.lexeme = lexemesptr + curentryptr->pos;
247  hash_key.length = curentryptr->len;
248 
249  /* Lookup current lexeme in hashtable, adding it if new */
250  item = (TrackItem *) hash_search(lexemes_tab,
251  (const void *) &hash_key,
252  HASH_ENTER, &found);
253 
254  if (found)
255  {
256  /* The lexeme is already on the tracking list */
257  item->frequency++;
258  }
259  else
260  {
261  /* Initialize new tracking list element */
262  item->frequency = 1;
263  item->delta = b_current - 1;
264  }
265 
266  /* lexeme_no is the number of elements processed (ie N) */
267  lexeme_no++;
268 
269  /* We prune the D structure after processing each bucket */
270  if (lexeme_no % bucket_width == 0)
271  {
272  prune_lexemes_hashtable(lexemes_tab, b_current);
273  b_current++;
274  }
275 
276  /* Advance to the next WordEntry in the tsvector */
277  curentryptr++;
278  }
279  }
280 
281  /* We can only compute real stats if we found some non-null values. */
282  if (null_cnt < samplerows)
283  {
284  int nonnull_cnt = samplerows - null_cnt;
285  int i;
286  TrackItem **sort_table;
287  int track_len;
288  int cutoff_freq;
289  int minfreq,
290  maxfreq;
291 
292  stats->stats_valid = true;
293  /* Do the simple null-frac and average width stats */
294  stats->stanullfrac = (double) null_cnt / (double) samplerows;
295  stats->stawidth = total_width / (double) nonnull_cnt;
296 
297  /* Assume it's a unique column (see notes above) */
298  stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
299 
300  /*
301  * Construct an array of the interesting hashtable items, that is,
302  * those meeting the cutoff frequency (s - epsilon)*N. Also identify
303  * the minimum and maximum frequencies among these items.
304  *
305  * Since epsilon = s/10 and bucket_width = 1/epsilon, the cutoff
306  * frequency is 9*N / bucket_width.
307  */
308  cutoff_freq = 9 * lexeme_no / bucket_width;
309 
310  i = hash_get_num_entries(lexemes_tab); /* surely enough space */
311  sort_table = (TrackItem **) palloc(sizeof(TrackItem *) * i);
312 
313  hash_seq_init(&scan_status, lexemes_tab);
314  track_len = 0;
315  minfreq = lexeme_no;
316  maxfreq = 0;
317  while ((item = (TrackItem *) hash_seq_search(&scan_status)) != NULL)
318  {
319  if (item->frequency > cutoff_freq)
320  {
321  sort_table[track_len++] = item;
322  minfreq = Min(minfreq, item->frequency);
323  maxfreq = Max(maxfreq, item->frequency);
324  }
325  }
326  Assert(track_len <= i);
327 
328  /* emit some statistics for debug purposes */
329  elog(DEBUG3, "tsvector_stats: target # mces = %d, bucket width = %d, "
330  "# lexemes = %d, hashtable size = %d, usable entries = %d",
331  num_mcelem, bucket_width, lexeme_no, i, track_len);
332 
333  /*
334  * If we obtained more lexemes than we really want, get rid of those
335  * with least frequencies. The easiest way is to qsort the array into
336  * descending frequency order and truncate the array.
337  */
338  if (num_mcelem < track_len)
339  {
340  qsort(sort_table, track_len, sizeof(TrackItem *),
342  /* reset minfreq to the smallest frequency we're keeping */
343  minfreq = sort_table[num_mcelem - 1]->frequency;
344  }
345  else
346  num_mcelem = track_len;
347 
348  /* Generate MCELEM slot entry */
349  if (num_mcelem > 0)
350  {
351  MemoryContext old_context;
352  Datum *mcelem_values;
353  float4 *mcelem_freqs;
354 
355  /*
356  * We want to store statistics sorted on the lexeme value using
357  * first length, then byte-for-byte comparison. The reason for
358  * doing length comparison first is that we don't care about the
359  * ordering so long as it's consistent, and comparing lengths
360  * first gives us a chance to avoid a strncmp() call.
361  *
362  * This is different from what we do with scalar statistics --
363  * they get sorted on frequencies. The rationale is that we
364  * usually search through most common elements looking for a
365  * specific value, so we can grab its frequency. When values are
366  * presorted we can employ binary search for that. See
367  * ts_selfuncs.c for a real usage scenario.
368  */
369  qsort(sort_table, num_mcelem, sizeof(TrackItem *),
371 
372  /* Must copy the target values into anl_context */
373  old_context = MemoryContextSwitchTo(stats->anl_context);
374 
375  /*
376  * We sorted statistics on the lexeme value, but we want to be
377  * able to find out the minimal and maximal frequency without
378  * going through all the values. We keep those two extra
379  * frequencies in two extra cells in mcelem_freqs.
380  *
381  * (Note: the MCELEM statistics slot definition allows for a third
382  * extra number containing the frequency of nulls, but we don't
383  * create that for a tsvector column, since null elements aren't
384  * possible.)
385  */
386  mcelem_values = (Datum *) palloc(num_mcelem * sizeof(Datum));
387  mcelem_freqs = (float4 *) palloc((num_mcelem + 2) * sizeof(float4));
388 
389  /*
390  * See comments above about use of nonnull_cnt as the divisor for
391  * the final frequency estimates.
392  */
393  for (i = 0; i < num_mcelem; i++)
394  {
395  TrackItem *item = sort_table[i];
396 
397  mcelem_values[i] =
399  item->key.length));
400  mcelem_freqs[i] = (double) item->frequency / (double) nonnull_cnt;
401  }
402  mcelem_freqs[i++] = (double) minfreq / (double) nonnull_cnt;
403  mcelem_freqs[i] = (double) maxfreq / (double) nonnull_cnt;
404  MemoryContextSwitchTo(old_context);
405 
406  stats->stakind[0] = STATISTIC_KIND_MCELEM;
407  stats->staop[0] = TextEqualOperator;
408  stats->stanumbers[0] = mcelem_freqs;
409  /* See above comment about two extra frequency fields */
410  stats->numnumbers[0] = num_mcelem + 2;
411  stats->stavalues[0] = mcelem_values;
412  stats->numvalues[0] = num_mcelem;
413  /* We are storing text values */
414  stats->statypid[0] = TEXTOID;
415  stats->statyplen[0] = -1; /* typlen, -1 for varlena */
416  stats->statypbyval[0] = false;
417  stats->statypalign[0] = 'i';
418  }
419  }
420  else
421  {
422  /* We found only nulls; assume the column is entirely null */
423  stats->stats_valid = true;
424  stats->stanullfrac = 1.0;
425  stats->stawidth = 0; /* "unknown" */
426  stats->stadistinct = 0.0; /* "unknown" */
427  }
428 
429  /*
430  * We don't need to bother cleaning up any of our temporary palloc's. The
431  * hashtable should also go away, as it used a child memory context.
432  */
433 }
static struct @76 value
#define HASH_CONTEXT
Definition: hsearch.h:93
#define HASH_ELEM
Definition: hsearch.h:87
MemoryContext hcxt
Definition: hsearch.h:78
#define DEBUG3
Definition: elog.h:23
#define TEXTOID
Definition: pg_type.h:324
#define PointerGetDatum(X)
Definition: postgres.h:562
#define Min(x, y)
Definition: c.h:806
Datum * stavalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:108
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define TextEqualOperator
Definition: pg_operator.h:136
Size entrysize
Definition: hsearch.h:73
uint32 len
Definition: ts_type.h:44
#define MemSet(start, val, len)
Definition: c.h:857
long hash_get_num_entries(HTAB *hashp)
Definition: dynahash.c:1297
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:118
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
char statypalign[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:119
Form_pg_attribute attr
Definition: vacuum.h:81
Definition: dynahash.c:193
int32 stawidth
Definition: vacuum.h:101
text * cstring_to_text_with_len(const char *s, int len)
Definition: varlena.c:163
int numnumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:105
LexemeHashKey key
Definition: ts_typanalyze.c:33
int32 size
Definition: ts_type.h:93
static int lexeme_match(const void *key1, const void *key2, Size keysize)
static void prune_lexemes_hashtable(HTAB *lexemes_tab, int b_current)
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
#define DatumGetTSVector(X)
Definition: ts_type.h:117
float4 stanullfrac
Definition: vacuum.h:100
Oid staop[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:104
bool stats_valid
Definition: vacuum.h:99
float float4
Definition: c.h:380
uintptr_t Datum
Definition: postgres.h:372
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:301
int16 stakind[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:103
Size keysize
Definition: hsearch.h:72
HashCompareFunc match
Definition: hsearch.h:75
#define VARSIZE_ANY(PTR)
Definition: postgres.h:334
Oid statypid[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:116
static uint32 lexeme_hash(const void *key, Size keysize)
#define Max(x, y)
Definition: c.h:800
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static int trackitem_compare_frequencies_desc(const void *e1, const void *e2)
float4 * stanumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:106
#define HASH_COMPARE
Definition: hsearch.h:90
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1353
uint32 pos
Definition: ts_type.h:44
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1343
MemoryContext anl_context
Definition: vacuum.h:85
static int trackitem_compare_lexemes(const void *e1, const void *e2)
#define DatumGetPointer(X)
Definition: postgres.h:555
int numvalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:107
void * palloc(Size size)
Definition: mcxt.c:849
#define STRPTR(x)
Definition: hstore.h:76
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:117
#define STATISTIC_KIND_MCELEM
Definition: pg_statistic.h:257
int i
#define ARRPTR(x)
Definition: cube.c:26
#define elog
Definition: elog.h:219
#define qsort(a, b, c, d)
Definition: port.h:440
void vacuum_delay_point(void)
Definition: vacuum.c:1560
HashValueFunc hash
Definition: hsearch.h:74
#define HASH_FUNCTION
Definition: hsearch.h:89
float4 stadistinct
Definition: vacuum.h:102
static int lexeme_compare ( const void *  key1,
const void *  key2 
)
static

Definition at line 484 of file ts_typanalyze.c.

References LexemeHashKey::length, and LexemeHashKey::lexeme.

Referenced by lexeme_match(), and trackitem_compare_lexemes().

485 {
486  const LexemeHashKey *d1 = (const LexemeHashKey *) key1;
487  const LexemeHashKey *d2 = (const LexemeHashKey *) key2;
488 
489  /* First, compare by length */
490  if (d1->length > d2->length)
491  return 1;
492  else if (d1->length < d2->length)
493  return -1;
494  /* Lengths are equal, do a byte-by-byte comparison */
495  return strncmp(d1->lexeme, d2->lexeme, d1->length);
496 }
static uint32 lexeme_hash ( const void *  key,
Size  keysize 
)
static

Definition at line 462 of file ts_typanalyze.c.

References DatumGetUInt32, hash_any(), LexemeHashKey::length, and LexemeHashKey::lexeme.

Referenced by compute_tsvector_stats().

463 {
464  const LexemeHashKey *l = (const LexemeHashKey *) key;
465 
466  return DatumGetUInt32(hash_any((const unsigned char *) l->lexeme,
467  l->length));
468 }
#define DatumGetUInt32(X)
Definition: postgres.h:492
Datum hash_any(register const unsigned char *k, register int keylen)
Definition: hashfunc.c:307
static int lexeme_match ( const void *  key1,
const void *  key2,
Size  keysize 
)
static

Definition at line 474 of file ts_typanalyze.c.

References lexeme_compare().

Referenced by compute_tsvector_stats().

475 {
476  /* The keysize parameter is superfluous, the keys store their lengths */
477  return lexeme_compare(key1, key2);
478 }
static int lexeme_compare(const void *key1, const void *key2)
static void prune_lexemes_hashtable ( HTAB lexemes_tab,
int  b_current 
)
static

Definition at line 440 of file ts_typanalyze.c.

References TrackItem::delta, elog, ERROR, TrackItem::frequency, HASH_REMOVE, hash_search(), hash_seq_init(), hash_seq_search(), TrackItem::key, and NULL.

Referenced by compute_tsvector_stats().

441 {
442  HASH_SEQ_STATUS scan_status;
443  TrackItem *item;
444 
445  hash_seq_init(&scan_status, lexemes_tab);
446  while ((item = (TrackItem *) hash_seq_search(&scan_status)) != NULL)
447  {
448  if (item->frequency + item->delta <= b_current)
449  {
450  if (hash_search(lexemes_tab, (const void *) &item->key,
451  HASH_REMOVE, NULL) == NULL)
452  elog(ERROR, "hash table corrupted");
453  }
454  }
455 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
#define ERROR
Definition: elog.h:43
LexemeHashKey key
Definition: ts_typanalyze.c:33
#define NULL
Definition: c.h:229
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1353
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1343
#define elog
Definition: elog.h:219
static int trackitem_compare_frequencies_desc ( const void *  e1,
const void *  e2 
)
static

Definition at line 502 of file ts_typanalyze.c.

References TrackItem::frequency.

Referenced by compute_tsvector_stats().

503 {
504  const TrackItem *const * t1 = (const TrackItem *const *) e1;
505  const TrackItem *const * t2 = (const TrackItem *const *) e2;
506 
507  return (*t2)->frequency - (*t1)->frequency;
508 }
static int trackitem_compare_lexemes ( const void *  e1,
const void *  e2 
)
static

Definition at line 514 of file ts_typanalyze.c.

References lexeme_compare().

Referenced by compute_tsvector_stats().

515 {
516  const TrackItem *const * t1 = (const TrackItem *const *) e1;
517  const TrackItem *const * t2 = (const TrackItem *const *) e2;
518 
519  return lexeme_compare(&(*t1)->key, &(*t2)->key);
520 }
static int lexeme_compare(const void *key1, const void *key2)
Datum ts_typanalyze ( PG_FUNCTION_ARGS  )

Definition at line 54 of file ts_typanalyze.c.

References VacAttrStats::attr, VacAttrStats::compute_stats, compute_tsvector_stats(), default_statistics_target, VacAttrStats::minrows, PG_GETARG_POINTER, and PG_RETURN_BOOL.

55 {
57  Form_pg_attribute attr = stats->attr;
58 
59  /* If the attstattarget column is negative, use the default value */
60  /* NB: it is okay to scribble on stats->attr since it's a copy */
61  if (attr->attstattarget < 0)
62  attr->attstattarget = default_statistics_target;
63 
65  /* see comment about the choice of minrows in commands/analyze.c */
66  stats->minrows = 300 * attr->attstattarget;
67 
68  PG_RETURN_BOOL(true);
69 }
int minrows
Definition: vacuum.h:92
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:233
Form_pg_attribute attr
Definition: vacuum.h:81
static void compute_tsvector_stats(VacAttrStats *stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:311
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:91
int default_statistics_target
Definition: analyze.c:71