1 /*-------------------------------------------------------------------------
4 * POSTGRES type cache code
6 * The type cache exists to speed lookup of certain information about data
7 * types that is not directly available from a type's pg_type row. In
8 * particular, we use a type's default btree opclass, or the default hash
9 * opclass if no btree opclass exists, to determine which operators should
10 * be used for grouping and sorting the type (GROUP BY, ORDER BY ASC/DESC).
12 * Several seemingly-odd choices have been made to support use of the type
13 * cache by the generic array comparison routines array_eq() and array_cmp().
14 * Because these routines are used as index support operations, they cannot
15 * leak memory. To allow them to execute efficiently, all information that
16 * either of them would like to re-use across calls is made available in the
19 * Once created, a type cache entry lives as long as the backend does, so
20 * there is no need for a call to release a cache entry. (For present uses,
21 * it would be okay to flush type cache entries at the ends of transactions,
22 * if we needed to reclaim space.)
24 * There is presently no provision for clearing out a cache entry if the
25 * stored data becomes obsolete. (The code will work if a type acquires
26 * opclasses it didn't have before while a backend runs --- but not if the
27 * definition of an existing opclass is altered.) However, the relcache
28 * doesn't cope with opclasses changing under it, either, so this seems
29 * a low-priority problem.
31 * We do support clearing the tuple descriptor part of a rowtype's cache
32 * entry, since that may need to change as a consequence of ALTER TABLE.
35 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
36 * Portions Copyright (c) 1994, Regents of the University of California
39 * $PostgreSQL: pgsql/src/backend/utils/cache/typcache.c,v 1.21 2006/07/14 14:52:25 momjian Exp $
41 *-------------------------------------------------------------------------
45 #include "access/hash.h"
46 #include "access/heapam.h"
47 #include "access/nbtree.h"
48 #include "catalog/pg_type.h"
49 #include "commands/defrem.h"
50 #include "utils/builtins.h"
51 #include "utils/lsyscache.h"
52 #include "utils/syscache.h"
53 #include "utils/typcache.h"
56 /* The main type cache hashtable searched by lookup_type_cache */
57 static HTAB *TypeCacheHash = NULL;
60 * We use a separate table for storing the definitions of non-anonymous
61 * record types. Once defined, a record type will be remembered for the
62 * life of the backend. Subsequent uses of the "same" record type (where
63 * sameness means equalTupleDescs) will refer to the existing table entry.
65 * Stored record types are remembered in a linear array of TupleDescs,
66 * which can be indexed quickly with the assigned typmod. There is also
67 * a hash table to speed searches for matching TupleDescs. The hash key
68 * uses just the first N columns' type OIDs, and so we may have multiple
69 * entries with the same hash key.
71 #define REC_HASH_KEYS 16 /* use this many columns in hash key */
73 typedef struct RecordCacheEntry
75 /* the hash lookup key MUST BE FIRST */
76 Oid hashkey[REC_HASH_KEYS]; /* column type IDs, zero-filled */
78 /* list of TupleDescs for record types with this hashkey */
82 static HTAB *RecordCacheHash = NULL;
84 static TupleDesc *RecordCacheArray = NULL;
85 static int32 RecordCacheArrayLen = 0; /* allocated length of array */
86 static int32 NextRecordTypmod = 0; /* number of entries used */
92 * Fetch the type cache entry for the specified datatype, and make sure that
93 * all the fields requested by bits in 'flags' are valid.
95 * The result is never NULL --- we will elog() if the passed type OID is
96 * invalid. Note however that we may fail to find one or more of the
97 * requested opclass-dependent fields; the caller needs to check whether
98 * the fields are InvalidOid or not.
101 lookup_type_cache(Oid type_id, int flags)
103 TypeCacheEntry *typentry;
106 if (TypeCacheHash == NULL)
108 /* First time through: initialize the hash table */
111 if (!CacheMemoryContext)
112 CreateCacheMemoryContext();
114 MemSet(&ctl, 0, sizeof(ctl));
115 ctl.keysize = sizeof(Oid);
116 ctl.entrysize = sizeof(TypeCacheEntry);
118 TypeCacheHash = hash_create("Type information cache", 64,
119 &ctl, HASH_ELEM | HASH_FUNCTION);
122 /* Try to look up an existing entry */
123 typentry = (TypeCacheEntry *) hash_search(TypeCacheHash,
126 if (typentry == NULL)
129 * If we didn't find one, we want to make one. But first look up the
130 * pg_type row, just to make sure we don't make a cache entry for an
136 tp = SearchSysCache(TYPEOID,
137 ObjectIdGetDatum(type_id),
139 if (!HeapTupleIsValid(tp))
140 elog(ERROR, "cache lookup failed for type %u", type_id);
141 typtup = (Form_pg_type) GETSTRUCT(tp);
142 if (!typtup->typisdefined)
144 (errcode(ERRCODE_UNDEFINED_OBJECT),
145 errmsg("type \"%s\" is only a shell",
146 NameStr(typtup->typname))));
148 /* Now make the typcache entry */
149 typentry = (TypeCacheEntry *) hash_search(TypeCacheHash,
152 Assert(!found); /* it wasn't there a moment ago */
154 MemSet(typentry, 0, sizeof(TypeCacheEntry));
155 typentry->type_id = type_id;
156 typentry->typlen = typtup->typlen;
157 typentry->typbyval = typtup->typbyval;
158 typentry->typalign = typtup->typalign;
159 typentry->typtype = typtup->typtype;
160 typentry->typrelid = typtup->typrelid;
165 /* If we haven't already found the opclass, try to do so */
166 if ((flags & (TYPECACHE_EQ_OPR | TYPECACHE_LT_OPR | TYPECACHE_GT_OPR |
168 TYPECACHE_EQ_OPR_FINFO | TYPECACHE_CMP_PROC_FINFO)) &&
169 typentry->btree_opc == InvalidOid)
171 typentry->btree_opc = GetDefaultOpClass(type_id,
173 /* Only care about hash opclass if no btree opclass... */
174 if (typentry->btree_opc == InvalidOid)
176 if (typentry->hash_opc == InvalidOid)
177 typentry->hash_opc = GetDefaultOpClass(type_id,
183 * If we find a btree opclass where previously we only found a
184 * hash opclass, forget the hash equality operator so we can use
185 * the btree operator instead.
187 typentry->eq_opr = InvalidOid;
188 typentry->eq_opr_finfo.fn_oid = InvalidOid;
192 /* Look for requested operators and functions */
193 if ((flags & (TYPECACHE_EQ_OPR | TYPECACHE_EQ_OPR_FINFO)) &&
194 typentry->eq_opr == InvalidOid)
196 if (typentry->btree_opc != InvalidOid)
197 typentry->eq_opr = get_opclass_member(typentry->btree_opc,
199 BTEqualStrategyNumber);
200 if (typentry->eq_opr == InvalidOid &&
201 typentry->hash_opc != InvalidOid)
202 typentry->eq_opr = get_opclass_member(typentry->hash_opc,
204 HTEqualStrategyNumber);
206 if ((flags & TYPECACHE_LT_OPR) && typentry->lt_opr == InvalidOid)
208 if (typentry->btree_opc != InvalidOid)
209 typentry->lt_opr = get_opclass_member(typentry->btree_opc,
211 BTLessStrategyNumber);
213 if ((flags & TYPECACHE_GT_OPR) && typentry->gt_opr == InvalidOid)
215 if (typentry->btree_opc != InvalidOid)
216 typentry->gt_opr = get_opclass_member(typentry->btree_opc,
218 BTGreaterStrategyNumber);
220 if ((flags & (TYPECACHE_CMP_PROC | TYPECACHE_CMP_PROC_FINFO)) &&
221 typentry->cmp_proc == InvalidOid)
223 if (typentry->btree_opc != InvalidOid)
224 typentry->cmp_proc = get_opclass_proc(typentry->btree_opc,
230 * Set up fmgr lookup info as requested
232 * Note: we tell fmgr the finfo structures live in CacheMemoryContext,
233 * which is not quite right (they're really in DynaHashContext) but this
234 * will do for our purposes.
236 if ((flags & TYPECACHE_EQ_OPR_FINFO) &&
237 typentry->eq_opr_finfo.fn_oid == InvalidOid &&
238 typentry->eq_opr != InvalidOid)
242 eq_opr_func = get_opcode(typentry->eq_opr);
243 if (eq_opr_func != InvalidOid)
244 fmgr_info_cxt(eq_opr_func, &typentry->eq_opr_finfo,
247 if ((flags & TYPECACHE_CMP_PROC_FINFO) &&
248 typentry->cmp_proc_finfo.fn_oid == InvalidOid &&
249 typentry->cmp_proc != InvalidOid)
251 fmgr_info_cxt(typentry->cmp_proc, &typentry->cmp_proc_finfo,
256 * If it's a composite type (row type), get tupdesc if requested
258 if ((flags & TYPECACHE_TUPDESC) &&
259 typentry->tupDesc == NULL &&
260 typentry->typtype == 'c')
264 if (!OidIsValid(typentry->typrelid)) /* should not happen */
265 elog(ERROR, "invalid typrelid for composite type %u",
267 rel = relation_open(typentry->typrelid, AccessShareLock);
268 Assert(rel->rd_rel->reltype == typentry->type_id);
271 * Link to the tupdesc and increment its refcount (we assert it's
272 * a refcounted descriptor). We don't use IncrTupleDescRefCount()
273 * for this, because the reference mustn't be entered in the current
274 * resource owner; it can outlive the current query.
276 typentry->tupDesc = RelationGetDescr(rel);
278 Assert(typentry->tupDesc->tdrefcount > 0);
279 typentry->tupDesc->tdrefcount++;
281 relation_close(rel, AccessShareLock);
288 * lookup_rowtype_tupdesc_internal --- internal routine to lookup a rowtype
290 * Same API as lookup_rowtype_tupdesc_noerror, but the returned tupdesc
291 * hasn't had its refcount bumped.
294 lookup_rowtype_tupdesc_internal(Oid type_id, int32 typmod, bool noError)
296 if (type_id != RECORDOID)
299 * It's a named composite type, so use the regular typcache.
301 TypeCacheEntry *typentry;
303 typentry = lookup_type_cache(type_id, TYPECACHE_TUPDESC);
304 if (typentry->tupDesc == NULL && !noError)
306 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
307 errmsg("type %s is not composite",
308 format_type_be(type_id))));
309 return typentry->tupDesc;
314 * It's a transient record type, so look in our record-type table.
316 if (typmod < 0 || typmod >= NextRecordTypmod)
320 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
321 errmsg("record type has not been registered")));
324 return RecordCacheArray[typmod];
329 * lookup_rowtype_tupdesc
331 * Given a typeid/typmod that should describe a known composite type,
332 * return the tuple descriptor for the type. Will ereport on failure.
334 * Note: on success, we increment the refcount of the returned TupleDesc,
335 * and log the reference in CurrentResourceOwner. Caller should call
336 * ReleaseTupleDesc or DecrTupleDescRefCount when done using the tupdesc.
339 lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
343 tupDesc = lookup_rowtype_tupdesc_internal(type_id, typmod, false);
344 IncrTupleDescRefCount(tupDesc);
349 * lookup_rowtype_tupdesc_noerror
351 * As above, but if the type is not a known composite type and noError
352 * is true, returns NULL instead of ereport'ing. (Note that if a bogus
353 * type_id is passed, you'll get an ereport anyway.)
356 lookup_rowtype_tupdesc_noerror(Oid type_id, int32 typmod, bool noError)
360 tupDesc = lookup_rowtype_tupdesc_internal(type_id, typmod, noError);
362 IncrTupleDescRefCount(tupDesc);
367 * lookup_rowtype_tupdesc_copy
369 * Like lookup_rowtype_tupdesc(), but the returned TupleDesc has been
370 * copied into the CurrentMemoryContext and is not reference-counted.
373 lookup_rowtype_tupdesc_copy(Oid type_id, int32 typmod)
377 tmp = lookup_rowtype_tupdesc_internal(type_id, typmod, false);
378 return CreateTupleDescCopyConstr(tmp);
383 * assign_record_type_typmod
385 * Given a tuple descriptor for a RECORD type, find or create a cache entry
386 * for the type, and set the tupdesc's tdtypmod field to a value that will
387 * identify this cache entry to lookup_rowtype_tupdesc.
390 assign_record_type_typmod(TupleDesc tupDesc)
392 RecordCacheEntry *recentry;
394 Oid hashkey[REC_HASH_KEYS];
399 MemoryContext oldcxt;
401 Assert(tupDesc->tdtypeid == RECORDOID);
403 if (RecordCacheHash == NULL)
405 /* First time through: initialize the hash table */
408 if (!CacheMemoryContext)
409 CreateCacheMemoryContext();
411 MemSet(&ctl, 0, sizeof(ctl));
412 ctl.keysize = REC_HASH_KEYS * sizeof(Oid);
413 ctl.entrysize = sizeof(RecordCacheEntry);
415 RecordCacheHash = hash_create("Record information cache", 64,
416 &ctl, HASH_ELEM | HASH_FUNCTION);
419 /* Find or create a hashtable entry for this hash class */
420 MemSet(hashkey, 0, sizeof(hashkey));
421 for (i = 0; i < tupDesc->natts; i++)
423 if (i >= REC_HASH_KEYS)
425 hashkey[i] = tupDesc->attrs[i]->atttypid;
427 recentry = (RecordCacheEntry *) hash_search(RecordCacheHash,
432 /* New entry ... hash_search initialized only the hash key */
433 recentry->tupdescs = NIL;
436 /* Look for existing record cache entry */
437 foreach(l, recentry->tupdescs)
439 entDesc = (TupleDesc) lfirst(l);
440 if (equalTupleDescs(tupDesc, entDesc))
442 tupDesc->tdtypmod = entDesc->tdtypmod;
447 /* Not present, so need to manufacture an entry */
448 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
450 if (RecordCacheArray == NULL)
452 RecordCacheArray = (TupleDesc *) palloc(64 * sizeof(TupleDesc));
453 RecordCacheArrayLen = 64;
455 else if (NextRecordTypmod >= RecordCacheArrayLen)
457 int32 newlen = RecordCacheArrayLen * 2;
459 RecordCacheArray = (TupleDesc *) repalloc(RecordCacheArray,
460 newlen * sizeof(TupleDesc));
461 RecordCacheArrayLen = newlen;
464 /* if fail in subrs, no damage except possibly some wasted memory... */
465 entDesc = CreateTupleDescCopy(tupDesc);
466 recentry->tupdescs = lcons(entDesc, recentry->tupdescs);
467 /* mark it as a reference-counted tupdesc */
468 entDesc->tdrefcount = 1;
469 /* now it's safe to advance NextRecordTypmod */
470 newtypmod = NextRecordTypmod++;
471 entDesc->tdtypmod = newtypmod;
472 RecordCacheArray[newtypmod] = entDesc;
474 /* report to caller as well */
475 tupDesc->tdtypmod = newtypmod;
477 MemoryContextSwitchTo(oldcxt);
481 * flush_rowtype_cache
483 * If a typcache entry exists for a rowtype, delete the entry's cached
484 * tuple descriptor link. This is called from relcache.c when a cached
485 * relation tupdesc is about to be dropped.
488 flush_rowtype_cache(Oid type_id)
490 TypeCacheEntry *typentry;
492 if (TypeCacheHash == NULL)
493 return; /* no table, so certainly no entry */
495 typentry = (TypeCacheEntry *) hash_search(TypeCacheHash,
498 if (typentry == NULL)
499 return; /* no matching entry */
500 if (typentry->tupDesc == NULL)
501 return; /* tupdesc hasn't been requested */
504 * Release our refcount and free the tupdesc if none remain.
505 * (Can't use DecrTupleDescRefCount because this reference is not
506 * logged in current resource owner.)
508 Assert(typentry->tupDesc->tdrefcount > 0);
509 if (--typentry->tupDesc->tdrefcount == 0)
510 FreeTupleDesc(typentry->tupDesc);
512 typentry->tupDesc = NULL;