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