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

Generated by: LCOV version 1.13