1 /*-------------------------------------------------------------------------
4 * Convenience routines for common queries in the system catalog cache.
6 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * src/backend/utils/cache/lsyscache.c
13 * Eventually, the index information should go through here, too.
14 *-------------------------------------------------------------------------
18 #include "access/hash.h"
19 #include "access/nbtree.h"
20 #include "bootstrap/bootstrap.h"
21 #include "catalog/pg_amop.h"
22 #include "catalog/pg_amproc.h"
23 #include "catalog/pg_collation.h"
24 #include "catalog/pg_constraint.h"
25 #include "catalog/pg_namespace.h"
26 #include "catalog/pg_opclass.h"
27 #include "catalog/pg_operator.h"
28 #include "catalog/pg_proc.h"
29 #include "catalog/pg_statistic.h"
30 #include "catalog/pg_type.h"
31 #include "miscadmin.h"
32 #include "nodes/makefuncs.h"
33 #include "utils/array.h"
34 #include "utils/builtins.h"
35 #include "utils/datum.h"
36 #include "utils/lsyscache.h"
37 #include "utils/syscache.h"
38 #include "utils/typcache.h"
40 /* Hook for plugins to get control in get_attavgwidth() */
41 get_attavgwidth_hook_type get_attavgwidth_hook = NULL;
44 /* ---------- AMOP CACHES ---------- */
49 * Return t iff operator 'opno' is in operator family 'opfamily'.
51 * This function only considers search operators, not ordering operators.
54 op_in_opfamily(Oid opno, Oid opfamily)
56 return SearchSysCacheExists3(AMOPOPID,
57 ObjectIdGetDatum(opno),
58 CharGetDatum(AMOP_SEARCH),
59 ObjectIdGetDatum(opfamily));
63 * get_op_opfamily_strategy
65 * Get the operator's strategy number within the specified opfamily,
66 * or 0 if it's not a member of the opfamily.
68 * This function only considers search operators, not ordering operators.
71 get_op_opfamily_strategy(Oid opno, Oid opfamily)
74 Form_pg_amop amop_tup;
77 tp = SearchSysCache3(AMOPOPID,
78 ObjectIdGetDatum(opno),
79 CharGetDatum(AMOP_SEARCH),
80 ObjectIdGetDatum(opfamily));
81 if (!HeapTupleIsValid(tp))
83 amop_tup = (Form_pg_amop) GETSTRUCT(tp);
84 result = amop_tup->amopstrategy;
90 * get_op_opfamily_sortfamily
92 * If the operator is an ordering operator within the specified opfamily,
93 * return its amopsortfamily OID; else return InvalidOid.
96 get_op_opfamily_sortfamily(Oid opno, Oid opfamily)
99 Form_pg_amop amop_tup;
102 tp = SearchSysCache3(AMOPOPID,
103 ObjectIdGetDatum(opno),
104 CharGetDatum(AMOP_ORDER),
105 ObjectIdGetDatum(opfamily));
106 if (!HeapTupleIsValid(tp))
108 amop_tup = (Form_pg_amop) GETSTRUCT(tp);
109 result = amop_tup->amopsortfamily;
115 * get_op_opfamily_properties
117 * Get the operator's strategy number and declared input data types
118 * within the specified opfamily.
120 * Caller should already have verified that opno is a member of opfamily,
121 * therefore we raise an error if the tuple is not found.
124 get_op_opfamily_properties(Oid opno, Oid opfamily, bool ordering_op,
130 Form_pg_amop amop_tup;
132 tp = SearchSysCache3(AMOPOPID,
133 ObjectIdGetDatum(opno),
134 CharGetDatum(ordering_op ? AMOP_ORDER : AMOP_SEARCH),
135 ObjectIdGetDatum(opfamily));
136 if (!HeapTupleIsValid(tp))
137 elog(ERROR, "operator %u is not a member of opfamily %u",
139 amop_tup = (Form_pg_amop) GETSTRUCT(tp);
140 *strategy = amop_tup->amopstrategy;
141 *lefttype = amop_tup->amoplefttype;
142 *righttype = amop_tup->amoprighttype;
147 * get_opfamily_member
148 * Get the OID of the operator that implements the specified strategy
149 * with the specified datatypes for the specified opfamily.
151 * Returns InvalidOid if there is no pg_amop entry for the given keys.
154 get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype,
158 Form_pg_amop amop_tup;
161 tp = SearchSysCache4(AMOPSTRATEGY,
162 ObjectIdGetDatum(opfamily),
163 ObjectIdGetDatum(lefttype),
164 ObjectIdGetDatum(righttype),
165 Int16GetDatum(strategy));
166 if (!HeapTupleIsValid(tp))
168 amop_tup = (Form_pg_amop) GETSTRUCT(tp);
169 result = amop_tup->amopopr;
175 * get_ordering_op_properties
176 * Given the OID of an ordering operator (a btree "<" or ">" operator),
177 * determine its opfamily, its declared input datatype, and its
178 * strategy number (BTLessStrategyNumber or BTGreaterStrategyNumber).
180 * Returns TRUE if successful, FALSE if no matching pg_amop entry exists.
181 * (This indicates that the operator is not a valid ordering operator.)
183 * Note: the operator could be registered in multiple families, for example
184 * if someone were to build a "reverse sort" opfamily. This would result in
185 * uncertainty as to whether "ORDER BY USING op" would default to NULLS FIRST
186 * or NULLS LAST, as well as inefficient planning due to failure to match up
187 * pathkeys that should be the same. So we want a determinate result here.
188 * Because of the way the syscache search works, we'll use the interpretation
189 * associated with the opfamily with smallest OID, which is probably
190 * determinate enough. Since there is no longer any particularly good reason
191 * to build reverse-sort opfamilies, it doesn't seem worth expending any
192 * additional effort on ensuring consistency.
195 get_ordering_op_properties(Oid opno,
196 Oid *opfamily, Oid *opcintype, int16 *strategy)
202 /* ensure outputs are initialized on failure */
203 *opfamily = InvalidOid;
204 *opcintype = InvalidOid;
208 * Search pg_amop to see if the target operator is registered as the "<"
209 * or ">" operator of any btree opfamily.
211 catlist = SearchSysCacheList1(AMOPOPID, ObjectIdGetDatum(opno));
213 for (i = 0; i < catlist->n_members; i++)
215 HeapTuple tuple = &catlist->members[i]->tuple;
216 Form_pg_amop aform = (Form_pg_amop) GETSTRUCT(tuple);
219 if (aform->amopmethod != BTREE_AM_OID)
222 if (aform->amopstrategy == BTLessStrategyNumber ||
223 aform->amopstrategy == BTGreaterStrategyNumber)
225 /* Found it ... should have consistent input types */
226 if (aform->amoplefttype == aform->amoprighttype)
228 /* Found a suitable opfamily, return info */
229 *opfamily = aform->amopfamily;
230 *opcintype = aform->amoplefttype;
231 *strategy = aform->amopstrategy;
238 ReleaseSysCacheList(catlist);
244 * get_compare_function_for_ordering_op
245 * Get the OID of the datatype-specific btree comparison function
246 * associated with an ordering operator (a "<" or ">" operator).
248 * *cmpfunc receives the comparison function OID.
249 * *reverse is set FALSE if the operator is "<", TRUE if it's ">"
250 * (indicating the comparison result must be negated before use).
252 * Returns TRUE if successful, FALSE if no btree function can be found.
253 * (This indicates that the operator is not a valid ordering operator.)
256 get_compare_function_for_ordering_op(Oid opno, Oid *cmpfunc, bool *reverse)
262 /* Find the operator in pg_amop */
263 if (get_ordering_op_properties(opno,
264 &opfamily, &opcintype, &strategy))
266 /* Found a suitable opfamily, get matching support function */
267 *cmpfunc = get_opfamily_proc(opfamily,
272 if (!OidIsValid(*cmpfunc)) /* should not happen */
273 elog(ERROR, "missing support function %d(%u,%u) in opfamily %u",
274 BTORDER_PROC, opcintype, opcintype, opfamily);
275 *reverse = (strategy == BTGreaterStrategyNumber);
279 /* ensure outputs are set on failure */
280 *cmpfunc = InvalidOid;
287 * get_equality_op_for_ordering_op
288 * Get the OID of the datatype-specific btree equality operator
289 * associated with an ordering operator (a "<" or ">" operator).
291 * If "reverse" isn't NULL, also set *reverse to FALSE if the operator is "<",
294 * Returns InvalidOid if no matching equality operator can be found.
295 * (This indicates that the operator is not a valid ordering operator.)
298 get_equality_op_for_ordering_op(Oid opno, bool *reverse)
300 Oid result = InvalidOid;
305 /* Find the operator in pg_amop */
306 if (get_ordering_op_properties(opno,
307 &opfamily, &opcintype, &strategy))
309 /* Found a suitable opfamily, get matching equality operator */
310 result = get_opfamily_member(opfamily,
313 BTEqualStrategyNumber);
315 *reverse = (strategy == BTGreaterStrategyNumber);
322 * get_ordering_op_for_equality_op
323 * Get the OID of a datatype-specific btree ordering operator
324 * associated with an equality operator. (If there are multiple
325 * possibilities, assume any one will do.)
327 * This function is used when we have to sort data before unique-ifying,
328 * and don't much care which sorting op is used as long as it's compatible
329 * with the intended equality operator. Since we need a sorting operator,
330 * it should be single-data-type even if the given operator is cross-type.
331 * The caller specifies whether to find an op for the LHS or RHS data type.
333 * Returns InvalidOid if no matching ordering operator can be found.
336 get_ordering_op_for_equality_op(Oid opno, bool use_lhs_type)
338 Oid result = InvalidOid;
343 * Search pg_amop to see if the target operator is registered as the "="
344 * operator of any btree opfamily.
346 catlist = SearchSysCacheList1(AMOPOPID, ObjectIdGetDatum(opno));
348 for (i = 0; i < catlist->n_members; i++)
350 HeapTuple tuple = &catlist->members[i]->tuple;
351 Form_pg_amop aform = (Form_pg_amop) GETSTRUCT(tuple);
354 if (aform->amopmethod != BTREE_AM_OID)
357 if (aform->amopstrategy == BTEqualStrategyNumber)
359 /* Found a suitable opfamily, get matching ordering operator */
362 typid = use_lhs_type ? aform->amoplefttype : aform->amoprighttype;
363 result = get_opfamily_member(aform->amopfamily,
365 BTLessStrategyNumber);
366 if (OidIsValid(result))
368 /* failure probably shouldn't happen, but keep looking if so */
372 ReleaseSysCacheList(catlist);
378 * get_mergejoin_opfamilies
379 * Given a putatively mergejoinable operator, return a list of the OIDs
380 * of the btree opfamilies in which it represents equality.
382 * It is possible (though at present unusual) for an operator to be equality
383 * in more than one opfamily, hence the result is a list. This also lets us
384 * return NIL if the operator is not found in any opfamilies.
386 * The planner currently uses simple equal() tests to compare the lists
387 * returned by this function, which makes the list order relevant, though
388 * strictly speaking it should not be. Because of the way syscache list
389 * searches are handled, in normal operation the result will be sorted by OID
390 * so everything works fine. If running with system index usage disabled,
391 * the result ordering is unspecified and hence the planner might fail to
392 * recognize optimization opportunities ... but that's hardly a scenario in
393 * which performance is good anyway, so there's no point in expending code
394 * or cycles here to guarantee the ordering in that case.
397 get_mergejoin_opfamilies(Oid opno)
404 * Search pg_amop to see if the target operator is registered as the "="
405 * operator of any btree opfamily.
407 catlist = SearchSysCacheList1(AMOPOPID, ObjectIdGetDatum(opno));
409 for (i = 0; i < catlist->n_members; i++)
411 HeapTuple tuple = &catlist->members[i]->tuple;
412 Form_pg_amop aform = (Form_pg_amop) GETSTRUCT(tuple);
414 /* must be btree equality */
415 if (aform->amopmethod == BTREE_AM_OID &&
416 aform->amopstrategy == BTEqualStrategyNumber)
417 result = lappend_oid(result, aform->amopfamily);
420 ReleaseSysCacheList(catlist);
426 * get_compatible_hash_operators
427 * Get the OID(s) of hash equality operator(s) compatible with the given
428 * operator, but operating on its LHS and/or RHS datatype.
430 * An operator for the LHS type is sought and returned into *lhs_opno if
431 * lhs_opno isn't NULL. Similarly, an operator for the RHS type is sought
432 * and returned into *rhs_opno if rhs_opno isn't NULL.
434 * If the given operator is not cross-type, the results should be the same
435 * operator, but in cross-type situations they will be different.
437 * Returns true if able to find the requested operator(s), false if not.
438 * (This indicates that the operator should not have been marked oprcanhash.)
441 get_compatible_hash_operators(Oid opno,
442 Oid *lhs_opno, Oid *rhs_opno)
448 /* Ensure output args are initialized on failure */
450 *lhs_opno = InvalidOid;
452 *rhs_opno = InvalidOid;
455 * Search pg_amop to see if the target operator is registered as the "="
456 * operator of any hash opfamily. If the operator is registered in
457 * multiple opfamilies, assume we can use any one.
459 catlist = SearchSysCacheList1(AMOPOPID, ObjectIdGetDatum(opno));
461 for (i = 0; i < catlist->n_members; i++)
463 HeapTuple tuple = &catlist->members[i]->tuple;
464 Form_pg_amop aform = (Form_pg_amop) GETSTRUCT(tuple);
466 if (aform->amopmethod == HASH_AM_OID &&
467 aform->amopstrategy == HTEqualStrategyNumber)
469 /* No extra lookup needed if given operator is single-type */
470 if (aform->amoplefttype == aform->amoprighttype)
481 * Get the matching single-type operator(s). Failure probably
482 * shouldn't happen --- it implies a bogus opfamily --- but
483 * continue looking if so.
487 *lhs_opno = get_opfamily_member(aform->amopfamily,
490 HTEqualStrategyNumber);
491 if (!OidIsValid(*lhs_opno))
493 /* Matching LHS found, done if caller doesn't want RHS */
502 *rhs_opno = get_opfamily_member(aform->amopfamily,
503 aform->amoprighttype,
504 aform->amoprighttype,
505 HTEqualStrategyNumber);
506 if (!OidIsValid(*rhs_opno))
508 /* Forget any LHS operator from this opfamily */
510 *lhs_opno = InvalidOid;
513 /* Matching RHS found, so done */
520 ReleaseSysCacheList(catlist);
526 * get_op_hash_functions
527 * Get the OID(s) of hash support function(s) compatible with the given
528 * operator, operating on its LHS and/or RHS datatype as required.
530 * A function for the LHS type is sought and returned into *lhs_procno if
531 * lhs_procno isn't NULL. Similarly, a function for the RHS type is sought
532 * and returned into *rhs_procno if rhs_procno isn't NULL.
534 * If the given operator is not cross-type, the results should be the same
535 * function, but in cross-type situations they will be different.
537 * Returns true if able to find the requested function(s), false if not.
538 * (This indicates that the operator should not have been marked oprcanhash.)
541 get_op_hash_functions(Oid opno,
542 RegProcedure *lhs_procno, RegProcedure *rhs_procno)
548 /* Ensure output args are initialized on failure */
550 *lhs_procno = InvalidOid;
552 *rhs_procno = InvalidOid;
555 * Search pg_amop to see if the target operator is registered as the "="
556 * operator of any hash opfamily. If the operator is registered in
557 * multiple opfamilies, assume we can use any one.
559 catlist = SearchSysCacheList1(AMOPOPID, ObjectIdGetDatum(opno));
561 for (i = 0; i < catlist->n_members; i++)
563 HeapTuple tuple = &catlist->members[i]->tuple;
564 Form_pg_amop aform = (Form_pg_amop) GETSTRUCT(tuple);
566 if (aform->amopmethod == HASH_AM_OID &&
567 aform->amopstrategy == HTEqualStrategyNumber)
570 * Get the matching support function(s). Failure probably
571 * shouldn't happen --- it implies a bogus opfamily --- but
572 * continue looking if so.
576 *lhs_procno = get_opfamily_proc(aform->amopfamily,
580 if (!OidIsValid(*lhs_procno))
582 /* Matching LHS found, done if caller doesn't want RHS */
588 /* Only one lookup needed if given operator is single-type */
589 if (aform->amoplefttype == aform->amoprighttype)
591 *rhs_procno = *lhs_procno;
598 *rhs_procno = get_opfamily_proc(aform->amopfamily,
599 aform->amoprighttype,
600 aform->amoprighttype,
602 if (!OidIsValid(*rhs_procno))
604 /* Forget any LHS function from this opfamily */
606 *lhs_procno = InvalidOid;
609 /* Matching RHS found, so done */
616 ReleaseSysCacheList(catlist);
622 * get_op_btree_interpretation
623 * Given an operator's OID, find out which btree opfamilies it belongs to,
624 * and what strategy number it has within each one. The results are
625 * returned as an OID list and a parallel integer list.
627 * In addition to the normal btree operators, we consider a <> operator to be
628 * a "member" of an opfamily if its negator is an equality operator of the
629 * opfamily. ROWCOMPARE_NE is returned as the strategy number for this case.
632 get_op_btree_interpretation(Oid opno, List **opfamilies, List **opstrats)
642 * Find all the pg_amop entries containing the operator.
644 catlist = SearchSysCacheList1(AMOPOPID, ObjectIdGetDatum(opno));
647 * If we can't find any opfamily containing the op, perhaps it is a <>
648 * operator. See if it has a negator that is in an opfamily.
651 if (catlist->n_members == 0)
653 Oid op_negator = get_negator(opno);
655 if (OidIsValid(op_negator))
658 ReleaseSysCacheList(catlist);
659 catlist = SearchSysCacheList1(AMOPOPID,
660 ObjectIdGetDatum(op_negator));
664 /* Now search the opfamilies */
665 for (i = 0; i < catlist->n_members; i++)
667 HeapTuple op_tuple = &catlist->members[i]->tuple;
668 Form_pg_amop op_form = (Form_pg_amop) GETSTRUCT(op_tuple);
670 StrategyNumber op_strategy;
673 if (op_form->amopmethod != BTREE_AM_OID)
676 /* Get the operator's btree strategy number */
677 opfamily_id = op_form->amopfamily;
678 op_strategy = (StrategyNumber) op_form->amopstrategy;
679 Assert(op_strategy >= 1 && op_strategy <= 5);
683 /* Only consider negators that are = */
684 if (op_strategy != BTEqualStrategyNumber)
686 op_strategy = ROWCOMPARE_NE;
689 *opfamilies = lappend_oid(*opfamilies, opfamily_id);
690 *opstrats = lappend_int(*opstrats, op_strategy);
693 ReleaseSysCacheList(catlist);
697 * equality_ops_are_compatible
698 * Return TRUE if the two given equality operators have compatible
701 * This is trivially true if they are the same operator. Otherwise,
702 * we look to see if they can be found in the same btree or hash opfamily.
703 * Either finding allows us to assume that they have compatible notions
704 * of equality. (The reason we need to do these pushups is that one might
705 * be a cross-type operator; for instance int24eq vs int4eq.)
708 equality_ops_are_compatible(Oid opno1, Oid opno2)
714 /* Easy if they're the same operator */
719 * We search through all the pg_amop entries for opno1.
721 catlist = SearchSysCacheList1(AMOPOPID, ObjectIdGetDatum(opno1));
724 for (i = 0; i < catlist->n_members; i++)
726 HeapTuple op_tuple = &catlist->members[i]->tuple;
727 Form_pg_amop op_form = (Form_pg_amop) GETSTRUCT(op_tuple);
729 /* must be btree or hash */
730 if (op_form->amopmethod == BTREE_AM_OID ||
731 op_form->amopmethod == HASH_AM_OID)
733 if (op_in_opfamily(opno2, op_form->amopfamily))
741 ReleaseSysCacheList(catlist);
747 /* ---------- AMPROC CACHES ---------- */
751 * Get the OID of the specified support function
752 * for the specified opfamily and datatypes.
754 * Returns InvalidOid if there is no pg_amproc entry for the given keys.
757 get_opfamily_proc(Oid opfamily, Oid lefttype, Oid righttype, int16 procnum)
760 Form_pg_amproc amproc_tup;
763 tp = SearchSysCache4(AMPROCNUM,
764 ObjectIdGetDatum(opfamily),
765 ObjectIdGetDatum(lefttype),
766 ObjectIdGetDatum(righttype),
767 Int16GetDatum(procnum));
768 if (!HeapTupleIsValid(tp))
770 amproc_tup = (Form_pg_amproc) GETSTRUCT(tp);
771 result = amproc_tup->amproc;
777 /* ---------- ATTRIBUTE CACHES ---------- */
781 * Given the relation id and the attribute number,
782 * return the "attname" field from the attribute relation.
784 * Note: returns a palloc'd copy of the string, or NULL if no such attribute.
787 get_attname(Oid relid, AttrNumber attnum)
791 tp = SearchSysCache2(ATTNUM,
792 ObjectIdGetDatum(relid),
793 Int16GetDatum(attnum));
794 if (HeapTupleIsValid(tp))
796 Form_pg_attribute att_tup = (Form_pg_attribute) GETSTRUCT(tp);
799 result = pstrdup(NameStr(att_tup->attname));
808 * get_relid_attribute_name
810 * Same as above routine get_attname(), except that error
811 * is handled by elog() instead of returning NULL.
814 get_relid_attribute_name(Oid relid, AttrNumber attnum)
818 attname = get_attname(relid, attnum);
820 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
828 * Given the relation id and the attribute name,
829 * return the "attnum" field from the attribute relation.
831 * Returns InvalidAttrNumber if the attr doesn't exist (or is dropped).
834 get_attnum(Oid relid, const char *attname)
838 tp = SearchSysCacheAttName(relid, attname);
839 if (HeapTupleIsValid(tp))
841 Form_pg_attribute att_tup = (Form_pg_attribute) GETSTRUCT(tp);
844 result = att_tup->attnum;
849 return InvalidAttrNumber;
855 * Given the relation OID and the attribute number with the relation,
856 * return the attribute type OID.
859 get_atttype(Oid relid, AttrNumber attnum)
863 tp = SearchSysCache2(ATTNUM,
864 ObjectIdGetDatum(relid),
865 Int16GetDatum(attnum));
866 if (HeapTupleIsValid(tp))
868 Form_pg_attribute att_tup = (Form_pg_attribute) GETSTRUCT(tp);
871 result = att_tup->atttypid;
882 * Given the relation id and the attribute number,
883 * return the "atttypmod" field from the attribute relation.
886 get_atttypmod(Oid relid, AttrNumber attnum)
890 tp = SearchSysCache2(ATTNUM,
891 ObjectIdGetDatum(relid),
892 Int16GetDatum(attnum));
893 if (HeapTupleIsValid(tp))
895 Form_pg_attribute att_tup = (Form_pg_attribute) GETSTRUCT(tp);
898 result = att_tup->atttypmod;
907 * get_atttypetypmodcoll
909 * A three-fer: given the relation id and the attribute number,
910 * fetch atttypid, atttypmod, and attcollation in a single cache lookup.
912 * Unlike the otherwise-similar get_atttype/get_atttypmod, this routine
913 * raises an error if it can't obtain the information.
916 get_atttypetypmodcoll(Oid relid, AttrNumber attnum,
917 Oid *typid, int32 *typmod, Oid *collid)
920 Form_pg_attribute att_tup;
922 tp = SearchSysCache2(ATTNUM,
923 ObjectIdGetDatum(relid),
924 Int16GetDatum(attnum));
925 if (!HeapTupleIsValid(tp))
926 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
928 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
930 *typid = att_tup->atttypid;
931 *typmod = att_tup->atttypmod;
932 *collid = att_tup->attcollation;
936 /* ---------- COLLATION CACHE ---------- */
940 * Returns the name of a given pg_collation entry.
942 * Returns a palloc'd copy of the string, or NULL if no such constraint.
944 * NOTE: since collation name is not unique, be wary of code that uses this
945 * for anything except preparing error messages.
948 get_collation_name(Oid colloid)
952 tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(colloid));
953 if (HeapTupleIsValid(tp))
955 Form_pg_collation colltup = (Form_pg_collation) GETSTRUCT(tp);
958 result = pstrdup(NameStr(colltup->collname));
966 /* ---------- CONSTRAINT CACHE ---------- */
969 * get_constraint_name
970 * Returns the name of a given pg_constraint entry.
972 * Returns a palloc'd copy of the string, or NULL if no such constraint.
974 * NOTE: since constraint name is not unique, be wary of code that uses this
975 * for anything except preparing error messages.
978 get_constraint_name(Oid conoid)
982 tp = SearchSysCache1(CONSTROID, ObjectIdGetDatum(conoid));
983 if (HeapTupleIsValid(tp))
985 Form_pg_constraint contup = (Form_pg_constraint) GETSTRUCT(tp);
988 result = pstrdup(NameStr(contup->conname));
996 /* ---------- OPCLASS CACHE ---------- */
1001 * Returns the OID of the operator family the opclass belongs to.
1004 get_opclass_family(Oid opclass)
1007 Form_pg_opclass cla_tup;
1010 tp = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1011 if (!HeapTupleIsValid(tp))
1012 elog(ERROR, "cache lookup failed for opclass %u", opclass);
1013 cla_tup = (Form_pg_opclass) GETSTRUCT(tp);
1015 result = cla_tup->opcfamily;
1016 ReleaseSysCache(tp);
1021 * get_opclass_input_type
1023 * Returns the OID of the datatype the opclass indexes.
1026 get_opclass_input_type(Oid opclass)
1029 Form_pg_opclass cla_tup;
1032 tp = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1033 if (!HeapTupleIsValid(tp))
1034 elog(ERROR, "cache lookup failed for opclass %u", opclass);
1035 cla_tup = (Form_pg_opclass) GETSTRUCT(tp);
1037 result = cla_tup->opcintype;
1038 ReleaseSysCache(tp);
1042 /* ---------- OPERATOR CACHE ---------- */
1047 * Returns the regproc id of the routine used to implement an
1048 * operator given the operator oid.
1051 get_opcode(Oid opno)
1055 tp = SearchSysCache1(OPEROID, ObjectIdGetDatum(opno));
1056 if (HeapTupleIsValid(tp))
1058 Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
1059 RegProcedure result;
1061 result = optup->oprcode;
1062 ReleaseSysCache(tp);
1066 return (RegProcedure) InvalidOid;
1071 * returns the name of the operator with the given opno
1073 * Note: returns a palloc'd copy of the string, or NULL if no such operator.
1076 get_opname(Oid opno)
1080 tp = SearchSysCache1(OPEROID, ObjectIdGetDatum(opno));
1081 if (HeapTupleIsValid(tp))
1083 Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
1086 result = pstrdup(NameStr(optup->oprname));
1087 ReleaseSysCache(tp);
1097 * Returns the left and right input datatypes for an operator
1098 * (InvalidOid if not relevant).
1101 op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
1104 Form_pg_operator optup;
1106 tp = SearchSysCache1(OPEROID, ObjectIdGetDatum(opno));
1107 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
1108 elog(ERROR, "cache lookup failed for operator %u", opno);
1109 optup = (Form_pg_operator) GETSTRUCT(tp);
1110 *lefttype = optup->oprleft;
1111 *righttype = optup->oprright;
1112 ReleaseSysCache(tp);
1118 * Returns true if the operator is potentially mergejoinable. (The planner
1119 * will fail to find any mergejoin plans unless there are suitable btree
1120 * opfamily entries for this operator and associated sortops. The pg_operator
1121 * flag is just a hint to tell the planner whether to bother looking.)
1123 * In some cases (currently only array_eq), mergejoinability depends on the
1124 * specific input data type the operator is invoked for, so that must be
1125 * passed as well. We currently assume that only one input's type is needed
1126 * to check this --- by convention, pass the left input's data type.
1129 op_mergejoinable(Oid opno, Oid inputtype)
1132 bool result = false;
1134 if (opno == ARRAY_EQ_OP)
1137 * For array_eq, can sort if element type has a default btree opclass.
1138 * We could use GetDefaultOpClass, but that's fairly expensive and not
1139 * cached, so let's use the typcache instead.
1141 Oid elem_type = get_base_element_type(inputtype);
1143 if (OidIsValid(elem_type))
1145 TypeCacheEntry *typentry;
1147 typentry = lookup_type_cache(elem_type, TYPECACHE_BTREE_OPFAMILY);
1148 if (OidIsValid(typentry->btree_opf))
1154 /* For all other operators, rely on pg_operator.oprcanmerge */
1155 tp = SearchSysCache1(OPEROID, ObjectIdGetDatum(opno));
1156 if (HeapTupleIsValid(tp))
1158 Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
1160 result = optup->oprcanmerge;
1161 ReleaseSysCache(tp);
1170 * Returns true if the operator is hashjoinable. (There must be a suitable
1171 * hash opfamily entry for this operator if it is so marked.)
1173 * In some cases (currently only array_eq), hashjoinability depends on the
1174 * specific input data type the operator is invoked for, so that must be
1175 * passed as well. We currently assume that only one input's type is needed
1176 * to check this --- by convention, pass the left input's data type.
1179 op_hashjoinable(Oid opno, Oid inputtype)
1182 bool result = false;
1184 if (opno == ARRAY_EQ_OP)
1186 /* For array_eq, can hash if element type has a default hash opclass */
1187 Oid elem_type = get_base_element_type(inputtype);
1189 if (OidIsValid(elem_type))
1191 TypeCacheEntry *typentry;
1193 typentry = lookup_type_cache(elem_type, TYPECACHE_HASH_OPFAMILY);
1194 if (OidIsValid(typentry->hash_opf))
1200 /* For all other operators, rely on pg_operator.oprcanhash */
1201 tp = SearchSysCache1(OPEROID, ObjectIdGetDatum(opno));
1202 if (HeapTupleIsValid(tp))
1204 Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
1206 result = optup->oprcanhash;
1207 ReleaseSysCache(tp);
1216 * Get the proisstrict flag for the operator's underlying function.
1221 RegProcedure funcid = get_opcode(opno);
1223 if (funcid == (RegProcedure) InvalidOid)
1224 elog(ERROR, "operator %u does not exist", opno);
1226 return func_strict((Oid) funcid);
1232 * Get the provolatile flag for the operator's underlying function.
1235 op_volatile(Oid opno)
1237 RegProcedure funcid = get_opcode(opno);
1239 if (funcid == (RegProcedure) InvalidOid)
1240 elog(ERROR, "operator %u does not exist", opno);
1242 return func_volatile((Oid) funcid);
1248 * Returns the corresponding commutator of an operator.
1251 get_commutator(Oid opno)
1255 tp = SearchSysCache1(OPEROID, ObjectIdGetDatum(opno));
1256 if (HeapTupleIsValid(tp))
1258 Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
1261 result = optup->oprcom;
1262 ReleaseSysCache(tp);
1272 * Returns the corresponding negator of an operator.
1275 get_negator(Oid opno)
1279 tp = SearchSysCache1(OPEROID, ObjectIdGetDatum(opno));
1280 if (HeapTupleIsValid(tp))
1282 Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
1285 result = optup->oprnegate;
1286 ReleaseSysCache(tp);
1296 * Returns procedure id for computing selectivity of an operator.
1299 get_oprrest(Oid opno)
1303 tp = SearchSysCache1(OPEROID, ObjectIdGetDatum(opno));
1304 if (HeapTupleIsValid(tp))
1306 Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
1307 RegProcedure result;
1309 result = optup->oprrest;
1310 ReleaseSysCache(tp);
1314 return (RegProcedure) InvalidOid;
1320 * Returns procedure id for computing selectivity of a join.
1323 get_oprjoin(Oid opno)
1327 tp = SearchSysCache1(OPEROID, ObjectIdGetDatum(opno));
1328 if (HeapTupleIsValid(tp))
1330 Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
1331 RegProcedure result;
1333 result = optup->oprjoin;
1334 ReleaseSysCache(tp);
1338 return (RegProcedure) InvalidOid;
1341 /* ---------- FUNCTION CACHE ---------- */
1345 * returns the name of the function with the given funcid
1347 * Note: returns a palloc'd copy of the string, or NULL if no such function.
1350 get_func_name(Oid funcid)
1354 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1355 if (HeapTupleIsValid(tp))
1357 Form_pg_proc functup = (Form_pg_proc) GETSTRUCT(tp);
1360 result = pstrdup(NameStr(functup->proname));
1361 ReleaseSysCache(tp);
1369 * get_func_namespace
1371 * Returns the pg_namespace OID associated with a given function.
1374 get_func_namespace(Oid funcid)
1378 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1379 if (HeapTupleIsValid(tp))
1381 Form_pg_proc functup = (Form_pg_proc) GETSTRUCT(tp);
1384 result = functup->pronamespace;
1385 ReleaseSysCache(tp);
1394 * Given procedure id, return the function's result type.
1397 get_func_rettype(Oid funcid)
1402 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1403 if (!HeapTupleIsValid(tp))
1404 elog(ERROR, "cache lookup failed for function %u", funcid);
1406 result = ((Form_pg_proc) GETSTRUCT(tp))->prorettype;
1407 ReleaseSysCache(tp);
1413 * Given procedure id, return the number of arguments.
1416 get_func_nargs(Oid funcid)
1421 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1422 if (!HeapTupleIsValid(tp))
1423 elog(ERROR, "cache lookup failed for function %u", funcid);
1425 result = ((Form_pg_proc) GETSTRUCT(tp))->pronargs;
1426 ReleaseSysCache(tp);
1431 * get_func_signature
1432 * Given procedure id, return the function's argument and result types.
1433 * (The return value is the result type.)
1435 * The arguments are returned as a palloc'd array.
1438 get_func_signature(Oid funcid, Oid **argtypes, int *nargs)
1441 Form_pg_proc procstruct;
1444 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1445 if (!HeapTupleIsValid(tp))
1446 elog(ERROR, "cache lookup failed for function %u", funcid);
1448 procstruct = (Form_pg_proc) GETSTRUCT(tp);
1450 result = procstruct->prorettype;
1451 *nargs = (int) procstruct->pronargs;
1452 Assert(*nargs == procstruct->proargtypes.dim1);
1453 *argtypes = (Oid *) palloc(*nargs * sizeof(Oid));
1454 memcpy(*argtypes, procstruct->proargtypes.values, *nargs * sizeof(Oid));
1456 ReleaseSysCache(tp);
1462 * Given procedure id, return the function's proretset flag.
1465 get_func_retset(Oid funcid)
1470 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1471 if (!HeapTupleIsValid(tp))
1472 elog(ERROR, "cache lookup failed for function %u", funcid);
1474 result = ((Form_pg_proc) GETSTRUCT(tp))->proretset;
1475 ReleaseSysCache(tp);
1481 * Given procedure id, return the function's proisstrict flag.
1484 func_strict(Oid funcid)
1489 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1490 if (!HeapTupleIsValid(tp))
1491 elog(ERROR, "cache lookup failed for function %u", funcid);
1493 result = ((Form_pg_proc) GETSTRUCT(tp))->proisstrict;
1494 ReleaseSysCache(tp);
1500 * Given procedure id, return the function's provolatile flag.
1503 func_volatile(Oid funcid)
1508 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1509 if (!HeapTupleIsValid(tp))
1510 elog(ERROR, "cache lookup failed for function %u", funcid);
1512 result = ((Form_pg_proc) GETSTRUCT(tp))->provolatile;
1513 ReleaseSysCache(tp);
1519 * Given procedure id, return the function's procost field.
1522 get_func_cost(Oid funcid)
1527 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1528 if (!HeapTupleIsValid(tp))
1529 elog(ERROR, "cache lookup failed for function %u", funcid);
1531 result = ((Form_pg_proc) GETSTRUCT(tp))->procost;
1532 ReleaseSysCache(tp);
1538 * Given procedure id, return the function's prorows field.
1541 get_func_rows(Oid funcid)
1546 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1547 if (!HeapTupleIsValid(tp))
1548 elog(ERROR, "cache lookup failed for function %u", funcid);
1550 result = ((Form_pg_proc) GETSTRUCT(tp))->prorows;
1551 ReleaseSysCache(tp);
1555 /* ---------- RELATION CACHE ---------- */
1559 * Given name and namespace of a relation, look up the OID.
1561 * Returns InvalidOid if there is no such relation.
1564 get_relname_relid(const char *relname, Oid relnamespace)
1566 return GetSysCacheOid2(RELNAMENSP,
1567 PointerGetDatum(relname),
1568 ObjectIdGetDatum(relnamespace));
1575 * Returns the number of attributes for a given relation.
1578 get_relnatts(Oid relid)
1582 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
1583 if (HeapTupleIsValid(tp))
1585 Form_pg_class reltup = (Form_pg_class) GETSTRUCT(tp);
1588 result = reltup->relnatts;
1589 ReleaseSysCache(tp);
1593 return InvalidAttrNumber;
1599 * Returns the name of a given relation.
1601 * Returns a palloc'd copy of the string, or NULL if no such relation.
1603 * NOTE: since relation name is not unique, be wary of code that uses this
1604 * for anything except preparing error messages.
1607 get_rel_name(Oid relid)
1611 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
1612 if (HeapTupleIsValid(tp))
1614 Form_pg_class reltup = (Form_pg_class) GETSTRUCT(tp);
1617 result = pstrdup(NameStr(reltup->relname));
1618 ReleaseSysCache(tp);
1628 * Returns the pg_namespace OID associated with a given relation.
1631 get_rel_namespace(Oid relid)
1635 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
1636 if (HeapTupleIsValid(tp))
1638 Form_pg_class reltup = (Form_pg_class) GETSTRUCT(tp);
1641 result = reltup->relnamespace;
1642 ReleaseSysCache(tp);
1652 * Returns the pg_type OID associated with a given relation.
1654 * Note: not all pg_class entries have associated pg_type OIDs; so be
1655 * careful to check for InvalidOid result.
1658 get_rel_type_id(Oid relid)
1662 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
1663 if (HeapTupleIsValid(tp))
1665 Form_pg_class reltup = (Form_pg_class) GETSTRUCT(tp);
1668 result = reltup->reltype;
1669 ReleaseSysCache(tp);
1679 * Returns the relkind associated with a given relation.
1682 get_rel_relkind(Oid relid)
1686 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
1687 if (HeapTupleIsValid(tp))
1689 Form_pg_class reltup = (Form_pg_class) GETSTRUCT(tp);
1692 result = reltup->relkind;
1693 ReleaseSysCache(tp);
1701 * get_rel_tablespace
1703 * Returns the pg_tablespace OID associated with a given relation.
1705 * Note: InvalidOid might mean either that we couldn't find the relation,
1706 * or that it is in the database's default tablespace.
1709 get_rel_tablespace(Oid relid)
1713 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
1714 if (HeapTupleIsValid(tp))
1716 Form_pg_class reltup = (Form_pg_class) GETSTRUCT(tp);
1719 result = reltup->reltablespace;
1720 ReleaseSysCache(tp);
1728 /* ---------- TYPE CACHE ---------- */
1733 * Given the type OID, determine whether the type is defined
1734 * (if not, it's only a shell).
1737 get_typisdefined(Oid typid)
1741 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
1742 if (HeapTupleIsValid(tp))
1744 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
1747 result = typtup->typisdefined;
1748 ReleaseSysCache(tp);
1758 * Given the type OID, return the length of the type.
1761 get_typlen(Oid typid)
1765 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
1766 if (HeapTupleIsValid(tp))
1768 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
1771 result = typtup->typlen;
1772 ReleaseSysCache(tp);
1782 * Given the type OID, determine whether the type is returned by value or
1783 * not. Returns true if by value, false if by reference.
1786 get_typbyval(Oid typid)
1790 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
1791 if (HeapTupleIsValid(tp))
1793 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
1796 result = typtup->typbyval;
1797 ReleaseSysCache(tp);
1807 * A two-fer: given the type OID, return both typlen and typbyval.
1809 * Since both pieces of info are needed to know how to copy a Datum,
1810 * many places need both. Might as well get them with one cache lookup
1811 * instead of two. Also, this routine raises an error instead of
1812 * returning a bogus value when given a bad type OID.
1815 get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
1818 Form_pg_type typtup;
1820 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
1821 if (!HeapTupleIsValid(tp))
1822 elog(ERROR, "cache lookup failed for type %u", typid);
1823 typtup = (Form_pg_type) GETSTRUCT(tp);
1824 *typlen = typtup->typlen;
1825 *typbyval = typtup->typbyval;
1826 ReleaseSysCache(tp);
1830 * get_typlenbyvalalign
1832 * A three-fer: given the type OID, return typlen, typbyval, typalign.
1835 get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval,
1839 Form_pg_type typtup;
1841 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
1842 if (!HeapTupleIsValid(tp))
1843 elog(ERROR, "cache lookup failed for type %u", typid);
1844 typtup = (Form_pg_type) GETSTRUCT(tp);
1845 *typlen = typtup->typlen;
1846 *typbyval = typtup->typbyval;
1847 *typalign = typtup->typalign;
1848 ReleaseSysCache(tp);
1853 * Given a pg_type row, select the type OID to pass to I/O functions
1855 * Formerly, all I/O functions were passed pg_type.typelem as their second
1856 * parameter, but we now have a more complex rule about what to pass.
1857 * This knowledge is intended to be centralized here --- direct references
1858 * to typelem elsewhere in the code are wrong, if they are associated with
1859 * I/O calls and not with actual subscripting operations! (But see
1860 * bootstrap.c's boot_get_type_io_data() if you need to change this.)
1862 * As of PostgreSQL 8.1, output functions receive only the value itself
1863 * and not any auxiliary parameters, so the name of this routine is now
1864 * a bit of a misnomer ... it should be getTypeInputParam.
1867 getTypeIOParam(HeapTuple typeTuple)
1869 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTuple);
1872 * Array types get their typelem as parameter; everybody else gets their
1873 * own type OID as parameter. (As of 8.2, domains must get their own OID
1874 * even if their base type is an array.)
1876 if (typeStruct->typtype == TYPTYPE_BASE && OidIsValid(typeStruct->typelem))
1877 return typeStruct->typelem;
1879 return HeapTupleGetOid(typeTuple);
1885 * A six-fer: given the type OID, return typlen, typbyval, typalign,
1886 * typdelim, typioparam, and IO function OID. The IO function
1887 * returned is controlled by IOFuncSelector
1890 get_type_io_data(Oid typid,
1891 IOFuncSelector which_func,
1899 HeapTuple typeTuple;
1900 Form_pg_type typeStruct;
1903 * In bootstrap mode, pass it off to bootstrap.c. This hack allows us to
1904 * use array_in and array_out during bootstrap.
1906 if (IsBootstrapProcessingMode())
1911 boot_get_type_io_data(typid,
1928 elog(ERROR, "binary I/O not supported during bootstrap");
1934 typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
1935 if (!HeapTupleIsValid(typeTuple))
1936 elog(ERROR, "cache lookup failed for type %u", typid);
1937 typeStruct = (Form_pg_type) GETSTRUCT(typeTuple);
1939 *typlen = typeStruct->typlen;
1940 *typbyval = typeStruct->typbyval;
1941 *typalign = typeStruct->typalign;
1942 *typdelim = typeStruct->typdelim;
1943 *typioparam = getTypeIOParam(typeTuple);
1947 *func = typeStruct->typinput;
1950 *func = typeStruct->typoutput;
1952 case IOFunc_receive:
1953 *func = typeStruct->typreceive;
1956 *func = typeStruct->typsend;
1959 ReleaseSysCache(typeTuple);
1964 get_typalign(Oid typid)
1968 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
1969 if (HeapTupleIsValid(tp))
1971 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
1974 result = typtup->typalign;
1975 ReleaseSysCache(tp);
1984 get_typstorage(Oid typid)
1988 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
1989 if (HeapTupleIsValid(tp))
1991 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
1994 result = typtup->typstorage;
1995 ReleaseSysCache(tp);
2004 * Given a type OID, return the type's default value, if any.
2006 * The result is a palloc'd expression node tree, or NULL if there
2007 * is no defined default for the datatype.
2009 * NB: caller should be prepared to coerce result to correct datatype;
2010 * the returned expression tree might produce something of the wrong type.
2013 get_typdefault(Oid typid)
2015 HeapTuple typeTuple;
2021 typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2022 if (!HeapTupleIsValid(typeTuple))
2023 elog(ERROR, "cache lookup failed for type %u", typid);
2024 type = (Form_pg_type) GETSTRUCT(typeTuple);
2027 * typdefault and typdefaultbin are potentially null, so don't try to
2028 * access 'em as struct fields. Must do it the hard way with
2031 datum = SysCacheGetAttr(TYPEOID,
2033 Anum_pg_type_typdefaultbin,
2038 /* We have an expression default */
2039 expr = stringToNode(TextDatumGetCString(datum));
2043 /* Perhaps we have a plain literal default */
2044 datum = SysCacheGetAttr(TYPEOID,
2046 Anum_pg_type_typdefault,
2051 char *strDefaultVal;
2053 /* Convert text datum to C string */
2054 strDefaultVal = TextDatumGetCString(datum);
2055 /* Convert C string to a value of the given type */
2056 datum = OidInputFunctionCall(type->typinput, strDefaultVal,
2057 getTypeIOParam(typeTuple), -1);
2058 /* Build a Const node containing the value */
2059 expr = (Node *) makeConst(typid,
2066 pfree(strDefaultVal);
2075 ReleaseSysCache(typeTuple);
2082 * If the given type is a domain, return its base type;
2083 * otherwise return the type's own OID.
2086 getBaseType(Oid typid)
2090 return getBaseTypeAndTypmod(typid, &typmod);
2094 * getBaseTypeAndTypmod
2095 * If the given type is a domain, return its base type and typmod;
2096 * otherwise return the type's own OID, and leave *typmod unchanged.
2098 * Note that the "applied typmod" should be -1 for every domain level
2099 * above the bottommost; therefore, if the passed-in typid is indeed
2100 * a domain, *typmod should be -1.
2103 getBaseTypeAndTypmod(Oid typid, int32 *typmod)
2106 * We loop to find the bottom base type in a stack of domains.
2111 Form_pg_type typTup;
2113 tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2114 if (!HeapTupleIsValid(tup))
2115 elog(ERROR, "cache lookup failed for type %u", typid);
2116 typTup = (Form_pg_type) GETSTRUCT(tup);
2117 if (typTup->typtype != TYPTYPE_DOMAIN)
2119 /* Not a domain, so done */
2120 ReleaseSysCache(tup);
2124 Assert(*typmod == -1);
2125 typid = typTup->typbasetype;
2126 *typmod = typTup->typtypmod;
2128 ReleaseSysCache(tup);
2137 * Given a type OID and a typmod value (pass -1 if typmod is unknown),
2138 * estimate the average width of values of the type. This is used by
2139 * the planner, which doesn't require absolutely correct results;
2140 * it's OK (and expected) to guess if we don't know for sure.
2143 get_typavgwidth(Oid typid, int32 typmod)
2145 int typlen = get_typlen(typid);
2149 * Easy if it's a fixed-width type
2155 * type_maximum_size knows the encoding of typmod for some datatypes;
2156 * don't duplicate that knowledge here.
2158 maxwidth = type_maximum_size(typid, typmod);
2162 * For BPCHAR, the max width is also the only width. Otherwise we
2163 * need to guess about the typical data width given the max. A sliding
2164 * scale for percentage of max width seems reasonable.
2166 if (typid == BPCHAROID)
2169 return maxwidth; /* assume full width */
2170 if (maxwidth < 1000)
2171 return 32 + (maxwidth - 32) / 2; /* assume 50% */
2174 * Beyond 1000, assume we're looking at something like
2175 * "varchar(10000)" where the limit isn't actually reached often, and
2176 * use a fixed estimate.
2178 return 32 + (1000 - 32) / 2;
2182 * Ooops, we have no idea ... wild guess time.
2190 * Given the type OID, find if it is a basic type, a complex type, etc.
2191 * It returns the null char if the cache lookup fails...
2194 get_typtype(Oid typid)
2198 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2199 if (HeapTupleIsValid(tp))
2201 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
2204 result = typtup->typtype;
2205 ReleaseSysCache(tp);
2215 * Convenience function to determine whether a type OID represents
2216 * a "rowtype" type --- either RECORD or a named composite type.
2219 type_is_rowtype(Oid typid)
2221 return (typid == RECORDOID || get_typtype(typid) == TYPTYPE_COMPOSITE);
2226 * Returns true if the given type is an enum type.
2229 type_is_enum(Oid typid)
2231 return (get_typtype(typid) == TYPTYPE_ENUM);
2235 * get_type_category_preferred
2237 * Given the type OID, fetch its category and preferred-type status.
2238 * Throws error on failure.
2241 get_type_category_preferred(Oid typid, char *typcategory, bool *typispreferred)
2244 Form_pg_type typtup;
2246 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2247 if (!HeapTupleIsValid(tp))
2248 elog(ERROR, "cache lookup failed for type %u", typid);
2249 typtup = (Form_pg_type) GETSTRUCT(tp);
2250 *typcategory = typtup->typcategory;
2251 *typispreferred = typtup->typispreferred;
2252 ReleaseSysCache(tp);
2258 * Given the type OID, get the typrelid (InvalidOid if not a complex
2262 get_typ_typrelid(Oid typid)
2266 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2267 if (HeapTupleIsValid(tp))
2269 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
2272 result = typtup->typrelid;
2273 ReleaseSysCache(tp);
2283 * Given the type OID, get the typelem (InvalidOid if not an array type).
2285 * NB: this only considers varlena arrays to be true arrays; InvalidOid is
2286 * returned if the input is a fixed-length array type.
2289 get_element_type(Oid typid)
2293 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2294 if (HeapTupleIsValid(tp))
2296 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
2299 if (typtup->typlen == -1)
2300 result = typtup->typelem;
2302 result = InvalidOid;
2303 ReleaseSysCache(tp);
2313 * Given the type OID, get the corresponding "true" array type.
2314 * Returns InvalidOid if no array type can be found.
2317 get_array_type(Oid typid)
2320 Oid result = InvalidOid;
2322 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2323 if (HeapTupleIsValid(tp))
2325 result = ((Form_pg_type) GETSTRUCT(tp))->typarray;
2326 ReleaseSysCache(tp);
2332 * get_base_element_type
2333 * Given the type OID, get the typelem, looking "through" any domain
2334 * to its underlying array type.
2336 * This is equivalent to get_element_type(getBaseType(typid)), but avoids
2337 * an extra cache lookup. Note that it fails to provide any information
2338 * about the typmod of the array.
2341 get_base_element_type(Oid typid)
2344 * We loop to find the bottom base type in a stack of domains.
2349 Form_pg_type typTup;
2351 tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2352 if (!HeapTupleIsValid(tup))
2354 typTup = (Form_pg_type) GETSTRUCT(tup);
2355 if (typTup->typtype != TYPTYPE_DOMAIN)
2357 /* Not a domain, so stop descending */
2360 /* This test must match get_element_type */
2361 if (typTup->typlen == -1)
2362 result = typTup->typelem;
2364 result = InvalidOid;
2365 ReleaseSysCache(tup);
2369 typid = typTup->typbasetype;
2370 ReleaseSysCache(tup);
2373 /* Like get_element_type, silently return InvalidOid for bogus input */
2380 * Get info needed for converting values of a type to internal form
2383 getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
2385 HeapTuple typeTuple;
2388 typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type));
2389 if (!HeapTupleIsValid(typeTuple))
2390 elog(ERROR, "cache lookup failed for type %u", type);
2391 pt = (Form_pg_type) GETSTRUCT(typeTuple);
2393 if (!pt->typisdefined)
2395 (errcode(ERRCODE_UNDEFINED_OBJECT),
2396 errmsg("type %s is only a shell",
2397 format_type_be(type))));
2398 if (!OidIsValid(pt->typinput))
2400 (errcode(ERRCODE_UNDEFINED_FUNCTION),
2401 errmsg("no input function available for type %s",
2402 format_type_be(type))));
2404 *typInput = pt->typinput;
2405 *typIOParam = getTypeIOParam(typeTuple);
2407 ReleaseSysCache(typeTuple);
2413 * Get info needed for printing values of a type
2416 getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
2418 HeapTuple typeTuple;
2421 typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type));
2422 if (!HeapTupleIsValid(typeTuple))
2423 elog(ERROR, "cache lookup failed for type %u", type);
2424 pt = (Form_pg_type) GETSTRUCT(typeTuple);
2426 if (!pt->typisdefined)
2428 (errcode(ERRCODE_UNDEFINED_OBJECT),
2429 errmsg("type %s is only a shell",
2430 format_type_be(type))));
2431 if (!OidIsValid(pt->typoutput))
2433 (errcode(ERRCODE_UNDEFINED_FUNCTION),
2434 errmsg("no output function available for type %s",
2435 format_type_be(type))));
2437 *typOutput = pt->typoutput;
2438 *typIsVarlena = (!pt->typbyval) && (pt->typlen == -1);
2440 ReleaseSysCache(typeTuple);
2444 * getTypeBinaryInputInfo
2446 * Get info needed for binary input of values of a type
2449 getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam)
2451 HeapTuple typeTuple;
2454 typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type));
2455 if (!HeapTupleIsValid(typeTuple))
2456 elog(ERROR, "cache lookup failed for type %u", type);
2457 pt = (Form_pg_type) GETSTRUCT(typeTuple);
2459 if (!pt->typisdefined)
2461 (errcode(ERRCODE_UNDEFINED_OBJECT),
2462 errmsg("type %s is only a shell",
2463 format_type_be(type))));
2464 if (!OidIsValid(pt->typreceive))
2466 (errcode(ERRCODE_UNDEFINED_FUNCTION),
2467 errmsg("no binary input function available for type %s",
2468 format_type_be(type))));
2470 *typReceive = pt->typreceive;
2471 *typIOParam = getTypeIOParam(typeTuple);
2473 ReleaseSysCache(typeTuple);
2477 * getTypeBinaryOutputInfo
2479 * Get info needed for binary output of values of a type
2482 getTypeBinaryOutputInfo(Oid type, Oid *typSend, bool *typIsVarlena)
2484 HeapTuple typeTuple;
2487 typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type));
2488 if (!HeapTupleIsValid(typeTuple))
2489 elog(ERROR, "cache lookup failed for type %u", type);
2490 pt = (Form_pg_type) GETSTRUCT(typeTuple);
2492 if (!pt->typisdefined)
2494 (errcode(ERRCODE_UNDEFINED_OBJECT),
2495 errmsg("type %s is only a shell",
2496 format_type_be(type))));
2497 if (!OidIsValid(pt->typsend))
2499 (errcode(ERRCODE_UNDEFINED_FUNCTION),
2500 errmsg("no binary output function available for type %s",
2501 format_type_be(type))));
2503 *typSend = pt->typsend;
2504 *typIsVarlena = (!pt->typbyval) && (pt->typlen == -1);
2506 ReleaseSysCache(typeTuple);
2512 * Given the type OID, return the type's typmodin procedure, if any.
2515 get_typmodin(Oid typid)
2519 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2520 if (HeapTupleIsValid(tp))
2522 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
2525 result = typtup->typmodin;
2526 ReleaseSysCache(tp);
2537 * Given the type OID, return the type's typmodout procedure, if any.
2540 get_typmodout(Oid typid)
2544 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2545 if (HeapTupleIsValid(tp))
2547 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
2550 result = typtup->typmodout;
2551 ReleaseSysCache(tp);
2557 #endif /* NOT_USED */
2562 * Given the type OID, return the type's typcollation attribute.
2565 get_typcollation(Oid typid)
2569 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2570 if (HeapTupleIsValid(tp))
2572 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
2575 result = typtup->typcollation;
2576 ReleaseSysCache(tp);
2585 * type_is_collatable
2587 * Return whether the type cares about collations
2590 type_is_collatable(Oid typid)
2592 return OidIsValid(get_typcollation(typid));
2596 /* ---------- STATISTICS CACHE ---------- */
2601 * Given the table and attribute number of a column, get the average
2602 * width of entries in the column. Return zero if no data available.
2604 * Currently this is only consulted for individual tables, not for inheritance
2605 * trees, so we don't need an "inh" parameter.
2607 * Calling a hook at this point looks somewhat strange, but is required
2608 * because the optimizer calls this function without any other way for
2609 * plug-ins to control the result.
2612 get_attavgwidth(Oid relid, AttrNumber attnum)
2617 if (get_attavgwidth_hook)
2619 stawidth = (*get_attavgwidth_hook) (relid, attnum);
2623 tp = SearchSysCache3(STATRELATTINH,
2624 ObjectIdGetDatum(relid),
2625 Int16GetDatum(attnum),
2626 BoolGetDatum(false));
2627 if (HeapTupleIsValid(tp))
2629 stawidth = ((Form_pg_statistic) GETSTRUCT(tp))->stawidth;
2630 ReleaseSysCache(tp);
2640 * Extract the contents of a "slot" of a pg_statistic tuple.
2641 * Returns TRUE if requested slot type was found, else FALSE.
2643 * Unlike other routines in this file, this takes a pointer to an
2644 * already-looked-up tuple in the pg_statistic cache. We do this since
2645 * most callers will want to extract more than one value from the cache
2646 * entry, and we don't want to repeat the cache lookup unnecessarily.
2647 * Also, this API allows this routine to be used with statistics tuples
2648 * that have been provided by a stats hook and didn't really come from
2651 * statstuple: pg_statistics tuple to be examined.
2652 * atttype: type OID of attribute (can be InvalidOid if values == NULL).
2653 * atttypmod: typmod of attribute (can be 0 if values == NULL).
2654 * reqkind: STAKIND code for desired statistics slot kind.
2655 * reqop: STAOP value wanted, or InvalidOid if don't care.
2656 * actualop: if not NULL, *actualop receives the actual STAOP value.
2657 * values, nvalues: if not NULL, the slot's stavalues are extracted.
2658 * numbers, nnumbers: if not NULL, the slot's stanumbers are extracted.
2660 * If assigned, values and numbers are set to point to palloc'd arrays.
2661 * If the attribute type is pass-by-reference, the values referenced by
2662 * the values array are themselves palloc'd. The palloc'd stuff can be
2663 * freed by calling free_attstatsslot.
2665 * Note: at present, atttype/atttypmod aren't actually used here at all.
2666 * But the caller must have the correct (or at least binary-compatible)
2667 * type ID to pass to free_attstatsslot later.
2670 get_attstatsslot(HeapTuple statstuple,
2671 Oid atttype, int32 atttypmod,
2672 int reqkind, Oid reqop,
2674 Datum **values, int *nvalues,
2675 float4 **numbers, int *nnumbers)
2677 Form_pg_statistic stats = (Form_pg_statistic) GETSTRUCT(statstuple);
2682 ArrayType *statarray;
2685 HeapTuple typeTuple;
2686 Form_pg_type typeForm;
2688 for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
2690 if ((&stats->stakind1)[i] == reqkind &&
2691 (reqop == InvalidOid || (&stats->staop1)[i] == reqop))
2694 if (i >= STATISTIC_NUM_SLOTS)
2695 return false; /* not there */
2698 *actualop = (&stats->staop1)[i];
2702 val = SysCacheGetAttr(STATRELATTINH, statstuple,
2703 Anum_pg_statistic_stavalues1 + i,
2706 elog(ERROR, "stavalues is null");
2707 statarray = DatumGetArrayTypeP(val);
2710 * Need to get info about the array element type. We look at the
2711 * actual element type embedded in the array, which might be only
2712 * binary-compatible with the passed-in atttype. The info we
2713 * extract here should be the same either way, but deconstruct_array
2714 * is picky about having an exact type OID match.
2716 arrayelemtype = ARR_ELEMTYPE(statarray);
2717 typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(arrayelemtype));
2718 if (!HeapTupleIsValid(typeTuple))
2719 elog(ERROR, "cache lookup failed for type %u", arrayelemtype);
2720 typeForm = (Form_pg_type) GETSTRUCT(typeTuple);
2722 /* Deconstruct array into Datum elements; NULLs not expected */
2723 deconstruct_array(statarray,
2728 values, NULL, nvalues);
2731 * If the element type is pass-by-reference, we now have a bunch of
2732 * Datums that are pointers into the syscache value. Copy them to
2733 * avoid problems if syscache decides to drop the entry.
2735 if (!typeForm->typbyval)
2737 for (j = 0; j < *nvalues; j++)
2739 (*values)[j] = datumCopy((*values)[j],
2745 ReleaseSysCache(typeTuple);
2748 * Free statarray if it's a detoasted copy.
2750 if ((Pointer) statarray != DatumGetPointer(val))
2756 val = SysCacheGetAttr(STATRELATTINH, statstuple,
2757 Anum_pg_statistic_stanumbers1 + i,
2760 elog(ERROR, "stanumbers is null");
2761 statarray = DatumGetArrayTypeP(val);
2764 * We expect the array to be a 1-D float4 array; verify that. We don't
2765 * need to use deconstruct_array() since the array data is just going
2766 * to look like a C array of float4 values.
2768 narrayelem = ARR_DIMS(statarray)[0];
2769 if (ARR_NDIM(statarray) != 1 || narrayelem <= 0 ||
2770 ARR_HASNULL(statarray) ||
2771 ARR_ELEMTYPE(statarray) != FLOAT4OID)
2772 elog(ERROR, "stanumbers is not a 1-D float4 array");
2773 *numbers = (float4 *) palloc(narrayelem * sizeof(float4));
2774 memcpy(*numbers, ARR_DATA_PTR(statarray), narrayelem * sizeof(float4));
2775 *nnumbers = narrayelem;
2778 * Free statarray if it's a detoasted copy.
2780 if ((Pointer) statarray != DatumGetPointer(val))
2789 * Free data allocated by get_attstatsslot
2791 * atttype need be valid only if values != NULL.
2794 free_attstatsslot(Oid atttype,
2795 Datum *values, int nvalues,
2796 float4 *numbers, int nnumbers)
2800 if (!get_typbyval(atttype))
2804 for (i = 0; i < nvalues; i++)
2805 pfree(DatumGetPointer(values[i]));
2813 /* ---------- PG_NAMESPACE CACHE ---------- */
2816 * get_namespace_name
2817 * Returns the name of a given namespace
2819 * Returns a palloc'd copy of the string, or NULL if no such namespace.
2822 get_namespace_name(Oid nspid)
2826 tp = SearchSysCache1(NAMESPACEOID, ObjectIdGetDatum(nspid));
2827 if (HeapTupleIsValid(tp))
2829 Form_pg_namespace nsptup = (Form_pg_namespace) GETSTRUCT(tp);
2832 result = pstrdup(NameStr(nsptup->nspname));
2833 ReleaseSysCache(tp);