LCOV - differential code coverage report
Current view: top level - src/backend/utils/cache - typcache.c (source / functions) Coverage Total Hit UNC LBC UIC UBC GBC GIC GNC CBC EUB ECB DUB DCB
Current: Differential Code Coverage HEAD vs 15 Lines: 88.2 % 926 817 2 10 29 68 8 220 589 30 217 3 1
Current Date: 2023-04-08 17:13:01 Functions: 96.4 % 55 53 2 24 1 28 24
Baseline: 15 Line coverage date bins:
Baseline Date: 2023-04-08 15:09:40 (120,180] days: 0.0 % 2 0 2
Legend: Lines: hit not hit (240..) days: 88.4 % 924 817 10 29 68 8 220 589 30 217
Function coverage date bins:
(240..) days: 67.1 % 79 53 2 24 1 28 24

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

Generated by: LCOV version v1.16-55-g56c0a2a