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.23 2006/12/23 00:43:11 tgl 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 TYPECACHE_BTREE_OPFAMILY)) &&
170 typentry->btree_opf == InvalidOid)
174 opclass = GetDefaultOpClass(type_id, BTREE_AM_OID);
175 if (OidIsValid(opclass))
177 typentry->btree_opf = get_opclass_family(opclass);
178 typentry->btree_opintype = get_opclass_input_type(opclass);
180 /* Only care about hash opclass if no btree opclass... */
181 if (typentry->btree_opf == InvalidOid)
183 if (typentry->hash_opf == InvalidOid)
185 opclass = GetDefaultOpClass(type_id, HASH_AM_OID);
186 if (OidIsValid(opclass))
188 typentry->hash_opf = get_opclass_family(opclass);
189 typentry->hash_opintype = get_opclass_input_type(opclass);
196 * If we find a btree opclass where previously we only found a
197 * hash opclass, forget the hash equality operator so we can use
198 * the btree operator instead.
200 typentry->eq_opr = InvalidOid;
201 typentry->eq_opr_finfo.fn_oid = InvalidOid;
205 /* Look for requested operators and functions */
206 if ((flags & (TYPECACHE_EQ_OPR | TYPECACHE_EQ_OPR_FINFO)) &&
207 typentry->eq_opr == InvalidOid)
209 if (typentry->btree_opf != InvalidOid)
210 typentry->eq_opr = get_opfamily_member(typentry->btree_opf,
211 typentry->btree_opintype,
212 typentry->btree_opintype,
213 BTEqualStrategyNumber);
214 if (typentry->eq_opr == InvalidOid &&
215 typentry->hash_opf != InvalidOid)
216 typentry->eq_opr = get_opfamily_member(typentry->hash_opf,
217 typentry->hash_opintype,
218 typentry->hash_opintype,
219 HTEqualStrategyNumber);
221 if ((flags & TYPECACHE_LT_OPR) && typentry->lt_opr == InvalidOid)
223 if (typentry->btree_opf != InvalidOid)
224 typentry->lt_opr = get_opfamily_member(typentry->btree_opf,
225 typentry->btree_opintype,
226 typentry->btree_opintype,
227 BTLessStrategyNumber);
229 if ((flags & TYPECACHE_GT_OPR) && typentry->gt_opr == InvalidOid)
231 if (typentry->btree_opf != InvalidOid)
232 typentry->gt_opr = get_opfamily_member(typentry->btree_opf,
233 typentry->btree_opintype,
234 typentry->btree_opintype,
235 BTGreaterStrategyNumber);
237 if ((flags & (TYPECACHE_CMP_PROC | TYPECACHE_CMP_PROC_FINFO)) &&
238 typentry->cmp_proc == InvalidOid)
240 if (typentry->btree_opf != InvalidOid)
241 typentry->cmp_proc = get_opfamily_proc(typentry->btree_opf,
242 typentry->btree_opintype,
243 typentry->btree_opintype,
248 * Set up fmgr lookup info as requested
250 * Note: we tell fmgr the finfo structures live in CacheMemoryContext,
251 * which is not quite right (they're really in DynaHashContext) but this
252 * will do for our purposes.
254 if ((flags & TYPECACHE_EQ_OPR_FINFO) &&
255 typentry->eq_opr_finfo.fn_oid == InvalidOid &&
256 typentry->eq_opr != InvalidOid)
260 eq_opr_func = get_opcode(typentry->eq_opr);
261 if (eq_opr_func != InvalidOid)
262 fmgr_info_cxt(eq_opr_func, &typentry->eq_opr_finfo,
265 if ((flags & TYPECACHE_CMP_PROC_FINFO) &&
266 typentry->cmp_proc_finfo.fn_oid == InvalidOid &&
267 typentry->cmp_proc != InvalidOid)
269 fmgr_info_cxt(typentry->cmp_proc, &typentry->cmp_proc_finfo,
274 * If it's a composite type (row type), get tupdesc if requested
276 if ((flags & TYPECACHE_TUPDESC) &&
277 typentry->tupDesc == NULL &&
278 typentry->typtype == 'c')
282 if (!OidIsValid(typentry->typrelid)) /* should not happen */
283 elog(ERROR, "invalid typrelid for composite type %u",
285 rel = relation_open(typentry->typrelid, AccessShareLock);
286 Assert(rel->rd_rel->reltype == typentry->type_id);
289 * Link to the tupdesc and increment its refcount (we assert it's a
290 * refcounted descriptor). We don't use IncrTupleDescRefCount() for
291 * this, because the reference mustn't be entered in the current
292 * resource owner; it can outlive the current query.
294 typentry->tupDesc = RelationGetDescr(rel);
296 Assert(typentry->tupDesc->tdrefcount > 0);
297 typentry->tupDesc->tdrefcount++;
299 relation_close(rel, AccessShareLock);
306 * lookup_rowtype_tupdesc_internal --- internal routine to lookup a rowtype
308 * Same API as lookup_rowtype_tupdesc_noerror, but the returned tupdesc
309 * hasn't had its refcount bumped.
312 lookup_rowtype_tupdesc_internal(Oid type_id, int32 typmod, bool noError)
314 if (type_id != RECORDOID)
317 * It's a named composite type, so use the regular typcache.
319 TypeCacheEntry *typentry;
321 typentry = lookup_type_cache(type_id, TYPECACHE_TUPDESC);
322 if (typentry->tupDesc == NULL && !noError)
324 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
325 errmsg("type %s is not composite",
326 format_type_be(type_id))));
327 return typentry->tupDesc;
332 * It's a transient record type, so look in our record-type table.
334 if (typmod < 0 || typmod >= NextRecordTypmod)
338 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
339 errmsg("record type has not been registered")));
342 return RecordCacheArray[typmod];
347 * lookup_rowtype_tupdesc
349 * Given a typeid/typmod that should describe a known composite type,
350 * return the tuple descriptor for the type. Will ereport on failure.
352 * Note: on success, we increment the refcount of the returned TupleDesc,
353 * and log the reference in CurrentResourceOwner. Caller should call
354 * ReleaseTupleDesc or DecrTupleDescRefCount when done using the tupdesc.
357 lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
361 tupDesc = lookup_rowtype_tupdesc_internal(type_id, typmod, false);
362 IncrTupleDescRefCount(tupDesc);
367 * lookup_rowtype_tupdesc_noerror
369 * As above, but if the type is not a known composite type and noError
370 * is true, returns NULL instead of ereport'ing. (Note that if a bogus
371 * type_id is passed, you'll get an ereport anyway.)
374 lookup_rowtype_tupdesc_noerror(Oid type_id, int32 typmod, bool noError)
378 tupDesc = lookup_rowtype_tupdesc_internal(type_id, typmod, noError);
380 IncrTupleDescRefCount(tupDesc);
385 * lookup_rowtype_tupdesc_copy
387 * Like lookup_rowtype_tupdesc(), but the returned TupleDesc has been
388 * copied into the CurrentMemoryContext and is not reference-counted.
391 lookup_rowtype_tupdesc_copy(Oid type_id, int32 typmod)
395 tmp = lookup_rowtype_tupdesc_internal(type_id, typmod, false);
396 return CreateTupleDescCopyConstr(tmp);
401 * assign_record_type_typmod
403 * Given a tuple descriptor for a RECORD type, find or create a cache entry
404 * for the type, and set the tupdesc's tdtypmod field to a value that will
405 * identify this cache entry to lookup_rowtype_tupdesc.
408 assign_record_type_typmod(TupleDesc tupDesc)
410 RecordCacheEntry *recentry;
412 Oid hashkey[REC_HASH_KEYS];
417 MemoryContext oldcxt;
419 Assert(tupDesc->tdtypeid == RECORDOID);
421 if (RecordCacheHash == NULL)
423 /* First time through: initialize the hash table */
426 if (!CacheMemoryContext)
427 CreateCacheMemoryContext();
429 MemSet(&ctl, 0, sizeof(ctl));
430 ctl.keysize = REC_HASH_KEYS * sizeof(Oid);
431 ctl.entrysize = sizeof(RecordCacheEntry);
433 RecordCacheHash = hash_create("Record information cache", 64,
434 &ctl, HASH_ELEM | HASH_FUNCTION);
437 /* Find or create a hashtable entry for this hash class */
438 MemSet(hashkey, 0, sizeof(hashkey));
439 for (i = 0; i < tupDesc->natts; i++)
441 if (i >= REC_HASH_KEYS)
443 hashkey[i] = tupDesc->attrs[i]->atttypid;
445 recentry = (RecordCacheEntry *) hash_search(RecordCacheHash,
450 /* New entry ... hash_search initialized only the hash key */
451 recentry->tupdescs = NIL;
454 /* Look for existing record cache entry */
455 foreach(l, recentry->tupdescs)
457 entDesc = (TupleDesc) lfirst(l);
458 if (equalTupleDescs(tupDesc, entDesc))
460 tupDesc->tdtypmod = entDesc->tdtypmod;
465 /* Not present, so need to manufacture an entry */
466 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
468 if (RecordCacheArray == NULL)
470 RecordCacheArray = (TupleDesc *) palloc(64 * sizeof(TupleDesc));
471 RecordCacheArrayLen = 64;
473 else if (NextRecordTypmod >= RecordCacheArrayLen)
475 int32 newlen = RecordCacheArrayLen * 2;
477 RecordCacheArray = (TupleDesc *) repalloc(RecordCacheArray,
478 newlen * sizeof(TupleDesc));
479 RecordCacheArrayLen = newlen;
482 /* if fail in subrs, no damage except possibly some wasted memory... */
483 entDesc = CreateTupleDescCopy(tupDesc);
484 recentry->tupdescs = lcons(entDesc, recentry->tupdescs);
485 /* mark it as a reference-counted tupdesc */
486 entDesc->tdrefcount = 1;
487 /* now it's safe to advance NextRecordTypmod */
488 newtypmod = NextRecordTypmod++;
489 entDesc->tdtypmod = newtypmod;
490 RecordCacheArray[newtypmod] = entDesc;
492 /* report to caller as well */
493 tupDesc->tdtypmod = newtypmod;
495 MemoryContextSwitchTo(oldcxt);
499 * flush_rowtype_cache
501 * If a typcache entry exists for a rowtype, delete the entry's cached
502 * tuple descriptor link. This is called from relcache.c when a cached
503 * relation tupdesc is about to be dropped.
506 flush_rowtype_cache(Oid type_id)
508 TypeCacheEntry *typentry;
510 if (TypeCacheHash == NULL)
511 return; /* no table, so certainly no entry */
513 typentry = (TypeCacheEntry *) hash_search(TypeCacheHash,
516 if (typentry == NULL)
517 return; /* no matching entry */
518 if (typentry->tupDesc == NULL)
519 return; /* tupdesc hasn't been requested */
522 * Release our refcount and free the tupdesc if none remain. (Can't use
523 * DecrTupleDescRefCount because this reference is not logged in current
526 Assert(typentry->tupDesc->tdrefcount > 0);
527 if (--typentry->tupDesc->tdrefcount == 0)
528 FreeTupleDesc(typentry->tupDesc);
530 typentry->tupDesc = NULL;