1 /*-------------------------------------------------------------------------
4 * executor utility routines for grouping, hashing, and aggregation
6 * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/executor/execGrouping.c,v 1.22 2007/01/05 22:19:27 momjian Exp $
13 *-------------------------------------------------------------------------
17 #include "executor/executor.h"
18 #include "parser/parse_oper.h"
19 #include "utils/lsyscache.h"
20 #include "utils/memutils.h"
21 #include "utils/syscache.h"
24 static TupleHashTable CurTupleHashTable = NULL;
26 static uint32 TupleHashTableHash(const void *key, Size keysize);
27 static int TupleHashTableMatch(const void *key1, const void *key2,
31 /*****************************************************************************
32 * Utility routines for grouping tuples together
33 *****************************************************************************/
37 * Return true if two tuples match in all the indicated fields.
39 * This actually implements SQL's notion of "not distinct". Two nulls
40 * match, a null and a not-null don't match.
42 * slot1, slot2: the tuples to compare (must have same columns!)
43 * numCols: the number of attributes to be examined
44 * matchColIdx: array of attribute column numbers
45 * eqFunctions: array of fmgr lookup info for the equality functions to use
46 * evalContext: short-term memory context for executing the functions
48 * NB: evalContext is reset each time!
51 execTuplesMatch(TupleTableSlot *slot1,
52 TupleTableSlot *slot2,
54 AttrNumber *matchColIdx,
55 FmgrInfo *eqfunctions,
56 MemoryContext evalContext)
58 MemoryContext oldContext;
62 /* Reset and switch into the temp context. */
63 MemoryContextReset(evalContext);
64 oldContext = MemoryContextSwitchTo(evalContext);
67 * We cannot report a match without checking all the fields, but we can
68 * report a non-match as soon as we find unequal fields. So, start
69 * comparing at the last field (least significant sort key). That's the
70 * most likely to be different if we are dealing with sorted input.
74 for (i = numCols; --i >= 0;)
76 AttrNumber att = matchColIdx[i];
82 attr1 = slot_getattr(slot1, att, &isNull1);
84 attr2 = slot_getattr(slot2, att, &isNull2);
86 if (isNull1 != isNull2)
88 result = false; /* one null and one not; they aren't equal */
93 continue; /* both are null, treat as equal */
95 /* Apply the type-specific equality function */
97 if (!DatumGetBool(FunctionCall2(&eqfunctions[i],
100 result = false; /* they aren't equal */
105 MemoryContextSwitchTo(oldContext);
112 * Return true if two tuples are definitely unequal in the indicated
115 * Nulls are neither equal nor unequal to anything else. A true result
116 * is obtained only if there are non-null fields that compare not-equal.
118 * Parameters are identical to execTuplesMatch.
121 execTuplesUnequal(TupleTableSlot *slot1,
122 TupleTableSlot *slot2,
124 AttrNumber *matchColIdx,
125 FmgrInfo *eqfunctions,
126 MemoryContext evalContext)
128 MemoryContext oldContext;
132 /* Reset and switch into the temp context. */
133 MemoryContextReset(evalContext);
134 oldContext = MemoryContextSwitchTo(evalContext);
137 * We cannot report a match without checking all the fields, but we can
138 * report a non-match as soon as we find unequal fields. So, start
139 * comparing at the last field (least significant sort key). That's the
140 * most likely to be different if we are dealing with sorted input.
144 for (i = numCols; --i >= 0;)
146 AttrNumber att = matchColIdx[i];
152 attr1 = slot_getattr(slot1, att, &isNull1);
155 continue; /* can't prove anything here */
157 attr2 = slot_getattr(slot2, att, &isNull2);
160 continue; /* can't prove anything here */
162 /* Apply the type-specific equality function */
164 if (!DatumGetBool(FunctionCall2(&eqfunctions[i],
167 result = true; /* they are unequal */
172 MemoryContextSwitchTo(oldContext);
179 * execTuplesMatchPrepare
180 * Look up the equality functions needed for execTuplesMatch or
183 * The result is a palloc'd array.
186 execTuplesMatchPrepare(TupleDesc tupdesc,
188 AttrNumber *matchColIdx)
190 FmgrInfo *eqfunctions = (FmgrInfo *) palloc(numCols * sizeof(FmgrInfo));
193 for (i = 0; i < numCols; i++)
195 AttrNumber att = matchColIdx[i];
196 Oid typid = tupdesc->attrs[att - 1]->atttypid;
199 eq_function = equality_oper_funcid(typid);
200 fmgr_info(eq_function, &eqfunctions[i]);
207 * execTuplesHashPrepare
208 * Look up the equality and hashing functions needed for a TupleHashTable.
210 * This is similar to execTuplesMatchPrepare, but we also need to find the
211 * hash functions associated with the equality operators. *eqfunctions and
212 * *hashfunctions receive the palloc'd result arrays.
215 execTuplesHashPrepare(TupleDesc tupdesc,
217 AttrNumber *matchColIdx,
218 FmgrInfo **eqfunctions,
219 FmgrInfo **hashfunctions)
223 *eqfunctions = (FmgrInfo *) palloc(numCols * sizeof(FmgrInfo));
224 *hashfunctions = (FmgrInfo *) palloc(numCols * sizeof(FmgrInfo));
226 for (i = 0; i < numCols; i++)
228 AttrNumber att = matchColIdx[i];
229 Oid typid = tupdesc->attrs[att - 1]->atttypid;
235 optup = equality_oper(typid, false);
236 eq_opr = oprid(optup);
237 eq_function = oprfuncid(optup);
238 ReleaseSysCache(optup);
239 hash_function = get_op_hash_function(eq_opr);
240 if (!OidIsValid(hash_function)) /* should not happen */
241 elog(ERROR, "could not find hash function for hash operator %u",
243 fmgr_info(eq_function, &(*eqfunctions)[i]);
244 fmgr_info(hash_function, &(*hashfunctions)[i]);
249 /*****************************************************************************
250 * Utility routines for all-in-memory hash tables
252 * These routines build hash tables for grouping tuples together (eg, for
253 * hash aggregation). There is one entry for each not-distinct set of tuples
255 *****************************************************************************/
258 * Construct an empty TupleHashTable
260 * numCols, keyColIdx: identify the tuple fields to use as lookup key
261 * eqfunctions: equality comparison functions to use
262 * hashfunctions: datatype-specific hashing functions to use
263 * nbuckets: initial estimate of hashtable size
264 * entrysize: size of each entry (at least sizeof(TupleHashEntryData))
265 * tablecxt: memory context in which to store table and table entries
266 * tempcxt: short-lived context for evaluation hash and comparison functions
268 * The function arrays may be made with execTuplesHashPrepare().
270 * Note that keyColIdx, eqfunctions, and hashfunctions must be allocated in
271 * storage that will live as long as the hashtable does.
274 BuildTupleHashTable(int numCols, AttrNumber *keyColIdx,
275 FmgrInfo *eqfunctions,
276 FmgrInfo *hashfunctions,
277 int nbuckets, Size entrysize,
278 MemoryContext tablecxt, MemoryContext tempcxt)
280 TupleHashTable hashtable;
283 Assert(nbuckets > 0);
284 Assert(entrysize >= sizeof(TupleHashEntryData));
286 hashtable = (TupleHashTable) MemoryContextAlloc(tablecxt,
287 sizeof(TupleHashTableData));
289 hashtable->numCols = numCols;
290 hashtable->keyColIdx = keyColIdx;
291 hashtable->eqfunctions = eqfunctions;
292 hashtable->hashfunctions = hashfunctions;
293 hashtable->tablecxt = tablecxt;
294 hashtable->tempcxt = tempcxt;
295 hashtable->entrysize = entrysize;
296 hashtable->tableslot = NULL; /* will be made on first lookup */
297 hashtable->inputslot = NULL;
299 MemSet(&hash_ctl, 0, sizeof(hash_ctl));
300 hash_ctl.keysize = sizeof(TupleHashEntryData);
301 hash_ctl.entrysize = entrysize;
302 hash_ctl.hash = TupleHashTableHash;
303 hash_ctl.match = TupleHashTableMatch;
304 hash_ctl.hcxt = tablecxt;
305 hashtable->hashtab = hash_create("TupleHashTable", (long) nbuckets,
307 HASH_ELEM | HASH_FUNCTION | HASH_COMPARE | HASH_CONTEXT);
313 * Find or create a hashtable entry for the tuple group containing the
316 * If isnew is NULL, we do not create new entries; we return NULL if no
319 * If isnew isn't NULL, then a new entry is created if no existing entry
320 * matches. On return, *isnew is true if the entry is newly created,
321 * false if it existed already. Any extra space in a new entry has been
325 LookupTupleHashEntry(TupleHashTable hashtable, TupleTableSlot *slot,
328 TupleHashEntry entry;
329 MemoryContext oldContext;
330 TupleHashTable saveCurHT;
331 TupleHashEntryData dummy;
334 /* If first time through, clone the input slot to make table slot */
335 if (hashtable->tableslot == NULL)
339 oldContext = MemoryContextSwitchTo(hashtable->tablecxt);
342 * We copy the input tuple descriptor just for safety --- we assume
343 * all input tuples will have equivalent descriptors.
345 tupdesc = CreateTupleDescCopy(slot->tts_tupleDescriptor);
346 hashtable->tableslot = MakeSingleTupleTableSlot(tupdesc);
347 MemoryContextSwitchTo(oldContext);
350 /* Need to run the hash functions in short-lived context */
351 oldContext = MemoryContextSwitchTo(hashtable->tempcxt);
354 * Set up data needed by hash and match functions
356 * We save and restore CurTupleHashTable just in case someone manages to
357 * invoke this code re-entrantly.
359 hashtable->inputslot = slot;
360 saveCurHT = CurTupleHashTable;
361 CurTupleHashTable = hashtable;
363 /* Search the hash table */
364 dummy.firstTuple = NULL; /* flag to reference inputslot */
365 entry = (TupleHashEntry) hash_search(hashtable->hashtab,
367 isnew ? HASH_ENTER : HASH_FIND,
374 /* found pre-existing entry */
382 * Zero any caller-requested space in the entry. (This zaps the
383 * "key data" dynahash.c copied into the new entry, but we don't
384 * care since we're about to overwrite it anyway.)
386 MemSet(entry, 0, hashtable->entrysize);
388 /* Copy the first tuple into the table context */
389 MemoryContextSwitchTo(hashtable->tablecxt);
390 entry->firstTuple = ExecCopySlotMinimalTuple(slot);
396 CurTupleHashTable = saveCurHT;
398 MemoryContextSwitchTo(oldContext);
404 * Compute the hash value for a tuple
406 * The passed-in key is a pointer to TupleHashEntryData. In an actual hash
407 * table entry, the firstTuple field points to a tuple (in MinimalTuple
408 * format). LookupTupleHashEntry sets up a dummy TupleHashEntryData with a
409 * NULL firstTuple field --- that cues us to look at the inputslot instead.
410 * This convention avoids the need to materialize virtual input tuples unless
411 * they actually need to get copied into the table.
413 * CurTupleHashTable must be set before calling this, since dynahash.c
414 * doesn't provide any API that would let us get at the hashtable otherwise.
416 * Also, the caller must select an appropriate memory context for running
417 * the hash functions. (dynahash.c doesn't change CurrentMemoryContext.)
420 TupleHashTableHash(const void *key, Size keysize)
422 MinimalTuple tuple = ((const TupleHashEntryData *) key)->firstTuple;
423 TupleTableSlot *slot;
424 TupleHashTable hashtable = CurTupleHashTable;
425 int numCols = hashtable->numCols;
426 AttrNumber *keyColIdx = hashtable->keyColIdx;
432 /* Process the current input tuple for the table */
433 slot = hashtable->inputslot;
437 /* Process a tuple already stored in the table */
438 /* (this case never actually occurs in current dynahash.c code) */
439 slot = hashtable->tableslot;
440 ExecStoreMinimalTuple(tuple, slot, false);
443 for (i = 0; i < numCols; i++)
445 AttrNumber att = keyColIdx[i];
449 /* rotate hashkey left 1 bit at each step */
450 hashkey = (hashkey << 1) | ((hashkey & 0x80000000) ? 1 : 0);
452 attr = slot_getattr(slot, att, &isNull);
454 if (!isNull) /* treat nulls as having hash key 0 */
458 hkey = DatumGetUInt32(FunctionCall1(&hashtable->hashfunctions[i],
468 * See whether two tuples (presumably of the same hash value) match
470 * As above, the passed pointers are pointers to TupleHashEntryData.
472 * CurTupleHashTable must be set before calling this, since dynahash.c
473 * doesn't provide any API that would let us get at the hashtable otherwise.
475 * Also, the caller must select an appropriate memory context for running
476 * the compare functions. (dynahash.c doesn't change CurrentMemoryContext.)
479 TupleHashTableMatch(const void *key1, const void *key2, Size keysize)
481 MinimalTuple tuple1 = ((const TupleHashEntryData *) key1)->firstTuple;
483 #ifdef USE_ASSERT_CHECKING
484 MinimalTuple tuple2 = ((const TupleHashEntryData *) key2)->firstTuple;
486 TupleTableSlot *slot1;
487 TupleTableSlot *slot2;
488 TupleHashTable hashtable = CurTupleHashTable;
491 * We assume that dynahash.c will only ever call us with the first
492 * argument being an actual table entry, and the second argument being
493 * LookupTupleHashEntry's dummy TupleHashEntryData. The other direction
494 * could be supported too, but is not currently used by dynahash.c.
496 Assert(tuple1 != NULL);
497 slot1 = hashtable->tableslot;
498 ExecStoreMinimalTuple(tuple1, slot1, false);
499 Assert(tuple2 == NULL);
500 slot2 = hashtable->inputslot;
502 if (execTuplesMatch(slot1,
505 hashtable->keyColIdx,
506 hashtable->eqfunctions,