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