LCOV - code coverage report
Current view: top level - src/backend/utils/cache - typcache.c (source / functions) Hit Total Coverage
Test: PostgreSQL 17devel Lines: 787 891 88.3 %
Date: 2024-03-29 12:13:04 Functions: 53 55 96.4 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14