LCOV - code coverage report
Current view: top level - src/backend/utils/cache - typcache.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 88.6 % 979 867
Test Date: 2026-07-03 19:57:34 Functions: 96.8 % 62 60
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 73.1 % 632 462

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

Generated by: LCOV version 2.0-1