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