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