Debian Codegraph @

src/backend/utils/cache/typcache.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * typcache.c
4 * POSTGRES type cache code
5 *
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. For
8 * example, 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).
11 *
12 * Several seemingly-odd choices have been made to support use of the type
13 * cache by generic array and record handling routines, such as array_eq(),
14 * record_cmp(), and hash_array(). Because those routines are used as index
15 * support operations, they cannot leak memory. To allow them to execute
16 * efficiently, all information that they would like to re-use across calls
17 * is kept in the type cache.
18 *
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. If the type is
21 * dropped, the cache entry simply becomes wasted storage. This is not
22 * expected to happen often, and assuming that typcache entries are good
23 * permanently allows caching pointers to them in long-lived places.
24 *
25 * We have some provisions for updating cache entries if the stored data
26 * becomes obsolete. Core data extracted from the pg_type row is updated
27 * when we detect updates to pg_type. Information dependent on opclasses is
28 * cleared if we detect updates to pg_opclass. We also support clearing the
29 * tuple descriptor and operator/function parts of a rowtype's cache entry,
30 * since those may need to change as a consequence of ALTER TABLE. Domain
31 * constraint changes are also tracked properly.
32 *
33 *
34 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
35 * Portions Copyright (c) 1994, Regents of the University of California
36 *
37 * IDENTIFICATION
38 * src/backend/utils/cache/typcache.c
39 *
40 *-------------------------------------------------------------------------
41 */
42 #include "postgres.h"
43
44 #include <limits.h>
45
46 #include "access/hash.h"
47 #include "access/htup_details.h"
48 #include "access/nbtree.h"
49 #include "access/parallel.h"
50 #include "access/relation.h"
51 #include "access/session.h"
52 #include "access/table.h"
53 #include "catalog/pg_am.h"
54 #include "catalog/pg_constraint.h"
55 #include "catalog/pg_enum.h"
56 #include "catalog/pg_operator.h"
57 #include "catalog/pg_range.h"
58 #include "catalog/pg_type.h"
59 #include "commands/defrem.h"
60 #include "common/int.h"
61 #include "executor/executor.h"
62 #include "lib/dshash.h"
63 #include "optimizer/optimizer.h"
64 #include "port/pg_bitutils.h"
65 #include "storage/lwlock.h"
66 #include "utils/builtins.h"
67 #include "utils/catcache.h"
68 #include "utils/fmgroids.h"
69 #include "utils/injection_point.h"
70 #include "utils/inval.h"
71 #include "utils/lsyscache.h"
72 #include "utils/memutils.h"
73 #include "utils/rel.h"
74 #include "utils/syscache.h"
75 #include "utils/typcache.h"
76
77
78 /* The main type cache hashtable searched by lookup_type_cache */
79 static HTAB *TypeCacheHash = NULL;
80
81 /*
82 * The mapping of relation's OID to the corresponding composite type OID.
83 * We're keeping the map entry when the corresponding typentry has something
84 * to clear i.e it has either TCFLAGS_HAVE_PG_TYPE_DATA, or
85 * TCFLAGS_OPERATOR_FLAGS, or tupdesc.
86 */
87 static HTAB *RelIdToTypeIdCacheHash = NULL;
88
89 typedef struct RelIdToTypeIdCacheEntry
90 {
91 Oid relid; /* OID of the relation */
92 Oid composite_typid; /* OID of the relation's composite type */
93 } RelIdToTypeIdCacheEntry;
94
95 /* List of type cache entries for domain types */
96 static TypeCacheEntry *firstDomainTypeEntry = NULL;
97
98 /* Private flag bits in the TypeCacheEntry.flags field */
99 #define TCFLAGS_HAVE_PG_TYPE_DATA 0x000001
100 #define TCFLAGS_CHECKED_BTREE_OPCLASS 0x000002
101 #define TCFLAGS_CHECKED_HASH_OPCLASS 0x000004
102 #define TCFLAGS_CHECKED_EQ_OPR 0x000008
103 #define TCFLAGS_CHECKED_LT_OPR 0x000010
104 #define TCFLAGS_CHECKED_GT_OPR 0x000020
105 #define TCFLAGS_CHECKED_CMP_PROC 0x000040
106 #define TCFLAGS_CHECKED_HASH_PROC 0x000080
107 #define TCFLAGS_CHECKED_HASH_EXTENDED_PROC 0x000100
108 #define TCFLAGS_CHECKED_ELEM_PROPERTIES 0x000200
109 #define TCFLAGS_HAVE_ELEM_EQUALITY 0x000400
110 #define TCFLAGS_HAVE_ELEM_COMPARE 0x000800
111 #define TCFLAGS_HAVE_ELEM_HASHING 0x001000
112 #define TCFLAGS_HAVE_ELEM_EXTENDED_HASHING 0x002000
113 #define TCFLAGS_CHECKED_FIELD_PROPERTIES 0x004000
114 #define TCFLAGS_HAVE_FIELD_EQUALITY 0x008000
115 #define TCFLAGS_HAVE_FIELD_COMPARE 0x010000
116 #define TCFLAGS_HAVE_FIELD_HASHING 0x020000
117 #define TCFLAGS_HAVE_FIELD_EXTENDED_HASHING 0x040000
118 #define TCFLAGS_CHECKED_DOMAIN_CONSTRAINTS 0x080000
119 #define TCFLAGS_DOMAIN_BASE_IS_COMPOSITE 0x100000
120
121 /* The flags associated with equality/comparison/hashing are all but these: */
122 #define TCFLAGS_OPERATOR_FLAGS \
123 (~(TCFLAGS_HAVE_PG_TYPE_DATA | \
124 TCFLAGS_CHECKED_DOMAIN_CONSTRAINTS | \
125 TCFLAGS_DOMAIN_BASE_IS_COMPOSITE))
126
127 /*
128 * Data stored about a domain type's constraints. Note that we do not create
129 * this struct for the common case of a constraint-less domain; we just set
130 * domainData to NULL to indicate that.
131 *
132 * Within a DomainConstraintCache, we store expression plan trees, but the
133 * check_exprstate fields of the DomainConstraintState nodes are just NULL.
134 * When needed, expression evaluation nodes are built by flat-copying the
135 * DomainConstraintState nodes and applying ExecInitExpr to check_expr.
136 * Such a node tree is not part of the DomainConstraintCache, but is
137 * considered to belong to a DomainConstraintRef.
138 */
139 struct DomainConstraintCache
140 {
141 List *constraints; /* list of DomainConstraintState nodes */
142 MemoryContext dccContext; /* memory context holding all associated data */
143 long dccRefCount; /* number of references to this struct */
144 };
145
146 /* Private information to support comparisons of enum values */
147 typedef struct
148 {
149 Oid enum_oid; /* OID of one enum value */
150 float4 sort_order; /* its sort position */
151 } EnumItem;
152
153 typedef struct TypeCacheEnumData
154 {
155 Oid bitmap_base; /* OID corresponding to bit 0 of bitmapset */
156 Bitmapset *sorted_values; /* Set of OIDs known to be in order */
157 int num_values; /* total number of values in enum */
158 EnumItem enum_values[FLEXIBLE_ARRAY_MEMBER];
159 } TypeCacheEnumData;
160
161 /*
162 * We use a separate table for storing the definitions of non-anonymous
163 * record types. Once defined, a record type will be remembered for the
164 * life of the backend. Subsequent uses of the "same" record type (where
165 * sameness means equalRowTypes) will refer to the existing table entry.
166 *
167 * Stored record types are remembered in a linear array of TupleDescs,
168 * which can be indexed quickly with the assigned typmod. There is also
169 * a hash table to speed searches for matching TupleDescs.
170 */
171
172 typedef struct RecordCacheEntry
173 {
174 TupleDesc tupdesc;
175 } RecordCacheEntry;
176
177 /*
178 * To deal with non-anonymous record types that are exchanged by backends
179 * involved in a parallel query, we also need a shared version of the above.
180 */
181 struct SharedRecordTypmodRegistry
182 {
183 /* A hash table for finding a matching TupleDesc. */
184 dshash_table_handle record_table_handle;
185 /* A hash table for finding a TupleDesc by typmod. */
186 dshash_table_handle typmod_table_handle;
187 /* A source of new record typmod numbers. */
188 pg_atomic_uint32 next_typmod;
189 };
190
191 /*
192 * When using shared tuple descriptors as hash table keys we need a way to be
193 * able to search for an equal shared TupleDesc using a backend-local
194 * TupleDesc. So we use this type which can hold either, and hash and compare
195 * functions that know how to handle both.
196 */
197 typedef struct SharedRecordTableKey
198 {
199 union
200 {
201 TupleDesc local_tupdesc;
202 dsa_pointer shared_tupdesc;
203 } u;
204 bool shared;
205 } SharedRecordTableKey;
206
207 /*
208 * The shared version of RecordCacheEntry. This lets us look up a typmod
209 * using a TupleDesc which may be in local or shared memory.
210 */
211 typedef struct SharedRecordTableEntry
212 {
213 SharedRecordTableKey key;
214 } SharedRecordTableEntry;
215
216 /*
217 * An entry in SharedRecordTypmodRegistry's typmod table. This lets us look
218 * up a TupleDesc in shared memory using a typmod.
219 */
220 typedef struct SharedTypmodTableEntry
221 {
222 uint32 typmod;
223 dsa_pointer shared_tupdesc;
224 } SharedTypmodTableEntry;
225
226 static Oid *in_progress_list;
227 static int in_progress_list_len;
228 static int in_progress_list_maxlen;
229
230 /*
231 * A comparator function for SharedRecordTableKey.
232 */
233 static int
234 shared_record_table_compare(const void *a, const void *b, size_t size,
235 void *arg)
236 {
237 dsa_area *area = (dsa_area *) arg;
238 SharedRecordTableKey *k1 = (SharedRecordTableKey *) a;
239 SharedRecordTableKey *k2 = (SharedRecordTableKey *) b;
240 TupleDesc t1;
241 TupleDesc t2;
242
243 if (k1->shared)
244 t1 = (TupleDesc) dsa_get_address(area, k1->u.shared_tupdesc);
245 else
246 t1 = k1->u.local_tupdesc;
247
248 if (k2->shared)
249 t2 = (TupleDesc) dsa_get_address(area, k2->u.shared_tupdesc);
250 else
251 t2 = k2->u.local_tupdesc;
252
253 return equalRowTypes(t1, t2) ? 0 : 1;
254 }
255
256 /*
257 * A hash function for SharedRecordTableKey.
258 */
259 static uint32
260 shared_record_table_hash(const void *a, size_t size, void *arg)
261 {
262 dsa_area *area = (dsa_area *) arg;
263 SharedRecordTableKey *k = (SharedRecordTableKey *) a;
264 TupleDesc t;
265
266 if (k->shared)
267 t = (TupleDesc) dsa_get_address(area, k->u.shared_tupdesc);
268 else
269 t = k->u.local_tupdesc;
270
271 return hashRowType(t);
272 }
273
274 /* Parameters for SharedRecordTypmodRegistry's TupleDesc table. */
275 static const dshash_parameters srtr_record_table_params = {
276 sizeof(SharedRecordTableKey), /* unused */
277 sizeof(SharedRecordTableEntry),
278 shared_record_table_compare,
279 shared_record_table_hash,
280 dshash_memcpy,
281 LWTRANCHE_PER_SESSION_RECORD_TYPE
282 };
283
284 /* Parameters for SharedRecordTypmodRegistry's typmod hash table. */
285 static const dshash_parameters srtr_typmod_table_params = {
286 sizeof(uint32),
287 sizeof(SharedTypmodTableEntry),
288 dshash_memcmp,
289 dshash_memhash,
290 dshash_memcpy,
291 LWTRANCHE_PER_SESSION_RECORD_TYPMOD
292 };
293
294 /* hashtable for recognizing registered record types */
295 static HTAB *RecordCacheHash = NULL;
296
297 typedef struct RecordCacheArrayEntry
298 {
299 uint64 id;
300 TupleDesc tupdesc;
301 } RecordCacheArrayEntry;
302
303 /* array of info about registered record types, indexed by assigned typmod */
304 static RecordCacheArrayEntry *RecordCacheArray = NULL;
305 static int32 RecordCacheArrayLen = 0; /* allocated length of above array */
306 static int32 NextRecordTypmod = 0; /* number of entries used */
307
308 /*
309 * Process-wide counter for generating unique tupledesc identifiers.
310 * Zero and one (INVALID_TUPLEDESC_IDENTIFIER) aren't allowed to be chosen
311 * as identifiers, so we start the counter at INVALID_TUPLEDESC_IDENTIFIER.
312 */
313 static uint64 tupledesc_id_counter = INVALID_TUPLEDESC_IDENTIFIER;
314
315 static void load_typcache_tupdesc(TypeCacheEntry *typentry);
316 static void load_rangetype_info(TypeCacheEntry *typentry);
317 static void load_multirangetype_info(TypeCacheEntry *typentry);
318 static void load_domaintype_info(TypeCacheEntry *typentry);
319 static int dcs_cmp(const void *a, const void *b);
320 static void decr_dcc_refcount(DomainConstraintCache *dcc);
321 static void dccref_deletion_callback(void *arg);
322 static List *prep_domain_constraints(List *constraints, MemoryContext execctx);
323 static bool array_element_has_equality(TypeCacheEntry *typentry);
324 static bool array_element_has_compare(TypeCacheEntry *typentry);
325 static bool array_element_has_hashing(TypeCacheEntry *typentry);
326 static bool array_element_has_extended_hashing(TypeCacheEntry *typentry);
327 static void cache_array_element_properties(TypeCacheEntry *typentry);
328 static bool record_fields_have_equality(TypeCacheEntry *typentry);
329 static bool record_fields_have_compare(TypeCacheEntry *typentry);
330 static bool record_fields_have_hashing(TypeCacheEntry *typentry);
331 static bool record_fields_have_extended_hashing(TypeCacheEntry *typentry);
332 static void cache_record_field_properties(TypeCacheEntry *typentry);
333 static bool range_element_has_hashing(TypeCacheEntry *typentry);
334 static bool range_element_has_extended_hashing(TypeCacheEntry *typentry);
335 static void cache_range_element_properties(TypeCacheEntry *typentry);
336 static bool multirange_element_has_hashing(TypeCacheEntry *typentry);
337 static bool multirange_element_has_extended_hashing(TypeCacheEntry *typentry);
338 static void cache_multirange_element_properties(TypeCacheEntry *typentry);
339 static void TypeCacheRelCallback(Datum arg, Oid relid);
340 static void TypeCacheTypCallback(Datum arg, int cacheid, uint32 hashvalue);
341 static void TypeCacheOpcCallback(Datum arg, int cacheid, uint32 hashvalue);
342 static void TypeCacheConstrCallback(Datum arg, int cacheid, uint32 hashvalue);
343 static void load_enum_cache_data(TypeCacheEntry *tcache);
344 static EnumItem *find_enumitem(TypeCacheEnumData *enumdata, Oid arg);
345 static int enum_oid_cmp(const void *left, const void *right);
346 static void shared_record_typmod_registry_detach(dsm_segment *segment,
347 Datum datum);
348 static TupleDesc find_or_make_matching_shared_tupledesc(TupleDesc tupdesc);
349 static dsa_pointer share_tupledesc(dsa_area *area, TupleDesc tupdesc,
350 uint32 typmod);
351 static void insert_rel_type_cache_if_needed(TypeCacheEntry *typentry);
352 static void delete_rel_type_cache_if_needed(TypeCacheEntry *typentry);
353
354
355 /*
356 * Hash function compatible with one-arg system cache hash function.
357 */
358 static uint32
359 type_cache_syshash(const void *key, Size keysize)
360 {
361 Assert(keysize == sizeof(Oid));
362 return GetSysCacheHashValue1(TYPEOID, ObjectIdGetDatum(*(const Oid *) key));
363 }
364
365 /*
366 * lookup_type_cache
367 *
368 * Fetch the type cache entry for the specified datatype, and make sure that
369 * all the fields requested by bits in 'flags' are valid.
370 *
371 * The result is never NULL --- we will ereport() if the passed type OID is
372 * invalid. Note however that we may fail to find one or more of the
373 * values requested by 'flags'; the caller needs to check whether the fields
374 * are InvalidOid or not.
375 *
376 * Note that while filling TypeCacheEntry we might process concurrent
377 * invalidation messages, causing our not-yet-filled TypeCacheEntry to be
378 * invalidated. In this case, we typically only clear flags while values are
379 * still available for the caller. It's expected that the caller holds
380 * enough locks on type-depending objects that the values are still relevant.
381 * It's also important that the tupdesc is filled after all other
382 * TypeCacheEntry items for TYPTYPE_COMPOSITE. So, tupdesc can't get
383 * invalidated during the lookup_type_cache() call.
384 */
385 TypeCacheEntry *
386 lookup_type_cache(Oid type_id, int flags)
387 {
388 TypeCacheEntry *typentry;
389 bool found;
390 int in_progress_offset;
391
392 if (TypeCacheHash == NULL)
393 {
394 /* First time through: initialize the hash table */
395 HASHCTL ctl;
396 int allocsize;
397
398 ctl.keysize = sizeof(Oid);
399 ctl.entrysize = sizeof(TypeCacheEntry);
400
401 /*
402 * TypeCacheEntry takes hash value from the system cache. For
403 * TypeCacheHash we use the same hash in order to speedup search by
404 * hash value. This is used by hash_seq_init_with_hash_value().
405 */
406 ctl.hash = type_cache_syshash;
407
408 TypeCacheHash = hash_create("Type information cache", 64,
409 &ctl, HASH_ELEM | HASH_FUNCTION);
410
411 Assert(RelIdToTypeIdCacheHash == NULL);
412
413 ctl.keysize = sizeof(Oid);
414 ctl.entrysize = sizeof(RelIdToTypeIdCacheEntry);
415 RelIdToTypeIdCacheHash = hash_create("Map from relid to OID of cached composite type", 64,
416 &ctl, HASH_ELEM | HASH_BLOBS);
417
418 /* Also set up callbacks for SI invalidations */
419 CacheRegisterRelcacheCallback(TypeCacheRelCallback, (Datum) 0);
420 CacheRegisterSyscacheCallback(TYPEOID, TypeCacheTypCallback, (Datum) 0);
421 CacheRegisterSyscacheCallback(CLAOID, TypeCacheOpcCallback, (Datum) 0);
422 CacheRegisterSyscacheCallback(CONSTROID, TypeCacheConstrCallback, (Datum) 0);
423
424 /* Also make sure CacheMemoryContext exists */
425 if (!CacheMemoryContext)
426 CreateCacheMemoryContext();
427
428 /*
429 * reserve enough in_progress_list slots for many cases
430 */
431 allocsize = 4;
432 in_progress_list =
433 MemoryContextAlloc(CacheMemoryContext,
434 allocsize * sizeof(*in_progress_list));
435 in_progress_list_maxlen = allocsize;
436 }
437
438 Assert(TypeCacheHash != NULL && RelIdToTypeIdCacheHash != NULL);
439
440 /* Register to catch invalidation messages */
441 if (in_progress_list_len >= in_progress_list_maxlen)
442 {
443 int allocsize;
444
445 allocsize = in_progress_list_maxlen * 2;
446 in_progress_list = repalloc(in_progress_list,
447 allocsize * sizeof(*in_progress_list));
448 in_progress_list_maxlen = allocsize;
449 }
450 in_progress_offset = in_progress_list_len++;
451 in_progress_list[in_progress_offset] = type_id;
452
453 /* Try to look up an existing entry */
454 typentry = (TypeCacheEntry *) hash_search(TypeCacheHash,
455 &type_id,
456 HASH_FIND, NULL);
457 if (typentry == NULL)
458 {
459 /*
460 * If we didn't find one, we want to make one. But first look up the
461 * pg_type row, just to make sure we don't make a cache entry for an
462 * invalid type OID. If the type OID is not valid, present a
463 * user-facing error, since some code paths such as domain_in() allow
464 * this function to be reached with a user-supplied OID.
465 */
466 HeapTuple tp;
467 Form_pg_type typtup;
468
469 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type_id));
470 if (!HeapTupleIsValid(tp))
471 ereport(ERROR,
472 (errcode(ERRCODE_UNDEFINED_OBJECT),
473 errmsg("type with OID %u does not exist", type_id)));
474 typtup = (Form_pg_type) GETSTRUCT(tp);
475 if (!typtup->typisdefined)
476 ereport(ERROR,
477 (errcode(ERRCODE_UNDEFINED_OBJECT),
478 errmsg("type \"%s\" is only a shell",
479 NameStr(typtup->typname))));
480
481 /* Now make the typcache entry */
482 typentry = (TypeCacheEntry *) hash_search(TypeCacheHash,
483 &type_id,
484 HASH_ENTER, &found);
485 Assert(!found); /* it wasn't there a moment ago */
486
487 MemSet(typentry, 0, sizeof(TypeCacheEntry));
488
489 /* These fields can never change, by definition */
490 typentry->type_id = type_id;
491 typentry->type_id_hash = get_hash_value(TypeCacheHash, &type_id);
492
493 /* Keep this part in sync with the code below */
494 typentry->typlen = typtup->typlen;
495 typentry->typbyval = typtup->typbyval;
496 typentry->typalign = typtup->typalign;
497 typentry->typstorage = typtup->typstorage;
498 typentry->typtype = typtup->typtype;
499 typentry->typrelid = typtup->typrelid;
500 typentry->typsubscript = typtup->typsubscript;
501 typentry->typelem = typtup->typelem;
502 typentry->typarray = typtup->typarray;
503 typentry->typcollation = typtup->typcollation;
504 typentry->flags |= TCFLAGS_HAVE_PG_TYPE_DATA;
505
506 /* If it's a domain, immediately thread it into the domain cache list */
507 if (typentry->typtype == TYPTYPE_DOMAIN)
508 {
509 typentry->nextDomain = firstDomainTypeEntry;
510 firstDomainTypeEntry = typentry;
511 }
512
513 ReleaseSysCache(tp);
514 }
515 else if (!(typentry->flags & TCFLAGS_HAVE_PG_TYPE_DATA))
516 {
517 /*
518 * We have an entry, but its pg_type row got changed, so reload the
519 * data obtained directly from pg_type.
520 */
521 HeapTuple tp;
522 Form_pg_type typtup;
523
524 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type_id));
525 if (!HeapTupleIsValid(tp))
526 ereport(ERROR,
527 (errcode(ERRCODE_UNDEFINED_OBJECT),
528 errmsg("type with OID %u does not exist", type_id)));
529 typtup = (Form_pg_type) GETSTRUCT(tp);
530 if (!typtup->typisdefined)
531 ereport(ERROR,
532 (errcode(ERRCODE_UNDEFINED_OBJECT),
533 errmsg("type \"%s\" is only a shell",
534 NameStr(typtup->typname))));
535
536 /*
537 * Keep this part in sync with the code above. Many of these fields
538 * shouldn't ever change, particularly typtype, but copy 'em anyway.
539 */
540 typentry->typlen = typtup->typlen;
541 typentry->typbyval = typtup->typbyval;
542 typentry->typalign = typtup->typalign;
543 typentry->typstorage = typtup->typstorage;
544 typentry->typtype = typtup->typtype;
545 typentry->typrelid = typtup->typrelid;
546 typentry->typsubscript = typtup->typsubscript;
547 typentry->typelem = typtup->typelem;
548 typentry->typarray = typtup->typarray;
549 typentry->typcollation = typtup->typcollation;
550 typentry->flags |= TCFLAGS_HAVE_PG_TYPE_DATA;
551
552 ReleaseSysCache(tp);
553 }
554
555 /*
556 * Look up opclasses if we haven't already and any dependent info is
557 * requested.
558 */
559 if ((flags & (TYPECACHE_EQ_OPR | TYPECACHE_LT_OPR | TYPECACHE_GT_OPR |
560 TYPECACHE_CMP_PROC |
561 TYPECACHE_EQ_OPR_FINFO | TYPECACHE_CMP_PROC_FINFO |
562 TYPECACHE_BTREE_OPFAMILY)) &&
563 !(typentry->flags & TCFLAGS_CHECKED_BTREE_OPCLASS))
564 {
565 Oid opclass;
566
567 opclass = GetDefaultOpClass(type_id, BTREE_AM_OID);
568 if (OidIsValid(opclass))
569 {
570 typentry->btree_opf = get_opclass_family(opclass);
571 typentry->btree_opintype = get_opclass_input_type(opclass);
572 }
573 else
574 {
575 typentry->btree_opf = typentry->btree_opintype = InvalidOid;
576 }
577
578 /*
579 * Reset information derived from btree opclass. Note in particular
580 * that we'll redetermine the eq_opr even if we previously found one;
581 * this matters in case a btree opclass has been added to a type that
582 * previously had only a hash opclass.
583 */
584 typentry->flags &= ~(TCFLAGS_CHECKED_EQ_OPR |
585 TCFLAGS_CHECKED_LT_OPR |
586 TCFLAGS_CHECKED_GT_OPR |
587 TCFLAGS_CHECKED_CMP_PROC);
588 typentry->flags |= TCFLAGS_CHECKED_BTREE_OPCLASS;
589 }
590
591 /*
592 * If we need to look up equality operator, and there's no btree opclass,
593 * force lookup of hash opclass.
594 */
595 if ((flags & (TYPECACHE_EQ_OPR | TYPECACHE_EQ_OPR_FINFO)) &&
596 !(typentry->flags & TCFLAGS_CHECKED_EQ_OPR) &&
597 typentry->btree_opf == InvalidOid)
598 flags |= TYPECACHE_HASH_OPFAMILY;
599
600 if ((flags & (TYPECACHE_HASH_PROC | TYPECACHE_HASH_PROC_FINFO |
601 TYPECACHE_HASH_EXTENDED_PROC |
602 TYPECACHE_HASH_EXTENDED_PROC_FINFO |
603 TYPECACHE_HASH_OPFAMILY)) &&
604 !(typentry->flags & TCFLAGS_CHECKED_HASH_OPCLASS))
605 {
606 Oid opclass;
607
608 opclass = GetDefaultOpClass(type_id, HASH_AM_OID);
609 if (OidIsValid(opclass))
610 {
611 typentry->hash_opf = get_opclass_family(opclass);
612 typentry->hash_opintype = get_opclass_input_type(opclass);
613 }
614 else
615 {
616 typentry->hash_opf = typentry->hash_opintype = InvalidOid;
617 }
618
619 /*
620 * Reset information derived from hash opclass. We do *not* reset the
621 * eq_opr; if we already found one from the btree opclass, that
622 * decision is still good.
623 */
624 typentry->flags &= ~(TCFLAGS_CHECKED_HASH_PROC |
625 TCFLAGS_CHECKED_HASH_EXTENDED_PROC);
626 typentry->flags |= TCFLAGS_CHECKED_HASH_OPCLASS;
627 }
628
629 /*
630 * Look for requested operators and functions, if we haven't already.
631 */
632 if ((flags & (TYPECACHE_EQ_OPR | TYPECACHE_EQ_OPR_FINFO)) &&
633 !(typentry->flags & TCFLAGS_CHECKED_EQ_OPR))
634 {
635 Oid eq_opr = InvalidOid;
636
637 if (typentry->btree_opf != InvalidOid)
638 eq_opr = get_opfamily_member(typentry->btree_opf,
639 typentry->btree_opintype,
640 typentry->btree_opintype,
641 BTEqualStrategyNumber);
642 if (eq_opr == InvalidOid &&
643 typentry->hash_opf != InvalidOid)
644 eq_opr = get_opfamily_member(typentry->hash_opf,
645 typentry->hash_opintype,
646 typentry->hash_opintype,
647 HTEqualStrategyNumber);
648
649 /*
650 * If the proposed equality operator is array_eq or record_eq, check
651 * to see if the element type or column types support equality. If
652 * not, array_eq or record_eq would fail at runtime, so we don't want
653 * to report that the type has equality. (We can omit similar
654 * checking for ranges and multiranges because ranges can't be created
655 * in the first place unless their subtypes support equality.)
656 */
657 if (eq_opr == ARRAY_EQ_OP &&
658 !array_element_has_equality(typentry))
659 eq_opr = InvalidOid;
660 else if (eq_opr == RECORD_EQ_OP &&
661 !record_fields_have_equality(typentry))
662 eq_opr = InvalidOid;
663
664 /* Force update of eq_opr_finfo only if we're changing state */
665 if (typentry->eq_opr != eq_opr)
666 typentry->eq_opr_finfo.fn_oid = InvalidOid;
667
668 typentry->eq_opr = eq_opr;
669
670 /*
671 * Reset info about hash functions whenever we pick up new info about
672 * equality operator. This is so we can ensure that the hash
673 * functions match the operator.
674 */
675 typentry->flags &= ~(TCFLAGS_CHECKED_HASH_PROC |
676 TCFLAGS_CHECKED_HASH_EXTENDED_PROC);
677 typentry->flags |= TCFLAGS_CHECKED_EQ_OPR;
678 }
679 if ((flags & TYPECACHE_LT_OPR) &&
680 !(typentry->flags & TCFLAGS_CHECKED_LT_OPR))
681 {
682 Oid lt_opr = InvalidOid;
683
684 if (typentry->btree_opf != InvalidOid)
685 lt_opr = get_opfamily_member(typentry->btree_opf,
686 typentry->btree_opintype,
687 typentry->btree_opintype,
688 BTLessStrategyNumber);
689
690 /*
691 * As above, make sure array_cmp or record_cmp will succeed; but again
692 * we need no special check for ranges or multiranges.
693 */
694 if (lt_opr == ARRAY_LT_OP &&
695 !array_element_has_compare(typentry))
696 lt_opr = InvalidOid;
697 else if (lt_opr == RECORD_LT_OP &&
698 !record_fields_have_compare(typentry))
699 lt_opr = InvalidOid;
700
701 typentry->lt_opr = lt_opr;
702 typentry->flags |= TCFLAGS_CHECKED_LT_OPR;
703 }
704 if ((flags & TYPECACHE_GT_OPR) &&
705 !(typentry->flags & TCFLAGS_CHECKED_GT_OPR))
706 {
707 Oid gt_opr = InvalidOid;
708
709 if (typentry->btree_opf != InvalidOid)
710 gt_opr = get_opfamily_member(typentry->btree_opf,
711 typentry->btree_opintype,
712 typentry->btree_opintype,
713 BTGreaterStrategyNumber);
714
715 /*
716 * As above, make sure array_cmp or record_cmp will succeed; but again
717 * we need no special check for ranges or multiranges.
718 */
719 if (gt_opr == ARRAY_GT_OP &&
720 !array_element_has_compare(typentry))
721 gt_opr = InvalidOid;
722 else if (gt_opr == RECORD_GT_OP &&
723 !record_fields_have_compare(typentry))
724 gt_opr = InvalidOid;
725
726 typentry->gt_opr = gt_opr;
727 typentry->flags |= TCFLAGS_CHECKED_GT_OPR;
728 }
729 if ((flags & (TYPECACHE_CMP_PROC | TYPECACHE_CMP_PROC_FINFO)) &&
730 !(typentry->flags & TCFLAGS_CHECKED_CMP_PROC))
731 {
732 Oid cmp_proc = InvalidOid;
733
734 if (typentry->btree_opf != InvalidOid)
735 cmp_proc = get_opfamily_proc(typentry->btree_opf,
736 typentry->btree_opintype,
737 typentry->btree_opintype,
738 BTORDER_PROC);
739
740 /*
741 * As above, make sure array_cmp or record_cmp will succeed; but again
742 * we need no special check for ranges or multiranges.
743 */
744 if (cmp_proc == F_BTARRAYCMP &&
745 !array_element_has_compare(typentry))
746 cmp_proc = InvalidOid;
747 else if (cmp_proc == F_BTRECORDCMP &&
748 !record_fields_have_compare(typentry))
749 cmp_proc = InvalidOid;
750
751 /* Force update of cmp_proc_finfo only if we're changing state */
752 if (typentry->cmp_proc != cmp_proc)
753 typentry->cmp_proc_finfo.fn_oid = InvalidOid;
754
755 typentry->cmp_proc = cmp_proc;
756 typentry->flags |= TCFLAGS_CHECKED_CMP_PROC;
757 }
758 if ((flags & (TYPECACHE_HASH_PROC | TYPECACHE_HASH_PROC_FINFO)) &&
759 !(typentry->flags & TCFLAGS_CHECKED_HASH_PROC))
760 {
761 Oid hash_proc = InvalidOid;
762
763 /*
764 * We insist that the eq_opr, if one has been determined, match the
765 * hash opclass; else report there is no hash function.
766 */
767 if (typentry->hash_opf != InvalidOid &&
768 (!OidIsValid(typentry->eq_opr) ||
769 typentry->eq_opr == get_opfamily_member(typentry->hash_opf,
770 typentry->hash_opintype,
771 typentry->hash_opintype,
772 HTEqualStrategyNumber)))
773 hash_proc = get_opfamily_proc(typentry->hash_opf,
774 typentry->hash_opintype,
775 typentry->hash_opintype,
776 HASHSTANDARD_PROC);
777
778 /*
779 * As above, make sure hash_array, hash_record, hash_range, or
780 * hash_multirange will succeed. Here we do need to check the range
781 * cases.
782 */
783 if (hash_proc == F_HASH_ARRAY &&
784 !array_element_has_hashing(typentry))
785 hash_proc = InvalidOid;
786 else if (hash_proc == F_HASH_RECORD &&
787 !record_fields_have_hashing(typentry))
788 hash_proc = InvalidOid;
789 else if (hash_proc == F_HASH_RANGE &&
790 !range_element_has_hashing(typentry))
791 hash_proc = InvalidOid;
792 else if (hash_proc == F_HASH_MULTIRANGE &&
793 !multirange_element_has_hashing(typentry))
794 hash_proc = InvalidOid;
795
796 /* Force update of hash_proc_finfo only if we're changing state */
797 if (typentry->hash_proc != hash_proc)
798 typentry->hash_proc_finfo.fn_oid = InvalidOid;
799
800 typentry->hash_proc = hash_proc;
801 typentry->flags |= TCFLAGS_CHECKED_HASH_PROC;
802 }
803 if ((flags & (TYPECACHE_HASH_EXTENDED_PROC |
804 TYPECACHE_HASH_EXTENDED_PROC_FINFO)) &&
805 !(typentry->flags & TCFLAGS_CHECKED_HASH_EXTENDED_PROC))
806 {
807 Oid hash_extended_proc = InvalidOid;
808
809 /*
810 * We insist that the eq_opr, if one has been determined, match the
811 * hash opclass; else report there is no hash function.
812 */
813 if (typentry->hash_opf != InvalidOid &&
814 (!OidIsValid(typentry->eq_opr) ||
815 typentry->eq_opr == get_opfamily_member(typentry->hash_opf,
816 typentry->hash_opintype,
817 typentry->hash_opintype,
818 HTEqualStrategyNumber)))
819 hash_extended_proc = get_opfamily_proc(typentry->hash_opf,
820 typentry->hash_opintype,
821 typentry->hash_opintype,
822 HASHEXTENDED_PROC);
823
824 /*
825 * As above, make sure hash_array_extended, hash_record_extended,
826 * hash_range_extended, or hash_multirange_extended will succeed.
827 */
828 if (hash_extended_proc == F_HASH_ARRAY_EXTENDED &&
829 !array_element_has_extended_hashing(typentry))
830 hash_extended_proc = InvalidOid;
831 else if (hash_extended_proc == F_HASH_RECORD_EXTENDED &&
832 !record_fields_have_extended_hashing(typentry))
833 hash_extended_proc = InvalidOid;
834 else if (hash_extended_proc == F_HASH_RANGE_EXTENDED &&
835 !range_element_has_extended_hashing(typentry))
836 hash_extended_proc = InvalidOid;
837 else if (hash_extended_proc == F_HASH_MULTIRANGE_EXTENDED &&
838 !multirange_element_has_extended_hashing(typentry))
839 hash_extended_proc = InvalidOid;
840
841 /* Force update of proc finfo only if we're changing state */
842 if (typentry->hash_extended_proc != hash_extended_proc)
843 typentry->hash_extended_proc_finfo.fn_oid = InvalidOid;
844
845 typentry->hash_extended_proc = hash_extended_proc;
846 typentry->flags |= TCFLAGS_CHECKED_HASH_EXTENDED_PROC;
847 }
848
849 /*
850 * Set up fmgr lookup info as requested
851 *
852 * Note: we tell fmgr the finfo structures live in CacheMemoryContext,
853 * which is not quite right (they're really in the hash table's private
854 * memory context) but this will do for our purposes.
855 *
856 * Note: the code above avoids invalidating the finfo structs unless the
857 * referenced operator/function OID actually changes. This is to prevent
858 * unnecessary leakage of any subsidiary data attached to an finfo, since
859 * that would cause session-lifespan memory leaks.
860 */
861 if ((flags & TYPECACHE_EQ_OPR_FINFO) &&
862 typentry->eq_opr_finfo.fn_oid == InvalidOid &&
863 typentry->eq_opr != InvalidOid)
864 {
865 Oid eq_opr_func;
866
867 eq_opr_func = get_opcode(typentry->eq_opr);
868 if (eq_opr_func != InvalidOid)
869 fmgr_info_cxt(eq_opr_func, &typentry->eq_opr_finfo,
870 CacheMemoryContext);
871 }
872 if ((flags & TYPECACHE_CMP_PROC_FINFO) &&
873 typentry->cmp_proc_finfo.fn_oid == InvalidOid &&
874 typentry->cmp_proc != InvalidOid)
875 {
876 fmgr_info_cxt(typentry->cmp_proc, &typentry->cmp_proc_finfo,
877 CacheMemoryContext);
878 }
879 if ((flags & TYPECACHE_HASH_PROC_FINFO) &&
880 typentry->hash_proc_finfo.fn_oid == InvalidOid &&
881 typentry->hash_proc != InvalidOid)
882 {
883 fmgr_info_cxt(typentry->hash_proc, &typentry->hash_proc_finfo,
884 CacheMemoryContext);
885 }
886 if ((flags & TYPECACHE_HASH_EXTENDED_PROC_FINFO) &&
887 typentry->hash_extended_proc_finfo.fn_oid == InvalidOid &&
888 typentry->hash_extended_proc != InvalidOid)
889 {
890 fmgr_info_cxt(typentry->hash_extended_proc,
891 &typentry->hash_extended_proc_finfo,
892 CacheMemoryContext);
893 }
894
895 /*
896 * If it's a composite type (row type), get tupdesc if requested
897 */
898 if ((flags & TYPECACHE_TUPDESC) &&
899 typentry->tupDesc == NULL &&
900 typentry->typtype == TYPTYPE_COMPOSITE)
901 {
902 load_typcache_tupdesc(typentry);
903 }
904
905 /*
906 * If requested, get information about a range type
907 *
908 * This includes making sure that the basic info about the range element
909 * type is up-to-date.
910 */
911 if ((flags & TYPECACHE_RANGE_INFO) &&
912 typentry->typtype == TYPTYPE_RANGE)
913 {
914 if (typentry->rngelemtype == NULL)
915 load_rangetype_info(typentry);
916 else if (!(typentry->rngelemtype->flags & TCFLAGS_HAVE_PG_TYPE_DATA))
917 (void) lookup_type_cache(typentry->rngelemtype->type_id, 0);
918 }
919
920 /*
921 * If requested, get information about a multirange type
922 */
923 if ((flags & TYPECACHE_MULTIRANGE_INFO) &&
924 typentry->rngtype == NULL &&
925 typentry->typtype == TYPTYPE_MULTIRANGE)
926 {
927 load_multirangetype_info(typentry);
928 }
929
930 /*
931 * If requested, get information about a domain type
932 */
933 if ((flags & TYPECACHE_DOMAIN_BASE_INFO) &&
934 typentry->domainBaseType == InvalidOid &&
935 typentry->typtype == TYPTYPE_DOMAIN)
936 {
937 typentry->domainBaseTypmod = -1;
938 typentry->domainBaseType =
939 getBaseTypeAndTypmod(type_id, &typentry->domainBaseTypmod);
940 }
941 if ((flags & TYPECACHE_DOMAIN_CONSTR_INFO) &&
942 (typentry->flags & TCFLAGS_CHECKED_DOMAIN_CONSTRAINTS) == 0 &&
943 typentry->typtype == TYPTYPE_DOMAIN)
944 {
945 load_domaintype_info(typentry);
946 }
947
948 INJECTION_POINT("typecache-before-rel-type-cache-insert", NULL);
949
950 Assert(in_progress_offset + 1 == in_progress_list_len);
951 in_progress_list_len--;
952
953 insert_rel_type_cache_if_needed(typentry);
954
955 return typentry;
956 }
957
958 /*
959 * load_typcache_tupdesc --- helper routine to set up composite type's tupDesc
960 */
961 static void
962 load_typcache_tupdesc(TypeCacheEntry *typentry)
963 {
964 Relation rel;
965
966 if (!OidIsValid(typentry->typrelid)) /* should not happen */
967 elog(ERROR, "invalid typrelid for composite type %u",
968 typentry->type_id);
969 rel = relation_open(typentry->typrelid, AccessShareLock);
970 Assert(rel->rd_rel->reltype == typentry->type_id);
971
972 /*
973 * Link to the tupdesc and increment its refcount (we assert it's a
974 * refcounted descriptor). We don't use IncrTupleDescRefCount() for this,
975 * because the reference mustn't be entered in the current resource owner;
976 * it can outlive the current query.
977 */
978 typentry->tupDesc = RelationGetDescr(rel);
979
980 Assert(typentry->tupDesc->tdrefcount > 0);
981 typentry->tupDesc->tdrefcount++;
982
983 /*
984 * In future, we could take some pains to not change tupDesc_identifier if
985 * the tupdesc didn't really change; but for now it's not worth it.
986 */
987 typentry->tupDesc_identifier = ++tupledesc_id_counter;
988
989 relation_close(rel, AccessShareLock);
990 }
991
992 /*
993 * load_rangetype_info --- helper routine to set up range type information
994 */
995 static void
996 load_rangetype_info(TypeCacheEntry *typentry)
997 {
998 Form_pg_range pg_range;
999 HeapTuple tup;
1000 Oid subtypeOid;
1001 Oid opclassOid;
1002 Oid canonicalOid;
1003 Oid subdiffOid;
1004 Oid opfamilyOid;
1005 Oid opcintype;
1006 Oid cmpFnOid;
1007
1008 /* get information from pg_range */
1009 tup = SearchSysCache1(RANGETYPE, ObjectIdGetDatum(typentry->type_id));
1010 /* should not fail, since we already checked typtype ... */
1011 if (!HeapTupleIsValid(tup))
1012 elog(ERROR, "cache lookup failed for range type %u",
1013 typentry->type_id);
1014 pg_range = (Form_pg_range) GETSTRUCT(tup);
1015
1016 subtypeOid = pg_range->rngsubtype;
1017 typentry->rng_collation = pg_range->rngcollation;
1018 opclassOid = pg_range->rngsubopc;
1019 canonicalOid = pg_range->rngcanonical;
1020 subdiffOid = pg_range->rngsubdiff;
1021
1022 ReleaseSysCache(tup);
1023
1024 /* get opclass properties and look up the comparison function */
1025 opfamilyOid = get_opclass_family(opclassOid);
1026 opcintype = get_opclass_input_type(opclassOid);
1027 typentry->rng_opfamily = opfamilyOid;
1028
1029 cmpFnOid = get_opfamily_proc(opfamilyOid, opcintype, opcintype,
1030 BTORDER_PROC);
1031 if (!RegProcedureIsValid(cmpFnOid))
1032 elog(ERROR, "missing support function %d(%u,%u) in opfamily %u",
1033 BTORDER_PROC, opcintype, opcintype, opfamilyOid);
1034
1035 /* set up cached fmgrinfo structs */
1036 fmgr_info_cxt(cmpFnOid, &typentry->rng_cmp_proc_finfo,
1037 CacheMemoryContext);
1038 if (OidIsValid(canonicalOid))
1039 fmgr_info_cxt(canonicalOid, &typentry->rng_canonical_finfo,
1040 CacheMemoryContext);
1041 if (OidIsValid(subdiffOid))
1042 fmgr_info_cxt(subdiffOid, &typentry->rng_subdiff_finfo,
1043 CacheMemoryContext);
1044
1045 /* Lastly, set up link to the element type --- this marks data valid */
1046 typentry->rngelemtype = lookup_type_cache(subtypeOid, 0);
1047 }
1048
1049 /*
1050 * load_multirangetype_info --- helper routine to set up multirange type
1051 * information
1052 */
1053 static void
1054 load_multirangetype_info(TypeCacheEntry *typentry)
1055 {
1056 Oid rangetypeOid;
1057
1058 rangetypeOid = get_multirange_range(typentry->type_id);
1059 if (!OidIsValid(rangetypeOid))
1060 elog(ERROR, "cache lookup failed for multirange type %u",
1061 typentry->type_id);
1062
1063 typentry->rngtype = lookup_type_cache(rangetypeOid, TYPECACHE_RANGE_INFO);
1064 }
1065
1066 /*
1067 * load_domaintype_info --- helper routine to set up domain constraint info
1068 *
1069 * Note: we assume we're called in a relatively short-lived context, so it's
1070 * okay to leak data into the current context while scanning pg_constraint.
1071 * We build the new DomainConstraintCache data in a context underneath
1072 * CurrentMemoryContext, and reparent it under CacheMemoryContext when
1073 * complete.
1074 */
1075 static void
1076 load_domaintype_info(TypeCacheEntry *typentry)
1077 {
1078 Oid typeOid = typentry->type_id;
1079 DomainConstraintCache *dcc;
1080 bool notNull = false;
1081 DomainConstraintState **ccons;
1082 int cconslen;
1083 Relation conRel;
1084 MemoryContext oldcxt;
1085
1086 /*
1087 * If we're here, any existing constraint info is stale, so release it.
1088 * For safety, be sure to null the link before trying to delete the data.
1089 */
1090 if (typentry->domainData)
1091 {
1092 dcc = typentry->domainData;
1093 typentry->domainData = NULL;
1094 decr_dcc_refcount(dcc);
1095 }
1096
1097 /*
1098 * We try to optimize the common case of no domain constraints, so don't
1099 * create the dcc object and context until we find a constraint. Likewise
1100 * for the temp sorting array.
1101 */
1102 dcc = NULL;
1103 ccons = NULL;
1104 cconslen = 0;
1105
1106 /*
1107 * Scan pg_constraint for relevant constraints. We want to find
1108 * constraints for not just this domain, but any ancestor domains, so the
1109 * outer loop crawls up the domain stack.
1110 */
1111 conRel = table_open(ConstraintRelationId, AccessShareLock);
1112
1113 for (;;)
1114 {
1115 HeapTuple tup;
1116 HeapTuple conTup;
1117 Form_pg_type typTup;
1118 int nccons = 0;
1119 ScanKeyData key[1];
1120 SysScanDesc scan;
1121
1122 tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typeOid));
1123 if (!HeapTupleIsValid(tup))
1124 elog(ERROR, "cache lookup failed for type %u", typeOid);
1125 typTup = (Form_pg_type) GETSTRUCT(tup);
1126
1127 if (typTup->typtype != TYPTYPE_DOMAIN)
1128 {
1129 /* Not a domain, so done */
1130 ReleaseSysCache(tup);
1131 break;
1132 }
1133
1134 /* Test for NOT NULL Constraint */
1135 if (typTup->typnotnull)
1136 notNull = true;
1137
1138 /* Look for CHECK Constraints on this domain */
1139 ScanKeyInit(&key[0],
1140 Anum_pg_constraint_contypid,
1141 BTEqualStrategyNumber, F_OIDEQ,
1142 ObjectIdGetDatum(typeOid));
1143
1144 scan = systable_beginscan(conRel, ConstraintTypidIndexId, true,
1145 NULL, 1, key);
1146
1147 while (HeapTupleIsValid(conTup = systable_getnext(scan)))
1148 {
1149 Form_pg_constraint c = (Form_pg_constraint) GETSTRUCT(conTup);
1150 Datum val;
1151 bool isNull;
1152 char *constring;
1153 Expr *check_expr;
1154 DomainConstraintState *r;
1155
1156 /* Ignore non-CHECK constraints */
1157 if (c->contype != CONSTRAINT_CHECK)
1158 continue;
1159
1160 /* Not expecting conbin to be NULL, but we'll test for it anyway */
1161 val = fastgetattr(conTup, Anum_pg_constraint_conbin,
1162 conRel->rd_att, &isNull);
1163 if (isNull)
1164 elog(ERROR, "domain \"%s\" constraint \"%s\" has NULL conbin",
1165 NameStr(typTup->typname), NameStr(c->conname));
1166
1167 /* Convert conbin to C string in caller context */
1168 constring = TextDatumGetCString(val);
1169
1170 /* Create the DomainConstraintCache object and context if needed */
1171 if (dcc == NULL)
1172 {
1173 MemoryContext cxt;
1174
1175 cxt = AllocSetContextCreate(CurrentMemoryContext,
1176 "Domain constraints",
1177 ALLOCSET_SMALL_SIZES);
1178 dcc = (DomainConstraintCache *)
1179 MemoryContextAlloc(cxt, sizeof(DomainConstraintCache));
1180 dcc->constraints = NIL;
1181 dcc->dccContext = cxt;
1182 dcc->dccRefCount = 0;
1183 }
1184
1185 /* Create node trees in DomainConstraintCache's context */
1186 oldcxt = MemoryContextSwitchTo(dcc->dccContext);
1187
1188 check_expr = (Expr *) stringToNode(constring);
1189
1190 /*
1191 * Plan the expression, since ExecInitExpr will expect that.
1192 *
1193 * Note: caching the result of expression_planner() is not very
1194 * good practice. Ideally we'd use a CachedExpression here so
1195 * that we would react promptly to, eg, changes in inlined
1196 * functions. However, because we don't support mutable domain
1197 * CHECK constraints, it's not really clear that it's worth the
1198 * extra overhead to do that.
1199 */
1200 check_expr = expression_planner(check_expr);
1201
1202 r = makeNode(DomainConstraintState);
1203 r->constrainttype = DOM_CONSTRAINT_CHECK;
1204 r->name = pstrdup(NameStr(c->conname));
1205 r->check_expr = check_expr;
1206 r->check_exprstate = NULL;
1207
1208 MemoryContextSwitchTo(oldcxt);
1209
1210 /* Accumulate constraints in an array, for sorting below */
1211 if (ccons == NULL)
1212 {
1213 cconslen = 8;
1214 ccons = (DomainConstraintState **)
1215 palloc(cconslen * sizeof(DomainConstraintState *));
1216 }
1217 else if (nccons >= cconslen)
1218 {
1219 cconslen *= 2;
1220 ccons = (DomainConstraintState **)
1221 repalloc(ccons, cconslen * sizeof(DomainConstraintState *));
1222 }
1223 ccons[nccons++] = r;
1224 }
1225
1226 systable_endscan(scan);
1227
1228 if (nccons > 0)
1229 {
1230 /*
1231 * Sort the items for this domain, so that CHECKs are applied in a
1232 * deterministic order.
1233 */
1234 if (nccons > 1)
1235 qsort(ccons, nccons, sizeof(DomainConstraintState *), dcs_cmp);
1236
1237 /*
1238 * Now attach them to the overall list. Use lcons() here because
1239 * constraints of parent domains should be applied earlier.
1240 */
1241 oldcxt = MemoryContextSwitchTo(dcc->dccContext);
1242 while (nccons > 0)
1243 dcc->constraints = lcons(ccons[--nccons], dcc->constraints);
1244 MemoryContextSwitchTo(oldcxt);
1245 }
1246
1247 /* loop to next domain in stack */
1248 typeOid = typTup->typbasetype;
1249 ReleaseSysCache(tup);
1250 }
1251
1252 table_close(conRel, AccessShareLock);
1253
1254 /*
1255 * Only need to add one NOT NULL check regardless of how many domains in
1256 * the stack request it.
1257 */
1258 if (notNull)
1259 {
1260 DomainConstraintState *r;
1261
1262 /* Create the DomainConstraintCache object and context if needed */
1263 if (dcc == NULL)
1264 {
1265 MemoryContext cxt;
1266
1267 cxt = AllocSetContextCreate(CurrentMemoryContext,
1268 "Domain constraints",
1269 ALLOCSET_SMALL_SIZES);
1270 dcc = (DomainConstraintCache *)
1271 MemoryContextAlloc(cxt, sizeof(DomainConstraintCache));
1272 dcc->constraints = NIL;
1273 dcc->dccContext = cxt;
1274 dcc->dccRefCount = 0;
1275 }
1276
1277 /* Create node trees in DomainConstraintCache's context */
1278 oldcxt = MemoryContextSwitchTo(dcc->dccContext);
1279
1280 r = makeNode(DomainConstraintState);
1281
1282 r->constrainttype = DOM_CONSTRAINT_NOTNULL;
1283 r->name = pstrdup("NOT NULL");
1284 r->check_expr = NULL;
1285 r->check_exprstate = NULL;
1286
1287 /* lcons to apply the nullness check FIRST */
1288 dcc->constraints = lcons(r, dcc->constraints);
1289
1290 MemoryContextSwitchTo(oldcxt);
1291 }
1292
1293 /*
1294 * If we made a constraint object, move it into CacheMemoryContext and
1295 * attach it to the typcache entry.
1296 */
1297 if (dcc)
1298 {
1299 MemoryContextSetParent(dcc->dccContext, CacheMemoryContext);
1300 typentry->domainData = dcc;
1301 dcc->dccRefCount++; /* count the typcache's reference */
1302 }
1303
1304 /* Either way, the typcache entry's domain data is now valid. */
1305 typentry->flags |= TCFLAGS_CHECKED_DOMAIN_CONSTRAINTS;
1306 }
1307
1308 /*
1309 * qsort comparator to sort DomainConstraintState pointers by name
1310 */
1311 static int
1312 dcs_cmp(const void *a, const void *b)
1313 {
1314 const DomainConstraintState *const *ca = (const DomainConstraintState *const *) a;
1315 const DomainConstraintState *const *cb = (const DomainConstraintState *const *) b;
1316
1317 return strcmp((*ca)->name, (*cb)->name);
1318 }
1319
1320 /*
1321 * decr_dcc_refcount --- decrement a DomainConstraintCache's refcount,
1322 * and free it if no references remain
1323 */
1324 static void
1325 decr_dcc_refcount(DomainConstraintCache *dcc)
1326 {
1327 Assert(dcc->dccRefCount > 0);
1328 if (--(dcc->dccRefCount) <= 0)
1329 MemoryContextDelete(dcc->dccContext);
1330 }
1331
1332 /*
1333 * Context reset/delete callback for a DomainConstraintRef
1334 */
1335 static void
1336 dccref_deletion_callback(void *arg)
1337 {
1338 DomainConstraintRef *ref = (DomainConstraintRef *) arg;
1339 DomainConstraintCache *dcc = ref->dcc;
1340
1341 /* Paranoia --- be sure link is nulled before trying to release */
1342 if (dcc)
1343 {
1344 ref->constraints = NIL;
1345 ref->dcc = NULL;
1346 decr_dcc_refcount(dcc);
1347 }
1348 }
1349
1350 /*
1351 * prep_domain_constraints --- prepare domain constraints for execution
1352 *
1353 * The expression trees stored in the DomainConstraintCache's list are
1354 * converted to executable expression state trees stored in execctx.
1355 */
1356 static List *
1357 prep_domain_constraints(List *constraints, MemoryContext execctx)
1358 {
1359 List *result = NIL;
1360 MemoryContext oldcxt;
1361 ListCell *lc;
1362
1363 oldcxt = MemoryContextSwitchTo(execctx);
1364
1365 foreach(lc, constraints)
1366 {
1367 DomainConstraintState *r = (DomainConstraintState *) lfirst(lc);
1368 DomainConstraintState *newr;
1369
1370 newr = makeNode(DomainConstraintState);
1371 newr->constrainttype = r->constrainttype;
1372 newr->name = r->name;
1373 newr->check_expr = r->check_expr;
1374 newr->check_exprstate = ExecInitExpr(r->check_expr, NULL);
1375
1376 result = lappend(result, newr);
1377 }
1378
1379 MemoryContextSwitchTo(oldcxt);
1380
1381 return result;
1382 }
1383
1384 /*
1385 * InitDomainConstraintRef --- initialize a DomainConstraintRef struct
1386 *
1387 * Caller must tell us the MemoryContext in which the DomainConstraintRef
1388 * lives. The ref will be cleaned up when that context is reset/deleted.
1389 *
1390 * Caller must also tell us whether it wants check_exprstate fields to be
1391 * computed in the DomainConstraintState nodes attached to this ref.
1392 * If it doesn't, we need not make a copy of the DomainConstraintState list.
1393 */
1394 void
1395 InitDomainConstraintRef(Oid type_id, DomainConstraintRef *ref,
1396 MemoryContext refctx, bool need_exprstate)
1397 {
1398 /* Look up the typcache entry --- we assume it survives indefinitely */
1399 ref->tcache = lookup_type_cache(type_id, TYPECACHE_DOMAIN_CONSTR_INFO);
1400 ref->need_exprstate = need_exprstate;
1401 /* For safety, establish the callback before acquiring a refcount */
1402 ref->refctx = refctx;
1403 ref->dcc = NULL;
1404 ref->callback.func = dccref_deletion_callback;
1405 ref->callback.arg = ref;
1406 MemoryContextRegisterResetCallback(refctx, &ref->callback);
1407 /* Acquire refcount if there are constraints, and set up exported list */
1408 if (ref->tcache->domainData)
1409 {
1410 ref->dcc = ref->tcache->domainData;
1411 ref->dcc->dccRefCount++;
1412 if (ref->need_exprstate)
1413 ref->constraints = prep_domain_constraints(ref->dcc->constraints,
1414 ref->refctx);
1415 else
1416 ref->constraints = ref->dcc->constraints;
1417 }
1418 else
1419 ref->constraints = NIL;
1420 }
1421
1422 /*
1423 * UpdateDomainConstraintRef --- recheck validity of domain constraint info
1424 *
1425 * If the domain's constraint set changed, ref->constraints is updated to
1426 * point at a new list of cached constraints.
1427 *
1428 * In the normal case where nothing happened to the domain, this is cheap
1429 * enough that it's reasonable (and expected) to check before *each* use
1430 * of the constraint info.
1431 */
1432 void
1433 UpdateDomainConstraintRef(DomainConstraintRef *ref)
1434 {
1435 TypeCacheEntry *typentry = ref->tcache;
1436
1437 /* Make sure typcache entry's data is up to date */
1438 if ((typentry->flags & TCFLAGS_CHECKED_DOMAIN_CONSTRAINTS) == 0 &&
1439 typentry->typtype == TYPTYPE_DOMAIN)
1440 load_domaintype_info(typentry);
1441
1442 /* Transfer to ref object if there's new info, adjusting refcounts */
1443 if (ref->dcc != typentry->domainData)
1444 {
1445 /* Paranoia --- be sure link is nulled before trying to release */
1446 DomainConstraintCache *dcc = ref->dcc;
1447
1448 if (dcc)
1449 {
1450 /*
1451 * Note: we just leak the previous list of executable domain
1452 * constraints. Alternatively, we could keep those in a child
1453 * context of ref->refctx and free that context at this point.
1454 * However, in practice this code path will be taken so seldom
1455 * that the extra bookkeeping for a child context doesn't seem
1456 * worthwhile; we'll just allow a leak for the lifespan of refctx.
1457 */
1458 ref->constraints = NIL;
1459 ref->dcc = NULL;
1460 decr_dcc_refcount(dcc);
1461 }
1462 dcc = typentry->domainData;
1463 if (dcc)
1464 {
1465 ref->dcc = dcc;
1466 dcc->dccRefCount++;
1467 if (ref->need_exprstate)
1468 ref->constraints = prep_domain_constraints(dcc->constraints,
1469 ref->refctx);
1470 else
1471 ref->constraints = dcc->constraints;
1472 }
1473 }
1474 }
1475
1476 /*
1477 * DomainHasConstraints --- utility routine to check if a domain has constraints
1478 *
1479 * This is defined to return false, not fail, if type is not a domain.
1480 */
1481 bool
1482 DomainHasConstraints(Oid type_id)
1483 {
1484 TypeCacheEntry *typentry;
1485
1486 /*
1487 * Note: a side effect is to cause the typcache's domain data to become
1488 * valid. This is fine since we'll likely need it soon if there is any.
1489 */
1490 typentry = lookup_type_cache(type_id, TYPECACHE_DOMAIN_CONSTR_INFO);
1491
1492 return (typentry->domainData != NULL);
1493 }
1494
1495
1496 /*
1497 * array_element_has_equality and friends are helper routines to check
1498 * whether we should believe that array_eq and related functions will work
1499 * on the given array type or composite type.
1500 *
1501 * The logic above may call these repeatedly on the same type entry, so we
1502 * make use of the typentry->flags field to cache the results once known.
1503 * Also, we assume that we'll probably want all these facts about the type
1504 * if we want any, so we cache them all using only one lookup of the
1505 * component datatype(s).
1506 */
1507
1508 static bool
1509 array_element_has_equality(TypeCacheEntry *typentry)
1510 {
1511 if (!(typentry->flags & TCFLAGS_CHECKED_ELEM_PROPERTIES))
1512 cache_array_element_properties(typentry);
1513 return (typentry->flags & TCFLAGS_HAVE_ELEM_EQUALITY) != 0;
1514 }
1515
1516 static bool
1517 array_element_has_compare(TypeCacheEntry *typentry)
1518 {
1519 if (!(typentry->flags & TCFLAGS_CHECKED_ELEM_PROPERTIES))
1520 cache_array_element_properties(typentry);
1521 return (typentry->flags & TCFLAGS_HAVE_ELEM_COMPARE) != 0;
1522 }
1523
1524 static bool
1525 array_element_has_hashing(TypeCacheEntry *typentry)
1526 {
1527 if (!(typentry->flags & TCFLAGS_CHECKED_ELEM_PROPERTIES))
1528 cache_array_element_properties(typentry);
1529 return (typentry->flags & TCFLAGS_HAVE_ELEM_HASHING) != 0;
1530 }
1531
1532 static bool
1533 array_element_has_extended_hashing(TypeCacheEntry *typentry)
1534 {
1535 if (!(typentry->flags & TCFLAGS_CHECKED_ELEM_PROPERTIES))
1536 cache_array_element_properties(typentry);
1537 return (typentry->flags & TCFLAGS_HAVE_ELEM_EXTENDED_HASHING) != 0;
1538 }
1539
1540 static void
1541 cache_array_element_properties(TypeCacheEntry *typentry)
1542 {
1543 Oid elem_type = get_base_element_type(typentry->type_id);
1544
1545 if (OidIsValid(elem_type))
1546 {
1547 TypeCacheEntry *elementry;
1548
1549 elementry = lookup_type_cache(elem_type,
1550 TYPECACHE_EQ_OPR |
1551 TYPECACHE_CMP_PROC |
1552 TYPECACHE_HASH_PROC |
1553 TYPECACHE_HASH_EXTENDED_PROC);
1554 if (OidIsValid(elementry->eq_opr))
1555 typentry->flags |= TCFLAGS_HAVE_ELEM_EQUALITY;
1556 if (OidIsValid(elementry->cmp_proc))
1557 typentry->flags |= TCFLAGS_HAVE_ELEM_COMPARE;
1558 if (OidIsValid(elementry->hash_proc))
1559 typentry->flags |= TCFLAGS_HAVE_ELEM_HASHING;
1560 if (OidIsValid(elementry->hash_extended_proc))
1561 typentry->flags |= TCFLAGS_HAVE_ELEM_EXTENDED_HASHING;
1562 }
1563 typentry->flags |= TCFLAGS_CHECKED_ELEM_PROPERTIES;
1564 }
1565
1566 /*
1567 * Likewise, some helper functions for composite types.
1568 */
1569
1570 static bool
1571 record_fields_have_equality(TypeCacheEntry *typentry)
1572 {
1573 if (!(typentry->flags & TCFLAGS_CHECKED_FIELD_PROPERTIES))
1574 cache_record_field_properties(typentry);
1575 return (typentry->flags & TCFLAGS_HAVE_FIELD_EQUALITY) != 0;
1576 }
1577
1578 static bool
1579 record_fields_have_compare(TypeCacheEntry *typentry)
1580 {
1581 if (!(typentry->flags & TCFLAGS_CHECKED_FIELD_PROPERTIES))
1582 cache_record_field_properties(typentry);
1583 return (typentry->flags & TCFLAGS_HAVE_FIELD_COMPARE) != 0;
1584 }
1585
1586 static bool
1587 record_fields_have_hashing(TypeCacheEntry *typentry)
1588 {
1589 if (!(typentry->flags & TCFLAGS_CHECKED_FIELD_PROPERTIES))
1590 cache_record_field_properties(typentry);
1591 return (typentry->flags & TCFLAGS_HAVE_FIELD_HASHING) != 0;
1592 }
1593
1594 static bool
1595 record_fields_have_extended_hashing(TypeCacheEntry *typentry)
1596 {
1597 if (!(typentry->flags & TCFLAGS_CHECKED_FIELD_PROPERTIES))
1598 cache_record_field_properties(typentry);
1599 return (typentry->flags & TCFLAGS_HAVE_FIELD_EXTENDED_HASHING) != 0;
1600 }
1601
1602 static void
1603 cache_record_field_properties(TypeCacheEntry *typentry)
1604 {
1605 /*
1606 * For type RECORD, we can't really tell what will work, since we don't
1607 * have access here to the specific anonymous type. Just assume that
1608 * equality and comparison will (we may get a failure at runtime). We
1609 * could also claim that hashing works, but then if code that has the
1610 * option between a comparison-based (sort-based) and a hash-based plan
1611 * chooses hashing, stuff could fail that would otherwise work if it chose
1612 * a comparison-based plan. In practice more types support comparison
1613 * than hashing.
1614 */
1615 if (typentry->type_id == RECORDOID)
1616 {
1617 typentry->flags |= (TCFLAGS_HAVE_FIELD_EQUALITY |
1618 TCFLAGS_HAVE_FIELD_COMPARE);
1619 }
1620 else if (typentry->typtype == TYPTYPE_COMPOSITE)
1621 {
1622 TupleDesc tupdesc;
1623 int newflags;
1624 int i;
1625
1626 /* Fetch composite type's tupdesc if we don't have it already */
1627 if (typentry->tupDesc == NULL)
1628 load_typcache_tupdesc(typentry);
1629 tupdesc = typentry->tupDesc;
1630
1631 /* Must bump the refcount while we do additional catalog lookups */
1632 IncrTupleDescRefCount(tupdesc);
1633
1634 /* Have each property if all non-dropped fields have the property */
1635 newflags = (TCFLAGS_HAVE_FIELD_EQUALITY |
1636 TCFLAGS_HAVE_FIELD_COMPARE |
1637 TCFLAGS_HAVE_FIELD_HASHING |
1638 TCFLAGS_HAVE_FIELD_EXTENDED_HASHING);
1639 for (i = 0; i < tupdesc->natts; i++)
1640 {
1641 TypeCacheEntry *fieldentry;
1642 Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
1643
1644 if (attr->attisdropped)
1645 continue;
1646
1647 fieldentry = lookup_type_cache(attr->atttypid,
1648 TYPECACHE_EQ_OPR |
1649 TYPECACHE_CMP_PROC |
1650 TYPECACHE_HASH_PROC |
1651 TYPECACHE_HASH_EXTENDED_PROC);
1652 if (!OidIsValid(fieldentry->eq_opr))
1653 newflags &= ~TCFLAGS_HAVE_FIELD_EQUALITY;
1654 if (!OidIsValid(fieldentry->cmp_proc))
1655 newflags &= ~TCFLAGS_HAVE_FIELD_COMPARE;
1656 if (!OidIsValid(fieldentry->hash_proc))
1657 newflags &= ~TCFLAGS_HAVE_FIELD_HASHING;
1658 if (!OidIsValid(fieldentry->hash_extended_proc))
1659 newflags &= ~TCFLAGS_HAVE_FIELD_EXTENDED_HASHING;
1660
1661 /* We can drop out of the loop once we disprove all bits */
1662 if (newflags == 0)
1663 break;
1664 }
1665 typentry->flags |= newflags;
1666
1667 DecrTupleDescRefCount(tupdesc);
1668 }
1669 else if (typentry->typtype == TYPTYPE_DOMAIN)
1670 {
1671 /* If it's domain over composite, copy base type's properties */
1672 TypeCacheEntry *baseentry;
1673
1674 /* load up basetype info if we didn't already */
1675 if (typentry->domainBaseType == InvalidOid)
1676 {
1677 typentry->domainBaseTypmod = -1;
1678 typentry->domainBaseType =
1679 getBaseTypeAndTypmod(typentry->type_id,
1680 &typentry->domainBaseTypmod);
1681 }
1682 baseentry = lookup_type_cache(typentry->domainBaseType,
1683 TYPECACHE_EQ_OPR |
1684 TYPECACHE_CMP_PROC |
1685 TYPECACHE_HASH_PROC |
1686 TYPECACHE_HASH_EXTENDED_PROC);
1687 if (baseentry->typtype == TYPTYPE_COMPOSITE)
1688 {
1689 typentry->flags |= TCFLAGS_DOMAIN_BASE_IS_COMPOSITE;
1690 typentry->flags |= baseentry->flags & (TCFLAGS_HAVE_FIELD_EQUALITY |
1691 TCFLAGS_HAVE_FIELD_COMPARE |
1692 TCFLAGS_HAVE_FIELD_HASHING |
1693 TCFLAGS_HAVE_FIELD_EXTENDED_HASHING);
1694 }
1695 }
1696 typentry->flags |= TCFLAGS_CHECKED_FIELD_PROPERTIES;
1697 }
1698
1699 /*
1700 * Likewise, some helper functions for range and multirange types.
1701 *
1702 * We can borrow the flag bits for array element properties to use for range
1703 * element properties, since those flag bits otherwise have no use in a
1704 * range or multirange type's typcache entry.
1705 */
1706
1707 static bool
1708 range_element_has_hashing(TypeCacheEntry *typentry)
1709 {
1710 if (!(typentry->flags & TCFLAGS_CHECKED_ELEM_PROPERTIES))
1711 cache_range_element_properties(typentry);
1712 return (typentry->flags & TCFLAGS_HAVE_ELEM_HASHING) != 0;
1713 }
1714
1715 static bool
1716 range_element_has_extended_hashing(TypeCacheEntry *typentry)
1717 {
1718 if (!(typentry->flags & TCFLAGS_CHECKED_ELEM_PROPERTIES))
1719 cache_range_element_properties(typentry);
1720 return (typentry->flags & TCFLAGS_HAVE_ELEM_EXTENDED_HASHING) != 0;
1721 }
1722
1723 static void
1724 cache_range_element_properties(TypeCacheEntry *typentry)
1725 {
1726 /* load up subtype link if we didn't already */
1727 if (typentry->rngelemtype == NULL &&
1728 typentry->typtype == TYPTYPE_RANGE)
1729 load_rangetype_info(typentry);
1730
1731 if (typentry->rngelemtype != NULL)
1732 {
1733 TypeCacheEntry *elementry;
1734
1735 /* might need to calculate subtype's hash function properties */
1736 elementry = lookup_type_cache(typentry->rngelemtype->type_id,
1737 TYPECACHE_HASH_PROC |
1738 TYPECACHE_HASH_EXTENDED_PROC);
1739 if (OidIsValid(elementry->hash_proc))
1740 typentry->flags |= TCFLAGS_HAVE_ELEM_HASHING;
1741 if (OidIsValid(elementry->hash_extended_proc))
1742 typentry->flags |= TCFLAGS_HAVE_ELEM_EXTENDED_HASHING;
1743 }
1744 typentry->flags |= TCFLAGS_CHECKED_ELEM_PROPERTIES;
1745 }
1746
1747 static bool
1748 multirange_element_has_hashing(TypeCacheEntry *typentry)
1749 {
1750 if (!(typentry->flags & TCFLAGS_CHECKED_ELEM_PROPERTIES))
1751 cache_multirange_element_properties(typentry);
1752 return (typentry->flags & TCFLAGS_HAVE_ELEM_HASHING) != 0;
1753 }
1754
1755 static bool
1756 multirange_element_has_extended_hashing(TypeCacheEntry *typentry)
1757 {
1758 if (!(typentry->flags & TCFLAGS_CHECKED_ELEM_PROPERTIES))
1759 cache_multirange_element_properties(typentry);
1760 return (typentry->flags & TCFLAGS_HAVE_ELEM_EXTENDED_HASHING) != 0;
1761 }
1762
1763 static void
1764 cache_multirange_element_properties(TypeCacheEntry *typentry)
1765 {
1766 /* load up range link if we didn't already */
1767 if (typentry->rngtype == NULL &&
1768 typentry->typtype == TYPTYPE_MULTIRANGE)
1769 load_multirangetype_info(typentry);
1770
1771 if (typentry->rngtype != NULL && typentry->rngtype->rngelemtype != NULL)
1772 {
1773 TypeCacheEntry *elementry;
1774
1775 /* might need to calculate subtype's hash function properties */
1776 elementry = lookup_type_cache(typentry->rngtype->rngelemtype->type_id,
1777 TYPECACHE_HASH_PROC |
1778 TYPECACHE_HASH_EXTENDED_PROC);
1779 if (OidIsValid(elementry->hash_proc))
1780 typentry->flags |= TCFLAGS_HAVE_ELEM_HASHING;
1781 if (OidIsValid(elementry->hash_extended_proc))
1782 typentry->flags |= TCFLAGS_HAVE_ELEM_EXTENDED_HASHING;
1783 }
1784 typentry->flags |= TCFLAGS_CHECKED_ELEM_PROPERTIES;
1785 }
1786
1787 /*
1788 * Make sure that RecordCacheArray and RecordIdentifierArray are large enough
1789 * to store 'typmod'.
1790 */
1791 static void
1792 ensure_record_cache_typmod_slot_exists(int32 typmod)
1793 {
1794 if (RecordCacheArray == NULL)
1795 {
1796 RecordCacheArray = (RecordCacheArrayEntry *)
1797 MemoryContextAllocZero(CacheMemoryContext,
1798 64 * sizeof(RecordCacheArrayEntry));
1799 RecordCacheArrayLen = 64;
1800 }
1801
1802 if (typmod >= RecordCacheArrayLen)
1803 {
1804 int32 newlen = pg_nextpower2_32(typmod + 1);
1805
1806 RecordCacheArray = repalloc0_array(RecordCacheArray,
1807 RecordCacheArrayEntry,
1808 RecordCacheArrayLen,
1809 newlen);
1810 RecordCacheArrayLen = newlen;
1811 }
1812 }
1813
1814 /*
1815 * lookup_rowtype_tupdesc_internal --- internal routine to lookup a rowtype
1816 *
1817 * Same API as lookup_rowtype_tupdesc_noerror, but the returned tupdesc
1818 * hasn't had its refcount bumped.
1819 */
1820 static TupleDesc
1821 lookup_rowtype_tupdesc_internal(Oid type_id, int32 typmod, bool noError)
1822 {
1823 if (type_id != RECORDOID)
1824 {
1825 /*
1826 * It's a named composite type, so use the regular typcache.
1827 */
1828 TypeCacheEntry *typentry;
1829
1830 typentry = lookup_type_cache(type_id, TYPECACHE_TUPDESC);
1831 if (typentry->tupDesc == NULL && !noError)
1832 ereport(ERROR,
1833 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1834 errmsg("type %s is not composite",
1835 format_type_be(type_id))));
1836 return typentry->tupDesc;
1837 }
1838 else
1839 {
1840 /*
1841 * It's a transient record type, so look in our record-type table.
1842 */
1843 if (typmod >= 0)
1844 {
1845 /* It is already in our local cache? */
1846 if (typmod < RecordCacheArrayLen &&
1847 RecordCacheArray[typmod].tupdesc != NULL)
1848 return RecordCacheArray[typmod].tupdesc;
1849
1850 /* Are we attached to a shared record typmod registry? */
1851 if (CurrentSession->shared_typmod_registry != NULL)
1852 {
1853 SharedTypmodTableEntry *entry;
1854
1855 /* Try to find it in the shared typmod index. */
1856 entry = dshash_find(CurrentSession->shared_typmod_table,
1857 &typmod, false);
1858 if (entry != NULL)
1859 {
1860 TupleDesc tupdesc;
1861
1862 tupdesc = (TupleDesc)
1863 dsa_get_address(CurrentSession->area,
1864 entry->shared_tupdesc);
1865 Assert(typmod == tupdesc->tdtypmod);
1866
1867 /* We may need to extend the local RecordCacheArray. */
1868 ensure_record_cache_typmod_slot_exists(typmod);
1869
1870 /*
1871 * Our local array can now point directly to the TupleDesc
1872 * in shared memory, which is non-reference-counted.
1873 */
1874 RecordCacheArray[typmod].tupdesc = tupdesc;
1875 Assert(tupdesc->tdrefcount == -1);
1876
1877 /*
1878 * We don't share tupdesc identifiers across processes, so
1879 * assign one locally.
1880 */
1881 RecordCacheArray[typmod].id = ++tupledesc_id_counter;
1882
1883 dshash_release_lock(CurrentSession->shared_typmod_table,
1884 entry);
1885
1886 return RecordCacheArray[typmod].tupdesc;
1887 }
1888 }
1889 }
1890
1891 if (!noError)
1892 ereport(ERROR,
1893 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1894 errmsg("record type has not been registered")));
1895 return NULL;
1896 }
1897 }
1898
1899 /*
1900 * lookup_rowtype_tupdesc
1901 *
1902 * Given a typeid/typmod that should describe a known composite type,
1903 * return the tuple descriptor for the type. Will ereport on failure.
1904 * (Use ereport because this is reachable with user-specified OIDs,
1905 * for example from record_in().)
1906 *
1907 * Note: on success, we increment the refcount of the returned TupleDesc,
1908 * and log the reference in CurrentResourceOwner. Caller must call
1909 * ReleaseTupleDesc when done using the tupdesc. (There are some
1910 * cases in which the returned tupdesc is not refcounted, in which
1911 * case PinTupleDesc/ReleaseTupleDesc are no-ops; but in these cases
1912 * the tupdesc is guaranteed to live till process exit.)
1913 */
1914 TupleDesc
1915 lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
1916 {
1917 TupleDesc tupDesc;
1918
1919 tupDesc = lookup_rowtype_tupdesc_internal(type_id, typmod, false);
1920 PinTupleDesc(tupDesc);
1921 return tupDesc;
1922 }
1923
1924 /*
1925 * lookup_rowtype_tupdesc_noerror
1926 *
1927 * As above, but if the type is not a known composite type and noError
1928 * is true, returns NULL instead of ereport'ing. (Note that if a bogus
1929 * type_id is passed, you'll get an ereport anyway.)
1930 */
1931 TupleDesc
1932 lookup_rowtype_tupdesc_noerror(Oid type_id, int32 typmod, bool noError)
1933 {
1934 TupleDesc tupDesc;
1935
1936 tupDesc = lookup_rowtype_tupdesc_internal(type_id, typmod, noError);
1937 if (tupDesc != NULL)
1938 PinTupleDesc(tupDesc);
1939 return tupDesc;
1940 }
1941
1942 /*
1943 * lookup_rowtype_tupdesc_copy
1944 *
1945 * Like lookup_rowtype_tupdesc(), but the returned TupleDesc has been
1946 * copied into the CurrentMemoryContext and is not reference-counted.
1947 */
1948 TupleDesc
1949 lookup_rowtype_tupdesc_copy(Oid type_id, int32 typmod)
1950 {
1951 TupleDesc tmp;
1952
1953 tmp = lookup_rowtype_tupdesc_internal(type_id, typmod, false);
1954 return CreateTupleDescCopyConstr(tmp);
1955 }
1956
1957 /*
1958 * lookup_rowtype_tupdesc_domain
1959 *
1960 * Same as lookup_rowtype_tupdesc_noerror(), except that the type can also be
1961 * a domain over a named composite type; so this is effectively equivalent to
1962 * lookup_rowtype_tupdesc_noerror(getBaseType(type_id), typmod, noError)
1963 * except for being a tad faster.
1964 *
1965 * Note: the reason we don't fold the look-through-domain behavior into plain
1966 * lookup_rowtype_tupdesc() is that we want callers to know they might be
1967 * dealing with a domain. Otherwise they might construct a tuple that should
1968 * be of the domain type, but not apply domain constraints.
1969 */
1970 TupleDesc
1971 lookup_rowtype_tupdesc_domain(Oid type_id, int32 typmod, bool noError)
1972 {
1973 TupleDesc tupDesc;
1974
1975 if (type_id != RECORDOID)
1976 {
1977 /*
1978 * Check for domain or named composite type. We might as well load
1979 * whichever data is needed.
1980 */
1981 TypeCacheEntry *typentry;
1982
1983 typentry = lookup_type_cache(type_id,
1984 TYPECACHE_TUPDESC |
1985 TYPECACHE_DOMAIN_BASE_INFO);
1986 if (typentry->typtype == TYPTYPE_DOMAIN)
1987 return lookup_rowtype_tupdesc_noerror(typentry->domainBaseType,
1988 typentry->domainBaseTypmod,
1989 noError);
1990 if (typentry->tupDesc == NULL && !noError)
1991 ereport(ERROR,
1992 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1993 errmsg("type %s is not composite",
1994 format_type_be(type_id))));
1995 tupDesc = typentry->tupDesc;
1996 }
1997 else
1998 tupDesc = lookup_rowtype_tupdesc_internal(type_id, typmod, noError);
1999 if (tupDesc != NULL)
2000 PinTupleDesc(tupDesc);
2001 return tupDesc;
2002 }
2003
2004 /*
2005 * Hash function for the hash table of RecordCacheEntry.
2006 */
2007 static uint32
2008 record_type_typmod_hash(const void *data, size_t size)
2009 {
2010 RecordCacheEntry *entry = (RecordCacheEntry *) data;
2011
2012 return hashRowType(entry->tupdesc);
2013 }
2014
2015 /*
2016 * Match function for the hash table of RecordCacheEntry.
2017 */
2018 static int
2019 record_type_typmod_compare(const void *a, const void *b, size_t size)
2020 {
2021 RecordCacheEntry *left = (RecordCacheEntry *) a;
2022 RecordCacheEntry *right = (RecordCacheEntry *) b;
2023
2024 return equalRowTypes(left->tupdesc, right->tupdesc) ? 0 : 1;
2025 }
2026
2027 /*
2028 * assign_record_type_typmod
2029 *
2030 * Given a tuple descriptor for a RECORD type, find or create a cache entry
2031 * for the type, and set the tupdesc's tdtypmod field to a value that will
2032 * identify this cache entry to lookup_rowtype_tupdesc.
2033 */
2034 void
2035 assign_record_type_typmod(TupleDesc tupDesc)
2036 {
2037 RecordCacheEntry *recentry;
2038 TupleDesc entDesc;
2039 bool found;
2040 MemoryContext oldcxt;
2041
2042 Assert(tupDesc->tdtypeid == RECORDOID);
2043
2044 if (RecordCacheHash == NULL)
2045 {
2046 /* First time through: initialize the hash table */
2047 HASHCTL ctl;
2048
2049 ctl.keysize = sizeof(TupleDesc); /* just the pointer */
2050 ctl.entrysize = sizeof(RecordCacheEntry);
2051 ctl.hash = record_type_typmod_hash;
2052 ctl.match = record_type_typmod_compare;
2053 RecordCacheHash = hash_create("Record information cache", 64,
2054 &ctl,
2055 HASH_ELEM | HASH_FUNCTION | HASH_COMPARE);
2056
2057 /* Also make sure CacheMemoryContext exists */
2058 if (!CacheMemoryContext)
2059 CreateCacheMemoryContext();
2060 }
2061
2062 /*
2063 * Find a hashtable entry for this tuple descriptor. We don't use
2064 * HASH_ENTER yet, because if it's missing, we need to make sure that all
2065 * the allocations succeed before we create the new entry.
2066 */
2067 recentry = (RecordCacheEntry *) hash_search(RecordCacheHash,
2068 &tupDesc,
2069 HASH_FIND, &found);
2070 if (found && recentry->tupdesc != NULL)
2071 {
2072 tupDesc->tdtypmod = recentry->tupdesc->tdtypmod;
2073 return;
2074 }
2075
2076 /* Not present, so need to manufacture an entry */
2077 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
2078
2079 /* Look in the SharedRecordTypmodRegistry, if attached */
2080 entDesc = find_or_make_matching_shared_tupledesc(tupDesc);
2081 if (entDesc == NULL)
2082 {
2083 /*
2084 * Make sure we have room before we CreateTupleDescCopy() or advance
2085 * NextRecordTypmod.
2086 */
2087 ensure_record_cache_typmod_slot_exists(NextRecordTypmod);
2088
2089 /* Reference-counted local cache only. */
2090 entDesc = CreateTupleDescCopy(tupDesc);
2091 entDesc->tdrefcount = 1;
2092 entDesc->tdtypmod = NextRecordTypmod++;
2093 }
2094 else
2095 {
2096 ensure_record_cache_typmod_slot_exists(entDesc->tdtypmod);
2097 }
2098
2099 RecordCacheArray[entDesc->tdtypmod].tupdesc = entDesc;
2100
2101 /* Assign a unique tupdesc identifier, too. */
2102 RecordCacheArray[entDesc->tdtypmod].id = ++tupledesc_id_counter;
2103
2104 /* Fully initialized; create the hash table entry */
2105 recentry = (RecordCacheEntry *) hash_search(RecordCacheHash,
2106 &tupDesc,
2107 HASH_ENTER, NULL);
2108 recentry->tupdesc = entDesc;
2109
2110 /* Update the caller's tuple descriptor. */
2111 tupDesc->tdtypmod = entDesc->tdtypmod;
2112
2113 MemoryContextSwitchTo(oldcxt);
2114 }
2115
2116 /*
2117 * assign_record_type_identifier
2118 *
2119 * Get an identifier, which will be unique over the lifespan of this backend
2120 * process, for the current tuple descriptor of the specified composite type.
2121 * For named composite types, the value is guaranteed to change if the type's
2122 * definition does. For registered RECORD types, the value will not change
2123 * once assigned, since the registered type won't either. If an anonymous
2124 * RECORD type is specified, we return a new identifier on each call.
2125 */
2126 uint64
2127 assign_record_type_identifier(Oid type_id, int32 typmod)
2128 {
2129 if (type_id != RECORDOID)
2130 {
2131 /*
2132 * It's a named composite type, so use the regular typcache.
2133 */
2134 TypeCacheEntry *typentry;
2135
2136 typentry = lookup_type_cache(type_id, TYPECACHE_TUPDESC);
2137 if (typentry->tupDesc == NULL)
2138 ereport(ERROR,
2139 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2140 errmsg("type %s is not composite",
2141 format_type_be(type_id))));
2142 Assert(typentry->tupDesc_identifier != 0);
2143 return typentry->tupDesc_identifier;
2144 }
2145 else
2146 {
2147 /*
2148 * It's a transient record type, so look in our record-type table.
2149 */
2150 if (typmod >= 0 && typmod < RecordCacheArrayLen &&
2151 RecordCacheArray[typmod].tupdesc != NULL)
2152 {
2153 Assert(RecordCacheArray[typmod].id != 0);
2154 return RecordCacheArray[typmod].id;
2155 }
2156
2157 /* For anonymous or unrecognized record type, generate a new ID */
2158 return ++tupledesc_id_counter;
2159 }
2160 }
2161
2162 /*
2163 * Return the amount of shmem required to hold a SharedRecordTypmodRegistry.
2164 * This exists only to avoid exposing private innards of
2165 * SharedRecordTypmodRegistry in a header.
2166 */
2167 size_t
2168 SharedRecordTypmodRegistryEstimate(void)
2169 {
2170 return sizeof(SharedRecordTypmodRegistry);
2171 }
2172
2173 /*
2174 * Initialize 'registry' in a pre-existing shared memory region, which must be
2175 * maximally aligned and have space for SharedRecordTypmodRegistryEstimate()
2176 * bytes.
2177 *
2178 * 'area' will be used to allocate shared memory space as required for the
2179 * typemod registration. The current process, expected to be a leader process
2180 * in a parallel query, will be attached automatically and its current record
2181 * types will be loaded into *registry. While attached, all calls to
2182 * assign_record_type_typmod will use the shared registry. Worker backends
2183 * will need to attach explicitly.
2184 *
2185 * Note that this function takes 'area' and 'segment' as arguments rather than
2186 * accessing them via CurrentSession, because they aren't installed there
2187 * until after this function runs.
2188 */
2189 void
2190 SharedRecordTypmodRegistryInit(SharedRecordTypmodRegistry *registry,
2191 dsm_segment *segment,
2192 dsa_area *area)
2193 {
2194 MemoryContext old_context;
2195 dshash_table *record_table;
2196 dshash_table *typmod_table;
2197 int32 typmod;
2198
2199 Assert(!IsParallelWorker());
2200
2201 /* We can't already be attached to a shared registry. */
2202 Assert(CurrentSession->shared_typmod_registry == NULL);
2203 Assert(CurrentSession->shared_record_table == NULL);
2204 Assert(CurrentSession->shared_typmod_table == NULL);
2205
2206 old_context = MemoryContextSwitchTo(TopMemoryContext);
2207
2208 /* Create the hash table of tuple descriptors indexed by themselves. */
2209 record_table = dshash_create(area, &srtr_record_table_params, area);
2210
2211 /* Create the hash table of tuple descriptors indexed by typmod. */
2212 typmod_table = dshash_create(area, &srtr_typmod_table_params, NULL);
2213
2214 MemoryContextSwitchTo(old_context);
2215
2216 /* Initialize the SharedRecordTypmodRegistry. */
2217 registry->record_table_handle = dshash_get_hash_table_handle(record_table);
2218 registry->typmod_table_handle = dshash_get_hash_table_handle(typmod_table);
2219 pg_atomic_init_u32(&registry->next_typmod, NextRecordTypmod);
2220
2221 /*
2222 * Copy all entries from this backend's private registry into the shared
2223 * registry.
2224 */
2225 for (typmod = 0; typmod < NextRecordTypmod; ++typmod)
2226 {
2227 SharedTypmodTableEntry *typmod_table_entry;
2228 SharedRecordTableEntry *record_table_entry;
2229 SharedRecordTableKey record_table_key;
2230 dsa_pointer shared_dp;
2231 TupleDesc tupdesc;
2232 bool found;
2233
2234 tupdesc = RecordCacheArray[typmod].tupdesc;
2235 if (tupdesc == NULL)
2236 continue;
2237
2238 /* Copy the TupleDesc into shared memory. */
2239 shared_dp = share_tupledesc(area, tupdesc, typmod);
2240
2241 /* Insert into the typmod table. */
2242 typmod_table_entry = dshash_find_or_insert(typmod_table,
2243 &tupdesc->tdtypmod,
2244 &found);
2245 if (found)
2246 elog(ERROR, "cannot create duplicate shared record typmod");
2247 typmod_table_entry->typmod = tupdesc->tdtypmod;
2248 typmod_table_entry->shared_tupdesc = shared_dp;
2249 dshash_release_lock(typmod_table, typmod_table_entry);
2250
2251 /* Insert into the record table. */
2252 record_table_key.shared = false;
2253 record_table_key.u.local_tupdesc = tupdesc;
2254 record_table_entry = dshash_find_or_insert(record_table,
2255 &record_table_key,
2256 &found);
2257 if (!found)
2258 {
2259 record_table_entry->key.shared = true;
2260 record_table_entry->key.u.shared_tupdesc = shared_dp;
2261 }
2262 dshash_release_lock(record_table, record_table_entry);
2263 }
2264
2265 /*
2266 * Set up the global state that will tell assign_record_type_typmod and
2267 * lookup_rowtype_tupdesc_internal about the shared registry.
2268 */
2269 CurrentSession->shared_record_table = record_table;
2270 CurrentSession->shared_typmod_table = typmod_table;
2271 CurrentSession->shared_typmod_registry = registry;
2272
2273 /*
2274 * We install a detach hook in the leader, but only to handle cleanup on
2275 * failure during GetSessionDsmHandle(). Once GetSessionDsmHandle() pins
2276 * the memory, the leader process will use a shared registry until it
2277 * exits.
2278 */
2279 on_dsm_detach(segment, shared_record_typmod_registry_detach, (Datum) 0);
2280 }
2281
2282 /*
2283 * Attach to 'registry', which must have been initialized already by another
2284 * backend. Future calls to assign_record_type_typmod and
2285 * lookup_rowtype_tupdesc_internal will use the shared registry until the
2286 * current session is detached.
2287 */
2288 void
2289 SharedRecordTypmodRegistryAttach(SharedRecordTypmodRegistry *registry)
2290 {
2291 MemoryContext old_context;
2292 dshash_table *record_table;
2293 dshash_table *typmod_table;
2294
2295 Assert(IsParallelWorker());
2296
2297 /* We can't already be attached to a shared registry. */
2298 Assert(CurrentSession != NULL);
2299 Assert(CurrentSession->segment != NULL);
2300 Assert(CurrentSession->area != NULL);
2301 Assert(CurrentSession->shared_typmod_registry == NULL);
2302 Assert(CurrentSession->shared_record_table == NULL);
2303 Assert(CurrentSession->shared_typmod_table == NULL);
2304
2305 /*
2306 * We can't already have typmods in our local cache, because they'd clash
2307 * with those imported by SharedRecordTypmodRegistryInit. This should be
2308 * a freshly started parallel worker. If we ever support worker
2309 * recycling, a worker would need to zap its local cache in between
2310 * servicing different queries, in order to be able to call this and
2311 * synchronize typmods with a new leader; but that's problematic because
2312 * we can't be very sure that record-typmod-related state hasn't escaped
2313 * to anywhere else in the process.
2314 */
2315 Assert(NextRecordTypmod == 0);
2316
2317 old_context = MemoryContextSwitchTo(TopMemoryContext);
2318
2319 /* Attach to the two hash tables. */
2320 record_table = dshash_attach(CurrentSession->area,
2321 &srtr_record_table_params,
2322 registry->record_table_handle,
2323 CurrentSession->area);
2324 typmod_table = dshash_attach(CurrentSession->area,
2325 &srtr_typmod_table_params,
2326 registry->typmod_table_handle,
2327 NULL);
2328
2329 MemoryContextSwitchTo(old_context);
2330
2331 /*
2332 * Set up detach hook to run at worker exit. Currently this is the same
2333 * as the leader's detach hook, but in future they might need to be
2334 * different.
2335 */
2336 on_dsm_detach(CurrentSession->segment,
2337 shared_record_typmod_registry_detach,
2338 PointerGetDatum(registry));
2339
2340 /*
2341 * Set up the session state that will tell assign_record_type_typmod and
2342 * lookup_rowtype_tupdesc_internal about the shared registry.
2343 */
2344 CurrentSession->shared_typmod_registry = registry;
2345 CurrentSession->shared_record_table = record_table;
2346 CurrentSession->shared_typmod_table = typmod_table;
2347 }
2348
2349 /*
2350 * InvalidateCompositeTypeCacheEntry
2351 * Invalidate particular TypeCacheEntry on Relcache inval callback
2352 *
2353 * Delete the cached tuple descriptor (if any) for the given composite
2354 * type, and reset whatever info we have cached about the composite type's
2355 * comparability.
2356 */
2357 static void
2358 InvalidateCompositeTypeCacheEntry(TypeCacheEntry *typentry)
2359 {
2360 bool hadTupDescOrOpclass;
2361
2362 Assert(typentry->typtype == TYPTYPE_COMPOSITE &&
2363 OidIsValid(typentry->typrelid));
2364
2365 hadTupDescOrOpclass = (typentry->tupDesc != NULL) ||
2366 (typentry->flags & TCFLAGS_OPERATOR_FLAGS);
2367
2368 /* Delete tupdesc if we have it */
2369 if (typentry->tupDesc != NULL)
2370 {
2371 /*
2372 * Release our refcount and free the tupdesc if none remain. We can't
2373 * use DecrTupleDescRefCount here because this reference is not logged
2374 * by the current resource owner.
2375 */
2376 Assert(typentry->tupDesc->tdrefcount > 0);
2377 if (--typentry->tupDesc->tdrefcount == 0)
2378 FreeTupleDesc(typentry->tupDesc);
2379 typentry->tupDesc = NULL;
2380
2381 /*
2382 * Also clear tupDesc_identifier, so that anyone watching it will
2383 * realize that the tupdesc has changed.
2384 */
2385 typentry->tupDesc_identifier = 0;
2386 }
2387
2388 /* Reset equality/comparison/hashing validity information */
2389 typentry->flags &= ~TCFLAGS_OPERATOR_FLAGS;
2390
2391 /*
2392 * Call delete_rel_type_cache_if_needed() if we actually cleared
2393 * something.
2394 */
2395 if (hadTupDescOrOpclass)
2396 delete_rel_type_cache_if_needed(typentry);
2397 }
2398
2399 /*
2400 * TypeCacheRelCallback
2401 * Relcache inval callback function
2402 *
2403 * Delete the cached tuple descriptor (if any) for the given rel's composite
2404 * type, or for all composite types if relid == InvalidOid. Also reset
2405 * whatever info we have cached about the composite type's comparability.
2406 *
2407 * This is called when a relcache invalidation event occurs for the given
2408 * relid. We can't use syscache to find a type corresponding to the given
2409 * relation because the code can be called outside of transaction. Thus, we
2410 * use the RelIdToTypeIdCacheHash map to locate appropriate typcache entry.
2411 */
2412 static void
2413 TypeCacheRelCallback(Datum arg, Oid relid)
2414 {
2415 TypeCacheEntry *typentry;
2416
2417 /*
2418 * RelIdToTypeIdCacheHash and TypeCacheHash should exist, otherwise this
2419 * callback wouldn't be registered
2420 */
2421 if (OidIsValid(relid))
2422 {
2423 RelIdToTypeIdCacheEntry *relentry;
2424
2425 /*
2426 * Find an RelIdToTypeIdCacheHash entry, which should exist as soon as
2427 * corresponding typcache entry has something to clean.
2428 */
2429 relentry = (RelIdToTypeIdCacheEntry *) hash_search(RelIdToTypeIdCacheHash,
2430 &relid,
2431 HASH_FIND, NULL);
2432
2433 if (relentry != NULL)
2434 {
2435 typentry = (TypeCacheEntry *) hash_search(TypeCacheHash,
2436 &relentry->composite_typid,
2437 HASH_FIND, NULL);
2438
2439 if (typentry != NULL)
2440 {
2441 Assert(typentry->typtype == TYPTYPE_COMPOSITE);
2442 Assert(relid == typentry->typrelid);
2443
2444 InvalidateCompositeTypeCacheEntry(typentry);
2445 }
2446 }
2447
2448 /*
2449 * Visit all the domain types sequentially. Typically, this shouldn't
2450 * affect performance since domain types are less tended to bloat.
2451 * Domain types are created manually, unlike composite types which are
2452 * automatically created for every temporary table.
2453 */
2454 for (typentry = firstDomainTypeEntry;
2455 typentry != NULL;
2456 typentry = typentry->nextDomain)
2457 {
2458 /*
2459 * If it's domain over composite, reset flags. (We don't bother
2460 * trying to determine whether the specific base type needs a
2461 * reset.) Note that if we haven't determined whether the base
2462 * type is composite, we don't need to reset anything.
2463 */
2464 if (typentry->flags & TCFLAGS_DOMAIN_BASE_IS_COMPOSITE)
2465 typentry->flags &= ~TCFLAGS_OPERATOR_FLAGS;
2466 }
2467 }
2468 else
2469 {
2470 HASH_SEQ_STATUS status;
2471
2472 /*
2473 * Relid is invalid. By convention, we need to reset all composite
2474 * types in cache. Also, we should reset flags for domain types, and
2475 * we loop over all entries in hash, so, do it in a single scan.
2476 */
2477 hash_seq_init(&status, TypeCacheHash);
2478 while ((typentry = (TypeCacheEntry *) hash_seq_search(&status)) != NULL)
2479 {
2480 if (typentry->typtype == TYPTYPE_COMPOSITE)
2481 {
2482 InvalidateCompositeTypeCacheEntry(typentry);
2483 }
2484 else if (typentry->typtype == TYPTYPE_DOMAIN)
2485 {
2486 /*
2487 * If it's domain over composite, reset flags. (We don't
2488 * bother trying to determine whether the specific base type
2489 * needs a reset.) Note that if we haven't determined whether
2490 * the base type is composite, we don't need to reset
2491 * anything.
2492 */
2493 if (typentry->flags & TCFLAGS_DOMAIN_BASE_IS_COMPOSITE)
2494 typentry->flags &= ~TCFLAGS_OPERATOR_FLAGS;
2495 }
2496 }
2497 }
2498 }
2499
2500 /*
2501 * TypeCacheTypCallback
2502 * Syscache inval callback function
2503 *
2504 * This is called when a syscache invalidation event occurs for any
2505 * pg_type row. If we have information cached about that type, mark
2506 * it as needing to be reloaded.
2507 */
2508 static void
2509 TypeCacheTypCallback(Datum arg, int cacheid, uint32 hashvalue)
2510 {
2511 HASH_SEQ_STATUS status;
2512 TypeCacheEntry *typentry;
2513
2514 /* TypeCacheHash must exist, else this callback wouldn't be registered */
2515
2516 /*
2517 * By convention, zero hash value is passed to the callback as a sign that
2518 * it's time to invalidate the whole cache. See sinval.c, inval.c and
2519 * InvalidateSystemCachesExtended().
2520 */
2521 if (hashvalue == 0)
2522 hash_seq_init(&status, TypeCacheHash);
2523 else
2524 hash_seq_init_with_hash_value(&status, TypeCacheHash, hashvalue);
2525
2526 while ((typentry = (TypeCacheEntry *) hash_seq_search(&status)) != NULL)
2527 {
2528 bool hadPgTypeData = (typentry->flags & TCFLAGS_HAVE_PG_TYPE_DATA);
2529
2530 Assert(hashvalue == 0 || typentry->type_id_hash == hashvalue);
2531
2532 /*
2533 * Mark the data obtained directly from pg_type as invalid. Also, if
2534 * it's a domain, typnotnull might've changed, so we'll need to
2535 * recalculate its constraints.
2536 */
2537 typentry->flags &= ~(TCFLAGS_HAVE_PG_TYPE_DATA |
2538 TCFLAGS_CHECKED_DOMAIN_CONSTRAINTS);
2539
2540 /*
2541 * Call delete_rel_type_cache_if_needed() if we cleaned
2542 * TCFLAGS_HAVE_PG_TYPE_DATA flag previously.
2543 */
2544 if (hadPgTypeData)
2545 delete_rel_type_cache_if_needed(typentry);
2546 }
2547 }
2548
2549 /*
2550 * TypeCacheOpcCallback
2551 * Syscache inval callback function
2552 *
2553 * This is called when a syscache invalidation event occurs for any pg_opclass
2554 * row. In principle we could probably just invalidate data dependent on the
2555 * particular opclass, but since updates on pg_opclass are rare in production
2556 * it doesn't seem worth a lot of complication: we just mark all cached data
2557 * invalid.
2558 *
2559 * Note that we don't bother watching for updates on pg_amop or pg_amproc.
2560 * This should be safe because ALTER OPERATOR FAMILY ADD/DROP OPERATOR/FUNCTION
2561 * is not allowed to be used to add/drop the primary operators and functions
2562 * of an opclass, only cross-type members of a family; and the latter sorts
2563 * of members are not going to get cached here.
2564 */
2565 static void
2566 TypeCacheOpcCallback(Datum arg, int cacheid, uint32 hashvalue)
2567 {
2568 HASH_SEQ_STATUS status;
2569 TypeCacheEntry *typentry;
2570
2571 /* TypeCacheHash must exist, else this callback wouldn't be registered */
2572 hash_seq_init(&status, TypeCacheHash);
2573 while ((typentry = (TypeCacheEntry *) hash_seq_search(&status)) != NULL)
2574 {
2575 bool hadOpclass = (typentry->flags & TCFLAGS_OPERATOR_FLAGS);
2576
2577 /* Reset equality/comparison/hashing validity information */
2578 typentry->flags &= ~TCFLAGS_OPERATOR_FLAGS;
2579
2580 /*
2581 * Call delete_rel_type_cache_if_needed() if we actually cleared some
2582 * of TCFLAGS_OPERATOR_FLAGS.
2583 */
2584 if (hadOpclass)
2585 delete_rel_type_cache_if_needed(typentry);
2586 }
2587 }
2588
2589 /*
2590 * TypeCacheConstrCallback
2591 * Syscache inval callback function
2592 *
2593 * This is called when a syscache invalidation event occurs for any
2594 * pg_constraint row. We flush information about domain constraints
2595 * when this happens.
2596 *
2597 * It's slightly annoying that we can't tell whether the inval event was for
2598 * a domain constraint record or not; there's usually more update traffic
2599 * for table constraints than domain constraints, so we'll do a lot of
2600 * useless flushes. Still, this is better than the old no-caching-at-all
2601 * approach to domain constraints.
2602 */
2603 static void
2604 TypeCacheConstrCallback(Datum arg, int cacheid, uint32 hashvalue)
2605 {
2606 TypeCacheEntry *typentry;
2607
2608 /*
2609 * Because this is called very frequently, and typically very few of the
2610 * typcache entries are for domains, we don't use hash_seq_search here.
2611 * Instead we thread all the domain-type entries together so that we can
2612 * visit them cheaply.
2613 */
2614 for (typentry = firstDomainTypeEntry;
2615 typentry != NULL;
2616 typentry = typentry->nextDomain)
2617 {
2618 /* Reset domain constraint validity information */
2619 typentry->flags &= ~TCFLAGS_CHECKED_DOMAIN_CONSTRAINTS;
2620 }
2621 }
2622
2623
2624 /*
2625 * Check if given OID is part of the subset that's sortable by comparisons
2626 */
2627 static inline bool
2628 enum_known_sorted(TypeCacheEnumData *enumdata, Oid arg)
2629 {
2630 Oid offset;
2631
2632 if (arg < enumdata->bitmap_base)
2633 return false;
2634 offset = arg - enumdata->bitmap_base;
2635 if (offset > (Oid) INT_MAX)
2636 return false;
2637 return bms_is_member((int) offset, enumdata->sorted_values);
2638 }
2639
2640
2641 /*
2642 * compare_values_of_enum
2643 * Compare two members of an enum type.
2644 * Return <0, 0, or >0 according as arg1 <, =, or > arg2.
2645 *
2646 * Note: currently, the enumData cache is refreshed only if we are asked
2647 * to compare an enum value that is not already in the cache. This is okay
2648 * because there is no support for re-ordering existing values, so comparisons
2649 * of previously cached values will return the right answer even if other
2650 * values have been added since we last loaded the cache.
2651 *
2652 * Note: the enum logic has a special-case rule about even-numbered versus
2653 * odd-numbered OIDs, but we take no account of that rule here; this
2654 * routine shouldn't even get called when that rule applies.
2655 */
2656 int
2657 compare_values_of_enum(TypeCacheEntry *tcache, Oid arg1, Oid arg2)
2658 {
2659 TypeCacheEnumData *enumdata;
2660 EnumItem *item1;
2661 EnumItem *item2;
2662
2663 /*
2664 * Equal OIDs are certainly equal --- this case was probably handled by
2665 * our caller, but we may as well check.
2666 */
2667 if (arg1 == arg2)
2668 return 0;
2669
2670 /* Load up the cache if first time through */
2671 if (tcache->enumData == NULL)
2672 load_enum_cache_data(tcache);
2673 enumdata = tcache->enumData;
2674
2675 /*
2676 * If both OIDs are known-sorted, we can just compare them directly.
2677 */
2678 if (enum_known_sorted(enumdata, arg1) &&
2679 enum_known_sorted(enumdata, arg2))
2680 {
2681 if (arg1 < arg2)
2682 return -1;
2683 else
2684 return 1;
2685 }
2686
2687 /*
2688 * Slow path: we have to identify their actual sort-order positions.
2689 */
2690 item1 = find_enumitem(enumdata, arg1);
2691 item2 = find_enumitem(enumdata, arg2);
2692
2693 if (item1 == NULL || item2 == NULL)
2694 {
2695 /*
2696 * We couldn't find one or both values. That means the enum has
2697 * changed under us, so re-initialize the cache and try again. We
2698 * don't bother retrying the known-sorted case in this path.
2699 */
2700 load_enum_cache_data(tcache);
2701 enumdata = tcache->enumData;
2702
2703 item1 = find_enumitem(enumdata, arg1);
2704 item2 = find_enumitem(enumdata, arg2);
2705
2706 /*
2707 * If we still can't find the values, complain: we must have corrupt
2708 * data.
2709 */
2710 if (item1 == NULL)
2711 elog(ERROR, "enum value %u not found in cache for enum %s",
2712 arg1, format_type_be(tcache->type_id));
2713 if (item2 == NULL)
2714 elog(ERROR, "enum value %u not found in cache for enum %s",
2715 arg2, format_type_be(tcache->type_id));
2716 }
2717
2718 if (item1->sort_order < item2->sort_order)
2719 return -1;
2720 else if (item1->sort_order > item2->sort_order)
2721 return 1;
2722 else
2723 return 0;
2724 }
2725
2726 /*
2727 * Load (or re-load) the enumData member of the typcache entry.
2728 */
2729 static void
2730 load_enum_cache_data(TypeCacheEntry *tcache)
2731 {
2732 TypeCacheEnumData *enumdata;
2733 Relation enum_rel;
2734 SysScanDesc enum_scan;
2735 HeapTuple enum_tuple;
2736 ScanKeyData skey;
2737 EnumItem *items;
2738 int numitems;
2739 int maxitems;
2740 Oid bitmap_base;
2741 Bitmapset *bitmap;
2742 MemoryContext oldcxt;
2743 int bm_size,
2744 start_pos;
2745
2746 /* Check that this is actually an enum */
2747 if (tcache->typtype != TYPTYPE_ENUM)
2748 ereport(ERROR,
2749 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2750 errmsg("%s is not an enum",
2751 format_type_be(tcache->type_id))));
2752
2753 /*
2754 * Read all the information for members of the enum type. We collect the
2755 * info in working memory in the caller's context, and then transfer it to
2756 * permanent memory in CacheMemoryContext. This minimizes the risk of
2757 * leaking memory from CacheMemoryContext in the event of an error partway
2758 * through.
2759 */
2760 maxitems = 64;
2761 items = (EnumItem *) palloc(sizeof(EnumItem) * maxitems);
2762 numitems = 0;
2763
2764 /* Scan pg_enum for the members of the target enum type. */
2765 ScanKeyInit(&skey,
2766 Anum_pg_enum_enumtypid,
2767 BTEqualStrategyNumber, F_OIDEQ,
2768 ObjectIdGetDatum(tcache->type_id));
2769
2770 enum_rel = table_open(EnumRelationId, AccessShareLock);
2771 enum_scan = systable_beginscan(enum_rel,
2772 EnumTypIdLabelIndexId,
2773 true, NULL,
2774 1, &skey);
2775
2776 while (HeapTupleIsValid(enum_tuple = systable_getnext(enum_scan)))
2777 {
2778 Form_pg_enum en = (Form_pg_enum) GETSTRUCT(enum_tuple);
2779
2780 if (numitems >= maxitems)
2781 {
2782 maxitems *= 2;
2783 items = (EnumItem *) repalloc(items, sizeof(EnumItem) * maxitems);
2784 }
2785 items[numitems].enum_oid = en->oid;
2786 items[numitems].sort_order = en->enumsortorder;
2787 numitems++;
2788 }
2789
2790 systable_endscan(enum_scan);
2791 table_close(enum_rel, AccessShareLock);
2792
2793 /* Sort the items into OID order */
2794 qsort(items, numitems, sizeof(EnumItem), enum_oid_cmp);
2795
2796 /*
2797 * Here, we create a bitmap listing a subset of the enum's OIDs that are
2798 * known to be in order and can thus be compared with just OID comparison.
2799 *
2800 * The point of this is that the enum's initial OIDs were certainly in
2801 * order, so there is some subset that can be compared via OID comparison;
2802 * and we'd rather not do binary searches unnecessarily.
2803 *
2804 * This is somewhat heuristic, and might identify a subset of OIDs that
2805 * isn't exactly what the type started with. That's okay as long as the
2806 * subset is correctly sorted.
2807 */
2808 bitmap_base = InvalidOid;
2809 bitmap = NULL;
2810 bm_size = 1; /* only save sets of at least 2 OIDs */
2811
2812 for (start_pos = 0; start_pos < numitems - 1; start_pos++)
2813 {
2814 /*
2815 * Identify longest sorted subsequence starting at start_pos
2816 */
2817 Bitmapset *this_bitmap = bms_make_singleton(0);
2818 int this_bm_size = 1;
2819 Oid start_oid = items[start_pos].enum_oid;
2820 float4 prev_order = items[start_pos].sort_order;
2821 int i;
2822
2823 for (i = start_pos + 1; i < numitems; i++)
2824 {
2825 Oid offset;
2826
2827 offset = items[i].enum_oid - start_oid;
2828 /* quit if bitmap would be too large; cutoff is arbitrary */
2829 if (offset >= 8192)
2830 break;
2831 /* include the item if it's in-order */
2832 if (items[i].sort_order > prev_order)
2833 {
2834 prev_order = items[i].sort_order;
2835 this_bitmap = bms_add_member(this_bitmap, (int) offset);
2836 this_bm_size++;
2837 }
2838 }
2839
2840 /* Remember it if larger than previous best */
2841 if (this_bm_size > bm_size)
2842 {
2843 bms_free(bitmap);
2844 bitmap_base = start_oid;
2845 bitmap = this_bitmap;
2846 bm_size = this_bm_size;
2847 }
2848 else
2849 bms_free(this_bitmap);
2850
2851 /*
2852 * Done if it's not possible to find a longer sequence in the rest of
2853 * the list. In typical cases this will happen on the first
2854 * iteration, which is why we create the bitmaps on the fly instead of
2855 * doing a second pass over the list.
2856 */
2857 if (bm_size >= (numitems - start_pos - 1))
2858 break;
2859 }
2860
2861 /* OK, copy the data into CacheMemoryContext */
2862 oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
2863 enumdata = (TypeCacheEnumData *)
2864 palloc(offsetof(TypeCacheEnumData, enum_values) +
2865 numitems * sizeof(EnumItem));
2866 enumdata->bitmap_base = bitmap_base;
2867 enumdata->sorted_values = bms_copy(bitmap);
2868 enumdata->num_values = numitems;
2869 memcpy(enumdata->enum_values, items, numitems * sizeof(EnumItem));
2870 MemoryContextSwitchTo(oldcxt);
2871
2872 pfree(items);
2873 bms_free(bitmap);
2874
2875 /* And link the finished cache struct into the typcache */
2876 if (tcache->enumData != NULL)
2877 pfree(tcache->enumData);
2878 tcache->enumData = enumdata;
2879 }
2880
2881 /*
2882 * Locate the EnumItem with the given OID, if present
2883 */
2884 static EnumItem *
2885 find_enumitem(TypeCacheEnumData *enumdata, Oid arg)
2886 {
2887 EnumItem srch;
2888
2889 /* On some versions of Solaris, bsearch of zero items dumps core */
2890 if (enumdata->num_values <= 0)
2891 return NULL;
2892
2893 srch.enum_oid = arg;
2894 return bsearch(&srch, enumdata->enum_values, enumdata->num_values,
2895 sizeof(EnumItem), enum_oid_cmp);
2896 }
2897
2898 /*
2899 * qsort comparison function for OID-ordered EnumItems
2900 */
2901 static int
2902 enum_oid_cmp(const void *left, const void *right)
2903 {
2904 const EnumItem *l = (const EnumItem *) left;
2905 const EnumItem *r = (const EnumItem *) right;
2906
2907 return pg_cmp_u32(l->enum_oid, r->enum_oid);
2908 }
2909
2910 /*
2911 * Copy 'tupdesc' into newly allocated shared memory in 'area', set its typmod
2912 * to the given value and return a dsa_pointer.
2913 */
2914 static dsa_pointer
2915 share_tupledesc(dsa_area *area, TupleDesc tupdesc, uint32 typmod)
2916 {
2917 dsa_pointer shared_dp;
2918 TupleDesc shared;
2919
2920 shared_dp = dsa_allocate(area, TupleDescSize(tupdesc));
2921 shared = (TupleDesc) dsa_get_address(area, shared_dp);
2922 TupleDescCopy(shared, tupdesc);
2923 shared->tdtypmod = typmod;
2924
2925 return shared_dp;
2926 }
2927
2928 /*
2929 * If we are attached to a SharedRecordTypmodRegistry, use it to find or
2930 * create a shared TupleDesc that matches 'tupdesc'. Otherwise return NULL.
2931 * Tuple descriptors returned by this function are not reference counted, and
2932 * will exist at least as long as the current backend remained attached to the
2933 * current session.
2934 */
2935 static TupleDesc
2936 find_or_make_matching_shared_tupledesc(TupleDesc tupdesc)
2937 {
2938 TupleDesc result;
2939 SharedRecordTableKey key;
2940 SharedRecordTableEntry *record_table_entry;
2941 SharedTypmodTableEntry *typmod_table_entry;
2942 dsa_pointer shared_dp;
2943 bool found;
2944 uint32 typmod;
2945
2946 /* If not even attached, nothing to do. */
2947 if (CurrentSession->shared_typmod_registry == NULL)
2948 return NULL;
2949
2950 /* Try to find a matching tuple descriptor in the record table. */
2951 key.shared = false;
2952 key.u.local_tupdesc = tupdesc;
2953 record_table_entry = (SharedRecordTableEntry *)
2954 dshash_find(CurrentSession->shared_record_table, &key, false);
2955 if (record_table_entry)
2956 {
2957 Assert(record_table_entry->key.shared);
2958 dshash_release_lock(CurrentSession->shared_record_table,
2959 record_table_entry);
2960 result = (TupleDesc)
2961 dsa_get_address(CurrentSession->area,
2962 record_table_entry->key.u.shared_tupdesc);
2963 Assert(result->tdrefcount == -1);
2964
2965 return result;
2966 }
2967
2968 /* Allocate a new typmod number. This will be wasted if we error out. */
2969 typmod = (int)
2970 pg_atomic_fetch_add_u32(&CurrentSession->shared_typmod_registry->next_typmod,
2971 1);
2972
2973 /* Copy the TupleDesc into shared memory. */
2974 shared_dp = share_tupledesc(CurrentSession->area, tupdesc, typmod);
2975
2976 /*
2977 * Create an entry in the typmod table so that others will understand this
2978 * typmod number.
2979 */
2980 PG_TRY();
2981 {
2982 typmod_table_entry = (SharedTypmodTableEntry *)
2983 dshash_find_or_insert(CurrentSession->shared_typmod_table,
2984 &typmod, &found);
2985 if (found)
2986 elog(ERROR, "cannot create duplicate shared record typmod");
2987 }
2988 PG_CATCH();
2989 {
2990 dsa_free(CurrentSession->area, shared_dp);
2991 PG_RE_THROW();
2992 }
2993 PG_END_TRY();
2994 typmod_table_entry->typmod = typmod;
2995 typmod_table_entry->shared_tupdesc = shared_dp;
2996 dshash_release_lock(CurrentSession->shared_typmod_table,
2997 typmod_table_entry);
2998
2999 /*
3000 * Finally create an entry in the record table so others with matching
3001 * tuple descriptors can reuse the typmod.
3002 */
3003 record_table_entry = (SharedRecordTableEntry *)
3004 dshash_find_or_insert(CurrentSession->shared_record_table, &key,
3005 &found);
3006 if (found)
3007 {
3008 /*
3009 * Someone concurrently inserted a matching tuple descriptor since the
3010 * first time we checked. Use that one instead.
3011 */
3012 dshash_release_lock(CurrentSession->shared_record_table,
3013 record_table_entry);
3014
3015 /* Might as well free up the space used by the one we created. */
3016 found = dshash_delete_key(CurrentSession->shared_typmod_table,
3017 &typmod);
3018 Assert(found);
3019 dsa_free(CurrentSession->area, shared_dp);
3020
3021 /* Return the one we found. */
3022 Assert(record_table_entry->key.shared);
3023 result = (TupleDesc)
3024 dsa_get_address(CurrentSession->area,
3025 record_table_entry->key.u.shared_tupdesc);
3026 Assert(result->tdrefcount == -1);
3027
3028 return result;
3029 }
3030
3031 /* Store it and return it. */
3032 record_table_entry->key.shared = true;
3033 record_table_entry->key.u.shared_tupdesc = shared_dp;
3034 dshash_release_lock(CurrentSession->shared_record_table,
3035 record_table_entry);
3036 result = (TupleDesc)
3037 dsa_get_address(CurrentSession->area, shared_dp);
3038 Assert(result->tdrefcount == -1);
3039
3040 return result;
3041 }
3042
3043 /*
3044 * On-DSM-detach hook to forget about the current shared record typmod
3045 * infrastructure. This is currently used by both leader and workers.
3046 */
3047 static void
3048 shared_record_typmod_registry_detach(dsm_segment *segment, Datum datum)
3049 {
3050 /* Be cautious here: maybe we didn't finish initializing. */
3051 if (CurrentSession->shared_record_table != NULL)
3052 {
3053 dshash_detach(CurrentSession->shared_record_table);
3054 CurrentSession->shared_record_table = NULL;
3055 }
3056 if (CurrentSession->shared_typmod_table != NULL)
3057 {
3058 dshash_detach(CurrentSession->shared_typmod_table);
3059 CurrentSession->shared_typmod_table = NULL;
3060 }
3061 CurrentSession->shared_typmod_registry = NULL;
3062 }
3063
3064 /*
3065 * Insert RelIdToTypeIdCacheHash entry if needed.
3066 */
3067 static void
3068 insert_rel_type_cache_if_needed(TypeCacheEntry *typentry)
3069 {
3070 /* Immediately quit for non-composite types */
3071 if (typentry->typtype != TYPTYPE_COMPOSITE)
3072 return;
3073
3074 /* typrelid should be given for composite types */
3075 Assert(OidIsValid(typentry->typrelid));
3076
3077 /*
3078 * Insert a RelIdToTypeIdCacheHash entry if the typentry have any
3079 * information indicating it should be here.
3080 */
3081 if ((typentry->flags & TCFLAGS_HAVE_PG_TYPE_DATA) ||
3082 (typentry->flags & TCFLAGS_OPERATOR_FLAGS) ||
3083 typentry->tupDesc != NULL)
3084 {
3085 RelIdToTypeIdCacheEntry *relentry;
3086 bool found;
3087
3088 relentry = (RelIdToTypeIdCacheEntry *) hash_search(RelIdToTypeIdCacheHash,
3089 &typentry->typrelid,
3090 HASH_ENTER, &found);
3091 relentry->relid = typentry->typrelid;
3092 relentry->composite_typid = typentry->type_id;
3093 }
3094 }
3095
3096 /*
3097 * Delete entry RelIdToTypeIdCacheHash if needed after resetting of the
3098 * TCFLAGS_HAVE_PG_TYPE_DATA flag, or any of TCFLAGS_OPERATOR_FLAGS,
3099 * or tupDesc.
3100 */
3101 static void
3102 delete_rel_type_cache_if_needed(TypeCacheEntry *typentry)
3103 {
3104 #ifdef USE_ASSERT_CHECKING
3105 int i;
3106 bool is_in_progress = false;
3107
3108 for (i = 0; i < in_progress_list_len; i++)
3109 {
3110 if (in_progress_list[i] == typentry->type_id)
3111 {
3112 is_in_progress = true;
3113 break;
3114 }
3115 }
3116 #endif
3117
3118 /* Immediately quit for non-composite types */
3119 if (typentry->typtype != TYPTYPE_COMPOSITE)
3120 return;
3121
3122 /* typrelid should be given for composite types */
3123 Assert(OidIsValid(typentry->typrelid));
3124
3125 /*
3126 * Delete a RelIdToTypeIdCacheHash entry if the typentry doesn't have any
3127 * information indicating entry should be still there.
3128 */
3129 if (!(typentry->flags & TCFLAGS_HAVE_PG_TYPE_DATA) &&
3130 !(typentry->flags & TCFLAGS_OPERATOR_FLAGS) &&
3131 typentry->tupDesc == NULL)
3132 {
3133 bool found;
3134
3135 (void) hash_search(RelIdToTypeIdCacheHash,
3136 &typentry->typrelid,
3137 HASH_REMOVE, &found);
3138 Assert(found || is_in_progress);
3139 }
3140 else
3141 {
3142 #ifdef USE_ASSERT_CHECKING
3143 /*
3144 * In assert-enabled builds otherwise check for RelIdToTypeIdCacheHash
3145 * entry if it should exist.
3146 */
3147 bool found;
3148
3149 if (!is_in_progress)
3150 {
3151 (void) hash_search(RelIdToTypeIdCacheHash,
3152 &typentry->typrelid,
3153 HASH_FIND, &found);
3154 Assert(found);
3155 }
3156 #endif
3157 }
3158 }
3159
3160 /*
3161 * Add possibly missing RelIdToTypeId entries related to TypeCacheHash
3162 * entries, marked as in-progress by lookup_type_cache(). It may happen
3163 * in case of an error or interruption during the lookup_type_cache() call.
3164 */
3165 static void
3166 finalize_in_progress_typentries(void)
3167 {
3168 int i;
3169
3170 for (i = 0; i < in_progress_list_len; i++)
3171 {
3172 TypeCacheEntry *typentry;
3173
3174 typentry = (TypeCacheEntry *) hash_search(TypeCacheHash,
3175 &in_progress_list[i],
3176 HASH_FIND, NULL);
3177 if (typentry)
3178 insert_rel_type_cache_if_needed(typentry);
3179 }
3180
3181 in_progress_list_len = 0;
3182 }
3183
3184 void
3185 AtEOXact_TypeCache(void)
3186 {
3187 finalize_in_progress_typentries();
3188 }
3189
3190 void
3191 AtEOSubXact_TypeCache(void)
3192 {
3193 finalize_in_progress_typentries();
3194 }