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

Generated by: LCOV version 1.14