LCOV - differential code coverage report
Current view: top level - src/backend/utils/cache - typcache.c (source / functions) Coverage Total Hit UBC GNC CBC DCB
Current: 77aeca80249c9e640c811e80633a2e334a9320de vs 38afc3dcb25c45b744d4025029ce0a6c90b7059f Lines: 88.7 % 1027 911 116 2 909 2
Current Date: 2026-07-25 19:08:27 +0900 Functions: 96.8 % 62 60 2 1 59
Baseline: lcov-20260725-baseline Branches: 70.0 % 724 507 217 507
Baseline Date: 2026-07-25 19:09:19 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 100.0 % 2 2 2
(30,360] days: 83.7 % 43 36 7 36
(360..) days: 88.9 % 982 873 109 873
Function coverage date bins:
(30,360] days: 100.0 % 4 4 4
(360..) days: 96.6 % 58 56 2 1 55
Branch coverage date bins:
(30,360] days: 42.9 % 28 12 16 12
(360..) days: 71.1 % 696 495 201 495

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

Generated by: LCOV version 2.0-1