LCOV - code coverage report
Current view: top level - src/backend/utils/cache - typcache.c (source / functions) Coverage Total Hit
Test: PostgreSQL 19beta1 Lines: 88.5 % 977 865
Test Date: 2026-06-13 17:16:46 Functions: 96.8 % 62 60
Legend: Lines:     hit not hit

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

Generated by: LCOV version 2.0-1